workbox-5199072c.js 126 KB

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