fluxion-ts 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var fs = require('node:fs');
4
- var path = require('node:path');
4
+ var path$1 = require('node:path');
5
5
  var cluster = require('node:cluster');
6
6
  var os = require('node:os');
7
7
  var http = require('node:http');
@@ -672,7 +672,7 @@ function readCertificateContent(content, moduleDir) {
672
672
  // Check if it looks like a file path (not a PEM certificate)
673
673
  // PEM certificates start with "-----BEGIN"
674
674
  if (!content.startsWith('-----BEGIN')) {
675
- const filePath = path.isAbsolute(content) ? content : path.join(moduleDir, content);
675
+ const filePath = path$1.isAbsolute(content) ? content : path$1.join(moduleDir, content);
676
676
  if (fs.existsSync(filePath)) {
677
677
  return fs.readFileSync(filePath);
678
678
  }
@@ -710,7 +710,20 @@ function normalizeHttpsOptions(https, moduleDir) {
710
710
  */
711
711
  function normalizeOptions(options) {
712
712
  expect.isObject(options, 'FluxionOptions must be an object');
713
- let { dir, host, port, metaPort, injections = [], moduleDir = process.cwd(), workerOptions = {}, maxRequestBytes = 8_000_000, reloadDelay = 300, apiExts = ['.ts'], routerExclude = [], https, } = options;
713
+ let { dir, host, port, metaPort, injections = [], moduleDir = process.cwd(), workerOptions = {}, maxRequestBytes = 8_000_000, reloadDelay = 300, include = ['**/*'], apiInclude = ['**/*.ts'], exclude = [
714
+ '**/node_modules/**',
715
+ '**/.git/**',
716
+ '**/dist/**',
717
+ '**/build/**',
718
+ '**/.vscode/**',
719
+ '**/.idea/**',
720
+ '**/*.log',
721
+ '**/.DS_Store',
722
+ '**/coverage/**',
723
+ '**/.nyc_output/**',
724
+ '**/*.tmp',
725
+ '**/*.temp',
726
+ ], https, } = options;
714
727
  const logger = options.logger ?? 'one-line';
715
728
  expectLoggerOption(logger);
716
729
  expect.isString(dir, 'FluxionOptions.dir must be a string');
@@ -749,8 +762,9 @@ function normalizeOptions(options) {
749
762
  workerOptions: resolveWorkerOptions(workerOptions),
750
763
  maxRequestBytes,
751
764
  logger,
752
- apiExts,
753
- routerExclude,
765
+ include,
766
+ apiInclude,
767
+ exclude,
754
768
  https: normalizeHttpsOptions(https, moduleDir),
755
769
  };
756
770
  }
@@ -1442,12 +1456,14 @@ class FluxionWatcher {
1442
1456
  * Recursively register all files in the options directory.
1443
1457
  */
1444
1458
  init() {
1445
- const dirPath = path.join(process.cwd(), this.cx.options.dir);
1459
+ const dirPath = path$1.isAbsolute(this.cx.options.dir)
1460
+ ? this.cx.options.dir
1461
+ : path$1.join(process.cwd(), this.cx.options.dir);
1446
1462
  const registerRecursive = (dir, relativePath) => {
1447
1463
  const entries = fs.readdirSync(dir, { withFileTypes: true });
1448
1464
  for (const entry of entries) {
1449
- const entryPath = path.join(dir, entry.name);
1450
- const entryRelativePath = path.join(relativePath, entry.name);
1465
+ const entryPath = path$1.join(dir, entry.name);
1466
+ const entryRelativePath = path$1.join(relativePath, entry.name);
1451
1467
  if (entry.isDirectory()) {
1452
1468
  registerRecursive(entryPath, entryRelativePath);
1453
1469
  }
@@ -1522,6 +1538,2415 @@ class FluxionWatcher {
1522
1538
  }
1523
1539
  }
1524
1540
 
1541
+ const balanced = (a, b, str) => {
1542
+ const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
1543
+ const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
1544
+ const r = ma !== null && mb != null && range(ma, mb, str);
1545
+ return (r && {
1546
+ start: r[0],
1547
+ end: r[1],
1548
+ pre: str.slice(0, r[0]),
1549
+ body: str.slice(r[0] + ma.length, r[1]),
1550
+ post: str.slice(r[1] + mb.length),
1551
+ });
1552
+ };
1553
+ const maybeMatch = (reg, str) => {
1554
+ const m = str.match(reg);
1555
+ return m ? m[0] : null;
1556
+ };
1557
+ const range = (a, b, str) => {
1558
+ let begs, beg, left, right = undefined, result;
1559
+ let ai = str.indexOf(a);
1560
+ let bi = str.indexOf(b, ai + 1);
1561
+ let i = ai;
1562
+ if (ai >= 0 && bi > 0) {
1563
+ if (a === b) {
1564
+ return [ai, bi];
1565
+ }
1566
+ begs = [];
1567
+ left = str.length;
1568
+ while (i >= 0 && !result) {
1569
+ if (i === ai) {
1570
+ begs.push(i);
1571
+ ai = str.indexOf(a, i + 1);
1572
+ }
1573
+ else if (begs.length === 1) {
1574
+ const r = begs.pop();
1575
+ if (r !== undefined)
1576
+ result = [r, bi];
1577
+ }
1578
+ else {
1579
+ beg = begs.pop();
1580
+ if (beg !== undefined && beg < left) {
1581
+ left = beg;
1582
+ right = bi;
1583
+ }
1584
+ bi = str.indexOf(b, i + 1);
1585
+ }
1586
+ i = ai < bi && ai >= 0 ? ai : bi;
1587
+ }
1588
+ if (begs.length && right !== undefined) {
1589
+ result = [left, right];
1590
+ }
1591
+ }
1592
+ return result;
1593
+ };
1594
+
1595
+ const escSlash = '\0SLASH' + Math.random() + '\0';
1596
+ const escOpen = '\0OPEN' + Math.random() + '\0';
1597
+ const escClose = '\0CLOSE' + Math.random() + '\0';
1598
+ const escComma = '\0COMMA' + Math.random() + '\0';
1599
+ const escPeriod = '\0PERIOD' + Math.random() + '\0';
1600
+ const escSlashPattern = new RegExp(escSlash, 'g');
1601
+ const escOpenPattern = new RegExp(escOpen, 'g');
1602
+ const escClosePattern = new RegExp(escClose, 'g');
1603
+ const escCommaPattern = new RegExp(escComma, 'g');
1604
+ const escPeriodPattern = new RegExp(escPeriod, 'g');
1605
+ const slashPattern = /\\\\/g;
1606
+ const openPattern = /\\{/g;
1607
+ const closePattern = /\\}/g;
1608
+ const commaPattern = /\\,/g;
1609
+ const periodPattern = /\\\./g;
1610
+ const EXPANSION_MAX = 100_000;
1611
+ function numeric(str) {
1612
+ return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
1613
+ }
1614
+ function escapeBraces(str) {
1615
+ return str
1616
+ .replace(slashPattern, escSlash)
1617
+ .replace(openPattern, escOpen)
1618
+ .replace(closePattern, escClose)
1619
+ .replace(commaPattern, escComma)
1620
+ .replace(periodPattern, escPeriod);
1621
+ }
1622
+ function unescapeBraces(str) {
1623
+ return str
1624
+ .replace(escSlashPattern, '\\')
1625
+ .replace(escOpenPattern, '{')
1626
+ .replace(escClosePattern, '}')
1627
+ .replace(escCommaPattern, ',')
1628
+ .replace(escPeriodPattern, '.');
1629
+ }
1630
+ /**
1631
+ * Basically just str.split(","), but handling cases
1632
+ * where we have nested braced sections, which should be
1633
+ * treated as individual members, like {a,{b,c},d}
1634
+ */
1635
+ function parseCommaParts(str) {
1636
+ if (!str) {
1637
+ return [''];
1638
+ }
1639
+ const parts = [];
1640
+ const m = balanced('{', '}', str);
1641
+ if (!m) {
1642
+ return str.split(',');
1643
+ }
1644
+ const { pre, body, post } = m;
1645
+ const p = pre.split(',');
1646
+ p[p.length - 1] += '{' + body + '}';
1647
+ const postParts = parseCommaParts(post);
1648
+ if (post.length) {
1649
+ p[p.length - 1] += postParts.shift();
1650
+ p.push.apply(p, postParts);
1651
+ }
1652
+ parts.push.apply(parts, p);
1653
+ return parts;
1654
+ }
1655
+ function expand(str, options = {}) {
1656
+ if (!str) {
1657
+ return [];
1658
+ }
1659
+ const { max = EXPANSION_MAX } = options;
1660
+ // I don't know why Bash 4.3 does this, but it does.
1661
+ // Anything starting with {} will have the first two bytes preserved
1662
+ // but *only* at the top level, so {},a}b will not expand to anything,
1663
+ // but a{},b}c will be expanded to [a}c,abc].
1664
+ // One could argue that this is a bug in Bash, but since the goal of
1665
+ // this module is to match Bash's rules, we escape a leading {}
1666
+ if (str.slice(0, 2) === '{}') {
1667
+ str = '\\{\\}' + str.slice(2);
1668
+ }
1669
+ return expand_(escapeBraces(str), max, true).map(unescapeBraces);
1670
+ }
1671
+ function embrace(str) {
1672
+ return '{' + str + '}';
1673
+ }
1674
+ function isPadded(el) {
1675
+ return /^-?0\d/.test(el);
1676
+ }
1677
+ function lte(i, y) {
1678
+ return i <= y;
1679
+ }
1680
+ function gte(i, y) {
1681
+ return i >= y;
1682
+ }
1683
+ function expand_(str, max, isTop) {
1684
+ /** @type {string[]} */
1685
+ const expansions = [];
1686
+ const m = balanced('{', '}', str);
1687
+ if (!m)
1688
+ return [str];
1689
+ // no need to expand pre, since it is guaranteed to be free of brace-sets
1690
+ const pre = m.pre;
1691
+ const post = m.post.length ? expand_(m.post, max, false) : [''];
1692
+ if (/\$$/.test(m.pre)) {
1693
+ for (let k = 0; k < post.length && k < max; k++) {
1694
+ const expansion = pre + '{' + m.body + '}' + post[k];
1695
+ expansions.push(expansion);
1696
+ }
1697
+ }
1698
+ else {
1699
+ const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
1700
+ const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
1701
+ const isSequence = isNumericSequence || isAlphaSequence;
1702
+ const isOptions = m.body.indexOf(',') >= 0;
1703
+ if (!isSequence && !isOptions) {
1704
+ // {a},b}
1705
+ if (m.post.match(/,(?!,).*\}/)) {
1706
+ str = m.pre + '{' + m.body + escClose + m.post;
1707
+ return expand_(str, max, true);
1708
+ }
1709
+ return [str];
1710
+ }
1711
+ let n;
1712
+ if (isSequence) {
1713
+ n = m.body.split(/\.\./);
1714
+ }
1715
+ else {
1716
+ n = parseCommaParts(m.body);
1717
+ if (n.length === 1 && n[0] !== undefined) {
1718
+ // x{{a,b}}y ==> x{a}y x{b}y
1719
+ n = expand_(n[0], max, false).map(embrace);
1720
+ //XXX is this necessary? Can't seem to hit it in tests.
1721
+ /* c8 ignore start */
1722
+ if (n.length === 1) {
1723
+ return post.map(p => m.pre + n[0] + p);
1724
+ }
1725
+ /* c8 ignore stop */
1726
+ }
1727
+ }
1728
+ // at this point, n is the parts, and we know it's not a comma set
1729
+ // with a single entry.
1730
+ let N;
1731
+ if (isSequence && n[0] !== undefined && n[1] !== undefined) {
1732
+ const x = numeric(n[0]);
1733
+ const y = numeric(n[1]);
1734
+ const width = Math.max(n[0].length, n[1].length);
1735
+ let incr = n.length === 3 && n[2] !== undefined ?
1736
+ Math.max(Math.abs(numeric(n[2])), 1)
1737
+ : 1;
1738
+ let test = lte;
1739
+ const reverse = y < x;
1740
+ if (reverse) {
1741
+ incr *= -1;
1742
+ test = gte;
1743
+ }
1744
+ const pad = n.some(isPadded);
1745
+ N = [];
1746
+ for (let i = x; test(i, y) && N.length < max; i += incr) {
1747
+ let c;
1748
+ if (isAlphaSequence) {
1749
+ c = String.fromCharCode(i);
1750
+ if (c === '\\') {
1751
+ c = '';
1752
+ }
1753
+ }
1754
+ else {
1755
+ c = String(i);
1756
+ if (pad) {
1757
+ const need = width - c.length;
1758
+ if (need > 0) {
1759
+ const z = new Array(need + 1).join('0');
1760
+ if (i < 0) {
1761
+ c = '-' + z + c.slice(1);
1762
+ }
1763
+ else {
1764
+ c = z + c;
1765
+ }
1766
+ }
1767
+ }
1768
+ }
1769
+ N.push(c);
1770
+ }
1771
+ }
1772
+ else {
1773
+ N = [];
1774
+ for (let j = 0; j < n.length; j++) {
1775
+ N.push.apply(N, expand_(n[j], max, false));
1776
+ }
1777
+ }
1778
+ for (let j = 0; j < N.length; j++) {
1779
+ for (let k = 0; k < post.length && expansions.length < max; k++) {
1780
+ const expansion = pre + N[j] + post[k];
1781
+ if (!isTop || isSequence || expansion) {
1782
+ expansions.push(expansion);
1783
+ }
1784
+ }
1785
+ }
1786
+ }
1787
+ return expansions;
1788
+ }
1789
+
1790
+ const MAX_PATTERN_LENGTH = 1024 * 64;
1791
+ const assertValidPattern = (pattern) => {
1792
+ if (typeof pattern !== 'string') {
1793
+ throw new TypeError('invalid pattern');
1794
+ }
1795
+ if (pattern.length > MAX_PATTERN_LENGTH) {
1796
+ throw new TypeError('pattern is too long');
1797
+ }
1798
+ };
1799
+
1800
+ // translate the various posix character classes into unicode properties
1801
+ // this works across all unicode locales
1802
+ // { <posix class>: [<translation>, /u flag required, negated]
1803
+ const posixClasses = {
1804
+ '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
1805
+ '[:alpha:]': ['\\p{L}\\p{Nl}', true],
1806
+ '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
1807
+ '[:blank:]': ['\\p{Zs}\\t', true],
1808
+ '[:cntrl:]': ['\\p{Cc}', true],
1809
+ '[:digit:]': ['\\p{Nd}', true],
1810
+ '[:graph:]': ['\\p{Z}\\p{C}', true, true],
1811
+ '[:lower:]': ['\\p{Ll}', true],
1812
+ '[:print:]': ['\\p{C}', true],
1813
+ '[:punct:]': ['\\p{P}', true],
1814
+ '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
1815
+ '[:upper:]': ['\\p{Lu}', true],
1816
+ '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
1817
+ '[:xdigit:]': ['A-Fa-f0-9', false],
1818
+ };
1819
+ // only need to escape a few things inside of brace expressions
1820
+ // escapes: [ \ ] -
1821
+ const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
1822
+ // escape all regexp magic characters
1823
+ const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
1824
+ // everything has already been escaped, we just have to join
1825
+ const rangesToString = (ranges) => ranges.join('');
1826
+ // takes a glob string at a posix brace expression, and returns
1827
+ // an equivalent regular expression source, and boolean indicating
1828
+ // whether the /u flag needs to be applied, and the number of chars
1829
+ // consumed to parse the character class.
1830
+ // This also removes out of order ranges, and returns ($.) if the
1831
+ // entire class just no good.
1832
+ const parseClass = (glob, position) => {
1833
+ const pos = position;
1834
+ /* c8 ignore start */
1835
+ if (glob.charAt(pos) !== '[') {
1836
+ throw new Error('not in a brace expression');
1837
+ }
1838
+ /* c8 ignore stop */
1839
+ const ranges = [];
1840
+ const negs = [];
1841
+ let i = pos + 1;
1842
+ let sawStart = false;
1843
+ let uflag = false;
1844
+ let escaping = false;
1845
+ let negate = false;
1846
+ let endPos = pos;
1847
+ let rangeStart = '';
1848
+ WHILE: while (i < glob.length) {
1849
+ const c = glob.charAt(i);
1850
+ if ((c === '!' || c === '^') && i === pos + 1) {
1851
+ negate = true;
1852
+ i++;
1853
+ continue;
1854
+ }
1855
+ if (c === ']' && sawStart && !escaping) {
1856
+ endPos = i + 1;
1857
+ break;
1858
+ }
1859
+ sawStart = true;
1860
+ if (c === '\\') {
1861
+ if (!escaping) {
1862
+ escaping = true;
1863
+ i++;
1864
+ continue;
1865
+ }
1866
+ // escaped \ char, fall through and treat like normal char
1867
+ }
1868
+ if (c === '[' && !escaping) {
1869
+ // either a posix class, a collation equivalent, or just a [
1870
+ for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
1871
+ if (glob.startsWith(cls, i)) {
1872
+ // invalid, [a-[] is fine, but not [a-[:alpha]]
1873
+ if (rangeStart) {
1874
+ return ['$.', false, glob.length - pos, true];
1875
+ }
1876
+ i += cls.length;
1877
+ if (neg)
1878
+ negs.push(unip);
1879
+ else
1880
+ ranges.push(unip);
1881
+ uflag = uflag || u;
1882
+ continue WHILE;
1883
+ }
1884
+ }
1885
+ }
1886
+ // now it's just a normal character, effectively
1887
+ escaping = false;
1888
+ if (rangeStart) {
1889
+ // throw this range away if it's not valid, but others
1890
+ // can still match.
1891
+ if (c > rangeStart) {
1892
+ ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
1893
+ }
1894
+ else if (c === rangeStart) {
1895
+ ranges.push(braceEscape(c));
1896
+ }
1897
+ rangeStart = '';
1898
+ i++;
1899
+ continue;
1900
+ }
1901
+ // now might be the start of a range.
1902
+ // can be either c-d or c-] or c<more...>] or c] at this point
1903
+ if (glob.startsWith('-]', i + 1)) {
1904
+ ranges.push(braceEscape(c + '-'));
1905
+ i += 2;
1906
+ continue;
1907
+ }
1908
+ if (glob.startsWith('-', i + 1)) {
1909
+ rangeStart = c;
1910
+ i += 2;
1911
+ continue;
1912
+ }
1913
+ // not the start of a range, just a single character
1914
+ ranges.push(braceEscape(c));
1915
+ i++;
1916
+ }
1917
+ if (endPos < i) {
1918
+ // didn't see the end of the class, not a valid class,
1919
+ // but might still be valid as a literal match.
1920
+ return ['', false, 0, false];
1921
+ }
1922
+ // if we got no ranges and no negates, then we have a range that
1923
+ // cannot possibly match anything, and that poisons the whole glob
1924
+ if (!ranges.length && !negs.length) {
1925
+ return ['$.', false, glob.length - pos, true];
1926
+ }
1927
+ // if we got one positive range, and it's a single character, then that's
1928
+ // not actually a magic pattern, it's just that one literal character.
1929
+ // we should not treat that as "magic", we should just return the literal
1930
+ // character. [_] is a perfectly valid way to escape glob magic chars.
1931
+ if (negs.length === 0 &&
1932
+ ranges.length === 1 &&
1933
+ /^\\?.$/.test(ranges[0]) &&
1934
+ !negate) {
1935
+ const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
1936
+ return [regexpEscape(r), false, endPos - pos, false];
1937
+ }
1938
+ const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
1939
+ const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
1940
+ const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
1941
+ : ranges.length ? sranges
1942
+ : snegs;
1943
+ return [comb, uflag, endPos - pos, true];
1944
+ };
1945
+
1946
+ /**
1947
+ * Un-escape a string that has been escaped with {@link escape}.
1948
+ *
1949
+ * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
1950
+ * square-bracket escapes are removed, but not backslash escapes.
1951
+ *
1952
+ * For example, it will turn the string `'[*]'` into `*`, but it will not
1953
+ * turn `'\\*'` into `'*'`, because `\` is a path separator in
1954
+ * `windowsPathsNoEscape` mode.
1955
+ *
1956
+ * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
1957
+ * backslash escapes are removed.
1958
+ *
1959
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
1960
+ * or unescaped.
1961
+ *
1962
+ * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
1963
+ * unescaped.
1964
+ */
1965
+ const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
1966
+ if (magicalBraces) {
1967
+ return windowsPathsNoEscape ?
1968
+ s.replace(/\[([^/\\])\]/g, '$1')
1969
+ : s
1970
+ .replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2')
1971
+ .replace(/\\([^/])/g, '$1');
1972
+ }
1973
+ return windowsPathsNoEscape ?
1974
+ s.replace(/\[([^/\\{}])\]/g, '$1')
1975
+ : s
1976
+ .replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2')
1977
+ .replace(/\\([^/{}])/g, '$1');
1978
+ };
1979
+
1980
+ // parse a single path portion
1981
+ var _a;
1982
+ const types = new Set(['!', '?', '+', '*', '@']);
1983
+ const isExtglobType = (c) => types.has(c);
1984
+ const isExtglobAST = (c) => isExtglobType(c.type);
1985
+ // Map of which extglob types can adopt the children of a nested extglob
1986
+ //
1987
+ // anything but ! can adopt a matching type:
1988
+ // +(a|+(b|c)|d) => +(a|b|c|d)
1989
+ // *(a|*(b|c)|d) => *(a|b|c|d)
1990
+ // @(a|@(b|c)|d) => @(a|b|c|d)
1991
+ // ?(a|?(b|c)|d) => ?(a|b|c|d)
1992
+ //
1993
+ // * can adopt anything, because 0 or repetition is allowed
1994
+ // *(a|?(b|c)|d) => *(a|b|c|d)
1995
+ // *(a|+(b|c)|d) => *(a|b|c|d)
1996
+ // *(a|@(b|c)|d) => *(a|b|c|d)
1997
+ //
1998
+ // + can adopt @, because 1 or repetition is allowed
1999
+ // +(a|@(b|c)|d) => +(a|b|c|d)
2000
+ //
2001
+ // + and @ CANNOT adopt *, because 0 would be allowed
2002
+ // +(a|*(b|c)|d) => would match "", on *(b|c)
2003
+ // @(a|*(b|c)|d) => would match "", on *(b|c)
2004
+ //
2005
+ // + and @ CANNOT adopt ?, because 0 would be allowed
2006
+ // +(a|?(b|c)|d) => would match "", on ?(b|c)
2007
+ // @(a|?(b|c)|d) => would match "", on ?(b|c)
2008
+ //
2009
+ // ? can adopt @, because 0 or 1 is allowed
2010
+ // ?(a|@(b|c)|d) => ?(a|b|c|d)
2011
+ //
2012
+ // ? and @ CANNOT adopt * or +, because >1 would be allowed
2013
+ // ?(a|*(b|c)|d) => would match bbb on *(b|c)
2014
+ // @(a|*(b|c)|d) => would match bbb on *(b|c)
2015
+ // ?(a|+(b|c)|d) => would match bbb on +(b|c)
2016
+ // @(a|+(b|c)|d) => would match bbb on +(b|c)
2017
+ //
2018
+ // ! CANNOT adopt ! (nothing else can either)
2019
+ // !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)
2020
+ //
2021
+ // ! can adopt @
2022
+ // !(a|@(b|c)|d) => !(a|b|c|d)
2023
+ //
2024
+ // ! CANNOT adopt *
2025
+ // !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
2026
+ //
2027
+ // ! CANNOT adopt +
2028
+ // !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
2029
+ //
2030
+ // ! CANNOT adopt ?
2031
+ // x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x"
2032
+ const adoptionMap = new Map([
2033
+ ['!', ['@']],
2034
+ ['?', ['?', '@']],
2035
+ ['@', ['@']],
2036
+ ['*', ['*', '+', '?', '@']],
2037
+ ['+', ['+', '@']],
2038
+ ]);
2039
+ // nested extglobs that can be adopted in, but with the addition of
2040
+ // a blank '' element.
2041
+ const adoptionWithSpaceMap = new Map([
2042
+ ['!', ['?']],
2043
+ ['@', ['?']],
2044
+ ['+', ['?', '*']],
2045
+ ]);
2046
+ // union of the previous two maps
2047
+ const adoptionAnyMap = new Map([
2048
+ ['!', ['?', '@']],
2049
+ ['?', ['?', '@']],
2050
+ ['@', ['?', '@']],
2051
+ ['*', ['*', '+', '?', '@']],
2052
+ ['+', ['+', '@', '?', '*']],
2053
+ ]);
2054
+ // Extglobs that can take over their parent if they are the only child
2055
+ // the key is parent, value maps child to resulting extglob parent type
2056
+ // '@' is omitted because it's a special case. An `@` extglob with a single
2057
+ // member can always be usurped by that subpattern.
2058
+ const usurpMap = new Map([
2059
+ ['!', new Map([['!', '@']])],
2060
+ [
2061
+ '?',
2062
+ new Map([
2063
+ ['*', '*'],
2064
+ ['+', '*'],
2065
+ ]),
2066
+ ],
2067
+ [
2068
+ '@',
2069
+ new Map([
2070
+ ['!', '!'],
2071
+ ['?', '?'],
2072
+ ['@', '@'],
2073
+ ['*', '*'],
2074
+ ['+', '+'],
2075
+ ]),
2076
+ ],
2077
+ [
2078
+ '+',
2079
+ new Map([
2080
+ ['?', '*'],
2081
+ ['*', '*'],
2082
+ ]),
2083
+ ],
2084
+ ]);
2085
+ // Patterns that get prepended to bind to the start of either the
2086
+ // entire string, or just a single path portion, to prevent dots
2087
+ // and/or traversal patterns, when needed.
2088
+ // Exts don't need the ^ or / bit, because the root binds that already.
2089
+ const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
2090
+ const startNoDot = '(?!\\.)';
2091
+ // characters that indicate a start of pattern needs the "no dots" bit,
2092
+ // because a dot *might* be matched. ( is not in the list, because in
2093
+ // the case of a child extglob, it will handle the prevention itself.
2094
+ const addPatternStart = new Set(['[', '.']);
2095
+ // cases where traversal is A-OK, no dot prevention needed
2096
+ const justDots = new Set(['..', '.']);
2097
+ const reSpecials = new Set('().*{}+?[]^$\\!');
2098
+ const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
2099
+ // any single thing other than /
2100
+ const qmark$1 = '[^/]';
2101
+ // * => any number of characters
2102
+ const star$1 = qmark$1 + '*?';
2103
+ // use + when we need to ensure that *something* matches, because the * is
2104
+ // the only thing in the path portion.
2105
+ const starNoEmpty = qmark$1 + '+?';
2106
+ // remove the \ chars that we added if we end up doing a nonmagic compare
2107
+ // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
2108
+ let ID = 0;
2109
+ class AST {
2110
+ type;
2111
+ #root;
2112
+ #hasMagic;
2113
+ #uflag = false;
2114
+ #parts = [];
2115
+ #parent;
2116
+ #parentIndex;
2117
+ #negs;
2118
+ #filledNegs = false;
2119
+ #options;
2120
+ #toString;
2121
+ // set to true if it's an extglob with no children
2122
+ // (which really means one child of '')
2123
+ #emptyExt = false;
2124
+ id = ++ID;
2125
+ get depth() {
2126
+ return (this.#parent?.depth ?? -1) + 1;
2127
+ }
2128
+ [Symbol.for('nodejs.util.inspect.custom')]() {
2129
+ return {
2130
+ '@@type': 'AST',
2131
+ id: this.id,
2132
+ type: this.type,
2133
+ root: this.#root.id,
2134
+ parent: this.#parent?.id,
2135
+ depth: this.depth,
2136
+ partsLength: this.#parts.length,
2137
+ parts: this.#parts,
2138
+ };
2139
+ }
2140
+ constructor(type, parent, options = {}) {
2141
+ this.type = type;
2142
+ // extglobs are inherently magical
2143
+ if (type)
2144
+ this.#hasMagic = true;
2145
+ this.#parent = parent;
2146
+ this.#root = this.#parent ? this.#parent.#root : this;
2147
+ this.#options = this.#root === this ? options : this.#root.#options;
2148
+ this.#negs = this.#root === this ? [] : this.#root.#negs;
2149
+ if (type === '!' && !this.#root.#filledNegs)
2150
+ this.#negs.push(this);
2151
+ this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
2152
+ }
2153
+ get hasMagic() {
2154
+ /* c8 ignore start */
2155
+ if (this.#hasMagic !== undefined)
2156
+ return this.#hasMagic;
2157
+ /* c8 ignore stop */
2158
+ for (const p of this.#parts) {
2159
+ if (typeof p === 'string')
2160
+ continue;
2161
+ if (p.type || p.hasMagic)
2162
+ return (this.#hasMagic = true);
2163
+ }
2164
+ // note: will be undefined until we generate the regexp src and find out
2165
+ return this.#hasMagic;
2166
+ }
2167
+ // reconstructs the pattern
2168
+ toString() {
2169
+ return (this.#toString !== undefined ? this.#toString
2170
+ : !this.type ?
2171
+ (this.#toString = this.#parts.map(p => String(p)).join(''))
2172
+ : (this.#toString =
2173
+ this.type +
2174
+ '(' +
2175
+ this.#parts.map(p => String(p)).join('|') +
2176
+ ')'));
2177
+ }
2178
+ #fillNegs() {
2179
+ /* c8 ignore start */
2180
+ if (this !== this.#root)
2181
+ throw new Error('should only call on root');
2182
+ if (this.#filledNegs)
2183
+ return this;
2184
+ /* c8 ignore stop */
2185
+ // call toString() once to fill this out
2186
+ this.toString();
2187
+ this.#filledNegs = true;
2188
+ let n;
2189
+ while ((n = this.#negs.pop())) {
2190
+ if (n.type !== '!')
2191
+ continue;
2192
+ // walk up the tree, appending everthing that comes AFTER parentIndex
2193
+ let p = n;
2194
+ let pp = p.#parent;
2195
+ while (pp) {
2196
+ for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
2197
+ for (const part of n.#parts) {
2198
+ /* c8 ignore start */
2199
+ if (typeof part === 'string') {
2200
+ throw new Error('string part in extglob AST??');
2201
+ }
2202
+ /* c8 ignore stop */
2203
+ part.copyIn(pp.#parts[i]);
2204
+ }
2205
+ }
2206
+ p = pp;
2207
+ pp = p.#parent;
2208
+ }
2209
+ }
2210
+ return this;
2211
+ }
2212
+ push(...parts) {
2213
+ for (const p of parts) {
2214
+ if (p === '')
2215
+ continue;
2216
+ /* c8 ignore start */
2217
+ if (typeof p !== 'string' &&
2218
+ !(p instanceof _a && p.#parent === this)) {
2219
+ throw new Error('invalid part: ' + p);
2220
+ }
2221
+ /* c8 ignore stop */
2222
+ this.#parts.push(p);
2223
+ }
2224
+ }
2225
+ toJSON() {
2226
+ const ret = this.type === null ?
2227
+ this.#parts
2228
+ .slice()
2229
+ .map(p => (typeof p === 'string' ? p : p.toJSON()))
2230
+ : [this.type, ...this.#parts.map(p => p.toJSON())];
2231
+ if (this.isStart() && !this.type)
2232
+ ret.unshift([]);
2233
+ if (this.isEnd() &&
2234
+ (this === this.#root ||
2235
+ (this.#root.#filledNegs && this.#parent?.type === '!'))) {
2236
+ ret.push({});
2237
+ }
2238
+ return ret;
2239
+ }
2240
+ isStart() {
2241
+ if (this.#root === this)
2242
+ return true;
2243
+ // if (this.type) return !!this.#parent?.isStart()
2244
+ if (!this.#parent?.isStart())
2245
+ return false;
2246
+ if (this.#parentIndex === 0)
2247
+ return true;
2248
+ // if everything AHEAD of this is a negation, then it's still the "start"
2249
+ const p = this.#parent;
2250
+ for (let i = 0; i < this.#parentIndex; i++) {
2251
+ const pp = p.#parts[i];
2252
+ if (!(pp instanceof _a && pp.type === '!')) {
2253
+ return false;
2254
+ }
2255
+ }
2256
+ return true;
2257
+ }
2258
+ isEnd() {
2259
+ if (this.#root === this)
2260
+ return true;
2261
+ if (this.#parent?.type === '!')
2262
+ return true;
2263
+ if (!this.#parent?.isEnd())
2264
+ return false;
2265
+ if (!this.type)
2266
+ return this.#parent?.isEnd();
2267
+ // if not root, it'll always have a parent
2268
+ /* c8 ignore start */
2269
+ const pl = this.#parent ? this.#parent.#parts.length : 0;
2270
+ /* c8 ignore stop */
2271
+ return this.#parentIndex === pl - 1;
2272
+ }
2273
+ copyIn(part) {
2274
+ if (typeof part === 'string')
2275
+ this.push(part);
2276
+ else
2277
+ this.push(part.clone(this));
2278
+ }
2279
+ clone(parent) {
2280
+ const c = new _a(this.type, parent);
2281
+ for (const p of this.#parts) {
2282
+ c.copyIn(p);
2283
+ }
2284
+ return c;
2285
+ }
2286
+ static #parseAST(str, ast, pos, opt, extDepth) {
2287
+ const maxDepth = opt.maxExtglobRecursion ?? 2;
2288
+ let escaping = false;
2289
+ let inBrace = false;
2290
+ let braceStart = -1;
2291
+ let braceNeg = false;
2292
+ if (ast.type === null) {
2293
+ // outside of a extglob, append until we find a start
2294
+ let i = pos;
2295
+ let acc = '';
2296
+ while (i < str.length) {
2297
+ const c = str.charAt(i++);
2298
+ // still accumulate escapes at this point, but we do ignore
2299
+ // starts that are escaped
2300
+ if (escaping || c === '\\') {
2301
+ escaping = !escaping;
2302
+ acc += c;
2303
+ continue;
2304
+ }
2305
+ if (inBrace) {
2306
+ if (i === braceStart + 1) {
2307
+ if (c === '^' || c === '!') {
2308
+ braceNeg = true;
2309
+ }
2310
+ }
2311
+ else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
2312
+ inBrace = false;
2313
+ }
2314
+ acc += c;
2315
+ continue;
2316
+ }
2317
+ else if (c === '[') {
2318
+ inBrace = true;
2319
+ braceStart = i;
2320
+ braceNeg = false;
2321
+ acc += c;
2322
+ continue;
2323
+ }
2324
+ // we don't have to check for adoption here, because that's
2325
+ // done at the other recursion point.
2326
+ const doRecurse = !opt.noext &&
2327
+ isExtglobType(c) &&
2328
+ str.charAt(i) === '(' &&
2329
+ extDepth <= maxDepth;
2330
+ if (doRecurse) {
2331
+ ast.push(acc);
2332
+ acc = '';
2333
+ const ext = new _a(c, ast);
2334
+ i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
2335
+ ast.push(ext);
2336
+ continue;
2337
+ }
2338
+ acc += c;
2339
+ }
2340
+ ast.push(acc);
2341
+ return i;
2342
+ }
2343
+ // some kind of extglob, pos is at the (
2344
+ // find the next | or )
2345
+ let i = pos + 1;
2346
+ let part = new _a(null, ast);
2347
+ const parts = [];
2348
+ let acc = '';
2349
+ while (i < str.length) {
2350
+ const c = str.charAt(i++);
2351
+ // still accumulate escapes at this point, but we do ignore
2352
+ // starts that are escaped
2353
+ if (escaping || c === '\\') {
2354
+ escaping = !escaping;
2355
+ acc += c;
2356
+ continue;
2357
+ }
2358
+ if (inBrace) {
2359
+ if (i === braceStart + 1) {
2360
+ if (c === '^' || c === '!') {
2361
+ braceNeg = true;
2362
+ }
2363
+ }
2364
+ else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
2365
+ inBrace = false;
2366
+ }
2367
+ acc += c;
2368
+ continue;
2369
+ }
2370
+ else if (c === '[') {
2371
+ inBrace = true;
2372
+ braceStart = i;
2373
+ braceNeg = false;
2374
+ acc += c;
2375
+ continue;
2376
+ }
2377
+ const doRecurse = !opt.noext &&
2378
+ isExtglobType(c) &&
2379
+ str.charAt(i) === '(' &&
2380
+ /* c8 ignore start - the maxDepth is sufficient here */
2381
+ (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)));
2382
+ /* c8 ignore stop */
2383
+ if (doRecurse) {
2384
+ const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
2385
+ part.push(acc);
2386
+ acc = '';
2387
+ const ext = new _a(c, part);
2388
+ part.push(ext);
2389
+ i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
2390
+ continue;
2391
+ }
2392
+ if (c === '|') {
2393
+ part.push(acc);
2394
+ acc = '';
2395
+ parts.push(part);
2396
+ part = new _a(null, ast);
2397
+ continue;
2398
+ }
2399
+ if (c === ')') {
2400
+ if (acc === '' && ast.#parts.length === 0) {
2401
+ ast.#emptyExt = true;
2402
+ }
2403
+ part.push(acc);
2404
+ acc = '';
2405
+ ast.push(...parts, part);
2406
+ return i;
2407
+ }
2408
+ acc += c;
2409
+ }
2410
+ // unfinished extglob
2411
+ // if we got here, it was a malformed extglob! not an extglob, but
2412
+ // maybe something else in there.
2413
+ ast.type = null;
2414
+ ast.#hasMagic = undefined;
2415
+ ast.#parts = [str.substring(pos - 1)];
2416
+ return i;
2417
+ }
2418
+ #canAdoptWithSpace(child) {
2419
+ return this.#canAdopt(child, adoptionWithSpaceMap);
2420
+ }
2421
+ #canAdopt(child, map = adoptionMap) {
2422
+ if (!child ||
2423
+ typeof child !== 'object' ||
2424
+ child.type !== null ||
2425
+ child.#parts.length !== 1 ||
2426
+ this.type === null) {
2427
+ return false;
2428
+ }
2429
+ const gc = child.#parts[0];
2430
+ if (!gc || typeof gc !== 'object' || gc.type === null) {
2431
+ return false;
2432
+ }
2433
+ return this.#canAdoptType(gc.type, map);
2434
+ }
2435
+ #canAdoptType(c, map = adoptionAnyMap) {
2436
+ return !!map.get(this.type)?.includes(c);
2437
+ }
2438
+ #adoptWithSpace(child, index) {
2439
+ const gc = child.#parts[0];
2440
+ const blank = new _a(null, gc, this.options);
2441
+ blank.#parts.push('');
2442
+ gc.push(blank);
2443
+ this.#adopt(child, index);
2444
+ }
2445
+ #adopt(child, index) {
2446
+ const gc = child.#parts[0];
2447
+ this.#parts.splice(index, 1, ...gc.#parts);
2448
+ for (const p of gc.#parts) {
2449
+ if (typeof p === 'object')
2450
+ p.#parent = this;
2451
+ }
2452
+ this.#toString = undefined;
2453
+ }
2454
+ #canUsurpType(c) {
2455
+ const m = usurpMap.get(this.type);
2456
+ return !!m?.has(c);
2457
+ }
2458
+ #canUsurp(child) {
2459
+ if (!child ||
2460
+ typeof child !== 'object' ||
2461
+ child.type !== null ||
2462
+ child.#parts.length !== 1 ||
2463
+ this.type === null ||
2464
+ this.#parts.length !== 1) {
2465
+ return false;
2466
+ }
2467
+ const gc = child.#parts[0];
2468
+ if (!gc || typeof gc !== 'object' || gc.type === null) {
2469
+ return false;
2470
+ }
2471
+ return this.#canUsurpType(gc.type);
2472
+ }
2473
+ #usurp(child) {
2474
+ const m = usurpMap.get(this.type);
2475
+ const gc = child.#parts[0];
2476
+ const nt = m?.get(gc.type);
2477
+ /* c8 ignore start - impossible */
2478
+ if (!nt)
2479
+ return false;
2480
+ /* c8 ignore stop */
2481
+ this.#parts = gc.#parts;
2482
+ for (const p of this.#parts) {
2483
+ if (typeof p === 'object') {
2484
+ p.#parent = this;
2485
+ }
2486
+ }
2487
+ this.type = nt;
2488
+ this.#toString = undefined;
2489
+ this.#emptyExt = false;
2490
+ }
2491
+ static fromGlob(pattern, options = {}) {
2492
+ const ast = new _a(null, undefined, options);
2493
+ _a.#parseAST(pattern, ast, 0, options, 0);
2494
+ return ast;
2495
+ }
2496
+ // returns the regular expression if there's magic, or the unescaped
2497
+ // string if not.
2498
+ toMMPattern() {
2499
+ // should only be called on root
2500
+ /* c8 ignore start */
2501
+ if (this !== this.#root)
2502
+ return this.#root.toMMPattern();
2503
+ /* c8 ignore stop */
2504
+ const glob = this.toString();
2505
+ const [re, body, hasMagic, uflag] = this.toRegExpSource();
2506
+ // if we're in nocase mode, and not nocaseMagicOnly, then we do
2507
+ // still need a regular expression if we have to case-insensitively
2508
+ // match capital/lowercase characters.
2509
+ const anyMagic = hasMagic ||
2510
+ this.#hasMagic ||
2511
+ (this.#options.nocase &&
2512
+ !this.#options.nocaseMagicOnly &&
2513
+ glob.toUpperCase() !== glob.toLowerCase());
2514
+ if (!anyMagic) {
2515
+ return body;
2516
+ }
2517
+ const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
2518
+ return Object.assign(new RegExp(`^${re}$`, flags), {
2519
+ _src: re,
2520
+ _glob: glob,
2521
+ });
2522
+ }
2523
+ get options() {
2524
+ return this.#options;
2525
+ }
2526
+ // returns the string match, the regexp source, whether there's magic
2527
+ // in the regexp (so a regular expression is required) and whether or
2528
+ // not the uflag is needed for the regular expression (for posix classes)
2529
+ // TODO: instead of injecting the start/end at this point, just return
2530
+ // the BODY of the regexp, along with the start/end portions suitable
2531
+ // for binding the start/end in either a joined full-path makeRe context
2532
+ // (where we bind to (^|/), or a standalone matchPart context (where
2533
+ // we bind to ^, and not /). Otherwise slashes get duped!
2534
+ //
2535
+ // In part-matching mode, the start is:
2536
+ // - if not isStart: nothing
2537
+ // - if traversal possible, but not allowed: ^(?!\.\.?$)
2538
+ // - if dots allowed or not possible: ^
2539
+ // - if dots possible and not allowed: ^(?!\.)
2540
+ // end is:
2541
+ // - if not isEnd(): nothing
2542
+ // - else: $
2543
+ //
2544
+ // In full-path matching mode, we put the slash at the START of the
2545
+ // pattern, so start is:
2546
+ // - if first pattern: same as part-matching mode
2547
+ // - if not isStart(): nothing
2548
+ // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
2549
+ // - if dots allowed or not possible: /
2550
+ // - if dots possible and not allowed: /(?!\.)
2551
+ // end is:
2552
+ // - if last pattern, same as part-matching mode
2553
+ // - else nothing
2554
+ //
2555
+ // Always put the (?:$|/) on negated tails, though, because that has to be
2556
+ // there to bind the end of the negated pattern portion, and it's easier to
2557
+ // just stick it in now rather than try to inject it later in the middle of
2558
+ // the pattern.
2559
+ //
2560
+ // We can just always return the same end, and leave it up to the caller
2561
+ // to know whether it's going to be used joined or in parts.
2562
+ // And, if the start is adjusted slightly, can do the same there:
2563
+ // - if not isStart: nothing
2564
+ // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
2565
+ // - if dots allowed or not possible: (?:/|^)
2566
+ // - if dots possible and not allowed: (?:/|^)(?!\.)
2567
+ //
2568
+ // But it's better to have a simpler binding without a conditional, for
2569
+ // performance, so probably better to return both start options.
2570
+ //
2571
+ // Then the caller just ignores the end if it's not the first pattern,
2572
+ // and the start always gets applied.
2573
+ //
2574
+ // But that's always going to be $ if it's the ending pattern, or nothing,
2575
+ // so the caller can just attach $ at the end of the pattern when building.
2576
+ //
2577
+ // So the todo is:
2578
+ // - better detect what kind of start is needed
2579
+ // - return both flavors of starting pattern
2580
+ // - attach $ at the end of the pattern when creating the actual RegExp
2581
+ //
2582
+ // Ah, but wait, no, that all only applies to the root when the first pattern
2583
+ // is not an extglob. If the first pattern IS an extglob, then we need all
2584
+ // that dot prevention biz to live in the extglob portions, because eg
2585
+ // +(*|.x*) can match .xy but not .yx.
2586
+ //
2587
+ // So, return the two flavors if it's #root and the first child is not an
2588
+ // AST, otherwise leave it to the child AST to handle it, and there,
2589
+ // use the (?:^|/) style of start binding.
2590
+ //
2591
+ // Even simplified further:
2592
+ // - Since the start for a join is eg /(?!\.) and the start for a part
2593
+ // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
2594
+ // or start or whatever) and prepend ^ or / at the Regexp construction.
2595
+ toRegExpSource(allowDot) {
2596
+ const dot = allowDot ?? !!this.#options.dot;
2597
+ if (this.#root === this) {
2598
+ this.#flatten();
2599
+ this.#fillNegs();
2600
+ }
2601
+ if (!isExtglobAST(this)) {
2602
+ const noEmpty = this.isStart() &&
2603
+ this.isEnd() &&
2604
+ !this.#parts.some(s => typeof s !== 'string');
2605
+ const src = this.#parts
2606
+ .map(p => {
2607
+ const [re, _, hasMagic, uflag] = typeof p === 'string' ?
2608
+ _a.#parseGlob(p, this.#hasMagic, noEmpty)
2609
+ : p.toRegExpSource(allowDot);
2610
+ this.#hasMagic = this.#hasMagic || hasMagic;
2611
+ this.#uflag = this.#uflag || uflag;
2612
+ return re;
2613
+ })
2614
+ .join('');
2615
+ let start = '';
2616
+ if (this.isStart()) {
2617
+ if (typeof this.#parts[0] === 'string') {
2618
+ // this is the string that will match the start of the pattern,
2619
+ // so we need to protect against dots and such.
2620
+ // '.' and '..' cannot match unless the pattern is that exactly,
2621
+ // even if it starts with . or dot:true is set.
2622
+ const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
2623
+ if (!dotTravAllowed) {
2624
+ const aps = addPatternStart;
2625
+ // check if we have a possibility of matching . or ..,
2626
+ // and prevent that.
2627
+ const needNoTrav =
2628
+ // dots are allowed, and the pattern starts with [ or .
2629
+ (dot && aps.has(src.charAt(0))) ||
2630
+ // the pattern starts with \., and then [ or .
2631
+ (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
2632
+ // the pattern starts with \.\., and then [ or .
2633
+ (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
2634
+ // no need to prevent dots if it can't match a dot, or if a
2635
+ // sub-pattern will be preventing it anyway.
2636
+ const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
2637
+ start =
2638
+ needNoTrav ? startNoTraversal
2639
+ : needNoDot ? startNoDot
2640
+ : '';
2641
+ }
2642
+ }
2643
+ }
2644
+ // append the "end of path portion" pattern to negation tails
2645
+ let end = '';
2646
+ if (this.isEnd() &&
2647
+ this.#root.#filledNegs &&
2648
+ this.#parent?.type === '!') {
2649
+ end = '(?:$|\\/)';
2650
+ }
2651
+ const final = start + src + end;
2652
+ return [
2653
+ final,
2654
+ unescape(src),
2655
+ (this.#hasMagic = !!this.#hasMagic),
2656
+ this.#uflag,
2657
+ ];
2658
+ }
2659
+ // We need to calculate the body *twice* if it's a repeat pattern
2660
+ // at the start, once in nodot mode, then again in dot mode, so a
2661
+ // pattern like *(?) can match 'x.y'
2662
+ const repeated = this.type === '*' || this.type === '+';
2663
+ // some kind of extglob
2664
+ const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
2665
+ let body = this.#partsToRegExp(dot);
2666
+ if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
2667
+ // invalid extglob, has to at least be *something* present, if it's
2668
+ // the entire path portion.
2669
+ const s = this.toString();
2670
+ const me = this;
2671
+ me.#parts = [s];
2672
+ me.type = null;
2673
+ me.#hasMagic = undefined;
2674
+ return [s, unescape(this.toString()), false, false];
2675
+ }
2676
+ let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ?
2677
+ ''
2678
+ : this.#partsToRegExp(true);
2679
+ if (bodyDotAllowed === body) {
2680
+ bodyDotAllowed = '';
2681
+ }
2682
+ if (bodyDotAllowed) {
2683
+ body = `(?:${body})(?:${bodyDotAllowed})*?`;
2684
+ }
2685
+ // an empty !() is exactly equivalent to a starNoEmpty
2686
+ let final = '';
2687
+ if (this.type === '!' && this.#emptyExt) {
2688
+ final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
2689
+ }
2690
+ else {
2691
+ const close = this.type === '!' ?
2692
+ // !() must match something,but !(x) can match ''
2693
+ '))' +
2694
+ (this.isStart() && !dot && !allowDot ? startNoDot : '') +
2695
+ star$1 +
2696
+ ')'
2697
+ : this.type === '@' ? ')'
2698
+ : this.type === '?' ? ')?'
2699
+ : this.type === '+' && bodyDotAllowed ? ')'
2700
+ : this.type === '*' && bodyDotAllowed ? `)?`
2701
+ : `)${this.type}`;
2702
+ final = start + body + close;
2703
+ }
2704
+ return [
2705
+ final,
2706
+ unescape(body),
2707
+ (this.#hasMagic = !!this.#hasMagic),
2708
+ this.#uflag,
2709
+ ];
2710
+ }
2711
+ #flatten() {
2712
+ if (!isExtglobAST(this)) {
2713
+ for (const p of this.#parts) {
2714
+ if (typeof p === 'object') {
2715
+ p.#flatten();
2716
+ }
2717
+ }
2718
+ }
2719
+ else {
2720
+ // do up to 10 passes to flatten as much as possible
2721
+ let iterations = 0;
2722
+ let done = false;
2723
+ do {
2724
+ done = true;
2725
+ for (let i = 0; i < this.#parts.length; i++) {
2726
+ const c = this.#parts[i];
2727
+ if (typeof c === 'object') {
2728
+ c.#flatten();
2729
+ if (this.#canAdopt(c)) {
2730
+ done = false;
2731
+ this.#adopt(c, i);
2732
+ }
2733
+ else if (this.#canAdoptWithSpace(c)) {
2734
+ done = false;
2735
+ this.#adoptWithSpace(c, i);
2736
+ }
2737
+ else if (this.#canUsurp(c)) {
2738
+ done = false;
2739
+ this.#usurp(c);
2740
+ }
2741
+ }
2742
+ }
2743
+ } while (!done && ++iterations < 10);
2744
+ }
2745
+ this.#toString = undefined;
2746
+ }
2747
+ #partsToRegExp(dot) {
2748
+ return this.#parts
2749
+ .map(p => {
2750
+ // extglob ASTs should only contain parent ASTs
2751
+ /* c8 ignore start */
2752
+ if (typeof p === 'string') {
2753
+ throw new Error('string type in extglob ast??');
2754
+ }
2755
+ /* c8 ignore stop */
2756
+ // can ignore hasMagic, because extglobs are already always magic
2757
+ const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
2758
+ this.#uflag = this.#uflag || uflag;
2759
+ return re;
2760
+ })
2761
+ .filter(p => !(this.isStart() && this.isEnd()) || !!p)
2762
+ .join('|');
2763
+ }
2764
+ static #parseGlob(glob, hasMagic, noEmpty = false) {
2765
+ let escaping = false;
2766
+ let re = '';
2767
+ let uflag = false;
2768
+ // multiple stars that aren't globstars coalesce into one *
2769
+ let inStar = false;
2770
+ for (let i = 0; i < glob.length; i++) {
2771
+ const c = glob.charAt(i);
2772
+ if (escaping) {
2773
+ escaping = false;
2774
+ re += (reSpecials.has(c) ? '\\' : '') + c;
2775
+ continue;
2776
+ }
2777
+ if (c === '*') {
2778
+ if (inStar)
2779
+ continue;
2780
+ inStar = true;
2781
+ re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star$1;
2782
+ hasMagic = true;
2783
+ continue;
2784
+ }
2785
+ else {
2786
+ inStar = false;
2787
+ }
2788
+ if (c === '\\') {
2789
+ if (i === glob.length - 1) {
2790
+ re += '\\\\';
2791
+ }
2792
+ else {
2793
+ escaping = true;
2794
+ }
2795
+ continue;
2796
+ }
2797
+ if (c === '[') {
2798
+ const [src, needUflag, consumed, magic] = parseClass(glob, i);
2799
+ if (consumed) {
2800
+ re += src;
2801
+ uflag = uflag || needUflag;
2802
+ i += consumed - 1;
2803
+ hasMagic = hasMagic || magic;
2804
+ continue;
2805
+ }
2806
+ }
2807
+ if (c === '?') {
2808
+ re += qmark$1;
2809
+ hasMagic = true;
2810
+ continue;
2811
+ }
2812
+ re += regExpEscape$1(c);
2813
+ }
2814
+ return [re, unescape(glob), !!hasMagic, uflag];
2815
+ }
2816
+ }
2817
+ _a = AST;
2818
+
2819
+ /**
2820
+ * Escape all magic characters in a glob pattern.
2821
+ *
2822
+ * If the {@link MinimatchOptions.windowsPathsNoEscape}
2823
+ * option is used, then characters are escaped by wrapping in `[]`, because
2824
+ * a magic character wrapped in a character class can only be satisfied by
2825
+ * that exact character. In this mode, `\` is _not_ escaped, because it is
2826
+ * not interpreted as a magic character, but instead as a path separator.
2827
+ *
2828
+ * If the {@link MinimatchOptions.magicalBraces} option is used,
2829
+ * then braces (`{` and `}`) will be escaped.
2830
+ */
2831
+ const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
2832
+ // don't need to escape +@! because we escape the parens
2833
+ // that make those magic, and escaping ! as [!] isn't valid,
2834
+ // because [!]] is a valid glob class meaning not ']'.
2835
+ if (magicalBraces) {
2836
+ return windowsPathsNoEscape ?
2837
+ s.replace(/[?*()[\]{}]/g, '[$&]')
2838
+ : s.replace(/[?*()[\]\\{}]/g, '\\$&');
2839
+ }
2840
+ return windowsPathsNoEscape ?
2841
+ s.replace(/[?*()[\]]/g, '[$&]')
2842
+ : s.replace(/[?*()[\]\\]/g, '\\$&');
2843
+ };
2844
+
2845
+ const minimatch = (p, pattern, options = {}) => {
2846
+ assertValidPattern(pattern);
2847
+ // shortcut: comments match nothing.
2848
+ if (!options.nocomment && pattern.charAt(0) === '#') {
2849
+ return false;
2850
+ }
2851
+ return new Minimatch(pattern, options).match(p);
2852
+ };
2853
+ // Optimized checking for the most common glob patterns.
2854
+ const starDotExtRE = /^\*+([^+@!?*[(]*)$/;
2855
+ const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
2856
+ const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
2857
+ const starDotExtTestNocase = (ext) => {
2858
+ ext = ext.toLowerCase();
2859
+ return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
2860
+ };
2861
+ const starDotExtTestNocaseDot = (ext) => {
2862
+ ext = ext.toLowerCase();
2863
+ return (f) => f.toLowerCase().endsWith(ext);
2864
+ };
2865
+ const starDotStarRE = /^\*+\.\*+$/;
2866
+ const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
2867
+ const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
2868
+ const dotStarRE = /^\.\*+$/;
2869
+ const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
2870
+ const starRE = /^\*+$/;
2871
+ const starTest = (f) => f.length !== 0 && !f.startsWith('.');
2872
+ const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
2873
+ const qmarksRE = /^\?+([^+@!?*[(]*)?$/;
2874
+ const qmarksTestNocase = ([$0, ext = '']) => {
2875
+ const noext = qmarksTestNoExt([$0]);
2876
+ if (!ext)
2877
+ return noext;
2878
+ ext = ext.toLowerCase();
2879
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext);
2880
+ };
2881
+ const qmarksTestNocaseDot = ([$0, ext = '']) => {
2882
+ const noext = qmarksTestNoExtDot([$0]);
2883
+ if (!ext)
2884
+ return noext;
2885
+ ext = ext.toLowerCase();
2886
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext);
2887
+ };
2888
+ const qmarksTestDot = ([$0, ext = '']) => {
2889
+ const noext = qmarksTestNoExtDot([$0]);
2890
+ return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
2891
+ };
2892
+ const qmarksTest = ([$0, ext = '']) => {
2893
+ const noext = qmarksTestNoExt([$0]);
2894
+ return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
2895
+ };
2896
+ const qmarksTestNoExt = ([$0]) => {
2897
+ const len = $0.length;
2898
+ return (f) => f.length === len && !f.startsWith('.');
2899
+ };
2900
+ const qmarksTestNoExtDot = ([$0]) => {
2901
+ const len = $0.length;
2902
+ return (f) => f.length === len && f !== '.' && f !== '..';
2903
+ };
2904
+ /* c8 ignore start */
2905
+ const defaultPlatform = (typeof process === 'object' && process ?
2906
+ (typeof process.env === 'object' &&
2907
+ process.env &&
2908
+ process.env.__MINIMATCH_TESTING_PLATFORM__) ||
2909
+ process.platform
2910
+ : 'posix');
2911
+ const path = {
2912
+ win32: { sep: '\\' },
2913
+ posix: { sep: '/' },
2914
+ };
2915
+ /* c8 ignore stop */
2916
+ const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
2917
+ minimatch.sep = sep;
2918
+ const GLOBSTAR = Symbol('globstar **');
2919
+ minimatch.GLOBSTAR = GLOBSTAR;
2920
+ // any single thing other than /
2921
+ // don't need to escape / when using new RegExp()
2922
+ const qmark = '[^/]';
2923
+ // * => any number of characters
2924
+ const star = qmark + '*?';
2925
+ // ** when dots are allowed. Anything goes, except .. and .
2926
+ // not (^ or / followed by one or two dots followed by $ or /),
2927
+ // followed by anything, any number of times.
2928
+ const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
2929
+ // not a ^ or / followed by a dot,
2930
+ // followed by anything, any number of times.
2931
+ const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
2932
+ const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
2933
+ minimatch.filter = filter;
2934
+ const ext = (a, b = {}) => Object.assign({}, a, b);
2935
+ const defaults = (def) => {
2936
+ if (!def || typeof def !== 'object' || !Object.keys(def).length) {
2937
+ return minimatch;
2938
+ }
2939
+ const orig = minimatch;
2940
+ const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
2941
+ return Object.assign(m, {
2942
+ Minimatch: class Minimatch extends orig.Minimatch {
2943
+ constructor(pattern, options = {}) {
2944
+ super(pattern, ext(def, options));
2945
+ }
2946
+ static defaults(options) {
2947
+ return orig.defaults(ext(def, options)).Minimatch;
2948
+ }
2949
+ },
2950
+ AST: class AST extends orig.AST {
2951
+ /* c8 ignore start */
2952
+ constructor(type, parent, options = {}) {
2953
+ super(type, parent, ext(def, options));
2954
+ }
2955
+ /* c8 ignore stop */
2956
+ static fromGlob(pattern, options = {}) {
2957
+ return orig.AST.fromGlob(pattern, ext(def, options));
2958
+ }
2959
+ },
2960
+ unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
2961
+ escape: (s, options = {}) => orig.escape(s, ext(def, options)),
2962
+ filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
2963
+ defaults: (options) => orig.defaults(ext(def, options)),
2964
+ makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
2965
+ braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
2966
+ match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
2967
+ sep: orig.sep,
2968
+ GLOBSTAR: GLOBSTAR,
2969
+ });
2970
+ };
2971
+ minimatch.defaults = defaults;
2972
+ // Brace expansion:
2973
+ // a{b,c}d -> abd acd
2974
+ // a{b,}c -> abc ac
2975
+ // a{0..3}d -> a0d a1d a2d a3d
2976
+ // a{b,c{d,e}f}g -> abg acdfg acefg
2977
+ // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
2978
+ //
2979
+ // Invalid sets are not expanded.
2980
+ // a{2..}b -> a{2..}b
2981
+ // a{b}c -> a{b}c
2982
+ const braceExpand = (pattern, options = {}) => {
2983
+ assertValidPattern(pattern);
2984
+ // Thanks to Yeting Li <https://github.com/yetingli> for
2985
+ // improving this regexp to avoid a ReDOS vulnerability.
2986
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
2987
+ // shortcut. no need to expand.
2988
+ return [pattern];
2989
+ }
2990
+ return expand(pattern, { max: options.braceExpandMax });
2991
+ };
2992
+ minimatch.braceExpand = braceExpand;
2993
+ // parse a component of the expanded set.
2994
+ // At this point, no pattern may contain "/" in it
2995
+ // so we're going to return a 2d array, where each entry is the full
2996
+ // pattern, split on '/', and then turned into a regular expression.
2997
+ // A regexp is made at the end which joins each array with an
2998
+ // escaped /, and another full one which joins each regexp with |.
2999
+ //
3000
+ // Following the lead of Bash 4.1, note that "**" only has special meaning
3001
+ // when it is the *only* thing in a path portion. Otherwise, any series
3002
+ // of * is equivalent to a single *. Globstar behavior is enabled by
3003
+ // default, and can be disabled by setting options.noglobstar.
3004
+ const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
3005
+ minimatch.makeRe = makeRe;
3006
+ const match = (list, pattern, options = {}) => {
3007
+ const mm = new Minimatch(pattern, options);
3008
+ list = list.filter(f => mm.match(f));
3009
+ if (mm.options.nonull && !list.length) {
3010
+ list.push(pattern);
3011
+ }
3012
+ return list;
3013
+ };
3014
+ minimatch.match = match;
3015
+ // replace stuff like \* with *
3016
+ const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
3017
+ const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
3018
+ class Minimatch {
3019
+ options;
3020
+ set;
3021
+ pattern;
3022
+ windowsPathsNoEscape;
3023
+ nonegate;
3024
+ negate;
3025
+ comment;
3026
+ empty;
3027
+ preserveMultipleSlashes;
3028
+ partial;
3029
+ globSet;
3030
+ globParts;
3031
+ nocase;
3032
+ isWindows;
3033
+ platform;
3034
+ windowsNoMagicRoot;
3035
+ maxGlobstarRecursion;
3036
+ regexp;
3037
+ constructor(pattern, options = {}) {
3038
+ assertValidPattern(pattern);
3039
+ options = options || {};
3040
+ this.options = options;
3041
+ this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
3042
+ this.pattern = pattern;
3043
+ this.platform = options.platform || defaultPlatform;
3044
+ this.isWindows = this.platform === 'win32';
3045
+ // avoid the annoying deprecation flag lol
3046
+ const awe = ('allowWindow' + 'sEscape');
3047
+ this.windowsPathsNoEscape =
3048
+ !!options.windowsPathsNoEscape || options[awe] === false;
3049
+ if (this.windowsPathsNoEscape) {
3050
+ this.pattern = this.pattern.replace(/\\/g, '/');
3051
+ }
3052
+ this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
3053
+ this.regexp = null;
3054
+ this.negate = false;
3055
+ this.nonegate = !!options.nonegate;
3056
+ this.comment = false;
3057
+ this.empty = false;
3058
+ this.partial = !!options.partial;
3059
+ this.nocase = !!this.options.nocase;
3060
+ this.windowsNoMagicRoot =
3061
+ options.windowsNoMagicRoot !== undefined ?
3062
+ options.windowsNoMagicRoot
3063
+ : !!(this.isWindows && this.nocase);
3064
+ this.globSet = [];
3065
+ this.globParts = [];
3066
+ this.set = [];
3067
+ // make the set of regexps etc.
3068
+ this.make();
3069
+ }
3070
+ hasMagic() {
3071
+ if (this.options.magicalBraces && this.set.length > 1) {
3072
+ return true;
3073
+ }
3074
+ for (const pattern of this.set) {
3075
+ for (const part of pattern) {
3076
+ if (typeof part !== 'string')
3077
+ return true;
3078
+ }
3079
+ }
3080
+ return false;
3081
+ }
3082
+ debug(..._) { }
3083
+ make() {
3084
+ const pattern = this.pattern;
3085
+ const options = this.options;
3086
+ // empty patterns and comments match nothing.
3087
+ if (!options.nocomment && pattern.charAt(0) === '#') {
3088
+ this.comment = true;
3089
+ return;
3090
+ }
3091
+ if (!pattern) {
3092
+ this.empty = true;
3093
+ return;
3094
+ }
3095
+ // step 1: figure out negation, etc.
3096
+ this.parseNegate();
3097
+ // step 2: expand braces
3098
+ this.globSet = [...new Set(this.braceExpand())];
3099
+ if (options.debug) {
3100
+ //oxlint-disable-next-line no-console
3101
+ this.debug = (...args) => console.error(...args);
3102
+ }
3103
+ this.debug(this.pattern, this.globSet);
3104
+ // step 3: now we have a set, so turn each one into a series of
3105
+ // path-portion matching patterns.
3106
+ // These will be regexps, except in the case of "**", which is
3107
+ // set to the GLOBSTAR object for globstar behavior,
3108
+ // and will not contain any / characters
3109
+ //
3110
+ // First, we preprocess to make the glob pattern sets a bit simpler
3111
+ // and deduped. There are some perf-killing patterns that can cause
3112
+ // problems with a glob walk, but we can simplify them down a bit.
3113
+ const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
3114
+ this.globParts = this.preprocess(rawGlobParts);
3115
+ this.debug(this.pattern, this.globParts);
3116
+ // glob --> regexps
3117
+ let set = this.globParts.map((s, _, __) => {
3118
+ if (this.isWindows && this.windowsNoMagicRoot) {
3119
+ // check if it's a drive or unc path.
3120
+ const isUNC = s[0] === '' &&
3121
+ s[1] === '' &&
3122
+ (s[2] === '?' || !globMagic.test(s[2])) &&
3123
+ !globMagic.test(s[3]);
3124
+ const isDrive = /^[a-z]:/i.test(s[0]);
3125
+ if (isUNC) {
3126
+ return [
3127
+ ...s.slice(0, 4),
3128
+ ...s.slice(4).map(ss => this.parse(ss)),
3129
+ ];
3130
+ }
3131
+ else if (isDrive) {
3132
+ return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
3133
+ }
3134
+ }
3135
+ return s.map(ss => this.parse(ss));
3136
+ });
3137
+ this.debug(this.pattern, set);
3138
+ // filter out everything that didn't compile properly.
3139
+ this.set = set.filter(s => s.indexOf(false) === -1);
3140
+ // do not treat the ? in UNC paths as magic
3141
+ if (this.isWindows) {
3142
+ for (let i = 0; i < this.set.length; i++) {
3143
+ const p = this.set[i];
3144
+ if (p[0] === '' &&
3145
+ p[1] === '' &&
3146
+ this.globParts[i][2] === '?' &&
3147
+ typeof p[3] === 'string' &&
3148
+ /^[a-z]:$/i.test(p[3])) {
3149
+ p[2] = '?';
3150
+ }
3151
+ }
3152
+ }
3153
+ this.debug(this.pattern, this.set);
3154
+ }
3155
+ // various transforms to equivalent pattern sets that are
3156
+ // faster to process in a filesystem walk. The goal is to
3157
+ // eliminate what we can, and push all ** patterns as far
3158
+ // to the right as possible, even if it increases the number
3159
+ // of patterns that we have to process.
3160
+ preprocess(globParts) {
3161
+ // if we're not in globstar mode, then turn ** into *
3162
+ if (this.options.noglobstar) {
3163
+ for (const partset of globParts) {
3164
+ for (let j = 0; j < partset.length; j++) {
3165
+ if (partset[j] === '**') {
3166
+ partset[j] = '*';
3167
+ }
3168
+ }
3169
+ }
3170
+ }
3171
+ const { optimizationLevel = 1 } = this.options;
3172
+ if (optimizationLevel >= 2) {
3173
+ // aggressive optimization for the purpose of fs walking
3174
+ globParts = this.firstPhasePreProcess(globParts);
3175
+ globParts = this.secondPhasePreProcess(globParts);
3176
+ }
3177
+ else if (optimizationLevel >= 1) {
3178
+ // just basic optimizations to remove some .. parts
3179
+ globParts = this.levelOneOptimize(globParts);
3180
+ }
3181
+ else {
3182
+ // just collapse multiple ** portions into one
3183
+ globParts = this.adjascentGlobstarOptimize(globParts);
3184
+ }
3185
+ return globParts;
3186
+ }
3187
+ // just get rid of adjascent ** portions
3188
+ adjascentGlobstarOptimize(globParts) {
3189
+ return globParts.map(parts => {
3190
+ let gs = -1;
3191
+ while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
3192
+ let i = gs;
3193
+ while (parts[i + 1] === '**') {
3194
+ i++;
3195
+ }
3196
+ if (i !== gs) {
3197
+ parts.splice(gs, i - gs);
3198
+ }
3199
+ }
3200
+ return parts;
3201
+ });
3202
+ }
3203
+ // get rid of adjascent ** and resolve .. portions
3204
+ levelOneOptimize(globParts) {
3205
+ return globParts.map(parts => {
3206
+ parts = parts.reduce((set, part) => {
3207
+ const prev = set[set.length - 1];
3208
+ if (part === '**' && prev === '**') {
3209
+ return set;
3210
+ }
3211
+ if (part === '..') {
3212
+ if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
3213
+ set.pop();
3214
+ return set;
3215
+ }
3216
+ }
3217
+ set.push(part);
3218
+ return set;
3219
+ }, []);
3220
+ return parts.length === 0 ? [''] : parts;
3221
+ });
3222
+ }
3223
+ levelTwoFileOptimize(parts) {
3224
+ if (!Array.isArray(parts)) {
3225
+ parts = this.slashSplit(parts);
3226
+ }
3227
+ let didSomething = false;
3228
+ do {
3229
+ didSomething = false;
3230
+ // <pre>/<e>/<rest> -> <pre>/<rest>
3231
+ if (!this.preserveMultipleSlashes) {
3232
+ for (let i = 1; i < parts.length - 1; i++) {
3233
+ const p = parts[i];
3234
+ // don't squeeze out UNC patterns
3235
+ if (i === 1 && p === '' && parts[0] === '')
3236
+ continue;
3237
+ if (p === '.' || p === '') {
3238
+ didSomething = true;
3239
+ parts.splice(i, 1);
3240
+ i--;
3241
+ }
3242
+ }
3243
+ if (parts[0] === '.' &&
3244
+ parts.length === 2 &&
3245
+ (parts[1] === '.' || parts[1] === '')) {
3246
+ didSomething = true;
3247
+ parts.pop();
3248
+ }
3249
+ }
3250
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
3251
+ let dd = 0;
3252
+ while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
3253
+ const p = parts[dd - 1];
3254
+ if (p &&
3255
+ p !== '.' &&
3256
+ p !== '..' &&
3257
+ p !== '**' &&
3258
+ !(this.isWindows && /^[a-z]:$/i.test(p))) {
3259
+ didSomething = true;
3260
+ parts.splice(dd - 1, 2);
3261
+ dd -= 2;
3262
+ }
3263
+ }
3264
+ } while (didSomething);
3265
+ return parts.length === 0 ? [''] : parts;
3266
+ }
3267
+ // First phase: single-pattern processing
3268
+ // <pre> is 1 or more portions
3269
+ // <rest> is 1 or more portions
3270
+ // <p> is any portion other than ., .., '', or **
3271
+ // <e> is . or ''
3272
+ //
3273
+ // **/.. is *brutal* for filesystem walking performance, because
3274
+ // it effectively resets the recursive walk each time it occurs,
3275
+ // and ** cannot be reduced out by a .. pattern part like a regexp
3276
+ // or most strings (other than .., ., and '') can be.
3277
+ //
3278
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
3279
+ // <pre>/<e>/<rest> -> <pre>/<rest>
3280
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
3281
+ // **/**/<rest> -> **/<rest>
3282
+ //
3283
+ // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
3284
+ // this WOULD be allowed if ** did follow symlinks, or * didn't
3285
+ firstPhasePreProcess(globParts) {
3286
+ let didSomething = false;
3287
+ do {
3288
+ didSomething = false;
3289
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
3290
+ for (let parts of globParts) {
3291
+ let gs = -1;
3292
+ while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
3293
+ let gss = gs;
3294
+ while (parts[gss + 1] === '**') {
3295
+ // <pre>/**/**/<rest> -> <pre>/**/<rest>
3296
+ gss++;
3297
+ }
3298
+ // eg, if gs is 2 and gss is 4, that means we have 3 **
3299
+ // parts, and can remove 2 of them.
3300
+ if (gss > gs) {
3301
+ parts.splice(gs + 1, gss - gs);
3302
+ }
3303
+ let next = parts[gs + 1];
3304
+ const p = parts[gs + 2];
3305
+ const p2 = parts[gs + 3];
3306
+ if (next !== '..')
3307
+ continue;
3308
+ if (!p ||
3309
+ p === '.' ||
3310
+ p === '..' ||
3311
+ !p2 ||
3312
+ p2 === '.' ||
3313
+ p2 === '..') {
3314
+ continue;
3315
+ }
3316
+ didSomething = true;
3317
+ // edit parts in place, and push the new one
3318
+ parts.splice(gs, 1);
3319
+ const other = parts.slice(0);
3320
+ other[gs] = '**';
3321
+ globParts.push(other);
3322
+ gs--;
3323
+ }
3324
+ // <pre>/<e>/<rest> -> <pre>/<rest>
3325
+ if (!this.preserveMultipleSlashes) {
3326
+ for (let i = 1; i < parts.length - 1; i++) {
3327
+ const p = parts[i];
3328
+ // don't squeeze out UNC patterns
3329
+ if (i === 1 && p === '' && parts[0] === '')
3330
+ continue;
3331
+ if (p === '.' || p === '') {
3332
+ didSomething = true;
3333
+ parts.splice(i, 1);
3334
+ i--;
3335
+ }
3336
+ }
3337
+ if (parts[0] === '.' &&
3338
+ parts.length === 2 &&
3339
+ (parts[1] === '.' || parts[1] === '')) {
3340
+ didSomething = true;
3341
+ parts.pop();
3342
+ }
3343
+ }
3344
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
3345
+ let dd = 0;
3346
+ while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
3347
+ const p = parts[dd - 1];
3348
+ if (p && p !== '.' && p !== '..' && p !== '**') {
3349
+ didSomething = true;
3350
+ const needDot = dd === 1 && parts[dd + 1] === '**';
3351
+ const splin = needDot ? ['.'] : [];
3352
+ parts.splice(dd - 1, 2, ...splin);
3353
+ if (parts.length === 0)
3354
+ parts.push('');
3355
+ dd -= 2;
3356
+ }
3357
+ }
3358
+ }
3359
+ } while (didSomething);
3360
+ return globParts;
3361
+ }
3362
+ // second phase: multi-pattern dedupes
3363
+ // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
3364
+ // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
3365
+ // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
3366
+ //
3367
+ // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
3368
+ // ^-- not valid because ** doens't follow symlinks
3369
+ secondPhasePreProcess(globParts) {
3370
+ for (let i = 0; i < globParts.length - 1; i++) {
3371
+ for (let j = i + 1; j < globParts.length; j++) {
3372
+ const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
3373
+ if (matched) {
3374
+ globParts[i] = [];
3375
+ globParts[j] = matched;
3376
+ break;
3377
+ }
3378
+ }
3379
+ }
3380
+ return globParts.filter(gs => gs.length);
3381
+ }
3382
+ partsMatch(a, b, emptyGSMatch = false) {
3383
+ let ai = 0;
3384
+ let bi = 0;
3385
+ let result = [];
3386
+ let which = '';
3387
+ while (ai < a.length && bi < b.length) {
3388
+ if (a[ai] === b[bi]) {
3389
+ result.push(which === 'b' ? b[bi] : a[ai]);
3390
+ ai++;
3391
+ bi++;
3392
+ }
3393
+ else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
3394
+ result.push(a[ai]);
3395
+ ai++;
3396
+ }
3397
+ else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
3398
+ result.push(b[bi]);
3399
+ bi++;
3400
+ }
3401
+ else if (a[ai] === '*' &&
3402
+ b[bi] &&
3403
+ (this.options.dot || !b[bi].startsWith('.')) &&
3404
+ b[bi] !== '**') {
3405
+ if (which === 'b')
3406
+ return false;
3407
+ which = 'a';
3408
+ result.push(a[ai]);
3409
+ ai++;
3410
+ bi++;
3411
+ }
3412
+ else if (b[bi] === '*' &&
3413
+ a[ai] &&
3414
+ (this.options.dot || !a[ai].startsWith('.')) &&
3415
+ a[ai] !== '**') {
3416
+ if (which === 'a')
3417
+ return false;
3418
+ which = 'b';
3419
+ result.push(b[bi]);
3420
+ ai++;
3421
+ bi++;
3422
+ }
3423
+ else {
3424
+ return false;
3425
+ }
3426
+ }
3427
+ // if we fall out of the loop, it means they two are identical
3428
+ // as long as their lengths match
3429
+ return a.length === b.length && result;
3430
+ }
3431
+ parseNegate() {
3432
+ if (this.nonegate)
3433
+ return;
3434
+ const pattern = this.pattern;
3435
+ let negate = false;
3436
+ let negateOffset = 0;
3437
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
3438
+ negate = !negate;
3439
+ negateOffset++;
3440
+ }
3441
+ if (negateOffset)
3442
+ this.pattern = pattern.slice(negateOffset);
3443
+ this.negate = negate;
3444
+ }
3445
+ // set partial to true to test if, for example,
3446
+ // "/a/b" matches the start of "/*/b/*/d"
3447
+ // Partial means, if you run out of file before you run
3448
+ // out of pattern, then that's fine, as long as all
3449
+ // the parts match.
3450
+ matchOne(file, pattern, partial = false) {
3451
+ let fileStartIndex = 0;
3452
+ let patternStartIndex = 0;
3453
+ // UNC paths like //?/X:/... can match X:/... and vice versa
3454
+ // Drive letters in absolute drive or unc paths are always compared
3455
+ // case-insensitively.
3456
+ if (this.isWindows) {
3457
+ const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
3458
+ const fileUNC = !fileDrive &&
3459
+ file[0] === '' &&
3460
+ file[1] === '' &&
3461
+ file[2] === '?' &&
3462
+ /^[a-z]:$/i.test(file[3]);
3463
+ const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
3464
+ const patternUNC = !patternDrive &&
3465
+ pattern[0] === '' &&
3466
+ pattern[1] === '' &&
3467
+ pattern[2] === '?' &&
3468
+ typeof pattern[3] === 'string' &&
3469
+ /^[a-z]:$/i.test(pattern[3]);
3470
+ const fdi = fileUNC ? 3
3471
+ : fileDrive ? 0
3472
+ : undefined;
3473
+ const pdi = patternUNC ? 3
3474
+ : patternDrive ? 0
3475
+ : undefined;
3476
+ if (typeof fdi === 'number' && typeof pdi === 'number') {
3477
+ const [fd, pd] = [
3478
+ file[fdi],
3479
+ pattern[pdi],
3480
+ ];
3481
+ // start matching at the drive letter index of each
3482
+ if (fd.toLowerCase() === pd.toLowerCase()) {
3483
+ pattern[pdi] = fd;
3484
+ patternStartIndex = pdi;
3485
+ fileStartIndex = fdi;
3486
+ }
3487
+ }
3488
+ }
3489
+ // resolve and reduce . and .. portions in the file as well.
3490
+ // don't need to do the second phase, because it's only one string[]
3491
+ const { optimizationLevel = 1 } = this.options;
3492
+ if (optimizationLevel >= 2) {
3493
+ file = this.levelTwoFileOptimize(file);
3494
+ }
3495
+ if (pattern.includes(GLOBSTAR)) {
3496
+ return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
3497
+ }
3498
+ return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
3499
+ }
3500
+ #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
3501
+ // split the pattern into head, tail, and middle of ** delimited parts
3502
+ const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
3503
+ const lastgs = pattern.lastIndexOf(GLOBSTAR);
3504
+ // split the pattern up into globstar-delimited sections
3505
+ // the tail has to be at the end, and the others just have
3506
+ // to be found in order from the head.
3507
+ const [head, body, tail] = partial ?
3508
+ [
3509
+ pattern.slice(patternIndex, firstgs),
3510
+ pattern.slice(firstgs + 1),
3511
+ [],
3512
+ ]
3513
+ : [
3514
+ pattern.slice(patternIndex, firstgs),
3515
+ pattern.slice(firstgs + 1, lastgs),
3516
+ pattern.slice(lastgs + 1),
3517
+ ];
3518
+ // check the head, from the current file/pattern index.
3519
+ if (head.length) {
3520
+ const fileHead = file.slice(fileIndex, fileIndex + head.length);
3521
+ if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
3522
+ return false;
3523
+ }
3524
+ fileIndex += head.length;
3525
+ patternIndex += head.length;
3526
+ }
3527
+ // now we know the head matches!
3528
+ // if the last portion is not empty, it MUST match the end
3529
+ // check the tail
3530
+ let fileTailMatch = 0;
3531
+ if (tail.length) {
3532
+ // if head + tail > file, then we cannot possibly match
3533
+ if (tail.length + fileIndex > file.length)
3534
+ return false;
3535
+ // try to match the tail
3536
+ let tailStart = file.length - tail.length;
3537
+ if (this.#matchOne(file, tail, partial, tailStart, 0)) {
3538
+ fileTailMatch = tail.length;
3539
+ }
3540
+ else {
3541
+ // affordance for stuff like a/**/* matching a/b/
3542
+ // if the last file portion is '', and there's more to the pattern
3543
+ // then try without the '' bit.
3544
+ if (file[file.length - 1] !== '' ||
3545
+ fileIndex + tail.length === file.length) {
3546
+ return false;
3547
+ }
3548
+ tailStart--;
3549
+ if (!this.#matchOne(file, tail, partial, tailStart, 0)) {
3550
+ return false;
3551
+ }
3552
+ fileTailMatch = tail.length + 1;
3553
+ }
3554
+ }
3555
+ // now we know the tail matches!
3556
+ // the middle is zero or more portions wrapped in **, possibly
3557
+ // containing more ** sections.
3558
+ // so a/**/b/**/c/**/d has become **/b/**/c/**
3559
+ // if it's empty, it means a/**/b, just verify we have no bad dots
3560
+ // if there's no tail, so it ends on /**, then we must have *something*
3561
+ // after the head, or it's not a matc
3562
+ if (!body.length) {
3563
+ let sawSome = !!fileTailMatch;
3564
+ for (let i = fileIndex; i < file.length - fileTailMatch; i++) {
3565
+ const f = String(file[i]);
3566
+ sawSome = true;
3567
+ if (f === '.' ||
3568
+ f === '..' ||
3569
+ (!this.options.dot && f.startsWith('.'))) {
3570
+ return false;
3571
+ }
3572
+ }
3573
+ // in partial mode, we just need to get past all file parts
3574
+ return partial || sawSome;
3575
+ }
3576
+ // now we know that there's one or more body sections, which can
3577
+ // be matched anywhere from the 0 index (because the head was pruned)
3578
+ // through to the length-fileTailMatch index.
3579
+ // split the body up into sections, and note the minimum index it can
3580
+ // be found at (start with the length of all previous segments)
3581
+ // [section, before, after]
3582
+ const bodySegments = [[[], 0]];
3583
+ let currentBody = bodySegments[0];
3584
+ let nonGsParts = 0;
3585
+ const nonGsPartsSums = [0];
3586
+ for (const b of body) {
3587
+ if (b === GLOBSTAR) {
3588
+ nonGsPartsSums.push(nonGsParts);
3589
+ currentBody = [[], 0];
3590
+ bodySegments.push(currentBody);
3591
+ }
3592
+ else {
3593
+ currentBody[0].push(b);
3594
+ nonGsParts++;
3595
+ }
3596
+ }
3597
+ let i = bodySegments.length - 1;
3598
+ const fileLength = file.length - fileTailMatch;
3599
+ for (const b of bodySegments) {
3600
+ b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
3601
+ }
3602
+ return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
3603
+ }
3604
+ // return false for "nope, not matching"
3605
+ // return null for "not matching, cannot keep trying"
3606
+ #matchGlobStarBodySections(file,
3607
+ // pattern section, last possible position for it
3608
+ bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
3609
+ // take the first body segment, and walk from fileIndex to its "after"
3610
+ // value at the end
3611
+ // If it doesn't match at that position, we increment, until we hit
3612
+ // that final possible position, and give up.
3613
+ // If it does match, then advance and try to rest.
3614
+ // If any of them fail we keep walking forward.
3615
+ // this is still a bit recursively painful, but it's more constrained
3616
+ // than previous implementations, because we never test something that
3617
+ // can't possibly be a valid matching condition.
3618
+ const bs = bodySegments[bodyIndex];
3619
+ if (!bs) {
3620
+ // just make sure that there's no bad dots
3621
+ for (let i = fileIndex; i < file.length; i++) {
3622
+ sawTail = true;
3623
+ const f = file[i];
3624
+ if (f === '.' ||
3625
+ f === '..' ||
3626
+ (!this.options.dot && f.startsWith('.'))) {
3627
+ return false;
3628
+ }
3629
+ }
3630
+ return sawTail;
3631
+ }
3632
+ // have a non-globstar body section to test
3633
+ const [body, after] = bs;
3634
+ while (fileIndex <= after) {
3635
+ const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
3636
+ // if limit exceeded, no match. intentional false negative,
3637
+ // acceptable break in correctness for security.
3638
+ if (m && globStarDepth < this.maxGlobstarRecursion) {
3639
+ // match! see if the rest match. if so, we're done!
3640
+ const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
3641
+ if (sub !== false) {
3642
+ return sub;
3643
+ }
3644
+ }
3645
+ const f = file[fileIndex];
3646
+ if (f === '.' ||
3647
+ f === '..' ||
3648
+ (!this.options.dot && f.startsWith('.'))) {
3649
+ return false;
3650
+ }
3651
+ fileIndex++;
3652
+ }
3653
+ // walked off. no point continuing
3654
+ return partial || null;
3655
+ }
3656
+ #matchOne(file, pattern, partial, fileIndex, patternIndex) {
3657
+ let fi;
3658
+ let pi;
3659
+ let pl;
3660
+ let fl;
3661
+ for (fi = fileIndex,
3662
+ pi = patternIndex,
3663
+ fl = file.length,
3664
+ pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
3665
+ this.debug('matchOne loop');
3666
+ let p = pattern[pi];
3667
+ let f = file[fi];
3668
+ this.debug(pattern, p, f);
3669
+ // should be impossible.
3670
+ // some invalid regexp stuff in the set.
3671
+ /* c8 ignore start */
3672
+ if (p === false || p === GLOBSTAR) {
3673
+ return false;
3674
+ }
3675
+ /* c8 ignore stop */
3676
+ // something other than **
3677
+ // non-magic patterns just have to match exactly
3678
+ // patterns with magic have been turned into regexps.
3679
+ let hit;
3680
+ if (typeof p === 'string') {
3681
+ hit = f === p;
3682
+ this.debug('string match', p, f, hit);
3683
+ }
3684
+ else {
3685
+ hit = p.test(f);
3686
+ this.debug('pattern match', p, f, hit);
3687
+ }
3688
+ if (!hit)
3689
+ return false;
3690
+ }
3691
+ // Note: ending in / means that we'll get a final ""
3692
+ // at the end of the pattern. This can only match a
3693
+ // corresponding "" at the end of the file.
3694
+ // If the file ends in /, then it can only match a
3695
+ // a pattern that ends in /, unless the pattern just
3696
+ // doesn't have any more for it. But, a/b/ should *not*
3697
+ // match "a/b/*", even though "" matches against the
3698
+ // [^/]*? pattern, except in partial mode, where it might
3699
+ // simply not be reached yet.
3700
+ // However, a/b/ should still satisfy a/*
3701
+ // now either we fell off the end of the pattern, or we're done.
3702
+ if (fi === fl && pi === pl) {
3703
+ // ran out of pattern and filename at the same time.
3704
+ // an exact hit!
3705
+ return true;
3706
+ }
3707
+ else if (fi === fl) {
3708
+ // ran out of file, but still had pattern left.
3709
+ // this is ok if we're doing the match as part of
3710
+ // a glob fs traversal.
3711
+ return partial;
3712
+ }
3713
+ else if (pi === pl) {
3714
+ // ran out of pattern, still have file left.
3715
+ // this is only acceptable if we're on the very last
3716
+ // empty segment of a file with a trailing slash.
3717
+ // a/* should match a/b/
3718
+ return fi === fl - 1 && file[fi] === '';
3719
+ /* c8 ignore start */
3720
+ }
3721
+ else {
3722
+ // should be unreachable.
3723
+ throw new Error('wtf?');
3724
+ }
3725
+ /* c8 ignore stop */
3726
+ }
3727
+ braceExpand() {
3728
+ return braceExpand(this.pattern, this.options);
3729
+ }
3730
+ parse(pattern) {
3731
+ assertValidPattern(pattern);
3732
+ const options = this.options;
3733
+ // shortcuts
3734
+ if (pattern === '**')
3735
+ return GLOBSTAR;
3736
+ if (pattern === '')
3737
+ return '';
3738
+ // far and away, the most common glob pattern parts are
3739
+ // *, *.*, and *.<ext> Add a fast check method for those.
3740
+ let m;
3741
+ let fastTest = null;
3742
+ if ((m = pattern.match(starRE))) {
3743
+ fastTest = options.dot ? starTestDot : starTest;
3744
+ }
3745
+ else if ((m = pattern.match(starDotExtRE))) {
3746
+ fastTest = (options.nocase ?
3747
+ options.dot ?
3748
+ starDotExtTestNocaseDot
3749
+ : starDotExtTestNocase
3750
+ : options.dot ? starDotExtTestDot
3751
+ : starDotExtTest)(m[1]);
3752
+ }
3753
+ else if ((m = pattern.match(qmarksRE))) {
3754
+ fastTest = (options.nocase ?
3755
+ options.dot ?
3756
+ qmarksTestNocaseDot
3757
+ : qmarksTestNocase
3758
+ : options.dot ? qmarksTestDot
3759
+ : qmarksTest)(m);
3760
+ }
3761
+ else if ((m = pattern.match(starDotStarRE))) {
3762
+ fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
3763
+ }
3764
+ else if ((m = pattern.match(dotStarRE))) {
3765
+ fastTest = dotStarTest;
3766
+ }
3767
+ const re = AST.fromGlob(pattern, this.options).toMMPattern();
3768
+ if (fastTest && typeof re === 'object') {
3769
+ // Avoids overriding in frozen environments
3770
+ Reflect.defineProperty(re, 'test', { value: fastTest });
3771
+ }
3772
+ return re;
3773
+ }
3774
+ makeRe() {
3775
+ if (this.regexp || this.regexp === false)
3776
+ return this.regexp;
3777
+ // at this point, this.set is a 2d array of partial
3778
+ // pattern strings, or "**".
3779
+ //
3780
+ // It's better to use .match(). This function shouldn't
3781
+ // be used, really, but it's pretty convenient sometimes,
3782
+ // when you just want to work with a regex.
3783
+ const set = this.set;
3784
+ if (!set.length) {
3785
+ this.regexp = false;
3786
+ return this.regexp;
3787
+ }
3788
+ const options = this.options;
3789
+ const twoStar = options.noglobstar ? star
3790
+ : options.dot ? twoStarDot
3791
+ : twoStarNoDot;
3792
+ const flags = new Set(options.nocase ? ['i'] : []);
3793
+ // regexpify non-globstar patterns
3794
+ // if ** is only item, then we just do one twoStar
3795
+ // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
3796
+ // if ** is last, append (\/twoStar|) to previous
3797
+ // if ** is in the middle, append (\/|\/twoStar\/) to previous
3798
+ // then filter out GLOBSTAR symbols
3799
+ let re = set
3800
+ .map(pattern => {
3801
+ const pp = pattern.map(p => {
3802
+ if (p instanceof RegExp) {
3803
+ for (const f of p.flags.split(''))
3804
+ flags.add(f);
3805
+ }
3806
+ return (typeof p === 'string' ? regExpEscape(p)
3807
+ : p === GLOBSTAR ? GLOBSTAR
3808
+ : p._src);
3809
+ });
3810
+ pp.forEach((p, i) => {
3811
+ const next = pp[i + 1];
3812
+ const prev = pp[i - 1];
3813
+ if (p !== GLOBSTAR || prev === GLOBSTAR) {
3814
+ return;
3815
+ }
3816
+ if (prev === undefined) {
3817
+ if (next !== undefined && next !== GLOBSTAR) {
3818
+ pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
3819
+ }
3820
+ else {
3821
+ pp[i] = twoStar;
3822
+ }
3823
+ }
3824
+ else if (next === undefined) {
3825
+ pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
3826
+ }
3827
+ else if (next !== GLOBSTAR) {
3828
+ pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
3829
+ pp[i + 1] = GLOBSTAR;
3830
+ }
3831
+ });
3832
+ const filtered = pp.filter(p => p !== GLOBSTAR);
3833
+ // For partial matches, we need to make the pattern match
3834
+ // any prefix of the full path. We do this by generating
3835
+ // alternative patterns that match progressively longer prefixes.
3836
+ if (this.partial && filtered.length >= 1) {
3837
+ const prefixes = [];
3838
+ for (let i = 1; i <= filtered.length; i++) {
3839
+ prefixes.push(filtered.slice(0, i).join('/'));
3840
+ }
3841
+ return '(?:' + prefixes.join('|') + ')';
3842
+ }
3843
+ return filtered.join('/');
3844
+ })
3845
+ .join('|');
3846
+ // need to wrap in parens if we had more than one thing with |,
3847
+ // otherwise only the first will be anchored to ^ and the last to $
3848
+ const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
3849
+ // must match entire pattern
3850
+ // ending in a * or ** will make it less strict.
3851
+ re = '^' + open + re + close + '$';
3852
+ // In partial mode, '/' should always match as it's a valid prefix for any pattern
3853
+ if (this.partial) {
3854
+ re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
3855
+ }
3856
+ // can match anything, as long as it's not this.
3857
+ if (this.negate)
3858
+ re = '^(?!' + re + ').+$';
3859
+ try {
3860
+ this.regexp = new RegExp(re, [...flags].join(''));
3861
+ /* c8 ignore start */
3862
+ }
3863
+ catch {
3864
+ // should be impossible
3865
+ this.regexp = false;
3866
+ }
3867
+ /* c8 ignore stop */
3868
+ return this.regexp;
3869
+ }
3870
+ slashSplit(p) {
3871
+ // if p starts with // on windows, we preserve that
3872
+ // so that UNC paths aren't broken. Otherwise, any number of
3873
+ // / characters are coalesced into one, unless
3874
+ // preserveMultipleSlashes is set to true.
3875
+ if (this.preserveMultipleSlashes) {
3876
+ return p.split('/');
3877
+ }
3878
+ else if (this.isWindows && /^\/\/[^/]+/.test(p)) {
3879
+ // add an extra '' for the one we lose
3880
+ return ['', ...p.split(/\/+/)];
3881
+ }
3882
+ else {
3883
+ return p.split(/\/+/);
3884
+ }
3885
+ }
3886
+ match(f, partial = this.partial) {
3887
+ this.debug('match', f, this.pattern);
3888
+ // short-circuit in the case of busted things.
3889
+ // comments, etc.
3890
+ if (this.comment) {
3891
+ return false;
3892
+ }
3893
+ if (this.empty) {
3894
+ return f === '';
3895
+ }
3896
+ if (f === '/' && partial) {
3897
+ return true;
3898
+ }
3899
+ const options = this.options;
3900
+ // windows: need to use /, not \
3901
+ if (this.isWindows) {
3902
+ f = f.split('\\').join('/');
3903
+ }
3904
+ // treat the test path as a set of pathparts.
3905
+ const ff = this.slashSplit(f);
3906
+ this.debug(this.pattern, 'split', ff);
3907
+ // just ONE of the pattern sets in this.set needs to match
3908
+ // in order for it to be valid. If negating, then just one
3909
+ // match means that we have failed.
3910
+ // Either way, return on the first hit.
3911
+ const set = this.set;
3912
+ this.debug(this.pattern, 'set', set);
3913
+ // Find the basename of the path by looking for the last non-empty segment
3914
+ let filename = ff[ff.length - 1];
3915
+ if (!filename) {
3916
+ for (let i = ff.length - 2; !filename && i >= 0; i--) {
3917
+ filename = ff[i];
3918
+ }
3919
+ }
3920
+ for (const pattern of set) {
3921
+ let file = ff;
3922
+ if (options.matchBase && pattern.length === 1) {
3923
+ file = [filename];
3924
+ }
3925
+ const hit = this.matchOne(file, pattern, partial);
3926
+ if (hit) {
3927
+ if (options.flipNegate) {
3928
+ return true;
3929
+ }
3930
+ return !this.negate;
3931
+ }
3932
+ }
3933
+ // didn't get any hits. this is success if it's a negative
3934
+ // pattern, failure otherwise.
3935
+ if (options.flipNegate) {
3936
+ return false;
3937
+ }
3938
+ return this.negate;
3939
+ }
3940
+ static defaults(def) {
3941
+ return minimatch.defaults(def).Minimatch;
3942
+ }
3943
+ }
3944
+ /* c8 ignore stop */
3945
+ minimatch.AST = AST;
3946
+ minimatch.Minimatch = Minimatch;
3947
+ minimatch.escape = escape;
3948
+ minimatch.unescape = unescape;
3949
+
1525
3950
  class FluxionRouter {
1526
3951
  constructor(cx) {
1527
3952
  /**
@@ -1532,7 +3957,9 @@ class FluxionRouter {
1532
3957
  this.cx = cx;
1533
3958
  }
1534
3959
  makeStaticResource(filepath) {
1535
- const fullPath = path.join(this.cx.options.dir, filepath);
3960
+ const fullPath = path$1.isAbsolute(this.cx.options.dir)
3961
+ ? path$1.join(this.cx.options.dir, filepath)
3962
+ : path$1.join(process.cwd(), this.cx.options.dir, filepath);
1536
3963
  return async (normalized, _req, res) => {
1537
3964
  if (normalized.method !== 'GET' && normalized.method !== 'HEAD') {
1538
3965
  res.statusCode = 405;
@@ -1551,7 +3978,7 @@ class FluxionRouter {
1551
3978
  res.end('Not Found');
1552
3979
  return;
1553
3980
  }
1554
- const extension = path.extname(filepath).toLowerCase();
3981
+ const extension = path$1.extname(filepath).toLowerCase();
1555
3982
  const contentType = STATIC_CONTENT_TYPES[extension] ?? 'application/octet-stream';
1556
3983
  res.statusCode = 200;
1557
3984
  res.setHeader('Content-Type', contentType);
@@ -1569,29 +3996,44 @@ class FluxionRouter {
1569
3996
  };
1570
3997
  }
1571
3998
  /**
3999
+ * File registration logic with fast-glob pattern matching:
1572
4000
  * 1. Check if the path exists, if not, delete the handler;
1573
- * 2. If the file extension matches `routerExclude`, delete it and return early;
1574
- * 3. If the file extension matches `apiExts`, register it as an API, otherwise register as static resource;
4001
+ * 2. If file doesn't match include patterns, skip registration;
4002
+ * 3. If file matches exclude patterns, skip registration;
4003
+ * 4. If file matches apiInclude patterns, register as API handler;
4004
+ * 5. Otherwise, register as static resource.
1575
4005
  * @param filepath
1576
4006
  */
1577
4007
  register(filepath) {
1578
- const fullpath = path.join(process.cwd(), this.cx.options.dir, filepath);
4008
+ const fullpath = path$1.isAbsolute(this.cx.options.dir)
4009
+ ? path$1.join(this.cx.options.dir, filepath)
4010
+ : path$1.join(process.cwd(), this.cx.options.dir, filepath);
1579
4011
  if (!fs.existsSync(fullpath)) {
1580
4012
  this.handlers.delete(filepath);
1581
4013
  this.cx.logger.info(`[${filepath}] deleted`);
1582
4014
  return;
1583
4015
  }
1584
4016
  delete require.cache[fullpath];
1585
- const extension = path.extname(filepath).toLowerCase();
1586
- // Check if this file should be excluded from registration
1587
- if (this.cx.options.routerExclude.some((ext) => extension === ext)) {
4017
+ // Step 2: Check if file matches include patterns (default: all files)
4018
+ // If not matching, skip registration
4019
+ const matchesInclude = this.cx.options.include.some((pattern) => minimatch(filepath, pattern));
4020
+ if (!matchesInclude) {
4021
+ this.handlers.delete(filepath);
4022
+ this.cx.logger.info(`[${filepath}] skipped (not in include)`);
4023
+ return;
4024
+ }
4025
+ // Step 3: Check if file matches exclude patterns
4026
+ // If matching, skip registration
4027
+ const matchesExclude = this.cx.options.exclude.some((pattern) => minimatch(filepath, pattern));
4028
+ if (matchesExclude) {
1588
4029
  this.handlers.delete(filepath);
1589
4030
  this.cx.logger.info(`[${filepath}] excluded`);
1590
4031
  return;
1591
4032
  }
1592
- // register as api
1593
- // ! Files with extensions matching `apiExts` are considered as API handlers.
1594
- if (this.cx.options.apiExts.some((ext) => extension === ext)) {
4033
+ // Step 4 & 5: Check if file matches apiInclude patterns
4034
+ // If matching, register as API handler; otherwise as static resource
4035
+ const matchesApiInclude = this.cx.options.apiInclude.some((pattern) => minimatch(filepath, pattern));
4036
+ if (matchesApiInclude) {
1595
4037
  const handler = loadFunction({ modulePath: fullpath });
1596
4038
  this.handlers.set(filepath, handler);
1597
4039
  this.cx.logger.info(`[${filepath}] handler registered`);