hexo-swpp 1.2.2 → 1.2.4

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,14 +10,14 @@ const path = require('path')
10
10
  const findScript = () => path.resolve('./', 'sw-cache')
11
11
 
12
12
  const config = hexo.config
13
- const pluginConfig = config.swpp
14
- const root = config.url + config.root
13
+ const pluginConfig = config.swpp || hexo.theme.config
14
+ const root = config.url + (config.root ?? '/')
15
15
  const { cacheList, replaceList } = pluginConfig?.enable ? require(findScript()) : undefined
16
16
 
17
17
  if (pluginConfig?.enable) {
18
18
  // 生成 update.json
19
- hexo.on('exit', async () => {
20
- if (!fs.existsSync('public/index.html'))
19
+ hexo.extend.console.register('swpp', '生成前端更新需要的 json 文件以及相关缓存', {}, async () => {
20
+ if (!fs.existsSync(config.public_dir))
21
21
  return logger.info('跳过生成 update.json')
22
22
  const cachePath = 'cacheList.json'
23
23
  const updatePath = 'update.json'
@@ -50,7 +50,7 @@ if (pluginConfig?.enable) {
50
50
  (() => {
51
51
  const sw = navigator.serviceWorker
52
52
  const error = () => ${pluginConfig.sw.onerror}
53
- if (!sw?.register('/sw.js')?.then(() => {
53
+ if (!sw?.register('${new URL(root).pathname}sw.js')?.then(() => {
54
54
  if (!sw.controller) ${pluginConfig.sw.onsuccess}
55
55
  })?.catch(error)) error()
56
56
  })()
@@ -124,7 +124,7 @@ const buildNewJson = path => {
124
124
  let publicRoot = config.public_dir || 'public/'
125
125
  if (!publicRoot.endsWith('/')) publicRoot += '/'
126
126
  fs.writeFileSync(`${publicRoot}${path}`, JSON.stringify(result), 'utf-8')
127
- logger.info(`Generated: ${path}`)
127
+ logger.info(`SwppGenerated: ${path}`)
128
128
  return result
129
129
  }
130
130
 
@@ -141,9 +141,6 @@ const getJsonFromNetwork = async path => {
141
141
  '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'
142
142
  }
143
143
  })
144
- if (result.status < 200 || result.status >= 400)
145
- // noinspection ExceptionCaughtLocallyJS
146
- throw `拉取 ${url} 时出现异常(${result.status})`
147
144
  return await result.json()
148
145
  } catch (e) {
149
146
  // noinspection SpellCheckingInspection
@@ -211,7 +208,7 @@ const buildUpdateJson = (name, dif, oldUpdate) => {
211
208
  /** 将对象写入文件,如果对象为 null 或 undefined 则跳过写入 */
212
209
  const writeJson = json => {
213
210
  if (json) {
214
- logger.info(`Generated: ${name}`)
211
+ logger.info(`SwppGenerated: ${name}`)
215
212
  fs.writeFileSync(`public/${name}`, JSON.stringify(json), 'utf-8')
216
213
  }
217
214
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hexo-swpp",
3
- "version": "1.2.2",
3
+ "version": "1.2.4",
4
4
  "main": "index.js",
5
5
  "dependencies": {
6
6
  "hexo-log": "^3.0.0",
@@ -8,7 +8,8 @@
8
8
  },
9
9
  "files": [
10
10
  "index.js",
11
- "sw-template.js"
11
+ "sw-template.js",
12
+ "sw-dom.js"
12
13
  ],
13
14
  "keywords": [
14
15
  "hexo",
package/sw-dom.js ADDED
@@ -0,0 +1,68 @@
1
+ (() => {
2
+ /** 检查 SW 是否可用 */
3
+ const checkServiceWorker = () => 'serviceWorker' in navigator && navigator.serviceWorker.controller
4
+ /** 发送信息到 sw */
5
+ const postMessage2SW = type => navigator.serviceWorker.controller.postMessage(type)
6
+ const pjaxUpdate = url => new Promise(resolve => {
7
+ const type = url.endsWith('js') ? 'script' : 'link'
8
+ const name = type.length === 4 ? 'href' : 'src'
9
+ for (let item of document.querySelectorAll(type)) {
10
+ const itUrl = item[name]
11
+ if (url.length > itUrl ? url.endsWith(itUrl) : itUrl.endsWith(url)) {
12
+ const newEle = document.createElement(type)
13
+ const content = item.text || item.textContent || item.innerHTML || ''
14
+ Array.from(item.attributes).forEach(attr => newEle.setAttribute(attr.name, attr.value))
15
+ newEle.appendChild(document.createTextNode(content))
16
+ item.parentNode.replaceChildren(newEle, item)
17
+ return resolve(true)
18
+ }
19
+ }
20
+ resolve(false)
21
+ })
22
+ const compareUrls = (arg0, arg1) => {
23
+ if (
24
+ (arg0.endsWith('/') && arg1.endsWith('/')) ||
25
+ (arg0.endsWith('/index.html') && arg1.endsWith('/index.html'))
26
+ ) {
27
+ let count = 0
28
+ for (let i = arg0.length - 1, k = arg1.length - 1; arg0[i] === arg1[k]; --i, --k) {
29
+ if (arg0[i] === '/' && ++count === 2) return true
30
+ }
31
+ }
32
+ return false
33
+ }
34
+ if (!checkServiceWorker()) return
35
+ if (sessionStorage.getItem('updated')) {
36
+ // ${onSuccess}
37
+ sessionStorage.removeItem('updated')
38
+ } else setTimeout(() => postMessage2SW('update'), 1000)
39
+ navigator.serviceWorker.addEventListener('message', event => {
40
+ const data = event.data
41
+ switch (data.type) {
42
+ case 'update':
43
+ const list = data.update
44
+ if (!list) break
45
+ sessionStorage.setItem('updated', '1')
46
+ // noinspection JSUnresolvedVariable,JSUnresolvedFunction
47
+ if (Pjax?.isSupported()) {
48
+ Promise.all(list.map(url => {
49
+ if (url.endsWith('.js'))
50
+ return pjaxUpdate(url)
51
+ if (url.endsWith('.css'))
52
+ return pjaxUpdate(url)
53
+ return Promise.resolve(url.endsWith('.json') || compareUrls(url, location.href))
54
+ })).then(list => {
55
+ for (let it of list) {
56
+ if (it) return location.reload()
57
+ }
58
+ sessionStorage.removeItem('updated')
59
+ // ${onSuccess}
60
+ })
61
+ } else location.reload()
62
+ break
63
+ case 'refresh':
64
+ location.reload()
65
+ break
66
+ }
67
+ })
68
+ })
package/sw-template.js CHANGED
@@ -264,7 +264,7 @@
264
264
  this.match = checkCache
265
265
  break
266
266
  case 'html':
267
- this.match = url => url.href.match(/(\/|\/index\.html)$/)
267
+ this.match = url => url.match(/(\/|\/index\.html)$/)
268
268
  break
269
269
  case 'page':
270
270
  this.match = url => forEachValues(