-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
337 lines (316 loc) · 11.9 KB
/
sw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// noinspection JSIgnoredPromiseFromCall
(() => {
/** 缓存库名称 */
const CACHE_NAME = 'kmarBlogCache'
/** 控制信息存储地址(必须以`/`结尾) */
const CTRL_PATH = 'https://id.v3/'
/** 控制信息读写操作 */
const dbVersion = {
write: (id) => caches.open(CACHE_NAME)
.then(cache => cache.put(CTRL_PATH, new Response(JSON.stringify(id)))),
read: () => caches.match(CTRL_PATH).then(response => response?.json())
}
self.addEventListener('install', () => {
self.skipWaiting()
const escape = 0
if (escape) {
dbVersion.read().then(oldVersion => {
if (oldVersion && oldVersion.escape !== escape) {
oldVersion.escape = escape
dbVersion.write(oldVersion)
// noinspection JSUnresolvedVariable
caches.delete(CACHE_NAME)
.then(() => clients.matchAll())
.then(list => list.forEach(client => client.postMessage({type: 'escape'})))
}
})
}
})
// sw 激活后立即对所有页面生效,而非等待刷新
// noinspection JSUnresolvedReference
self.addEventListener('activate', event => event.waitUntil(clients.claim()))
// noinspection JSFileReferences
let getSpareUrls = srcUrl => {
if (srcUrl.startsWith('https://cdn.jsdelivr.net/npm')) {
return {
timeout: 3000,
list: [
srcUrl,
`https://npm.elemecdn.com${new URL(srcUrl).pathname}`
]
}
}
}
let cacheRules = {
simple: {
clean: true,
search: false,
match: url => url.host === 'lumit.top' && url.pathname.match(/\.(woff2|woff|ttf|cur)$/)}
}
let getRaceUrls = srcUrl => {
if (srcUrl.startsWith('https://npm.elemecdn.com')) {
const url = new URL(srcUrl)
return [
srcUrl,
`https://cdn.jsdelivr.net/npm` + url.pathname,
`https://cdn1.tianli0.top/npm` + url.pathname,
`https://fastly.jsdelivr.net/npm` + url.pathname
]
}
}
const fetchFile = (request, banCache) => {
const fetchArgs = {
cache: banCache ? 'no-store' : 'default',
mode: 'cors',
credentials: 'same-origin'
}
const list = getRaceUrls(request.url)
if (!list || !Promise.any) return fetch(request, fetchArgs)
const res = list.map(url => new Request(url, request))
const controllers = []
// noinspection JSCheckFunctionSignatures
return Promise.any(res.map(
(it, index) => fetch(it, Object.assign(
{signal: (controllers[index] = new AbortController()).signal},
fetchArgs
)).then(response => checkResponse(response) ? {index, response} : Promise.reject())
)).then(it => {
for (let i in controllers) {
if (i !== it.index) controllers[i].abort()
}
return it.response
})
}
// 检查请求是否成功
// noinspection JSUnusedLocalSymbols
const checkResponse = response => response.ok || [301, 302, 307, 308].includes(response.status)
/**
* 删除指定缓存
* @param list 要删除的缓存列表
* @return {Promise<string[]>} 删除的缓存的URL列表
*/
const deleteCache = list => caches.open(CACHE_NAME).then(cache => cache.keys()
.then(keys => Promise.all(
keys.map(async it => {
const url = it.url
if (url !== CTRL_PATH && list.match(url)) {
// [debug delete]
// noinspection ES6MissingAwait,JSCheckFunctionSignatures
cache.delete(it)
return url
}
return null
})
)).then(list => list.filter(it => it))
)
/**
* 缓存列表
* @type {Map<string, {s, e}[]>}
*/
const cacheMap = new Map()
self.addEventListener('fetch', event => {
let request = event.request
let url = new URL(request.url)
// [blockRequest call]
if (request.method !== 'GET' || !request.url.startsWith('http')) return
// [modifyRequest call]
let cacheKey = url.hostname + url.pathname + url.search
let cache = cacheMap.get(cacheKey)
if (cache) {
return event.respondWith(
new Promise((resolve, reject) => {
cacheMap.get(cacheKey).push({s: resolve, e: reject})
})
)
}
cacheMap.set(cacheKey, cache = [])
/** 处理拉取 */
const handleFetch = promise =>
event.respondWith(promise.then(response => {
for (let item of cache) {
item.s(response.clone())
}
}).catch(err => {
for (let item of cache) {
item.e(err)
}
}).then(() => {
cacheMap.delete(cacheKey)
return promise
}))
const cacheRule = findCache(url)
if (cacheRule) {
let key = `https://${url.host}${url.pathname}`
if (key.endsWith('/index.html')) key = key.substring(0, key.length - 10)
if (cacheRule.search) key += url.search
handleFetch(
caches.match(key).then(
cache => cache ?? fetchFile(request, true)
.then(response => {
if (checkResponse(response)) {
const clone = response.clone()
caches.open(CACHE_NAME).then(it => it.put(key, clone))
// [debug put]
}
return response
})
)
)
} else {
const spare = getSpareUrls(request.url)
if (spare) handleFetch(fetchFile(request, false, spare))
// [modifyRequest else-if]
else handleFetch(fetch(request))
}
})
self.addEventListener('message', event => {
// [debug message]
if (event.data === 'update')
updateJson().then(info =>
// noinspection JSUnresolvedVariable
event.source.postMessage({
type: 'update',
update: info.list,
version: info.version,
})
)
})
/**
* 判断指定 url 击中了哪一种缓存,都没有击中则返回 null
* @param url {URL}
*/
const findCache = url => {
if (url.hostname === 'localhost') return
for (let key in cacheRules) {
const value = cacheRules[key]
if (value.match(url)) return value
}
}
/**
* 根据JSON删除缓存
* @returns {Promise<{version, list}>}
*/
const updateJson = () => {
/**
* 解析elements,并把结果输出到list中
* @return boolean 是否刷新全站缓存
*/
const parseChange = (list, elements, ver) => {
for (let element of elements) {
const {version, change} = element
if (version === ver) return false
if (change) {
for (let it of change)
list.push(new CacheChangeExpression(it))
}
}
// 跨版本幅度过大,直接清理全站
return true
}
/** 解析字符串 */
const parseJson = json => dbVersion.read().then(oldVersion => {
const {info, global} = json
const newVersion = {global, local: info[0].version, escape: oldVersion?.escape ?? 0}
//新用户不进行更新操作
if (!oldVersion) {
dbVersion.write(newVersion)
return newVersion
}
let list = new VersionList()
let refresh = parseChange(list, info, oldVersion.local)
dbVersion.write(newVersion)
// [debug escape]
//如果需要清理全站
if (refresh) {
if (global !== oldVersion.global) list.force = true
else list.refresh = true
}
return {list, version: newVersion}
})
return fetchFile(new Request('/update.json'), false)
.then(response => {
if (checkResponse(response))
return response.json().then(json =>
parseJson(json).then(result => {
return result.list ? deleteCache(result.list)
.then(list => list.length === 0 ? null : list)
.then(list => ({list, version: result.version}))
: {version: result}
}
)
)
else throw `加载 update.json 时遇到异常,状态码:${response.status}`
})
}
/**
* 版本列表
* @constructor
*/
function VersionList() {
const list = []
/**
* 推送一个表达式
* @param element {CacheChangeExpression} 要推送的表达式
*/
this.push = element => {
list.push(element)
}
/**
* 判断指定 URL 是否和某一条规则匹配
* @param url {string} URL
* @return {boolean}
*/
this.match = url => {
if (this.force) return true
// noinspection JSValidateTypes
url = new URL(url)
if (this.refresh) return findCache(url).clean
else {
for (let it of list) {
if (it.match(url)) return true
}
}
return false
}
}
// noinspection SpellCheckingInspection
/**
* 缓存更新匹配规则表达式
* @param json 格式{"flag": ..., "value": ...}
* @see https://kmar.top/posts/bcfe8408/#23bb4130
* @constructor
*/
function CacheChangeExpression(json) {
/**
* 遍历所有value
* @param action {function(string): boolean} 接受value并返回bool的函数
* @return {boolean} 如果value只有一个则返回`action(value)`,否则返回所有运算的或运算(带短路)
*/
const forEachValues = action => {
const value = json.value
if (Array.isArray(value)) {
for (let it of value) {
if (action(it)) return true
}
return false
} else return action(value)
}
const getMatch = () => {
switch (json['flag']) {
case 'html':
return url => url.pathname.match(/(\/|\.html)$/)
case 'end':
return url => forEachValues(value => url.href.endsWith(value))
case 'begin':
return url => forEachValues(value => url.pathname.startsWith(value))
case 'str':
return url => forEachValues(value => url.href.includes(value))
case 'reg':
// noinspection JSCheckFunctionSignatures
return url => forEachValues(value => url.href.match(new RegExp(value, 'i')))
default: throw `未知表达式:${JSON.stringify(json)}`
}
}
this.match = getMatch()
}
})()