swpp-backends 0.0.1-alpha.0
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/LICENSE +661 -0
- package/README.md +5 -0
- package/dist/fileAnalyzer.js +205 -0
- package/dist/index.js +28 -0
- package/dist/resources/sw-dom.js +51 -0
- package/dist/resources/sw-template.js +265 -0
- package/dist/serviceWorkerBuilder.js +144 -0
- package/dist/swppRules.js +99 -0
- package/dist/utils.js +160 -0
- package/gulpfile.js +3 -0
- package/package.json +22 -0
- package/src/FileAnalyzer.ts +417 -0
- package/src/ServiceWorkerBuilder.ts +156 -0
- package/src/SwppConfig.ts +125 -0
- package/src/SwppRules.ts +200 -0
- package/src/UpdateJsonBuilder.ts +279 -0
- package/src/Utils.ts +195 -0
- package/src/VersionAnalyzer.ts +77 -0
- package/src/index.ts +64 -0
- package/src/resources/sw-dom.js +51 -0
- package/src/resources/sw-template.js +257 -0
- package/tsconfig.json +109 -0
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
|
+
};
|
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
+
exports.replaceRequest = exports.findCache = exports.eachAllLinkInJavaScript = exports.eachAllLinkInCss = exports.eachAllLinkInHtml = exports.eachAllLinkInUrl = exports.buildCacheJson = void 0;
|
|
30
|
+
const fs_1 = __importDefault(require("fs"));
|
|
31
|
+
const path_1 = __importDefault(require("path"));
|
|
32
|
+
const node_fetch_1 = require("node-fetch");
|
|
33
|
+
const utils_1 = require("./utils");
|
|
34
|
+
const crypto = __importStar(require("crypto"));
|
|
35
|
+
const buffer_1 = require("buffer");
|
|
36
|
+
const fast_html_parser_1 = __importDefault(require("fast-html-parser"));
|
|
37
|
+
const css_1 = __importDefault(require("css"));
|
|
38
|
+
const utils_2 = require("./utils");
|
|
39
|
+
/**
|
|
40
|
+
* 遍历指定目录下的所有文件
|
|
41
|
+
* @param root 根目录
|
|
42
|
+
* @param cb 回调函数
|
|
43
|
+
*/
|
|
44
|
+
function eachAllFile(root, cb) {
|
|
45
|
+
const stats = fs_1.default.statSync(root);
|
|
46
|
+
if (stats.isFile())
|
|
47
|
+
cb(root);
|
|
48
|
+
else {
|
|
49
|
+
const files = fs_1.default.readdirSync(root);
|
|
50
|
+
files.forEach(it => eachAllFile(path_1.default.join(root, it), cb));
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** 判断指定文件是否排除 */
|
|
54
|
+
function isExclude(pathname, rules) {
|
|
55
|
+
const exclude = rules.config.json.exclude;
|
|
56
|
+
for (let reg of exclude) {
|
|
57
|
+
if (pathname.match(reg))
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* 构建一个 cache json
|
|
64
|
+
* @param protocol 网站地网络协议
|
|
65
|
+
* @param webRoot 网站根路径(不包括网络协议)
|
|
66
|
+
* @param root 根目录
|
|
67
|
+
* @param rules swpp 规则文件
|
|
68
|
+
*/
|
|
69
|
+
function buildCacheJson(protocol, webRoot, root, rules) {
|
|
70
|
+
const result = [];
|
|
71
|
+
eachAllFile(root, path => {
|
|
72
|
+
const endIndex = path.length - (path.endsWith('/index.html') ? 10 : 0);
|
|
73
|
+
const url = new URL(protocol + path_1.default.join(webRoot, path.substring(root.length, endIndex)));
|
|
74
|
+
if (isExclude(url.pathname, rules))
|
|
75
|
+
return;
|
|
76
|
+
let content = null;
|
|
77
|
+
if (findCache(url, rules)) {
|
|
78
|
+
content = fs_1.default.readFileSync(path, 'utf-8');
|
|
79
|
+
const key = decodeURIComponent(url.pathname);
|
|
80
|
+
result.push({
|
|
81
|
+
url: key,
|
|
82
|
+
md5: crypto.createHash('md5').update(content).digest('hex')
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
exports.buildCacheJson = buildCacheJson;
|
|
88
|
+
const successStatus = [200, 301, 302, 307, 308];
|
|
89
|
+
/** 遍历一个 URL 指向地文件中所有地外部链接 */
|
|
90
|
+
async function eachAllLinkInUrl(webRoot, url, rules) {
|
|
91
|
+
const response = await (0, utils_1.fetchFile)(rules.config, url);
|
|
92
|
+
if (!successStatus.includes(response.status))
|
|
93
|
+
throw response;
|
|
94
|
+
const result = [];
|
|
95
|
+
const pathname = new URL(url).pathname;
|
|
96
|
+
let content = null;
|
|
97
|
+
switch (true) {
|
|
98
|
+
case pathname.endsWith('.html'):
|
|
99
|
+
case pathname.endsWith('/'):
|
|
100
|
+
content = await response.text();
|
|
101
|
+
result.push(...await eachAllLinkInHtml(webRoot, content, rules));
|
|
102
|
+
break;
|
|
103
|
+
case pathname.endsWith('.css'):
|
|
104
|
+
content = await response.text();
|
|
105
|
+
result.push(...await eachAllLinkInCss(webRoot, content, rules));
|
|
106
|
+
break;
|
|
107
|
+
case pathname.endsWith('.js'):
|
|
108
|
+
content = await response.text();
|
|
109
|
+
result.push(...await eachAllLinkInJavaScript(webRoot, content, rules));
|
|
110
|
+
break;
|
|
111
|
+
default:
|
|
112
|
+
const buffer = buffer_1.Buffer.from(await response.arrayBuffer());
|
|
113
|
+
result.push({
|
|
114
|
+
url, md5: crypto.createHash('md5').update(buffer).digest('hex')
|
|
115
|
+
});
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
if (content)
|
|
119
|
+
result.push({
|
|
120
|
+
url, md5: crypto.createHash('md5').update(content).digest('hex')
|
|
121
|
+
});
|
|
122
|
+
return result;
|
|
123
|
+
}
|
|
124
|
+
exports.eachAllLinkInUrl = eachAllLinkInUrl;
|
|
125
|
+
/** 遍历 HTML 文件中的所有外部链接 */
|
|
126
|
+
async function eachAllLinkInHtml(webRoot, content, rules) {
|
|
127
|
+
const result = [];
|
|
128
|
+
const each = async (node) => {
|
|
129
|
+
let url = undefined;
|
|
130
|
+
switch (node.tagName) {
|
|
131
|
+
case 'link':
|
|
132
|
+
url = node.attributes.href;
|
|
133
|
+
break;
|
|
134
|
+
case 'script':
|
|
135
|
+
case 'img':
|
|
136
|
+
case 'source':
|
|
137
|
+
case 'iframe':
|
|
138
|
+
case 'embed':
|
|
139
|
+
url = node.attributes.src;
|
|
140
|
+
break;
|
|
141
|
+
case 'object':
|
|
142
|
+
url = node.attributes.data;
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
if (url) {
|
|
146
|
+
if (isExternalLink(webRoot, url) && findCache(new URL(url), rules))
|
|
147
|
+
result.push(...await eachAllLinkInUrl(webRoot, url, rules));
|
|
148
|
+
}
|
|
149
|
+
else if (node.tagName === 'script') {
|
|
150
|
+
result.push(...await eachAllLinkInJavaScript(webRoot, node.rawText, rules));
|
|
151
|
+
}
|
|
152
|
+
else if (node.tagName === 'style') {
|
|
153
|
+
result.push(...await eachAllLinkInCss(webRoot, node.rawText, rules));
|
|
154
|
+
}
|
|
155
|
+
for (let childNode of node.childNodes) {
|
|
156
|
+
await each(childNode);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
await each(fast_html_parser_1.default.parse(content, { style: true, script: true }));
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
exports.eachAllLinkInHtml = eachAllLinkInHtml;
|
|
163
|
+
/** 遍历 CSS 文件中的所有外部链接 */
|
|
164
|
+
async function eachAllLinkInCss(webRoot, content, rules) {
|
|
165
|
+
const result = [];
|
|
166
|
+
const each = (rules) => {
|
|
167
|
+
if (!rules)
|
|
168
|
+
return;
|
|
169
|
+
for (let rule of rules) {
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
each(css_1.default.parse(content).stylesheet?.rules);
|
|
173
|
+
return result;
|
|
174
|
+
}
|
|
175
|
+
exports.eachAllLinkInCss = eachAllLinkInCss;
|
|
176
|
+
/** 遍历 JS 文件中地所有外部链接 */
|
|
177
|
+
async function eachAllLinkInJavaScript(webRoot, content, rules) {
|
|
178
|
+
}
|
|
179
|
+
exports.eachAllLinkInJavaScript = eachAllLinkInJavaScript;
|
|
180
|
+
/** 判断一个 URL 是否是外部链接 */
|
|
181
|
+
function isExternalLink(webRoot, url) {
|
|
182
|
+
return url.startsWith(`https://${webRoot}`);
|
|
183
|
+
}
|
|
184
|
+
/** 查询缓存规则 */
|
|
185
|
+
function findCache(url, rules) {
|
|
186
|
+
const { cacheList } = rules;
|
|
187
|
+
const eject = (0, utils_2.readEjectData)();
|
|
188
|
+
url = new URL(replaceRequest(url.href, rules));
|
|
189
|
+
for (let key in cacheList) {
|
|
190
|
+
const value = cacheList[key];
|
|
191
|
+
if (value.match(url, eject.nodeEject))
|
|
192
|
+
return value;
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
exports.findCache = findCache;
|
|
197
|
+
/** 替换请求 */
|
|
198
|
+
function replaceRequest(url, rules) {
|
|
199
|
+
if (!('modifyRequest' in rules))
|
|
200
|
+
return url;
|
|
201
|
+
const { modifyRequest } = rules;
|
|
202
|
+
const request = new node_fetch_1.Request(url);
|
|
203
|
+
return modifyRequest(request, (0, utils_2.readEjectData)().nodeEject)?.url ?? url;
|
|
204
|
+
}
|
|
205
|
+
exports.replaceRequest = replaceRequest;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
const CSSParser = __importStar(require("css"));
|
|
27
|
+
const tmp = CSSParser.parse('.name0 .name1 { color: red; }');
|
|
28
|
+
console.log(tmp);
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
document.addEventListener('DOMContentLoaded', () => {
|
|
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
|
+
if (!checkServiceWorker()) return
|
|
23
|
+
if (sessionStorage.getItem('updated')) {
|
|
24
|
+
sessionStorage.removeItem('updated')
|
|
25
|
+
// ${onSuccess}
|
|
26
|
+
} else postMessage2SW('update')
|
|
27
|
+
navigator.serviceWorker.addEventListener('message', event => {
|
|
28
|
+
const data = event.data
|
|
29
|
+
switch (data.type) {
|
|
30
|
+
case 'update':
|
|
31
|
+
const list = data.update
|
|
32
|
+
if (!list) break
|
|
33
|
+
sessionStorage.setItem('updated', '1')
|
|
34
|
+
// noinspection JSUnresolvedVariable,JSUnresolvedFunction
|
|
35
|
+
if (window.Pjax?.isSupported()) {
|
|
36
|
+
Promise.all(list.map(url => {
|
|
37
|
+
if (url.endsWith('.js'))
|
|
38
|
+
return pjaxUpdate(url)
|
|
39
|
+
if (url.endsWith('.css'))
|
|
40
|
+
return pjaxUpdate(url)
|
|
41
|
+
return Promise.resolve()
|
|
42
|
+
})).then(() => location.reload())
|
|
43
|
+
} else location.reload()
|
|
44
|
+
break
|
|
45
|
+
case 'escape':
|
|
46
|
+
sessionStorage.setItem('updated', '1')
|
|
47
|
+
location.reload()
|
|
48
|
+
break
|
|
49
|
+
}
|
|
50
|
+
})
|
|
51
|
+
})
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// noinspection JSIgnoredPromiseFromCall
|
|
2
|
+
|
|
3
|
+
(() => {
|
|
4
|
+
/** 缓存库名称 */
|
|
5
|
+
const CACHE_NAME = '@$$[cacheName]'
|
|
6
|
+
/** 控制信息存储地址(必须以`/`结尾) */
|
|
7
|
+
const CTRL_PATH = 'https://id.v3/'
|
|
8
|
+
|
|
9
|
+
// [insertion site] values
|
|
10
|
+
|
|
11
|
+
/** 控制信息读写操作 */
|
|
12
|
+
const dbVersion = {
|
|
13
|
+
write: (id) => caches.open(CACHE_NAME)
|
|
14
|
+
.then(cache => cache.put(CTRL_PATH, new Response(JSON.stringify(id)))),
|
|
15
|
+
read: () => caches.match(CTRL_PATH).then(response => response?.json())
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
self.addEventListener('install', () => {
|
|
19
|
+
self.skipWaiting()
|
|
20
|
+
const escape = '@$$[escape]'
|
|
21
|
+
dbVersion.read().then(oldVersion => {
|
|
22
|
+
if (oldVersion && oldVersion.escape !== escape) {
|
|
23
|
+
oldVersion.escape = escape
|
|
24
|
+
// noinspection JSUnresolvedVariable
|
|
25
|
+
caches.delete(CACHE_NAME)
|
|
26
|
+
.then(() => clients.matchAll())
|
|
27
|
+
.then(list => list.forEach(client => client.postMessage({type: 'escape'})))
|
|
28
|
+
}
|
|
29
|
+
})
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
// sw 激活后立即对所有页面生效,而非等待刷新
|
|
33
|
+
// noinspection JSUnresolvedReference
|
|
34
|
+
self.addEventListener('activate', event => event.waitUntil(clients.claim()))
|
|
35
|
+
|
|
36
|
+
// noinspection JSFileReferences
|
|
37
|
+
const { cacheList, fetchFile, getSpareUrls } = require('../sw-rules')
|
|
38
|
+
|
|
39
|
+
// 检查请求是否成功
|
|
40
|
+
// noinspection JSUnusedLocalSymbols
|
|
41
|
+
const checkResponse = response => response.ok || [301, 302, 307, 308].includes(response.status)
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 删除指定缓存
|
|
45
|
+
* @param list 要删除的缓存列表
|
|
46
|
+
* @return {Promise<string[]>} 删除的缓存的URL列表
|
|
47
|
+
*/
|
|
48
|
+
const deleteCache = list => caches.open(CACHE_NAME).then(cache => cache.keys()
|
|
49
|
+
.then(keys => Promise.all(
|
|
50
|
+
keys.map(async it => {
|
|
51
|
+
const url = it.url
|
|
52
|
+
if (url !== CTRL_PATH && list.match(url)) {
|
|
53
|
+
// [debug delete]
|
|
54
|
+
// noinspection ES6MissingAwait,JSCheckFunctionSignatures
|
|
55
|
+
cache.delete(it)
|
|
56
|
+
return url
|
|
57
|
+
}
|
|
58
|
+
return null
|
|
59
|
+
})
|
|
60
|
+
)).then(list => list.filter(it => it))
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
self.addEventListener('fetch', event => {
|
|
64
|
+
let request = event.request
|
|
65
|
+
if (request.method !== 'GET' || !request.url.startsWith('http')) return
|
|
66
|
+
// [modifyRequest call]
|
|
67
|
+
const url = new URL(request.url)
|
|
68
|
+
// [blockRequest call]
|
|
69
|
+
const cacheRule = findCache(url)
|
|
70
|
+
if (cacheRule) {
|
|
71
|
+
let key = `https://${url.host}${url.pathname}`
|
|
72
|
+
if (key.endsWith('/index.html')) key = key.substring(0, key.length - 10)
|
|
73
|
+
if (cacheRule.search) key += url.search
|
|
74
|
+
event.respondWith(caches.match(key)
|
|
75
|
+
.then(cache => cache ?? fetchFile(request, true)
|
|
76
|
+
.then(response => {
|
|
77
|
+
if (checkResponse(response)) {
|
|
78
|
+
const clone = response.clone()
|
|
79
|
+
caches.open(CACHE_NAME).then(it => it.put(key, clone))
|
|
80
|
+
// [debug put]
|
|
81
|
+
}
|
|
82
|
+
return response
|
|
83
|
+
})
|
|
84
|
+
)
|
|
85
|
+
)
|
|
86
|
+
} else {
|
|
87
|
+
const spare = getSpareUrls(request.url)
|
|
88
|
+
if (spare) event.respondWith(fetchFile(request, false, spare))
|
|
89
|
+
// [modifyRequest else-if]
|
|
90
|
+
}
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
self.addEventListener('message', event => {
|
|
94
|
+
// [debug message]
|
|
95
|
+
if (event.data === 'update')
|
|
96
|
+
updateJson().then(info =>
|
|
97
|
+
// noinspection JSUnresolvedVariable
|
|
98
|
+
event.source.postMessage({
|
|
99
|
+
type: 'update',
|
|
100
|
+
update: info.list,
|
|
101
|
+
version: info.version,
|
|
102
|
+
})
|
|
103
|
+
)
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
/** 判断指定url击中了哪一种缓存,都没有击中则返回null */
|
|
107
|
+
function findCache(url) {
|
|
108
|
+
if (url.hostname === 'localhost') return
|
|
109
|
+
for (let key in cacheList) {
|
|
110
|
+
const value = cacheList[key]
|
|
111
|
+
if (value.match(url)) return value
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* 根据JSON删除缓存
|
|
117
|
+
* @returns {Promise<{version, list}>}
|
|
118
|
+
*/
|
|
119
|
+
const updateJson = () => {
|
|
120
|
+
/**
|
|
121
|
+
* 解析elements,并把结果输出到list中
|
|
122
|
+
* @return boolean 是否刷新全站缓存
|
|
123
|
+
*/
|
|
124
|
+
const parseChange = (list, elements, ver) => {
|
|
125
|
+
for (let element of elements) {
|
|
126
|
+
const {version, change} = element
|
|
127
|
+
if (version === ver) return false
|
|
128
|
+
if (change) {
|
|
129
|
+
for (let it of change)
|
|
130
|
+
list.push(new CacheChangeExpression(it))
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// 跨版本幅度过大,直接清理全站
|
|
134
|
+
return true
|
|
135
|
+
}
|
|
136
|
+
/** 解析字符串 */
|
|
137
|
+
const parseJson = json => dbVersion.read().then(oldVersion => {
|
|
138
|
+
const {info, global} = json
|
|
139
|
+
const newVersion = {global, local: info[0].version, escape: oldVersion?.escape}
|
|
140
|
+
//新用户不进行更新操作
|
|
141
|
+
if (!oldVersion) {
|
|
142
|
+
dbVersion.write(newVersion)
|
|
143
|
+
return newVersion
|
|
144
|
+
}
|
|
145
|
+
let list = new VersionList()
|
|
146
|
+
let refresh = parseChange(list, info, oldVersion.local)
|
|
147
|
+
dbVersion.write(newVersion)
|
|
148
|
+
// [debug escape]
|
|
149
|
+
//如果需要清理全站
|
|
150
|
+
if (refresh) {
|
|
151
|
+
if (global !== oldVersion.global) list.refresh = true
|
|
152
|
+
else list.clean(new CacheChangeExpression({'flag': 'all'}))
|
|
153
|
+
}
|
|
154
|
+
return {list, version: newVersion}
|
|
155
|
+
})
|
|
156
|
+
return fetchFile(new Request('/update.json'), false)
|
|
157
|
+
.then(response => {
|
|
158
|
+
if (checkResponse(response))
|
|
159
|
+
return response.json().then(json =>
|
|
160
|
+
parseJson(json).then(result => {
|
|
161
|
+
return result.list ? deleteCache(result.list)
|
|
162
|
+
.then(list => list.length === 0 ? null : list)
|
|
163
|
+
.then(list => ({list, version: result.version}))
|
|
164
|
+
: {version: result}
|
|
165
|
+
}
|
|
166
|
+
)
|
|
167
|
+
)
|
|
168
|
+
else throw `加载 update.json 时遇到异常,状态码:${response.status}`
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 版本列表
|
|
174
|
+
* @constructor
|
|
175
|
+
*/
|
|
176
|
+
function VersionList() {
|
|
177
|
+
|
|
178
|
+
const list = []
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 推送一个表达式
|
|
182
|
+
* @param element {CacheChangeExpression} 要推送的表达式
|
|
183
|
+
*/
|
|
184
|
+
this.push = element => {
|
|
185
|
+
list.push(element)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* 清除列表,并将指定元素推入列表中
|
|
190
|
+
* @param element {CacheChangeExpression} 要推入的元素,留空表示不推入
|
|
191
|
+
*/
|
|
192
|
+
this.clean = element => {
|
|
193
|
+
list.length = 0
|
|
194
|
+
if (!element) this.push(element)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* 判断指定 URL 是否和某一条规则匹配
|
|
199
|
+
* @param url {string} URL
|
|
200
|
+
* @return {boolean}
|
|
201
|
+
*/
|
|
202
|
+
this.match = url => {
|
|
203
|
+
if (this.refresh) return true
|
|
204
|
+
else {
|
|
205
|
+
for (let it of list) {
|
|
206
|
+
if (it.match(url)) return true
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return false
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// noinspection SpellCheckingInspection
|
|
215
|
+
/**
|
|
216
|
+
* 缓存更新匹配规则表达式
|
|
217
|
+
* @param json 格式{"flag": ..., "value": ...}
|
|
218
|
+
* @see https://kmar.top/posts/bcfe8408/#23bb4130
|
|
219
|
+
* @constructor
|
|
220
|
+
*/
|
|
221
|
+
function CacheChangeExpression(json) {
|
|
222
|
+
const checkCache = url => {
|
|
223
|
+
const cache = findCache(new URL(url))
|
|
224
|
+
return !cache || cache.clean
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* 遍历所有value
|
|
228
|
+
* @param action {function(string): boolean} 接受value并返回bool的函数
|
|
229
|
+
* @return {boolean} 如果value只有一个则返回`action(value)`,否则返回所有运算的或运算(带短路)
|
|
230
|
+
*/
|
|
231
|
+
const forEachValues = action => {
|
|
232
|
+
const value = json.value
|
|
233
|
+
if (Array.isArray(value)) {
|
|
234
|
+
for (let it of value) {
|
|
235
|
+
if (action(it)) return true
|
|
236
|
+
}
|
|
237
|
+
return false
|
|
238
|
+
} else return action(value)
|
|
239
|
+
}
|
|
240
|
+
switch (json['flag']) {
|
|
241
|
+
case 'all':
|
|
242
|
+
this.match = checkCache
|
|
243
|
+
break
|
|
244
|
+
case 'html':
|
|
245
|
+
this.match = url => url.match(/(\/|\.html)$/)
|
|
246
|
+
break
|
|
247
|
+
case 'page':
|
|
248
|
+
this.match = url => forEachValues(
|
|
249
|
+
// \/xxx(\/|\.html)$
|
|
250
|
+
value => url.match(new RegExp(`\\/${value}(\\/|\\.html)\$`))
|
|
251
|
+
)
|
|
252
|
+
break
|
|
253
|
+
case 'file':
|
|
254
|
+
this.match = url => forEachValues(value => url.endsWith(value))
|
|
255
|
+
break
|
|
256
|
+
case 'str':
|
|
257
|
+
this.match = url => forEachValues(value => url.includes(value))
|
|
258
|
+
break
|
|
259
|
+
case 'reg':
|
|
260
|
+
this.match = url => forEachValues(value => url.match(new RegExp(value, 'i')))
|
|
261
|
+
break
|
|
262
|
+
default: throw `未知表达式:${JSON.stringify(json)}`
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
})()
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.buildServiceWorker = void 0;
|
|
7
|
+
const utils_1 = require("./utils");
|
|
8
|
+
const fs_1 = __importDefault(require("fs"));
|
|
9
|
+
const path_1 = __importDefault(require("path"));
|
|
10
|
+
/** 构建 sw */
|
|
11
|
+
function buildServiceWorker(rules, eject) {
|
|
12
|
+
const { modifyRequest, fetchNoCache, getCdnList, getSpareUrls, blockRequest, config } = rules;
|
|
13
|
+
const serviceWorkerConfig = config.serviceWorker;
|
|
14
|
+
const templatePath = path_1.default.resolve('./', module.path, 'sw-template.js');
|
|
15
|
+
// 获取拓展文件
|
|
16
|
+
let cache = (0, utils_1.getSource)(rules, undefined, [
|
|
17
|
+
'cacheList', 'modifyRequest', 'getCdnList', 'getSpareUrls', 'blockRequest',
|
|
18
|
+
...('external' in rules && Array.isArray(rules.external) ? rules.external : [])
|
|
19
|
+
], true) + '\n';
|
|
20
|
+
if (!fetchNoCache) {
|
|
21
|
+
if (getCdnList)
|
|
22
|
+
cache += JS_CODE_GET_CDN_LIST;
|
|
23
|
+
else if (getSpareUrls)
|
|
24
|
+
cache += JS_CODE_GET_SPARE_URLS;
|
|
25
|
+
else
|
|
26
|
+
cache += JS_CODE_DEF_FETCH_FILE;
|
|
27
|
+
}
|
|
28
|
+
if (!getSpareUrls)
|
|
29
|
+
cache += `\nconst getSpareUrls = _ => {}`;
|
|
30
|
+
if ('afterJoin' in rules)
|
|
31
|
+
cache += `(${(0, utils_1.getSource)(rules['afterJoin'])})()\n`;
|
|
32
|
+
if ('afterTheme' in rules)
|
|
33
|
+
cache += `(${(0, utils_1.getSource)(rules['afterTheme'])})()\n`;
|
|
34
|
+
const keyword = "const { cacheList, fetchFile, getSpareUrls } = require('../sw-rules')";
|
|
35
|
+
// noinspection JSUnresolvedVariable
|
|
36
|
+
let content = fs_1.default.readFileSync(templatePath, 'utf8')
|
|
37
|
+
.replaceAll("// [insertion site] values", eject.strValue ?? '')
|
|
38
|
+
.replaceAll(keyword, cache)
|
|
39
|
+
.replaceAll("'@$$[escape]'", (serviceWorkerConfig.escape).toString())
|
|
40
|
+
.replaceAll("'@$$[cacheName]'", `'${serviceWorkerConfig.cacheName}'`);
|
|
41
|
+
if (modifyRequest) {
|
|
42
|
+
content = content.replaceAll('// [modifyRequest call]', `
|
|
43
|
+
const modify = modifyRequest(request)
|
|
44
|
+
if (modify) request = modify
|
|
45
|
+
`).replaceAll('// [modifyRequest else-if]', `
|
|
46
|
+
else if (modify) event.respondWith(fetch(request))
|
|
47
|
+
`);
|
|
48
|
+
}
|
|
49
|
+
if (blockRequest) {
|
|
50
|
+
content = content.replace('// [blockRequest call]', `
|
|
51
|
+
if (blockRequest(url))
|
|
52
|
+
return event.respondWith(new Response(null, {status: 208}))
|
|
53
|
+
`);
|
|
54
|
+
}
|
|
55
|
+
// noinspection JSUnresolvedVariable
|
|
56
|
+
if (serviceWorkerConfig.debug) {
|
|
57
|
+
content = content.replaceAll('// [debug delete]', `
|
|
58
|
+
console.debug(\`delete cache: \${url}\`)
|
|
59
|
+
`).replaceAll('// [debug put]', `
|
|
60
|
+
console.debug(\`put cache: \${key}\`)
|
|
61
|
+
`).replaceAll('// [debug message]', `
|
|
62
|
+
console.debug(\`receive: \${event.data}\`)
|
|
63
|
+
`).replaceAll('// [debug escape]', `
|
|
64
|
+
console.debug(\`escape: \${aid}\`)
|
|
65
|
+
`);
|
|
66
|
+
}
|
|
67
|
+
return content;
|
|
68
|
+
}
|
|
69
|
+
exports.buildServiceWorker = buildServiceWorker;
|
|
70
|
+
// 缺省的 fetchFile 函数的代码
|
|
71
|
+
const JS_CODE_DEF_FETCH_FILE = `
|
|
72
|
+
const fetchFile = (request, banCache) => fetch(request, {
|
|
73
|
+
cache: banCache ? "no-store" : "default",
|
|
74
|
+
mode: 'cors',
|
|
75
|
+
credentials: 'same-origin'
|
|
76
|
+
})
|
|
77
|
+
`;
|
|
78
|
+
// getCdnList 函数的代码
|
|
79
|
+
const JS_CODE_GET_CDN_LIST = `
|
|
80
|
+
const fetchFile = (request, banCache) => {
|
|
81
|
+
const fetchArgs = {
|
|
82
|
+
cache: banCache ? 'no-store' : 'default',
|
|
83
|
+
mode: 'cors',
|
|
84
|
+
credentials: 'same-origin'
|
|
85
|
+
}
|
|
86
|
+
const list = getCdnList(request.url)
|
|
87
|
+
if (!list || !Promise.any) return fetch(request, fetchArgs)
|
|
88
|
+
const res = list.map(url => new Request(url, request))
|
|
89
|
+
const controllers = []
|
|
90
|
+
return Promise.any(res.map(
|
|
91
|
+
(it, index) => fetch(it, Object.assign(
|
|
92
|
+
{signal: (controllers[index] = new AbortController()).signal},
|
|
93
|
+
fetchArgs
|
|
94
|
+
)).then(response => checkResponse(response) ? {index, response} : Promise.reject())
|
|
95
|
+
)).then(it => {
|
|
96
|
+
for (let i in controllers) {
|
|
97
|
+
if (i != it.index) controllers[i].abort()
|
|
98
|
+
}
|
|
99
|
+
return it.response
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
`;
|
|
103
|
+
// getSpareUrls 函数的代码
|
|
104
|
+
const JS_CODE_GET_SPARE_URLS = `
|
|
105
|
+
const fetchFile = (request, banCache, spare = null) => {
|
|
106
|
+
const fetchArgs = {
|
|
107
|
+
cache: banCache ? 'no-store' : 'default',
|
|
108
|
+
mode: 'cors',
|
|
109
|
+
credentials: 'same-origin'
|
|
110
|
+
}
|
|
111
|
+
if (!spare) spare = getSpareUrls(request.url)
|
|
112
|
+
if (!spare) return fetch(request, fetchArgs)
|
|
113
|
+
const list = spare.list
|
|
114
|
+
const controllers = []
|
|
115
|
+
let error = 0
|
|
116
|
+
return new Promise((resolve, reject) => {
|
|
117
|
+
const pull = () => {
|
|
118
|
+
const flag = controllers.length
|
|
119
|
+
if (flag === list.length) return
|
|
120
|
+
const plusError = () => {
|
|
121
|
+
if (++error === list.length) reject(\`请求 \${request.url} 失败\`)
|
|
122
|
+
else if (flag + 1 === controllers.length) {
|
|
123
|
+
clearTimeout(controllers[flag].id)
|
|
124
|
+
pull()
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
controllers.push({
|
|
128
|
+
ctrl: new AbortController(),
|
|
129
|
+
id: setTimeout(pull, spare.timeout)
|
|
130
|
+
})
|
|
131
|
+
fetch(new Request(list[flag], request), fetchArgs).then(response => {
|
|
132
|
+
if (checkResponse(response)) {
|
|
133
|
+
for (let i in controllers) {
|
|
134
|
+
if (i !== flag) controllers[i].ctrl.abort()
|
|
135
|
+
clearTimeout(controllers[i].id)
|
|
136
|
+
}
|
|
137
|
+
resolve(response)
|
|
138
|
+
} else plusError()
|
|
139
|
+
}).catch(plusError)
|
|
140
|
+
}
|
|
141
|
+
pull()
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
`;
|