workbox-routing.dev.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. this.workbox = this.workbox || {};
  2. this.workbox.routing = (function (exports, assert_mjs, logger_mjs, cacheNames_mjs, WorkboxError_mjs, getFriendlyURL_mjs) {
  3. 'use strict';
  4. try {
  5. self['workbox:routing:4.3.1'] && _();
  6. } catch (e) {} // eslint-disable-line
  7. /*
  8. Copyright 2018 Google LLC
  9. Use of this source code is governed by an MIT-style
  10. license that can be found in the LICENSE file or at
  11. https://opensource.org/licenses/MIT.
  12. */
  13. /**
  14. * The default HTTP method, 'GET', used when there's no specific method
  15. * configured for a route.
  16. *
  17. * @type {string}
  18. *
  19. * @private
  20. */
  21. const defaultMethod = 'GET';
  22. /**
  23. * The list of valid HTTP methods associated with requests that could be routed.
  24. *
  25. * @type {Array<string>}
  26. *
  27. * @private
  28. */
  29. const validMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT'];
  30. /*
  31. Copyright 2018 Google LLC
  32. Use of this source code is governed by an MIT-style
  33. license that can be found in the LICENSE file or at
  34. https://opensource.org/licenses/MIT.
  35. */
  36. /**
  37. * @param {function()|Object} handler Either a function, or an object with a
  38. * 'handle' method.
  39. * @return {Object} An object with a handle method.
  40. *
  41. * @private
  42. */
  43. const normalizeHandler = handler => {
  44. if (handler && typeof handler === 'object') {
  45. {
  46. assert_mjs.assert.hasMethod(handler, 'handle', {
  47. moduleName: 'workbox-routing',
  48. className: 'Route',
  49. funcName: 'constructor',
  50. paramName: 'handler'
  51. });
  52. }
  53. return handler;
  54. } else {
  55. {
  56. assert_mjs.assert.isType(handler, 'function', {
  57. moduleName: 'workbox-routing',
  58. className: 'Route',
  59. funcName: 'constructor',
  60. paramName: 'handler'
  61. });
  62. }
  63. return {
  64. handle: handler
  65. };
  66. }
  67. };
  68. /*
  69. Copyright 2018 Google LLC
  70. Use of this source code is governed by an MIT-style
  71. license that can be found in the LICENSE file or at
  72. https://opensource.org/licenses/MIT.
  73. */
  74. /**
  75. * A `Route` consists of a pair of callback functions, "match" and "handler".
  76. * The "match" callback determine if a route should be used to "handle" a
  77. * request by returning a non-falsy value if it can. The "handler" callback
  78. * is called when there is a match and should return a Promise that resolves
  79. * to a `Response`.
  80. *
  81. * @memberof workbox.routing
  82. */
  83. class Route {
  84. /**
  85. * Constructor for Route class.
  86. *
  87. * @param {workbox.routing.Route~matchCallback} match
  88. * A callback function that determines whether the route matches a given
  89. * `fetch` event by returning a non-falsy value.
  90. * @param {workbox.routing.Route~handlerCallback} handler A callback
  91. * function that returns a Promise resolving to a Response.
  92. * @param {string} [method='GET'] The HTTP method to match the Route
  93. * against.
  94. */
  95. constructor(match, handler, method) {
  96. {
  97. assert_mjs.assert.isType(match, 'function', {
  98. moduleName: 'workbox-routing',
  99. className: 'Route',
  100. funcName: 'constructor',
  101. paramName: 'match'
  102. });
  103. if (method) {
  104. assert_mjs.assert.isOneOf(method, validMethods, {
  105. paramName: 'method'
  106. });
  107. }
  108. } // These values are referenced directly by Router so cannot be
  109. // altered by minifification.
  110. this.handler = normalizeHandler(handler);
  111. this.match = match;
  112. this.method = method || defaultMethod;
  113. }
  114. }
  115. /*
  116. Copyright 2018 Google LLC
  117. Use of this source code is governed by an MIT-style
  118. license that can be found in the LICENSE file or at
  119. https://opensource.org/licenses/MIT.
  120. */
  121. /**
  122. * NavigationRoute makes it easy to create a [Route]{@link
  123. * workbox.routing.Route} that matches for browser
  124. * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}.
  125. *
  126. * It will only match incoming Requests whose
  127. * [`mode`]{@link https://fetch.spec.whatwg.org/#concept-request-mode}
  128. * is set to `navigate`.
  129. *
  130. * You can optionally only apply this route to a subset of navigation requests
  131. * by using one or both of the `blacklist` and `whitelist` parameters.
  132. *
  133. * @memberof workbox.routing
  134. * @extends workbox.routing.Route
  135. */
  136. class NavigationRoute extends Route {
  137. /**
  138. * If both `blacklist` and `whiltelist` are provided, the `blacklist` will
  139. * take precedence and the request will not match this route.
  140. *
  141. * The regular expressions in `whitelist` and `blacklist`
  142. * are matched against the concatenated
  143. * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname}
  144. * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search}
  145. * portions of the requested URL.
  146. *
  147. * @param {workbox.routing.Route~handlerCallback} handler A callback
  148. * function that returns a Promise resulting in a Response.
  149. * @param {Object} options
  150. * @param {Array<RegExp>} [options.blacklist] If any of these patterns match,
  151. * the route will not handle the request (even if a whitelist RegExp matches).
  152. * @param {Array<RegExp>} [options.whitelist=[/./]] If any of these patterns
  153. * match the URL's pathname and search parameter, the route will handle the
  154. * request (assuming the blacklist doesn't match).
  155. */
  156. constructor(handler, {
  157. whitelist = [/./],
  158. blacklist = []
  159. } = {}) {
  160. {
  161. assert_mjs.assert.isArrayOfClass(whitelist, RegExp, {
  162. moduleName: 'workbox-routing',
  163. className: 'NavigationRoute',
  164. funcName: 'constructor',
  165. paramName: 'options.whitelist'
  166. });
  167. assert_mjs.assert.isArrayOfClass(blacklist, RegExp, {
  168. moduleName: 'workbox-routing',
  169. className: 'NavigationRoute',
  170. funcName: 'constructor',
  171. paramName: 'options.blacklist'
  172. });
  173. }
  174. super(options => this._match(options), handler);
  175. this._whitelist = whitelist;
  176. this._blacklist = blacklist;
  177. }
  178. /**
  179. * Routes match handler.
  180. *
  181. * @param {Object} options
  182. * @param {URL} options.url
  183. * @param {Request} options.request
  184. * @return {boolean}
  185. *
  186. * @private
  187. */
  188. _match({
  189. url,
  190. request
  191. }) {
  192. if (request.mode !== 'navigate') {
  193. return false;
  194. }
  195. const pathnameAndSearch = url.pathname + url.search;
  196. for (const regExp of this._blacklist) {
  197. if (regExp.test(pathnameAndSearch)) {
  198. {
  199. logger_mjs.logger.log(`The navigation route is not being used, since the ` + `URL matches this blacklist pattern: ${regExp}`);
  200. }
  201. return false;
  202. }
  203. }
  204. if (this._whitelist.some(regExp => regExp.test(pathnameAndSearch))) {
  205. {
  206. logger_mjs.logger.debug(`The navigation route is being used.`);
  207. }
  208. return true;
  209. }
  210. {
  211. logger_mjs.logger.log(`The navigation route is not being used, since the URL ` + `being navigated to doesn't match the whitelist.`);
  212. }
  213. return false;
  214. }
  215. }
  216. /*
  217. Copyright 2018 Google LLC
  218. Use of this source code is governed by an MIT-style
  219. license that can be found in the LICENSE file or at
  220. https://opensource.org/licenses/MIT.
  221. */
  222. /**
  223. * RegExpRoute makes it easy to create a regular expression based
  224. * [Route]{@link workbox.routing.Route}.
  225. *
  226. * For same-origin requests the RegExp only needs to match part of the URL. For
  227. * requests against third-party servers, you must define a RegExp that matches
  228. * the start of the URL.
  229. *
  230. * [See the module docs for info.]{@link https://developers.google.com/web/tools/workbox/modules/workbox-routing}
  231. *
  232. * @memberof workbox.routing
  233. * @extends workbox.routing.Route
  234. */
  235. class RegExpRoute extends Route {
  236. /**
  237. * If the regulard expression contains
  238. * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},
  239. * th ecaptured values will be passed to the
  240. * [handler's]{@link workbox.routing.Route~handlerCallback} `params`
  241. * argument.
  242. *
  243. * @param {RegExp} regExp The regular expression to match against URLs.
  244. * @param {workbox.routing.Route~handlerCallback} handler A callback
  245. * function that returns a Promise resulting in a Response.
  246. * @param {string} [method='GET'] The HTTP method to match the Route
  247. * against.
  248. */
  249. constructor(regExp, handler, method) {
  250. {
  251. assert_mjs.assert.isInstance(regExp, RegExp, {
  252. moduleName: 'workbox-routing',
  253. className: 'RegExpRoute',
  254. funcName: 'constructor',
  255. paramName: 'pattern'
  256. });
  257. }
  258. const match = ({
  259. url
  260. }) => {
  261. const result = regExp.exec(url.href); // Return null immediately if there's no match.
  262. if (!result) {
  263. return null;
  264. } // Require that the match start at the first character in the URL string
  265. // if it's a cross-origin request.
  266. // See https://github.com/GoogleChrome/workbox/issues/281 for the context
  267. // behind this behavior.
  268. if (url.origin !== location.origin && result.index !== 0) {
  269. {
  270. logger_mjs.logger.debug(`The regular expression '${regExp}' only partially matched ` + `against the cross-origin URL '${url}'. RegExpRoute's will only ` + `handle cross-origin requests if they match the entire URL.`);
  271. }
  272. return null;
  273. } // If the route matches, but there aren't any capture groups defined, then
  274. // this will return [], which is truthy and therefore sufficient to
  275. // indicate a match.
  276. // If there are capture groups, then it will return their values.
  277. return result.slice(1);
  278. };
  279. super(match, handler, method);
  280. }
  281. }
  282. /*
  283. Copyright 2018 Google LLC
  284. Use of this source code is governed by an MIT-style
  285. license that can be found in the LICENSE file or at
  286. https://opensource.org/licenses/MIT.
  287. */
  288. /**
  289. * The Router can be used to process a FetchEvent through one or more
  290. * [Routes]{@link workbox.routing.Route} responding with a Request if
  291. * a matching route exists.
  292. *
  293. * If no route matches a given a request, the Router will use a "default"
  294. * handler if one is defined.
  295. *
  296. * Should the matching Route throw an error, the Router will use a "catch"
  297. * handler if one is defined to gracefully deal with issues and respond with a
  298. * Request.
  299. *
  300. * If a request matches multiple routes, the **earliest** registered route will
  301. * be used to respond to the request.
  302. *
  303. * @memberof workbox.routing
  304. */
  305. class Router {
  306. /**
  307. * Initializes a new Router.
  308. */
  309. constructor() {
  310. this._routes = new Map();
  311. }
  312. /**
  313. * @return {Map<string, Array<workbox.routing.Route>>} routes A `Map` of HTTP
  314. * method name ('GET', etc.) to an array of all the corresponding `Route`
  315. * instances that are registered.
  316. */
  317. get routes() {
  318. return this._routes;
  319. }
  320. /**
  321. * Adds a fetch event listener to respond to events when a route matches
  322. * the event's request.
  323. */
  324. addFetchListener() {
  325. self.addEventListener('fetch', event => {
  326. const {
  327. request
  328. } = event;
  329. const responsePromise = this.handleRequest({
  330. request,
  331. event
  332. });
  333. if (responsePromise) {
  334. event.respondWith(responsePromise);
  335. }
  336. });
  337. }
  338. /**
  339. * Adds a message event listener for URLs to cache from the window.
  340. * This is useful to cache resources loaded on the page prior to when the
  341. * service worker started controlling it.
  342. *
  343. * The format of the message data sent from the window should be as follows.
  344. * Where the `urlsToCache` array may consist of URL strings or an array of
  345. * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
  346. *
  347. * ```
  348. * {
  349. * type: 'CACHE_URLS',
  350. * payload: {
  351. * urlsToCache: [
  352. * './script1.js',
  353. * './script2.js',
  354. * ['./script3.js', {mode: 'no-cors'}],
  355. * ],
  356. * },
  357. * }
  358. * ```
  359. */
  360. addCacheListener() {
  361. self.addEventListener('message', async event => {
  362. if (event.data && event.data.type === 'CACHE_URLS') {
  363. const {
  364. payload
  365. } = event.data;
  366. {
  367. logger_mjs.logger.debug(`Caching URLs from the window`, payload.urlsToCache);
  368. }
  369. const requestPromises = Promise.all(payload.urlsToCache.map(entry => {
  370. if (typeof entry === 'string') {
  371. entry = [entry];
  372. }
  373. const request = new Request(...entry);
  374. return this.handleRequest({
  375. request
  376. });
  377. }));
  378. event.waitUntil(requestPromises); // If a MessageChannel was used, reply to the message on success.
  379. if (event.ports && event.ports[0]) {
  380. await requestPromises;
  381. event.ports[0].postMessage(true);
  382. }
  383. }
  384. });
  385. }
  386. /**
  387. * Apply the routing rules to a FetchEvent object to get a Response from an
  388. * appropriate Route's handler.
  389. *
  390. * @param {Object} options
  391. * @param {Request} options.request The request to handle (this is usually
  392. * from a fetch event, but it does not have to be).
  393. * @param {FetchEvent} [options.event] The event that triggered the request,
  394. * if applicable.
  395. * @return {Promise<Response>|undefined} A promise is returned if a
  396. * registered route can handle the request. If there is no matching
  397. * route and there's no `defaultHandler`, `undefined` is returned.
  398. */
  399. handleRequest({
  400. request,
  401. event
  402. }) {
  403. {
  404. assert_mjs.assert.isInstance(request, Request, {
  405. moduleName: 'workbox-routing',
  406. className: 'Router',
  407. funcName: 'handleRequest',
  408. paramName: 'options.request'
  409. });
  410. }
  411. const url = new URL(request.url, location);
  412. if (!url.protocol.startsWith('http')) {
  413. {
  414. logger_mjs.logger.debug(`Workbox Router only supports URLs that start with 'http'.`);
  415. }
  416. return;
  417. }
  418. let {
  419. params,
  420. route
  421. } = this.findMatchingRoute({
  422. url,
  423. request,
  424. event
  425. });
  426. let handler = route && route.handler;
  427. let debugMessages = [];
  428. {
  429. if (handler) {
  430. debugMessages.push([`Found a route to handle this request:`, route]);
  431. if (params) {
  432. debugMessages.push([`Passing the following params to the route's handler:`, params]);
  433. }
  434. }
  435. } // If we don't have a handler because there was no matching route, then
  436. // fall back to defaultHandler if that's defined.
  437. if (!handler && this._defaultHandler) {
  438. {
  439. debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler.`); // This is used for debugging in logs in the case of an error.
  440. route = '[Default Handler]';
  441. }
  442. handler = this._defaultHandler;
  443. }
  444. if (!handler) {
  445. {
  446. // No handler so Workbox will do nothing. If logs is set of debug
  447. // i.e. verbose, we should print out this information.
  448. logger_mjs.logger.debug(`No route found for: ${getFriendlyURL_mjs.getFriendlyURL(url)}`);
  449. }
  450. return;
  451. }
  452. {
  453. // We have a handler, meaning Workbox is going to handle the route.
  454. // print the routing details to the console.
  455. logger_mjs.logger.groupCollapsed(`Router is responding to: ${getFriendlyURL_mjs.getFriendlyURL(url)}`);
  456. debugMessages.forEach(msg => {
  457. if (Array.isArray(msg)) {
  458. logger_mjs.logger.log(...msg);
  459. } else {
  460. logger_mjs.logger.log(msg);
  461. }
  462. }); // The Request and Response objects contains a great deal of information,
  463. // hide it under a group in case developers want to see it.
  464. logger_mjs.logger.groupCollapsed(`View request details here.`);
  465. logger_mjs.logger.log(request);
  466. logger_mjs.logger.groupEnd();
  467. logger_mjs.logger.groupEnd();
  468. } // Wrap in try and catch in case the handle method throws a synchronous
  469. // error. It should still callback to the catch handler.
  470. let responsePromise;
  471. try {
  472. responsePromise = handler.handle({
  473. url,
  474. request,
  475. event,
  476. params
  477. });
  478. } catch (err) {
  479. responsePromise = Promise.reject(err);
  480. }
  481. if (responsePromise && this._catchHandler) {
  482. responsePromise = responsePromise.catch(err => {
  483. {
  484. // Still include URL here as it will be async from the console group
  485. // and may not make sense without the URL
  486. logger_mjs.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL_mjs.getFriendlyURL(url)}. Falling back to Catch Handler.`);
  487. logger_mjs.logger.error(`Error thrown by:`, route);
  488. logger_mjs.logger.error(err);
  489. logger_mjs.logger.groupEnd();
  490. }
  491. return this._catchHandler.handle({
  492. url,
  493. event,
  494. err
  495. });
  496. });
  497. }
  498. return responsePromise;
  499. }
  500. /**
  501. * Checks a request and URL (and optionally an event) against the list of
  502. * registered routes, and if there's a match, returns the corresponding
  503. * route along with any params generated by the match.
  504. *
  505. * @param {Object} options
  506. * @param {URL} options.url
  507. * @param {Request} options.request The request to match.
  508. * @param {FetchEvent} [options.event] The corresponding event (unless N/A).
  509. * @return {Object} An object with `route` and `params` properties.
  510. * They are populated if a matching route was found or `undefined`
  511. * otherwise.
  512. */
  513. findMatchingRoute({
  514. url,
  515. request,
  516. event
  517. }) {
  518. {
  519. assert_mjs.assert.isInstance(url, URL, {
  520. moduleName: 'workbox-routing',
  521. className: 'Router',
  522. funcName: 'findMatchingRoute',
  523. paramName: 'options.url'
  524. });
  525. assert_mjs.assert.isInstance(request, Request, {
  526. moduleName: 'workbox-routing',
  527. className: 'Router',
  528. funcName: 'findMatchingRoute',
  529. paramName: 'options.request'
  530. });
  531. }
  532. const routes = this._routes.get(request.method) || [];
  533. for (const route of routes) {
  534. let params;
  535. let matchResult = route.match({
  536. url,
  537. request,
  538. event
  539. });
  540. if (matchResult) {
  541. if (Array.isArray(matchResult) && matchResult.length > 0) {
  542. // Instead of passing an empty array in as params, use undefined.
  543. params = matchResult;
  544. } else if (matchResult.constructor === Object && Object.keys(matchResult).length > 0) {
  545. // Instead of passing an empty object in as params, use undefined.
  546. params = matchResult;
  547. } // Return early if have a match.
  548. return {
  549. route,
  550. params
  551. };
  552. }
  553. } // If no match was found above, return and empty object.
  554. return {};
  555. }
  556. /**
  557. * Define a default `handler` that's called when no routes explicitly
  558. * match the incoming request.
  559. *
  560. * Without a default handler, unmatched requests will go against the
  561. * network as if there were no service worker present.
  562. *
  563. * @param {workbox.routing.Route~handlerCallback} handler A callback
  564. * function that returns a Promise resulting in a Response.
  565. */
  566. setDefaultHandler(handler) {
  567. this._defaultHandler = normalizeHandler(handler);
  568. }
  569. /**
  570. * If a Route throws an error while handling a request, this `handler`
  571. * will be called and given a chance to provide a response.
  572. *
  573. * @param {workbox.routing.Route~handlerCallback} handler A callback
  574. * function that returns a Promise resulting in a Response.
  575. */
  576. setCatchHandler(handler) {
  577. this._catchHandler = normalizeHandler(handler);
  578. }
  579. /**
  580. * Registers a route with the router.
  581. *
  582. * @param {workbox.routing.Route} route The route to register.
  583. */
  584. registerRoute(route) {
  585. {
  586. assert_mjs.assert.isType(route, 'object', {
  587. moduleName: 'workbox-routing',
  588. className: 'Router',
  589. funcName: 'registerRoute',
  590. paramName: 'route'
  591. });
  592. assert_mjs.assert.hasMethod(route, 'match', {
  593. moduleName: 'workbox-routing',
  594. className: 'Router',
  595. funcName: 'registerRoute',
  596. paramName: 'route'
  597. });
  598. assert_mjs.assert.isType(route.handler, 'object', {
  599. moduleName: 'workbox-routing',
  600. className: 'Router',
  601. funcName: 'registerRoute',
  602. paramName: 'route'
  603. });
  604. assert_mjs.assert.hasMethod(route.handler, 'handle', {
  605. moduleName: 'workbox-routing',
  606. className: 'Router',
  607. funcName: 'registerRoute',
  608. paramName: 'route.handler'
  609. });
  610. assert_mjs.assert.isType(route.method, 'string', {
  611. moduleName: 'workbox-routing',
  612. className: 'Router',
  613. funcName: 'registerRoute',
  614. paramName: 'route.method'
  615. });
  616. }
  617. if (!this._routes.has(route.method)) {
  618. this._routes.set(route.method, []);
  619. } // Give precedence to all of the earlier routes by adding this additional
  620. // route to the end of the array.
  621. this._routes.get(route.method).push(route);
  622. }
  623. /**
  624. * Unregisters a route with the router.
  625. *
  626. * @param {workbox.routing.Route} route The route to unregister.
  627. */
  628. unregisterRoute(route) {
  629. if (!this._routes.has(route.method)) {
  630. throw new WorkboxError_mjs.WorkboxError('unregister-route-but-not-found-with-method', {
  631. method: route.method
  632. });
  633. }
  634. const routeIndex = this._routes.get(route.method).indexOf(route);
  635. if (routeIndex > -1) {
  636. this._routes.get(route.method).splice(routeIndex, 1);
  637. } else {
  638. throw new WorkboxError_mjs.WorkboxError('unregister-route-route-not-registered');
  639. }
  640. }
  641. }
  642. /*
  643. Copyright 2019 Google LLC
  644. Use of this source code is governed by an MIT-style
  645. license that can be found in the LICENSE file or at
  646. https://opensource.org/licenses/MIT.
  647. */
  648. let defaultRouter;
  649. /**
  650. * Creates a new, singleton Router instance if one does not exist. If one
  651. * does already exist, that instance is returned.
  652. *
  653. * @private
  654. * @return {Router}
  655. */
  656. const getOrCreateDefaultRouter = () => {
  657. if (!defaultRouter) {
  658. defaultRouter = new Router(); // The helpers that use the default Router assume these listeners exist.
  659. defaultRouter.addFetchListener();
  660. defaultRouter.addCacheListener();
  661. }
  662. return defaultRouter;
  663. };
  664. /*
  665. Copyright 2019 Google LLC
  666. Use of this source code is governed by an MIT-style
  667. license that can be found in the LICENSE file or at
  668. https://opensource.org/licenses/MIT.
  669. */
  670. /**
  671. * Registers a route that will return a precached file for a navigation
  672. * request. This is useful for the
  673. * [application shell pattern]{@link https://developers.google.com/web/fundamentals/architecture/app-shell}.
  674. *
  675. * When determining the URL of the precached HTML document, you will likely need
  676. * to call `workbox.precaching.getCacheKeyForURL(originalUrl)`, to account for
  677. * the fact that Workbox's precaching naming conventions often results in URL
  678. * cache keys that contain extra revisioning info.
  679. *
  680. * This method will generate a
  681. * [NavigationRoute]{@link workbox.routing.NavigationRoute}
  682. * and call
  683. * [Router.registerRoute()]{@link workbox.routing.Router#registerRoute} on a
  684. * singleton Router instance.
  685. *
  686. * @param {string} cachedAssetUrl The cache key to use for the HTML file.
  687. * @param {Object} [options]
  688. * @param {string} [options.cacheName] Cache name to store and retrieve
  689. * requests. Defaults to precache cache name provided by
  690. * [workbox-core.cacheNames]{@link workbox.core.cacheNames}.
  691. * @param {Array<RegExp>} [options.blacklist=[]] If any of these patterns
  692. * match, the route will not handle the request (even if a whitelist entry
  693. * matches).
  694. * @param {Array<RegExp>} [options.whitelist=[/./]] If any of these patterns
  695. * match the URL's pathname and search parameter, the route will handle the
  696. * request (assuming the blacklist doesn't match).
  697. * @return {workbox.routing.NavigationRoute} Returns the generated
  698. * Route.
  699. *
  700. * @alias workbox.routing.registerNavigationRoute
  701. */
  702. const registerNavigationRoute = (cachedAssetUrl, options = {}) => {
  703. {
  704. assert_mjs.assert.isType(cachedAssetUrl, 'string', {
  705. moduleName: 'workbox-routing',
  706. funcName: 'registerNavigationRoute',
  707. paramName: 'cachedAssetUrl'
  708. });
  709. }
  710. const cacheName = cacheNames_mjs.cacheNames.getPrecacheName(options.cacheName);
  711. const handler = async () => {
  712. try {
  713. const response = await caches.match(cachedAssetUrl, {
  714. cacheName
  715. });
  716. if (response) {
  717. return response;
  718. } // This shouldn't normally happen, but there are edge cases:
  719. // https://github.com/GoogleChrome/workbox/issues/1441
  720. throw new Error(`The cache ${cacheName} did not have an entry for ` + `${cachedAssetUrl}.`);
  721. } catch (error) {
  722. // If there's either a cache miss, or the caches.match() call threw
  723. // an exception, then attempt to fulfill the navigation request with
  724. // a response from the network rather than leaving the user with a
  725. // failed navigation.
  726. {
  727. logger_mjs.logger.debug(`Unable to respond to navigation request with ` + `cached response. Falling back to network.`, error);
  728. } // This might still fail if the browser is offline...
  729. return fetch(cachedAssetUrl);
  730. }
  731. };
  732. const route = new NavigationRoute(handler, {
  733. whitelist: options.whitelist,
  734. blacklist: options.blacklist
  735. });
  736. const defaultRouter = getOrCreateDefaultRouter();
  737. defaultRouter.registerRoute(route);
  738. return route;
  739. };
  740. /*
  741. Copyright 2019 Google LLC
  742. Use of this source code is governed by an MIT-style
  743. license that can be found in the LICENSE file or at
  744. https://opensource.org/licenses/MIT.
  745. */
  746. /**
  747. * Easily register a RegExp, string, or function with a caching
  748. * strategy to a singleton Router instance.
  749. *
  750. * This method will generate a Route for you if needed and
  751. * call [Router.registerRoute()]{@link
  752. * workbox.routing.Router#registerRoute}.
  753. *
  754. * @param {
  755. * RegExp|
  756. * string|
  757. * workbox.routing.Route~matchCallback|
  758. * workbox.routing.Route
  759. * } capture
  760. * If the capture param is a `Route`, all other arguments will be ignored.
  761. * @param {workbox.routing.Route~handlerCallback} handler A callback
  762. * function that returns a Promise resulting in a Response.
  763. * @param {string} [method='GET'] The HTTP method to match the Route
  764. * against.
  765. * @return {workbox.routing.Route} The generated `Route`(Useful for
  766. * unregistering).
  767. *
  768. * @alias workbox.routing.registerRoute
  769. */
  770. const registerRoute = (capture, handler, method = 'GET') => {
  771. let route;
  772. if (typeof capture === 'string') {
  773. const captureUrl = new URL(capture, location);
  774. {
  775. if (!(capture.startsWith('/') || capture.startsWith('http'))) {
  776. throw new WorkboxError_mjs.WorkboxError('invalid-string', {
  777. moduleName: 'workbox-routing',
  778. funcName: 'registerRoute',
  779. paramName: 'capture'
  780. });
  781. } // We want to check if Express-style wildcards are in the pathname only.
  782. // TODO: Remove this log message in v4.
  783. const valueToCheck = capture.startsWith('http') ? captureUrl.pathname : capture; // See https://github.com/pillarjs/path-to-regexp#parameters
  784. const wildcards = '[*:?+]';
  785. if (valueToCheck.match(new RegExp(`${wildcards}`))) {
  786. logger_mjs.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.`);
  787. }
  788. }
  789. const matchCallback = ({
  790. url
  791. }) => {
  792. {
  793. if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
  794. logger_mjs.logger.debug(`${capture} only partially matches the cross-origin URL ` + `${url}. This route will only handle cross-origin requests ` + `if they match the entire URL.`);
  795. }
  796. }
  797. return url.href === captureUrl.href;
  798. };
  799. route = new Route(matchCallback, handler, method);
  800. } else if (capture instanceof RegExp) {
  801. route = new RegExpRoute(capture, handler, method);
  802. } else if (typeof capture === 'function') {
  803. route = new Route(capture, handler, method);
  804. } else if (capture instanceof Route) {
  805. route = capture;
  806. } else {
  807. throw new WorkboxError_mjs.WorkboxError('unsupported-route-type', {
  808. moduleName: 'workbox-routing',
  809. funcName: 'registerRoute',
  810. paramName: 'capture'
  811. });
  812. }
  813. const defaultRouter = getOrCreateDefaultRouter();
  814. defaultRouter.registerRoute(route);
  815. return route;
  816. };
  817. /*
  818. Copyright 2019 Google LLC
  819. Use of this source code is governed by an MIT-style
  820. license that can be found in the LICENSE file or at
  821. https://opensource.org/licenses/MIT.
  822. */
  823. /**
  824. * If a Route throws an error while handling a request, this `handler`
  825. * will be called and given a chance to provide a response.
  826. *
  827. * @param {workbox.routing.Route~handlerCallback} handler A callback
  828. * function that returns a Promise resulting in a Response.
  829. *
  830. * @alias workbox.routing.setCatchHandler
  831. */
  832. const setCatchHandler = handler => {
  833. const defaultRouter = getOrCreateDefaultRouter();
  834. defaultRouter.setCatchHandler(handler);
  835. };
  836. /*
  837. Copyright 2019 Google LLC
  838. Use of this source code is governed by an MIT-style
  839. license that can be found in the LICENSE file or at
  840. https://opensource.org/licenses/MIT.
  841. */
  842. /**
  843. * Define a default `handler` that's called when no routes explicitly
  844. * match the incoming request.
  845. *
  846. * Without a default handler, unmatched requests will go against the
  847. * network as if there were no service worker present.
  848. *
  849. * @param {workbox.routing.Route~handlerCallback} handler A callback
  850. * function that returns a Promise resulting in a Response.
  851. *
  852. * @alias workbox.routing.setDefaultHandler
  853. */
  854. const setDefaultHandler = handler => {
  855. const defaultRouter = getOrCreateDefaultRouter();
  856. defaultRouter.setDefaultHandler(handler);
  857. };
  858. /*
  859. Copyright 2018 Google LLC
  860. Use of this source code is governed by an MIT-style
  861. license that can be found in the LICENSE file or at
  862. https://opensource.org/licenses/MIT.
  863. */
  864. {
  865. assert_mjs.assert.isSWEnv('workbox-routing');
  866. }
  867. exports.NavigationRoute = NavigationRoute;
  868. exports.RegExpRoute = RegExpRoute;
  869. exports.registerNavigationRoute = registerNavigationRoute;
  870. exports.registerRoute = registerRoute;
  871. exports.Route = Route;
  872. exports.Router = Router;
  873. exports.setCatchHandler = setCatchHandler;
  874. exports.setDefaultHandler = setDefaultHandler;
  875. return exports;
  876. }({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private));
  877. //# sourceMappingURL=workbox-routing.dev.js.map