feature: vor und nachteile

This commit is contained in:
Hikyu
2026-05-31 13:54:31 +02:00
parent 552a947a1c
commit e3dad17446
23270 changed files with 3024794 additions and 200 deletions
+64
View File
@@ -0,0 +1,64 @@
import {Options} from 'function-timeout';
export type Match = {
match: string;
index: number;
groups: string[];
namedGroups: Record<string, string>;
input: string;
};
export interface MatchesOptions extends Options {
/**
The time in milliseconds to wait before timing out when searching for each match.
*/
readonly matchTimeout?: number;
}
/**
Returns a boolean for whether the given `regex` matches the given `string`.
If the regex takes longer to match than the given timeout, it returns `false`.
_This method is similar to [`RegExp#test`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test), but differs in that the given `regex` is [never mutated, even when it has the `/g` flag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test#using_test_on_a_regex_with_the_global_flag)._
@example
```
import {isMatch} from 'super-regex';
console.log(isMatch(/\d+/, getUserInput(), {timeout: 1000}));
```
*/
export function isMatch(regex: RegExp, string: string, options?: Options): boolean;
/**
Returns the first match or `undefined` if there was no match.
If the regex takes longer to match than the given timeout, it returns `undefined`.
@example
```
import {firstMatch} from 'super-regex';
console.log(firstMatch(/\d+/, getUserInput(), {timeout: 1000}));
```
*/
export function firstMatch(regex: RegExp, string: string, options?: Options): Match | undefined;
/**
Returns an iterable of matches.
If the regex takes longer to match than the given timeout, it returns an empty array.
__The `regex` must have the `/g` flag.__
@example
```
import {matches} from 'super-regex';
console.log([...matches(/\d+/, getUserInput(), {timeout: 1000})]);
```
*/
export function matches(regex: RegExp, string: string, options?: MatchesOptions): Iterable<Match>;
export {Options} from 'function-timeout';
+73
View File
@@ -0,0 +1,73 @@
import functionTimeout, {isTimeoutError} from 'function-timeout';
import timeSpan from 'time-span';
import cloneRegexp from 'clone-regexp'; // TODO: Use `structuredClone` instead when targeting Node.js 18.
const resultToMatch = result => ({
match: result[0],
index: result.index,
groups: result.slice(1),
namedGroups: result.groups ?? {},
input: result.input,
});
export function isMatch(regex, string, {timeout} = {}) {
try {
return functionTimeout(() => cloneRegexp(regex).test(string), {timeout})();
} catch (error) {
if (isTimeoutError(error)) {
return false;
}
throw error;
}
}
export function firstMatch(regex, string, {timeout} = {}) {
try {
const result = functionTimeout(() => cloneRegexp(regex).exec(string), {timeout})();
if (result === null) {
return;
}
return resultToMatch(result);
} catch (error) {
if (isTimeoutError(error)) {
return;
}
throw error;
}
}
export function matches(regex, string, {timeout = Number.POSITIVE_INFINITY, matchTimeout = Number.POSITIVE_INFINITY} = {}) {
if (!regex.global) {
throw new Error('The regex must have the global flag, otherwise, use `firstMatch()` instead');
}
return {
* [Symbol.iterator]() {
try {
const matches = string.matchAll(regex); // The regex is only executed when iterated over.
while (true) {
const nextMatch = functionTimeout(() => matches.next(), {timeout: (timeout !== Number.POSITIVE_INFINITY || matchTimeout !== Number.POSITIVE_INFINITY) ? Math.min(timeout, matchTimeout) : undefined}); // `matches.next` must be called within an arrow function so that it doesn't loose its context.
const end = timeSpan();
const {value, done} = nextMatch();
timeout -= Math.ceil(end());
if (done) {
break;
}
yield resultToMatch(value);
}
} catch (error) {
if (!isTimeoutError(error)) {
throw error;
}
}
},
};
}
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+52
View File
@@ -0,0 +1,52 @@
{
"name": "super-regex",
"version": "0.2.0",
"description": "Make a regular expression time out if it takes too long to execute",
"license": "MIT",
"repository": "sindresorhus/super-regex",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"types": "./index.d.ts",
"engines": {
"node": ">=14.16"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"regex",
"regexp",
"regular",
"expression",
"timeout",
"time",
"out",
"cancel",
"expire",
"abort",
"redos",
"security",
"script",
"execute"
],
"dependencies": {
"clone-regexp": "^3.0.0",
"function-timeout": "^0.1.0",
"time-span": "^5.1.0"
},
"devDependencies": {
"ava": "^4.3.0",
"tsd": "^0.20.0",
"xo": "^0.49.0"
}
}
+81
View File
@@ -0,0 +1,81 @@
# super-regex
> Make a regular expression time out if it takes too long to execute
This can be used to prevent [ReDoS vulnerabilities](https://en.wikipedia.org/wiki/ReDoS) when running a regular expression against untrusted user input.
This package also has a better API than the built-in regular expression methods. For example, none of the methods mutate the regex.
The timeout only works in Node.js. In the browser, it will simply not time out.
## Install
```sh
npm install super-regex
```
## Usage
```js
import {isMatch} from 'super-regex';
console.log(isMatch(/\d+/, getUserInput(), {timeout: 1000}));
```
## API
### isMatch(regex, string, options?)
Returns a boolean for whether the given `regex` matches the given `string`.
If the regex takes longer to match than the given timeout, it returns `false`.
*This method is similar to [`RegExp#test`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test), but differs in that the given `regex` is [never mutated, even when it has the `/g` flag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test#using_test_on_a_regex_with_the_global_flag).*
### firstMatch(regex, string, options?)
Returns the first `Match` or `undefined` if there was no match.
If the regex takes longer to match than the given timeout, it returns `undefined`.
### matches(regex, string, options?)
Returns an iterable of `Match`es.
If the regex takes longer to match than the given timeout, it returns an empty array.
**The `regex` must have the `/g` flag.**
#### options
Type: `object`
##### timeout?
Type: `number` *(integer)*
The time in milliseconds to wait before timing out.
##### matchTimeout?
Type: `number` *(integer)*
Only works in `matches()`.
The time in milliseconds to wait before timing out when searching for each match.
### Match
```ts
{
match: string;
index: number;
groups: string[];
namedGroups: {string: string}; // object with string values
input: string;
}
```
## Related
- [function-timeout](https://github.com/sindresorhus/function-timeout) - Make a synchronous function have a timeout