Skip to content

Commit

Permalink
doesUrlMatchPatterns
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante committed Jan 18, 2024
1 parent 25c0860 commit 0b6e0cb
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
18 changes: 18 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,24 @@ export function isValidPattern(matchPattern: string): boolean {
return matchPattern === '<all_urls>' || patternValidationRegex.test(matchPattern);
}

export function doesUrlMatchPatterns(url: string, ...matchPattern: string[]): boolean {
if (matchPattern.includes('<all_urls>') && allUrlsRegex.test(url)) {
return true;
}

if (matchPattern.includes('*://*/*') && allStarsRegex.test(url)) {
return true;
}

for (const pattern of matchPattern) {
if (patternToRegex(pattern).test(url)) {
return true;
}
}

return false;
}

function getRawPatternRegex(matchPattern: string): string {
assertValidPattern(matchPattern);

Expand Down
10 changes: 10 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
patternToRegex,
globToRegex,
excludeDuplicatePatterns
doesUrlMatchPatterns,
assertValidPattern,
isValidPattern,
} from 'webext-patterns';
Expand Down Expand Up @@ -112,6 +113,15 @@ excludeDuplicatePatterns([
// Returns ["https://*/*"]
```

#### doesUrlMatchPatterns(url, ...patterns)

Accepts a URL and any number of patterns and returns `true` if the URL matches any of the patterns. This is a convenience method that wraps `patternToRegex` for single use. If you plan on testing multiple URLs to the same pattern, it's better to convert the patterns to a regex once and reuse that.

```js
doesUrlMatchPatterns('https://google.com/', ['https://*.google.com/*', '*://example.com/*']);
// Returns true
```

#### assertValidPattern(pattern)

Accepts a pattern and throws an error if it's invalid.
Expand Down
3 changes: 2 additions & 1 deletion test/patterns.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import test from 'ava';
import {patternToRegex, isValidPattern, assertValidPattern} from '../index.js';
import {patternToRegex, isValidPattern, assertValidPattern, doesUrlMatchPatterns} from '../index.js';

function macro(t, pattern, matching) {
const regex = patternToRegex(pattern);
for (const url of matching) {
t.regex(url, regex);
t.true(isValidPattern(pattern));
t.notThrows(() => assertValidPattern(pattern));
t.true(doesUrlMatchPatterns(url, 'http://never.example.com/*', pattern, 'http://nope.example.com/*'));
}
}

Expand Down

0 comments on commit 0b6e0cb

Please sign in to comment.