workbox-routing.dev.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. this.workbox = this.workbox || {};
  2. this.workbox.routing = (function (exports, assert_js, logger_js, WorkboxError_js, getFriendlyURL_js) {
  3. 'use strict';
  4. try {
  5. self['workbox:routing:5.1.4'] && _();
  6. } catch (e) {}
  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_js.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_js.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 module:workbox-routing
  82. */
  83. class Route {
  84. /**
  85. * Constructor for Route class.
  86. *
  87. * @param {module:workbox-routing~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 {module:workbox-routing~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 = defaultMethod) {
  96. {
  97. assert_js.assert.isType(match, 'function', {
  98. moduleName: 'workbox-routing',
  99. className: 'Route',
  100. funcName: 'constructor',
  101. paramName: 'match'
  102. });
  103. if (method) {
  104. assert_js.assert.isOneOf(method, validMethods, {
  105. paramName: 'method'
  106. });
  107. }
  108. } // These values are referenced directly by Router so cannot be
  109. // altered by minificaton.
  110. this.handler = normalizeHandler(handler);
  111. this.match = match;
  112. this.method = method;
  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
  123. * [Route]{@link module: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 `denylist` and `allowlist` parameters.
  132. *
  133. * @memberof module:workbox-routing
  134. * @extends module:workbox-routing.Route
  135. */
  136. class NavigationRoute extends Route {
  137. /**
  138. * If both `denylist` and `allowlist` are provided, the `denylist` will
  139. * take precedence and the request will not match this route.
  140. *
  141. * The regular expressions in `allowlist` and `denylist`
  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 {module:workbox-routing~handlerCallback} handler A callback
  148. * function that returns a Promise resulting in a Response.
  149. * @param {Object} options
  150. * @param {Array<RegExp>} [options.denylist] If any of these patterns match,
  151. * the route will not handle the request (even if a allowlist RegExp matches).
  152. * @param {Array<RegExp>} [options.allowlist=[/./]] If any of these patterns
  153. * match the URL's pathname and search parameter, the route will handle the
  154. * request (assuming the denylist doesn't match).
  155. */
  156. constructor(handler, {
  157. allowlist = [/./],
  158. denylist = []
  159. } = {}) {
  160. {
  161. assert_js.assert.isArrayOfClass(allowlist, RegExp, {
  162. moduleName: 'workbox-routing',
  163. className: 'NavigationRoute',
  164. funcName: 'constructor',
  165. paramName: 'options.allowlist'
  166. });
  167. assert_js.assert.isArrayOfClass(denylist, RegExp, {
  168. moduleName: 'workbox-routing',
  169. className: 'NavigationRoute',
  170. funcName: 'constructor',
  171. paramName: 'options.denylist'
  172. });
  173. }
  174. super(options => this._match(options), handler);
  175. this._allowlist = allowlist;
  176. this._denylist = denylist;
  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 && request.mode !== 'navigate') {
  193. return false;
  194. }
  195. const pathnameAndSearch = url.pathname + url.search;
  196. for (const regExp of this._denylist) {
  197. if (regExp.test(pathnameAndSearch)) {
  198. {
  199. logger_js.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL matches this denylist pattern: ` + `${regExp}`);
  200. }
  201. return false;
  202. }
  203. }
  204. if (this._allowlist.some(regExp => regExp.test(pathnameAndSearch))) {
  205. {
  206. logger_js.logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`);
  207. }
  208. return true;
  209. }
  210. {
  211. logger_js.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL being navigated to doesn't ` + `match the allowlist.`);
  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 module: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 module:workbox-routing
  233. * @extends module:workbox-routing.Route
  234. */
  235. class RegExpRoute extends Route {
  236. /**
  237. * If the regular expression contains
  238. * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},
  239. * the captured values will be passed to the
  240. * [handler's]{@link module:workbox-routing~handlerCallback} `params`
  241. * argument.
  242. *
  243. * @param {RegExp} regExp The regular expression to match against URLs.
  244. * @param {module:workbox-routing~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_js.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 immediately if there's no match.
  262. if (!result) {
  263. return;
  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_js.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;
  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 module: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 module: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<module: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. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  326. self.addEventListener('fetch', event => {
  327. const {
  328. request
  329. } = event;
  330. const responsePromise = this.handleRequest({
  331. request,
  332. event
  333. });
  334. if (responsePromise) {
  335. event.respondWith(responsePromise);
  336. }
  337. });
  338. }
  339. /**
  340. * Adds a message event listener for URLs to cache from the window.
  341. * This is useful to cache resources loaded on the page prior to when the
  342. * service worker started controlling it.
  343. *
  344. * The format of the message data sent from the window should be as follows.
  345. * Where the `urlsToCache` array may consist of URL strings or an array of
  346. * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
  347. *
  348. * ```
  349. * {
  350. * type: 'CACHE_URLS',
  351. * payload: {
  352. * urlsToCache: [
  353. * './script1.js',
  354. * './script2.js',
  355. * ['./script3.js', {mode: 'no-cors'}],
  356. * ],
  357. * },
  358. * }
  359. * ```
  360. */
  361. addCacheListener() {
  362. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  363. self.addEventListener('message', event => {
  364. if (event.data && event.data.type === 'CACHE_URLS') {
  365. const {
  366. payload
  367. } = event.data;
  368. {
  369. logger_js.logger.debug(`Caching URLs from the window`, payload.urlsToCache);
  370. }
  371. const requestPromises = Promise.all(payload.urlsToCache.map(entry => {
  372. if (typeof entry === 'string') {
  373. entry = [entry];
  374. }
  375. const request = new Request(...entry);
  376. return this.handleRequest({
  377. request
  378. }); // TODO(philipwalton): TypeScript errors without this typecast for
  379. // some reason (probably a bug). The real type here should work but
  380. // doesn't: `Array<Promise<Response> | undefined>`.
  381. })); // TypeScript
  382. event.waitUntil(requestPromises); // If a MessageChannel was used, reply to the message on success.
  383. if (event.ports && event.ports[0]) {
  384. requestPromises.then(() => event.ports[0].postMessage(true));
  385. }
  386. }
  387. });
  388. }
  389. /**
  390. * Apply the routing rules to a FetchEvent object to get a Response from an
  391. * appropriate Route's handler.
  392. *
  393. * @param {Object} options
  394. * @param {Request} options.request The request to handle (this is usually
  395. * from a fetch event, but it does not have to be).
  396. * @param {FetchEvent} [options.event] The event that triggered the request,
  397. * if applicable.
  398. * @return {Promise<Response>|undefined} A promise is returned if a
  399. * registered route can handle the request. If there is no matching
  400. * route and there's no `defaultHandler`, `undefined` is returned.
  401. */
  402. handleRequest({
  403. request,
  404. event
  405. }) {
  406. {
  407. assert_js.assert.isInstance(request, Request, {
  408. moduleName: 'workbox-routing',
  409. className: 'Router',
  410. funcName: 'handleRequest',
  411. paramName: 'options.request'
  412. });
  413. }
  414. const url = new URL(request.url, location.href);
  415. if (!url.protocol.startsWith('http')) {
  416. {
  417. logger_js.logger.debug(`Workbox Router only supports URLs that start with 'http'.`);
  418. }
  419. return;
  420. }
  421. const {
  422. params,
  423. route
  424. } = this.findMatchingRoute({
  425. url,
  426. request,
  427. event
  428. });
  429. let handler = route && route.handler;
  430. const debugMessages = [];
  431. {
  432. if (handler) {
  433. debugMessages.push([`Found a route to handle this request:`, route]);
  434. if (params) {
  435. debugMessages.push([`Passing the following params to the route's handler:`, params]);
  436. }
  437. }
  438. } // If we don't have a handler because there was no matching route, then
  439. // fall back to defaultHandler if that's defined.
  440. if (!handler && this._defaultHandler) {
  441. {
  442. debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler.`);
  443. }
  444. handler = this._defaultHandler;
  445. }
  446. if (!handler) {
  447. {
  448. // No handler so Workbox will do nothing. If logs is set of debug
  449. // i.e. verbose, we should print out this information.
  450. logger_js.logger.debug(`No route found for: ${getFriendlyURL_js.getFriendlyURL(url)}`);
  451. }
  452. return;
  453. }
  454. {
  455. // We have a handler, meaning Workbox is going to handle the route.
  456. // print the routing details to the console.
  457. logger_js.logger.groupCollapsed(`Router is responding to: ${getFriendlyURL_js.getFriendlyURL(url)}`);
  458. debugMessages.forEach(msg => {
  459. if (Array.isArray(msg)) {
  460. logger_js.logger.log(...msg);
  461. } else {
  462. logger_js.logger.log(msg);
  463. }
  464. });
  465. logger_js.logger.groupEnd();
  466. } // Wrap in try and catch in case the handle method throws a synchronous
  467. // error. It should still callback to the catch handler.
  468. let responsePromise;
  469. try {
  470. responsePromise = handler.handle({
  471. url,
  472. request,
  473. event,
  474. params
  475. });
  476. } catch (err) {
  477. responsePromise = Promise.reject(err);
  478. }
  479. if (responsePromise instanceof Promise && this._catchHandler) {
  480. responsePromise = responsePromise.catch(err => {
  481. {
  482. // Still include URL here as it will be async from the console group
  483. // and may not make sense without the URL
  484. logger_js.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL_js.getFriendlyURL(url)}. Falling back to Catch Handler.`);
  485. logger_js.logger.error(`Error thrown by:`, route);
  486. logger_js.logger.error(err);
  487. logger_js.logger.groupEnd();
  488. }
  489. return this._catchHandler.handle({
  490. url,
  491. request,
  492. event
  493. });
  494. });
  495. }
  496. return responsePromise;
  497. }
  498. /**
  499. * Checks a request and URL (and optionally an event) against the list of
  500. * registered routes, and if there's a match, returns the corresponding
  501. * route along with any params generated by the match.
  502. *
  503. * @param {Object} options
  504. * @param {URL} options.url
  505. * @param {Request} options.request The request to match.
  506. * @param {Event} [options.event] The corresponding event (unless N/A).
  507. * @return {Object} An object with `route` and `params` properties.
  508. * They are populated if a matching route was found or `undefined`
  509. * otherwise.
  510. */
  511. findMatchingRoute({
  512. url,
  513. request,
  514. event
  515. }) {
  516. {
  517. assert_js.assert.isInstance(url, URL, {
  518. moduleName: 'workbox-routing',
  519. className: 'Router',
  520. funcName: 'findMatchingRoute',
  521. paramName: 'options.url'
  522. });
  523. assert_js.assert.isInstance(request, Request, {
  524. moduleName: 'workbox-routing',
  525. className: 'Router',
  526. funcName: 'findMatchingRoute',
  527. paramName: 'options.request'
  528. });
  529. }
  530. const routes = this._routes.get(request.method) || [];
  531. for (const route of routes) {
  532. let params;
  533. const matchResult = route.match({
  534. url,
  535. request,
  536. event
  537. });
  538. if (matchResult) {
  539. // See https://github.com/GoogleChrome/workbox/issues/2079
  540. params = matchResult;
  541. if (Array.isArray(matchResult) && matchResult.length === 0) {
  542. // Instead of passing an empty array in as params, use undefined.
  543. params = undefined;
  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 = undefined;
  547. } else if (typeof matchResult === 'boolean') {
  548. // For the boolean value true (rather than just something truth-y),
  549. // don't set params.
  550. // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
  551. params = undefined;
  552. } // Return early if have a match.
  553. return {
  554. route,
  555. params
  556. };
  557. }
  558. } // If no match was found above, return and empty object.
  559. return {};
  560. }
  561. /**
  562. * Define a default `handler` that's called when no routes explicitly
  563. * match the incoming request.
  564. *
  565. * Without a default handler, unmatched requests will go against the
  566. * network as if there were no service worker present.
  567. *
  568. * @param {module:workbox-routing~handlerCallback} handler A callback
  569. * function that returns a Promise resulting in a Response.
  570. */
  571. setDefaultHandler(handler) {
  572. this._defaultHandler = normalizeHandler(handler);
  573. }
  574. /**
  575. * If a Route throws an error while handling a request, this `handler`
  576. * will be called and given a chance to provide a response.
  577. *
  578. * @param {module:workbox-routing~handlerCallback} handler A callback
  579. * function that returns a Promise resulting in a Response.
  580. */
  581. setCatchHandler(handler) {
  582. this._catchHandler = normalizeHandler(handler);
  583. }
  584. /**
  585. * Registers a route with the router.
  586. *
  587. * @param {module:workbox-routing.Route} route The route to register.
  588. */
  589. registerRoute(route) {
  590. {
  591. assert_js.assert.isType(route, 'object', {
  592. moduleName: 'workbox-routing',
  593. className: 'Router',
  594. funcName: 'registerRoute',
  595. paramName: 'route'
  596. });
  597. assert_js.assert.hasMethod(route, 'match', {
  598. moduleName: 'workbox-routing',
  599. className: 'Router',
  600. funcName: 'registerRoute',
  601. paramName: 'route'
  602. });
  603. assert_js.assert.isType(route.handler, 'object', {
  604. moduleName: 'workbox-routing',
  605. className: 'Router',
  606. funcName: 'registerRoute',
  607. paramName: 'route'
  608. });
  609. assert_js.assert.hasMethod(route.handler, 'handle', {
  610. moduleName: 'workbox-routing',
  611. className: 'Router',
  612. funcName: 'registerRoute',
  613. paramName: 'route.handler'
  614. });
  615. assert_js.assert.isType(route.method, 'string', {
  616. moduleName: 'workbox-routing',
  617. className: 'Router',
  618. funcName: 'registerRoute',
  619. paramName: 'route.method'
  620. });
  621. }
  622. if (!this._routes.has(route.method)) {
  623. this._routes.set(route.method, []);
  624. } // Give precedence to all of the earlier routes by adding this additional
  625. // route to the end of the array.
  626. this._routes.get(route.method).push(route);
  627. }
  628. /**
  629. * Unregisters a route with the router.
  630. *
  631. * @param {module:workbox-routing.Route} route The route to unregister.
  632. */
  633. unregisterRoute(route) {
  634. if (!this._routes.has(route.method)) {
  635. throw new WorkboxError_js.WorkboxError('unregister-route-but-not-found-with-method', {
  636. method: route.method
  637. });
  638. }
  639. const routeIndex = this._routes.get(route.method).indexOf(route);
  640. if (routeIndex > -1) {
  641. this._routes.get(route.method).splice(routeIndex, 1);
  642. } else {
  643. throw new WorkboxError_js.WorkboxError('unregister-route-route-not-registered');
  644. }
  645. }
  646. }
  647. /*
  648. Copyright 2019 Google LLC
  649. Use of this source code is governed by an MIT-style
  650. license that can be found in the LICENSE file or at
  651. https://opensource.org/licenses/MIT.
  652. */
  653. let defaultRouter;
  654. /**
  655. * Creates a new, singleton Router instance if one does not exist. If one
  656. * does already exist, that instance is returned.
  657. *
  658. * @private
  659. * @return {Router}
  660. */
  661. const getOrCreateDefaultRouter = () => {
  662. if (!defaultRouter) {
  663. defaultRouter = new Router(); // The helpers that use the default Router assume these listeners exist.
  664. defaultRouter.addFetchListener();
  665. defaultRouter.addCacheListener();
  666. }
  667. return defaultRouter;
  668. };
  669. /*
  670. Copyright 2019 Google LLC
  671. Use of this source code is governed by an MIT-style
  672. license that can be found in the LICENSE file or at
  673. https://opensource.org/licenses/MIT.
  674. */
  675. /**
  676. * Easily register a RegExp, string, or function with a caching
  677. * strategy to a singleton Router instance.
  678. *
  679. * This method will generate a Route for you if needed and
  680. * call [registerRoute()]{@link module:workbox-routing.Router#registerRoute}.
  681. *
  682. * @param {RegExp|string|module:workbox-routing.Route~matchCallback|module:workbox-routing.Route} capture
  683. * If the capture param is a `Route`, all other arguments will be ignored.
  684. * @param {module:workbox-routing~handlerCallback} [handler] A callback
  685. * function that returns a Promise resulting in a Response. This parameter
  686. * is required if `capture` is not a `Route` object.
  687. * @param {string} [method='GET'] The HTTP method to match the Route
  688. * against.
  689. * @return {module:workbox-routing.Route} The generated `Route`(Useful for
  690. * unregistering).
  691. *
  692. * @memberof module:workbox-routing
  693. */
  694. function registerRoute(capture, handler, method) {
  695. let route;
  696. if (typeof capture === 'string') {
  697. const captureUrl = new URL(capture, location.href);
  698. {
  699. if (!(capture.startsWith('/') || capture.startsWith('http'))) {
  700. throw new WorkboxError_js.WorkboxError('invalid-string', {
  701. moduleName: 'workbox-routing',
  702. funcName: 'registerRoute',
  703. paramName: 'capture'
  704. });
  705. } // We want to check if Express-style wildcards are in the pathname only.
  706. // TODO: Remove this log message in v4.
  707. const valueToCheck = capture.startsWith('http') ? captureUrl.pathname : capture; // See https://github.com/pillarjs/path-to-regexp#parameters
  708. const wildcards = '[*:?+]';
  709. if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
  710. logger_js.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.`);
  711. }
  712. }
  713. const matchCallback = ({
  714. url
  715. }) => {
  716. {
  717. if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
  718. logger_js.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.`);
  719. }
  720. }
  721. return url.href === captureUrl.href;
  722. }; // If `capture` is a string then `handler` and `method` must be present.
  723. route = new Route(matchCallback, handler, method);
  724. } else if (capture instanceof RegExp) {
  725. // If `capture` is a `RegExp` then `handler` and `method` must be present.
  726. route = new RegExpRoute(capture, handler, method);
  727. } else if (typeof capture === 'function') {
  728. // If `capture` is a function then `handler` and `method` must be present.
  729. route = new Route(capture, handler, method);
  730. } else if (capture instanceof Route) {
  731. route = capture;
  732. } else {
  733. throw new WorkboxError_js.WorkboxError('unsupported-route-type', {
  734. moduleName: 'workbox-routing',
  735. funcName: 'registerRoute',
  736. paramName: 'capture'
  737. });
  738. }
  739. const defaultRouter = getOrCreateDefaultRouter();
  740. defaultRouter.registerRoute(route);
  741. return route;
  742. }
  743. /*
  744. Copyright 2019 Google LLC
  745. Use of this source code is governed by an MIT-style
  746. license that can be found in the LICENSE file or at
  747. https://opensource.org/licenses/MIT.
  748. */
  749. /**
  750. * If a Route throws an error while handling a request, this `handler`
  751. * will be called and given a chance to provide a response.
  752. *
  753. * @param {module:workbox-routing~handlerCallback} handler A callback
  754. * function that returns a Promise resulting in a Response.
  755. *
  756. * @memberof module:workbox-routing
  757. */
  758. function setCatchHandler(handler) {
  759. const defaultRouter = getOrCreateDefaultRouter();
  760. defaultRouter.setCatchHandler(handler);
  761. }
  762. /*
  763. Copyright 2019 Google LLC
  764. Use of this source code is governed by an MIT-style
  765. license that can be found in the LICENSE file or at
  766. https://opensource.org/licenses/MIT.
  767. */
  768. /**
  769. * Define a default `handler` that's called when no routes explicitly
  770. * match the incoming request.
  771. *
  772. * Without a default handler, unmatched requests will go against the
  773. * network as if there were no service worker present.
  774. *
  775. * @param {module:workbox-routing~handlerCallback} handler A callback
  776. * function that returns a Promise resulting in a Response.
  777. *
  778. * @memberof module:workbox-routing
  779. */
  780. function setDefaultHandler(handler) {
  781. const defaultRouter = getOrCreateDefaultRouter();
  782. defaultRouter.setDefaultHandler(handler);
  783. }
  784. exports.NavigationRoute = NavigationRoute;
  785. exports.RegExpRoute = RegExpRoute;
  786. exports.Route = Route;
  787. exports.Router = Router;
  788. exports.registerRoute = registerRoute;
  789. exports.setCatchHandler = setCatchHandler;
  790. exports.setDefaultHandler = setDefaultHandler;
  791. return exports;
  792. }({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private));
  793. //# sourceMappingURL=workbox-routing.dev.js.map