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/files.js ADDED
@@ -0,0 +1,388 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { copyFileSync, existsSync, lstatSync } from 'node:fs';
3
+ import { devNull } from 'node:os';
4
+ import { dirname, join, resolve, sep } from 'node:path';
5
+ import { findProgram } from './programs.js';
6
+ import { guardedFolder, releaseFolder } from './rules.js';
7
+ import { bytesOfName, nameOf, onDisk, quotedLine } from './names.js';
8
+ import { receiveMessageOnPort } from 'node:worker_threads';
9
+ import { step } from './progress.js';
10
+ export class NoGit extends Error {
11
+ }
12
+ export class GitFailed extends Error {
13
+ }
14
+ const loose = new TextDecoder('utf-8', { ignoreBOM: true });
15
+ let channel = null;
16
+ // In the worker git runs in the main thread, which can end it at a signal; the worker waits for its reply as a synchronous call would.
17
+ export function gitThroughMainThread(port, flag) {
18
+ channel = { port, flag: new Int32Array(flag) };
19
+ }
20
+ function run(request) {
21
+ if (channel === null) {
22
+ const result = spawnSync(request.program, request.args, { cwd: request.root, env: request.env, input: request.input, maxBuffer: 1 << 30, stdio: [request.input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] });
23
+ const error = result.error ? { code: result.error.code ?? null, message: result.error.message } : null;
24
+ return { error, status: result.status, signal: result.signal, stdout: result.stdout ?? new Uint8Array(), stderr: result.stderr ?? new Uint8Array() };
25
+ }
26
+ Atomics.store(channel.flag, 0, 0);
27
+ channel.port.postMessage(request);
28
+ for (;;) {
29
+ Atomics.wait(channel.flag, 0, 0);
30
+ const reply = receiveMessageOnPort(channel.port);
31
+ if (reply !== undefined)
32
+ return reply.message;
33
+ Atomics.store(channel.flag, 0, 0);
34
+ }
35
+ }
36
+ const filters = new Map();
37
+ function filterKeys(program, cwd) {
38
+ let keys = filters.get(cwd);
39
+ if (keys === undefined) {
40
+ const listed = run({ program, root: cwd, args: ['config', '-z', '--name-only', '--get-regexp', '^filter\\.'], env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' } });
41
+ keys = listed.status === 0 ? new TextDecoder().decode(listed.stdout).split('\0').filter((key) => /^filter\..+\.(clean|smudge|process)$/.test(key)) : [];
42
+ filters.set(cwd, keys);
43
+ }
44
+ return keys;
45
+ }
46
+ // A repository's config and attributes can name programs that git starts while it only reads; these settings start none of them.
47
+ function startsNothing(program, cwd) {
48
+ const settings = [
49
+ ['core.fsmonitor', ''],
50
+ ['core.hooksPath', devNull],
51
+ ['diff.external', ''],
52
+ ];
53
+ for (const key of filterKeys(program, cwd))
54
+ settings.push([key, ''], [`${key.slice(0, key.lastIndexOf('.'))}.required`, 'false']);
55
+ const env = { ...process.env, GIT_OPTIONAL_LOCKS: '0' };
56
+ const given = Number(env.GIT_CONFIG_COUNT);
57
+ const start = Number.isInteger(given) && given > 0 ? given : 0;
58
+ settings.forEach(([key, value], index) => {
59
+ env[`GIT_CONFIG_KEY_${start + index}`] = key;
60
+ env[`GIT_CONFIG_VALUE_${start + index}`] = value;
61
+ });
62
+ env.GIT_CONFIG_COUNT = String(start + settings.length);
63
+ return env;
64
+ }
65
+ let gitProgram;
66
+ export function git(root, args, extra = {}, input) {
67
+ // git by its path on PATH, so no relative entry and no current folder can put the repository's own git in its place; Windows starts git.exe alone.
68
+ gitProgram ??= findProgram('git', { ...Object.fromEntries(Object.entries(process.env).filter(([name]) => name.toUpperCase() !== 'PATHEXT')), PATHEXT: '.EXE' });
69
+ if (gitProgram === null)
70
+ throw new NoGit('git cannot be started: it is not on the PATH');
71
+ step(`running git ${args.join(' ')}`);
72
+ const result = run({ program: gitProgram, root, args, env: { ...startsNothing(gitProgram, root), ...extra }, input });
73
+ if (result.error) {
74
+ const code = result.error.code;
75
+ if (code === 'ENOENT' || code === 'EACCES')
76
+ throw new NoGit(`git cannot be started: ${result.error.message}`);
77
+ throw new GitFailed(`git ${args[0]} failed: ${result.error.message}`);
78
+ }
79
+ if (result.status === null)
80
+ throw new GitFailed(`git ${args[0]} ended by the signal ${result.signal}`);
81
+ return { status: result.status, stdout: Buffer.from(result.stdout.buffer, result.stdout.byteOffset, result.stdout.byteLength), stderr: Buffer.from(result.stderr.buffer, result.stderr.byteOffset, result.stderr.byteLength) };
82
+ }
83
+ function firstPrinted(result) {
84
+ const text = loose.decode(result.stderr.length > 0 ? result.stderr : result.stdout);
85
+ return text.split(/\r?\n/).find((line) => line.trim() !== '') ?? '';
86
+ }
87
+ function failed(args, result) {
88
+ return new GitFailed(`git ${args.join(' ')} exited with ${result.status}: ${firstPrinted(result)}`);
89
+ }
90
+ export function splitZ(output) {
91
+ const paths = [];
92
+ let start = 0;
93
+ for (let i = 0; i < output.length; i++) {
94
+ if (output[i] !== 0)
95
+ continue;
96
+ if (i > start)
97
+ paths.push(nameOf(output.subarray(start, i)));
98
+ start = i + 1;
99
+ }
100
+ return paths;
101
+ }
102
+ export function workTreeProblem(root) {
103
+ const args = ['rev-parse', '--is-inside-work-tree'];
104
+ const result = git(root, args);
105
+ const word = loose.decode(result.stdout).trim();
106
+ if (result.status === 0 && word === 'true')
107
+ return null;
108
+ return `git does not see a work tree here: ${firstPrinted(result)}`;
109
+ }
110
+ function quoted(path) {
111
+ return /^[\w@%+=:,./\\-]+$/.test(path) ? path : `'${path.replace(/'/g, `'\\''`)}'`;
112
+ }
113
+ function repositoryAbove(dir) {
114
+ for (let at = resolve(dir);; at = dirname(at)) {
115
+ if (existsSync(join(at, '.git')))
116
+ return at;
117
+ if (dirname(at) === at)
118
+ return null;
119
+ }
120
+ }
121
+ // What git's own sentence asks of the user, where the plain next line of no-git would send them to the work tree they are in. The command is written for a POSIX shell, as docs/ci.md says.
122
+ export function gitNext(dir, problem) {
123
+ const dubious = /dubious ownership in repository at '(.*)'\s*$/.exec(problem);
124
+ if (dubious !== null) {
125
+ const command = `git config --global --add safe.directory ${quoted(dubious[1])}`;
126
+ return { next: `let git trust the repository: ${command}, then run lawcheck check`, command };
127
+ }
128
+ const repository = /not a git repository/.test(problem) ? repositoryAbove(dir) : null;
129
+ if (repository !== null)
130
+ return { next: `repair the repository at ${repository}, so that git status works there, then run lawcheck check` };
131
+ return undefined;
132
+ }
133
+ export function listFiles(root, listed = listedPaths(root)) {
134
+ const files = [];
135
+ for (const path of listed) {
136
+ try {
137
+ if (lstatSync(onDisk(root, path)).isFile())
138
+ files.push(path);
139
+ }
140
+ catch (error) {
141
+ const code = error.code;
142
+ // A path git lists below a folder that cannot be searched may be a file; reading it later names it as unreadable when a type takes it.
143
+ if (code === 'EACCES' || code === 'EPERM')
144
+ files.push(path);
145
+ else if (code !== 'ENOENT' && code !== 'ENOTDIR')
146
+ throw error;
147
+ }
148
+ }
149
+ return files.sort(comparePaths);
150
+ }
151
+ export function comparePaths(a, b) {
152
+ return a < b ? -1 : a > b ? 1 : 0;
153
+ }
154
+ export function hasHead(root) {
155
+ const args = ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'];
156
+ const result = git(root, args);
157
+ if (result.status === 0)
158
+ return true;
159
+ if (result.status === 1)
160
+ return false;
161
+ throw failed(args, result);
162
+ }
163
+ export function defaultBase(root) {
164
+ const args = ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'];
165
+ const result = git(root, args);
166
+ if (result.status === 0)
167
+ return loose.decode(result.stdout).trim();
168
+ if (result.status === 1)
169
+ return null;
170
+ throw failed(args, result);
171
+ }
172
+ export function resolveCommit(root, base) {
173
+ const result = git(root, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${base}^{commit}`]);
174
+ return result.status === 0 ? loose.decode(result.stdout).trim() : null;
175
+ }
176
+ export function remoteNames(root) {
177
+ const result = git(root, ['remote']);
178
+ return result.status === 0 ? loose.decode(result.stdout).split(/\r?\n/).filter((name) => name !== '') : [];
179
+ }
180
+ // A clone made with --single-branch or --depth fetches one branch; its fetch lines name no refs/heads/*.
181
+ export function fetchesEveryBranch(root, remote) {
182
+ const result = git(root, ['config', '--get-all', `remote.${remote}.fetch`]);
183
+ return result.status !== 0 || loose.decode(result.stdout).split(/\r?\n/).some((line) => line.includes('refs/heads/*'));
184
+ }
185
+ export function isShallow(root) {
186
+ const result = git(root, ['rev-parse', '--is-shallow-repository']);
187
+ return result.status === 0 && loose.decode(result.stdout).trim() === 'true';
188
+ }
189
+ export function mergeBase(root, commit) {
190
+ const args = ['merge-base', 'HEAD', commit];
191
+ const result = git(root, args);
192
+ if (result.status === 0)
193
+ return loose.decode(result.stdout).trim();
194
+ if (result.status === 1)
195
+ return null;
196
+ throw failed(args, result);
197
+ }
198
+ // git diff writes the index again when the times of its files no longer match it, whatever GIT_OPTIONAL_LOCKS says, so the change is read through a copy of the index.
199
+ function onIndexCopy(root, read) {
200
+ const pathArgs = ['rev-parse', '--git-path', 'index'];
201
+ const found = git(root, pathArgs);
202
+ if (found.status !== 0)
203
+ throw failed(pathArgs, found);
204
+ const resolved = resolve(root, loose.decode(found.stdout).replace(/\r?\n$/, ''));
205
+ if (!existsSync(resolved))
206
+ return read({});
207
+ let folder;
208
+ try {
209
+ folder = guardedFolder('lawcheck-index-');
210
+ }
211
+ catch {
212
+ // Without a temporary folder the diff reads the index itself: the change is the same, and git may write the index again with fresh times.
213
+ return read({});
214
+ }
215
+ try {
216
+ try {
217
+ copyFileSync(resolved, join(folder, 'index'));
218
+ }
219
+ catch {
220
+ return read({});
221
+ }
222
+ return read({ GIT_INDEX_FILE: join(folder, 'index') });
223
+ }
224
+ finally {
225
+ releaseFolder(folder);
226
+ }
227
+ }
228
+ export function changedPaths(root, base) {
229
+ const diffArgs = ['diff', '--no-ext-diff', '--no-textconv', '--ignore-submodules=all', '-z', '--name-only', '--no-renames', '--relative', base, '--'];
230
+ const diff = onIndexCopy(root, (env) => git(root, diffArgs, env));
231
+ if (diff.status !== 0)
232
+ throw failed(diffArgs, diff);
233
+ const othersArgs = ['ls-files', '-z', '--others', '--exclude-standard'];
234
+ const others = git(root, othersArgs);
235
+ if (others.status !== 0)
236
+ throw failed(othersArgs, others);
237
+ return [...splitZ(diff.stdout), ...splitZ(others.stdout), ...hiddenEdits(root, base)];
238
+ }
239
+ // git's diff trusts the index for a file marked assume-unchanged or skip-worktree (a sparse checkout sets the second), so an edit of one on disk is found by its content (stress finding S1-14).
240
+ function hiddenEdits(root, base) {
241
+ const listArgs = ['ls-files', '-v', '-z'];
242
+ const listed = git(root, listArgs);
243
+ if (listed.status !== 0)
244
+ throw failed(listArgs, listed);
245
+ const marked = [];
246
+ let start = 0;
247
+ const out = listed.stdout;
248
+ for (let i = 0; i < out.length; i++) {
249
+ if (out[i] !== 0)
250
+ continue;
251
+ const tag = out[start];
252
+ if (i - start > 2 && ((tag >= 0x61 && tag <= 0x7a) || tag === 0x53)) {
253
+ const bytes = out.subarray(start + 2, i);
254
+ try {
255
+ if (lstatSync(onDisk(root, nameOf(bytes))).isFile())
256
+ marked.push(bytes);
257
+ }
258
+ catch {
259
+ // A marked file that is gone is the index's business; git's diff shows a deletion only when the index changed.
260
+ }
261
+ }
262
+ start = i + 1;
263
+ }
264
+ if (marked.length === 0)
265
+ return [];
266
+ const hashArgs = ['hash-object', '--stdin-paths'];
267
+ const prefix = showPrefix(root);
268
+ const hashed = git(root, hashArgs, {}, Buffer.concat(marked.map((bytes) => quotedLine(prefix, bytes))));
269
+ if (hashed.status !== 0)
270
+ throw failed(hashArgs, hashed);
271
+ const ids = hashed.stdout.toString('utf8').split('\n');
272
+ const treeArgs = ['ls-tree', '-r', '-z', base];
273
+ const tree = git(root, treeArgs);
274
+ if (tree.status !== 0)
275
+ throw failed(treeArgs, tree);
276
+ const inBase = new Map();
277
+ for (const entry of splitZ(tree.stdout)) {
278
+ const tab = entry.indexOf('\t');
279
+ inBase.set(entry.slice(tab + 1), entry.slice(0, tab).split(' ')[2]);
280
+ }
281
+ return marked.map((bytes) => nameOf(bytes)).filter((name, i) => inBase.get(name) !== ids[i]);
282
+ }
283
+ export function showPrefix(dir) {
284
+ const args = ['rev-parse', '--show-prefix'];
285
+ const result = git(dir, args);
286
+ if (result.status !== 0)
287
+ throw failed(args, result);
288
+ return loose.decode(result.stdout).replace(/\r?\n$/, '');
289
+ }
290
+ export function ignoresPath(root, path) {
291
+ const args = ['check-ignore', '-q', '--no-index', '--stdin', '-z'];
292
+ const result = git(root, args, {}, Buffer.concat([bytesOfName(path), Buffer.from([0])]));
293
+ if (result.status === 0)
294
+ return true;
295
+ if (result.status === 1)
296
+ return false;
297
+ throw failed(args, result);
298
+ }
299
+ // Every link git tracks under the root and in its checked-out submodules, by its bytes: a name with a line break or bytes that are not UTF-8 is a link like any other. Each submodule is listed in its own folder, since git 2.34 refuses --recurse-submodules with --stage.
300
+ export function trackedLinks(root) {
301
+ const links = [];
302
+ const list = (dir, prefix) => {
303
+ const args = ['ls-files', '-z', '--stage'];
304
+ const result = git(dir.toString('utf8'), args);
305
+ if (result.status !== 0)
306
+ throw failed(args, result);
307
+ let start = 0;
308
+ for (let i = 0; i < result.stdout.length; i++) {
309
+ if (result.stdout[i] !== 0)
310
+ continue;
311
+ const entry = result.stdout.subarray(start, i);
312
+ start = i + 1;
313
+ const tab = entry.indexOf(9);
314
+ if (tab < 0)
315
+ continue;
316
+ const path = Buffer.from(entry.subarray(tab + 1));
317
+ const mode = entry.subarray(0, 7).toString('latin1');
318
+ if (mode === '120000 ') {
319
+ const bytes = Buffer.concat([prefix, path]);
320
+ links.push({ name: loose.decode(bytes), bytes });
321
+ }
322
+ else if (mode === '160000 ') {
323
+ const sub = Buffer.concat([dir, Buffer.from(sep), path]);
324
+ if (existsSync(Buffer.concat([sub, Buffer.from(sep + '.git')])))
325
+ list(sub, Buffer.concat([prefix, path, Buffer.from('/')]));
326
+ }
327
+ }
328
+ };
329
+ list(Buffer.from(root), Buffer.alloc(0));
330
+ return links;
331
+ }
332
+ export function workTreeTop(root) {
333
+ const args = ['rev-parse', '--show-toplevel'];
334
+ const result = git(root, args);
335
+ if (result.status !== 0)
336
+ throw failed(args, result);
337
+ return loose.decode(result.stdout).replace(/\r?\n$/, '');
338
+ }
339
+ export function listedPaths(root) {
340
+ const args = ['ls-files', '-z', '--cached', '--others', '--exclude-standard'];
341
+ const result = git(root, args);
342
+ if (result.status !== 0)
343
+ throw failed(args, result);
344
+ return new Set(splitZ(result.stdout));
345
+ }
346
+ // A submodule is listed as its directory, and an untracked repository inside the work tree as its directory with a trailing slash; git lists no file of either.
347
+ export function nestedRepositories(root, listed) {
348
+ const out = [];
349
+ for (const path of listed) {
350
+ const dir = path.endsWith('/') ? path.slice(0, -1) : path;
351
+ try {
352
+ if (lstatSync(onDisk(root, dir)).isDirectory())
353
+ out.push({ dir, submodule: !path.endsWith('/') });
354
+ }
355
+ catch (error) {
356
+ const code = error.code;
357
+ if (code !== 'ENOENT' && code !== 'ENOTDIR' && code !== 'ENAMETOOLONG')
358
+ throw error;
359
+ }
360
+ }
361
+ return out.sort((a, b) => comparePaths(a.dir, b.dir));
362
+ }
363
+ export function repositoryHolding(root, path, listed) {
364
+ const parts = path.split('/');
365
+ for (let i = 1; i < parts.length; i++) {
366
+ const dir = parts.slice(0, i).join('/');
367
+ if (listed.has(dir) || listed.has(`${dir}/`)) {
368
+ try {
369
+ if (lstatSync(onDisk(root, dir)).isDirectory())
370
+ return { dir, submodule: listed.has(dir) };
371
+ }
372
+ catch {
373
+ return null;
374
+ }
375
+ }
376
+ try {
377
+ lstatSync(onDisk(root, `${dir}/.git`));
378
+ return { dir, submodule: false };
379
+ }
380
+ catch {
381
+ // No repository of its own at this level.
382
+ }
383
+ }
384
+ return null;
385
+ }
386
+ export function nestedReason(nested) {
387
+ return `it lies in ${nested.dir}, ${nested.submodule ? 'a submodule' : 'a repository of its own'}, which Lawcheck does not look into`;
388
+ }
package/dist/glob.js ADDED
@@ -0,0 +1,268 @@
1
+ export function patternProblem(pattern) {
2
+ if (pattern === '')
3
+ return 'is empty';
4
+ const body = pattern.startsWith('!') ? pattern.slice(1) : pattern;
5
+ if (body === '')
6
+ return "is '!' alone";
7
+ let open = false;
8
+ let length = 0;
9
+ for (const ch of body) {
10
+ if (ch === '{') {
11
+ if (open)
12
+ return 'nests a brace';
13
+ open = true;
14
+ length = 0;
15
+ }
16
+ else if (ch === '}') {
17
+ if (!open)
18
+ return 'closes a brace it never opened';
19
+ if (length === 0)
20
+ return 'holds an empty alternative';
21
+ open = false;
22
+ }
23
+ else if (open && ch === ',') {
24
+ if (length === 0)
25
+ return 'holds an empty alternative';
26
+ length = 0;
27
+ }
28
+ else if (open && ch === '/') {
29
+ return "holds a '/' inside a brace";
30
+ }
31
+ else if (open) {
32
+ length++;
33
+ }
34
+ }
35
+ if (open)
36
+ return 'leaves a brace unclosed';
37
+ for (const segment of body.split('/')) {
38
+ if (segment === '')
39
+ return 'holds an empty segment';
40
+ if (segment === '.' || segment === '..')
41
+ return `holds the segment '${segment}'`;
42
+ if (segment !== '**' && segment.includes('**'))
43
+ return 'holds ** beside other characters in one segment';
44
+ }
45
+ return null;
46
+ }
47
+ const EPSILON = 0;
48
+ const CHARACTER = 1;
49
+ const NOT_SLASH = 2;
50
+ const ANY = 3;
51
+ const MATCH = 4;
52
+ const SLASH = 0x2f;
53
+ // The states a matcher keeps between paths; past this many it starts afresh, so memory stays bounded whatever the paths.
54
+ const MOST_STATES = 4096;
55
+ class Automaton {
56
+ kinds = [];
57
+ points = [];
58
+ outs = [];
59
+ add(kind, point = 0) {
60
+ this.kinds.push(kind);
61
+ this.points.push(point);
62
+ this.outs.push([]);
63
+ return this.kinds.length - 1;
64
+ }
65
+ link(from, to) {
66
+ this.outs[from].push(to);
67
+ }
68
+ step(tail, kind, point = 0) {
69
+ const state = this.add(kind, point);
70
+ this.link(tail, state);
71
+ const next = this.add(EPSILON);
72
+ this.link(state, next);
73
+ return next;
74
+ }
75
+ }
76
+ function segmentStates(nfa, tail, segment) {
77
+ let open = false;
78
+ let branchStart = tail;
79
+ let end = -1;
80
+ for (const ch of segment) {
81
+ if (ch === '{') {
82
+ open = true;
83
+ branchStart = tail;
84
+ end = nfa.add(EPSILON);
85
+ }
86
+ else if (ch === '}' && open) {
87
+ nfa.link(tail, end);
88
+ tail = end;
89
+ open = false;
90
+ }
91
+ else if (ch === ',' && open) {
92
+ nfa.link(tail, end);
93
+ tail = branchStart;
94
+ }
95
+ else if (ch === '*') {
96
+ const loop = nfa.add(EPSILON);
97
+ nfa.link(tail, loop);
98
+ const any = nfa.add(NOT_SLASH);
99
+ nfa.link(loop, any);
100
+ nfa.link(any, loop);
101
+ tail = loop;
102
+ }
103
+ else if (ch === '?') {
104
+ tail = nfa.step(tail, NOT_SLASH);
105
+ }
106
+ else {
107
+ tail = nfa.step(tail, CHARACTER, ch.codePointAt(0));
108
+ }
109
+ }
110
+ return tail;
111
+ }
112
+ function build(pattern) {
113
+ const nfa = new Automaton();
114
+ let tail = nfa.add(EPSILON);
115
+ const segments = pattern.split('/');
116
+ segments.forEach((segment, index) => {
117
+ const last = index === segments.length - 1;
118
+ if (segment === '**' && last) {
119
+ const any = nfa.add(ANY);
120
+ nfa.link(tail, any);
121
+ const after = nfa.add(EPSILON);
122
+ nfa.link(any, after);
123
+ nfa.link(after, any);
124
+ tail = after;
125
+ }
126
+ else if (segment === '**') {
127
+ const start = nfa.add(EPSILON);
128
+ nfa.link(tail, start);
129
+ const first = nfa.add(NOT_SLASH);
130
+ nfa.link(start, first);
131
+ const inName = nfa.add(EPSILON);
132
+ nfa.link(first, inName);
133
+ const more = nfa.add(NOT_SLASH);
134
+ nfa.link(inName, more);
135
+ nfa.link(more, inName);
136
+ const slash = nfa.add(CHARACTER, SLASH);
137
+ nfa.link(inName, slash);
138
+ nfa.link(slash, start);
139
+ tail = start;
140
+ }
141
+ else {
142
+ tail = segmentStates(nfa, tail, segment);
143
+ if (!last)
144
+ tail = nfa.step(tail, CHARACTER, SLASH);
145
+ }
146
+ });
147
+ nfa.link(tail, nfa.add(MATCH));
148
+ return nfa;
149
+ }
150
+ // A pattern runs as an automaton over the path's code points, built into a deterministic one as paths need it, so a match costs time linear in the path whatever the pattern holds; a backtracking regular expression costs a power of the path's length for a segment like *a*a*a*b.
151
+ export function compilePattern(pattern) {
152
+ const nfa = build(pattern);
153
+ const count = nfa.kinds.length;
154
+ const classes = new Map([[SLASH, 1]]);
155
+ for (let state = 0; state < count; state++) {
156
+ if (nfa.kinds[state] === CHARACTER && !classes.has(nfa.points[state]))
157
+ classes.set(nfa.points[state], classes.size + 1);
158
+ }
159
+ const width = classes.size + 1;
160
+ const mark = new Int32Array(count);
161
+ let generation = 0;
162
+ const close = (seeds) => {
163
+ generation++;
164
+ const out = [];
165
+ const stack = [...seeds];
166
+ while (stack.length > 0) {
167
+ const state = stack.pop();
168
+ if (mark[state] === generation)
169
+ continue;
170
+ mark[state] = generation;
171
+ if (nfa.kinds[state] === EPSILON)
172
+ for (const next of nfa.outs[state])
173
+ stack.push(next);
174
+ else
175
+ out.push(state);
176
+ }
177
+ return out.sort((a, b) => a - b);
178
+ };
179
+ let sets = [];
180
+ let accepting = [];
181
+ let ids = new Map();
182
+ let moves = [];
183
+ const intern = (set) => {
184
+ const key = set.join(',');
185
+ let id = ids.get(key);
186
+ if (id === undefined) {
187
+ id = sets.length;
188
+ ids.set(key, id);
189
+ sets.push(set);
190
+ accepting.push(set.some((state) => nfa.kinds[state] === MATCH));
191
+ moves.push(new Int32Array(width).fill(-1));
192
+ }
193
+ return id;
194
+ };
195
+ const reset = () => {
196
+ sets = [];
197
+ accepting = [];
198
+ ids = new Map();
199
+ moves = [];
200
+ intern(close([0]));
201
+ };
202
+ reset();
203
+ const leads = new Uint8Array(count);
204
+ const back = Array.from({ length: count }, () => []);
205
+ for (let state = 0; state < count; state++)
206
+ for (const next of nfa.outs[state])
207
+ back[next].push(state);
208
+ const queue = nfa.kinds.flatMap((kind, state) => (kind === MATCH ? [state] : []));
209
+ for (const state of queue)
210
+ leads[state] = 1;
211
+ while (queue.length > 0) {
212
+ for (const before of back[queue.pop()]) {
213
+ if (leads[before] === 0) {
214
+ leads[before] = 1;
215
+ queue.push(before);
216
+ }
217
+ }
218
+ }
219
+ const move = (from, point, cls) => {
220
+ const seeds = [];
221
+ for (const state of sets[from]) {
222
+ const kind = nfa.kinds[state];
223
+ const takes = kind === ANY ||
224
+ (kind === NOT_SLASH && point !== SLASH) ||
225
+ (kind === CHARACTER && nfa.points[state] === point);
226
+ if (takes)
227
+ seeds.push(...nfa.outs[state]);
228
+ }
229
+ const to = intern(close(seeds));
230
+ moves[from][cls] = to;
231
+ return to;
232
+ };
233
+ const run = (path) => {
234
+ if (sets.length > MOST_STATES)
235
+ reset();
236
+ let at = 0;
237
+ for (const ch of path) {
238
+ const point = ch.codePointAt(0);
239
+ const cls = classes.get(point) ?? 0;
240
+ const known = moves[at][cls];
241
+ at = known >= 0 ? known : move(at, point, cls);
242
+ if (sets[at].length === 0)
243
+ return null;
244
+ }
245
+ return at;
246
+ };
247
+ return {
248
+ test(path) {
249
+ const at = run(path);
250
+ return at !== null && accepting[at];
251
+ },
252
+ reaches(prefix) {
253
+ const at = run(prefix);
254
+ return at !== null && sets[at].some((state) => leads[state] === 1);
255
+ },
256
+ };
257
+ }
258
+ export function compileList(patterns) {
259
+ const plain = [];
260
+ const excluded = [];
261
+ for (const pattern of patterns) {
262
+ if (pattern.startsWith('!'))
263
+ excluded.push(compilePattern(pattern.slice(1)));
264
+ else
265
+ plain.push(compilePattern(pattern));
266
+ }
267
+ return (path) => plain.some((p) => p.test(path)) && !excluded.some((p) => p.test(path));
268
+ }