@tobi-or-not/quorum 0.4.0 → 0.5.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.
Files changed (71) hide show
  1. package/README.md +1 -1
  2. package/dist/bench/fingerprint.d.ts +7 -5
  3. package/dist/bench/fingerprint.js +22 -9
  4. package/dist/bench/records.d.ts +70 -0
  5. package/dist/bench/records.js +30 -0
  6. package/dist/bench/runner.d.ts +18 -0
  7. package/dist/bench/runner.js +29 -3
  8. package/dist/cli/bench.d.ts +11 -4
  9. package/dist/cli/bench.js +34 -17
  10. package/dist/cli/bin.js +2 -2
  11. package/dist/cli/main.d.ts +34 -14
  12. package/dist/cli/main.js +99 -20
  13. package/dist/cli/print-config.d.ts +8 -6
  14. package/dist/cli/print-config.js +21 -8
  15. package/dist/cli/render.d.ts +2 -2
  16. package/dist/cli/render.js +21 -2
  17. package/dist/config/env.d.ts +32 -19
  18. package/dist/config/env.js +95 -32
  19. package/dist/config/from-config.js +15 -3
  20. package/dist/config/resolve.d.ts +9 -1
  21. package/dist/config/resolve.js +17 -1
  22. package/dist/config/schema.d.ts +141 -5
  23. package/dist/config/schema.js +125 -12
  24. package/dist/core/clock.d.ts +17 -0
  25. package/dist/core/clock.js +14 -0
  26. package/dist/core/coverage.d.ts +49 -0
  27. package/dist/core/coverage.js +144 -0
  28. package/dist/core/diff.d.ts +24 -0
  29. package/dist/core/diff.js +63 -18
  30. package/dist/core/errors.d.ts +12 -3
  31. package/dist/core/errors.js +21 -2
  32. package/dist/core/exclude.d.ts +42 -0
  33. package/dist/core/exclude.js +189 -0
  34. package/dist/core/limits.d.ts +82 -0
  35. package/dist/core/limits.js +163 -0
  36. package/dist/core/output.d.ts +3 -2
  37. package/dist/core/output.js +3 -2
  38. package/dist/core/ports.d.ts +57 -2
  39. package/dist/core/ports.js +36 -1
  40. package/dist/core/quorum.d.ts +24 -8
  41. package/dist/core/quorum.js +187 -56
  42. package/dist/core/retry.d.ts +36 -0
  43. package/dist/core/retry.js +46 -0
  44. package/dist/core/stages/context.d.ts +118 -23
  45. package/dist/core/stages/context.js +304 -46
  46. package/dist/core/stages/panel.d.ts +5 -4
  47. package/dist/core/stages/panel.js +30 -11
  48. package/dist/core/stages/research.d.ts +15 -6
  49. package/dist/core/stages/research.js +75 -18
  50. package/dist/core/tokens.d.ts +31 -0
  51. package/dist/core/tokens.js +81 -0
  52. package/dist/core/types.d.ts +77 -10
  53. package/dist/index.d.ts +1 -1
  54. package/dist/providers/anthropic.d.ts +2 -1
  55. package/dist/providers/anthropic.js +8 -3
  56. package/dist/providers/claude-code.d.ts +51 -11
  57. package/dist/providers/claude-code.js +60 -25
  58. package/dist/providers/gemini.d.ts +4 -1
  59. package/dist/providers/gemini.js +63 -11
  60. package/dist/providers/http.d.ts +49 -4
  61. package/dist/providers/http.js +155 -14
  62. package/dist/providers/ollama.d.ts +3 -1
  63. package/dist/providers/ollama.js +11 -5
  64. package/dist/providers/openai-compatible.d.ts +3 -1
  65. package/dist/providers/openai-compatible.js +11 -5
  66. package/dist/providers/options.d.ts +12 -3
  67. package/dist/providers/options.js +30 -10
  68. package/dist/providers/size.d.ts +10 -14
  69. package/dist/providers/size.js +15 -69
  70. package/package.json +1 -1
  71. package/schema/quorum.schema.json +34 -1
@@ -0,0 +1,144 @@
1
+ import { diffSections, movedTo } from "./diff.js";
2
+ const BINARY_FILES_START = 'Binary files ';
3
+ const BINARY_FILES_END = ' differ';
4
+ const BINARY_PATCH = 'GIT binary patch';
5
+ const SUBPROJECT_COMMIT = 'Subproject commit ';
6
+ const SUBMODULE_MODES = new Set([
7
+ 'new file mode 160000',
8
+ 'deleted file mode 160000',
9
+ 'old mode 160000',
10
+ 'new mode 160000',
11
+ ]);
12
+ const INDEX_START = 'index ';
13
+ const GITLINK_MODE_END = ' 160000';
14
+ /** The line git's `log` and `diff` submodule formats print in place of a header, at the end of the section before it. */
15
+ const SUBMODULE_LINE_START = 'Submodule ';
16
+ /** The characters a hunk row starts with, the only ones that can come before `Subproject commit`. */
17
+ const ROW_MARKERS = '+- ';
18
+ /** Whether `line` (less its `\r`) is a line of the section's own submodule. */
19
+ function isOwnSubmodule(line) {
20
+ return line.startsWith(SUBPROJECT_COMMIT)
21
+ || (line.startsWith(SUBPROJECT_COMMIT, 1) && ROW_MARKERS.includes(line[0]))
22
+ || SUBMODULE_MODES.has(line)
23
+ || (line.startsWith(INDEX_START) && line.endsWith(GITLINK_MODE_END));
24
+ }
25
+ /** The markers of one section, each line read on its own, with no hunk parsing, and at most one marker for a line: binary first, then the section's own submodule, then a `Submodule` line. */
26
+ function markersOf(text) {
27
+ const markers = { binary: false, submodule: false, submoduleLine: false };
28
+ for (const raw of text.split('\n')) {
29
+ const line = raw.endsWith('\r')
30
+ ? raw.slice(0, -1)
31
+ : raw;
32
+ if ((line.startsWith(BINARY_FILES_START) && line.endsWith(BINARY_FILES_END)) || line.startsWith(BINARY_PATCH))
33
+ markers.binary = true;
34
+ else if (isOwnSubmodule(line))
35
+ markers.submodule = true;
36
+ else if (line.startsWith(SUBMODULE_LINE_START))
37
+ markers.submoduleLine = true;
38
+ }
39
+ return markers;
40
+ }
41
+ /**
42
+ * What a review covers of a diff: the files `excluded` leaves out, and the files whose change the
43
+ * diff does not carry, found from the markers git prints in their place, each section read line by
44
+ * line (a trailing `\r` is dropped), so a Windows-made diff reads as any other. In each section:
45
+ * - a `binary` file shows as a line that starts with `Binary files ` and ends with ` differ`, or one
46
+ * that starts with `GIT binary patch`;
47
+ * - a `submodule` shows as a `Subproject commit` row (past at most one leading `+`, `-` or space), a
48
+ * header of mode 160000 (`new file mode`, `deleted file mode`, `old mode` and `new mode`), or an
49
+ * `index` line that ends in ` 160000`;
50
+ * - a `Submodule` line, which git's `log` and `diff` formats print in place of a header, at the end of
51
+ * the section before it, lists a `submodule` under the empty name, whatever section holds it.
52
+ *
53
+ * A file is listed by the diff's own path, decoded, in the diff's order, once per file and reason.
54
+ * `excluded` is asked once per distinct path a header names; a section it takes is listed as
55
+ * `excluded`, leaves the scope's `diff` and has its own markers left unread, but its `Submodule`
56
+ * lines still list their submodule, since such a line belongs to no section. Nothing a header does
57
+ * not name is ever excluded: the text before the first header, a diff without such headers and a
58
+ * header that names no path quorum reads.
59
+ *
60
+ * A header can read two ways: git does not quote a path that holds a space, so a rename's header
61
+ * (`a/src/auth.js b/src/x b/dist/auth.js`) can name a path the file does not have. A section is
62
+ * therefore excluded only when every `rename to` and `copy to` line it holds names the header's
63
+ * path, as `movedTo` reads them; otherwise it is kept, as a header quorum cannot read is, its markers
64
+ * read and its text sent. A forged line, such as a `format-patch` series carries in the next mail's
65
+ * message, can then only make quorum exclude less. That next mail's headers and message sit at the
66
+ * end of the previous file's section and leave with it when that file is excluded: no code hides
67
+ * there, since `git am` applies only the patch sections, and a `Submodule` line still counts.
68
+ *
69
+ * The empty name stands for a part of the diff that no `diff --git` header names: the text before the
70
+ * first header, a diff without such headers, a header that names no path quorum reads, and a
71
+ * `Submodule` line. A readable header never names the empty path, so it is never a file's.
72
+ *
73
+ * Detection is generous: a line of the same form elsewhere, such as a commit message line of a
74
+ * `format-patch` series, lists the file whose section holds it, since a gap it should not have stops a
75
+ * review for a person to look, where a missed one would pass a change unread. The scope's `diff` is
76
+ * the given string itself when no section was excluded, the kept sections joined by line feeds when
77
+ * some were, and '' when every section was.
78
+ */
79
+ export function reviewScope(diff, excluded = () => false) {
80
+ const leftOut = [];
81
+ const listed = {
82
+ excluded: new Set(),
83
+ binary: new Set(),
84
+ submodule: new Set(),
85
+ };
86
+ const list = (file, reason) => {
87
+ if (listed[reason].has(file))
88
+ return;
89
+ listed[reason].add(file);
90
+ leftOut.push({ file, reason });
91
+ };
92
+ const answers = new Map();
93
+ const isExcluded = (path) => {
94
+ let answer = answers.get(path);
95
+ if (answer === undefined) {
96
+ answer = excluded(path);
97
+ answers.set(path, answer);
98
+ }
99
+ return answer;
100
+ };
101
+ const sections = diffSections(diff);
102
+ const kept = [];
103
+ for (const { path, text } of sections) {
104
+ const markers = markersOf(text);
105
+ if (path !== undefined && path !== '' && isExcluded(path) && movedTo(text).every(moved => moved === path)) {
106
+ list(path, 'excluded');
107
+ }
108
+ else {
109
+ kept.push(text);
110
+ if (markers.binary)
111
+ list(path ?? '', 'binary');
112
+ if (markers.submodule)
113
+ list(path ?? '', 'submodule');
114
+ }
115
+ if (markers.submoduleLine)
116
+ list('', 'submodule');
117
+ }
118
+ return {
119
+ diff: kept.length === sections.length
120
+ ? diff
121
+ : kept.join('\n'),
122
+ leftOut,
123
+ };
124
+ }
125
+ /** How a gap's detail names what it counts. An excluded file is no gap, so `excluded` has no entry. */
126
+ const GAP_THINGS = {
127
+ binary: 'binary file(s)',
128
+ submodule: 'submodule(s)',
129
+ };
130
+ /** The gaps the files left out make for one profile: one per reason, binary then submodule, counting its files, and none for a reason with no file. */
131
+ export function leftOutGaps(profile, leftOut) {
132
+ return ['binary', 'submodule'].flatMap((reason) => {
133
+ const count = leftOut.filter(entry => entry.reason === reason).length;
134
+ return count === 0
135
+ ? []
136
+ : [
137
+ {
138
+ profile,
139
+ reason,
140
+ detail: `the diff carries no content for ${count} ${GAP_THINGS[reason]}, listed in meta.leftOut`,
141
+ },
142
+ ];
143
+ });
144
+ }
@@ -1,3 +1,27 @@
1
+ /**
2
+ * The paths the `rename to ` and `copy to ` lines of a section name, in order, each less a trailing
3
+ * `\r` and decoded when git quoted it. Git does not quote a path that holds a space, so a path with a
4
+ * space before `b/` makes a rename's `diff --git` header read two ways (`a/src/auth.js b/src/x
5
+ * b/dist/auth.js` reads as a rename to `dist/auth.js`), while these lines name the new path whole. A
6
+ * hunk row starts with a space, `+`, `-` or `\`, never with these words, so the section's lines are
7
+ * read with no hunk parsing.
8
+ */
9
+ export declare function movedTo(text: string): string[];
10
+ /** One section of a diff: the text from a `diff --git` header to the next, or the text before the first one. */
11
+ export interface DiffSection {
12
+ /** The path the header names; '' for the text before the first header or a diff without headers; undefined for a header that names no readable path. */
13
+ readonly path: string | undefined;
14
+ readonly text: string;
15
+ }
16
+ /**
17
+ * Every section of a git-style unified diff, in order. Only `diff --git` lines open a section, so the
18
+ * text before the first one is a section of its own, of path '', and a diff without such headers
19
+ * (plain `diff -u` output) is one section of path ''. A header that names no path quorum can read
20
+ * gives a section of path `undefined`, kept here whatever `splitDiff` does with it. A section holds
21
+ * at least one line, so a diff that starts with its header has no section before it, and the texts
22
+ * joined by line feeds are the diff.
23
+ */
24
+ export declare function diffSections(diff: string): DiffSection[];
1
25
  /**
2
26
  * Split a git-style unified diff into sections keyed by file path. Only `diff --git` lines open a
3
27
  * section: inside a hunk every line starts with ' ', '+', '-' or '\', so that text cannot appear
package/dist/core/diff.js CHANGED
@@ -1,6 +1,7 @@
1
1
  const GIT_HEADER = 'diff --git ';
2
2
  const QUOTED_NEW_SIDE = ' "b/';
3
3
  const NEW_SIDE_MARKERS = [QUOTED_NEW_SIDE, ' b/'];
4
+ const MOVED_TO_PREFIXES = ['rename to ', 'copy to '];
4
5
  const PATH_PREFIX = /^(?:[ab]\/|\.\/)/;
5
6
  const HUNK_HEADER = /^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
6
7
  /** How many diff lines of a hunk, either side of the cited one, make up a finding's evidence. */
@@ -143,6 +144,61 @@ function headerPath(header) {
143
144
  const names = line.slice(GIT_HEADER.length);
144
145
  return sharedPath(names) || renamedPath(names) || undefined;
145
146
  }
147
+ /**
148
+ * The paths the `rename to ` and `copy to ` lines of a section name, in order, each less a trailing
149
+ * `\r` and decoded when git quoted it. Git does not quote a path that holds a space, so a path with a
150
+ * space before `b/` makes a rename's `diff --git` header read two ways (`a/src/auth.js b/src/x
151
+ * b/dist/auth.js` reads as a rename to `dist/auth.js`), while these lines name the new path whole. A
152
+ * hunk row starts with a space, `+`, `-` or `\`, never with these words, so the section's lines are
153
+ * read with no hunk parsing.
154
+ */
155
+ export function movedTo(text) {
156
+ const paths = [];
157
+ for (const raw of text.split('\n')) {
158
+ const line = raw.endsWith('\r')
159
+ ? raw.slice(0, -1)
160
+ : raw;
161
+ const prefix = MOVED_TO_PREFIXES.find(start => line.startsWith(start));
162
+ if (prefix === undefined)
163
+ continue;
164
+ const name = line.slice(prefix.length);
165
+ paths.push(isQuoted(name)
166
+ ? decodeQuoted(name.slice(1, -1))
167
+ : name);
168
+ }
169
+ return paths;
170
+ }
171
+ /**
172
+ * Every section of a git-style unified diff, in order. Only `diff --git` lines open a section, so the
173
+ * text before the first one is a section of its own, of path '', and a diff without such headers
174
+ * (plain `diff -u` output) is one section of path ''. A header that names no path quorum can read
175
+ * gives a section of path `undefined`, kept here whatever `splitDiff` does with it. A section holds
176
+ * at least one line, so a diff that starts with its header has no section before it, and the texts
177
+ * joined by line feeds are the diff.
178
+ */
179
+ export function diffSections(diff) {
180
+ const sections = [];
181
+ let path = '';
182
+ let lines = [];
183
+ const flush = () => {
184
+ if (lines.length > 0) {
185
+ sections.push({
186
+ path,
187
+ text: lines.join('\n'),
188
+ });
189
+ }
190
+ };
191
+ for (const line of diff.split('\n')) {
192
+ if (line.startsWith(GIT_HEADER)) {
193
+ flush();
194
+ path = headerPath(line);
195
+ lines = [];
196
+ }
197
+ lines.push(line);
198
+ }
199
+ flush();
200
+ return sections;
201
+ }
146
202
  /**
147
203
  * Split a git-style unified diff into sections keyed by file path. Only `diff --git` lines open a
148
204
  * section: inside a hunk every line starts with ' ', '+', '-' or '\', so that text cannot appear
@@ -160,29 +216,18 @@ function headerPath(header) {
160
216
  */
161
217
  export function splitDiff(diff) {
162
218
  const sections = new Map();
163
- let path = '';
164
- let lines = [];
165
- const flush = () => {
166
- if (path === undefined || lines.length === 0)
167
- return;
168
- const text = lines.join('\n');
219
+ const all = diffSections(diff);
220
+ for (const { path, text } of all) {
221
+ if (path === undefined)
222
+ continue;
169
223
  const previous = sections.get(path);
170
224
  sections.set(path, previous === undefined
171
225
  ? text
172
226
  : `${previous}\n${text}`);
173
- };
174
- for (const line of diff.split('\n')) {
175
- if (line.startsWith(GIT_HEADER)) {
176
- flush();
177
- path = headerPath(line);
178
- lines = [];
179
- }
180
- lines.push(line);
181
227
  }
182
- flush();
183
- // `path` is '' only before the first header: when every header was unreadable, the preamble is
184
- // all that is left, and it must not stand for a file.
185
- if (path !== '' && sections.size === 1)
228
+ // A section whose path is not '' means a header was met, an unreadable one included: when every
229
+ // header was unreadable, the preamble is all that is left, and it must not stand for a file.
230
+ if (all.some(({ path }) => path !== '') && sections.size === 1)
186
231
  sections.delete('');
187
232
  return sections;
188
233
  }
@@ -27,8 +27,10 @@ export declare class ConfigError extends QuorumError {
27
27
  readonly issues: readonly ConfigIssue[];
28
28
  constructor(issues: readonly ConfigIssue[]);
29
29
  }
30
- /** What went wrong with a provider call. `retryable` is derived from it. */
31
- export type ProviderErrorKind = 'http' | 'network' | 'process' | 'timeout' | 'aborted' | 'refusal' | 'truncated' | 'invalid-response' | 'unsupported' | 'too-large';
30
+ /** Every kind of a provider call's failure: the kinds a `ProviderError` has, and the only ones a gap's detail names. */
31
+ export declare const PROVIDER_ERROR_KINDS: readonly ["http", "network", "process", "timeout", "aborted", "refusal", "truncated", "invalid-response", "unsupported", "too-large"];
32
+ /** What went wrong with a provider call. `retryable` is derived from it, unless the adapter sets it. */
33
+ export type ProviderErrorKind = typeof PROVIDER_ERROR_KINDS[number];
32
34
  /**
33
35
  * A provider call that failed. The message starts with the provider id. Adapters never put request
34
36
  * headers, keys or the runtime's own error text in it; they quote server text through `snippet`.
@@ -39,8 +41,13 @@ export declare class ProviderError extends QuorumError {
39
41
  readonly providerId: string;
40
42
  readonly kind: ProviderErrorKind;
41
43
  readonly status: number | undefined;
42
- /** True for network errors, timeouts, 408, 409, 429 and 5xx; a caller may retry the call. */
44
+ /**
45
+ * A caller may retry the call: true for network errors, timeouts, 408, 409, 429 and 5xx, unless
46
+ * the adapter set it. The core retries only `network`, `timeout` and `http` failures, whatever it says.
47
+ */
43
48
  readonly retryable: boolean;
49
+ /** The wait the server asked for at least, in milliseconds, when the adapter read one. */
50
+ readonly retryAfterMs: number | undefined;
44
51
  /** What the reply the call failed on reported, when the provider read one: the review counts it as the failed call's usage. */
45
52
  readonly usage: Usage | undefined;
46
53
  constructor(details: {
@@ -48,6 +55,8 @@ export declare class ProviderError extends QuorumError {
48
55
  kind: ProviderErrorKind;
49
56
  message: string;
50
57
  status?: number;
58
+ retryable?: boolean;
59
+ retryAfterMs?: number;
51
60
  usage?: Usage;
52
61
  cause?: unknown;
53
62
  });
@@ -52,6 +52,19 @@ export class ConfigError extends QuorumError {
52
52
  this.issues = issues;
53
53
  }
54
54
  }
55
+ /** Every kind of a provider call's failure: the kinds a `ProviderError` has, and the only ones a gap's detail names. */
56
+ export const PROVIDER_ERROR_KINDS = [
57
+ 'http',
58
+ 'network',
59
+ 'process',
60
+ 'timeout',
61
+ 'aborted',
62
+ 'refusal',
63
+ 'truncated',
64
+ 'invalid-response',
65
+ 'unsupported',
66
+ 'too-large',
67
+ ];
55
68
  const RETRYABLE_STATUSES = new Set([408, 409, 429]);
56
69
  function isRetryable(kind, status) {
57
70
  if (kind === 'network' || kind === 'timeout')
@@ -68,8 +81,13 @@ export class ProviderError extends QuorumError {
68
81
  providerId;
69
82
  kind;
70
83
  status;
71
- /** True for network errors, timeouts, 408, 409, 429 and 5xx; a caller may retry the call. */
84
+ /**
85
+ * A caller may retry the call: true for network errors, timeouts, 408, 409, 429 and 5xx, unless
86
+ * the adapter set it. The core retries only `network`, `timeout` and `http` failures, whatever it says.
87
+ */
72
88
  retryable;
89
+ /** The wait the server asked for at least, in milliseconds, when the adapter read one. */
90
+ retryAfterMs;
73
91
  /** What the reply the call failed on reported, when the provider read one: the review counts it as the failed call's usage. */
74
92
  usage;
75
93
  constructor(details) {
@@ -79,7 +97,8 @@ export class ProviderError extends QuorumError {
79
97
  this.providerId = details.providerId;
80
98
  this.kind = details.kind;
81
99
  this.status = details.status;
82
- this.retryable = isRetryable(details.kind, details.status);
100
+ this.retryable = details.retryable ?? isRetryable(details.kind, details.status);
101
+ this.retryAfterMs = details.retryAfterMs;
83
102
  this.usage = details.usage;
84
103
  }
85
104
  }
@@ -0,0 +1,42 @@
1
+ import type { ConfigIssue } from './errors.ts';
2
+ /** The most patterns `exclude` may hold. */
3
+ export declare const MAX_PATTERNS = 100;
4
+ /** The longest pattern, in characters. */
5
+ export declare const MAX_PATTERN_LENGTH = 256;
6
+ /** What a list of more than `MAX_PATTERNS` patterns is told. */
7
+ export declare const TOO_MANY_PATTERNS = "must hold at most 100 patterns";
8
+ /**
9
+ * The first problem with a pattern, with what to write instead, or undefined when it can be taken.
10
+ * The problems come in this order: empty, too long, a `\`, a `!`, a `{`, a trailing `/`, a `**`
11
+ * inside a name (a segment other than `**` that holds it), and an empty, `.` or `..` name (a segment
12
+ * of the pattern, less one leading `/`, that is one of them: no path in a diff has such a name, so
13
+ * the pattern would match less than its author meant). A pattern that would exclude something other
14
+ * than what its author meant is refused rather than guessed at. No message repeats the pattern.
15
+ */
16
+ export declare function patternProblem(pattern: string): string | undefined;
17
+ /**
18
+ * Every problem with a value given as `exclude`, so an untyped caller gets issues, never a
19
+ * TypeError: none when it is unset, `exclude: must be an array`, `exclude: must hold at most 100
20
+ * patterns` (the entries are then not read), or, for each entry, `exclude.<index>` with `must be a
21
+ * string` or the pattern's own problem.
22
+ */
23
+ export declare function excludeIssues(value: unknown): ConfigIssue[];
24
+ /**
25
+ * Whether `glob`, where `*` stands for any run of characters and `?` for one (a surrogate pair
26
+ * counts once), matches the whole of `name`; every other character is literal and case counts. It
27
+ * is the greedy algorithm: it goes back to the last `*` only, so it takes at most as many steps as
28
+ * the glob has characters times the name has, whatever the two hold. It compares code units, since
29
+ * indexing a string allocates a string per character on Bun.
30
+ */
31
+ export declare function matchName(glob: string, name: string): boolean;
32
+ /**
33
+ * The test of a path against checked patterns, each compiled once into its segments: `*` and `?`
34
+ * inside a name, `**` for whole directories, every other character literal and case-sensitive, and
35
+ * no pattern ever becomes a regular expression. The paths come from the diff, so an attacker
36
+ * controls them, and a matcher that backtracks would hang the review: this one is greedy, going back
37
+ * to the last star only. One pattern and one path cost at most as many steps as the pattern has
38
+ * characters times the path has, so with the caps (100 patterns of 256 characters) a review's
39
+ * matching costs at most 25 600 steps per character of path text, and an ordinary pattern a few.
40
+ * The matcher keeps no reference to the array it was given.
41
+ */
42
+ export declare function excludeMatcher(patterns: readonly string[]): (path: string) => boolean;
@@ -0,0 +1,189 @@
1
+ /** The most patterns `exclude` may hold. */
2
+ export const MAX_PATTERNS = 100;
3
+ /** The longest pattern, in characters. */
4
+ export const MAX_PATTERN_LENGTH = 256;
5
+ /** What a list of more than `MAX_PATTERNS` patterns is told. */
6
+ export const TOO_MANY_PATTERNS = `must hold at most ${MAX_PATTERNS} patterns`;
7
+ const STAR = 0x2A;
8
+ const QUESTION = 0x3F;
9
+ const HIGH_SURROGATES = [0xD800, 0xDBFF];
10
+ const LOW_SURROGATES = [0xDC00, 0xDFFF];
11
+ const WHOLE_DIRECTORIES = '**';
12
+ /** The names a segment of a pattern can hold that no path of a diff has. */
13
+ const NAMES_NO_PATH_HAS = new Set(['', '.', '..']);
14
+ /** How many code units the character at `at` takes: 2 for a surrogate pair, else 1. */
15
+ function width(text, at) {
16
+ const unit = text.charCodeAt(at);
17
+ if (unit < HIGH_SURROGATES[0] || unit > HIGH_SURROGATES[1])
18
+ return 1;
19
+ const next = text.charCodeAt(at + 1);
20
+ return next >= LOW_SURROGATES[0] && next <= LOW_SURROGATES[1]
21
+ ? 2
22
+ : 1;
23
+ }
24
+ /** The segments of a pattern with a `/` in it: those of the pattern less one leading `/`. */
25
+ function anchoredSegments(pattern) {
26
+ return (pattern.startsWith('/')
27
+ ? pattern.slice(1)
28
+ : pattern).split('/');
29
+ }
30
+ /**
31
+ * The first problem with a pattern, with what to write instead, or undefined when it can be taken.
32
+ * The problems come in this order: empty, too long, a `\`, a `!`, a `{`, a trailing `/`, a `**`
33
+ * inside a name (a segment other than `**` that holds it), and an empty, `.` or `..` name (a segment
34
+ * of the pattern, less one leading `/`, that is one of them: no path in a diff has such a name, so
35
+ * the pattern would match less than its author meant). A pattern that would exclude something other
36
+ * than what its author meant is refused rather than guessed at. No message repeats the pattern.
37
+ */
38
+ export function patternProblem(pattern) {
39
+ if (pattern === '')
40
+ return 'must not be empty';
41
+ if (pattern.length > MAX_PATTERN_LENGTH)
42
+ return `must be at most ${MAX_PATTERN_LENGTH} characters long`;
43
+ if (pattern.includes('\\'))
44
+ return 'holds \\, which escapes nothing here: write / between directories, and every other character as it is';
45
+ if (pattern.includes('!'))
46
+ return 'holds !, which negates nothing here: list only the paths to leave out';
47
+ if (pattern.includes('{'))
48
+ return 'holds {, which lists no alternatives here: write one pattern for each';
49
+ if (pattern.endsWith('/'))
50
+ return 'ends with /, so it matches no file: end it with /** to leave out what the directory holds';
51
+ const segments = anchoredSegments(pattern);
52
+ if (segments.some(segment => segment !== WHOLE_DIRECTORIES && segment.includes(WHOLE_DIRECTORIES))) {
53
+ return 'holds ** inside a name: ** stands for whole directories, as in **/*.min.js, and * for any characters of a name';
54
+ }
55
+ if (segments.some(segment => NAMES_NO_PATH_HAS.has(segment))) {
56
+ return 'holds an empty, . or .. name, which no path in a diff has: write the path from the root, as in dist/**';
57
+ }
58
+ return undefined;
59
+ }
60
+ /**
61
+ * Every problem with a value given as `exclude`, so an untyped caller gets issues, never a
62
+ * TypeError: none when it is unset, `exclude: must be an array`, `exclude: must hold at most 100
63
+ * patterns` (the entries are then not read), or, for each entry, `exclude.<index>` with `must be a
64
+ * string` or the pattern's own problem.
65
+ */
66
+ export function excludeIssues(value) {
67
+ if (value === undefined)
68
+ return [];
69
+ if (!Array.isArray(value)) {
70
+ return [
71
+ { path: 'exclude', message: 'must be an array' },
72
+ ];
73
+ }
74
+ if (value.length > MAX_PATTERNS) {
75
+ return [
76
+ { path: 'exclude', message: TOO_MANY_PATTERNS },
77
+ ];
78
+ }
79
+ // `Array.from` reads a hole as `undefined`, so it is reported like any other entry that is not a string.
80
+ return Array.from(value).flatMap((pattern, index) => {
81
+ const problem = typeof pattern === 'string'
82
+ ? patternProblem(pattern)
83
+ : 'must be a string';
84
+ return problem === undefined
85
+ ? []
86
+ : [
87
+ { path: `exclude.${index}`, message: problem },
88
+ ];
89
+ });
90
+ }
91
+ /**
92
+ * Whether `glob`, where `*` stands for any run of characters and `?` for one (a surrogate pair
93
+ * counts once), matches the whole of `name`; every other character is literal and case counts. It
94
+ * is the greedy algorithm: it goes back to the last `*` only, so it takes at most as many steps as
95
+ * the glob has characters times the name has, whatever the two hold. It compares code units, since
96
+ * indexing a string allocates a string per character on Bun.
97
+ */
98
+ export function matchName(glob, name) {
99
+ let g = 0;
100
+ let n = 0;
101
+ let star = -1;
102
+ let mark = 0;
103
+ while (n < name.length) {
104
+ if (g < glob.length && glob.charCodeAt(g) === STAR) {
105
+ star = g++;
106
+ mark = n;
107
+ }
108
+ else if (g < glob.length && glob.charCodeAt(g) === QUESTION) {
109
+ g++;
110
+ n += width(name, n);
111
+ }
112
+ else if (g < glob.length && glob.charCodeAt(g) === name.charCodeAt(n)) {
113
+ g++;
114
+ n++;
115
+ }
116
+ else if (star !== -1) {
117
+ g = star + 1;
118
+ mark += width(name, mark);
119
+ n = mark;
120
+ }
121
+ else {
122
+ return false;
123
+ }
124
+ }
125
+ while (g < glob.length && glob.charCodeAt(g) === STAR)
126
+ g++;
127
+ return g === glob.length;
128
+ }
129
+ /** Whether the segments of a pattern, `**` standing for any number of directories, match all the segments of a path: `matchName`'s loop, over segments. */
130
+ function matchPath(pattern, path) {
131
+ let p = 0;
132
+ let s = 0;
133
+ let star = -1;
134
+ let mark = 0;
135
+ while (s < path.length) {
136
+ if (p < pattern.length && pattern[p] === WHOLE_DIRECTORIES) {
137
+ star = p++;
138
+ mark = s;
139
+ }
140
+ else if (p < pattern.length && matchName(pattern[p], path[s])) {
141
+ p++;
142
+ s++;
143
+ }
144
+ else if (star !== -1) {
145
+ p = star + 1;
146
+ mark++;
147
+ s = mark;
148
+ }
149
+ else {
150
+ return false;
151
+ }
152
+ }
153
+ while (p < pattern.length && pattern[p] === WHOLE_DIRECTORIES)
154
+ p++;
155
+ return p === pattern.length;
156
+ }
157
+ /**
158
+ * The segments a checked pattern matches a path by: no `/` in it reads as `**` then the pattern, so
159
+ * it matches a file's name in any directory; else the pattern less one leading `/`, matched from the
160
+ * root; a last segment `**` gains `*` after it, so `dir/**` holds what is inside `dir` and never a
161
+ * file named `dir`; consecutive `**` collapse into one.
162
+ */
163
+ function segmentsOf(pattern) {
164
+ const segments = pattern.includes('/')
165
+ ? anchoredSegments(pattern)
166
+ : [WHOLE_DIRECTORIES, pattern];
167
+ if (segments.at(-1) === WHOLE_DIRECTORIES)
168
+ segments.push('*');
169
+ return segments.filter((segment, index) => segment !== WHOLE_DIRECTORIES || segments[index - 1] !== WHOLE_DIRECTORIES);
170
+ }
171
+ /**
172
+ * The test of a path against checked patterns, each compiled once into its segments: `*` and `?`
173
+ * inside a name, `**` for whole directories, every other character literal and case-sensitive, and
174
+ * no pattern ever becomes a regular expression. The paths come from the diff, so an attacker
175
+ * controls them, and a matcher that backtracks would hang the review: this one is greedy, going back
176
+ * to the last star only. One pattern and one path cost at most as many steps as the pattern has
177
+ * characters times the path has, so with the caps (100 patterns of 256 characters) a review's
178
+ * matching costs at most 25 600 steps per character of path text, and an ordinary pattern a few.
179
+ * The matcher keeps no reference to the array it was given.
180
+ */
181
+ export function excludeMatcher(patterns) {
182
+ const compiled = patterns.map(segmentsOf);
183
+ if (compiled.length === 0)
184
+ return () => false;
185
+ return (path) => {
186
+ const parts = path.split('/');
187
+ return compiled.some(segments => matchPath(segments, parts));
188
+ };
189
+ }