@common.js/super-regex 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @common.js/super-regex
2
+
3
+ The [super-regex](https://www.npmjs.com/package/super-regex) package exported as CommonJS modules.
4
+
5
+ Exported from [super-regex@0.2.0](https://www.npmjs.com/package/super-regex/v/0.2.0) using https://github.com/etienne-martin/common.js.
package/index.d.ts ADDED
@@ -0,0 +1,64 @@
1
+ import {Options} from 'function-timeout';
2
+
3
+ export type Match = {
4
+ match: string;
5
+ index: number;
6
+ groups: string[];
7
+ namedGroups: Record<string, string>;
8
+ input: string;
9
+ };
10
+
11
+ export interface MatchesOptions extends Options {
12
+ /**
13
+ The time in milliseconds to wait before timing out when searching for each match.
14
+ */
15
+ readonly matchTimeout?: number;
16
+ }
17
+
18
+ /**
19
+ Returns a boolean for whether the given `regex` matches the given `string`.
20
+
21
+ If the regex takes longer to match than the given timeout, it returns `false`.
22
+
23
+ _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)._
24
+
25
+ @example
26
+ ```
27
+ import {isMatch} from 'super-regex';
28
+
29
+ console.log(isMatch(/\d+/, getUserInput(), {timeout: 1000}));
30
+ ```
31
+ */
32
+ export function isMatch(regex: RegExp, string: string, options?: Options): boolean;
33
+
34
+ /**
35
+ Returns the first match or `undefined` if there was no match.
36
+
37
+ If the regex takes longer to match than the given timeout, it returns `undefined`.
38
+
39
+ @example
40
+ ```
41
+ import {firstMatch} from 'super-regex';
42
+
43
+ console.log(firstMatch(/\d+/, getUserInput(), {timeout: 1000}));
44
+ ```
45
+ */
46
+ export function firstMatch(regex: RegExp, string: string, options?: Options): Match | undefined;
47
+
48
+ /**
49
+ Returns an iterable of matches.
50
+
51
+ If the regex takes longer to match than the given timeout, it returns an empty array.
52
+
53
+ __The `regex` must have the `/g` flag.__
54
+
55
+ @example
56
+ ```
57
+ import {matches} from 'super-regex';
58
+
59
+ console.log([...matches(/\d+/, getUserInput(), {timeout: 1000})]);
60
+ ```
61
+ */
62
+ export function matches(regex: RegExp, string: string, options?: MatchesOptions): Iterable<Match>;
63
+
64
+ export {Options} from 'function-timeout';
package/index.js ADDED
@@ -0,0 +1,289 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ isMatch: function() {
13
+ return isMatch;
14
+ },
15
+ firstMatch: function() {
16
+ return firstMatch;
17
+ },
18
+ matches: function() {
19
+ return matches;
20
+ }
21
+ });
22
+ var _functionTimeout = /*#__PURE__*/ _interopRequireWildcard(require("function-timeout"));
23
+ var _timeSpan = /*#__PURE__*/ _interopRequireDefault(require("time-span"));
24
+ var _cloneRegexp = /*#__PURE__*/ _interopRequireDefault(require("clone-regexp"));
25
+ function _defineProperty(obj, key, value) {
26
+ if (key in obj) {
27
+ Object.defineProperty(obj, key, {
28
+ value: value,
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true
32
+ });
33
+ } else {
34
+ obj[key] = value;
35
+ }
36
+ return obj;
37
+ }
38
+ function _interopRequireDefault(obj) {
39
+ return obj && obj.__esModule ? obj : {
40
+ default: obj
41
+ };
42
+ }
43
+ function _getRequireWildcardCache(nodeInterop) {
44
+ if (typeof WeakMap !== "function") return null;
45
+ var cacheBabelInterop = new WeakMap();
46
+ var cacheNodeInterop = new WeakMap();
47
+ return (_getRequireWildcardCache = function(nodeInterop) {
48
+ return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
49
+ })(nodeInterop);
50
+ }
51
+ function _interopRequireWildcard(obj, nodeInterop) {
52
+ if (!nodeInterop && obj && obj.__esModule) {
53
+ return obj;
54
+ }
55
+ if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
56
+ return {
57
+ default: obj
58
+ };
59
+ }
60
+ var cache = _getRequireWildcardCache(nodeInterop);
61
+ if (cache && cache.has(obj)) {
62
+ return cache.get(obj);
63
+ }
64
+ var newObj = {};
65
+ var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
66
+ for(var key in obj){
67
+ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
68
+ var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
69
+ if (desc && (desc.get || desc.set)) {
70
+ Object.defineProperty(newObj, key, desc);
71
+ } else {
72
+ newObj[key] = obj[key];
73
+ }
74
+ }
75
+ }
76
+ newObj.default = obj;
77
+ if (cache) {
78
+ cache.set(obj, newObj);
79
+ }
80
+ return newObj;
81
+ }
82
+ var __generator = (void 0) && (void 0).__generator || function(thisArg, body) {
83
+ var f, y, t, g, _ = {
84
+ label: 0,
85
+ sent: function() {
86
+ if (t[0] & 1) throw t[1];
87
+ return t[1];
88
+ },
89
+ trys: [],
90
+ ops: []
91
+ };
92
+ return g = {
93
+ next: verb(0),
94
+ "throw": verb(1),
95
+ "return": verb(2)
96
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
97
+ return this;
98
+ }), g;
99
+ function verb(n) {
100
+ return function(v) {
101
+ return step([
102
+ n,
103
+ v
104
+ ]);
105
+ };
106
+ }
107
+ function step(op) {
108
+ if (f) throw new TypeError("Generator is already executing.");
109
+ while(_)try {
110
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
111
+ if (y = 0, t) op = [
112
+ op[0] & 2,
113
+ t.value
114
+ ];
115
+ switch(op[0]){
116
+ case 0:
117
+ case 1:
118
+ t = op;
119
+ break;
120
+ case 4:
121
+ _.label++;
122
+ return {
123
+ value: op[1],
124
+ done: false
125
+ };
126
+ case 5:
127
+ _.label++;
128
+ y = op[1];
129
+ op = [
130
+ 0
131
+ ];
132
+ continue;
133
+ case 7:
134
+ op = _.ops.pop();
135
+ _.trys.pop();
136
+ continue;
137
+ default:
138
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
139
+ _ = 0;
140
+ continue;
141
+ }
142
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
143
+ _.label = op[1];
144
+ break;
145
+ }
146
+ if (op[0] === 6 && _.label < t[1]) {
147
+ _.label = t[1];
148
+ t = op;
149
+ break;
150
+ }
151
+ if (t && _.label < t[2]) {
152
+ _.label = t[2];
153
+ _.ops.push(op);
154
+ break;
155
+ }
156
+ if (t[2]) _.ops.pop();
157
+ _.trys.pop();
158
+ continue;
159
+ }
160
+ op = body.call(thisArg, _);
161
+ } catch (e) {
162
+ op = [
163
+ 6,
164
+ e
165
+ ];
166
+ y = 0;
167
+ } finally{
168
+ f = t = 0;
169
+ }
170
+ if (op[0] & 5) throw op[1];
171
+ return {
172
+ value: op[0] ? op[1] : void 0,
173
+ done: true
174
+ };
175
+ }
176
+ };
177
+ var _groups;
178
+ var resultToMatch = function(result) {
179
+ return {
180
+ match: result[0],
181
+ index: result.index,
182
+ groups: result.slice(1),
183
+ namedGroups: (_groups = result.groups) !== null && _groups !== void 0 ? _groups : {},
184
+ input: result.input
185
+ };
186
+ };
187
+ function isMatch(regex, string) {
188
+ var timeout = (arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}).timeout;
189
+ try {
190
+ return (0, _functionTimeout.default)(function() {
191
+ return (0, _cloneRegexp.default)(regex).test(string);
192
+ }, {
193
+ timeout: timeout
194
+ })();
195
+ } catch (error) {
196
+ if ((0, _functionTimeout.isTimeoutError)(error)) {
197
+ return false;
198
+ }
199
+ throw error;
200
+ }
201
+ }
202
+ function firstMatch(regex, string) {
203
+ var timeout = (arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}).timeout;
204
+ try {
205
+ var result = (0, _functionTimeout.default)(function() {
206
+ return (0, _cloneRegexp.default)(regex).exec(string);
207
+ }, {
208
+ timeout: timeout
209
+ })();
210
+ if (result === null) {
211
+ return;
212
+ }
213
+ return resultToMatch(result);
214
+ } catch (error) {
215
+ if ((0, _functionTimeout.isTimeoutError)(error)) {
216
+ return;
217
+ }
218
+ throw error;
219
+ }
220
+ }
221
+ function matches(regex, string) {
222
+ var ref = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}, _timeout = ref.timeout, timeout = _timeout === void 0 ? Number.POSITIVE_INFINITY : _timeout, _matchTimeout = ref.matchTimeout, matchTimeout = _matchTimeout === void 0 ? Number.POSITIVE_INFINITY : _matchTimeout;
223
+ if (!regex.global) {
224
+ throw new Error("The regex must have the global flag, otherwise, use `firstMatch()` instead");
225
+ }
226
+ return _defineProperty({}, Symbol.iterator, function() {
227
+ var matches, nextMatch, end, ref, value, done, error;
228
+ return __generator(this, function(_state) {
229
+ switch(_state.label){
230
+ case 0:
231
+ _state.trys.push([
232
+ 0,
233
+ 4,
234
+ ,
235
+ 5
236
+ ]);
237
+ matches = string.matchAll(regex); // The regex is only executed when iterated over.
238
+ _state.label = 1;
239
+ case 1:
240
+ if (!true) return [
241
+ 3,
242
+ 3
243
+ ];
244
+ nextMatch = (0, _functionTimeout.default)(function() {
245
+ return matches.next();
246
+ }, {
247
+ timeout: timeout !== Number.POSITIVE_INFINITY || matchTimeout !== Number.POSITIVE_INFINITY ? Math.min(timeout, matchTimeout) : undefined
248
+ }); // `matches.next` must be called within an arrow function so that it doesn't loose its context.
249
+ end = (0, _timeSpan.default)();
250
+ ref = nextMatch(), value = ref.value, done = ref.done;
251
+ timeout -= Math.ceil(end());
252
+ if (done) {
253
+ return [
254
+ 3,
255
+ 3
256
+ ];
257
+ }
258
+ return [
259
+ 4,
260
+ resultToMatch(value)
261
+ ];
262
+ case 2:
263
+ _state.sent();
264
+ return [
265
+ 3,
266
+ 1
267
+ ];
268
+ case 3:
269
+ return [
270
+ 3,
271
+ 5
272
+ ];
273
+ case 4:
274
+ error = _state.sent();
275
+ if (!(0, _functionTimeout.isTimeoutError)(error)) {
276
+ throw error;
277
+ }
278
+ return [
279
+ 3,
280
+ 5
281
+ ];
282
+ case 5:
283
+ return [
284
+ 2
285
+ ];
286
+ }
287
+ });
288
+ });
289
+ }
package/license ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
4
+
5
+ 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:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ 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.
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@common.js/super-regex",
3
+ "version": "0.2.0",
4
+ "description": "Make a regular expression time out if it takes too long to execute",
5
+ "license": "MIT",
6
+ "repository": "etienne-martin/common.js",
7
+ "funding": "https://github.com/sponsors/sindresorhus",
8
+ "type": "commonjs",
9
+ "types": "./index.d.ts",
10
+ "engines": {
11
+ "node": ">=14.16"
12
+ },
13
+ "scripts": {
14
+ "test": "xo && ava && tsd"
15
+ },
16
+ "files": [
17
+ "index.js",
18
+ "index.d.ts"
19
+ ],
20
+ "dependencies": {
21
+ "@common.js/clone-regexp": "^3.0.0",
22
+ "@common.js/function-timeout": "^0.1.0",
23
+ "@common.js/time-span": "^5.1.0"
24
+ },
25
+ "devDependencies": {
26
+ "ava": "^4.3.0",
27
+ "tsd": "^0.20.0",
28
+ "xo": "^0.49.0"
29
+ },
30
+ "homepage": "https://github.com/etienne-martin/common.js#readme",
31
+ "main": "./index.js"
32
+ }
package/readme.md ADDED
@@ -0,0 +1,81 @@
1
+ # super-regex
2
+
3
+ > Make a regular expression time out if it takes too long to execute
4
+
5
+ This can be used to prevent [ReDoS vulnerabilities](https://en.wikipedia.org/wiki/ReDoS) when running a regular expression against untrusted user input.
6
+
7
+ This package also has a better API than the built-in regular expression methods. For example, none of the methods mutate the regex.
8
+
9
+ The timeout only works in Node.js. In the browser, it will simply not time out.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install super-regex
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```js
20
+ import {isMatch} from 'super-regex';
21
+
22
+ console.log(isMatch(/\d+/, getUserInput(), {timeout: 1000}));
23
+ ```
24
+
25
+ ## API
26
+
27
+ ### isMatch(regex, string, options?)
28
+
29
+ Returns a boolean for whether the given `regex` matches the given `string`.
30
+
31
+ If the regex takes longer to match than the given timeout, it returns `false`.
32
+
33
+ *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).*
34
+
35
+ ### firstMatch(regex, string, options?)
36
+
37
+ Returns the first `Match` or `undefined` if there was no match.
38
+
39
+ If the regex takes longer to match than the given timeout, it returns `undefined`.
40
+
41
+ ### matches(regex, string, options?)
42
+
43
+ Returns an iterable of `Match`es.
44
+
45
+ If the regex takes longer to match than the given timeout, it returns an empty array.
46
+
47
+ **The `regex` must have the `/g` flag.**
48
+
49
+ #### options
50
+
51
+ Type: `object`
52
+
53
+ ##### timeout?
54
+
55
+ Type: `number` *(integer)*
56
+
57
+ The time in milliseconds to wait before timing out.
58
+
59
+ ##### matchTimeout?
60
+
61
+ Type: `number` *(integer)*
62
+
63
+ Only works in `matches()`.
64
+
65
+ The time in milliseconds to wait before timing out when searching for each match.
66
+
67
+ ### Match
68
+
69
+ ```ts
70
+ {
71
+ match: string;
72
+ index: number;
73
+ groups: string[];
74
+ namedGroups: {string: string}; // object with string values
75
+ input: string;
76
+ }
77
+ ```
78
+
79
+ ## Related
80
+
81
+ - [function-timeout](https://github.com/sindresorhus/function-timeout) - Make a synchronous function have a timeout