PageSourceSearch

https://shanlunjiajian.github.io/sw.js

js shanlunjiajian.github.io collected 2026-10-03 09:56:20 UTC 9,650 bytes, 262 lines download raw bytes

1/* ===========================================================
2 * sw.js
3 * ===========================================================
4 * Copyright 2016 @huxpro
5 * Licensed under Apache 2.0
6 * service worker scripting
7 * ========================================================== */
8
9// CACHE_NAMESPACE
10// CacheStorage is shared between all sites under same domain.
11// A namespace can prevent potential name conflicts and mis-deletion.
12const CACHE_NAMESPACE = 'main-'
13
14const CACHE = CACHE_NAMESPACE + 'precache-then-runtime';
15const PRECACHE_LIST = [
16  "./",
17  "./offline.html",
18  "./js/jquery.min.js",
19  "./js/bootstrap.min.js",
20  "./js/hux-blog.min.js",
21  "./js/snackbar.js",
22  "./css/hux-blog.min.css",
23  "./css/bootstrap.min.css"
24  // "//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css",
25  // "//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/fonts/fontawesome-webfont.woff2?v=4.6.3",
26  // "//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js"
27]
28const HOSTNAME_WHITELIST = [
29  self.location.hostname,
30  "cdnjs.cloudflare.com"
31]
32const DEPRECATED_CACHES = ['precache-v1', 'runtime', 'main-precache-v1', 'main-runtime']
33
34
35// The Util Function to hack URLs of intercepted requests
36const getCacheBustingUrl = (req) => {
37  var now = Date.now();
38  url = new URL(req.url)
39
40  // 1. fixed http URL
41  // Just keep syncing with location.protocol
42  // fetch(httpURL) belongs to active mixed content.
43  // And fetch(httpRequest) is not supported yet.
44  url.protocol = self.location.protocol
45
46  // 2. add query for caching-busting.
47  // Github Pages served with Cache-Control: max-age=600
48  // max-age on mutable content is error-prone, with SW life of bugs can even extend.
49  // Until cache mode of Fetch API landed, we have to workaround cache-busting with query string.
50  // Cache-Control-Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=453190
51  url.search += (url.search ? '&' : '?') + 'cache-bust=' + now;
52  return url.href
53}
54
55// The Util Function to detect and polyfill req.mode="navigate"
56// request.mode of 'navigate' is unfortunately not supported in Chrome
57// versions older than 49, so we need to include a less precise fallback,
58// which checks for a GET request with an Accept: text/html header.
59const isNavigationReq = (req) => (req.mode === 'navigate' || (req.method === 'GET' && req.headers.get('accept').includes('text/html')))
60
61// The Util Function to detect if a req is end with extension
62// Accordin to Fetch API spec <https://fetch.spec.whatwg.org/#concept-request-destination>
63// Any HTML's navigation has consistently mode="navigate" type="" and destination="document"
64// including requesting an img (or any static resources) from URL Bar directly.
65// So It ends up with that regExp is still the king of URL routing ;)
66// P.S. An url.pathname has no '.' can not indicate it ends with extension (e.g. /api/version/1.2/)
67const endWithExtension = (req) => Boolean(new URL(req.url).pathname.match(/\.\w+$/))
68
69// Redirect in SW manually fixed github pages arbitray 404s on things?blah
70// what we want:
71//    repo?blah -> !(gh 404) -> sw 302 -> repo/?blah
72//    .ext?blah -> !(sw 302 -> .ext/?blah -> gh 404) -> .ext?blah
73// If It's a navigation req and it's url.pathname isn't end with '/' or '.ext'
74// it should be a dir/repo request and need to be fixed (a.k.a be redirected)
75// Tracking https://twitter.com/Huxpro/status/798816417097224193
76const shouldRedirect = (req) => (isNavigationReq(req) && new URL(req.url).pathname.substr(-1) !== "/" && !endWithExtension(req))
77
78// The Util Function to get redirect URL
79// `${url}/` would mis-add "/" in the end of query, so we use URL object.
80// P.P.S. Always trust url.pathname instead of the whole url string.
81const getRedirectUrl = (req) => {
82  url = new URL(req.url)
83  url.pathname += "/"
84  return url.href
85}
86
87
88/**
89 *  @Lifecycle Install
90 *  Precache anything static to this version of your app.
91 *  e.g. App Shell, 404, JS/CSS dependencies...
92 *
93 *  waitUntil() : installing ====> installed
94 *  skipWaiting() : waiting(installed) ====> activating
95 */
96self.addEventListener('install', e => {
97  e.waitUntil(
98    caches.open(CACHE).then(cache => {
99      return cache.addAll(PRECACHE_LIST)
100        .then(self.skipWaiting())
101        .catch(err => console.log(err))
102    })
103  )
104});
105
106
107/**
108 *  @Lifecycle Activate
109 *  New one activated when old isnt being used.
110 *
111 *  waitUntil(): activating ====> activated
112 */
113self.addEventListener('activate', event => {
114  // delete old deprecated caches.
115  caches.keys().then(cacheNames => Promise.all(
116    cacheNames
117      .filter(cacheName => DEPRECATED_CACHES.includes(cacheName))
118      .map(cacheName => caches.delete(cacheName))
119  ))
120  console.log('service worker activated.')
121  event.waitUntil(self.clients.claim());
122});
123
124
125var fetchHelper = {
126
127  fetchThenCache: function(request){
128    // Requests with mode "no-cors" can result in Opaque Response,
129    // Requests to Allow-Control-Cross-Origin: * can't include credentials.
130    const init = { mode: "cors", credentials: "omit" } 
131
132    const fetched = fetch(request, init)
133    const fetchedCopy = fetched.then(resp => resp.clone());
134
135    // NOTE: Opaque Responses have no hedaders so [[ok]] make no sense to them
136    //       so Opaque Resp will not be cached in this case.
137    Promise.all([fetchedCopy, caches.open(CACHE)])
138      .then(([response, cache]) => response.ok && cache.put(request, response))
139      .catch(_ => {/* eat any errors */})
140    
141    return fetched;
142  },
143
144  cacheFirst: function(url){
145    return caches.match(url) 
146      .then(resp => resp || this.fetchThenCache(url))
147      .catch(_ => {/* eat any errors */})
148  }
149}
150
151
152/**
153 *  @Functional Fetch
154 *  All network requests are being intercepted here.
155 *
156 *  void respondWith(Promise<Response> r);
157 */
158self.addEventListener('fetch', event => {
159  // logs for debugging
160  //console.log(`fetch ${event.request.url}`)
161  //console.log(` - type: ${event.request.type}; destination: ${event.request.destination}`)
162  //console.log(` - mode: ${event.request.mode}, accept: ${event.request.headers.get('accept')}`)
163
164  // Skip some of cross-origin requests, like those for Google Analytics.
165  if (HOSTNAME_WHITELIST.indexOf(new URL(event.request.url).hostname) > -1) {
166
167    // Redirect in SW manually fixed github pages 404s on repo?blah
168    if (shouldRedirect(event.request)) {
169      event.respondWith(Response.redirect(getRedirectUrl(event.request)))
170      return;
171    }
172
173    // Cache-only Startgies for ys.static resources
174    if (event.request.url.indexOf('ys.static') > -1){
175      event.respondWith(fetchHelper.cacheFirst(event.request.url))
176      return;
177    }
178
179    // Stale-while-revalidate for possiblily dynamic content
180    // similar to HTTP's stale-while-revalidate: https://www.mnot.net/blog/2007/12/12/stale
181    // Upgrade from Jake's to Surma's: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1
182    const cached = caches.match(event.request);
183    const fetched = fetch(getCacheBustingUrl(event.request), { cache: "no-store" });
184    const fetchedCopy = fetched.then(resp => resp.clone());
185    
186    // Call respondWith() with whatever we get first.
187    // Promise.race() resolves with first one settled (even rejected)
188    // If the fetch fails (e.g disconnected), wait for the cache.
189    // If there’s nothing in cache, wait for the fetch.
190    // If neither yields a response, return offline pages.
191    event.respondWith(
192      Promise.race([fetched.catch(_ => cached), cached])
193        .then(resp => resp || fetched)
194        .catch(_ => caches.match('offline.html'))
195    );
196
197    // Update the cache with the version we fetched (only for ok status)
198    event.waitUntil(
199      Promise.all([fetchedCopy, caches.open(CACHE)])
200        .then(([response, cache]) => response.ok && cache.put(event.request, response))
201        .catch(_ => {/* eat any errors */ })
202    );
203
204    // If one request is a HTML naviagtion, checking update!
205    if (isNavigationReq(event.request)) {
206      // you need "preserve logs" to see this log
207      // cuz it happened before navigating
208      console.log(`fetch ${event.request.url}`)
209      event.waitUntil(revalidateContent(cached, fetchedCopy))
210    }
211  }
212});
213
214
215/**
216 * Broadcasting all clients with MessageChannel API
217 */
218function sendMessageToAllClients(msg) {
219  self.clients.matchAll().then(clients => {
220    clients.forEach(client => {
221      console.log(client);
222      client.postMessage(msg)
223    })
224  })
225}
226
227/**
228 * Broadcasting all clients async
229 */
230function sendMessageToClientsAsync(msg) {
231  // waiting for new client alive with "async" setTimeout hacking
232  // https://twitter.com/Huxpro/status/799265578443751424
233  // https://jakearchibald.com/2016/service-worker-meeting-notes/#fetch-event-clients
234  setTimeout(() => {
235    sendMessageToAllClients(msg)
236  }, 1000)
237}
238
239/**
240 * if content modified, we can notify clients to refresh
241 * TODO: Gh-pages rebuild everything in each release. should find a workaround (e.g. ETag with cloudflare)
242 * 
243 * @param  {Promise<response>} cachedResp  [description]
244 * @param  {Promise<response>} fetchedResp [description]
245 * @return {Promise}
246 */
247function revalidateContent(cachedResp, fetchedResp) {
248  // revalidate when both promise resolved
249  return Promise.all([cachedResp, fetchedResp])
250    .then(([cached, fetched]) => {
251      const cachedVer = cached.headers.get('last-modified')
252      const fetchedVer = fetched.headers.get('last-modified')
253      console.log(`"${cachedVer}" vs. "${fetchedVer}"`);
254      if (cachedVer !== fetchedVer) {
255        sendMessageToClientsAsync({
256          'command': 'UPDATE_FOUND',
257          'url': fetched.url
258        })
259      }
260    })
261    .catch(err => console.log(err))
262}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.