index.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.toMatcher = exports.toRegex = void 0;
  4. const escapeRe = (ch) => (/[.^$+{}()|\\]/.test(ch) ? `\\${ch}` : ch);
  5. /**
  6. * Parse an extended glob pattern like ?(a|b|c)
  7. * Returns the regex string equivalent and the new index position
  8. */
  9. const parseExtGlob = (pattern, startIdx, prefix, options) => {
  10. let i = startIdx; // startIdx should be pointing at the character after '('
  11. const parts = [];
  12. let cur = '';
  13. let depth = 1; // Track parenthesis depth for nested patterns
  14. while (i < pattern.length && depth > 0) {
  15. const ch = pattern[i];
  16. if (ch === '(') {
  17. depth++;
  18. cur += ch;
  19. i++;
  20. }
  21. else if (ch === ')') {
  22. depth--;
  23. if (depth === 0) {
  24. // Found the closing parenthesis
  25. parts.push(cur);
  26. i++; // consume ')'
  27. break;
  28. }
  29. else {
  30. cur += ch;
  31. i++;
  32. }
  33. }
  34. else if (ch === '|' && depth === 1) {
  35. // Pipe separator at top level of this extglob
  36. parts.push(cur);
  37. cur = '';
  38. i++;
  39. }
  40. else {
  41. cur += ch;
  42. i++;
  43. }
  44. }
  45. if (depth !== 0)
  46. return; // Unclosed parenthesis
  47. let alternatives = '';
  48. const length = parts.length;
  49. for (let j = 0; j < length; j++)
  50. alternatives += (alternatives ? '|' : '') + (0, exports.toRegex)(parts[j], options).source.replace(/^\^/, '').replace(/\$$/, '');
  51. switch (prefix) {
  52. case '?': // zero or one
  53. return [`(?:${alternatives})?`, i];
  54. case '*': // zero or more
  55. return [`(?:${alternatives})*`, i];
  56. case '+': // one or more
  57. return [`(?:${alternatives})+`, i];
  58. case '@': // exactly one
  59. return [`(?:${alternatives})`, i];
  60. case '!': // none of (negative match)
  61. // For negation, we need to match anything that doesn't match the pattern
  62. // Use negative lookahead without consuming characters after
  63. return [`(?!${alternatives})[^/]*`, i];
  64. }
  65. return;
  66. };
  67. /**
  68. * Convert a glob pattern to a regular expression
  69. *
  70. * Supports:
  71. * - `/` to separate path segments
  72. * - `*` to match zero or more characters in a path segment
  73. * - `?` to match one character in a path segment
  74. * - `**` to match any number of path segments, including none
  75. * - `{}` to group conditions (e.g. `{html,txt}`)
  76. * - `[abc]`, `[a-z]`, `[!a-z]`, `[!abc]` character classes
  77. * - Extended globbing (when `extglob: true` option is set):
  78. * - `?(pattern-list)` zero or one occurrence
  79. * - `*(pattern-list)` zero or more occurrences
  80. * - `+(pattern-list)` one or more occurrences
  81. * - `@(pattern-list)` exactly one of the patterns
  82. * - `!(pattern-list)` anything except the patterns
  83. */
  84. const toRegex = (pattern, options) => {
  85. let regexStr = '';
  86. let i = 0;
  87. // Helper to parse a brace group like {a,b,c}. No nesting support.
  88. const parseBraceGroup = () => {
  89. // Assume current char is '{'
  90. i++; // skip '{'
  91. const parts = [];
  92. let cur = '';
  93. let closed = false;
  94. while (i < pattern.length) {
  95. const ch = pattern[i];
  96. if (ch === '}') {
  97. parts.push(cur);
  98. i++; // consume '}'
  99. closed = true;
  100. break;
  101. }
  102. if (ch === ',') {
  103. parts.push(cur);
  104. cur = '';
  105. i++;
  106. continue;
  107. }
  108. cur += ch;
  109. i++;
  110. }
  111. if (!closed) {
  112. // treat as literal '{...'
  113. return '\\{' + escapeRe(cur);
  114. }
  115. // Convert each part recursively to support globs inside braces
  116. const alt = parts.map((p) => (0, exports.toRegex)(p, options).source.replace(/^\^/, '').replace(/\$$/, '')).join('|');
  117. return `(?:${alt})`;
  118. };
  119. const extglob = !!options?.extglob;
  120. while (i < pattern.length) {
  121. const char = pattern[i];
  122. // Check for extended glob patterns when extglob is enabled
  123. if (extglob && pattern[i + 1] === '(') {
  124. if (char === '?' || char === '*' || char === '+' || char === '@' || char === '!') {
  125. const result = parseExtGlob(pattern, i + 2, char, options);
  126. if (result) {
  127. regexStr += result[0];
  128. i = result[1];
  129. continue;
  130. }
  131. // If parse failed, fall through to normal handling
  132. }
  133. }
  134. switch (char) {
  135. case '*': {
  136. // Check for double star **
  137. if (pattern[i + 1] === '*') {
  138. // Collapse consecutive * beyond two (e.g., *** -> **)
  139. let j = i + 2;
  140. while (pattern[j] === '*')
  141. j++;
  142. // If followed by a slash, make it optional to allow zero segments
  143. if (pattern[j] === '/') {
  144. regexStr += '(?:.*/)?';
  145. i = j + 1; // consume **/
  146. }
  147. else {
  148. regexStr += '.*';
  149. i = j; // consume **
  150. }
  151. }
  152. else {
  153. regexStr += '[^/]*';
  154. i++;
  155. }
  156. break;
  157. }
  158. case '?':
  159. regexStr += '[^/]';
  160. i++;
  161. break;
  162. case '[': {
  163. // Copy character class as-is with support for leading '!'
  164. let cls = '[';
  165. i++;
  166. if (i < pattern.length && pattern[i] === '!') {
  167. cls += '^';
  168. i++;
  169. }
  170. // if first after [ or [^ is ']' include it literally
  171. if (i < pattern.length && pattern[i] === ']') {
  172. cls += ']';
  173. i++;
  174. }
  175. while (i < pattern.length && pattern[i] !== ']') {
  176. const ch = pattern[i];
  177. // Escape backslash inside class
  178. cls += ch === '\\' ? '\\\\' : ch;
  179. i++;
  180. }
  181. if (i < pattern.length && pattern[i] === ']') {
  182. cls += ']';
  183. i++;
  184. }
  185. else {
  186. // Unclosed class -> treat '[' literally
  187. regexStr += '\\[';
  188. continue;
  189. }
  190. regexStr += cls;
  191. break;
  192. }
  193. case '{': {
  194. regexStr += parseBraceGroup();
  195. break;
  196. }
  197. case '/':
  198. regexStr += '/';
  199. i++;
  200. break;
  201. case '.':
  202. case '^':
  203. case '$':
  204. case '+':
  205. case '(':
  206. case ')':
  207. case '|':
  208. case '\\':
  209. regexStr += `\\${char}`;
  210. i++;
  211. break;
  212. default:
  213. regexStr += char;
  214. i++;
  215. break;
  216. }
  217. }
  218. const flags = options?.nocase ? 'i' : '';
  219. return new RegExp('^' + regexStr + '$', flags);
  220. };
  221. exports.toRegex = toRegex;
  222. const isRegExp = /^\/(.{1,4096})\/([gimsuy]{0,6})$/;
  223. const toMatcher = (pattern, options) => {
  224. const regexes = [];
  225. const patterns = Array.isArray(pattern) ? pattern : [pattern];
  226. for (const pat of patterns) {
  227. if (typeof pat === 'string') {
  228. const match = isRegExp.exec(pat);
  229. if (match) {
  230. const [, expr, flags] = match;
  231. regexes.push(new RegExp(expr, flags));
  232. }
  233. else {
  234. regexes.push((0, exports.toRegex)(pat, options));
  235. }
  236. }
  237. else {
  238. regexes.push(pat);
  239. }
  240. }
  241. return regexes.length
  242. ? new Function('p', 'return ' + regexes.map((r) => r + '.test(p)').join('||'))
  243. : () => false;
  244. };
  245. exports.toMatcher = toMatcher;