@serwist/routing 8.4.4 → 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.
Files changed (43) hide show
  1. package/dist/NavigationRoute.d.ts +2 -2
  2. package/dist/NavigationRoute.d.ts.map +1 -0
  3. package/dist/RegExpRoute.d.ts +2 -2
  4. package/dist/RegExpRoute.d.ts.map +1 -0
  5. package/dist/Route.d.ts +2 -2
  6. package/dist/Route.d.ts.map +1 -0
  7. package/dist/Router.d.ts +2 -2
  8. package/dist/Router.d.ts.map +1 -0
  9. package/dist/_types.d.ts +1 -0
  10. package/dist/_types.d.ts.map +1 -0
  11. package/dist/index.d.ts +3 -1
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +37 -289
  14. package/dist/registerRoute.d.ts +3 -3
  15. package/dist/registerRoute.d.ts.map +1 -0
  16. package/dist/setCatchHandler.d.ts +2 -2
  17. package/dist/setCatchHandler.d.ts.map +1 -0
  18. package/dist/setDefaultHandler.d.ts +3 -3
  19. package/dist/setDefaultHandler.d.ts.map +1 -0
  20. package/dist/unregisterRoute.d.ts +8 -0
  21. package/dist/unregisterRoute.d.ts.map +1 -0
  22. package/dist/utils/constants.d.ts +3 -6
  23. package/dist/utils/constants.d.ts.map +1 -0
  24. package/dist/utils/getOrCreateDefaultRouter.d.ts +1 -0
  25. package/dist/utils/getOrCreateDefaultRouter.d.ts.map +1 -0
  26. package/dist/utils/normalizeHandler.d.ts +1 -0
  27. package/dist/utils/normalizeHandler.d.ts.map +1 -0
  28. package/package.json +18 -16
  29. package/src/NavigationRoute.ts +119 -0
  30. package/src/RegExpRoute.ts +74 -0
  31. package/src/Route.ts +68 -0
  32. package/src/Router.ts +436 -0
  33. package/src/_types.ts +62 -0
  34. package/src/index.ts +22 -0
  35. package/src/registerRoute.ts +89 -0
  36. package/src/setCatchHandler.ts +22 -0
  37. package/src/setDefaultHandler.ts +25 -0
  38. package/src/unregisterRoute.ts +12 -0
  39. package/src/utils/constants.ts +24 -0
  40. package/src/utils/getOrCreateDefaultRouter.ts +29 -0
  41. package/src/utils/normalizeHandler.ts +40 -0
  42. package/dist/index.cjs +0 -728
  43. package/dist/index.d.cts +0 -0
@@ -23,7 +23,7 @@ export interface NavigationRouteMatchOptions {
23
23
  * You can optionally only apply this route to a subset of navigation requests
24
24
  * by using one or both of the `denylist` and `allowlist` parameters.
25
25
  */
26
- declare class NavigationRoute extends Route {
26
+ export declare class NavigationRoute extends Route {
27
27
  private readonly _allowlist;
28
28
  private readonly _denylist;
29
29
  /**
@@ -54,4 +54,4 @@ declare class NavigationRoute extends Route {
54
54
  */
55
55
  private _match;
56
56
  }
57
- export { NavigationRoute };
57
+ //# sourceMappingURL=NavigationRoute.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NavigationRoute.d.ts","sourceRoot":"","sources":["../src/NavigationRoute.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAA6B,MAAM,eAAe,CAAC;AAG7E,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEnC,MAAM,WAAW,2BAA2B;IAC1C;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAED;;;;;;;;GAQG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACxC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAW;IACtC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAW;IAErC;;;;;;;;;;;;;;;;;OAiBG;gBACS,OAAO,EAAE,YAAY,EAAE,EAAE,SAAiB,EAAE,QAAa,EAAE,GAAE,2BAAgC;IAsBzG;;;;;;OAMG;IACH,OAAO,CAAC,MAAM;CA8Bf"}
@@ -8,7 +8,7 @@ import type { HTTPMethod } from "./utils/constants.js";
8
8
  * requests against third-party servers, you must define a RegExp that matches
9
9
  * the start of the URL.
10
10
  */
11
- declare class RegExpRoute extends Route {
11
+ export declare class RegExpRoute extends Route {
12
12
  /**
13
13
  * If the regular expression contains
14
14
  * [capture groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references),
@@ -21,4 +21,4 @@ declare class RegExpRoute extends Route {
21
21
  */
22
22
  constructor(regExp: RegExp, handler: RouteHandler, method?: HTTPMethod);
23
23
  }
24
- export { RegExpRoute };
24
+ //# sourceMappingURL=RegExpRoute.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RegExpRoute.d.ts","sourceRoot":"","sources":["../src/RegExpRoute.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAiD,MAAM,eAAe,CAAC;AAGjG,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEvD;;;;;;GAMG;AACH,qBAAa,WAAY,SAAQ,KAAK;IACpC;;;;;;;;;OASG;gBACS,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,CAAC,EAAE,UAAU;CAyCvE"}
package/dist/Route.d.ts CHANGED
@@ -7,7 +7,7 @@ import type { HTTPMethod } from "./utils/constants.js";
7
7
  * is called when there is a match and should return a Promise that resolves
8
8
  * to a `Response`.
9
9
  */
10
- declare class Route {
10
+ export declare class Route {
11
11
  handler: RouteHandlerObject;
12
12
  match: RouteMatchCallback;
13
13
  method: HTTPMethod;
@@ -30,4 +30,4 @@ declare class Route {
30
30
  */
31
31
  setCatchHandler(handler: RouteHandler): void;
32
32
  }
33
- export { Route };
33
+ //# sourceMappingURL=Route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Route.d.ts","sourceRoot":"","sources":["../src/Route.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAG1F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAIvD;;;;;;GAMG;AACH,qBAAa,KAAK;IAChB,OAAO,EAAE,kBAAkB,CAAC;IAC5B,KAAK,EAAE,kBAAkB,CAAC;IAC1B,MAAM,EAAE,UAAU,CAAC;IACnB,YAAY,CAAC,EAAE,kBAAkB,CAAC;IAElC;;;;;;;;;OASG;gBACS,KAAK,EAAE,kBAAkB,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,GAAE,UAA0B;IAqBhG;;;;OAIG;IACH,eAAe,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI;CAG7C"}
package/dist/Router.d.ts CHANGED
@@ -13,7 +13,7 @@ import type { HTTPMethod } from "./utils/constants.js";
13
13
  * If a request matches multiple routes, the **earliest** registered route will
14
14
  * be used to respond to the request.
15
15
  */
16
- declare class Router {
16
+ export declare class Router {
17
17
  private readonly _routes;
18
18
  private readonly _defaultHandlerMap;
19
19
  private _catchHandler?;
@@ -121,4 +121,4 @@ declare class Router {
121
121
  */
122
122
  unregisterRoute(route: Route): void;
123
123
  }
124
- export { Router };
124
+ //# sourceMappingURL=Router.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Router.d.ts","sourceRoot":"","sources":["../src/Router.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,2BAA2B,EAAsB,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAG9H,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAavD;;;;;;;;;;;GAWG;AACH,qBAAa,MAAM;IACjB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA2B;IACnD,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAsC;IACzE,OAAO,CAAC,aAAa,CAAC,CAAqB;IAE3C;;OAEG;;IAMH;;;OAGG;IACH,IAAI,MAAM,IAAI,GAAG,CAAC,UAAU,EAAE,KAAK,EAAE,CAAC,CAErC;IAED;;;OAGG;IACH,gBAAgB,IAAI,IAAI;IAWxB;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,gBAAgB,IAAI,IAAI;IAkCxB;;;;;;;;OAQG;IACH,aAAa,CAAC,EACZ,OAAO,EACP,KAAK,GACN,EAAE;QACD;;WAEG;QACH,OAAO,EAAE,OAAO,CAAC;QACjB;;WAEG;QACH,KAAK,EAAE,eAAe,CAAC;KACxB,GAAG,OAAO,CAAC,QAAQ,CAAC,GAAG,SAAS;IA8HjC;;;;;;;;OAQG;IACH,iBAAiB,CAAC,EAAE,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,yBAAyB,GAAG;QACjF,KAAK,CAAC,EAAE,KAAK,CAAC;QACd,MAAM,CAAC,EAAE,2BAA2B,CAAC,QAAQ,CAAC,CAAC;KAChD;IAgDD;;;;;;;;;;;;OAYG;IACH,iBAAiB,CAAC,OAAO,EAAE,YAAY,EAAE,MAAM,GAAE,UAA0B,GAAG,IAAI;IAIlF;;;;;;OAMG;IACH,eAAe,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI;IAI5C;;;;OAIG;IACH,aAAa,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IA+CjC;;;;OAIG;IACH,eAAe,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;CAcpC"}
package/dist/_types.d.ts CHANGED
@@ -45,3 +45,4 @@ export {};
45
45
  *
46
46
  * @memberof workbox-routing
47
47
  */
48
+ //# sourceMappingURL=_types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_types.d.ts","sourceRoot":"","sources":["../src/_types.ts"],"names":[],"mappings":";AAeA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG"}
package/dist/index.d.ts CHANGED
@@ -6,6 +6,8 @@ import { Router } from "./Router.js";
6
6
  import { registerRoute } from "./registerRoute.js";
7
7
  import { setCatchHandler } from "./setCatchHandler.js";
8
8
  import { setDefaultHandler } from "./setDefaultHandler.js";
9
+ import { unregisterRoute } from "./unregisterRoute.js";
9
10
  import type { HTTPMethod } from "./utils/constants.js";
10
- export { NavigationRoute, RegExpRoute, registerRoute, Route, Router, setCatchHandler, setDefaultHandler };
11
+ export { NavigationRoute, RegExpRoute, registerRoute, Route, Router, setCatchHandler, setDefaultHandler, unregisterRoute };
11
12
  export type { HTTPMethod, NavigationRouteMatchOptions };
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEvD,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,aAAa,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,iBAAiB,EAAE,eAAe,EAAE,CAAC;AAE3H,YAAY,EAAE,UAAU,EAAE,2BAA2B,EAAE,CAAC"}
package/dist/index.js CHANGED
@@ -1,26 +1,7 @@
1
1
  import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/internal';
2
2
 
3
- /*
4
- Copyright 2018 Google LLC
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
- * @type {string}
14
- *
15
- * @private
16
- */ const defaultMethod = "GET";
17
- /**
18
- * The list of valid HTTP methods associated with requests that could be routed.
19
- *
20
- * @type {Array<string>}
21
- *
22
- * @private
23
- */ const validMethods = [
3
+ const defaultMethod = "GET";
4
+ const validMethods = [
24
5
  "DELETE",
25
6
  "GET",
26
7
  "HEAD",
@@ -29,13 +10,7 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
29
10
  "PUT"
30
11
  ];
31
12
 
32
- /**
33
- * @param handler Either a function, or an object with a
34
- * 'handle' method.
35
- * @returns An object with a handle method.
36
- *
37
- * @private
38
- */ const normalizeHandler = (handler)=>{
13
+ const normalizeHandler = (handler)=>{
39
14
  if (handler && typeof handler === "object") {
40
15
  if (process.env.NODE_ENV !== "production") {
41
16
  assert.hasMethod(handler, "handle", {
@@ -60,27 +35,12 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
60
35
  };
61
36
  };
62
37
 
63
- /**
64
- * A `Route` consists of a pair of callback functions, "match" and "handler".
65
- * The "match" callback determine if a route should be used to "handle" a
66
- * request by returning a non-falsy value if it can. The "handler" callback
67
- * is called when there is a match and should return a Promise that resolves
68
- * to a `Response`.
69
- */ class Route {
38
+ class Route {
70
39
  handler;
71
40
  match;
72
41
  method;
73
42
  catchHandler;
74
- /**
75
- * Constructor for Route class.
76
- *
77
- * @param match A callback function that determines whether the
78
- * route matches a given `fetch` event by returning a non-falsy value.
79
- * @param handler A callback function that returns a Promise resolving
80
- * to a Response.
81
- * @param method The HTTP method to match the Route against. Defaults
82
- * to GET.
83
- */ constructor(match, handler, method = defaultMethod){
43
+ constructor(match, handler, method = defaultMethod){
84
44
  if (process.env.NODE_ENV !== "production") {
85
45
  assert.isType(match, "function", {
86
46
  moduleName: "@serwist/routing",
@@ -94,50 +54,19 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
94
54
  });
95
55
  }
96
56
  }
97
- // These values are referenced directly by Router so cannot be
98
- // altered by minificaton.
99
57
  this.handler = normalizeHandler(handler);
100
58
  this.match = match;
101
59
  this.method = method;
102
60
  }
103
- /**
104
- *
105
- * @param handler A callback function that returns a Promise resolving
106
- * to a Response.
107
- */ setCatchHandler(handler) {
61
+ setCatchHandler(handler) {
108
62
  this.catchHandler = normalizeHandler(handler);
109
63
  }
110
64
  }
111
65
 
112
- /**
113
- * NavigationRoute makes it easy to create a `@serwist/routing` Route that matches for browser
114
- * [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests).
115
- *
116
- * It will only match incoming Requests whose [mode](https://fetch.spec.whatwg.org/#concept-request-mode) is set to `navigate`.
117
- *
118
- * You can optionally only apply this route to a subset of navigation requests
119
- * by using one or both of the `denylist` and `allowlist` parameters.
120
- */ class NavigationRoute extends Route {
66
+ class NavigationRoute extends Route {
121
67
  _allowlist;
122
68
  _denylist;
123
- /**
124
- * If both `denylist` and `allowlist` are provided, the `denylist` will
125
- * take precedence and the request will not match this route.
126
- *
127
- * The regular expressions in `allowlist` and `denylist`
128
- * are matched against the concatenated
129
- * [`pathname`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname)
130
- * and [`search`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search)
131
- * portions of the requested URL.
132
- *
133
- * *Note*: These RegExps may be evaluated against every destination URL during
134
- * a navigation. Avoid using
135
- * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
136
- * or else your users may see delays when navigating your site.
137
- *
138
- * @param handler A callback function that returns a Promise resulting in a Response.
139
- * @param options
140
- */ constructor(handler, { allowlist = [
69
+ constructor(handler, { allowlist = [
141
70
  /./
142
71
  ], denylist = [] } = {}){
143
72
  if (process.env.NODE_ENV !== "production") {
@@ -158,13 +87,7 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
158
87
  this._allowlist = allowlist;
159
88
  this._denylist = denylist;
160
89
  }
161
- /**
162
- * Routes match handler.
163
- *
164
- * @param options
165
- * @returns
166
- * @private
167
- */ _match({ url, request }) {
90
+ _match({ url, request }) {
168
91
  if (request && request.mode !== "navigate") {
169
92
  return false;
170
93
  }
@@ -190,23 +113,8 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
190
113
  }
191
114
  }
192
115
 
193
- /**
194
- * RegExpRoute makes it easy to create a regular expression based on a `@serwist/routing` Route.
195
- *
196
- * For same-origin requests the RegExp only needs to match part of the URL. For
197
- * requests against third-party servers, you must define a RegExp that matches
198
- * the start of the URL.
199
- */ class RegExpRoute extends Route {
200
- /**
201
- * If the regular expression contains
202
- * [capture groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references),
203
- * the captured values will be passed to the `params` argument.
204
- *
205
- * @param regExp The regular expression to match against URLs.
206
- * @param handler A callback function that returns a Promise resulting in a Response.
207
- * @param method The HTTP method to match the Route, defaults to GET.
208
- * against.
209
- */ constructor(regExp, handler, method){
116
+ class RegExpRoute extends Route {
117
+ constructor(regExp, handler, method){
210
118
  if (process.env.NODE_ENV !== "production") {
211
119
  assert.isInstance(regExp, RegExp, {
212
120
  moduleName: "@serwist/routing",
@@ -217,62 +125,33 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
217
125
  }
218
126
  const match = ({ url })=>{
219
127
  const result = regExp.exec(url.href);
220
- // Return immediately if there's no match.
221
128
  if (!result) {
222
129
  return;
223
130
  }
224
- // Require that the match start at the first character in the URL string
225
- // if it's a cross-origin request.
226
- // See https://github.com/GoogleChrome/workbox/issues/281 for the context
227
- // behind this behavior.
228
131
  if (url.origin !== location.origin && result.index !== 0) {
229
132
  if (process.env.NODE_ENV !== "production") {
230
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.`);
231
134
  }
232
135
  return;
233
136
  }
234
- // If the route matches, but there aren't any capture groups defined, then
235
- // this will return [], which is truthy and therefore sufficient to
236
- // indicate a match.
237
- // If there are capture groups, then it will return their values.
238
137
  return result.slice(1);
239
138
  };
240
139
  super(match, handler, method);
241
140
  }
242
141
  }
243
142
 
244
- /**
245
- * The Router can be used to process a `FetchEvent` using one or more `@serwist/routing` Route(s),
246
- * responding with a `Response` if a matching route exists.
247
- *
248
- * If no route matches a given a request, the Router will use a "default" handler if one is defined.
249
- *
250
- * Should the matching Route throw an error, the Router will use a "catch" handler if one is defined to
251
- * gracefully deal with issues and respond with a Request.
252
- *
253
- * If a request matches multiple routes, the **earliest** registered route will
254
- * be used to respond to the request.
255
- */ class Router {
143
+ class Router {
256
144
  _routes;
257
145
  _defaultHandlerMap;
258
146
  _catchHandler;
259
- /**
260
- * Initializes a new Router.
261
- */ constructor(){
147
+ constructor(){
262
148
  this._routes = new Map();
263
149
  this._defaultHandlerMap = new Map();
264
150
  }
265
- /**
266
- * @returns routes A `Map` of HTTP method name ('GET', etc.) to an array of all the corresponding `Route`
267
- * instances that are registered.
268
- */ get routes() {
151
+ get routes() {
269
152
  return this._routes;
270
153
  }
271
- /**
272
- * Adds a fetch event listener to respond to events when a route matches
273
- * the event's request.
274
- */ addFetchListener() {
275
- // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
154
+ addFetchListener() {
276
155
  self.addEventListener("fetch", (event)=>{
277
156
  const { request } = event;
278
157
  const responsePromise = this.handleRequest({
@@ -284,34 +163,9 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
284
163
  }
285
164
  });
286
165
  }
287
- /**
288
- * Adds a message event listener for URLs to cache from the window.
289
- * This is useful to cache resources loaded on the page prior to when the
290
- * service worker started controlling it.
291
- *
292
- * The format of the message data sent from the window should be as follows.
293
- * Where the `urlsToCache` array may consist of URL strings or an array of
294
- * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
295
- *
296
- * ```
297
- * {
298
- * type: 'CACHE_URLS',
299
- * payload: {
300
- * urlsToCache: [
301
- * './script1.js',
302
- * './script2.js',
303
- * ['./script3.js', {mode: 'no-cors'}],
304
- * ],
305
- * },
306
- * }
307
- * ```
308
- */ addCacheListener() {
309
- // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
166
+ addCacheListener() {
310
167
  self.addEventListener("message", (event)=>{
311
- // event.data is type 'any'
312
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
313
168
  if (event.data && event.data.type === "CACHE_URLS") {
314
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
315
169
  const { payload } = event.data;
316
170
  if (process.env.NODE_ENV !== "production") {
317
171
  logger.debug("Caching URLs from the window", payload.urlsToCache);
@@ -327,27 +181,15 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
327
181
  request,
328
182
  event
329
183
  });
330
- // TODO(philipwalton): TypeScript errors without this typecast for
331
- // some reason (probably a bug). The real type here should work but
332
- // doesn't: `Array<Promise<Response> | undefined>`.
333
- })); // TypeScript
184
+ }));
334
185
  event.waitUntil(requestPromises);
335
- // If a MessageChannel was used, reply to the message on success.
336
186
  if (event.ports?.[0]) {
337
187
  void requestPromises.then(()=>event.ports[0].postMessage(true));
338
188
  }
339
189
  }
340
190
  });
341
191
  }
342
- /**
343
- * Apply the routing rules to a FetchEvent object to get a Response from an
344
- * appropriate Route's handler.
345
- *
346
- * @param options
347
- * @returns A promise is returned if a registered route can handle the request.
348
- * If there is no matching route and there's no `defaultHandler`, `undefined`
349
- * is returned.
350
- */ handleRequest({ request, event }) {
192
+ handleRequest({ request, event }) {
351
193
  if (process.env.NODE_ENV !== "production") {
352
194
  assert.isInstance(request, Request, {
353
195
  moduleName: "@serwist/routing",
@@ -386,8 +228,6 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
386
228
  }
387
229
  }
388
230
  }
389
- // If we don't have a handler because there was no matching route, then
390
- // fall back to defaultHandler if that's defined.
391
231
  const method = request.method;
392
232
  if (!handler && this._defaultHandlerMap.has(method)) {
393
233
  if (process.env.NODE_ENV !== "production") {
@@ -397,15 +237,11 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
397
237
  }
398
238
  if (!handler) {
399
239
  if (process.env.NODE_ENV !== "production") {
400
- // No handler so Serwist will do nothing. If logs is set of debug
401
- // i.e. verbose, we should print out this information.
402
240
  logger.debug(`No route found for: ${getFriendlyURL(url)}`);
403
241
  }
404
242
  return;
405
243
  }
406
244
  if (process.env.NODE_ENV !== "production") {
407
- // We have a handler, meaning Serwist is going to handle the route.
408
- // print the routing details to the console.
409
245
  logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
410
246
  for (const msg of debugMessages){
411
247
  if (Array.isArray(msg)) {
@@ -416,8 +252,6 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
416
252
  }
417
253
  logger.groupEnd();
418
254
  }
419
- // Wrap in try and catch in case the handle method throws a synchronous
420
- // error. It should still callback to the catch handler.
421
255
  let responsePromise;
422
256
  try {
423
257
  responsePromise = handler.handle({
@@ -429,15 +263,11 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
429
263
  } catch (err) {
430
264
  responsePromise = Promise.reject(err);
431
265
  }
432
- // Get route's catch handler, if it exists
433
266
  const catchHandler = route?.catchHandler;
434
267
  if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
435
268
  responsePromise = responsePromise.catch(async (err)=>{
436
- // If there's a route catch handler, process that first
437
269
  if (catchHandler) {
438
270
  if (process.env.NODE_ENV !== "production") {
439
- // Still include URL here as it will be async from the console group
440
- // and may not make sense without the URL
441
271
  logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
442
272
  logger.error("Error thrown by:", route);
443
273
  logger.error(err);
@@ -458,8 +288,6 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
458
288
  }
459
289
  if (this._catchHandler) {
460
290
  if (process.env.NODE_ENV !== "production") {
461
- // Still include URL here as it will be async from the console group
462
- // and may not make sense without the URL
463
291
  logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
464
292
  logger.error("Error thrown by:", route);
465
293
  logger.error(err);
@@ -476,20 +304,10 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
476
304
  }
477
305
  return responsePromise;
478
306
  }
479
- /**
480
- * Checks a request and URL (and optionally an event) against the list of
481
- * registered routes, and if there's a match, returns the corresponding
482
- * route along with any params generated by the match.
483
- *
484
- * @param options
485
- * @returns An object with `route` and `params` properties. They are populated
486
- * if a matching route was found or `undefined` otherwise.
487
- */ findMatchingRoute({ url, sameOrigin, request, event }) {
307
+ findMatchingRoute({ url, sameOrigin, request, event }) {
488
308
  const routes = this._routes.get(request.method) || [];
489
309
  for (const route of routes){
490
310
  let params;
491
- // route.match returns type any, not possible to change right now.
492
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
493
311
  const matchResult = route.match({
494
312
  url,
495
313
  sameOrigin,
@@ -498,67 +316,33 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
498
316
  });
499
317
  if (matchResult) {
500
318
  if (process.env.NODE_ENV !== "production") {
501
- // Warn developers that using an async matchCallback is almost always
502
- // not the right thing to do.
503
319
  if (matchResult instanceof Promise) {
504
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);
505
321
  }
506
322
  }
507
- // See https://github.com/GoogleChrome/workbox/issues/2079
508
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
509
323
  params = matchResult;
510
324
  if (Array.isArray(params) && params.length === 0) {
511
- // Instead of passing an empty array in as params, use undefined.
512
325
  params = undefined;
513
- } else if (matchResult.constructor === Object && // eslint-disable-line
514
- Object.keys(matchResult).length === 0) {
515
- // Instead of passing an empty object in as params, use undefined.
326
+ } else if (matchResult.constructor === Object && Object.keys(matchResult).length === 0) {
516
327
  params = undefined;
517
328
  } else if (typeof matchResult === "boolean") {
518
- // For the boolean value true (rather than just something truth-y),
519
- // don't set params.
520
- // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
521
329
  params = undefined;
522
330
  }
523
- // Return early if have a match.
524
331
  return {
525
332
  route,
526
333
  params
527
334
  };
528
335
  }
529
336
  }
530
- // If no match was found above, return and empty object.
531
337
  return {};
532
338
  }
533
- /**
534
- * Define a default `handler` that's called when no routes explicitly
535
- * match the incoming request.
536
- *
537
- * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
538
- *
539
- * Without a default handler, unmatched requests will go against the
540
- * network as if there were no service worker present.
541
- *
542
- * @param handler A callback function that returns a Promise resulting in a Response.
543
- * @param method The HTTP method to associate with this default handler. Each method
544
- * has its own default. Defaults to GET.
545
- */ setDefaultHandler(handler, method = defaultMethod) {
339
+ setDefaultHandler(handler, method = defaultMethod) {
546
340
  this._defaultHandlerMap.set(method, normalizeHandler(handler));
547
341
  }
548
- /**
549
- * If a Route throws an error while handling a request, this `handler`
550
- * will be called and given a chance to provide a response.
551
- *
552
- * @param handler A callback function that returns a Promise resulting
553
- * in a Response.
554
- */ setCatchHandler(handler) {
342
+ setCatchHandler(handler) {
555
343
  this._catchHandler = normalizeHandler(handler);
556
344
  }
557
- /**
558
- * Registers a route with the router.
559
- *
560
- * @param route The route to register.
561
- */ registerRoute(route) {
345
+ registerRoute(route) {
562
346
  if (process.env.NODE_ENV !== "production") {
563
347
  assert.isType(route, "object", {
564
348
  moduleName: "@serwist/routing",
@@ -594,15 +378,9 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
594
378
  if (!this._routes.has(route.method)) {
595
379
  this._routes.set(route.method, []);
596
380
  }
597
- // Give precedence to all of the earlier routes by adding this additional
598
- // route to the end of the array.
599
381
  this._routes.get(route.method).push(route);
600
382
  }
601
- /**
602
- * Unregisters a route with the router.
603
- *
604
- * @param route The route to unregister.
605
- */ unregisterRoute(route) {
383
+ unregisterRoute(route) {
606
384
  if (!this._routes.has(route.method)) {
607
385
  throw new SerwistError("unregister-route-but-not-found-with-method", {
608
386
  method: route.method
@@ -618,32 +396,16 @@ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/inte
618
396
  }
619
397
 
620
398
  let defaultRouter;
621
- /**
622
- * Creates a new, singleton Router instance if one does not exist. If one
623
- * does already exist, that instance is returned.
624
- *
625
- * @private
626
- * @returns
627
- */ const getOrCreateDefaultRouter = ()=>{
399
+ const getOrCreateDefaultRouter = ()=>{
628
400
  if (!defaultRouter) {
629
401
  defaultRouter = new Router();
630
- // The helpers that use the default Router assume these listeners exist.
631
402
  defaultRouter.addFetchListener();
632
403
  defaultRouter.addCacheListener();
633
404
  }
634
405
  return defaultRouter;
635
406
  };
636
407
 
637
- /**
638
- * Easily register a RegExp, string, or function with a caching
639
- * strategy to a singleton Router instance.
640
- *
641
- * @param capture If the capture param is a `Route`, all other arguments will be ignored.
642
- * @param handler A callback function that returns a Promise resulting in a Response.
643
- * This parameter is required if `capture` is not a `Route` object.
644
- * @param method The HTTP method to match the Route against. Defaults to GET.
645
- * @returns The generated `Route`.
646
- */ function registerRoute(capture, handler, method) {
408
+ const registerRoute = (capture, handler, method)=>{
647
409
  let route;
648
410
  if (typeof capture === "string") {
649
411
  const captureUrl = new URL(capture, location.href);
@@ -655,10 +417,7 @@ let defaultRouter;
655
417
  paramName: "capture"
656
418
  });
657
419
  }
658
- // We want to check if Express-style wildcards are in the pathname only.
659
- // TODO: Remove this log message in v4.
660
420
  const valueToCheck = capture.startsWith("http") ? captureUrl.pathname : capture;
661
- // See https://github.com/pillarjs/path-to-regexp#parameters
662
421
  const wildcards = "[*:?+]";
663
422
  if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
664
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.`);
@@ -672,13 +431,10 @@ let defaultRouter;
672
431
  }
673
432
  return url.href === captureUrl.href;
674
433
  };
675
- // If `capture` is a string then `handler` and `method` must be present.
676
434
  route = new Route(matchCallback, handler, method);
677
435
  } else if (capture instanceof RegExp) {
678
- // If `capture` is a `RegExp` then `handler` and `method` must be present.
679
436
  route = new RegExpRoute(capture, handler, method);
680
437
  } else if (typeof capture === "function") {
681
- // If `capture` is a function then `handler` and `method` must be present.
682
438
  route = new Route(capture, handler, method);
683
439
  } else if (capture instanceof Route) {
684
440
  route = capture;
@@ -692,29 +448,21 @@ let defaultRouter;
692
448
  const defaultRouter = getOrCreateDefaultRouter();
693
449
  defaultRouter.registerRoute(route);
694
450
  return route;
695
- }
451
+ };
696
452
 
697
- /**
698
- * If a Route throws an error while handling a request, this `handler`
699
- * will be called and given a chance to provide a response.
700
- *
701
- * @param handler A callback function that returns a Promise resulting in a Response.
702
- */ function setCatchHandler(handler) {
453
+ const setCatchHandler = (handler)=>{
703
454
  const defaultRouter = getOrCreateDefaultRouter();
704
455
  defaultRouter.setCatchHandler(handler);
705
- }
456
+ };
706
457
 
707
- /**
708
- * Define a default `handler` that's called when no routes explicitly
709
- * match the incoming request.
710
- *
711
- * Without a default handler, unmatched requests will go against the
712
- * network as if there were no service worker present.
713
- *
714
- * @param handler A callback function that returns a Promise resulting in a Response.
715
- */ function setDefaultHandler(handler) {
458
+ const setDefaultHandler = (handler)=>{
716
459
  const defaultRouter = getOrCreateDefaultRouter();
717
460
  defaultRouter.setDefaultHandler(handler);
718
- }
461
+ };
462
+
463
+ const unregisterRoute = (route)=>{
464
+ const defaultRouter = getOrCreateDefaultRouter();
465
+ defaultRouter.unregisterRoute(route);
466
+ };
719
467
 
720
- export { NavigationRoute, RegExpRoute, Route, Router, registerRoute, setCatchHandler, setDefaultHandler };
468
+ export { NavigationRoute, RegExpRoute, Route, Router, registerRoute, setCatchHandler, setDefaultHandler, unregisterRoute };