eslint-plugin-slonik 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +48 -0
- package/README.md +368 -0
- package/dist/config.cjs +61 -0
- package/dist/config.cjs.map +1 -0
- package/dist/config.d.cts +192 -0
- package/dist/config.d.mts +192 -0
- package/dist/config.d.ts +192 -0
- package/dist/config.mjs +59 -0
- package/dist/config.mjs.map +1 -0
- package/dist/index.cjs +27 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +319 -0
- package/dist/index.d.mts +319 -0
- package/dist/index.d.ts +319 -0
- package/dist/index.mjs +20 -0
- package/dist/index.mjs.map +1 -0
- package/dist/shared/eslint-plugin-slonik.1m1xlVmw.d.cts +611 -0
- package/dist/shared/eslint-plugin-slonik.1m1xlVmw.d.mts +611 -0
- package/dist/shared/eslint-plugin-slonik.1m1xlVmw.d.ts +611 -0
- package/dist/shared/eslint-plugin-slonik.BxexVlk1.cjs +1539 -0
- package/dist/shared/eslint-plugin-slonik.BxexVlk1.cjs.map +1 -0
- package/dist/shared/eslint-plugin-slonik.C0xTyWZ2.mjs +2866 -0
- package/dist/shared/eslint-plugin-slonik.C0xTyWZ2.mjs.map +1 -0
- package/dist/shared/eslint-plugin-slonik.DbzoLz5_.mjs +1514 -0
- package/dist/shared/eslint-plugin-slonik.DbzoLz5_.mjs.map +1 -0
- package/dist/shared/eslint-plugin-slonik.rlOTrCdf.cjs +2929 -0
- package/dist/shared/eslint-plugin-slonik.rlOTrCdf.cjs.map +1 -0
- package/dist/workers/check-sql.worker.cjs +2436 -0
- package/dist/workers/check-sql.worker.cjs.map +1 -0
- package/dist/workers/check-sql.worker.d.cts +171 -0
- package/dist/workers/check-sql.worker.d.mts +171 -0
- package/dist/workers/check-sql.worker.d.ts +171 -0
- package/dist/workers/check-sql.worker.mjs +2412 -0
- package/dist/workers/check-sql.worker.mjs.map +1 -0
- package/package.json +103 -0
|
@@ -0,0 +1,2929 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const path$1 = require('path');
|
|
4
|
+
const postgres = require('postgres');
|
|
5
|
+
const crypto = require('crypto');
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const tsPattern = require('ts-pattern');
|
|
8
|
+
const utils = require('@typescript-eslint/utils');
|
|
9
|
+
const E = require('fp-ts/lib/Either.js');
|
|
10
|
+
const function_js = require('fp-ts/lib/function.js');
|
|
11
|
+
require('fp-ts/lib/Option.js');
|
|
12
|
+
const TE = require('fp-ts/lib/TaskEither.js');
|
|
13
|
+
require('fp-ts/lib/Json.js');
|
|
14
|
+
const pgConnectionString = require('pg-connection-string');
|
|
15
|
+
|
|
16
|
+
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
|
|
17
|
+
|
|
18
|
+
function _interopNamespaceCompat(e) {
|
|
19
|
+
if (e && typeof e === 'object' && 'default' in e) return e;
|
|
20
|
+
const n = Object.create(null);
|
|
21
|
+
if (e) {
|
|
22
|
+
for (const k in e) {
|
|
23
|
+
n[k] = e[k];
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
n.default = e;
|
|
27
|
+
return n;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const path__default = /*#__PURE__*/_interopDefaultCompat(path$1);
|
|
31
|
+
const postgres__default = /*#__PURE__*/_interopDefaultCompat(postgres);
|
|
32
|
+
const crypto__default = /*#__PURE__*/_interopDefaultCompat(crypto);
|
|
33
|
+
const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
|
|
34
|
+
const E__namespace = /*#__PURE__*/_interopNamespaceCompat(E);
|
|
35
|
+
const TE__namespace = /*#__PURE__*/_interopNamespaceCompat(TE);
|
|
36
|
+
const pgConnectionString__default = /*#__PURE__*/_interopDefaultCompat(pgConnectionString);
|
|
37
|
+
|
|
38
|
+
const balanced = (a, b, str) => {
|
|
39
|
+
const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
|
|
40
|
+
const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
|
|
41
|
+
const r = ma !== null && mb != null && range(ma, mb, str);
|
|
42
|
+
return (r && {
|
|
43
|
+
start: r[0],
|
|
44
|
+
end: r[1],
|
|
45
|
+
pre: str.slice(0, r[0]),
|
|
46
|
+
body: str.slice(r[0] + ma.length, r[1]),
|
|
47
|
+
post: str.slice(r[1] + mb.length),
|
|
48
|
+
});
|
|
49
|
+
};
|
|
50
|
+
const maybeMatch = (reg, str) => {
|
|
51
|
+
const m = str.match(reg);
|
|
52
|
+
return m ? m[0] : null;
|
|
53
|
+
};
|
|
54
|
+
const range = (a, b, str) => {
|
|
55
|
+
let begs, beg, left, right = undefined, result;
|
|
56
|
+
let ai = str.indexOf(a);
|
|
57
|
+
let bi = str.indexOf(b, ai + 1);
|
|
58
|
+
let i = ai;
|
|
59
|
+
if (ai >= 0 && bi > 0) {
|
|
60
|
+
if (a === b) {
|
|
61
|
+
return [ai, bi];
|
|
62
|
+
}
|
|
63
|
+
begs = [];
|
|
64
|
+
left = str.length;
|
|
65
|
+
while (i >= 0 && !result) {
|
|
66
|
+
if (i === ai) {
|
|
67
|
+
begs.push(i);
|
|
68
|
+
ai = str.indexOf(a, i + 1);
|
|
69
|
+
}
|
|
70
|
+
else if (begs.length === 1) {
|
|
71
|
+
const r = begs.pop();
|
|
72
|
+
if (r !== undefined)
|
|
73
|
+
result = [r, bi];
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
beg = begs.pop();
|
|
77
|
+
if (beg !== undefined && beg < left) {
|
|
78
|
+
left = beg;
|
|
79
|
+
right = bi;
|
|
80
|
+
}
|
|
81
|
+
bi = str.indexOf(b, i + 1);
|
|
82
|
+
}
|
|
83
|
+
i = ai < bi && ai >= 0 ? ai : bi;
|
|
84
|
+
}
|
|
85
|
+
if (begs.length && right !== undefined) {
|
|
86
|
+
result = [left, right];
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return result;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const escSlash = '\0SLASH' + Math.random() + '\0';
|
|
93
|
+
const escOpen = '\0OPEN' + Math.random() + '\0';
|
|
94
|
+
const escClose = '\0CLOSE' + Math.random() + '\0';
|
|
95
|
+
const escComma = '\0COMMA' + Math.random() + '\0';
|
|
96
|
+
const escPeriod = '\0PERIOD' + Math.random() + '\0';
|
|
97
|
+
const escSlashPattern = new RegExp(escSlash, 'g');
|
|
98
|
+
const escOpenPattern = new RegExp(escOpen, 'g');
|
|
99
|
+
const escClosePattern = new RegExp(escClose, 'g');
|
|
100
|
+
const escCommaPattern = new RegExp(escComma, 'g');
|
|
101
|
+
const escPeriodPattern = new RegExp(escPeriod, 'g');
|
|
102
|
+
const slashPattern = /\\\\/g;
|
|
103
|
+
const openPattern = /\\{/g;
|
|
104
|
+
const closePattern = /\\}/g;
|
|
105
|
+
const commaPattern = /\\,/g;
|
|
106
|
+
const periodPattern = /\\./g;
|
|
107
|
+
function numeric(str) {
|
|
108
|
+
return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
|
|
109
|
+
}
|
|
110
|
+
function escapeBraces(str) {
|
|
111
|
+
return str
|
|
112
|
+
.replace(slashPattern, escSlash)
|
|
113
|
+
.replace(openPattern, escOpen)
|
|
114
|
+
.replace(closePattern, escClose)
|
|
115
|
+
.replace(commaPattern, escComma)
|
|
116
|
+
.replace(periodPattern, escPeriod);
|
|
117
|
+
}
|
|
118
|
+
function unescapeBraces(str) {
|
|
119
|
+
return str
|
|
120
|
+
.replace(escSlashPattern, '\\')
|
|
121
|
+
.replace(escOpenPattern, '{')
|
|
122
|
+
.replace(escClosePattern, '}')
|
|
123
|
+
.replace(escCommaPattern, ',')
|
|
124
|
+
.replace(escPeriodPattern, '.');
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Basically just str.split(","), but handling cases
|
|
128
|
+
* where we have nested braced sections, which should be
|
|
129
|
+
* treated as individual members, like {a,{b,c},d}
|
|
130
|
+
*/
|
|
131
|
+
function parseCommaParts(str) {
|
|
132
|
+
if (!str) {
|
|
133
|
+
return [''];
|
|
134
|
+
}
|
|
135
|
+
const parts = [];
|
|
136
|
+
const m = balanced('{', '}', str);
|
|
137
|
+
if (!m) {
|
|
138
|
+
return str.split(',');
|
|
139
|
+
}
|
|
140
|
+
const { pre, body, post } = m;
|
|
141
|
+
const p = pre.split(',');
|
|
142
|
+
p[p.length - 1] += '{' + body + '}';
|
|
143
|
+
const postParts = parseCommaParts(post);
|
|
144
|
+
if (post.length) {
|
|
145
|
+
p[p.length - 1] += postParts.shift();
|
|
146
|
+
p.push.apply(p, postParts);
|
|
147
|
+
}
|
|
148
|
+
parts.push.apply(parts, p);
|
|
149
|
+
return parts;
|
|
150
|
+
}
|
|
151
|
+
function expand(str) {
|
|
152
|
+
if (!str) {
|
|
153
|
+
return [];
|
|
154
|
+
}
|
|
155
|
+
// I don't know why Bash 4.3 does this, but it does.
|
|
156
|
+
// Anything starting with {} will have the first two bytes preserved
|
|
157
|
+
// but *only* at the top level, so {},a}b will not expand to anything,
|
|
158
|
+
// but a{},b}c will be expanded to [a}c,abc].
|
|
159
|
+
// One could argue that this is a bug in Bash, but since the goal of
|
|
160
|
+
// this module is to match Bash's rules, we escape a leading {}
|
|
161
|
+
if (str.slice(0, 2) === '{}') {
|
|
162
|
+
str = '\\{\\}' + str.slice(2);
|
|
163
|
+
}
|
|
164
|
+
return expand_(escapeBraces(str), true).map(unescapeBraces);
|
|
165
|
+
}
|
|
166
|
+
function embrace(str) {
|
|
167
|
+
return '{' + str + '}';
|
|
168
|
+
}
|
|
169
|
+
function isPadded(el) {
|
|
170
|
+
return /^-?0\d/.test(el);
|
|
171
|
+
}
|
|
172
|
+
function lte(i, y) {
|
|
173
|
+
return i <= y;
|
|
174
|
+
}
|
|
175
|
+
function gte(i, y) {
|
|
176
|
+
return i >= y;
|
|
177
|
+
}
|
|
178
|
+
function expand_(str, isTop) {
|
|
179
|
+
/** @type {string[]} */
|
|
180
|
+
const expansions = [];
|
|
181
|
+
const m = balanced('{', '}', str);
|
|
182
|
+
if (!m)
|
|
183
|
+
return [str];
|
|
184
|
+
// no need to expand pre, since it is guaranteed to be free of brace-sets
|
|
185
|
+
const pre = m.pre;
|
|
186
|
+
const post = m.post.length ? expand_(m.post, false) : [''];
|
|
187
|
+
if (/\$$/.test(m.pre)) {
|
|
188
|
+
for (let k = 0; k < post.length; k++) {
|
|
189
|
+
const expansion = pre + '{' + m.body + '}' + post[k];
|
|
190
|
+
expansions.push(expansion);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
|
|
195
|
+
const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
|
|
196
|
+
const isSequence = isNumericSequence || isAlphaSequence;
|
|
197
|
+
const isOptions = m.body.indexOf(',') >= 0;
|
|
198
|
+
if (!isSequence && !isOptions) {
|
|
199
|
+
// {a},b}
|
|
200
|
+
if (m.post.match(/,(?!,).*\}/)) {
|
|
201
|
+
str = m.pre + '{' + m.body + escClose + m.post;
|
|
202
|
+
return expand_(str);
|
|
203
|
+
}
|
|
204
|
+
return [str];
|
|
205
|
+
}
|
|
206
|
+
let n;
|
|
207
|
+
if (isSequence) {
|
|
208
|
+
n = m.body.split(/\.\./);
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
n = parseCommaParts(m.body);
|
|
212
|
+
if (n.length === 1 && n[0] !== undefined) {
|
|
213
|
+
// x{{a,b}}y ==> x{a}y x{b}y
|
|
214
|
+
n = expand_(n[0], false).map(embrace);
|
|
215
|
+
//XXX is this necessary? Can't seem to hit it in tests.
|
|
216
|
+
/* c8 ignore start */
|
|
217
|
+
if (n.length === 1) {
|
|
218
|
+
return post.map(p => m.pre + n[0] + p);
|
|
219
|
+
}
|
|
220
|
+
/* c8 ignore stop */
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// at this point, n is the parts, and we know it's not a comma set
|
|
224
|
+
// with a single entry.
|
|
225
|
+
let N;
|
|
226
|
+
if (isSequence && n[0] !== undefined && n[1] !== undefined) {
|
|
227
|
+
const x = numeric(n[0]);
|
|
228
|
+
const y = numeric(n[1]);
|
|
229
|
+
const width = Math.max(n[0].length, n[1].length);
|
|
230
|
+
let incr = n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1;
|
|
231
|
+
let test = lte;
|
|
232
|
+
const reverse = y < x;
|
|
233
|
+
if (reverse) {
|
|
234
|
+
incr *= -1;
|
|
235
|
+
test = gte;
|
|
236
|
+
}
|
|
237
|
+
const pad = n.some(isPadded);
|
|
238
|
+
N = [];
|
|
239
|
+
for (let i = x; test(i, y); i += incr) {
|
|
240
|
+
let c;
|
|
241
|
+
if (isAlphaSequence) {
|
|
242
|
+
c = String.fromCharCode(i);
|
|
243
|
+
if (c === '\\') {
|
|
244
|
+
c = '';
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
c = String(i);
|
|
249
|
+
if (pad) {
|
|
250
|
+
const need = width - c.length;
|
|
251
|
+
if (need > 0) {
|
|
252
|
+
const z = new Array(need + 1).join('0');
|
|
253
|
+
if (i < 0) {
|
|
254
|
+
c = '-' + z + c.slice(1);
|
|
255
|
+
}
|
|
256
|
+
else {
|
|
257
|
+
c = z + c;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
N.push(c);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
N = [];
|
|
267
|
+
for (let j = 0; j < n.length; j++) {
|
|
268
|
+
N.push.apply(N, expand_(n[j], false));
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
for (let j = 0; j < N.length; j++) {
|
|
272
|
+
for (let k = 0; k < post.length; k++) {
|
|
273
|
+
const expansion = pre + N[j] + post[k];
|
|
274
|
+
if (!isTop || isSequence || expansion) {
|
|
275
|
+
expansions.push(expansion);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return expansions;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const MAX_PATTERN_LENGTH = 1024 * 64;
|
|
284
|
+
const assertValidPattern = (pattern) => {
|
|
285
|
+
if (typeof pattern !== 'string') {
|
|
286
|
+
throw new TypeError('invalid pattern');
|
|
287
|
+
}
|
|
288
|
+
if (pattern.length > MAX_PATTERN_LENGTH) {
|
|
289
|
+
throw new TypeError('pattern is too long');
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
// translate the various posix character classes into unicode properties
|
|
294
|
+
// this works across all unicode locales
|
|
295
|
+
// { <posix class>: [<translation>, /u flag required, negated]
|
|
296
|
+
const posixClasses = {
|
|
297
|
+
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
|
|
298
|
+
'[:alpha:]': ['\\p{L}\\p{Nl}', true],
|
|
299
|
+
'[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
|
|
300
|
+
'[:blank:]': ['\\p{Zs}\\t', true],
|
|
301
|
+
'[:cntrl:]': ['\\p{Cc}', true],
|
|
302
|
+
'[:digit:]': ['\\p{Nd}', true],
|
|
303
|
+
'[:graph:]': ['\\p{Z}\\p{C}', true, true],
|
|
304
|
+
'[:lower:]': ['\\p{Ll}', true],
|
|
305
|
+
'[:print:]': ['\\p{C}', true],
|
|
306
|
+
'[:punct:]': ['\\p{P}', true],
|
|
307
|
+
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
|
|
308
|
+
'[:upper:]': ['\\p{Lu}', true],
|
|
309
|
+
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
|
|
310
|
+
'[:xdigit:]': ['A-Fa-f0-9', false],
|
|
311
|
+
};
|
|
312
|
+
// only need to escape a few things inside of brace expressions
|
|
313
|
+
// escapes: [ \ ] -
|
|
314
|
+
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
|
|
315
|
+
// escape all regexp magic characters
|
|
316
|
+
const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
|
|
317
|
+
// everything has already been escaped, we just have to join
|
|
318
|
+
const rangesToString = (ranges) => ranges.join('');
|
|
319
|
+
// takes a glob string at a posix brace expression, and returns
|
|
320
|
+
// an equivalent regular expression source, and boolean indicating
|
|
321
|
+
// whether the /u flag needs to be applied, and the number of chars
|
|
322
|
+
// consumed to parse the character class.
|
|
323
|
+
// This also removes out of order ranges, and returns ($.) if the
|
|
324
|
+
// entire class just no good.
|
|
325
|
+
const parseClass = (glob, position) => {
|
|
326
|
+
const pos = position;
|
|
327
|
+
/* c8 ignore start */
|
|
328
|
+
if (glob.charAt(pos) !== '[') {
|
|
329
|
+
throw new Error('not in a brace expression');
|
|
330
|
+
}
|
|
331
|
+
/* c8 ignore stop */
|
|
332
|
+
const ranges = [];
|
|
333
|
+
const negs = [];
|
|
334
|
+
let i = pos + 1;
|
|
335
|
+
let sawStart = false;
|
|
336
|
+
let uflag = false;
|
|
337
|
+
let escaping = false;
|
|
338
|
+
let negate = false;
|
|
339
|
+
let endPos = pos;
|
|
340
|
+
let rangeStart = '';
|
|
341
|
+
WHILE: while (i < glob.length) {
|
|
342
|
+
const c = glob.charAt(i);
|
|
343
|
+
if ((c === '!' || c === '^') && i === pos + 1) {
|
|
344
|
+
negate = true;
|
|
345
|
+
i++;
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
if (c === ']' && sawStart && !escaping) {
|
|
349
|
+
endPos = i + 1;
|
|
350
|
+
break;
|
|
351
|
+
}
|
|
352
|
+
sawStart = true;
|
|
353
|
+
if (c === '\\') {
|
|
354
|
+
if (!escaping) {
|
|
355
|
+
escaping = true;
|
|
356
|
+
i++;
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
// escaped \ char, fall through and treat like normal char
|
|
360
|
+
}
|
|
361
|
+
if (c === '[' && !escaping) {
|
|
362
|
+
// either a posix class, a collation equivalent, or just a [
|
|
363
|
+
for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
|
|
364
|
+
if (glob.startsWith(cls, i)) {
|
|
365
|
+
// invalid, [a-[] is fine, but not [a-[:alpha]]
|
|
366
|
+
if (rangeStart) {
|
|
367
|
+
return ['$.', false, glob.length - pos, true];
|
|
368
|
+
}
|
|
369
|
+
i += cls.length;
|
|
370
|
+
if (neg)
|
|
371
|
+
negs.push(unip);
|
|
372
|
+
else
|
|
373
|
+
ranges.push(unip);
|
|
374
|
+
uflag = uflag || u;
|
|
375
|
+
continue WHILE;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
// now it's just a normal character, effectively
|
|
380
|
+
escaping = false;
|
|
381
|
+
if (rangeStart) {
|
|
382
|
+
// throw this range away if it's not valid, but others
|
|
383
|
+
// can still match.
|
|
384
|
+
if (c > rangeStart) {
|
|
385
|
+
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
|
|
386
|
+
}
|
|
387
|
+
else if (c === rangeStart) {
|
|
388
|
+
ranges.push(braceEscape(c));
|
|
389
|
+
}
|
|
390
|
+
rangeStart = '';
|
|
391
|
+
i++;
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
// now might be the start of a range.
|
|
395
|
+
// can be either c-d or c-] or c<more...>] or c] at this point
|
|
396
|
+
if (glob.startsWith('-]', i + 1)) {
|
|
397
|
+
ranges.push(braceEscape(c + '-'));
|
|
398
|
+
i += 2;
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
if (glob.startsWith('-', i + 1)) {
|
|
402
|
+
rangeStart = c;
|
|
403
|
+
i += 2;
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
// not the start of a range, just a single character
|
|
407
|
+
ranges.push(braceEscape(c));
|
|
408
|
+
i++;
|
|
409
|
+
}
|
|
410
|
+
if (endPos < i) {
|
|
411
|
+
// didn't see the end of the class, not a valid class,
|
|
412
|
+
// but might still be valid as a literal match.
|
|
413
|
+
return ['', false, 0, false];
|
|
414
|
+
}
|
|
415
|
+
// if we got no ranges and no negates, then we have a range that
|
|
416
|
+
// cannot possibly match anything, and that poisons the whole glob
|
|
417
|
+
if (!ranges.length && !negs.length) {
|
|
418
|
+
return ['$.', false, glob.length - pos, true];
|
|
419
|
+
}
|
|
420
|
+
// if we got one positive range, and it's a single character, then that's
|
|
421
|
+
// not actually a magic pattern, it's just that one literal character.
|
|
422
|
+
// we should not treat that as "magic", we should just return the literal
|
|
423
|
+
// character. [_] is a perfectly valid way to escape glob magic chars.
|
|
424
|
+
if (negs.length === 0 &&
|
|
425
|
+
ranges.length === 1 &&
|
|
426
|
+
/^\\?.$/.test(ranges[0]) &&
|
|
427
|
+
!negate) {
|
|
428
|
+
const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
|
|
429
|
+
return [regexpEscape(r), false, endPos - pos, false];
|
|
430
|
+
}
|
|
431
|
+
const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
|
|
432
|
+
const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
|
|
433
|
+
const comb = ranges.length && negs.length
|
|
434
|
+
? '(' + sranges + '|' + snegs + ')'
|
|
435
|
+
: ranges.length
|
|
436
|
+
? sranges
|
|
437
|
+
: snegs;
|
|
438
|
+
return [comb, uflag, endPos - pos, true];
|
|
439
|
+
};
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Un-escape a string that has been escaped with {@link escape}.
|
|
443
|
+
*
|
|
444
|
+
* If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
|
|
445
|
+
* square-bracket escapes are removed, but not backslash escapes.
|
|
446
|
+
*
|
|
447
|
+
* For example, it will turn the string `'[*]'` into `*`, but it will not
|
|
448
|
+
* turn `'\\*'` into `'*'`, because `\` is a path separator in
|
|
449
|
+
* `windowsPathsNoEscape` mode.
|
|
450
|
+
*
|
|
451
|
+
* When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
|
|
452
|
+
* backslash escapes are removed.
|
|
453
|
+
*
|
|
454
|
+
* Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
|
|
455
|
+
* or unescaped.
|
|
456
|
+
*
|
|
457
|
+
* When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
|
|
458
|
+
* unescaped.
|
|
459
|
+
*/
|
|
460
|
+
const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
|
|
461
|
+
if (magicalBraces) {
|
|
462
|
+
return windowsPathsNoEscape
|
|
463
|
+
? s.replace(/\[([^\/\\])\]/g, '$1')
|
|
464
|
+
: s
|
|
465
|
+
.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2')
|
|
466
|
+
.replace(/\\([^\/])/g, '$1');
|
|
467
|
+
}
|
|
468
|
+
return windowsPathsNoEscape
|
|
469
|
+
? s.replace(/\[([^\/\\{}])\]/g, '$1')
|
|
470
|
+
: s
|
|
471
|
+
.replace(/((?!\\).|^)\[([^\/\\{}])\]/g, '$1$2')
|
|
472
|
+
.replace(/\\([^\/{}])/g, '$1');
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
// parse a single path portion
|
|
476
|
+
const types = new Set(['!', '?', '+', '*', '@']);
|
|
477
|
+
const isExtglobType = (c) => types.has(c);
|
|
478
|
+
// Patterns that get prepended to bind to the start of either the
|
|
479
|
+
// entire string, or just a single path portion, to prevent dots
|
|
480
|
+
// and/or traversal patterns, when needed.
|
|
481
|
+
// Exts don't need the ^ or / bit, because the root binds that already.
|
|
482
|
+
const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
|
|
483
|
+
const startNoDot = '(?!\\.)';
|
|
484
|
+
// characters that indicate a start of pattern needs the "no dots" bit,
|
|
485
|
+
// because a dot *might* be matched. ( is not in the list, because in
|
|
486
|
+
// the case of a child extglob, it will handle the prevention itself.
|
|
487
|
+
const addPatternStart = new Set(['[', '.']);
|
|
488
|
+
// cases where traversal is A-OK, no dot prevention needed
|
|
489
|
+
const justDots = new Set(['..', '.']);
|
|
490
|
+
const reSpecials = new Set('().*{}+?[]^$\\!');
|
|
491
|
+
const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
|
|
492
|
+
// any single thing other than /
|
|
493
|
+
const qmark$1 = '[^/]';
|
|
494
|
+
// * => any number of characters
|
|
495
|
+
const star$1 = qmark$1 + '*?';
|
|
496
|
+
// use + when we need to ensure that *something* matches, because the * is
|
|
497
|
+
// the only thing in the path portion.
|
|
498
|
+
const starNoEmpty = qmark$1 + '+?';
|
|
499
|
+
// remove the \ chars that we added if we end up doing a nonmagic compare
|
|
500
|
+
// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
|
|
501
|
+
class AST {
|
|
502
|
+
type;
|
|
503
|
+
#root;
|
|
504
|
+
#hasMagic;
|
|
505
|
+
#uflag = false;
|
|
506
|
+
#parts = [];
|
|
507
|
+
#parent;
|
|
508
|
+
#parentIndex;
|
|
509
|
+
#negs;
|
|
510
|
+
#filledNegs = false;
|
|
511
|
+
#options;
|
|
512
|
+
#toString;
|
|
513
|
+
// set to true if it's an extglob with no children
|
|
514
|
+
// (which really means one child of '')
|
|
515
|
+
#emptyExt = false;
|
|
516
|
+
constructor(type, parent, options = {}) {
|
|
517
|
+
this.type = type;
|
|
518
|
+
// extglobs are inherently magical
|
|
519
|
+
if (type)
|
|
520
|
+
this.#hasMagic = true;
|
|
521
|
+
this.#parent = parent;
|
|
522
|
+
this.#root = this.#parent ? this.#parent.#root : this;
|
|
523
|
+
this.#options = this.#root === this ? options : this.#root.#options;
|
|
524
|
+
this.#negs = this.#root === this ? [] : this.#root.#negs;
|
|
525
|
+
if (type === '!' && !this.#root.#filledNegs)
|
|
526
|
+
this.#negs.push(this);
|
|
527
|
+
this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
|
|
528
|
+
}
|
|
529
|
+
get hasMagic() {
|
|
530
|
+
/* c8 ignore start */
|
|
531
|
+
if (this.#hasMagic !== undefined)
|
|
532
|
+
return this.#hasMagic;
|
|
533
|
+
/* c8 ignore stop */
|
|
534
|
+
for (const p of this.#parts) {
|
|
535
|
+
if (typeof p === 'string')
|
|
536
|
+
continue;
|
|
537
|
+
if (p.type || p.hasMagic)
|
|
538
|
+
return (this.#hasMagic = true);
|
|
539
|
+
}
|
|
540
|
+
// note: will be undefined until we generate the regexp src and find out
|
|
541
|
+
return this.#hasMagic;
|
|
542
|
+
}
|
|
543
|
+
// reconstructs the pattern
|
|
544
|
+
toString() {
|
|
545
|
+
if (this.#toString !== undefined)
|
|
546
|
+
return this.#toString;
|
|
547
|
+
if (!this.type) {
|
|
548
|
+
return (this.#toString = this.#parts.map(p => String(p)).join(''));
|
|
549
|
+
}
|
|
550
|
+
else {
|
|
551
|
+
return (this.#toString =
|
|
552
|
+
this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
#fillNegs() {
|
|
556
|
+
/* c8 ignore start */
|
|
557
|
+
if (this !== this.#root)
|
|
558
|
+
throw new Error('should only call on root');
|
|
559
|
+
if (this.#filledNegs)
|
|
560
|
+
return this;
|
|
561
|
+
/* c8 ignore stop */
|
|
562
|
+
// call toString() once to fill this out
|
|
563
|
+
this.toString();
|
|
564
|
+
this.#filledNegs = true;
|
|
565
|
+
let n;
|
|
566
|
+
while ((n = this.#negs.pop())) {
|
|
567
|
+
if (n.type !== '!')
|
|
568
|
+
continue;
|
|
569
|
+
// walk up the tree, appending everthing that comes AFTER parentIndex
|
|
570
|
+
let p = n;
|
|
571
|
+
let pp = p.#parent;
|
|
572
|
+
while (pp) {
|
|
573
|
+
for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
|
|
574
|
+
for (const part of n.#parts) {
|
|
575
|
+
/* c8 ignore start */
|
|
576
|
+
if (typeof part === 'string') {
|
|
577
|
+
throw new Error('string part in extglob AST??');
|
|
578
|
+
}
|
|
579
|
+
/* c8 ignore stop */
|
|
580
|
+
part.copyIn(pp.#parts[i]);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
p = pp;
|
|
584
|
+
pp = p.#parent;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
return this;
|
|
588
|
+
}
|
|
589
|
+
push(...parts) {
|
|
590
|
+
for (const p of parts) {
|
|
591
|
+
if (p === '')
|
|
592
|
+
continue;
|
|
593
|
+
/* c8 ignore start */
|
|
594
|
+
if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
|
|
595
|
+
throw new Error('invalid part: ' + p);
|
|
596
|
+
}
|
|
597
|
+
/* c8 ignore stop */
|
|
598
|
+
this.#parts.push(p);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
toJSON() {
|
|
602
|
+
const ret = this.type === null
|
|
603
|
+
? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
|
|
604
|
+
: [this.type, ...this.#parts.map(p => p.toJSON())];
|
|
605
|
+
if (this.isStart() && !this.type)
|
|
606
|
+
ret.unshift([]);
|
|
607
|
+
if (this.isEnd() &&
|
|
608
|
+
(this === this.#root ||
|
|
609
|
+
(this.#root.#filledNegs && this.#parent?.type === '!'))) {
|
|
610
|
+
ret.push({});
|
|
611
|
+
}
|
|
612
|
+
return ret;
|
|
613
|
+
}
|
|
614
|
+
isStart() {
|
|
615
|
+
if (this.#root === this)
|
|
616
|
+
return true;
|
|
617
|
+
// if (this.type) return !!this.#parent?.isStart()
|
|
618
|
+
if (!this.#parent?.isStart())
|
|
619
|
+
return false;
|
|
620
|
+
if (this.#parentIndex === 0)
|
|
621
|
+
return true;
|
|
622
|
+
// if everything AHEAD of this is a negation, then it's still the "start"
|
|
623
|
+
const p = this.#parent;
|
|
624
|
+
for (let i = 0; i < this.#parentIndex; i++) {
|
|
625
|
+
const pp = p.#parts[i];
|
|
626
|
+
if (!(pp instanceof AST && pp.type === '!')) {
|
|
627
|
+
return false;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return true;
|
|
631
|
+
}
|
|
632
|
+
isEnd() {
|
|
633
|
+
if (this.#root === this)
|
|
634
|
+
return true;
|
|
635
|
+
if (this.#parent?.type === '!')
|
|
636
|
+
return true;
|
|
637
|
+
if (!this.#parent?.isEnd())
|
|
638
|
+
return false;
|
|
639
|
+
if (!this.type)
|
|
640
|
+
return this.#parent?.isEnd();
|
|
641
|
+
// if not root, it'll always have a parent
|
|
642
|
+
/* c8 ignore start */
|
|
643
|
+
const pl = this.#parent ? this.#parent.#parts.length : 0;
|
|
644
|
+
/* c8 ignore stop */
|
|
645
|
+
return this.#parentIndex === pl - 1;
|
|
646
|
+
}
|
|
647
|
+
copyIn(part) {
|
|
648
|
+
if (typeof part === 'string')
|
|
649
|
+
this.push(part);
|
|
650
|
+
else
|
|
651
|
+
this.push(part.clone(this));
|
|
652
|
+
}
|
|
653
|
+
clone(parent) {
|
|
654
|
+
const c = new AST(this.type, parent);
|
|
655
|
+
for (const p of this.#parts) {
|
|
656
|
+
c.copyIn(p);
|
|
657
|
+
}
|
|
658
|
+
return c;
|
|
659
|
+
}
|
|
660
|
+
static #parseAST(str, ast, pos, opt) {
|
|
661
|
+
let escaping = false;
|
|
662
|
+
let inBrace = false;
|
|
663
|
+
let braceStart = -1;
|
|
664
|
+
let braceNeg = false;
|
|
665
|
+
if (ast.type === null) {
|
|
666
|
+
// outside of a extglob, append until we find a start
|
|
667
|
+
let i = pos;
|
|
668
|
+
let acc = '';
|
|
669
|
+
while (i < str.length) {
|
|
670
|
+
const c = str.charAt(i++);
|
|
671
|
+
// still accumulate escapes at this point, but we do ignore
|
|
672
|
+
// starts that are escaped
|
|
673
|
+
if (escaping || c === '\\') {
|
|
674
|
+
escaping = !escaping;
|
|
675
|
+
acc += c;
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
if (inBrace) {
|
|
679
|
+
if (i === braceStart + 1) {
|
|
680
|
+
if (c === '^' || c === '!') {
|
|
681
|
+
braceNeg = true;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
|
|
685
|
+
inBrace = false;
|
|
686
|
+
}
|
|
687
|
+
acc += c;
|
|
688
|
+
continue;
|
|
689
|
+
}
|
|
690
|
+
else if (c === '[') {
|
|
691
|
+
inBrace = true;
|
|
692
|
+
braceStart = i;
|
|
693
|
+
braceNeg = false;
|
|
694
|
+
acc += c;
|
|
695
|
+
continue;
|
|
696
|
+
}
|
|
697
|
+
if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
|
|
698
|
+
ast.push(acc);
|
|
699
|
+
acc = '';
|
|
700
|
+
const ext = new AST(c, ast);
|
|
701
|
+
i = AST.#parseAST(str, ext, i, opt);
|
|
702
|
+
ast.push(ext);
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
acc += c;
|
|
706
|
+
}
|
|
707
|
+
ast.push(acc);
|
|
708
|
+
return i;
|
|
709
|
+
}
|
|
710
|
+
// some kind of extglob, pos is at the (
|
|
711
|
+
// find the next | or )
|
|
712
|
+
let i = pos + 1;
|
|
713
|
+
let part = new AST(null, ast);
|
|
714
|
+
const parts = [];
|
|
715
|
+
let acc = '';
|
|
716
|
+
while (i < str.length) {
|
|
717
|
+
const c = str.charAt(i++);
|
|
718
|
+
// still accumulate escapes at this point, but we do ignore
|
|
719
|
+
// starts that are escaped
|
|
720
|
+
if (escaping || c === '\\') {
|
|
721
|
+
escaping = !escaping;
|
|
722
|
+
acc += c;
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
if (inBrace) {
|
|
726
|
+
if (i === braceStart + 1) {
|
|
727
|
+
if (c === '^' || c === '!') {
|
|
728
|
+
braceNeg = true;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
|
|
732
|
+
inBrace = false;
|
|
733
|
+
}
|
|
734
|
+
acc += c;
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
else if (c === '[') {
|
|
738
|
+
inBrace = true;
|
|
739
|
+
braceStart = i;
|
|
740
|
+
braceNeg = false;
|
|
741
|
+
acc += c;
|
|
742
|
+
continue;
|
|
743
|
+
}
|
|
744
|
+
if (isExtglobType(c) && str.charAt(i) === '(') {
|
|
745
|
+
part.push(acc);
|
|
746
|
+
acc = '';
|
|
747
|
+
const ext = new AST(c, part);
|
|
748
|
+
part.push(ext);
|
|
749
|
+
i = AST.#parseAST(str, ext, i, opt);
|
|
750
|
+
continue;
|
|
751
|
+
}
|
|
752
|
+
if (c === '|') {
|
|
753
|
+
part.push(acc);
|
|
754
|
+
acc = '';
|
|
755
|
+
parts.push(part);
|
|
756
|
+
part = new AST(null, ast);
|
|
757
|
+
continue;
|
|
758
|
+
}
|
|
759
|
+
if (c === ')') {
|
|
760
|
+
if (acc === '' && ast.#parts.length === 0) {
|
|
761
|
+
ast.#emptyExt = true;
|
|
762
|
+
}
|
|
763
|
+
part.push(acc);
|
|
764
|
+
acc = '';
|
|
765
|
+
ast.push(...parts, part);
|
|
766
|
+
return i;
|
|
767
|
+
}
|
|
768
|
+
acc += c;
|
|
769
|
+
}
|
|
770
|
+
// unfinished extglob
|
|
771
|
+
// if we got here, it was a malformed extglob! not an extglob, but
|
|
772
|
+
// maybe something else in there.
|
|
773
|
+
ast.type = null;
|
|
774
|
+
ast.#hasMagic = undefined;
|
|
775
|
+
ast.#parts = [str.substring(pos - 1)];
|
|
776
|
+
return i;
|
|
777
|
+
}
|
|
778
|
+
static fromGlob(pattern, options = {}) {
|
|
779
|
+
const ast = new AST(null, undefined, options);
|
|
780
|
+
AST.#parseAST(pattern, ast, 0, options);
|
|
781
|
+
return ast;
|
|
782
|
+
}
|
|
783
|
+
// returns the regular expression if there's magic, or the unescaped
|
|
784
|
+
// string if not.
|
|
785
|
+
toMMPattern() {
|
|
786
|
+
// should only be called on root
|
|
787
|
+
/* c8 ignore start */
|
|
788
|
+
if (this !== this.#root)
|
|
789
|
+
return this.#root.toMMPattern();
|
|
790
|
+
/* c8 ignore stop */
|
|
791
|
+
const glob = this.toString();
|
|
792
|
+
const [re, body, hasMagic, uflag] = this.toRegExpSource();
|
|
793
|
+
// if we're in nocase mode, and not nocaseMagicOnly, then we do
|
|
794
|
+
// still need a regular expression if we have to case-insensitively
|
|
795
|
+
// match capital/lowercase characters.
|
|
796
|
+
const anyMagic = hasMagic ||
|
|
797
|
+
this.#hasMagic ||
|
|
798
|
+
(this.#options.nocase &&
|
|
799
|
+
!this.#options.nocaseMagicOnly &&
|
|
800
|
+
glob.toUpperCase() !== glob.toLowerCase());
|
|
801
|
+
if (!anyMagic) {
|
|
802
|
+
return body;
|
|
803
|
+
}
|
|
804
|
+
const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
|
|
805
|
+
return Object.assign(new RegExp(`^${re}$`, flags), {
|
|
806
|
+
_src: re,
|
|
807
|
+
_glob: glob,
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
get options() {
|
|
811
|
+
return this.#options;
|
|
812
|
+
}
|
|
813
|
+
// returns the string match, the regexp source, whether there's magic
|
|
814
|
+
// in the regexp (so a regular expression is required) and whether or
|
|
815
|
+
// not the uflag is needed for the regular expression (for posix classes)
|
|
816
|
+
// TODO: instead of injecting the start/end at this point, just return
|
|
817
|
+
// the BODY of the regexp, along with the start/end portions suitable
|
|
818
|
+
// for binding the start/end in either a joined full-path makeRe context
|
|
819
|
+
// (where we bind to (^|/), or a standalone matchPart context (where
|
|
820
|
+
// we bind to ^, and not /). Otherwise slashes get duped!
|
|
821
|
+
//
|
|
822
|
+
// In part-matching mode, the start is:
|
|
823
|
+
// - if not isStart: nothing
|
|
824
|
+
// - if traversal possible, but not allowed: ^(?!\.\.?$)
|
|
825
|
+
// - if dots allowed or not possible: ^
|
|
826
|
+
// - if dots possible and not allowed: ^(?!\.)
|
|
827
|
+
// end is:
|
|
828
|
+
// - if not isEnd(): nothing
|
|
829
|
+
// - else: $
|
|
830
|
+
//
|
|
831
|
+
// In full-path matching mode, we put the slash at the START of the
|
|
832
|
+
// pattern, so start is:
|
|
833
|
+
// - if first pattern: same as part-matching mode
|
|
834
|
+
// - if not isStart(): nothing
|
|
835
|
+
// - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
|
|
836
|
+
// - if dots allowed or not possible: /
|
|
837
|
+
// - if dots possible and not allowed: /(?!\.)
|
|
838
|
+
// end is:
|
|
839
|
+
// - if last pattern, same as part-matching mode
|
|
840
|
+
// - else nothing
|
|
841
|
+
//
|
|
842
|
+
// Always put the (?:$|/) on negated tails, though, because that has to be
|
|
843
|
+
// there to bind the end of the negated pattern portion, and it's easier to
|
|
844
|
+
// just stick it in now rather than try to inject it later in the middle of
|
|
845
|
+
// the pattern.
|
|
846
|
+
//
|
|
847
|
+
// We can just always return the same end, and leave it up to the caller
|
|
848
|
+
// to know whether it's going to be used joined or in parts.
|
|
849
|
+
// And, if the start is adjusted slightly, can do the same there:
|
|
850
|
+
// - if not isStart: nothing
|
|
851
|
+
// - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
|
|
852
|
+
// - if dots allowed or not possible: (?:/|^)
|
|
853
|
+
// - if dots possible and not allowed: (?:/|^)(?!\.)
|
|
854
|
+
//
|
|
855
|
+
// But it's better to have a simpler binding without a conditional, for
|
|
856
|
+
// performance, so probably better to return both start options.
|
|
857
|
+
//
|
|
858
|
+
// Then the caller just ignores the end if it's not the first pattern,
|
|
859
|
+
// and the start always gets applied.
|
|
860
|
+
//
|
|
861
|
+
// But that's always going to be $ if it's the ending pattern, or nothing,
|
|
862
|
+
// so the caller can just attach $ at the end of the pattern when building.
|
|
863
|
+
//
|
|
864
|
+
// So the todo is:
|
|
865
|
+
// - better detect what kind of start is needed
|
|
866
|
+
// - return both flavors of starting pattern
|
|
867
|
+
// - attach $ at the end of the pattern when creating the actual RegExp
|
|
868
|
+
//
|
|
869
|
+
// Ah, but wait, no, that all only applies to the root when the first pattern
|
|
870
|
+
// is not an extglob. If the first pattern IS an extglob, then we need all
|
|
871
|
+
// that dot prevention biz to live in the extglob portions, because eg
|
|
872
|
+
// +(*|.x*) can match .xy but not .yx.
|
|
873
|
+
//
|
|
874
|
+
// So, return the two flavors if it's #root and the first child is not an
|
|
875
|
+
// AST, otherwise leave it to the child AST to handle it, and there,
|
|
876
|
+
// use the (?:^|/) style of start binding.
|
|
877
|
+
//
|
|
878
|
+
// Even simplified further:
|
|
879
|
+
// - Since the start for a join is eg /(?!\.) and the start for a part
|
|
880
|
+
// is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
|
|
881
|
+
// or start or whatever) and prepend ^ or / at the Regexp construction.
|
|
882
|
+
toRegExpSource(allowDot) {
|
|
883
|
+
const dot = allowDot ?? !!this.#options.dot;
|
|
884
|
+
if (this.#root === this)
|
|
885
|
+
this.#fillNegs();
|
|
886
|
+
if (!this.type) {
|
|
887
|
+
const noEmpty = this.isStart() &&
|
|
888
|
+
this.isEnd() &&
|
|
889
|
+
!this.#parts.some(s => typeof s !== 'string');
|
|
890
|
+
const src = this.#parts
|
|
891
|
+
.map(p => {
|
|
892
|
+
const [re, _, hasMagic, uflag] = typeof p === 'string'
|
|
893
|
+
? AST.#parseGlob(p, this.#hasMagic, noEmpty)
|
|
894
|
+
: p.toRegExpSource(allowDot);
|
|
895
|
+
this.#hasMagic = this.#hasMagic || hasMagic;
|
|
896
|
+
this.#uflag = this.#uflag || uflag;
|
|
897
|
+
return re;
|
|
898
|
+
})
|
|
899
|
+
.join('');
|
|
900
|
+
let start = '';
|
|
901
|
+
if (this.isStart()) {
|
|
902
|
+
if (typeof this.#parts[0] === 'string') {
|
|
903
|
+
// this is the string that will match the start of the pattern,
|
|
904
|
+
// so we need to protect against dots and such.
|
|
905
|
+
// '.' and '..' cannot match unless the pattern is that exactly,
|
|
906
|
+
// even if it starts with . or dot:true is set.
|
|
907
|
+
const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
|
|
908
|
+
if (!dotTravAllowed) {
|
|
909
|
+
const aps = addPatternStart;
|
|
910
|
+
// check if we have a possibility of matching . or ..,
|
|
911
|
+
// and prevent that.
|
|
912
|
+
const needNoTrav =
|
|
913
|
+
// dots are allowed, and the pattern starts with [ or .
|
|
914
|
+
(dot && aps.has(src.charAt(0))) ||
|
|
915
|
+
// the pattern starts with \., and then [ or .
|
|
916
|
+
(src.startsWith('\\.') && aps.has(src.charAt(2))) ||
|
|
917
|
+
// the pattern starts with \.\., and then [ or .
|
|
918
|
+
(src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
|
|
919
|
+
// no need to prevent dots if it can't match a dot, or if a
|
|
920
|
+
// sub-pattern will be preventing it anyway.
|
|
921
|
+
const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
|
|
922
|
+
start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
// append the "end of path portion" pattern to negation tails
|
|
927
|
+
let end = '';
|
|
928
|
+
if (this.isEnd() &&
|
|
929
|
+
this.#root.#filledNegs &&
|
|
930
|
+
this.#parent?.type === '!') {
|
|
931
|
+
end = '(?:$|\\/)';
|
|
932
|
+
}
|
|
933
|
+
const final = start + src + end;
|
|
934
|
+
return [
|
|
935
|
+
final,
|
|
936
|
+
unescape(src),
|
|
937
|
+
(this.#hasMagic = !!this.#hasMagic),
|
|
938
|
+
this.#uflag,
|
|
939
|
+
];
|
|
940
|
+
}
|
|
941
|
+
// We need to calculate the body *twice* if it's a repeat pattern
|
|
942
|
+
// at the start, once in nodot mode, then again in dot mode, so a
|
|
943
|
+
// pattern like *(?) can match 'x.y'
|
|
944
|
+
const repeated = this.type === '*' || this.type === '+';
|
|
945
|
+
// some kind of extglob
|
|
946
|
+
const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
|
|
947
|
+
let body = this.#partsToRegExp(dot);
|
|
948
|
+
if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
|
|
949
|
+
// invalid extglob, has to at least be *something* present, if it's
|
|
950
|
+
// the entire path portion.
|
|
951
|
+
const s = this.toString();
|
|
952
|
+
this.#parts = [s];
|
|
953
|
+
this.type = null;
|
|
954
|
+
this.#hasMagic = undefined;
|
|
955
|
+
return [s, unescape(this.toString()), false, false];
|
|
956
|
+
}
|
|
957
|
+
// XXX abstract out this map method
|
|
958
|
+
let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
|
|
959
|
+
? ''
|
|
960
|
+
: this.#partsToRegExp(true);
|
|
961
|
+
if (bodyDotAllowed === body) {
|
|
962
|
+
bodyDotAllowed = '';
|
|
963
|
+
}
|
|
964
|
+
if (bodyDotAllowed) {
|
|
965
|
+
body = `(?:${body})(?:${bodyDotAllowed})*?`;
|
|
966
|
+
}
|
|
967
|
+
// an empty !() is exactly equivalent to a starNoEmpty
|
|
968
|
+
let final = '';
|
|
969
|
+
if (this.type === '!' && this.#emptyExt) {
|
|
970
|
+
final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
|
|
971
|
+
}
|
|
972
|
+
else {
|
|
973
|
+
const close = this.type === '!'
|
|
974
|
+
? // !() must match something,but !(x) can match ''
|
|
975
|
+
'))' +
|
|
976
|
+
(this.isStart() && !dot && !allowDot ? startNoDot : '') +
|
|
977
|
+
star$1 +
|
|
978
|
+
')'
|
|
979
|
+
: this.type === '@'
|
|
980
|
+
? ')'
|
|
981
|
+
: this.type === '?'
|
|
982
|
+
? ')?'
|
|
983
|
+
: this.type === '+' && bodyDotAllowed
|
|
984
|
+
? ')'
|
|
985
|
+
: this.type === '*' && bodyDotAllowed
|
|
986
|
+
? `)?`
|
|
987
|
+
: `)${this.type}`;
|
|
988
|
+
final = start + body + close;
|
|
989
|
+
}
|
|
990
|
+
return [
|
|
991
|
+
final,
|
|
992
|
+
unescape(body),
|
|
993
|
+
(this.#hasMagic = !!this.#hasMagic),
|
|
994
|
+
this.#uflag,
|
|
995
|
+
];
|
|
996
|
+
}
|
|
997
|
+
#partsToRegExp(dot) {
|
|
998
|
+
return this.#parts
|
|
999
|
+
.map(p => {
|
|
1000
|
+
// extglob ASTs should only contain parent ASTs
|
|
1001
|
+
/* c8 ignore start */
|
|
1002
|
+
if (typeof p === 'string') {
|
|
1003
|
+
throw new Error('string type in extglob ast??');
|
|
1004
|
+
}
|
|
1005
|
+
/* c8 ignore stop */
|
|
1006
|
+
// can ignore hasMagic, because extglobs are already always magic
|
|
1007
|
+
const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
|
|
1008
|
+
this.#uflag = this.#uflag || uflag;
|
|
1009
|
+
return re;
|
|
1010
|
+
})
|
|
1011
|
+
.filter(p => !(this.isStart() && this.isEnd()) || !!p)
|
|
1012
|
+
.join('|');
|
|
1013
|
+
}
|
|
1014
|
+
static #parseGlob(glob, hasMagic, noEmpty = false) {
|
|
1015
|
+
let escaping = false;
|
|
1016
|
+
let re = '';
|
|
1017
|
+
let uflag = false;
|
|
1018
|
+
for (let i = 0; i < glob.length; i++) {
|
|
1019
|
+
const c = glob.charAt(i);
|
|
1020
|
+
if (escaping) {
|
|
1021
|
+
escaping = false;
|
|
1022
|
+
re += (reSpecials.has(c) ? '\\' : '') + c;
|
|
1023
|
+
continue;
|
|
1024
|
+
}
|
|
1025
|
+
if (c === '\\') {
|
|
1026
|
+
if (i === glob.length - 1) {
|
|
1027
|
+
re += '\\\\';
|
|
1028
|
+
}
|
|
1029
|
+
else {
|
|
1030
|
+
escaping = true;
|
|
1031
|
+
}
|
|
1032
|
+
continue;
|
|
1033
|
+
}
|
|
1034
|
+
if (c === '[') {
|
|
1035
|
+
const [src, needUflag, consumed, magic] = parseClass(glob, i);
|
|
1036
|
+
if (consumed) {
|
|
1037
|
+
re += src;
|
|
1038
|
+
uflag = uflag || needUflag;
|
|
1039
|
+
i += consumed - 1;
|
|
1040
|
+
hasMagic = hasMagic || magic;
|
|
1041
|
+
continue;
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
if (c === '*') {
|
|
1045
|
+
re += noEmpty && glob === '*' ? starNoEmpty : star$1;
|
|
1046
|
+
hasMagic = true;
|
|
1047
|
+
continue;
|
|
1048
|
+
}
|
|
1049
|
+
if (c === '?') {
|
|
1050
|
+
re += qmark$1;
|
|
1051
|
+
hasMagic = true;
|
|
1052
|
+
continue;
|
|
1053
|
+
}
|
|
1054
|
+
re += regExpEscape$1(c);
|
|
1055
|
+
}
|
|
1056
|
+
return [re, unescape(glob), !!hasMagic, uflag];
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
/**
|
|
1061
|
+
* Escape all magic characters in a glob pattern.
|
|
1062
|
+
*
|
|
1063
|
+
* If the {@link MinimatchOptions.windowsPathsNoEscape}
|
|
1064
|
+
* option is used, then characters are escaped by wrapping in `[]`, because
|
|
1065
|
+
* a magic character wrapped in a character class can only be satisfied by
|
|
1066
|
+
* that exact character. In this mode, `\` is _not_ escaped, because it is
|
|
1067
|
+
* not interpreted as a magic character, but instead as a path separator.
|
|
1068
|
+
*
|
|
1069
|
+
* If the {@link MinimatchOptions.magicalBraces} option is used,
|
|
1070
|
+
* then braces (`{` and `}`) will be escaped.
|
|
1071
|
+
*/
|
|
1072
|
+
const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
|
|
1073
|
+
// don't need to escape +@! because we escape the parens
|
|
1074
|
+
// that make those magic, and escaping ! as [!] isn't valid,
|
|
1075
|
+
// because [!]] is a valid glob class meaning not ']'.
|
|
1076
|
+
if (magicalBraces) {
|
|
1077
|
+
return windowsPathsNoEscape
|
|
1078
|
+
? s.replace(/[?*()[\]{}]/g, '[$&]')
|
|
1079
|
+
: s.replace(/[?*()[\]\\{}]/g, '\\$&');
|
|
1080
|
+
}
|
|
1081
|
+
return windowsPathsNoEscape
|
|
1082
|
+
? s.replace(/[?*()[\]]/g, '[$&]')
|
|
1083
|
+
: s.replace(/[?*()[\]\\]/g, '\\$&');
|
|
1084
|
+
};
|
|
1085
|
+
|
|
1086
|
+
const minimatch = (p, pattern, options = {}) => {
|
|
1087
|
+
assertValidPattern(pattern);
|
|
1088
|
+
// shortcut: comments match nothing.
|
|
1089
|
+
if (!options.nocomment && pattern.charAt(0) === '#') {
|
|
1090
|
+
return false;
|
|
1091
|
+
}
|
|
1092
|
+
return new Minimatch(pattern, options).match(p);
|
|
1093
|
+
};
|
|
1094
|
+
// Optimized checking for the most common glob patterns.
|
|
1095
|
+
const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
|
|
1096
|
+
const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
|
|
1097
|
+
const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
|
|
1098
|
+
const starDotExtTestNocase = (ext) => {
|
|
1099
|
+
ext = ext.toLowerCase();
|
|
1100
|
+
return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
|
|
1101
|
+
};
|
|
1102
|
+
const starDotExtTestNocaseDot = (ext) => {
|
|
1103
|
+
ext = ext.toLowerCase();
|
|
1104
|
+
return (f) => f.toLowerCase().endsWith(ext);
|
|
1105
|
+
};
|
|
1106
|
+
const starDotStarRE = /^\*+\.\*+$/;
|
|
1107
|
+
const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
|
|
1108
|
+
const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
|
|
1109
|
+
const dotStarRE = /^\.\*+$/;
|
|
1110
|
+
const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
|
|
1111
|
+
const starRE = /^\*+$/;
|
|
1112
|
+
const starTest = (f) => f.length !== 0 && !f.startsWith('.');
|
|
1113
|
+
const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
|
|
1114
|
+
const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
|
|
1115
|
+
const qmarksTestNocase = ([$0, ext = '']) => {
|
|
1116
|
+
const noext = qmarksTestNoExt([$0]);
|
|
1117
|
+
if (!ext)
|
|
1118
|
+
return noext;
|
|
1119
|
+
ext = ext.toLowerCase();
|
|
1120
|
+
return (f) => noext(f) && f.toLowerCase().endsWith(ext);
|
|
1121
|
+
};
|
|
1122
|
+
const qmarksTestNocaseDot = ([$0, ext = '']) => {
|
|
1123
|
+
const noext = qmarksTestNoExtDot([$0]);
|
|
1124
|
+
if (!ext)
|
|
1125
|
+
return noext;
|
|
1126
|
+
ext = ext.toLowerCase();
|
|
1127
|
+
return (f) => noext(f) && f.toLowerCase().endsWith(ext);
|
|
1128
|
+
};
|
|
1129
|
+
const qmarksTestDot = ([$0, ext = '']) => {
|
|
1130
|
+
const noext = qmarksTestNoExtDot([$0]);
|
|
1131
|
+
return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
|
|
1132
|
+
};
|
|
1133
|
+
const qmarksTest = ([$0, ext = '']) => {
|
|
1134
|
+
const noext = qmarksTestNoExt([$0]);
|
|
1135
|
+
return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
|
|
1136
|
+
};
|
|
1137
|
+
const qmarksTestNoExt = ([$0]) => {
|
|
1138
|
+
const len = $0.length;
|
|
1139
|
+
return (f) => f.length === len && !f.startsWith('.');
|
|
1140
|
+
};
|
|
1141
|
+
const qmarksTestNoExtDot = ([$0]) => {
|
|
1142
|
+
const len = $0.length;
|
|
1143
|
+
return (f) => f.length === len && f !== '.' && f !== '..';
|
|
1144
|
+
};
|
|
1145
|
+
/* c8 ignore start */
|
|
1146
|
+
const defaultPlatform = (typeof process === 'object' && process
|
|
1147
|
+
? (typeof process.env === 'object' &&
|
|
1148
|
+
process.env &&
|
|
1149
|
+
process.env.__MINIMATCH_TESTING_PLATFORM__) ||
|
|
1150
|
+
process.platform
|
|
1151
|
+
: 'posix');
|
|
1152
|
+
const path = {
|
|
1153
|
+
win32: { sep: '\\' },
|
|
1154
|
+
posix: { sep: '/' },
|
|
1155
|
+
};
|
|
1156
|
+
/* c8 ignore stop */
|
|
1157
|
+
const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
|
|
1158
|
+
minimatch.sep = sep;
|
|
1159
|
+
const GLOBSTAR = Symbol('globstar **');
|
|
1160
|
+
minimatch.GLOBSTAR = GLOBSTAR;
|
|
1161
|
+
// any single thing other than /
|
|
1162
|
+
// don't need to escape / when using new RegExp()
|
|
1163
|
+
const qmark = '[^/]';
|
|
1164
|
+
// * => any number of characters
|
|
1165
|
+
const star = qmark + '*?';
|
|
1166
|
+
// ** when dots are allowed. Anything goes, except .. and .
|
|
1167
|
+
// not (^ or / followed by one or two dots followed by $ or /),
|
|
1168
|
+
// followed by anything, any number of times.
|
|
1169
|
+
const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
|
|
1170
|
+
// not a ^ or / followed by a dot,
|
|
1171
|
+
// followed by anything, any number of times.
|
|
1172
|
+
const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
|
|
1173
|
+
const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
|
|
1174
|
+
minimatch.filter = filter;
|
|
1175
|
+
const ext = (a, b = {}) => Object.assign({}, a, b);
|
|
1176
|
+
const defaults = (def) => {
|
|
1177
|
+
if (!def || typeof def !== 'object' || !Object.keys(def).length) {
|
|
1178
|
+
return minimatch;
|
|
1179
|
+
}
|
|
1180
|
+
const orig = minimatch;
|
|
1181
|
+
const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
|
|
1182
|
+
return Object.assign(m, {
|
|
1183
|
+
Minimatch: class Minimatch extends orig.Minimatch {
|
|
1184
|
+
constructor(pattern, options = {}) {
|
|
1185
|
+
super(pattern, ext(def, options));
|
|
1186
|
+
}
|
|
1187
|
+
static defaults(options) {
|
|
1188
|
+
return orig.defaults(ext(def, options)).Minimatch;
|
|
1189
|
+
}
|
|
1190
|
+
},
|
|
1191
|
+
AST: class AST extends orig.AST {
|
|
1192
|
+
/* c8 ignore start */
|
|
1193
|
+
constructor(type, parent, options = {}) {
|
|
1194
|
+
super(type, parent, ext(def, options));
|
|
1195
|
+
}
|
|
1196
|
+
/* c8 ignore stop */
|
|
1197
|
+
static fromGlob(pattern, options = {}) {
|
|
1198
|
+
return orig.AST.fromGlob(pattern, ext(def, options));
|
|
1199
|
+
}
|
|
1200
|
+
},
|
|
1201
|
+
unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
|
|
1202
|
+
escape: (s, options = {}) => orig.escape(s, ext(def, options)),
|
|
1203
|
+
filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
|
|
1204
|
+
defaults: (options) => orig.defaults(ext(def, options)),
|
|
1205
|
+
makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
|
|
1206
|
+
braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
|
|
1207
|
+
match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
|
|
1208
|
+
sep: orig.sep,
|
|
1209
|
+
GLOBSTAR: GLOBSTAR,
|
|
1210
|
+
});
|
|
1211
|
+
};
|
|
1212
|
+
minimatch.defaults = defaults;
|
|
1213
|
+
// Brace expansion:
|
|
1214
|
+
// a{b,c}d -> abd acd
|
|
1215
|
+
// a{b,}c -> abc ac
|
|
1216
|
+
// a{0..3}d -> a0d a1d a2d a3d
|
|
1217
|
+
// a{b,c{d,e}f}g -> abg acdfg acefg
|
|
1218
|
+
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
|
|
1219
|
+
//
|
|
1220
|
+
// Invalid sets are not expanded.
|
|
1221
|
+
// a{2..}b -> a{2..}b
|
|
1222
|
+
// a{b}c -> a{b}c
|
|
1223
|
+
const braceExpand = (pattern, options = {}) => {
|
|
1224
|
+
assertValidPattern(pattern);
|
|
1225
|
+
// Thanks to Yeting Li <https://github.com/yetingli> for
|
|
1226
|
+
// improving this regexp to avoid a ReDOS vulnerability.
|
|
1227
|
+
if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
|
|
1228
|
+
// shortcut. no need to expand.
|
|
1229
|
+
return [pattern];
|
|
1230
|
+
}
|
|
1231
|
+
return expand(pattern);
|
|
1232
|
+
};
|
|
1233
|
+
minimatch.braceExpand = braceExpand;
|
|
1234
|
+
// parse a component of the expanded set.
|
|
1235
|
+
// At this point, no pattern may contain "/" in it
|
|
1236
|
+
// so we're going to return a 2d array, where each entry is the full
|
|
1237
|
+
// pattern, split on '/', and then turned into a regular expression.
|
|
1238
|
+
// A regexp is made at the end which joins each array with an
|
|
1239
|
+
// escaped /, and another full one which joins each regexp with |.
|
|
1240
|
+
//
|
|
1241
|
+
// Following the lead of Bash 4.1, note that "**" only has special meaning
|
|
1242
|
+
// when it is the *only* thing in a path portion. Otherwise, any series
|
|
1243
|
+
// of * is equivalent to a single *. Globstar behavior is enabled by
|
|
1244
|
+
// default, and can be disabled by setting options.noglobstar.
|
|
1245
|
+
const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
|
|
1246
|
+
minimatch.makeRe = makeRe;
|
|
1247
|
+
const match = (list, pattern, options = {}) => {
|
|
1248
|
+
const mm = new Minimatch(pattern, options);
|
|
1249
|
+
list = list.filter(f => mm.match(f));
|
|
1250
|
+
if (mm.options.nonull && !list.length) {
|
|
1251
|
+
list.push(pattern);
|
|
1252
|
+
}
|
|
1253
|
+
return list;
|
|
1254
|
+
};
|
|
1255
|
+
minimatch.match = match;
|
|
1256
|
+
// replace stuff like \* with *
|
|
1257
|
+
const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
|
|
1258
|
+
const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
|
|
1259
|
+
class Minimatch {
|
|
1260
|
+
options;
|
|
1261
|
+
set;
|
|
1262
|
+
pattern;
|
|
1263
|
+
windowsPathsNoEscape;
|
|
1264
|
+
nonegate;
|
|
1265
|
+
negate;
|
|
1266
|
+
comment;
|
|
1267
|
+
empty;
|
|
1268
|
+
preserveMultipleSlashes;
|
|
1269
|
+
partial;
|
|
1270
|
+
globSet;
|
|
1271
|
+
globParts;
|
|
1272
|
+
nocase;
|
|
1273
|
+
isWindows;
|
|
1274
|
+
platform;
|
|
1275
|
+
windowsNoMagicRoot;
|
|
1276
|
+
regexp;
|
|
1277
|
+
constructor(pattern, options = {}) {
|
|
1278
|
+
assertValidPattern(pattern);
|
|
1279
|
+
options = options || {};
|
|
1280
|
+
this.options = options;
|
|
1281
|
+
this.pattern = pattern;
|
|
1282
|
+
this.platform = options.platform || defaultPlatform;
|
|
1283
|
+
this.isWindows = this.platform === 'win32';
|
|
1284
|
+
this.windowsPathsNoEscape =
|
|
1285
|
+
!!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
|
|
1286
|
+
if (this.windowsPathsNoEscape) {
|
|
1287
|
+
this.pattern = this.pattern.replace(/\\/g, '/');
|
|
1288
|
+
}
|
|
1289
|
+
this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
|
|
1290
|
+
this.regexp = null;
|
|
1291
|
+
this.negate = false;
|
|
1292
|
+
this.nonegate = !!options.nonegate;
|
|
1293
|
+
this.comment = false;
|
|
1294
|
+
this.empty = false;
|
|
1295
|
+
this.partial = !!options.partial;
|
|
1296
|
+
this.nocase = !!this.options.nocase;
|
|
1297
|
+
this.windowsNoMagicRoot =
|
|
1298
|
+
options.windowsNoMagicRoot !== undefined
|
|
1299
|
+
? options.windowsNoMagicRoot
|
|
1300
|
+
: !!(this.isWindows && this.nocase);
|
|
1301
|
+
this.globSet = [];
|
|
1302
|
+
this.globParts = [];
|
|
1303
|
+
this.set = [];
|
|
1304
|
+
// make the set of regexps etc.
|
|
1305
|
+
this.make();
|
|
1306
|
+
}
|
|
1307
|
+
hasMagic() {
|
|
1308
|
+
if (this.options.magicalBraces && this.set.length > 1) {
|
|
1309
|
+
return true;
|
|
1310
|
+
}
|
|
1311
|
+
for (const pattern of this.set) {
|
|
1312
|
+
for (const part of pattern) {
|
|
1313
|
+
if (typeof part !== 'string')
|
|
1314
|
+
return true;
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
return false;
|
|
1318
|
+
}
|
|
1319
|
+
debug(..._) { }
|
|
1320
|
+
make() {
|
|
1321
|
+
const pattern = this.pattern;
|
|
1322
|
+
const options = this.options;
|
|
1323
|
+
// empty patterns and comments match nothing.
|
|
1324
|
+
if (!options.nocomment && pattern.charAt(0) === '#') {
|
|
1325
|
+
this.comment = true;
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1328
|
+
if (!pattern) {
|
|
1329
|
+
this.empty = true;
|
|
1330
|
+
return;
|
|
1331
|
+
}
|
|
1332
|
+
// step 1: figure out negation, etc.
|
|
1333
|
+
this.parseNegate();
|
|
1334
|
+
// step 2: expand braces
|
|
1335
|
+
this.globSet = [...new Set(this.braceExpand())];
|
|
1336
|
+
if (options.debug) {
|
|
1337
|
+
this.debug = (...args) => console.error(...args);
|
|
1338
|
+
}
|
|
1339
|
+
this.debug(this.pattern, this.globSet);
|
|
1340
|
+
// step 3: now we have a set, so turn each one into a series of
|
|
1341
|
+
// path-portion matching patterns.
|
|
1342
|
+
// These will be regexps, except in the case of "**", which is
|
|
1343
|
+
// set to the GLOBSTAR object for globstar behavior,
|
|
1344
|
+
// and will not contain any / characters
|
|
1345
|
+
//
|
|
1346
|
+
// First, we preprocess to make the glob pattern sets a bit simpler
|
|
1347
|
+
// and deduped. There are some perf-killing patterns that can cause
|
|
1348
|
+
// problems with a glob walk, but we can simplify them down a bit.
|
|
1349
|
+
const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
|
|
1350
|
+
this.globParts = this.preprocess(rawGlobParts);
|
|
1351
|
+
this.debug(this.pattern, this.globParts);
|
|
1352
|
+
// glob --> regexps
|
|
1353
|
+
let set = this.globParts.map((s, _, __) => {
|
|
1354
|
+
if (this.isWindows && this.windowsNoMagicRoot) {
|
|
1355
|
+
// check if it's a drive or unc path.
|
|
1356
|
+
const isUNC = s[0] === '' &&
|
|
1357
|
+
s[1] === '' &&
|
|
1358
|
+
(s[2] === '?' || !globMagic.test(s[2])) &&
|
|
1359
|
+
!globMagic.test(s[3]);
|
|
1360
|
+
const isDrive = /^[a-z]:/i.test(s[0]);
|
|
1361
|
+
if (isUNC) {
|
|
1362
|
+
return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
|
|
1363
|
+
}
|
|
1364
|
+
else if (isDrive) {
|
|
1365
|
+
return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
return s.map(ss => this.parse(ss));
|
|
1369
|
+
});
|
|
1370
|
+
this.debug(this.pattern, set);
|
|
1371
|
+
// filter out everything that didn't compile properly.
|
|
1372
|
+
this.set = set.filter(s => s.indexOf(false) === -1);
|
|
1373
|
+
// do not treat the ? in UNC paths as magic
|
|
1374
|
+
if (this.isWindows) {
|
|
1375
|
+
for (let i = 0; i < this.set.length; i++) {
|
|
1376
|
+
const p = this.set[i];
|
|
1377
|
+
if (p[0] === '' &&
|
|
1378
|
+
p[1] === '' &&
|
|
1379
|
+
this.globParts[i][2] === '?' &&
|
|
1380
|
+
typeof p[3] === 'string' &&
|
|
1381
|
+
/^[a-z]:$/i.test(p[3])) {
|
|
1382
|
+
p[2] = '?';
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
this.debug(this.pattern, this.set);
|
|
1387
|
+
}
|
|
1388
|
+
// various transforms to equivalent pattern sets that are
|
|
1389
|
+
// faster to process in a filesystem walk. The goal is to
|
|
1390
|
+
// eliminate what we can, and push all ** patterns as far
|
|
1391
|
+
// to the right as possible, even if it increases the number
|
|
1392
|
+
// of patterns that we have to process.
|
|
1393
|
+
preprocess(globParts) {
|
|
1394
|
+
// if we're not in globstar mode, then turn all ** into *
|
|
1395
|
+
if (this.options.noglobstar) {
|
|
1396
|
+
for (let i = 0; i < globParts.length; i++) {
|
|
1397
|
+
for (let j = 0; j < globParts[i].length; j++) {
|
|
1398
|
+
if (globParts[i][j] === '**') {
|
|
1399
|
+
globParts[i][j] = '*';
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
const { optimizationLevel = 1 } = this.options;
|
|
1405
|
+
if (optimizationLevel >= 2) {
|
|
1406
|
+
// aggressive optimization for the purpose of fs walking
|
|
1407
|
+
globParts = this.firstPhasePreProcess(globParts);
|
|
1408
|
+
globParts = this.secondPhasePreProcess(globParts);
|
|
1409
|
+
}
|
|
1410
|
+
else if (optimizationLevel >= 1) {
|
|
1411
|
+
// just basic optimizations to remove some .. parts
|
|
1412
|
+
globParts = this.levelOneOptimize(globParts);
|
|
1413
|
+
}
|
|
1414
|
+
else {
|
|
1415
|
+
// just collapse multiple ** portions into one
|
|
1416
|
+
globParts = this.adjascentGlobstarOptimize(globParts);
|
|
1417
|
+
}
|
|
1418
|
+
return globParts;
|
|
1419
|
+
}
|
|
1420
|
+
// just get rid of adjascent ** portions
|
|
1421
|
+
adjascentGlobstarOptimize(globParts) {
|
|
1422
|
+
return globParts.map(parts => {
|
|
1423
|
+
let gs = -1;
|
|
1424
|
+
while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
|
|
1425
|
+
let i = gs;
|
|
1426
|
+
while (parts[i + 1] === '**') {
|
|
1427
|
+
i++;
|
|
1428
|
+
}
|
|
1429
|
+
if (i !== gs) {
|
|
1430
|
+
parts.splice(gs, i - gs);
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
return parts;
|
|
1434
|
+
});
|
|
1435
|
+
}
|
|
1436
|
+
// get rid of adjascent ** and resolve .. portions
|
|
1437
|
+
levelOneOptimize(globParts) {
|
|
1438
|
+
return globParts.map(parts => {
|
|
1439
|
+
parts = parts.reduce((set, part) => {
|
|
1440
|
+
const prev = set[set.length - 1];
|
|
1441
|
+
if (part === '**' && prev === '**') {
|
|
1442
|
+
return set;
|
|
1443
|
+
}
|
|
1444
|
+
if (part === '..') {
|
|
1445
|
+
if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
|
|
1446
|
+
set.pop();
|
|
1447
|
+
return set;
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
set.push(part);
|
|
1451
|
+
return set;
|
|
1452
|
+
}, []);
|
|
1453
|
+
return parts.length === 0 ? [''] : parts;
|
|
1454
|
+
});
|
|
1455
|
+
}
|
|
1456
|
+
levelTwoFileOptimize(parts) {
|
|
1457
|
+
if (!Array.isArray(parts)) {
|
|
1458
|
+
parts = this.slashSplit(parts);
|
|
1459
|
+
}
|
|
1460
|
+
let didSomething = false;
|
|
1461
|
+
do {
|
|
1462
|
+
didSomething = false;
|
|
1463
|
+
// <pre>/<e>/<rest> -> <pre>/<rest>
|
|
1464
|
+
if (!this.preserveMultipleSlashes) {
|
|
1465
|
+
for (let i = 1; i < parts.length - 1; i++) {
|
|
1466
|
+
const p = parts[i];
|
|
1467
|
+
// don't squeeze out UNC patterns
|
|
1468
|
+
if (i === 1 && p === '' && parts[0] === '')
|
|
1469
|
+
continue;
|
|
1470
|
+
if (p === '.' || p === '') {
|
|
1471
|
+
didSomething = true;
|
|
1472
|
+
parts.splice(i, 1);
|
|
1473
|
+
i--;
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
if (parts[0] === '.' &&
|
|
1477
|
+
parts.length === 2 &&
|
|
1478
|
+
(parts[1] === '.' || parts[1] === '')) {
|
|
1479
|
+
didSomething = true;
|
|
1480
|
+
parts.pop();
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
// <pre>/<p>/../<rest> -> <pre>/<rest>
|
|
1484
|
+
let dd = 0;
|
|
1485
|
+
while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
|
|
1486
|
+
const p = parts[dd - 1];
|
|
1487
|
+
if (p && p !== '.' && p !== '..' && p !== '**') {
|
|
1488
|
+
didSomething = true;
|
|
1489
|
+
parts.splice(dd - 1, 2);
|
|
1490
|
+
dd -= 2;
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
} while (didSomething);
|
|
1494
|
+
return parts.length === 0 ? [''] : parts;
|
|
1495
|
+
}
|
|
1496
|
+
// First phase: single-pattern processing
|
|
1497
|
+
// <pre> is 1 or more portions
|
|
1498
|
+
// <rest> is 1 or more portions
|
|
1499
|
+
// <p> is any portion other than ., .., '', or **
|
|
1500
|
+
// <e> is . or ''
|
|
1501
|
+
//
|
|
1502
|
+
// **/.. is *brutal* for filesystem walking performance, because
|
|
1503
|
+
// it effectively resets the recursive walk each time it occurs,
|
|
1504
|
+
// and ** cannot be reduced out by a .. pattern part like a regexp
|
|
1505
|
+
// or most strings (other than .., ., and '') can be.
|
|
1506
|
+
//
|
|
1507
|
+
// <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
|
|
1508
|
+
// <pre>/<e>/<rest> -> <pre>/<rest>
|
|
1509
|
+
// <pre>/<p>/../<rest> -> <pre>/<rest>
|
|
1510
|
+
// **/**/<rest> -> **/<rest>
|
|
1511
|
+
//
|
|
1512
|
+
// **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
|
|
1513
|
+
// this WOULD be allowed if ** did follow symlinks, or * didn't
|
|
1514
|
+
firstPhasePreProcess(globParts) {
|
|
1515
|
+
let didSomething = false;
|
|
1516
|
+
do {
|
|
1517
|
+
didSomething = false;
|
|
1518
|
+
// <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
|
|
1519
|
+
for (let parts of globParts) {
|
|
1520
|
+
let gs = -1;
|
|
1521
|
+
while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
|
|
1522
|
+
let gss = gs;
|
|
1523
|
+
while (parts[gss + 1] === '**') {
|
|
1524
|
+
// <pre>/**/**/<rest> -> <pre>/**/<rest>
|
|
1525
|
+
gss++;
|
|
1526
|
+
}
|
|
1527
|
+
// eg, if gs is 2 and gss is 4, that means we have 3 **
|
|
1528
|
+
// parts, and can remove 2 of them.
|
|
1529
|
+
if (gss > gs) {
|
|
1530
|
+
parts.splice(gs + 1, gss - gs);
|
|
1531
|
+
}
|
|
1532
|
+
let next = parts[gs + 1];
|
|
1533
|
+
const p = parts[gs + 2];
|
|
1534
|
+
const p2 = parts[gs + 3];
|
|
1535
|
+
if (next !== '..')
|
|
1536
|
+
continue;
|
|
1537
|
+
if (!p ||
|
|
1538
|
+
p === '.' ||
|
|
1539
|
+
p === '..' ||
|
|
1540
|
+
!p2 ||
|
|
1541
|
+
p2 === '.' ||
|
|
1542
|
+
p2 === '..') {
|
|
1543
|
+
continue;
|
|
1544
|
+
}
|
|
1545
|
+
didSomething = true;
|
|
1546
|
+
// edit parts in place, and push the new one
|
|
1547
|
+
parts.splice(gs, 1);
|
|
1548
|
+
const other = parts.slice(0);
|
|
1549
|
+
other[gs] = '**';
|
|
1550
|
+
globParts.push(other);
|
|
1551
|
+
gs--;
|
|
1552
|
+
}
|
|
1553
|
+
// <pre>/<e>/<rest> -> <pre>/<rest>
|
|
1554
|
+
if (!this.preserveMultipleSlashes) {
|
|
1555
|
+
for (let i = 1; i < parts.length - 1; i++) {
|
|
1556
|
+
const p = parts[i];
|
|
1557
|
+
// don't squeeze out UNC patterns
|
|
1558
|
+
if (i === 1 && p === '' && parts[0] === '')
|
|
1559
|
+
continue;
|
|
1560
|
+
if (p === '.' || p === '') {
|
|
1561
|
+
didSomething = true;
|
|
1562
|
+
parts.splice(i, 1);
|
|
1563
|
+
i--;
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
if (parts[0] === '.' &&
|
|
1567
|
+
parts.length === 2 &&
|
|
1568
|
+
(parts[1] === '.' || parts[1] === '')) {
|
|
1569
|
+
didSomething = true;
|
|
1570
|
+
parts.pop();
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
// <pre>/<p>/../<rest> -> <pre>/<rest>
|
|
1574
|
+
let dd = 0;
|
|
1575
|
+
while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
|
|
1576
|
+
const p = parts[dd - 1];
|
|
1577
|
+
if (p && p !== '.' && p !== '..' && p !== '**') {
|
|
1578
|
+
didSomething = true;
|
|
1579
|
+
const needDot = dd === 1 && parts[dd + 1] === '**';
|
|
1580
|
+
const splin = needDot ? ['.'] : [];
|
|
1581
|
+
parts.splice(dd - 1, 2, ...splin);
|
|
1582
|
+
if (parts.length === 0)
|
|
1583
|
+
parts.push('');
|
|
1584
|
+
dd -= 2;
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
} while (didSomething);
|
|
1589
|
+
return globParts;
|
|
1590
|
+
}
|
|
1591
|
+
// second phase: multi-pattern dedupes
|
|
1592
|
+
// {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
|
|
1593
|
+
// {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
|
|
1594
|
+
// {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
|
|
1595
|
+
//
|
|
1596
|
+
// {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
|
|
1597
|
+
// ^-- not valid because ** doens't follow symlinks
|
|
1598
|
+
secondPhasePreProcess(globParts) {
|
|
1599
|
+
for (let i = 0; i < globParts.length - 1; i++) {
|
|
1600
|
+
for (let j = i + 1; j < globParts.length; j++) {
|
|
1601
|
+
const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
|
|
1602
|
+
if (matched) {
|
|
1603
|
+
globParts[i] = [];
|
|
1604
|
+
globParts[j] = matched;
|
|
1605
|
+
break;
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
return globParts.filter(gs => gs.length);
|
|
1610
|
+
}
|
|
1611
|
+
partsMatch(a, b, emptyGSMatch = false) {
|
|
1612
|
+
let ai = 0;
|
|
1613
|
+
let bi = 0;
|
|
1614
|
+
let result = [];
|
|
1615
|
+
let which = '';
|
|
1616
|
+
while (ai < a.length && bi < b.length) {
|
|
1617
|
+
if (a[ai] === b[bi]) {
|
|
1618
|
+
result.push(which === 'b' ? b[bi] : a[ai]);
|
|
1619
|
+
ai++;
|
|
1620
|
+
bi++;
|
|
1621
|
+
}
|
|
1622
|
+
else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
|
|
1623
|
+
result.push(a[ai]);
|
|
1624
|
+
ai++;
|
|
1625
|
+
}
|
|
1626
|
+
else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
|
|
1627
|
+
result.push(b[bi]);
|
|
1628
|
+
bi++;
|
|
1629
|
+
}
|
|
1630
|
+
else if (a[ai] === '*' &&
|
|
1631
|
+
b[bi] &&
|
|
1632
|
+
(this.options.dot || !b[bi].startsWith('.')) &&
|
|
1633
|
+
b[bi] !== '**') {
|
|
1634
|
+
if (which === 'b')
|
|
1635
|
+
return false;
|
|
1636
|
+
which = 'a';
|
|
1637
|
+
result.push(a[ai]);
|
|
1638
|
+
ai++;
|
|
1639
|
+
bi++;
|
|
1640
|
+
}
|
|
1641
|
+
else if (b[bi] === '*' &&
|
|
1642
|
+
a[ai] &&
|
|
1643
|
+
(this.options.dot || !a[ai].startsWith('.')) &&
|
|
1644
|
+
a[ai] !== '**') {
|
|
1645
|
+
if (which === 'a')
|
|
1646
|
+
return false;
|
|
1647
|
+
which = 'b';
|
|
1648
|
+
result.push(b[bi]);
|
|
1649
|
+
ai++;
|
|
1650
|
+
bi++;
|
|
1651
|
+
}
|
|
1652
|
+
else {
|
|
1653
|
+
return false;
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
// if we fall out of the loop, it means they two are identical
|
|
1657
|
+
// as long as their lengths match
|
|
1658
|
+
return a.length === b.length && result;
|
|
1659
|
+
}
|
|
1660
|
+
parseNegate() {
|
|
1661
|
+
if (this.nonegate)
|
|
1662
|
+
return;
|
|
1663
|
+
const pattern = this.pattern;
|
|
1664
|
+
let negate = false;
|
|
1665
|
+
let negateOffset = 0;
|
|
1666
|
+
for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
|
|
1667
|
+
negate = !negate;
|
|
1668
|
+
negateOffset++;
|
|
1669
|
+
}
|
|
1670
|
+
if (negateOffset)
|
|
1671
|
+
this.pattern = pattern.slice(negateOffset);
|
|
1672
|
+
this.negate = negate;
|
|
1673
|
+
}
|
|
1674
|
+
// set partial to true to test if, for example,
|
|
1675
|
+
// "/a/b" matches the start of "/*/b/*/d"
|
|
1676
|
+
// Partial means, if you run out of file before you run
|
|
1677
|
+
// out of pattern, then that's fine, as long as all
|
|
1678
|
+
// the parts match.
|
|
1679
|
+
matchOne(file, pattern, partial = false) {
|
|
1680
|
+
const options = this.options;
|
|
1681
|
+
// UNC paths like //?/X:/... can match X:/... and vice versa
|
|
1682
|
+
// Drive letters in absolute drive or unc paths are always compared
|
|
1683
|
+
// case-insensitively.
|
|
1684
|
+
if (this.isWindows) {
|
|
1685
|
+
const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
|
|
1686
|
+
const fileUNC = !fileDrive &&
|
|
1687
|
+
file[0] === '' &&
|
|
1688
|
+
file[1] === '' &&
|
|
1689
|
+
file[2] === '?' &&
|
|
1690
|
+
/^[a-z]:$/i.test(file[3]);
|
|
1691
|
+
const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
|
|
1692
|
+
const patternUNC = !patternDrive &&
|
|
1693
|
+
pattern[0] === '' &&
|
|
1694
|
+
pattern[1] === '' &&
|
|
1695
|
+
pattern[2] === '?' &&
|
|
1696
|
+
typeof pattern[3] === 'string' &&
|
|
1697
|
+
/^[a-z]:$/i.test(pattern[3]);
|
|
1698
|
+
const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
|
|
1699
|
+
const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
|
|
1700
|
+
if (typeof fdi === 'number' && typeof pdi === 'number') {
|
|
1701
|
+
const [fd, pd] = [file[fdi], pattern[pdi]];
|
|
1702
|
+
if (fd.toLowerCase() === pd.toLowerCase()) {
|
|
1703
|
+
pattern[pdi] = fd;
|
|
1704
|
+
if (pdi > fdi) {
|
|
1705
|
+
pattern = pattern.slice(pdi);
|
|
1706
|
+
}
|
|
1707
|
+
else if (fdi > pdi) {
|
|
1708
|
+
file = file.slice(fdi);
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
// resolve and reduce . and .. portions in the file as well.
|
|
1714
|
+
// don't need to do the second phase, because it's only one string[]
|
|
1715
|
+
const { optimizationLevel = 1 } = this.options;
|
|
1716
|
+
if (optimizationLevel >= 2) {
|
|
1717
|
+
file = this.levelTwoFileOptimize(file);
|
|
1718
|
+
}
|
|
1719
|
+
this.debug('matchOne', this, { file, pattern });
|
|
1720
|
+
this.debug('matchOne', file.length, pattern.length);
|
|
1721
|
+
for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
|
|
1722
|
+
this.debug('matchOne loop');
|
|
1723
|
+
var p = pattern[pi];
|
|
1724
|
+
var f = file[fi];
|
|
1725
|
+
this.debug(pattern, p, f);
|
|
1726
|
+
// should be impossible.
|
|
1727
|
+
// some invalid regexp stuff in the set.
|
|
1728
|
+
/* c8 ignore start */
|
|
1729
|
+
if (p === false) {
|
|
1730
|
+
return false;
|
|
1731
|
+
}
|
|
1732
|
+
/* c8 ignore stop */
|
|
1733
|
+
if (p === GLOBSTAR) {
|
|
1734
|
+
this.debug('GLOBSTAR', [pattern, p, f]);
|
|
1735
|
+
// "**"
|
|
1736
|
+
// a/**/b/**/c would match the following:
|
|
1737
|
+
// a/b/x/y/z/c
|
|
1738
|
+
// a/x/y/z/b/c
|
|
1739
|
+
// a/b/x/b/x/c
|
|
1740
|
+
// a/b/c
|
|
1741
|
+
// To do this, take the rest of the pattern after
|
|
1742
|
+
// the **, and see if it would match the file remainder.
|
|
1743
|
+
// If so, return success.
|
|
1744
|
+
// If not, the ** "swallows" a segment, and try again.
|
|
1745
|
+
// This is recursively awful.
|
|
1746
|
+
//
|
|
1747
|
+
// a/**/b/**/c matching a/b/x/y/z/c
|
|
1748
|
+
// - a matches a
|
|
1749
|
+
// - doublestar
|
|
1750
|
+
// - matchOne(b/x/y/z/c, b/**/c)
|
|
1751
|
+
// - b matches b
|
|
1752
|
+
// - doublestar
|
|
1753
|
+
// - matchOne(x/y/z/c, c) -> no
|
|
1754
|
+
// - matchOne(y/z/c, c) -> no
|
|
1755
|
+
// - matchOne(z/c, c) -> no
|
|
1756
|
+
// - matchOne(c, c) yes, hit
|
|
1757
|
+
var fr = fi;
|
|
1758
|
+
var pr = pi + 1;
|
|
1759
|
+
if (pr === pl) {
|
|
1760
|
+
this.debug('** at the end');
|
|
1761
|
+
// a ** at the end will just swallow the rest.
|
|
1762
|
+
// We have found a match.
|
|
1763
|
+
// however, it will not swallow /.x, unless
|
|
1764
|
+
// options.dot is set.
|
|
1765
|
+
// . and .. are *never* matched by **, for explosively
|
|
1766
|
+
// exponential reasons.
|
|
1767
|
+
for (; fi < fl; fi++) {
|
|
1768
|
+
if (file[fi] === '.' ||
|
|
1769
|
+
file[fi] === '..' ||
|
|
1770
|
+
(!options.dot && file[fi].charAt(0) === '.'))
|
|
1771
|
+
return false;
|
|
1772
|
+
}
|
|
1773
|
+
return true;
|
|
1774
|
+
}
|
|
1775
|
+
// ok, let's see if we can swallow whatever we can.
|
|
1776
|
+
while (fr < fl) {
|
|
1777
|
+
var swallowee = file[fr];
|
|
1778
|
+
this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
|
|
1779
|
+
// XXX remove this slice. Just pass the start index.
|
|
1780
|
+
if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
|
|
1781
|
+
this.debug('globstar found match!', fr, fl, swallowee);
|
|
1782
|
+
// found a match.
|
|
1783
|
+
return true;
|
|
1784
|
+
}
|
|
1785
|
+
else {
|
|
1786
|
+
// can't swallow "." or ".." ever.
|
|
1787
|
+
// can only swallow ".foo" when explicitly asked.
|
|
1788
|
+
if (swallowee === '.' ||
|
|
1789
|
+
swallowee === '..' ||
|
|
1790
|
+
(!options.dot && swallowee.charAt(0) === '.')) {
|
|
1791
|
+
this.debug('dot detected!', file, fr, pattern, pr);
|
|
1792
|
+
break;
|
|
1793
|
+
}
|
|
1794
|
+
// ** swallows a segment, and continue.
|
|
1795
|
+
this.debug('globstar swallow a segment, and continue');
|
|
1796
|
+
fr++;
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
// no match was found.
|
|
1800
|
+
// However, in partial mode, we can't say this is necessarily over.
|
|
1801
|
+
/* c8 ignore start */
|
|
1802
|
+
if (partial) {
|
|
1803
|
+
// ran out of file
|
|
1804
|
+
this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
|
|
1805
|
+
if (fr === fl) {
|
|
1806
|
+
return true;
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
/* c8 ignore stop */
|
|
1810
|
+
return false;
|
|
1811
|
+
}
|
|
1812
|
+
// something other than **
|
|
1813
|
+
// non-magic patterns just have to match exactly
|
|
1814
|
+
// patterns with magic have been turned into regexps.
|
|
1815
|
+
let hit;
|
|
1816
|
+
if (typeof p === 'string') {
|
|
1817
|
+
hit = f === p;
|
|
1818
|
+
this.debug('string match', p, f, hit);
|
|
1819
|
+
}
|
|
1820
|
+
else {
|
|
1821
|
+
hit = p.test(f);
|
|
1822
|
+
this.debug('pattern match', p, f, hit);
|
|
1823
|
+
}
|
|
1824
|
+
if (!hit)
|
|
1825
|
+
return false;
|
|
1826
|
+
}
|
|
1827
|
+
// Note: ending in / means that we'll get a final ""
|
|
1828
|
+
// at the end of the pattern. This can only match a
|
|
1829
|
+
// corresponding "" at the end of the file.
|
|
1830
|
+
// If the file ends in /, then it can only match a
|
|
1831
|
+
// a pattern that ends in /, unless the pattern just
|
|
1832
|
+
// doesn't have any more for it. But, a/b/ should *not*
|
|
1833
|
+
// match "a/b/*", even though "" matches against the
|
|
1834
|
+
// [^/]*? pattern, except in partial mode, where it might
|
|
1835
|
+
// simply not be reached yet.
|
|
1836
|
+
// However, a/b/ should still satisfy a/*
|
|
1837
|
+
// now either we fell off the end of the pattern, or we're done.
|
|
1838
|
+
if (fi === fl && pi === pl) {
|
|
1839
|
+
// ran out of pattern and filename at the same time.
|
|
1840
|
+
// an exact hit!
|
|
1841
|
+
return true;
|
|
1842
|
+
}
|
|
1843
|
+
else if (fi === fl) {
|
|
1844
|
+
// ran out of file, but still had pattern left.
|
|
1845
|
+
// this is ok if we're doing the match as part of
|
|
1846
|
+
// a glob fs traversal.
|
|
1847
|
+
return partial;
|
|
1848
|
+
}
|
|
1849
|
+
else if (pi === pl) {
|
|
1850
|
+
// ran out of pattern, still have file left.
|
|
1851
|
+
// this is only acceptable if we're on the very last
|
|
1852
|
+
// empty segment of a file with a trailing slash.
|
|
1853
|
+
// a/* should match a/b/
|
|
1854
|
+
return fi === fl - 1 && file[fi] === '';
|
|
1855
|
+
/* c8 ignore start */
|
|
1856
|
+
}
|
|
1857
|
+
else {
|
|
1858
|
+
// should be unreachable.
|
|
1859
|
+
throw new Error('wtf?');
|
|
1860
|
+
}
|
|
1861
|
+
/* c8 ignore stop */
|
|
1862
|
+
}
|
|
1863
|
+
braceExpand() {
|
|
1864
|
+
return braceExpand(this.pattern, this.options);
|
|
1865
|
+
}
|
|
1866
|
+
parse(pattern) {
|
|
1867
|
+
assertValidPattern(pattern);
|
|
1868
|
+
const options = this.options;
|
|
1869
|
+
// shortcuts
|
|
1870
|
+
if (pattern === '**')
|
|
1871
|
+
return GLOBSTAR;
|
|
1872
|
+
if (pattern === '')
|
|
1873
|
+
return '';
|
|
1874
|
+
// far and away, the most common glob pattern parts are
|
|
1875
|
+
// *, *.*, and *.<ext> Add a fast check method for those.
|
|
1876
|
+
let m;
|
|
1877
|
+
let fastTest = null;
|
|
1878
|
+
if ((m = pattern.match(starRE))) {
|
|
1879
|
+
fastTest = options.dot ? starTestDot : starTest;
|
|
1880
|
+
}
|
|
1881
|
+
else if ((m = pattern.match(starDotExtRE))) {
|
|
1882
|
+
fastTest = (options.nocase
|
|
1883
|
+
? options.dot
|
|
1884
|
+
? starDotExtTestNocaseDot
|
|
1885
|
+
: starDotExtTestNocase
|
|
1886
|
+
: options.dot
|
|
1887
|
+
? starDotExtTestDot
|
|
1888
|
+
: starDotExtTest)(m[1]);
|
|
1889
|
+
}
|
|
1890
|
+
else if ((m = pattern.match(qmarksRE))) {
|
|
1891
|
+
fastTest = (options.nocase
|
|
1892
|
+
? options.dot
|
|
1893
|
+
? qmarksTestNocaseDot
|
|
1894
|
+
: qmarksTestNocase
|
|
1895
|
+
: options.dot
|
|
1896
|
+
? qmarksTestDot
|
|
1897
|
+
: qmarksTest)(m);
|
|
1898
|
+
}
|
|
1899
|
+
else if ((m = pattern.match(starDotStarRE))) {
|
|
1900
|
+
fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
|
|
1901
|
+
}
|
|
1902
|
+
else if ((m = pattern.match(dotStarRE))) {
|
|
1903
|
+
fastTest = dotStarTest;
|
|
1904
|
+
}
|
|
1905
|
+
const re = AST.fromGlob(pattern, this.options).toMMPattern();
|
|
1906
|
+
if (fastTest && typeof re === 'object') {
|
|
1907
|
+
// Avoids overriding in frozen environments
|
|
1908
|
+
Reflect.defineProperty(re, 'test', { value: fastTest });
|
|
1909
|
+
}
|
|
1910
|
+
return re;
|
|
1911
|
+
}
|
|
1912
|
+
makeRe() {
|
|
1913
|
+
if (this.regexp || this.regexp === false)
|
|
1914
|
+
return this.regexp;
|
|
1915
|
+
// at this point, this.set is a 2d array of partial
|
|
1916
|
+
// pattern strings, or "**".
|
|
1917
|
+
//
|
|
1918
|
+
// It's better to use .match(). This function shouldn't
|
|
1919
|
+
// be used, really, but it's pretty convenient sometimes,
|
|
1920
|
+
// when you just want to work with a regex.
|
|
1921
|
+
const set = this.set;
|
|
1922
|
+
if (!set.length) {
|
|
1923
|
+
this.regexp = false;
|
|
1924
|
+
return this.regexp;
|
|
1925
|
+
}
|
|
1926
|
+
const options = this.options;
|
|
1927
|
+
const twoStar = options.noglobstar
|
|
1928
|
+
? star
|
|
1929
|
+
: options.dot
|
|
1930
|
+
? twoStarDot
|
|
1931
|
+
: twoStarNoDot;
|
|
1932
|
+
const flags = new Set(options.nocase ? ['i'] : []);
|
|
1933
|
+
// regexpify non-globstar patterns
|
|
1934
|
+
// if ** is only item, then we just do one twoStar
|
|
1935
|
+
// if ** is first, and there are more, prepend (\/|twoStar\/)? to next
|
|
1936
|
+
// if ** is last, append (\/twoStar|) to previous
|
|
1937
|
+
// if ** is in the middle, append (\/|\/twoStar\/) to previous
|
|
1938
|
+
// then filter out GLOBSTAR symbols
|
|
1939
|
+
let re = set
|
|
1940
|
+
.map(pattern => {
|
|
1941
|
+
const pp = pattern.map(p => {
|
|
1942
|
+
if (p instanceof RegExp) {
|
|
1943
|
+
for (const f of p.flags.split(''))
|
|
1944
|
+
flags.add(f);
|
|
1945
|
+
}
|
|
1946
|
+
return typeof p === 'string'
|
|
1947
|
+
? regExpEscape(p)
|
|
1948
|
+
: p === GLOBSTAR
|
|
1949
|
+
? GLOBSTAR
|
|
1950
|
+
: p._src;
|
|
1951
|
+
});
|
|
1952
|
+
pp.forEach((p, i) => {
|
|
1953
|
+
const next = pp[i + 1];
|
|
1954
|
+
const prev = pp[i - 1];
|
|
1955
|
+
if (p !== GLOBSTAR || prev === GLOBSTAR) {
|
|
1956
|
+
return;
|
|
1957
|
+
}
|
|
1958
|
+
if (prev === undefined) {
|
|
1959
|
+
if (next !== undefined && next !== GLOBSTAR) {
|
|
1960
|
+
pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
|
|
1961
|
+
}
|
|
1962
|
+
else {
|
|
1963
|
+
pp[i] = twoStar;
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
else if (next === undefined) {
|
|
1967
|
+
pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
|
|
1968
|
+
}
|
|
1969
|
+
else if (next !== GLOBSTAR) {
|
|
1970
|
+
pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
|
|
1971
|
+
pp[i + 1] = GLOBSTAR;
|
|
1972
|
+
}
|
|
1973
|
+
});
|
|
1974
|
+
const filtered = pp.filter(p => p !== GLOBSTAR);
|
|
1975
|
+
// For partial matches, we need to make the pattern match
|
|
1976
|
+
// any prefix of the full path. We do this by generating
|
|
1977
|
+
// alternative patterns that match progressively longer prefixes.
|
|
1978
|
+
if (this.partial && filtered.length >= 1) {
|
|
1979
|
+
const prefixes = [];
|
|
1980
|
+
for (let i = 1; i <= filtered.length; i++) {
|
|
1981
|
+
prefixes.push(filtered.slice(0, i).join('/'));
|
|
1982
|
+
}
|
|
1983
|
+
return '(?:' + prefixes.join('|') + ')';
|
|
1984
|
+
}
|
|
1985
|
+
return filtered.join('/');
|
|
1986
|
+
})
|
|
1987
|
+
.join('|');
|
|
1988
|
+
// need to wrap in parens if we had more than one thing with |,
|
|
1989
|
+
// otherwise only the first will be anchored to ^ and the last to $
|
|
1990
|
+
const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
|
|
1991
|
+
// must match entire pattern
|
|
1992
|
+
// ending in a * or ** will make it less strict.
|
|
1993
|
+
re = '^' + open + re + close + '$';
|
|
1994
|
+
// In partial mode, '/' should always match as it's a valid prefix for any pattern
|
|
1995
|
+
if (this.partial) {
|
|
1996
|
+
re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
|
|
1997
|
+
}
|
|
1998
|
+
// can match anything, as long as it's not this.
|
|
1999
|
+
if (this.negate)
|
|
2000
|
+
re = '^(?!' + re + ').+$';
|
|
2001
|
+
try {
|
|
2002
|
+
this.regexp = new RegExp(re, [...flags].join(''));
|
|
2003
|
+
/* c8 ignore start */
|
|
2004
|
+
}
|
|
2005
|
+
catch (ex) {
|
|
2006
|
+
// should be impossible
|
|
2007
|
+
this.regexp = false;
|
|
2008
|
+
}
|
|
2009
|
+
/* c8 ignore stop */
|
|
2010
|
+
return this.regexp;
|
|
2011
|
+
}
|
|
2012
|
+
slashSplit(p) {
|
|
2013
|
+
// if p starts with // on windows, we preserve that
|
|
2014
|
+
// so that UNC paths aren't broken. Otherwise, any number of
|
|
2015
|
+
// / characters are coalesced into one, unless
|
|
2016
|
+
// preserveMultipleSlashes is set to true.
|
|
2017
|
+
if (this.preserveMultipleSlashes) {
|
|
2018
|
+
return p.split('/');
|
|
2019
|
+
}
|
|
2020
|
+
else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
|
|
2021
|
+
// add an extra '' for the one we lose
|
|
2022
|
+
return ['', ...p.split(/\/+/)];
|
|
2023
|
+
}
|
|
2024
|
+
else {
|
|
2025
|
+
return p.split(/\/+/);
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
match(f, partial = this.partial) {
|
|
2029
|
+
this.debug('match', f, this.pattern);
|
|
2030
|
+
// short-circuit in the case of busted things.
|
|
2031
|
+
// comments, etc.
|
|
2032
|
+
if (this.comment) {
|
|
2033
|
+
return false;
|
|
2034
|
+
}
|
|
2035
|
+
if (this.empty) {
|
|
2036
|
+
return f === '';
|
|
2037
|
+
}
|
|
2038
|
+
if (f === '/' && partial) {
|
|
2039
|
+
return true;
|
|
2040
|
+
}
|
|
2041
|
+
const options = this.options;
|
|
2042
|
+
// windows: need to use /, not \
|
|
2043
|
+
if (this.isWindows) {
|
|
2044
|
+
f = f.split('\\').join('/');
|
|
2045
|
+
}
|
|
2046
|
+
// treat the test path as a set of pathparts.
|
|
2047
|
+
const ff = this.slashSplit(f);
|
|
2048
|
+
this.debug(this.pattern, 'split', ff);
|
|
2049
|
+
// just ONE of the pattern sets in this.set needs to match
|
|
2050
|
+
// in order for it to be valid. If negating, then just one
|
|
2051
|
+
// match means that we have failed.
|
|
2052
|
+
// Either way, return on the first hit.
|
|
2053
|
+
const set = this.set;
|
|
2054
|
+
this.debug(this.pattern, 'set', set);
|
|
2055
|
+
// Find the basename of the path by looking for the last non-empty segment
|
|
2056
|
+
let filename = ff[ff.length - 1];
|
|
2057
|
+
if (!filename) {
|
|
2058
|
+
for (let i = ff.length - 2; !filename && i >= 0; i--) {
|
|
2059
|
+
filename = ff[i];
|
|
2060
|
+
}
|
|
2061
|
+
}
|
|
2062
|
+
for (let i = 0; i < set.length; i++) {
|
|
2063
|
+
const pattern = set[i];
|
|
2064
|
+
let file = ff;
|
|
2065
|
+
if (options.matchBase && pattern.length === 1) {
|
|
2066
|
+
file = [filename];
|
|
2067
|
+
}
|
|
2068
|
+
const hit = this.matchOne(file, pattern, partial);
|
|
2069
|
+
if (hit) {
|
|
2070
|
+
if (options.flipNegate) {
|
|
2071
|
+
return true;
|
|
2072
|
+
}
|
|
2073
|
+
return !this.negate;
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
// didn't get any hits. this is success if it's a negative
|
|
2077
|
+
// pattern, failure otherwise.
|
|
2078
|
+
if (options.flipNegate) {
|
|
2079
|
+
return false;
|
|
2080
|
+
}
|
|
2081
|
+
return this.negate;
|
|
2082
|
+
}
|
|
2083
|
+
static defaults(def) {
|
|
2084
|
+
return minimatch.defaults(def).Minimatch;
|
|
2085
|
+
}
|
|
2086
|
+
}
|
|
2087
|
+
/* c8 ignore stop */
|
|
2088
|
+
minimatch.AST = AST;
|
|
2089
|
+
minimatch.Minimatch = Minimatch;
|
|
2090
|
+
minimatch.escape = escape;
|
|
2091
|
+
minimatch.unescape = unescape;
|
|
2092
|
+
|
|
2093
|
+
function isDefined$1(value) {
|
|
2094
|
+
return value !== void 0 && value !== null;
|
|
2095
|
+
}
|
|
2096
|
+
function fmap(v, predicate) {
|
|
2097
|
+
if (!isDefined$1(v)) {
|
|
2098
|
+
return null;
|
|
2099
|
+
}
|
|
2100
|
+
return predicate(v);
|
|
2101
|
+
}
|
|
2102
|
+
function groupBy(objects, ...by) {
|
|
2103
|
+
if (by.length === 0) {
|
|
2104
|
+
return objects;
|
|
2105
|
+
}
|
|
2106
|
+
const [k0, ...kr] = by;
|
|
2107
|
+
const topLevelGroups = /* @__PURE__ */ new Map();
|
|
2108
|
+
for (const obj of objects) {
|
|
2109
|
+
const k = obj[k0];
|
|
2110
|
+
let arr = topLevelGroups.get(k);
|
|
2111
|
+
if (!arr) {
|
|
2112
|
+
arr = [];
|
|
2113
|
+
topLevelGroups.set(k, arr);
|
|
2114
|
+
}
|
|
2115
|
+
arr.push(obj);
|
|
2116
|
+
}
|
|
2117
|
+
return new Map(Array.from(topLevelGroups, ([k, v]) => [k, groupBy(v, ...kr)]));
|
|
2118
|
+
}
|
|
2119
|
+
function objectKeys(obj) {
|
|
2120
|
+
return Object.keys(obj);
|
|
2121
|
+
}
|
|
2122
|
+
function objectKeysNonEmpty(obj) {
|
|
2123
|
+
const keys = objectKeys(obj);
|
|
2124
|
+
if (keys.length === 0) {
|
|
2125
|
+
throw new Error("expected non-empty object");
|
|
2126
|
+
}
|
|
2127
|
+
return keys;
|
|
2128
|
+
}
|
|
2129
|
+
function assertNever(caseType) {
|
|
2130
|
+
throw new Error(`assertNever: ${caseType}`);
|
|
2131
|
+
}
|
|
2132
|
+
async function getOrSetFromMapWithEnabled(params) {
|
|
2133
|
+
return params.shouldCache ? getOrSetFromMap(params) : params.value();
|
|
2134
|
+
}
|
|
2135
|
+
async function getOrSetFromMap(params) {
|
|
2136
|
+
const { map, key, value } = params;
|
|
2137
|
+
if (map.has(key)) {
|
|
2138
|
+
return map.get(key);
|
|
2139
|
+
}
|
|
2140
|
+
const val = await value();
|
|
2141
|
+
map.set(key, val);
|
|
2142
|
+
return val;
|
|
2143
|
+
}
|
|
2144
|
+
function normalizeIndent(template, ...args) {
|
|
2145
|
+
const fullString = template.reduce((accumulator, str, i) => {
|
|
2146
|
+
return accumulator + str + (args[i] || "");
|
|
2147
|
+
}, "");
|
|
2148
|
+
const lines = fullString.split("\n");
|
|
2149
|
+
const nonEmptyLines = lines.filter((line) => line.trim() !== "");
|
|
2150
|
+
if (nonEmptyLines.length === 0) {
|
|
2151
|
+
return "";
|
|
2152
|
+
}
|
|
2153
|
+
const indent = nonEmptyLines[0].match(/^\s*/)?.[0];
|
|
2154
|
+
const normalized = nonEmptyLines.map((line) => line.replace(indent, "")).join("\n");
|
|
2155
|
+
return normalized;
|
|
2156
|
+
}
|
|
2157
|
+
|
|
2158
|
+
function toCase(str, caseType) {
|
|
2159
|
+
switch (caseType) {
|
|
2160
|
+
case void 0:
|
|
2161
|
+
return str;
|
|
2162
|
+
case "snake":
|
|
2163
|
+
return toSnakeCase(str);
|
|
2164
|
+
case "camel":
|
|
2165
|
+
return toCamelCase(str);
|
|
2166
|
+
case "pascal":
|
|
2167
|
+
return toPascalCase(str);
|
|
2168
|
+
case "screaming snake":
|
|
2169
|
+
return toScreamingSnakeCase(str);
|
|
2170
|
+
default:
|
|
2171
|
+
assertNever(caseType);
|
|
2172
|
+
}
|
|
2173
|
+
}
|
|
2174
|
+
function toCamelCase(str) {
|
|
2175
|
+
return str.replace(/([-_][a-z])/gi, ($1) => {
|
|
2176
|
+
return $1.toUpperCase().replace("-", "").replace("_", "");
|
|
2177
|
+
});
|
|
2178
|
+
}
|
|
2179
|
+
function toPascalCase(str) {
|
|
2180
|
+
return toCamelCase(str).replace(/^[a-z]/, (val) => val.toUpperCase());
|
|
2181
|
+
}
|
|
2182
|
+
function toSnakeCase(str) {
|
|
2183
|
+
return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();
|
|
2184
|
+
}
|
|
2185
|
+
function toScreamingSnakeCase(str) {
|
|
2186
|
+
return toSnakeCase(str).toUpperCase();
|
|
2187
|
+
}
|
|
2188
|
+
|
|
2189
|
+
class DatabaseInitializationError extends Error {
|
|
2190
|
+
_tag = "DatabaseInitializationError";
|
|
2191
|
+
constructor(message) {
|
|
2192
|
+
super(`Database initialization failed (${message})`);
|
|
2193
|
+
this.message = message;
|
|
2194
|
+
}
|
|
2195
|
+
static of(pgError) {
|
|
2196
|
+
return new DatabaseInitializationError(pgError);
|
|
2197
|
+
}
|
|
2198
|
+
static to(error) {
|
|
2199
|
+
if (error instanceof Error) {
|
|
2200
|
+
return DatabaseInitializationError.of(error.message);
|
|
2201
|
+
}
|
|
2202
|
+
return DatabaseInitializationError.of("Unknown error");
|
|
2203
|
+
}
|
|
2204
|
+
toJSON() {
|
|
2205
|
+
return {
|
|
2206
|
+
_tag: this._tag,
|
|
2207
|
+
message: this.message
|
|
2208
|
+
};
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
class InvalidMigrationsPathError extends Error {
|
|
2212
|
+
_tag = "InvalidMigrationsPathError";
|
|
2213
|
+
migrationsPath;
|
|
2214
|
+
constructor(migrationsPath, message) {
|
|
2215
|
+
super(`Failed to read migrations directory "${migrationsPath}" (${message})`);
|
|
2216
|
+
this.migrationsPath = migrationsPath;
|
|
2217
|
+
this.message = message;
|
|
2218
|
+
}
|
|
2219
|
+
static of(filePath, pgError) {
|
|
2220
|
+
return new InvalidMigrationsPathError(filePath, pgError);
|
|
2221
|
+
}
|
|
2222
|
+
static fromErrorC(migrationsPath) {
|
|
2223
|
+
return (error) => InvalidMigrationsPathError.of(migrationsPath, error.message);
|
|
2224
|
+
}
|
|
2225
|
+
toJSON() {
|
|
2226
|
+
return {
|
|
2227
|
+
_tag: this._tag,
|
|
2228
|
+
migrationsPath: this.migrationsPath,
|
|
2229
|
+
message: this.message
|
|
2230
|
+
};
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
class InvalidConfigError extends Error {
|
|
2234
|
+
_tag = "InvalidConfigError";
|
|
2235
|
+
constructor(message) {
|
|
2236
|
+
super(`Invalid configuration (${message})`);
|
|
2237
|
+
this.message = message;
|
|
2238
|
+
}
|
|
2239
|
+
static of(message) {
|
|
2240
|
+
return new InvalidConfigError(message);
|
|
2241
|
+
}
|
|
2242
|
+
toJSON() {
|
|
2243
|
+
return {
|
|
2244
|
+
_tag: this._tag,
|
|
2245
|
+
message: this.message
|
|
2246
|
+
};
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
class InvalidMigrationError extends Error {
|
|
2250
|
+
_tag = "InvalidMigrationError";
|
|
2251
|
+
filePath;
|
|
2252
|
+
constructor(filePath, message) {
|
|
2253
|
+
super(`Failed to run migration "${path__default.basename(filePath)}" (${message})`);
|
|
2254
|
+
this.filePath = filePath;
|
|
2255
|
+
this.message = message;
|
|
2256
|
+
}
|
|
2257
|
+
static of(filePath, pgError) {
|
|
2258
|
+
return new InvalidMigrationError(filePath, pgError);
|
|
2259
|
+
}
|
|
2260
|
+
static fromErrorC(migrationsPath) {
|
|
2261
|
+
return (error) => InvalidMigrationError.of(migrationsPath, error.message);
|
|
2262
|
+
}
|
|
2263
|
+
toJSON() {
|
|
2264
|
+
return {
|
|
2265
|
+
_tag: this._tag,
|
|
2266
|
+
filePath: this.filePath,
|
|
2267
|
+
message: this.message
|
|
2268
|
+
};
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
class InvalidQueryError extends Error {
|
|
2272
|
+
_tag = "InvalidQueryError";
|
|
2273
|
+
node;
|
|
2274
|
+
constructor(error, node) {
|
|
2275
|
+
super(error);
|
|
2276
|
+
this.node = node;
|
|
2277
|
+
}
|
|
2278
|
+
static of(error, node) {
|
|
2279
|
+
return new InvalidQueryError(error, node);
|
|
2280
|
+
}
|
|
2281
|
+
toJSON() {
|
|
2282
|
+
return {
|
|
2283
|
+
_tag: this._tag,
|
|
2284
|
+
message: this.message,
|
|
2285
|
+
node: this.node
|
|
2286
|
+
};
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
class InternalError extends Error {
|
|
2290
|
+
_tag = "InternalError";
|
|
2291
|
+
constructor(error) {
|
|
2292
|
+
super(`Internal error: ${error}`);
|
|
2293
|
+
}
|
|
2294
|
+
static of(error) {
|
|
2295
|
+
return new InternalError(error);
|
|
2296
|
+
}
|
|
2297
|
+
static to(error) {
|
|
2298
|
+
if (error instanceof AggregateError) {
|
|
2299
|
+
const e = InternalError.of(error.errors.map((e2) => e2.message).join(", "));
|
|
2300
|
+
e.stack = error.stack;
|
|
2301
|
+
return e;
|
|
2302
|
+
}
|
|
2303
|
+
if (error instanceof Error) {
|
|
2304
|
+
const e = InternalError.of(error.message);
|
|
2305
|
+
e.stack = error.stack;
|
|
2306
|
+
return e;
|
|
2307
|
+
}
|
|
2308
|
+
return InternalError.of(`Unknown (${error})`);
|
|
2309
|
+
}
|
|
2310
|
+
toJSON() {
|
|
2311
|
+
return {
|
|
2312
|
+
_tag: this._tag,
|
|
2313
|
+
stack: this.stack,
|
|
2314
|
+
message: this.message
|
|
2315
|
+
};
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
class DuplicateColumnsError extends Error {
|
|
2319
|
+
_tag = "DuplicateColumnsError";
|
|
2320
|
+
columns;
|
|
2321
|
+
queryText;
|
|
2322
|
+
position;
|
|
2323
|
+
sourcemaps;
|
|
2324
|
+
constructor(params) {
|
|
2325
|
+
super(`Duplicate columns: ${params.columns.join(", ")}`);
|
|
2326
|
+
this.columns = params.columns;
|
|
2327
|
+
this.queryText = params.queryText;
|
|
2328
|
+
this.position = params.position;
|
|
2329
|
+
this.sourcemaps = params.sourcemaps;
|
|
2330
|
+
}
|
|
2331
|
+
static of(params) {
|
|
2332
|
+
return new DuplicateColumnsError(params);
|
|
2333
|
+
}
|
|
2334
|
+
toJSON() {
|
|
2335
|
+
return {
|
|
2336
|
+
_tag: this._tag,
|
|
2337
|
+
message: this.message,
|
|
2338
|
+
columns: this.columns,
|
|
2339
|
+
queryText: this.queryText,
|
|
2340
|
+
position: this.position,
|
|
2341
|
+
sourcemaps: this.sourcemaps
|
|
2342
|
+
};
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
class PostgresError extends Error {
|
|
2346
|
+
_tag = "PostgresError";
|
|
2347
|
+
queryText;
|
|
2348
|
+
message;
|
|
2349
|
+
line;
|
|
2350
|
+
position;
|
|
2351
|
+
sourcemaps;
|
|
2352
|
+
constructor(params) {
|
|
2353
|
+
super(params.message);
|
|
2354
|
+
this.name = "PostgresError";
|
|
2355
|
+
this.queryText = params.queryText;
|
|
2356
|
+
this.message = params.message;
|
|
2357
|
+
this.line = params.line;
|
|
2358
|
+
this.position = Number(params.position);
|
|
2359
|
+
this.sourcemaps = params.sourcemaps;
|
|
2360
|
+
}
|
|
2361
|
+
static of(params) {
|
|
2362
|
+
return new PostgresError(params);
|
|
2363
|
+
}
|
|
2364
|
+
static to(query, error, sourcemaps) {
|
|
2365
|
+
if (isPostgresError(error)) {
|
|
2366
|
+
return PostgresError.of({
|
|
2367
|
+
queryText: query,
|
|
2368
|
+
message: error.message,
|
|
2369
|
+
line: error.line,
|
|
2370
|
+
position: error.position,
|
|
2371
|
+
sourcemaps
|
|
2372
|
+
});
|
|
2373
|
+
}
|
|
2374
|
+
return PostgresError.of({
|
|
2375
|
+
queryText: query,
|
|
2376
|
+
message: `${error}`,
|
|
2377
|
+
line: "1",
|
|
2378
|
+
position: isPgParserError(error) ? error.cursorPosition : 0,
|
|
2379
|
+
sourcemaps
|
|
2380
|
+
});
|
|
2381
|
+
}
|
|
2382
|
+
toJSON() {
|
|
2383
|
+
return {
|
|
2384
|
+
_tag: this._tag,
|
|
2385
|
+
queryText: this.queryText,
|
|
2386
|
+
message: this.message,
|
|
2387
|
+
line: this.line,
|
|
2388
|
+
position: this.position,
|
|
2389
|
+
sourcemaps: this.sourcemaps
|
|
2390
|
+
};
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
function isPostgresError(e) {
|
|
2394
|
+
if (e instanceof postgres__default.PostgresError) {
|
|
2395
|
+
return true;
|
|
2396
|
+
}
|
|
2397
|
+
if (e instanceof Error && e.name === "PostgresError") {
|
|
2398
|
+
return true;
|
|
2399
|
+
}
|
|
2400
|
+
return false;
|
|
2401
|
+
}
|
|
2402
|
+
function isPgParserError(error) {
|
|
2403
|
+
return error instanceof Error && "cursorPosition" in error;
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
const defaultTypeMapping = {
|
|
2407
|
+
// Integer types
|
|
2408
|
+
int2: "number",
|
|
2409
|
+
int4: "number",
|
|
2410
|
+
int8: "string",
|
|
2411
|
+
smallint: "number",
|
|
2412
|
+
int: "number",
|
|
2413
|
+
bigint: "string",
|
|
2414
|
+
// Precision types
|
|
2415
|
+
real: "number",
|
|
2416
|
+
float4: "number",
|
|
2417
|
+
float: "number",
|
|
2418
|
+
float8: "number",
|
|
2419
|
+
numeric: "string",
|
|
2420
|
+
decimal: "number",
|
|
2421
|
+
// Serial types
|
|
2422
|
+
smallserial: "number",
|
|
2423
|
+
serial: "number",
|
|
2424
|
+
bigserial: "string",
|
|
2425
|
+
// Common string types
|
|
2426
|
+
uuid: "string",
|
|
2427
|
+
text: "string",
|
|
2428
|
+
varchar: "string",
|
|
2429
|
+
char: "string",
|
|
2430
|
+
bpchar: "string",
|
|
2431
|
+
citext: "string",
|
|
2432
|
+
// Bool types
|
|
2433
|
+
bit: "boolean",
|
|
2434
|
+
bool: "boolean",
|
|
2435
|
+
boolean: "boolean",
|
|
2436
|
+
// Dates and times
|
|
2437
|
+
date: "Date",
|
|
2438
|
+
timestamp: "Date",
|
|
2439
|
+
timestamptz: "Date",
|
|
2440
|
+
time: "string",
|
|
2441
|
+
timetz: "string",
|
|
2442
|
+
interval: "string",
|
|
2443
|
+
// Network address types
|
|
2444
|
+
inet: "string",
|
|
2445
|
+
cidr: "string",
|
|
2446
|
+
macaddr: "string",
|
|
2447
|
+
macaddr8: "string",
|
|
2448
|
+
// Extra types
|
|
2449
|
+
money: "number",
|
|
2450
|
+
void: "void",
|
|
2451
|
+
// JSON types
|
|
2452
|
+
json: "any",
|
|
2453
|
+
jsonb: "any",
|
|
2454
|
+
// Bytes
|
|
2455
|
+
bytea: "any",
|
|
2456
|
+
// null
|
|
2457
|
+
null: "null"
|
|
2458
|
+
};
|
|
2459
|
+
const defaultTypesMap = new Map(Object.entries(defaultTypeMapping));
|
|
2460
|
+
|
|
2461
|
+
function doesMatchPattern(params) {
|
|
2462
|
+
const { pattern, text } = params;
|
|
2463
|
+
if (typeof pattern === "string") {
|
|
2464
|
+
return minimatch(text, pattern);
|
|
2465
|
+
}
|
|
2466
|
+
return new RegExp(`^${pattern.regex}$`).test(text);
|
|
2467
|
+
}
|
|
2468
|
+
|
|
2469
|
+
function isIdentifier(node) {
|
|
2470
|
+
return node?.type === utils.TSESTree.AST_NODE_TYPES.Identifier;
|
|
2471
|
+
}
|
|
2472
|
+
function isMemberExpression(node) {
|
|
2473
|
+
return node?.type === utils.TSESTree.AST_NODE_TYPES.MemberExpression;
|
|
2474
|
+
}
|
|
2475
|
+
function isOneOf(value, options) {
|
|
2476
|
+
return options.includes(value);
|
|
2477
|
+
}
|
|
2478
|
+
|
|
2479
|
+
function mapConnectionOptionsToString(connectionOptions) {
|
|
2480
|
+
return `postgres://${connectionOptions.user}:${connectionOptions.password}@${connectionOptions.host}:${connectionOptions.port}/${connectionOptions.database}`;
|
|
2481
|
+
}
|
|
2482
|
+
function parseConnection(databaseUrl) {
|
|
2483
|
+
const connection = pgConnectionString__default.parse(databaseUrl);
|
|
2484
|
+
if (connection.host === null) {
|
|
2485
|
+
throw new Error("Could not resolve database host");
|
|
2486
|
+
}
|
|
2487
|
+
if (!isDefined(connection.port)) {
|
|
2488
|
+
throw new Error("Could not resolve database port");
|
|
2489
|
+
}
|
|
2490
|
+
if (!isDefined(connection.user)) {
|
|
2491
|
+
throw new Error("Could not resolve database user");
|
|
2492
|
+
}
|
|
2493
|
+
if (!isDefined(connection.password)) {
|
|
2494
|
+
throw new Error("Could not resolve database password");
|
|
2495
|
+
}
|
|
2496
|
+
if (!isDefined(connection.database)) {
|
|
2497
|
+
throw new Error("Could not resolve database name");
|
|
2498
|
+
}
|
|
2499
|
+
return {
|
|
2500
|
+
host: connection.host,
|
|
2501
|
+
port: parseInt(connection.port, 10),
|
|
2502
|
+
user: connection.user,
|
|
2503
|
+
password: connection.password,
|
|
2504
|
+
database: connection.database
|
|
2505
|
+
};
|
|
2506
|
+
}
|
|
2507
|
+
function initDatabase(sql, database) {
|
|
2508
|
+
return function_js.pipe(
|
|
2509
|
+
TE__namespace.Do,
|
|
2510
|
+
TE__namespace.chain(() => dropDatabase(sql, database)),
|
|
2511
|
+
TE__namespace.altW(() => TE__namespace.right(void 0)),
|
|
2512
|
+
TE__namespace.chain(() => createDatabase(sql, database))
|
|
2513
|
+
);
|
|
2514
|
+
}
|
|
2515
|
+
function createDatabase(sql, database) {
|
|
2516
|
+
return TE__namespace.tryCatch(
|
|
2517
|
+
() => sql.unsafe(`CREATE DATABASE ${database}`),
|
|
2518
|
+
DatabaseInitializationError.to
|
|
2519
|
+
);
|
|
2520
|
+
}
|
|
2521
|
+
function dropDatabase(sql, database) {
|
|
2522
|
+
return TE__namespace.tryCatch(async () => {
|
|
2523
|
+
const [{ withForce }] = await sql.unsafe(`
|
|
2524
|
+
SELECT (string_to_array(version(), ' '))[2]::numeric >= 13 AS "withForce"
|
|
2525
|
+
`);
|
|
2526
|
+
return withForce ? sql.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`) : sql.unsafe(`DROP DATABASE IF EXISTS ${database}`);
|
|
2527
|
+
}, DatabaseInitializationError.to);
|
|
2528
|
+
}
|
|
2529
|
+
function isDefined(value) {
|
|
2530
|
+
return value !== null && value !== void 0;
|
|
2531
|
+
}
|
|
2532
|
+
|
|
2533
|
+
const DEFAULT_CONNECTION_URL = "postgres://postgres:postgres@localhost:5432/postgres";
|
|
2534
|
+
function isReplacerFromTo(replacer) {
|
|
2535
|
+
return Array.isArray(replacer) && replacer.length === 2;
|
|
2536
|
+
}
|
|
2537
|
+
function transformType(typeString, typeReplacer) {
|
|
2538
|
+
return isReplacerFromTo(typeReplacer) ? typeString.replace(new RegExp(typeReplacer[0], "g"), typeReplacer[1]) : typeReplacer.replace("{type}", typeString);
|
|
2539
|
+
}
|
|
2540
|
+
function transformTypes(typeString, transform) {
|
|
2541
|
+
if (transform === void 0 || typeString === null) {
|
|
2542
|
+
return typeString;
|
|
2543
|
+
}
|
|
2544
|
+
if (typeof transform === "string") {
|
|
2545
|
+
return transformType(typeString, transform);
|
|
2546
|
+
}
|
|
2547
|
+
let transformed = typeString;
|
|
2548
|
+
for (const replacer of transform) {
|
|
2549
|
+
transformed = transformType(transformed, replacer);
|
|
2550
|
+
}
|
|
2551
|
+
return transformed;
|
|
2552
|
+
}
|
|
2553
|
+
function getFinalResolvedTargetString(params) {
|
|
2554
|
+
const asString = getResolvedTargetString({
|
|
2555
|
+
target: params.target,
|
|
2556
|
+
nullAsOptional: params.nullAsOptional,
|
|
2557
|
+
nullAsUndefined: params.nullAsUndefined,
|
|
2558
|
+
inferLiterals: params.inferLiterals
|
|
2559
|
+
});
|
|
2560
|
+
return fmap(params.transform, (transform) => transformTypes(asString, transform)) ?? asString;
|
|
2561
|
+
}
|
|
2562
|
+
function reportInvalidQueryError(params) {
|
|
2563
|
+
const { context, error } = params;
|
|
2564
|
+
return context.report({
|
|
2565
|
+
messageId: "invalidQuery",
|
|
2566
|
+
node: error.node,
|
|
2567
|
+
data: { error: error.message }
|
|
2568
|
+
});
|
|
2569
|
+
}
|
|
2570
|
+
function reportBaseError(params) {
|
|
2571
|
+
const { context, tag, error } = params;
|
|
2572
|
+
return context.report({
|
|
2573
|
+
node: tag,
|
|
2574
|
+
messageId: "error",
|
|
2575
|
+
data: {
|
|
2576
|
+
error: [error.message, fmap(params.hint, (hint) => `Hint: ${hint}`)].filter(Boolean).join("\n")
|
|
2577
|
+
}
|
|
2578
|
+
});
|
|
2579
|
+
}
|
|
2580
|
+
function reportInvalidConfig(params) {
|
|
2581
|
+
const { tag, context, error } = params;
|
|
2582
|
+
return context.report({
|
|
2583
|
+
node: tag,
|
|
2584
|
+
messageId: "invalidQuery",
|
|
2585
|
+
loc: context.sourceCode.getLocFromIndex(tag.quasi.range[0]),
|
|
2586
|
+
data: {
|
|
2587
|
+
error: error.message
|
|
2588
|
+
}
|
|
2589
|
+
});
|
|
2590
|
+
}
|
|
2591
|
+
function reportDuplicateColumns(params) {
|
|
2592
|
+
const { tag, context, error } = params;
|
|
2593
|
+
const location = getQueryErrorPosition({
|
|
2594
|
+
tag,
|
|
2595
|
+
error,
|
|
2596
|
+
sourceCode: context.sourceCode
|
|
2597
|
+
});
|
|
2598
|
+
return context.report({
|
|
2599
|
+
node: tag,
|
|
2600
|
+
messageId: "invalidQuery",
|
|
2601
|
+
loc: location.sourceLocation,
|
|
2602
|
+
data: {
|
|
2603
|
+
error: error.message
|
|
2604
|
+
}
|
|
2605
|
+
});
|
|
2606
|
+
}
|
|
2607
|
+
function reportPostgresError(params) {
|
|
2608
|
+
const { context, tag, error } = params;
|
|
2609
|
+
const location = getQueryErrorPosition({
|
|
2610
|
+
tag,
|
|
2611
|
+
error,
|
|
2612
|
+
sourceCode: context.sourceCode
|
|
2613
|
+
});
|
|
2614
|
+
return context.report({
|
|
2615
|
+
node: tag,
|
|
2616
|
+
messageId: "invalidQuery",
|
|
2617
|
+
loc: location.sourceLocation,
|
|
2618
|
+
data: {
|
|
2619
|
+
error: error.message
|
|
2620
|
+
}
|
|
2621
|
+
});
|
|
2622
|
+
}
|
|
2623
|
+
function reportMissingTypeAnnotations(params) {
|
|
2624
|
+
const { context, tag, baseNode, actual } = params;
|
|
2625
|
+
return context.report({
|
|
2626
|
+
node: tag,
|
|
2627
|
+
messageId: "missingTypeAnnotations",
|
|
2628
|
+
loc: baseNode.loc,
|
|
2629
|
+
fix: (fixer) => fixer.insertTextAfterRange(baseNode.range, `<${actual}>`),
|
|
2630
|
+
data: {
|
|
2631
|
+
fix: actual
|
|
2632
|
+
}
|
|
2633
|
+
});
|
|
2634
|
+
}
|
|
2635
|
+
function reportIncorrectTypeAnnotations(params) {
|
|
2636
|
+
const { context, typeParameter } = params;
|
|
2637
|
+
const newValue = params.actual === null ? "" : `<${params.actual}>`;
|
|
2638
|
+
return context.report({
|
|
2639
|
+
node: typeParameter.params[0],
|
|
2640
|
+
messageId: "incorrectTypeAnnotations",
|
|
2641
|
+
fix: (fixer) => fixer.replaceText(typeParameter, newValue),
|
|
2642
|
+
data: {
|
|
2643
|
+
expected: params.expected,
|
|
2644
|
+
actual: params.actual ?? "No type annotation"
|
|
2645
|
+
}
|
|
2646
|
+
});
|
|
2647
|
+
}
|
|
2648
|
+
function reportInvalidTypeAnnotations(params) {
|
|
2649
|
+
const { context, typeParameter } = params;
|
|
2650
|
+
return context.report({
|
|
2651
|
+
node: typeParameter.params[0],
|
|
2652
|
+
messageId: "invalidTypeAnnotations"
|
|
2653
|
+
});
|
|
2654
|
+
}
|
|
2655
|
+
function getDatabaseName(params) {
|
|
2656
|
+
const { databaseName, projectDir, migrationsDir } = params;
|
|
2657
|
+
if (databaseName !== void 0) {
|
|
2658
|
+
return databaseName;
|
|
2659
|
+
}
|
|
2660
|
+
const projectDirName = projectDir.split("/").pop() ?? "";
|
|
2661
|
+
const projectUnderscoreName = projectDirName.replace(/[^A-z0-9]/g, "_").toLowerCase();
|
|
2662
|
+
const hash = crypto__default.createHash("sha1").update(migrationsDir).digest("hex").substring(0, 8);
|
|
2663
|
+
return `slonik_${projectUnderscoreName}_${hash}`;
|
|
2664
|
+
}
|
|
2665
|
+
function shouldLintFile(params) {
|
|
2666
|
+
const fileName = params.getFilename();
|
|
2667
|
+
for (const extension of ["ts", "tsx", "mts", "mtsx"]) {
|
|
2668
|
+
if (fileName.endsWith(`.${extension}`)) {
|
|
2669
|
+
return true;
|
|
2670
|
+
}
|
|
2671
|
+
}
|
|
2672
|
+
return false;
|
|
2673
|
+
}
|
|
2674
|
+
function isMigrationConnection(connection) {
|
|
2675
|
+
return "migrationsDir" in connection;
|
|
2676
|
+
}
|
|
2677
|
+
function isWatchMigrationsDirEnabled(connection) {
|
|
2678
|
+
return isMigrationConnection(connection) && (connection.watchMode ?? true) === true;
|
|
2679
|
+
}
|
|
2680
|
+
function getMigrationDatabaseMetadata(params) {
|
|
2681
|
+
const connectionOptions = {
|
|
2682
|
+
...parseConnection(params.connectionUrl),
|
|
2683
|
+
database: params.databaseName
|
|
2684
|
+
};
|
|
2685
|
+
const databaseUrl = mapConnectionOptionsToString(connectionOptions);
|
|
2686
|
+
return { databaseUrl, connectionOptions };
|
|
2687
|
+
}
|
|
2688
|
+
function getConnectionStrategyByRuleOptionConnection(params) {
|
|
2689
|
+
const { connection, projectDir } = params;
|
|
2690
|
+
if ("databaseUrl" in connection) {
|
|
2691
|
+
return { type: "databaseUrl", ...connection };
|
|
2692
|
+
}
|
|
2693
|
+
if ("migrationsDir" in connection) {
|
|
2694
|
+
return {
|
|
2695
|
+
type: "migrations",
|
|
2696
|
+
connectionUrl: DEFAULT_CONNECTION_URL,
|
|
2697
|
+
databaseName: getDatabaseName({
|
|
2698
|
+
databaseName: connection.databaseName,
|
|
2699
|
+
migrationsDir: connection.migrationsDir,
|
|
2700
|
+
projectDir
|
|
2701
|
+
}),
|
|
2702
|
+
watchMode: isWatchMigrationsDirEnabled(connection),
|
|
2703
|
+
...connection
|
|
2704
|
+
};
|
|
2705
|
+
}
|
|
2706
|
+
return tsPattern.match(connection).exhaustive();
|
|
2707
|
+
}
|
|
2708
|
+
function runMigrations(params) {
|
|
2709
|
+
const runSingleMigrationFileWithSql = (filePath) => {
|
|
2710
|
+
return runSingleMigrationFile(params.sql, filePath);
|
|
2711
|
+
};
|
|
2712
|
+
return function_js.pipe(
|
|
2713
|
+
TE__namespace.Do,
|
|
2714
|
+
TE__namespace.chain(() => getMigrationFiles(params.migrationsPath)),
|
|
2715
|
+
TE__namespace.chainW((files) => TE__namespace.sequenceSeqArray(files.map(runSingleMigrationFileWithSql)))
|
|
2716
|
+
);
|
|
2717
|
+
}
|
|
2718
|
+
function findDeepSqlFiles(migrationsPath) {
|
|
2719
|
+
const sqlFilePaths = [];
|
|
2720
|
+
function findDeepSqlFilesRecursively(dir) {
|
|
2721
|
+
const files = fs__default.readdirSync(dir);
|
|
2722
|
+
files.forEach((file) => {
|
|
2723
|
+
const filePath = path__default.join(dir, file);
|
|
2724
|
+
const isDirectory = fs__default.statSync(filePath).isDirectory();
|
|
2725
|
+
if (isDirectory) {
|
|
2726
|
+
findDeepSqlFilesRecursively(filePath);
|
|
2727
|
+
} else if (filePath.endsWith(".sql")) {
|
|
2728
|
+
sqlFilePaths.push(filePath);
|
|
2729
|
+
}
|
|
2730
|
+
});
|
|
2731
|
+
}
|
|
2732
|
+
findDeepSqlFilesRecursively(migrationsPath);
|
|
2733
|
+
return sqlFilePaths;
|
|
2734
|
+
}
|
|
2735
|
+
function getMigrationFiles(migrationsPath) {
|
|
2736
|
+
return function_js.pipe(
|
|
2737
|
+
E__namespace.tryCatch(() => findDeepSqlFiles(migrationsPath), E__namespace.toError),
|
|
2738
|
+
TE__namespace.fromEither,
|
|
2739
|
+
TE__namespace.mapLeft(InvalidMigrationsPathError.fromErrorC(migrationsPath))
|
|
2740
|
+
);
|
|
2741
|
+
}
|
|
2742
|
+
function runSingleMigrationFile(sql, filePath) {
|
|
2743
|
+
return function_js.pipe(
|
|
2744
|
+
TE__namespace.tryCatch(() => fs__default.promises.readFile(filePath).then((x) => x.toString()), E__namespace.toError),
|
|
2745
|
+
TE__namespace.chain((content) => TE__namespace.tryCatch(() => sql.unsafe(content), E__namespace.toError)),
|
|
2746
|
+
TE__namespace.mapLeft(InvalidMigrationError.fromErrorC(filePath))
|
|
2747
|
+
);
|
|
2748
|
+
}
|
|
2749
|
+
function shouldInferLiteral(base, inferLiterals) {
|
|
2750
|
+
if (base.kind !== "type") return true;
|
|
2751
|
+
if (inferLiterals === true) return true;
|
|
2752
|
+
if (Array.isArray(inferLiterals) && isOneOf(base.value, inferLiterals)) return true;
|
|
2753
|
+
return false;
|
|
2754
|
+
}
|
|
2755
|
+
function unique(array) {
|
|
2756
|
+
return Array.from(new Set(array));
|
|
2757
|
+
}
|
|
2758
|
+
function getResolvedTargetComparableString(params) {
|
|
2759
|
+
const { target, nullAsUndefined, nullAsOptional } = params;
|
|
2760
|
+
const nullType = nullAsUndefined ? "undefined" : "null";
|
|
2761
|
+
switch (target.kind) {
|
|
2762
|
+
case "literal": {
|
|
2763
|
+
const value = shouldInferLiteral(target.base, params.inferLiterals) ? target.value : getResolvedTargetComparableString({
|
|
2764
|
+
target: target.base,
|
|
2765
|
+
nullAsOptional: params.nullAsOptional,
|
|
2766
|
+
nullAsUndefined: params.nullAsUndefined,
|
|
2767
|
+
inferLiterals: params.inferLiterals
|
|
2768
|
+
});
|
|
2769
|
+
return value === "null" ? nullType : value;
|
|
2770
|
+
}
|
|
2771
|
+
case "type":
|
|
2772
|
+
return target.value === "null" ? nullType : target.value.replace(/"/g, "'");
|
|
2773
|
+
case "union":
|
|
2774
|
+
return unique(
|
|
2775
|
+
target.value.map((target2) => getResolvedTargetComparableString({ ...params, target: target2 })).sort()
|
|
2776
|
+
).join(" | ");
|
|
2777
|
+
case "array": {
|
|
2778
|
+
let arrayString = getResolvedTargetComparableString({ ...params, target: target.value });
|
|
2779
|
+
if (target.value.kind === "union" && arrayString.includes("|")) {
|
|
2780
|
+
arrayString = `(${arrayString})`;
|
|
2781
|
+
}
|
|
2782
|
+
return target.syntax === "type-reference" ? `Array<${arrayString}>` : `${arrayString}[]`;
|
|
2783
|
+
}
|
|
2784
|
+
case "object": {
|
|
2785
|
+
if (target.value.length === 0) {
|
|
2786
|
+
return `{ }`;
|
|
2787
|
+
}
|
|
2788
|
+
const entriesString = target.value.map(([key, target2]) => {
|
|
2789
|
+
const isNullable = isNullableResolvedTarget(target2);
|
|
2790
|
+
const keyString = isNullable && nullAsOptional ? `${key}?` : key;
|
|
2791
|
+
const valueString = getResolvedTargetComparableString({ ...params, target: target2 });
|
|
2792
|
+
return `${keyString}: ${valueString}`;
|
|
2793
|
+
}).sort().join(";");
|
|
2794
|
+
return `{ ${entriesString} }`;
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
function getResolvedTargetString(params) {
|
|
2799
|
+
const { target, nullAsUndefined, nullAsOptional } = params;
|
|
2800
|
+
const nullType = nullAsUndefined ? "undefined" : "null";
|
|
2801
|
+
switch (target.kind) {
|
|
2802
|
+
case "literal": {
|
|
2803
|
+
const value = shouldInferLiteral(target.base, params.inferLiterals) ? target.value : getResolvedTargetString({
|
|
2804
|
+
target: target.base,
|
|
2805
|
+
nullAsOptional: params.nullAsOptional,
|
|
2806
|
+
nullAsUndefined: params.nullAsUndefined,
|
|
2807
|
+
inferLiterals: params.inferLiterals
|
|
2808
|
+
});
|
|
2809
|
+
return value === "null" ? nullType : value;
|
|
2810
|
+
}
|
|
2811
|
+
case "type":
|
|
2812
|
+
return target.value === "null" ? nullType : target.value;
|
|
2813
|
+
case "union":
|
|
2814
|
+
return unique(
|
|
2815
|
+
target.value.map((target2) => getResolvedTargetString({ ...params, target: target2 }))
|
|
2816
|
+
).join(" | ");
|
|
2817
|
+
case "array": {
|
|
2818
|
+
const arrayString = getResolvedTargetString({ ...params, target: target.value });
|
|
2819
|
+
return target.value.kind === "union" && arrayString.includes("|") ? `(${arrayString})[]` : `${arrayString}[]`;
|
|
2820
|
+
}
|
|
2821
|
+
case "object": {
|
|
2822
|
+
if (target.value.length === 0) {
|
|
2823
|
+
return `{ }`;
|
|
2824
|
+
}
|
|
2825
|
+
const entriesString = target.value.map(([key, target2]) => {
|
|
2826
|
+
const isNullable = isNullableResolvedTarget(target2);
|
|
2827
|
+
const valueString = getResolvedTargetString({ ...params, target: target2 });
|
|
2828
|
+
let keyString = key;
|
|
2829
|
+
if (/[^A-z_]/.test(keyString)) {
|
|
2830
|
+
keyString = `'${keyString}'`;
|
|
2831
|
+
}
|
|
2832
|
+
keyString = isNullable && nullAsOptional ? `${keyString}?` : keyString;
|
|
2833
|
+
return `${keyString}: ${valueString}`;
|
|
2834
|
+
}).join("; ");
|
|
2835
|
+
return `{ ${entriesString} }`;
|
|
2836
|
+
}
|
|
2837
|
+
}
|
|
2838
|
+
}
|
|
2839
|
+
function isNullableResolvedTarget(target) {
|
|
2840
|
+
switch (target.kind) {
|
|
2841
|
+
case "type":
|
|
2842
|
+
case "literal":
|
|
2843
|
+
return ["any", "null"].includes(target.value) === false;
|
|
2844
|
+
case "union":
|
|
2845
|
+
return target.value.some((x) => x.kind === "type" && x.value === "null");
|
|
2846
|
+
case "array":
|
|
2847
|
+
case "object":
|
|
2848
|
+
return false;
|
|
2849
|
+
}
|
|
2850
|
+
}
|
|
2851
|
+
function getQueryErrorPosition(params) {
|
|
2852
|
+
const range = [params.error.position, params.error.position + 1];
|
|
2853
|
+
for (const entry of params.error.sourcemaps) {
|
|
2854
|
+
const generatedLength = Math.max(0, entry.generated.end - entry.generated.start);
|
|
2855
|
+
const originalLength = Math.max(0, entry.original.end - entry.original.start);
|
|
2856
|
+
const adjustment = originalLength - generatedLength;
|
|
2857
|
+
if (range[0] >= entry.generated.start && range[1] <= entry.generated.end) {
|
|
2858
|
+
range[0] = entry.original.start + entry.offset;
|
|
2859
|
+
range[1] = entry.original.start + entry.offset + 1;
|
|
2860
|
+
continue;
|
|
2861
|
+
}
|
|
2862
|
+
if (params.error.position >= entry.generated.start) {
|
|
2863
|
+
range[0] += adjustment;
|
|
2864
|
+
}
|
|
2865
|
+
if (params.error.position >= entry.generated.end) {
|
|
2866
|
+
range[1] += adjustment;
|
|
2867
|
+
}
|
|
2868
|
+
}
|
|
2869
|
+
const start = params.sourceCode.getLocFromIndex(params.tag.quasi.range[0] + range[0]);
|
|
2870
|
+
const startLineText = params.sourceCode.getLines()[start.line - 1];
|
|
2871
|
+
const remainingLineText = startLineText.substring(start.column);
|
|
2872
|
+
const remainingWordLength = (remainingLineText.match(/^[\w.{}'$"]+/)?.at(0)?.length ?? 1) - 1;
|
|
2873
|
+
const end = params.sourceCode.getLocFromIndex(params.tag.quasi.range[0] + range[1]);
|
|
2874
|
+
const sourceLocation = {
|
|
2875
|
+
start,
|
|
2876
|
+
end: {
|
|
2877
|
+
line: end.line,
|
|
2878
|
+
column: end.column + remainingWordLength
|
|
2879
|
+
}
|
|
2880
|
+
};
|
|
2881
|
+
return {
|
|
2882
|
+
range,
|
|
2883
|
+
sourceLocation,
|
|
2884
|
+
remainingLineText,
|
|
2885
|
+
remainingWordLength
|
|
2886
|
+
};
|
|
2887
|
+
}
|
|
2888
|
+
|
|
2889
|
+
exports.DEFAULT_CONNECTION_URL = DEFAULT_CONNECTION_URL;
|
|
2890
|
+
exports.DuplicateColumnsError = DuplicateColumnsError;
|
|
2891
|
+
exports.InternalError = InternalError;
|
|
2892
|
+
exports.InvalidConfigError = InvalidConfigError;
|
|
2893
|
+
exports.InvalidQueryError = InvalidQueryError;
|
|
2894
|
+
exports.PostgresError = PostgresError;
|
|
2895
|
+
exports.assertNever = assertNever;
|
|
2896
|
+
exports.defaultTypeMapping = defaultTypeMapping;
|
|
2897
|
+
exports.defaultTypesMap = defaultTypesMap;
|
|
2898
|
+
exports.doesMatchPattern = doesMatchPattern;
|
|
2899
|
+
exports.fmap = fmap;
|
|
2900
|
+
exports.getConnectionStrategyByRuleOptionConnection = getConnectionStrategyByRuleOptionConnection;
|
|
2901
|
+
exports.getDatabaseName = getDatabaseName;
|
|
2902
|
+
exports.getFinalResolvedTargetString = getFinalResolvedTargetString;
|
|
2903
|
+
exports.getMigrationDatabaseMetadata = getMigrationDatabaseMetadata;
|
|
2904
|
+
exports.getOrSetFromMapWithEnabled = getOrSetFromMapWithEnabled;
|
|
2905
|
+
exports.getResolvedTargetComparableString = getResolvedTargetComparableString;
|
|
2906
|
+
exports.getResolvedTargetString = getResolvedTargetString;
|
|
2907
|
+
exports.groupBy = groupBy;
|
|
2908
|
+
exports.initDatabase = initDatabase;
|
|
2909
|
+
exports.isIdentifier = isIdentifier;
|
|
2910
|
+
exports.isMemberExpression = isMemberExpression;
|
|
2911
|
+
exports.isPostgresError = isPostgresError;
|
|
2912
|
+
exports.isWatchMigrationsDirEnabled = isWatchMigrationsDirEnabled;
|
|
2913
|
+
exports.mapConnectionOptionsToString = mapConnectionOptionsToString;
|
|
2914
|
+
exports.normalizeIndent = normalizeIndent;
|
|
2915
|
+
exports.objectKeysNonEmpty = objectKeysNonEmpty;
|
|
2916
|
+
exports.parseConnection = parseConnection;
|
|
2917
|
+
exports.reportBaseError = reportBaseError;
|
|
2918
|
+
exports.reportDuplicateColumns = reportDuplicateColumns;
|
|
2919
|
+
exports.reportIncorrectTypeAnnotations = reportIncorrectTypeAnnotations;
|
|
2920
|
+
exports.reportInvalidConfig = reportInvalidConfig;
|
|
2921
|
+
exports.reportInvalidQueryError = reportInvalidQueryError;
|
|
2922
|
+
exports.reportInvalidTypeAnnotations = reportInvalidTypeAnnotations;
|
|
2923
|
+
exports.reportMissingTypeAnnotations = reportMissingTypeAnnotations;
|
|
2924
|
+
exports.reportPostgresError = reportPostgresError;
|
|
2925
|
+
exports.runMigrations = runMigrations;
|
|
2926
|
+
exports.shouldLintFile = shouldLintFile;
|
|
2927
|
+
exports.toCase = toCase;
|
|
2928
|
+
exports.transformTypes = transformTypes;
|
|
2929
|
+
//# sourceMappingURL=eslint-plugin-slonik.rlOTrCdf.cjs.map
|