hexo-swpp 2.3.0-beta.0 → 2.3.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -10,9 +10,9 @@ if (pluginConfig?.enable) {
10
10
  const rules = require(nodePath.resolve('./', 'sw-rules'))
11
11
 
12
12
  // 排序
13
- require('/lib/sort')(pluginConfig)
13
+ require('./lib/sort.js')(pluginConfig)
14
14
  // 生成 update.json
15
- require('/lib/json')(config, pluginConfig, rules)
15
+ require('./lib/jsonBuilder.js')(hexo, config, pluginConfig, rules)
16
16
  // 生成 sw.js
17
- require('/lib/sw')(config, pluginConfig, rules)
17
+ require('./lib/swBuilder.js')(hexo, config, pluginConfig, rules)
18
18
  }
File without changes
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hexo-swpp",
3
- "version": "2.3.0-beta.0",
3
+ "version": "2.3.0-beta.1",
4
4
  "main": "index.js",
5
5
  "dependencies": {
6
6
  "hexo-log": "^3.0.0",
@@ -10,8 +10,8 @@
10
10
  },
11
11
  "files": [
12
12
  "index.js",
13
- "sw-template.js",
14
- "sw-dom.js",
13
+ "lib/sw-template.js",
14
+ "lib/sw-dom.js",
15
15
  "lib/sw.js",
16
16
  "lib/json.js",
17
17
  "lib/sort.js"
package/lib/json.js DELETED
@@ -1,484 +0,0 @@
1
- module.exports = (config, pluginConfig, swRules) => {
2
- const logger = require('hexo-log')()
3
- const fs = require('fs')
4
- const fetch = require('node-fetch')
5
- const nodePath = require('path')
6
- const crypto = require("crypto")
7
- const cheerio = require('cheerio')
8
- const postcss = require('postcss')
9
- const {
10
- cacheList,
11
- modifyRequest
12
- } = swRules
13
- const root = config.url + (config.root ?? '/')
14
- const domain = new URL(root).hostname
15
-
16
- hexo.extend.console.register('swpp', '生成前端更新需要的 json 文件以及相关缓存', {}, async () => {
17
- if (!fs.existsSync(config.public_dir))
18
- return logger.info('未检测到发布目录,跳过 swpp 执行')
19
- const cachePath = 'cacheList.json'
20
- const updatePath = 'update.json'
21
- const oldCache = await getJsonFromNetwork(cachePath)
22
- const oldUpdate = await getJsonFromNetwork(updatePath)
23
- const newCache = await buildNewJson(cachePath)
24
- const dif = compare(oldCache, newCache)
25
- buildUpdateJson(updatePath, dif, oldUpdate)
26
- })
27
-
28
-
29
- /** 遍历指定目录下的所有文件 */
30
- const eachAllFile = (root, cb) => {
31
- const stats = fs.statSync(root)
32
- if (stats.isFile()) cb(root)
33
- else {
34
- const files = fs.readdirSync(root)
35
- files.forEach(it => eachAllFile(nodePath.join(root, it), cb))
36
- }
37
- }
38
-
39
- /** 判断指定文件是否需要排除 */
40
- const isExclude = pathname => {
41
- for (let reg of pluginConfig.json.exclude) {
42
- if (pathname.match(new RegExp(reg, 'i'))) return true
43
- }
44
- return false
45
- }
46
-
47
- const isSkipFetch = url => {
48
- const skipList = pluginConfig.external?.skip
49
- if (!skipList) return false
50
- for (let reg of skipList) {
51
- if (url.match(new RegExp(reg))) return true
52
- }
53
- return false
54
- }
55
-
56
- /**
57
- * 构建 md5 缓存表并写入到发布目录中
58
- *
59
- * 格式为 `{"[path]": "[md5Value]"}`
60
- *
61
- * @param path 相对于根目录的路径
62
- * @return {Promise<Object>} 生成的 json 对象
63
- */
64
- const buildNewJson = path => new Promise(resolve => {
65
- const result = {} // 存储新的 MD5 表
66
- const removeIndex = config.pretty_urls?.trailing_index
67
- const removeHtml = config.pretty_urls?.trailing_html
68
- const taskList = [] // 拉取任务列表
69
- const cache = new Set() // 已经计算过的文件
70
- eachAllFile(config.public_dir, path => {
71
- if (!fs.existsSync(path)) return logger.error(`${path} 不存在!`)
72
- let endIndex
73
- if (removeIndex && path.endsWith('/index.html')) endIndex = path.length - 10
74
- else if (removeHtml && path.endsWith('.html')) endIndex = path.length - 5
75
- else endIndex = path.length
76
- const url = new URL(nodePath.join(root, path.substring(7, endIndex)))
77
- if (isExclude(url.href)) return
78
- let content = null
79
- if (findCache(url)) {
80
- content = fs.readFileSync(path, 'utf-8')
81
- const key = decodeURIComponent(url.pathname)
82
- result[key] = crypto.createHash('md5').update(content).digest('hex')
83
- }
84
- // 外链监控
85
- const external = pluginConfig.external
86
- if (!pluginConfig.external?.enable) return
87
- const indexOf = (str, ...chars) => {
88
- let result = str.length
89
- chars.forEach(it => {
90
- const index = str.indexOf(it)
91
- result = Math.min(result, index < 0 ? result : index)
92
- })
93
- return result
94
- }
95
- const lastIndexOf = (str, ...chars) => {
96
- let result = -1
97
- chars.forEach(it => result = Math.max(result, str.lastIndexOf(it)))
98
- return result
99
- }
100
- // 处理指定链接
101
- const handleLink = link => {
102
- // 跳过本地文件的计算
103
- if (!link.match(/^(http|\/\/)/) || cache.has(link)) return
104
- cache.add(link)
105
- const url = new URL(link.startsWith('/') ? `http:${link}` : link)
106
- if (url.hostname === domain || !findCache(url) || isExclude(url.href)) return
107
- if (isSkipFetch(url.href)) result[decodeURIComponent(link)] = '0'
108
- else taskList.push(
109
- fetchFile(link)
110
- .then(response => response.text())
111
- .then(text => {
112
- const key = decodeURIComponent(link)
113
- result[key] = crypto.createHash('md5').update(text).digest('hex')
114
- if (key.endsWith('.js')) handleJsContent(text)
115
- else if (key.endsWith('.css')) handleCssContent(text)
116
- }).catch(err => logger.error(`拉取 ${err.url} 时出现 ${err.status ?? '未知'} 异常:${err}`))
117
- )
118
- }
119
- // 处理指定 JS
120
- const handleJsContent = text => {
121
- if (!external.js) return
122
- if (cache.has(text)) return
123
- cache.add(text)
124
- external.js.forEach(it => {
125
- const reg = new RegExp(`${it.head}(['"\`])(.*?)\\1${it.tail}`, 'mg')
126
- text.match(reg)?.forEach(content => {
127
- try {
128
- const start = indexOf(content, "'", '"', '`') + 1
129
- const end = lastIndexOf(content, "'", '"', '`')
130
- const link = content.substring(start, end)
131
- if (!link.match(/['"$`]/)) handleLink(link)
132
- } catch (e) {
133
- logger.error(`SwppJsHandler: 处理 ${content} 时出现异常`)
134
- logger.error(e)
135
- }
136
- })
137
- })
138
- }
139
- // 处理 CSS 内容
140
- const handleCssContent = text => {
141
- if (cache.has(text)) return
142
- cache.add(text)
143
- postcss.parse(text).walkDecls(decl => {
144
- if (decl.value.includes('url')) {
145
- decl.value.match(/url\(([^)]+)\)/g)
146
- .map(it => it.match(/^(url\(['"])/) ? it.substring(5, it.length - 2) : it.substring(4, it.length - 1))
147
- .forEach(link => handleLink(link))
148
- }
149
- })
150
- }
151
- // 如果是 html 则获取所有 script 和 link 标签拉取的文件
152
- if (path.endsWith('/') || path.endsWith('.html')) {
153
- if (!content) content = fs.readFileSync(path, 'utf-8')
154
- const html = cheerio.load(content)
155
- html('script[src]')
156
- .map((i, ele) => html(ele).attr('src'))
157
- .each((i, it) => handleLink(it))
158
- html('link[href]')
159
- .map((i, ele) => html(ele).attr('href'))
160
- .each((i, it) => handleLink(it))
161
- html('script:not([src])')
162
- .map((i, ele) => html(ele).text())
163
- .each((i, text) => handleJsContent(text))
164
- html('style')
165
- .map((i, ele) => html(ele).text())
166
- .each((i, text) => handleCssContent(text))
167
- } else if (path.endsWith('.js')) {
168
- if (!content) content = fs.readFileSync(path, 'utf-8')
169
- handleJsContent(content)
170
- } else if (path.endsWith('.css')) {
171
- if (!content) content = fs.readFileSync(path, 'utf-8')
172
- handleCssContent(content)
173
- }
174
- })
175
- Promise.all(taskList).then(() => {
176
- const publicRoot = config.public_dir
177
- fs.writeFileSync(nodePath.join(publicRoot, path), JSON.stringify(result), 'utf-8')
178
- logger.info(`Generated: ${path}`)
179
- resolve(result)
180
- })
181
- })
182
-
183
- /**
184
- * 从网络拉取一个文件
185
- * @param link 文件链接
186
- * @returns {Promise<*>} response
187
- */
188
- const fetchFile = link => new Promise((resolve, reject) => {
189
- link = replaceDevRequest(link)
190
- // noinspection SpellCheckingInspection
191
- fetch(link, {
192
- headers: {
193
- referer: new URL(link).hostname,
194
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.62'
195
- },
196
- timeout: pluginConfig.external.timeout ?? 1500
197
- }).then(response => {
198
- switch (response.status) {
199
- case 200: case 301: case 302:
200
- resolve(response)
201
- break
202
- default:
203
- reject(response)
204
- break
205
- }
206
- }).catch(err => {
207
- err.url = link
208
- reject(err)
209
- })
210
- })
211
-
212
- /**
213
- * 从网络拉取 json 文件
214
- * @param path 文件路径(相对于根目录)
215
- */
216
- const getJsonFromNetwork = path => new Promise(resolve => {
217
- const url = nodePath.join(root, path)
218
- fetchFile(url)
219
- .then(response => resolve(response.json()))
220
- .catch(err => {
221
- if (err.status === 404) {
222
- logger.error(`拉取 ${err.url} 时出现 404,如果您是第一次构建请忽略这个错误`)
223
- resolve()
224
- } else throw err
225
- })
226
- })
227
-
228
- /**
229
- * 对比两个 md5 缓存表的区别
230
- * @return [string] 需要更新的文件路径
231
- */
232
- const compare = (oldCache, newCache) => {
233
- const result = []
234
- if (!oldCache) return result
235
- for (let path in oldCache) {
236
- if (newCache[path] !== oldCache[path]) result.push(path)
237
- }
238
- return result
239
- }
240
-
241
- /** 判断指定资源是否需要合并 */
242
- const isMerge = (pathname, tidied) => {
243
- const optional = pluginConfig.json.merge
244
- if (!optional) return false
245
- if (pathname.includes(`/${config.tag_dir}/`)) {
246
- if (optional.tags ?? true)
247
- return tidied.tags = true
248
- } else if (pathname.includes(`/${config.archive_dir}/`)) {
249
- if (optional.archives ?? true)
250
- return tidied.archives = true
251
- } else if (pathname.includes(`/${config.category_dir}/`)) {
252
- if (optional.categories ?? true)
253
- return tidied.categories = true
254
- } else if (pathname.startsWith('/page/') || pathname.length <= 1) {
255
- if (optional.index ?? true)
256
- return tidied.index = true
257
- } else {
258
- const list = optional.custom
259
- if (!list) return false
260
- for (let reg of list) {
261
- if (pathname.startsWith(`/${reg}/`))
262
- return tidied.custom[reg] = true
263
- }
264
- }
265
- }
266
-
267
- /**
268
- * 从一个字符串中提取最后两个 / 之间的内容
269
- * @param it {string} 要操作的字符串
270
- * @param keep {boolean} 是否保留最后一个 / 及其后面的内容
271
- */
272
- const clipPageName = (it, keep) => {
273
- const end = it.lastIndexOf('/')
274
- let index = end - 1
275
- for (; index > 0; --index) {
276
- if (it[index] === '/') break
277
- }
278
- return it.substring(index + 1, keep ? it.length : end)
279
- }
280
-
281
- /** 构建新的 update.json */
282
- const buildUpdateJson = (name, dif, oldUpdate) => {
283
- /** 将对象写入文件,如果对象为 null 或 undefined 则跳过写入 */
284
- const writeJson = json => {
285
- if (json) {
286
- logger.info(`Generated: ${name}`)
287
- fs.writeFileSync(`public/${name}`, JSON.stringify(json), 'utf-8')
288
- }
289
- }
290
- // 读取拓展 json
291
- const expand = fs.existsSync(name) ? JSON.parse(fs.readFileSync(name, 'utf-8')) : undefined
292
- // 获取上次最新的版本
293
- let oldVersion = oldUpdate?.info?.at(0)?.version ?? 0
294
- if (typeof oldVersion !== 'number') {
295
- // 当上次最新的版本号不是数字是尝试对其进行转换,如果无法转换则直接置零
296
- if (oldVersion.match('\D')) oldVersion = 0
297
- else oldVersion = Number.parseInt(oldVersion)
298
- }
299
- // 存储本次更新的内容
300
- const newInfo = {
301
- version: oldVersion + 1,
302
- change: expand?.change ?? []
303
- }
304
- // 整理更新的数据
305
- const tidied = tidyDiff(dif, expand)
306
- if (expand?.all) return writeJson({
307
- global: (oldUpdate?.global ?? 0) + (tidied.updateGlobal ? 1 : 0),
308
- info: [newInfo]
309
- })
310
- // 如果没有更新的文件就直接退出
311
- if (
312
- tidied.page.size === 0 && tidied.file.size === 0 &&
313
- !(tidied.archives || tidied.categories || tidied.tags || tidied.index)
314
- ) return writeJson(oldUpdate ?? {
315
- global: 0,
316
- info: [{version: 0}]
317
- })
318
- pushUpdateToInfo(newInfo, tidied)
319
- const result = mergeUpdateWithOld(newInfo, oldUpdate, tidied)
320
- return writeJson(result)
321
- }
322
-
323
- const mergeUpdateWithOld = (newInfo, oldUpdate, tidied) => {
324
- const result = {
325
- global: (oldUpdate?.global ?? 0) + (tidied.updateGlobal ? 1 : 0),
326
- info: [newInfo]
327
- }
328
- const charLimit = pluginConfig.json.charLimit ?? 1024
329
- if (JSON.stringify(result).length > charLimit) {
330
- return {
331
- global: result.global,
332
- info: [{version: newInfo.version}]
333
- }
334
- }
335
- if (!oldUpdate) return result
336
- for (let it of oldUpdate.info) {
337
- if (it.change) it.change = zipInfo(newInfo, it)
338
- result.info.push(it)
339
- if (JSON.stringify(result).length > charLimit) {
340
- result.info.pop()
341
- break
342
- }
343
- }
344
- return result
345
- }
346
-
347
- // 压缩相同项目
348
- const zipInfo = (newInfo, oldInfo) => {
349
- oldInfo = oldInfo.change
350
- newInfo = newInfo.change
351
- const result = []
352
- for (let i = oldInfo.length - 1; i !== -1; --i) {
353
- const value = oldInfo[i]
354
- if (value.flag === 'page' && newInfo.find(it => it.flag === 'html')) continue
355
- const newValue = newInfo.find(it => it.flag === value.flag)
356
- if (!newValue) {
357
- result.push(value)
358
- continue
359
- }
360
- if (!value.value) continue
361
- const isArray = Array.isArray(newValue.value)
362
- if (Array.isArray(value.value)) {
363
- const array = value.value
364
- .filter(it => isArray ? !newValue.value.find(that => that === it) : it !== newValue.value)
365
- if (array.length === 0) continue
366
- result.push({flag: value.flag, value: array.length === 1 ? array[0] : array})
367
- } else if (isArray) {
368
- if (!newValue.value.find(it => it === value.value))
369
- result.push(value)
370
- } else {
371
- if (newValue.value !== value.value)
372
- result.push(value)
373
- }
374
- }
375
- return result.length === 0 ? undefined : result
376
- }
377
-
378
- // 将更新推送到 info
379
- const pushUpdateToInfo = (info, tidied) => {
380
- const merges = [] // 要合并的更新
381
- // 推送页面更新
382
- if (tidied.page.size > (pluginConfig.json.maxHtml ?? 15)) {
383
- // 如果 html 数量超过阈值就直接清掉所有 html
384
- info.change.push({flag: 'html'})
385
- } else {
386
- const pages = [] // 独立更新
387
- tidied.page.forEach(it => pages.push(it))
388
- if (tidied.tags) merges.push(config.tag_dir)
389
- if (tidied.archives) merges.push(config.archive_dir)
390
- if (tidied.categories) merges.push(config.category_dir)
391
- if (tidied.index) {
392
- pages.push(clipPageName(root, false))
393
- merges.push('page')
394
- }
395
- if (pages.length > 0)
396
- info.change.push({flag: 'page', value: pages})
397
- }
398
- for (let key in tidied.custom) merges.push(key)
399
- if (merges.length > 0)
400
- info.change.push({flag: 'str', value: merges.map(it => `/${it}/`)})
401
- // 推送文件更新
402
- if (tidied.file.size > 0) {
403
- const list = []
404
- tidied.file.forEach(it => list.push(it))
405
- info.change.push({flag: 'file', value: list})
406
- }
407
- }
408
-
409
- // 将 diff 整理分类
410
- const tidyDiff = (dif, expand) => {
411
- const tidied = {
412
- /** 所有 HTML 页面 */
413
- page: new Set(),
414
- /** 所有文件 */
415
- file: new Set(),
416
- /** 标记 tags 是否更新 */
417
- tags: false,
418
- /** 标记 archives 是否更新 */
419
- archives: false,
420
- /** 标记 categories 是否更新 */
421
- categories: false,
422
- /** 标记 index 是否更新 */
423
- index: false,
424
- /** 自定义配置项 */
425
- custom: {},
426
- /** 标记是否更新 global 版本号 */
427
- updateGlobal: expand?.global
428
- }
429
- const mode = pluginConfig.json.precisionMode
430
- for (let it of dif) {
431
- const url = new URL(nodePath.join(root, it)) // 当前文件的 URL
432
- const cache = findCache(url) // 查询缓存
433
- if (!cache) {
434
- logger.error(`[buildUpdate] 指定 URL(${url.pathname}) 未查询到缓存规则!`)
435
- continue
436
- }
437
- if (!cache.clean) tidied.updateGlobal = true
438
- if (isMerge(url.pathname, tidied)) continue
439
- if (it.match(/(\/|\.html)$/)) { // 判断缓存是否是 html
440
- if (mode.html ?? false) tidied.page.add(url.pathname)
441
- else tidied.page.add(clipPageName(url.href, !it.endsWith('/')))
442
- } else {
443
- const extendedName = (it.includes('.') ? it.match(/[^.]+$/)[0] : null) ?? 'default'
444
- const setting = mode[extendedName] ?? (mode.default ?? false)
445
- if (setting) tidied.file.add(url.pathname)
446
- else {
447
- let name = url.href.match(/[^/]+$/)[0]
448
- if (!name) throw `${url.href} 格式错误`
449
- tidied.file.add(name)
450
- }
451
- }
452
- }
453
- return tidied
454
- }
455
-
456
- function findCache(url) {
457
- url = new URL(replaceRequest(url.href))
458
- for (let key in cacheList) {
459
- const value = cacheList[key]
460
- if (value.match(url)) return value
461
- }
462
- return null
463
- }
464
-
465
- function replaceRequest(url) {
466
- if (!modifyRequest) return url
467
- const request = new Request(url)
468
- const newRequest = modifyRequest(request)
469
- return newRequest?.url ?? url
470
- }
471
-
472
- function replaceDevRequest(url) {
473
- const external = pluginConfig.external
474
- if (!external?.enable || !external.replace) return url
475
- for (let value of external.replace) {
476
- for (let source of value.source) {
477
- if (url.match(source)) {
478
- url = url.replace(source, value.dist)
479
- }
480
- }
481
- }
482
- return url
483
- }
484
- }
package/lib/sw.js DELETED
@@ -1,153 +0,0 @@
1
- module.exports = (config, pluginConfig, rules) => {
2
- const {
3
- modifyRequest,
4
- fetchNoCache,
5
- getCdnList,
6
- getSpareUrls,
7
- blockRequest
8
- } = rules
9
- const nodePath = require('path')
10
- const fs = require('fs')
11
-
12
- const root = config.url + (config.root ?? '/')
13
-
14
- hexo.extend.generator.register('buildSw', () => {
15
- if (pluginConfig.sw.custom) return
16
- const absPath = module.path + '/sw-template.js'
17
- const rootPath = nodePath.resolve('./')
18
- const relativePath = nodePath.relative(rootPath, absPath)
19
- // 获取拓展文件
20
- let cache = fs.readFileSync('sw-rules.js', 'utf8')
21
- .replaceAll('module.exports.', 'const ')
22
- if (!fetchNoCache) {
23
- if (pluginConfig.sw.cdnRacing && getCdnList) {
24
- cache +=`
25
- const fetchFile = (request, banCache) => {
26
- const fetchArgs = {
27
- cache: banCache ? 'no-store' : 'default',
28
- mode: 'cors',
29
- credentials: 'same-origin'
30
- }
31
- const list = getCdnList(request.url)
32
- if (!list || !Promise.any) return fetch(request, fetchArgs)
33
- const res = list.map(url => new Request(url, request))
34
- const controllers = []
35
- return Promise.any(res.map(
36
- (it, index) => fetch(it, Object.assign(
37
- {signal: (controllers[index] = new AbortController()).signal},
38
- fetchArgs
39
- )).then(response => checkResponse(response) ? {index, response} : Promise.reject())
40
- )).then(it => {
41
- for (let i in controllers) {
42
- if (i != it.index) controllers[i].abort()
43
- }
44
- return it.response
45
- })
46
- }
47
- `
48
- } else if (pluginConfig.sw.spareUrl && getSpareUrls) {
49
- cache += `
50
- const fetchFile = (request, banCache, spare = null) => {
51
- const fetchArgs = {
52
- cache: banCache ? 'no-store' : 'default',
53
- mode: 'cors',
54
- credentials: 'same-origin'
55
- }
56
- if (!spare) spare = getSpareUrls(request.url)
57
- if (!spare) return fetch(request, fetchArgs)
58
- const list = spare.list
59
- const controllers = []
60
- let error = 0
61
- return new Promise((resolve, reject) => {
62
- const pull = () => {
63
- const flag = controllers.length
64
- if (flag === list.length) return
65
- const plusError = () => {
66
- if (++error === list.length) reject(\`请求 \${request.url} 失败\`)
67
- else if (flag + 1 === controllers.length) {
68
- clearTimeout(controllers[flag].id)
69
- pull()
70
- }
71
- }
72
- controllers.push({
73
- ctrl: new AbortController(),
74
- id: setTimeout(pull, spare.timeout)
75
- })
76
- fetch(new Request(list[flag], request), fetchArgs).then(response => {
77
- if (checkResponse(response)) {
78
- for (let i in controllers) {
79
- if (i !== flag) controllers[i].ctrl.abort()
80
- }
81
- clearTimeout(controllers[controllers.length - 1].id)
82
- resolve(response)
83
- } else plusError()
84
- }).catch(plusError)
85
- }
86
- pull()
87
- })
88
- }
89
- `
90
- } else cache += `
91
- const fetchFile = (request, banCache) => fetch(request, {
92
- cache: banCache ? "no-store" : "default",
93
- mode: 'cors',
94
- credentials: 'same-origin'
95
- })
96
- `
97
- }
98
- if (!getSpareUrls) cache += `\nconst getSpareUrls = _ => {}`
99
- let swContent = fs.readFileSync(relativePath, 'utf8')
100
- .replaceAll("const { cacheList, fetchFile, getSpareUrls } = require('../sw-rules')", cache)
101
- .replaceAll("'@$$[escape]'", (pluginConfig.sw.escape ?? 0).toString())
102
- .replaceAll("'@$$[cacheName]'", `'${pluginConfig.sw.cacheName ?? 'kmarBlogCache'}'`)
103
- if (modifyRequest) {
104
- swContent = swContent.replaceAll('// [modifyRequest call]', `
105
- const modify = modifyRequest(request)
106
- if (modify) request = modify
107
- `).replaceAll('// [modifyRequest else-if]', `
108
- else if (modify) event.respondWith(fetch(request))
109
- `)
110
- }
111
- if (blockRequest) {
112
- swContent = swContent.replace('// [blockRequest call]', `
113
- if (blockRequest(url)) return
114
- `)
115
- }
116
- return {
117
- path: 'sw.js',
118
- data: swContent
119
- }
120
- })
121
-
122
- // 生成注册 sw 的代码
123
- hexo.extend.injector.register('head_begin', () => {
124
- return `<script>
125
- (() => {
126
- const sw = navigator.serviceWorker
127
- const error = () => ${pluginConfig.sw.onerror}
128
- if (!sw?.register('${new URL(root).pathname}sw.js')?.then(() => {
129
- if (!sw.controller) ${pluginConfig.sw.onsuccess}
130
- })?.catch(error)) error()
131
- })()
132
- </script>`
133
- }, "default")
134
-
135
- // 插入 sw-dom.js
136
- if (!pluginConfig.dom?.custom) {
137
- hexo.extend.injector.register('body_begin', () => {
138
- // noinspection HtmlUnknownTarget
139
- return `<script src="/sw-dom.js"></script>`
140
- })
141
- hexo.extend.generator.register('buildDomJs', () => {
142
- const absPath = module.path + '/sw-dom.js'
143
- const rootPath = nodePath.resolve('./')
144
- const relativePath = nodePath.relative(rootPath, absPath)
145
- const template = fs.readFileSync(relativePath, 'utf-8')
146
- .replaceAll('// ${onSuccess}', pluginConfig.dom.onsuccess)
147
- return {
148
- path: 'sw-dom.js',
149
- data: template
150
- }
151
- })
152
- }
153
- }