path-to-regexp 2.2.0 → 3.0.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/History.md CHANGED
@@ -1,4 +1,19 @@
1
- 2.1.0 / 2018-03-06
1
+ 2.4.0 / 2018-08-26
2
+ ==================
3
+
4
+ * Support `start` option to disable anchoring from beginning of the string
5
+
6
+ 2.3.0 / 2018-08-20
7
+ ==================
8
+
9
+ * Use `delimiter` when processing repeated matching groups (e.g. `foo/bar` has no prefix, but has a delimiter)
10
+
11
+ 2.2.1 / 2018-04-24
12
+ ==================
13
+
14
+ * Allow empty string with `end: false` to match both relative and absolute paths
15
+
16
+ 2.2.0 / 2018-03-06
2
17
  ==================
3
18
 
4
19
  * Pass `token` as second argument to `encode` option (e.g. `encode(value, token)`)
package/Readme.md CHANGED
@@ -18,7 +18,7 @@ npm install path-to-regexp --save
18
18
  ## Usage
19
19
 
20
20
  ```javascript
21
- var pathToRegexp = require('path-to-regexp')
21
+ const pathToRegexp = require('path-to-regexp')
22
22
 
23
23
  // pathToRegexp(path, keys?, options?)
24
24
  // pathToRegexp.parse(path)
@@ -26,24 +26,24 @@ var pathToRegexp = require('path-to-regexp')
26
26
  ```
27
27
 
28
28
  - **path** A string, array of strings, or a regular expression.
29
- - **keys** An array to be populated with the keys found in the path.
29
+ - **keys** An array to populate with keys found in the path.
30
30
  - **options**
31
- - **sensitive** When `true` the route will be case sensitive. (default: `false`)
32
- - **strict** When `false` the trailing slash is optional. (default: `false`)
33
- - **end** When `false` the path will match at the beginning. (default: `true`)
34
- - Advanced options (use for non-pathname strings, e.g. host names):
35
- - **delimiter** The default delimiter for segments. (default: `'/'`)
36
- - **endsWith** Optional character, or list of characters, to treat as "end" characters.
37
- - **delimiters** List of characters to consider delimiters when parsing. (default: `'./'`)
31
+ - **sensitive** When `true` the regexp will be case sensitive. (default: `false`)
32
+ - **strict** When `true` the regexp allows an optional trailing delimiter to match. (default: `false`)
33
+ - **end** When `true` the regexp will match to the end of the string. (default: `true`)
34
+ - **start** When `true` the regexp will match from the beginning of the string. (default: `true`)
35
+ - **delimiter** The default delimiter for segments. (default: `'/'`)
36
+ - **endsWith** Optional character, or list of characters, to treat as "end" characters.
37
+ - **whitelist** List of characters to consider delimiters when parsing. (default: `undefined`, any character)
38
38
 
39
39
  ```javascript
40
- var keys = []
41
- var re = pathToRegexp('/foo/:bar', keys)
42
- // re = /^\/foo\/([^\/]+?)\/?$/i
40
+ const keys = []
41
+ const regexp = pathToRegexp('/foo/:bar', keys)
42
+ // regexp = /^\/foo\/([^\/]+?)\/?$/i
43
43
  // keys = [{ name: 'bar', prefix: '/', delimiter: '/', optional: false, repeat: false, pattern: '[^\\/]+?' }]
44
44
  ```
45
45
 
46
- **Please note:** The `RegExp` returned by `path-to-regexp` is intended for ordered data (e.g. pathnames, hostnames). It does not handle arbitrary data (e.g. query strings, URL fragments, JSON, etc).
46
+ **Please note:** The `RegExp` returned by `path-to-regexp` is intended for ordered data (e.g. pathnames, hostnames). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc).
47
47
 
48
48
  ### Parameters
49
49
 
@@ -51,17 +51,17 @@ The path argument is used to define parameters and populate the list of keys.
51
51
 
52
52
  #### Named Parameters
53
53
 
54
- Named parameters are defined by prefixing a colon to the parameter name (`:foo`). By default, the parameter will match until the following path segment.
54
+ Named parameters are defined by prefixing a colon to the parameter name (`:foo`). By default, the parameter will match until the next prefix (e.g. `[^/]+`).
55
55
 
56
56
  ```js
57
- var re = pathToRegexp('/:foo/:bar')
57
+ const regexp = pathToRegexp('/:foo/:bar')
58
58
  // keys = [{ name: 'foo', prefix: '/', ... }, { name: 'bar', prefix: '/', ... }]
59
59
 
60
60
  re.exec('/test/route')
61
61
  //=> ['/test/route', 'test', 'route']
62
62
  ```
63
63
 
64
- **Please note:** Parameter names must be made up of "word characters" (`[A-Za-z0-9_]`).
64
+ **Please note:** Parameter names must use "word characters" (`[A-Za-z0-9_]`).
65
65
 
66
66
  #### Parameter Modifiers
67
67
 
@@ -70,7 +70,7 @@ re.exec('/test/route')
70
70
  Parameters can be suffixed with a question mark (`?`) to make the parameter optional.
71
71
 
72
72
  ```js
73
- var re = pathToRegexp('/:foo/:bar?')
73
+ const regexp = pathToRegexp('/:foo/:bar?')
74
74
  // keys = [{ name: 'foo', ... }, { name: 'bar', delimiter: '/', optional: true, repeat: false }]
75
75
 
76
76
  re.exec('/test')
@@ -80,14 +80,14 @@ re.exec('/test/route')
80
80
  //=> ['/test', 'test', 'route']
81
81
  ```
82
82
 
83
- **Tip:** If the parameter is the _only_ value in the segment, the prefix is also optional.
83
+ **Tip:** The prefix is also optional, escape the prefix `\/` to make it required.
84
84
 
85
85
  ##### Zero or more
86
86
 
87
- Parameters can be suffixed with an asterisk (`*`) to denote a zero or more parameter matches. The prefix is taken into account for each match.
87
+ Parameters can be suffixed with an asterisk (`*`) to denote a zero or more parameter matches. The prefix is used for each match.
88
88
 
89
89
  ```js
90
- var re = pathToRegexp('/:foo*')
90
+ const regexp = pathToRegexp('/:foo*')
91
91
  // keys = [{ name: 'foo', delimiter: '/', optional: true, repeat: true }]
92
92
 
93
93
  re.exec('/')
@@ -99,10 +99,10 @@ re.exec('/bar/baz')
99
99
 
100
100
  ##### One or more
101
101
 
102
- Parameters can be suffixed with a plus sign (`+`) to denote a one or more parameter matches. The prefix is taken into account for each match.
102
+ Parameters can be suffixed with a plus sign (`+`) to denote a one or more parameter matches. The prefix is used for each match.
103
103
 
104
104
  ```js
105
- var re = pathToRegexp('/:foo+')
105
+ const regexp = pathToRegexp('/:foo+')
106
106
  // keys = [{ name: 'foo', delimiter: '/', optional: false, repeat: true }]
107
107
 
108
108
  re.exec('/')
@@ -112,41 +112,50 @@ re.exec('/bar/baz')
112
112
  //=> ['/bar/baz', 'bar/baz']
113
113
  ```
114
114
 
115
+ #### Unnamed Parameters
116
+
117
+ It is possible to write an unnamed parameter that only consists of a matching group. It works the same as a named parameter, except it will be numerically indexed.
118
+
119
+ ```js
120
+ const regexp = pathToRegexp('/:foo/(.*)')
121
+ // keys = [{ name: 'foo', ... }, { name: 0, ... }]
122
+
123
+ regexp.exec('/test/route')
124
+ //=> ['/test/route', 'test', 'route']
125
+ ```
126
+
115
127
  #### Custom Matching Parameters
116
128
 
117
- All parameters can be provided a custom regexp, which overrides the default match (`[^\/]+`). For example, you can match digits in the path:
129
+ All parameters can have a custom regexp, which overrides the default match (`[^/]+`). For example, you can match digits or names in a path:
118
130
 
119
131
  ```js
120
- var re = pathToRegexp('/icon-:foo(\\d+).png')
132
+ const regexpNumbers = pathToRegexp('/icon-:foo(\\d+).png')
121
133
  // keys = [{ name: 'foo', ... }]
122
134
 
123
- re.exec('/icon-123.png')
135
+ regexpNumbers.exec('/icon-123.png')
124
136
  //=> ['/icon-123.png', '123']
125
137
 
126
- re.exec('/icon-abc.png')
138
+ regexpNumbers.exec('/icon-abc.png')
127
139
  //=> null
128
- ```
129
140
 
130
- **Please note:** Backslashes need to be escaped with another backslash in strings.
141
+ const regexpWord = pathToRegexp('/(user|u)')
142
+ // keys = [{ name: 0, ... }]
131
143
 
132
- #### Unnamed Parameters
133
-
134
- It is possible to write an unnamed parameter that only consists of a matching group. It works the same as a named parameter, except it will be numerically indexed.
135
-
136
- ```js
137
- var re = pathToRegexp('/:foo/(.*)')
138
- // keys = [{ name: 'foo', ... }, { name: 0, ... }]
144
+ regexpWord.exec('/u')
145
+ //=> ['/u', 'u']
139
146
 
140
- re.exec('/test/route')
141
- //=> ['/test/route', 'test', 'route']
147
+ regexpWord.exec('/users')
148
+ //=> null
142
149
  ```
143
150
 
151
+ **Tip:** Backslashes need to be escaped with another backslash in JavaScript strings.
152
+
144
153
  ### Parse
145
154
 
146
155
  The parse function is exposed via `pathToRegexp.parse`. This will return an array of strings and keys.
147
156
 
148
157
  ```js
149
- var tokens = pathToRegexp.parse('/route/:foo/(.*)')
158
+ const tokens = pathToRegexp.parse('/route/:foo/(.*)')
150
159
 
151
160
  console.log(tokens[0])
152
161
  //=> "/route"
@@ -165,7 +174,7 @@ console.log(tokens[2])
165
174
  Path-To-RegExp exposes a compile function for transforming a string into a valid path.
166
175
 
167
176
  ```js
168
- var toPath = pathToRegexp.compile('/user/:id')
177
+ const toPath = pathToRegexp.compile('/user/:id')
169
178
 
170
179
  toPath({ id: 123 }) //=> "/user/123"
171
180
  toPath({ id: 'café' }) //=> "/user/caf%C3%A9"
@@ -174,12 +183,12 @@ toPath({ id: '/' }) //=> "/user/%2F"
174
183
  toPath({ id: ':/' }) //=> "/user/%3A%2F"
175
184
  toPath({ id: ':/' }, { encode: (value, token) => value }) //=> "/user/:/"
176
185
 
177
- var toPathRepeated = pathToRegexp.compile('/:segment+')
186
+ const toPathRepeated = pathToRegexp.compile('/:segment+')
178
187
 
179
188
  toPathRepeated({ segment: 'foo' }) //=> "/foo"
180
189
  toPathRepeated({ segment: ['a', 'b', 'c'] }) //=> "/a/b/c"
181
190
 
182
- var toPathRegexp = pathToRegexp.compile('/user/:id(\\d+)')
191
+ const toPathRegexp = pathToRegexp.compile('/user/:id(\\d+)')
183
192
 
184
193
  toPathRegexp({ id: 123 }) //=> "/user/123"
185
194
  toPathRegexp({ id: '123' }) //=> "/user/123"
@@ -192,17 +201,16 @@ toPathRegexp({ id: 'abc' }) //=> Throws `TypeError`.
192
201
 
193
202
  Path-To-RegExp exposes the two functions used internally that accept an array of tokens.
194
203
 
195
- * `pathToRegexp.tokensToRegExp(tokens, options)` Transform an array of tokens into a matching regular expression.
204
+ * `pathToRegexp.tokensToRegExp(tokens, keys?, options?)` Transform an array of tokens into a matching regular expression.
196
205
  * `pathToRegexp.tokensToFunction(tokens)` Transform an array of tokens into a path generator function.
197
206
 
198
207
  #### Token Information
199
208
 
200
209
  * `name` The name of the token (`string` for named or `number` for index)
201
- * `prefix` The prefix character for the segment (`/` or `.`)
202
- * `delimiter` The delimiter for the segment (same as prefix or `/`)
210
+ * `prefix` The prefix character for the segment (e.g. `/`)
211
+ * `delimiter` The delimiter for the segment (same as prefix or default delimiter)
203
212
  * `optional` Indicates the token is optional (`boolean`)
204
213
  * `repeat` Indicates the token is repeated (`boolean`)
205
- * `partial` Indicates this token is a partial path segment (`boolean`)
206
214
  * `pattern` The RegExp used to match this token (`string`)
207
215
 
208
216
  ## Compatibility with Express <= 4.x
package/index.d.ts CHANGED
@@ -3,17 +3,21 @@ declare function pathToRegexp (path: pathToRegexp.Path, keys?: pathToRegexp.Key[
3
3
  declare namespace pathToRegexp {
4
4
  export interface RegExpOptions {
5
5
  /**
6
- * When `true` the route will be case sensitive. (default: `false`)
6
+ * When `true` the regexp will be case sensitive. (default: `false`)
7
7
  */
8
8
  sensitive?: boolean;
9
9
  /**
10
- * When `false` the trailing slash is optional. (default: `false`)
10
+ * When `true` the regexp allows an optional trailing delimiter to match. (default: `false`)
11
11
  */
12
12
  strict?: boolean;
13
13
  /**
14
- * When `false` the path will match at the beginning. (default: `true`)
14
+ * When `true` the regexp will match to the end of the string. (default: `true`)
15
15
  */
16
16
  end?: boolean;
17
+ /**
18
+ * When `true` the regexp will match from the beginning of the string. (default: `true`)
19
+ */
20
+ start?: boolean;
17
21
  /**
18
22
  * Sets the final character for non-ending optimistic matches. (default: `/`)
19
23
  */
@@ -22,6 +26,10 @@ declare namespace pathToRegexp {
22
26
  * List of characters that can also be "end" characters.
23
27
  */
24
28
  endsWith?: string | string[];
29
+ /**
30
+ * List of characters to consider delimiters when parsing. (default: `undefined`, any character)
31
+ */
32
+ whitelist?: string | string[];
25
33
  }
26
34
 
27
35
  export interface ParseOptions {
@@ -29,10 +37,6 @@ declare namespace pathToRegexp {
29
37
  * Set the default delimiter for repeat parameters. (default: `'/'`)
30
38
  */
31
39
  delimiter?: string;
32
- /**
33
- * List of valid delimiter characters. (default: `'./'`)
34
- */
35
- delimiters?: string | string[];
36
40
  }
37
41
 
38
42
  /**
@@ -43,12 +47,12 @@ declare namespace pathToRegexp {
43
47
  /**
44
48
  * Transforming an Express-style path into a valid path.
45
49
  */
46
- export function compile (path: string, options?: ParseOptions): PathFunction;
50
+ export function compile <P extends object = object> (path: string, options?: ParseOptions): PathFunction<P>;
47
51
 
48
52
  /**
49
53
  * Transform an array of tokens into a path generator function.
50
54
  */
51
- export function tokensToFunction (tokens: Token[]): PathFunction;
55
+ export function tokensToFunction <P extends object = object> (tokens: Token[]): PathFunction<P>;
52
56
 
53
57
  /**
54
58
  * Transform an array of tokens into a matching regular expression.
@@ -62,7 +66,6 @@ declare namespace pathToRegexp {
62
66
  optional: boolean;
63
67
  repeat: boolean;
64
68
  pattern: string;
65
- partial: boolean;
66
69
  }
67
70
 
68
71
  interface PathFunctionOptions {
@@ -74,7 +77,7 @@ declare namespace pathToRegexp {
74
77
 
75
78
  export type Token = string | Key;
76
79
  export type Path = string | RegExp | Array<string | RegExp>;
77
- export type PathFunction = (data?: Object, options?: PathFunctionOptions) => string;
80
+ export type PathFunction <P extends object = object> = (data?: P, options?: PathFunctionOptions) => string;
78
81
  }
79
82
 
80
83
  export = pathToRegexp;
package/index.js CHANGED
@@ -11,7 +11,6 @@ module.exports.tokensToRegExp = tokensToRegExp
11
11
  * Default configs.
12
12
  */
13
13
  var DEFAULT_DELIMITER = '/'
14
- var DEFAULT_DELIMITERS = './'
15
14
 
16
15
  /**
17
16
  * The main path matching regexp utility.
@@ -25,8 +24,8 @@ var PATH_REGEXP = new RegExp([
25
24
  // Match Express-style parameters and un-named parameters with a prefix
26
25
  // and optional suffixes. Matches appear as:
27
26
  //
28
- // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?"]
29
- // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined]
27
+ // ":test(\\d+)?" => ["test", "\d+", undefined, "?"]
28
+ // "(\\d+)" => [undefined, undefined, "\d+", undefined]
30
29
  '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?'
31
30
  ].join('|'), 'g')
32
31
 
@@ -43,7 +42,7 @@ function parse (str, options) {
43
42
  var index = 0
44
43
  var path = ''
45
44
  var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER
46
- var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS
45
+ var whitelist = (options && options.whitelist) || undefined
47
46
  var pathEscaped = false
48
47
  var res
49
48
 
@@ -62,7 +61,6 @@ function parse (str, options) {
62
61
  }
63
62
 
64
63
  var prev = ''
65
- var next = str[index]
66
64
  var name = res[2]
67
65
  var capture = res[3]
68
66
  var group = res[4]
@@ -70,9 +68,11 @@ function parse (str, options) {
70
68
 
71
69
  if (!pathEscaped && path.length) {
72
70
  var k = path.length - 1
71
+ var c = path[k]
72
+ var matches = whitelist ? whitelist.indexOf(c) > -1 : true
73
73
 
74
- if (delimiters.indexOf(path[k]) > -1) {
75
- prev = path[k]
74
+ if (matches) {
75
+ prev = c
76
76
  path = path.slice(0, k)
77
77
  }
78
78
  }
@@ -84,11 +84,10 @@ function parse (str, options) {
84
84
  pathEscaped = false
85
85
  }
86
86
 
87
- var partial = prev !== '' && next !== undefined && next !== prev
88
87
  var repeat = modifier === '+' || modifier === '*'
89
88
  var optional = modifier === '?' || modifier === '*'
90
- var delimiter = prev || defaultDelimiter
91
89
  var pattern = capture || group
90
+ var delimiter = prev || defaultDelimiter
92
91
 
93
92
  tokens.push({
94
93
  name: name || key++,
@@ -96,8 +95,9 @@ function parse (str, options) {
96
95
  delimiter: delimiter,
97
96
  optional: optional,
98
97
  repeat: repeat,
99
- partial: partial,
100
- pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?'
98
+ pattern: pattern
99
+ ? escapeGroup(pattern)
100
+ : '[^' + escapeString(delimiter === defaultDelimiter ? delimiter : (delimiter + defaultDelimiter)) + ']+?'
101
101
  })
102
102
  }
103
103
 
@@ -184,12 +184,7 @@ function tokensToFunction (tokens) {
184
184
  continue
185
185
  }
186
186
 
187
- if (token.optional) {
188
- // Prepend partial segment prefixes.
189
- if (token.partial) path += token.prefix
190
-
191
- continue
192
- }
187
+ if (token.optional) continue
193
188
 
194
189
  throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string'))
195
190
  }
@@ -249,7 +244,6 @@ function regexpToRegexp (path, keys) {
249
244
  delimiter: null,
250
245
  optional: false,
251
246
  repeat: false,
252
- partial: false,
253
247
  pattern: null
254
248
  })
255
249
  }
@@ -300,12 +294,11 @@ function tokensToRegExp (tokens, keys, options) {
300
294
  options = options || {}
301
295
 
302
296
  var strict = options.strict
297
+ var start = options.start !== false
303
298
  var end = options.end !== false
304
- var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER)
305
- var delimiters = options.delimiters || DEFAULT_DELIMITERS
299
+ var delimiter = options.delimiter || DEFAULT_DELIMITER
306
300
  var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|')
307
- var route = ''
308
- var isEndDelimited = false
301
+ var route = start ? '^' : ''
309
302
 
310
303
  // Iterate over the tokens and create our regexp string.
311
304
  for (var i = 0; i < tokens.length; i++) {
@@ -313,37 +306,40 @@ function tokensToRegExp (tokens, keys, options) {
313
306
 
314
307
  if (typeof token === 'string') {
315
308
  route += escapeString(token)
316
- isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1
317
309
  } else {
318
- var prefix = escapeString(token.prefix)
319
310
  var capture = token.repeat
320
- ? '(?:' + token.pattern + ')(?:' + prefix + '(?:' + token.pattern + '))*'
311
+ ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*'
321
312
  : token.pattern
322
313
 
323
314
  if (keys) keys.push(token)
324
315
 
325
316
  if (token.optional) {
326
- if (token.partial) {
327
- route += prefix + '(' + capture + ')?'
317
+ if (!token.prefix) {
318
+ route += '(' + capture + ')?'
328
319
  } else {
329
- route += '(?:' + prefix + '(' + capture + '))?'
320
+ route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?'
330
321
  }
331
322
  } else {
332
- route += prefix + '(' + capture + ')'
323
+ route += escapeString(token.prefix) + '(' + capture + ')'
333
324
  }
334
325
  }
335
326
  }
336
327
 
337
328
  if (end) {
338
- if (!strict) route += '(?:' + delimiter + ')?'
329
+ if (!strict) route += '(?:' + escapeString(delimiter) + ')?'
339
330
 
340
331
  route += endsWith === '$' ? '$' : '(?=' + endsWith + ')'
341
332
  } else {
342
- if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?'
343
- if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')'
333
+ var endToken = tokens[tokens.length - 1]
334
+ var isEndDelimited = typeof endToken === 'string'
335
+ ? endToken[endToken.length - 1] === delimiter
336
+ : endToken === undefined
337
+
338
+ if (!strict) route += '(?:' + escapeString(delimiter) + '(?=' + endsWith + '))?'
339
+ if (!isEndDelimited) route += '(?=' + escapeString(delimiter) + '|' + endsWith + ')'
344
340
  }
345
341
 
346
- return new RegExp('^' + route, flags(options))
342
+ return new RegExp(route, flags(options))
347
343
  }
348
344
 
349
345
  /**
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "path-to-regexp",
3
3
  "description": "Express style path to RegExp utility",
4
- "version": "2.2.0",
4
+ "version": "3.0.0",
5
5
  "main": "index.js",
6
6
  "typings": "index.d.ts",
7
7
  "files": [
@@ -33,13 +33,13 @@
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/chai": "^4.0.4",
36
- "@types/mocha": "^2.2.42",
37
- "@types/node": "^8.0.24",
36
+ "@types/mocha": "^5.2.5",
37
+ "@types/node": "^10.7.1",
38
38
  "chai": "^4.1.1",
39
39
  "istanbul": "^0.4.5",
40
- "mocha": "^3.5.0",
41
- "standard": "^10.0.3",
42
- "ts-node": "^3.3.0",
43
- "typescript": "^2.4.2"
40
+ "mocha": "^5.2.0",
41
+ "standard": "^12.0.1",
42
+ "ts-node": "^7.0.1",
43
+ "typescript": "^3.0.1"
44
44
  }
45
45
  }