Router.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /*
  2. Copyright 2018 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import { assert } from 'workbox-core/_private/assert.js';
  8. import { logger } from 'workbox-core/_private/logger.js';
  9. import { WorkboxError } from 'workbox-core/_private/WorkboxError.js';
  10. import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';
  11. import { normalizeHandler } from './utils/normalizeHandler.js';
  12. import './_version.js';
  13. /**
  14. * The Router can be used to process a FetchEvent through one or more
  15. * [Routes]{@link module:workbox-routing.Route} responding with a Request if
  16. * a matching route exists.
  17. *
  18. * If no route matches a given a request, the Router will use a "default"
  19. * handler if one is defined.
  20. *
  21. * Should the matching Route throw an error, the Router will use a "catch"
  22. * handler if one is defined to gracefully deal with issues and respond with a
  23. * Request.
  24. *
  25. * If a request matches multiple routes, the **earliest** registered route will
  26. * be used to respond to the request.
  27. *
  28. * @memberof module:workbox-routing
  29. */
  30. class Router {
  31. /**
  32. * Initializes a new Router.
  33. */
  34. constructor() {
  35. this._routes = new Map();
  36. }
  37. /**
  38. * @return {Map<string, Array<module:workbox-routing.Route>>} routes A `Map` of HTTP
  39. * method name ('GET', etc.) to an array of all the corresponding `Route`
  40. * instances that are registered.
  41. */
  42. get routes() {
  43. return this._routes;
  44. }
  45. /**
  46. * Adds a fetch event listener to respond to events when a route matches
  47. * the event's request.
  48. */
  49. addFetchListener() {
  50. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  51. self.addEventListener('fetch', ((event) => {
  52. const { request } = event;
  53. const responsePromise = this.handleRequest({ request, event });
  54. if (responsePromise) {
  55. event.respondWith(responsePromise);
  56. }
  57. }));
  58. }
  59. /**
  60. * Adds a message event listener for URLs to cache from the window.
  61. * This is useful to cache resources loaded on the page prior to when the
  62. * service worker started controlling it.
  63. *
  64. * The format of the message data sent from the window should be as follows.
  65. * Where the `urlsToCache` array may consist of URL strings or an array of
  66. * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
  67. *
  68. * ```
  69. * {
  70. * type: 'CACHE_URLS',
  71. * payload: {
  72. * urlsToCache: [
  73. * './script1.js',
  74. * './script2.js',
  75. * ['./script3.js', {mode: 'no-cors'}],
  76. * ],
  77. * },
  78. * }
  79. * ```
  80. */
  81. addCacheListener() {
  82. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  83. self.addEventListener('message', ((event) => {
  84. if (event.data && event.data.type === 'CACHE_URLS') {
  85. const { payload } = event.data;
  86. if (process.env.NODE_ENV !== 'production') {
  87. logger.debug(`Caching URLs from the window`, payload.urlsToCache);
  88. }
  89. const requestPromises = Promise.all(payload.urlsToCache.map((entry) => {
  90. if (typeof entry === 'string') {
  91. entry = [entry];
  92. }
  93. const request = new Request(...entry);
  94. return this.handleRequest({ request });
  95. // TODO(philipwalton): TypeScript errors without this typecast for
  96. // some reason (probably a bug). The real type here should work but
  97. // doesn't: `Array<Promise<Response> | undefined>`.
  98. })); // TypeScript
  99. event.waitUntil(requestPromises);
  100. // If a MessageChannel was used, reply to the message on success.
  101. if (event.ports && event.ports[0]) {
  102. requestPromises.then(() => event.ports[0].postMessage(true));
  103. }
  104. }
  105. }));
  106. }
  107. /**
  108. * Apply the routing rules to a FetchEvent object to get a Response from an
  109. * appropriate Route's handler.
  110. *
  111. * @param {Object} options
  112. * @param {Request} options.request The request to handle (this is usually
  113. * from a fetch event, but it does not have to be).
  114. * @param {FetchEvent} [options.event] The event that triggered the request,
  115. * if applicable.
  116. * @return {Promise<Response>|undefined} A promise is returned if a
  117. * registered route can handle the request. If there is no matching
  118. * route and there's no `defaultHandler`, `undefined` is returned.
  119. */
  120. handleRequest({ request, event }) {
  121. if (process.env.NODE_ENV !== 'production') {
  122. assert.isInstance(request, Request, {
  123. moduleName: 'workbox-routing',
  124. className: 'Router',
  125. funcName: 'handleRequest',
  126. paramName: 'options.request',
  127. });
  128. }
  129. const url = new URL(request.url, location.href);
  130. if (!url.protocol.startsWith('http')) {
  131. if (process.env.NODE_ENV !== 'production') {
  132. logger.debug(`Workbox Router only supports URLs that start with 'http'.`);
  133. }
  134. return;
  135. }
  136. const { params, route } = this.findMatchingRoute({ url, request, event });
  137. let handler = route && route.handler;
  138. const debugMessages = [];
  139. if (process.env.NODE_ENV !== 'production') {
  140. if (handler) {
  141. debugMessages.push([
  142. `Found a route to handle this request:`, route,
  143. ]);
  144. if (params) {
  145. debugMessages.push([
  146. `Passing the following params to the route's handler:`, params,
  147. ]);
  148. }
  149. }
  150. }
  151. // If we don't have a handler because there was no matching route, then
  152. // fall back to defaultHandler if that's defined.
  153. if (!handler && this._defaultHandler) {
  154. if (process.env.NODE_ENV !== 'production') {
  155. debugMessages.push(`Failed to find a matching route. Falling ` +
  156. `back to the default handler.`);
  157. }
  158. handler = this._defaultHandler;
  159. }
  160. if (!handler) {
  161. if (process.env.NODE_ENV !== 'production') {
  162. // No handler so Workbox will do nothing. If logs is set of debug
  163. // i.e. verbose, we should print out this information.
  164. logger.debug(`No route found for: ${getFriendlyURL(url)}`);
  165. }
  166. return;
  167. }
  168. if (process.env.NODE_ENV !== 'production') {
  169. // We have a handler, meaning Workbox is going to handle the route.
  170. // print the routing details to the console.
  171. logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
  172. debugMessages.forEach((msg) => {
  173. if (Array.isArray(msg)) {
  174. logger.log(...msg);
  175. }
  176. else {
  177. logger.log(msg);
  178. }
  179. });
  180. logger.groupEnd();
  181. }
  182. // Wrap in try and catch in case the handle method throws a synchronous
  183. // error. It should still callback to the catch handler.
  184. let responsePromise;
  185. try {
  186. responsePromise = handler.handle({ url, request, event, params });
  187. }
  188. catch (err) {
  189. responsePromise = Promise.reject(err);
  190. }
  191. if (responsePromise instanceof Promise && this._catchHandler) {
  192. responsePromise = responsePromise.catch((err) => {
  193. if (process.env.NODE_ENV !== 'production') {
  194. // Still include URL here as it will be async from the console group
  195. // and may not make sense without the URL
  196. logger.groupCollapsed(`Error thrown when responding to: ` +
  197. ` ${getFriendlyURL(url)}. Falling back to Catch Handler.`);
  198. logger.error(`Error thrown by:`, route);
  199. logger.error(err);
  200. logger.groupEnd();
  201. }
  202. return this._catchHandler.handle({ url, request, event });
  203. });
  204. }
  205. return responsePromise;
  206. }
  207. /**
  208. * Checks a request and URL (and optionally an event) against the list of
  209. * registered routes, and if there's a match, returns the corresponding
  210. * route along with any params generated by the match.
  211. *
  212. * @param {Object} options
  213. * @param {URL} options.url
  214. * @param {Request} options.request The request to match.
  215. * @param {Event} [options.event] The corresponding event (unless N/A).
  216. * @return {Object} An object with `route` and `params` properties.
  217. * They are populated if a matching route was found or `undefined`
  218. * otherwise.
  219. */
  220. findMatchingRoute({ url, request, event }) {
  221. if (process.env.NODE_ENV !== 'production') {
  222. assert.isInstance(url, URL, {
  223. moduleName: 'workbox-routing',
  224. className: 'Router',
  225. funcName: 'findMatchingRoute',
  226. paramName: 'options.url',
  227. });
  228. assert.isInstance(request, Request, {
  229. moduleName: 'workbox-routing',
  230. className: 'Router',
  231. funcName: 'findMatchingRoute',
  232. paramName: 'options.request',
  233. });
  234. }
  235. const routes = this._routes.get(request.method) || [];
  236. for (const route of routes) {
  237. let params;
  238. const matchResult = route.match({ url, request, event });
  239. if (matchResult) {
  240. // See https://github.com/GoogleChrome/workbox/issues/2079
  241. params = matchResult;
  242. if (Array.isArray(matchResult) && matchResult.length === 0) {
  243. // Instead of passing an empty array in as params, use undefined.
  244. params = undefined;
  245. }
  246. else if ((matchResult.constructor === Object &&
  247. Object.keys(matchResult).length === 0)) {
  248. // Instead of passing an empty object in as params, use undefined.
  249. params = undefined;
  250. }
  251. else if (typeof matchResult === 'boolean') {
  252. // For the boolean value true (rather than just something truth-y),
  253. // don't set params.
  254. // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
  255. params = undefined;
  256. }
  257. // Return early if have a match.
  258. return { route, params };
  259. }
  260. }
  261. // If no match was found above, return and empty object.
  262. return {};
  263. }
  264. /**
  265. * Define a default `handler` that's called when no routes explicitly
  266. * match the incoming request.
  267. *
  268. * Without a default handler, unmatched requests will go against the
  269. * network as if there were no service worker present.
  270. *
  271. * @param {module:workbox-routing~handlerCallback} handler A callback
  272. * function that returns a Promise resulting in a Response.
  273. */
  274. setDefaultHandler(handler) {
  275. this._defaultHandler = normalizeHandler(handler);
  276. }
  277. /**
  278. * If a Route throws an error while handling a request, this `handler`
  279. * will be called and given a chance to provide a response.
  280. *
  281. * @param {module:workbox-routing~handlerCallback} handler A callback
  282. * function that returns a Promise resulting in a Response.
  283. */
  284. setCatchHandler(handler) {
  285. this._catchHandler = normalizeHandler(handler);
  286. }
  287. /**
  288. * Registers a route with the router.
  289. *
  290. * @param {module:workbox-routing.Route} route The route to register.
  291. */
  292. registerRoute(route) {
  293. if (process.env.NODE_ENV !== 'production') {
  294. assert.isType(route, 'object', {
  295. moduleName: 'workbox-routing',
  296. className: 'Router',
  297. funcName: 'registerRoute',
  298. paramName: 'route',
  299. });
  300. assert.hasMethod(route, 'match', {
  301. moduleName: 'workbox-routing',
  302. className: 'Router',
  303. funcName: 'registerRoute',
  304. paramName: 'route',
  305. });
  306. assert.isType(route.handler, 'object', {
  307. moduleName: 'workbox-routing',
  308. className: 'Router',
  309. funcName: 'registerRoute',
  310. paramName: 'route',
  311. });
  312. assert.hasMethod(route.handler, 'handle', {
  313. moduleName: 'workbox-routing',
  314. className: 'Router',
  315. funcName: 'registerRoute',
  316. paramName: 'route.handler',
  317. });
  318. assert.isType(route.method, 'string', {
  319. moduleName: 'workbox-routing',
  320. className: 'Router',
  321. funcName: 'registerRoute',
  322. paramName: 'route.method',
  323. });
  324. }
  325. if (!this._routes.has(route.method)) {
  326. this._routes.set(route.method, []);
  327. }
  328. // Give precedence to all of the earlier routes by adding this additional
  329. // route to the end of the array.
  330. this._routes.get(route.method).push(route);
  331. }
  332. /**
  333. * Unregisters a route with the router.
  334. *
  335. * @param {module:workbox-routing.Route} route The route to unregister.
  336. */
  337. unregisterRoute(route) {
  338. if (!this._routes.has(route.method)) {
  339. throw new WorkboxError('unregister-route-but-not-found-with-method', {
  340. method: route.method,
  341. });
  342. }
  343. const routeIndex = this._routes.get(route.method).indexOf(route);
  344. if (routeIndex > -1) {
  345. this._routes.get(route.method).splice(routeIndex, 1);
  346. }
  347. else {
  348. throw new WorkboxError('unregister-route-route-not-registered');
  349. }
  350. }
  351. }
  352. export { Router };