workbox-f2cb1a81.js 182 KB

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