Cars project 3 do dokończenia

This commit is contained in:
aplikacje committed 2026-11-05 10:50:57 +01:00
1 parent 3b96ac1be8
commit b3be59a011
159 files changed
+9794 -3786

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
# Blue Oak Model License
Version 1.0.0
## Purpose
This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.
## Acceptance
In order to receive this license, you must agree to its
rules. The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.
## Copyright
Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.
## Notices
You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
<https://blueoakcouncil.org/license/1.0.0>.
## Excuse
If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice. If you do not do so, your license
ends immediately.
## Patent
Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.
## Reliability
No contributor can revoke this license.
## No Liability
***As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim.***
+333
View File
@@ -0,0 +1,333 @@
# @isaacs/nonrecursive-glob-match
This is a glob matcher that can be applied to a single path
portion (ie, not `/`), which completes in polynomial time because
it doesn't compile to Regular Expressions or any other
backtrack-dependent algorithm.
## USAGE
```ts
import { Matcher } from '@isaacs/nonrecursive-glob-match'
const m = new Matcher('a*a!(y|z)')
console.log(m.test('abcay')) // false
console.log(m.test('abcax')) // true
console.log(m.test('aa')) // true
```
The pattern and the tested string must be a single path portion.
If either one contains a `/` character, the matcher throws an
error.
If you already split a path on `/`, use `m.testUnchecked(s)`. It
gives the same result as `m.test(s)`, but it does not check `s`
for a `/` character. This can make it faster, because some
patterns, such as `*.js`, then do not need to look at each
character. If `s` has a `/`, the result is not defined.
## Why
Patterns like this frustrate most glob matchers: `a*a*a*a*a*a*a`.
They can be used to take down servers if applied to untrusted
input. Fixing these vulns is like playing whack-a-mole with the
whole internet.
If compiled to a regular expression like
`/^a[^/]*a[^/]*a[^/]*a[^/]*a[^/]*a[^/]*a$/`, and then applied to
a path portion like `aaaaaaaaaaaaaaaaaaab`, the engine must check
every possible path through the pattern, constantly rewinding
back to the first character each time and trying a different
number of `a` characters matched against the `[^/]*` to see if it
matches. Because nothing matches, it must test every possible
path before ultimately giving up.
In contrast, the algorithm presented here is based on the
Thompson NFA paper from 1968, which tests every possible path
through the string at the same time, so that it only has to walk
the string one time. This algorithm is also implemented in the
RegExp engines used by `egrep` and `awk`, which is why those
tools are so fast, even when matching complicated RegExps against
extremely large strings.
The `Matcher` objects have a `test` method which takes a string,
just like a `RegExp` object, and can be a drop-in replacement for
the regular expressions used in minimatch and other matchers.
However, they are _not_ a complete drop-in replacement for a
RegExp, so be careful when replacing one with the other. (For
example, they do not capture, do not track match indexes, no
fancy RegExp features, etc.)
## Patterns Supported
Here are the patterns supported, and their effective state
machines drawn in lovely ASCII diagrams.
### `*` 0 or more of any character, not starting with `.`
```
--+-------------------+->
v ^
+<------------------+
v ^
+-->any character-->+
```
### `?`
```
-->any character-->
```
### `[<set>]`
```
-->character in set-->
```
This covers named posix sets like `[[:alpha:]]` as well as
character classes like `[a-b]`. (In this case, a regular
expression actually is compiled, but it's not subject to ReDoS,
becuase it's just a `/[a-z]/` style pattern tested against one
character at a time.)
### `@(e1|e2|...)`
"One" extglob.
```
--+--> e1 -->+-->
v ^
+--> e2 -->+
v ^
+--> e3 -->+
v ... ^
```
### `?(e1|e2|...)`
"Zero or one" extglob.
```
--+--------->+-->
v ^
+--> e1 -->+
v ^
+--> e2 -->+
v ^
+--> e3 -->+
v ... ^
```
### `*(e1|e2|...)`
"Zero or more" extglob.
```
--+--------->+-->
v ^
+<---------+
v ^
+--> e1 -->+
v ^
+--> e2 -->+
v ^
+--> e3 -->+
v ... ^
```
### `+(e1|e2|...)`
"One or more" extglob.
```
+<---------+
v ^
--+--> e1 -->+-->
v ^
+--> e2 -->+
v ^
+--> e3 -->+
v ... ^
```
### `!(e1|e2|...)`
"Negative" extglob.
The challenge with negation is that it opens the door to a whole
heap of edge cases. Especially, _any_ expression can be nested
inside the negation, and it needs to match anything at all, as
long as it _doesn't_ match one of the supplied patterns. This is
where it gets complicated, and past attempts have run into
problems.
We handle this by starting a "Run" that technically does recurse,
and thus can push the performance out from `O(n * m)` to
`O(n * m * r)` where `n` is the string length, `m` is the pattern
length, and `r` is the number of negative extglob portions it
contains. In practice, this is limited by the pattern length, and
still doesn't allow ReDOS-style explosive recursive backtracking,
so this is fine.
## Unicode Normalization
A char such as `é` can be one code point (U+00E9), or `e`
followed by a combining accent (U+0301). Some file systems, such
as on macOS, can give file names in the second form. These two
forms do not match by default.
Set the `normalize` option to normalize the pattern and each
tested string to the same form. Use `'NFC'`, `'NFD'`, `'NFKC'`,
or `'NFKD'`. `true` means `'NFC'`.
```ts
const m = new Matcher('café', { normalize: true })
m.test('café') // true
```
- Use NFC if you are not sure. With NFD and NFKD, `é` is two
code points. Then `?` does not match `é`, and `[é]` can not
match it.
- NFKC and NFKD also fold compatibility chars. For example, `fi`
matches `fi`, and full-width `A` matches `A`.
- Syntax is parsed before normalization. So, a char that
normalizes to a syntax char stays a literal. For example, with
NFKC, full-width `*` matches only `*` or `*`, and it is not a
wildcard.
- Each run of literal chars normalizes as one string. Each member
of a `[...]` class normalizes on its own, and stays as it is if
its normal form is more than one code point.
- A combining mark after a wildcard is its own literal, and does
not compose with the char that the wildcard matches. So, with
NFC, `?́` does not match `é`. With NFD, it does match,
because `é` is also two code points in the string. Patterns
match code points, not grapheme clusters.
- With `nocase`, normalization comes first, then case folding.
- The `/` check uses the strings as given. So, full-width `/`
does not cause an error.
## Differences from Bash
Bash 5 is the reference for this module, with two known
deviations.
### Dotfiles
If `dot` is not set, a string that starts with `.` only matches
if a literal `.` in the pattern matches that first character.
Extglobs before that `.` can match the empty string, and the
pattern can still match. For example, `!(.a|js)@(.*)` matches
`.a`, `.a.js`, and `.js`, because `!(.a|js)` matches the empty
string, and `@(.*)` matches the rest. Bash does not match these
dotfiles. See [this bug
report](https://lists.gnu.org/archive/html/bug-bash/2026-03/msg00034.html).
A `*` can never match at the start of a dotfile, even if it
matches the empty string. So, `*.js` does not match `.js`, as in
Bash.
### Case-insensitive matching
Bash compares chars with the case functions of the C library for
the current locale. So, the results can change with the locale
and the platform.
With `nocase`, this module uses Unicode simple case folding, one
code point at a time. This is the same folding that a JavaScript
RegExp uses with the `iu` flags. It does not change with the
locale, and literals, `[...]` classes, and ranges all use it.
- `Σ`, `σ`, and final sigma `ς` all match each other.
- The micro sign `µ` matches `μ` and `Μ`. The Kelvin sign `K`
matches `k`. The Angstrom sign `Å` matches `å`.
- `ẞ` matches `ß`, but `ß` does not match `ss`. A fold never
changes the number of chars, so ligatures such as `fi` do not
match `fi`.
- There are no Turkish rules. `I` matches `i`, but dotted `İ`
and dotless `ı` only match themselves.
## Algorithm
A glob pattern is parsed and compiled into a series of attached
state machines.
For example, the glob patttern `*(a|[c-d]|+(x|y|z))z` would
compile to a state machine something like the following flow
diagram:
```
-->+----------------------->+-->8 LITERAL(z)-->9 end
v ^
+<-----------------------6
v ^
0-->LITERAL(a)---------->|
v |
1-->CLASS(c-d)---------->|
v |
2-->+<---------------+-->+
v ^
3-->LITERAL(x)-->7
v |
4-->LITERAL(y)-->|
v |
5-->LITERAL(z)-->+
```
Then, for each character in the string, we walk through the
resulting graph until we find a test node.
These test nodes are all executed on the current character, and
for any tests pass, their output nodes are added to the walk, and
we proceed to walk until hitting a test node again.
Because all routes eventually get to the exit, which only passes
when the string is at its last character, we are guaranteed to
eventually either fail (and have no more states to process), or
exit with a match.
At each branching point, effectively we increase the memory usage
by a tiny bit to track which nodes are being processed, but
importantly, we _don't_ have to try all the way to the exit and
then backtrack recursively, storing multiple states of the string
in an exponential explosion.
A pattern like `a*a*a*a*a*a*a*a*a*a*a`, which could be naively
converted into a Regular Expression
`^a.*a.*a.*a.*a.*a.*a.*a.*a.*a.*a$`, would take over 33 seconds
to match the string `'a'.repeat(50) + 'b'` using standard
JavaScript regular expressions, because it must attempt every
possible grouping of characters, backtracking after each failure.
By contrast, this implementation can solve this match for either
a pass or failure in roughly the same amount of time, which
is bound by `C * N`, where `C` is the number of states in the
machine, and `N` is the length of the string, finishing both
failure and success cases in polynomial time.
Even on the first rather naive implementation in JavaScript, with
no optimizations for repeated `*` or other common tweaks, this
finishes in 300-400 µs for the pathological case described, and
as the numbers increase, this time rises roughly linearly.
That's somewhat worse than RegExp's performance in the _success_
case, which is around 40µs, but as it's around 100,000x faster in
the failure case, this is already quite promising. And, future
iterations of this can likely bring that performance closer to
the native RegExp implementation.
## Acknowledgement
The algorithm and ideas in this implementation are inspired,
borrowed, and at times outright stolen from [Russ
Cox](https://research.swtch.com)'s explanation of Ken Thompson's
work in [Regular Expression Matching Can Be Simple And
Fast](https://swtch.com/~rsc/regexp/regexp1.html). I am both
impressed by and grateful for their work.
The code here in this library was written entirely by me, [Isaac
Z. Schlueter](https://izs.me), and so you should not blame either
of them (or anyone else) for any problems it might have. You
should also not blame me. It's open source, after all, no
warrantees express or implied, etc.
@@ -0,0 +1,114 @@
import { type Form } from './parse-class.js';
export type { Form };
export type MatcherOptions = {
/** perform a case-insensitive match */
nocase?: boolean;
/** do not treat strings starting with `.` specially */
dot?: boolean;
/** do not match extglobs (treat them as normal strings) */
noext?: boolean;
/**
* normalize unicode in the pattern and the tested strings, with
* this form. `true` means `'NFC'`.
*/
normalize?: boolean | Form;
};
export type Item = {
t: 'lit';
ch: string;
} | {
t: 'any' | 'star';
} | {
t: 'class';
re: RegExp;
} | {
t: 'ext';
type: string;
alts: Item[][];
};
export type Token = Item | {
t: 'open';
type: string;
} | {
t: 'bar';
} | {
t: 'close';
};
export type NegNode = {
t: 'neg';
id: number;
sub: Node;
next: Node;
};
export type SplitNode = {
t: 'split';
id: number;
out: Node[];
};
export type Node = ({
t: 'lit';
id: number;
next: Node;
} & Lit) | {
t: 'any' | 'star';
id: number;
next: Node;
} | {
t: 'class';
id: number;
re: RegExp;
next: Node;
} | SplitNode | NegNode | {
t: 'match';
id: number;
};
/**
* A literal char. With `nocase:true`, `re` folds case, and `ascii`
* holds its results for ASCII chars, by char code: 1 for a match,
* and 2 for not.
*/
export type Lit = {
ch: string;
re?: RegExp;
ascii?: Uint8Array;
};
/**
* For each node id, the gen of the last state that has the node as
* a thread, and of the last state that walked through it. A state is
* built to the end before the states around it go on, and the nodes
* of a negated sub-pattern are only in its states (other than the
* match node, which is never marked). So one mark for each node is
* enough to know if the state being built has it. The Sims of a
* matcher never run at the same time, so they share one Marks.
*/
export type Marks = {
has: Float64Array;
seen: Float64Array;
gen: number;
};
/**
* A node in a graph with no splits or negations. Such a graph is a
* chain of nodes that each match one char, or a `*`.
*/
export type LinearNode = Exclude<Node, SplitNode | NegNode | {
t: 'match';
}>;
export declare class Matcher {
#private;
pattern: string;
options: MatcherOptions;
constructor(pattern: string, options?: MatcherOptions);
test(s: string): boolean;
/**
* The same as {@link Matcher#test}, but the string is not checked
* for `/` chars, so the result for a string that has one is not
* defined. Only use it for a string that is known to be one path
* portion, such as a part of a path that was split on `/`. It can
* be faster, because some patterns do not need to look at each char
* of the string.
*/
testUnchecked(s: string): boolean;
/** a readable listing of the state machine */
toString(): string;
}
//# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,EAAc,MAAM,kBAAkB,CAAA;AAExD,YAAY,EAAE,IAAI,EAAE,CAAA;AAEpB,MAAM,MAAM,cAAc,GAAG;IAC3B,uCAAuC;IACvC,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,uDAAuD;IACvD,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,2DAA2D;IAC3D,KAAK,CAAC,EAAE,OAAO,CAAA;IACf;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,GAAG,IAAI,CAAA;CAC3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AE,IAAI,CAAA;CAAE,GAClD,SAAS,GACT,OAAO,GACP;IAAE,CAAC,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAA;AA4B9B;;;;GAIG;AACH,MAAM,MAAM,GAAG,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,UAAU,CAAA;CAAE,CAAA;AAgPjE;;;;;;;;GAQG;AACH,MAAM,MAAM,KAAK,GAAG;IAAE,GAAG,EAAE,YAAY,CAAC;IAAC,IAAI,EAAE,YAAY,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAA;AA8P1E;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,OAAO,CAC9B,IAAI,EACJ,SAAS,GAAG,OAAO,GAAG;IAAE,CAAC,EAAE,OAAO,CAAA;CAAE,CACrC,CAAA;AA8GD,qBAAa,OAAO;;IAClB,OAAO,EAAE,MAAM,CAAA;IACf,OAAO,EAAE,cAAc,CAAA;gBAmCX,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;IAuDzD,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;IAexB;;;;;;;OAOG;IACH,aAAa,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;IAwFjC,8CAA8C;IAC9C,QAAQ,IAAI,MAAM;CAGnB"}
@@ -0,0 +1,762 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Matcher = void 0;
const parse_class_js_1 = require("./parse-class.js");
// the end of the pattern, or of a negated sub-pattern
const MATCH = { t: 'match', id: 0 };
const extTypes = '!?+*@';
const lit = (ch) => ({ t: 'lit', ch });
const reEscape = (s) => s.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&');
// a RegExp that only matches `s`, with unicode case folding
const newFoldRe = (s) => new RegExp(`^${reEscape(s)}$`, 'iu');
// foldRe for one literal char. The same chars are in most patterns,
// so keep them. A RegExp without the `g` or `y` flag has no state to
// share.
const foldCache = new Map();
const foldRe = (ch) => {
let re = foldCache.get(ch);
if (!re) {
re = newFoldRe(ch);
if (foldCache.size >= 1000)
foldCache.clear();
foldCache.set(ch, re);
}
return re;
};
const litMatch = (l, c) => {
if (c === l.ch)
return true;
if (!l.re)
return false;
const code = c.charCodeAt(0);
if (code >= 128)
return l.re.test(c);
const ascii = (l.ascii ??= new Uint8Array(128));
ascii[code] ||= l.re.test(c) ? 1 : 2;
return ascii[code] === 1;
};
const tokenize = (p, nocase, noext, form) => {
const toks = [];
for (let i = 0; i < p.length;) {
const c = String.fromCodePoint(p.codePointAt(i));
if (c === '\\') {
// a trailing \ is a literal \
const e = p.codePointAt(i + 1);
const ch = e === undefined ? c : String.fromCodePoint(e);
toks.push(lit(ch));
i += 1 + ch.length;
continue;
}
if (c === '[') {
const [re, consumed] = (0, parse_class_js_1.parseClass)(p, i, nocase, form);
if (consumed) {
toks.push({ t: 'class', re });
i += consumed;
continue;
}
}
if (!noext && extTypes.includes(c) && p[i + 1] === '(') {
toks.push({ t: 'open', type: c });
i += 2;
continue;
}
toks.push(!noext && c === '|' ? { t: 'bar' }
: !noext && c === ')' ? { t: 'close' }
: c === '*' ? { t: 'star' }
: c === '?' ? { t: 'any' }
: lit(c));
i += c.length;
}
return toks;
};
// map each open token index to the index of its close token
const pair = (toks) => {
const pairs = new Map();
const stack = [];
toks.forEach((tok, i) => {
if (tok.t === 'open')
stack.push(i);
else if (tok.t === 'close' && stack.length)
pairs.set(stack.pop(), i);
});
return pairs;
};
// build the alternatives between start and end. An open token that
// is not closed is never inside a closed extglob, so bar and close
// tokens are only literal at the top level.
const build = (toks, pairs, start, end, top) => {
let seq = [];
const alts = [seq];
for (let i = start; i < end; i++) {
const tok = toks[i];
const close = pairs.get(i);
if (tok.t === 'open' && close !== undefined) {
const sub = build(toks, pairs, i + 1, close, false);
seq.push({ t: 'ext', type: tok.type, alts: sub });
i = close;
}
else if (tok.t === 'bar' && !top) {
alts.push((seq = []));
}
else if (tok.t === 'open') {
seq.push(lit(tok.type), lit('('));
}
else if (tok.t === 'bar') {
seq.push(lit('|'));
}
else if (tok.t === 'close') {
seq.push(lit(')'));
}
else {
seq.push(tok);
}
}
return alts;
};
// normalize each run of literal chars as one string, so that a char
// and the combining marks after it compose (or decompose) together.
// Syntax is already parsed, so a char that normalizes to a syntax
// char (such as full-width `*` in NFKC) stays a literal.
const normalize = (items, form) => {
const out = [];
let run = '';
const flush = () => {
for (const ch of run.normalize(form))
out.push(lit(ch));
run = '';
};
for (const it of items) {
if (it.t === 'lit') {
run += it.ch;
continue;
}
flush();
out.push(it.t === 'ext' ?
{ ...it, alts: it.alts.map(a => normalize(a, form)) }
: it);
}
flush();
return out;
};
// the start node, and the number of node ids. Ids are dense, from 0
// for the match node.
const compile = (items, nocase) => {
let id = 1;
const split = (out) => ({ t: 'split', id: id++, out });
const seq = (items, next) => items.reduceRight((next, it) => item(it, next), next);
const item = (it, next) => {
switch (it.t) {
case 'lit':
const re = nocase ? foldRe(it.ch) : undefined;
return { t: 'lit', id: id++, ch: it.ch, re, next };
case 'any':
case 'star':
return { t: it.t, id: id++, next };
case 'class':
return { t: 'class', id: id++, re: it.re, next };
}
const alts = (next) => it.alts.map(a => seq(a, next));
switch (it.type) {
case '@':
return split(alts(next));
case '?':
return split([next, ...alts(next)]);
case '!':
return { t: 'neg', id: id++, sub: split(alts(MATCH)), next };
}
// * and +, loop back after each match
const after = split([]);
const entry = split(alts(after));
after.out.push(next, entry);
return it.type === '*' ? after : entry;
};
const start = seq(items, MATCH);
return [start, id];
};
// one line per node, in the order that a walk from the start
// reaches them. Edges point to node ids. The nodes of a negated
// sub-pattern are indented under their negation.
const show = (start) => {
const lines = [];
const seen = new Set();
const ref = (n) => (n.t === 'match' ? 'match' : String(n.id));
const walk = (n, indent) => {
if (n.t === 'match' || seen.has(n))
return;
seen.add(n);
const line = (desc) => lines.push(`${indent}${n.id}: ${desc}`);
switch (n.t) {
case 'split':
line(`split -> ${n.out.map(ref).join(', ')}`);
for (const o of n.out)
walk(o, indent);
return;
case 'neg':
line(`!(${ref(n.sub)}) -> ${ref(n.next)}`);
walk(n.sub, indent + ' ');
return walk(n.next, indent);
case 'lit':
line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`);
break;
case 'class':
line(`${n.re} -> ${ref(n.next)}`);
break;
default:
line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`);
}
walk(n.next, indent);
};
walk(start, '');
return [`start -> ${ref(start)}`, ...lines].join('\n');
};
// The threads at one position in the string. Each node thread is
// only kept once, and runs with the same state are only kept once,
// so that identical threads merge. The match node is not in
// `threads`, because it can not step. It sets `match` instead.
class State {
// set by the Sim, to mark the nodes that this state has
gen;
threads = [];
match = false;
runs = [];
// the sorted ids of the threads, with 0 for a match, once the
// state is done
ids = [];
constructor(gen) {
this.gen = gen;
}
// no threads, so nothing more can match
get dead() {
return !this.threads.length && !this.match && !this.runs.length;
}
}
// true if the two states hold the same threads
const sameState = (a, b) => {
if (a.ids.length !== b.ids.length)
return false;
if (a.runs.length !== b.runs.length)
return false;
if (a.ids.some((id, i) => id !== b.ids[i]))
return false;
return a.runs.every(r => b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)));
};
const marks = (size) => ({
has: new Float64Array(size),
seen: new Float64Array(size),
gen: 0,
});
class Sim {
// `.` and `..` only match literal dots, even with `dot:true`
dots;
// the string starts with `.`, and `dot:true` is not set
dotStart;
#marks;
constructor(dots, dotStart, marks) {
this.dots = dots;
this.dotStart = dotStart;
this.#marks = marks;
}
state() {
return new State(++this.#marks.gen);
}
// sort the ids of a state, once it has all of its threads
done(state) {
state.ids = state.threads.map(n => n.id).sort((a, b) => a - b);
if (state.match)
state.ids.unshift(MATCH.id);
return state;
}
// true the first time that the state walks through the node, so
// that loops in the graph stop
#visit(state, node) {
const { seen } = this.#marks;
if (seen[node.id] === state.gen)
return false;
seen[node.id] = state.gen;
return true;
}
#addThread(state, node) {
const { has } = this.#marks;
if (has[node.id] === state.gen)
return false;
has[node.id] = state.gen;
state.threads.push(node);
return true;
}
// wildcards only match a leading dot if `dot:true`. In a negated
// sub-pattern, this does not apply, because the negation itself
// can not match a leading dot.
restricted(i, top) {
return top && (this.dots || (this.dotStart && i === 0));
}
add(state, node, i, top) {
switch (node.t) {
case 'split':
if (!this.#visit(state, node))
return;
for (const o of node.out)
this.add(state, o, i, top);
return;
case 'neg':
if (!this.#visit(state, node))
return;
const sub = this.state();
this.add(sub, node.sub, i, false);
this.done(sub);
return this.addRun(state, { t: 'run', neg: node, state: sub }, i, top);
case 'star':
// a * can not start a dotfile, even if it matches nothing
if (this.restricted(i, top))
return;
if (this.#addThread(state, node))
this.add(state, node.next, i, top);
return;
case 'match':
state.match = true;
return;
default:
this.#addThread(state, node);
}
}
addRun(state, run, i, top) {
for (const r of state.runs) {
if (r.neg === run.neg && sameState(r.state, run.state))
return;
}
state.runs.push(run);
if (!run.state.match) {
this.add(state, run.neg.next, i, top);
}
}
// the threads after char `c`, at index `i`
step(state, c, i, top) {
const next = this.state();
for (const th of state.threads) {
switch (th.t) {
case 'lit':
if (litMatch(th, c)) {
this.add(next, th.next, i + 1, top);
}
break;
case 'any':
if (!this.restricted(i, top))
this.add(next, th.next, i + 1, top);
break;
case 'class':
if (!this.restricted(i, top) && th.re.test(c)) {
this.add(next, th.next, i + 1, top);
}
break;
case 'star':
if (!this.restricted(i, top))
this.add(next, th, i + 1, top);
}
}
if (!this.restricted(i, top)) {
for (const run of state.runs) {
// a sub-pattern with no threads can not match again, so the
// run stays the same
if (run.state.dead) {
this.addRun(next, run, i + 1, top);
continue;
}
const sub = this.step(run.state, c, i, false);
this.addRun(next, { t: 'run', neg: run.neg, state: sub }, i + 1, top);
}
}
return this.done(next);
}
}
// A canonical key for the threads in a state. States with the same
// key hold the same threads, so they match the same strings.
const stateKey = (state) => {
const ids = state.ids.join();
if (!state.runs.length)
return ids;
const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`);
return `${ids}|${runs.sort().join('|')}`;
};
// The cache can hold about this many chars of state keys and
// transitions. When it is full, it is cleared, so that a pattern
// can not use an unbounded amount of memory.
const DFA_BUDGET = 1 << 18;
// A cache of the states that the simulation reaches, built as the
// matcher is used. Each char of a string is then one Map lookup,
// once the states that it leads to are known.
//
// The dot rules only restrict the first char of a dotfile (strings
// that are only `.` or `..` do not use the cache). So a dotfile
// starts at its own state, which takes its first step with the
// restriction, and every other state takes steps without it.
class Dfa {
#start;
#states = new Map();
#size = 0;
#plain;
#dotStart;
#sim;
#dotSim;
constructor(start, marks) {
this.#start = start;
this.#sim = new Sim(false, false, marks);
this.#dotSim = new Sim(false, true, marks);
}
#make(state) {
return {
state,
match: state.match,
dead: state.dead,
next: new Map(),
};
}
#intern(state) {
const key = stateKey(state);
const found = this.#states.get(key);
if (found)
return found;
if (this.#size > DFA_BUDGET)
this.#clear();
const d = this.#make(state);
this.#states.set(key, d);
this.#size += key.length + 1;
return d;
}
#clear() {
this.#states.clear();
this.#size = 0;
this.#plain = undefined;
this.#dotStart = undefined;
}
start(dotStart) {
if (dotStart) {
if (this.#dotStart)
return this.#dotStart;
const state = this.#dotSim.state();
this.#dotSim.add(state, this.#start, 0, true);
return (this.#dotStart = this.#make(this.#dotSim.done(state)));
}
if (this.#plain)
return this.#plain;
const state = this.#sim.state();
this.#sim.add(state, this.#start, 0, true);
return (this.#plain = this.#intern(this.#sim.done(state)));
}
// the next state, after a miss in `d.ascii`
next(d, c) {
const code = c.charCodeAt(0);
const found = code < 128 ? undefined : d.next.get(c);
if (found)
return found;
// the dotfile start is not in the cache, so it is never shared
const n = d === this.#dotStart ?
this.#intern(this.#dotSim.step(d.state, c, 0, true))
: this.#intern(this.#sim.step(d.state, c, 1, true));
if (code < 128) {
if (!d.ascii) {
d.ascii = new Array(128);
this.#size += 128;
}
d.ascii[code] = n;
}
else {
d.next.set(c, n);
}
this.#size++;
return n;
}
}
// the nodes in order, if the graph is a single chain
const linear = (start) => {
const nodes = [];
for (let n = start; n.t !== 'match'; n = n.next) {
if (n.t === 'split' || n.t === 'neg')
return undefined;
nodes.push(n);
}
return nodes;
};
// Match a chain of nodes. Each node other than `*` matches exactly
// one char, so on a failure it is enough to go back to the last `*`
// and let it match one more char. This takes at most
// nodes.length * chars.length steps.
const testLinear = (nodes, chars, start, end) => {
let ni = 0;
let ci = start;
let starNi = -1;
let starCi = 0;
while (ci < end) {
const n = nodes[ni];
if (n?.t === 'star') {
starNi = ni++;
starCi = ci;
continue;
}
const c = chars[ci];
if (n &&
(n.t === 'any' ||
(n.t === 'lit' && litMatch(n, c)) ||
(n.t === 'class' && n.re.test(c)))) {
ni++;
ci++;
continue;
}
if (starNi === -1)
return false;
ni = starNi + 1;
ci = ++starCi;
}
while (nodes[ni]?.t === 'star')
ni++;
return ni === nodes.length;
};
// The least and most chars that the items can match. These are only
// bounds: a negation can match a string of any length, so it counts
// as 0 to Infinity.
const lengths = (items) => {
let min = 0;
let max = 0;
for (const it of items) {
const [lo, hi] = itemLengths(it);
min += lo;
max += hi;
}
return [min, max];
};
const itemLengths = (it) => {
if (it.t === 'star')
return [0, Infinity];
if (it.t !== 'ext')
return [1, 1];
if (it.type === '!')
return [0, Infinity];
const alts = it.alts.map(lengths);
const min = Math.min(...alts.map(a => a[0]));
const max = Math.max(...alts.map(a => a[1]));
// a loop of alternatives that only match the empty string is empty
const loop = max === 0 ? 0 : Infinity;
return (it.type === '@' ? [min, max]
: it.type === '?' ? [0, max]
: it.type === '*' ? [0, loop]
: [min, loop]);
};
// true if the chars from `start` match the literals
const hasAffix = (lits, chars, start) => {
for (let j = 0; j < lits.length; j++) {
if (!litMatch(lits[j], chars[start + j]))
return false;
}
return true;
};
// a `/`, or half of a surrogate pair
const slashOrSurrogate = /[/\ud800-\udfff]/;
const surrogate = /[\ud800-\udfff]/;
// a string can be indexed by code point, unless it has surrogate
// pairs
const codePoints = (s) => surrogate.test(s) ? [...s] : s;
const noSlash = (s) => {
if (s.includes('/')) {
throw new Error('can only match a single path portion, got: ' + s);
}
};
class Matcher {
pattern;
options;
#start;
// the number of node ids
#size;
#marks;
// the Sim for strings that are only `.` or `..`
#dotsSim;
// the string to compare, if the pattern has no magic. With
// `nocase:true`, the RegExp that folds case is made when it is
// first used.
#literal;
#literalFold = false;
#literalRe;
// the nodes between the prefix and suffix, if the graph is a
// single chain
#linear;
// the linear nodes are only `*` and `?`, so the length bounds and
// the prefix and suffix decide the match
#wild = false;
// the least and most chars that a match can have
#min = 0;
#max = Infinity;
// the literals that a match must start and end with. Each one
// matches exactly one char, and they are distinct items in the
// pattern, so a string that does not have them can not match.
#prefix = [];
#suffix = [];
// the prefix and suffix as strings, if they do not fold case
#prefixStr;
#suffixStr;
// there is a prefix or suffix to check
#affix = false;
#dfa;
#form;
constructor(pattern, options = {}) {
if (pattern.includes('/')) {
throw new Error('can only match a single path portion, got pattern: ' + pattern);
}
this.pattern = pattern;
this.options = options;
const { nocase = false, noext = false, normalize: n } = options;
this.#form = n === true ? 'NFC' : n || undefined;
// a pattern that is only an empty extglob is a literal string,
// except for `!()`, which matches any non-empty string
const literal = /^[?*+@]\(\)$/.test(pattern);
const toks = tokenize(pattern, nocase, noext || literal, this.#form);
let [items] = build(toks, pair(toks), 0, toks.length, true);
if (this.#form)
items = normalize(items, this.#form);
const [start, size] = compile(items, nocase);
this.#start = start;
this.#size = size;
if (items.every(it => it.t === 'lit')) {
this.#literal = items.map(it => it.ch).join('');
this.#literalFold = nocase;
}
else {
const lit = (it) => it.t !== 'lit' ? undefined
: nocase ? { ch: it.ch, re: foldRe(it.ch) }
: { ch: it.ch };
for (const it of items) {
const l = lit(it);
if (!l)
break;
this.#prefix.push(l);
}
for (let j = items.length - 1; j >= 0; j--) {
const l = lit(items[j]);
if (!l)
break;
this.#suffix.unshift(l);
}
this.#affix = !!(this.#prefix.length || this.#suffix.length);
if (!nocase) {
this.#prefixStr = this.#prefix.map(l => l.ch).join('');
this.#suffixStr = this.#suffix.map(l => l.ch).join('');
}
this.#linear = linear(this.#start)?.slice(this.#prefix.length, -this.#suffix.length || undefined);
this.#wild = !!this.#linear?.every(n => n.t === 'star' || n.t === 'any');
const [min, max] = lengths(items);
this.#min = min;
this.#max = max;
}
}
test(s) {
// The `/` check uses the string as given, so with normalization it
// is a separate step. Otherwise, one scan finds both a `/` and the
// surrogate pairs that stop the string being indexed by code point.
if (this.#form) {
noSlash(s);
return this.#test(s.normalize(this.#form));
}
if (slashOrSurrogate.test(s)) {
noSlash(s);
return this.#test(s, [...s]);
}
return this.#test(s, s);
}
/**
* The same as {@link Matcher#test}, but the string is not checked
* for `/` chars, so the result for a string that has one is not
* defined. Only use it for a string that is known to be one path
* portion, such as a part of a path that was split on `/`. It can
* be faster, because some patterns do not need to look at each char
* of the string.
*/
testUnchecked(s) {
return this.#test(this.#form ? s.normalize(this.#form) : s);
}
// Test a string that has no `/`. `chars` indexes it by code point.
// If it is not given, it is only found if a step needs it.
#test(s, chars) {
if (this.#literal !== undefined) {
return this.#literalFold ?
(this.#literalRe ??= newFoldRe(this.#literal)).test(s)
: s === this.#literal;
}
// the length check means that the prefix and suffix do not
// overlap. Without the chars, the length in code points is from
// half of the UTF-16 length (if each one is a surrogate pair) to
// all of it, which is often enough to know.
const min = this.#min;
const max = this.#max;
if (chars === undefined) {
const most = s.length;
const least = (most + 1) >> 1;
if (most < min || least > max)
return false;
if (least < min || most > max)
chars = codePoints(s);
}
if (chars !== undefined &&
(chars.length < min || chars.length > max)) {
return false;
}
const prefix = this.#prefix.length;
if (this.#affix) {
if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {
if (!s.startsWith(this.#prefixStr) ||
!s.endsWith(this.#suffixStr)) {
return false;
}
}
else {
chars ??= codePoints(s);
const end = chars.length - this.#suffix.length;
if (!hasAffix(this.#prefix, chars, 0) ||
!hasAffix(this.#suffix, chars, end)) {
return false;
}
}
}
const dotStart = !this.options.dot && s.startsWith('.');
if (this.#linear) {
// `.` and `..` only match literal dots, even with `dot:true`
if (s === '.' || s === '..')
return false;
// only a literal can match the leading dot. A `*` can not
// start a dotfile, even if it matches nothing.
if (dotStart && !prefix)
return false;
if (this.#wild)
return true;
chars ??= codePoints(s);
const end = chars.length - this.#suffix.length;
return testLinear(this.#linear, chars, prefix, end);
}
chars ??= codePoints(s);
if (s === '.' || s === '..') {
this.#marks ??= marks(this.#size);
const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks));
const start = sim.state();
sim.add(start, this.#start, 0, true);
let state = sim.done(start);
for (let i = 0; i < chars.length; i++) {
state = sim.step(state, chars[i], i, true);
}
return state.match;
}
this.#marks ??= marks(this.#size);
const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks));
let d = dfa.start(dotStart);
// read char codes from the string, so that a one-char string is
// only made for a cache miss
const str = chars === s;
for (let i = 0; i < chars.length; i++) {
if (d.dead)
return false;
const code = str ? s.charCodeAt(i) : chars[i].charCodeAt(0);
d = d.ascii?.[code] ?? dfa.next(d, chars[i]);
}
return d.match;
}
/** a readable listing of the state machine */
toString() {
return show(this.#start);
}
}
exports.Matcher = Matcher;
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,qDAAwD;AAyCxD,sDAAsD;AACtD,MAAM,KAAK,GAAS,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,EAAE,CAAA;AAEzC,MAAM,QAAQ,GAAG,OAAO,CAAA;AAExB,MAAM,GAAG,GAAG,CAAC,EAAU,EAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAA;AAEpD,MAAM,QAAQ,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,sBAAsB,EAAE,MAAM,CAAC,CAAA;AAEzE,4DAA4D;AAC5D,MAAM,SAAS,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IA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AC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAA;QACpB,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QACf,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,oEAAoE;AACpE,oEAAoE;AACpE,kEAAkE;AAClE,yDAAyD;AACzD,MAAM,SAAS,GAAG,CAAC,KAAa,EAAE,IAAU,EAAU,EAAE;IACtD,MAAM,GAAG,GAAW,EAAE,CAAA;IACtB,IAAI,GAAG,GAAG,EAAE,CAAA;IACZ,MAAM,KAAK,GAAG,GAAG,EAAELine truncated
@@ -0,0 +1,3 @@
"use strict";var D=(i,t)=>()=>{try{return t||i((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}};var E=D(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.parseClass=void 0;var G={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}"],"[:alpha:]":["\\p{L}\\p{Nl}"],"[:ascii:]":["\\x00-\\x7f"],"[:blank:]":["\\p{Zs}\\t"],"[:cntrl:]":["\\p{Cc}"],"[:digit:]":["\\p{Nd}"],"[:graph:]":["\\p{Z}\\p{C}",!0],"[:lower:]":["\\p{Ll}"],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}\\p{S}"],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f"],"[:upper:]":["\\p{Lu}"],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"],"[:xdigit:]":["A-Fa-f0-9"]},x=i=>i.replace(/[[\]\\-]/g,"\\$&"),A=/$./,H=(i,t,e=!1,s)=>{let h=p=>{let m=s?p.normalize(s):p;return[...m].length===1?m:p},n=t;if(i.charAt(n)!=="[")throw new Error("not in a brace expression");let o=[],a=[],r=n+1,l=!1,c=!1,u=!1,g=n,d="";t:for(;r<i.length;){let p=String.fromCodePoint(i.codePointAt(r));if((p==="!"||p==="^")&&r===n+1){u=!0,r++;continue}if(p==="]"&&l&&!c){g=r+1;break}if(l=!0,p==="\\"&&!c){c=!0,r++;continue}if(p==="["&&!c){for(let[R,[v,B]]of Object.entries(G))if(i.startsWith(R,r)){if(d)return[A,i.length-n];r+=R.length,B?a.push(v):o.push(v);continue t}}c=!1;let m=h(p);if(d){m.codePointAt(0)>d.codePointAt(0)?o.push(x(d)+"-"+x(m)):m===d&&o.push(x(m)),d="",r+=p.length;continue}if(i.startsWith("-]",r+p.length)){o.push(x(m+"-")),r+=p.length+1;continue}if(i.startsWith("-",r+p.length)){d=m,r+=p.length+1;continue}o.push(x(m)),r+=p.length}if(g<r)return[A,0];if(!o.length&&!a.length)return[A,i.length-n];let f="["+(u?"^":"")+o.join("")+"]",w="["+(u?"":"^")+a.join("")+"]",Z="^"+(o.length&&a.length?"("+f+"|"+w+")":o.length?f:w);return[new RegExp(Z,e?"iu":"u"),g-n]};S.parseClass=H});Object.defineProperty(exports,"__esModule",{value:!0});exports.Matcher=void 0;var J=E(),b={t:"match",id:0},K="!?+*@",y=i=>({t:"lit",ch:i}),Q=i=>i.replace(/[\\^$.*+?()[\]{}|/]/g,"\\$&"),L=i=>new RegExp(`^${Q(i)}$`,"iu"),C=new Map,W=i=>{let t=C.get(i);return t||(t=L(i),C.size>=1e3&&C.clear(),C.set(i,t)),t},z=(i,t)=>{if(t===i.ch)return!0;if(!i.re)return!1;let e=t.charCodeAt(0);if(e>=128)return i.re.test(t);let s=i.ascii??=new Uint8Array(128);return s[e]||=i.re.test(t)?1:2,s[e]===1},V=(i,t,e,s)=>{let h=[];for(let n=0;n<i.length;){let o=String.fromCodePoint(i.codePointAt(n));if(o==="\\"){let a=i.codePointAt(n+1),r=a===void 0?o:String.fromCodePoint(a);h.push(y(r)),n+=1+r.length;continue}if(o==="["){let[a,r]=(0,J.parseClass)(i,n,t,s);if(r){h.push({t:"class",re:a}),n+=r;continue}}if(!e&&K.includes(o)&&i[n+1]==="("){h.push({t:"open",type:o}),n+=2;continue}h.push(!e&&o==="|"?{t:"bar"}:!e&&o===")"?{t:"close"}:o==="*"?{t:"star"}:o==="?"?{t:"any"}:y(o)),n+=o.length}return h},X=i=>{let t=new Map,e=[];return i.forEach((s,h)=>{s.t==="open"?e.push(h):s.t==="close"&&e.length&&t.set(e.pop(),h)}),t},O=(i,t,e,s,h)=>{let n=[],o=[n];for(let a=e;a<s;a++){let r=i[a],l=t.get(a);if(r.t==="open"&&l!==void 0){let c=O(i,t,a+1,l,!1);n.push({t:"ext",type:r.type,alts:c}),a=l}else r.t==="bar"&&!h?o.push(n=[]):r.t==="open"?n.push(y(r.type),y("(")):r.t==="bar"?n.push(y("|")):r.t==="close"?n.push(y(")")):n.push(r)}return o},I=(i,t)=>{let e=[],s="",h=()=>{for(let n of s.normalize(t))e.push(y(n));s=""};for(let n of i){if(n.t==="lit"){s+=n.ch;continue}h(),e.push(n.t==="ext"?{...n,alts:n.alts.map(o=>I(o,t))}:n)}return h(),e},Y=(i,t)=>{let e=1,s=a=>({t:"split",id:e++,out:a}),h=(a,r)=>a.reduceRight((l,c)=>n(c,l),r),n=(a,r)=>{switch(a.t){case"lit":let g=t?W(a.ch):void 0;return{t:"lit",id:e++,ch:a.ch,re:g,next:r};case"any":case"star":return{t:a.t,id:e++,next:r};case"class":return{t:"class",id:e++,re:a.re,next:r}}let l=g=>a.alts.map(d=>h(d,g));switch(a.type){case"@":return s(l(r));case"?":return s([r,...l(r)]);case"!":return{t:"neg",id:e++,sub:s(l(b)),next:r}}let c=s([]),u=s(l(c));return c.out.push(r,u),a.type==="*"?c:u};return[h(i,b),e]},tt=i=>{let t=[],e=new Set,s=n=>n.t==="match"?"match":String(n.id),h=(n,o)=>{if(n.t==="match"||e.has(n))return;e.add(n);let a=r=>t.push(`${o}${n.id}: ${r}`);switch(n.t){case"split":a(`split -> ${n.out.map(s).join(", ")}`);for(let r of n.out)h(r,o);return;case"neg":return a(`!(${s(n.sub)}) -> ${s(n.next)}`),h(n.sub,o+" "),h(n.next,o);case"lit":a(`${JSON.stringify(n.ch)} -> ${s(n.next)}`);break;case"class":a(`${n.re} -> ${s(n.next)}`);break;default:a(`${n.t==="any"?"?":"*"} -> ${s(n.next)}`)}h(n.next,o)};return h(i,""),[`start -> ${s(i)}`,...t].join(`
`)},j=class{gen;threads=[];match=!1;runs=[];ids=[];constructor(t){this.gen=t}get dead(){return!this.threads.length&&!this.match&&!this.runs.length}},T=(i,t)=>i.ids.length!==t.ids.length||i.runs.length!==t.runs.length||i.ids.some((e,s)=>e!==t.ids[s])?!1:i.runs.every(e=>t.runs.some(s=>s.neg===e.neg&&T(s.state,e.state))),N=i=>({has:new Float64Array(i),seen:new Float64Array(i),gen:0}),$=class{dots;dotStart;#t;constructor(t,e,s){this.dots=t,this.dotStart=e,this.#t=s}state(){return new j(++this.#t.gen)}done(t){return t.ids=t.threads.map(e=>e.id).sort((e,s)=>e-s),t.match&&t.ids.unshift(b.id),t}#s(t,e){let{seen:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,!0)}#e(t,e){let{has:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,t.threads.push(e),!0)}restricted(t,e){return e&&(this.dots||this.dotStart&&t===0)}add(t,e,s,h){switch(e.t){case"split":if(!this.#s(t,e))return;for(let o of e.out)this.add(t,o,s,h);return;case"neg":if(!this.#s(t,e))return;let n=this.state();return this.add(n,e.sub,s,!1),this.done(n),this.addRun(t,{t:"run",neg:e,state:n},s,h);case"star":if(this.restricted(s,h))return;this.#e(t,e)&&this.add(t,e.next,s,h);return;case"match":t.match=!0;return;default:this.#e(t,e)}}addRun(t,e,s,h){for(let n of t.runs)if(n.neg===e.neg&&T(n.state,e.state))return;t.runs.push(e),e.state.match||this.add(t,e.neg.next,s,h)}step(t,e,s,h){let n=this.state();for(let o of t.threads)switch(o.t){case"lit":z(o,e)&&this.add(n,o.next,s+1,h);break;case"any":this.restricted(s,h)||this.add(n,o.next,s+1,h);break;case"class":!this.restricted(s,h)&&o.re.test(e)&&this.add(n,o.next,s+1,h);break;case"star":this.restricted(s,h)||this.add(n,o,s+1,h)}if(!this.restricted(s,h))for(let o of t.runs){if(o.state.dead){this.addRun(n,o,s+1,h);continue}let a=this.step(o.state,e,s,!1);this.addRun(n,{t:"run",neg:o.neg,state:a},s+1,h)}return this.done(n)}},q=i=>{let t=i.ids.join();if(!i.runs.length)return t;let e=i.runs.map(s=>`${s.neg.id}(${q(s.state)})`);return`${t}|${e.sort().join("|")}`},et=1<<18,P=class{#t;#s=new Map;#e=0;#c;#n;#i;#h;constructor(t,e){this.#t=t,this.#i=new $(!1,!1,e),this.#h=new $(!1,!0,e)}#o(t){return{state:t,match:t.match,dead:t.dead,next:new Map}}#u(t){let e=q(t),s=this.#s.get(e);if(s)return s;this.#e>et&&this.#f();let h=this.#o(t);return this.#s.set(e,h),this.#e+=e.length+1,h}#f(){this.#s.clear(),this.#e=0,this.#c=void 0,this.#n=void 0}start(t){if(t){if(this.#n)return this.#n;let s=this.#h.state();return this.#h.add(s,this.#t,0,!0),this.#n=this.#o(this.#h.done(s))}if(this.#c)return this.#c;let e=this.#i.state();return this.#i.add(e,this.#t,0,!0),this.#c=this.#u(this.#i.done(e))}next(t,e){let s=e.charCodeAt(0),h=s<128?void 0:t.next.get(e);if(h)return h;let n=t===this.#n?this.#u(this.#h.step(t.state,e,0,!0)):this.#u(this.#i.step(t.state,e,1,!0));return s<128?(t.ascii||(t.ascii=new Array(128),this.#e+=128),t.ascii[s]=n):t.next.set(e,n),this.#e++,n}},st=i=>{let t=[];for(let e=i;e.t!=="match";e=e.next){if(e.t==="split"||e.t==="neg")return;t.push(e)}return t},nt=(i,t,e,s)=>{let h=0,n=e,o=-1,a=0;for(;n<s;){let r=i[h];if(r?.t==="star"){o=h++,a=n;continue}let l=t[n];if(r&&(r.t==="any"||r.t==="lit"&&z(r,l)||r.t==="class"&&r.re.test(l))){h++,n++;continue}if(o===-1)return!1;h=o+1,n=++a}for(;i[h]?.t==="star";)h++;return h===i.length},U=i=>{let t=0,e=0;for(let s of i){let[h,n]=it(s);t+=h,e+=n}return[t,e]},it=i=>{if(i.t==="star")return[0,1/0];if(i.t!=="ext")return[1,1];if(i.type==="!")return[0,1/0];let t=i.alts.map(U),e=Math.min(...t.map(n=>n[0])),s=Math.max(...t.map(n=>n[1])),h=s===0?0:1/0;return i.type==="@"?[e,s]:i.type==="?"?[0,s]:i.type==="*"?[0,h]:[e,h]},_=(i,t,e)=>{for(let s=0;s<i.length;s++)if(!z(i[s],t[e+s]))return!1;return!0},rt=/[/\ud800-\udfff]/,ht=/[\ud800-\udfff]/,k=i=>ht.test(i)?[...i]:i,F=i=>{if(i.includes("/"))throw new Error("can only match a single path portion, got: "+i)},M=class{pattern;options;#t;#s;#e;#c;#n;#i=!1;#h;#o;#u=!1;#f=0;#m=1/0;#l=[];#a=[];#p;#g;#w=!1;#y;#r;constructor(t,e={}){if(t.includes("/"))throw new Error("can only match a single path portion, got pattern: "+t);this.pattern=t,this.options=e;let{nocase:s=!1,noext:h=!1,normalize:n}=e;this.#r=n===!0?"NFC":n||void 0;let o=/^[?*+@]\(\)$/.test(t),a=V(t,s,h||o,this.#r),[r]=O(a,X(a),0,a.length,!0);this.#r&&(r=I(r,this.#r));let[l,c]=Y(r,s);if(this.#t=l,this.#s=c,r.every(u=>u.t==="lit"))this.#n=r.map(u=>u.ch).join(""),this.#i=s;else{let u=f=>f.t!=="lit"?void 0:s?{ch:f.ch,re:W(f.ch)}:{ch:f.ch};for(let f of r){let w=u(f);if(!w)break;this.#l.push(w)}for(let f=r.length-1;f>=0;f--){let w=u(r[f]);if(!w)break;this.#a.unshift(w)}this.#w=!!(this.#l.length||this.#a.length),s||(this.#p=this.#l.map(f=>f.ch).join(""),this.#g=this.#a.map(f=>f.ch).join("")),this.#o=st(this.#t)?.slice(this.#l.length,-this.#a.length||void 0),this.#u=!!this.#o?.every(f=>f.t==="star"||f.t==="any");let[g,d]=U(r);this.#f=g,this.#m=d}}test(t){return this.#r?(F(t),this.#d(t.normalize(this.#r))):rt.test(t)?(F(t),this.#d(t,[...t])):this.#d(t,t)}testUnchecked(t){return this.#d(this.#r?t.normalize(this. Line truncated
//# sourceMappingURL=index.min.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../src/parse-class.ts", "../../src/index.ts"],
"sourcesContent": ["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { <posix class>: [<translation>, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}'],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}'],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f'],\n '[:blank:]': ['\\\\p{Zs}\\\\t'],\n '[:cntrl:]': ['\\\\p{Cc}'],\n '[:digit:]': ['\\\\p{Nd}'],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true],\n '[:lower:]': ['\\\\p{Ll}'],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}\\\\p{S}'],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f'],\n '[:upper:]': ['\\\\p{Lu}'],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}'],\n '[:xdigit:]': ['A-Fa-f0-9'],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n\nexport type ParseClassResult = [re: RegExp, consumed: number]\n\nexport type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'\n\nconst noMatch = /$./\n\n// Takes a glob string at a posix brace expression. Returns a RegExp\n// that tests one character, and the number of glob chars consumed.\n// If the class is not closed, consumed is 0, and the `[` must be\n// treated as a literal character.\n// Out of order ranges are removed. If nothing is left, the RegExp\n// is `/$./`, and the rest of the glob is consumed, so that the\n// whole glob cannot match.\nexport const parseClass = (\n glob: string,\n position: number,\n nocase: boolean = false,\n form?: Form,\n): ParseClassResult => {\n // normalize one class member, if it stays one code point\n const norm = (c: string) => {\n const n = form ? c.normalize(form) : c\n return [...n].length === 1 ? n : c\n }\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = String.fromCodePoint(glob.codePointAt(i)!)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return [noMatch, glob.length - pos]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n const n = norm(c)\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))\n } else if (n === rangeStart) {\n ranges.push(braceEscape(n))\n }\n rangeStart = ''\n i += c.length\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c<more...>] or c] at this point\n if (glob.startsWith('-]', i + c.length)) {\n ranges.push(braceEscape(n + '-'))\n i += c.length + 1\n continue\n }\n if (glob.startsWith('-', i + c.length)) {\n rangeStart = n\n i += c.length + 1\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(n))\n i += c.length\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return [noMatch, 0]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return [noMatch, glob.length - pos]\n }\n\n const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'\n const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'\n const comb =\n '^' +\n (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n : ranges.length ? sranges\n : snegs)\n\n return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]\n}\n", "import { type Form, parseClass } from './parse-class.js'\nLine truncated
"mappings": "0MAIA,IAAMA,EAA0D,CAC9D,YAAa,CAAC,sBAAsB,EACpC,YAAa,CAAC,eAAe,EAC7B,YAAa,CAAC,aAAuB,EACrC,YAAa,CAAC,YAAY,EAC1B,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,eAAgB,EAAI,EAClC,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,SAAU,EAAI,EAC5B,YAAa,CAAC,cAAc,EAC5B,YAAa,CAAC,uBAAuB,EACrC,YAAa,CAAC,SAAS,EACvB,WAAY,CAAC,6BAA6B,EAC1C,aAAc,CAAC,WAAW,GAKtBC,EAAeC,GAAcA,EAAE,QAAQ,YAAa,MAAM,EAM1DC,EAAU,KASHC,EAAa,CACxBC,EACAC,EACAC,EAAkB,GAClBC,IACoB,CAEpB,IAAMC,EAAQC,GAAa,CACzB,IAAMC,EAAIH,EAAOE,EAAE,UAAUF,CAAI,EAAIE,EACrC,MAAO,CAAC,GAAGC,CAAC,EAAE,SAAW,EAAIA,EAAID,CACnC,EACME,EAAMN,EAEZ,GAAID,EAAK,OAAOO,CAAG,IAAM,IACvB,MAAM,IAAI,MAAM,2BAA2B,EAG7C,IAAMC,EAAmB,CAAA,EACnBC,EAAiB,CAAA,EAEn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,QACF,CACAD,EAAK,EACLF,EAAI,KACFG,EAAG,IAAM,MACP,CAAE,GAAGA,EAAI,KAAMA,EAALine truncated
"names": ["posixClasses", "braceEscape", "s", "noMatch", "parseClass", "glob", "position", "nocase", "form", "norm", "c", "n", "pos", "ranges", "negs", "i", "sawStart", "escaping", "negate", "endPos", "rangeStart", "WHILE", "cls", "unip", "neg", "sranges", "snegs", "comb", "exports", "parse_class_js_1", "MATCH", "extTypes", "lit", "ch", "reEscape", "s", "newFoldRe", "foldCache", "foldRe", "re", "litMatch", "l", "c", "code", "ascii", "tokenize", "p", "nocase", "noext", "form", "toks", "i", "e", "consumed", "pair", "pairs", "stack", "tok", "build", "start", "end", "top", "seq", "alts", "close", "sub", "normalize", "items", "out", "run", "flush", "it", "a", "compile", "id", "split", "next", "item", "after", "entry", "show", "lines", "seen", "ref", "walk", "indent", "line", "desc", "o", "State", "gen", "sameState", "b", "r", "marks", "size", "Sim", "#marks", "dots", "dotStart", "state", "n", "#visit", "node", "#addThread", "has", "th", "stateKey", "ids", "runs", "DFA_BUDGET", "Dfa", "#start", "#states", "#size", "#plain", "#dotStart", "#sim", "#dotSim", "#make", "#intern", "key", "found", "#clear", "d", "linear", "nodes", "testLinear", "chars", "ni", "ci", "starNi", "starCi", "lengths", "min", "max", "lo", "hi", "itemLengths", "loop", "hasAffix", "lits", "j", "slashOrSurrogate", "surrogate", "codePoints", "noSlash", "Matcher", "#dotsSim", "#literal", "#literalFold", "#literalRe", "#linear", "#wild", "#min", "#max", "#prefix", "#suffix", "#prefixStr", "#suffixStr", "#affix", "#dfa", "#form", "pattern", "options", "literal", "#test", "most", "least", "prefix", "sim", "dfa", "str"]
}
@@ -0,0 +1,3 @@
{
"type": "commonjs"
}
@@ -0,0 +1,4 @@
export type ParseClassResult = [re: RegExp, consumed: number];
export type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD';
export declare const parseClass: (glob: string, position: number, nocase?: boolean, form?: Form) => ParseClassResult;
//# sourceMappingURL=parse-class.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"parse-class.d.ts","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":"AAyBA,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;AAE7D,MAAM,MAAM,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAA;AAWlD,eAAO,MAAM,UAAU,GACrB,MAAM,MAAM,EACZ,UAAU,MAAM,EAChB,SAAQ,OAAe,EACvB,OAAO,IAAI,KACV,gBAkHF,CAAA"}
@@ -0,0 +1,142 @@
"use strict";
// translate the various posix character classes into unicode properties
// this works across all unicode locales
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseClass = void 0;
// { <posix class>: [<translation>, negated]
const posixClasses = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}'],
'[:alpha:]': ['\\p{L}\\p{Nl}'],
'[:ascii:]': ['\\x' + '00-\\x' + '7f'],
'[:blank:]': ['\\p{Zs}\\t'],
'[:cntrl:]': ['\\p{Cc}'],
'[:digit:]': ['\\p{Nd}'],
'[:graph:]': ['\\p{Z}\\p{C}', true],
'[:lower:]': ['\\p{Ll}'],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}\\p{S}'],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f'],
'[:upper:]': ['\\p{Lu}'],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}'],
'[:xdigit:]': ['A-Fa-f0-9'],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
const noMatch = /$./;
// Takes a glob string at a posix brace expression. Returns a RegExp
// that tests one character, and the number of glob chars consumed.
// If the class is not closed, consumed is 0, and the `[` must be
// treated as a literal character.
// Out of order ranges are removed. If nothing is left, the RegExp
// is `/$./`, and the rest of the glob is consumed, so that the
// whole glob cannot match.
const parseClass = (glob, position, nocase = false, form) => {
// normalize one class member, if it stays one code point
const norm = (c) => {
const n = form ? c.normalize(form) : c;
return [...n].length === 1 ? n : c;
};
const pos = position;
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression');
}
/* c8 ignore stop */
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = '';
WHILE: while (i < glob.length) {
const c = String.fromCodePoint(glob.codePointAt(i));
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === '\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return [noMatch, glob.length - pos];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
continue WHILE;
}
}
}
// now it's just a normal character, effectively
escaping = false;
const n = norm(c);
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (n.codePointAt(0) > rangeStart.codePointAt(0)) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n));
}
else if (n === rangeStart) {
ranges.push(braceEscape(n));
}
rangeStart = '';
i += c.length;
continue;
}
// now might be the start of a range.
// can be either c-d or c-] or c<more...>] or c] at this point
if (glob.startsWith('-]', i + c.length)) {
ranges.push(braceEscape(n + '-'));
i += c.length + 1;
continue;
}
if (glob.startsWith('-', i + c.length)) {
rangeStart = n;
i += c.length + 1;
continue;
}
// not the start of a range, just a single character
ranges.push(braceEscape(n));
i += c.length;
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return [noMatch, 0];
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return [noMatch, glob.length - pos];
}
const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']';
const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']';
const comb = '^' +
(ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
: ranges.length ? sranges
: snegs);
return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos];
};
exports.parseClass = parseClass;
//# sourceMappingURL=parse-class.js.map
@@ -0,0 +1 @@
{"version":3,"file":"parse-class.js","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":";AAAA,wEAAwE;AACxE,wCAAwC;;;AAExC,4CAA4C;AAC5C,MAAM,YAAY,GAA8C;IAC9D,WAAW,EAAE,CAAC,sBAAsB,CAAC;IACrC,WAAW,EAAE,CAAC,eAAe,CAAC;IAC9B,WAAW,EAAE,CAAC,KAAK,GAAG,QAAQ,GAAG,IAAI,CAAC;IACtC,WAAW,EAAE,CAAC,YAAY,CAAC;IAC3B,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,cAAc,EAAE,IAAI,CAAC;IACnC,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,cAAc,CAAC;IAC7B,WAAW,EAAE,CAAC,uBAAuB,CAAC;IACtC,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,UAAU,EAAE,CAAC,6BAA6B,CAAC;IAC3C,YAAY,EAAE,CAAC,WAAW,CAAC;CAC5B,CAAA;AAED,+DAA+D;AAC/D,mBAAmB;AACnB,MAAM,WAAW,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,MAAM,CAAC,CAAA;AAMjE,MAAM,OAAO,GAAG,IAAI,CAAA;AAEpB,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gE;IAChE,kEAAkE;IAClE,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QACnC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,CAAA;IACrC,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,CAAA;IACjE,MAAM,KAAK,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,CAAA;IAC7D,MAAM,IAAI,GACR,GAAG;QACH,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG;YACjE,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO;gBACzB,CAAC,CAAC,KAAK,CAAC,CAAA;IAEV,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC,CAAA;AAC9D,CAAC,CAAA;AAvHY,QAAA,UAAU,cAuHtB","sourcesContent":["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { <posix class>: [<translation>, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolLine truncated
@@ -0,0 +1,114 @@
import { type Form } from './parse-class.js';
export type { Form };
export type MatcherOptions = {
/** perform a case-insensitive match */
nocase?: boolean;
/** do not treat strings starting with `.` specially */
dot?: boolean;
/** do not match extglobs (treat them as normal strings) */
noext?: boolean;
/**
* normalize unicode in the pattern and the tested strings, with
* this form. `true` means `'NFC'`.
*/
normalize?: boolean | Form;
};
export type Item = {
t: 'lit';
ch: string;
} | {
t: 'any' | 'star';
} | {
t: 'class';
re: RegExp;
} | {
t: 'ext';
type: string;
alts: Item[][];
};
export type Token = Item | {
t: 'open';
type: string;
} | {
t: 'bar';
} | {
t: 'close';
};
export type NegNode = {
t: 'neg';
id: number;
sub: Node;
next: Node;
};
export type SplitNode = {
t: 'split';
id: number;
out: Node[];
};
export type Node = ({
t: 'lit';
id: number;
next: Node;
} & Lit) | {
t: 'any' | 'star';
id: number;
next: Node;
} | {
t: 'class';
id: number;
re: RegExp;
next: Node;
} | SplitNode | NegNode | {
t: 'match';
id: number;
};
/**
* A literal char. With `nocase:true`, `re` folds case, and `ascii`
* holds its results for ASCII chars, by char code: 1 for a match,
* and 2 for not.
*/
export type Lit = {
ch: string;
re?: RegExp;
ascii?: Uint8Array;
};
/**
* For each node id, the gen of the last state that has the node as
* a thread, and of the last state that walked through it. A state is
* built to the end before the states around it go on, and the nodes
* of a negated sub-pattern are only in its states (other than the
* match node, which is never marked). So one mark for each node is
* enough to know if the state being built has it. The Sims of a
* matcher never run at the same time, so they share one Marks.
*/
export type Marks = {
has: Float64Array;
seen: Float64Array;
gen: number;
};
/**
* A node in a graph with no splits or negations. Such a graph is a
* chain of nodes that each match one char, or a `*`.
*/
export type LinearNode = Exclude<Node, SplitNode | NegNode | {
t: 'match';
}>;
export declare class Matcher {
#private;
pattern: string;
options: MatcherOptions;
constructor(pattern: string, options?: MatcherOptions);
test(s: string): boolean;
/**
* The same as {@link Matcher#test}, but the string is not checked
* for `/` chars, so the result for a string that has one is not
* defined. Only use it for a string that is known to be one path
* portion, such as a part of a path that was split on `/`. It can
* be faster, because some patterns do not need to look at each char
* of the string.
*/
testUnchecked(s: string): boolean;
/** a readable listing of the state machine */
toString(): string;
}
//# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/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M;CAGnB"}
@@ -0,0 +1,758 @@
import { parseClass } from './parse-class.js';
// the end of the pattern, or of a negated sub-pattern
const MATCH = { t: 'match', id: 0 };
const extTypes = '!?+*@';
const lit = (ch) => ({ t: 'lit', ch });
const reEscape = (s) => s.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&');
// a RegExp that only matches `s`, with unicode case folding
const newFoldRe = (s) => new RegExp(`^${reEscape(s)}$`, 'iu');
// foldRe for one literal char. The same chars are in most patterns,
// so keep them. A RegExp without the `g` or `y` flag has no state to
// share.
const foldCache = new Map();
const foldRe = (ch) => {
let re = foldCache.get(ch);
if (!re) {
re = newFoldRe(ch);
if (foldCache.size >= 1000)
foldCache.clear();
foldCache.set(ch, re);
}
return re;
};
const litMatch = (l, c) => {
if (c === l.ch)
return true;
if (!l.re)
return false;
const code = c.charCodeAt(0);
if (code >= 128)
return l.re.test(c);
const ascii = (l.ascii ??= new Uint8Array(128));
ascii[code] ||= l.re.test(c) ? 1 : 2;
return ascii[code] === 1;
};
const tokenize = (p, nocase, noext, form) => {
const toks = [];
for (let i = 0; i < p.length;) {
const c = String.fromCodePoint(p.codePointAt(i));
if (c === '\\') {
// a trailing \ is a literal \
const e = p.codePointAt(i + 1);
const ch = e === undefined ? c : String.fromCodePoint(e);
toks.push(lit(ch));
i += 1 + ch.length;
continue;
}
if (c === '[') {
const [re, consumed] = parseClass(p, i, nocase, form);
if (consumed) {
toks.push({ t: 'class', re });
i += consumed;
continue;
}
}
if (!noext && extTypes.includes(c) && p[i + 1] === '(') {
toks.push({ t: 'open', type: c });
i += 2;
continue;
}
toks.push(!noext && c === '|' ? { t: 'bar' }
: !noext && c === ')' ? { t: 'close' }
: c === '*' ? { t: 'star' }
: c === '?' ? { t: 'any' }
: lit(c));
i += c.length;
}
return toks;
};
// map each open token index to the index of its close token
const pair = (toks) => {
const pairs = new Map();
const stack = [];
toks.forEach((tok, i) => {
if (tok.t === 'open')
stack.push(i);
else if (tok.t === 'close' && stack.length)
pairs.set(stack.pop(), i);
});
return pairs;
};
// build the alternatives between start and end. An open token that
// is not closed is never inside a closed extglob, so bar and close
// tokens are only literal at the top level.
const build = (toks, pairs, start, end, top) => {
let seq = [];
const alts = [seq];
for (let i = start; i < end; i++) {
const tok = toks[i];
const close = pairs.get(i);
if (tok.t === 'open' && close !== undefined) {
const sub = build(toks, pairs, i + 1, close, false);
seq.push({ t: 'ext', type: tok.type, alts: sub });
i = close;
}
else if (tok.t === 'bar' && !top) {
alts.push((seq = []));
}
else if (tok.t === 'open') {
seq.push(lit(tok.type), lit('('));
}
else if (tok.t === 'bar') {
seq.push(lit('|'));
}
else if (tok.t === 'close') {
seq.push(lit(')'));
}
else {
seq.push(tok);
}
}
return alts;
};
// normalize each run of literal chars as one string, so that a char
// and the combining marks after it compose (or decompose) together.
// Syntax is already parsed, so a char that normalizes to a syntax
// char (such as full-width `*` in NFKC) stays a literal.
const normalize = (items, form) => {
const out = [];
let run = '';
const flush = () => {
for (const ch of run.normalize(form))
out.push(lit(ch));
run = '';
};
for (const it of items) {
if (it.t === 'lit') {
run += it.ch;
continue;
}
flush();
out.push(it.t === 'ext' ?
{ ...it, alts: it.alts.map(a => normalize(a, form)) }
: it);
}
flush();
return out;
};
// the start node, and the number of node ids. Ids are dense, from 0
// for the match node.
const compile = (items, nocase) => {
let id = 1;
const split = (out) => ({ t: 'split', id: id++, out });
const seq = (items, next) => items.reduceRight((next, it) => item(it, next), next);
const item = (it, next) => {
switch (it.t) {
case 'lit':
const re = nocase ? foldRe(it.ch) : undefined;
return { t: 'lit', id: id++, ch: it.ch, re, next };
case 'any':
case 'star':
return { t: it.t, id: id++, next };
case 'class':
return { t: 'class', id: id++, re: it.re, next };
}
const alts = (next) => it.alts.map(a => seq(a, next));
switch (it.type) {
case '@':
return split(alts(next));
case '?':
return split([next, ...alts(next)]);
case '!':
return { t: 'neg', id: id++, sub: split(alts(MATCH)), next };
}
// * and +, loop back after each match
const after = split([]);
const entry = split(alts(after));
after.out.push(next, entry);
return it.type === '*' ? after : entry;
};
const start = seq(items, MATCH);
return [start, id];
};
// one line per node, in the order that a walk from the start
// reaches them. Edges point to node ids. The nodes of a negated
// sub-pattern are indented under their negation.
const show = (start) => {
const lines = [];
const seen = new Set();
const ref = (n) => (n.t === 'match' ? 'match' : String(n.id));
const walk = (n, indent) => {
if (n.t === 'match' || seen.has(n))
return;
seen.add(n);
const line = (desc) => lines.push(`${indent}${n.id}: ${desc}`);
switch (n.t) {
case 'split':
line(`split -> ${n.out.map(ref).join(', ')}`);
for (const o of n.out)
walk(o, indent);
return;
case 'neg':
line(`!(${ref(n.sub)}) -> ${ref(n.next)}`);
walk(n.sub, indent + ' ');
return walk(n.next, indent);
case 'lit':
line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`);
break;
case 'class':
line(`${n.re} -> ${ref(n.next)}`);
break;
default:
line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`);
}
walk(n.next, indent);
};
walk(start, '');
return [`start -> ${ref(start)}`, ...lines].join('\n');
};
// The threads at one position in the string. Each node thread is
// only kept once, and runs with the same state are only kept once,
// so that identical threads merge. The match node is not in
// `threads`, because it can not step. It sets `match` instead.
class State {
// set by the Sim, to mark the nodes that this state has
gen;
threads = [];
match = false;
runs = [];
// the sorted ids of the threads, with 0 for a match, once the
// state is done
ids = [];
constructor(gen) {
this.gen = gen;
}
// no threads, so nothing more can match
get dead() {
return !this.threads.length && !this.match && !this.runs.length;
}
}
// true if the two states hold the same threads
const sameState = (a, b) => {
if (a.ids.length !== b.ids.length)
return false;
if (a.runs.length !== b.runs.length)
return false;
if (a.ids.some((id, i) => id !== b.ids[i]))
return false;
return a.runs.every(r => b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)));
};
const marks = (size) => ({
has: new Float64Array(size),
seen: new Float64Array(size),
gen: 0,
});
class Sim {
// `.` and `..` only match literal dots, even with `dot:true`
dots;
// the string starts with `.`, and `dot:true` is not set
dotStart;
#marks;
constructor(dots, dotStart, marks) {
this.dots = dots;
this.dotStart = dotStart;
this.#marks = marks;
}
state() {
return new State(++this.#marks.gen);
}
// sort the ids of a state, once it has all of its threads
done(state) {
state.ids = state.threads.map(n => n.id).sort((a, b) => a - b);
if (state.match)
state.ids.unshift(MATCH.id);
return state;
}
// true the first time that the state walks through the node, so
// that loops in the graph stop
#visit(state, node) {
const { seen } = this.#marks;
if (seen[node.id] === state.gen)
return false;
seen[node.id] = state.gen;
return true;
}
#addThread(state, node) {
const { has } = this.#marks;
if (has[node.id] === state.gen)
return false;
has[node.id] = state.gen;
state.threads.push(node);
return true;
}
// wildcards only match a leading dot if `dot:true`. In a negated
// sub-pattern, this does not apply, because the negation itself
// can not match a leading dot.
restricted(i, top) {
return top && (this.dots || (this.dotStart && i === 0));
}
add(state, node, i, top) {
switch (node.t) {
case 'split':
if (!this.#visit(state, node))
return;
for (const o of node.out)
this.add(state, o, i, top);
return;
case 'neg':
if (!this.#visit(state, node))
return;
const sub = this.state();
this.add(sub, node.sub, i, false);
this.done(sub);
return this.addRun(state, { t: 'run', neg: node, state: sub }, i, top);
case 'star':
// a * can not start a dotfile, even if it matches nothing
if (this.restricted(i, top))
return;
if (this.#addThread(state, node))
this.add(state, node.next, i, top);
return;
case 'match':
state.match = true;
return;
default:
this.#addThread(state, node);
}
}
addRun(state, run, i, top) {
for (const r of state.runs) {
if (r.neg === run.neg && sameState(r.state, run.state))
return;
}
state.runs.push(run);
if (!run.state.match) {
this.add(state, run.neg.next, i, top);
}
}
// the threads after char `c`, at index `i`
step(state, c, i, top) {
const next = this.state();
for (const th of state.threads) {
switch (th.t) {
case 'lit':
if (litMatch(th, c)) {
this.add(next, th.next, i + 1, top);
}
break;
case 'any':
if (!this.restricted(i, top))
this.add(next, th.next, i + 1, top);
break;
case 'class':
if (!this.restricted(i, top) && th.re.test(c)) {
this.add(next, th.next, i + 1, top);
}
break;
case 'star':
if (!this.restricted(i, top))
this.add(next, th, i + 1, top);
}
}
if (!this.restricted(i, top)) {
for (const run of state.runs) {
// a sub-pattern with no threads can not match again, so the
// run stays the same
if (run.state.dead) {
this.addRun(next, run, i + 1, top);
continue;
}
const sub = this.step(run.state, c, i, false);
this.addRun(next, { t: 'run', neg: run.neg, state: sub }, i + 1, top);
}
}
return this.done(next);
}
}
// A canonical key for the threads in a state. States with the same
// key hold the same threads, so they match the same strings.
const stateKey = (state) => {
const ids = state.ids.join();
if (!state.runs.length)
return ids;
const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`);
return `${ids}|${runs.sort().join('|')}`;
};
// The cache can hold about this many chars of state keys and
// transitions. When it is full, it is cleared, so that a pattern
// can not use an unbounded amount of memory.
const DFA_BUDGET = 1 << 18;
// A cache of the states that the simulation reaches, built as the
// matcher is used. Each char of a string is then one Map lookup,
// once the states that it leads to are known.
//
// The dot rules only restrict the first char of a dotfile (strings
// that are only `.` or `..` do not use the cache). So a dotfile
// starts at its own state, which takes its first step with the
// restriction, and every other state takes steps without it.
class Dfa {
#start;
#states = new Map();
#size = 0;
#plain;
#dotStart;
#sim;
#dotSim;
constructor(start, marks) {
this.#start = start;
this.#sim = new Sim(false, false, marks);
this.#dotSim = new Sim(false, true, marks);
}
#make(state) {
return {
state,
match: state.match,
dead: state.dead,
next: new Map(),
};
}
#intern(state) {
const key = stateKey(state);
const found = this.#states.get(key);
if (found)
return found;
if (this.#size > DFA_BUDGET)
this.#clear();
const d = this.#make(state);
this.#states.set(key, d);
this.#size += key.length + 1;
return d;
}
#clear() {
this.#states.clear();
this.#size = 0;
this.#plain = undefined;
this.#dotStart = undefined;
}
start(dotStart) {
if (dotStart) {
if (this.#dotStart)
return this.#dotStart;
const state = this.#dotSim.state();
this.#dotSim.add(state, this.#start, 0, true);
return (this.#dotStart = this.#make(this.#dotSim.done(state)));
}
if (this.#plain)
return this.#plain;
const state = this.#sim.state();
this.#sim.add(state, this.#start, 0, true);
return (this.#plain = this.#intern(this.#sim.done(state)));
}
// the next state, after a miss in `d.ascii`
next(d, c) {
const code = c.charCodeAt(0);
const found = code < 128 ? undefined : d.next.get(c);
if (found)
return found;
// the dotfile start is not in the cache, so it is never shared
const n = d === this.#dotStart ?
this.#intern(this.#dotSim.step(d.state, c, 0, true))
: this.#intern(this.#sim.step(d.state, c, 1, true));
if (code < 128) {
if (!d.ascii) {
d.ascii = new Array(128);
this.#size += 128;
}
d.ascii[code] = n;
}
else {
d.next.set(c, n);
}
this.#size++;
return n;
}
}
// the nodes in order, if the graph is a single chain
const linear = (start) => {
const nodes = [];
for (let n = start; n.t !== 'match'; n = n.next) {
if (n.t === 'split' || n.t === 'neg')
return undefined;
nodes.push(n);
}
return nodes;
};
// Match a chain of nodes. Each node other than `*` matches exactly
// one char, so on a failure it is enough to go back to the last `*`
// and let it match one more char. This takes at most
// nodes.length * chars.length steps.
const testLinear = (nodes, chars, start, end) => {
let ni = 0;
let ci = start;
let starNi = -1;
let starCi = 0;
while (ci < end) {
const n = nodes[ni];
if (n?.t === 'star') {
starNi = ni++;
starCi = ci;
continue;
}
const c = chars[ci];
if (n &&
(n.t === 'any' ||
(n.t === 'lit' && litMatch(n, c)) ||
(n.t === 'class' && n.re.test(c)))) {
ni++;
ci++;
continue;
}
if (starNi === -1)
return false;
ni = starNi + 1;
ci = ++starCi;
}
while (nodes[ni]?.t === 'star')
ni++;
return ni === nodes.length;
};
// The least and most chars that the items can match. These are only
// bounds: a negation can match a string of any length, so it counts
// as 0 to Infinity.
const lengths = (items) => {
let min = 0;
let max = 0;
for (const it of items) {
const [lo, hi] = itemLengths(it);
min += lo;
max += hi;
}
return [min, max];
};
const itemLengths = (it) => {
if (it.t === 'star')
return [0, Infinity];
if (it.t !== 'ext')
return [1, 1];
if (it.type === '!')
return [0, Infinity];
const alts = it.alts.map(lengths);
const min = Math.min(...alts.map(a => a[0]));
const max = Math.max(...alts.map(a => a[1]));
// a loop of alternatives that only match the empty string is empty
const loop = max === 0 ? 0 : Infinity;
return (it.type === '@' ? [min, max]
: it.type === '?' ? [0, max]
: it.type === '*' ? [0, loop]
: [min, loop]);
};
// true if the chars from `start` match the literals
const hasAffix = (lits, chars, start) => {
for (let j = 0; j < lits.length; j++) {
if (!litMatch(lits[j], chars[start + j]))
return false;
}
return true;
};
// a `/`, or half of a surrogate pair
const slashOrSurrogate = /[/\ud800-\udfff]/;
const surrogate = /[\ud800-\udfff]/;
// a string can be indexed by code point, unless it has surrogate
// pairs
const codePoints = (s) => surrogate.test(s) ? [...s] : s;
const noSlash = (s) => {
if (s.includes('/')) {
throw new Error('can only match a single path portion, got: ' + s);
}
};
export class Matcher {
pattern;
options;
#start;
// the number of node ids
#size;
#marks;
// the Sim for strings that are only `.` or `..`
#dotsSim;
// the string to compare, if the pattern has no magic. With
// `nocase:true`, the RegExp that folds case is made when it is
// first used.
#literal;
#literalFold = false;
#literalRe;
// the nodes between the prefix and suffix, if the graph is a
// single chain
#linear;
// the linear nodes are only `*` and `?`, so the length bounds and
// the prefix and suffix decide the match
#wild = false;
// the least and most chars that a match can have
#min = 0;
#max = Infinity;
// the literals that a match must start and end with. Each one
// matches exactly one char, and they are distinct items in the
// pattern, so a string that does not have them can not match.
#prefix = [];
#suffix = [];
// the prefix and suffix as strings, if they do not fold case
#prefixStr;
#suffixStr;
// there is a prefix or suffix to check
#affix = false;
#dfa;
#form;
constructor(pattern, options = {}) {
if (pattern.includes('/')) {
throw new Error('can only match a single path portion, got pattern: ' + pattern);
}
this.pattern = pattern;
this.options = options;
const { nocase = false, noext = false, normalize: n } = options;
this.#form = n === true ? 'NFC' : n || undefined;
// a pattern that is only an empty extglob is a literal string,
// except for `!()`, which matches any non-empty string
const literal = /^[?*+@]\(\)$/.test(pattern);
const toks = tokenize(pattern, nocase, noext || literal, this.#form);
let [items] = build(toks, pair(toks), 0, toks.length, true);
if (this.#form)
items = normalize(items, this.#form);
const [start, size] = compile(items, nocase);
this.#start = start;
this.#size = size;
if (items.every(it => it.t === 'lit')) {
this.#literal = items.map(it => it.ch).join('');
this.#literalFold = nocase;
}
else {
const lit = (it) => it.t !== 'lit' ? undefined
: nocase ? { ch: it.ch, re: foldRe(it.ch) }
: { ch: it.ch };
for (const it of items) {
const l = lit(it);
if (!l)
break;
this.#prefix.push(l);
}
for (let j = items.length - 1; j >= 0; j--) {
const l = lit(items[j]);
if (!l)
break;
this.#suffix.unshift(l);
}
this.#affix = !!(this.#prefix.length || this.#suffix.length);
if (!nocase) {
this.#prefixStr = this.#prefix.map(l => l.ch).join('');
this.#suffixStr = this.#suffix.map(l => l.ch).join('');
}
this.#linear = linear(this.#start)?.slice(this.#prefix.length, -this.#suffix.length || undefined);
this.#wild = !!this.#linear?.every(n => n.t === 'star' || n.t === 'any');
const [min, max] = lengths(items);
this.#min = min;
this.#max = max;
}
}
test(s) {
// The `/` check uses the string as given, so with normalization it
// is a separate step. Otherwise, one scan finds both a `/` and the
// surrogate pairs that stop the string being indexed by code point.
if (this.#form) {
noSlash(s);
return this.#test(s.normalize(this.#form));
}
if (slashOrSurrogate.test(s)) {
noSlash(s);
return this.#test(s, [...s]);
}
return this.#test(s, s);
}
/**
* The same as {@link Matcher#test}, but the string is not checked
* for `/` chars, so the result for a string that has one is not
* defined. Only use it for a string that is known to be one path
* portion, such as a part of a path that was split on `/`. It can
* be faster, because some patterns do not need to look at each char
* of the string.
*/
testUnchecked(s) {
return this.#test(this.#form ? s.normalize(this.#form) : s);
}
// Test a string that has no `/`. `chars` indexes it by code point.
// If it is not given, it is only found if a step needs it.
#test(s, chars) {
if (this.#literal !== undefined) {
return this.#literalFold ?
(this.#literalRe ??= newFoldRe(this.#literal)).test(s)
: s === this.#literal;
}
// the length check means that the prefix and suffix do not
// overlap. Without the chars, the length in code points is from
// half of the UTF-16 length (if each one is a surrogate pair) to
// all of it, which is often enough to know.
const min = this.#min;
const max = this.#max;
if (chars === undefined) {
const most = s.length;
const least = (most + 1) >> 1;
if (most < min || least > max)
return false;
if (least < min || most > max)
chars = codePoints(s);
}
if (chars !== undefined &&
(chars.length < min || chars.length > max)) {
return false;
}
const prefix = this.#prefix.length;
if (this.#affix) {
if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {
if (!s.startsWith(this.#prefixStr) ||
!s.endsWith(this.#suffixStr)) {
return false;
}
}
else {
chars ??= codePoints(s);
const end = chars.length - this.#suffix.length;
if (!hasAffix(this.#prefix, chars, 0) ||
!hasAffix(this.#suffix, chars, end)) {
return false;
}
}
}
const dotStart = !this.options.dot && s.startsWith('.');
if (this.#linear) {
// `.` and `..` only match literal dots, even with `dot:true`
if (s === '.' || s === '..')
return false;
// only a literal can match the leading dot. A `*` can not
// start a dotfile, even if it matches nothing.
if (dotStart && !prefix)
return false;
if (this.#wild)
return true;
chars ??= codePoints(s);
const end = chars.length - this.#suffix.length;
return testLinear(this.#linear, chars, prefix, end);
}
chars ??= codePoints(s);
if (s === '.' || s === '..') {
this.#marks ??= marks(this.#size);
const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks));
const start = sim.state();
sim.add(start, this.#start, 0, true);
let state = sim.done(start);
for (let i = 0; i < chars.length; i++) {
state = sim.step(state, chars[i], i, true);
}
return state.match;
}
this.#marks ??= marks(this.#size);
const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks));
let d = dfa.start(dotStart);
// read char codes from the string, so that a one-char string is
// only made for a cache miss
const str = chars === s;
for (let i = 0; i < chars.length; i++) {
if (d.dead)
return false;
const code = str ? s.charCodeAt(i) : chars[i].charCodeAt(0);
d = d.ascii?.[code] ?? dfa.next(d, chars[i]);
}
return d.match;
}
/** a readable listing of the state machine */
toString() {
return show(this.#start);
}
}
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAyCxD,sDAAsD;AACtD,MAAM,KAAK,GAAS,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,EAAE,CAAA;AAEzC,MAAM,QAAQ,GAAG,OAAO,CAAA;AAExB,MAAM,G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CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAA;QACnC,CAAC;aAAM,IAAI,GAAG,CAAC,CAAC,KAAK,KAAK,EAAE,CAAC;YAC3B,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAA;QACpB,CAAC;aAAM,IAAI,GAAG,CAAC,CAAC,KAAK,OAAO,EAAE,CAAC;YAC7B,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAA;QACpB,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QACf,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,oEAAoE;AACpE,oEAAoE;AACpE,kEAAkE;AAClE,yDAAyD;AACzD,MAAM,SAAS,GAAG,CAAC,KAAa,EAAE,IAAU,EAAU,EAAE;IACtD,MAAM,GAAG,GAAW,EAAE,CAAA;IACtB,IAAI,GAAG,GAAG,EAAE,CAAA;IACZ,MAALine truncated
@@ -0,0 +1,3 @@
var D={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}"],"[:alpha:]":["\\p{L}\\p{Nl}"],"[:ascii:]":["\\x00-\\x7f"],"[:blank:]":["\\p{Zs}\\t"],"[:cntrl:]":["\\p{Cc}"],"[:digit:]":["\\p{Nd}"],"[:graph:]":["\\p{Z}\\p{C}",!0],"[:lower:]":["\\p{Ll}"],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}\\p{S}"],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f"],"[:upper:]":["\\p{Lu}"],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"],"[:xdigit:]":["A-Fa-f0-9"]},y=i=>i.replace(/[[\]\\-]/g,"\\$&"),A=/$./,E=(i,t,e=!1,s)=>{let h=p=>{let m=s?p.normalize(s):p;return[...m].length===1?m:p},n=t;if(i.charAt(n)!=="[")throw new Error("not in a brace expression");let o=[],a=[],r=n+1,l=!1,c=!1,u=!1,g=n,d="";t:for(;r<i.length;){let p=String.fromCodePoint(i.codePointAt(r));if((p==="!"||p==="^")&&r===n+1){u=!0,r++;continue}if(p==="]"&&l&&!c){g=r+1;break}if(l=!0,p==="\\"&&!c){c=!0,r++;continue}if(p==="["&&!c){for(let[z,[R,B]]of Object.entries(D))if(i.startsWith(z,r)){if(d)return[A,i.length-n];r+=z.length,B?a.push(R):o.push(R);continue t}}c=!1;let m=h(p);if(d){m.codePointAt(0)>d.codePointAt(0)?o.push(y(d)+"-"+y(m)):m===d&&o.push(y(m)),d="",r+=p.length;continue}if(i.startsWith("-]",r+p.length)){o.push(y(m+"-")),r+=p.length+1;continue}if(i.startsWith("-",r+p.length)){d=m,r+=p.length+1;continue}o.push(y(m)),r+=p.length}if(g<r)return[A,0];if(!o.length&&!a.length)return[A,i.length-n];let f="["+(u?"^":"")+o.join("")+"]",w="["+(u?"":"^")+a.join("")+"]",q="^"+(o.length&&a.length?"("+f+"|"+w+")":o.length?f:w);return[new RegExp(q,e?"iu":"u"),g-n]};var C={t:"match",id:0},G="!?+*@",x=i=>({t:"lit",ch:i}),H=i=>i.replace(/[\\^$.*+?()[\]{}|/]/g,"\\$&"),W=i=>new RegExp(`^${H(i)}$`,"iu"),S=new Map,v=i=>{let t=S.get(i);return t||(t=W(i),S.size>=1e3&&S.clear(),S.set(i,t)),t},P=(i,t)=>{if(t===i.ch)return!0;if(!i.re)return!1;let e=t.charCodeAt(0);if(e>=128)return i.re.test(t);let s=i.ascii??=new Uint8Array(128);return s[e]||=i.re.test(t)?1:2,s[e]===1},J=(i,t,e,s)=>{let h=[];for(let n=0;n<i.length;){let o=String.fromCodePoint(i.codePointAt(n));if(o==="\\"){let a=i.codePointAt(n+1),r=a===void 0?o:String.fromCodePoint(a);h.push(x(r)),n+=1+r.length;continue}if(o==="["){let[a,r]=E(i,n,t,s);if(r){h.push({t:"class",re:a}),n+=r;continue}}if(!e&&G.includes(o)&&i[n+1]==="("){h.push({t:"open",type:o}),n+=2;continue}h.push(!e&&o==="|"?{t:"bar"}:!e&&o===")"?{t:"close"}:o==="*"?{t:"star"}:o==="?"?{t:"any"}:x(o)),n+=o.length}return h},K=i=>{let t=new Map,e=[];return i.forEach((s,h)=>{s.t==="open"?e.push(h):s.t==="close"&&e.length&&t.set(e.pop(),h)}),t},I=(i,t,e,s,h)=>{let n=[],o=[n];for(let a=e;a<s;a++){let r=i[a],l=t.get(a);if(r.t==="open"&&l!==void 0){let c=I(i,t,a+1,l,!1);n.push({t:"ext",type:r.type,alts:c}),a=l}else r.t==="bar"&&!h?o.push(n=[]):r.t==="open"?n.push(x(r.type),x("(")):r.t==="bar"?n.push(x("|")):r.t==="close"?n.push(x(")")):n.push(r)}return o},T=(i,t)=>{let e=[],s="",h=()=>{for(let n of s.normalize(t))e.push(x(n));s=""};for(let n of i){if(n.t==="lit"){s+=n.ch;continue}h(),e.push(n.t==="ext"?{...n,alts:n.alts.map(o=>T(o,t))}:n)}return h(),e},_=(i,t)=>{let e=1,s=a=>({t:"split",id:e++,out:a}),h=(a,r)=>a.reduceRight((l,c)=>n(c,l),r),n=(a,r)=>{switch(a.t){case"lit":let g=t?v(a.ch):void 0;return{t:"lit",id:e++,ch:a.ch,re:g,next:r};case"any":case"star":return{t:a.t,id:e++,next:r};case"class":return{t:"class",id:e++,re:a.re,next:r}}let l=g=>a.alts.map(d=>h(d,g));switch(a.type){case"@":return s(l(r));case"?":return s([r,...l(r)]);case"!":return{t:"neg",id:e++,sub:s(l(C)),next:r}}let c=s([]),u=s(l(c));return c.out.push(r,u),a.type==="*"?c:u};return[h(i,C),e]},Q=i=>{let t=[],e=new Set,s=n=>n.t==="match"?"match":String(n.id),h=(n,o)=>{if(n.t==="match"||e.has(n))return;e.add(n);let a=r=>t.push(`${o}${n.id}: ${r}`);switch(n.t){case"split":a(`split -> ${n.out.map(s).join(", ")}`);for(let r of n.out)h(r,o);return;case"neg":return a(`!(${s(n.sub)}) -> ${s(n.next)}`),h(n.sub,o+" "),h(n.next,o);case"lit":a(`${JSON.stringify(n.ch)} -> ${s(n.next)}`);break;case"class":a(`${n.re} -> ${s(n.next)}`);break;default:a(`${n.t==="any"?"?":"*"} -> ${s(n.next)}`)}h(n.next,o)};return h(i,""),[`start -> ${s(i)}`,...t].join(`
`)},b=class{gen;threads=[];match=!1;runs=[];ids=[];constructor(t){this.gen=t}get dead(){return!this.threads.length&&!this.match&&!this.runs.length}},O=(i,t)=>i.ids.length!==t.ids.length||i.runs.length!==t.runs.length||i.ids.some((e,s)=>e!==t.ids[s])?!1:i.runs.every(e=>t.runs.some(s=>s.neg===e.neg&&O(s.state,e.state))),N=i=>({has:new Float64Array(i),seen:new Float64Array(i),gen:0}),$=class{dots;dotStart;#t;constructor(t,e,s){this.dots=t,this.dotStart=e,this.#t=s}state(){return new b(++this.#t.gen)}done(t){return t.ids=t.threads.map(e=>e.id).sort((e,s)=>e-s),t.match&&t.ids.unshift(C.id),t}#s(t,e){let{seen:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,!0)}#e(t,e){let{has:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,t.threads.push(e),!0)}restricted(t,e){return e&&(this.dots||this.dotStart&&t===0)}add(t,e,s,h){switch(e.t){case"split":if(!this.#s(t,e))return;for(let o of e.out)this.add(t,o,s,h);return;case"neg":if(!this.#s(t,e))return;let n=this.state();return this.add(n,e.sub,s,!1),this.done(n),this.addRun(t,{t:"run",neg:e,state:n},s,h);case"star":if(this.restricted(s,h))return;this.#e(t,e)&&this.add(t,e.next,s,h);return;case"match":t.match=!0;return;default:this.#e(t,e)}}addRun(t,e,s,h){for(let n of t.runs)if(n.neg===e.neg&&O(n.state,e.state))return;t.runs.push(e),e.state.match||this.add(t,e.neg.next,s,h)}step(t,e,s,h){let n=this.state();for(let o of t.threads)switch(o.t){case"lit":P(o,e)&&this.add(n,o.next,s+1,h);break;case"any":this.restricted(s,h)||this.add(n,o.next,s+1,h);break;case"class":!this.restricted(s,h)&&o.re.test(e)&&this.add(n,o.next,s+1,h);break;case"star":this.restricted(s,h)||this.add(n,o,s+1,h)}if(!this.restricted(s,h))for(let o of t.runs){if(o.state.dead){this.addRun(n,o,s+1,h);continue}let a=this.step(o.state,e,s,!1);this.addRun(n,{t:"run",neg:o.neg,state:a},s+1,h)}return this.done(n)}},U=i=>{let t=i.ids.join();if(!i.runs.length)return t;let e=i.runs.map(s=>`${s.neg.id}(${U(s.state)})`);return`${t}|${e.sort().join("|")}`},V=1<<18,j=class{#t;#s=new Map;#e=0;#c;#n;#i;#h;constructor(t,e){this.#t=t,this.#i=new $(!1,!1,e),this.#h=new $(!1,!0,e)}#o(t){return{state:t,match:t.match,dead:t.dead,next:new Map}}#u(t){let e=U(t),s=this.#s.get(e);if(s)return s;this.#e>V&&this.#f();let h=this.#o(t);return this.#s.set(e,h),this.#e+=e.length+1,h}#f(){this.#s.clear(),this.#e=0,this.#c=void 0,this.#n=void 0}start(t){if(t){if(this.#n)return this.#n;let s=this.#h.state();return this.#h.add(s,this.#t,0,!0),this.#n=this.#o(this.#h.done(s))}if(this.#c)return this.#c;let e=this.#i.state();return this.#i.add(e,this.#t,0,!0),this.#c=this.#u(this.#i.done(e))}next(t,e){let s=e.charCodeAt(0),h=s<128?void 0:t.next.get(e);if(h)return h;let n=t===this.#n?this.#u(this.#h.step(t.state,e,0,!0)):this.#u(this.#i.step(t.state,e,1,!0));return s<128?(t.ascii||(t.ascii=new Array(128),this.#e+=128),t.ascii[s]=n):t.next.set(e,n),this.#e++,n}},X=i=>{let t=[];for(let e=i;e.t!=="match";e=e.next){if(e.t==="split"||e.t==="neg")return;t.push(e)}return t},Y=(i,t,e,s)=>{let h=0,n=e,o=-1,a=0;for(;n<s;){let r=i[h];if(r?.t==="star"){o=h++,a=n;continue}let l=t[n];if(r&&(r.t==="any"||r.t==="lit"&&P(r,l)||r.t==="class"&&r.re.test(l))){h++,n++;continue}if(o===-1)return!1;h=o+1,n=++a}for(;i[h]?.t==="star";)h++;return h===i.length},Z=i=>{let t=0,e=0;for(let s of i){let[h,n]=tt(s);t+=h,e+=n}return[t,e]},tt=i=>{if(i.t==="star")return[0,1/0];if(i.t!=="ext")return[1,1];if(i.type==="!")return[0,1/0];let t=i.alts.map(Z),e=Math.min(...t.map(n=>n[0])),s=Math.max(...t.map(n=>n[1])),h=s===0?0:1/0;return i.type==="@"?[e,s]:i.type==="?"?[0,s]:i.type==="*"?[0,h]:[e,h]},M=(i,t,e)=>{for(let s=0;s<i.length;s++)if(!P(i[s],t[e+s]))return!1;return!0},et=/[/\ud800-\udfff]/,st=/[\ud800-\udfff]/,k=i=>st.test(i)?[...i]:i,F=i=>{if(i.includes("/"))throw new Error("can only match a single path portion, got: "+i)},L=class{pattern;options;#t;#s;#e;#c;#n;#i=!1;#h;#o;#u=!1;#f=0;#m=1/0;#l=[];#a=[];#p;#g;#w=!1;#x;#r;constructor(t,e={}){if(t.includes("/"))throw new Error("can only match a single path portion, got pattern: "+t);this.pattern=t,this.options=e;let{nocase:s=!1,noext:h=!1,normalize:n}=e;this.#r=n===!0?"NFC":n||void 0;let o=/^[?*+@]\(\)$/.test(t),a=J(t,s,h||o,this.#r),[r]=I(a,K(a),0,a.length,!0);this.#r&&(r=T(r,this.#r));let[l,c]=_(r,s);if(this.#t=l,this.#s=c,r.every(u=>u.t==="lit"))this.#n=r.map(u=>u.ch).join(""),this.#i=s;else{let u=f=>f.t!=="lit"?void 0:s?{ch:f.ch,re:v(f.ch)}:{ch:f.ch};for(let f of r){let w=u(f);if(!w)break;this.#l.push(w)}for(let f=r.length-1;f>=0;f--){let w=u(r[f]);if(!w)break;this.#a.unshift(w)}this.#w=!!(this.#l.length||this.#a.length),s||(this.#p=this.#l.map(f=>f.ch).join(""),this.#g=this.#a.map(f=>f.ch).join("")),this.#o=X(this.#t)?.slice(this.#l.length,-this.#a.length||void 0),this.#u=!!this.#o?.every(f=>f.t==="star"||f.t==="any");let[g,d]=Z(r);this.#f=g,this.#m=d}}test(t){return this.#r?(F(t),this.#d(t.normalize(this.#r))):et.test(t)?(F(t),this.#d(t,[...t])):this.#d(t,t)}testUnchecked(t){return this.#d(this.#r?t.normalize(this.#r):t Line truncated
//# sourceMappingURL=index.min.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../src/parse-class.ts", "../../src/index.ts"],
"sourcesContent": ["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { <posix class>: [<translation>, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}'],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}'],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f'],\n '[:blank:]': ['\\\\p{Zs}\\\\t'],\n '[:cntrl:]': ['\\\\p{Cc}'],\n '[:digit:]': ['\\\\p{Nd}'],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true],\n '[:lower:]': ['\\\\p{Ll}'],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}\\\\p{S}'],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f'],\n '[:upper:]': ['\\\\p{Lu}'],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}'],\n '[:xdigit:]': ['A-Fa-f0-9'],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n\nexport type ParseClassResult = [re: RegExp, consumed: number]\n\nexport type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'\n\nconst noMatch = /$./\n\n// Takes a glob string at a posix brace expression. Returns a RegExp\n// that tests one character, and the number of glob chars consumed.\n// If the class is not closed, consumed is 0, and the `[` must be\n// treated as a literal character.\n// Out of order ranges are removed. If nothing is left, the RegExp\n// is `/$./`, and the rest of the glob is consumed, so that the\n// whole glob cannot match.\nexport const parseClass = (\n glob: string,\n position: number,\n nocase: boolean = false,\n form?: Form,\n): ParseClassResult => {\n // normalize one class member, if it stays one code point\n const norm = (c: string) => {\n const n = form ? c.normalize(form) : c\n return [...n].length === 1 ? n : c\n }\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = String.fromCodePoint(glob.codePointAt(i)!)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return [noMatch, glob.length - pos]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n const n = norm(c)\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))\n } else if (n === rangeStart) {\n ranges.push(braceEscape(n))\n }\n rangeStart = ''\n i += c.length\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c<more...>] or c] at this point\n if (glob.startsWith('-]', i + c.length)) {\n ranges.push(braceEscape(n + '-'))\n i += c.length + 1\n continue\n }\n if (glob.startsWith('-', i + c.length)) {\n rangeStart = n\n i += c.length + 1\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(n))\n i += c.length\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return [noMatch, 0]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return [noMatch, glob.length - pos]\n }\n\n const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'\n const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'\n const comb =\n '^' +\n (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n : ranges.length ? sranges\n : snegs)\n\n return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]\n}\n", "import { type Form, parseClass } from './parse-class.js'\nLine truncated
"mappings": "AAIA,IAAMA,EAA0D,CAC9D,YAAa,CAAC,sBAAsB,EACpC,YAAa,CAAC,eAAe,EAC7B,YAAa,CAAC,aAAuB,EACrC,YAAa,CAAC,YAAY,EAC1B,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,eAAgB,EAAI,EAClC,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,SAAU,EAAI,EAC5B,YAAa,CAAC,cAAc,EAC5B,YAAa,CAAC,uBAAuB,EACrC,YAAa,CAAC,SAAS,EACvB,WAAY,CAAC,6BAA6B,EAC1C,aAAc,CAAC,WAAW,GAKtBC,EAAeC,GAAcA,EAAE,QAAQ,YAAa,MAAM,EAM1DC,EAAU,KASHC,EAAa,CACxBC,EACAC,EACAC,EAAkB,GAClBC,IACoB,CAEpB,IAAMC,EAAQC,GAAa,CACzB,IAAMC,EAAIH,EAAOE,EAAE,UAAUF,CAAI,EAAIE,EACrC,MAAO,CAAC,GAAGC,CAAC,EAAE,SAAW,EAAIA,EAAID,CACnC,EACME,EAAMN,EAEZ,GAAID,EAAK,OAAOO,CAAG,IAAM,IACvB,MAAM,I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AClBF,GAAOE,EAAG,GACV,QACF,CACAD,EAAK,EACLF,EAAI,KACFG,EAAG,IAAM,MACP,CAAE,GAAGA,EAAI,KAAMA,EAAG,KAAK,IAAIC,GAAKN,EAAUM,EAAGxB,CAAI,CAAC,Line truncated
"names": ["posixClasses", "braceEscape", "s", "noMatch", "parseClass", "glob", "position", "nocase", "form", "norm", "c", "n", "pos", "ranges", "negs", "i", "sawStart", "escaping", "negate", "endPos", "rangeStart", "WHILE", "cls", "unip", "neg", "sranges", "snegs", "comb", "MATCH", "extTypes", "lit", "ch", "reEscape", "s", "newFoldRe", "foldCache", "foldRe", "re", "litMatch", "l", "c", "code", "ascii", "tokenize", "p", "nocase", "noext", "form", "toks", "i", "e", "consumed", "parseClass", "pair", "pairs", "stack", "tok", "build", "start", "end", "top", "seq", "alts", "close", "sub", "normalize", "items", "out", "run", "flush", "it", "a", "compile", "id", "split", "next", "item", "after", "entry", "show", "lines", "seen", "ref", "walk", "indent", "line", "desc", "o", "State", "gen", "sameState", "b", "r", "marks", "size", "Sim", "#marks", "dots", "dotStart", "state", "n", "#visit", "node", "#addThread", "has", "th", "stateKey", "ids", "runs", "DFA_BUDGET", "Dfa", "#start", "#states", "#size", "#plain", "#dotStart", "#sim", "#dotSim", "#make", "#intern", "key", "found", "#clear", "d", "linear", "nodes", "testLinear", "chars", "ni", "ci", "starNi", "starCi", "lengths", "min", "max", "lo", "hi", "itemLengths", "loop", "hasAffix", "lits", "j", "slashOrSurrogate", "surrogate", "codePoints", "noSlash", "Matcher", "#dotsSim", "#literal", "#literalFold", "#literalRe", "#linear", "#wild", "#min", "#max", "#prefix", "#suffix", "#prefixStr", "#suffixStr", "#affix", "#dfa", "#form", "pattern", "options", "literal", "#test", "most", "least", "prefix", "sim", "dfa", "str"]
}
@@ -0,0 +1,3 @@
{
"type": "module"
}
@@ -0,0 +1,4 @@
export type ParseClassResult = [re: RegExp, consumed: number];
export type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD';
export declare const parseClass: (glob: string, position: number, nocase?: boolean, form?: Form) => ParseClassResult;
//# sourceMappingURL=parse-class.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"parse-class.d.ts","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":"AAyBA,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;AAE7D,MAAM,MAAM,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAA;AAWlD,eAAO,MAAM,UAAU,GACrB,MAAM,MAAM,EACZ,UAAU,MAAM,EAChB,SAAQ,OAAe,EACvB,OAAO,IAAI,KACV,gBAkHF,CAAA"}
@@ -0,0 +1,138 @@
// translate the various posix character classes into unicode properties
// this works across all unicode locales
// { <posix class>: [<translation>, negated]
const posixClasses = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}'],
'[:alpha:]': ['\\p{L}\\p{Nl}'],
'[:ascii:]': ['\\x' + '00-\\x' + '7f'],
'[:blank:]': ['\\p{Zs}\\t'],
'[:cntrl:]': ['\\p{Cc}'],
'[:digit:]': ['\\p{Nd}'],
'[:graph:]': ['\\p{Z}\\p{C}', true],
'[:lower:]': ['\\p{Ll}'],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}\\p{S}'],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f'],
'[:upper:]': ['\\p{Lu}'],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}'],
'[:xdigit:]': ['A-Fa-f0-9'],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
const noMatch = /$./;
// Takes a glob string at a posix brace expression. Returns a RegExp
// that tests one character, and the number of glob chars consumed.
// If the class is not closed, consumed is 0, and the `[` must be
// treated as a literal character.
// Out of order ranges are removed. If nothing is left, the RegExp
// is `/$./`, and the rest of the glob is consumed, so that the
// whole glob cannot match.
export const parseClass = (glob, position, nocase = false, form) => {
// normalize one class member, if it stays one code point
const norm = (c) => {
const n = form ? c.normalize(form) : c;
return [...n].length === 1 ? n : c;
};
const pos = position;
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression');
}
/* c8 ignore stop */
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = '';
WHILE: while (i < glob.length) {
const c = String.fromCodePoint(glob.codePointAt(i));
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === '\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return [noMatch, glob.length - pos];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
continue WHILE;
}
}
}
// now it's just a normal character, effectively
escaping = false;
const n = norm(c);
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (n.codePointAt(0) > rangeStart.codePointAt(0)) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n));
}
else if (n === rangeStart) {
ranges.push(braceEscape(n));
}
rangeStart = '';
i += c.length;
continue;
}
// now might be the start of a range.
// can be either c-d or c-] or c<more...>] or c] at this point
if (glob.startsWith('-]', i + c.length)) {
ranges.push(braceEscape(n + '-'));
i += c.length + 1;
continue;
}
if (glob.startsWith('-', i + c.length)) {
rangeStart = n;
i += c.length + 1;
continue;
}
// not the start of a range, just a single character
ranges.push(braceEscape(n));
i += c.length;
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return [noMatch, 0];
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return [noMatch, glob.length - pos];
}
const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']';
const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']';
const comb = '^' +
(ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
: ranges.length ? sranges
: snegs);
return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos];
};
//# sourceMappingURL=parse-class.js.map
@@ -0,0 +1 @@
{"version":3,"file":"parse-class.js","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,wCAAwC;AAExC,4CAA4C;AAC5C,MAAM,YAAY,GAA8C;IAC9D,WAAW,EAAE,CAAC,sBAAsB,CAAC;IACrC,WAAW,EAAE,CAAC,eAAe,CAAC;IAC9B,WAAW,EAAE,CAAC,KAAK,GAAG,QAAQ,GAAG,IAAI,CAAC;IACtC,WAAW,EAAE,CAAC,YAAY,CAAC;IAC3B,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,cAAc,EAAE,IAAI,CAAC;IACnC,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,cAAc,CAAC;IAC7B,WAAW,EAAE,CAAC,uBAAuB,CAAC;IACtC,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,UAAU,EAAE,CAAC,6BAA6B,CAAC;IAC3C,YAAY,EAAE,CAAC,WAAW,CAAC;CAC5B,CAAA;AAED,+DAA+D;AAC/D,mBAAmB;AACnB,MAAM,WAAW,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,MAAM,CAAC,CAAA;AAMjE,MAAM,OAAO,GAAG,IAAI,CAAA;AAEpB,oEAAoE;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gEAAgE;IAChE,kEAAkE;IAClE,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QACnC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,CAAA;IACrC,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,CAAA;IACjE,MAAM,KAAK,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,CAAA;IAC7D,MAAM,IAAI,GACR,GAAG;QACH,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG;YACjE,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO;gBACzB,CAAC,CAAC,KAAK,CAAC,CAAA;IAEV,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC,CAAA;AAC9D,CAAC,CAAA","sourcesContent":["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { <posix class>: [<translation>, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n '[Line truncated
+56
View File
@@ -0,0 +1,56 @@
{
"name": "@isaacs/nonrecursive-glob-match",
"description": "a single-path-portion glob matcher not subject to recursive backtracking ReDoS",
"version": "1.0.3",
"license": "BlueOak-1.0.0",
"files": [
"dist",
"src"
],
"devDependencies": {
"esbuild": "^0.28.2",
"prettier": "^3.9.10",
"tap": "^21.8.0",
"tshy": "^4.1.3",
"typedoc": "^0.28.20"
},
"scripts": {
"format": "prettier --write .",
"test": "tap",
"snap": "tap",
"typedoc": "typedoc",
"pretest": "npm run prepare",
"presnap": "npm run prepare",
"prepare": "tshy && bash scripts/build.sh",
"preversion": "npm test",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags"
},
"type": "module",
"tshy": {
"selfLink": false,
"exports": {
"./package.json": "./package.json",
".": "./src/index.ts"
}
},
"exports": {
"./package.json": "./package.json",
".": {
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/commonjs/index.d.ts",
"default": "./dist/commonjs/index.js"
}
}
},
"main": "./dist/commonjs/index.js",
"types": "./dist/commonjs/index.d.ts",
"module": "./dist/esm/index.js",
"allowScripts": {
"[email protected]": true
}
}
+900
View File
@@ -0,0 +1,900 @@
import { type Form, parseClass } from './parse-class.js'
export type { Form }
export type MatcherOptions = {
/** perform a case-insensitive match */
nocase?: boolean
/** do not treat strings starting with `.` specially */
dot?: boolean
/** do not match extglobs (treat them as normal strings) */
noext?: boolean
/**
* normalize unicode in the pattern and the tested strings, with
* this form. `true` means `'NFC'`.
*/
normalize?: boolean | Form
}
// parsed pattern items
export type Item =
| { t: 'lit'; ch: string }
| { t: 'any' | 'star' }
| { t: 'class'; re: RegExp }
| { t: 'ext'; type: string; alts: Item[][] }
// extglob syntax tokens become literals if they are not part of a
// closed extglob
export type Token =
Item | { t: 'open'; type: string } | { t: 'bar' } | { t: 'close' }
// state machine nodes
export type NegNode = { t: 'neg'; id: number; sub: Node; next: Node }
export type SplitNode = { t: 'split'; id: number; out: Node[] }
export type Node =
| ({ t: 'lit'; id: number; next: Node } & Lit)
| { t: 'any' | 'star'; id: number; next: Node }
| { t: 'class'; id: number; re: RegExp; next: Node }
| SplitNode
| NegNode
| { t: 'match'; id: number }
// the end of the pattern, or of a negated sub-pattern
const MATCH: Node = { t: 'match', id: 0 }
const extTypes = '!?+*@'
const lit = (ch: string): Item => ({ t: 'lit', ch })
const reEscape = (s: string) => s.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&')
// a RegExp that only matches `s`, with unicode case folding
const newFoldRe = (s: string) => new RegExp(`^${reEscape(s)}$`, 'iu')
// foldRe for one literal char. The same chars are in most patterns,
// so keep them. A RegExp without the `g` or `y` flag has no state to
// share.
const foldCache = new Map<string, RegExp>()
const foldRe = (ch: string) => {
let re = foldCache.get(ch)
if (!re) {
re = newFoldRe(ch)
if (foldCache.size >= 1000) foldCache.clear()
foldCache.set(ch, re)
}
return re
}
/**
* A literal char. With `nocase:true`, `re` folds case, and `ascii`
* holds its results for ASCII chars, by char code: 1 for a match,
* and 2 for not.
*/
export type Lit = { ch: string; re?: RegExp; ascii?: Uint8Array }
const litMatch = (l: Lit, c: string) => {
if (c === l.ch) return true
if (!l.re) return false
const code = c.charCodeAt(0)
if (code >= 128) return l.re.test(c)
const ascii = (l.ascii ??= new Uint8Array(128))
ascii[code] ||= l.re.test(c) ? 1 : 2
return ascii[code] === 1
}
const tokenize = (
p: string,
nocase: boolean,
noext: boolean,
form?: Form,
) => {
const toks: Token[] = []
for (let i = 0; i < p.length;) {
const c = String.fromCodePoint(p.codePointAt(i)!)
if (c === '\\') {
// a trailing \ is a literal \
const e = p.codePointAt(i + 1)
const ch = e === undefined ? c : String.fromCodePoint(e)
toks.push(lit(ch))
i += 1 + ch.length
continue
}
if (c === '[') {
const [re, consumed] = parseClass(p, i, nocase, form)
if (consumed) {
toks.push({ t: 'class', re })
i += consumed
continue
}
}
if (!noext && extTypes.includes(c) && p[i + 1] === '(') {
toks.push({ t: 'open', type: c })
i += 2
continue
}
toks.push(
!noext && c === '|' ? { t: 'bar' }
: !noext && c === ')' ? { t: 'close' }
: c === '*' ? { t: 'star' }
: c === '?' ? { t: 'any' }
: lit(c),
)
i += c.length
}
return toks
}
// map each open token index to the index of its close token
const pair = (toks: Token[]) => {
const pairs = new Map<number, number>()
const stack: number[] = []
toks.forEach((tok, i) => {
if (tok.t === 'open') stack.push(i)
else if (tok.t === 'close' && stack.length) pairs.set(stack.pop()!, i)
})
return pairs
}
// build the alternatives between start and end. An open token that
// is not closed is never inside a closed extglob, so bar and close
// tokens are only literal at the top level.
const build = (
toks: Token[],
pairs: Map<number, number>,
start: number,
end: number,
top: boolean,
): Item[][] => {
let seq: Item[] = []
const alts = [seq]
for (let i = start; i < end; i++) {
const tok = toks[i]!
const close = pairs.get(i)
if (tok.t === 'open' && close !== undefined) {
const sub = build(toks, pairs, i + 1, close, false)
seq.push({ t: 'ext', type: tok.type, alts: sub })
i = close
} else if (tok.t === 'bar' && !top) {
alts.push((seq = []))
} else if (tok.t === 'open') {
seq.push(lit(tok.type), lit('('))
} else if (tok.t === 'bar') {
seq.push(lit('|'))
} else if (tok.t === 'close') {
seq.push(lit(')'))
} else {
seq.push(tok)
}
}
return alts
}
// normalize each run of literal chars as one string, so that a char
// and the combining marks after it compose (or decompose) together.
// Syntax is already parsed, so a char that normalizes to a syntax
// char (such as full-width `*` in NFKC) stays a literal.
const normalize = (items: Item[], form: Form): Item[] => {
const out: Item[] = []
let run = ''
const flush = () => {
for (const ch of run.normalize(form)) out.push(lit(ch))
run = ''
}
for (const it of items) {
if (it.t === 'lit') {
run += it.ch
continue
}
flush()
out.push(
it.t === 'ext' ?
{ ...it, alts: it.alts.map(a => normalize(a, form)) }
: it,
)
}
flush()
return out
}
// the start node, and the number of node ids. Ids are dense, from 0
// for the match node.
const compile = (
items: Item[],
nocase: boolean,
): [start: Node, size: number] => {
let id = 1
const split = (out: Node[]): SplitNode => ({ t: 'split', id: id++, out })
const seq = (items: Item[], next: Node): Node =>
items.reduceRight((next, it) => item(it, next), next)
const item = (it: Item, next: Node): Node => {
switch (it.t) {
case 'lit':
const re = nocase ? foldRe(it.ch) : undefined
return { t: 'lit', id: id++, ch: it.ch, re, next }
case 'any':
case 'star':
return { t: it.t, id: id++, next }
case 'class':
return { t: 'class', id: id++, re: it.re, next }
}
const alts = (next: Node) => it.alts.map(a => seq(a, next))
switch (it.type) {
case '@':
return split(alts(next))
case '?':
return split([next, ...alts(next)])
case '!':
return { t: 'neg', id: id++, sub: split(alts(MATCH)), next }
}
// * and +, loop back after each match
const after = split([])
const entry = split(alts(after))
after.out.push(next, entry)
return it.type === '*' ? after : entry
}
const start = seq(items, MATCH)
return [start, id]
}
// one line per node, in the order that a walk from the start
// reaches them. Edges point to node ids. The nodes of a negated
// sub-pattern are indented under their negation.
const show = (start: Node): string => {
const lines: string[] = []
const seen = new Set<Node>()
const ref = (n: Node) => (n.t === 'match' ? 'match' : String(n.id))
const walk = (n: Node, indent: string) => {
if (n.t === 'match' || seen.has(n)) return
seen.add(n)
const line = (desc: string) => lines.push(`${indent}${n.id}: ${desc}`)
switch (n.t) {
case 'split':
line(`split -> ${n.out.map(ref).join(', ')}`)
for (const o of n.out) walk(o, indent)
return
case 'neg':
line(`!(${ref(n.sub)}) -> ${ref(n.next)}`)
walk(n.sub, indent + ' ')
return walk(n.next, indent)
case 'lit':
line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`)
break
case 'class':
line(`${n.re} -> ${ref(n.next)}`)
break
default:
line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`)
}
walk(n.next, indent)
}
walk(start, '')
return [`start -> ${ref(start)}`, ...lines].join('\n')
}
// A thread inside a !(...) negation. It holds the threads of the
// negated sub-pattern, started where the negation started. The
// negation matches the chars so far if the sub-pattern does not.
type Run = { t: 'run'; neg: NegNode; state: State }
// The threads at one position in the string. Each node thread is
// only kept once, and runs with the same state are only kept once,
// so that identical threads merge. The match node is not in
// `threads`, because it can not step. It sets `match` instead.
class State {
// set by the Sim, to mark the nodes that this state has
gen: number
threads: Node[] = []
match = false
runs: Run[] = []
// the sorted ids of the threads, with 0 for a match, once the
// state is done
ids: number[] = []
constructor(gen: number) {
this.gen = gen
}
// no threads, so nothing more can match
get dead() {
return !this.threads.length && !this.match && !this.runs.length
}
}
// true if the two states hold the same threads
const sameState = (a: State, b: State): boolean => {
if (a.ids.length !== b.ids.length) return false
if (a.runs.length !== b.runs.length) return false
if (a.ids.some((id, i) => id !== b.ids[i])) return false
return a.runs.every(r =>
b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)),
)
}
/**
* For each node id, the gen of the last state that has the node as
* a thread, and of the last state that walked through it. A state is
* built to the end before the states around it go on, and the nodes
* of a negated sub-pattern are only in its states (other than the
* match node, which is never marked). So one mark for each node is
* enough to know if the state being built has it. The Sims of a
* matcher never run at the same time, so they share one Marks.
*/
export type Marks = { has: Float64Array; seen: Float64Array; gen: number }
const marks = (size: number): Marks => ({
has: new Float64Array(size),
seen: new Float64Array(size),
gen: 0,
})
class Sim {
// `.` and `..` only match literal dots, even with `dot:true`
dots: boolean
// the string starts with `.`, and `dot:true` is not set
dotStart: boolean
#marks: Marks
constructor(dots: boolean, dotStart: boolean, marks: Marks) {
this.dots = dots
this.dotStart = dotStart
this.#marks = marks
}
state() {
return new State(++this.#marks.gen)
}
// sort the ids of a state, once it has all of its threads
done(state: State) {
state.ids = state.threads.map(n => n.id).sort((a, b) => a - b)
if (state.match) state.ids.unshift(MATCH.id)
return state
}
// true the first time that the state walks through the node, so
// that loops in the graph stop
#visit(state: State, node: Node) {
const { seen } = this.#marks
if (seen[node.id] === state.gen) return false
seen[node.id] = state.gen
return true
}
#addThread(state: State, node: Node) {
const { has } = this.#marks
if (has[node.id] === state.gen) return false
has[node.id] = state.gen
state.threads.push(node)
return true
}
// wildcards only match a leading dot if `dot:true`. In a negated
// sub-pattern, this does not apply, because the negation itself
// can not match a leading dot.
restricted(i: number, top: boolean) {
return top && (this.dots || (this.dotStart && i === 0))
}
add(state: State, node: Node, i: number, top: boolean): void {
switch (node.t) {
case 'split':
if (!this.#visit(state, node)) return
for (const o of node.out) this.add(state, o, i, top)
return
case 'neg':
if (!this.#visit(state, node)) return
const sub = this.state()
this.add(sub, node.sub, i, false)
this.done(sub)
return this.addRun(
state,
{ t: 'run', neg: node, state: sub },
i,
top,
)
case 'star':
// a * can not start a dotfile, even if it matches nothing
if (this.restricted(i, top)) return
if (this.#addThread(state, node))
this.add(state, node.next, i, top)
return
case 'match':
state.match = true
return
default:
this.#addThread(state, node)
}
}
addRun(state: State, run: Run, i: number, top: boolean) {
for (const r of state.runs) {
if (r.neg === run.neg && sameState(r.state, run.state)) return
}
state.runs.push(run)
if (!run.state.match) {
this.add(state, run.neg.next, i, top)
}
}
// the threads after char `c`, at index `i`
step(state: State, c: string, i: number, top: boolean): State {
const next = this.state()
for (const th of state.threads) {
switch (th.t) {
case 'lit':
if (litMatch(th, c)) {
this.add(next, th.next, i + 1, top)
}
break
case 'any':
if (!this.restricted(i, top)) this.add(next, th.next, i + 1, top)
break
case 'class':
if (!this.restricted(i, top) && th.re.test(c)) {
this.add(next, th.next, i + 1, top)
}
break
case 'star':
if (!this.restricted(i, top)) this.add(next, th, i + 1, top)
}
}
if (!this.restricted(i, top)) {
for (const run of state.runs) {
// a sub-pattern with no threads can not match again, so the
// run stays the same
if (run.state.dead) {
this.addRun(next, run, i + 1, top)
continue
}
const sub = this.step(run.state, c, i, false)
this.addRun(
next,
{ t: 'run', neg: run.neg, state: sub },
i + 1,
top,
)
}
}
return this.done(next)
}
}
// A canonical key for the threads in a state. States with the same
// key hold the same threads, so they match the same strings.
const stateKey = (state: State): string => {
const ids = state.ids.join()
if (!state.runs.length) return ids
const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`)
return `${ids}|${runs.sort().join('|')}`
}
// A cached state of the simulation, and the states that each char
// leads to.
type DState = {
state: State
match: boolean
// no threads, so nothing more can match
dead: boolean
// the next state for each ASCII char, by char code, and for the
// other chars
ascii?: (DState | undefined)[]
next: Map<string, DState>
}
// The cache can hold about this many chars of state keys and
// transitions. When it is full, it is cleared, so that a pattern
// can not use an unbounded amount of memory.
const DFA_BUDGET = 1 << 18
// A cache of the states that the simulation reaches, built as the
// matcher is used. Each char of a string is then one Map lookup,
// once the states that it leads to are known.
//
// The dot rules only restrict the first char of a dotfile (strings
// that are only `.` or `..` do not use the cache). So a dotfile
// starts at its own state, which takes its first step with the
// restriction, and every other state takes steps without it.
class Dfa {
#start: Node
#states = new Map<string, DState>()
#size = 0
#plain?: DState
#dotStart?: DState
#sim: Sim
#dotSim: Sim
constructor(start: Node, marks: Marks) {
this.#start = start
this.#sim = new Sim(false, false, marks)
this.#dotSim = new Sim(false, true, marks)
}
#make(state: State): DState {
return {
state,
match: state.match,
dead: state.dead,
next: new Map(),
}
}
#intern(state: State): DState {
const key = stateKey(state)
const found = this.#states.get(key)
if (found) return found
if (this.#size > DFA_BUDGET) this.#clear()
const d = this.#make(state)
this.#states.set(key, d)
this.#size += key.length + 1
return d
}
#clear() {
this.#states.clear()
this.#size = 0
this.#plain = undefined
this.#dotStart = undefined
}
start(dotStart: boolean): DState {
if (dotStart) {
if (this.#dotStart) return this.#dotStart
const state = this.#dotSim.state()
this.#dotSim.add(state, this.#start, 0, true)
return (this.#dotStart = this.#make(this.#dotSim.done(state)))
}
if (this.#plain) return this.#plain
const state = this.#sim.state()
this.#sim.add(state, this.#start, 0, true)
return (this.#plain = this.#intern(this.#sim.done(state)))
}
// the next state, after a miss in `d.ascii`
next(d: DState, c: string): DState {
const code = c.charCodeAt(0)
const found = code < 128 ? undefined : d.next.get(c)
if (found) return found
// the dotfile start is not in the cache, so it is never shared
const n =
d === this.#dotStart ?
this.#intern(this.#dotSim.step(d.state, c, 0, true))
: this.#intern(this.#sim.step(d.state, c, 1, true))
if (code < 128) {
if (!d.ascii) {
d.ascii = new Array(128)
this.#size += 128
}
d.ascii[code] = n
} else {
d.next.set(c, n)
}
this.#size++
return n
}
}
/**
* A node in a graph with no splits or negations. Such a graph is a
* chain of nodes that each match one char, or a `*`.
*/
export type LinearNode = Exclude<
Node,
SplitNode | NegNode | { t: 'match' }
>
// the nodes in order, if the graph is a single chain
const linear = (start: Node): LinearNode[] | undefined => {
const nodes: LinearNode[] = []
for (let n = start; n.t !== 'match'; n = n.next) {
if (n.t === 'split' || n.t === 'neg') return undefined
nodes.push(n)
}
return nodes
}
// Match a chain of nodes. Each node other than `*` matches exactly
// one char, so on a failure it is enough to go back to the last `*`
// and let it match one more char. This takes at most
// nodes.length * chars.length steps.
const testLinear = (
nodes: LinearNode[],
chars: ArrayLike<string>,
start: number,
end: number,
) => {
let ni = 0
let ci = start
let starNi = -1
let starCi = 0
while (ci < end) {
const n = nodes[ni]
if (n?.t === 'star') {
starNi = ni++
starCi = ci
continue
}
const c = chars[ci]!
if (
n &&
(n.t === 'any' ||
(n.t === 'lit' && litMatch(n, c)) ||
(n.t === 'class' && n.re.test(c)))
) {
ni++
ci++
continue
}
if (starNi === -1) return false
ni = starNi + 1
ci = ++starCi
}
while (nodes[ni]?.t === 'star') ni++
return ni === nodes.length
}
// The least and most chars that the items can match. These are only
// bounds: a negation can match a string of any length, so it counts
// as 0 to Infinity.
const lengths = (items: Item[]): [min: number, max: number] => {
let min = 0
let max = 0
for (const it of items) {
const [lo, hi] = itemLengths(it)
min += lo
max += hi
}
return [min, max]
}
const itemLengths = (it: Item): [min: number, max: number] => {
if (it.t === 'star') return [0, Infinity]
if (it.t !== 'ext') return [1, 1]
if (it.type === '!') return [0, Infinity]
const alts = it.alts.map(lengths)
const min = Math.min(...alts.map(a => a[0]))
const max = Math.max(...alts.map(a => a[1]))
// a loop of alternatives that only match the empty string is empty
const loop = max === 0 ? 0 : Infinity
return (
it.type === '@' ? [min, max]
: it.type === '?' ? [0, max]
: it.type === '*' ? [0, loop]
: [min, loop]
)
}
// true if the chars from `start` match the literals
const hasAffix = (
lits: Lit[],
chars: ArrayLike<string>,
start: number,
) => {
for (let j = 0; j < lits.length; j++) {
if (!litMatch(lits[j]!, chars[start + j]!)) return false
}
return true
}
// a `/`, or half of a surrogate pair
const slashOrSurrogate = /[/\ud800-\udfff]/
const surrogate = /[\ud800-\udfff]/
// a string can be indexed by code point, unless it has surrogate
// pairs
const codePoints = (s: string): ArrayLike<string> =>
surrogate.test(s) ? [...s] : s
const noSlash = (s: string) => {
if (s.includes('/')) {
throw new Error('can only match a single path portion, got: ' + s)
}
}
export class Matcher {
pattern: string
options: MatcherOptions
#start: Node
// the number of node ids
#size: number
#marks?: Marks
// the Sim for strings that are only `.` or `..`
#dotsSim?: Sim
// the string to compare, if the pattern has no magic. With
// `nocase:true`, the RegExp that folds case is made when it is
// first used.
#literal?: string
#literalFold = false
#literalRe?: RegExp
// the nodes between the prefix and suffix, if the graph is a
// single chain
#linear?: LinearNode[]
// the linear nodes are only `*` and `?`, so the length bounds and
// the prefix and suffix decide the match
#wild = false
// the least and most chars that a match can have
#min = 0
#max = Infinity
// the literals that a match must start and end with. Each one
// matches exactly one char, and they are distinct items in the
// pattern, so a string that does not have them can not match.
#prefix: Lit[] = []
#suffix: Lit[] = []
// the prefix and suffix as strings, if they do not fold case
#prefixStr?: string
#suffixStr?: string
// there is a prefix or suffix to check
#affix = false
#dfa?: Dfa
#form?: Form
constructor(pattern: string, options: MatcherOptions = {}) {
if (pattern.includes('/')) {
throw new Error(
'can only match a single path portion, got pattern: ' + pattern,
)
}
this.pattern = pattern
this.options = options
const { nocase = false, noext = false, normalize: n } = options
this.#form = n === true ? 'NFC' : n || undefined
// a pattern that is only an empty extglob is a literal string,
// except for `!()`, which matches any non-empty string
const literal = /^[?*+@]\(\)$/.test(pattern)
const toks = tokenize(pattern, nocase, noext || literal, this.#form)
let [items] = build(toks, pair(toks), 0, toks.length, true)
if (this.#form) items = normalize(items!, this.#form)
const [start, size] = compile(items!, nocase)
this.#start = start
this.#size = size
if (items!.every(it => it.t === 'lit')) {
this.#literal = items!.map(it => it.ch).join('')
this.#literalFold = nocase
} else {
const lit = (it: Item): Lit | undefined =>
it.t !== 'lit' ? undefined
: nocase ? { ch: it.ch, re: foldRe(it.ch) }
: { ch: it.ch }
for (const it of items!) {
const l = lit(it)
if (!l) break
this.#prefix.push(l)
}
for (let j = items!.length - 1; j >= 0; j--) {
const l = lit(items![j]!)
if (!l) break
this.#suffix.unshift(l)
}
this.#affix = !!(this.#prefix.length || this.#suffix.length)
if (!nocase) {
this.#prefixStr = this.#prefix.map(l => l.ch).join('')
this.#suffixStr = this.#suffix.map(l => l.ch).join('')
}
this.#linear = linear(this.#start)?.slice(
this.#prefix.length,
-this.#suffix.length || undefined,
)
this.#wild = !!this.#linear?.every(
n => n.t === 'star' || n.t === 'any',
)
const [min, max] = lengths(items!)
this.#min = min
this.#max = max
}
}
test(s: string): boolean {
// The `/` check uses the string as given, so with normalization it
// is a separate step. Otherwise, one scan finds both a `/` and the
// surrogate pairs that stop the string being indexed by code point.
if (this.#form) {
noSlash(s)
return this.#test(s.normalize(this.#form))
}
if (slashOrSurrogate.test(s)) {
noSlash(s)
return this.#test(s, [...s])
}
return this.#test(s, s)
}
/**
* The same as {@link Matcher#test}, but the string is not checked
* for `/` chars, so the result for a string that has one is not
* defined. Only use it for a string that is known to be one path
* portion, such as a part of a path that was split on `/`. It can
* be faster, because some patterns do not need to look at each char
* of the string.
*/
testUnchecked(s: string): boolean {
return this.#test(this.#form ? s.normalize(this.#form) : s)
}
// Test a string that has no `/`. `chars` indexes it by code point.
// If it is not given, it is only found if a step needs it.
#test(s: string, chars?: ArrayLike<string>): boolean {
if (this.#literal !== undefined) {
return this.#literalFold ?
(this.#literalRe ??= newFoldRe(this.#literal)).test(s)
: s === this.#literal
}
// the length check means that the prefix and suffix do not
// overlap. Without the chars, the length in code points is from
// half of the UTF-16 length (if each one is a surrogate pair) to
// all of it, which is often enough to know.
const min = this.#min
const max = this.#max
if (chars === undefined) {
const most = s.length
const least = (most + 1) >> 1
if (most < min || least > max) return false
if (least < min || most > max) chars = codePoints(s)
}
if (
chars !== undefined &&
(chars.length < min || chars.length > max)
) {
return false
}
const prefix = this.#prefix.length
if (this.#affix) {
if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {
if (
!s.startsWith(this.#prefixStr) ||
!s.endsWith(this.#suffixStr)
) {
return false
}
} else {
chars ??= codePoints(s)
const end = chars.length - this.#suffix.length
if (
!hasAffix(this.#prefix, chars, 0) ||
!hasAffix(this.#suffix, chars, end)
) {
return false
}
}
}
const dotStart = !this.options.dot && s.startsWith('.')
if (this.#linear) {
// `.` and `..` only match literal dots, even with `dot:true`
if (s === '.' || s === '..') return false
// only a literal can match the leading dot. A `*` can not
// start a dotfile, even if it matches nothing.
if (dotStart && !prefix) return false
if (this.#wild) return true
chars ??= codePoints(s)
const end = chars.length - this.#suffix.length
return testLinear(this.#linear, chars, prefix, end)
}
chars ??= codePoints(s)
if (s === '.' || s === '..') {
this.#marks ??= marks(this.#size)
const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks))
const start = sim.state()
sim.add(start, this.#start, 0, true)
let state = sim.done(start)
for (let i = 0; i < chars.length; i++) {
state = sim.step(state, chars[i]!, i, true)
}
return state.match
}
this.#marks ??= marks(this.#size)
const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks))
let d = dfa.start(dotStart)
// read char codes from the string, so that a one-char string is
// only made for a cache miss
const str = chars === s
for (let i = 0; i < chars.length; i++) {
if (d.dead) return false
const code = str ? s.charCodeAt(i) : chars[i]!.charCodeAt(0)
d = d.ascii?.[code] ?? dfa.next(d, chars[i]!)
}
return d.match
}
/** a readable listing of the state machine */
toString(): string {
return show(this.#start)
}
}
@@ -0,0 +1,158 @@
// translate the various posix character classes into unicode properties
// this works across all unicode locales
// { <posix class>: [<translation>, negated]
const posixClasses: { [k: string]: [e: string, n?: boolean] } = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}'],
'[:alpha:]': ['\\p{L}\\p{Nl}'],
'[:ascii:]': ['\\x' + '00-\\x' + '7f'],
'[:blank:]': ['\\p{Zs}\\t'],
'[:cntrl:]': ['\\p{Cc}'],
'[:digit:]': ['\\p{Nd}'],
'[:graph:]': ['\\p{Z}\\p{C}', true],
'[:lower:]': ['\\p{Ll}'],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}\\p{S}'],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f'],
'[:upper:]': ['\\p{Lu}'],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}'],
'[:xdigit:]': ['A-Fa-f0-9'],
}
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s: string) => s.replace(/[[\]\\-]/g, '\\$&')
export type ParseClassResult = [re: RegExp, consumed: number]
export type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'
const noMatch = /$./
// Takes a glob string at a posix brace expression. Returns a RegExp
// that tests one character, and the number of glob chars consumed.
// If the class is not closed, consumed is 0, and the `[` must be
// treated as a literal character.
// Out of order ranges are removed. If nothing is left, the RegExp
// is `/$./`, and the rest of the glob is consumed, so that the
// whole glob cannot match.
export const parseClass = (
glob: string,
position: number,
nocase: boolean = false,
form?: Form,
): ParseClassResult => {
// normalize one class member, if it stays one code point
const norm = (c: string) => {
const n = form ? c.normalize(form) : c
return [...n].length === 1 ? n : c
}
const pos = position
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression')
}
/* c8 ignore stop */
const ranges: string[] = []
const negs: string[] = []
let i = pos + 1
let sawStart = false
let escaping = false
let negate = false
let endPos = pos
let rangeStart = ''
WHILE: while (i < glob.length) {
const c = String.fromCodePoint(glob.codePointAt(i)!)
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true
i++
continue
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1
break
}
sawStart = true
if (c === '\\') {
if (!escaping) {
escaping = true
i++
continue
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return [noMatch, glob.length - pos]
}
i += cls.length
if (neg) negs.push(unip)
else ranges.push(unip)
continue WHILE
}
}
}
// now it's just a normal character, effectively
escaping = false
const n = norm(c)
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))
} else if (n === rangeStart) {
ranges.push(braceEscape(n))
}
rangeStart = ''
i += c.length
continue
}
// now might be the start of a range.
// can be either c-d or c-] or c<more...>] or c] at this point
if (glob.startsWith('-]', i + c.length)) {
ranges.push(braceEscape(n + '-'))
i += c.length + 1
continue
}
if (glob.startsWith('-', i + c.length)) {
rangeStart = n
i += c.length + 1
continue
}
// not the start of a range, just a single character
ranges.push(braceEscape(n))
i += c.length
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return [noMatch, 0]
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return [noMatch, glob.length - pos]
}
const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'
const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'
const comb =
'^' +
(ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
: ranges.length ? sranges
: snegs)
return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]
}