|
| 1 | +import type { PrecacheEntry, SerwistGlobalConfig } from "serwist"; |
| 2 | +import { |
| 3 | + Serwist, |
| 4 | + NetworkFirst, |
| 5 | + CacheableResponsePlugin, |
| 6 | + ExpirationPlugin, |
| 7 | + StaleWhileRevalidate, |
| 8 | + CacheFirst, |
| 9 | +} from "serwist"; |
| 10 | +import { cleanupOutdatedCaches } from "serwist/internal"; |
| 11 | + |
| 12 | +declare global { |
| 13 | + interface WorkerGlobalScope extends SerwistGlobalConfig { |
| 14 | + __SW_MANIFEST: (PrecacheEntry | string)[] | undefined; |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +declare const self: WorkerGlobalScope; |
| 19 | + |
| 20 | +const pageStrategy = new NetworkFirst({ |
| 21 | + cacheName: "pages", |
| 22 | + matchOptions: { ignoreVary: true }, |
| 23 | + networkTimeoutSeconds: 5, |
| 24 | + plugins: [ |
| 25 | + new CacheableResponsePlugin({ statuses: [200] }), |
| 26 | + new ExpirationPlugin({ |
| 27 | + maxEntries: 128, |
| 28 | + maxAgeSeconds: 30 * 24 * 60 * 60, |
| 29 | + }), |
| 30 | + ], |
| 31 | +}); |
| 32 | + |
| 33 | +cleanupOutdatedCaches(); |
| 34 | + |
| 35 | +const serwist = new Serwist({ |
| 36 | + precacheEntries: self.__SW_MANIFEST, |
| 37 | + skipWaiting: true, |
| 38 | + clientsClaim: true, |
| 39 | + navigationPreload: false, |
| 40 | + runtimeCaching: [ |
| 41 | + { |
| 42 | + matcher: ({ request }) => request.mode === "navigate", |
| 43 | + handler: pageStrategy, |
| 44 | + }, |
| 45 | + { |
| 46 | + matcher: ({ request, sameOrigin }) => |
| 47 | + request.headers.get("RSC") === "1" && sameOrigin, |
| 48 | + handler: pageStrategy, |
| 49 | + }, |
| 50 | + { |
| 51 | + matcher: /\/_next\/static.+\.js$/i, |
| 52 | + handler: new CacheFirst({ |
| 53 | + cacheName: "static-js", |
| 54 | + plugins: [ |
| 55 | + new ExpirationPlugin({ |
| 56 | + maxEntries: 64, |
| 57 | + maxAgeSeconds: 30 * 24 * 60 * 60, |
| 58 | + }), |
| 59 | + ], |
| 60 | + }), |
| 61 | + }, |
| 62 | + { |
| 63 | + matcher: /\.(?:css|woff|woff2|ttf|eot|otf)$/i, |
| 64 | + handler: new StaleWhileRevalidate({ |
| 65 | + cacheName: "static-assets", |
| 66 | + plugins: [ |
| 67 | + new ExpirationPlugin({ |
| 68 | + maxEntries: 64, |
| 69 | + maxAgeSeconds: 30 * 24 * 60 * 60, |
| 70 | + }), |
| 71 | + ], |
| 72 | + }), |
| 73 | + }, |
| 74 | + { |
| 75 | + matcher: /\.(?:jpg|jpeg|gif|png|svg|ico|webp)$/i, |
| 76 | + handler: new StaleWhileRevalidate({ |
| 77 | + cacheName: "images", |
| 78 | + plugins: [ |
| 79 | + new ExpirationPlugin({ |
| 80 | + maxEntries: 128, |
| 81 | + maxAgeSeconds: 30 * 24 * 60 * 60, |
| 82 | + }), |
| 83 | + ], |
| 84 | + }), |
| 85 | + }, |
| 86 | + ], |
| 87 | +}); |
| 88 | + |
| 89 | +serwist.addEventListeners(); |
0 commit comments