workbox-74d02f44.js 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744
  1. define(['exports'], (function (exports) { 'use strict';
  2. try {
  3. self['workbox:core:6.5.2'] && _();
  4. } catch (e) {}
  5. /*
  6. Copyright 2019 Google LLC
  7. Use of this source code is governed by an MIT-style
  8. license that can be found in the LICENSE file or at
  9. https://opensource.org/licenses/MIT.
  10. */
  11. const logger = (() => {
  12. // Don't overwrite this value if it's already set.
  13. // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
  14. if (!('__WB_DISABLE_DEV_LOGS' in self)) {
  15. self.__WB_DISABLE_DEV_LOGS = false;
  16. }
  17. let inGroup = false;
  18. const methodToColorMap = {
  19. debug: `#7f8c8d`,
  20. log: `#2ecc71`,
  21. warn: `#f39c12`,
  22. error: `#c0392b`,
  23. groupCollapsed: `#3498db`,
  24. groupEnd: null // No colored prefix on groupEnd
  25. };
  26. const print = function (method, args) {
  27. if (self.__WB_DISABLE_DEV_LOGS) {
  28. return;
  29. }
  30. if (method === 'groupCollapsed') {
  31. // Safari doesn't print all console.groupCollapsed() arguments:
  32. // https://bugs.webkit.org/show_bug.cgi?id=182754
  33. if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
  34. console[method](...args);
  35. return;
  36. }
  37. }
  38. const styles = [`background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em`]; // When in a group, the workbox prefix is not displayed.
  39. const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
  40. console[method](...logPrefix, ...args);
  41. if (method === 'groupCollapsed') {
  42. inGroup = true;
  43. }
  44. if (method === 'groupEnd') {
  45. inGroup = false;
  46. }
  47. }; // eslint-disable-next-line @typescript-eslint/ban-types
  48. const api = {};
  49. const loggerMethods = Object.keys(methodToColorMap);
  50. for (const key of loggerMethods) {
  51. const method = key;
  52. api[method] = (...args) => {
  53. print(method, args);
  54. };
  55. }
  56. return api;
  57. })();
  58. /*
  59. Copyright 2018 Google LLC
  60. Use of this source code is governed by an MIT-style
  61. license that can be found in the LICENSE file or at
  62. https://opensource.org/licenses/MIT.
  63. */
  64. const messages$1 = {
  65. 'invalid-value': ({
  66. paramName,
  67. validValueDescription,
  68. value
  69. }) => {
  70. if (!paramName || !validValueDescription) {
  71. throw new Error(`Unexpected input to 'invalid-value' error.`);
  72. }
  73. return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
  74. },
  75. 'not-an-array': ({
  76. moduleName,
  77. className,
  78. funcName,
  79. paramName
  80. }) => {
  81. if (!moduleName || !className || !funcName || !paramName) {
  82. throw new Error(`Unexpected input to 'not-an-array' error.`);
  83. }
  84. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
  85. },
  86. 'incorrect-type': ({
  87. expectedType,
  88. paramName,
  89. moduleName,
  90. className,
  91. funcName
  92. }) => {
  93. if (!expectedType || !paramName || !moduleName || !funcName) {
  94. throw new Error(`Unexpected input to 'incorrect-type' error.`);
  95. }
  96. const classNameStr = className ? `${className}.` : '';
  97. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`;
  98. },
  99. 'incorrect-class': ({
  100. expectedClassName,
  101. paramName,
  102. moduleName,
  103. className,
  104. funcName,
  105. isReturnValueProblem
  106. }) => {
  107. if (!expectedClassName || !moduleName || !funcName) {
  108. throw new Error(`Unexpected input to 'incorrect-class' error.`);
  109. }
  110. const classNameStr = className ? `${className}.` : '';
  111. if (isReturnValueProblem) {
  112. return `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
  113. }
  114. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
  115. },
  116. 'missing-a-method': ({
  117. expectedMethod,
  118. paramName,
  119. moduleName,
  120. className,
  121. funcName
  122. }) => {
  123. if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
  124. throw new Error(`Unexpected input to 'missing-a-method' error.`);
  125. }
  126. return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
  127. },
  128. 'add-to-cache-list-unexpected-type': ({
  129. entry
  130. }) => {
  131. return `An unexpected entry was passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` + `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` + `strings with one or more characters, objects with a url property or ` + `Request objects.`;
  132. },
  133. 'add-to-cache-list-conflicting-entries': ({
  134. firstEntry,
  135. secondEntry
  136. }) => {
  137. if (!firstEntry || !secondEntry) {
  138. throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
  139. }
  140. return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${firstEntry} but different revision details. Workbox is ` + `unable to cache and version the asset correctly. Please remove one ` + `of the entries.`;
  141. },
  142. 'plugin-error-request-will-fetch': ({
  143. thrownErrorMessage
  144. }) => {
  145. if (!thrownErrorMessage) {
  146. throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
  147. }
  148. return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownErrorMessage}'.`;
  149. },
  150. 'invalid-cache-name': ({
  151. cacheNameId,
  152. value
  153. }) => {
  154. if (!cacheNameId) {
  155. throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
  156. }
  157. return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`;
  158. },
  159. 'unregister-route-but-not-found-with-method': ({
  160. method
  161. }) => {
  162. if (!method) {
  163. throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`);
  164. }
  165. return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`;
  166. },
  167. 'unregister-route-route-not-registered': () => {
  168. return `The route you're trying to unregister was not previously ` + `registered.`;
  169. },
  170. 'queue-replay-failed': ({
  171. name
  172. }) => {
  173. return `Replaying the background sync queue '${name}' failed.`;
  174. },
  175. 'duplicate-queue-name': ({
  176. name
  177. }) => {
  178. return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`;
  179. },
  180. 'expired-test-without-max-age': ({
  181. methodName,
  182. paramName
  183. }) => {
  184. return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
  185. },
  186. 'unsupported-route-type': ({
  187. moduleName,
  188. className,
  189. funcName,
  190. paramName
  191. }) => {
  192. return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`;
  193. },
  194. 'not-array-of-class': ({
  195. value,
  196. expectedClass,
  197. moduleName,
  198. className,
  199. funcName,
  200. paramName
  201. }) => {
  202. return `The supplied '${paramName}' parameter must be an array of ` + `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` + `Please check the call to ${moduleName}.${className}.${funcName}() ` + `to fix the issue.`;
  203. },
  204. 'max-entries-or-age-required': ({
  205. moduleName,
  206. className,
  207. funcName
  208. }) => {
  209. return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`;
  210. },
  211. 'statuses-or-headers-required': ({
  212. moduleName,
  213. className,
  214. funcName
  215. }) => {
  216. return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`;
  217. },
  218. 'invalid-string': ({
  219. moduleName,
  220. funcName,
  221. paramName
  222. }) => {
  223. if (!paramName || !moduleName || !funcName) {
  224. throw new Error(`Unexpected input to 'invalid-string' error.`);
  225. }
  226. return `When using strings, the '${paramName}' parameter must start with ` + `'http' (for cross-origin matches) or '/' (for same-origin matches). ` + `Please see the docs for ${moduleName}.${funcName}() for ` + `more info.`;
  227. },
  228. 'channel-name-required': () => {
  229. return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`;
  230. },
  231. 'invalid-responses-are-same-args': () => {
  232. return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`;
  233. },
  234. 'expire-custom-caches-only': () => {
  235. return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`;
  236. },
  237. 'unit-must-be-bytes': ({
  238. normalizedRangeHeader
  239. }) => {
  240. if (!normalizedRangeHeader) {
  241. throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
  242. }
  243. return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`;
  244. },
  245. 'single-range-only': ({
  246. normalizedRangeHeader
  247. }) => {
  248. if (!normalizedRangeHeader) {
  249. throw new Error(`Unexpected input to 'single-range-only' error.`);
  250. }
  251. return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`;
  252. },
  253. 'invalid-range-values': ({
  254. normalizedRangeHeader
  255. }) => {
  256. if (!normalizedRangeHeader) {
  257. throw new Error(`Unexpected input to 'invalid-range-values' error.`);
  258. }
  259. return `The Range header is missing both start and end values. At least ` + `one of those values is needed. The Range header provided was ` + `"${normalizedRangeHeader}"`;
  260. },
  261. 'no-range-header': () => {
  262. return `No Range header was found in the Request provided.`;
  263. },
  264. 'range-not-satisfiable': ({
  265. size,
  266. start,
  267. end
  268. }) => {
  269. return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
  270. },
  271. 'attempt-to-cache-non-get-request': ({
  272. url,
  273. method
  274. }) => {
  275. return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`;
  276. },
  277. 'cache-put-with-no-response': ({
  278. url
  279. }) => {
  280. return `There was an attempt to cache '${url}' but the response was not ` + `defined.`;
  281. },
  282. 'no-response': ({
  283. url,
  284. error
  285. }) => {
  286. let message = `The strategy could not generate a response for '${url}'.`;
  287. if (error) {
  288. message += ` The underlying error is ${error}.`;
  289. }
  290. return message;
  291. },
  292. 'bad-precaching-response': ({
  293. url,
  294. status
  295. }) => {
  296. return `The precaching request for '${url}' failed` + (status ? ` with an HTTP status of ${status}.` : `.`);
  297. },
  298. 'non-precached-url': ({
  299. url
  300. }) => {
  301. return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`;
  302. },
  303. 'add-to-cache-list-conflicting-integrities': ({
  304. url
  305. }) => {
  306. return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`;
  307. },
  308. 'missing-precache-entry': ({
  309. cacheName,
  310. url
  311. }) => {
  312. return `Unable to find a precached response in ${cacheName} for ${url}.`;
  313. },
  314. 'cross-origin-copy-response': ({
  315. origin
  316. }) => {
  317. return `workbox-core.copyResponse() can only be used with same-origin ` + `responses. It was passed a response with origin ${origin}.`;
  318. },
  319. 'opaque-streams-source': ({
  320. type
  321. }) => {
  322. const message = `One of the workbox-streams sources resulted in an ` + `'${type}' response.`;
  323. if (type === 'opaqueredirect') {
  324. return `${message} Please do not use a navigation request that results ` + `in a redirect as a source.`;
  325. }
  326. return `${message} Please ensure your sources are CORS-enabled.`;
  327. }
  328. };
  329. /*
  330. Copyright 2018 Google LLC
  331. Use of this source code is governed by an MIT-style
  332. license that can be found in the LICENSE file or at
  333. https://opensource.org/licenses/MIT.
  334. */
  335. const generatorFunction = (code, details = {}) => {
  336. const message = messages$1[code];
  337. if (!message) {
  338. throw new Error(`Unable to find message for code '${code}'.`);
  339. }
  340. return message(details);
  341. };
  342. const messageGenerator = generatorFunction;
  343. /*
  344. Copyright 2018 Google LLC
  345. Use of this source code is governed by an MIT-style
  346. license that can be found in the LICENSE file or at
  347. https://opensource.org/licenses/MIT.
  348. */
  349. /**
  350. * Workbox errors should be thrown with this class.
  351. * This allows use to ensure the type easily in tests,
  352. * helps developers identify errors from workbox
  353. * easily and allows use to optimise error
  354. * messages correctly.
  355. *
  356. * @private
  357. */
  358. class WorkboxError extends Error {
  359. /**
  360. *
  361. * @param {string} errorCode The error code that
  362. * identifies this particular error.
  363. * @param {Object=} details Any relevant arguments
  364. * that will help developers identify issues should
  365. * be added as a key on the context object.
  366. */
  367. constructor(errorCode, details) {
  368. const message = messageGenerator(errorCode, details);
  369. super(message);
  370. this.name = errorCode;
  371. this.details = details;
  372. }
  373. }
  374. /*
  375. Copyright 2018 Google LLC
  376. Use of this source code is governed by an MIT-style
  377. license that can be found in the LICENSE file or at
  378. https://opensource.org/licenses/MIT.
  379. */
  380. /*
  381. * This method throws if the supplied value is not an array.
  382. * The destructed values are required to produce a meaningful error for users.
  383. * The destructed and restructured object is so it's clear what is
  384. * needed.
  385. */
  386. const isArray = (value, details) => {
  387. if (!Array.isArray(value)) {
  388. throw new WorkboxError('not-an-array', details);
  389. }
  390. };
  391. const hasMethod = (object, expectedMethod, details) => {
  392. const type = typeof object[expectedMethod];
  393. if (type !== 'function') {
  394. details['expectedMethod'] = expectedMethod;
  395. throw new WorkboxError('missing-a-method', details);
  396. }
  397. };
  398. const isType = (object, expectedType, details) => {
  399. if (typeof object !== expectedType) {
  400. details['expectedType'] = expectedType;
  401. throw new WorkboxError('incorrect-type', details);
  402. }
  403. };
  404. const isInstance = (object, // Need the general type to do the check later.
  405. // eslint-disable-next-line @typescript-eslint/ban-types
  406. expectedClass, details) => {
  407. if (!(object instanceof expectedClass)) {
  408. details['expectedClassName'] = expectedClass.name;
  409. throw new WorkboxError('incorrect-class', details);
  410. }
  411. };
  412. const isOneOf = (value, validValues, details) => {
  413. if (!validValues.includes(value)) {
  414. details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`;
  415. throw new WorkboxError('invalid-value', details);
  416. }
  417. };
  418. const isArrayOfClass = (value, // Need general type to do check later.
  419. expectedClass, // eslint-disable-line
  420. details) => {
  421. const error = new WorkboxError('not-array-of-class', details);
  422. if (!Array.isArray(value)) {
  423. throw error;
  424. }
  425. for (const item of value) {
  426. if (!(item instanceof expectedClass)) {
  427. throw error;
  428. }
  429. }
  430. };
  431. const finalAssertExports = {
  432. hasMethod,
  433. isArray,
  434. isInstance,
  435. isOneOf,
  436. isType,
  437. isArrayOfClass
  438. };
  439. try {
  440. self['workbox:routing:6.5.2'] && _();
  441. } catch (e) {}
  442. /*
  443. Copyright 2018 Google LLC
  444. Use of this source code is governed by an MIT-style
  445. license that can be found in the LICENSE file or at
  446. https://opensource.org/licenses/MIT.
  447. */
  448. /**
  449. * The default HTTP method, 'GET', used when there's no specific method
  450. * configured for a route.
  451. *
  452. * @type {string}
  453. *
  454. * @private
  455. */
  456. const defaultMethod = 'GET';
  457. /**
  458. * The list of valid HTTP methods associated with requests that could be routed.
  459. *
  460. * @type {Array<string>}
  461. *
  462. * @private
  463. */
  464. const validMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT'];
  465. /*
  466. Copyright 2018 Google LLC
  467. Use of this source code is governed by an MIT-style
  468. license that can be found in the LICENSE file or at
  469. https://opensource.org/licenses/MIT.
  470. */
  471. /**
  472. * @param {function()|Object} handler Either a function, or an object with a
  473. * 'handle' method.
  474. * @return {Object} An object with a handle method.
  475. *
  476. * @private
  477. */
  478. const normalizeHandler = handler => {
  479. if (handler && typeof handler === 'object') {
  480. {
  481. finalAssertExports.hasMethod(handler, 'handle', {
  482. moduleName: 'workbox-routing',
  483. className: 'Route',
  484. funcName: 'constructor',
  485. paramName: 'handler'
  486. });
  487. }
  488. return handler;
  489. } else {
  490. {
  491. finalAssertExports.isType(handler, 'function', {
  492. moduleName: 'workbox-routing',
  493. className: 'Route',
  494. funcName: 'constructor',
  495. paramName: 'handler'
  496. });
  497. }
  498. return {
  499. handle: handler
  500. };
  501. }
  502. };
  503. /*
  504. Copyright 2018 Google LLC
  505. Use of this source code is governed by an MIT-style
  506. license that can be found in the LICENSE file or at
  507. https://opensource.org/licenses/MIT.
  508. */
  509. /**
  510. * A `Route` consists of a pair of callback functions, "match" and "handler".
  511. * The "match" callback determine if a route should be used to "handle" a
  512. * request by returning a non-falsy value if it can. The "handler" callback
  513. * is called when there is a match and should return a Promise that resolves
  514. * to a `Response`.
  515. *
  516. * @memberof workbox-routing
  517. */
  518. class Route {
  519. /**
  520. * Constructor for Route class.
  521. *
  522. * @param {workbox-routing~matchCallback} match
  523. * A callback function that determines whether the route matches a given
  524. * `fetch` event by returning a non-falsy value.
  525. * @param {workbox-routing~handlerCallback} handler A callback
  526. * function that returns a Promise resolving to a Response.
  527. * @param {string} [method='GET'] The HTTP method to match the Route
  528. * against.
  529. */
  530. constructor(match, handler, method = defaultMethod) {
  531. {
  532. finalAssertExports.isType(match, 'function', {
  533. moduleName: 'workbox-routing',
  534. className: 'Route',
  535. funcName: 'constructor',
  536. paramName: 'match'
  537. });
  538. if (method) {
  539. finalAssertExports.isOneOf(method, validMethods, {
  540. paramName: 'method'
  541. });
  542. }
  543. } // These values are referenced directly by Router so cannot be
  544. // altered by minificaton.
  545. this.handler = normalizeHandler(handler);
  546. this.match = match;
  547. this.method = method;
  548. }
  549. /**
  550. *
  551. * @param {workbox-routing-handlerCallback} handler A callback
  552. * function that returns a Promise resolving to a Response
  553. */
  554. setCatchHandler(handler) {
  555. this.catchHandler = normalizeHandler(handler);
  556. }
  557. }
  558. /*
  559. Copyright 2018 Google LLC
  560. Use of this source code is governed by an MIT-style
  561. license that can be found in the LICENSE file or at
  562. https://opensource.org/licenses/MIT.
  563. */
  564. /**
  565. * RegExpRoute makes it easy to create a regular expression based
  566. * {@link workbox-routing.Route}.
  567. *
  568. * For same-origin requests the RegExp only needs to match part of the URL. For
  569. * requests against third-party servers, you must define a RegExp that matches
  570. * the start of the URL.
  571. *
  572. * @memberof workbox-routing
  573. * @extends workbox-routing.Route
  574. */
  575. class RegExpRoute extends Route {
  576. /**
  577. * If the regular expression contains
  578. * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},
  579. * the captured values will be passed to the
  580. * {@link workbox-routing~handlerCallback} `params`
  581. * argument.
  582. *
  583. * @param {RegExp} regExp The regular expression to match against URLs.
  584. * @param {workbox-routing~handlerCallback} handler A callback
  585. * function that returns a Promise resulting in a Response.
  586. * @param {string} [method='GET'] The HTTP method to match the Route
  587. * against.
  588. */
  589. constructor(regExp, handler, method) {
  590. {
  591. finalAssertExports.isInstance(regExp, RegExp, {
  592. moduleName: 'workbox-routing',
  593. className: 'RegExpRoute',
  594. funcName: 'constructor',
  595. paramName: 'pattern'
  596. });
  597. }
  598. const match = ({
  599. url
  600. }) => {
  601. const result = regExp.exec(url.href); // Return immediately if there's no match.
  602. if (!result) {
  603. return;
  604. } // Require that the match start at the first character in the URL string
  605. // if it's a cross-origin request.
  606. // See https://github.com/GoogleChrome/workbox/issues/281 for the context
  607. // behind this behavior.
  608. if (url.origin !== location.origin && result.index !== 0) {
  609. {
  610. 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.`);
  611. }
  612. return;
  613. } // If the route matches, but there aren't any capture groups defined, then
  614. // this will return [], which is truthy and therefore sufficient to
  615. // indicate a match.
  616. // If there are capture groups, then it will return their values.
  617. return result.slice(1);
  618. };
  619. super(match, handler, method);
  620. }
  621. }
  622. /*
  623. Copyright 2018 Google LLC
  624. Use of this source code is governed by an MIT-style
  625. license that can be found in the LICENSE file or at
  626. https://opensource.org/licenses/MIT.
  627. */
  628. const getFriendlyURL = url => {
  629. const urlObj = new URL(String(url), location.href); // See https://github.com/GoogleChrome/workbox/issues/2323
  630. // We want to include everything, except for the origin if it's same-origin.
  631. return urlObj.href.replace(new RegExp(`^${location.origin}`), '');
  632. };
  633. /*
  634. Copyright 2018 Google LLC
  635. Use of this source code is governed by an MIT-style
  636. license that can be found in the LICENSE file or at
  637. https://opensource.org/licenses/MIT.
  638. */
  639. /**
  640. * The Router can be used to process a `FetchEvent` using one or more
  641. * {@link workbox-routing.Route}, responding with a `Response` if
  642. * a matching route exists.
  643. *
  644. * If no route matches a given a request, the Router will use a "default"
  645. * handler if one is defined.
  646. *
  647. * Should the matching Route throw an error, the Router will use a "catch"
  648. * handler if one is defined to gracefully deal with issues and respond with a
  649. * Request.
  650. *
  651. * If a request matches multiple routes, the **earliest** registered route will
  652. * be used to respond to the request.
  653. *
  654. * @memberof workbox-routing
  655. */
  656. class Router {
  657. /**
  658. * Initializes a new Router.
  659. */
  660. constructor() {
  661. this._routes = new Map();
  662. this._defaultHandlerMap = new Map();
  663. }
  664. /**
  665. * @return {Map<string, Array<workbox-routing.Route>>} routes A `Map` of HTTP
  666. * method name ('GET', etc.) to an array of all the corresponding `Route`
  667. * instances that are registered.
  668. */
  669. get routes() {
  670. return this._routes;
  671. }
  672. /**
  673. * Adds a fetch event listener to respond to events when a route matches
  674. * the event's request.
  675. */
  676. addFetchListener() {
  677. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  678. self.addEventListener('fetch', event => {
  679. const {
  680. request
  681. } = event;
  682. const responsePromise = this.handleRequest({
  683. request,
  684. event
  685. });
  686. if (responsePromise) {
  687. event.respondWith(responsePromise);
  688. }
  689. });
  690. }
  691. /**
  692. * Adds a message event listener for URLs to cache from the window.
  693. * This is useful to cache resources loaded on the page prior to when the
  694. * service worker started controlling it.
  695. *
  696. * The format of the message data sent from the window should be as follows.
  697. * Where the `urlsToCache` array may consist of URL strings or an array of
  698. * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
  699. *
  700. * ```
  701. * {
  702. * type: 'CACHE_URLS',
  703. * payload: {
  704. * urlsToCache: [
  705. * './script1.js',
  706. * './script2.js',
  707. * ['./script3.js', {mode: 'no-cors'}],
  708. * ],
  709. * },
  710. * }
  711. * ```
  712. */
  713. addCacheListener() {
  714. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  715. self.addEventListener('message', event => {
  716. // event.data is type 'any'
  717. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  718. if (event.data && event.data.type === 'CACHE_URLS') {
  719. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  720. const {
  721. payload
  722. } = event.data;
  723. {
  724. logger.debug(`Caching URLs from the window`, payload.urlsToCache);
  725. }
  726. const requestPromises = Promise.all(payload.urlsToCache.map(entry => {
  727. if (typeof entry === 'string') {
  728. entry = [entry];
  729. }
  730. const request = new Request(...entry);
  731. return this.handleRequest({
  732. request,
  733. event
  734. }); // TODO(philipwalton): TypeScript errors without this typecast for
  735. // some reason (probably a bug). The real type here should work but
  736. // doesn't: `Array<Promise<Response> | undefined>`.
  737. })); // TypeScript
  738. event.waitUntil(requestPromises); // If a MessageChannel was used, reply to the message on success.
  739. if (event.ports && event.ports[0]) {
  740. void requestPromises.then(() => event.ports[0].postMessage(true));
  741. }
  742. }
  743. });
  744. }
  745. /**
  746. * Apply the routing rules to a FetchEvent object to get a Response from an
  747. * appropriate Route's handler.
  748. *
  749. * @param {Object} options
  750. * @param {Request} options.request The request to handle.
  751. * @param {ExtendableEvent} options.event The event that triggered the
  752. * request.
  753. * @return {Promise<Response>|undefined} A promise is returned if a
  754. * registered route can handle the request. If there is no matching
  755. * route and there's no `defaultHandler`, `undefined` is returned.
  756. */
  757. handleRequest({
  758. request,
  759. event
  760. }) {
  761. {
  762. finalAssertExports.isInstance(request, Request, {
  763. moduleName: 'workbox-routing',
  764. className: 'Router',
  765. funcName: 'handleRequest',
  766. paramName: 'options.request'
  767. });
  768. }
  769. const url = new URL(request.url, location.href);
  770. if (!url.protocol.startsWith('http')) {
  771. {
  772. logger.debug(`Workbox Router only supports URLs that start with 'http'.`);
  773. }
  774. return;
  775. }
  776. const sameOrigin = url.origin === location.origin;
  777. const {
  778. params,
  779. route
  780. } = this.findMatchingRoute({
  781. event,
  782. request,
  783. sameOrigin,
  784. url
  785. });
  786. let handler = route && route.handler;
  787. const debugMessages = [];
  788. {
  789. if (handler) {
  790. debugMessages.push([`Found a route to handle this request:`, route]);
  791. if (params) {
  792. debugMessages.push([`Passing the following params to the route's handler:`, params]);
  793. }
  794. }
  795. } // If we don't have a handler because there was no matching route, then
  796. // fall back to defaultHandler if that's defined.
  797. const method = request.method;
  798. if (!handler && this._defaultHandlerMap.has(method)) {
  799. {
  800. debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler for ${method}.`);
  801. }
  802. handler = this._defaultHandlerMap.get(method);
  803. }
  804. if (!handler) {
  805. {
  806. // No handler so Workbox will do nothing. If logs is set of debug
  807. // i.e. verbose, we should print out this information.
  808. logger.debug(`No route found for: ${getFriendlyURL(url)}`);
  809. }
  810. return;
  811. }
  812. {
  813. // We have a handler, meaning Workbox is going to handle the route.
  814. // print the routing details to the console.
  815. logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
  816. debugMessages.forEach(msg => {
  817. if (Array.isArray(msg)) {
  818. logger.log(...msg);
  819. } else {
  820. logger.log(msg);
  821. }
  822. });
  823. logger.groupEnd();
  824. } // Wrap in try and catch in case the handle method throws a synchronous
  825. // error. It should still callback to the catch handler.
  826. let responsePromise;
  827. try {
  828. responsePromise = handler.handle({
  829. url,
  830. request,
  831. event,
  832. params
  833. });
  834. } catch (err) {
  835. responsePromise = Promise.reject(err);
  836. } // Get route's catch handler, if it exists
  837. const catchHandler = route && route.catchHandler;
  838. if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
  839. responsePromise = responsePromise.catch(async err => {
  840. // If there's a route catch handler, process that first
  841. if (catchHandler) {
  842. {
  843. // Still include URL here as it will be async from the console group
  844. // and may not make sense without the URL
  845. logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
  846. logger.error(`Error thrown by:`, route);
  847. logger.error(err);
  848. logger.groupEnd();
  849. }
  850. try {
  851. return await catchHandler.handle({
  852. url,
  853. request,
  854. event,
  855. params
  856. });
  857. } catch (catchErr) {
  858. if (catchErr instanceof Error) {
  859. err = catchErr;
  860. }
  861. }
  862. }
  863. if (this._catchHandler) {
  864. {
  865. // Still include URL here as it will be async from the console group
  866. // and may not make sense without the URL
  867. logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
  868. logger.error(`Error thrown by:`, route);
  869. logger.error(err);
  870. logger.groupEnd();
  871. }
  872. return this._catchHandler.handle({
  873. url,
  874. request,
  875. event
  876. });
  877. }
  878. throw err;
  879. });
  880. }
  881. return responsePromise;
  882. }
  883. /**
  884. * Checks a request and URL (and optionally an event) against the list of
  885. * registered routes, and if there's a match, returns the corresponding
  886. * route along with any params generated by the match.
  887. *
  888. * @param {Object} options
  889. * @param {URL} options.url
  890. * @param {boolean} options.sameOrigin The result of comparing `url.origin`
  891. * against the current origin.
  892. * @param {Request} options.request The request to match.
  893. * @param {Event} options.event The corresponding event.
  894. * @return {Object} An object with `route` and `params` properties.
  895. * They are populated if a matching route was found or `undefined`
  896. * otherwise.
  897. */
  898. findMatchingRoute({
  899. url,
  900. sameOrigin,
  901. request,
  902. event
  903. }) {
  904. const routes = this._routes.get(request.method) || [];
  905. for (const route of routes) {
  906. let params; // route.match returns type any, not possible to change right now.
  907. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  908. const matchResult = route.match({
  909. url,
  910. sameOrigin,
  911. request,
  912. event
  913. });
  914. if (matchResult) {
  915. {
  916. // Warn developers that using an async matchCallback is almost always
  917. // not the right thing to do.
  918. if (matchResult instanceof Promise) {
  919. logger.warn(`While routing ${getFriendlyURL(url)}, an async ` + `matchCallback function was used. Please convert the ` + `following route to use a synchronous matchCallback function:`, route);
  920. }
  921. } // See https://github.com/GoogleChrome/workbox/issues/2079
  922. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  923. params = matchResult;
  924. if (Array.isArray(params) && params.length === 0) {
  925. // Instead of passing an empty array in as params, use undefined.
  926. params = undefined;
  927. } else if (matchResult.constructor === Object && // eslint-disable-line
  928. Object.keys(matchResult).length === 0) {
  929. // Instead of passing an empty object in as params, use undefined.
  930. params = undefined;
  931. } else if (typeof matchResult === 'boolean') {
  932. // For the boolean value true (rather than just something truth-y),
  933. // don't set params.
  934. // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
  935. params = undefined;
  936. } // Return early if have a match.
  937. return {
  938. route,
  939. params
  940. };
  941. }
  942. } // If no match was found above, return and empty object.
  943. return {};
  944. }
  945. /**
  946. * Define a default `handler` that's called when no routes explicitly
  947. * match the incoming request.
  948. *
  949. * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
  950. *
  951. * Without a default handler, unmatched requests will go against the
  952. * network as if there were no service worker present.
  953. *
  954. * @param {workbox-routing~handlerCallback} handler A callback
  955. * function that returns a Promise resulting in a Response.
  956. * @param {string} [method='GET'] The HTTP method to associate with this
  957. * default handler. Each method has its own default.
  958. */
  959. setDefaultHandler(handler, method = defaultMethod) {
  960. this._defaultHandlerMap.set(method, normalizeHandler(handler));
  961. }
  962. /**
  963. * If a Route throws an error while handling a request, this `handler`
  964. * will be called and given a chance to provide a response.
  965. *
  966. * @param {workbox-routing~handlerCallback} handler A callback
  967. * function that returns a Promise resulting in a Response.
  968. */
  969. setCatchHandler(handler) {
  970. this._catchHandler = normalizeHandler(handler);
  971. }
  972. /**
  973. * Registers a route with the router.
  974. *
  975. * @param {workbox-routing.Route} route The route to register.
  976. */
  977. registerRoute(route) {
  978. {
  979. finalAssertExports.isType(route, 'object', {
  980. moduleName: 'workbox-routing',
  981. className: 'Router',
  982. funcName: 'registerRoute',
  983. paramName: 'route'
  984. });
  985. finalAssertExports.hasMethod(route, 'match', {
  986. moduleName: 'workbox-routing',
  987. className: 'Router',
  988. funcName: 'registerRoute',
  989. paramName: 'route'
  990. });
  991. finalAssertExports.isType(route.handler, 'object', {
  992. moduleName: 'workbox-routing',
  993. className: 'Router',
  994. funcName: 'registerRoute',
  995. paramName: 'route'
  996. });
  997. finalAssertExports.hasMethod(route.handler, 'handle', {
  998. moduleName: 'workbox-routing',
  999. className: 'Router',
  1000. funcName: 'registerRoute',
  1001. paramName: 'route.handler'
  1002. });
  1003. finalAssertExports.isType(route.method, 'string', {
  1004. moduleName: 'workbox-routing',
  1005. className: 'Router',
  1006. funcName: 'registerRoute',
  1007. paramName: 'route.method'
  1008. });
  1009. }
  1010. if (!this._routes.has(route.method)) {
  1011. this._routes.set(route.method, []);
  1012. } // Give precedence to all of the earlier routes by adding this additional
  1013. // route to the end of the array.
  1014. this._routes.get(route.method).push(route);
  1015. }
  1016. /**
  1017. * Unregisters a route with the router.
  1018. *
  1019. * @param {workbox-routing.Route} route The route to unregister.
  1020. */
  1021. unregisterRoute(route) {
  1022. if (!this._routes.has(route.method)) {
  1023. throw new WorkboxError('unregister-route-but-not-found-with-method', {
  1024. method: route.method
  1025. });
  1026. }
  1027. const routeIndex = this._routes.get(route.method).indexOf(route);
  1028. if (routeIndex > -1) {
  1029. this._routes.get(route.method).splice(routeIndex, 1);
  1030. } else {
  1031. throw new WorkboxError('unregister-route-route-not-registered');
  1032. }
  1033. }
  1034. }
  1035. /*
  1036. Copyright 2019 Google LLC
  1037. Use of this source code is governed by an MIT-style
  1038. license that can be found in the LICENSE file or at
  1039. https://opensource.org/licenses/MIT.
  1040. */
  1041. let defaultRouter;
  1042. /**
  1043. * Creates a new, singleton Router instance if one does not exist. If one
  1044. * does already exist, that instance is returned.
  1045. *
  1046. * @private
  1047. * @return {Router}
  1048. */
  1049. const getOrCreateDefaultRouter = () => {
  1050. if (!defaultRouter) {
  1051. defaultRouter = new Router(); // The helpers that use the default Router assume these listeners exist.
  1052. defaultRouter.addFetchListener();
  1053. defaultRouter.addCacheListener();
  1054. }
  1055. return defaultRouter;
  1056. };
  1057. /*
  1058. Copyright 2019 Google LLC
  1059. Use of this source code is governed by an MIT-style
  1060. license that can be found in the LICENSE file or at
  1061. https://opensource.org/licenses/MIT.
  1062. */
  1063. /**
  1064. * Easily register a RegExp, string, or function with a caching
  1065. * strategy to a singleton Router instance.
  1066. *
  1067. * This method will generate a Route for you if needed and
  1068. * call {@link workbox-routing.Router#registerRoute}.
  1069. *
  1070. * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture
  1071. * If the capture param is a `Route`, all other arguments will be ignored.
  1072. * @param {workbox-routing~handlerCallback} [handler] A callback
  1073. * function that returns a Promise resulting in a Response. This parameter
  1074. * is required if `capture` is not a `Route` object.
  1075. * @param {string} [method='GET'] The HTTP method to match the Route
  1076. * against.
  1077. * @return {workbox-routing.Route} The generated `Route`.
  1078. *
  1079. * @memberof workbox-routing
  1080. */
  1081. function registerRoute(capture, handler, method) {
  1082. let route;
  1083. if (typeof capture === 'string') {
  1084. const captureUrl = new URL(capture, location.href);
  1085. {
  1086. if (!(capture.startsWith('/') || capture.startsWith('http'))) {
  1087. throw new WorkboxError('invalid-string', {
  1088. moduleName: 'workbox-routing',
  1089. funcName: 'registerRoute',
  1090. paramName: 'capture'
  1091. });
  1092. } // We want to check if Express-style wildcards are in the pathname only.
  1093. // TODO: Remove this log message in v4.
  1094. const valueToCheck = capture.startsWith('http') ? captureUrl.pathname : capture; // See https://github.com/pillarjs/path-to-regexp#parameters
  1095. const wildcards = '[*:?+]';
  1096. if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
  1097. 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.`);
  1098. }
  1099. }
  1100. const matchCallback = ({
  1101. url
  1102. }) => {
  1103. {
  1104. if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
  1105. 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.`);
  1106. }
  1107. }
  1108. return url.href === captureUrl.href;
  1109. }; // If `capture` is a string then `handler` and `method` must be present.
  1110. route = new Route(matchCallback, handler, method);
  1111. } else if (capture instanceof RegExp) {
  1112. // If `capture` is a `RegExp` then `handler` and `method` must be present.
  1113. route = new RegExpRoute(capture, handler, method);
  1114. } else if (typeof capture === 'function') {
  1115. // If `capture` is a function then `handler` and `method` must be present.
  1116. route = new Route(capture, handler, method);
  1117. } else if (capture instanceof Route) {
  1118. route = capture;
  1119. } else {
  1120. throw new WorkboxError('unsupported-route-type', {
  1121. moduleName: 'workbox-routing',
  1122. funcName: 'registerRoute',
  1123. paramName: 'capture'
  1124. });
  1125. }
  1126. const defaultRouter = getOrCreateDefaultRouter();
  1127. defaultRouter.registerRoute(route);
  1128. return route;
  1129. }
  1130. try {
  1131. self['workbox:strategies:6.5.2'] && _();
  1132. } catch (e) {}
  1133. /*
  1134. Copyright 2018 Google LLC
  1135. Use of this source code is governed by an MIT-style
  1136. license that can be found in the LICENSE file or at
  1137. https://opensource.org/licenses/MIT.
  1138. */
  1139. const cacheOkAndOpaquePlugin = {
  1140. /**
  1141. * Returns a valid response (to allow caching) if the status is 200 (OK) or
  1142. * 0 (opaque).
  1143. *
  1144. * @param {Object} options
  1145. * @param {Response} options.response
  1146. * @return {Response|null}
  1147. *
  1148. * @private
  1149. */
  1150. cacheWillUpdate: async ({
  1151. response
  1152. }) => {
  1153. if (response.status === 200 || response.status === 0) {
  1154. return response;
  1155. }
  1156. return null;
  1157. }
  1158. };
  1159. /*
  1160. Copyright 2018 Google LLC
  1161. Use of this source code is governed by an MIT-style
  1162. license that can be found in the LICENSE file or at
  1163. https://opensource.org/licenses/MIT.
  1164. */
  1165. const _cacheNameDetails = {
  1166. googleAnalytics: 'googleAnalytics',
  1167. precache: 'precache-v2',
  1168. prefix: 'workbox',
  1169. runtime: 'runtime',
  1170. suffix: typeof registration !== 'undefined' ? registration.scope : ''
  1171. };
  1172. const _createCacheName = cacheName => {
  1173. return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter(value => value && value.length > 0).join('-');
  1174. };
  1175. const eachCacheNameDetail = fn => {
  1176. for (const key of Object.keys(_cacheNameDetails)) {
  1177. fn(key);
  1178. }
  1179. };
  1180. const cacheNames = {
  1181. updateDetails: details => {
  1182. eachCacheNameDetail(key => {
  1183. if (typeof details[key] === 'string') {
  1184. _cacheNameDetails[key] = details[key];
  1185. }
  1186. });
  1187. },
  1188. getGoogleAnalyticsName: userCacheName => {
  1189. return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
  1190. },
  1191. getPrecacheName: userCacheName => {
  1192. return userCacheName || _createCacheName(_cacheNameDetails.precache);
  1193. },
  1194. getPrefix: () => {
  1195. return _cacheNameDetails.prefix;
  1196. },
  1197. getRuntimeName: userCacheName => {
  1198. return userCacheName || _createCacheName(_cacheNameDetails.runtime);
  1199. },
  1200. getSuffix: () => {
  1201. return _cacheNameDetails.suffix;
  1202. }
  1203. };
  1204. /*
  1205. Copyright 2020 Google LLC
  1206. Use of this source code is governed by an MIT-style
  1207. license that can be found in the LICENSE file or at
  1208. https://opensource.org/licenses/MIT.
  1209. */
  1210. function stripParams(fullURL, ignoreParams) {
  1211. const strippedURL = new URL(fullURL);
  1212. for (const param of ignoreParams) {
  1213. strippedURL.searchParams.delete(param);
  1214. }
  1215. return strippedURL.href;
  1216. }
  1217. /**
  1218. * Matches an item in the cache, ignoring specific URL params. This is similar
  1219. * to the `ignoreSearch` option, but it allows you to ignore just specific
  1220. * params (while continuing to match on the others).
  1221. *
  1222. * @private
  1223. * @param {Cache} cache
  1224. * @param {Request} request
  1225. * @param {Object} matchOptions
  1226. * @param {Array<string>} ignoreParams
  1227. * @return {Promise<Response|undefined>}
  1228. */
  1229. async function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {
  1230. const strippedRequestURL = stripParams(request.url, ignoreParams); // If the request doesn't include any ignored params, match as normal.
  1231. if (request.url === strippedRequestURL) {
  1232. return cache.match(request, matchOptions);
  1233. } // Otherwise, match by comparing keys
  1234. const keysOptions = Object.assign(Object.assign({}, matchOptions), {
  1235. ignoreSearch: true
  1236. });
  1237. const cacheKeys = await cache.keys(request, keysOptions);
  1238. for (const cacheKey of cacheKeys) {
  1239. const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);
  1240. if (strippedRequestURL === strippedCacheKeyURL) {
  1241. return cache.match(cacheKey, matchOptions);
  1242. }
  1243. }
  1244. return;
  1245. }
  1246. /*
  1247. Copyright 2018 Google LLC
  1248. Use of this source code is governed by an MIT-style
  1249. license that can be found in the LICENSE file or at
  1250. https://opensource.org/licenses/MIT.
  1251. */
  1252. /**
  1253. * The Deferred class composes Promises in a way that allows for them to be
  1254. * resolved or rejected from outside the constructor. In most cases promises
  1255. * should be used directly, but Deferreds can be necessary when the logic to
  1256. * resolve a promise must be separate.
  1257. *
  1258. * @private
  1259. */
  1260. class Deferred {
  1261. /**
  1262. * Creates a promise and exposes its resolve and reject functions as methods.
  1263. */
  1264. constructor() {
  1265. this.promise = new Promise((resolve, reject) => {
  1266. this.resolve = resolve;
  1267. this.reject = reject;
  1268. });
  1269. }
  1270. }
  1271. /*
  1272. Copyright 2018 Google LLC
  1273. Use of this source code is governed by an MIT-style
  1274. license that can be found in the LICENSE file or at
  1275. https://opensource.org/licenses/MIT.
  1276. */
  1277. // Can't change Function type right now.
  1278. // eslint-disable-next-line @typescript-eslint/ban-types
  1279. const quotaErrorCallbacks = new Set();
  1280. /*
  1281. Copyright 2018 Google LLC
  1282. Use of this source code is governed by an MIT-style
  1283. license that can be found in the LICENSE file or at
  1284. https://opensource.org/licenses/MIT.
  1285. */
  1286. /**
  1287. * Runs all of the callback functions, one at a time sequentially, in the order
  1288. * in which they were registered.
  1289. *
  1290. * @memberof workbox-core
  1291. * @private
  1292. */
  1293. async function executeQuotaErrorCallbacks() {
  1294. {
  1295. logger.log(`About to run ${quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`);
  1296. }
  1297. for (const callback of quotaErrorCallbacks) {
  1298. await callback();
  1299. {
  1300. logger.log(callback, 'is complete.');
  1301. }
  1302. }
  1303. {
  1304. logger.log('Finished running callbacks.');
  1305. }
  1306. }
  1307. /*
  1308. Copyright 2019 Google LLC
  1309. Use of this source code is governed by an MIT-style
  1310. license that can be found in the LICENSE file or at
  1311. https://opensource.org/licenses/MIT.
  1312. */
  1313. /**
  1314. * Returns a promise that resolves and the passed number of milliseconds.
  1315. * This utility is an async/await-friendly version of `setTimeout`.
  1316. *
  1317. * @param {number} ms
  1318. * @return {Promise}
  1319. * @private
  1320. */
  1321. function timeout(ms) {
  1322. return new Promise(resolve => setTimeout(resolve, ms));
  1323. }
  1324. /*
  1325. Copyright 2020 Google LLC
  1326. Use of this source code is governed by an MIT-style
  1327. license that can be found in the LICENSE file or at
  1328. https://opensource.org/licenses/MIT.
  1329. */
  1330. function toRequest(input) {
  1331. return typeof input === 'string' ? new Request(input) : input;
  1332. }
  1333. /**
  1334. * A class created every time a Strategy instance instance calls
  1335. * {@link workbox-strategies.Strategy~handle} or
  1336. * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and
  1337. * cache actions around plugin callbacks and keeps track of when the strategy
  1338. * is "done" (i.e. all added `event.waitUntil()` promises have resolved).
  1339. *
  1340. * @memberof workbox-strategies
  1341. */
  1342. class StrategyHandler {
  1343. /**
  1344. * Creates a new instance associated with the passed strategy and event
  1345. * that's handling the request.
  1346. *
  1347. * The constructor also initializes the state that will be passed to each of
  1348. * the plugins handling this request.
  1349. *
  1350. * @param {workbox-strategies.Strategy} strategy
  1351. * @param {Object} options
  1352. * @param {Request|string} options.request A request to run this strategy for.
  1353. * @param {ExtendableEvent} options.event The event associated with the
  1354. * request.
  1355. * @param {URL} [options.url]
  1356. * @param {*} [options.params] The return value from the
  1357. * {@link workbox-routing~matchCallback} (if applicable).
  1358. */
  1359. constructor(strategy, options) {
  1360. this._cacheKeys = {};
  1361. /**
  1362. * The request the strategy is performing (passed to the strategy's
  1363. * `handle()` or `handleAll()` method).
  1364. * @name request
  1365. * @instance
  1366. * @type {Request}
  1367. * @memberof workbox-strategies.StrategyHandler
  1368. */
  1369. /**
  1370. * The event associated with this request.
  1371. * @name event
  1372. * @instance
  1373. * @type {ExtendableEvent}
  1374. * @memberof workbox-strategies.StrategyHandler
  1375. */
  1376. /**
  1377. * A `URL` instance of `request.url` (if passed to the strategy's
  1378. * `handle()` or `handleAll()` method).
  1379. * Note: the `url` param will be present if the strategy was invoked
  1380. * from a workbox `Route` object.
  1381. * @name url
  1382. * @instance
  1383. * @type {URL|undefined}
  1384. * @memberof workbox-strategies.StrategyHandler
  1385. */
  1386. /**
  1387. * A `param` value (if passed to the strategy's
  1388. * `handle()` or `handleAll()` method).
  1389. * Note: the `param` param will be present if the strategy was invoked
  1390. * from a workbox `Route` object and the
  1391. * {@link workbox-routing~matchCallback} returned
  1392. * a truthy value (it will be that value).
  1393. * @name params
  1394. * @instance
  1395. * @type {*|undefined}
  1396. * @memberof workbox-strategies.StrategyHandler
  1397. */
  1398. {
  1399. finalAssertExports.isInstance(options.event, ExtendableEvent, {
  1400. moduleName: 'workbox-strategies',
  1401. className: 'StrategyHandler',
  1402. funcName: 'constructor',
  1403. paramName: 'options.event'
  1404. });
  1405. }
  1406. Object.assign(this, options);
  1407. this.event = options.event;
  1408. this._strategy = strategy;
  1409. this._handlerDeferred = new Deferred();
  1410. this._extendLifetimePromises = []; // Copy the plugins list (since it's mutable on the strategy),
  1411. // so any mutations don't affect this handler instance.
  1412. this._plugins = [...strategy.plugins];
  1413. this._pluginStateMap = new Map();
  1414. for (const plugin of this._plugins) {
  1415. this._pluginStateMap.set(plugin, {});
  1416. }
  1417. this.event.waitUntil(this._handlerDeferred.promise);
  1418. }
  1419. /**
  1420. * Fetches a given request (and invokes any applicable plugin callback
  1421. * methods) using the `fetchOptions` (for non-navigation requests) and
  1422. * `plugins` defined on the `Strategy` object.
  1423. *
  1424. * The following plugin lifecycle methods are invoked when using this method:
  1425. * - `requestWillFetch()`
  1426. * - `fetchDidSucceed()`
  1427. * - `fetchDidFail()`
  1428. *
  1429. * @param {Request|string} input The URL or request to fetch.
  1430. * @return {Promise<Response>}
  1431. */
  1432. async fetch(input) {
  1433. const {
  1434. event
  1435. } = this;
  1436. let request = toRequest(input);
  1437. if (request.mode === 'navigate' && event instanceof FetchEvent && event.preloadResponse) {
  1438. const possiblePreloadResponse = await event.preloadResponse;
  1439. if (possiblePreloadResponse) {
  1440. {
  1441. logger.log(`Using a preloaded navigation response for ` + `'${getFriendlyURL(request.url)}'`);
  1442. }
  1443. return possiblePreloadResponse;
  1444. }
  1445. } // If there is a fetchDidFail plugin, we need to save a clone of the
  1446. // original request before it's either modified by a requestWillFetch
  1447. // plugin or before the original request's body is consumed via fetch().
  1448. const originalRequest = this.hasCallback('fetchDidFail') ? request.clone() : null;
  1449. try {
  1450. for (const cb of this.iterateCallbacks('requestWillFetch')) {
  1451. request = await cb({
  1452. request: request.clone(),
  1453. event
  1454. });
  1455. }
  1456. } catch (err) {
  1457. if (err instanceof Error) {
  1458. throw new WorkboxError('plugin-error-request-will-fetch', {
  1459. thrownErrorMessage: err.message
  1460. });
  1461. }
  1462. } // The request can be altered by plugins with `requestWillFetch` making
  1463. // the original request (most likely from a `fetch` event) different
  1464. // from the Request we make. Pass both to `fetchDidFail` to aid debugging.
  1465. const pluginFilteredRequest = request.clone();
  1466. try {
  1467. let fetchResponse; // See https://github.com/GoogleChrome/workbox/issues/1796
  1468. fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions);
  1469. if ("development" !== 'production') {
  1470. logger.debug(`Network request for ` + `'${getFriendlyURL(request.url)}' returned a response with ` + `status '${fetchResponse.status}'.`);
  1471. }
  1472. for (const callback of this.iterateCallbacks('fetchDidSucceed')) {
  1473. fetchResponse = await callback({
  1474. event,
  1475. request: pluginFilteredRequest,
  1476. response: fetchResponse
  1477. });
  1478. }
  1479. return fetchResponse;
  1480. } catch (error) {
  1481. {
  1482. logger.log(`Network request for ` + `'${getFriendlyURL(request.url)}' threw an error.`, error);
  1483. } // `originalRequest` will only exist if a `fetchDidFail` callback
  1484. // is being used (see above).
  1485. if (originalRequest) {
  1486. await this.runCallbacks('fetchDidFail', {
  1487. error: error,
  1488. event,
  1489. originalRequest: originalRequest.clone(),
  1490. request: pluginFilteredRequest.clone()
  1491. });
  1492. }
  1493. throw error;
  1494. }
  1495. }
  1496. /**
  1497. * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on
  1498. * the response generated by `this.fetch()`.
  1499. *
  1500. * The call to `this.cachePut()` automatically invokes `this.waitUntil()`,
  1501. * so you do not have to manually call `waitUntil()` on the event.
  1502. *
  1503. * @param {Request|string} input The request or URL to fetch and cache.
  1504. * @return {Promise<Response>}
  1505. */
  1506. async fetchAndCachePut(input) {
  1507. const response = await this.fetch(input);
  1508. const responseClone = response.clone();
  1509. void this.waitUntil(this.cachePut(input, responseClone));
  1510. return response;
  1511. }
  1512. /**
  1513. * Matches a request from the cache (and invokes any applicable plugin
  1514. * callback methods) using the `cacheName`, `matchOptions`, and `plugins`
  1515. * defined on the strategy object.
  1516. *
  1517. * The following plugin lifecycle methods are invoked when using this method:
  1518. * - cacheKeyWillByUsed()
  1519. * - cachedResponseWillByUsed()
  1520. *
  1521. * @param {Request|string} key The Request or URL to use as the cache key.
  1522. * @return {Promise<Response|undefined>} A matching response, if found.
  1523. */
  1524. async cacheMatch(key) {
  1525. const request = toRequest(key);
  1526. let cachedResponse;
  1527. const {
  1528. cacheName,
  1529. matchOptions
  1530. } = this._strategy;
  1531. const effectiveRequest = await this.getCacheKey(request, 'read');
  1532. const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), {
  1533. cacheName
  1534. });
  1535. cachedResponse = await caches.match(effectiveRequest, multiMatchOptions);
  1536. {
  1537. if (cachedResponse) {
  1538. logger.debug(`Found a cached response in '${cacheName}'.`);
  1539. } else {
  1540. logger.debug(`No cached response found in '${cacheName}'.`);
  1541. }
  1542. }
  1543. for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) {
  1544. cachedResponse = (await callback({
  1545. cacheName,
  1546. matchOptions,
  1547. cachedResponse,
  1548. request: effectiveRequest,
  1549. event: this.event
  1550. })) || undefined;
  1551. }
  1552. return cachedResponse;
  1553. }
  1554. /**
  1555. * Puts a request/response pair in the cache (and invokes any applicable
  1556. * plugin callback methods) using the `cacheName` and `plugins` defined on
  1557. * the strategy object.
  1558. *
  1559. * The following plugin lifecycle methods are invoked when using this method:
  1560. * - cacheKeyWillByUsed()
  1561. * - cacheWillUpdate()
  1562. * - cacheDidUpdate()
  1563. *
  1564. * @param {Request|string} key The request or URL to use as the cache key.
  1565. * @param {Response} response The response to cache.
  1566. * @return {Promise<boolean>} `false` if a cacheWillUpdate caused the response
  1567. * not be cached, and `true` otherwise.
  1568. */
  1569. async cachePut(key, response) {
  1570. const request = toRequest(key); // Run in the next task to avoid blocking other cache reads.
  1571. // https://github.com/w3c/ServiceWorker/issues/1397
  1572. await timeout(0);
  1573. const effectiveRequest = await this.getCacheKey(request, 'write');
  1574. {
  1575. if (effectiveRequest.method && effectiveRequest.method !== 'GET') {
  1576. throw new WorkboxError('attempt-to-cache-non-get-request', {
  1577. url: getFriendlyURL(effectiveRequest.url),
  1578. method: effectiveRequest.method
  1579. });
  1580. } // See https://github.com/GoogleChrome/workbox/issues/2818
  1581. const vary = response.headers.get('Vary');
  1582. if (vary) {
  1583. logger.debug(`The response for ${getFriendlyURL(effectiveRequest.url)} ` + `has a 'Vary: ${vary}' header. ` + `Consider setting the {ignoreVary: true} option on your strategy ` + `to ensure cache matching and deletion works as expected.`);
  1584. }
  1585. }
  1586. if (!response) {
  1587. {
  1588. logger.error(`Cannot cache non-existent response for ` + `'${getFriendlyURL(effectiveRequest.url)}'.`);
  1589. }
  1590. throw new WorkboxError('cache-put-with-no-response', {
  1591. url: getFriendlyURL(effectiveRequest.url)
  1592. });
  1593. }
  1594. const responseToCache = await this._ensureResponseSafeToCache(response);
  1595. if (!responseToCache) {
  1596. {
  1597. logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` + `will not be cached.`, responseToCache);
  1598. }
  1599. return false;
  1600. }
  1601. const {
  1602. cacheName,
  1603. matchOptions
  1604. } = this._strategy;
  1605. const cache = await self.caches.open(cacheName);
  1606. const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate');
  1607. const oldResponse = hasCacheUpdateCallback ? await cacheMatchIgnoreParams( // TODO(philipwalton): the `__WB_REVISION__` param is a precaching
  1608. // feature. Consider into ways to only add this behavior if using
  1609. // precaching.
  1610. cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions) : null;
  1611. {
  1612. logger.debug(`Updating the '${cacheName}' cache with a new Response ` + `for ${getFriendlyURL(effectiveRequest.url)}.`);
  1613. }
  1614. try {
  1615. await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);
  1616. } catch (error) {
  1617. if (error instanceof Error) {
  1618. // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
  1619. if (error.name === 'QuotaExceededError') {
  1620. await executeQuotaErrorCallbacks();
  1621. }
  1622. throw error;
  1623. }
  1624. }
  1625. for (const callback of this.iterateCallbacks('cacheDidUpdate')) {
  1626. await callback({
  1627. cacheName,
  1628. oldResponse,
  1629. newResponse: responseToCache.clone(),
  1630. request: effectiveRequest,
  1631. event: this.event
  1632. });
  1633. }
  1634. return true;
  1635. }
  1636. /**
  1637. * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and
  1638. * executes any of those callbacks found in sequence. The final `Request`
  1639. * object returned by the last plugin is treated as the cache key for cache
  1640. * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have
  1641. * been registered, the passed request is returned unmodified
  1642. *
  1643. * @param {Request} request
  1644. * @param {string} mode
  1645. * @return {Promise<Request>}
  1646. */
  1647. async getCacheKey(request, mode) {
  1648. const key = `${request.url} | ${mode}`;
  1649. if (!this._cacheKeys[key]) {
  1650. let effectiveRequest = request;
  1651. for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) {
  1652. effectiveRequest = toRequest(await callback({
  1653. mode,
  1654. request: effectiveRequest,
  1655. event: this.event,
  1656. // params has a type any can't change right now.
  1657. params: this.params // eslint-disable-line
  1658. }));
  1659. }
  1660. this._cacheKeys[key] = effectiveRequest;
  1661. }
  1662. return this._cacheKeys[key];
  1663. }
  1664. /**
  1665. * Returns true if the strategy has at least one plugin with the given
  1666. * callback.
  1667. *
  1668. * @param {string} name The name of the callback to check for.
  1669. * @return {boolean}
  1670. */
  1671. hasCallback(name) {
  1672. for (const plugin of this._strategy.plugins) {
  1673. if (name in plugin) {
  1674. return true;
  1675. }
  1676. }
  1677. return false;
  1678. }
  1679. /**
  1680. * Runs all plugin callbacks matching the given name, in order, passing the
  1681. * given param object (merged ith the current plugin state) as the only
  1682. * argument.
  1683. *
  1684. * Note: since this method runs all plugins, it's not suitable for cases
  1685. * where the return value of a callback needs to be applied prior to calling
  1686. * the next callback. See
  1687. * {@link workbox-strategies.StrategyHandler#iterateCallbacks}
  1688. * below for how to handle that case.
  1689. *
  1690. * @param {string} name The name of the callback to run within each plugin.
  1691. * @param {Object} param The object to pass as the first (and only) param
  1692. * when executing each callback. This object will be merged with the
  1693. * current plugin state prior to callback execution.
  1694. */
  1695. async runCallbacks(name, param) {
  1696. for (const callback of this.iterateCallbacks(name)) {
  1697. // TODO(philipwalton): not sure why `any` is needed. It seems like
  1698. // this should work with `as WorkboxPluginCallbackParam[C]`.
  1699. await callback(param);
  1700. }
  1701. }
  1702. /**
  1703. * Accepts a callback and returns an iterable of matching plugin callbacks,
  1704. * where each callback is wrapped with the current handler state (i.e. when
  1705. * you call each callback, whatever object parameter you pass it will
  1706. * be merged with the plugin's current state).
  1707. *
  1708. * @param {string} name The name fo the callback to run
  1709. * @return {Array<Function>}
  1710. */
  1711. *iterateCallbacks(name) {
  1712. for (const plugin of this._strategy.plugins) {
  1713. if (typeof plugin[name] === 'function') {
  1714. const state = this._pluginStateMap.get(plugin);
  1715. const statefulCallback = param => {
  1716. const statefulParam = Object.assign(Object.assign({}, param), {
  1717. state
  1718. }); // TODO(philipwalton): not sure why `any` is needed. It seems like
  1719. // this should work with `as WorkboxPluginCallbackParam[C]`.
  1720. return plugin[name](statefulParam);
  1721. };
  1722. yield statefulCallback;
  1723. }
  1724. }
  1725. }
  1726. /**
  1727. * Adds a promise to the
  1728. * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises}
  1729. * of the event event associated with the request being handled (usually a
  1730. * `FetchEvent`).
  1731. *
  1732. * Note: you can await
  1733. * {@link workbox-strategies.StrategyHandler~doneWaiting}
  1734. * to know when all added promises have settled.
  1735. *
  1736. * @param {Promise} promise A promise to add to the extend lifetime promises
  1737. * of the event that triggered the request.
  1738. */
  1739. waitUntil(promise) {
  1740. this._extendLifetimePromises.push(promise);
  1741. return promise;
  1742. }
  1743. /**
  1744. * Returns a promise that resolves once all promises passed to
  1745. * {@link workbox-strategies.StrategyHandler~waitUntil}
  1746. * have settled.
  1747. *
  1748. * Note: any work done after `doneWaiting()` settles should be manually
  1749. * passed to an event's `waitUntil()` method (not this handler's
  1750. * `waitUntil()` method), otherwise the service worker thread my be killed
  1751. * prior to your work completing.
  1752. */
  1753. async doneWaiting() {
  1754. let promise;
  1755. while (promise = this._extendLifetimePromises.shift()) {
  1756. await promise;
  1757. }
  1758. }
  1759. /**
  1760. * Stops running the strategy and immediately resolves any pending
  1761. * `waitUntil()` promises.
  1762. */
  1763. destroy() {
  1764. this._handlerDeferred.resolve(null);
  1765. }
  1766. /**
  1767. * This method will call cacheWillUpdate on the available plugins (or use
  1768. * status === 200) to determine if the Response is safe and valid to cache.
  1769. *
  1770. * @param {Request} options.request
  1771. * @param {Response} options.response
  1772. * @return {Promise<Response|undefined>}
  1773. *
  1774. * @private
  1775. */
  1776. async _ensureResponseSafeToCache(response) {
  1777. let responseToCache = response;
  1778. let pluginsUsed = false;
  1779. for (const callback of this.iterateCallbacks('cacheWillUpdate')) {
  1780. responseToCache = (await callback({
  1781. request: this.request,
  1782. response: responseToCache,
  1783. event: this.event
  1784. })) || undefined;
  1785. pluginsUsed = true;
  1786. if (!responseToCache) {
  1787. break;
  1788. }
  1789. }
  1790. if (!pluginsUsed) {
  1791. if (responseToCache && responseToCache.status !== 200) {
  1792. responseToCache = undefined;
  1793. }
  1794. {
  1795. if (responseToCache) {
  1796. if (responseToCache.status !== 200) {
  1797. if (responseToCache.status === 0) {
  1798. logger.warn(`The response for '${this.request.url}' ` + `is an opaque response. The caching strategy that you're ` + `using will not cache opaque responses by default.`);
  1799. } else {
  1800. logger.debug(`The response for '${this.request.url}' ` + `returned a status code of '${response.status}' and won't ` + `be cached as a result.`);
  1801. }
  1802. }
  1803. }
  1804. }
  1805. }
  1806. return responseToCache;
  1807. }
  1808. }
  1809. /*
  1810. Copyright 2020 Google LLC
  1811. Use of this source code is governed by an MIT-style
  1812. license that can be found in the LICENSE file or at
  1813. https://opensource.org/licenses/MIT.
  1814. */
  1815. /**
  1816. * An abstract base class that all other strategy classes must extend from:
  1817. *
  1818. * @memberof workbox-strategies
  1819. */
  1820. class Strategy {
  1821. /**
  1822. * Creates a new instance of the strategy and sets all documented option
  1823. * properties as public instance properties.
  1824. *
  1825. * Note: if a custom strategy class extends the base Strategy class and does
  1826. * not need more than these properties, it does not need to define its own
  1827. * constructor.
  1828. *
  1829. * @param {Object} [options]
  1830. * @param {string} [options.cacheName] Cache name to store and retrieve
  1831. * requests. Defaults to the cache names provided by
  1832. * {@link workbox-core.cacheNames}.
  1833. * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  1834. * to use in conjunction with this caching strategy.
  1835. * @param {Object} [options.fetchOptions] Values passed along to the
  1836. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  1837. * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
  1838. * `fetch()` requests made by this strategy.
  1839. * @param {Object} [options.matchOptions] The
  1840. * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
  1841. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  1842. */
  1843. constructor(options = {}) {
  1844. /**
  1845. * Cache name to store and retrieve
  1846. * requests. Defaults to the cache names provided by
  1847. * {@link workbox-core.cacheNames}.
  1848. *
  1849. * @type {string}
  1850. */
  1851. this.cacheName = cacheNames.getRuntimeName(options.cacheName);
  1852. /**
  1853. * The list
  1854. * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  1855. * used by this strategy.
  1856. *
  1857. * @type {Array<Object>}
  1858. */
  1859. this.plugins = options.plugins || [];
  1860. /**
  1861. * Values passed along to the
  1862. * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters}
  1863. * of all fetch() requests made by this strategy.
  1864. *
  1865. * @type {Object}
  1866. */
  1867. this.fetchOptions = options.fetchOptions;
  1868. /**
  1869. * The
  1870. * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
  1871. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  1872. *
  1873. * @type {Object}
  1874. */
  1875. this.matchOptions = options.matchOptions;
  1876. }
  1877. /**
  1878. * Perform a request strategy and returns a `Promise` that will resolve with
  1879. * a `Response`, invoking all relevant plugin callbacks.
  1880. *
  1881. * When a strategy instance is registered with a Workbox
  1882. * {@link workbox-routing.Route}, this method is automatically
  1883. * called when the route matches.
  1884. *
  1885. * Alternatively, this method can be used in a standalone `FetchEvent`
  1886. * listener by passing it to `event.respondWith()`.
  1887. *
  1888. * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
  1889. * properties listed below.
  1890. * @param {Request|string} options.request A request to run this strategy for.
  1891. * @param {ExtendableEvent} options.event The event associated with the
  1892. * request.
  1893. * @param {URL} [options.url]
  1894. * @param {*} [options.params]
  1895. */
  1896. handle(options) {
  1897. const [responseDone] = this.handleAll(options);
  1898. return responseDone;
  1899. }
  1900. /**
  1901. * Similar to {@link workbox-strategies.Strategy~handle}, but
  1902. * instead of just returning a `Promise` that resolves to a `Response` it
  1903. * it will return an tuple of `[response, done]` promises, where the former
  1904. * (`response`) is equivalent to what `handle()` returns, and the latter is a
  1905. * Promise that will resolve once any promises that were added to
  1906. * `event.waitUntil()` as part of performing the strategy have completed.
  1907. *
  1908. * You can await the `done` promise to ensure any extra work performed by
  1909. * the strategy (usually caching responses) completes successfully.
  1910. *
  1911. * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
  1912. * properties listed below.
  1913. * @param {Request|string} options.request A request to run this strategy for.
  1914. * @param {ExtendableEvent} options.event The event associated with the
  1915. * request.
  1916. * @param {URL} [options.url]
  1917. * @param {*} [options.params]
  1918. * @return {Array<Promise>} A tuple of [response, done]
  1919. * promises that can be used to determine when the response resolves as
  1920. * well as when the handler has completed all its work.
  1921. */
  1922. handleAll(options) {
  1923. // Allow for flexible options to be passed.
  1924. if (options instanceof FetchEvent) {
  1925. options = {
  1926. event: options,
  1927. request: options.request
  1928. };
  1929. }
  1930. const event = options.event;
  1931. const request = typeof options.request === 'string' ? new Request(options.request) : options.request;
  1932. const params = 'params' in options ? options.params : undefined;
  1933. const handler = new StrategyHandler(this, {
  1934. event,
  1935. request,
  1936. params
  1937. });
  1938. const responseDone = this._getResponse(handler, request, event);
  1939. const handlerDone = this._awaitComplete(responseDone, handler, request, event); // Return an array of promises, suitable for use with Promise.all().
  1940. return [responseDone, handlerDone];
  1941. }
  1942. async _getResponse(handler, request, event) {
  1943. await handler.runCallbacks('handlerWillStart', {
  1944. event,
  1945. request
  1946. });
  1947. let response = undefined;
  1948. try {
  1949. response = await this._handle(request, handler); // The "official" Strategy subclasses all throw this error automatically,
  1950. // but in case a third-party Strategy doesn't, ensure that we have a
  1951. // consistent failure when there's no response or an error response.
  1952. if (!response || response.type === 'error') {
  1953. throw new WorkboxError('no-response', {
  1954. url: request.url
  1955. });
  1956. }
  1957. } catch (error) {
  1958. if (error instanceof Error) {
  1959. for (const callback of handler.iterateCallbacks('handlerDidError')) {
  1960. response = await callback({
  1961. error,
  1962. event,
  1963. request
  1964. });
  1965. if (response) {
  1966. break;
  1967. }
  1968. }
  1969. }
  1970. if (!response) {
  1971. throw error;
  1972. } else {
  1973. logger.log(`While responding to '${getFriendlyURL(request.url)}', ` + `an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` + `a handlerDidError plugin.`);
  1974. }
  1975. }
  1976. for (const callback of handler.iterateCallbacks('handlerWillRespond')) {
  1977. response = await callback({
  1978. event,
  1979. request,
  1980. response
  1981. });
  1982. }
  1983. return response;
  1984. }
  1985. async _awaitComplete(responseDone, handler, request, event) {
  1986. let response;
  1987. let error;
  1988. try {
  1989. response = await responseDone;
  1990. } catch (error) {// Ignore errors, as response errors should be caught via the `response`
  1991. // promise above. The `done` promise will only throw for errors in
  1992. // promises passed to `handler.waitUntil()`.
  1993. }
  1994. try {
  1995. await handler.runCallbacks('handlerDidRespond', {
  1996. event,
  1997. request,
  1998. response
  1999. });
  2000. await handler.doneWaiting();
  2001. } catch (waitUntilError) {
  2002. if (waitUntilError instanceof Error) {
  2003. error = waitUntilError;
  2004. }
  2005. }
  2006. await handler.runCallbacks('handlerDidComplete', {
  2007. event,
  2008. request,
  2009. response,
  2010. error: error
  2011. });
  2012. handler.destroy();
  2013. if (error) {
  2014. throw error;
  2015. }
  2016. }
  2017. }
  2018. /**
  2019. * Classes extending the `Strategy` based class should implement this method,
  2020. * and leverage the {@link workbox-strategies.StrategyHandler}
  2021. * arg to perform all fetching and cache logic, which will ensure all relevant
  2022. * cache, cache options, fetch options and plugins are used (per the current
  2023. * strategy instance).
  2024. *
  2025. * @name _handle
  2026. * @instance
  2027. * @abstract
  2028. * @function
  2029. * @param {Request} request
  2030. * @param {workbox-strategies.StrategyHandler} handler
  2031. * @return {Promise<Response>}
  2032. *
  2033. * @memberof workbox-strategies.Strategy
  2034. */
  2035. /*
  2036. Copyright 2018 Google LLC
  2037. Use of this source code is governed by an MIT-style
  2038. license that can be found in the LICENSE file or at
  2039. https://opensource.org/licenses/MIT.
  2040. */
  2041. const messages = {
  2042. strategyStart: (strategyName, request) => `Using ${strategyName} to respond to '${getFriendlyURL(request.url)}'`,
  2043. printFinalResponse: response => {
  2044. if (response) {
  2045. logger.groupCollapsed(`View the final response here.`);
  2046. logger.log(response || '[No response returned]');
  2047. logger.groupEnd();
  2048. }
  2049. }
  2050. };
  2051. /*
  2052. Copyright 2018 Google LLC
  2053. Use of this source code is governed by an MIT-style
  2054. license that can be found in the LICENSE file or at
  2055. https://opensource.org/licenses/MIT.
  2056. */
  2057. /**
  2058. * An implementation of a
  2059. * [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache)
  2060. * request strategy.
  2061. *
  2062. * By default, this strategy will cache responses with a 200 status code as
  2063. * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
  2064. * Opaque responses are are cross-origin requests where the response doesn't
  2065. * support [CORS](https://enable-cors.org/).
  2066. *
  2067. * If the network request fails, and there is no cache match, this will throw
  2068. * a `WorkboxError` exception.
  2069. *
  2070. * @extends workbox-strategies.Strategy
  2071. * @memberof workbox-strategies
  2072. */
  2073. class NetworkFirst extends Strategy {
  2074. /**
  2075. * @param {Object} [options]
  2076. * @param {string} [options.cacheName] Cache name to store and retrieve
  2077. * requests. Defaults to cache names provided by
  2078. * {@link workbox-core.cacheNames}.
  2079. * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  2080. * to use in conjunction with this caching strategy.
  2081. * @param {Object} [options.fetchOptions] Values passed along to the
  2082. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  2083. * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
  2084. * `fetch()` requests made by this strategy.
  2085. * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)
  2086. * @param {number} [options.networkTimeoutSeconds] If set, any network requests
  2087. * that fail to respond within the timeout will fallback to the cache.
  2088. *
  2089. * This option can be used to combat
  2090. * "[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}"
  2091. * scenarios.
  2092. */
  2093. constructor(options = {}) {
  2094. super(options); // If this instance contains no plugins with a 'cacheWillUpdate' callback,
  2095. // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list.
  2096. if (!this.plugins.some(p => 'cacheWillUpdate' in p)) {
  2097. this.plugins.unshift(cacheOkAndOpaquePlugin);
  2098. }
  2099. this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;
  2100. {
  2101. if (this._networkTimeoutSeconds) {
  2102. finalAssertExports.isType(this._networkTimeoutSeconds, 'number', {
  2103. moduleName: 'workbox-strategies',
  2104. className: this.constructor.name,
  2105. funcName: 'constructor',
  2106. paramName: 'networkTimeoutSeconds'
  2107. });
  2108. }
  2109. }
  2110. }
  2111. /**
  2112. * @private
  2113. * @param {Request|string} request A request to run this strategy for.
  2114. * @param {workbox-strategies.StrategyHandler} handler The event that
  2115. * triggered the request.
  2116. * @return {Promise<Response>}
  2117. */
  2118. async _handle(request, handler) {
  2119. const logs = [];
  2120. {
  2121. finalAssertExports.isInstance(request, Request, {
  2122. moduleName: 'workbox-strategies',
  2123. className: this.constructor.name,
  2124. funcName: 'handle',
  2125. paramName: 'makeRequest'
  2126. });
  2127. }
  2128. const promises = [];
  2129. let timeoutId;
  2130. if (this._networkTimeoutSeconds) {
  2131. const {
  2132. id,
  2133. promise
  2134. } = this._getTimeoutPromise({
  2135. request,
  2136. logs,
  2137. handler
  2138. });
  2139. timeoutId = id;
  2140. promises.push(promise);
  2141. }
  2142. const networkPromise = this._getNetworkPromise({
  2143. timeoutId,
  2144. request,
  2145. logs,
  2146. handler
  2147. });
  2148. promises.push(networkPromise);
  2149. const response = await handler.waitUntil((async () => {
  2150. // Promise.race() will resolve as soon as the first promise resolves.
  2151. return (await handler.waitUntil(Promise.race(promises))) || ( // If Promise.race() resolved with null, it might be due to a network
  2152. // timeout + a cache miss. If that were to happen, we'd rather wait until
  2153. // the networkPromise resolves instead of returning null.
  2154. // Note that it's fine to await an already-resolved promise, so we don't
  2155. // have to check to see if it's still "in flight".
  2156. await networkPromise);
  2157. })());
  2158. {
  2159. logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
  2160. for (const log of logs) {
  2161. logger.log(log);
  2162. }
  2163. messages.printFinalResponse(response);
  2164. logger.groupEnd();
  2165. }
  2166. if (!response) {
  2167. throw new WorkboxError('no-response', {
  2168. url: request.url
  2169. });
  2170. }
  2171. return response;
  2172. }
  2173. /**
  2174. * @param {Object} options
  2175. * @param {Request} options.request
  2176. * @param {Array} options.logs A reference to the logs array
  2177. * @param {Event} options.event
  2178. * @return {Promise<Response>}
  2179. *
  2180. * @private
  2181. */
  2182. _getTimeoutPromise({
  2183. request,
  2184. logs,
  2185. handler
  2186. }) {
  2187. let timeoutId;
  2188. const timeoutPromise = new Promise(resolve => {
  2189. const onNetworkTimeout = async () => {
  2190. {
  2191. logs.push(`Timing out the network response at ` + `${this._networkTimeoutSeconds} seconds.`);
  2192. }
  2193. resolve(await handler.cacheMatch(request));
  2194. };
  2195. timeoutId = setTimeout(onNetworkTimeout, this._networkTimeoutSeconds * 1000);
  2196. });
  2197. return {
  2198. promise: timeoutPromise,
  2199. id: timeoutId
  2200. };
  2201. }
  2202. /**
  2203. * @param {Object} options
  2204. * @param {number|undefined} options.timeoutId
  2205. * @param {Request} options.request
  2206. * @param {Array} options.logs A reference to the logs Array.
  2207. * @param {Event} options.event
  2208. * @return {Promise<Response>}
  2209. *
  2210. * @private
  2211. */
  2212. async _getNetworkPromise({
  2213. timeoutId,
  2214. request,
  2215. logs,
  2216. handler
  2217. }) {
  2218. let error;
  2219. let response;
  2220. try {
  2221. response = await handler.fetchAndCachePut(request);
  2222. } catch (fetchError) {
  2223. if (fetchError instanceof Error) {
  2224. error = fetchError;
  2225. }
  2226. }
  2227. if (timeoutId) {
  2228. clearTimeout(timeoutId);
  2229. }
  2230. {
  2231. if (response) {
  2232. logs.push(`Got response from network.`);
  2233. } else {
  2234. logs.push(`Unable to get a response from the network. Will respond ` + `with a cached response.`);
  2235. }
  2236. }
  2237. if (error || !response) {
  2238. response = await handler.cacheMatch(request);
  2239. {
  2240. if (response) {
  2241. logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache.`);
  2242. } else {
  2243. logs.push(`No response found in the '${this.cacheName}' cache.`);
  2244. }
  2245. }
  2246. }
  2247. return response;
  2248. }
  2249. }
  2250. /*
  2251. Copyright 2018 Google LLC
  2252. Use of this source code is governed by an MIT-style
  2253. license that can be found in the LICENSE file or at
  2254. https://opensource.org/licenses/MIT.
  2255. */
  2256. /**
  2257. * An implementation of a
  2258. * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only)
  2259. * request strategy.
  2260. *
  2261. * This class is useful if you want to take advantage of any
  2262. * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).
  2263. *
  2264. * If the network request fails, this will throw a `WorkboxError` exception.
  2265. *
  2266. * @extends workbox-strategies.Strategy
  2267. * @memberof workbox-strategies
  2268. */
  2269. class NetworkOnly extends Strategy {
  2270. /**
  2271. * @param {Object} [options]
  2272. * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  2273. * to use in conjunction with this caching strategy.
  2274. * @param {Object} [options.fetchOptions] Values passed along to the
  2275. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  2276. * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
  2277. * `fetch()` requests made by this strategy.
  2278. * @param {number} [options.networkTimeoutSeconds] If set, any network requests
  2279. * that fail to respond within the timeout will result in a network error.
  2280. */
  2281. constructor(options = {}) {
  2282. super(options);
  2283. this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;
  2284. }
  2285. /**
  2286. * @private
  2287. * @param {Request|string} request A request to run this strategy for.
  2288. * @param {workbox-strategies.StrategyHandler} handler The event that
  2289. * triggered the request.
  2290. * @return {Promise<Response>}
  2291. */
  2292. async _handle(request, handler) {
  2293. {
  2294. finalAssertExports.isInstance(request, Request, {
  2295. moduleName: 'workbox-strategies',
  2296. className: this.constructor.name,
  2297. funcName: '_handle',
  2298. paramName: 'request'
  2299. });
  2300. }
  2301. let error = undefined;
  2302. let response;
  2303. try {
  2304. const promises = [handler.fetch(request)];
  2305. if (this._networkTimeoutSeconds) {
  2306. const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000);
  2307. promises.push(timeoutPromise);
  2308. }
  2309. response = await Promise.race(promises);
  2310. if (!response) {
  2311. throw new Error(`Timed out the network response after ` + `${this._networkTimeoutSeconds} seconds.`);
  2312. }
  2313. } catch (err) {
  2314. if (err instanceof Error) {
  2315. error = err;
  2316. }
  2317. }
  2318. {
  2319. logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
  2320. if (response) {
  2321. logger.log(`Got response from network.`);
  2322. } else {
  2323. logger.log(`Unable to get a response from the network.`);
  2324. }
  2325. messages.printFinalResponse(response);
  2326. logger.groupEnd();
  2327. }
  2328. if (!response) {
  2329. throw new WorkboxError('no-response', {
  2330. url: request.url,
  2331. error
  2332. });
  2333. }
  2334. return response;
  2335. }
  2336. }
  2337. /*
  2338. Copyright 2019 Google LLC
  2339. Use of this source code is governed by an MIT-style
  2340. license that can be found in the LICENSE file or at
  2341. https://opensource.org/licenses/MIT.
  2342. */
  2343. /**
  2344. * Claim any currently available clients once the service worker
  2345. * becomes active. This is normally used in conjunction with `skipWaiting()`.
  2346. *
  2347. * @memberof workbox-core
  2348. */
  2349. function clientsClaim() {
  2350. self.addEventListener('activate', () => self.clients.claim());
  2351. }
  2352. exports.NetworkFirst = NetworkFirst;
  2353. exports.NetworkOnly = NetworkOnly;
  2354. exports.clientsClaim = clientsClaim;
  2355. exports.registerRoute = registerRoute;
  2356. }));
  2357. //# sourceMappingURL=workbox-74d02f44.js.map