slicekit 0.5.0 → 0.6.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.
@@ -61,6 +61,37 @@ export function real(p) {
61
61
  return rest === '' ? resolved : path.join(resolved, rest);
62
62
  }
63
63
 
64
+ // Whether a path relative to a directory leaves it: `..` counts only as a whole component, so the
65
+ // file `..secret` is inside (issue #123).
66
+ export const leaves = (rel) => rel === '..' || rel.startsWith('../') || rel.startsWith('..\\') || path.isAbsolute(rel);
67
+
68
+ // The paths inside `root` (a canonical path) that abs names, as written: abs itself when it lies under
69
+ // root, and, for each leading directory of abs that resolves inside root, where that directory resolves
70
+ // with the rest of abs kept as written. A link or junction to the root, or to a directory in it, from
71
+ // outside the repository or from inside it, names the same files as the root does (issue #122). Empty
72
+ // when no part of abs leads into root.
73
+ export function namesUnder(root, abs) {
74
+ const key = (p) => (process.platform === 'win32' ? p.toLowerCase() : p);
75
+ const inside = (p) => key(p) === key(root) || key(p).startsWith(key(root) + path.sep);
76
+ const full = path.resolve(abs);
77
+ const out = inside(full) ? [full] : [];
78
+ const top = path.parse(full).root;
79
+ const segs = full.slice(top.length).split(path.sep).filter((x) => x !== '');
80
+ let prefix = top;
81
+ for (let k = 0; k < segs.length; k++) {
82
+ prefix = path.join(prefix, segs[k]);
83
+ let resolved;
84
+ try {
85
+ resolved = fs.realpathSync.native(prefix);
86
+ } catch {
87
+ break;
88
+ }
89
+ const mapped = path.join(resolved, ...segs.slice(k + 1));
90
+ if (inside(resolved) && !out.some((p) => key(p) === key(mapped))) out.push(mapped);
91
+ }
92
+ return out;
93
+ }
94
+
64
95
  // The slice the branch at root names: {id, state}, or {id, error} when its state file cannot be read,
65
96
  // or null when the branch is not a slice branch, has no state file, or root is not a repository.
66
97
  export function activeSlice(root, cfg) {
@@ -109,6 +140,174 @@ export function frozenTests(root, cfg) {
109
140
 
110
141
  // ---- agents.denyPaths (REQ-3.13, D-72) ----
111
142
 
143
+ // The members within ASCII of each class name Bash knows, as [first, last] character codes.
144
+ const ALPHA = [[65, 90], [97, 122]];
145
+ const DIGIT = [[48, 57]];
146
+ const POSIX_CLASS = {
147
+ alpha: ALPHA,
148
+ digit: DIGIT,
149
+ alnum: [...ALPHA, ...DIGIT],
150
+ upper: [[65, 90]],
151
+ lower: [[97, 122]],
152
+ space: [[9, 13], [32, 32]],
153
+ blank: [[9, 9], [32, 32]],
154
+ punct: [[33, 47], [58, 64], [91, 96], [123, 126]],
155
+ xdigit: [...DIGIT, [65, 70], [97, 102]],
156
+ word: [...ALPHA, ...DIGIT, [95, 95]],
157
+ cntrl: [[0, 31], [127, 127]],
158
+ print: [[32, 126]],
159
+ graph: [[33, 126]],
160
+ ascii: [[0, 127]],
161
+ };
162
+ // The classes that hold no character outside ASCII in any locale.
163
+ const ASCII_ONLY = new Set(['digit', 'xdigit', 'ascii']);
164
+
165
+ // How a quoted backslash is written as a member of a bracket expression in a pattern string: the
166
+ // collating symbol of this private-use character. A backslash itself is a path separator to the code
167
+ // that carries the string, so it cannot stand there.
168
+ export const BACKSLASH_MEMBER = String.fromCharCode(0xe000);
169
+
170
+ // The bracket expression that opens at p[i], read as Bash 5 reads one in a file name pattern.
171
+ // -> null when no `]` closes it before the path segment ends, so the `[` is a literal character (a
172
+ // bracket expression does not reach across a `/`);
173
+ // -> {end, unsure: true} when it holds a form this does not read to its end as Bash does; a caller
174
+ // then takes the word to be one it cannot judge, never one that matches nothing;
175
+ // -> {end, negated, ranges, wide, reversed}: `end` is the index of the closing `]`, `ranges` the
176
+ // members as [first, last] character codes, `wide` whether a member may also be any character
177
+ // outside ASCII, `reversed` whether a range was left out for running backwards.
178
+ // `quoted(j)` says that the shell took p[j] quoted or escaped: such a character is a member and
179
+ // nothing else, so it does not negate, close, open a class or make a range. Without `quoted`, p is a
180
+ // pattern string and a backslash makes the next character a member.
181
+ // What is read: a leading `!` or `^` negates; a `]` that comes first is a member; `[`, `!` and `^`
182
+ // elsewhere are members; `a-c` is a range by character code, as Bash orders one with its default
183
+ // `globasciiranges`, a `-` that comes first or last is a member, and a range that runs backwards is
184
+ // left out while the other members stay (`[z-ab]` is `b`); `[:alpha:]` and the other class names are
185
+ // read, and may hold any character outside ASCII where a locale adds letters; a collating symbol of
186
+ // one character (`[.d.]`) is that character, as a member or as an end of a range; an equivalence
187
+ // class of one character (`[=d=]`) is that character and any character outside ASCII.
188
+ // What is not read, and so is `unsure`: a class name Bash does not know; a collating symbol or an
189
+ // equivalence class named by more than one character, or one nothing closes; an equivalence class in
190
+ // a negated expression; a class or an equivalence class as the end of a range; a quoted character
191
+ // inside a class, symbol or equivalence name; a character outside the Basic Multilingual Plane.
192
+ export function readBracket(p, i, quoted = null) {
193
+ const q = (j) => quoted !== null && quoted(j);
194
+ const is = (j, c) => p[j] === c && !q(j);
195
+ let stop = p.indexOf('/', i);
196
+ if (stop === -1) stop = p.length;
197
+ const unsure = { end: stop - 1, unsure: true };
198
+ // A surrogate is half of a character this does not compare, and the private-use character stands
199
+ // for a backslash only inside a collating symbol.
200
+ const odd = (code) => (code >= 0xd800 && code <= 0xdfff) || code === 0xe000 || Number.isNaN(code);
201
+ // Whether any character from j up to k (k not included) was quoted.
202
+ const anyQuoted = (j, k) => {
203
+ for (let n = j; n < k; n++) if (q(n)) return true;
204
+ return false;
205
+ };
206
+ // One character at j, written plainly, escaped or as a collating symbol -> {code, next}, or null.
207
+ const single = (j) => {
208
+ if (is(j, '[') && is(j + 1, '.')) {
209
+ const close = p.indexOf('.]', j + 3);
210
+ if (close === -1 || close + 1 >= stop || anyQuoted(j + 2, close + 2)) return null;
211
+ const name = p.slice(j + 2, close);
212
+ if (name.length !== 1) return null;
213
+ if (name === BACKSLASH_MEMBER) return { code: 92, next: close + 2 };
214
+ return odd(name.charCodeAt(0)) ? null : { code: name.charCodeAt(0), next: close + 2 };
215
+ }
216
+ const at = quoted === null && p[j] === '\\' && j + 1 < stop ? j + 1 : j;
217
+ return odd(p.charCodeAt(at)) ? null : { code: p.charCodeAt(at), next: at + 1 };
218
+ };
219
+ let j = i + 1;
220
+ const negated = is(j, '!') || is(j, '^');
221
+ if (negated) j += 1;
222
+ const ranges = [];
223
+ let wide = false;
224
+ let reversed = false;
225
+ for (let first = true; ; first = false) {
226
+ if (j >= stop) return null;
227
+ if (is(j, ']') && !first) break;
228
+ if (is(j, '[') && is(j + 1, ':')) {
229
+ const close = p.indexOf(':]', j + 2);
230
+ if (close !== -1 && close + 1 < stop) {
231
+ if (anyQuoted(j + 2, close + 2)) return unsure;
232
+ const name = p.slice(j + 2, close);
233
+ if (!Object.hasOwn(POSIX_CLASS, name)) return unsure;
234
+ ranges.push(...POSIX_CLASS[name]);
235
+ if (!ASCII_ONLY.has(name)) wide = true;
236
+ j = close + 2;
237
+ continue;
238
+ }
239
+ // No `:]` follows: the `[` is a member, as Bash reads it.
240
+ } else if (is(j, '[') && is(j + 1, '=')) {
241
+ if (j + 4 < stop && is(j + 3, '=') && is(j + 4, ']')) {
242
+ const code = p.charCodeAt(j + 2);
243
+ // In a negated expression the characters a locale adds would be left out, and are not known.
244
+ if (q(j + 2) || odd(code) || negated) return unsure;
245
+ ranges.push([code, code]);
246
+ wide = true;
247
+ j += 5;
248
+ continue;
249
+ }
250
+ const close = p.indexOf('=]', j + 2);
251
+ if (close !== -1 && close + 1 < stop) return unsure;
252
+ // No `=]` follows: the `[` is a member.
253
+ }
254
+ const lo = single(j);
255
+ if (lo === null) return unsure;
256
+ j = lo.next;
257
+ if (is(j, '-') && j + 1 < stop && !is(j + 1, ']')) {
258
+ if (is(j + 1, '[') && (is(j + 2, ':') || is(j + 2, '='))) return unsure;
259
+ const hi = single(j + 1);
260
+ if (hi === null) return unsure;
261
+ j = hi.next;
262
+ if (lo.code > hi.code) reversed = true;
263
+ else ranges.push([lo.code, hi.code]);
264
+ } else {
265
+ ranges.push([lo.code, lo.code]);
266
+ }
267
+ }
268
+ return { end: j, negated, ranges, wide, reversed };
269
+ }
270
+
271
+ // A bracket expression `readBracket` read, as the source of a regular-expression class. Each member is
272
+ // written as an escape, so no member is syntax. In a negated expression the characters outside ASCII
273
+ // that a class may hold are not left out: the class then matches more, never less, than Bash's.
274
+ // With `fold` (Windows, in a regular expression with no `i` flag), an expression that is not negated
275
+ // takes each letter in both cases, and a negated one leaves out only the characters it names, as Bash
276
+ // does: under an `i` flag `[!A]` would refuse `a`, which Bash matches.
277
+ export function classSrc({ ranges, negated, wide }, fold = false) {
278
+ const u = (code) => `\\u${code.toString(16).padStart(4, '0')}`;
279
+ const all = [...ranges];
280
+ let any = wide && !negated;
281
+ if (fold && !negated) {
282
+ for (const [lo, hi] of ranges) {
283
+ if (hi - lo > 1024) {
284
+ any = true;
285
+ all.push(...ALPHA);
286
+ continue;
287
+ }
288
+ for (let c = lo; c <= hi; c++) {
289
+ const s = String.fromCharCode(c);
290
+ for (const v of [s.toLowerCase(), s.toUpperCase()]) {
291
+ if (v.length === 1 && v !== s) all.push([v.charCodeAt(0), v.charCodeAt(0)]);
292
+ }
293
+ }
294
+ }
295
+ }
296
+ const body = all.map(([lo, hi]) => (lo === hi ? u(lo) : `${u(lo)}-${u(hi)}`)).join('') + (any ? '\\u0080-\\uffff' : '');
297
+ return `[${negated ? '^' : ''}${body}]`;
298
+ }
299
+
300
+ // The bracket expression that opens at p[i] of a pattern string, as the source of a
301
+ // regular-expression class: {src, end}; null when the `[` is a literal character. `unsure` marks one
302
+ // `readBracket` does not read, whose `src` is not to be relied on, and `reversed` one that holds a
303
+ // range running backwards (`[z-a]`).
304
+ export function bracketClass(p, i) {
305
+ const b = readBracket(p, i);
306
+ if (b === null) return null;
307
+ if (b.unsure) return { src: '[^]', end: b.end, unsure: true };
308
+ return b.reversed ? { src: classSrc(b), end: b.end, reversed: true } : { src: classSrc(b), end: b.end };
309
+ }
310
+
112
311
  // One gitignore-style pattern over repository-relative POSIX paths as an anchored regular expression:
113
312
  // `**` crosses segments, `*` and `?` stay in one, `[...]` is a class; a leading `/` or `./` anchors at
114
313
  // the root, which a pattern with no inner `/` is not (it matches at any depth); a trailing `/` names a
@@ -137,16 +336,30 @@ function denyRe(pattern) {
137
336
  }
138
337
  } else if (c === '*') src += '[^/]*';
139
338
  else if (c === '?') src += '[^/]';
140
- else if (c === '[' && p.indexOf(']', i + 2) !== -1) {
141
- const end = p.indexOf(']', i + 2);
142
- const body = p.slice(i + 1, end).replace(/^!/, '^').replace(/\\/g, '\\\\');
143
- src += `[${body}]`;
144
- i = end;
339
+ else if (c === '[' && bracketClass(p, i) !== null) {
340
+ const cls = bracketClass(p, i);
341
+ // A pattern is not matched by a guess: validateConfig refuses it by name.
342
+ if (cls.unsure) throw new Error(`bracket expression ${p.slice(i, cls.end + 1)} holds a class name, a collating symbol or an equivalence class the guards cannot read`);
343
+ if (cls.reversed) throw new Error('Range out of order in character class');
344
+ src += cls.src;
345
+ i = cls.end;
145
346
  } else src += c.replace(/[.+^${}()|\\[\]]/g, '\\$&');
146
347
  }
147
348
  return new RegExp(`^${anchored ? '' : '(?:.*/)?'}${src}$`, process.platform === 'win32' ? 'i' : '');
148
349
  }
149
350
 
351
+ // -> why the guards cannot compile `pattern`, or null when they can. validateConfig refuses a pattern
352
+ // with a reason (issue #120), so a guard does not meet one when it matches.
353
+ export function denyPatternError(pattern) {
354
+ try {
355
+ denyRe(pattern);
356
+ return null;
357
+ } catch (e) {
358
+ const why = String(e?.message ?? e).split(': ').pop();
359
+ return `${pattern} does not compile as a glob (${why.charAt(0).toLowerCase()}${why.slice(1)})`;
360
+ }
361
+ }
362
+
150
363
  // -> the first pattern of `patterns` that matches the repository-relative POSIX path `rel` or one of
151
364
  // its parent directories, or null. Shared by pre-edit and pre-bash.
152
365
  export function matchesDeny(rel, patterns) {