workbox-d49dec61.js 171 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568
  1. define(['exports'], (function (exports) { 'use strict';
  2. // @ts-ignore
  3. try {
  4. self['workbox:core:7.0.0'] && _();
  5. } catch (e) {}
  6. /*
  7. Copyright 2019 Google LLC
  8. Use of this source code is governed by an MIT-style
  9. license that can be found in the LICENSE file or at
  10. https://opensource.org/licenses/MIT.
  11. */
  12. const logger = (() => {
  13. // Don't overwrite this value if it's already set.
  14. // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
  15. if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {
  16. self.__WB_DISABLE_DEV_LOGS = false;
  17. }
  18. let inGroup = false;
  19. const methodToColorMap = {
  20. debug: `#7f8c8d`,
  21. log: `#2ecc71`,
  22. warn: `#f39c12`,
  23. error: `#c0392b`,
  24. groupCollapsed: `#3498db`,
  25. groupEnd: null // No colored prefix on groupEnd
  26. };
  27. const print = function (method, args) {
  28. if (self.__WB_DISABLE_DEV_LOGS) {
  29. return;
  30. }
  31. if (method === 'groupCollapsed') {
  32. // Safari doesn't print all console.groupCollapsed() arguments:
  33. // https://bugs.webkit.org/show_bug.cgi?id=182754
  34. if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
  35. console[method](...args);
  36. return;
  37. }
  38. }
  39. const styles = [`background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em`];
  40. // When in a group, the workbox prefix is not displayed.
  41. const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
  42. console[method](...logPrefix, ...args);
  43. if (method === 'groupCollapsed') {
  44. inGroup = true;
  45. }
  46. if (method === 'groupEnd') {
  47. inGroup = false;
  48. }
  49. };
  50. // eslint-disable-next-line @typescript-eslint/ban-types
  51. const api = {};
  52. const loggerMethods = Object.keys(methodToColorMap);
  53. for (const key of loggerMethods) {
  54. const method = key;
  55. api[method] = (...args) => {
  56. print(method, args);
  57. };
  58. }
  59. return api;
  60. })();
  61. /*
  62. Copyright 2018 Google LLC
  63. Use of this source code is governed by an MIT-style
  64. license that can be found in the LICENSE file or at
  65. https://opensource.org/licenses/MIT.
  66. */
  67. const messages$1 = {
  68. 'invalid-value': ({
  69. paramName,
  70. validValueDescription,
  71. value
  72. }) => {
  73. if (!paramName || !validValueDescription) {
  74. throw new Error(`Unexpected input to 'invalid-value' error.`);
  75. }
  76. return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
  77. },
  78. 'not-an-array': ({
  79. moduleName,
  80. className,
  81. funcName,
  82. paramName
  83. }) => {
  84. if (!moduleName || !className || !funcName || !paramName) {
  85. throw new Error(`Unexpected input to 'not-an-array' error.`);
  86. }
  87. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
  88. },
  89. 'incorrect-type': ({
  90. expectedType,
  91. paramName,
  92. moduleName,
  93. className,
  94. funcName
  95. }) => {
  96. if (!expectedType || !paramName || !moduleName || !funcName) {
  97. throw new Error(`Unexpected input to 'incorrect-type' error.`);
  98. }
  99. const classNameStr = className ? `${className}.` : '';
  100. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`;
  101. },
  102. 'incorrect-class': ({
  103. expectedClassName,
  104. paramName,
  105. moduleName,
  106. className,
  107. funcName,
  108. isReturnValueProblem
  109. }) => {
  110. if (!expectedClassName || !moduleName || !funcName) {
  111. throw new Error(`Unexpected input to 'incorrect-class' error.`);
  112. }
  113. const classNameStr = className ? `${className}.` : '';
  114. if (isReturnValueProblem) {
  115. return `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
  116. }
  117. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
  118. },
  119. 'missing-a-method': ({
  120. expectedMethod,
  121. paramName,
  122. moduleName,
  123. className,
  124. funcName
  125. }) => {
  126. if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
  127. throw new Error(`Unexpected input to 'missing-a-method' error.`);
  128. }
  129. return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
  130. },
  131. 'add-to-cache-list-unexpected-type': ({
  132. entry
  133. }) => {
  134. return `An unexpected entry was passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` + `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` + `strings with one or more characters, objects with a url property or ` + `Request objects.`;
  135. },
  136. 'add-to-cache-list-conflicting-entries': ({
  137. firstEntry,
  138. secondEntry
  139. }) => {
  140. if (!firstEntry || !secondEntry) {
  141. throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
  142. }
  143. return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${firstEntry} but different revision details. Workbox is ` + `unable to cache and version the asset correctly. Please remove one ` + `of the entries.`;
  144. },
  145. 'plugin-error-request-will-fetch': ({
  146. thrownErrorMessage
  147. }) => {
  148. if (!thrownErrorMessage) {
  149. throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
  150. }
  151. return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownErrorMessage}'.`;
  152. },
  153. 'invalid-cache-name': ({
  154. cacheNameId,
  155. value
  156. }) => {
  157. if (!cacheNameId) {
  158. throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
  159. }
  160. return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`;
  161. },
  162. 'unregister-route-but-not-found-with-method': ({
  163. method
  164. }) => {
  165. if (!method) {
  166. throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`);
  167. }
  168. return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`;
  169. },
  170. 'unregister-route-route-not-registered': () => {
  171. return `The route you're trying to unregister was not previously ` + `registered.`;
  172. },
  173. 'queue-replay-failed': ({
  174. name
  175. }) => {
  176. return `Replaying the background sync queue '${name}' failed.`;
  177. },
  178. 'duplicate-queue-name': ({
  179. name
  180. }) => {
  181. return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`;
  182. },
  183. 'expired-test-without-max-age': ({
  184. methodName,
  185. paramName
  186. }) => {
  187. return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
  188. },
  189. 'unsupported-route-type': ({
  190. moduleName,
  191. className,
  192. funcName,
  193. paramName
  194. }) => {
  195. return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`;
  196. },
  197. 'not-array-of-class': ({
  198. value,
  199. expectedClass,
  200. moduleName,
  201. className,
  202. funcName,
  203. paramName
  204. }) => {
  205. return `The supplied '${paramName}' parameter must be an array of ` + `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` + `Please check the call to ${moduleName}.${className}.${funcName}() ` + `to fix the issue.`;
  206. },
  207. 'max-entries-or-age-required': ({
  208. moduleName,
  209. className,
  210. funcName
  211. }) => {
  212. return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`;
  213. },
  214. 'statuses-or-headers-required': ({
  215. moduleName,
  216. className,
  217. funcName
  218. }) => {
  219. return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`;
  220. },
  221. 'invalid-string': ({
  222. moduleName,
  223. funcName,
  224. paramName
  225. }) => {
  226. if (!paramName || !moduleName || !funcName) {
  227. throw new Error(`Unexpected input to 'invalid-string' error.`);
  228. }
  229. return `When using strings, the '${paramName}' parameter must start with ` + `'http' (for cross-origin matches) or '/' (for same-origin matches). ` + `Please see the docs for ${moduleName}.${funcName}() for ` + `more info.`;
  230. },
  231. 'channel-name-required': () => {
  232. return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`;
  233. },
  234. 'invalid-responses-are-same-args': () => {
  235. return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`;
  236. },
  237. 'expire-custom-caches-only': () => {
  238. return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`;
  239. },
  240. 'unit-must-be-bytes': ({
  241. normalizedRangeHeader
  242. }) => {
  243. if (!normalizedRangeHeader) {
  244. throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
  245. }
  246. return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`;
  247. },
  248. 'single-range-only': ({
  249. normalizedRangeHeader
  250. }) => {
  251. if (!normalizedRangeHeader) {
  252. throw new Error(`Unexpected input to 'single-range-only' error.`);
  253. }
  254. return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`;
  255. },
  256. 'invalid-range-values': ({
  257. normalizedRangeHeader
  258. }) => {
  259. if (!normalizedRangeHeader) {
  260. throw new Error(`Unexpected input to 'invalid-range-values' error.`);
  261. }
  262. return `The Range header is missing both start and end values. At least ` + `one of those values is needed. The Range header provided was ` + `"${normalizedRangeHeader}"`;
  263. },
  264. 'no-range-header': () => {
  265. return `No Range header was found in the Request provided.`;
  266. },
  267. 'range-not-satisfiable': ({
  268. size,
  269. start,
  270. end
  271. }) => {
  272. return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
  273. },
  274. 'attempt-to-cache-non-get-request': ({
  275. url,
  276. method
  277. }) => {
  278. return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`;
  279. },
  280. 'cache-put-with-no-response': ({
  281. url
  282. }) => {
  283. return `There was an attempt to cache '${url}' but the response was not ` + `defined.`;
  284. },
  285. 'no-response': ({
  286. url,
  287. error
  288. }) => {
  289. let message = `The strategy could not generate a response for '${url}'.`;
  290. if (error) {
  291. message += ` The underlying error is ${error}.`;
  292. }
  293. return message;
  294. },
  295. 'bad-precaching-response': ({
  296. url,
  297. status
  298. }) => {
  299. return `The precaching request for '${url}' failed` + (status ? ` with an HTTP status of ${status}.` : `.`);
  300. },
  301. 'non-precached-url': ({
  302. url
  303. }) => {
  304. return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`;
  305. },
  306. 'add-to-cache-list-conflicting-integrities': ({
  307. url
  308. }) => {
  309. return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`;
  310. },
  311. 'missing-precache-entry': ({
  312. cacheName,
  313. url
  314. }) => {
  315. return `Unable to find a precached response in ${cacheName} for ${url}.`;
  316. },
  317. 'cross-origin-copy-response': ({
  318. origin
  319. }) => {
  320. return `workbox-core.copyResponse() can only be used with same-origin ` + `responses. It was passed a response with origin ${origin}.`;
  321. },
  322. 'opaque-streams-source': ({
  323. type
  324. }) => {
  325. const message = `One of the workbox-streams sources resulted in an ` + `'${type}' response.`;
  326. if (type === 'opaqueredirect') {
  327. return `${message} Please do not use a navigation request that results ` + `in a redirect as a source.`;
  328. }
  329. return `${message} Please ensure your sources are CORS-enabled.`;
  330. }
  331. };
  332. /*
  333. Copyright 2018 Google LLC
  334. Use of this source code is governed by an MIT-style
  335. license that can be found in the LICENSE file or at
  336. https://opensource.org/licenses/MIT.
  337. */
  338. const generatorFunction = (code, details = {}) => {
  339. const message = messages$1[code];
  340. if (!message) {
  341. throw new Error(`Unable to find message for code '${code}'.`);
  342. }
  343. return message(details);
  344. };
  345. const messageGenerator = generatorFunction;
  346. /*
  347. Copyright 2018 Google LLC
  348. Use of this source code is governed by an MIT-style
  349. license that can be found in the LICENSE file or at
  350. https://opensource.org/licenses/MIT.
  351. */
  352. /**
  353. * Workbox errors should be thrown with this class.
  354. * This allows use to ensure the type easily in tests,
  355. * helps developers identify errors from workbox
  356. * easily and allows use to optimise error
  357. * messages correctly.
  358. *
  359. * @private
  360. */
  361. class WorkboxError extends Error {
  362. /**
  363. *
  364. * @param {string} errorCode The error code that
  365. * identifies this particular error.
  366. * @param {Object=} details Any relevant arguments
  367. * that will help developers identify issues should
  368. * be added as a key on the context object.
  369. */
  370. constructor(errorCode, details) {
  371. const message = messageGenerator(errorCode, details);
  372. super(message);
  373. this.name = errorCode;
  374. this.details = details;
  375. }
  376. }
  377. /*
  378. Copyright 2018 Google LLC
  379. Use of this source code is governed by an MIT-style
  380. license that can be found in the LICENSE file or at
  381. https://opensource.org/licenses/MIT.
  382. */
  383. /*
  384. * This method throws if the supplied value is not an array.
  385. * The destructed values are required to produce a meaningful error for users.
  386. * The destructed and restructured object is so it's clear what is
  387. * needed.
  388. */
  389. const isArray = (value, details) => {
  390. if (!Array.isArray(value)) {
  391. throw new WorkboxError('not-an-array', details);
  392. }
  393. };
  394. const hasMethod = (object, expectedMethod, details) => {
  395. const type = typeof object[expectedMethod];
  396. if (type !== 'function') {
  397. details['expectedMethod'] = expectedMethod;
  398. throw new WorkboxError('missing-a-method', details);
  399. }
  400. };
  401. const isType = (object, expectedType, details) => {
  402. if (typeof object !== expectedType) {
  403. details['expectedType'] = expectedType;
  404. throw new WorkboxError('incorrect-type', details);
  405. }
  406. };
  407. const isInstance = (object,
  408. // Need the general type to do the check later.
  409. // eslint-disable-next-line @typescript-eslint/ban-types
  410. expectedClass, details) => {
  411. if (!(object instanceof expectedClass)) {
  412. details['expectedClassName'] = expectedClass.name;
  413. throw new WorkboxError('incorrect-class', details);
  414. }
  415. };
  416. const isOneOf = (value, validValues, details) => {
  417. if (!validValues.includes(value)) {
  418. details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`;
  419. throw new WorkboxError('invalid-value', details);
  420. }
  421. };
  422. const isArrayOfClass = (value,
  423. // Need general type to do check later.
  424. expectedClass,
  425. // eslint-disable-line
  426. details) => {
  427. const error = new WorkboxError('not-array-of-class', details);
  428. if (!Array.isArray(value)) {
  429. throw error;
  430. }
  431. for (const item of value) {
  432. if (!(item instanceof expectedClass)) {
  433. throw error;
  434. }
  435. }
  436. };
  437. const finalAssertExports = {
  438. hasMethod,
  439. isArray,
  440. isInstance,
  441. isOneOf,
  442. isType,
  443. isArrayOfClass
  444. };
  445. // @ts-ignore
  446. try {
  447. self['workbox:routing:7.0.0'] && _();
  448. } catch (e) {}
  449. /*
  450. Copyright 2018 Google LLC
  451. Use of this source code is governed by an MIT-style
  452. license that can be found in the LICENSE file or at
  453. https://opensource.org/licenses/MIT.
  454. */
  455. /**
  456. * The default HTTP method, 'GET', used when there's no specific method
  457. * configured for a route.
  458. *
  459. * @type {string}
  460. *
  461. * @private
  462. */
  463. const defaultMethod = 'GET';
  464. /**
  465. * The list of valid HTTP methods associated with requests that could be routed.
  466. *
  467. * @type {Array<string>}
  468. *
  469. * @private
  470. */
  471. const validMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT'];
  472. /*
  473. Copyright 2018 Google LLC
  474. Use of this source code is governed by an MIT-style
  475. license that can be found in the LICENSE file or at
  476. https://opensource.org/licenses/MIT.
  477. */
  478. /**
  479. * @param {function()|Object} handler Either a function, or an object with a
  480. * 'handle' method.
  481. * @return {Object} An object with a handle method.
  482. *
  483. * @private
  484. */
  485. const normalizeHandler = handler => {
  486. if (handler && typeof handler === 'object') {
  487. {
  488. finalAssertExports.hasMethod(handler, 'handle', {
  489. moduleName: 'workbox-routing',
  490. className: 'Route',
  491. funcName: 'constructor',
  492. paramName: 'handler'
  493. });
  494. }
  495. return handler;
  496. } else {
  497. {
  498. finalAssertExports.isType(handler, 'function', {
  499. moduleName: 'workbox-routing',
  500. className: 'Route',
  501. funcName: 'constructor',
  502. paramName: 'handler'
  503. });
  504. }
  505. return {
  506. handle: handler
  507. };
  508. }
  509. };
  510. /*
  511. Copyright 2018 Google LLC
  512. Use of this source code is governed by an MIT-style
  513. license that can be found in the LICENSE file or at
  514. https://opensource.org/licenses/MIT.
  515. */
  516. /**
  517. * A `Route` consists of a pair of callback functions, "match" and "handler".
  518. * The "match" callback determine if a route should be used to "handle" a
  519. * request by returning a non-falsy value if it can. The "handler" callback
  520. * is called when there is a match and should return a Promise that resolves
  521. * to a `Response`.
  522. *
  523. * @memberof workbox-routing
  524. */
  525. class Route {
  526. /**
  527. * Constructor for Route class.
  528. *
  529. * @param {workbox-routing~matchCallback} match
  530. * A callback function that determines whether the route matches a given
  531. * `fetch` event by returning a non-falsy value.
  532. * @param {workbox-routing~handlerCallback} handler A callback
  533. * function that returns a Promise resolving to a Response.
  534. * @param {string} [method='GET'] The HTTP method to match the Route
  535. * against.
  536. */
  537. constructor(match, handler, method = defaultMethod) {
  538. {
  539. finalAssertExports.isType(match, 'function', {
  540. moduleName: 'workbox-routing',
  541. className: 'Route',
  542. funcName: 'constructor',
  543. paramName: 'match'
  544. });
  545. if (method) {
  546. finalAssertExports.isOneOf(method, validMethods, {
  547. paramName: 'method'
  548. });
  549. }
  550. }
  551. // These values are referenced directly by Router so cannot be
  552. // altered by minificaton.
  553. this.handler = normalizeHandler(handler);
  554. this.match = match;
  555. this.method = method;
  556. }
  557. /**
  558. *
  559. * @param {workbox-routing-handlerCallback} handler A callback
  560. * function that returns a Promise resolving to a Response
  561. */
  562. setCatchHandler(handler) {
  563. this.catchHandler = normalizeHandler(handler);
  564. }
  565. }
  566. /*
  567. Copyright 2018 Google LLC
  568. Use of this source code is governed by an MIT-style
  569. license that can be found in the LICENSE file or at
  570. https://opensource.org/licenses/MIT.
  571. */
  572. /**
  573. * RegExpRoute makes it easy to create a regular expression based
  574. * {@link workbox-routing.Route}.
  575. *
  576. * For same-origin requests the RegExp only needs to match part of the URL. For
  577. * requests against third-party servers, you must define a RegExp that matches
  578. * the start of the URL.
  579. *
  580. * @memberof workbox-routing
  581. * @extends workbox-routing.Route
  582. */
  583. class RegExpRoute extends Route {
  584. /**
  585. * If the regular expression contains
  586. * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},
  587. * the captured values will be passed to the
  588. * {@link workbox-routing~handlerCallback} `params`
  589. * argument.
  590. *
  591. * @param {RegExp} regExp The regular expression to match against URLs.
  592. * @param {workbox-routing~handlerCallback} handler A callback
  593. * function that returns a Promise resulting in a Response.
  594. * @param {string} [method='GET'] The HTTP method to match the Route
  595. * against.
  596. */
  597. constructor(regExp, handler, method) {
  598. {
  599. finalAssertExports.isInstance(regExp, RegExp, {
  600. moduleName: 'workbox-routing',
  601. className: 'RegExpRoute',
  602. funcName: 'constructor',
  603. paramName: 'pattern'
  604. });
  605. }
  606. const match = ({
  607. url
  608. }) => {
  609. const result = regExp.exec(url.href);
  610. // Return immediately if there's no match.
  611. if (!result) {
  612. return;
  613. }
  614. // Require that the match start at the first character in the URL string
  615. // if it's a cross-origin request.
  616. // See https://github.com/GoogleChrome/workbox/issues/281 for the context
  617. // behind this behavior.
  618. if (url.origin !== location.origin && result.index !== 0) {
  619. {
  620. logger.debug(`The regular expression '${regExp.toString()}' only partially matched ` + `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` + `handle cross-origin requests if they match the entire URL.`);
  621. }
  622. return;
  623. }
  624. // If the route matches, but there aren't any capture groups defined, then
  625. // this will return [], which is truthy and therefore sufficient to
  626. // indicate a match.
  627. // If there are capture groups, then it will return their values.
  628. return result.slice(1);
  629. };
  630. super(match, handler, method);
  631. }
  632. }
  633. /*
  634. Copyright 2018 Google LLC
  635. Use of this source code is governed by an MIT-style
  636. license that can be found in the LICENSE file or at
  637. https://opensource.org/licenses/MIT.
  638. */
  639. const getFriendlyURL = url => {
  640. const urlObj = new URL(String(url), location.href);
  641. // See https://github.com/GoogleChrome/workbox/issues/2323
  642. // We want to include everything, except for the origin if it's same-origin.
  643. return urlObj.href.replace(new RegExp(`^${location.origin}`), '');
  644. };
  645. /*
  646. Copyright 2018 Google LLC
  647. Use of this source code is governed by an MIT-style
  648. license that can be found in the LICENSE file or at
  649. https://opensource.org/licenses/MIT.
  650. */
  651. /**
  652. * The Router can be used to process a `FetchEvent` using one or more
  653. * {@link workbox-routing.Route}, responding with a `Response` if
  654. * a matching route exists.
  655. *
  656. * If no route matches a given a request, the Router will use a "default"
  657. * handler if one is defined.
  658. *
  659. * Should the matching Route throw an error, the Router will use a "catch"
  660. * handler if one is defined to gracefully deal with issues and respond with a
  661. * Request.
  662. *
  663. * If a request matches multiple routes, the **earliest** registered route will
  664. * be used to respond to the request.
  665. *
  666. * @memberof workbox-routing
  667. */
  668. class Router {
  669. /**
  670. * Initializes a new Router.
  671. */
  672. constructor() {
  673. this._routes = new Map();
  674. this._defaultHandlerMap = new Map();
  675. }
  676. /**
  677. * @return {Map<string, Array<workbox-routing.Route>>} routes A `Map` of HTTP
  678. * method name ('GET', etc.) to an array of all the corresponding `Route`
  679. * instances that are registered.
  680. */
  681. get routes() {
  682. return this._routes;
  683. }
  684. /**
  685. * Adds a fetch event listener to respond to events when a route matches
  686. * the event's request.
  687. */
  688. addFetchListener() {
  689. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  690. self.addEventListener('fetch', event => {
  691. const {
  692. request
  693. } = event;
  694. const responsePromise = this.handleRequest({
  695. request,
  696. event
  697. });
  698. if (responsePromise) {
  699. event.respondWith(responsePromise);
  700. }
  701. });
  702. }
  703. /**
  704. * Adds a message event listener for URLs to cache from the window.
  705. * This is useful to cache resources loaded on the page prior to when the
  706. * service worker started controlling it.
  707. *
  708. * The format of the message data sent from the window should be as follows.
  709. * Where the `urlsToCache` array may consist of URL strings or an array of
  710. * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
  711. *
  712. * ```
  713. * {
  714. * type: 'CACHE_URLS',
  715. * payload: {
  716. * urlsToCache: [
  717. * './script1.js',
  718. * './script2.js',
  719. * ['./script3.js', {mode: 'no-cors'}],
  720. * ],
  721. * },
  722. * }
  723. * ```
  724. */
  725. addCacheListener() {
  726. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  727. self.addEventListener('message', event => {
  728. // event.data is type 'any'
  729. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  730. if (event.data && event.data.type === 'CACHE_URLS') {
  731. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  732. const {
  733. payload
  734. } = event.data;
  735. {
  736. logger.debug(`Caching URLs from the window`, payload.urlsToCache);
  737. }
  738. const requestPromises = Promise.all(payload.urlsToCache.map(entry => {
  739. if (typeof entry === 'string') {
  740. entry = [entry];
  741. }
  742. const request = new Request(...entry);
  743. return this.handleRequest({
  744. request,
  745. event
  746. });
  747. // TODO(philipwalton): TypeScript errors without this typecast for
  748. // some reason (probably a bug). The real type here should work but
  749. // doesn't: `Array<Promise<Response> | undefined>`.
  750. })); // TypeScript
  751. event.waitUntil(requestPromises);
  752. // If a MessageChannel was used, reply to the message on success.
  753. if (event.ports && event.ports[0]) {
  754. void requestPromises.then(() => event.ports[0].postMessage(true));
  755. }
  756. }
  757. });
  758. }
  759. /**
  760. * Apply the routing rules to a FetchEvent object to get a Response from an
  761. * appropriate Route's handler.
  762. *
  763. * @param {Object} options
  764. * @param {Request} options.request The request to handle.
  765. * @param {ExtendableEvent} options.event The event that triggered the
  766. * request.
  767. * @return {Promise<Response>|undefined} A promise is returned if a
  768. * registered route can handle the request. If there is no matching
  769. * route and there's no `defaultHandler`, `undefined` is returned.
  770. */
  771. handleRequest({
  772. request,
  773. event
  774. }) {
  775. {
  776. finalAssertExports.isInstance(request, Request, {
  777. moduleName: 'workbox-routing',
  778. className: 'Router',
  779. funcName: 'handleRequest',
  780. paramName: 'options.request'
  781. });
  782. }
  783. const url = new URL(request.url, location.href);
  784. if (!url.protocol.startsWith('http')) {
  785. {
  786. logger.debug(`Workbox Router only supports URLs that start with 'http'.`);
  787. }
  788. return;
  789. }
  790. const sameOrigin = url.origin === location.origin;
  791. const {
  792. params,
  793. route
  794. } = this.findMatchingRoute({
  795. event,
  796. request,
  797. sameOrigin,
  798. url
  799. });
  800. let handler = route && route.handler;
  801. const debugMessages = [];
  802. {
  803. if (handler) {
  804. debugMessages.push([`Found a route to handle this request:`, route]);
  805. if (params) {
  806. debugMessages.push([`Passing the following params to the route's handler:`, params]);
  807. }
  808. }
  809. }
  810. // If we don't have a handler because there was no matching route, then
  811. // fall back to defaultHandler if that's defined.
  812. const method = request.method;
  813. if (!handler && this._defaultHandlerMap.has(method)) {
  814. {
  815. debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler for ${method}.`);
  816. }
  817. handler = this._defaultHandlerMap.get(method);
  818. }
  819. if (!handler) {
  820. {
  821. // No handler so Workbox will do nothing. If logs is set of debug
  822. // i.e. verbose, we should print out this information.
  823. logger.debug(`No route found for: ${getFriendlyURL(url)}`);
  824. }
  825. return;
  826. }
  827. {
  828. // We have a handler, meaning Workbox is going to handle the route.
  829. // print the routing details to the console.
  830. logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
  831. debugMessages.forEach(msg => {
  832. if (Array.isArray(msg)) {
  833. logger.log(...msg);
  834. } else {
  835. logger.log(msg);
  836. }
  837. });
  838. logger.groupEnd();
  839. }
  840. // Wrap in try and catch in case the handle method throws a synchronous
  841. // error. It should still callback to the catch handler.
  842. let responsePromise;
  843. try {
  844. responsePromise = handler.handle({
  845. url,
  846. request,
  847. event,
  848. params
  849. });
  850. } catch (err) {
  851. responsePromise = Promise.reject(err);
  852. }
  853. // Get route's catch handler, if it exists
  854. const catchHandler = route && route.catchHandler;
  855. if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
  856. responsePromise = responsePromise.catch(async err => {
  857. // If there's a route catch handler, process that first
  858. if (catchHandler) {
  859. {
  860. // Still include URL here as it will be async from the console group
  861. // and may not make sense without the URL
  862. logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
  863. logger.error(`Error thrown by:`, route);
  864. logger.error(err);
  865. logger.groupEnd();
  866. }
  867. try {
  868. return await catchHandler.handle({
  869. url,
  870. request,
  871. event,
  872. params
  873. });
  874. } catch (catchErr) {
  875. if (catchErr instanceof Error) {
  876. err = catchErr;
  877. }
  878. }
  879. }
  880. if (this._catchHandler) {
  881. {
  882. // Still include URL here as it will be async from the console group
  883. // and may not make sense without the URL
  884. logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
  885. logger.error(`Error thrown by:`, route);
  886. logger.error(err);
  887. logger.groupEnd();
  888. }
  889. return this._catchHandler.handle({
  890. url,
  891. request,
  892. event
  893. });
  894. }
  895. throw err;
  896. });
  897. }
  898. return responsePromise;
  899. }
  900. /**
  901. * Checks a request and URL (and optionally an event) against the list of
  902. * registered routes, and if there's a match, returns the corresponding
  903. * route along with any params generated by the match.
  904. *
  905. * @param {Object} options
  906. * @param {URL} options.url
  907. * @param {boolean} options.sameOrigin The result of comparing `url.origin`
  908. * against the current origin.
  909. * @param {Request} options.request The request to match.
  910. * @param {Event} options.event The corresponding event.
  911. * @return {Object} An object with `route` and `params` properties.
  912. * They are populated if a matching route was found or `undefined`
  913. * otherwise.
  914. */
  915. findMatchingRoute({
  916. url,
  917. sameOrigin,
  918. request,
  919. event
  920. }) {
  921. const routes = this._routes.get(request.method) || [];
  922. for (const route of routes) {
  923. let params;
  924. // route.match returns type any, not possible to change right now.
  925. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  926. const matchResult = route.match({
  927. url,
  928. sameOrigin,
  929. request,
  930. event
  931. });
  932. if (matchResult) {
  933. {
  934. // Warn developers that using an async matchCallback is almost always
  935. // not the right thing to do.
  936. if (matchResult instanceof Promise) {
  937. logger.warn(`While routing ${getFriendlyURL(url)}, an async ` + `matchCallback function was used. Please convert the ` + `following route to use a synchronous matchCallback function:`, route);
  938. }
  939. }
  940. // See https://github.com/GoogleChrome/workbox/issues/2079
  941. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  942. params = matchResult;
  943. if (Array.isArray(params) && params.length === 0) {
  944. // Instead of passing an empty array in as params, use undefined.
  945. params = undefined;
  946. } else if (matchResult.constructor === Object &&
  947. // eslint-disable-line
  948. Object.keys(matchResult).length === 0) {
  949. // Instead of passing an empty object in as params, use undefined.
  950. params = undefined;
  951. } else if (typeof matchResult === 'boolean') {
  952. // For the boolean value true (rather than just something truth-y),
  953. // don't set params.
  954. // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
  955. params = undefined;
  956. }
  957. // Return early if have a match.
  958. return {
  959. route,
  960. params
  961. };
  962. }
  963. }
  964. // If no match was found above, return and empty object.
  965. return {};
  966. }
  967. /**
  968. * Define a default `handler` that's called when no routes explicitly
  969. * match the incoming request.
  970. *
  971. * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
  972. *
  973. * Without a default handler, unmatched requests will go against the
  974. * network as if there were no service worker present.
  975. *
  976. * @param {workbox-routing~handlerCallback} handler A callback
  977. * function that returns a Promise resulting in a Response.
  978. * @param {string} [method='GET'] The HTTP method to associate with this
  979. * default handler. Each method has its own default.
  980. */
  981. setDefaultHandler(handler, method = defaultMethod) {
  982. this._defaultHandlerMap.set(method, normalizeHandler(handler));
  983. }
  984. /**
  985. * If a Route throws an error while handling a request, this `handler`
  986. * will be called and given a chance to provide a response.
  987. *
  988. * @param {workbox-routing~handlerCallback} handler A callback
  989. * function that returns a Promise resulting in a Response.
  990. */
  991. setCatchHandler(handler) {
  992. this._catchHandler = normalizeHandler(handler);
  993. }
  994. /**
  995. * Registers a route with the router.
  996. *
  997. * @param {workbox-routing.Route} route The route to register.
  998. */
  999. registerRoute(route) {
  1000. {
  1001. finalAssertExports.isType(route, 'object', {
  1002. moduleName: 'workbox-routing',
  1003. className: 'Router',
  1004. funcName: 'registerRoute',
  1005. paramName: 'route'
  1006. });
  1007. finalAssertExports.hasMethod(route, 'match', {
  1008. moduleName: 'workbox-routing',
  1009. className: 'Router',
  1010. funcName: 'registerRoute',
  1011. paramName: 'route'
  1012. });
  1013. finalAssertExports.isType(route.handler, 'object', {
  1014. moduleName: 'workbox-routing',
  1015. className: 'Router',
  1016. funcName: 'registerRoute',
  1017. paramName: 'route'
  1018. });
  1019. finalAssertExports.hasMethod(route.handler, 'handle', {
  1020. moduleName: 'workbox-routing',
  1021. className: 'Router',
  1022. funcName: 'registerRoute',
  1023. paramName: 'route.handler'
  1024. });
  1025. finalAssertExports.isType(route.method, 'string', {
  1026. moduleName: 'workbox-routing',
  1027. className: 'Router',
  1028. funcName: 'registerRoute',
  1029. paramName: 'route.method'
  1030. });
  1031. }
  1032. if (!this._routes.has(route.method)) {
  1033. this._routes.set(route.method, []);
  1034. }
  1035. // Give precedence to all of the earlier routes by adding this additional
  1036. // route to the end of the array.
  1037. this._routes.get(route.method).push(route);
  1038. }
  1039. /**
  1040. * Unregisters a route with the router.
  1041. *
  1042. * @param {workbox-routing.Route} route The route to unregister.
  1043. */
  1044. unregisterRoute(route) {
  1045. if (!this._routes.has(route.method)) {
  1046. throw new WorkboxError('unregister-route-but-not-found-with-method', {
  1047. method: route.method
  1048. });
  1049. }
  1050. const routeIndex = this._routes.get(route.method).indexOf(route);
  1051. if (routeIndex > -1) {
  1052. this._routes.get(route.method).splice(routeIndex, 1);
  1053. } else {
  1054. throw new WorkboxError('unregister-route-route-not-registered');
  1055. }
  1056. }
  1057. }
  1058. /*
  1059. Copyright 2019 Google LLC
  1060. Use of this source code is governed by an MIT-style
  1061. license that can be found in the LICENSE file or at
  1062. https://opensource.org/licenses/MIT.
  1063. */
  1064. let defaultRouter;
  1065. /**
  1066. * Creates a new, singleton Router instance if one does not exist. If one
  1067. * does already exist, that instance is returned.
  1068. *
  1069. * @private
  1070. * @return {Router}
  1071. */
  1072. const getOrCreateDefaultRouter = () => {
  1073. if (!defaultRouter) {
  1074. defaultRouter = new Router();
  1075. // The helpers that use the default Router assume these listeners exist.
  1076. defaultRouter.addFetchListener();
  1077. defaultRouter.addCacheListener();
  1078. }
  1079. return defaultRouter;
  1080. };
  1081. /*
  1082. Copyright 2019 Google LLC
  1083. Use of this source code is governed by an MIT-style
  1084. license that can be found in the LICENSE file or at
  1085. https://opensource.org/licenses/MIT.
  1086. */
  1087. /**
  1088. * Easily register a RegExp, string, or function with a caching
  1089. * strategy to a singleton Router instance.
  1090. *
  1091. * This method will generate a Route for you if needed and
  1092. * call {@link workbox-routing.Router#registerRoute}.
  1093. *
  1094. * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture
  1095. * If the capture param is a `Route`, all other arguments will be ignored.
  1096. * @param {workbox-routing~handlerCallback} [handler] A callback
  1097. * function that returns a Promise resulting in a Response. This parameter
  1098. * is required if `capture` is not a `Route` object.
  1099. * @param {string} [method='GET'] The HTTP method to match the Route
  1100. * against.
  1101. * @return {workbox-routing.Route} The generated `Route`.
  1102. *
  1103. * @memberof workbox-routing
  1104. */
  1105. function registerRoute(capture, handler, method) {
  1106. let route;
  1107. if (typeof capture === 'string') {
  1108. const captureUrl = new URL(capture, location.href);
  1109. {
  1110. if (!(capture.startsWith('/') || capture.startsWith('http'))) {
  1111. throw new WorkboxError('invalid-string', {
  1112. moduleName: 'workbox-routing',
  1113. funcName: 'registerRoute',
  1114. paramName: 'capture'
  1115. });
  1116. }
  1117. // We want to check if Express-style wildcards are in the pathname only.
  1118. // TODO: Remove this log message in v4.
  1119. const valueToCheck = capture.startsWith('http') ? captureUrl.pathname : capture;
  1120. // See https://github.com/pillarjs/path-to-regexp#parameters
  1121. const wildcards = '[*:?+]';
  1122. if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
  1123. logger.debug(`The '$capture' parameter contains an Express-style wildcard ` + `character (${wildcards}). Strings are now always interpreted as ` + `exact matches; use a RegExp for partial or wildcard matches.`);
  1124. }
  1125. }
  1126. const matchCallback = ({
  1127. url
  1128. }) => {
  1129. {
  1130. if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
  1131. logger.debug(`${capture} only partially matches the cross-origin URL ` + `${url.toString()}. This route will only handle cross-origin requests ` + `if they match the entire URL.`);
  1132. }
  1133. }
  1134. return url.href === captureUrl.href;
  1135. };
  1136. // If `capture` is a string then `handler` and `method` must be present.
  1137. route = new Route(matchCallback, handler, method);
  1138. } else if (capture instanceof RegExp) {
  1139. // If `capture` is a `RegExp` then `handler` and `method` must be present.
  1140. route = new RegExpRoute(capture, handler, method);
  1141. } else if (typeof capture === 'function') {
  1142. // If `capture` is a function then `handler` and `method` must be present.
  1143. route = new Route(capture, handler, method);
  1144. } else if (capture instanceof Route) {
  1145. route = capture;
  1146. } else {
  1147. throw new WorkboxError('unsupported-route-type', {
  1148. moduleName: 'workbox-routing',
  1149. funcName: 'registerRoute',
  1150. paramName: 'capture'
  1151. });
  1152. }
  1153. const defaultRouter = getOrCreateDefaultRouter();
  1154. defaultRouter.registerRoute(route);
  1155. return route;
  1156. }
  1157. /*
  1158. Copyright 2019 Google LLC
  1159. Use of this source code is governed by an MIT-style
  1160. license that can be found in the LICENSE file or at
  1161. https://opensource.org/licenses/MIT.
  1162. */
  1163. /**
  1164. * Returns a promise that resolves and the passed number of milliseconds.
  1165. * This utility is an async/await-friendly version of `setTimeout`.
  1166. *
  1167. * @param {number} ms
  1168. * @return {Promise}
  1169. * @private
  1170. */
  1171. function timeout(ms) {
  1172. return new Promise(resolve => setTimeout(resolve, ms));
  1173. }
  1174. /*
  1175. Copyright 2018 Google LLC
  1176. Use of this source code is governed by an MIT-style
  1177. license that can be found in the LICENSE file or at
  1178. https://opensource.org/licenses/MIT.
  1179. */
  1180. const _cacheNameDetails = {
  1181. googleAnalytics: 'googleAnalytics',
  1182. precache: 'precache-v2',
  1183. prefix: 'workbox',
  1184. runtime: 'runtime',
  1185. suffix: typeof registration !== 'undefined' ? registration.scope : ''
  1186. };
  1187. const _createCacheName = cacheName => {
  1188. return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter(value => value && value.length > 0).join('-');
  1189. };
  1190. const eachCacheNameDetail = fn => {
  1191. for (const key of Object.keys(_cacheNameDetails)) {
  1192. fn(key);
  1193. }
  1194. };
  1195. const cacheNames = {
  1196. updateDetails: details => {
  1197. eachCacheNameDetail(key => {
  1198. if (typeof details[key] === 'string') {
  1199. _cacheNameDetails[key] = details[key];
  1200. }
  1201. });
  1202. },
  1203. getGoogleAnalyticsName: userCacheName => {
  1204. return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
  1205. },
  1206. getPrecacheName: userCacheName => {
  1207. return userCacheName || _createCacheName(_cacheNameDetails.precache);
  1208. },
  1209. getPrefix: () => {
  1210. return _cacheNameDetails.prefix;
  1211. },
  1212. getRuntimeName: userCacheName => {
  1213. return userCacheName || _createCacheName(_cacheNameDetails.runtime);
  1214. },
  1215. getSuffix: () => {
  1216. return _cacheNameDetails.suffix;
  1217. }
  1218. };
  1219. /*
  1220. Copyright 2020 Google LLC
  1221. Use of this source code is governed by an MIT-style
  1222. license that can be found in the LICENSE file or at
  1223. https://opensource.org/licenses/MIT.
  1224. */
  1225. function stripParams(fullURL, ignoreParams) {
  1226. const strippedURL = new URL(fullURL);
  1227. for (const param of ignoreParams) {
  1228. strippedURL.searchParams.delete(param);
  1229. }
  1230. return strippedURL.href;
  1231. }
  1232. /**
  1233. * Matches an item in the cache, ignoring specific URL params. This is similar
  1234. * to the `ignoreSearch` option, but it allows you to ignore just specific
  1235. * params (while continuing to match on the others).
  1236. *
  1237. * @private
  1238. * @param {Cache} cache
  1239. * @param {Request} request
  1240. * @param {Object} matchOptions
  1241. * @param {Array<string>} ignoreParams
  1242. * @return {Promise<Response|undefined>}
  1243. */
  1244. async function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {
  1245. const strippedRequestURL = stripParams(request.url, ignoreParams);
  1246. // If the request doesn't include any ignored params, match as normal.
  1247. if (request.url === strippedRequestURL) {
  1248. return cache.match(request, matchOptions);
  1249. }
  1250. // Otherwise, match by comparing keys
  1251. const keysOptions = Object.assign(Object.assign({}, matchOptions), {
  1252. ignoreSearch: true
  1253. });
  1254. const cacheKeys = await cache.keys(request, keysOptions);
  1255. for (const cacheKey of cacheKeys) {
  1256. const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);
  1257. if (strippedRequestURL === strippedCacheKeyURL) {
  1258. return cache.match(cacheKey, matchOptions);
  1259. }
  1260. }
  1261. return;
  1262. }
  1263. /*
  1264. Copyright 2018 Google LLC
  1265. Use of this source code is governed by an MIT-style
  1266. license that can be found in the LICENSE file or at
  1267. https://opensource.org/licenses/MIT.
  1268. */
  1269. /**
  1270. * The Deferred class composes Promises in a way that allows for them to be
  1271. * resolved or rejected from outside the constructor. In most cases promises
  1272. * should be used directly, but Deferreds can be necessary when the logic to
  1273. * resolve a promise must be separate.
  1274. *
  1275. * @private
  1276. */
  1277. class Deferred {
  1278. /**
  1279. * Creates a promise and exposes its resolve and reject functions as methods.
  1280. */
  1281. constructor() {
  1282. this.promise = new Promise((resolve, reject) => {
  1283. this.resolve = resolve;
  1284. this.reject = reject;
  1285. });
  1286. }
  1287. }
  1288. /*
  1289. Copyright 2018 Google LLC
  1290. Use of this source code is governed by an MIT-style
  1291. license that can be found in the LICENSE file or at
  1292. https://opensource.org/licenses/MIT.
  1293. */
  1294. // Callbacks to be executed whenever there's a quota error.
  1295. // Can't change Function type right now.
  1296. // eslint-disable-next-line @typescript-eslint/ban-types
  1297. const quotaErrorCallbacks = new Set();
  1298. /*
  1299. Copyright 2018 Google LLC
  1300. Use of this source code is governed by an MIT-style
  1301. license that can be found in the LICENSE file or at
  1302. https://opensource.org/licenses/MIT.
  1303. */
  1304. /**
  1305. * Runs all of the callback functions, one at a time sequentially, in the order
  1306. * in which they were registered.
  1307. *
  1308. * @memberof workbox-core
  1309. * @private
  1310. */
  1311. async function executeQuotaErrorCallbacks() {
  1312. {
  1313. logger.log(`About to run ${quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`);
  1314. }
  1315. for (const callback of quotaErrorCallbacks) {
  1316. await callback();
  1317. {
  1318. logger.log(callback, 'is complete.');
  1319. }
  1320. }
  1321. {
  1322. logger.log('Finished running callbacks.');
  1323. }
  1324. }
  1325. // @ts-ignore
  1326. try {
  1327. self['workbox:strategies:7.0.0'] && _();
  1328. } catch (e) {}
  1329. /*
  1330. Copyright 2020 Google LLC
  1331. Use of this source code is governed by an MIT-style
  1332. license that can be found in the LICENSE file or at
  1333. https://opensource.org/licenses/MIT.
  1334. */
  1335. function toRequest(input) {
  1336. return typeof input === 'string' ? new Request(input) : input;
  1337. }
  1338. /**
  1339. * A class created every time a Strategy instance instance calls
  1340. * {@link workbox-strategies.Strategy~handle} or
  1341. * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and
  1342. * cache actions around plugin callbacks and keeps track of when the strategy
  1343. * is "done" (i.e. all added `event.waitUntil()` promises have resolved).
  1344. *
  1345. * @memberof workbox-strategies
  1346. */
  1347. class StrategyHandler {
  1348. /**
  1349. * Creates a new instance associated with the passed strategy and event
  1350. * that's handling the request.
  1351. *
  1352. * The constructor also initializes the state that will be passed to each of
  1353. * the plugins handling this request.
  1354. *
  1355. * @param {workbox-strategies.Strategy} strategy
  1356. * @param {Object} options
  1357. * @param {Request|string} options.request A request to run this strategy for.
  1358. * @param {ExtendableEvent} options.event The event associated with the
  1359. * request.
  1360. * @param {URL} [options.url]
  1361. * @param {*} [options.params] The return value from the
  1362. * {@link workbox-routing~matchCallback} (if applicable).
  1363. */
  1364. constructor(strategy, options) {
  1365. this._cacheKeys = {};
  1366. /**
  1367. * The request the strategy is performing (passed to the strategy's
  1368. * `handle()` or `handleAll()` method).
  1369. * @name request
  1370. * @instance
  1371. * @type {Request}
  1372. * @memberof workbox-strategies.StrategyHandler
  1373. */
  1374. /**
  1375. * The event associated with this request.
  1376. * @name event
  1377. * @instance
  1378. * @type {ExtendableEvent}
  1379. * @memberof workbox-strategies.StrategyHandler
  1380. */
  1381. /**
  1382. * A `URL` instance of `request.url` (if passed to the strategy's
  1383. * `handle()` or `handleAll()` method).
  1384. * Note: the `url` param will be present if the strategy was invoked
  1385. * from a workbox `Route` object.
  1386. * @name url
  1387. * @instance
  1388. * @type {URL|undefined}
  1389. * @memberof workbox-strategies.StrategyHandler
  1390. */
  1391. /**
  1392. * A `param` value (if passed to the strategy's
  1393. * `handle()` or `handleAll()` method).
  1394. * Note: the `param` param will be present if the strategy was invoked
  1395. * from a workbox `Route` object and the
  1396. * {@link workbox-routing~matchCallback} returned
  1397. * a truthy value (it will be that value).
  1398. * @name params
  1399. * @instance
  1400. * @type {*|undefined}
  1401. * @memberof workbox-strategies.StrategyHandler
  1402. */
  1403. {
  1404. finalAssertExports.isInstance(options.event, ExtendableEvent, {
  1405. moduleName: 'workbox-strategies',
  1406. className: 'StrategyHandler',
  1407. funcName: 'constructor',
  1408. paramName: 'options.event'
  1409. });
  1410. }
  1411. Object.assign(this, options);
  1412. this.event = options.event;
  1413. this._strategy = strategy;
  1414. this._handlerDeferred = new Deferred();
  1415. this._extendLifetimePromises = [];
  1416. // Copy the plugins list (since it's mutable on the strategy),
  1417. // so any mutations don't affect this handler instance.
  1418. this._plugins = [...strategy.plugins];
  1419. this._pluginStateMap = new Map();
  1420. for (const plugin of this._plugins) {
  1421. this._pluginStateMap.set(plugin, {});
  1422. }
  1423. this.event.waitUntil(this._handlerDeferred.promise);
  1424. }
  1425. /**
  1426. * Fetches a given request (and invokes any applicable plugin callback
  1427. * methods) using the `fetchOptions` (for non-navigation requests) and
  1428. * `plugins` defined on the `Strategy` object.
  1429. *
  1430. * The following plugin lifecycle methods are invoked when using this method:
  1431. * - `requestWillFetch()`
  1432. * - `fetchDidSucceed()`
  1433. * - `fetchDidFail()`
  1434. *
  1435. * @param {Request|string} input The URL or request to fetch.
  1436. * @return {Promise<Response>}
  1437. */
  1438. async fetch(input) {
  1439. const {
  1440. event
  1441. } = this;
  1442. let request = toRequest(input);
  1443. if (request.mode === 'navigate' && event instanceof FetchEvent && event.preloadResponse) {
  1444. const possiblePreloadResponse = await event.preloadResponse;
  1445. if (possiblePreloadResponse) {
  1446. {
  1447. logger.log(`Using a preloaded navigation response for ` + `'${getFriendlyURL(request.url)}'`);
  1448. }
  1449. return possiblePreloadResponse;
  1450. }
  1451. }
  1452. // If there is a fetchDidFail plugin, we need to save a clone of the
  1453. // original request before it's either modified by a requestWillFetch
  1454. // plugin or before the original request's body is consumed via fetch().
  1455. const originalRequest = this.hasCallback('fetchDidFail') ? request.clone() : null;
  1456. try {
  1457. for (const cb of this.iterateCallbacks('requestWillFetch')) {
  1458. request = await cb({
  1459. request: request.clone(),
  1460. event
  1461. });
  1462. }
  1463. } catch (err) {
  1464. if (err instanceof Error) {
  1465. throw new WorkboxError('plugin-error-request-will-fetch', {
  1466. thrownErrorMessage: err.message
  1467. });
  1468. }
  1469. }
  1470. // The request can be altered by plugins with `requestWillFetch` making
  1471. // the original request (most likely from a `fetch` event) different
  1472. // from the Request we make. Pass both to `fetchDidFail` to aid debugging.
  1473. const pluginFilteredRequest = request.clone();
  1474. try {
  1475. let fetchResponse;
  1476. // See https://github.com/GoogleChrome/workbox/issues/1796
  1477. fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions);
  1478. if ("development" !== 'production') {
  1479. logger.debug(`Network request for ` + `'${getFriendlyURL(request.url)}' returned a response with ` + `status '${fetchResponse.status}'.`);
  1480. }
  1481. for (const callback of this.iterateCallbacks('fetchDidSucceed')) {
  1482. fetchResponse = await callback({
  1483. event,
  1484. request: pluginFilteredRequest,
  1485. response: fetchResponse
  1486. });
  1487. }
  1488. return fetchResponse;
  1489. } catch (error) {
  1490. {
  1491. logger.log(`Network request for ` + `'${getFriendlyURL(request.url)}' threw an error.`, error);
  1492. }
  1493. // `originalRequest` will only exist if a `fetchDidFail` callback
  1494. // is being used (see above).
  1495. if (originalRequest) {
  1496. await this.runCallbacks('fetchDidFail', {
  1497. error: error,
  1498. event,
  1499. originalRequest: originalRequest.clone(),
  1500. request: pluginFilteredRequest.clone()
  1501. });
  1502. }
  1503. throw error;
  1504. }
  1505. }
  1506. /**
  1507. * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on
  1508. * the response generated by `this.fetch()`.
  1509. *
  1510. * The call to `this.cachePut()` automatically invokes `this.waitUntil()`,
  1511. * so you do not have to manually call `waitUntil()` on the event.
  1512. *
  1513. * @param {Request|string} input The request or URL to fetch and cache.
  1514. * @return {Promise<Response>}
  1515. */
  1516. async fetchAndCachePut(input) {
  1517. const response = await this.fetch(input);
  1518. const responseClone = response.clone();
  1519. void this.waitUntil(this.cachePut(input, responseClone));
  1520. return response;
  1521. }
  1522. /**
  1523. * Matches a request from the cache (and invokes any applicable plugin
  1524. * callback methods) using the `cacheName`, `matchOptions`, and `plugins`
  1525. * defined on the strategy object.
  1526. *
  1527. * The following plugin lifecycle methods are invoked when using this method:
  1528. * - cacheKeyWillByUsed()
  1529. * - cachedResponseWillByUsed()
  1530. *
  1531. * @param {Request|string} key The Request or URL to use as the cache key.
  1532. * @return {Promise<Response|undefined>} A matching response, if found.
  1533. */
  1534. async cacheMatch(key) {
  1535. const request = toRequest(key);
  1536. let cachedResponse;
  1537. const {
  1538. cacheName,
  1539. matchOptions
  1540. } = this._strategy;
  1541. const effectiveRequest = await this.getCacheKey(request, 'read');
  1542. const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), {
  1543. cacheName
  1544. });
  1545. cachedResponse = await caches.match(effectiveRequest, multiMatchOptions);
  1546. {
  1547. if (cachedResponse) {
  1548. logger.debug(`Found a cached response in '${cacheName}'.`);
  1549. } else {
  1550. logger.debug(`No cached response found in '${cacheName}'.`);
  1551. }
  1552. }
  1553. for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) {
  1554. cachedResponse = (await callback({
  1555. cacheName,
  1556. matchOptions,
  1557. cachedResponse,
  1558. request: effectiveRequest,
  1559. event: this.event
  1560. })) || undefined;
  1561. }
  1562. return cachedResponse;
  1563. }
  1564. /**
  1565. * Puts a request/response pair in the cache (and invokes any applicable
  1566. * plugin callback methods) using the `cacheName` and `plugins` defined on
  1567. * the strategy object.
  1568. *
  1569. * The following plugin lifecycle methods are invoked when using this method:
  1570. * - cacheKeyWillByUsed()
  1571. * - cacheWillUpdate()
  1572. * - cacheDidUpdate()
  1573. *
  1574. * @param {Request|string} key The request or URL to use as the cache key.
  1575. * @param {Response} response The response to cache.
  1576. * @return {Promise<boolean>} `false` if a cacheWillUpdate caused the response
  1577. * not be cached, and `true` otherwise.
  1578. */
  1579. async cachePut(key, response) {
  1580. const request = toRequest(key);
  1581. // Run in the next task to avoid blocking other cache reads.
  1582. // https://github.com/w3c/ServiceWorker/issues/1397
  1583. await timeout(0);
  1584. const effectiveRequest = await this.getCacheKey(request, 'write');
  1585. {
  1586. if (effectiveRequest.method && effectiveRequest.method !== 'GET') {
  1587. throw new WorkboxError('attempt-to-cache-non-get-request', {
  1588. url: getFriendlyURL(effectiveRequest.url),
  1589. method: effectiveRequest.method
  1590. });
  1591. }
  1592. // See https://github.com/GoogleChrome/workbox/issues/2818
  1593. const vary = response.headers.get('Vary');
  1594. if (vary) {
  1595. logger.debug(`The response for ${getFriendlyURL(effectiveRequest.url)} ` + `has a 'Vary: ${vary}' header. ` + `Consider setting the {ignoreVary: true} option on your strategy ` + `to ensure cache matching and deletion works as expected.`);
  1596. }
  1597. }
  1598. if (!response) {
  1599. {
  1600. logger.error(`Cannot cache non-existent response for ` + `'${getFriendlyURL(effectiveRequest.url)}'.`);
  1601. }
  1602. throw new WorkboxError('cache-put-with-no-response', {
  1603. url: getFriendlyURL(effectiveRequest.url)
  1604. });
  1605. }
  1606. const responseToCache = await this._ensureResponseSafeToCache(response);
  1607. if (!responseToCache) {
  1608. {
  1609. logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` + `will not be cached.`, responseToCache);
  1610. }
  1611. return false;
  1612. }
  1613. const {
  1614. cacheName,
  1615. matchOptions
  1616. } = this._strategy;
  1617. const cache = await self.caches.open(cacheName);
  1618. const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate');
  1619. const oldResponse = hasCacheUpdateCallback ? await cacheMatchIgnoreParams(
  1620. // TODO(philipwalton): the `__WB_REVISION__` param is a precaching
  1621. // feature. Consider into ways to only add this behavior if using
  1622. // precaching.
  1623. cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions) : null;
  1624. {
  1625. logger.debug(`Updating the '${cacheName}' cache with a new Response ` + `for ${getFriendlyURL(effectiveRequest.url)}.`);
  1626. }
  1627. try {
  1628. await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);
  1629. } catch (error) {
  1630. if (error instanceof Error) {
  1631. // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
  1632. if (error.name === 'QuotaExceededError') {
  1633. await executeQuotaErrorCallbacks();
  1634. }
  1635. throw error;
  1636. }
  1637. }
  1638. for (const callback of this.iterateCallbacks('cacheDidUpdate')) {
  1639. await callback({
  1640. cacheName,
  1641. oldResponse,
  1642. newResponse: responseToCache.clone(),
  1643. request: effectiveRequest,
  1644. event: this.event
  1645. });
  1646. }
  1647. return true;
  1648. }
  1649. /**
  1650. * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and
  1651. * executes any of those callbacks found in sequence. The final `Request`
  1652. * object returned by the last plugin is treated as the cache key for cache
  1653. * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have
  1654. * been registered, the passed request is returned unmodified
  1655. *
  1656. * @param {Request} request
  1657. * @param {string} mode
  1658. * @return {Promise<Request>}
  1659. */
  1660. async getCacheKey(request, mode) {
  1661. const key = `${request.url} | ${mode}`;
  1662. if (!this._cacheKeys[key]) {
  1663. let effectiveRequest = request;
  1664. for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) {
  1665. effectiveRequest = toRequest(await callback({
  1666. mode,
  1667. request: effectiveRequest,
  1668. event: this.event,
  1669. // params has a type any can't change right now.
  1670. params: this.params // eslint-disable-line
  1671. }));
  1672. }
  1673. this._cacheKeys[key] = effectiveRequest;
  1674. }
  1675. return this._cacheKeys[key];
  1676. }
  1677. /**
  1678. * Returns true if the strategy has at least one plugin with the given
  1679. * callback.
  1680. *
  1681. * @param {string} name The name of the callback to check for.
  1682. * @return {boolean}
  1683. */
  1684. hasCallback(name) {
  1685. for (const plugin of this._strategy.plugins) {
  1686. if (name in plugin) {
  1687. return true;
  1688. }
  1689. }
  1690. return false;
  1691. }
  1692. /**
  1693. * Runs all plugin callbacks matching the given name, in order, passing the
  1694. * given param object (merged ith the current plugin state) as the only
  1695. * argument.
  1696. *
  1697. * Note: since this method runs all plugins, it's not suitable for cases
  1698. * where the return value of a callback needs to be applied prior to calling
  1699. * the next callback. See
  1700. * {@link workbox-strategies.StrategyHandler#iterateCallbacks}
  1701. * below for how to handle that case.
  1702. *
  1703. * @param {string} name The name of the callback to run within each plugin.
  1704. * @param {Object} param The object to pass as the first (and only) param
  1705. * when executing each callback. This object will be merged with the
  1706. * current plugin state prior to callback execution.
  1707. */
  1708. async runCallbacks(name, param) {
  1709. for (const callback of this.iterateCallbacks(name)) {
  1710. // TODO(philipwalton): not sure why `any` is needed. It seems like
  1711. // this should work with `as WorkboxPluginCallbackParam[C]`.
  1712. await callback(param);
  1713. }
  1714. }
  1715. /**
  1716. * Accepts a callback and returns an iterable of matching plugin callbacks,
  1717. * where each callback is wrapped with the current handler state (i.e. when
  1718. * you call each callback, whatever object parameter you pass it will
  1719. * be merged with the plugin's current state).
  1720. *
  1721. * @param {string} name The name fo the callback to run
  1722. * @return {Array<Function>}
  1723. */
  1724. *iterateCallbacks(name) {
  1725. for (const plugin of this._strategy.plugins) {
  1726. if (typeof plugin[name] === 'function') {
  1727. const state = this._pluginStateMap.get(plugin);
  1728. const statefulCallback = param => {
  1729. const statefulParam = Object.assign(Object.assign({}, param), {
  1730. state
  1731. });
  1732. // TODO(philipwalton): not sure why `any` is needed. It seems like
  1733. // this should work with `as WorkboxPluginCallbackParam[C]`.
  1734. return plugin[name](statefulParam);
  1735. };
  1736. yield statefulCallback;
  1737. }
  1738. }
  1739. }
  1740. /**
  1741. * Adds a promise to the
  1742. * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises}
  1743. * of the event event associated with the request being handled (usually a
  1744. * `FetchEvent`).
  1745. *
  1746. * Note: you can await
  1747. * {@link workbox-strategies.StrategyHandler~doneWaiting}
  1748. * to know when all added promises have settled.
  1749. *
  1750. * @param {Promise} promise A promise to add to the extend lifetime promises
  1751. * of the event that triggered the request.
  1752. */
  1753. waitUntil(promise) {
  1754. this._extendLifetimePromises.push(promise);
  1755. return promise;
  1756. }
  1757. /**
  1758. * Returns a promise that resolves once all promises passed to
  1759. * {@link workbox-strategies.StrategyHandler~waitUntil}
  1760. * have settled.
  1761. *
  1762. * Note: any work done after `doneWaiting()` settles should be manually
  1763. * passed to an event's `waitUntil()` method (not this handler's
  1764. * `waitUntil()` method), otherwise the service worker thread my be killed
  1765. * prior to your work completing.
  1766. */
  1767. async doneWaiting() {
  1768. let promise;
  1769. while (promise = this._extendLifetimePromises.shift()) {
  1770. await promise;
  1771. }
  1772. }
  1773. /**
  1774. * Stops running the strategy and immediately resolves any pending
  1775. * `waitUntil()` promises.
  1776. */
  1777. destroy() {
  1778. this._handlerDeferred.resolve(null);
  1779. }
  1780. /**
  1781. * This method will call cacheWillUpdate on the available plugins (or use
  1782. * status === 200) to determine if the Response is safe and valid to cache.
  1783. *
  1784. * @param {Request} options.request
  1785. * @param {Response} options.response
  1786. * @return {Promise<Response|undefined>}
  1787. *
  1788. * @private
  1789. */
  1790. async _ensureResponseSafeToCache(response) {
  1791. let responseToCache = response;
  1792. let pluginsUsed = false;
  1793. for (const callback of this.iterateCallbacks('cacheWillUpdate')) {
  1794. responseToCache = (await callback({
  1795. request: this.request,
  1796. response: responseToCache,
  1797. event: this.event
  1798. })) || undefined;
  1799. pluginsUsed = true;
  1800. if (!responseToCache) {
  1801. break;
  1802. }
  1803. }
  1804. if (!pluginsUsed) {
  1805. if (responseToCache && responseToCache.status !== 200) {
  1806. responseToCache = undefined;
  1807. }
  1808. {
  1809. if (responseToCache) {
  1810. if (responseToCache.status !== 200) {
  1811. if (responseToCache.status === 0) {
  1812. logger.warn(`The response for '${this.request.url}' ` + `is an opaque response. The caching strategy that you're ` + `using will not cache opaque responses by default.`);
  1813. } else {
  1814. logger.debug(`The response for '${this.request.url}' ` + `returned a status code of '${response.status}' and won't ` + `be cached as a result.`);
  1815. }
  1816. }
  1817. }
  1818. }
  1819. }
  1820. return responseToCache;
  1821. }
  1822. }
  1823. /*
  1824. Copyright 2020 Google LLC
  1825. Use of this source code is governed by an MIT-style
  1826. license that can be found in the LICENSE file or at
  1827. https://opensource.org/licenses/MIT.
  1828. */
  1829. /**
  1830. * An abstract base class that all other strategy classes must extend from:
  1831. *
  1832. * @memberof workbox-strategies
  1833. */
  1834. class Strategy {
  1835. /**
  1836. * Creates a new instance of the strategy and sets all documented option
  1837. * properties as public instance properties.
  1838. *
  1839. * Note: if a custom strategy class extends the base Strategy class and does
  1840. * not need more than these properties, it does not need to define its own
  1841. * constructor.
  1842. *
  1843. * @param {Object} [options]
  1844. * @param {string} [options.cacheName] Cache name to store and retrieve
  1845. * requests. Defaults to the cache names provided by
  1846. * {@link workbox-core.cacheNames}.
  1847. * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  1848. * to use in conjunction with this caching strategy.
  1849. * @param {Object} [options.fetchOptions] Values passed along to the
  1850. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  1851. * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
  1852. * `fetch()` requests made by this strategy.
  1853. * @param {Object} [options.matchOptions] The
  1854. * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
  1855. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  1856. */
  1857. constructor(options = {}) {
  1858. /**
  1859. * Cache name to store and retrieve
  1860. * requests. Defaults to the cache names provided by
  1861. * {@link workbox-core.cacheNames}.
  1862. *
  1863. * @type {string}
  1864. */
  1865. this.cacheName = cacheNames.getRuntimeName(options.cacheName);
  1866. /**
  1867. * The list
  1868. * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  1869. * used by this strategy.
  1870. *
  1871. * @type {Array<Object>}
  1872. */
  1873. this.plugins = options.plugins || [];
  1874. /**
  1875. * Values passed along to the
  1876. * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters}
  1877. * of all fetch() requests made by this strategy.
  1878. *
  1879. * @type {Object}
  1880. */
  1881. this.fetchOptions = options.fetchOptions;
  1882. /**
  1883. * The
  1884. * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
  1885. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  1886. *
  1887. * @type {Object}
  1888. */
  1889. this.matchOptions = options.matchOptions;
  1890. }
  1891. /**
  1892. * Perform a request strategy and returns a `Promise` that will resolve with
  1893. * a `Response`, invoking all relevant plugin callbacks.
  1894. *
  1895. * When a strategy instance is registered with a Workbox
  1896. * {@link workbox-routing.Route}, this method is automatically
  1897. * called when the route matches.
  1898. *
  1899. * Alternatively, this method can be used in a standalone `FetchEvent`
  1900. * listener by passing it to `event.respondWith()`.
  1901. *
  1902. * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
  1903. * properties listed below.
  1904. * @param {Request|string} options.request A request to run this strategy for.
  1905. * @param {ExtendableEvent} options.event The event associated with the
  1906. * request.
  1907. * @param {URL} [options.url]
  1908. * @param {*} [options.params]
  1909. */
  1910. handle(options) {
  1911. const [responseDone] = this.handleAll(options);
  1912. return responseDone;
  1913. }
  1914. /**
  1915. * Similar to {@link workbox-strategies.Strategy~handle}, but
  1916. * instead of just returning a `Promise` that resolves to a `Response` it
  1917. * it will return an tuple of `[response, done]` promises, where the former
  1918. * (`response`) is equivalent to what `handle()` returns, and the latter is a
  1919. * Promise that will resolve once any promises that were added to
  1920. * `event.waitUntil()` as part of performing the strategy have completed.
  1921. *
  1922. * You can await the `done` promise to ensure any extra work performed by
  1923. * the strategy (usually caching responses) completes successfully.
  1924. *
  1925. * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
  1926. * properties listed below.
  1927. * @param {Request|string} options.request A request to run this strategy for.
  1928. * @param {ExtendableEvent} options.event The event associated with the
  1929. * request.
  1930. * @param {URL} [options.url]
  1931. * @param {*} [options.params]
  1932. * @return {Array<Promise>} A tuple of [response, done]
  1933. * promises that can be used to determine when the response resolves as
  1934. * well as when the handler has completed all its work.
  1935. */
  1936. handleAll(options) {
  1937. // Allow for flexible options to be passed.
  1938. if (options instanceof FetchEvent) {
  1939. options = {
  1940. event: options,
  1941. request: options.request
  1942. };
  1943. }
  1944. const event = options.event;
  1945. const request = typeof options.request === 'string' ? new Request(options.request) : options.request;
  1946. const params = 'params' in options ? options.params : undefined;
  1947. const handler = new StrategyHandler(this, {
  1948. event,
  1949. request,
  1950. params
  1951. });
  1952. const responseDone = this._getResponse(handler, request, event);
  1953. const handlerDone = this._awaitComplete(responseDone, handler, request, event);
  1954. // Return an array of promises, suitable for use with Promise.all().
  1955. return [responseDone, handlerDone];
  1956. }
  1957. async _getResponse(handler, request, event) {
  1958. await handler.runCallbacks('handlerWillStart', {
  1959. event,
  1960. request
  1961. });
  1962. let response = undefined;
  1963. try {
  1964. response = await this._handle(request, handler);
  1965. // The "official" Strategy subclasses all throw this error automatically,
  1966. // but in case a third-party Strategy doesn't, ensure that we have a
  1967. // consistent failure when there's no response or an error response.
  1968. if (!response || response.type === 'error') {
  1969. throw new WorkboxError('no-response', {
  1970. url: request.url
  1971. });
  1972. }
  1973. } catch (error) {
  1974. if (error instanceof Error) {
  1975. for (const callback of handler.iterateCallbacks('handlerDidError')) {
  1976. response = await callback({
  1977. error,
  1978. event,
  1979. request
  1980. });
  1981. if (response) {
  1982. break;
  1983. }
  1984. }
  1985. }
  1986. if (!response) {
  1987. throw error;
  1988. } else {
  1989. logger.log(`While responding to '${getFriendlyURL(request.url)}', ` + `an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` + `a handlerDidError plugin.`);
  1990. }
  1991. }
  1992. for (const callback of handler.iterateCallbacks('handlerWillRespond')) {
  1993. response = await callback({
  1994. event,
  1995. request,
  1996. response
  1997. });
  1998. }
  1999. return response;
  2000. }
  2001. async _awaitComplete(responseDone, handler, request, event) {
  2002. let response;
  2003. let error;
  2004. try {
  2005. response = await responseDone;
  2006. } catch (error) {
  2007. // Ignore errors, as response errors should be caught via the `response`
  2008. // promise above. The `done` promise will only throw for errors in
  2009. // promises passed to `handler.waitUntil()`.
  2010. }
  2011. try {
  2012. await handler.runCallbacks('handlerDidRespond', {
  2013. event,
  2014. request,
  2015. response
  2016. });
  2017. await handler.doneWaiting();
  2018. } catch (waitUntilError) {
  2019. if (waitUntilError instanceof Error) {
  2020. error = waitUntilError;
  2021. }
  2022. }
  2023. await handler.runCallbacks('handlerDidComplete', {
  2024. event,
  2025. request,
  2026. response,
  2027. error: error
  2028. });
  2029. handler.destroy();
  2030. if (error) {
  2031. throw error;
  2032. }
  2033. }
  2034. }
  2035. /**
  2036. * Classes extending the `Strategy` based class should implement this method,
  2037. * and leverage the {@link workbox-strategies.StrategyHandler}
  2038. * arg to perform all fetching and cache logic, which will ensure all relevant
  2039. * cache, cache options, fetch options and plugins are used (per the current
  2040. * strategy instance).
  2041. *
  2042. * @name _handle
  2043. * @instance
  2044. * @abstract
  2045. * @function
  2046. * @param {Request} request
  2047. * @param {workbox-strategies.StrategyHandler} handler
  2048. * @return {Promise<Response>}
  2049. *
  2050. * @memberof workbox-strategies.Strategy
  2051. */
  2052. /*
  2053. Copyright 2018 Google LLC
  2054. Use of this source code is governed by an MIT-style
  2055. license that can be found in the LICENSE file or at
  2056. https://opensource.org/licenses/MIT.
  2057. */
  2058. const messages = {
  2059. strategyStart: (strategyName, request) => `Using ${strategyName} to respond to '${getFriendlyURL(request.url)}'`,
  2060. printFinalResponse: response => {
  2061. if (response) {
  2062. logger.groupCollapsed(`View the final response here.`);
  2063. logger.log(response || '[No response returned]');
  2064. logger.groupEnd();
  2065. }
  2066. }
  2067. };
  2068. /*
  2069. Copyright 2018 Google LLC
  2070. Use of this source code is governed by an MIT-style
  2071. license that can be found in the LICENSE file or at
  2072. https://opensource.org/licenses/MIT.
  2073. */
  2074. /**
  2075. * An implementation of a
  2076. * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only)
  2077. * request strategy.
  2078. *
  2079. * This class is useful if you want to take advantage of any
  2080. * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).
  2081. *
  2082. * If the network request fails, this will throw a `WorkboxError` exception.
  2083. *
  2084. * @extends workbox-strategies.Strategy
  2085. * @memberof workbox-strategies
  2086. */
  2087. class NetworkOnly extends Strategy {
  2088. /**
  2089. * @param {Object} [options]
  2090. * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  2091. * to use in conjunction with this caching strategy.
  2092. * @param {Object} [options.fetchOptions] Values passed along to the
  2093. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  2094. * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
  2095. * `fetch()` requests made by this strategy.
  2096. * @param {number} [options.networkTimeoutSeconds] If set, any network requests
  2097. * that fail to respond within the timeout will result in a network error.
  2098. */
  2099. constructor(options = {}) {
  2100. super(options);
  2101. this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;
  2102. }
  2103. /**
  2104. * @private
  2105. * @param {Request|string} request A request to run this strategy for.
  2106. * @param {workbox-strategies.StrategyHandler} handler The event that
  2107. * triggered the request.
  2108. * @return {Promise<Response>}
  2109. */
  2110. async _handle(request, handler) {
  2111. {
  2112. finalAssertExports.isInstance(request, Request, {
  2113. moduleName: 'workbox-strategies',
  2114. className: this.constructor.name,
  2115. funcName: '_handle',
  2116. paramName: 'request'
  2117. });
  2118. }
  2119. let error = undefined;
  2120. let response;
  2121. try {
  2122. const promises = [handler.fetch(request)];
  2123. if (this._networkTimeoutSeconds) {
  2124. const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000);
  2125. promises.push(timeoutPromise);
  2126. }
  2127. response = await Promise.race(promises);
  2128. if (!response) {
  2129. throw new Error(`Timed out the network response after ` + `${this._networkTimeoutSeconds} seconds.`);
  2130. }
  2131. } catch (err) {
  2132. if (err instanceof Error) {
  2133. error = err;
  2134. }
  2135. }
  2136. {
  2137. logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
  2138. if (response) {
  2139. logger.log(`Got response from network.`);
  2140. } else {
  2141. logger.log(`Unable to get a response from the network.`);
  2142. }
  2143. messages.printFinalResponse(response);
  2144. logger.groupEnd();
  2145. }
  2146. if (!response) {
  2147. throw new WorkboxError('no-response', {
  2148. url: request.url,
  2149. error
  2150. });
  2151. }
  2152. return response;
  2153. }
  2154. }
  2155. /*
  2156. Copyright 2019 Google LLC
  2157. Use of this source code is governed by an MIT-style
  2158. license that can be found in the LICENSE file or at
  2159. https://opensource.org/licenses/MIT.
  2160. */
  2161. /**
  2162. * A helper function that prevents a promise from being flagged as unused.
  2163. *
  2164. * @private
  2165. **/
  2166. function dontWaitFor(promise) {
  2167. // Effective no-op.
  2168. void promise.then(() => {});
  2169. }
  2170. /*
  2171. Copyright 2019 Google LLC
  2172. Use of this source code is governed by an MIT-style
  2173. license that can be found in the LICENSE file or at
  2174. https://opensource.org/licenses/MIT.
  2175. */
  2176. /**
  2177. * Adds a function to the set of quotaErrorCallbacks that will be executed if
  2178. * there's a quota error.
  2179. *
  2180. * @param {Function} callback
  2181. * @memberof workbox-core
  2182. */
  2183. // Can't change Function type
  2184. // eslint-disable-next-line @typescript-eslint/ban-types
  2185. function registerQuotaErrorCallback(callback) {
  2186. {
  2187. finalAssertExports.isType(callback, 'function', {
  2188. moduleName: 'workbox-core',
  2189. funcName: 'register',
  2190. paramName: 'callback'
  2191. });
  2192. }
  2193. quotaErrorCallbacks.add(callback);
  2194. {
  2195. logger.log('Registered a callback to respond to quota errors.', callback);
  2196. }
  2197. }
  2198. function _extends() {
  2199. _extends = Object.assign ? Object.assign.bind() : function (target) {
  2200. for (var i = 1; i < arguments.length; i++) {
  2201. var source = arguments[i];
  2202. for (var key in source) {
  2203. if (Object.prototype.hasOwnProperty.call(source, key)) {
  2204. target[key] = source[key];
  2205. }
  2206. }
  2207. }
  2208. return target;
  2209. };
  2210. return _extends.apply(this, arguments);
  2211. }
  2212. const instanceOfAny = (object, constructors) => constructors.some(c => object instanceof c);
  2213. let idbProxyableTypes;
  2214. let cursorAdvanceMethods;
  2215. // This is a function to prevent it throwing up in node environments.
  2216. function getIdbProxyableTypes() {
  2217. return idbProxyableTypes || (idbProxyableTypes = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction]);
  2218. }
  2219. // This is a function to prevent it throwing up in node environments.
  2220. function getCursorAdvanceMethods() {
  2221. return cursorAdvanceMethods || (cursorAdvanceMethods = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey]);
  2222. }
  2223. const cursorRequestMap = new WeakMap();
  2224. const transactionDoneMap = new WeakMap();
  2225. const transactionStoreNamesMap = new WeakMap();
  2226. const transformCache = new WeakMap();
  2227. const reverseTransformCache = new WeakMap();
  2228. function promisifyRequest(request) {
  2229. const promise = new Promise((resolve, reject) => {
  2230. const unlisten = () => {
  2231. request.removeEventListener('success', success);
  2232. request.removeEventListener('error', error);
  2233. };
  2234. const success = () => {
  2235. resolve(wrap(request.result));
  2236. unlisten();
  2237. };
  2238. const error = () => {
  2239. reject(request.error);
  2240. unlisten();
  2241. };
  2242. request.addEventListener('success', success);
  2243. request.addEventListener('error', error);
  2244. });
  2245. promise.then(value => {
  2246. // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
  2247. // (see wrapFunction).
  2248. if (value instanceof IDBCursor) {
  2249. cursorRequestMap.set(value, request);
  2250. }
  2251. // Catching to avoid "Uncaught Promise exceptions"
  2252. }).catch(() => {});
  2253. // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
  2254. // is because we create many promises from a single IDBRequest.
  2255. reverseTransformCache.set(promise, request);
  2256. return promise;
  2257. }
  2258. function cacheDonePromiseForTransaction(tx) {
  2259. // Early bail if we've already created a done promise for this transaction.
  2260. if (transactionDoneMap.has(tx)) return;
  2261. const done = new Promise((resolve, reject) => {
  2262. const unlisten = () => {
  2263. tx.removeEventListener('complete', complete);
  2264. tx.removeEventListener('error', error);
  2265. tx.removeEventListener('abort', error);
  2266. };
  2267. const complete = () => {
  2268. resolve();
  2269. unlisten();
  2270. };
  2271. const error = () => {
  2272. reject(tx.error || new DOMException('AbortError', 'AbortError'));
  2273. unlisten();
  2274. };
  2275. tx.addEventListener('complete', complete);
  2276. tx.addEventListener('error', error);
  2277. tx.addEventListener('abort', error);
  2278. });
  2279. // Cache it for later retrieval.
  2280. transactionDoneMap.set(tx, done);
  2281. }
  2282. let idbProxyTraps = {
  2283. get(target, prop, receiver) {
  2284. if (target instanceof IDBTransaction) {
  2285. // Special handling for transaction.done.
  2286. if (prop === 'done') return transactionDoneMap.get(target);
  2287. // Polyfill for objectStoreNames because of Edge.
  2288. if (prop === 'objectStoreNames') {
  2289. return target.objectStoreNames || transactionStoreNamesMap.get(target);
  2290. }
  2291. // Make tx.store return the only store in the transaction, or undefined if there are many.
  2292. if (prop === 'store') {
  2293. return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]);
  2294. }
  2295. }
  2296. // Else transform whatever we get back.
  2297. return wrap(target[prop]);
  2298. },
  2299. set(target, prop, value) {
  2300. target[prop] = value;
  2301. return true;
  2302. },
  2303. has(target, prop) {
  2304. if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) {
  2305. return true;
  2306. }
  2307. return prop in target;
  2308. }
  2309. };
  2310. function replaceTraps(callback) {
  2311. idbProxyTraps = callback(idbProxyTraps);
  2312. }
  2313. function wrapFunction(func) {
  2314. // Due to expected object equality (which is enforced by the caching in `wrap`), we
  2315. // only create one new func per func.
  2316. // Edge doesn't support objectStoreNames (booo), so we polyfill it here.
  2317. if (func === IDBDatabase.prototype.transaction && !('objectStoreNames' in IDBTransaction.prototype)) {
  2318. return function (storeNames, ...args) {
  2319. const tx = func.call(unwrap(this), storeNames, ...args);
  2320. transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
  2321. return wrap(tx);
  2322. };
  2323. }
  2324. // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
  2325. // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
  2326. // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
  2327. // with real promises, so each advance methods returns a new promise for the cursor object, or
  2328. // undefined if the end of the cursor has been reached.
  2329. if (getCursorAdvanceMethods().includes(func)) {
  2330. return function (...args) {
  2331. // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
  2332. // the original object.
  2333. func.apply(unwrap(this), args);
  2334. return wrap(cursorRequestMap.get(this));
  2335. };
  2336. }
  2337. return function (...args) {
  2338. // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
  2339. // the original object.
  2340. return wrap(func.apply(unwrap(this), args));
  2341. };
  2342. }
  2343. function transformCachableValue(value) {
  2344. if (typeof value === 'function') return wrapFunction(value);
  2345. // This doesn't return, it just creates a 'done' promise for the transaction,
  2346. // which is later returned for transaction.done (see idbObjectHandler).
  2347. if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value);
  2348. if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps);
  2349. // Return the same value back if we're not going to transform it.
  2350. return value;
  2351. }
  2352. function wrap(value) {
  2353. // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
  2354. // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
  2355. if (value instanceof IDBRequest) return promisifyRequest(value);
  2356. // If we've already transformed this value before, reuse the transformed value.
  2357. // This is faster, but it also provides object equality.
  2358. if (transformCache.has(value)) return transformCache.get(value);
  2359. const newValue = transformCachableValue(value);
  2360. // Not all types are transformed.
  2361. // These may be primitive types, so they can't be WeakMap keys.
  2362. if (newValue !== value) {
  2363. transformCache.set(value, newValue);
  2364. reverseTransformCache.set(newValue, value);
  2365. }
  2366. return newValue;
  2367. }
  2368. const unwrap = value => reverseTransformCache.get(value);
  2369. /**
  2370. * Open a database.
  2371. *
  2372. * @param name Name of the database.
  2373. * @param version Schema version.
  2374. * @param callbacks Additional callbacks.
  2375. */
  2376. function openDB(name, version, {
  2377. blocked,
  2378. upgrade,
  2379. blocking,
  2380. terminated
  2381. } = {}) {
  2382. const request = indexedDB.open(name, version);
  2383. const openPromise = wrap(request);
  2384. if (upgrade) {
  2385. request.addEventListener('upgradeneeded', event => {
  2386. upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
  2387. });
  2388. }
  2389. if (blocked) {
  2390. request.addEventListener('blocked', event => blocked(
  2391. // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
  2392. event.oldVersion, event.newVersion, event));
  2393. }
  2394. openPromise.then(db => {
  2395. if (terminated) db.addEventListener('close', () => terminated());
  2396. if (blocking) {
  2397. db.addEventListener('versionchange', event => blocking(event.oldVersion, event.newVersion, event));
  2398. }
  2399. }).catch(() => {});
  2400. return openPromise;
  2401. }
  2402. /**
  2403. * Delete a database.
  2404. *
  2405. * @param name Name of the database.
  2406. */
  2407. function deleteDB(name, {
  2408. blocked
  2409. } = {}) {
  2410. const request = indexedDB.deleteDatabase(name);
  2411. if (blocked) {
  2412. request.addEventListener('blocked', event => blocked(
  2413. // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
  2414. event.oldVersion, event));
  2415. }
  2416. return wrap(request).then(() => undefined);
  2417. }
  2418. const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
  2419. const writeMethods = ['put', 'add', 'delete', 'clear'];
  2420. const cachedMethods = new Map();
  2421. function getMethod(target, prop) {
  2422. if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) {
  2423. return;
  2424. }
  2425. if (cachedMethods.get(prop)) return cachedMethods.get(prop);
  2426. const targetFuncName = prop.replace(/FromIndex$/, '');
  2427. const useIndex = prop !== targetFuncName;
  2428. const isWrite = writeMethods.includes(targetFuncName);
  2429. if (
  2430. // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
  2431. !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) {
  2432. return;
  2433. }
  2434. const method = async function (storeName, ...args) {
  2435. // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
  2436. const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
  2437. let target = tx.store;
  2438. if (useIndex) target = target.index(args.shift());
  2439. // Must reject if op rejects.
  2440. // If it's a write operation, must reject if tx.done rejects.
  2441. // Must reject with op rejection first.
  2442. // Must resolve with op value.
  2443. // Must handle both promises (no unhandled rejections)
  2444. return (await Promise.all([target[targetFuncName](...args), isWrite && tx.done]))[0];
  2445. };
  2446. cachedMethods.set(prop, method);
  2447. return method;
  2448. }
  2449. replaceTraps(oldTraps => _extends({}, oldTraps, {
  2450. get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
  2451. has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop)
  2452. }));
  2453. // @ts-ignore
  2454. try {
  2455. self['workbox:expiration:7.0.0'] && _();
  2456. } catch (e) {}
  2457. /*
  2458. Copyright 2018 Google LLC
  2459. Use of this source code is governed by an MIT-style
  2460. license that can be found in the LICENSE file or at
  2461. https://opensource.org/licenses/MIT.
  2462. */
  2463. const DB_NAME = 'workbox-expiration';
  2464. const CACHE_OBJECT_STORE = 'cache-entries';
  2465. const normalizeURL = unNormalizedUrl => {
  2466. const url = new URL(unNormalizedUrl, location.href);
  2467. url.hash = '';
  2468. return url.href;
  2469. };
  2470. /**
  2471. * Returns the timestamp model.
  2472. *
  2473. * @private
  2474. */
  2475. class CacheTimestampsModel {
  2476. /**
  2477. *
  2478. * @param {string} cacheName
  2479. *
  2480. * @private
  2481. */
  2482. constructor(cacheName) {
  2483. this._db = null;
  2484. this._cacheName = cacheName;
  2485. }
  2486. /**
  2487. * Performs an upgrade of indexedDB.
  2488. *
  2489. * @param {IDBPDatabase<CacheDbSchema>} db
  2490. *
  2491. * @private
  2492. */
  2493. _upgradeDb(db) {
  2494. // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we
  2495. // have to use the `id` keyPath here and create our own values (a
  2496. // concatenation of `url + cacheName`) instead of simply using
  2497. // `keyPath: ['url', 'cacheName']`, which is supported in other browsers.
  2498. const objStore = db.createObjectStore(CACHE_OBJECT_STORE, {
  2499. keyPath: 'id'
  2500. });
  2501. // TODO(philipwalton): once we don't have to support EdgeHTML, we can
  2502. // create a single index with the keyPath `['cacheName', 'timestamp']`
  2503. // instead of doing both these indexes.
  2504. objStore.createIndex('cacheName', 'cacheName', {
  2505. unique: false
  2506. });
  2507. objStore.createIndex('timestamp', 'timestamp', {
  2508. unique: false
  2509. });
  2510. }
  2511. /**
  2512. * Performs an upgrade of indexedDB and deletes deprecated DBs.
  2513. *
  2514. * @param {IDBPDatabase<CacheDbSchema>} db
  2515. *
  2516. * @private
  2517. */
  2518. _upgradeDbAndDeleteOldDbs(db) {
  2519. this._upgradeDb(db);
  2520. if (this._cacheName) {
  2521. void deleteDB(this._cacheName);
  2522. }
  2523. }
  2524. /**
  2525. * @param {string} url
  2526. * @param {number} timestamp
  2527. *
  2528. * @private
  2529. */
  2530. async setTimestamp(url, timestamp) {
  2531. url = normalizeURL(url);
  2532. const entry = {
  2533. url,
  2534. timestamp,
  2535. cacheName: this._cacheName,
  2536. // Creating an ID from the URL and cache name won't be necessary once
  2537. // Edge switches to Chromium and all browsers we support work with
  2538. // array keyPaths.
  2539. id: this._getId(url)
  2540. };
  2541. const db = await this.getDb();
  2542. const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', {
  2543. durability: 'relaxed'
  2544. });
  2545. await tx.store.put(entry);
  2546. await tx.done;
  2547. }
  2548. /**
  2549. * Returns the timestamp stored for a given URL.
  2550. *
  2551. * @param {string} url
  2552. * @return {number | undefined}
  2553. *
  2554. * @private
  2555. */
  2556. async getTimestamp(url) {
  2557. const db = await this.getDb();
  2558. const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url));
  2559. return entry === null || entry === void 0 ? void 0 : entry.timestamp;
  2560. }
  2561. /**
  2562. * Iterates through all the entries in the object store (from newest to
  2563. * oldest) and removes entries once either `maxCount` is reached or the
  2564. * entry's timestamp is less than `minTimestamp`.
  2565. *
  2566. * @param {number} minTimestamp
  2567. * @param {number} maxCount
  2568. * @return {Array<string>}
  2569. *
  2570. * @private
  2571. */
  2572. async expireEntries(minTimestamp, maxCount) {
  2573. const db = await this.getDb();
  2574. let cursor = await db.transaction(CACHE_OBJECT_STORE).store.index('timestamp').openCursor(null, 'prev');
  2575. const entriesToDelete = [];
  2576. let entriesNotDeletedCount = 0;
  2577. while (cursor) {
  2578. const result = cursor.value;
  2579. // TODO(philipwalton): once we can use a multi-key index, we
  2580. // won't have to check `cacheName` here.
  2581. if (result.cacheName === this._cacheName) {
  2582. // Delete an entry if it's older than the max age or
  2583. // if we already have the max number allowed.
  2584. if (minTimestamp && result.timestamp < minTimestamp || maxCount && entriesNotDeletedCount >= maxCount) {
  2585. // TODO(philipwalton): we should be able to delete the
  2586. // entry right here, but doing so causes an iteration
  2587. // bug in Safari stable (fixed in TP). Instead we can
  2588. // store the keys of the entries to delete, and then
  2589. // delete the separate transactions.
  2590. // https://github.com/GoogleChrome/workbox/issues/1978
  2591. // cursor.delete();
  2592. // We only need to return the URL, not the whole entry.
  2593. entriesToDelete.push(cursor.value);
  2594. } else {
  2595. entriesNotDeletedCount++;
  2596. }
  2597. }
  2598. cursor = await cursor.continue();
  2599. }
  2600. // TODO(philipwalton): once the Safari bug in the following issue is fixed,
  2601. // we should be able to remove this loop and do the entry deletion in the
  2602. // cursor loop above:
  2603. // https://github.com/GoogleChrome/workbox/issues/1978
  2604. const urlsDeleted = [];
  2605. for (const entry of entriesToDelete) {
  2606. await db.delete(CACHE_OBJECT_STORE, entry.id);
  2607. urlsDeleted.push(entry.url);
  2608. }
  2609. return urlsDeleted;
  2610. }
  2611. /**
  2612. * Takes a URL and returns an ID that will be unique in the object store.
  2613. *
  2614. * @param {string} url
  2615. * @return {string}
  2616. *
  2617. * @private
  2618. */
  2619. _getId(url) {
  2620. // Creating an ID from the URL and cache name won't be necessary once
  2621. // Edge switches to Chromium and all browsers we support work with
  2622. // array keyPaths.
  2623. return this._cacheName + '|' + normalizeURL(url);
  2624. }
  2625. /**
  2626. * Returns an open connection to the database.
  2627. *
  2628. * @private
  2629. */
  2630. async getDb() {
  2631. if (!this._db) {
  2632. this._db = await openDB(DB_NAME, 1, {
  2633. upgrade: this._upgradeDbAndDeleteOldDbs.bind(this)
  2634. });
  2635. }
  2636. return this._db;
  2637. }
  2638. }
  2639. /*
  2640. Copyright 2018 Google LLC
  2641. Use of this source code is governed by an MIT-style
  2642. license that can be found in the LICENSE file or at
  2643. https://opensource.org/licenses/MIT.
  2644. */
  2645. /**
  2646. * The `CacheExpiration` class allows you define an expiration and / or
  2647. * limit on the number of responses stored in a
  2648. * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).
  2649. *
  2650. * @memberof workbox-expiration
  2651. */
  2652. class CacheExpiration {
  2653. /**
  2654. * To construct a new CacheExpiration instance you must provide at least
  2655. * one of the `config` properties.
  2656. *
  2657. * @param {string} cacheName Name of the cache to apply restrictions to.
  2658. * @param {Object} config
  2659. * @param {number} [config.maxEntries] The maximum number of entries to cache.
  2660. * Entries used the least will be removed as the maximum is reached.
  2661. * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
  2662. * it's treated as stale and removed.
  2663. * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)
  2664. * that will be used when calling `delete()` on the cache.
  2665. */
  2666. constructor(cacheName, config = {}) {
  2667. this._isRunning = false;
  2668. this._rerunRequested = false;
  2669. {
  2670. finalAssertExports.isType(cacheName, 'string', {
  2671. moduleName: 'workbox-expiration',
  2672. className: 'CacheExpiration',
  2673. funcName: 'constructor',
  2674. paramName: 'cacheName'
  2675. });
  2676. if (!(config.maxEntries || config.maxAgeSeconds)) {
  2677. throw new WorkboxError('max-entries-or-age-required', {
  2678. moduleName: 'workbox-expiration',
  2679. className: 'CacheExpiration',
  2680. funcName: 'constructor'
  2681. });
  2682. }
  2683. if (config.maxEntries) {
  2684. finalAssertExports.isType(config.maxEntries, 'number', {
  2685. moduleName: 'workbox-expiration',
  2686. className: 'CacheExpiration',
  2687. funcName: 'constructor',
  2688. paramName: 'config.maxEntries'
  2689. });
  2690. }
  2691. if (config.maxAgeSeconds) {
  2692. finalAssertExports.isType(config.maxAgeSeconds, 'number', {
  2693. moduleName: 'workbox-expiration',
  2694. className: 'CacheExpiration',
  2695. funcName: 'constructor',
  2696. paramName: 'config.maxAgeSeconds'
  2697. });
  2698. }
  2699. }
  2700. this._maxEntries = config.maxEntries;
  2701. this._maxAgeSeconds = config.maxAgeSeconds;
  2702. this._matchOptions = config.matchOptions;
  2703. this._cacheName = cacheName;
  2704. this._timestampModel = new CacheTimestampsModel(cacheName);
  2705. }
  2706. /**
  2707. * Expires entries for the given cache and given criteria.
  2708. */
  2709. async expireEntries() {
  2710. if (this._isRunning) {
  2711. this._rerunRequested = true;
  2712. return;
  2713. }
  2714. this._isRunning = true;
  2715. const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : 0;
  2716. const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);
  2717. // Delete URLs from the cache
  2718. const cache = await self.caches.open(this._cacheName);
  2719. for (const url of urlsExpired) {
  2720. await cache.delete(url, this._matchOptions);
  2721. }
  2722. {
  2723. if (urlsExpired.length > 0) {
  2724. logger.groupCollapsed(`Expired ${urlsExpired.length} ` + `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + `'${this._cacheName}' cache.`);
  2725. logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);
  2726. urlsExpired.forEach(url => logger.log(` ${url}`));
  2727. logger.groupEnd();
  2728. } else {
  2729. logger.debug(`Cache expiration ran and found no entries to remove.`);
  2730. }
  2731. }
  2732. this._isRunning = false;
  2733. if (this._rerunRequested) {
  2734. this._rerunRequested = false;
  2735. dontWaitFor(this.expireEntries());
  2736. }
  2737. }
  2738. /**
  2739. * Update the timestamp for the given URL. This ensures the when
  2740. * removing entries based on maximum entries, most recently used
  2741. * is accurate or when expiring, the timestamp is up-to-date.
  2742. *
  2743. * @param {string} url
  2744. */
  2745. async updateTimestamp(url) {
  2746. {
  2747. finalAssertExports.isType(url, 'string', {
  2748. moduleName: 'workbox-expiration',
  2749. className: 'CacheExpiration',
  2750. funcName: 'updateTimestamp',
  2751. paramName: 'url'
  2752. });
  2753. }
  2754. await this._timestampModel.setTimestamp(url, Date.now());
  2755. }
  2756. /**
  2757. * Can be used to check if a URL has expired or not before it's used.
  2758. *
  2759. * This requires a look up from IndexedDB, so can be slow.
  2760. *
  2761. * Note: This method will not remove the cached entry, call
  2762. * `expireEntries()` to remove indexedDB and Cache entries.
  2763. *
  2764. * @param {string} url
  2765. * @return {boolean}
  2766. */
  2767. async isURLExpired(url) {
  2768. if (!this._maxAgeSeconds) {
  2769. {
  2770. throw new WorkboxError(`expired-test-without-max-age`, {
  2771. methodName: 'isURLExpired',
  2772. paramName: 'maxAgeSeconds'
  2773. });
  2774. }
  2775. } else {
  2776. const timestamp = await this._timestampModel.getTimestamp(url);
  2777. const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;
  2778. return timestamp !== undefined ? timestamp < expireOlderThan : true;
  2779. }
  2780. }
  2781. /**
  2782. * Removes the IndexedDB object store used to keep track of cache expiration
  2783. * metadata.
  2784. */
  2785. async delete() {
  2786. // Make sure we don't attempt another rerun if we're called in the middle of
  2787. // a cache expiration.
  2788. this._rerunRequested = false;
  2789. await this._timestampModel.expireEntries(Infinity); // Expires all.
  2790. }
  2791. }
  2792. /*
  2793. Copyright 2018 Google LLC
  2794. Use of this source code is governed by an MIT-style
  2795. license that can be found in the LICENSE file or at
  2796. https://opensource.org/licenses/MIT.
  2797. */
  2798. /**
  2799. * This plugin can be used in a `workbox-strategy` to regularly enforce a
  2800. * limit on the age and / or the number of cached requests.
  2801. *
  2802. * It can only be used with `workbox-strategy` instances that have a
  2803. * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies).
  2804. * In other words, it can't be used to expire entries in strategy that uses the
  2805. * default runtime cache name.
  2806. *
  2807. * Whenever a cached response is used or updated, this plugin will look
  2808. * at the associated cache and remove any old or extra responses.
  2809. *
  2810. * When using `maxAgeSeconds`, responses may be used *once* after expiring
  2811. * because the expiration clean up will not have occurred until *after* the
  2812. * cached response has been used. If the response has a "Date" header, then
  2813. * a light weight expiration check is performed and the response will not be
  2814. * used immediately.
  2815. *
  2816. * When using `maxEntries`, the entry least-recently requested will be removed
  2817. * from the cache first.
  2818. *
  2819. * @memberof workbox-expiration
  2820. */
  2821. class ExpirationPlugin {
  2822. /**
  2823. * @param {ExpirationPluginOptions} config
  2824. * @param {number} [config.maxEntries] The maximum number of entries to cache.
  2825. * Entries used the least will be removed as the maximum is reached.
  2826. * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
  2827. * it's treated as stale and removed.
  2828. * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)
  2829. * that will be used when calling `delete()` on the cache.
  2830. * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to
  2831. * automatic deletion if the available storage quota has been exceeded.
  2832. */
  2833. constructor(config = {}) {
  2834. /**
  2835. * A "lifecycle" callback that will be triggered automatically by the
  2836. * `workbox-strategies` handlers when a `Response` is about to be returned
  2837. * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to
  2838. * the handler. It allows the `Response` to be inspected for freshness and
  2839. * prevents it from being used if the `Response`'s `Date` header value is
  2840. * older than the configured `maxAgeSeconds`.
  2841. *
  2842. * @param {Object} options
  2843. * @param {string} options.cacheName Name of the cache the response is in.
  2844. * @param {Response} options.cachedResponse The `Response` object that's been
  2845. * read from a cache and whose freshness should be checked.
  2846. * @return {Response} Either the `cachedResponse`, if it's
  2847. * fresh, or `null` if the `Response` is older than `maxAgeSeconds`.
  2848. *
  2849. * @private
  2850. */
  2851. this.cachedResponseWillBeUsed = async ({
  2852. event,
  2853. request,
  2854. cacheName,
  2855. cachedResponse
  2856. }) => {
  2857. if (!cachedResponse) {
  2858. return null;
  2859. }
  2860. const isFresh = this._isResponseDateFresh(cachedResponse);
  2861. // Expire entries to ensure that even if the expiration date has
  2862. // expired, it'll only be used once.
  2863. const cacheExpiration = this._getCacheExpiration(cacheName);
  2864. dontWaitFor(cacheExpiration.expireEntries());
  2865. // Update the metadata for the request URL to the current timestamp,
  2866. // but don't `await` it as we don't want to block the response.
  2867. const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);
  2868. if (event) {
  2869. try {
  2870. event.waitUntil(updateTimestampDone);
  2871. } catch (error) {
  2872. {
  2873. // The event may not be a fetch event; only log the URL if it is.
  2874. if ('request' in event) {
  2875. logger.warn(`Unable to ensure service worker stays alive when ` + `updating cache entry for ` + `'${getFriendlyURL(event.request.url)}'.`);
  2876. }
  2877. }
  2878. }
  2879. }
  2880. return isFresh ? cachedResponse : null;
  2881. };
  2882. /**
  2883. * A "lifecycle" callback that will be triggered automatically by the
  2884. * `workbox-strategies` handlers when an entry is added to a cache.
  2885. *
  2886. * @param {Object} options
  2887. * @param {string} options.cacheName Name of the cache that was updated.
  2888. * @param {string} options.request The Request for the cached entry.
  2889. *
  2890. * @private
  2891. */
  2892. this.cacheDidUpdate = async ({
  2893. cacheName,
  2894. request
  2895. }) => {
  2896. {
  2897. finalAssertExports.isType(cacheName, 'string', {
  2898. moduleName: 'workbox-expiration',
  2899. className: 'Plugin',
  2900. funcName: 'cacheDidUpdate',
  2901. paramName: 'cacheName'
  2902. });
  2903. finalAssertExports.isInstance(request, Request, {
  2904. moduleName: 'workbox-expiration',
  2905. className: 'Plugin',
  2906. funcName: 'cacheDidUpdate',
  2907. paramName: 'request'
  2908. });
  2909. }
  2910. const cacheExpiration = this._getCacheExpiration(cacheName);
  2911. await cacheExpiration.updateTimestamp(request.url);
  2912. await cacheExpiration.expireEntries();
  2913. };
  2914. {
  2915. if (!(config.maxEntries || config.maxAgeSeconds)) {
  2916. throw new WorkboxError('max-entries-or-age-required', {
  2917. moduleName: 'workbox-expiration',
  2918. className: 'Plugin',
  2919. funcName: 'constructor'
  2920. });
  2921. }
  2922. if (config.maxEntries) {
  2923. finalAssertExports.isType(config.maxEntries, 'number', {
  2924. moduleName: 'workbox-expiration',
  2925. className: 'Plugin',
  2926. funcName: 'constructor',
  2927. paramName: 'config.maxEntries'
  2928. });
  2929. }
  2930. if (config.maxAgeSeconds) {
  2931. finalAssertExports.isType(config.maxAgeSeconds, 'number', {
  2932. moduleName: 'workbox-expiration',
  2933. className: 'Plugin',
  2934. funcName: 'constructor',
  2935. paramName: 'config.maxAgeSeconds'
  2936. });
  2937. }
  2938. }
  2939. this._config = config;
  2940. this._maxAgeSeconds = config.maxAgeSeconds;
  2941. this._cacheExpirations = new Map();
  2942. if (config.purgeOnQuotaError) {
  2943. registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());
  2944. }
  2945. }
  2946. /**
  2947. * A simple helper method to return a CacheExpiration instance for a given
  2948. * cache name.
  2949. *
  2950. * @param {string} cacheName
  2951. * @return {CacheExpiration}
  2952. *
  2953. * @private
  2954. */
  2955. _getCacheExpiration(cacheName) {
  2956. if (cacheName === cacheNames.getRuntimeName()) {
  2957. throw new WorkboxError('expire-custom-caches-only');
  2958. }
  2959. let cacheExpiration = this._cacheExpirations.get(cacheName);
  2960. if (!cacheExpiration) {
  2961. cacheExpiration = new CacheExpiration(cacheName, this._config);
  2962. this._cacheExpirations.set(cacheName, cacheExpiration);
  2963. }
  2964. return cacheExpiration;
  2965. }
  2966. /**
  2967. * @param {Response} cachedResponse
  2968. * @return {boolean}
  2969. *
  2970. * @private
  2971. */
  2972. _isResponseDateFresh(cachedResponse) {
  2973. if (!this._maxAgeSeconds) {
  2974. // We aren't expiring by age, so return true, it's fresh
  2975. return true;
  2976. }
  2977. // Check if the 'date' header will suffice a quick expiration check.
  2978. // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for
  2979. // discussion.
  2980. const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
  2981. if (dateHeaderTimestamp === null) {
  2982. // Unable to parse date, so assume it's fresh.
  2983. return true;
  2984. }
  2985. // If we have a valid headerTime, then our response is fresh iff the
  2986. // headerTime plus maxAgeSeconds is greater than the current time.
  2987. const now = Date.now();
  2988. return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;
  2989. }
  2990. /**
  2991. * This method will extract the data header and parse it into a useful
  2992. * value.
  2993. *
  2994. * @param {Response} cachedResponse
  2995. * @return {number|null}
  2996. *
  2997. * @private
  2998. */
  2999. _getDateHeaderTimestamp(cachedResponse) {
  3000. if (!cachedResponse.headers.has('date')) {
  3001. return null;
  3002. }
  3003. const dateHeader = cachedResponse.headers.get('date');
  3004. const parsedDate = new Date(dateHeader);
  3005. const headerTime = parsedDate.getTime();
  3006. // If the Date header was invalid for some reason, parsedDate.getTime()
  3007. // will return NaN.
  3008. if (isNaN(headerTime)) {
  3009. return null;
  3010. }
  3011. return headerTime;
  3012. }
  3013. /**
  3014. * This is a helper method that performs two operations:
  3015. *
  3016. * - Deletes *all* the underlying Cache instances associated with this plugin
  3017. * instance, by calling caches.delete() on your behalf.
  3018. * - Deletes the metadata from IndexedDB used to keep track of expiration
  3019. * details for each Cache instance.
  3020. *
  3021. * When using cache expiration, calling this method is preferable to calling
  3022. * `caches.delete()` directly, since this will ensure that the IndexedDB
  3023. * metadata is also cleanly removed and open IndexedDB instances are deleted.
  3024. *
  3025. * Note that if you're *not* using cache expiration for a given cache, calling
  3026. * `caches.delete()` and passing in the cache's name should be sufficient.
  3027. * There is no Workbox-specific method needed for cleanup in that case.
  3028. */
  3029. async deleteCacheAndMetadata() {
  3030. // Do this one at a time instead of all at once via `Promise.all()` to
  3031. // reduce the chance of inconsistency if a promise rejects.
  3032. for (const [cacheName, cacheExpiration] of this._cacheExpirations) {
  3033. await self.caches.delete(cacheName);
  3034. await cacheExpiration.delete();
  3035. }
  3036. // Reset this._cacheExpirations to its initial state.
  3037. this._cacheExpirations = new Map();
  3038. }
  3039. }
  3040. // @ts-ignore
  3041. try {
  3042. self['workbox:cacheable-response:7.0.0'] && _();
  3043. } catch (e) {}
  3044. /*
  3045. Copyright 2018 Google LLC
  3046. Use of this source code is governed by an MIT-style
  3047. license that can be found in the LICENSE file or at
  3048. https://opensource.org/licenses/MIT.
  3049. */
  3050. /**
  3051. * This class allows you to set up rules determining what
  3052. * status codes and/or headers need to be present in order for a
  3053. * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  3054. * to be considered cacheable.
  3055. *
  3056. * @memberof workbox-cacheable-response
  3057. */
  3058. class CacheableResponse {
  3059. /**
  3060. * To construct a new CacheableResponse instance you must provide at least
  3061. * one of the `config` properties.
  3062. *
  3063. * If both `statuses` and `headers` are specified, then both conditions must
  3064. * be met for the `Response` to be considered cacheable.
  3065. *
  3066. * @param {Object} config
  3067. * @param {Array<number>} [config.statuses] One or more status codes that a
  3068. * `Response` can have and be considered cacheable.
  3069. * @param {Object<string,string>} [config.headers] A mapping of header names
  3070. * and expected values that a `Response` can have and be considered cacheable.
  3071. * If multiple headers are provided, only one needs to be present.
  3072. */
  3073. constructor(config = {}) {
  3074. {
  3075. if (!(config.statuses || config.headers)) {
  3076. throw new WorkboxError('statuses-or-headers-required', {
  3077. moduleName: 'workbox-cacheable-response',
  3078. className: 'CacheableResponse',
  3079. funcName: 'constructor'
  3080. });
  3081. }
  3082. if (config.statuses) {
  3083. finalAssertExports.isArray(config.statuses, {
  3084. moduleName: 'workbox-cacheable-response',
  3085. className: 'CacheableResponse',
  3086. funcName: 'constructor',
  3087. paramName: 'config.statuses'
  3088. });
  3089. }
  3090. if (config.headers) {
  3091. finalAssertExports.isType(config.headers, 'object', {
  3092. moduleName: 'workbox-cacheable-response',
  3093. className: 'CacheableResponse',
  3094. funcName: 'constructor',
  3095. paramName: 'config.headers'
  3096. });
  3097. }
  3098. }
  3099. this._statuses = config.statuses;
  3100. this._headers = config.headers;
  3101. }
  3102. /**
  3103. * Checks a response to see whether it's cacheable or not, based on this
  3104. * object's configuration.
  3105. *
  3106. * @param {Response} response The response whose cacheability is being
  3107. * checked.
  3108. * @return {boolean} `true` if the `Response` is cacheable, and `false`
  3109. * otherwise.
  3110. */
  3111. isResponseCacheable(response) {
  3112. {
  3113. finalAssertExports.isInstance(response, Response, {
  3114. moduleName: 'workbox-cacheable-response',
  3115. className: 'CacheableResponse',
  3116. funcName: 'isResponseCacheable',
  3117. paramName: 'response'
  3118. });
  3119. }
  3120. let cacheable = true;
  3121. if (this._statuses) {
  3122. cacheable = this._statuses.includes(response.status);
  3123. }
  3124. if (this._headers && cacheable) {
  3125. cacheable = Object.keys(this._headers).some(headerName => {
  3126. return response.headers.get(headerName) === this._headers[headerName];
  3127. });
  3128. }
  3129. {
  3130. if (!cacheable) {
  3131. logger.groupCollapsed(`The request for ` + `'${getFriendlyURL(response.url)}' returned a response that does ` + `not meet the criteria for being cached.`);
  3132. logger.groupCollapsed(`View cacheability criteria here.`);
  3133. logger.log(`Cacheable statuses: ` + JSON.stringify(this._statuses));
  3134. logger.log(`Cacheable headers: ` + JSON.stringify(this._headers, null, 2));
  3135. logger.groupEnd();
  3136. const logFriendlyHeaders = {};
  3137. response.headers.forEach((value, key) => {
  3138. logFriendlyHeaders[key] = value;
  3139. });
  3140. logger.groupCollapsed(`View response status and headers here.`);
  3141. logger.log(`Response status: ${response.status}`);
  3142. logger.log(`Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2));
  3143. logger.groupEnd();
  3144. logger.groupCollapsed(`View full response details here.`);
  3145. logger.log(response.headers);
  3146. logger.log(response);
  3147. logger.groupEnd();
  3148. logger.groupEnd();
  3149. }
  3150. }
  3151. return cacheable;
  3152. }
  3153. }
  3154. /*
  3155. Copyright 2018 Google LLC
  3156. Use of this source code is governed by an MIT-style
  3157. license that can be found in the LICENSE file or at
  3158. https://opensource.org/licenses/MIT.
  3159. */
  3160. /**
  3161. * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it
  3162. * easier to add in cacheability checks to requests made via Workbox's built-in
  3163. * strategies.
  3164. *
  3165. * @memberof workbox-cacheable-response
  3166. */
  3167. class CacheableResponsePlugin {
  3168. /**
  3169. * To construct a new CacheableResponsePlugin instance you must provide at
  3170. * least one of the `config` properties.
  3171. *
  3172. * If both `statuses` and `headers` are specified, then both conditions must
  3173. * be met for the `Response` to be considered cacheable.
  3174. *
  3175. * @param {Object} config
  3176. * @param {Array<number>} [config.statuses] One or more status codes that a
  3177. * `Response` can have and be considered cacheable.
  3178. * @param {Object<string,string>} [config.headers] A mapping of header names
  3179. * and expected values that a `Response` can have and be considered cacheable.
  3180. * If multiple headers are provided, only one needs to be present.
  3181. */
  3182. constructor(config) {
  3183. /**
  3184. * @param {Object} options
  3185. * @param {Response} options.response
  3186. * @return {Response|null}
  3187. * @private
  3188. */
  3189. this.cacheWillUpdate = async ({
  3190. response
  3191. }) => {
  3192. if (this._cacheableResponse.isResponseCacheable(response)) {
  3193. return response;
  3194. }
  3195. return null;
  3196. };
  3197. this._cacheableResponse = new CacheableResponse(config);
  3198. }
  3199. }
  3200. /*
  3201. Copyright 2019 Google LLC
  3202. Use of this source code is governed by an MIT-style
  3203. license that can be found in the LICENSE file or at
  3204. https://opensource.org/licenses/MIT.
  3205. */
  3206. /**
  3207. * Claim any currently available clients once the service worker
  3208. * becomes active. This is normally used in conjunction with `skipWaiting()`.
  3209. *
  3210. * @memberof workbox-core
  3211. */
  3212. function clientsClaim() {
  3213. self.addEventListener('activate', () => self.clients.claim());
  3214. }
  3215. /*
  3216. Copyright 2020 Google LLC
  3217. Use of this source code is governed by an MIT-style
  3218. license that can be found in the LICENSE file or at
  3219. https://opensource.org/licenses/MIT.
  3220. */
  3221. /**
  3222. * A utility method that makes it easier to use `event.waitUntil` with
  3223. * async functions and return the result.
  3224. *
  3225. * @param {ExtendableEvent} event
  3226. * @param {Function} asyncFn
  3227. * @return {Function}
  3228. * @private
  3229. */
  3230. function waitUntil(event, asyncFn) {
  3231. const returnPromise = asyncFn();
  3232. event.waitUntil(returnPromise);
  3233. return returnPromise;
  3234. }
  3235. // @ts-ignore
  3236. try {
  3237. self['workbox:precaching:7.0.0'] && _();
  3238. } catch (e) {}
  3239. /*
  3240. Copyright 2018 Google LLC
  3241. Use of this source code is governed by an MIT-style
  3242. license that can be found in the LICENSE file or at
  3243. https://opensource.org/licenses/MIT.
  3244. */
  3245. // Name of the search parameter used to store revision info.
  3246. const REVISION_SEARCH_PARAM = '__WB_REVISION__';
  3247. /**
  3248. * Converts a manifest entry into a versioned URL suitable for precaching.
  3249. *
  3250. * @param {Object|string} entry
  3251. * @return {string} A URL with versioning info.
  3252. *
  3253. * @private
  3254. * @memberof workbox-precaching
  3255. */
  3256. function createCacheKey(entry) {
  3257. if (!entry) {
  3258. throw new WorkboxError('add-to-cache-list-unexpected-type', {
  3259. entry
  3260. });
  3261. }
  3262. // If a precache manifest entry is a string, it's assumed to be a versioned
  3263. // URL, like '/app.abcd1234.js'. Return as-is.
  3264. if (typeof entry === 'string') {
  3265. const urlObject = new URL(entry, location.href);
  3266. return {
  3267. cacheKey: urlObject.href,
  3268. url: urlObject.href
  3269. };
  3270. }
  3271. const {
  3272. revision,
  3273. url
  3274. } = entry;
  3275. if (!url) {
  3276. throw new WorkboxError('add-to-cache-list-unexpected-type', {
  3277. entry
  3278. });
  3279. }
  3280. // If there's just a URL and no revision, then it's also assumed to be a
  3281. // versioned URL.
  3282. if (!revision) {
  3283. const urlObject = new URL(url, location.href);
  3284. return {
  3285. cacheKey: urlObject.href,
  3286. url: urlObject.href
  3287. };
  3288. }
  3289. // Otherwise, construct a properly versioned URL using the custom Workbox
  3290. // search parameter along with the revision info.
  3291. const cacheKeyURL = new URL(url, location.href);
  3292. const originalURL = new URL(url, location.href);
  3293. cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
  3294. return {
  3295. cacheKey: cacheKeyURL.href,
  3296. url: originalURL.href
  3297. };
  3298. }
  3299. /*
  3300. Copyright 2020 Google LLC
  3301. Use of this source code is governed by an MIT-style
  3302. license that can be found in the LICENSE file or at
  3303. https://opensource.org/licenses/MIT.
  3304. */
  3305. /**
  3306. * A plugin, designed to be used with PrecacheController, to determine the
  3307. * of assets that were updated (or not updated) during the install event.
  3308. *
  3309. * @private
  3310. */
  3311. class PrecacheInstallReportPlugin {
  3312. constructor() {
  3313. this.updatedURLs = [];
  3314. this.notUpdatedURLs = [];
  3315. this.handlerWillStart = async ({
  3316. request,
  3317. state
  3318. }) => {
  3319. // TODO: `state` should never be undefined...
  3320. if (state) {
  3321. state.originalRequest = request;
  3322. }
  3323. };
  3324. this.cachedResponseWillBeUsed = async ({
  3325. event,
  3326. state,
  3327. cachedResponse
  3328. }) => {
  3329. if (event.type === 'install') {
  3330. if (state && state.originalRequest && state.originalRequest instanceof Request) {
  3331. // TODO: `state` should never be undefined...
  3332. const url = state.originalRequest.url;
  3333. if (cachedResponse) {
  3334. this.notUpdatedURLs.push(url);
  3335. } else {
  3336. this.updatedURLs.push(url);
  3337. }
  3338. }
  3339. }
  3340. return cachedResponse;
  3341. };
  3342. }
  3343. }
  3344. /*
  3345. Copyright 2020 Google LLC
  3346. Use of this source code is governed by an MIT-style
  3347. license that can be found in the LICENSE file or at
  3348. https://opensource.org/licenses/MIT.
  3349. */
  3350. /**
  3351. * A plugin, designed to be used with PrecacheController, to translate URLs into
  3352. * the corresponding cache key, based on the current revision info.
  3353. *
  3354. * @private
  3355. */
  3356. class PrecacheCacheKeyPlugin {
  3357. constructor({
  3358. precacheController
  3359. }) {
  3360. this.cacheKeyWillBeUsed = async ({
  3361. request,
  3362. params
  3363. }) => {
  3364. // Params is type any, can't change right now.
  3365. /* eslint-disable */
  3366. const cacheKey = (params === null || params === void 0 ? void 0 : params.cacheKey) || this._precacheController.getCacheKeyForURL(request.url);
  3367. /* eslint-enable */
  3368. return cacheKey ? new Request(cacheKey, {
  3369. headers: request.headers
  3370. }) : request;
  3371. };
  3372. this._precacheController = precacheController;
  3373. }
  3374. }
  3375. /*
  3376. Copyright 2018 Google LLC
  3377. Use of this source code is governed by an MIT-style
  3378. license that can be found in the LICENSE file or at
  3379. https://opensource.org/licenses/MIT.
  3380. */
  3381. /**
  3382. * @param {string} groupTitle
  3383. * @param {Array<string>} deletedURLs
  3384. *
  3385. * @private
  3386. */
  3387. const logGroup = (groupTitle, deletedURLs) => {
  3388. logger.groupCollapsed(groupTitle);
  3389. for (const url of deletedURLs) {
  3390. logger.log(url);
  3391. }
  3392. logger.groupEnd();
  3393. };
  3394. /**
  3395. * @param {Array<string>} deletedURLs
  3396. *
  3397. * @private
  3398. * @memberof workbox-precaching
  3399. */
  3400. function printCleanupDetails(deletedURLs) {
  3401. const deletionCount = deletedURLs.length;
  3402. if (deletionCount > 0) {
  3403. logger.groupCollapsed(`During precaching cleanup, ` + `${deletionCount} cached ` + `request${deletionCount === 1 ? ' was' : 's were'} deleted.`);
  3404. logGroup('Deleted Cache Requests', deletedURLs);
  3405. logger.groupEnd();
  3406. }
  3407. }
  3408. /*
  3409. Copyright 2018 Google LLC
  3410. Use of this source code is governed by an MIT-style
  3411. license that can be found in the LICENSE file or at
  3412. https://opensource.org/licenses/MIT.
  3413. */
  3414. /**
  3415. * @param {string} groupTitle
  3416. * @param {Array<string>} urls
  3417. *
  3418. * @private
  3419. */
  3420. function _nestedGroup(groupTitle, urls) {
  3421. if (urls.length === 0) {
  3422. return;
  3423. }
  3424. logger.groupCollapsed(groupTitle);
  3425. for (const url of urls) {
  3426. logger.log(url);
  3427. }
  3428. logger.groupEnd();
  3429. }
  3430. /**
  3431. * @param {Array<string>} urlsToPrecache
  3432. * @param {Array<string>} urlsAlreadyPrecached
  3433. *
  3434. * @private
  3435. * @memberof workbox-precaching
  3436. */
  3437. function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) {
  3438. const precachedCount = urlsToPrecache.length;
  3439. const alreadyPrecachedCount = urlsAlreadyPrecached.length;
  3440. if (precachedCount || alreadyPrecachedCount) {
  3441. let message = `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`;
  3442. if (alreadyPrecachedCount > 0) {
  3443. message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`;
  3444. }
  3445. logger.groupCollapsed(message);
  3446. _nestedGroup(`View newly precached URLs.`, urlsToPrecache);
  3447. _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached);
  3448. logger.groupEnd();
  3449. }
  3450. }
  3451. /*
  3452. Copyright 2019 Google LLC
  3453. Use of this source code is governed by an MIT-style
  3454. license that can be found in the LICENSE file or at
  3455. https://opensource.org/licenses/MIT.
  3456. */
  3457. let supportStatus;
  3458. /**
  3459. * A utility function that determines whether the current browser supports
  3460. * constructing a new `Response` from a `response.body` stream.
  3461. *
  3462. * @return {boolean} `true`, if the current browser can successfully
  3463. * construct a `Response` from a `response.body` stream, `false` otherwise.
  3464. *
  3465. * @private
  3466. */
  3467. function canConstructResponseFromBodyStream() {
  3468. if (supportStatus === undefined) {
  3469. const testResponse = new Response('');
  3470. if ('body' in testResponse) {
  3471. try {
  3472. new Response(testResponse.body);
  3473. supportStatus = true;
  3474. } catch (error) {
  3475. supportStatus = false;
  3476. }
  3477. }
  3478. supportStatus = false;
  3479. }
  3480. return supportStatus;
  3481. }
  3482. /*
  3483. Copyright 2019 Google LLC
  3484. Use of this source code is governed by an MIT-style
  3485. license that can be found in the LICENSE file or at
  3486. https://opensource.org/licenses/MIT.
  3487. */
  3488. /**
  3489. * Allows developers to copy a response and modify its `headers`, `status`,
  3490. * or `statusText` values (the values settable via a
  3491. * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}
  3492. * object in the constructor).
  3493. * To modify these values, pass a function as the second argument. That
  3494. * function will be invoked with a single object with the response properties
  3495. * `{headers, status, statusText}`. The return value of this function will
  3496. * be used as the `ResponseInit` for the new `Response`. To change the values
  3497. * either modify the passed parameter(s) and return it, or return a totally
  3498. * new object.
  3499. *
  3500. * This method is intentionally limited to same-origin responses, regardless of
  3501. * whether CORS was used or not.
  3502. *
  3503. * @param {Response} response
  3504. * @param {Function} modifier
  3505. * @memberof workbox-core
  3506. */
  3507. async function copyResponse(response, modifier) {
  3508. let origin = null;
  3509. // If response.url isn't set, assume it's cross-origin and keep origin null.
  3510. if (response.url) {
  3511. const responseURL = new URL(response.url);
  3512. origin = responseURL.origin;
  3513. }
  3514. if (origin !== self.location.origin) {
  3515. throw new WorkboxError('cross-origin-copy-response', {
  3516. origin
  3517. });
  3518. }
  3519. const clonedResponse = response.clone();
  3520. // Create a fresh `ResponseInit` object by cloning the headers.
  3521. const responseInit = {
  3522. headers: new Headers(clonedResponse.headers),
  3523. status: clonedResponse.status,
  3524. statusText: clonedResponse.statusText
  3525. };
  3526. // Apply any user modifications.
  3527. const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;
  3528. // Create the new response from the body stream and `ResponseInit`
  3529. // modifications. Note: not all browsers support the Response.body stream,
  3530. // so fall back to reading the entire body into memory as a blob.
  3531. const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob();
  3532. return new Response(body, modifiedResponseInit);
  3533. }
  3534. /*
  3535. Copyright 2020 Google LLC
  3536. Use of this source code is governed by an MIT-style
  3537. license that can be found in the LICENSE file or at
  3538. https://opensource.org/licenses/MIT.
  3539. */
  3540. /**
  3541. * A {@link workbox-strategies.Strategy} implementation
  3542. * specifically designed to work with
  3543. * {@link workbox-precaching.PrecacheController}
  3544. * to both cache and fetch precached assets.
  3545. *
  3546. * Note: an instance of this class is created automatically when creating a
  3547. * `PrecacheController`; it's generally not necessary to create this yourself.
  3548. *
  3549. * @extends workbox-strategies.Strategy
  3550. * @memberof workbox-precaching
  3551. */
  3552. class PrecacheStrategy extends Strategy {
  3553. /**
  3554. *
  3555. * @param {Object} [options]
  3556. * @param {string} [options.cacheName] Cache name to store and retrieve
  3557. * requests. Defaults to the cache names provided by
  3558. * {@link workbox-core.cacheNames}.
  3559. * @param {Array<Object>} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins}
  3560. * to use in conjunction with this caching strategy.
  3561. * @param {Object} [options.fetchOptions] Values passed along to the
  3562. * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}
  3563. * of all fetch() requests made by this strategy.
  3564. * @param {Object} [options.matchOptions] The
  3565. * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions}
  3566. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  3567. * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to
  3568. * get the response from the network if there's a precache miss.
  3569. */
  3570. constructor(options = {}) {
  3571. options.cacheName = cacheNames.getPrecacheName(options.cacheName);
  3572. super(options);
  3573. this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true;
  3574. // Redirected responses cannot be used to satisfy a navigation request, so
  3575. // any redirected response must be "copied" rather than cloned, so the new
  3576. // response doesn't contain the `redirected` flag. See:
  3577. // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1
  3578. this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);
  3579. }
  3580. /**
  3581. * @private
  3582. * @param {Request|string} request A request to run this strategy for.
  3583. * @param {workbox-strategies.StrategyHandler} handler The event that
  3584. * triggered the request.
  3585. * @return {Promise<Response>}
  3586. */
  3587. async _handle(request, handler) {
  3588. const response = await handler.cacheMatch(request);
  3589. if (response) {
  3590. return response;
  3591. }
  3592. // If this is an `install` event for an entry that isn't already cached,
  3593. // then populate the cache.
  3594. if (handler.event && handler.event.type === 'install') {
  3595. return await this._handleInstall(request, handler);
  3596. }
  3597. // Getting here means something went wrong. An entry that should have been
  3598. // precached wasn't found in the cache.
  3599. return await this._handleFetch(request, handler);
  3600. }
  3601. async _handleFetch(request, handler) {
  3602. let response;
  3603. const params = handler.params || {};
  3604. // Fall back to the network if we're configured to do so.
  3605. if (this._fallbackToNetwork) {
  3606. {
  3607. logger.warn(`The precached response for ` + `${getFriendlyURL(request.url)} in ${this.cacheName} was not ` + `found. Falling back to the network.`);
  3608. }
  3609. const integrityInManifest = params.integrity;
  3610. const integrityInRequest = request.integrity;
  3611. const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;
  3612. // Do not add integrity if the original request is no-cors
  3613. // See https://github.com/GoogleChrome/workbox/issues/3096
  3614. response = await handler.fetch(new Request(request, {
  3615. integrity: request.mode !== 'no-cors' ? integrityInRequest || integrityInManifest : undefined
  3616. }));
  3617. // It's only "safe" to repair the cache if we're using SRI to guarantee
  3618. // that the response matches the precache manifest's expectations,
  3619. // and there's either a) no integrity property in the incoming request
  3620. // or b) there is an integrity, and it matches the precache manifest.
  3621. // See https://github.com/GoogleChrome/workbox/issues/2858
  3622. // Also if the original request users no-cors we don't use integrity.
  3623. // See https://github.com/GoogleChrome/workbox/issues/3096
  3624. if (integrityInManifest && noIntegrityConflict && request.mode !== 'no-cors') {
  3625. this._useDefaultCacheabilityPluginIfNeeded();
  3626. const wasCached = await handler.cachePut(request, response.clone());
  3627. {
  3628. if (wasCached) {
  3629. logger.log(`A response for ${getFriendlyURL(request.url)} ` + `was used to "repair" the precache.`);
  3630. }
  3631. }
  3632. }
  3633. } else {
  3634. // This shouldn't normally happen, but there are edge cases:
  3635. // https://github.com/GoogleChrome/workbox/issues/1441
  3636. throw new WorkboxError('missing-precache-entry', {
  3637. cacheName: this.cacheName,
  3638. url: request.url
  3639. });
  3640. }
  3641. {
  3642. const cacheKey = params.cacheKey || (await handler.getCacheKey(request, 'read'));
  3643. // Workbox is going to handle the route.
  3644. // print the routing details to the console.
  3645. logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL(request.url));
  3646. logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);
  3647. logger.groupCollapsed(`View request details here.`);
  3648. logger.log(request);
  3649. logger.groupEnd();
  3650. logger.groupCollapsed(`View response details here.`);
  3651. logger.log(response);
  3652. logger.groupEnd();
  3653. logger.groupEnd();
  3654. }
  3655. return response;
  3656. }
  3657. async _handleInstall(request, handler) {
  3658. this._useDefaultCacheabilityPluginIfNeeded();
  3659. const response = await handler.fetch(request);
  3660. // Make sure we defer cachePut() until after we know the response
  3661. // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737
  3662. const wasCached = await handler.cachePut(request, response.clone());
  3663. if (!wasCached) {
  3664. // Throwing here will lead to the `install` handler failing, which
  3665. // we want to do if *any* of the responses aren't safe to cache.
  3666. throw new WorkboxError('bad-precaching-response', {
  3667. url: request.url,
  3668. status: response.status
  3669. });
  3670. }
  3671. return response;
  3672. }
  3673. /**
  3674. * This method is complex, as there a number of things to account for:
  3675. *
  3676. * The `plugins` array can be set at construction, and/or it might be added to
  3677. * to at any time before the strategy is used.
  3678. *
  3679. * At the time the strategy is used (i.e. during an `install` event), there
  3680. * needs to be at least one plugin that implements `cacheWillUpdate` in the
  3681. * array, other than `copyRedirectedCacheableResponsesPlugin`.
  3682. *
  3683. * - If this method is called and there are no suitable `cacheWillUpdate`
  3684. * plugins, we need to add `defaultPrecacheCacheabilityPlugin`.
  3685. *
  3686. * - If this method is called and there is exactly one `cacheWillUpdate`, then
  3687. * we don't have to do anything (this might be a previously added
  3688. * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin).
  3689. *
  3690. * - If this method is called and there is more than one `cacheWillUpdate`,
  3691. * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so,
  3692. * we need to remove it. (This situation is unlikely, but it could happen if
  3693. * the strategy is used multiple times, the first without a `cacheWillUpdate`,
  3694. * and then later on after manually adding a custom `cacheWillUpdate`.)
  3695. *
  3696. * See https://github.com/GoogleChrome/workbox/issues/2737 for more context.
  3697. *
  3698. * @private
  3699. */
  3700. _useDefaultCacheabilityPluginIfNeeded() {
  3701. let defaultPluginIndex = null;
  3702. let cacheWillUpdatePluginCount = 0;
  3703. for (const [index, plugin] of this.plugins.entries()) {
  3704. // Ignore the copy redirected plugin when determining what to do.
  3705. if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {
  3706. continue;
  3707. }
  3708. // Save the default plugin's index, in case it needs to be removed.
  3709. if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {
  3710. defaultPluginIndex = index;
  3711. }
  3712. if (plugin.cacheWillUpdate) {
  3713. cacheWillUpdatePluginCount++;
  3714. }
  3715. }
  3716. if (cacheWillUpdatePluginCount === 0) {
  3717. this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);
  3718. } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {
  3719. // Only remove the default plugin; multiple custom plugins are allowed.
  3720. this.plugins.splice(defaultPluginIndex, 1);
  3721. }
  3722. // Nothing needs to be done if cacheWillUpdatePluginCount is 1
  3723. }
  3724. }
  3725. PrecacheStrategy.defaultPrecacheCacheabilityPlugin = {
  3726. async cacheWillUpdate({
  3727. response
  3728. }) {
  3729. if (!response || response.status >= 400) {
  3730. return null;
  3731. }
  3732. return response;
  3733. }
  3734. };
  3735. PrecacheStrategy.copyRedirectedCacheableResponsesPlugin = {
  3736. async cacheWillUpdate({
  3737. response
  3738. }) {
  3739. return response.redirected ? await copyResponse(response) : response;
  3740. }
  3741. };
  3742. /*
  3743. Copyright 2019 Google LLC
  3744. Use of this source code is governed by an MIT-style
  3745. license that can be found in the LICENSE file or at
  3746. https://opensource.org/licenses/MIT.
  3747. */
  3748. /**
  3749. * Performs efficient precaching of assets.
  3750. *
  3751. * @memberof workbox-precaching
  3752. */
  3753. class PrecacheController {
  3754. /**
  3755. * Create a new PrecacheController.
  3756. *
  3757. * @param {Object} [options]
  3758. * @param {string} [options.cacheName] The cache to use for precaching.
  3759. * @param {string} [options.plugins] Plugins to use when precaching as well
  3760. * as responding to fetch events for precached assets.
  3761. * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to
  3762. * get the response from the network if there's a precache miss.
  3763. */
  3764. constructor({
  3765. cacheName,
  3766. plugins = [],
  3767. fallbackToNetwork = true
  3768. } = {}) {
  3769. this._urlsToCacheKeys = new Map();
  3770. this._urlsToCacheModes = new Map();
  3771. this._cacheKeysToIntegrities = new Map();
  3772. this._strategy = new PrecacheStrategy({
  3773. cacheName: cacheNames.getPrecacheName(cacheName),
  3774. plugins: [...plugins, new PrecacheCacheKeyPlugin({
  3775. precacheController: this
  3776. })],
  3777. fallbackToNetwork
  3778. });
  3779. // Bind the install and activate methods to the instance.
  3780. this.install = this.install.bind(this);
  3781. this.activate = this.activate.bind(this);
  3782. }
  3783. /**
  3784. * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and
  3785. * used to cache assets and respond to fetch events.
  3786. */
  3787. get strategy() {
  3788. return this._strategy;
  3789. }
  3790. /**
  3791. * Adds items to the precache list, removing any duplicates and
  3792. * stores the files in the
  3793. * {@link workbox-core.cacheNames|"precache cache"} when the service
  3794. * worker installs.
  3795. *
  3796. * This method can be called multiple times.
  3797. *
  3798. * @param {Array<Object|string>} [entries=[]] Array of entries to precache.
  3799. */
  3800. precache(entries) {
  3801. this.addToCacheList(entries);
  3802. if (!this._installAndActiveListenersAdded) {
  3803. self.addEventListener('install', this.install);
  3804. self.addEventListener('activate', this.activate);
  3805. this._installAndActiveListenersAdded = true;
  3806. }
  3807. }
  3808. /**
  3809. * This method will add items to the precache list, removing duplicates
  3810. * and ensuring the information is valid.
  3811. *
  3812. * @param {Array<workbox-precaching.PrecacheController.PrecacheEntry|string>} entries
  3813. * Array of entries to precache.
  3814. */
  3815. addToCacheList(entries) {
  3816. {
  3817. finalAssertExports.isArray(entries, {
  3818. moduleName: 'workbox-precaching',
  3819. className: 'PrecacheController',
  3820. funcName: 'addToCacheList',
  3821. paramName: 'entries'
  3822. });
  3823. }
  3824. const urlsToWarnAbout = [];
  3825. for (const entry of entries) {
  3826. // See https://github.com/GoogleChrome/workbox/issues/2259
  3827. if (typeof entry === 'string') {
  3828. urlsToWarnAbout.push(entry);
  3829. } else if (entry && entry.revision === undefined) {
  3830. urlsToWarnAbout.push(entry.url);
  3831. }
  3832. const {
  3833. cacheKey,
  3834. url
  3835. } = createCacheKey(entry);
  3836. const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default';
  3837. if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
  3838. throw new WorkboxError('add-to-cache-list-conflicting-entries', {
  3839. firstEntry: this._urlsToCacheKeys.get(url),
  3840. secondEntry: cacheKey
  3841. });
  3842. }
  3843. if (typeof entry !== 'string' && entry.integrity) {
  3844. if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
  3845. throw new WorkboxError('add-to-cache-list-conflicting-integrities', {
  3846. url
  3847. });
  3848. }
  3849. this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
  3850. }
  3851. this._urlsToCacheKeys.set(url, cacheKey);
  3852. this._urlsToCacheModes.set(url, cacheMode);
  3853. if (urlsToWarnAbout.length > 0) {
  3854. const warningMessage = `Workbox is precaching URLs without revision ` + `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` + `Learn more at https://bit.ly/wb-precache`;
  3855. {
  3856. logger.warn(warningMessage);
  3857. }
  3858. }
  3859. }
  3860. }
  3861. /**
  3862. * Precaches new and updated assets. Call this method from the service worker
  3863. * install event.
  3864. *
  3865. * Note: this method calls `event.waitUntil()` for you, so you do not need
  3866. * to call it yourself in your event handlers.
  3867. *
  3868. * @param {ExtendableEvent} event
  3869. * @return {Promise<workbox-precaching.InstallResult>}
  3870. */
  3871. install(event) {
  3872. // waitUntil returns Promise<any>
  3873. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  3874. return waitUntil(event, async () => {
  3875. const installReportPlugin = new PrecacheInstallReportPlugin();
  3876. this.strategy.plugins.push(installReportPlugin);
  3877. // Cache entries one at a time.
  3878. // See https://github.com/GoogleChrome/workbox/issues/2528
  3879. for (const [url, cacheKey] of this._urlsToCacheKeys) {
  3880. const integrity = this._cacheKeysToIntegrities.get(cacheKey);
  3881. const cacheMode = this._urlsToCacheModes.get(url);
  3882. const request = new Request(url, {
  3883. integrity,
  3884. cache: cacheMode,
  3885. credentials: 'same-origin'
  3886. });
  3887. await Promise.all(this.strategy.handleAll({
  3888. params: {
  3889. cacheKey
  3890. },
  3891. request,
  3892. event
  3893. }));
  3894. }
  3895. const {
  3896. updatedURLs,
  3897. notUpdatedURLs
  3898. } = installReportPlugin;
  3899. {
  3900. printInstallDetails(updatedURLs, notUpdatedURLs);
  3901. }
  3902. return {
  3903. updatedURLs,
  3904. notUpdatedURLs
  3905. };
  3906. });
  3907. }
  3908. /**
  3909. * Deletes assets that are no longer present in the current precache manifest.
  3910. * Call this method from the service worker activate event.
  3911. *
  3912. * Note: this method calls `event.waitUntil()` for you, so you do not need
  3913. * to call it yourself in your event handlers.
  3914. *
  3915. * @param {ExtendableEvent} event
  3916. * @return {Promise<workbox-precaching.CleanupResult>}
  3917. */
  3918. activate(event) {
  3919. // waitUntil returns Promise<any>
  3920. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  3921. return waitUntil(event, async () => {
  3922. const cache = await self.caches.open(this.strategy.cacheName);
  3923. const currentlyCachedRequests = await cache.keys();
  3924. const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
  3925. const deletedURLs = [];
  3926. for (const request of currentlyCachedRequests) {
  3927. if (!expectedCacheKeys.has(request.url)) {
  3928. await cache.delete(request);
  3929. deletedURLs.push(request.url);
  3930. }
  3931. }
  3932. {
  3933. printCleanupDetails(deletedURLs);
  3934. }
  3935. return {
  3936. deletedURLs
  3937. };
  3938. });
  3939. }
  3940. /**
  3941. * Returns a mapping of a precached URL to the corresponding cache key, taking
  3942. * into account the revision information for the URL.
  3943. *
  3944. * @return {Map<string, string>} A URL to cache key mapping.
  3945. */
  3946. getURLsToCacheKeys() {
  3947. return this._urlsToCacheKeys;
  3948. }
  3949. /**
  3950. * Returns a list of all the URLs that have been precached by the current
  3951. * service worker.
  3952. *
  3953. * @return {Array<string>} The precached URLs.
  3954. */
  3955. getCachedURLs() {
  3956. return [...this._urlsToCacheKeys.keys()];
  3957. }
  3958. /**
  3959. * Returns the cache key used for storing a given URL. If that URL is
  3960. * unversioned, like `/index.html', then the cache key will be the original
  3961. * URL with a search parameter appended to it.
  3962. *
  3963. * @param {string} url A URL whose cache key you want to look up.
  3964. * @return {string} The versioned URL that corresponds to a cache key
  3965. * for the original URL, or undefined if that URL isn't precached.
  3966. */
  3967. getCacheKeyForURL(url) {
  3968. const urlObject = new URL(url, location.href);
  3969. return this._urlsToCacheKeys.get(urlObject.href);
  3970. }
  3971. /**
  3972. * @param {string} url A cache key whose SRI you want to look up.
  3973. * @return {string} The subresource integrity associated with the cache key,
  3974. * or undefined if it's not set.
  3975. */
  3976. getIntegrityForCacheKey(cacheKey) {
  3977. return this._cacheKeysToIntegrities.get(cacheKey);
  3978. }
  3979. /**
  3980. * This acts as a drop-in replacement for
  3981. * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
  3982. * with the following differences:
  3983. *
  3984. * - It knows what the name of the precache is, and only checks in that cache.
  3985. * - It allows you to pass in an "original" URL without versioning parameters,
  3986. * and it will automatically look up the correct cache key for the currently
  3987. * active revision of that URL.
  3988. *
  3989. * E.g., `matchPrecache('index.html')` will find the correct precached
  3990. * response for the currently active service worker, even if the actual cache
  3991. * key is `'/index.html?__WB_REVISION__=1234abcd'`.
  3992. *
  3993. * @param {string|Request} request The key (without revisioning parameters)
  3994. * to look up in the precache.
  3995. * @return {Promise<Response|undefined>}
  3996. */
  3997. async matchPrecache(request) {
  3998. const url = request instanceof Request ? request.url : request;
  3999. const cacheKey = this.getCacheKeyForURL(url);
  4000. if (cacheKey) {
  4001. const cache = await self.caches.open(this.strategy.cacheName);
  4002. return cache.match(cacheKey);
  4003. }
  4004. return undefined;
  4005. }
  4006. /**
  4007. * Returns a function that looks up `url` in the precache (taking into
  4008. * account revision information), and returns the corresponding `Response`.
  4009. *
  4010. * @param {string} url The precached URL which will be used to lookup the
  4011. * `Response`.
  4012. * @return {workbox-routing~handlerCallback}
  4013. */
  4014. createHandlerBoundToURL(url) {
  4015. const cacheKey = this.getCacheKeyForURL(url);
  4016. if (!cacheKey) {
  4017. throw new WorkboxError('non-precached-url', {
  4018. url
  4019. });
  4020. }
  4021. return options => {
  4022. options.request = new Request(url);
  4023. options.params = Object.assign({
  4024. cacheKey
  4025. }, options.params);
  4026. return this.strategy.handle(options);
  4027. };
  4028. }
  4029. }
  4030. /*
  4031. Copyright 2019 Google LLC
  4032. Use of this source code is governed by an MIT-style
  4033. license that can be found in the LICENSE file or at
  4034. https://opensource.org/licenses/MIT.
  4035. */
  4036. let precacheController;
  4037. /**
  4038. * @return {PrecacheController}
  4039. * @private
  4040. */
  4041. const getOrCreatePrecacheController = () => {
  4042. if (!precacheController) {
  4043. precacheController = new PrecacheController();
  4044. }
  4045. return precacheController;
  4046. };
  4047. /*
  4048. Copyright 2018 Google LLC
  4049. Use of this source code is governed by an MIT-style
  4050. license that can be found in the LICENSE file or at
  4051. https://opensource.org/licenses/MIT.
  4052. */
  4053. /**
  4054. * Removes any URL search parameters that should be ignored.
  4055. *
  4056. * @param {URL} urlObject The original URL.
  4057. * @param {Array<RegExp>} ignoreURLParametersMatching RegExps to test against
  4058. * each search parameter name. Matches mean that the search parameter should be
  4059. * ignored.
  4060. * @return {URL} The URL with any ignored search parameters removed.
  4061. *
  4062. * @private
  4063. * @memberof workbox-precaching
  4064. */
  4065. function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) {
  4066. // Convert the iterable into an array at the start of the loop to make sure
  4067. // deletion doesn't mess up iteration.
  4068. for (const paramName of [...urlObject.searchParams.keys()]) {
  4069. if (ignoreURLParametersMatching.some(regExp => regExp.test(paramName))) {
  4070. urlObject.searchParams.delete(paramName);
  4071. }
  4072. }
  4073. return urlObject;
  4074. }
  4075. /*
  4076. Copyright 2019 Google LLC
  4077. Use of this source code is governed by an MIT-style
  4078. license that can be found in the LICENSE file or at
  4079. https://opensource.org/licenses/MIT.
  4080. */
  4081. /**
  4082. * Generator function that yields possible variations on the original URL to
  4083. * check, one at a time.
  4084. *
  4085. * @param {string} url
  4086. * @param {Object} options
  4087. *
  4088. * @private
  4089. * @memberof workbox-precaching
  4090. */
  4091. function* generateURLVariations(url, {
  4092. ignoreURLParametersMatching = [/^utm_/, /^fbclid$/],
  4093. directoryIndex = 'index.html',
  4094. cleanURLs = true,
  4095. urlManipulation
  4096. } = {}) {
  4097. const urlObject = new URL(url, location.href);
  4098. urlObject.hash = '';
  4099. yield urlObject.href;
  4100. const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);
  4101. yield urlWithoutIgnoredParams.href;
  4102. if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) {
  4103. const directoryURL = new URL(urlWithoutIgnoredParams.href);
  4104. directoryURL.pathname += directoryIndex;
  4105. yield directoryURL.href;
  4106. }
  4107. if (cleanURLs) {
  4108. const cleanURL = new URL(urlWithoutIgnoredParams.href);
  4109. cleanURL.pathname += '.html';
  4110. yield cleanURL.href;
  4111. }
  4112. if (urlManipulation) {
  4113. const additionalURLs = urlManipulation({
  4114. url: urlObject
  4115. });
  4116. for (const urlToAttempt of additionalURLs) {
  4117. yield urlToAttempt.href;
  4118. }
  4119. }
  4120. }
  4121. /*
  4122. Copyright 2020 Google LLC
  4123. Use of this source code is governed by an MIT-style
  4124. license that can be found in the LICENSE file or at
  4125. https://opensource.org/licenses/MIT.
  4126. */
  4127. /**
  4128. * A subclass of {@link workbox-routing.Route} that takes a
  4129. * {@link workbox-precaching.PrecacheController}
  4130. * instance and uses it to match incoming requests and handle fetching
  4131. * responses from the precache.
  4132. *
  4133. * @memberof workbox-precaching
  4134. * @extends workbox-routing.Route
  4135. */
  4136. class PrecacheRoute extends Route {
  4137. /**
  4138. * @param {PrecacheController} precacheController A `PrecacheController`
  4139. * instance used to both match requests and respond to fetch events.
  4140. * @param {Object} [options] Options to control how requests are matched
  4141. * against the list of precached URLs.
  4142. * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will
  4143. * check cache entries for a URLs ending with '/' to see if there is a hit when
  4144. * appending the `directoryIndex` value.
  4145. * @param {Array<RegExp>} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An
  4146. * array of regex's to remove search params when looking for a cache match.
  4147. * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will
  4148. * check the cache for the URL with a `.html` added to the end of the end.
  4149. * @param {workbox-precaching~urlManipulation} [options.urlManipulation]
  4150. * This is a function that should take a URL and return an array of
  4151. * alternative URLs that should be checked for precache matches.
  4152. */
  4153. constructor(precacheController, options) {
  4154. const match = ({
  4155. request
  4156. }) => {
  4157. const urlsToCacheKeys = precacheController.getURLsToCacheKeys();
  4158. for (const possibleURL of generateURLVariations(request.url, options)) {
  4159. const cacheKey = urlsToCacheKeys.get(possibleURL);
  4160. if (cacheKey) {
  4161. const integrity = precacheController.getIntegrityForCacheKey(cacheKey);
  4162. return {
  4163. cacheKey,
  4164. integrity
  4165. };
  4166. }
  4167. }
  4168. {
  4169. logger.debug(`Precaching did not find a match for ` + getFriendlyURL(request.url));
  4170. }
  4171. return;
  4172. };
  4173. super(match, precacheController.strategy);
  4174. }
  4175. }
  4176. /*
  4177. Copyright 2019 Google LLC
  4178. Use of this source code is governed by an MIT-style
  4179. license that can be found in the LICENSE file or at
  4180. https://opensource.org/licenses/MIT.
  4181. */
  4182. /**
  4183. * Add a `fetch` listener to the service worker that will
  4184. * respond to
  4185. * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}
  4186. * with precached assets.
  4187. *
  4188. * Requests for assets that aren't precached, the `FetchEvent` will not be
  4189. * responded to, allowing the event to fall through to other `fetch` event
  4190. * listeners.
  4191. *
  4192. * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute}
  4193. * options.
  4194. *
  4195. * @memberof workbox-precaching
  4196. */
  4197. function addRoute(options) {
  4198. const precacheController = getOrCreatePrecacheController();
  4199. const precacheRoute = new PrecacheRoute(precacheController, options);
  4200. registerRoute(precacheRoute);
  4201. }
  4202. /*
  4203. Copyright 2019 Google LLC
  4204. Use of this source code is governed by an MIT-style
  4205. license that can be found in the LICENSE file or at
  4206. https://opensource.org/licenses/MIT.
  4207. */
  4208. /**
  4209. * Adds items to the precache list, removing any duplicates and
  4210. * stores the files in the
  4211. * {@link workbox-core.cacheNames|"precache cache"} when the service
  4212. * worker installs.
  4213. *
  4214. * This method can be called multiple times.
  4215. *
  4216. * Please note: This method **will not** serve any of the cached files for you.
  4217. * It only precaches files. To respond to a network request you call
  4218. * {@link workbox-precaching.addRoute}.
  4219. *
  4220. * If you have a single array of files to precache, you can just call
  4221. * {@link workbox-precaching.precacheAndRoute}.
  4222. *
  4223. * @param {Array<Object|string>} [entries=[]] Array of entries to precache.
  4224. *
  4225. * @memberof workbox-precaching
  4226. */
  4227. function precache(entries) {
  4228. const precacheController = getOrCreatePrecacheController();
  4229. precacheController.precache(entries);
  4230. }
  4231. /*
  4232. Copyright 2019 Google LLC
  4233. Use of this source code is governed by an MIT-style
  4234. license that can be found in the LICENSE file or at
  4235. https://opensource.org/licenses/MIT.
  4236. */
  4237. /**
  4238. * This method will add entries to the precache list and add a route to
  4239. * respond to fetch events.
  4240. *
  4241. * This is a convenience method that will call
  4242. * {@link workbox-precaching.precache} and
  4243. * {@link workbox-precaching.addRoute} in a single call.
  4244. *
  4245. * @param {Array<Object|string>} entries Array of entries to precache.
  4246. * @param {Object} [options] See the
  4247. * {@link workbox-precaching.PrecacheRoute} options.
  4248. *
  4249. * @memberof workbox-precaching
  4250. */
  4251. function precacheAndRoute(entries, options) {
  4252. precache(entries);
  4253. addRoute(options);
  4254. }
  4255. /*
  4256. Copyright 2018 Google LLC
  4257. Use of this source code is governed by an MIT-style
  4258. license that can be found in the LICENSE file or at
  4259. https://opensource.org/licenses/MIT.
  4260. */
  4261. const SUBSTRING_TO_FIND = '-precache-';
  4262. /**
  4263. * Cleans up incompatible precaches that were created by older versions of
  4264. * Workbox, by a service worker registered under the current scope.
  4265. *
  4266. * This is meant to be called as part of the `activate` event.
  4267. *
  4268. * This should be safe to use as long as you don't include `substringToFind`
  4269. * (defaulting to `-precache-`) in your non-precache cache names.
  4270. *
  4271. * @param {string} currentPrecacheName The cache name currently in use for
  4272. * precaching. This cache won't be deleted.
  4273. * @param {string} [substringToFind='-precache-'] Cache names which include this
  4274. * substring will be deleted (excluding `currentPrecacheName`).
  4275. * @return {Array<string>} A list of all the cache names that were deleted.
  4276. *
  4277. * @private
  4278. * @memberof workbox-precaching
  4279. */
  4280. const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => {
  4281. const cacheNames = await self.caches.keys();
  4282. const cacheNamesToDelete = cacheNames.filter(cacheName => {
  4283. return cacheName.includes(substringToFind) && cacheName.includes(self.registration.scope) && cacheName !== currentPrecacheName;
  4284. });
  4285. await Promise.all(cacheNamesToDelete.map(cacheName => self.caches.delete(cacheName)));
  4286. return cacheNamesToDelete;
  4287. };
  4288. /*
  4289. Copyright 2019 Google LLC
  4290. Use of this source code is governed by an MIT-style
  4291. license that can be found in the LICENSE file or at
  4292. https://opensource.org/licenses/MIT.
  4293. */
  4294. /**
  4295. * Adds an `activate` event listener which will clean up incompatible
  4296. * precaches that were created by older versions of Workbox.
  4297. *
  4298. * @memberof workbox-precaching
  4299. */
  4300. function cleanupOutdatedCaches() {
  4301. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  4302. self.addEventListener('activate', event => {
  4303. const cacheName = cacheNames.getPrecacheName();
  4304. event.waitUntil(deleteOutdatedCaches(cacheName).then(cachesDeleted => {
  4305. {
  4306. if (cachesDeleted.length > 0) {
  4307. logger.log(`The following out-of-date precaches were cleaned up ` + `automatically:`, cachesDeleted);
  4308. }
  4309. }
  4310. }));
  4311. });
  4312. }
  4313. /*
  4314. Copyright 2018 Google LLC
  4315. Use of this source code is governed by an MIT-style
  4316. license that can be found in the LICENSE file or at
  4317. https://opensource.org/licenses/MIT.
  4318. */
  4319. /**
  4320. * NavigationRoute makes it easy to create a
  4321. * {@link workbox-routing.Route} that matches for browser
  4322. * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}.
  4323. *
  4324. * It will only match incoming Requests whose
  4325. * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode}
  4326. * is set to `navigate`.
  4327. *
  4328. * You can optionally only apply this route to a subset of navigation requests
  4329. * by using one or both of the `denylist` and `allowlist` parameters.
  4330. *
  4331. * @memberof workbox-routing
  4332. * @extends workbox-routing.Route
  4333. */
  4334. class NavigationRoute extends Route {
  4335. /**
  4336. * If both `denylist` and `allowlist` are provided, the `denylist` will
  4337. * take precedence and the request will not match this route.
  4338. *
  4339. * The regular expressions in `allowlist` and `denylist`
  4340. * are matched against the concatenated
  4341. * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname}
  4342. * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search}
  4343. * portions of the requested URL.
  4344. *
  4345. * *Note*: These RegExps may be evaluated against every destination URL during
  4346. * a navigation. Avoid using
  4347. * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
  4348. * or else your users may see delays when navigating your site.
  4349. *
  4350. * @param {workbox-routing~handlerCallback} handler A callback
  4351. * function that returns a Promise resulting in a Response.
  4352. * @param {Object} options
  4353. * @param {Array<RegExp>} [options.denylist] If any of these patterns match,
  4354. * the route will not handle the request (even if a allowlist RegExp matches).
  4355. * @param {Array<RegExp>} [options.allowlist=[/./]] If any of these patterns
  4356. * match the URL's pathname and search parameter, the route will handle the
  4357. * request (assuming the denylist doesn't match).
  4358. */
  4359. constructor(handler, {
  4360. allowlist = [/./],
  4361. denylist = []
  4362. } = {}) {
  4363. {
  4364. finalAssertExports.isArrayOfClass(allowlist, RegExp, {
  4365. moduleName: 'workbox-routing',
  4366. className: 'NavigationRoute',
  4367. funcName: 'constructor',
  4368. paramName: 'options.allowlist'
  4369. });
  4370. finalAssertExports.isArrayOfClass(denylist, RegExp, {
  4371. moduleName: 'workbox-routing',
  4372. className: 'NavigationRoute',
  4373. funcName: 'constructor',
  4374. paramName: 'options.denylist'
  4375. });
  4376. }
  4377. super(options => this._match(options), handler);
  4378. this._allowlist = allowlist;
  4379. this._denylist = denylist;
  4380. }
  4381. /**
  4382. * Routes match handler.
  4383. *
  4384. * @param {Object} options
  4385. * @param {URL} options.url
  4386. * @param {Request} options.request
  4387. * @return {boolean}
  4388. *
  4389. * @private
  4390. */
  4391. _match({
  4392. url,
  4393. request
  4394. }) {
  4395. if (request && request.mode !== 'navigate') {
  4396. return false;
  4397. }
  4398. const pathnameAndSearch = url.pathname + url.search;
  4399. for (const regExp of this._denylist) {
  4400. if (regExp.test(pathnameAndSearch)) {
  4401. {
  4402. logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL matches this denylist pattern: ` + `${regExp.toString()}`);
  4403. }
  4404. return false;
  4405. }
  4406. }
  4407. if (this._allowlist.some(regExp => regExp.test(pathnameAndSearch))) {
  4408. {
  4409. logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`);
  4410. }
  4411. return true;
  4412. }
  4413. {
  4414. logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL being navigated to doesn't ` + `match the allowlist.`);
  4415. }
  4416. return false;
  4417. }
  4418. }
  4419. /*
  4420. Copyright 2019 Google LLC
  4421. Use of this source code is governed by an MIT-style
  4422. license that can be found in the LICENSE file or at
  4423. https://opensource.org/licenses/MIT.
  4424. */
  4425. /**
  4426. * Helper function that calls
  4427. * {@link PrecacheController#createHandlerBoundToURL} on the default
  4428. * {@link PrecacheController} instance.
  4429. *
  4430. * If you are creating your own {@link PrecacheController}, then call the
  4431. * {@link PrecacheController#createHandlerBoundToURL} on that instance,
  4432. * instead of using this function.
  4433. *
  4434. * @param {string} url The precached URL which will be used to lookup the
  4435. * `Response`.
  4436. * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the
  4437. * response from the network if there's a precache miss.
  4438. * @return {workbox-routing~handlerCallback}
  4439. *
  4440. * @memberof workbox-precaching
  4441. */
  4442. function createHandlerBoundToURL(url) {
  4443. const precacheController = getOrCreatePrecacheController();
  4444. return precacheController.createHandlerBoundToURL(url);
  4445. }
  4446. exports.CacheableResponsePlugin = CacheableResponsePlugin;
  4447. exports.ExpirationPlugin = ExpirationPlugin;
  4448. exports.NavigationRoute = NavigationRoute;
  4449. exports.NetworkOnly = NetworkOnly;
  4450. exports.cleanupOutdatedCaches = cleanupOutdatedCaches;
  4451. exports.clientsClaim = clientsClaim;
  4452. exports.createHandlerBoundToURL = createHandlerBoundToURL;
  4453. exports.precacheAndRoute = precacheAndRoute;
  4454. exports.registerRoute = registerRoute;
  4455. }));