lawcheck 0.0.0 → 0.1.0-alpha.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 (75) hide show
  1. package/README.md +34 -2
  2. package/dist/args.js +168 -0
  3. package/dist/bin.cjs +20 -0
  4. package/dist/check.js +472 -0
  5. package/dist/cli.js +182 -0
  6. package/dist/config.js +278 -0
  7. package/dist/docs.js +41 -0
  8. package/dist/doctor.js +273 -0
  9. package/dist/environment.js +73 -0
  10. package/dist/explain.js +446 -0
  11. package/dist/files.js +388 -0
  12. package/dist/glob.js +268 -0
  13. package/dist/grammars/LICENSES.txt +353 -0
  14. package/dist/grammars/tree-sitter-c.wasm +0 -0
  15. package/dist/grammars/tree-sitter-c_sharp.wasm +0 -0
  16. package/dist/grammars/tree-sitter-cpp.wasm +0 -0
  17. package/dist/grammars/tree-sitter-go.wasm +0 -0
  18. package/dist/grammars/tree-sitter-java.wasm +0 -0
  19. package/dist/grammars/tree-sitter-javascript.wasm +0 -0
  20. package/dist/grammars/tree-sitter-kotlin.wasm +0 -0
  21. package/dist/grammars/tree-sitter-php.wasm +0 -0
  22. package/dist/grammars/tree-sitter-python.wasm +0 -0
  23. package/dist/grammars/tree-sitter-ruby.wasm +0 -0
  24. package/dist/grammars/tree-sitter-rust.wasm +0 -0
  25. package/dist/grammars/tree-sitter-tsx.wasm +0 -0
  26. package/dist/grammars/tree-sitter-typescript.wasm +0 -0
  27. package/dist/guard.js +179 -0
  28. package/dist/init.js +131 -0
  29. package/dist/keys.js +55 -0
  30. package/dist/law.js +416 -0
  31. package/dist/lawchange.js +208 -0
  32. package/dist/limits.js +207 -0
  33. package/dist/main.js +77 -0
  34. package/dist/names.js +117 -0
  35. package/dist/output.js +325 -0
  36. package/dist/prime.js +211 -0
  37. package/dist/programs.js +177 -0
  38. package/dist/progress.js +42 -0
  39. package/dist/prompt.js +317 -0
  40. package/dist/providers/anthropic.js +33 -0
  41. package/dist/providers/claude-code.js +41 -0
  42. package/dist/providers/codex.js +75 -0
  43. package/dist/providers/copilot-cli.js +56 -0
  44. package/dist/providers/gemini-cli.js +30 -0
  45. package/dist/providers/google.js +31 -0
  46. package/dist/providers/http.js +138 -0
  47. package/dist/providers/index.js +96 -0
  48. package/dist/providers/ollama.js +39 -0
  49. package/dist/providers/openai-compatible.js +41 -0
  50. package/dist/providers/openai.js +17 -0
  51. package/dist/providers/program.js +282 -0
  52. package/dist/readers.js +286 -0
  53. package/dist/review.js +116 -0
  54. package/dist/rules.js +418 -0
  55. package/dist/runner.js +177 -0
  56. package/dist/setup.js +388 -0
  57. package/dist/try.js +346 -0
  58. package/dist/types.js +99 -0
  59. package/dist/uses.js +78 -0
  60. package/dist/verdicts.js +337 -0
  61. package/dist/waivers.js +70 -0
  62. package/dist/work.js +21 -0
  63. package/docs/change.md +62 -0
  64. package/docs/ci.md +133 -0
  65. package/docs/codes.md +60 -0
  66. package/docs/config.md +117 -0
  67. package/docs/first-law.md +189 -0
  68. package/docs/json.md +72 -0
  69. package/docs/languages.md +87 -0
  70. package/docs/law.md +95 -0
  71. package/docs/providers.md +105 -0
  72. package/docs/reviewer-rules.md +96 -0
  73. package/docs/script-rules.md +90 -0
  74. package/docs/waivers.md +56 -0
  75. package/package.json +59 -3
package/dist/init.js ADDED
@@ -0,0 +1,131 @@
1
+ import { closeSync, lstatSync, mkdirSync, openSync, realpathSync, statSync, writeSync } from 'node:fs';
2
+ import { join, relative, resolve } from 'node:path';
3
+ import { documentOf, errorResult, noWords, usageError, version } from './args.js';
4
+ import { listFiles, showPrefix, workTreeProblem } from './files.js';
5
+ import { findRoot, LAW, stopped } from './setup.js';
6
+ import { noGit, Stop } from './setup.js';
7
+ export function lawText(packageVersion) {
8
+ const release = packageVersion.match(/^\d+\.\d+\.\d+/)?.[0] ?? packageVersion;
9
+ return [
10
+ `lawcheck: ${release}`,
11
+ '',
12
+ '# The law of this repository: the types of its files, and the rules each type keeps.',
13
+ '# lawcheck docs first-law shows how to write them. A small example:',
14
+ '#',
15
+ '# rules:',
16
+ '# no-console:',
17
+ '# why: Only the command layer writes to the terminal.',
18
+ '#',
19
+ '# types:',
20
+ '# source:',
21
+ '# about: Everything that ships.',
22
+ '# paths: ["src/**/*.ts"]',
23
+ '# rules: [no-console]',
24
+ '#',
25
+ '# Each rule has one file: .lawcheck/rules/no-console.mjs for a script,',
26
+ '# or .lawcheck/rules/no-console.md for the reviewer.',
27
+ '',
28
+ ].join('\n');
29
+ }
30
+ export const GITIGNORE = '.local/\nconfig.local.yaml\n';
31
+ const IGNORE = '.lawcheck/.gitignore';
32
+ const NEXT = 'describe your first file type in .lawcheck/law.yaml (lawcheck docs first-law shows how)';
33
+ function already(place, below = false) {
34
+ return new Stop([
35
+ {
36
+ code: 'already-initialized',
37
+ file: place,
38
+ line: null,
39
+ message: below ? 'a law already governs a directory below this one' : 'a law already governs this directory',
40
+ next: 'lawcheck doctor (shows how the law here stands)',
41
+ },
42
+ ]);
43
+ }
44
+ function notAFolder(path) {
45
+ let link;
46
+ try {
47
+ link = lstatSync(path).isSymbolicLink();
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ try {
53
+ if (statSync(path).isDirectory())
54
+ return null;
55
+ }
56
+ catch {
57
+ return 'it is a symbolic link to a place that does not exist, so the folder .lawcheck cannot be made';
58
+ }
59
+ return link ? 'it is a symbolic link to a file, so the folder .lawcheck cannot be made' : 'it is a file, so the folder .lawcheck cannot be made';
60
+ }
61
+ export function writeNew(path, content, place = path) {
62
+ let fd;
63
+ try {
64
+ fd = openSync(path, 'wx');
65
+ }
66
+ catch (error) {
67
+ if (error.code === 'EEXIST')
68
+ return false;
69
+ throw unwritable(place, error);
70
+ }
71
+ try {
72
+ writeSync(fd, content);
73
+ }
74
+ catch (error) {
75
+ throw unwritable(place, error);
76
+ }
77
+ finally {
78
+ closeSync(fd);
79
+ }
80
+ return true;
81
+ }
82
+ function unwritable(place, error) {
83
+ const code = error.code ?? 'an error';
84
+ return new Stop([{ code: 'file-unwritable', file: place, line: null, message: `cannot be written (${code})`, next: `make ${place} writable, then run lawcheck init again` }]);
85
+ }
86
+ export async function init(args, context, json) {
87
+ const extra = noWords(args);
88
+ if (extra !== null)
89
+ return usageError(extra, json, 'init');
90
+ const cwd = realpathSync(resolve(context.cwd));
91
+ const outcome = await stopped(() => {
92
+ const problem = workTreeProblem(cwd);
93
+ if (problem !== null)
94
+ throw new Stop([noGit(cwd, problem)]);
95
+ const root = findRoot(cwd);
96
+ if (root !== null)
97
+ throw already(relative(cwd, join(root, LAW)).split('\\').join('/'));
98
+ const below = listFiles(cwd).find((path) => path === LAW || path.endsWith(`/${LAW}`));
99
+ if (below !== undefined)
100
+ throw already(below, true);
101
+ const prefix = showPrefix(cwd);
102
+ const obstacle = notAFolder(join(cwd, '.lawcheck'));
103
+ if (obstacle !== null) {
104
+ throw new Stop([{ code: 'file-unwritable', file: '.lawcheck', line: null, message: obstacle, next: 'move .lawcheck out of the way, then run lawcheck init again' }]);
105
+ }
106
+ try {
107
+ mkdirSync(join(cwd, '.lawcheck'), { recursive: true });
108
+ }
109
+ catch (error) {
110
+ throw unwritable('.lawcheck', error);
111
+ }
112
+ if (!writeNew(join(cwd, LAW), lawText(version()), LAW))
113
+ throw already(LAW);
114
+ const created = [LAW];
115
+ const kept = [];
116
+ (writeNew(join(cwd, IGNORE), GITIGNORE, IGNORE) ? created : kept).push(IGNORE);
117
+ return { prefix, created, kept };
118
+ });
119
+ if ('errors' in outcome)
120
+ return errorResult(outcome.errors, json, 'init');
121
+ const { prefix, created, kept } = outcome;
122
+ if (json) {
123
+ return { code: 0, stdout: documentOf({ schema: 'lawcheck-init/0', root: prefix, created, kept, next: { command: null, text: NEXT } }) };
124
+ }
125
+ const first = kept.length === 0 ? `lawcheck: created ${created.join(' and ')}` : `lawcheck: created ${created.join(' and ')}; kept ${kept.join(' and ')}`;
126
+ const lines = [first];
127
+ if (prefix !== '')
128
+ lines.push(`note: the law covers only the files below ${prefix}`);
129
+ lines.push('', 'Nothing is checked yet: the law has no types.', `next: ${NEXT}`);
130
+ return { code: 0, stdout: lines.join('\n') + '\n' };
131
+ }
package/dist/keys.js ADDED
@@ -0,0 +1,55 @@
1
+ // The owner's ruling of question 89 (spec/questions.md): the exact key is written as [key] wherever Lawcheck prints or writes it.
2
+ export const KEY_SHOWN = '[key]';
3
+ const NAMED_ESCAPES = { '"': '\\"', '\\': '\\\\', '/': '\\/', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t' };
4
+ // The key in any spelling JSON allows: each character as it is, as a \u escape, or by its short escape.
5
+ function spellings(key) {
6
+ const parts = [...key].map((c) => {
7
+ const units = [...Array(c.length).keys()]
8
+ .map((i) => `\\\\u${[...c.charCodeAt(i).toString(16).padStart(4, '0')].map((d) => (/[a-f]/.test(d) ? `[${d}${d.toUpperCase()}]` : d)).join('')}`)
9
+ .join('');
10
+ const named = NAMED_ESCAPES[c];
11
+ return `(?:${named === undefined ? '' : `${named.replace(/\\/g, '\\\\')}|`}${units}|${c.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')})`;
12
+ });
13
+ return parts.join('');
14
+ }
15
+ // The build's reading of the ruling: a key shorter than this is no secret, such as a dummy key for a local endpoint, and replacing it would garble names that hold it.
16
+ export const SHORTEST = 8;
17
+ export function hidden(text, keys) {
18
+ const list = [...new Set(keys)].filter((key) => [...key].length >= SHORTEST).sort((a, b) => b.length - a.length);
19
+ if (list.length === 0)
20
+ return text;
21
+ // [key] itself is matched first, so a text that passes here twice stays as it was.
22
+ return text.replace(new RegExp(['\\[key\\]', ...list.map(spellings)].join('|'), 'g'), KEY_SHOWN);
23
+ }
24
+ // The environment key goes to whichever HTTP provider is configured, so it is hidden in every run; the configured provider adds the keys it would send or pass on once the config is read.
25
+ export const KEY_VARIABLES = ['LAWCHECK_REVIEWER_KEY'];
26
+ let known = [];
27
+ let environment = {};
28
+ export function useKeys(env) {
29
+ environment = env;
30
+ known = KEY_VARIABLES.map((name) => env[name] ?? '').filter((key) => key !== '');
31
+ }
32
+ export function keyEnvironment() {
33
+ return environment;
34
+ }
35
+ export function addKeys(keys) {
36
+ known = [...new Set([...known, ...keys])];
37
+ }
38
+ export function hide(text) {
39
+ return hidden(text, known);
40
+ }
41
+ // The fields of a document that hold text from outside Lawcheck; its own fields, such as schema, code, the ids and the counts, stay as they are.
42
+ const OUTSIDE_FIELDS = new Set(['file', 'files', 'message', 'base', 'path', 'paths', 'reason', 'what', 'candidates', 'answer', 'text', 'about', 'pattern', 'content', 'why', 'model']);
43
+ // The key written as [key] in the strings of the outside fields; the layout is the one every document has.
44
+ export function hiddenJson(text) {
45
+ let document;
46
+ try {
47
+ document = JSON.parse(text);
48
+ }
49
+ catch {
50
+ return text;
51
+ }
52
+ const masked = (value) => (typeof value === 'string' ? hide(value) : Array.isArray(value) ? value.map(masked) : value);
53
+ const walk = (value) => Array.isArray(value) ? value.map(walk) : value !== null && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([name, item]) => [name, OUTSIDE_FIELDS.has(name) ? masked(item) : walk(item)])) : value;
54
+ return JSON.stringify(walk(document), null, 2) + '\n';
55
+ }
package/dist/law.js ADDED
@@ -0,0 +1,416 @@
1
+ import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument, visit } from 'yaml';
2
+ import { LAW_RULES, LAW_TYPES } from './limits.js';
3
+ import { step } from './progress.js';
4
+ import { compileList, patternProblem } from './glob.js';
5
+ import { CODES } from './output.js';
6
+ const ID = /^[a-z0-9]+(-[a-z0-9]+)*$/;
7
+ const VERSION = /^\d+\.\d+\.\d+$/;
8
+ const TOP_KEYS = ['lawcheck', 'rules', 'types'];
9
+ const RULE_KEYS = ['why', 'status', 'context'];
10
+ const TYPE_KEYS = ['about', 'paths', 'content', 'rules', 'types', 'may_use', 'waivers'];
11
+ const RESERVED = new Set([...CODES, 'untyped-file']);
12
+ export function distance(a, b) {
13
+ const row = Array.from({ length: b.length + 1 }, (_, j) => j);
14
+ for (let i = 1; i <= a.length; i++) {
15
+ let diagonal = row[0];
16
+ row[0] = i;
17
+ for (let j = 1; j <= b.length; j++) {
18
+ const above = row[j];
19
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
20
+ diagonal = above;
21
+ }
22
+ }
23
+ return row[b.length];
24
+ }
25
+ export function nearestKey(key, known) {
26
+ let best = null;
27
+ let bestDistance = 3;
28
+ for (const candidate of known) {
29
+ const d = distance(key, candidate);
30
+ if (d < bestDistance) {
31
+ best = candidate;
32
+ bestDistance = d;
33
+ }
34
+ }
35
+ return best;
36
+ }
37
+ // The YAML library finds a repeated key by comparing it with every key before it, which takes minutes for a law of 200,000 rules; a set finds the same keys in one pass.
38
+ export function parseUnique(text, counter) {
39
+ const doc = parseDocument(text, { lineCounter: counter, prettyErrors: false, uniqueKeys: false });
40
+ const errors = doc.errors.map((error) => ({ pos: error.pos[0], message: error.message }));
41
+ visit(doc, {
42
+ Map(_, map) {
43
+ const seen = new Set();
44
+ for (const pair of map.items) {
45
+ if (!isScalar(pair.key))
46
+ continue;
47
+ if (seen.has(pair.key.value))
48
+ errors.push({ pos: pair.key.range?.[0] ?? 0, message: 'Map keys must be unique' });
49
+ seen.add(pair.key.value);
50
+ }
51
+ },
52
+ });
53
+ errors.sort((a, b) => a.pos - b.pos);
54
+ return { doc, errors };
55
+ }
56
+ export function parseLaw(text) {
57
+ step('reading the law');
58
+ const counter = new LineCounter();
59
+ const { doc, errors } = parseUnique(text, counter);
60
+ const problems = [];
61
+ if (errors.length > 0) {
62
+ for (const error of errors) {
63
+ const line = counter.linePos(error.pos).line;
64
+ problems.push({ line, message: `the law does not parse: ${error.message.split('\n')[0]}` });
65
+ }
66
+ return { law: null, problems };
67
+ }
68
+ return new Reader(doc, counter, problems).read();
69
+ }
70
+ function typeCount(types) {
71
+ let count = 0;
72
+ for (const pair of types.items) {
73
+ count++;
74
+ const below = isMap(pair.value) ? pair.value.get('types', true) : undefined;
75
+ if (isMap(below))
76
+ count += typeCount(below);
77
+ }
78
+ return count;
79
+ }
80
+ class Reader {
81
+ doc;
82
+ counter;
83
+ problems;
84
+ rules = new Map();
85
+ byId = new Map();
86
+ listed = [];
87
+ used = [];
88
+ reportedKeys = new Set();
89
+ open = new Set();
90
+ constructor(doc, counter, problems) {
91
+ this.doc = doc;
92
+ this.counter = counter;
93
+ this.problems = problems;
94
+ }
95
+ read() {
96
+ const top = this.resolve(this.doc.contents);
97
+ if (top === null || (isScalar(top) && (top.value === null || top.value === ''))) {
98
+ this.problem(1, 'the law is empty');
99
+ return { law: null, problems: this.problems };
100
+ }
101
+ if (!isMap(top)) {
102
+ this.problem(this.lineOf(top), 'the law is not a mapping');
103
+ return { law: null, problems: this.problems };
104
+ }
105
+ let types = [];
106
+ let sawVersion = false;
107
+ for (const pair of top.items) {
108
+ const key = this.keyOf(pair);
109
+ const value = this.resolve(pair.value);
110
+ const line = this.lineOf(pair.key);
111
+ if (key === 'lawcheck') {
112
+ sawVersion = true;
113
+ const version = this.string(value, line, "'lawcheck'");
114
+ if (version !== null && !VERSION.test(version))
115
+ this.problem(line, `'lawcheck' is '${version}'; it takes MAJOR.MINOR.PATCH`);
116
+ }
117
+ else if (key === 'rules') {
118
+ if (!this.mapping(value, line, "'rules'"))
119
+ continue;
120
+ const count = value.items.length;
121
+ if (count > LAW_RULES) {
122
+ this.problems.push({ line, message: `the law holds ${count.toLocaleString('en-US')} rules, more than the ${LAW_RULES.toLocaleString('en-US')} a law may hold`, tooLarge: true });
123
+ return { law: null, problems: this.problems };
124
+ }
125
+ this.readRules(value);
126
+ }
127
+ else if (key === 'types') {
128
+ if (!this.mapping(value, line, "'types'"))
129
+ continue;
130
+ const count = typeCount(value);
131
+ if (count > LAW_TYPES) {
132
+ this.problems.push({ line, message: `the law holds ${count.toLocaleString('en-US')} types, more than the ${LAW_TYPES.toLocaleString('en-US')} a law may hold`, tooLarge: true });
133
+ return { law: null, problems: this.problems };
134
+ }
135
+ types = this.readTypes(value, null);
136
+ }
137
+ else {
138
+ this.unknown(key, TOP_KEYS, line, 'at the top of the law');
139
+ }
140
+ }
141
+ if (!sawVersion)
142
+ this.problem(1, "the law has no key 'lawcheck'");
143
+ for (const { owner, rule, line } of this.listed) {
144
+ if (!this.rules.has(rule))
145
+ this.problem(line, `type '${owner}' lists the rule '${rule}', which the law does not have`);
146
+ }
147
+ for (const { owner, type, line } of this.used) {
148
+ if (!this.byId.has(type))
149
+ this.problem(line, `'may_use' of type '${owner}' names '${type}', which is no type of the law`);
150
+ }
151
+ if (this.problems.length > 0)
152
+ return { law: null, problems: this.problems };
153
+ return { law: { rules: this.rules, types, byId: this.byId }, problems: [] };
154
+ }
155
+ readRules(map) {
156
+ for (const pair of map.items) {
157
+ const id = this.keyOf(pair);
158
+ const line = this.lineOf(pair.key);
159
+ if (!ID.test(id))
160
+ this.problem(line, `the rule id '${id}' is not kebab-case`);
161
+ else if (RESERVED.has(id))
162
+ this.problem(line, `the rule id '${id}' is a code of Lawcheck`);
163
+ const value = this.resolve(pair.value);
164
+ if (!this.mapping(value, line, `rule '${id}'`))
165
+ continue;
166
+ let why = null;
167
+ let status = 'enforced';
168
+ let context = null;
169
+ let contextLine = null;
170
+ for (const field of value.items) {
171
+ const key = this.keyOf(field);
172
+ const fieldLine = this.lineOf(field.key);
173
+ const fieldValue = this.resolve(field.value);
174
+ if (key === 'why') {
175
+ why = this.line(fieldValue, fieldLine, `'why' of rule '${id}'`);
176
+ if (why !== null && [...why].length > 200)
177
+ this.problem(fieldLine, `'why' of rule '${id}' is longer than 200 characters`);
178
+ }
179
+ else if (key === 'status') {
180
+ const text = this.string(fieldValue, fieldLine, `'status' of rule '${id}'`);
181
+ if (text === 'enforced' || text === 'advisory')
182
+ status = text;
183
+ else if (text !== null)
184
+ this.problem(fieldLine, `'status' of rule '${id}' is '${text}'; it takes 'enforced' or 'advisory'`);
185
+ }
186
+ else if (key === 'context') {
187
+ contextLine = fieldLine;
188
+ context = this.paths(fieldValue, fieldLine, `'context' of rule '${id}'`);
189
+ }
190
+ else {
191
+ this.unknown(key, RULE_KEYS, fieldLine, `in rule '${id}'`);
192
+ }
193
+ }
194
+ if (!value.items.some((field) => this.keyOf(field) === 'why'))
195
+ this.problem(line, `rule '${id}' has no 'why'`);
196
+ this.rules.set(id, { id, why: why ?? '', status, line, context, contextLine });
197
+ }
198
+ }
199
+ readTypes(map, parent) {
200
+ const out = [];
201
+ for (const pair of map.items) {
202
+ const id = this.keyOf(pair);
203
+ const line = this.lineOf(pair.key);
204
+ if (!ID.test(id))
205
+ this.problem(line, `the type id '${id}' is not kebab-case`);
206
+ else if (this.byId.has(id))
207
+ this.problem(line, `the type id '${id}' appears twice in the law`);
208
+ const value = this.resolve(pair.value);
209
+ if (!this.mapping(value, line, `type '${id}'`))
210
+ continue;
211
+ if (this.open.has(value)) {
212
+ this.problem(line, `type '${id}' is, through an alias, a type that holds it`);
213
+ continue;
214
+ }
215
+ const type = { id, about: null, paths: [], matches: () => false, content: null, expression: null, rules: [], types: [], parent, line, mayUse: null, waivers: null };
216
+ if (!this.byId.has(id))
217
+ this.byId.set(id, type);
218
+ let sawPaths = false;
219
+ for (const field of value.items) {
220
+ const key = this.keyOf(field);
221
+ const fieldLine = this.lineOf(field.key);
222
+ const fieldValue = this.resolve(field.value);
223
+ if (key === 'about') {
224
+ type.about = this.line(fieldValue, fieldLine, `'about' of type '${id}'`);
225
+ }
226
+ else if (key === 'paths') {
227
+ sawPaths = true;
228
+ const patterns = this.strings(fieldValue, fieldLine, `'paths' of type '${id}'`);
229
+ if (patterns === null)
230
+ continue;
231
+ let valid = true;
232
+ for (const { text, line: itemLine } of patterns) {
233
+ const problem = patternProblem(text);
234
+ if (problem !== null) {
235
+ valid = false;
236
+ this.problem(itemLine, `the pattern '${text}' of type '${id}' ${problem}`);
237
+ }
238
+ }
239
+ if (!patterns.some(({ text }) => !text.startsWith('!'))) {
240
+ valid = false;
241
+ this.problem(fieldLine, `'paths' of type '${id}' holds no pattern without '!'`);
242
+ }
243
+ if (valid) {
244
+ type.paths = patterns.map(({ text }) => text);
245
+ type.matches = compileList(type.paths);
246
+ }
247
+ }
248
+ else if (key === 'content') {
249
+ const text = this.string(fieldValue, fieldLine, `'content' of type '${id}'`);
250
+ if (text === null)
251
+ continue;
252
+ try {
253
+ type.content = new RegExp(text, 'm');
254
+ type.expression = text;
255
+ }
256
+ catch (error) {
257
+ this.problem(fieldLine, `'content' of type '${id}' is no valid expression: ${firstLine(error)}`);
258
+ }
259
+ }
260
+ else if (key === 'rules') {
261
+ const ids = this.strings(fieldValue, fieldLine, `'rules' of type '${id}'`);
262
+ if (ids === null)
263
+ continue;
264
+ for (const { text, line: itemLine } of ids) {
265
+ this.listed.push({ owner: id, rule: text, line: itemLine });
266
+ if (!type.rules.includes(text))
267
+ type.rules.push(text);
268
+ }
269
+ }
270
+ else if (key === 'may_use') {
271
+ const ids = this.strings(fieldValue, fieldLine, `'may_use' of type '${id}'`);
272
+ if (ids === null)
273
+ continue;
274
+ type.mayUse = [];
275
+ for (const { text, line: itemLine } of ids) {
276
+ this.used.push({ owner: id, type: text, line: itemLine });
277
+ if (!type.mayUse.includes(text))
278
+ type.mayUse.push(text);
279
+ }
280
+ }
281
+ else if (key === 'waivers') {
282
+ if (isScalar(fieldValue) && typeof fieldValue.value === 'boolean')
283
+ type.waivers = fieldValue.value;
284
+ else
285
+ this.problem(fieldLine, `'waivers' of type '${id}' takes true or false, not ${describe(fieldValue)}`);
286
+ }
287
+ else if (key === 'types') {
288
+ if (this.mapping(fieldValue, fieldLine, `'types' of type '${id}'`)) {
289
+ this.open.add(value);
290
+ type.types = this.readTypes(fieldValue, type);
291
+ this.open.delete(value);
292
+ }
293
+ }
294
+ else {
295
+ this.unknown(key, TYPE_KEYS, fieldLine, `in type '${id}'`);
296
+ }
297
+ }
298
+ if (!sawPaths)
299
+ this.problem(line, `type '${id}' has no 'paths'`);
300
+ out.push(type);
301
+ }
302
+ return out;
303
+ }
304
+ resolve(node) {
305
+ let current = node;
306
+ for (let depth = 0; isAlias(current) && depth < 100; depth++)
307
+ current = current.resolve(this.doc) ?? null;
308
+ return (current ?? null);
309
+ }
310
+ keyOf(pair) {
311
+ const key = this.resolve(pair.key);
312
+ if (isScalar(key) && typeof key.value === 'string')
313
+ return key.value;
314
+ const text = isScalar(key) ? (key.source ?? String(key.value)) : String(key);
315
+ if (!this.reportedKeys.has(pair)) {
316
+ this.reportedKeys.add(pair);
317
+ this.problem(this.lineOf(pair.key), `the key '${text}' is no string; write it in quotes`);
318
+ }
319
+ return text;
320
+ }
321
+ lineOf(node) {
322
+ const range = node?.range;
323
+ return range ? this.counter.linePos(range[0]).line : 1;
324
+ }
325
+ problem(line, message) {
326
+ this.problems.push({ line, message });
327
+ }
328
+ unknown(key, known, line, where) {
329
+ const near = nearestKey(key, known);
330
+ this.problem(line, `unknown key '${key}' ${where}${near === null ? '' : ` (did you mean '${near}'?)`}`);
331
+ }
332
+ mapping(value, line, what) {
333
+ if (isMap(value))
334
+ return true;
335
+ this.problem(line, `${what} takes a mapping, not ${describe(value)}`);
336
+ return false;
337
+ }
338
+ string(value, line, what) {
339
+ if (isScalar(value) && typeof value.value === 'string')
340
+ return value.value;
341
+ this.problem(line, `${what} takes a string, not ${describe(value)}`);
342
+ return null;
343
+ }
344
+ line(value, line, what) {
345
+ const text = this.string(value, line, what);
346
+ if (text === null)
347
+ return null;
348
+ if (text.trim() === '') {
349
+ this.problem(line, `${what} is empty`);
350
+ return null;
351
+ }
352
+ if (/[\r\n]/.test(text)) {
353
+ this.problem(line, `${what} holds a line break`);
354
+ return null;
355
+ }
356
+ return text;
357
+ }
358
+ paths(value, line, what) {
359
+ const items = isSeq(value) ? value.items.map((item) => this.resolve(item)) : null;
360
+ if (items === null || items.some((node) => !(isScalar(node) && typeof node.value === 'string'))) {
361
+ this.problem(line, `${what} takes a sequence of paths, not ${isSeq(value) ? 'a sequence with an item that is no string' : describe(value)}`);
362
+ return null;
363
+ }
364
+ return items.map((node) => ({ path: node.value, line: this.lineOf(node) }));
365
+ }
366
+ strings(value, line, what) {
367
+ if (!isSeq(value)) {
368
+ this.problem(line, `${what} takes a sequence of strings, not ${describe(value)}`);
369
+ return null;
370
+ }
371
+ const out = [];
372
+ let valid = true;
373
+ for (const item of value.items) {
374
+ const node = this.resolve(item);
375
+ const itemLine = node ? this.lineOf(node) : line;
376
+ if (isScalar(node) && typeof node.value === 'string')
377
+ out.push({ text: node.value, line: itemLine });
378
+ else {
379
+ valid = false;
380
+ this.problem(itemLine, `${what} takes a sequence of strings, and one item is ${describe(node)}`);
381
+ }
382
+ }
383
+ return valid ? out : null;
384
+ }
385
+ }
386
+ function describe(value) {
387
+ if (value === null)
388
+ return 'nothing';
389
+ if (isMap(value))
390
+ return 'a mapping';
391
+ if (isSeq(value))
392
+ return 'a sequence';
393
+ if (isScalar(value)) {
394
+ const v = value.value;
395
+ if (v === null)
396
+ return 'nothing';
397
+ if (typeof v === 'string')
398
+ return 'a string';
399
+ if (typeof v === 'number' || typeof v === 'bigint')
400
+ return 'a number';
401
+ if (typeof v === 'boolean')
402
+ return 'a boolean';
403
+ }
404
+ return 'another kind of value';
405
+ }
406
+ // A type without the key takes its parent's value, and a root type without it reads waivers.
407
+ export function takesWaivers(type) {
408
+ for (let at = type; at !== null; at = at.parent)
409
+ if (at.waivers !== null)
410
+ return at.waivers;
411
+ return true;
412
+ }
413
+ export function firstLine(error) {
414
+ const text = error instanceof Error ? error.message : String(error);
415
+ return text.split(/\r?\n/)[0] ?? '';
416
+ }