workbox-routing.dev.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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:6.6.0'] && _();
  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 workbox-routing
  82. */
  83. class Route {
  84. /**
  85. * Constructor for Route class.
  86. *
  87. * @param {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 {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. * @param {workbox-routing-handlerCallback} handler A callback
  117. * function that returns a Promise resolving to a Response
  118. */
  119. setCatchHandler(handler) {
  120. this.catchHandler = normalizeHandler(handler);
  121. }
  122. }
  123. /*
  124. Copyright 2018 Google LLC
  125. Use of this source code is governed by an MIT-style
  126. license that can be found in the LICENSE file or at
  127. https://opensource.org/licenses/MIT.
  128. */
  129. /**
  130. * NavigationRoute makes it easy to create a
  131. * {@link workbox-routing.Route} that matches for browser
  132. * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}.
  133. *
  134. * It will only match incoming Requests whose
  135. * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode}
  136. * is set to `navigate`.
  137. *
  138. * You can optionally only apply this route to a subset of navigation requests
  139. * by using one or both of the `denylist` and `allowlist` parameters.
  140. *
  141. * @memberof workbox-routing
  142. * @extends workbox-routing.Route
  143. */
  144. class NavigationRoute extends Route {
  145. /**
  146. * If both `denylist` and `allowlist` are provided, the `denylist` will
  147. * take precedence and the request will not match this route.
  148. *
  149. * The regular expressions in `allowlist` and `denylist`
  150. * are matched against the concatenated
  151. * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname}
  152. * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search}
  153. * portions of the requested URL.
  154. *
  155. * *Note*: These RegExps may be evaluated against every destination URL during
  156. * a navigation. Avoid using
  157. * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
  158. * or else your users may see delays when navigating your site.
  159. *
  160. * @param {workbox-routing~handlerCallback} handler A callback
  161. * function that returns a Promise resulting in a Response.
  162. * @param {Object} options
  163. * @param {Array<RegExp>} [options.denylist] If any of these patterns match,
  164. * the route will not handle the request (even if a allowlist RegExp matches).
  165. * @param {Array<RegExp>} [options.allowlist=[/./]] If any of these patterns
  166. * match the URL's pathname and search parameter, the route will handle the
  167. * request (assuming the denylist doesn't match).
  168. */
  169. constructor(handler, {
  170. allowlist = [/./],
  171. denylist = []
  172. } = {}) {
  173. {
  174. assert_js.assert.isArrayOfClass(allowlist, RegExp, {
  175. moduleName: 'workbox-routing',
  176. className: 'NavigationRoute',
  177. funcName: 'constructor',
  178. paramName: 'options.allowlist'
  179. });
  180. assert_js.assert.isArrayOfClass(denylist, RegExp, {
  181. moduleName: 'workbox-routing',
  182. className: 'NavigationRoute',
  183. funcName: 'constructor',
  184. paramName: 'options.denylist'
  185. });
  186. }
  187. super(options => this._match(options), handler);
  188. this._allowlist = allowlist;
  189. this._denylist = denylist;
  190. }
  191. /**
  192. * Routes match handler.
  193. *
  194. * @param {Object} options
  195. * @param {URL} options.url
  196. * @param {Request} options.request
  197. * @return {boolean}
  198. *
  199. * @private
  200. */
  201. _match({
  202. url,
  203. request
  204. }) {
  205. if (request && request.mode !== 'navigate') {
  206. return false;
  207. }
  208. const pathnameAndSearch = url.pathname + url.search;
  209. for (const regExp of this._denylist) {
  210. if (regExp.test(pathnameAndSearch)) {
  211. {
  212. logger_js.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL matches this denylist pattern: ` + `${regExp.toString()}`);
  213. }
  214. return false;
  215. }
  216. }
  217. if (this._allowlist.some(regExp => regExp.test(pathnameAndSearch))) {
  218. {
  219. logger_js.logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`);
  220. }
  221. return true;
  222. }
  223. {
  224. logger_js.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL being navigated to doesn't ` + `match the allowlist.`);
  225. }
  226. return false;
  227. }
  228. }
  229. /*
  230. Copyright 2018 Google LLC
  231. Use of this source code is governed by an MIT-style
  232. license that can be found in the LICENSE file or at
  233. https://opensource.org/licenses/MIT.
  234. */
  235. /**
  236. * RegExpRoute makes it easy to create a regular expression based
  237. * {@link workbox-routing.Route}.
  238. *
  239. * For same-origin requests the RegExp only needs to match part of the URL. For
  240. * requests against third-party servers, you must define a RegExp that matches
  241. * the start of the URL.
  242. *
  243. * @memberof workbox-routing
  244. * @extends workbox-routing.Route
  245. */
  246. class RegExpRoute extends Route {
  247. /**
  248. * If the regular expression contains
  249. * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},
  250. * the captured values will be passed to the
  251. * {@link workbox-routing~handlerCallback} `params`
  252. * argument.
  253. *
  254. * @param {RegExp} regExp The regular expression to match against URLs.
  255. * @param {workbox-routing~handlerCallback} handler A callback
  256. * function that returns a Promise resulting in a Response.
  257. * @param {string} [method='GET'] The HTTP method to match the Route
  258. * against.
  259. */
  260. constructor(regExp, handler, method) {
  261. {
  262. assert_js.assert.isInstance(regExp, RegExp, {
  263. moduleName: 'workbox-routing',
  264. className: 'RegExpRoute',
  265. funcName: 'constructor',
  266. paramName: 'pattern'
  267. });
  268. }
  269. const match = ({
  270. url
  271. }) => {
  272. const result = regExp.exec(url.href); // Return immediately if there's no match.
  273. if (!result) {
  274. return;
  275. } // Require that the match start at the first character in the URL string
  276. // if it's a cross-origin request.
  277. // See https://github.com/GoogleChrome/workbox/issues/281 for the context
  278. // behind this behavior.
  279. if (url.origin !== location.origin && result.index !== 0) {
  280. {
  281. logger_js.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.`);
  282. }
  283. return;
  284. } // If the route matches, but there aren't any capture groups defined, then
  285. // this will return [], which is truthy and therefore sufficient to
  286. // indicate a match.
  287. // If there are capture groups, then it will return their values.
  288. return result.slice(1);
  289. };
  290. super(match, handler, method);
  291. }
  292. }
  293. /*
  294. Copyright 2018 Google LLC
  295. Use of this source code is governed by an MIT-style
  296. license that can be found in the LICENSE file or at
  297. https://opensource.org/licenses/MIT.
  298. */
  299. /**
  300. * The Router can be used to process a `FetchEvent` using one or more
  301. * {@link workbox-routing.Route}, responding with a `Response` if
  302. * a matching route exists.
  303. *
  304. * If no route matches a given a request, the Router will use a "default"
  305. * handler if one is defined.
  306. *
  307. * Should the matching Route throw an error, the Router will use a "catch"
  308. * handler if one is defined to gracefully deal with issues and respond with a
  309. * Request.
  310. *
  311. * If a request matches multiple routes, the **earliest** registered route will
  312. * be used to respond to the request.
  313. *
  314. * @memberof workbox-routing
  315. */
  316. class Router {
  317. /**
  318. * Initializes a new Router.
  319. */
  320. constructor() {
  321. this._routes = new Map();
  322. this._defaultHandlerMap = new Map();
  323. }
  324. /**
  325. * @return {Map<string, Array<workbox-routing.Route>>} routes A `Map` of HTTP
  326. * method name ('GET', etc.) to an array of all the corresponding `Route`
  327. * instances that are registered.
  328. */
  329. get routes() {
  330. return this._routes;
  331. }
  332. /**
  333. * Adds a fetch event listener to respond to events when a route matches
  334. * the event's request.
  335. */
  336. addFetchListener() {
  337. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  338. self.addEventListener('fetch', event => {
  339. const {
  340. request
  341. } = event;
  342. const responsePromise = this.handleRequest({
  343. request,
  344. event
  345. });
  346. if (responsePromise) {
  347. event.respondWith(responsePromise);
  348. }
  349. });
  350. }
  351. /**
  352. * Adds a message event listener for URLs to cache from the window.
  353. * This is useful to cache resources loaded on the page prior to when the
  354. * service worker started controlling it.
  355. *
  356. * The format of the message data sent from the window should be as follows.
  357. * Where the `urlsToCache` array may consist of URL strings or an array of
  358. * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
  359. *
  360. * ```
  361. * {
  362. * type: 'CACHE_URLS',
  363. * payload: {
  364. * urlsToCache: [
  365. * './script1.js',
  366. * './script2.js',
  367. * ['./script3.js', {mode: 'no-cors'}],
  368. * ],
  369. * },
  370. * }
  371. * ```
  372. */
  373. addCacheListener() {
  374. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  375. self.addEventListener('message', event => {
  376. // event.data is type 'any'
  377. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  378. if (event.data && event.data.type === 'CACHE_URLS') {
  379. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  380. const {
  381. payload
  382. } = event.data;
  383. {
  384. logger_js.logger.debug(`Caching URLs from the window`, payload.urlsToCache);
  385. }
  386. const requestPromises = Promise.all(payload.urlsToCache.map(entry => {
  387. if (typeof entry === 'string') {
  388. entry = [entry];
  389. }
  390. const request = new Request(...entry);
  391. return this.handleRequest({
  392. request,
  393. event
  394. }); // TODO(philipwalton): TypeScript errors without this typecast for
  395. // some reason (probably a bug). The real type here should work but
  396. // doesn't: `Array<Promise<Response> | undefined>`.
  397. })); // TypeScript
  398. event.waitUntil(requestPromises); // If a MessageChannel was used, reply to the message on success.
  399. if (event.ports && event.ports[0]) {
  400. void requestPromises.then(() => event.ports[0].postMessage(true));
  401. }
  402. }
  403. });
  404. }
  405. /**
  406. * Apply the routing rules to a FetchEvent object to get a Response from an
  407. * appropriate Route's handler.
  408. *
  409. * @param {Object} options
  410. * @param {Request} options.request The request to handle.
  411. * @param {ExtendableEvent} options.event The event that triggered the
  412. * request.
  413. * @return {Promise<Response>|undefined} A promise is returned if a
  414. * registered route can handle the request. If there is no matching
  415. * route and there's no `defaultHandler`, `undefined` is returned.
  416. */
  417. handleRequest({
  418. request,
  419. event
  420. }) {
  421. {
  422. assert_js.assert.isInstance(request, Request, {
  423. moduleName: 'workbox-routing',
  424. className: 'Router',
  425. funcName: 'handleRequest',
  426. paramName: 'options.request'
  427. });
  428. }
  429. const url = new URL(request.url, location.href);
  430. if (!url.protocol.startsWith('http')) {
  431. {
  432. logger_js.logger.debug(`Workbox Router only supports URLs that start with 'http'.`);
  433. }
  434. return;
  435. }
  436. const sameOrigin = url.origin === location.origin;
  437. const {
  438. params,
  439. route
  440. } = this.findMatchingRoute({
  441. event,
  442. request,
  443. sameOrigin,
  444. url
  445. });
  446. let handler = route && route.handler;
  447. const debugMessages = [];
  448. {
  449. if (handler) {
  450. debugMessages.push([`Found a route to handle this request:`, route]);
  451. if (params) {
  452. debugMessages.push([`Passing the following params to the route's handler:`, params]);
  453. }
  454. }
  455. } // If we don't have a handler because there was no matching route, then
  456. // fall back to defaultHandler if that's defined.
  457. const method = request.method;
  458. if (!handler && this._defaultHandlerMap.has(method)) {
  459. {
  460. debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler for ${method}.`);
  461. }
  462. handler = this._defaultHandlerMap.get(method);
  463. }
  464. if (!handler) {
  465. {
  466. // No handler so Workbox will do nothing. If logs is set of debug
  467. // i.e. verbose, we should print out this information.
  468. logger_js.logger.debug(`No route found for: ${getFriendlyURL_js.getFriendlyURL(url)}`);
  469. }
  470. return;
  471. }
  472. {
  473. // We have a handler, meaning Workbox is going to handle the route.
  474. // print the routing details to the console.
  475. logger_js.logger.groupCollapsed(`Router is responding to: ${getFriendlyURL_js.getFriendlyURL(url)}`);
  476. debugMessages.forEach(msg => {
  477. if (Array.isArray(msg)) {
  478. logger_js.logger.log(...msg);
  479. } else {
  480. logger_js.logger.log(msg);
  481. }
  482. });
  483. logger_js.logger.groupEnd();
  484. } // Wrap in try and catch in case the handle method throws a synchronous
  485. // error. It should still callback to the catch handler.
  486. let responsePromise;
  487. try {
  488. responsePromise = handler.handle({
  489. url,
  490. request,
  491. event,
  492. params
  493. });
  494. } catch (err) {
  495. responsePromise = Promise.reject(err);
  496. } // Get route's catch handler, if it exists
  497. const catchHandler = route && route.catchHandler;
  498. if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
  499. responsePromise = responsePromise.catch(async err => {
  500. // If there's a route catch handler, process that first
  501. if (catchHandler) {
  502. {
  503. // Still include URL here as it will be async from the console group
  504. // and may not make sense without the URL
  505. logger_js.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL_js.getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
  506. logger_js.logger.error(`Error thrown by:`, route);
  507. logger_js.logger.error(err);
  508. logger_js.logger.groupEnd();
  509. }
  510. try {
  511. return await catchHandler.handle({
  512. url,
  513. request,
  514. event,
  515. params
  516. });
  517. } catch (catchErr) {
  518. if (catchErr instanceof Error) {
  519. err = catchErr;
  520. }
  521. }
  522. }
  523. if (this._catchHandler) {
  524. {
  525. // Still include URL here as it will be async from the console group
  526. // and may not make sense without the URL
  527. logger_js.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL_js.getFriendlyURL(url)}. Falling back to global Catch Handler.`);
  528. logger_js.logger.error(`Error thrown by:`, route);
  529. logger_js.logger.error(err);
  530. logger_js.logger.groupEnd();
  531. }
  532. return this._catchHandler.handle({
  533. url,
  534. request,
  535. event
  536. });
  537. }
  538. throw err;
  539. });
  540. }
  541. return responsePromise;
  542. }
  543. /**
  544. * Checks a request and URL (and optionally an event) against the list of
  545. * registered routes, and if there's a match, returns the corresponding
  546. * route along with any params generated by the match.
  547. *
  548. * @param {Object} options
  549. * @param {URL} options.url
  550. * @param {boolean} options.sameOrigin The result of comparing `url.origin`
  551. * against the current origin.
  552. * @param {Request} options.request The request to match.
  553. * @param {Event} options.event The corresponding event.
  554. * @return {Object} An object with `route` and `params` properties.
  555. * They are populated if a matching route was found or `undefined`
  556. * otherwise.
  557. */
  558. findMatchingRoute({
  559. url,
  560. sameOrigin,
  561. request,
  562. event
  563. }) {
  564. const routes = this._routes.get(request.method) || [];
  565. for (const route of routes) {
  566. let params; // route.match returns type any, not possible to change right now.
  567. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  568. const matchResult = route.match({
  569. url,
  570. sameOrigin,
  571. request,
  572. event
  573. });
  574. if (matchResult) {
  575. {
  576. // Warn developers that using an async matchCallback is almost always
  577. // not the right thing to do.
  578. if (matchResult instanceof Promise) {
  579. logger_js.logger.warn(`While routing ${getFriendlyURL_js.getFriendlyURL(url)}, an async ` + `matchCallback function was used. Please convert the ` + `following route to use a synchronous matchCallback function:`, route);
  580. }
  581. } // See https://github.com/GoogleChrome/workbox/issues/2079
  582. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  583. params = matchResult;
  584. if (Array.isArray(params) && params.length === 0) {
  585. // Instead of passing an empty array in as params, use undefined.
  586. params = undefined;
  587. } else if (matchResult.constructor === Object && // eslint-disable-line
  588. Object.keys(matchResult).length === 0) {
  589. // Instead of passing an empty object in as params, use undefined.
  590. params = undefined;
  591. } else if (typeof matchResult === 'boolean') {
  592. // For the boolean value true (rather than just something truth-y),
  593. // don't set params.
  594. // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
  595. params = undefined;
  596. } // Return early if have a match.
  597. return {
  598. route,
  599. params
  600. };
  601. }
  602. } // If no match was found above, return and empty object.
  603. return {};
  604. }
  605. /**
  606. * Define a default `handler` that's called when no routes explicitly
  607. * match the incoming request.
  608. *
  609. * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
  610. *
  611. * Without a default handler, unmatched requests will go against the
  612. * network as if there were no service worker present.
  613. *
  614. * @param {workbox-routing~handlerCallback} handler A callback
  615. * function that returns a Promise resulting in a Response.
  616. * @param {string} [method='GET'] The HTTP method to associate with this
  617. * default handler. Each method has its own default.
  618. */
  619. setDefaultHandler(handler, method = defaultMethod) {
  620. this._defaultHandlerMap.set(method, normalizeHandler(handler));
  621. }
  622. /**
  623. * If a Route throws an error while handling a request, this `handler`
  624. * will be called and given a chance to provide a response.
  625. *
  626. * @param {workbox-routing~handlerCallback} handler A callback
  627. * function that returns a Promise resulting in a Response.
  628. */
  629. setCatchHandler(handler) {
  630. this._catchHandler = normalizeHandler(handler);
  631. }
  632. /**
  633. * Registers a route with the router.
  634. *
  635. * @param {workbox-routing.Route} route The route to register.
  636. */
  637. registerRoute(route) {
  638. {
  639. assert_js.assert.isType(route, 'object', {
  640. moduleName: 'workbox-routing',
  641. className: 'Router',
  642. funcName: 'registerRoute',
  643. paramName: 'route'
  644. });
  645. assert_js.assert.hasMethod(route, 'match', {
  646. moduleName: 'workbox-routing',
  647. className: 'Router',
  648. funcName: 'registerRoute',
  649. paramName: 'route'
  650. });
  651. assert_js.assert.isType(route.handler, 'object', {
  652. moduleName: 'workbox-routing',
  653. className: 'Router',
  654. funcName: 'registerRoute',
  655. paramName: 'route'
  656. });
  657. assert_js.assert.hasMethod(route.handler, 'handle', {
  658. moduleName: 'workbox-routing',
  659. className: 'Router',
  660. funcName: 'registerRoute',
  661. paramName: 'route.handler'
  662. });
  663. assert_js.assert.isType(route.method, 'string', {
  664. moduleName: 'workbox-routing',
  665. className: 'Router',
  666. funcName: 'registerRoute',
  667. paramName: 'route.method'
  668. });
  669. }
  670. if (!this._routes.has(route.method)) {
  671. this._routes.set(route.method, []);
  672. } // Give precedence to all of the earlier routes by adding this additional
  673. // route to the end of the array.
  674. this._routes.get(route.method).push(route);
  675. }
  676. /**
  677. * Unregisters a route with the router.
  678. *
  679. * @param {workbox-routing.Route} route The route to unregister.
  680. */
  681. unregisterRoute(route) {
  682. if (!this._routes.has(route.method)) {
  683. throw new WorkboxError_js.WorkboxError('unregister-route-but-not-found-with-method', {
  684. method: route.method
  685. });
  686. }
  687. const routeIndex = this._routes.get(route.method).indexOf(route);
  688. if (routeIndex > -1) {
  689. this._routes.get(route.method).splice(routeIndex, 1);
  690. } else {
  691. throw new WorkboxError_js.WorkboxError('unregister-route-route-not-registered');
  692. }
  693. }
  694. }
  695. /*
  696. Copyright 2019 Google LLC
  697. Use of this source code is governed by an MIT-style
  698. license that can be found in the LICENSE file or at
  699. https://opensource.org/licenses/MIT.
  700. */
  701. let defaultRouter;
  702. /**
  703. * Creates a new, singleton Router instance if one does not exist. If one
  704. * does already exist, that instance is returned.
  705. *
  706. * @private
  707. * @return {Router}
  708. */
  709. const getOrCreateDefaultRouter = () => {
  710. if (!defaultRouter) {
  711. defaultRouter = new Router(); // The helpers that use the default Router assume these listeners exist.
  712. defaultRouter.addFetchListener();
  713. defaultRouter.addCacheListener();
  714. }
  715. return defaultRouter;
  716. };
  717. /*
  718. Copyright 2019 Google LLC
  719. Use of this source code is governed by an MIT-style
  720. license that can be found in the LICENSE file or at
  721. https://opensource.org/licenses/MIT.
  722. */
  723. /**
  724. * Easily register a RegExp, string, or function with a caching
  725. * strategy to a singleton Router instance.
  726. *
  727. * This method will generate a Route for you if needed and
  728. * call {@link workbox-routing.Router#registerRoute}.
  729. *
  730. * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture
  731. * If the capture param is a `Route`, all other arguments will be ignored.
  732. * @param {workbox-routing~handlerCallback} [handler] A callback
  733. * function that returns a Promise resulting in a Response. This parameter
  734. * is required if `capture` is not a `Route` object.
  735. * @param {string} [method='GET'] The HTTP method to match the Route
  736. * against.
  737. * @return {workbox-routing.Route} The generated `Route`.
  738. *
  739. * @memberof workbox-routing
  740. */
  741. function registerRoute(capture, handler, method) {
  742. let route;
  743. if (typeof capture === 'string') {
  744. const captureUrl = new URL(capture, location.href);
  745. {
  746. if (!(capture.startsWith('/') || capture.startsWith('http'))) {
  747. throw new WorkboxError_js.WorkboxError('invalid-string', {
  748. moduleName: 'workbox-routing',
  749. funcName: 'registerRoute',
  750. paramName: 'capture'
  751. });
  752. } // We want to check if Express-style wildcards are in the pathname only.
  753. // TODO: Remove this log message in v4.
  754. const valueToCheck = capture.startsWith('http') ? captureUrl.pathname : capture; // See https://github.com/pillarjs/path-to-regexp#parameters
  755. const wildcards = '[*:?+]';
  756. if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
  757. 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.`);
  758. }
  759. }
  760. const matchCallback = ({
  761. url
  762. }) => {
  763. {
  764. if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
  765. logger_js.logger.debug(`${capture} only partially matches the cross-origin URL ` + `${url.toString()}. This route will only handle cross-origin requests ` + `if they match the entire URL.`);
  766. }
  767. }
  768. return url.href === captureUrl.href;
  769. }; // If `capture` is a string then `handler` and `method` must be present.
  770. route = new Route(matchCallback, handler, method);
  771. } else if (capture instanceof RegExp) {
  772. // If `capture` is a `RegExp` then `handler` and `method` must be present.
  773. route = new RegExpRoute(capture, handler, method);
  774. } else if (typeof capture === 'function') {
  775. // If `capture` is a function then `handler` and `method` must be present.
  776. route = new Route(capture, handler, method);
  777. } else if (capture instanceof Route) {
  778. route = capture;
  779. } else {
  780. throw new WorkboxError_js.WorkboxError('unsupported-route-type', {
  781. moduleName: 'workbox-routing',
  782. funcName: 'registerRoute',
  783. paramName: 'capture'
  784. });
  785. }
  786. const defaultRouter = getOrCreateDefaultRouter();
  787. defaultRouter.registerRoute(route);
  788. return route;
  789. }
  790. /*
  791. Copyright 2019 Google LLC
  792. Use of this source code is governed by an MIT-style
  793. license that can be found in the LICENSE file or at
  794. https://opensource.org/licenses/MIT.
  795. */
  796. /**
  797. * If a Route throws an error while handling a request, this `handler`
  798. * will be called and given a chance to provide a response.
  799. *
  800. * @param {workbox-routing~handlerCallback} handler A callback
  801. * function that returns a Promise resulting in a Response.
  802. *
  803. * @memberof workbox-routing
  804. */
  805. function setCatchHandler(handler) {
  806. const defaultRouter = getOrCreateDefaultRouter();
  807. defaultRouter.setCatchHandler(handler);
  808. }
  809. /*
  810. Copyright 2019 Google LLC
  811. Use of this source code is governed by an MIT-style
  812. license that can be found in the LICENSE file or at
  813. https://opensource.org/licenses/MIT.
  814. */
  815. /**
  816. * Define a default `handler` that's called when no routes explicitly
  817. * match the incoming request.
  818. *
  819. * Without a default handler, unmatched requests will go against the
  820. * network as if there were no service worker present.
  821. *
  822. * @param {workbox-routing~handlerCallback} handler A callback
  823. * function that returns a Promise resulting in a Response.
  824. *
  825. * @memberof workbox-routing
  826. */
  827. function setDefaultHandler(handler) {
  828. const defaultRouter = getOrCreateDefaultRouter();
  829. defaultRouter.setDefaultHandler(handler);
  830. }
  831. exports.NavigationRoute = NavigationRoute;
  832. exports.RegExpRoute = RegExpRoute;
  833. exports.Route = Route;
  834. exports.Router = Router;
  835. exports.registerRoute = registerRoute;
  836. exports.setCatchHandler = setCatchHandler;
  837. exports.setDefaultHandler = setDefaultHandler;
  838. return exports;
  839. }({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private));
  840. //# sourceMappingURL=workbox-routing.dev.js.map