@serwist/routing 9.0.0-preview.0 → 9.0.0-preview.1
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/dist/index.js +28 -282
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,22 +1,7 @@
|
|
|
1
1
|
import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/internal';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
Use of this source code is governed by an MIT-style
|
|
7
|
-
license that can be found in the LICENSE file or at
|
|
8
|
-
https://opensource.org/licenses/MIT.
|
|
9
|
-
*/ /**
|
|
10
|
-
* The default HTTP method, 'GET', used when there's no specific method
|
|
11
|
-
* configured for a route.
|
|
12
|
-
*
|
|
13
|
-
* @private
|
|
14
|
-
*/ const defaultMethod = "GET";
|
|
15
|
-
/**
|
|
16
|
-
* The list of valid HTTP methods associated with requests that could be routed.
|
|
17
|
-
*
|
|
18
|
-
* @private
|
|
19
|
-
*/ const validMethods = [
|
|
3
|
+
const defaultMethod = "GET";
|
|
4
|
+
const validMethods = [
|
|
20
5
|
"DELETE",
|
|
21
6
|
"GET",
|
|
22
7
|
"HEAD",
|
|
@@ -25,13 +10,7 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
25
10
|
"PUT"
|
|
26
11
|
];
|
|
27
12
|
|
|
28
|
-
|
|
29
|
-
* @param handler Either a function, or an object with a
|
|
30
|
-
* 'handle' method.
|
|
31
|
-
* @returns An object with a handle method.
|
|
32
|
-
*
|
|
33
|
-
* @private
|
|
34
|
-
*/ const normalizeHandler = (handler)=>{
|
|
13
|
+
const normalizeHandler = (handler)=>{
|
|
35
14
|
if (handler && typeof handler === "object") {
|
|
36
15
|
if (process.env.NODE_ENV !== "production") {
|
|
37
16
|
assert.hasMethod(handler, "handle", {
|
|
@@ -56,27 +35,12 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
56
35
|
};
|
|
57
36
|
};
|
|
58
37
|
|
|
59
|
-
|
|
60
|
-
* A `Route` consists of a pair of callback functions, "match" and "handler".
|
|
61
|
-
* The "match" callback determine if a route should be used to "handle" a
|
|
62
|
-
* request by returning a non-falsy value if it can. The "handler" callback
|
|
63
|
-
* is called when there is a match and should return a Promise that resolves
|
|
64
|
-
* to a `Response`.
|
|
65
|
-
*/ class Route {
|
|
38
|
+
class Route {
|
|
66
39
|
handler;
|
|
67
40
|
match;
|
|
68
41
|
method;
|
|
69
42
|
catchHandler;
|
|
70
|
-
|
|
71
|
-
* Constructor for Route class.
|
|
72
|
-
*
|
|
73
|
-
* @param match A callback function that determines whether the
|
|
74
|
-
* route matches a given `fetch` event by returning a non-falsy value.
|
|
75
|
-
* @param handler A callback function that returns a Promise resolving
|
|
76
|
-
* to a Response.
|
|
77
|
-
* @param method The HTTP method to match the Route against. Defaults
|
|
78
|
-
* to GET.
|
|
79
|
-
*/ constructor(match, handler, method = defaultMethod){
|
|
43
|
+
constructor(match, handler, method = defaultMethod){
|
|
80
44
|
if (process.env.NODE_ENV !== "production") {
|
|
81
45
|
assert.isType(match, "function", {
|
|
82
46
|
moduleName: "@serwist/routing",
|
|
@@ -90,50 +54,19 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
90
54
|
});
|
|
91
55
|
}
|
|
92
56
|
}
|
|
93
|
-
// These values are referenced directly by Router so cannot be
|
|
94
|
-
// altered by minificaton.
|
|
95
57
|
this.handler = normalizeHandler(handler);
|
|
96
58
|
this.match = match;
|
|
97
59
|
this.method = method;
|
|
98
60
|
}
|
|
99
|
-
|
|
100
|
-
*
|
|
101
|
-
* @param handler A callback function that returns a Promise resolving
|
|
102
|
-
* to a Response.
|
|
103
|
-
*/ setCatchHandler(handler) {
|
|
61
|
+
setCatchHandler(handler) {
|
|
104
62
|
this.catchHandler = normalizeHandler(handler);
|
|
105
63
|
}
|
|
106
64
|
}
|
|
107
65
|
|
|
108
|
-
|
|
109
|
-
* NavigationRoute makes it easy to create a `@serwist/routing` Route that matches for browser
|
|
110
|
-
* [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests).
|
|
111
|
-
*
|
|
112
|
-
* It will only match incoming Requests whose [mode](https://fetch.spec.whatwg.org/#concept-request-mode) is set to `navigate`.
|
|
113
|
-
*
|
|
114
|
-
* You can optionally only apply this route to a subset of navigation requests
|
|
115
|
-
* by using one or both of the `denylist` and `allowlist` parameters.
|
|
116
|
-
*/ class NavigationRoute extends Route {
|
|
66
|
+
class NavigationRoute extends Route {
|
|
117
67
|
_allowlist;
|
|
118
68
|
_denylist;
|
|
119
|
-
|
|
120
|
-
* If both `denylist` and `allowlist` are provided, the `denylist` will
|
|
121
|
-
* take precedence and the request will not match this route.
|
|
122
|
-
*
|
|
123
|
-
* The regular expressions in `allowlist` and `denylist`
|
|
124
|
-
* are matched against the concatenated
|
|
125
|
-
* [`pathname`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname)
|
|
126
|
-
* and [`search`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search)
|
|
127
|
-
* portions of the requested URL.
|
|
128
|
-
*
|
|
129
|
-
* *Note*: These RegExps may be evaluated against every destination URL during
|
|
130
|
-
* a navigation. Avoid using
|
|
131
|
-
* [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
|
|
132
|
-
* or else your users may see delays when navigating your site.
|
|
133
|
-
*
|
|
134
|
-
* @param handler A callback function that returns a Promise resulting in a Response.
|
|
135
|
-
* @param options
|
|
136
|
-
*/ constructor(handler, { allowlist = [
|
|
69
|
+
constructor(handler, { allowlist = [
|
|
137
70
|
/./
|
|
138
71
|
], denylist = [] } = {}){
|
|
139
72
|
if (process.env.NODE_ENV !== "production") {
|
|
@@ -154,13 +87,7 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
154
87
|
this._allowlist = allowlist;
|
|
155
88
|
this._denylist = denylist;
|
|
156
89
|
}
|
|
157
|
-
|
|
158
|
-
* Routes match handler.
|
|
159
|
-
*
|
|
160
|
-
* @param options
|
|
161
|
-
* @returns
|
|
162
|
-
* @private
|
|
163
|
-
*/ _match({ url, request }) {
|
|
90
|
+
_match({ url, request }) {
|
|
164
91
|
if (request && request.mode !== "navigate") {
|
|
165
92
|
return false;
|
|
166
93
|
}
|
|
@@ -186,23 +113,8 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
186
113
|
}
|
|
187
114
|
}
|
|
188
115
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
*
|
|
192
|
-
* For same-origin requests the RegExp only needs to match part of the URL. For
|
|
193
|
-
* requests against third-party servers, you must define a RegExp that matches
|
|
194
|
-
* the start of the URL.
|
|
195
|
-
*/ class RegExpRoute extends Route {
|
|
196
|
-
/**
|
|
197
|
-
* If the regular expression contains
|
|
198
|
-
* [capture groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references),
|
|
199
|
-
* the captured values will be passed to the `params` argument.
|
|
200
|
-
*
|
|
201
|
-
* @param regExp The regular expression to match against URLs.
|
|
202
|
-
* @param handler A callback function that returns a Promise resulting in a Response.
|
|
203
|
-
* @param method The HTTP method to match the Route, defaults to GET.
|
|
204
|
-
* against.
|
|
205
|
-
*/ constructor(regExp, handler, method){
|
|
116
|
+
class RegExpRoute extends Route {
|
|
117
|
+
constructor(regExp, handler, method){
|
|
206
118
|
if (process.env.NODE_ENV !== "production") {
|
|
207
119
|
assert.isInstance(regExp, RegExp, {
|
|
208
120
|
moduleName: "@serwist/routing",
|
|
@@ -213,62 +125,33 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
213
125
|
}
|
|
214
126
|
const match = ({ url })=>{
|
|
215
127
|
const result = regExp.exec(url.href);
|
|
216
|
-
// Return immediately if there's no match.
|
|
217
128
|
if (!result) {
|
|
218
129
|
return;
|
|
219
130
|
}
|
|
220
|
-
// Require that the match start at the first character in the URL string
|
|
221
|
-
// if it's a cross-origin request.
|
|
222
|
-
// See https://github.com/GoogleChrome/workbox/issues/281 for the context
|
|
223
|
-
// behind this behavior.
|
|
224
131
|
if (url.origin !== location.origin && result.index !== 0) {
|
|
225
132
|
if (process.env.NODE_ENV !== "production") {
|
|
226
133
|
logger.debug(`The regular expression '${regExp.toString()}' only partially matched against the cross-origin URL '${url.toString()}'. RegExpRoute's will only handle cross-origin requests if they match the entire URL.`);
|
|
227
134
|
}
|
|
228
135
|
return;
|
|
229
136
|
}
|
|
230
|
-
// If the route matches, but there aren't any capture groups defined, then
|
|
231
|
-
// this will return [], which is truthy and therefore sufficient to
|
|
232
|
-
// indicate a match.
|
|
233
|
-
// If there are capture groups, then it will return their values.
|
|
234
137
|
return result.slice(1);
|
|
235
138
|
};
|
|
236
139
|
super(match, handler, method);
|
|
237
140
|
}
|
|
238
141
|
}
|
|
239
142
|
|
|
240
|
-
|
|
241
|
-
* The Router can be used to process a `FetchEvent` using one or more `@serwist/routing` Route(s),
|
|
242
|
-
* responding with a `Response` if a matching route exists.
|
|
243
|
-
*
|
|
244
|
-
* If no route matches a given a request, the Router will use a "default" handler if one is defined.
|
|
245
|
-
*
|
|
246
|
-
* Should the matching Route throw an error, the Router will use a "catch" handler if one is defined to
|
|
247
|
-
* gracefully deal with issues and respond with a Request.
|
|
248
|
-
*
|
|
249
|
-
* If a request matches multiple routes, the **earliest** registered route will
|
|
250
|
-
* be used to respond to the request.
|
|
251
|
-
*/ class Router {
|
|
143
|
+
class Router {
|
|
252
144
|
_routes;
|
|
253
145
|
_defaultHandlerMap;
|
|
254
146
|
_catchHandler;
|
|
255
|
-
|
|
256
|
-
* Initializes a new Router.
|
|
257
|
-
*/ constructor(){
|
|
147
|
+
constructor(){
|
|
258
148
|
this._routes = new Map();
|
|
259
149
|
this._defaultHandlerMap = new Map();
|
|
260
150
|
}
|
|
261
|
-
|
|
262
|
-
* @returns routes A `Map` of HTTP method name ('GET', etc.) to an array of all the corresponding `Route`
|
|
263
|
-
* instances that are registered.
|
|
264
|
-
*/ get routes() {
|
|
151
|
+
get routes() {
|
|
265
152
|
return this._routes;
|
|
266
153
|
}
|
|
267
|
-
|
|
268
|
-
* Adds a fetch event listener to respond to events when a route matches
|
|
269
|
-
* the event's request.
|
|
270
|
-
*/ addFetchListener() {
|
|
271
|
-
// See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
|
|
154
|
+
addFetchListener() {
|
|
272
155
|
self.addEventListener("fetch", (event)=>{
|
|
273
156
|
const { request } = event;
|
|
274
157
|
const responsePromise = this.handleRequest({
|
|
@@ -280,34 +163,9 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
280
163
|
}
|
|
281
164
|
});
|
|
282
165
|
}
|
|
283
|
-
|
|
284
|
-
* Adds a message event listener for URLs to cache from the window.
|
|
285
|
-
* This is useful to cache resources loaded on the page prior to when the
|
|
286
|
-
* service worker started controlling it.
|
|
287
|
-
*
|
|
288
|
-
* The format of the message data sent from the window should be as follows.
|
|
289
|
-
* Where the `urlsToCache` array may consist of URL strings or an array of
|
|
290
|
-
* URL string + `requestInit` object (the same as you'd pass to `fetch()`).
|
|
291
|
-
*
|
|
292
|
-
* ```
|
|
293
|
-
* {
|
|
294
|
-
* type: 'CACHE_URLS',
|
|
295
|
-
* payload: {
|
|
296
|
-
* urlsToCache: [
|
|
297
|
-
* './script1.js',
|
|
298
|
-
* './script2.js',
|
|
299
|
-
* ['./script3.js', {mode: 'no-cors'}],
|
|
300
|
-
* ],
|
|
301
|
-
* },
|
|
302
|
-
* }
|
|
303
|
-
* ```
|
|
304
|
-
*/ addCacheListener() {
|
|
305
|
-
// See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
|
|
166
|
+
addCacheListener() {
|
|
306
167
|
self.addEventListener("message", (event)=>{
|
|
307
|
-
// event.data is type 'any'
|
|
308
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
|
309
168
|
if (event.data && event.data.type === "CACHE_URLS") {
|
|
310
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
311
169
|
const { payload } = event.data;
|
|
312
170
|
if (process.env.NODE_ENV !== "production") {
|
|
313
171
|
logger.debug("Caching URLs from the window", payload.urlsToCache);
|
|
@@ -325,22 +183,13 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
325
183
|
});
|
|
326
184
|
}));
|
|
327
185
|
event.waitUntil(requestPromises);
|
|
328
|
-
// If a MessageChannel was used, reply to the message on success.
|
|
329
186
|
if (event.ports?.[0]) {
|
|
330
187
|
void requestPromises.then(()=>event.ports[0].postMessage(true));
|
|
331
188
|
}
|
|
332
189
|
}
|
|
333
190
|
});
|
|
334
191
|
}
|
|
335
|
-
|
|
336
|
-
* Apply the routing rules to a FetchEvent object to get a Response from an
|
|
337
|
-
* appropriate Route's handler.
|
|
338
|
-
*
|
|
339
|
-
* @param options
|
|
340
|
-
* @returns A promise is returned if a registered route can handle the request.
|
|
341
|
-
* If there is no matching route and there's no `defaultHandler`, `undefined`
|
|
342
|
-
* is returned.
|
|
343
|
-
*/ handleRequest({ request, event }) {
|
|
192
|
+
handleRequest({ request, event }) {
|
|
344
193
|
if (process.env.NODE_ENV !== "production") {
|
|
345
194
|
assert.isInstance(request, Request, {
|
|
346
195
|
moduleName: "@serwist/routing",
|
|
@@ -379,8 +228,6 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
379
228
|
}
|
|
380
229
|
}
|
|
381
230
|
}
|
|
382
|
-
// If we don't have a handler because there was no matching route, then
|
|
383
|
-
// fall back to defaultHandler if that's defined.
|
|
384
231
|
const method = request.method;
|
|
385
232
|
if (!handler && this._defaultHandlerMap.has(method)) {
|
|
386
233
|
if (process.env.NODE_ENV !== "production") {
|
|
@@ -390,15 +237,11 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
390
237
|
}
|
|
391
238
|
if (!handler) {
|
|
392
239
|
if (process.env.NODE_ENV !== "production") {
|
|
393
|
-
// No handler so Serwist will do nothing. If logs is set of debug
|
|
394
|
-
// i.e. verbose, we should print out this information.
|
|
395
240
|
logger.debug(`No route found for: ${getFriendlyURL(url)}`);
|
|
396
241
|
}
|
|
397
242
|
return;
|
|
398
243
|
}
|
|
399
244
|
if (process.env.NODE_ENV !== "production") {
|
|
400
|
-
// We have a handler, meaning Serwist is going to handle the route.
|
|
401
|
-
// print the routing details to the console.
|
|
402
245
|
logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
|
|
403
246
|
for (const msg of debugMessages){
|
|
404
247
|
if (Array.isArray(msg)) {
|
|
@@ -409,8 +252,6 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
409
252
|
}
|
|
410
253
|
logger.groupEnd();
|
|
411
254
|
}
|
|
412
|
-
// Wrap in try and catch in case the handle method throws a synchronous
|
|
413
|
-
// error. It should still callback to the catch handler.
|
|
414
255
|
let responsePromise;
|
|
415
256
|
try {
|
|
416
257
|
responsePromise = handler.handle({
|
|
@@ -422,15 +263,11 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
422
263
|
} catch (err) {
|
|
423
264
|
responsePromise = Promise.reject(err);
|
|
424
265
|
}
|
|
425
|
-
// Get route's catch handler, if it exists
|
|
426
266
|
const catchHandler = route?.catchHandler;
|
|
427
267
|
if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
|
|
428
268
|
responsePromise = responsePromise.catch(async (err)=>{
|
|
429
|
-
// If there's a route catch handler, process that first
|
|
430
269
|
if (catchHandler) {
|
|
431
270
|
if (process.env.NODE_ENV !== "production") {
|
|
432
|
-
// Still include URL here as it will be async from the console group
|
|
433
|
-
// and may not make sense without the URL
|
|
434
271
|
logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
|
|
435
272
|
logger.error("Error thrown by:", route);
|
|
436
273
|
logger.error(err);
|
|
@@ -451,8 +288,6 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
451
288
|
}
|
|
452
289
|
if (this._catchHandler) {
|
|
453
290
|
if (process.env.NODE_ENV !== "production") {
|
|
454
|
-
// Still include URL here as it will be async from the console group
|
|
455
|
-
// and may not make sense without the URL
|
|
456
291
|
logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
|
|
457
292
|
logger.error("Error thrown by:", route);
|
|
458
293
|
logger.error(err);
|
|
@@ -469,20 +304,10 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
469
304
|
}
|
|
470
305
|
return responsePromise;
|
|
471
306
|
}
|
|
472
|
-
|
|
473
|
-
* Checks a request and URL (and optionally an event) against the list of
|
|
474
|
-
* registered routes, and if there's a match, returns the corresponding
|
|
475
|
-
* route along with any params generated by the match.
|
|
476
|
-
*
|
|
477
|
-
* @param options
|
|
478
|
-
* @returns An object with `route` and `params` properties. They are populated
|
|
479
|
-
* if a matching route was found or `undefined` otherwise.
|
|
480
|
-
*/ findMatchingRoute({ url, sameOrigin, request, event }) {
|
|
307
|
+
findMatchingRoute({ url, sameOrigin, request, event }) {
|
|
481
308
|
const routes = this._routes.get(request.method) || [];
|
|
482
309
|
for (const route of routes){
|
|
483
310
|
let params;
|
|
484
|
-
// route.match returns type any, not possible to change right now.
|
|
485
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
486
311
|
const matchResult = route.match({
|
|
487
312
|
url,
|
|
488
313
|
sameOrigin,
|
|
@@ -491,67 +316,33 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
491
316
|
});
|
|
492
317
|
if (matchResult) {
|
|
493
318
|
if (process.env.NODE_ENV !== "production") {
|
|
494
|
-
// Warn developers that using an async matchCallback is almost always
|
|
495
|
-
// not the right thing to do.
|
|
496
319
|
if (matchResult instanceof Promise) {
|
|
497
320
|
logger.warn(`While routing ${getFriendlyURL(url)}, an async matchCallback function was used. Please convert the following route to use a synchronous matchCallback function:`, route);
|
|
498
321
|
}
|
|
499
322
|
}
|
|
500
|
-
// See https://github.com/GoogleChrome/workbox/issues/2079
|
|
501
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
502
323
|
params = matchResult;
|
|
503
324
|
if (Array.isArray(params) && params.length === 0) {
|
|
504
|
-
// Instead of passing an empty array in as params, use undefined.
|
|
505
325
|
params = undefined;
|
|
506
|
-
} else if (matchResult.constructor === Object &&
|
|
507
|
-
Object.keys(matchResult).length === 0) {
|
|
508
|
-
// Instead of passing an empty object in as params, use undefined.
|
|
326
|
+
} else if (matchResult.constructor === Object && Object.keys(matchResult).length === 0) {
|
|
509
327
|
params = undefined;
|
|
510
328
|
} else if (typeof matchResult === "boolean") {
|
|
511
|
-
// For the boolean value true (rather than just something truth-y),
|
|
512
|
-
// don't set params.
|
|
513
|
-
// See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
|
|
514
329
|
params = undefined;
|
|
515
330
|
}
|
|
516
|
-
// Return early if have a match.
|
|
517
331
|
return {
|
|
518
332
|
route,
|
|
519
333
|
params
|
|
520
334
|
};
|
|
521
335
|
}
|
|
522
336
|
}
|
|
523
|
-
// If no match was found above, return and empty object.
|
|
524
337
|
return {};
|
|
525
338
|
}
|
|
526
|
-
|
|
527
|
-
* Define a default `handler` that's called when no routes explicitly
|
|
528
|
-
* match the incoming request.
|
|
529
|
-
*
|
|
530
|
-
* Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
|
|
531
|
-
*
|
|
532
|
-
* Without a default handler, unmatched requests will go against the
|
|
533
|
-
* network as if there were no service worker present.
|
|
534
|
-
*
|
|
535
|
-
* @param handler A callback function that returns a Promise resulting in a Response.
|
|
536
|
-
* @param method The HTTP method to associate with this default handler. Each method
|
|
537
|
-
* has its own default. Defaults to GET.
|
|
538
|
-
*/ setDefaultHandler(handler, method = defaultMethod) {
|
|
339
|
+
setDefaultHandler(handler, method = defaultMethod) {
|
|
539
340
|
this._defaultHandlerMap.set(method, normalizeHandler(handler));
|
|
540
341
|
}
|
|
541
|
-
|
|
542
|
-
* If a Route throws an error while handling a request, this `handler`
|
|
543
|
-
* will be called and given a chance to provide a response.
|
|
544
|
-
*
|
|
545
|
-
* @param handler A callback function that returns a Promise resulting
|
|
546
|
-
* in a Response.
|
|
547
|
-
*/ setCatchHandler(handler) {
|
|
342
|
+
setCatchHandler(handler) {
|
|
548
343
|
this._catchHandler = normalizeHandler(handler);
|
|
549
344
|
}
|
|
550
|
-
|
|
551
|
-
* Registers a route with the router.
|
|
552
|
-
*
|
|
553
|
-
* @param route The route to register.
|
|
554
|
-
*/ registerRoute(route) {
|
|
345
|
+
registerRoute(route) {
|
|
555
346
|
if (process.env.NODE_ENV !== "production") {
|
|
556
347
|
assert.isType(route, "object", {
|
|
557
348
|
moduleName: "@serwist/routing",
|
|
@@ -587,15 +378,9 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
587
378
|
if (!this._routes.has(route.method)) {
|
|
588
379
|
this._routes.set(route.method, []);
|
|
589
380
|
}
|
|
590
|
-
// Give precedence to all of the earlier routes by adding this additional
|
|
591
|
-
// route to the end of the array.
|
|
592
381
|
this._routes.get(route.method).push(route);
|
|
593
382
|
}
|
|
594
|
-
|
|
595
|
-
* Unregisters a route with the router.
|
|
596
|
-
*
|
|
597
|
-
* @param route The route to unregister.
|
|
598
|
-
*/ unregisterRoute(route) {
|
|
383
|
+
unregisterRoute(route) {
|
|
599
384
|
if (!this._routes.has(route.method)) {
|
|
600
385
|
throw new SerwistError("unregister-route-but-not-found-with-method", {
|
|
601
386
|
method: route.method
|
|
@@ -611,32 +396,16 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
|
|
|
611
396
|
}
|
|
612
397
|
|
|
613
398
|
let defaultRouter;
|
|
614
|
-
|
|
615
|
-
* Creates a new, singleton Router instance if one does not exist. If one
|
|
616
|
-
* does already exist, that instance is returned.
|
|
617
|
-
*
|
|
618
|
-
* @private
|
|
619
|
-
* @returns
|
|
620
|
-
*/ const getOrCreateDefaultRouter = ()=>{
|
|
399
|
+
const getOrCreateDefaultRouter = ()=>{
|
|
621
400
|
if (!defaultRouter) {
|
|
622
401
|
defaultRouter = new Router();
|
|
623
|
-
// The helpers that use the default Router assume these listeners exist.
|
|
624
402
|
defaultRouter.addFetchListener();
|
|
625
403
|
defaultRouter.addCacheListener();
|
|
626
404
|
}
|
|
627
405
|
return defaultRouter;
|
|
628
406
|
};
|
|
629
407
|
|
|
630
|
-
|
|
631
|
-
* Registers a RegExp, string, or function with a caching
|
|
632
|
-
* strategy to a singleton Router instance.
|
|
633
|
-
*
|
|
634
|
-
* @param capture If the capture param is a `Route`, all other arguments will be ignored.
|
|
635
|
-
* @param handler A callback function that returns a Promise resulting in a Response.
|
|
636
|
-
* This parameter is required if `capture` is not a `Route` object.
|
|
637
|
-
* @param method The HTTP method to match the Route against. Defaults to GET.
|
|
638
|
-
* @returns The generated `Route`.
|
|
639
|
-
*/ const registerRoute = (capture, handler, method)=>{
|
|
408
|
+
const registerRoute = (capture, handler, method)=>{
|
|
640
409
|
let route;
|
|
641
410
|
if (typeof capture === "string") {
|
|
642
411
|
const captureUrl = new URL(capture, location.href);
|
|
@@ -648,10 +417,7 @@ let defaultRouter;
|
|
|
648
417
|
paramName: "capture"
|
|
649
418
|
});
|
|
650
419
|
}
|
|
651
|
-
// We want to check if Express-style wildcards are in the pathname only.
|
|
652
|
-
// TODO: Remove this log message in v4.
|
|
653
420
|
const valueToCheck = capture.startsWith("http") ? captureUrl.pathname : capture;
|
|
654
|
-
// See https://github.com/pillarjs/path-to-regexp#parameters
|
|
655
421
|
const wildcards = "[*:?+]";
|
|
656
422
|
if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
|
|
657
423
|
logger.debug(`The '$capture' parameter contains an Express-style wildcard character (${wildcards}). Strings are now always interpreted as exact matches; use a RegExp for partial or wildcard matches.`);
|
|
@@ -665,13 +431,10 @@ let defaultRouter;
|
|
|
665
431
|
}
|
|
666
432
|
return url.href === captureUrl.href;
|
|
667
433
|
};
|
|
668
|
-
// If `capture` is a string then `handler` and `method` must be present.
|
|
669
434
|
route = new Route(matchCallback, handler, method);
|
|
670
435
|
} else if (capture instanceof RegExp) {
|
|
671
|
-
// If `capture` is a `RegExp` then `handler` and `method` must be present.
|
|
672
436
|
route = new RegExpRoute(capture, handler, method);
|
|
673
437
|
} else if (typeof capture === "function") {
|
|
674
|
-
// If `capture` is a function then `handler` and `method` must be present.
|
|
675
438
|
route = new Route(capture, handler, method);
|
|
676
439
|
} else if (capture instanceof Route) {
|
|
677
440
|
route = capture;
|
|
@@ -687,34 +450,17 @@ let defaultRouter;
|
|
|
687
450
|
return route;
|
|
688
451
|
};
|
|
689
452
|
|
|
690
|
-
|
|
691
|
-
* If a Route throws an error while handling a request, this `handler`
|
|
692
|
-
* will be called and given a chance to provide a response.
|
|
693
|
-
*
|
|
694
|
-
* @param handler A callback function that returns a Promise resulting in a Response.
|
|
695
|
-
*/ const setCatchHandler = (handler)=>{
|
|
453
|
+
const setCatchHandler = (handler)=>{
|
|
696
454
|
const defaultRouter = getOrCreateDefaultRouter();
|
|
697
455
|
defaultRouter.setCatchHandler(handler);
|
|
698
456
|
};
|
|
699
457
|
|
|
700
|
-
|
|
701
|
-
* Defines a default `handler` that's called when no routes explicitly
|
|
702
|
-
* match the incoming request.
|
|
703
|
-
*
|
|
704
|
-
* Without a default handler, unmatched requests will go against the
|
|
705
|
-
* network as if there were no service worker present.
|
|
706
|
-
*
|
|
707
|
-
* @param handler A callback function that returns a Promise resulting in a Response.
|
|
708
|
-
*/ const setDefaultHandler = (handler)=>{
|
|
458
|
+
const setDefaultHandler = (handler)=>{
|
|
709
459
|
const defaultRouter = getOrCreateDefaultRouter();
|
|
710
460
|
defaultRouter.setDefaultHandler(handler);
|
|
711
461
|
};
|
|
712
462
|
|
|
713
|
-
|
|
714
|
-
* Unregisters a route from the singleton Router instance.
|
|
715
|
-
*
|
|
716
|
-
* @param route The route to unregister.
|
|
717
|
-
*/ const unregisterRoute = (route)=>{
|
|
463
|
+
const unregisterRoute = (route)=>{
|
|
718
464
|
const defaultRouter = getOrCreateDefaultRouter();
|
|
719
465
|
defaultRouter.unregisterRoute(route);
|
|
720
466
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@serwist/routing",
|
|
3
|
-
"version": "9.0.0-preview.
|
|
3
|
+
"version": "9.0.0-preview.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "A service worker helper library to route request URLs to handlers.",
|
|
6
6
|
"files": [
|
|
@@ -30,12 +30,12 @@
|
|
|
30
30
|
"./package.json": "./package.json"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@serwist/core": "9.0.0-preview.
|
|
33
|
+
"@serwist/core": "9.0.0-preview.1"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"rollup": "4.9.6",
|
|
37
37
|
"typescript": "5.4.0-dev.20240203",
|
|
38
|
-
"@serwist/constants": "9.0.0-preview.
|
|
38
|
+
"@serwist/constants": "9.0.0-preview.1"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"typescript": ">=5.0.0"
|