workbox-16108a29.js 126 KB

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