Blazing fast and accurate glob matcher written in JavaScript, with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.
npx @tessl/cli install tessl/npm-picomatch@4.0.00
# Picomatch
1
2
Picomatch is a blazing fast and accurate glob matcher written in JavaScript with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.
3
4
## Package Information
5
6
- **Package Name**: picomatch
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install picomatch`
10
11
## Core Imports
12
13
```javascript
14
const picomatch = require('picomatch');
15
```
16
17
ES Modules:
18
19
```javascript
20
import picomatch from 'picomatch';
21
```
22
23
For POSIX-only usage:
24
25
```javascript
26
const picomatch = require('picomatch/posix');
27
```
28
29
## Basic Usage
30
31
```javascript
32
const picomatch = require('picomatch');
33
34
// Create a matcher function
35
const isMatch = picomatch('*.js');
36
37
console.log(isMatch('file.js')); // => true
38
console.log(isMatch('file.txt')); // => false
39
40
// Multiple patterns
41
const isMatchAny = picomatch(['*.js', '*.ts']);
42
console.log(isMatchAny('app.ts')); // => true
43
44
// With options
45
const matcher = picomatch('**/*.js', { ignore: '**/node_modules/**' });
46
console.log(matcher('src/utils.js')); // => true
47
console.log(matcher('node_modules/lib.js')); // => false
48
```
49
50
## Architecture
51
52
Picomatch is built around several key components:
53
54
- **Main Function**: Primary export that creates matcher functions from glob patterns
55
- **Static Methods**: Collection of utility methods for parsing, compiling, and testing patterns
56
- **Pattern Engine**: High-performance glob pattern parsing and regex compilation
57
- **Cross-Platform Support**: Windows and POSIX path handling with automatic detection
58
- **Zero Dependencies**: Self-contained implementation for minimal overhead
59
60
## Capabilities
61
62
### Core Matching
63
64
Primary matcher function creation and pattern matching capabilities. The main entry point for creating efficient matcher functions from glob patterns.
65
66
```javascript { .api }
67
/**
68
* Creates a matcher function from one or more glob patterns
69
* @param {string|string[]} glob - Glob pattern(s) to compile
70
* @param {object} options - Configuration options
71
* @param {boolean} returnState - Whether to return state information
72
* @returns {function} Matcher function that tests strings
73
*/
74
function picomatch(glob, options, returnState = false);
75
```
76
77
[Core Matching](./core-matching.md)
78
79
### Pattern Testing and Validation
80
81
Direct pattern testing without creating persistent matcher functions. Useful for one-off matching operations.
82
83
```javascript { .api }
84
/**
85
* Test input with the given regex
86
* @param {string} input - String to test
87
* @param {RegExp} regex - Regular expression to test against
88
* @param {object} options - Configuration options
89
* @param {object} context - Additional context (glob, posix)
90
* @returns {object} Object with matching info
91
*/
92
picomatch.test(input, regex, options, { glob, posix });
93
94
/**
95
* Returns true if any of the given patterns match the string
96
* @param {string} str - String to test
97
* @param {string|string[]} patterns - Glob pattern(s) to test
98
* @param {object} options - Configuration options
99
* @returns {boolean} True if any patterns match
100
*/
101
picomatch.isMatch(str, patterns, options);
102
```
103
104
[Pattern Testing](./pattern-testing.md)
105
106
### Pattern Parsing and Compilation
107
108
Low-level pattern parsing and regex compilation utilities for advanced use cases and custom implementations.
109
110
```javascript { .api }
111
/**
112
* Parse a glob pattern to create source string for regex
113
* @param {string|string[]} pattern - Glob pattern(s) to parse
114
* @param {object} options - Configuration options
115
* @returns {object|object[]} Parsed pattern object(s)
116
*/
117
picomatch.parse(pattern, options);
118
119
/**
120
* Create a regular expression from glob pattern
121
* @param {string} input - Glob pattern
122
* @param {object} options - Configuration options
123
* @param {boolean} returnOutput - Return output instead of regex
124
* @param {boolean} returnState - Include state in result
125
* @returns {RegExp} Compiled regular expression
126
*/
127
picomatch.makeRe(input, options, returnOutput, returnState);
128
```
129
130
[Pattern Parsing](./pattern-parsing.md)
131
132
### Constants and Utilities
133
134
Access to internal constants and utility functions for advanced use cases.
135
136
```javascript { .api }
137
/**
138
* Internal constants used by picomatch
139
*/
140
picomatch.constants: {
141
/** Maximum length for glob patterns */
142
MAX_LENGTH: 65536;
143
144
/** POSIX bracket expressions */
145
POSIX_REGEX_SOURCE: {
146
alnum: string;
147
alpha: string;
148
ascii: string;
149
blank: string;
150
cntrl: string;
151
digit: string;
152
graph: string;
153
lower: string;
154
print: string;
155
punct: string;
156
space: string;
157
upper: string;
158
word: string;
159
xdigit: string;
160
};
161
162
/** Regular expressions for parsing */
163
REGEX_BACKSLASH: RegExp;
164
REGEX_NON_SPECIAL_CHARS: RegExp;
165
REGEX_SPECIAL_CHARS: RegExp;
166
REGEX_SPECIAL_CHARS_BACKREF: RegExp;
167
REGEX_SPECIAL_CHARS_GLOBAL: RegExp;
168
REGEX_REMOVE_BACKSLASH: RegExp;
169
170
/** Pattern replacements for optimization */
171
REPLACEMENTS: {
172
'***': '*';
173
'**/**': '**';
174
'**/**/**': '**';
175
};
176
177
/** Character code constants */
178
CHAR_0: 48;
179
CHAR_9: 57;
180
CHAR_UPPERCASE_A: 65;
181
CHAR_LOWERCASE_A: 97;
182
CHAR_UPPERCASE_Z: 90;
183
CHAR_LOWERCASE_Z: 122;
184
CHAR_LEFT_PARENTHESES: 40;
185
CHAR_RIGHT_PARENTHESES: 41;
186
CHAR_ASTERISK: 42;
187
CHAR_AMPERSAND: 38;
188
CHAR_AT: 64;
189
CHAR_BACKWARD_SLASH: 92;
190
CHAR_CARRIAGE_RETURN: 13;
191
CHAR_CIRCUMFLEX_ACCENT: 94;
192
CHAR_COLON: 58;
193
CHAR_COMMA: 44;
194
CHAR_DOT: 46;
195
CHAR_DOUBLE_QUOTE: 34;
196
CHAR_EQUAL: 61;
197
CHAR_EXCLAMATION_MARK: 33;
198
CHAR_FORM_FEED: 12;
199
CHAR_FORWARD_SLASH: 47;
200
CHAR_GRAVE_ACCENT: 96;
201
CHAR_HASH: 35;
202
CHAR_HYPHEN_MINUS: 45;
203
CHAR_LEFT_ANGLE_BRACKET: 60;
204
CHAR_LEFT_CURLY_BRACE: 123;
205
CHAR_LEFT_SQUARE_BRACKET: 91;
206
CHAR_LINE_FEED: 10;
207
CHAR_NO_BREAK_SPACE: 160;
208
CHAR_PERCENT: 37;
209
CHAR_PLUS: 43;
210
CHAR_QUESTION_MARK: 63;
211
CHAR_RIGHT_ANGLE_BRACKET: 62;
212
CHAR_RIGHT_CURLY_BRACE: 125;
213
CHAR_RIGHT_SQUARE_BRACKET: 93;
214
CHAR_SEMICOLON: 59;
215
CHAR_SINGLE_QUOTE: 39;
216
CHAR_SPACE: 32;
217
CHAR_TAB: 9;
218
CHAR_UNDERSCORE: 95;
219
CHAR_VERTICAL_LINE: 124;
220
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279;
221
222
/** Create extglob character definitions */
223
extglobChars: (chars: object) => {
224
'!': { type: 'negate'; open: string; close: string };
225
'?': { type: 'qmark'; open: string; close: string };
226
'+': { type: 'plus'; open: string; close: string };
227
'*': { type: 'star'; open: string; close: string };
228
'@': { type: 'at'; open: string; close: string };
229
};
230
231
/** Create glob character definitions for platform */
232
globChars: (win32: boolean) => {
233
DOT_LITERAL: string;
234
PLUS_LITERAL: string;
235
QMARK_LITERAL: string;
236
SLASH_LITERAL: string;
237
ONE_CHAR: string;
238
QMARK: string;
239
END_ANCHOR: string;
240
DOTS_SLASH: string;
241
NO_DOT: string;
242
NO_DOTS: string;
243
NO_DOT_SLASH: string;
244
NO_DOTS_SLASH: string;
245
QMARK_NO_DOT: string;
246
STAR: string;
247
START_ANCHOR: string;
248
SEP: string;
249
};
250
}
251
```
252
253
## Options
254
255
```javascript { .api }
256
interface PicomatchOptions {
257
/** Force Windows-style path handling */
258
windows?: boolean;
259
/** Patterns to ignore */
260
ignore?: string | string[];
261
/** Callback for match events */
262
onMatch?: (result: MatchResult) => void;
263
/** Callback for all results */
264
onResult?: (result: MatchResult) => void;
265
/** Callback for ignored matches */
266
onIgnore?: (result: MatchResult) => void;
267
/** Enable/disable fast path optimizations */
268
fastpaths?: boolean;
269
/** Custom path format function */
270
format?: (path: string) => string;
271
/** Enable capture groups */
272
capture?: boolean;
273
/** Match anywhere in string (not anchored) */
274
contains?: boolean;
275
/** Match only basename (equivalent to basename) */
276
basename?: boolean;
277
/** Match only basename */
278
matchBase?: boolean;
279
/** Case insensitive matching */
280
nocase?: boolean;
281
/** Enable debug mode */
282
debug?: boolean;
283
/** Custom regex flags */
284
flags?: string;
285
/** Disable globstars (**) */
286
noglobstar?: boolean;
287
/** Disable extglobs (+(a|b)) */
288
noextglob?: boolean;
289
/** Disable braces ({a,b}) */
290
nobrace?: boolean;
291
/** Disable brackets ([abc]) */
292
nobracket?: boolean;
293
/** Custom expand range function for brackets */
294
expandRange?: (left: string, right: string, options: object) => string;
295
/** Strict slash handling */
296
strictSlashes?: boolean;
297
/** Unescape regex characters */
298
unescape?: boolean;
299
/** Maximum regex length */
300
maxLength?: number;
301
/** POSIX character classes */
302
posix?: boolean;
303
/** Dot handling in patterns */
304
dot?: boolean;
305
/** Custom star replacement */
306
star?: string;
307
/** Bash compatibility mode */
308
bash?: boolean;
309
}
310
311
interface MatchResult {
312
/** Original glob pattern */
313
glob: string;
314
/** Parsed state object */
315
state: {
316
input: string;
317
tokens: Token[];
318
output: string;
319
negated: boolean;
320
fastpaths: boolean;
321
};
322
/** Compiled regular expression */
323
regex: RegExp;
324
/** Whether POSIX mode is enabled */
325
posix: boolean;
326
/** Input string being tested */
327
input: string;
328
/** Formatted output string */
329
output: string;
330
/** Regex match result */
331
match: RegExpExecArray | null;
332
/** Whether the pattern matched */
333
isMatch: boolean;
334
}
335
336
interface Token {
337
/** Token type (star, text, globstar, etc.) */
338
type: string;
339
/** Token value */
340
value: string;
341
/** Compiled output for token */
342
output?: string;
343
/** Whether token is escaped */
344
escaped?: boolean;
345
/** Whether token is negated */
346
negated?: boolean;
347
}
348
```
349
350
## Error Handling
351
352
Picomatch throws specific errors for invalid inputs and provides error handling options:
353
354
```javascript { .api }
355
/** Exception thrown for invalid patterns */
356
class TypeError extends Error {
357
constructor(message: string);
358
}
359
```
360
361
**Common Error Conditions:**
362
363
- `TypeError: Expected pattern to be a non-empty string` - when pattern is empty, null, or not a string
364
- `TypeError: Expected input to be a string` - when input to test methods is not a string
365
- Invalid regex patterns return fallback regex `/$^/` (matches nothing) when debug is false
366
- Invalid regex patterns throw errors when debug is true
367
368
**Usage Examples:**
369
370
```javascript
371
// Pattern validation
372
try {
373
const matcher = picomatch(''); // Throws TypeError
374
} catch (error) {
375
console.log(error.message); // => 'Expected pattern to be a non-empty string'
376
}
377
378
try {
379
const matcher = picomatch(null); // Throws TypeError
380
} catch (error) {
381
console.log(error.message); // => 'Expected pattern to be a non-empty string'
382
}
383
384
// Input validation
385
try {
386
picomatch.test(123, /test/); // Throws TypeError
387
} catch (error) {
388
console.log(error.message); // => 'Expected input to be a string'
389
}
390
391
// Regex error handling
392
const validRegex = picomatch.toRegex('*.js'); // Works fine
393
const invalidRegex = picomatch.toRegex('[invalid'); // Returns /$^/ (matches nothing)
394
395
// With debug mode
396
try {
397
const debugRegex = picomatch.toRegex('[invalid', { debug: true }); // Throws
398
} catch (error) {
399
console.log('Invalid regex pattern detected');
400
}
401
```