path-to-regexp 6.2.1 → 7.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/Readme.md CHANGED
@@ -16,59 +16,54 @@ npm install path-to-regexp --save
16
16
 
17
17
  ## Usage
18
18
 
19
- ```javascript
19
+ ```js
20
20
  const { pathToRegexp, match, parse, compile } = require("path-to-regexp");
21
21
 
22
- // pathToRegexp(path, keys?, options?)
23
- // match(path)
24
- // parse(path)
25
- // compile(path)
22
+ // pathToRegexp(path, options?)
23
+ // match(path, options?)
24
+ // parse(path, options?)
25
+ // compile(path, options?)
26
26
  ```
27
27
 
28
28
  ### Path to regexp
29
29
 
30
- The `pathToRegexp` function will return a regular expression object based on the provided `path` argument. It accepts the following arguments:
30
+ The `pathToRegexp` function returns a regular expression with `keys` as a property. It accepts the following arguments:
31
31
 
32
- - **path** A string, array of strings, or a regular expression.
33
- - **keys** _(optional)_ An array to populate with keys found in the path.
32
+ - **path** A string.
34
33
  - **options** _(optional)_
35
- - **sensitive** When `true` the regexp will be case sensitive. (default: `false`)
36
- - **strict** When `true` the regexp won't allow an optional trailing delimiter to match. (default: `false`)
37
- - **end** When `true` the regexp will match to the end of the string. (default: `true`)
38
- - **start** When `true` the regexp will match from the beginning of the string. (default: `true`)
39
- - **delimiter** The default delimiter for segments, e.g. `[^/#?]` for `:named` patterns. (default: `'/#?'`)
40
- - **endsWith** Optional character, or list of characters, to treat as "end" characters.
41
- - **encode** A function to encode strings before inserting into `RegExp`. (default: `x => x`)
42
- - **prefixes** List of characters to automatically consider prefixes when parsing. (default: `./`)
43
-
44
- ```javascript
45
- const keys = [];
46
- const regexp = pathToRegexp("/foo/:bar", keys);
47
- // regexp = /^\/foo(?:\/([^\/#\?]+?))[\/#\?]?$/i
48
- // keys = [{ name: 'bar', prefix: '/', suffix: '', pattern: '[^\\/#\\?]+?', modifier: '' }]
34
+ - **sensitive** Regexp will be case sensitive. (default: `false`)
35
+ - **trailing** Regexp allows an optional trailing delimiter to match. (default: `true`)
36
+ - **end** Match to the end of the string. (default: `true`)
37
+ - **start** Match from the beginning of the string. (default: `true`)
38
+ - **loose** Allow the delimiter to be repeated an arbitrary number of times. (default: `true`)
39
+ - **delimiter** The default delimiter for segments, e.g. `[^/]` for `:named` parameters. (default: `'/'`)
40
+ - **encodePath** A function to encode strings before inserting into `RegExp`. (default: `x => x`, recommended: [`encodeurl`](https://github.com/pillarjs/encodeurl))
41
+
42
+ ```js
43
+ const regexp = pathToRegexp("/foo/:bar");
44
+ // regexp = /^\/+foo(?:\/+([^\/]+?))(?:\/+)?$/i
45
+ // keys = [{ name: 'bar', prefix: '', suffix: '', pattern: '', modifier: '' }]
49
46
  ```
50
47
 
51
- **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). When using paths that contain query strings, you need to escape the question mark (`?`) to ensure it does not flag the parameter as [optional](#optional).
48
+ **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).
52
49
 
53
50
  ### Parameters
54
51
 
55
52
  The path argument is used to define parameters and populate keys.
56
53
 
57
- #### Named Parameters
54
+ #### Named parameters
58
55
 
59
- Named parameters are defined by prefixing a colon to the parameter name (`:foo`).
56
+ Named parameters are defined by prefixing a colon to the parameter name (`:foo`). Parameter names can use any valid unicode identifier characters (similar to JavaScript).
60
57
 
61
58
  ```js
62
59
  const regexp = pathToRegexp("/:foo/:bar");
63
- // keys = [{ name: 'foo', prefix: '/', ... }, { name: 'bar', prefix: '/', ... }]
60
+ // keys = [{ name: 'foo', ... }, { name: 'bar', ... }]
64
61
 
65
62
  regexp.exec("/test/route");
66
- //=> [ '/test/route', 'test', 'route', index: 0, input: '/test/route', groups: undefined ]
63
+ //=> [ '/test/route', 'test', 'route', index: 0 ]
67
64
  ```
68
65
 
69
- **Please note:** Parameter names must use "word characters" (`[A-Za-z0-9_]`).
70
-
71
- ##### Custom Matching Parameters
66
+ ##### Custom matching parameters
72
67
 
73
68
  Parameters can have a custom regexp, which overrides the default match (`[^/]+`). For example, you can match digits or names in a path:
74
69
 
@@ -94,64 +89,49 @@ regexpWord.exec("/users");
94
89
 
95
90
  **Tip:** Backslashes need to be escaped with another backslash in JavaScript strings.
96
91
 
97
- ##### Custom Prefix and Suffix
92
+ #### Unnamed parameters
98
93
 
99
- Parameters can be wrapped in `{}` to create custom prefixes or suffixes for your segment:
94
+ It is possible to define a parameter without a name. The name will be numerically indexed:
100
95
 
101
96
  ```js
102
- const regexp = pathToRegexp("/:attr1?{-:attr2}?{-:attr3}?");
103
-
104
- regexp.exec("/test");
105
- // => ['/test', 'test', undefined, undefined]
97
+ const regexp = pathToRegexp("/:foo/(.*)");
98
+ // keys = [{ name: 'foo', ... }, { name: '0', ... }]
106
99
 
107
- regexp.exec("/test-test");
108
- // => ['/test', 'test', 'test', undefined]
100
+ regexp.exec("/test/route");
101
+ //=> [ '/test/route', 'test', 'route', index: 0 ]
109
102
  ```
110
103
 
111
- #### Unnamed Parameters
104
+ ##### Custom prefix and suffix
112
105
 
113
- It is possible to write an unnamed parameter that only consists of a regexp. It works the same the named parameter, except it will be numerically indexed:
106
+ Parameters can be wrapped in `{}` to create custom prefixes or suffixes for your segment:
114
107
 
115
108
  ```js
116
- const regexp = pathToRegexp("/:foo/(.*)");
117
- // keys = [{ name: 'foo', ... }, { name: 0, ... }]
109
+ const regexp = pathToRegexp("{/:attr1}?{-:attr2}?{-:attr3}?");
118
110
 
119
- regexp.exec("/test/route");
120
- //=> [ '/test/route', 'test', 'route', index: 0, input: '/test/route', groups: undefined ]
111
+ regexp.exec("/test");
112
+ // => ['/test', 'test', undefined, undefined]
113
+
114
+ regexp.exec("/test-test");
115
+ // => ['/test', 'test', 'test', undefined]
121
116
  ```
122
117
 
123
118
  #### Modifiers
124
119
 
125
- Modifiers must be placed after the parameter (e.g. `/:foo?`, `/(test)?`, `/:foo(test)?`, or `{-:foo(test)}?`).
120
+ Modifiers are used after parameters with custom prefixes and suffixes (`{}`).
126
121
 
127
122
  ##### Optional
128
123
 
129
124
  Parameters can be suffixed with a question mark (`?`) to make the parameter optional.
130
125
 
131
126
  ```js
132
- const regexp = pathToRegexp("/:foo/:bar?");
127
+ const regexp = pathToRegexp("/:foo{/:bar}?");
133
128
  // keys = [{ name: 'foo', ... }, { name: 'bar', prefix: '/', modifier: '?' }]
134
129
 
135
130
  regexp.exec("/test");
136
- //=> [ '/test', 'test', undefined, index: 0, input: '/test', groups: undefined ]
131
+ //=> [ '/test', 'test', undefined, index: 0 ]
137
132
 
138
133
  regexp.exec("/test/route");
139
- //=> [ '/test/route', 'test', 'route', index: 0, input: '/test/route', groups: undefined ]
140
- ```
141
-
142
- **Tip:** The prefix is also optional, escape the prefix `\/` to make it required.
143
-
144
- When dealing with query strings, escape the question mark (`?`) so it doesn't mark the parameter as optional. Handling unordered data is outside the scope of this library.
145
-
146
- ```js
147
- const regexp = pathToRegexp("/search/:tableName\\?useIndex=true&term=amazing");
148
-
149
- regexp.exec("/search/people?useIndex=true&term=amazing");
150
- //=> [ '/search/people?useIndex=true&term=amazing', 'people', index: 0, input: '/search/people?useIndex=true&term=amazing', groups: undefined ]
151
-
152
- // This library does not handle query strings in different orders
153
- regexp.exec("/search/people?term=amazing&useIndex=true");
154
- //=> null
134
+ //=> [ '/test/route', 'test', 'route', index: 0 ]
155
135
  ```
156
136
 
157
137
  ##### Zero or more
@@ -159,14 +139,14 @@ regexp.exec("/search/people?term=amazing&useIndex=true");
159
139
  Parameters can be suffixed with an asterisk (`*`) to denote a zero or more parameter matches.
160
140
 
161
141
  ```js
162
- const regexp = pathToRegexp("/:foo*");
142
+ const regexp = pathToRegexp("{/:foo}*");
163
143
  // keys = [{ name: 'foo', prefix: '/', modifier: '*' }]
164
144
 
165
- regexp.exec("/");
166
- //=> [ '/', undefined, index: 0, input: '/', groups: undefined ]
145
+ regexp.exec("/foo");
146
+ //=> [ '/foo', "foo", index: 0 ]
167
147
 
168
148
  regexp.exec("/bar/baz");
169
- //=> [ '/bar/baz', 'bar/baz', index: 0, input: '/bar/baz', groups: undefined ]
149
+ //=> [ '/bar/baz', 'bar/baz', index: 0 ]
170
150
  ```
171
151
 
172
152
  ##### One or more
@@ -174,168 +154,126 @@ regexp.exec("/bar/baz");
174
154
  Parameters can be suffixed with a plus sign (`+`) to denote a one or more parameter matches.
175
155
 
176
156
  ```js
177
- const regexp = pathToRegexp("/:foo+");
157
+ const regexp = pathToRegexp("{/:foo}+");
178
158
  // keys = [{ name: 'foo', prefix: '/', modifier: '+' }]
179
159
 
180
160
  regexp.exec("/");
181
161
  //=> null
182
162
 
183
163
  regexp.exec("/bar/baz");
184
- //=> [ '/bar/baz','bar/baz', index: 0, input: '/bar/baz', groups: undefined ]
164
+ //=> [ '/bar/baz', 'bar/baz', index: 0 ]
185
165
  ```
186
166
 
187
- ### Match
167
+ #### Wildcard
188
168
 
189
- The `match` function will return a function for transforming paths into parameters:
169
+ A wildcard can also be used. It is roughly equivalent to `(.*)`.
190
170
 
191
171
  ```js
192
- // Make sure you consistently `decode` segments.
193
- const fn = match("/user/:id", { decode: decodeURIComponent });
172
+ const regexp = pathToRegexp("/*");
173
+ // keys = [{ name: '0', pattern: '[^\\/]*', separator: '/', modifier: '*' }]
194
174
 
195
- fn("/user/123"); //=> { path: '/user/123', index: 0, params: { id: '123' } }
196
- fn("/invalid"); //=> false
197
- fn("/user/caf%C3%A9"); //=> { path: '/user/caf%C3%A9', index: 0, params: { id: 'café' } }
198
- ```
199
-
200
- The `match` function can be used to custom match named parameters. For example, this can be used to whitelist a small number of valid paths:
201
-
202
- ```js
203
- const urlMatch = match("/users/:id/:tab(home|photos|bio)", {
204
- decode: decodeURIComponent,
205
- });
206
-
207
- urlMatch("/users/1234/photos");
208
- //=> { path: '/users/1234/photos', index: 0, params: { id: '1234', tab: 'photos' } }
209
-
210
- urlMatch("/users/1234/bio");
211
- //=> { path: '/users/1234/bio', index: 0, params: { id: '1234', tab: 'bio' } }
212
-
213
- urlMatch("/users/1234/otherstuff");
214
- //=> false
215
- ```
216
-
217
- #### Process Pathname
218
-
219
- You should make sure variations of the same path match the expected `path`. Here's one possible solution using `encode`:
220
-
221
- ```js
222
- const fn = match("/café", { encode: encodeURI });
175
+ regexp.exec("/");
176
+ //=> [ '/', '', index: 0 ]
223
177
 
224
- fn("/caf%C3%A9"); //=> { path: '/caf%C3%A9', index: 0, params: {} }
178
+ regexp.exec("/bar/baz");
179
+ //=> [ '/bar/baz', 'bar/baz', index: 0 ]
225
180
  ```
226
181
 
227
- **Note:** [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) encodes paths, so `/café` would be normalized to `/caf%C3%A9` and match in the above example.
228
-
229
- ##### Alternative Using Normalize
230
-
231
- Sometimes you won't have already normalized paths to use, so you could normalize it yourself before matching:
232
-
233
- ```js
234
- /**
235
- * Normalize a pathname for matching, replaces multiple slashes with a single
236
- * slash and normalizes unicode characters to "NFC". When using this method,
237
- * `decode` should be an identity function so you don't decode strings twice.
238
- */
239
- function normalizePathname(pathname: string) {
240
- return (
241
- decodeURI(pathname)
242
- // Replaces repeated slashes in the URL.
243
- .replace(/\/+/g, "/")
244
- // Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
245
- // Note: Missing native IE support, may want to skip this step.
246
- .normalize()
247
- );
248
- }
249
-
250
- // Two possible ways of writing `/café`:
251
- const re = pathToRegexp("/caf\u00E9");
252
- const input = encodeURI("/cafe\u0301");
253
-
254
- re.test(input); //=> false
255
- re.test(normalizePathname(input)); //=> true
256
- ```
182
+ ### Match
257
183
 
258
- ### Parse
184
+ The `match` function returns a function for transforming paths into parameters:
259
185
 
260
- The `parse` function will return a list of strings and keys from a path string:
186
+ - **path** A string.
187
+ - **options** _(optional)_ The same options as `pathToRegexp`, plus:
188
+ - **decode** Function for decoding strings for params, or `false` to disable entirely. (default: `decodeURIComponent`)
261
189
 
262
190
  ```js
263
- const tokens = parse("/route/:foo/(.*)");
264
-
265
- console.log(tokens[0]);
266
- //=> "/route"
267
-
268
- console.log(tokens[1]);
269
- //=> { name: 'foo', prefix: '/', suffix: '', pattern: '[^\\/#\\?]+?', modifier: '' }
191
+ // Make sure you consistently `decode` segments.
192
+ const fn = match("/user/:id", { decode: decodeURIComponent });
270
193
 
271
- console.log(tokens[2]);
272
- //=> { name: 0, prefix: '/', suffix: '', pattern: '.*', modifier: '' }
194
+ fn("/user/123"); //=> { path: '/user/123', index: 0, params: { id: '123' } }
195
+ fn("/invalid"); //=> false
196
+ fn("/user/caf%C3%A9"); //=> { path: '/user/caf%C3%A9', index: 0, params: { id: 'café' } }
273
197
  ```
274
198
 
275
- **Note:** This method only works with strings.
199
+ **Note:** Setting `decode: false` disables the "splitting" behavior of repeated parameters, which is useful if you need the exactly matched parameter back.
276
200
 
277
201
  ### Compile ("Reverse" Path-To-RegExp)
278
202
 
279
203
  The `compile` function will return a function for transforming parameters into a valid path:
280
204
 
205
+ - **path** A string.
206
+ - **options** _(optional)_ Similar to `pathToRegexp` (`delimiter`, `encodePath`, `sensitive`, and `loose`), plus:
207
+ - **validate** When `false` the function can produce an invalid (unmatched) path. (default: `true`)
208
+ - **encode** Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`)
209
+
281
210
  ```js
282
- // Make sure you encode your path segments consistently.
283
- const toPath = compile("/user/:id", { encode: encodeURIComponent });
211
+ const toPath = compile("/user/:id");
284
212
 
285
213
  toPath({ id: 123 }); //=> "/user/123"
286
214
  toPath({ id: "café" }); //=> "/user/caf%C3%A9"
287
- toPath({ id: "/" }); //=> "/user/%2F"
288
-
289
215
  toPath({ id: ":/" }); //=> "/user/%3A%2F"
290
216
 
291
- // Without `encode`, you need to make sure inputs are encoded correctly.
292
- const toPathRaw = compile("/user/:id");
217
+ // When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted.
218
+ const toPathRaw = compile("/user/:id", { encode: false });
293
219
 
294
220
  toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F"
295
- toPathRaw({ id: ":/" }, { validate: false }); //=> "/user/:/"
221
+ toPathRaw({ id: ":/" }); //=> "/user/:/", throws when `validate: false` is not set.
296
222
 
297
- const toPathRepeated = compile("/:segment+");
223
+ const toPathRepeated = compile("{/:segment}+");
298
224
 
299
- toPathRepeated({ segment: "foo" }); //=> "/foo"
225
+ toPathRepeated({ segment: ["foo"] }); //=> "/foo"
300
226
  toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c"
301
227
 
302
228
  const toPathRegexp = compile("/user/:id(\\d+)");
303
229
 
304
- toPathRegexp({ id: 123 }); //=> "/user/123"
305
230
  toPathRegexp({ id: "123" }); //=> "/user/123"
306
- toPathRegexp({ id: "abc" }); //=> Throws `TypeError`.
307
- toPathRegexp({ id: "abc" }, { validate: false }); //=> "/user/abc"
308
231
  ```
309
232
 
310
- **Note:** The generated function will throw on invalid input.
233
+ ## Developers
234
+
235
+ - If you are rewriting paths with match and compiler, consider using `encode: false` and `decode: false` to keep raw paths passed around.
236
+ - To ensure matches work on paths containing characters usually encoded, consider using [encodeurl](https://github.com/pillarjs/encodeurl) for `encodePath`.
237
+ - If matches are intended to be exact, you need to set `loose: false`, `trailing: false`, and `sensitive: true`.
238
+
239
+ ### Parse
240
+
241
+ A `parse` function is available and returns `TokenData`, the set of tokens and other metadata parsed from the input string. `TokenData` is can passed directly into `pathToRegexp`, `match`, and `compile`. It accepts only two options, `delimiter` and `encodePath`, which makes those options redundant in the above methods.
242
+
243
+ ### Token Information
244
+
245
+ - `name` The name of the token
246
+ - `prefix` _(optional)_ The prefix string for the segment (e.g. `"/"`)
247
+ - `suffix` _(optional)_ The suffix string for the segment (e.g. `""`)
248
+ - `pattern` _(optional)_ The pattern defined to match this token
249
+ - `modifier` _(optional)_ The modifier character used for the segment (e.g. `?`)
250
+ - `separator` _(optional)_ The string used to separate repeated parameters
311
251
 
312
- ### Working with Tokens
252
+ ## Errors
313
253
 
314
- Path-To-RegExp exposes the two functions used internally that accept an array of tokens:
254
+ An effort has been made to ensure ambiguous paths from previous releases throw an error. This means you might be seeing an error when things worked before.
315
255
 
316
- - `tokensToRegexp(tokens, keys?, options?)` Transform an array of tokens into a matching regular expression.
317
- - `tokensToFunction(tokens)` Transform an array of tokens into a path generator function.
256
+ ### Unexpected `?`, `*`, or `+`
318
257
 
319
- #### Token Information
258
+ In previous major versions `/` and `.` were used as implicit prefixes of parameters. So `/:key?` was implicitly `{/:key}?`. For example:
320
259
 
321
- - `name` The name of the token (`string` for named or `number` for unnamed index)
322
- - `prefix` The prefix string for the segment (e.g. `"/"`)
323
- - `suffix` The suffix string for the segment (e.g. `""`)
324
- - `pattern` The RegExp used to match this token (`string`)
325
- - `modifier` The modifier character used for the segment (e.g. `?`)
260
+ - `/:key?` `{/:key}?` or `/:key*` `{/:key}*` or `/:key+` `{/:key}+`
261
+ - `.:key?` → `{.:key}?` or `.:key*` `{.:key}*` or `.:key+` `{.:key}+`
262
+ - `:key?` → `{:key}?` or `:key*` `{:key}*` or `:key+` `{:key}+`
326
263
 
327
- ## Compatibility with Express <= 4.x
264
+ ### Unexpected `!`, `@`, `,`, or `;`
328
265
 
329
- Path-To-RegExp breaks compatibility with Express <= `4.x`:
266
+ These characters have been reserved for future use.
330
267
 
331
- - RegExp special characters can only be used in a parameter
332
- - Express.js 4.x supported `RegExp` special characters regardless of position - this is considered a bug
333
- - Parameters have suffixes that augment meaning - `*`, `+` and `?`. E.g. `/:user*`
334
- - No wildcard asterisk (`*`) - use parameters instead (`(.*)` or `:splat*`)
268
+ ### Express <= 4.x
335
269
 
336
- ## Live Demo
270
+ Path-To-RegExp breaks compatibility with Express <= `4.x` in the following ways:
337
271
 
338
- You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.io/express-route-tester/).
272
+ - The only part of the string that is a regex is within `()`.
273
+ - In Express.js 4.x, everything was passed as-is after a simple replacement, so you could write `/[a-z]+` to match `/test`.
274
+ - The `?` optional character must be used after `{}`.
275
+ - Some characters have new meaning or have been reserved (`{}?*+@!;`).
276
+ - The parameter name now supports all unicode identifier characters, previously it was only `[a-z0-9]`.
339
277
 
340
278
  ## License
341
279
 
@@ -345,7 +283,7 @@ MIT
345
283
  [npm-url]: https://npmjs.org/package/path-to-regexp
346
284
  [downloads-image]: https://img.shields.io/npm/dm/path-to-regexp
347
285
  [downloads-url]: https://npmjs.org/package/path-to-regexp
348
- [build-image]: https://img.shields.io/github/workflow/status/pillarjs/path-to-regexp/CI/master
286
+ [build-image]: https://img.shields.io/github/actions/workflow/status/pillarjs/path-to-regexp/ci.yml?branch=master
349
287
  [build-url]: https://github.com/pillarjs/path-to-regexp/actions/workflows/ci.yml?query=branch%3Amaster
350
288
  [coverage-image]: https://img.shields.io/codecov/c/gh/pillarjs/path-to-regexp
351
289
  [coverage-url]: https://codecov.io/gh/pillarjs/path-to-regexp
package/dist/index.d.ts CHANGED
@@ -1,50 +1,89 @@
1
+ /**
2
+ * Encode a string into another string.
3
+ */
4
+ export type Encode = (value: string) => string;
5
+ /**
6
+ * Decode a string into another string.
7
+ */
8
+ export type Decode = (value: string) => string;
1
9
  export interface ParseOptions {
2
10
  /**
3
11
  * Set the default delimiter for repeat parameters. (default: `'/'`)
4
12
  */
5
13
  delimiter?: string;
6
14
  /**
7
- * List of characters to automatically consider prefixes when parsing.
15
+ * Function for encoding input strings for output into path.
8
16
  */
9
- prefixes?: string;
17
+ encodePath?: Encode;
10
18
  }
11
- /**
12
- * Parse a string for the raw tokens.
13
- */
14
- export declare function parse(str: string, options?: ParseOptions): Token[];
15
- export interface TokensToFunctionOptions {
19
+ export interface PathToRegexpOptions extends ParseOptions {
16
20
  /**
17
21
  * When `true` the regexp will be case sensitive. (default: `false`)
18
22
  */
19
23
  sensitive?: boolean;
20
24
  /**
21
- * Function for encoding input strings for output.
25
+ * Allow delimiter to be arbitrarily repeated. (default: `true`)
26
+ */
27
+ loose?: boolean;
28
+ /**
29
+ * When `true` the regexp will match to the end of the string. (default: `true`)
30
+ */
31
+ end?: boolean;
32
+ /**
33
+ * When `true` the regexp will match from the beginning of the string. (default: `true`)
34
+ */
35
+ start?: boolean;
36
+ /**
37
+ * When `true` the regexp allows an optional trailing delimiter to match. (default: `true`)
38
+ */
39
+ trailing?: boolean;
40
+ }
41
+ export interface MatchOptions extends PathToRegexpOptions {
42
+ /**
43
+ * Function for decoding strings for params, or `false` to disable entirely. (default: `decodeURIComponent`)
44
+ */
45
+ decode?: Decode | false;
46
+ }
47
+ export interface CompileOptions extends ParseOptions {
48
+ /**
49
+ * When `true` the validation will be case sensitive. (default: `false`)
50
+ */
51
+ sensitive?: boolean;
52
+ /**
53
+ * Allow delimiter to be arbitrarily repeated. (default: `true`)
22
54
  */
23
- encode?: (value: string, token: Key) => string;
55
+ loose?: boolean;
24
56
  /**
25
57
  * When `false` the function can produce an invalid (unmatched) path. (default: `true`)
26
58
  */
27
59
  validate?: boolean;
60
+ /**
61
+ * Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`)
62
+ */
63
+ encode?: Encode | false;
28
64
  }
29
65
  /**
30
- * Compile a string to a template function for the path.
66
+ * Tokenized path instance. Can we passed around instead of string.
31
67
  */
32
- export declare function compile<P extends object = object>(str: string, options?: ParseOptions & TokensToFunctionOptions): PathFunction<P>;
33
- export declare type PathFunction<P extends object = object> = (data?: P) => string;
68
+ export declare class TokenData {
69
+ readonly tokens: Token[];
70
+ readonly delimiter: string;
71
+ constructor(tokens: Token[], delimiter: string);
72
+ }
34
73
  /**
35
- * Expose a method for transforming tokens into the path function.
74
+ * Parse a string for the raw tokens.
36
75
  */
37
- export declare function tokensToFunction<P extends object = object>(tokens: Token[], options?: TokensToFunctionOptions): PathFunction<P>;
38
- export interface RegexpToFunctionOptions {
39
- /**
40
- * Function for decoding strings for params.
41
- */
42
- decode?: (value: string, token: Key) => string;
43
- }
76
+ export declare function parse(str: string, options?: ParseOptions): TokenData;
77
+ /**
78
+ * Compile a string to a template function for the path.
79
+ */
80
+ export declare function compile<P extends object = object>(path: Path, options?: CompileOptions): PathFunction<P>;
81
+ export type ParamData = Partial<Record<string, string | string[]>>;
82
+ export type PathFunction<P extends ParamData> = (data?: P) => string;
44
83
  /**
45
84
  * A match result contains data about the path match.
46
85
  */
47
- export interface MatchResult<P extends object = object> {
86
+ export interface MatchResult<P extends ParamData> {
48
87
  path: string;
49
88
  index: number;
50
89
  params: P;
@@ -52,71 +91,37 @@ export interface MatchResult<P extends object = object> {
52
91
  /**
53
92
  * A match is either `false` (no match) or a match result.
54
93
  */
55
- export declare type Match<P extends object = object> = false | MatchResult<P>;
94
+ export type Match<P extends ParamData> = false | MatchResult<P>;
56
95
  /**
57
96
  * The match function takes a string and returns whether it matched the path.
58
97
  */
59
- export declare type MatchFunction<P extends object = object> = (path: string) => Match<P>;
98
+ export type MatchFunction<P extends ParamData> = (path: string) => Match<P>;
60
99
  /**
61
100
  * Create path match function from `path-to-regexp` spec.
62
101
  */
63
- export declare function match<P extends object = object>(str: Path, options?: ParseOptions & TokensToRegexpOptions & RegexpToFunctionOptions): MatchFunction<P>;
64
- /**
65
- * Create a path match function from `path-to-regexp` output.
66
- */
67
- export declare function regexpToFunction<P extends object = object>(re: RegExp, keys: Key[], options?: RegexpToFunctionOptions): MatchFunction<P>;
102
+ export declare function match<P extends ParamData>(path: Path, options?: MatchOptions): MatchFunction<P>;
68
103
  /**
69
- * Metadata about a key.
104
+ * A key is a capture group in the regex.
70
105
  */
71
106
  export interface Key {
72
- name: string | number;
73
- prefix: string;
74
- suffix: string;
75
- pattern: string;
76
- modifier: string;
107
+ name: string;
108
+ prefix?: string;
109
+ suffix?: string;
110
+ pattern?: string;
111
+ modifier?: string;
112
+ separator?: string;
77
113
  }
78
114
  /**
79
115
  * A token is a string (nothing special) or key metadata (capture group).
80
116
  */
81
- export declare type Token = string | Key;
82
- export interface TokensToRegexpOptions {
83
- /**
84
- * When `true` the regexp will be case sensitive. (default: `false`)
85
- */
86
- sensitive?: boolean;
87
- /**
88
- * When `true` the regexp won't allow an optional trailing delimiter to match. (default: `false`)
89
- */
90
- strict?: boolean;
91
- /**
92
- * When `true` the regexp will match to the end of the string. (default: `true`)
93
- */
94
- end?: boolean;
95
- /**
96
- * When `true` the regexp will match from the beginning of the string. (default: `true`)
97
- */
98
- start?: boolean;
99
- /**
100
- * Sets the final character for non-ending optimistic matches. (default: `/`)
101
- */
102
- delimiter?: string;
103
- /**
104
- * List of characters that can also be "end" characters.
105
- */
106
- endsWith?: string;
107
- /**
108
- * Encode path tokens for use in the `RegExp`.
109
- */
110
- encode?: (value: string) => string;
111
- }
112
- /**
113
- * Expose a function for taking tokens and returning a RegExp.
114
- */
115
- export declare function tokensToRegexp(tokens: Token[], keys?: Key[], options?: TokensToRegexpOptions): RegExp;
117
+ export type Token = string | Key;
116
118
  /**
117
- * Supported `path-to-regexp` input types.
119
+ * Repeated and simple input types.
118
120
  */
119
- export declare type Path = string | RegExp | Array<string | RegExp>;
121
+ export type Path = string | TokenData;
122
+ export type PathRegExp = RegExp & {
123
+ keys: Key[];
124
+ };
120
125
  /**
121
126
  * Normalize the given path string, returning a regular expression.
122
127
  *
@@ -124,4 +129,6 @@ export declare type Path = string | RegExp | Array<string | RegExp>;
124
129
  * placeholder key descriptions. For example, using `/user/:id`, `keys` will
125
130
  * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
126
131
  */
127
- export declare function pathToRegexp(path: Path, keys?: Key[], options?: TokensToRegexpOptions & ParseOptions): RegExp;
132
+ export declare function pathToRegexp(path: Path, options?: PathToRegexpOptions): RegExp & {
133
+ keys: Key[];
134
+ };