workbox-87348480.js 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502
  1. define(['exports'], (function (exports) { 'use strict';
  2. // @ts-ignore
  3. try {
  4. self['workbox:core:7.0.0'] && _();
  5. } catch (e) {}
  6. /*
  7. Copyright 2019 Google LLC
  8. Use of this source code is governed by an MIT-style
  9. license that can be found in the LICENSE file or at
  10. https://opensource.org/licenses/MIT.
  11. */
  12. const logger = (() => {
  13. // Don't overwrite this value if it's already set.
  14. // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
  15. if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {
  16. self.__WB_DISABLE_DEV_LOGS = false;
  17. }
  18. let inGroup = false;
  19. const methodToColorMap = {
  20. debug: `#7f8c8d`,
  21. log: `#2ecc71`,
  22. warn: `#f39c12`,
  23. error: `#c0392b`,
  24. groupCollapsed: `#3498db`,
  25. groupEnd: null // No colored prefix on groupEnd
  26. };
  27. const print = function (method, args) {
  28. if (self.__WB_DISABLE_DEV_LOGS) {
  29. return;
  30. }
  31. if (method === 'groupCollapsed') {
  32. // Safari doesn't print all console.groupCollapsed() arguments:
  33. // https://bugs.webkit.org/show_bug.cgi?id=182754
  34. if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
  35. console[method](...args);
  36. return;
  37. }
  38. }
  39. const styles = [`background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em`];
  40. // When in a group, the workbox prefix is not displayed.
  41. const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
  42. console[method](...logPrefix, ...args);
  43. if (method === 'groupCollapsed') {
  44. inGroup = true;
  45. }
  46. if (method === 'groupEnd') {
  47. inGroup = false;
  48. }
  49. };
  50. // eslint-disable-next-line @typescript-eslint/ban-types
  51. const api = {};
  52. const loggerMethods = Object.keys(methodToColorMap);
  53. for (const key of loggerMethods) {
  54. const method = key;
  55. api[method] = (...args) => {
  56. print(method, args);
  57. };
  58. }
  59. return api;
  60. })();
  61. /*
  62. Copyright 2018 Google LLC
  63. Use of this source code is governed by an MIT-style
  64. license that can be found in the LICENSE file or at
  65. https://opensource.org/licenses/MIT.
  66. */
  67. const messages$1 = {
  68. 'invalid-value': ({
  69. paramName,
  70. validValueDescription,
  71. value
  72. }) => {
  73. if (!paramName || !validValueDescription) {
  74. throw new Error(`Unexpected input to 'invalid-value' error.`);
  75. }
  76. return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
  77. },
  78. 'not-an-array': ({
  79. moduleName,
  80. className,
  81. funcName,
  82. paramName
  83. }) => {
  84. if (!moduleName || !className || !funcName || !paramName) {
  85. throw new Error(`Unexpected input to 'not-an-array' error.`);
  86. }
  87. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
  88. },
  89. 'incorrect-type': ({
  90. expectedType,
  91. paramName,
  92. moduleName,
  93. className,
  94. funcName
  95. }) => {
  96. if (!expectedType || !paramName || !moduleName || !funcName) {
  97. throw new Error(`Unexpected input to 'incorrect-type' error.`);
  98. }
  99. const classNameStr = className ? `${className}.` : '';
  100. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`;
  101. },
  102. 'incorrect-class': ({
  103. expectedClassName,
  104. paramName,
  105. moduleName,
  106. className,
  107. funcName,
  108. isReturnValueProblem
  109. }) => {
  110. if (!expectedClassName || !moduleName || !funcName) {
  111. throw new Error(`Unexpected input to 'incorrect-class' error.`);
  112. }
  113. const classNameStr = className ? `${className}.` : '';
  114. if (isReturnValueProblem) {
  115. return `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
  116. }
  117. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
  118. },
  119. 'missing-a-method': ({
  120. expectedMethod,
  121. paramName,
  122. moduleName,
  123. className,
  124. funcName
  125. }) => {
  126. if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
  127. throw new Error(`Unexpected input to 'missing-a-method' error.`);
  128. }
  129. return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
  130. },
  131. 'add-to-cache-list-unexpected-type': ({
  132. entry
  133. }) => {
  134. 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.`;
  135. },
  136. 'add-to-cache-list-conflicting-entries': ({
  137. firstEntry,
  138. secondEntry
  139. }) => {
  140. if (!firstEntry || !secondEntry) {
  141. throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
  142. }
  143. 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.`;
  144. },
  145. 'plugin-error-request-will-fetch': ({
  146. thrownErrorMessage
  147. }) => {
  148. if (!thrownErrorMessage) {
  149. throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
  150. }
  151. return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownErrorMessage}'.`;
  152. },
  153. 'invalid-cache-name': ({
  154. cacheNameId,
  155. value
  156. }) => {
  157. if (!cacheNameId) {
  158. throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
  159. }
  160. return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`;
  161. },
  162. 'unregister-route-but-not-found-with-method': ({
  163. method
  164. }) => {
  165. if (!method) {
  166. throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`);
  167. }
  168. return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`;
  169. },
  170. 'unregister-route-route-not-registered': () => {
  171. return `The route you're trying to unregister was not previously ` + `registered.`;
  172. },
  173. 'queue-replay-failed': ({
  174. name
  175. }) => {
  176. return `Replaying the background sync queue '${name}' failed.`;
  177. },
  178. 'duplicate-queue-name': ({
  179. name
  180. }) => {
  181. return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`;
  182. },
  183. 'expired-test-without-max-age': ({
  184. methodName,
  185. paramName
  186. }) => {
  187. return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
  188. },
  189. 'unsupported-route-type': ({
  190. moduleName,
  191. className,
  192. funcName,
  193. paramName
  194. }) => {
  195. return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`;
  196. },
  197. 'not-array-of-class': ({
  198. value,
  199. expectedClass,
  200. moduleName,
  201. className,
  202. funcName,
  203. paramName
  204. }) => {
  205. 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.`;
  206. },
  207. 'max-entries-or-age-required': ({
  208. moduleName,
  209. className,
  210. funcName
  211. }) => {
  212. return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`;
  213. },
  214. 'statuses-or-headers-required': ({
  215. moduleName,
  216. className,
  217. funcName
  218. }) => {
  219. return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`;
  220. },
  221. 'invalid-string': ({
  222. moduleName,
  223. funcName,
  224. paramName
  225. }) => {
  226. if (!paramName || !moduleName || !funcName) {
  227. throw new Error(`Unexpected input to 'invalid-string' error.`);
  228. }
  229. 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.`;
  230. },
  231. 'channel-name-required': () => {
  232. return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`;
  233. },
  234. 'invalid-responses-are-same-args': () => {
  235. return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`;
  236. },
  237. 'expire-custom-caches-only': () => {
  238. return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`;
  239. },
  240. 'unit-must-be-bytes': ({
  241. normalizedRangeHeader
  242. }) => {
  243. if (!normalizedRangeHeader) {
  244. throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
  245. }
  246. return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`;
  247. },
  248. 'single-range-only': ({
  249. normalizedRangeHeader
  250. }) => {
  251. if (!normalizedRangeHeader) {
  252. throw new Error(`Unexpected input to 'single-range-only' error.`);
  253. }
  254. return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`;
  255. },
  256. 'invalid-range-values': ({
  257. normalizedRangeHeader
  258. }) => {
  259. if (!normalizedRangeHeader) {
  260. throw new Error(`Unexpected input to 'invalid-range-values' error.`);
  261. }
  262. 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}"`;
  263. },
  264. 'no-range-header': () => {
  265. return `No Range header was found in the Request provided.`;
  266. },
  267. 'range-not-satisfiable': ({
  268. size,
  269. start,
  270. end
  271. }) => {
  272. return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
  273. },
  274. 'attempt-to-cache-non-get-request': ({
  275. url,
  276. method
  277. }) => {
  278. return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`;
  279. },
  280. 'cache-put-with-no-response': ({
  281. url
  282. }) => {
  283. return `There was an attempt to cache '${url}' but the response was not ` + `defined.`;
  284. },
  285. 'no-response': ({
  286. url,
  287. error
  288. }) => {
  289. let message = `The strategy could not generate a response for '${url}'.`;
  290. if (error) {
  291. message += ` The underlying error is ${error}.`;
  292. }
  293. return message;
  294. },
  295. 'bad-precaching-response': ({
  296. url,
  297. status
  298. }) => {
  299. return `The precaching request for '${url}' failed` + (status ? ` with an HTTP status of ${status}.` : `.`);
  300. },
  301. 'non-precached-url': ({
  302. url
  303. }) => {
  304. return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`;
  305. },
  306. 'add-to-cache-list-conflicting-integrities': ({
  307. url
  308. }) => {
  309. return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`;
  310. },
  311. 'missing-precache-entry': ({
  312. cacheName,
  313. url
  314. }) => {
  315. return `Unable to find a precached response in ${cacheName} for ${url}.`;
  316. },
  317. 'cross-origin-copy-response': ({
  318. origin
  319. }) => {
  320. return `workbox-core.copyResponse() can only be used with same-origin ` + `responses. It was passed a response with origin ${origin}.`;
  321. },
  322. 'opaque-streams-source': ({
  323. type
  324. }) => {
  325. const message = `One of the workbox-streams sources resulted in an ` + `'${type}' response.`;
  326. if (type === 'opaqueredirect') {
  327. return `${message} Please do not use a navigation request that results ` + `in a redirect as a source.`;
  328. }
  329. return `${message} Please ensure your sources are CORS-enabled.`;
  330. }
  331. };
  332. /*
  333. Copyright 2018 Google LLC
  334. Use of this source code is governed by an MIT-style
  335. license that can be found in the LICENSE file or at
  336. https://opensource.org/licenses/MIT.
  337. */
  338. const generatorFunction = (code, details = {}) => {
  339. const message = messages$1[code];
  340. if (!message) {
  341. throw new Error(`Unable to find message for code '${code}'.`);
  342. }
  343. return message(details);
  344. };
  345. const messageGenerator = generatorFunction;
  346. /*
  347. Copyright 2018 Google LLC
  348. Use of this source code is governed by an MIT-style
  349. license that can be found in the LICENSE file or at
  350. https://opensource.org/licenses/MIT.
  351. */
  352. /**
  353. * Workbox errors should be thrown with this class.
  354. * This allows use to ensure the type easily in tests,
  355. * helps developers identify errors from workbox
  356. * easily and allows use to optimise error
  357. * messages correctly.
  358. *
  359. * @private
  360. */
  361. class WorkboxError extends Error {
  362. /**
  363. *
  364. * @param {string} errorCode The error code that
  365. * identifies this particular error.
  366. * @param {Object=} details Any relevant arguments
  367. * that will help developers identify issues should
  368. * be added as a key on the context object.
  369. */
  370. constructor(errorCode, details) {
  371. const message = messageGenerator(errorCode, details);
  372. super(message);
  373. this.name = errorCode;
  374. this.details = details;
  375. }
  376. }
  377. /*
  378. Copyright 2018 Google LLC
  379. Use of this source code is governed by an MIT-style
  380. license that can be found in the LICENSE file or at
  381. https://opensource.org/licenses/MIT.
  382. */
  383. /*
  384. * This method throws if the supplied value is not an array.
  385. * The destructed values are required to produce a meaningful error for users.
  386. * The destructed and restructured object is so it's clear what is
  387. * needed.
  388. */
  389. const isArray = (value, details) => {
  390. if (!Array.isArray(value)) {
  391. throw new WorkboxError('not-an-array', details);
  392. }
  393. };
  394. const hasMethod = (object, expectedMethod, details) => {
  395. const type = typeof object[expectedMethod];
  396. if (type !== 'function') {
  397. details['expectedMethod'] = expectedMethod;
  398. throw new WorkboxError('missing-a-method', details);
  399. }
  400. };
  401. const isType = (object, expectedType, details) => {
  402. if (typeof object !== expectedType) {
  403. details['expectedType'] = expectedType;
  404. throw new WorkboxError('incorrect-type', details);
  405. }
  406. };
  407. const isInstance = (object,
  408. // Need the general type to do the check later.
  409. // eslint-disable-next-line @typescript-eslint/ban-types
  410. expectedClass, details) => {
  411. if (!(object instanceof expectedClass)) {
  412. details['expectedClassName'] = expectedClass.name;
  413. throw new WorkboxError('incorrect-class', details);
  414. }
  415. };
  416. const isOneOf = (value, validValues, details) => {
  417. if (!validValues.includes(value)) {
  418. details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`;
  419. throw new WorkboxError('invalid-value', details);
  420. }
  421. };
  422. const isArrayOfClass = (value,
  423. // Need general type to do check later.
  424. expectedClass,
  425. // eslint-disable-line
  426. details) => {
  427. const error = new WorkboxError('not-array-of-class', details);
  428. if (!Array.isArray(value)) {
  429. throw error;
  430. }
  431. for (const item of value) {
  432. if (!(item instanceof expectedClass)) {
  433. throw error;
  434. }
  435. }
  436. };
  437. const finalAssertExports = {
  438. hasMethod,
  439. isArray,
  440. isInstance,
  441. isOneOf,
  442. isType,
  443. isArrayOfClass
  444. };
  445. // @ts-ignore
  446. try {
  447. self['workbox:routing:7.0.0'] && _();
  448. } catch (e) {}
  449. /*
  450. Copyright 2018 Google LLC
  451. Use of this source code is governed by an MIT-style
  452. license that can be found in the LICENSE file or at
  453. https://opensource.org/licenses/MIT.
  454. */
  455. /**
  456. * The default HTTP method, 'GET', used when there's no specific method
  457. * configured for a route.
  458. *
  459. * @type {string}
  460. *
  461. * @private
  462. */
  463. const defaultMethod = 'GET';
  464. /**
  465. * The list of valid HTTP methods associated with requests that could be routed.
  466. *
  467. * @type {Array<string>}
  468. *
  469. * @private
  470. */
  471. const validMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT'];
  472. /*
  473. Copyright 2018 Google LLC
  474. Use of this source code is governed by an MIT-style
  475. license that can be found in the LICENSE file or at
  476. https://opensource.org/licenses/MIT.
  477. */
  478. /**
  479. * @param {function()|Object} handler Either a function, or an object with a
  480. * 'handle' method.
  481. * @return {Object} An object with a handle method.
  482. *
  483. * @private
  484. */
  485. const normalizeHandler = handler => {
  486. if (handler && typeof handler === 'object') {
  487. {
  488. finalAssertExports.hasMethod(handler, 'handle', {
  489. moduleName: 'workbox-routing',
  490. className: 'Route',
  491. funcName: 'constructor',
  492. paramName: 'handler'
  493. });
  494. }
  495. return handler;
  496. } else {
  497. {
  498. finalAssertExports.isType(handler, 'function', {
  499. moduleName: 'workbox-routing',
  500. className: 'Route',
  501. funcName: 'constructor',
  502. paramName: 'handler'
  503. });
  504. }
  505. return {
  506. handle: handler
  507. };
  508. }
  509. };
  510. /*
  511. Copyright 2018 Google LLC
  512. Use of this source code is governed by an MIT-style
  513. license that can be found in the LICENSE file or at
  514. https://opensource.org/licenses/MIT.
  515. */
  516. /**
  517. * A `Route` consists of a pair of callback functions, "match" and "handler".
  518. * The "match" callback determine if a route should be used to "handle" a
  519. * request by returning a non-falsy value if it can. The "handler" callback
  520. * is called when there is a match and should return a Promise that resolves
  521. * to a `Response`.
  522. *
  523. * @memberof workbox-routing
  524. */
  525. class Route {
  526. /**
  527. * Constructor for Route class.
  528. *
  529. * @param {workbox-routing~matchCallback} match
  530. * A callback function that determines whether the route matches a given
  531. * `fetch` event by returning a non-falsy value.
  532. * @param {workbox-routing~handlerCallback} handler A callback
  533. * function that returns a Promise resolving to a Response.
  534. * @param {string} [method='GET'] The HTTP method to match the Route
  535. * against.
  536. */
  537. constructor(match, handler, method = defaultMethod) {
  538. {
  539. finalAssertExports.isType(match, 'function', {
  540. moduleName: 'workbox-routing',
  541. className: 'Route',
  542. funcName: 'constructor',
  543. paramName: 'match'
  544. });
  545. if (method) {
  546. finalAssertExports.isOneOf(method, validMethods, {
  547. paramName: 'method'
  548. });
  549. }
  550. }
  551. // These values are referenced directly by Router so cannot be
  552. // altered by minificaton.
  553. this.handler = normalizeHandler(handler);
  554. this.match = match;
  555. this.method = method;
  556. }
  557. /**
  558. *
  559. * @param {workbox-routing-handlerCallback} handler A callback
  560. * function that returns a Promise resolving to a Response
  561. */
  562. setCatchHandler(handler) {
  563. this.catchHandler = normalizeHandler(handler);
  564. }
  565. }
  566. /*
  567. Copyright 2018 Google LLC
  568. Use of this source code is governed by an MIT-style
  569. license that can be found in the LICENSE file or at
  570. https://opensource.org/licenses/MIT.
  571. */
  572. /**
  573. * RegExpRoute makes it easy to create a regular expression based
  574. * {@link workbox-routing.Route}.
  575. *
  576. * For same-origin requests the RegExp only needs to match part of the URL. For
  577. * requests against third-party servers, you must define a RegExp that matches
  578. * the start of the URL.
  579. *
  580. * @memberof workbox-routing
  581. * @extends workbox-routing.Route
  582. */
  583. class RegExpRoute extends Route {
  584. /**
  585. * If the regular expression contains
  586. * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},
  587. * the captured values will be passed to the
  588. * {@link workbox-routing~handlerCallback} `params`
  589. * argument.
  590. *
  591. * @param {RegExp} regExp The regular expression to match against URLs.
  592. * @param {workbox-routing~handlerCallback} handler A callback
  593. * function that returns a Promise resulting in a Response.
  594. * @param {string} [method='GET'] The HTTP method to match the Route
  595. * against.
  596. */
  597. constructor(regExp, handler, method) {
  598. {
  599. finalAssertExports.isInstance(regExp, RegExp, {
  600. moduleName: 'workbox-routing',
  601. className: 'RegExpRoute',
  602. funcName: 'constructor',
  603. paramName: 'pattern'
  604. });
  605. }
  606. const match = ({
  607. url
  608. }) => {
  609. const result = regExp.exec(url.href);
  610. // Return immediately if there's no match.
  611. if (!result) {
  612. return;
  613. }
  614. // Require that the match start at the first character in the URL string
  615. // if it's a cross-origin request.
  616. // See https://github.com/GoogleChrome/workbox/issues/281 for the context
  617. // behind this behavior.
  618. if (url.origin !== location.origin && result.index !== 0) {
  619. {
  620. 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.`);
  621. }
  622. return;
  623. }
  624. // If the route matches, but there aren't any capture groups defined, then
  625. // this will return [], which is truthy and therefore sufficient to
  626. // indicate a match.
  627. // If there are capture groups, then it will return their values.
  628. return result.slice(1);
  629. };
  630. super(match, handler, method);
  631. }
  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. const getFriendlyURL = url => {
  640. const urlObj = new URL(String(url), location.href);
  641. // See https://github.com/GoogleChrome/workbox/issues/2323
  642. // We want to include everything, except for the origin if it's same-origin.
  643. return urlObj.href.replace(new RegExp(`^${location.origin}`), '');
  644. };
  645. /*
  646. Copyright 2018 Google LLC
  647. Use of this source code is governed by an MIT-style
  648. license that can be found in the LICENSE file or at
  649. https://opensource.org/licenses/MIT.
  650. */
  651. /**
  652. * The Router can be used to process a `FetchEvent` using one or more
  653. * {@link workbox-routing.Route}, responding with a `Response` if
  654. * a matching route exists.
  655. *
  656. * If no route matches a given a request, the Router will use a "default"
  657. * handler if one is defined.
  658. *
  659. * Should the matching Route throw an error, the Router will use a "catch"
  660. * handler if one is defined to gracefully deal with issues and respond with a
  661. * Request.
  662. *
  663. * If a request matches multiple routes, the **earliest** registered route will
  664. * be used to respond to the request.
  665. *
  666. * @memberof workbox-routing
  667. */
  668. class Router {
  669. /**
  670. * Initializes a new Router.
  671. */
  672. constructor() {
  673. this._routes = new Map();
  674. this._defaultHandlerMap = new Map();
  675. }
  676. /**
  677. * @return {Map<string, Array<workbox-routing.Route>>} routes A `Map` of HTTP
  678. * method name ('GET', etc.) to an array of all the corresponding `Route`
  679. * instances that are registered.
  680. */
  681. get routes() {
  682. return this._routes;
  683. }
  684. /**
  685. * Adds a fetch event listener to respond to events when a route matches
  686. * the event's request.
  687. */
  688. addFetchListener() {
  689. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  690. self.addEventListener('fetch', event => {
  691. const {
  692. request
  693. } = event;
  694. const responsePromise = this.handleRequest({
  695. request,
  696. event
  697. });
  698. if (responsePromise) {
  699. event.respondWith(responsePromise);
  700. }
  701. });
  702. }
  703. /**
  704. * Adds a message event listener for URLs to cache from the window.
  705. * This is useful to cache resources loaded on the page prior to when the
  706. * service worker started controlling it.
  707. *
  708. * The format of the message data sent from the window should be as follows.
  709. * Where the `urlsToCache` array may consist of URL strings or an array of
  710. * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
  711. *
  712. * ```
  713. * {
  714. * type: 'CACHE_URLS',
  715. * payload: {
  716. * urlsToCache: [
  717. * './script1.js',
  718. * './script2.js',
  719. * ['./script3.js', {mode: 'no-cors'}],
  720. * ],
  721. * },
  722. * }
  723. * ```
  724. */
  725. addCacheListener() {
  726. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  727. self.addEventListener('message', event => {
  728. // event.data is type 'any'
  729. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  730. if (event.data && event.data.type === 'CACHE_URLS') {
  731. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  732. const {
  733. payload
  734. } = event.data;
  735. {
  736. logger.debug(`Caching URLs from the window`, payload.urlsToCache);
  737. }
  738. const requestPromises = Promise.all(payload.urlsToCache.map(entry => {
  739. if (typeof entry === 'string') {
  740. entry = [entry];
  741. }
  742. const request = new Request(...entry);
  743. return this.handleRequest({
  744. request,
  745. event
  746. });
  747. // TODO(philipwalton): TypeScript errors without this typecast for
  748. // some reason (probably a bug). The real type here should work but
  749. // doesn't: `Array<Promise<Response> | undefined>`.
  750. })); // TypeScript
  751. event.waitUntil(requestPromises);
  752. // If a MessageChannel was used, reply to the message on success.
  753. if (event.ports && event.ports[0]) {
  754. void requestPromises.then(() => event.ports[0].postMessage(true));
  755. }
  756. }
  757. });
  758. }
  759. /**
  760. * Apply the routing rules to a FetchEvent object to get a Response from an
  761. * appropriate Route's handler.
  762. *
  763. * @param {Object} options
  764. * @param {Request} options.request The request to handle.
  765. * @param {ExtendableEvent} options.event The event that triggered the
  766. * request.
  767. * @return {Promise<Response>|undefined} A promise is returned if a
  768. * registered route can handle the request. If there is no matching
  769. * route and there's no `defaultHandler`, `undefined` is returned.
  770. */
  771. handleRequest({
  772. request,
  773. event
  774. }) {
  775. {
  776. finalAssertExports.isInstance(request, Request, {
  777. moduleName: 'workbox-routing',
  778. className: 'Router',
  779. funcName: 'handleRequest',
  780. paramName: 'options.request'
  781. });
  782. }
  783. const url = new URL(request.url, location.href);
  784. if (!url.protocol.startsWith('http')) {
  785. {
  786. logger.debug(`Workbox Router only supports URLs that start with 'http'.`);
  787. }
  788. return;
  789. }
  790. const sameOrigin = url.origin === location.origin;
  791. const {
  792. params,
  793. route
  794. } = this.findMatchingRoute({
  795. event,
  796. request,
  797. sameOrigin,
  798. url
  799. });
  800. let handler = route && route.handler;
  801. const debugMessages = [];
  802. {
  803. if (handler) {
  804. debugMessages.push([`Found a route to handle this request:`, route]);
  805. if (params) {
  806. debugMessages.push([`Passing the following params to the route's handler:`, params]);
  807. }
  808. }
  809. }
  810. // If we don't have a handler because there was no matching route, then
  811. // fall back to defaultHandler if that's defined.
  812. const method = request.method;
  813. if (!handler && this._defaultHandlerMap.has(method)) {
  814. {
  815. debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler for ${method}.`);
  816. }
  817. handler = this._defaultHandlerMap.get(method);
  818. }
  819. if (!handler) {
  820. {
  821. // No handler so Workbox will do nothing. If logs is set of debug
  822. // i.e. verbose, we should print out this information.
  823. logger.debug(`No route found for: ${getFriendlyURL(url)}`);
  824. }
  825. return;
  826. }
  827. {
  828. // We have a handler, meaning Workbox is going to handle the route.
  829. // print the routing details to the console.
  830. logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
  831. debugMessages.forEach(msg => {
  832. if (Array.isArray(msg)) {
  833. logger.log(...msg);
  834. } else {
  835. logger.log(msg);
  836. }
  837. });
  838. logger.groupEnd();
  839. }
  840. // Wrap in try and catch in case the handle method throws a synchronous
  841. // error. It should still callback to the catch handler.
  842. let responsePromise;
  843. try {
  844. responsePromise = handler.handle({
  845. url,
  846. request,
  847. event,
  848. params
  849. });
  850. } catch (err) {
  851. responsePromise = Promise.reject(err);
  852. }
  853. // Get route's catch handler, if it exists
  854. const catchHandler = route && route.catchHandler;
  855. if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
  856. responsePromise = responsePromise.catch(async err => {
  857. // If there's a route catch handler, process that first
  858. if (catchHandler) {
  859. {
  860. // Still include URL here as it will be async from the console group
  861. // and may not make sense without the URL
  862. logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
  863. logger.error(`Error thrown by:`, route);
  864. logger.error(err);
  865. logger.groupEnd();
  866. }
  867. try {
  868. return await catchHandler.handle({
  869. url,
  870. request,
  871. event,
  872. params
  873. });
  874. } catch (catchErr) {
  875. if (catchErr instanceof Error) {
  876. err = catchErr;
  877. }
  878. }
  879. }
  880. if (this._catchHandler) {
  881. {
  882. // Still include URL here as it will be async from the console group
  883. // and may not make sense without the URL
  884. logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
  885. logger.error(`Error thrown by:`, route);
  886. logger.error(err);
  887. logger.groupEnd();
  888. }
  889. return this._catchHandler.handle({
  890. url,
  891. request,
  892. event
  893. });
  894. }
  895. throw err;
  896. });
  897. }
  898. return responsePromise;
  899. }
  900. /**
  901. * Checks a request and URL (and optionally an event) against the list of
  902. * registered routes, and if there's a match, returns the corresponding
  903. * route along with any params generated by the match.
  904. *
  905. * @param {Object} options
  906. * @param {URL} options.url
  907. * @param {boolean} options.sameOrigin The result of comparing `url.origin`
  908. * against the current origin.
  909. * @param {Request} options.request The request to match.
  910. * @param {Event} options.event The corresponding event.
  911. * @return {Object} An object with `route` and `params` properties.
  912. * They are populated if a matching route was found or `undefined`
  913. * otherwise.
  914. */
  915. findMatchingRoute({
  916. url,
  917. sameOrigin,
  918. request,
  919. event
  920. }) {
  921. const routes = this._routes.get(request.method) || [];
  922. for (const route of routes) {
  923. let params;
  924. // route.match returns type any, not possible to change right now.
  925. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  926. const matchResult = route.match({
  927. url,
  928. sameOrigin,
  929. request,
  930. event
  931. });
  932. if (matchResult) {
  933. {
  934. // Warn developers that using an async matchCallback is almost always
  935. // not the right thing to do.
  936. if (matchResult instanceof Promise) {
  937. logger.warn(`While routing ${getFriendlyURL(url)}, an async ` + `matchCallback function was used. Please convert the ` + `following route to use a synchronous matchCallback function:`, route);
  938. }
  939. }
  940. // See https://github.com/GoogleChrome/workbox/issues/2079
  941. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  942. params = matchResult;
  943. if (Array.isArray(params) && params.length === 0) {
  944. // Instead of passing an empty array in as params, use undefined.
  945. params = undefined;
  946. } else if (matchResult.constructor === Object &&
  947. // eslint-disable-line
  948. Object.keys(matchResult).length === 0) {
  949. // Instead of passing an empty object in as params, use undefined.
  950. params = undefined;
  951. } else if (typeof matchResult === 'boolean') {
  952. // For the boolean value true (rather than just something truth-y),
  953. // don't set params.
  954. // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
  955. params = undefined;
  956. }
  957. // Return early if have a match.
  958. return {
  959. route,
  960. params
  961. };
  962. }
  963. }
  964. // If no match was found above, return and empty object.
  965. return {};
  966. }
  967. /**
  968. * Define a default `handler` that's called when no routes explicitly
  969. * match the incoming request.
  970. *
  971. * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
  972. *
  973. * Without a default handler, unmatched requests will go against the
  974. * network as if there were no service worker present.
  975. *
  976. * @param {workbox-routing~handlerCallback} handler A callback
  977. * function that returns a Promise resulting in a Response.
  978. * @param {string} [method='GET'] The HTTP method to associate with this
  979. * default handler. Each method has its own default.
  980. */
  981. setDefaultHandler(handler, method = defaultMethod) {
  982. this._defaultHandlerMap.set(method, normalizeHandler(handler));
  983. }
  984. /**
  985. * If a Route throws an error while handling a request, this `handler`
  986. * will be called and given a chance to provide a response.
  987. *
  988. * @param {workbox-routing~handlerCallback} handler A callback
  989. * function that returns a Promise resulting in a Response.
  990. */
  991. setCatchHandler(handler) {
  992. this._catchHandler = normalizeHandler(handler);
  993. }
  994. /**
  995. * Registers a route with the router.
  996. *
  997. * @param {workbox-routing.Route} route The route to register.
  998. */
  999. registerRoute(route) {
  1000. {
  1001. finalAssertExports.isType(route, 'object', {
  1002. moduleName: 'workbox-routing',
  1003. className: 'Router',
  1004. funcName: 'registerRoute',
  1005. paramName: 'route'
  1006. });
  1007. finalAssertExports.hasMethod(route, 'match', {
  1008. moduleName: 'workbox-routing',
  1009. className: 'Router',
  1010. funcName: 'registerRoute',
  1011. paramName: 'route'
  1012. });
  1013. finalAssertExports.isType(route.handler, 'object', {
  1014. moduleName: 'workbox-routing',
  1015. className: 'Router',
  1016. funcName: 'registerRoute',
  1017. paramName: 'route'
  1018. });
  1019. finalAssertExports.hasMethod(route.handler, 'handle', {
  1020. moduleName: 'workbox-routing',
  1021. className: 'Router',
  1022. funcName: 'registerRoute',
  1023. paramName: 'route.handler'
  1024. });
  1025. finalAssertExports.isType(route.method, 'string', {
  1026. moduleName: 'workbox-routing',
  1027. className: 'Router',
  1028. funcName: 'registerRoute',
  1029. paramName: 'route.method'
  1030. });
  1031. }
  1032. if (!this._routes.has(route.method)) {
  1033. this._routes.set(route.method, []);
  1034. }
  1035. // Give precedence to all of the earlier routes by adding this additional
  1036. // route to the end of the array.
  1037. this._routes.get(route.method).push(route);
  1038. }
  1039. /**
  1040. * Unregisters a route with the router.
  1041. *
  1042. * @param {workbox-routing.Route} route The route to unregister.
  1043. */
  1044. unregisterRoute(route) {
  1045. if (!this._routes.has(route.method)) {
  1046. throw new WorkboxError('unregister-route-but-not-found-with-method', {
  1047. method: route.method
  1048. });
  1049. }
  1050. const routeIndex = this._routes.get(route.method).indexOf(route);
  1051. if (routeIndex > -1) {
  1052. this._routes.get(route.method).splice(routeIndex, 1);
  1053. } else {
  1054. throw new WorkboxError('unregister-route-route-not-registered');
  1055. }
  1056. }
  1057. }
  1058. /*
  1059. Copyright 2019 Google LLC
  1060. Use of this source code is governed by an MIT-style
  1061. license that can be found in the LICENSE file or at
  1062. https://opensource.org/licenses/MIT.
  1063. */
  1064. let defaultRouter;
  1065. /**
  1066. * Creates a new, singleton Router instance if one does not exist. If one
  1067. * does already exist, that instance is returned.
  1068. *
  1069. * @private
  1070. * @return {Router}
  1071. */
  1072. const getOrCreateDefaultRouter = () => {
  1073. if (!defaultRouter) {
  1074. defaultRouter = new Router();
  1075. // The helpers that use the default Router assume these listeners exist.
  1076. defaultRouter.addFetchListener();
  1077. defaultRouter.addCacheListener();
  1078. }
  1079. return defaultRouter;
  1080. };
  1081. /*
  1082. Copyright 2019 Google LLC
  1083. Use of this source code is governed by an MIT-style
  1084. license that can be found in the LICENSE file or at
  1085. https://opensource.org/licenses/MIT.
  1086. */
  1087. /**
  1088. * Easily register a RegExp, string, or function with a caching
  1089. * strategy to a singleton Router instance.
  1090. *
  1091. * This method will generate a Route for you if needed and
  1092. * call {@link workbox-routing.Router#registerRoute}.
  1093. *
  1094. * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture
  1095. * If the capture param is a `Route`, all other arguments will be ignored.
  1096. * @param {workbox-routing~handlerCallback} [handler] A callback
  1097. * function that returns a Promise resulting in a Response. This parameter
  1098. * is required if `capture` is not a `Route` object.
  1099. * @param {string} [method='GET'] The HTTP method to match the Route
  1100. * against.
  1101. * @return {workbox-routing.Route} The generated `Route`.
  1102. *
  1103. * @memberof workbox-routing
  1104. */
  1105. function registerRoute(capture, handler, method) {
  1106. let route;
  1107. if (typeof capture === 'string') {
  1108. const captureUrl = new URL(capture, location.href);
  1109. {
  1110. if (!(capture.startsWith('/') || capture.startsWith('http'))) {
  1111. throw new WorkboxError('invalid-string', {
  1112. moduleName: 'workbox-routing',
  1113. funcName: 'registerRoute',
  1114. paramName: 'capture'
  1115. });
  1116. }
  1117. // We want to check if Express-style wildcards are in the pathname only.
  1118. // TODO: Remove this log message in v4.
  1119. const valueToCheck = capture.startsWith('http') ? captureUrl.pathname : capture;
  1120. // See https://github.com/pillarjs/path-to-regexp#parameters
  1121. const wildcards = '[*:?+]';
  1122. if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
  1123. 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.`);
  1124. }
  1125. }
  1126. const matchCallback = ({
  1127. url
  1128. }) => {
  1129. {
  1130. if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
  1131. 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.`);
  1132. }
  1133. }
  1134. return url.href === captureUrl.href;
  1135. };
  1136. // If `capture` is a string then `handler` and `method` must be present.
  1137. route = new Route(matchCallback, handler, method);
  1138. } else if (capture instanceof RegExp) {
  1139. // If `capture` is a `RegExp` then `handler` and `method` must be present.
  1140. route = new RegExpRoute(capture, handler, method);
  1141. } else if (typeof capture === 'function') {
  1142. // If `capture` is a function then `handler` and `method` must be present.
  1143. route = new Route(capture, handler, method);
  1144. } else if (capture instanceof Route) {
  1145. route = capture;
  1146. } else {
  1147. throw new WorkboxError('unsupported-route-type', {
  1148. moduleName: 'workbox-routing',
  1149. funcName: 'registerRoute',
  1150. paramName: 'capture'
  1151. });
  1152. }
  1153. const defaultRouter = getOrCreateDefaultRouter();
  1154. defaultRouter.registerRoute(route);
  1155. return route;
  1156. }
  1157. /*
  1158. Copyright 2019 Google LLC
  1159. Use of this source code is governed by an MIT-style
  1160. license that can be found in the LICENSE file or at
  1161. https://opensource.org/licenses/MIT.
  1162. */
  1163. /**
  1164. * Returns a promise that resolves and the passed number of milliseconds.
  1165. * This utility is an async/await-friendly version of `setTimeout`.
  1166. *
  1167. * @param {number} ms
  1168. * @return {Promise}
  1169. * @private
  1170. */
  1171. function timeout(ms) {
  1172. return new Promise(resolve => setTimeout(resolve, ms));
  1173. }
  1174. /*
  1175. Copyright 2018 Google LLC
  1176. Use of this source code is governed by an MIT-style
  1177. license that can be found in the LICENSE file or at
  1178. https://opensource.org/licenses/MIT.
  1179. */
  1180. const _cacheNameDetails = {
  1181. googleAnalytics: 'googleAnalytics',
  1182. precache: 'precache-v2',
  1183. prefix: 'workbox',
  1184. runtime: 'runtime',
  1185. suffix: typeof registration !== 'undefined' ? registration.scope : ''
  1186. };
  1187. const _createCacheName = cacheName => {
  1188. return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter(value => value && value.length > 0).join('-');
  1189. };
  1190. const eachCacheNameDetail = fn => {
  1191. for (const key of Object.keys(_cacheNameDetails)) {
  1192. fn(key);
  1193. }
  1194. };
  1195. const cacheNames = {
  1196. updateDetails: details => {
  1197. eachCacheNameDetail(key => {
  1198. if (typeof details[key] === 'string') {
  1199. _cacheNameDetails[key] = details[key];
  1200. }
  1201. });
  1202. },
  1203. getGoogleAnalyticsName: userCacheName => {
  1204. return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
  1205. },
  1206. getPrecacheName: userCacheName => {
  1207. return userCacheName || _createCacheName(_cacheNameDetails.precache);
  1208. },
  1209. getPrefix: () => {
  1210. return _cacheNameDetails.prefix;
  1211. },
  1212. getRuntimeName: userCacheName => {
  1213. return userCacheName || _createCacheName(_cacheNameDetails.runtime);
  1214. },
  1215. getSuffix: () => {
  1216. return _cacheNameDetails.suffix;
  1217. }
  1218. };
  1219. /*
  1220. Copyright 2020 Google LLC
  1221. Use of this source code is governed by an MIT-style
  1222. license that can be found in the LICENSE file or at
  1223. https://opensource.org/licenses/MIT.
  1224. */
  1225. function stripParams(fullURL, ignoreParams) {
  1226. const strippedURL = new URL(fullURL);
  1227. for (const param of ignoreParams) {
  1228. strippedURL.searchParams.delete(param);
  1229. }
  1230. return strippedURL.href;
  1231. }
  1232. /**
  1233. * Matches an item in the cache, ignoring specific URL params. This is similar
  1234. * to the `ignoreSearch` option, but it allows you to ignore just specific
  1235. * params (while continuing to match on the others).
  1236. *
  1237. * @private
  1238. * @param {Cache} cache
  1239. * @param {Request} request
  1240. * @param {Object} matchOptions
  1241. * @param {Array<string>} ignoreParams
  1242. * @return {Promise<Response|undefined>}
  1243. */
  1244. async function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {
  1245. const strippedRequestURL = stripParams(request.url, ignoreParams);
  1246. // If the request doesn't include any ignored params, match as normal.
  1247. if (request.url === strippedRequestURL) {
  1248. return cache.match(request, matchOptions);
  1249. }
  1250. // Otherwise, match by comparing keys
  1251. const keysOptions = Object.assign(Object.assign({}, matchOptions), {
  1252. ignoreSearch: true
  1253. });
  1254. const cacheKeys = await cache.keys(request, keysOptions);
  1255. for (const cacheKey of cacheKeys) {
  1256. const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);
  1257. if (strippedRequestURL === strippedCacheKeyURL) {
  1258. return cache.match(cacheKey, matchOptions);
  1259. }
  1260. }
  1261. return;
  1262. }
  1263. /*
  1264. Copyright 2018 Google LLC
  1265. Use of this source code is governed by an MIT-style
  1266. license that can be found in the LICENSE file or at
  1267. https://opensource.org/licenses/MIT.
  1268. */
  1269. /**
  1270. * The Deferred class composes Promises in a way that allows for them to be
  1271. * resolved or rejected from outside the constructor. In most cases promises
  1272. * should be used directly, but Deferreds can be necessary when the logic to
  1273. * resolve a promise must be separate.
  1274. *
  1275. * @private
  1276. */
  1277. class Deferred {
  1278. /**
  1279. * Creates a promise and exposes its resolve and reject functions as methods.
  1280. */
  1281. constructor() {
  1282. this.promise = new Promise((resolve, reject) => {
  1283. this.resolve = resolve;
  1284. this.reject = reject;
  1285. });
  1286. }
  1287. }
  1288. /*
  1289. Copyright 2018 Google LLC
  1290. Use of this source code is governed by an MIT-style
  1291. license that can be found in the LICENSE file or at
  1292. https://opensource.org/licenses/MIT.
  1293. */
  1294. // Callbacks to be executed whenever there's a quota error.
  1295. // Can't change Function type right now.
  1296. // eslint-disable-next-line @typescript-eslint/ban-types
  1297. const quotaErrorCallbacks = new Set();
  1298. /*
  1299. Copyright 2018 Google LLC
  1300. Use of this source code is governed by an MIT-style
  1301. license that can be found in the LICENSE file or at
  1302. https://opensource.org/licenses/MIT.
  1303. */
  1304. /**
  1305. * Runs all of the callback functions, one at a time sequentially, in the order
  1306. * in which they were registered.
  1307. *
  1308. * @memberof workbox-core
  1309. * @private
  1310. */
  1311. async function executeQuotaErrorCallbacks() {
  1312. {
  1313. logger.log(`About to run ${quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`);
  1314. }
  1315. for (const callback of quotaErrorCallbacks) {
  1316. await callback();
  1317. {
  1318. logger.log(callback, 'is complete.');
  1319. }
  1320. }
  1321. {
  1322. logger.log('Finished running callbacks.');
  1323. }
  1324. }
  1325. // @ts-ignore
  1326. try {
  1327. self['workbox:strategies:7.0.0'] && _();
  1328. } catch (e) {}
  1329. /*
  1330. Copyright 2020 Google LLC
  1331. Use of this source code is governed by an MIT-style
  1332. license that can be found in the LICENSE file or at
  1333. https://opensource.org/licenses/MIT.
  1334. */
  1335. function toRequest(input) {
  1336. return typeof input === 'string' ? new Request(input) : input;
  1337. }
  1338. /**
  1339. * A class created every time a Strategy instance instance calls
  1340. * {@link workbox-strategies.Strategy~handle} or
  1341. * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and
  1342. * cache actions around plugin callbacks and keeps track of when the strategy
  1343. * is "done" (i.e. all added `event.waitUntil()` promises have resolved).
  1344. *
  1345. * @memberof workbox-strategies
  1346. */
  1347. class StrategyHandler {
  1348. /**
  1349. * Creates a new instance associated with the passed strategy and event
  1350. * that's handling the request.
  1351. *
  1352. * The constructor also initializes the state that will be passed to each of
  1353. * the plugins handling this request.
  1354. *
  1355. * @param {workbox-strategies.Strategy} strategy
  1356. * @param {Object} options
  1357. * @param {Request|string} options.request A request to run this strategy for.
  1358. * @param {ExtendableEvent} options.event The event associated with the
  1359. * request.
  1360. * @param {URL} [options.url]
  1361. * @param {*} [options.params] The return value from the
  1362. * {@link workbox-routing~matchCallback} (if applicable).
  1363. */
  1364. constructor(strategy, options) {
  1365. this._cacheKeys = {};
  1366. /**
  1367. * The request the strategy is performing (passed to the strategy's
  1368. * `handle()` or `handleAll()` method).
  1369. * @name request
  1370. * @instance
  1371. * @type {Request}
  1372. * @memberof workbox-strategies.StrategyHandler
  1373. */
  1374. /**
  1375. * The event associated with this request.
  1376. * @name event
  1377. * @instance
  1378. * @type {ExtendableEvent}
  1379. * @memberof workbox-strategies.StrategyHandler
  1380. */
  1381. /**
  1382. * A `URL` instance of `request.url` (if passed to the strategy's
  1383. * `handle()` or `handleAll()` method).
  1384. * Note: the `url` param will be present if the strategy was invoked
  1385. * from a workbox `Route` object.
  1386. * @name url
  1387. * @instance
  1388. * @type {URL|undefined}
  1389. * @memberof workbox-strategies.StrategyHandler
  1390. */
  1391. /**
  1392. * A `param` value (if passed to the strategy's
  1393. * `handle()` or `handleAll()` method).
  1394. * Note: the `param` param will be present if the strategy was invoked
  1395. * from a workbox `Route` object and the
  1396. * {@link workbox-routing~matchCallback} returned
  1397. * a truthy value (it will be that value).
  1398. * @name params
  1399. * @instance
  1400. * @type {*|undefined}
  1401. * @memberof workbox-strategies.StrategyHandler
  1402. */
  1403. {
  1404. finalAssertExports.isInstance(options.event, ExtendableEvent, {
  1405. moduleName: 'workbox-strategies',
  1406. className: 'StrategyHandler',
  1407. funcName: 'constructor',
  1408. paramName: 'options.event'
  1409. });
  1410. }
  1411. Object.assign(this, options);
  1412. this.event = options.event;
  1413. this._strategy = strategy;
  1414. this._handlerDeferred = new Deferred();
  1415. this._extendLifetimePromises = [];
  1416. // Copy the plugins list (since it's mutable on the strategy),
  1417. // so any mutations don't affect this handler instance.
  1418. this._plugins = [...strategy.plugins];
  1419. this._pluginStateMap = new Map();
  1420. for (const plugin of this._plugins) {
  1421. this._pluginStateMap.set(plugin, {});
  1422. }
  1423. this.event.waitUntil(this._handlerDeferred.promise);
  1424. }
  1425. /**
  1426. * Fetches a given request (and invokes any applicable plugin callback
  1427. * methods) using the `fetchOptions` (for non-navigation requests) and
  1428. * `plugins` defined on the `Strategy` object.
  1429. *
  1430. * The following plugin lifecycle methods are invoked when using this method:
  1431. * - `requestWillFetch()`
  1432. * - `fetchDidSucceed()`
  1433. * - `fetchDidFail()`
  1434. *
  1435. * @param {Request|string} input The URL or request to fetch.
  1436. * @return {Promise<Response>}
  1437. */
  1438. async fetch(input) {
  1439. const {
  1440. event
  1441. } = this;
  1442. let request = toRequest(input);
  1443. if (request.mode === 'navigate' && event instanceof FetchEvent && event.preloadResponse) {
  1444. const possiblePreloadResponse = await event.preloadResponse;
  1445. if (possiblePreloadResponse) {
  1446. {
  1447. logger.log(`Using a preloaded navigation response for ` + `'${getFriendlyURL(request.url)}'`);
  1448. }
  1449. return possiblePreloadResponse;
  1450. }
  1451. }
  1452. // If there is a fetchDidFail plugin, we need to save a clone of the
  1453. // original request before it's either modified by a requestWillFetch
  1454. // plugin or before the original request's body is consumed via fetch().
  1455. const originalRequest = this.hasCallback('fetchDidFail') ? request.clone() : null;
  1456. try {
  1457. for (const cb of this.iterateCallbacks('requestWillFetch')) {
  1458. request = await cb({
  1459. request: request.clone(),
  1460. event
  1461. });
  1462. }
  1463. } catch (err) {
  1464. if (err instanceof Error) {
  1465. throw new WorkboxError('plugin-error-request-will-fetch', {
  1466. thrownErrorMessage: err.message
  1467. });
  1468. }
  1469. }
  1470. // The request can be altered by plugins with `requestWillFetch` making
  1471. // the original request (most likely from a `fetch` event) different
  1472. // from the Request we make. Pass both to `fetchDidFail` to aid debugging.
  1473. const pluginFilteredRequest = request.clone();
  1474. try {
  1475. let fetchResponse;
  1476. // See https://github.com/GoogleChrome/workbox/issues/1796
  1477. fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions);
  1478. if ("development" !== 'production') {
  1479. logger.debug(`Network request for ` + `'${getFriendlyURL(request.url)}' returned a response with ` + `status '${fetchResponse.status}'.`);
  1480. }
  1481. for (const callback of this.iterateCallbacks('fetchDidSucceed')) {
  1482. fetchResponse = await callback({
  1483. event,
  1484. request: pluginFilteredRequest,
  1485. response: fetchResponse
  1486. });
  1487. }
  1488. return fetchResponse;
  1489. } catch (error) {
  1490. {
  1491. logger.log(`Network request for ` + `'${getFriendlyURL(request.url)}' threw an error.`, error);
  1492. }
  1493. // `originalRequest` will only exist if a `fetchDidFail` callback
  1494. // is being used (see above).
  1495. if (originalRequest) {
  1496. await this.runCallbacks('fetchDidFail', {
  1497. error: error,
  1498. event,
  1499. originalRequest: originalRequest.clone(),
  1500. request: pluginFilteredRequest.clone()
  1501. });
  1502. }
  1503. throw error;
  1504. }
  1505. }
  1506. /**
  1507. * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on
  1508. * the response generated by `this.fetch()`.
  1509. *
  1510. * The call to `this.cachePut()` automatically invokes `this.waitUntil()`,
  1511. * so you do not have to manually call `waitUntil()` on the event.
  1512. *
  1513. * @param {Request|string} input The request or URL to fetch and cache.
  1514. * @return {Promise<Response>}
  1515. */
  1516. async fetchAndCachePut(input) {
  1517. const response = await this.fetch(input);
  1518. const responseClone = response.clone();
  1519. void this.waitUntil(this.cachePut(input, responseClone));
  1520. return response;
  1521. }
  1522. /**
  1523. * Matches a request from the cache (and invokes any applicable plugin
  1524. * callback methods) using the `cacheName`, `matchOptions`, and `plugins`
  1525. * defined on the strategy object.
  1526. *
  1527. * The following plugin lifecycle methods are invoked when using this method:
  1528. * - cacheKeyWillByUsed()
  1529. * - cachedResponseWillByUsed()
  1530. *
  1531. * @param {Request|string} key The Request or URL to use as the cache key.
  1532. * @return {Promise<Response|undefined>} A matching response, if found.
  1533. */
  1534. async cacheMatch(key) {
  1535. const request = toRequest(key);
  1536. let cachedResponse;
  1537. const {
  1538. cacheName,
  1539. matchOptions
  1540. } = this._strategy;
  1541. const effectiveRequest = await this.getCacheKey(request, 'read');
  1542. const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), {
  1543. cacheName
  1544. });
  1545. cachedResponse = await caches.match(effectiveRequest, multiMatchOptions);
  1546. {
  1547. if (cachedResponse) {
  1548. logger.debug(`Found a cached response in '${cacheName}'.`);
  1549. } else {
  1550. logger.debug(`No cached response found in '${cacheName}'.`);
  1551. }
  1552. }
  1553. for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) {
  1554. cachedResponse = (await callback({
  1555. cacheName,
  1556. matchOptions,
  1557. cachedResponse,
  1558. request: effectiveRequest,
  1559. event: this.event
  1560. })) || undefined;
  1561. }
  1562. return cachedResponse;
  1563. }
  1564. /**
  1565. * Puts a request/response pair in the cache (and invokes any applicable
  1566. * plugin callback methods) using the `cacheName` and `plugins` defined on
  1567. * the strategy object.
  1568. *
  1569. * The following plugin lifecycle methods are invoked when using this method:
  1570. * - cacheKeyWillByUsed()
  1571. * - cacheWillUpdate()
  1572. * - cacheDidUpdate()
  1573. *
  1574. * @param {Request|string} key The request or URL to use as the cache key.
  1575. * @param {Response} response The response to cache.
  1576. * @return {Promise<boolean>} `false` if a cacheWillUpdate caused the response
  1577. * not be cached, and `true` otherwise.
  1578. */
  1579. async cachePut(key, response) {
  1580. const request = toRequest(key);
  1581. // Run in the next task to avoid blocking other cache reads.
  1582. // https://github.com/w3c/ServiceWorker/issues/1397
  1583. await timeout(0);
  1584. const effectiveRequest = await this.getCacheKey(request, 'write');
  1585. {
  1586. if (effectiveRequest.method && effectiveRequest.method !== 'GET') {
  1587. throw new WorkboxError('attempt-to-cache-non-get-request', {
  1588. url: getFriendlyURL(effectiveRequest.url),
  1589. method: effectiveRequest.method
  1590. });
  1591. }
  1592. // See https://github.com/GoogleChrome/workbox/issues/2818
  1593. const vary = response.headers.get('Vary');
  1594. if (vary) {
  1595. 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.`);
  1596. }
  1597. }
  1598. if (!response) {
  1599. {
  1600. logger.error(`Cannot cache non-existent response for ` + `'${getFriendlyURL(effectiveRequest.url)}'.`);
  1601. }
  1602. throw new WorkboxError('cache-put-with-no-response', {
  1603. url: getFriendlyURL(effectiveRequest.url)
  1604. });
  1605. }
  1606. const responseToCache = await this._ensureResponseSafeToCache(response);
  1607. if (!responseToCache) {
  1608. {
  1609. logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` + `will not be cached.`, responseToCache);
  1610. }
  1611. return false;
  1612. }
  1613. const {
  1614. cacheName,
  1615. matchOptions
  1616. } = this._strategy;
  1617. const cache = await self.caches.open(cacheName);
  1618. const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate');
  1619. const oldResponse = hasCacheUpdateCallback ? await cacheMatchIgnoreParams(
  1620. // TODO(philipwalton): the `__WB_REVISION__` param is a precaching
  1621. // feature. Consider into ways to only add this behavior if using
  1622. // precaching.
  1623. cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions) : null;
  1624. {
  1625. logger.debug(`Updating the '${cacheName}' cache with a new Response ` + `for ${getFriendlyURL(effectiveRequest.url)}.`);
  1626. }
  1627. try {
  1628. await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);
  1629. } catch (error) {
  1630. if (error instanceof Error) {
  1631. // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
  1632. if (error.name === 'QuotaExceededError') {
  1633. await executeQuotaErrorCallbacks();
  1634. }
  1635. throw error;
  1636. }
  1637. }
  1638. for (const callback of this.iterateCallbacks('cacheDidUpdate')) {
  1639. await callback({
  1640. cacheName,
  1641. oldResponse,
  1642. newResponse: responseToCache.clone(),
  1643. request: effectiveRequest,
  1644. event: this.event
  1645. });
  1646. }
  1647. return true;
  1648. }
  1649. /**
  1650. * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and
  1651. * executes any of those callbacks found in sequence. The final `Request`
  1652. * object returned by the last plugin is treated as the cache key for cache
  1653. * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have
  1654. * been registered, the passed request is returned unmodified
  1655. *
  1656. * @param {Request} request
  1657. * @param {string} mode
  1658. * @return {Promise<Request>}
  1659. */
  1660. async getCacheKey(request, mode) {
  1661. const key = `${request.url} | ${mode}`;
  1662. if (!this._cacheKeys[key]) {
  1663. let effectiveRequest = request;
  1664. for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) {
  1665. effectiveRequest = toRequest(await callback({
  1666. mode,
  1667. request: effectiveRequest,
  1668. event: this.event,
  1669. // params has a type any can't change right now.
  1670. params: this.params // eslint-disable-line
  1671. }));
  1672. }
  1673. this._cacheKeys[key] = effectiveRequest;
  1674. }
  1675. return this._cacheKeys[key];
  1676. }
  1677. /**
  1678. * Returns true if the strategy has at least one plugin with the given
  1679. * callback.
  1680. *
  1681. * @param {string} name The name of the callback to check for.
  1682. * @return {boolean}
  1683. */
  1684. hasCallback(name) {
  1685. for (const plugin of this._strategy.plugins) {
  1686. if (name in plugin) {
  1687. return true;
  1688. }
  1689. }
  1690. return false;
  1691. }
  1692. /**
  1693. * Runs all plugin callbacks matching the given name, in order, passing the
  1694. * given param object (merged ith the current plugin state) as the only
  1695. * argument.
  1696. *
  1697. * Note: since this method runs all plugins, it's not suitable for cases
  1698. * where the return value of a callback needs to be applied prior to calling
  1699. * the next callback. See
  1700. * {@link workbox-strategies.StrategyHandler#iterateCallbacks}
  1701. * below for how to handle that case.
  1702. *
  1703. * @param {string} name The name of the callback to run within each plugin.
  1704. * @param {Object} param The object to pass as the first (and only) param
  1705. * when executing each callback. This object will be merged with the
  1706. * current plugin state prior to callback execution.
  1707. */
  1708. async runCallbacks(name, param) {
  1709. for (const callback of this.iterateCallbacks(name)) {
  1710. // TODO(philipwalton): not sure why `any` is needed. It seems like
  1711. // this should work with `as WorkboxPluginCallbackParam[C]`.
  1712. await callback(param);
  1713. }
  1714. }
  1715. /**
  1716. * Accepts a callback and returns an iterable of matching plugin callbacks,
  1717. * where each callback is wrapped with the current handler state (i.e. when
  1718. * you call each callback, whatever object parameter you pass it will
  1719. * be merged with the plugin's current state).
  1720. *
  1721. * @param {string} name The name fo the callback to run
  1722. * @return {Array<Function>}
  1723. */
  1724. *iterateCallbacks(name) {
  1725. for (const plugin of this._strategy.plugins) {
  1726. if (typeof plugin[name] === 'function') {
  1727. const state = this._pluginStateMap.get(plugin);
  1728. const statefulCallback = param => {
  1729. const statefulParam = Object.assign(Object.assign({}, param), {
  1730. state
  1731. });
  1732. // TODO(philipwalton): not sure why `any` is needed. It seems like
  1733. // this should work with `as WorkboxPluginCallbackParam[C]`.
  1734. return plugin[name](statefulParam);
  1735. };
  1736. yield statefulCallback;
  1737. }
  1738. }
  1739. }
  1740. /**
  1741. * Adds a promise to the
  1742. * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises}
  1743. * of the event event associated with the request being handled (usually a
  1744. * `FetchEvent`).
  1745. *
  1746. * Note: you can await
  1747. * {@link workbox-strategies.StrategyHandler~doneWaiting}
  1748. * to know when all added promises have settled.
  1749. *
  1750. * @param {Promise} promise A promise to add to the extend lifetime promises
  1751. * of the event that triggered the request.
  1752. */
  1753. waitUntil(promise) {
  1754. this._extendLifetimePromises.push(promise);
  1755. return promise;
  1756. }
  1757. /**
  1758. * Returns a promise that resolves once all promises passed to
  1759. * {@link workbox-strategies.StrategyHandler~waitUntil}
  1760. * have settled.
  1761. *
  1762. * Note: any work done after `doneWaiting()` settles should be manually
  1763. * passed to an event's `waitUntil()` method (not this handler's
  1764. * `waitUntil()` method), otherwise the service worker thread my be killed
  1765. * prior to your work completing.
  1766. */
  1767. async doneWaiting() {
  1768. let promise;
  1769. while (promise = this._extendLifetimePromises.shift()) {
  1770. await promise;
  1771. }
  1772. }
  1773. /**
  1774. * Stops running the strategy and immediately resolves any pending
  1775. * `waitUntil()` promises.
  1776. */
  1777. destroy() {
  1778. this._handlerDeferred.resolve(null);
  1779. }
  1780. /**
  1781. * This method will call cacheWillUpdate on the available plugins (or use
  1782. * status === 200) to determine if the Response is safe and valid to cache.
  1783. *
  1784. * @param {Request} options.request
  1785. * @param {Response} options.response
  1786. * @return {Promise<Response|undefined>}
  1787. *
  1788. * @private
  1789. */
  1790. async _ensureResponseSafeToCache(response) {
  1791. let responseToCache = response;
  1792. let pluginsUsed = false;
  1793. for (const callback of this.iterateCallbacks('cacheWillUpdate')) {
  1794. responseToCache = (await callback({
  1795. request: this.request,
  1796. response: responseToCache,
  1797. event: this.event
  1798. })) || undefined;
  1799. pluginsUsed = true;
  1800. if (!responseToCache) {
  1801. break;
  1802. }
  1803. }
  1804. if (!pluginsUsed) {
  1805. if (responseToCache && responseToCache.status !== 200) {
  1806. responseToCache = undefined;
  1807. }
  1808. {
  1809. if (responseToCache) {
  1810. if (responseToCache.status !== 200) {
  1811. if (responseToCache.status === 0) {
  1812. 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.`);
  1813. } else {
  1814. logger.debug(`The response for '${this.request.url}' ` + `returned a status code of '${response.status}' and won't ` + `be cached as a result.`);
  1815. }
  1816. }
  1817. }
  1818. }
  1819. }
  1820. return responseToCache;
  1821. }
  1822. }
  1823. /*
  1824. Copyright 2020 Google LLC
  1825. Use of this source code is governed by an MIT-style
  1826. license that can be found in the LICENSE file or at
  1827. https://opensource.org/licenses/MIT.
  1828. */
  1829. /**
  1830. * An abstract base class that all other strategy classes must extend from:
  1831. *
  1832. * @memberof workbox-strategies
  1833. */
  1834. class Strategy {
  1835. /**
  1836. * Creates a new instance of the strategy and sets all documented option
  1837. * properties as public instance properties.
  1838. *
  1839. * Note: if a custom strategy class extends the base Strategy class and does
  1840. * not need more than these properties, it does not need to define its own
  1841. * constructor.
  1842. *
  1843. * @param {Object} [options]
  1844. * @param {string} [options.cacheName] Cache name to store and retrieve
  1845. * requests. Defaults to the cache names provided by
  1846. * {@link workbox-core.cacheNames}.
  1847. * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  1848. * to use in conjunction with this caching strategy.
  1849. * @param {Object} [options.fetchOptions] Values passed along to the
  1850. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  1851. * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
  1852. * `fetch()` requests made by this strategy.
  1853. * @param {Object} [options.matchOptions] The
  1854. * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
  1855. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  1856. */
  1857. constructor(options = {}) {
  1858. /**
  1859. * Cache name to store and retrieve
  1860. * requests. Defaults to the cache names provided by
  1861. * {@link workbox-core.cacheNames}.
  1862. *
  1863. * @type {string}
  1864. */
  1865. this.cacheName = cacheNames.getRuntimeName(options.cacheName);
  1866. /**
  1867. * The list
  1868. * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  1869. * used by this strategy.
  1870. *
  1871. * @type {Array<Object>}
  1872. */
  1873. this.plugins = options.plugins || [];
  1874. /**
  1875. * Values passed along to the
  1876. * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters}
  1877. * of all fetch() requests made by this strategy.
  1878. *
  1879. * @type {Object}
  1880. */
  1881. this.fetchOptions = options.fetchOptions;
  1882. /**
  1883. * The
  1884. * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
  1885. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  1886. *
  1887. * @type {Object}
  1888. */
  1889. this.matchOptions = options.matchOptions;
  1890. }
  1891. /**
  1892. * Perform a request strategy and returns a `Promise` that will resolve with
  1893. * a `Response`, invoking all relevant plugin callbacks.
  1894. *
  1895. * When a strategy instance is registered with a Workbox
  1896. * {@link workbox-routing.Route}, this method is automatically
  1897. * called when the route matches.
  1898. *
  1899. * Alternatively, this method can be used in a standalone `FetchEvent`
  1900. * listener by passing it to `event.respondWith()`.
  1901. *
  1902. * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
  1903. * properties listed below.
  1904. * @param {Request|string} options.request A request to run this strategy for.
  1905. * @param {ExtendableEvent} options.event The event associated with the
  1906. * request.
  1907. * @param {URL} [options.url]
  1908. * @param {*} [options.params]
  1909. */
  1910. handle(options) {
  1911. const [responseDone] = this.handleAll(options);
  1912. return responseDone;
  1913. }
  1914. /**
  1915. * Similar to {@link workbox-strategies.Strategy~handle}, but
  1916. * instead of just returning a `Promise` that resolves to a `Response` it
  1917. * it will return an tuple of `[response, done]` promises, where the former
  1918. * (`response`) is equivalent to what `handle()` returns, and the latter is a
  1919. * Promise that will resolve once any promises that were added to
  1920. * `event.waitUntil()` as part of performing the strategy have completed.
  1921. *
  1922. * You can await the `done` promise to ensure any extra work performed by
  1923. * the strategy (usually caching responses) completes successfully.
  1924. *
  1925. * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
  1926. * properties listed below.
  1927. * @param {Request|string} options.request A request to run this strategy for.
  1928. * @param {ExtendableEvent} options.event The event associated with the
  1929. * request.
  1930. * @param {URL} [options.url]
  1931. * @param {*} [options.params]
  1932. * @return {Array<Promise>} A tuple of [response, done]
  1933. * promises that can be used to determine when the response resolves as
  1934. * well as when the handler has completed all its work.
  1935. */
  1936. handleAll(options) {
  1937. // Allow for flexible options to be passed.
  1938. if (options instanceof FetchEvent) {
  1939. options = {
  1940. event: options,
  1941. request: options.request
  1942. };
  1943. }
  1944. const event = options.event;
  1945. const request = typeof options.request === 'string' ? new Request(options.request) : options.request;
  1946. const params = 'params' in options ? options.params : undefined;
  1947. const handler = new StrategyHandler(this, {
  1948. event,
  1949. request,
  1950. params
  1951. });
  1952. const responseDone = this._getResponse(handler, request, event);
  1953. const handlerDone = this._awaitComplete(responseDone, handler, request, event);
  1954. // Return an array of promises, suitable for use with Promise.all().
  1955. return [responseDone, handlerDone];
  1956. }
  1957. async _getResponse(handler, request, event) {
  1958. await handler.runCallbacks('handlerWillStart', {
  1959. event,
  1960. request
  1961. });
  1962. let response = undefined;
  1963. try {
  1964. response = await this._handle(request, handler);
  1965. // The "official" Strategy subclasses all throw this error automatically,
  1966. // but in case a third-party Strategy doesn't, ensure that we have a
  1967. // consistent failure when there's no response or an error response.
  1968. if (!response || response.type === 'error') {
  1969. throw new WorkboxError('no-response', {
  1970. url: request.url
  1971. });
  1972. }
  1973. } catch (error) {
  1974. if (error instanceof Error) {
  1975. for (const callback of handler.iterateCallbacks('handlerDidError')) {
  1976. response = await callback({
  1977. error,
  1978. event,
  1979. request
  1980. });
  1981. if (response) {
  1982. break;
  1983. }
  1984. }
  1985. }
  1986. if (!response) {
  1987. throw error;
  1988. } else {
  1989. 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.`);
  1990. }
  1991. }
  1992. for (const callback of handler.iterateCallbacks('handlerWillRespond')) {
  1993. response = await callback({
  1994. event,
  1995. request,
  1996. response
  1997. });
  1998. }
  1999. return response;
  2000. }
  2001. async _awaitComplete(responseDone, handler, request, event) {
  2002. let response;
  2003. let error;
  2004. try {
  2005. response = await responseDone;
  2006. } catch (error) {
  2007. // Ignore errors, as response errors should be caught via the `response`
  2008. // promise above. The `done` promise will only throw for errors in
  2009. // promises passed to `handler.waitUntil()`.
  2010. }
  2011. try {
  2012. await handler.runCallbacks('handlerDidRespond', {
  2013. event,
  2014. request,
  2015. response
  2016. });
  2017. await handler.doneWaiting();
  2018. } catch (waitUntilError) {
  2019. if (waitUntilError instanceof Error) {
  2020. error = waitUntilError;
  2021. }
  2022. }
  2023. await handler.runCallbacks('handlerDidComplete', {
  2024. event,
  2025. request,
  2026. response,
  2027. error: error
  2028. });
  2029. handler.destroy();
  2030. if (error) {
  2031. throw error;
  2032. }
  2033. }
  2034. }
  2035. /**
  2036. * Classes extending the `Strategy` based class should implement this method,
  2037. * and leverage the {@link workbox-strategies.StrategyHandler}
  2038. * arg to perform all fetching and cache logic, which will ensure all relevant
  2039. * cache, cache options, fetch options and plugins are used (per the current
  2040. * strategy instance).
  2041. *
  2042. * @name _handle
  2043. * @instance
  2044. * @abstract
  2045. * @function
  2046. * @param {Request} request
  2047. * @param {workbox-strategies.StrategyHandler} handler
  2048. * @return {Promise<Response>}
  2049. *
  2050. * @memberof workbox-strategies.Strategy
  2051. */
  2052. /*
  2053. Copyright 2018 Google LLC
  2054. Use of this source code is governed by an MIT-style
  2055. license that can be found in the LICENSE file or at
  2056. https://opensource.org/licenses/MIT.
  2057. */
  2058. const messages = {
  2059. strategyStart: (strategyName, request) => `Using ${strategyName} to respond to '${getFriendlyURL(request.url)}'`,
  2060. printFinalResponse: response => {
  2061. if (response) {
  2062. logger.groupCollapsed(`View the final response here.`);
  2063. logger.log(response || '[No response returned]');
  2064. logger.groupEnd();
  2065. }
  2066. }
  2067. };
  2068. /*
  2069. Copyright 2018 Google LLC
  2070. Use of this source code is governed by an MIT-style
  2071. license that can be found in the LICENSE file or at
  2072. https://opensource.org/licenses/MIT.
  2073. */
  2074. /**
  2075. * An implementation of a
  2076. * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only)
  2077. * request strategy.
  2078. *
  2079. * This class is useful if you want to take advantage of any
  2080. * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).
  2081. *
  2082. * If the network request fails, this will throw a `WorkboxError` exception.
  2083. *
  2084. * @extends workbox-strategies.Strategy
  2085. * @memberof workbox-strategies
  2086. */
  2087. class NetworkOnly extends Strategy {
  2088. /**
  2089. * @param {Object} [options]
  2090. * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  2091. * to use in conjunction with this caching strategy.
  2092. * @param {Object} [options.fetchOptions] Values passed along to the
  2093. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  2094. * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
  2095. * `fetch()` requests made by this strategy.
  2096. * @param {number} [options.networkTimeoutSeconds] If set, any network requests
  2097. * that fail to respond within the timeout will result in a network error.
  2098. */
  2099. constructor(options = {}) {
  2100. super(options);
  2101. this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;
  2102. }
  2103. /**
  2104. * @private
  2105. * @param {Request|string} request A request to run this strategy for.
  2106. * @param {workbox-strategies.StrategyHandler} handler The event that
  2107. * triggered the request.
  2108. * @return {Promise<Response>}
  2109. */
  2110. async _handle(request, handler) {
  2111. {
  2112. finalAssertExports.isInstance(request, Request, {
  2113. moduleName: 'workbox-strategies',
  2114. className: this.constructor.name,
  2115. funcName: '_handle',
  2116. paramName: 'request'
  2117. });
  2118. }
  2119. let error = undefined;
  2120. let response;
  2121. try {
  2122. const promises = [handler.fetch(request)];
  2123. if (this._networkTimeoutSeconds) {
  2124. const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000);
  2125. promises.push(timeoutPromise);
  2126. }
  2127. response = await Promise.race(promises);
  2128. if (!response) {
  2129. throw new Error(`Timed out the network response after ` + `${this._networkTimeoutSeconds} seconds.`);
  2130. }
  2131. } catch (err) {
  2132. if (err instanceof Error) {
  2133. error = err;
  2134. }
  2135. }
  2136. {
  2137. logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
  2138. if (response) {
  2139. logger.log(`Got response from network.`);
  2140. } else {
  2141. logger.log(`Unable to get a response from the network.`);
  2142. }
  2143. messages.printFinalResponse(response);
  2144. logger.groupEnd();
  2145. }
  2146. if (!response) {
  2147. throw new WorkboxError('no-response', {
  2148. url: request.url,
  2149. error
  2150. });
  2151. }
  2152. return response;
  2153. }
  2154. }
  2155. /*
  2156. Copyright 2019 Google LLC
  2157. Use of this source code is governed by an MIT-style
  2158. license that can be found in the LICENSE file or at
  2159. https://opensource.org/licenses/MIT.
  2160. */
  2161. /**
  2162. * Claim any currently available clients once the service worker
  2163. * becomes active. This is normally used in conjunction with `skipWaiting()`.
  2164. *
  2165. * @memberof workbox-core
  2166. */
  2167. function clientsClaim() {
  2168. self.addEventListener('activate', () => self.clients.claim());
  2169. }
  2170. /*
  2171. Copyright 2020 Google LLC
  2172. Use of this source code is governed by an MIT-style
  2173. license that can be found in the LICENSE file or at
  2174. https://opensource.org/licenses/MIT.
  2175. */
  2176. /**
  2177. * A utility method that makes it easier to use `event.waitUntil` with
  2178. * async functions and return the result.
  2179. *
  2180. * @param {ExtendableEvent} event
  2181. * @param {Function} asyncFn
  2182. * @return {Function}
  2183. * @private
  2184. */
  2185. function waitUntil(event, asyncFn) {
  2186. const returnPromise = asyncFn();
  2187. event.waitUntil(returnPromise);
  2188. return returnPromise;
  2189. }
  2190. // @ts-ignore
  2191. try {
  2192. self['workbox:precaching:7.0.0'] && _();
  2193. } catch (e) {}
  2194. /*
  2195. Copyright 2018 Google LLC
  2196. Use of this source code is governed by an MIT-style
  2197. license that can be found in the LICENSE file or at
  2198. https://opensource.org/licenses/MIT.
  2199. */
  2200. // Name of the search parameter used to store revision info.
  2201. const REVISION_SEARCH_PARAM = '__WB_REVISION__';
  2202. /**
  2203. * Converts a manifest entry into a versioned URL suitable for precaching.
  2204. *
  2205. * @param {Object|string} entry
  2206. * @return {string} A URL with versioning info.
  2207. *
  2208. * @private
  2209. * @memberof workbox-precaching
  2210. */
  2211. function createCacheKey(entry) {
  2212. if (!entry) {
  2213. throw new WorkboxError('add-to-cache-list-unexpected-type', {
  2214. entry
  2215. });
  2216. }
  2217. // If a precache manifest entry is a string, it's assumed to be a versioned
  2218. // URL, like '/app.abcd1234.js'. Return as-is.
  2219. if (typeof entry === 'string') {
  2220. const urlObject = new URL(entry, location.href);
  2221. return {
  2222. cacheKey: urlObject.href,
  2223. url: urlObject.href
  2224. };
  2225. }
  2226. const {
  2227. revision,
  2228. url
  2229. } = entry;
  2230. if (!url) {
  2231. throw new WorkboxError('add-to-cache-list-unexpected-type', {
  2232. entry
  2233. });
  2234. }
  2235. // If there's just a URL and no revision, then it's also assumed to be a
  2236. // versioned URL.
  2237. if (!revision) {
  2238. const urlObject = new URL(url, location.href);
  2239. return {
  2240. cacheKey: urlObject.href,
  2241. url: urlObject.href
  2242. };
  2243. }
  2244. // Otherwise, construct a properly versioned URL using the custom Workbox
  2245. // search parameter along with the revision info.
  2246. const cacheKeyURL = new URL(url, location.href);
  2247. const originalURL = new URL(url, location.href);
  2248. cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
  2249. return {
  2250. cacheKey: cacheKeyURL.href,
  2251. url: originalURL.href
  2252. };
  2253. }
  2254. /*
  2255. Copyright 2020 Google LLC
  2256. Use of this source code is governed by an MIT-style
  2257. license that can be found in the LICENSE file or at
  2258. https://opensource.org/licenses/MIT.
  2259. */
  2260. /**
  2261. * A plugin, designed to be used with PrecacheController, to determine the
  2262. * of assets that were updated (or not updated) during the install event.
  2263. *
  2264. * @private
  2265. */
  2266. class PrecacheInstallReportPlugin {
  2267. constructor() {
  2268. this.updatedURLs = [];
  2269. this.notUpdatedURLs = [];
  2270. this.handlerWillStart = async ({
  2271. request,
  2272. state
  2273. }) => {
  2274. // TODO: `state` should never be undefined...
  2275. if (state) {
  2276. state.originalRequest = request;
  2277. }
  2278. };
  2279. this.cachedResponseWillBeUsed = async ({
  2280. event,
  2281. state,
  2282. cachedResponse
  2283. }) => {
  2284. if (event.type === 'install') {
  2285. if (state && state.originalRequest && state.originalRequest instanceof Request) {
  2286. // TODO: `state` should never be undefined...
  2287. const url = state.originalRequest.url;
  2288. if (cachedResponse) {
  2289. this.notUpdatedURLs.push(url);
  2290. } else {
  2291. this.updatedURLs.push(url);
  2292. }
  2293. }
  2294. }
  2295. return cachedResponse;
  2296. };
  2297. }
  2298. }
  2299. /*
  2300. Copyright 2020 Google LLC
  2301. Use of this source code is governed by an MIT-style
  2302. license that can be found in the LICENSE file or at
  2303. https://opensource.org/licenses/MIT.
  2304. */
  2305. /**
  2306. * A plugin, designed to be used with PrecacheController, to translate URLs into
  2307. * the corresponding cache key, based on the current revision info.
  2308. *
  2309. * @private
  2310. */
  2311. class PrecacheCacheKeyPlugin {
  2312. constructor({
  2313. precacheController
  2314. }) {
  2315. this.cacheKeyWillBeUsed = async ({
  2316. request,
  2317. params
  2318. }) => {
  2319. // Params is type any, can't change right now.
  2320. /* eslint-disable */
  2321. const cacheKey = (params === null || params === void 0 ? void 0 : params.cacheKey) || this._precacheController.getCacheKeyForURL(request.url);
  2322. /* eslint-enable */
  2323. return cacheKey ? new Request(cacheKey, {
  2324. headers: request.headers
  2325. }) : request;
  2326. };
  2327. this._precacheController = precacheController;
  2328. }
  2329. }
  2330. /*
  2331. Copyright 2018 Google LLC
  2332. Use of this source code is governed by an MIT-style
  2333. license that can be found in the LICENSE file or at
  2334. https://opensource.org/licenses/MIT.
  2335. */
  2336. /**
  2337. * @param {string} groupTitle
  2338. * @param {Array<string>} deletedURLs
  2339. *
  2340. * @private
  2341. */
  2342. const logGroup = (groupTitle, deletedURLs) => {
  2343. logger.groupCollapsed(groupTitle);
  2344. for (const url of deletedURLs) {
  2345. logger.log(url);
  2346. }
  2347. logger.groupEnd();
  2348. };
  2349. /**
  2350. * @param {Array<string>} deletedURLs
  2351. *
  2352. * @private
  2353. * @memberof workbox-precaching
  2354. */
  2355. function printCleanupDetails(deletedURLs) {
  2356. const deletionCount = deletedURLs.length;
  2357. if (deletionCount > 0) {
  2358. logger.groupCollapsed(`During precaching cleanup, ` + `${deletionCount} cached ` + `request${deletionCount === 1 ? ' was' : 's were'} deleted.`);
  2359. logGroup('Deleted Cache Requests', deletedURLs);
  2360. logger.groupEnd();
  2361. }
  2362. }
  2363. /*
  2364. Copyright 2018 Google LLC
  2365. Use of this source code is governed by an MIT-style
  2366. license that can be found in the LICENSE file or at
  2367. https://opensource.org/licenses/MIT.
  2368. */
  2369. /**
  2370. * @param {string} groupTitle
  2371. * @param {Array<string>} urls
  2372. *
  2373. * @private
  2374. */
  2375. function _nestedGroup(groupTitle, urls) {
  2376. if (urls.length === 0) {
  2377. return;
  2378. }
  2379. logger.groupCollapsed(groupTitle);
  2380. for (const url of urls) {
  2381. logger.log(url);
  2382. }
  2383. logger.groupEnd();
  2384. }
  2385. /**
  2386. * @param {Array<string>} urlsToPrecache
  2387. * @param {Array<string>} urlsAlreadyPrecached
  2388. *
  2389. * @private
  2390. * @memberof workbox-precaching
  2391. */
  2392. function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) {
  2393. const precachedCount = urlsToPrecache.length;
  2394. const alreadyPrecachedCount = urlsAlreadyPrecached.length;
  2395. if (precachedCount || alreadyPrecachedCount) {
  2396. let message = `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`;
  2397. if (alreadyPrecachedCount > 0) {
  2398. message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`;
  2399. }
  2400. logger.groupCollapsed(message);
  2401. _nestedGroup(`View newly precached URLs.`, urlsToPrecache);
  2402. _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached);
  2403. logger.groupEnd();
  2404. }
  2405. }
  2406. /*
  2407. Copyright 2019 Google LLC
  2408. Use of this source code is governed by an MIT-style
  2409. license that can be found in the LICENSE file or at
  2410. https://opensource.org/licenses/MIT.
  2411. */
  2412. let supportStatus;
  2413. /**
  2414. * A utility function that determines whether the current browser supports
  2415. * constructing a new `Response` from a `response.body` stream.
  2416. *
  2417. * @return {boolean} `true`, if the current browser can successfully
  2418. * construct a `Response` from a `response.body` stream, `false` otherwise.
  2419. *
  2420. * @private
  2421. */
  2422. function canConstructResponseFromBodyStream() {
  2423. if (supportStatus === undefined) {
  2424. const testResponse = new Response('');
  2425. if ('body' in testResponse) {
  2426. try {
  2427. new Response(testResponse.body);
  2428. supportStatus = true;
  2429. } catch (error) {
  2430. supportStatus = false;
  2431. }
  2432. }
  2433. supportStatus = false;
  2434. }
  2435. return supportStatus;
  2436. }
  2437. /*
  2438. Copyright 2019 Google LLC
  2439. Use of this source code is governed by an MIT-style
  2440. license that can be found in the LICENSE file or at
  2441. https://opensource.org/licenses/MIT.
  2442. */
  2443. /**
  2444. * Allows developers to copy a response and modify its `headers`, `status`,
  2445. * or `statusText` values (the values settable via a
  2446. * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}
  2447. * object in the constructor).
  2448. * To modify these values, pass a function as the second argument. That
  2449. * function will be invoked with a single object with the response properties
  2450. * `{headers, status, statusText}`. The return value of this function will
  2451. * be used as the `ResponseInit` for the new `Response`. To change the values
  2452. * either modify the passed parameter(s) and return it, or return a totally
  2453. * new object.
  2454. *
  2455. * This method is intentionally limited to same-origin responses, regardless of
  2456. * whether CORS was used or not.
  2457. *
  2458. * @param {Response} response
  2459. * @param {Function} modifier
  2460. * @memberof workbox-core
  2461. */
  2462. async function copyResponse(response, modifier) {
  2463. let origin = null;
  2464. // If response.url isn't set, assume it's cross-origin and keep origin null.
  2465. if (response.url) {
  2466. const responseURL = new URL(response.url);
  2467. origin = responseURL.origin;
  2468. }
  2469. if (origin !== self.location.origin) {
  2470. throw new WorkboxError('cross-origin-copy-response', {
  2471. origin
  2472. });
  2473. }
  2474. const clonedResponse = response.clone();
  2475. // Create a fresh `ResponseInit` object by cloning the headers.
  2476. const responseInit = {
  2477. headers: new Headers(clonedResponse.headers),
  2478. status: clonedResponse.status,
  2479. statusText: clonedResponse.statusText
  2480. };
  2481. // Apply any user modifications.
  2482. const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;
  2483. // Create the new response from the body stream and `ResponseInit`
  2484. // modifications. Note: not all browsers support the Response.body stream,
  2485. // so fall back to reading the entire body into memory as a blob.
  2486. const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob();
  2487. return new Response(body, modifiedResponseInit);
  2488. }
  2489. /*
  2490. Copyright 2020 Google LLC
  2491. Use of this source code is governed by an MIT-style
  2492. license that can be found in the LICENSE file or at
  2493. https://opensource.org/licenses/MIT.
  2494. */
  2495. /**
  2496. * A {@link workbox-strategies.Strategy} implementation
  2497. * specifically designed to work with
  2498. * {@link workbox-precaching.PrecacheController}
  2499. * to both cache and fetch precached assets.
  2500. *
  2501. * Note: an instance of this class is created automatically when creating a
  2502. * `PrecacheController`; it's generally not necessary to create this yourself.
  2503. *
  2504. * @extends workbox-strategies.Strategy
  2505. * @memberof workbox-precaching
  2506. */
  2507. class PrecacheStrategy extends Strategy {
  2508. /**
  2509. *
  2510. * @param {Object} [options]
  2511. * @param {string} [options.cacheName] Cache name to store and retrieve
  2512. * requests. Defaults to the cache names provided by
  2513. * {@link workbox-core.cacheNames}.
  2514. * @param {Array<Object>} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins}
  2515. * to use in conjunction with this caching strategy.
  2516. * @param {Object} [options.fetchOptions] Values passed along to the
  2517. * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}
  2518. * of all fetch() requests made by this strategy.
  2519. * @param {Object} [options.matchOptions] The
  2520. * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions}
  2521. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  2522. * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to
  2523. * get the response from the network if there's a precache miss.
  2524. */
  2525. constructor(options = {}) {
  2526. options.cacheName = cacheNames.getPrecacheName(options.cacheName);
  2527. super(options);
  2528. this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true;
  2529. // Redirected responses cannot be used to satisfy a navigation request, so
  2530. // any redirected response must be "copied" rather than cloned, so the new
  2531. // response doesn't contain the `redirected` flag. See:
  2532. // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1
  2533. this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);
  2534. }
  2535. /**
  2536. * @private
  2537. * @param {Request|string} request A request to run this strategy for.
  2538. * @param {workbox-strategies.StrategyHandler} handler The event that
  2539. * triggered the request.
  2540. * @return {Promise<Response>}
  2541. */
  2542. async _handle(request, handler) {
  2543. const response = await handler.cacheMatch(request);
  2544. if (response) {
  2545. return response;
  2546. }
  2547. // If this is an `install` event for an entry that isn't already cached,
  2548. // then populate the cache.
  2549. if (handler.event && handler.event.type === 'install') {
  2550. return await this._handleInstall(request, handler);
  2551. }
  2552. // Getting here means something went wrong. An entry that should have been
  2553. // precached wasn't found in the cache.
  2554. return await this._handleFetch(request, handler);
  2555. }
  2556. async _handleFetch(request, handler) {
  2557. let response;
  2558. const params = handler.params || {};
  2559. // Fall back to the network if we're configured to do so.
  2560. if (this._fallbackToNetwork) {
  2561. {
  2562. logger.warn(`The precached response for ` + `${getFriendlyURL(request.url)} in ${this.cacheName} was not ` + `found. Falling back to the network.`);
  2563. }
  2564. const integrityInManifest = params.integrity;
  2565. const integrityInRequest = request.integrity;
  2566. const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;
  2567. // Do not add integrity if the original request is no-cors
  2568. // See https://github.com/GoogleChrome/workbox/issues/3096
  2569. response = await handler.fetch(new Request(request, {
  2570. integrity: request.mode !== 'no-cors' ? integrityInRequest || integrityInManifest : undefined
  2571. }));
  2572. // It's only "safe" to repair the cache if we're using SRI to guarantee
  2573. // that the response matches the precache manifest's expectations,
  2574. // and there's either a) no integrity property in the incoming request
  2575. // or b) there is an integrity, and it matches the precache manifest.
  2576. // See https://github.com/GoogleChrome/workbox/issues/2858
  2577. // Also if the original request users no-cors we don't use integrity.
  2578. // See https://github.com/GoogleChrome/workbox/issues/3096
  2579. if (integrityInManifest && noIntegrityConflict && request.mode !== 'no-cors') {
  2580. this._useDefaultCacheabilityPluginIfNeeded();
  2581. const wasCached = await handler.cachePut(request, response.clone());
  2582. {
  2583. if (wasCached) {
  2584. logger.log(`A response for ${getFriendlyURL(request.url)} ` + `was used to "repair" the precache.`);
  2585. }
  2586. }
  2587. }
  2588. } else {
  2589. // This shouldn't normally happen, but there are edge cases:
  2590. // https://github.com/GoogleChrome/workbox/issues/1441
  2591. throw new WorkboxError('missing-precache-entry', {
  2592. cacheName: this.cacheName,
  2593. url: request.url
  2594. });
  2595. }
  2596. {
  2597. const cacheKey = params.cacheKey || (await handler.getCacheKey(request, 'read'));
  2598. // Workbox is going to handle the route.
  2599. // print the routing details to the console.
  2600. logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL(request.url));
  2601. logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);
  2602. logger.groupCollapsed(`View request details here.`);
  2603. logger.log(request);
  2604. logger.groupEnd();
  2605. logger.groupCollapsed(`View response details here.`);
  2606. logger.log(response);
  2607. logger.groupEnd();
  2608. logger.groupEnd();
  2609. }
  2610. return response;
  2611. }
  2612. async _handleInstall(request, handler) {
  2613. this._useDefaultCacheabilityPluginIfNeeded();
  2614. const response = await handler.fetch(request);
  2615. // Make sure we defer cachePut() until after we know the response
  2616. // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737
  2617. const wasCached = await handler.cachePut(request, response.clone());
  2618. if (!wasCached) {
  2619. // Throwing here will lead to the `install` handler failing, which
  2620. // we want to do if *any* of the responses aren't safe to cache.
  2621. throw new WorkboxError('bad-precaching-response', {
  2622. url: request.url,
  2623. status: response.status
  2624. });
  2625. }
  2626. return response;
  2627. }
  2628. /**
  2629. * This method is complex, as there a number of things to account for:
  2630. *
  2631. * The `plugins` array can be set at construction, and/or it might be added to
  2632. * to at any time before the strategy is used.
  2633. *
  2634. * At the time the strategy is used (i.e. during an `install` event), there
  2635. * needs to be at least one plugin that implements `cacheWillUpdate` in the
  2636. * array, other than `copyRedirectedCacheableResponsesPlugin`.
  2637. *
  2638. * - If this method is called and there are no suitable `cacheWillUpdate`
  2639. * plugins, we need to add `defaultPrecacheCacheabilityPlugin`.
  2640. *
  2641. * - If this method is called and there is exactly one `cacheWillUpdate`, then
  2642. * we don't have to do anything (this might be a previously added
  2643. * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin).
  2644. *
  2645. * - If this method is called and there is more than one `cacheWillUpdate`,
  2646. * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so,
  2647. * we need to remove it. (This situation is unlikely, but it could happen if
  2648. * the strategy is used multiple times, the first without a `cacheWillUpdate`,
  2649. * and then later on after manually adding a custom `cacheWillUpdate`.)
  2650. *
  2651. * See https://github.com/GoogleChrome/workbox/issues/2737 for more context.
  2652. *
  2653. * @private
  2654. */
  2655. _useDefaultCacheabilityPluginIfNeeded() {
  2656. let defaultPluginIndex = null;
  2657. let cacheWillUpdatePluginCount = 0;
  2658. for (const [index, plugin] of this.plugins.entries()) {
  2659. // Ignore the copy redirected plugin when determining what to do.
  2660. if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {
  2661. continue;
  2662. }
  2663. // Save the default plugin's index, in case it needs to be removed.
  2664. if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {
  2665. defaultPluginIndex = index;
  2666. }
  2667. if (plugin.cacheWillUpdate) {
  2668. cacheWillUpdatePluginCount++;
  2669. }
  2670. }
  2671. if (cacheWillUpdatePluginCount === 0) {
  2672. this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);
  2673. } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {
  2674. // Only remove the default plugin; multiple custom plugins are allowed.
  2675. this.plugins.splice(defaultPluginIndex, 1);
  2676. }
  2677. // Nothing needs to be done if cacheWillUpdatePluginCount is 1
  2678. }
  2679. }
  2680. PrecacheStrategy.defaultPrecacheCacheabilityPlugin = {
  2681. async cacheWillUpdate({
  2682. response
  2683. }) {
  2684. if (!response || response.status >= 400) {
  2685. return null;
  2686. }
  2687. return response;
  2688. }
  2689. };
  2690. PrecacheStrategy.copyRedirectedCacheableResponsesPlugin = {
  2691. async cacheWillUpdate({
  2692. response
  2693. }) {
  2694. return response.redirected ? await copyResponse(response) : response;
  2695. }
  2696. };
  2697. /*
  2698. Copyright 2019 Google LLC
  2699. Use of this source code is governed by an MIT-style
  2700. license that can be found in the LICENSE file or at
  2701. https://opensource.org/licenses/MIT.
  2702. */
  2703. /**
  2704. * Performs efficient precaching of assets.
  2705. *
  2706. * @memberof workbox-precaching
  2707. */
  2708. class PrecacheController {
  2709. /**
  2710. * Create a new PrecacheController.
  2711. *
  2712. * @param {Object} [options]
  2713. * @param {string} [options.cacheName] The cache to use for precaching.
  2714. * @param {string} [options.plugins] Plugins to use when precaching as well
  2715. * as responding to fetch events for precached assets.
  2716. * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to
  2717. * get the response from the network if there's a precache miss.
  2718. */
  2719. constructor({
  2720. cacheName,
  2721. plugins = [],
  2722. fallbackToNetwork = true
  2723. } = {}) {
  2724. this._urlsToCacheKeys = new Map();
  2725. this._urlsToCacheModes = new Map();
  2726. this._cacheKeysToIntegrities = new Map();
  2727. this._strategy = new PrecacheStrategy({
  2728. cacheName: cacheNames.getPrecacheName(cacheName),
  2729. plugins: [...plugins, new PrecacheCacheKeyPlugin({
  2730. precacheController: this
  2731. })],
  2732. fallbackToNetwork
  2733. });
  2734. // Bind the install and activate methods to the instance.
  2735. this.install = this.install.bind(this);
  2736. this.activate = this.activate.bind(this);
  2737. }
  2738. /**
  2739. * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and
  2740. * used to cache assets and respond to fetch events.
  2741. */
  2742. get strategy() {
  2743. return this._strategy;
  2744. }
  2745. /**
  2746. * Adds items to the precache list, removing any duplicates and
  2747. * stores the files in the
  2748. * {@link workbox-core.cacheNames|"precache cache"} when the service
  2749. * worker installs.
  2750. *
  2751. * This method can be called multiple times.
  2752. *
  2753. * @param {Array<Object|string>} [entries=[]] Array of entries to precache.
  2754. */
  2755. precache(entries) {
  2756. this.addToCacheList(entries);
  2757. if (!this._installAndActiveListenersAdded) {
  2758. self.addEventListener('install', this.install);
  2759. self.addEventListener('activate', this.activate);
  2760. this._installAndActiveListenersAdded = true;
  2761. }
  2762. }
  2763. /**
  2764. * This method will add items to the precache list, removing duplicates
  2765. * and ensuring the information is valid.
  2766. *
  2767. * @param {Array<workbox-precaching.PrecacheController.PrecacheEntry|string>} entries
  2768. * Array of entries to precache.
  2769. */
  2770. addToCacheList(entries) {
  2771. {
  2772. finalAssertExports.isArray(entries, {
  2773. moduleName: 'workbox-precaching',
  2774. className: 'PrecacheController',
  2775. funcName: 'addToCacheList',
  2776. paramName: 'entries'
  2777. });
  2778. }
  2779. const urlsToWarnAbout = [];
  2780. for (const entry of entries) {
  2781. // See https://github.com/GoogleChrome/workbox/issues/2259
  2782. if (typeof entry === 'string') {
  2783. urlsToWarnAbout.push(entry);
  2784. } else if (entry && entry.revision === undefined) {
  2785. urlsToWarnAbout.push(entry.url);
  2786. }
  2787. const {
  2788. cacheKey,
  2789. url
  2790. } = createCacheKey(entry);
  2791. const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default';
  2792. if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
  2793. throw new WorkboxError('add-to-cache-list-conflicting-entries', {
  2794. firstEntry: this._urlsToCacheKeys.get(url),
  2795. secondEntry: cacheKey
  2796. });
  2797. }
  2798. if (typeof entry !== 'string' && entry.integrity) {
  2799. if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
  2800. throw new WorkboxError('add-to-cache-list-conflicting-integrities', {
  2801. url
  2802. });
  2803. }
  2804. this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
  2805. }
  2806. this._urlsToCacheKeys.set(url, cacheKey);
  2807. this._urlsToCacheModes.set(url, cacheMode);
  2808. if (urlsToWarnAbout.length > 0) {
  2809. const warningMessage = `Workbox is precaching URLs without revision ` + `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` + `Learn more at https://bit.ly/wb-precache`;
  2810. {
  2811. logger.warn(warningMessage);
  2812. }
  2813. }
  2814. }
  2815. }
  2816. /**
  2817. * Precaches new and updated assets. Call this method from the service worker
  2818. * install event.
  2819. *
  2820. * Note: this method calls `event.waitUntil()` for you, so you do not need
  2821. * to call it yourself in your event handlers.
  2822. *
  2823. * @param {ExtendableEvent} event
  2824. * @return {Promise<workbox-precaching.InstallResult>}
  2825. */
  2826. install(event) {
  2827. // waitUntil returns Promise<any>
  2828. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  2829. return waitUntil(event, async () => {
  2830. const installReportPlugin = new PrecacheInstallReportPlugin();
  2831. this.strategy.plugins.push(installReportPlugin);
  2832. // Cache entries one at a time.
  2833. // See https://github.com/GoogleChrome/workbox/issues/2528
  2834. for (const [url, cacheKey] of this._urlsToCacheKeys) {
  2835. const integrity = this._cacheKeysToIntegrities.get(cacheKey);
  2836. const cacheMode = this._urlsToCacheModes.get(url);
  2837. const request = new Request(url, {
  2838. integrity,
  2839. cache: cacheMode,
  2840. credentials: 'same-origin'
  2841. });
  2842. await Promise.all(this.strategy.handleAll({
  2843. params: {
  2844. cacheKey
  2845. },
  2846. request,
  2847. event
  2848. }));
  2849. }
  2850. const {
  2851. updatedURLs,
  2852. notUpdatedURLs
  2853. } = installReportPlugin;
  2854. {
  2855. printInstallDetails(updatedURLs, notUpdatedURLs);
  2856. }
  2857. return {
  2858. updatedURLs,
  2859. notUpdatedURLs
  2860. };
  2861. });
  2862. }
  2863. /**
  2864. * Deletes assets that are no longer present in the current precache manifest.
  2865. * Call this method from the service worker activate event.
  2866. *
  2867. * Note: this method calls `event.waitUntil()` for you, so you do not need
  2868. * to call it yourself in your event handlers.
  2869. *
  2870. * @param {ExtendableEvent} event
  2871. * @return {Promise<workbox-precaching.CleanupResult>}
  2872. */
  2873. activate(event) {
  2874. // waitUntil returns Promise<any>
  2875. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  2876. return waitUntil(event, async () => {
  2877. const cache = await self.caches.open(this.strategy.cacheName);
  2878. const currentlyCachedRequests = await cache.keys();
  2879. const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
  2880. const deletedURLs = [];
  2881. for (const request of currentlyCachedRequests) {
  2882. if (!expectedCacheKeys.has(request.url)) {
  2883. await cache.delete(request);
  2884. deletedURLs.push(request.url);
  2885. }
  2886. }
  2887. {
  2888. printCleanupDetails(deletedURLs);
  2889. }
  2890. return {
  2891. deletedURLs
  2892. };
  2893. });
  2894. }
  2895. /**
  2896. * Returns a mapping of a precached URL to the corresponding cache key, taking
  2897. * into account the revision information for the URL.
  2898. *
  2899. * @return {Map<string, string>} A URL to cache key mapping.
  2900. */
  2901. getURLsToCacheKeys() {
  2902. return this._urlsToCacheKeys;
  2903. }
  2904. /**
  2905. * Returns a list of all the URLs that have been precached by the current
  2906. * service worker.
  2907. *
  2908. * @return {Array<string>} The precached URLs.
  2909. */
  2910. getCachedURLs() {
  2911. return [...this._urlsToCacheKeys.keys()];
  2912. }
  2913. /**
  2914. * Returns the cache key used for storing a given URL. If that URL is
  2915. * unversioned, like `/index.html', then the cache key will be the original
  2916. * URL with a search parameter appended to it.
  2917. *
  2918. * @param {string} url A URL whose cache key you want to look up.
  2919. * @return {string} The versioned URL that corresponds to a cache key
  2920. * for the original URL, or undefined if that URL isn't precached.
  2921. */
  2922. getCacheKeyForURL(url) {
  2923. const urlObject = new URL(url, location.href);
  2924. return this._urlsToCacheKeys.get(urlObject.href);
  2925. }
  2926. /**
  2927. * @param {string} url A cache key whose SRI you want to look up.
  2928. * @return {string} The subresource integrity associated with the cache key,
  2929. * or undefined if it's not set.
  2930. */
  2931. getIntegrityForCacheKey(cacheKey) {
  2932. return this._cacheKeysToIntegrities.get(cacheKey);
  2933. }
  2934. /**
  2935. * This acts as a drop-in replacement for
  2936. * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
  2937. * with the following differences:
  2938. *
  2939. * - It knows what the name of the precache is, and only checks in that cache.
  2940. * - It allows you to pass in an "original" URL without versioning parameters,
  2941. * and it will automatically look up the correct cache key for the currently
  2942. * active revision of that URL.
  2943. *
  2944. * E.g., `matchPrecache('index.html')` will find the correct precached
  2945. * response for the currently active service worker, even if the actual cache
  2946. * key is `'/index.html?__WB_REVISION__=1234abcd'`.
  2947. *
  2948. * @param {string|Request} request The key (without revisioning parameters)
  2949. * to look up in the precache.
  2950. * @return {Promise<Response|undefined>}
  2951. */
  2952. async matchPrecache(request) {
  2953. const url = request instanceof Request ? request.url : request;
  2954. const cacheKey = this.getCacheKeyForURL(url);
  2955. if (cacheKey) {
  2956. const cache = await self.caches.open(this.strategy.cacheName);
  2957. return cache.match(cacheKey);
  2958. }
  2959. return undefined;
  2960. }
  2961. /**
  2962. * Returns a function that looks up `url` in the precache (taking into
  2963. * account revision information), and returns the corresponding `Response`.
  2964. *
  2965. * @param {string} url The precached URL which will be used to lookup the
  2966. * `Response`.
  2967. * @return {workbox-routing~handlerCallback}
  2968. */
  2969. createHandlerBoundToURL(url) {
  2970. const cacheKey = this.getCacheKeyForURL(url);
  2971. if (!cacheKey) {
  2972. throw new WorkboxError('non-precached-url', {
  2973. url
  2974. });
  2975. }
  2976. return options => {
  2977. options.request = new Request(url);
  2978. options.params = Object.assign({
  2979. cacheKey
  2980. }, options.params);
  2981. return this.strategy.handle(options);
  2982. };
  2983. }
  2984. }
  2985. /*
  2986. Copyright 2019 Google LLC
  2987. Use of this source code is governed by an MIT-style
  2988. license that can be found in the LICENSE file or at
  2989. https://opensource.org/licenses/MIT.
  2990. */
  2991. let precacheController;
  2992. /**
  2993. * @return {PrecacheController}
  2994. * @private
  2995. */
  2996. const getOrCreatePrecacheController = () => {
  2997. if (!precacheController) {
  2998. precacheController = new PrecacheController();
  2999. }
  3000. return precacheController;
  3001. };
  3002. /*
  3003. Copyright 2018 Google LLC
  3004. Use of this source code is governed by an MIT-style
  3005. license that can be found in the LICENSE file or at
  3006. https://opensource.org/licenses/MIT.
  3007. */
  3008. /**
  3009. * Removes any URL search parameters that should be ignored.
  3010. *
  3011. * @param {URL} urlObject The original URL.
  3012. * @param {Array<RegExp>} ignoreURLParametersMatching RegExps to test against
  3013. * each search parameter name. Matches mean that the search parameter should be
  3014. * ignored.
  3015. * @return {URL} The URL with any ignored search parameters removed.
  3016. *
  3017. * @private
  3018. * @memberof workbox-precaching
  3019. */
  3020. function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) {
  3021. // Convert the iterable into an array at the start of the loop to make sure
  3022. // deletion doesn't mess up iteration.
  3023. for (const paramName of [...urlObject.searchParams.keys()]) {
  3024. if (ignoreURLParametersMatching.some(regExp => regExp.test(paramName))) {
  3025. urlObject.searchParams.delete(paramName);
  3026. }
  3027. }
  3028. return urlObject;
  3029. }
  3030. /*
  3031. Copyright 2019 Google LLC
  3032. Use of this source code is governed by an MIT-style
  3033. license that can be found in the LICENSE file or at
  3034. https://opensource.org/licenses/MIT.
  3035. */
  3036. /**
  3037. * Generator function that yields possible variations on the original URL to
  3038. * check, one at a time.
  3039. *
  3040. * @param {string} url
  3041. * @param {Object} options
  3042. *
  3043. * @private
  3044. * @memberof workbox-precaching
  3045. */
  3046. function* generateURLVariations(url, {
  3047. ignoreURLParametersMatching = [/^utm_/, /^fbclid$/],
  3048. directoryIndex = 'index.html',
  3049. cleanURLs = true,
  3050. urlManipulation
  3051. } = {}) {
  3052. const urlObject = new URL(url, location.href);
  3053. urlObject.hash = '';
  3054. yield urlObject.href;
  3055. const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);
  3056. yield urlWithoutIgnoredParams.href;
  3057. if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) {
  3058. const directoryURL = new URL(urlWithoutIgnoredParams.href);
  3059. directoryURL.pathname += directoryIndex;
  3060. yield directoryURL.href;
  3061. }
  3062. if (cleanURLs) {
  3063. const cleanURL = new URL(urlWithoutIgnoredParams.href);
  3064. cleanURL.pathname += '.html';
  3065. yield cleanURL.href;
  3066. }
  3067. if (urlManipulation) {
  3068. const additionalURLs = urlManipulation({
  3069. url: urlObject
  3070. });
  3071. for (const urlToAttempt of additionalURLs) {
  3072. yield urlToAttempt.href;
  3073. }
  3074. }
  3075. }
  3076. /*
  3077. Copyright 2020 Google LLC
  3078. Use of this source code is governed by an MIT-style
  3079. license that can be found in the LICENSE file or at
  3080. https://opensource.org/licenses/MIT.
  3081. */
  3082. /**
  3083. * A subclass of {@link workbox-routing.Route} that takes a
  3084. * {@link workbox-precaching.PrecacheController}
  3085. * instance and uses it to match incoming requests and handle fetching
  3086. * responses from the precache.
  3087. *
  3088. * @memberof workbox-precaching
  3089. * @extends workbox-routing.Route
  3090. */
  3091. class PrecacheRoute extends Route {
  3092. /**
  3093. * @param {PrecacheController} precacheController A `PrecacheController`
  3094. * instance used to both match requests and respond to fetch events.
  3095. * @param {Object} [options] Options to control how requests are matched
  3096. * against the list of precached URLs.
  3097. * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will
  3098. * check cache entries for a URLs ending with '/' to see if there is a hit when
  3099. * appending the `directoryIndex` value.
  3100. * @param {Array<RegExp>} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An
  3101. * array of regex's to remove search params when looking for a cache match.
  3102. * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will
  3103. * check the cache for the URL with a `.html` added to the end of the end.
  3104. * @param {workbox-precaching~urlManipulation} [options.urlManipulation]
  3105. * This is a function that should take a URL and return an array of
  3106. * alternative URLs that should be checked for precache matches.
  3107. */
  3108. constructor(precacheController, options) {
  3109. const match = ({
  3110. request
  3111. }) => {
  3112. const urlsToCacheKeys = precacheController.getURLsToCacheKeys();
  3113. for (const possibleURL of generateURLVariations(request.url, options)) {
  3114. const cacheKey = urlsToCacheKeys.get(possibleURL);
  3115. if (cacheKey) {
  3116. const integrity = precacheController.getIntegrityForCacheKey(cacheKey);
  3117. return {
  3118. cacheKey,
  3119. integrity
  3120. };
  3121. }
  3122. }
  3123. {
  3124. logger.debug(`Precaching did not find a match for ` + getFriendlyURL(request.url));
  3125. }
  3126. return;
  3127. };
  3128. super(match, precacheController.strategy);
  3129. }
  3130. }
  3131. /*
  3132. Copyright 2019 Google LLC
  3133. Use of this source code is governed by an MIT-style
  3134. license that can be found in the LICENSE file or at
  3135. https://opensource.org/licenses/MIT.
  3136. */
  3137. /**
  3138. * Add a `fetch` listener to the service worker that will
  3139. * respond to
  3140. * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}
  3141. * with precached assets.
  3142. *
  3143. * Requests for assets that aren't precached, the `FetchEvent` will not be
  3144. * responded to, allowing the event to fall through to other `fetch` event
  3145. * listeners.
  3146. *
  3147. * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute}
  3148. * options.
  3149. *
  3150. * @memberof workbox-precaching
  3151. */
  3152. function addRoute(options) {
  3153. const precacheController = getOrCreatePrecacheController();
  3154. const precacheRoute = new PrecacheRoute(precacheController, options);
  3155. registerRoute(precacheRoute);
  3156. }
  3157. /*
  3158. Copyright 2019 Google LLC
  3159. Use of this source code is governed by an MIT-style
  3160. license that can be found in the LICENSE file or at
  3161. https://opensource.org/licenses/MIT.
  3162. */
  3163. /**
  3164. * Adds items to the precache list, removing any duplicates and
  3165. * stores the files in the
  3166. * {@link workbox-core.cacheNames|"precache cache"} when the service
  3167. * worker installs.
  3168. *
  3169. * This method can be called multiple times.
  3170. *
  3171. * Please note: This method **will not** serve any of the cached files for you.
  3172. * It only precaches files. To respond to a network request you call
  3173. * {@link workbox-precaching.addRoute}.
  3174. *
  3175. * If you have a single array of files to precache, you can just call
  3176. * {@link workbox-precaching.precacheAndRoute}.
  3177. *
  3178. * @param {Array<Object|string>} [entries=[]] Array of entries to precache.
  3179. *
  3180. * @memberof workbox-precaching
  3181. */
  3182. function precache(entries) {
  3183. const precacheController = getOrCreatePrecacheController();
  3184. precacheController.precache(entries);
  3185. }
  3186. /*
  3187. Copyright 2019 Google LLC
  3188. Use of this source code is governed by an MIT-style
  3189. license that can be found in the LICENSE file or at
  3190. https://opensource.org/licenses/MIT.
  3191. */
  3192. /**
  3193. * This method will add entries to the precache list and add a route to
  3194. * respond to fetch events.
  3195. *
  3196. * This is a convenience method that will call
  3197. * {@link workbox-precaching.precache} and
  3198. * {@link workbox-precaching.addRoute} in a single call.
  3199. *
  3200. * @param {Array<Object|string>} entries Array of entries to precache.
  3201. * @param {Object} [options] See the
  3202. * {@link workbox-precaching.PrecacheRoute} options.
  3203. *
  3204. * @memberof workbox-precaching
  3205. */
  3206. function precacheAndRoute(entries, options) {
  3207. precache(entries);
  3208. addRoute(options);
  3209. }
  3210. /*
  3211. Copyright 2018 Google LLC
  3212. Use of this source code is governed by an MIT-style
  3213. license that can be found in the LICENSE file or at
  3214. https://opensource.org/licenses/MIT.
  3215. */
  3216. const SUBSTRING_TO_FIND = '-precache-';
  3217. /**
  3218. * Cleans up incompatible precaches that were created by older versions of
  3219. * Workbox, by a service worker registered under the current scope.
  3220. *
  3221. * This is meant to be called as part of the `activate` event.
  3222. *
  3223. * This should be safe to use as long as you don't include `substringToFind`
  3224. * (defaulting to `-precache-`) in your non-precache cache names.
  3225. *
  3226. * @param {string} currentPrecacheName The cache name currently in use for
  3227. * precaching. This cache won't be deleted.
  3228. * @param {string} [substringToFind='-precache-'] Cache names which include this
  3229. * substring will be deleted (excluding `currentPrecacheName`).
  3230. * @return {Array<string>} A list of all the cache names that were deleted.
  3231. *
  3232. * @private
  3233. * @memberof workbox-precaching
  3234. */
  3235. const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => {
  3236. const cacheNames = await self.caches.keys();
  3237. const cacheNamesToDelete = cacheNames.filter(cacheName => {
  3238. return cacheName.includes(substringToFind) && cacheName.includes(self.registration.scope) && cacheName !== currentPrecacheName;
  3239. });
  3240. await Promise.all(cacheNamesToDelete.map(cacheName => self.caches.delete(cacheName)));
  3241. return cacheNamesToDelete;
  3242. };
  3243. /*
  3244. Copyright 2019 Google LLC
  3245. Use of this source code is governed by an MIT-style
  3246. license that can be found in the LICENSE file or at
  3247. https://opensource.org/licenses/MIT.
  3248. */
  3249. /**
  3250. * Adds an `activate` event listener which will clean up incompatible
  3251. * precaches that were created by older versions of Workbox.
  3252. *
  3253. * @memberof workbox-precaching
  3254. */
  3255. function cleanupOutdatedCaches() {
  3256. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  3257. self.addEventListener('activate', event => {
  3258. const cacheName = cacheNames.getPrecacheName();
  3259. event.waitUntil(deleteOutdatedCaches(cacheName).then(cachesDeleted => {
  3260. {
  3261. if (cachesDeleted.length > 0) {
  3262. logger.log(`The following out-of-date precaches were cleaned up ` + `automatically:`, cachesDeleted);
  3263. }
  3264. }
  3265. }));
  3266. });
  3267. }
  3268. /*
  3269. Copyright 2018 Google LLC
  3270. Use of this source code is governed by an MIT-style
  3271. license that can be found in the LICENSE file or at
  3272. https://opensource.org/licenses/MIT.
  3273. */
  3274. /**
  3275. * NavigationRoute makes it easy to create a
  3276. * {@link workbox-routing.Route} that matches for browser
  3277. * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}.
  3278. *
  3279. * It will only match incoming Requests whose
  3280. * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode}
  3281. * is set to `navigate`.
  3282. *
  3283. * You can optionally only apply this route to a subset of navigation requests
  3284. * by using one or both of the `denylist` and `allowlist` parameters.
  3285. *
  3286. * @memberof workbox-routing
  3287. * @extends workbox-routing.Route
  3288. */
  3289. class NavigationRoute extends Route {
  3290. /**
  3291. * If both `denylist` and `allowlist` are provided, the `denylist` will
  3292. * take precedence and the request will not match this route.
  3293. *
  3294. * The regular expressions in `allowlist` and `denylist`
  3295. * are matched against the concatenated
  3296. * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname}
  3297. * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search}
  3298. * portions of the requested URL.
  3299. *
  3300. * *Note*: These RegExps may be evaluated against every destination URL during
  3301. * a navigation. Avoid using
  3302. * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
  3303. * or else your users may see delays when navigating your site.
  3304. *
  3305. * @param {workbox-routing~handlerCallback} handler A callback
  3306. * function that returns a Promise resulting in a Response.
  3307. * @param {Object} options
  3308. * @param {Array<RegExp>} [options.denylist] If any of these patterns match,
  3309. * the route will not handle the request (even if a allowlist RegExp matches).
  3310. * @param {Array<RegExp>} [options.allowlist=[/./]] If any of these patterns
  3311. * match the URL's pathname and search parameter, the route will handle the
  3312. * request (assuming the denylist doesn't match).
  3313. */
  3314. constructor(handler, {
  3315. allowlist = [/./],
  3316. denylist = []
  3317. } = {}) {
  3318. {
  3319. finalAssertExports.isArrayOfClass(allowlist, RegExp, {
  3320. moduleName: 'workbox-routing',
  3321. className: 'NavigationRoute',
  3322. funcName: 'constructor',
  3323. paramName: 'options.allowlist'
  3324. });
  3325. finalAssertExports.isArrayOfClass(denylist, RegExp, {
  3326. moduleName: 'workbox-routing',
  3327. className: 'NavigationRoute',
  3328. funcName: 'constructor',
  3329. paramName: 'options.denylist'
  3330. });
  3331. }
  3332. super(options => this._match(options), handler);
  3333. this._allowlist = allowlist;
  3334. this._denylist = denylist;
  3335. }
  3336. /**
  3337. * Routes match handler.
  3338. *
  3339. * @param {Object} options
  3340. * @param {URL} options.url
  3341. * @param {Request} options.request
  3342. * @return {boolean}
  3343. *
  3344. * @private
  3345. */
  3346. _match({
  3347. url,
  3348. request
  3349. }) {
  3350. if (request && request.mode !== 'navigate') {
  3351. return false;
  3352. }
  3353. const pathnameAndSearch = url.pathname + url.search;
  3354. for (const regExp of this._denylist) {
  3355. if (regExp.test(pathnameAndSearch)) {
  3356. {
  3357. logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL matches this denylist pattern: ` + `${regExp.toString()}`);
  3358. }
  3359. return false;
  3360. }
  3361. }
  3362. if (this._allowlist.some(regExp => regExp.test(pathnameAndSearch))) {
  3363. {
  3364. logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`);
  3365. }
  3366. return true;
  3367. }
  3368. {
  3369. logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL being navigated to doesn't ` + `match the allowlist.`);
  3370. }
  3371. return false;
  3372. }
  3373. }
  3374. /*
  3375. Copyright 2019 Google LLC
  3376. Use of this source code is governed by an MIT-style
  3377. license that can be found in the LICENSE file or at
  3378. https://opensource.org/licenses/MIT.
  3379. */
  3380. /**
  3381. * Helper function that calls
  3382. * {@link PrecacheController#createHandlerBoundToURL} on the default
  3383. * {@link PrecacheController} instance.
  3384. *
  3385. * If you are creating your own {@link PrecacheController}, then call the
  3386. * {@link PrecacheController#createHandlerBoundToURL} on that instance,
  3387. * instead of using this function.
  3388. *
  3389. * @param {string} url The precached URL which will be used to lookup the
  3390. * `Response`.
  3391. * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the
  3392. * response from the network if there's a precache miss.
  3393. * @return {workbox-routing~handlerCallback}
  3394. *
  3395. * @memberof workbox-precaching
  3396. */
  3397. function createHandlerBoundToURL(url) {
  3398. const precacheController = getOrCreatePrecacheController();
  3399. return precacheController.createHandlerBoundToURL(url);
  3400. }
  3401. exports.NavigationRoute = NavigationRoute;
  3402. exports.NetworkOnly = NetworkOnly;
  3403. exports.cleanupOutdatedCaches = cleanupOutdatedCaches;
  3404. exports.clientsClaim = clientsClaim;
  3405. exports.createHandlerBoundToURL = createHandlerBoundToURL;
  3406. exports.precacheAndRoute = precacheAndRoute;
  3407. exports.registerRoute = registerRoute;
  3408. }));