-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathgulpfile.js
More file actions
494 lines (465 loc) · 20.8 KB
/
Copy pathgulpfile.js
File metadata and controls
494 lines (465 loc) · 20.8 KB
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/**
* FeHelper Chrome Extension Builder By Gulp
* @author zhaoxianlie
*/
const gulp = require('gulp');
const clean = require('gulp-clean');
const copy = require('gulp-copy');
const zip = require('gulp-zip');
const uglifyjs = require('gulp-uglify-es').default;
const uglifycss = require('gulp-uglifycss');
const htmlmin = require('gulp-htmlmin');
const jsonmin = require('gulp-jsonminify');
const fs = require('fs');
const through = require('through2');
const path = require('path');
const pretty = require('pretty-bytes');
const shell = require('shelljs');
const babel = require('gulp-babel');
const assert = require('assert');
const gulpIf = require('gulp-if');
const imagemin = require('gulp-imagemin');
const imageminGifsicle = require('imagemin-gifsicle');
const imageminMozjpeg = require('imagemin-mozjpeg');
const imageminSvgo = require('imagemin-svgo');
let isSilentDetect = false; // <-- 添加全局标志位
const FIREFOX_REMOVE_TOOLS = [
'color-picker', 'postman', 'devtools', 'websocket', 'page-timing',
'grid-ruler', 'naotu', 'screenshot', 'page-monkey', 'excel2json'
];
const FIREFOX_REQUEST_UPDATE_CHECK_KEY = 'String.fromCharCode(114,101,113,117,101,115,116,85,112,100,97,116,101,67,104,101,99,107)';
// ============================================================================
// 浏览器差异化补丁:基础以 apps/manifest.json 为准(默认 Chrome MV3 形态),
// 不同浏览器只在这里做最小化调整,后续维护只需改一个 manifest.json 即可。
// ============================================================================
const BROWSER_PATCHES = {
chrome(manifest) {
// Chrome 商店需要 update_url(webstore 自更新)
manifest.update_url = 'https://clients2.google.com/service/update2/crx';
return manifest;
},
edge(manifest) {
// Edge 商店不需要 update_url
delete manifest.update_url;
return manifest;
},
firefox(manifest) {
delete manifest.update_url;
// Firefox WebExtensions 支持 alarms/webNavigation;后台脚本需要这两个权限。
// Firefox MV3 后台脚本走 scripts 而非 service_worker
if (manifest.background && manifest.background.service_worker) {
manifest.background = {
scripts: [manifest.background.service_worker],
type: manifest.background.type || 'module'
};
}
// 必须的 gecko 扩展元信息
manifest.browser_specific_settings = {
gecko: {
id: 'firefox@fehelper.com',
strict_min_version: '140.0',
data_collection_permissions: {
required: ['none']
}
},
gecko_android: {
strict_min_version: '142.0'
}
};
// Firefox CSP 需要 wasm-unsafe-eval / worker-src / connect-src 列表
manifest.content_security_policy = {
extension_pages: "script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; object-src 'self'; connect-src 'self' blob: https://chrome.fehelper.com https://api.siliconflow.cn https://baidufe.com https://www.baidufe.com https://img.shields.io;"
};
return manifest;
}
};
// 基于唯一的 apps/manifest.json 生成目标浏览器的 manifest 并写入 outputDir
function buildManifest(browser, outputDir) {
const srcPath = path.resolve('apps/manifest.json');
const base = JSON.parse(fs.readFileSync(srcPath, 'utf-8'));
const patcher = BROWSER_PATCHES[browser];
if (!patcher) throw new Error(`Unknown browser target: ${browser}`);
const finalManifest = patcher(base);
fs.writeFileSync(path.join(outputDir, 'manifest.json'), JSON.stringify(finalManifest));
}
// 清理输出目录
function cleanOutput(outputDir = 'output-chrome') {
return gulp.src(outputDir, {read: false, allowEmpty: true}).pipe(clean({force: true}));
}
// 复制静态资源
function copyAssets(outputDir = 'output-chrome/apps') {
return gulp.src(['apps/**/*.{gif,png,jpg,jpeg,cur,ico,woff2,svg,md,txt,json}']).pipe(gulp.dest(outputDir));
}
// 处理JSON文件
function processJson(outputDir = 'output-chrome/apps') {
return gulp.src('apps/**/*.json').pipe(jsonmin()).pipe(gulp.dest(outputDir));
}
// 处理HTML文件
function processHtml(outputDir = 'output-chrome/apps') {
return gulp.src('apps/**/*.html').pipe(htmlmin({collapseWhitespace: true})).pipe(gulp.dest(outputDir));
}
// 合并 & 压缩 js
function processJs(outputDir = 'output-chrome/apps') {
let jsMerge = () => {
return through.obj(function (file, enc, cb) {
let contents = file.contents.toString('utf-8');
let merge = (fp, fc) => {
return fc.replace(/__importScript\(\s*(['"])([^'"]*)\1\s*\)/gm, function (frag, $1, mod) {
let mp = path.resolve(fp, '../' + mod + (/\.js$/.test(mod) ? '' : '.js'));
let mc = fs.readFileSync(mp).toString('utf-8');
return merge(mp, mc + ';');
});
};
contents = merge(file.path, contents);
file.contents = Buffer.from(contents);
this.push(file);
return cb();
})
};
const shouldSkipProcessing = (file) => {
const relativePath = path.relative(path.join(process.cwd(), 'apps'), file.path);
return relativePath === 'chart-maker/lib/xlsx.full.min.js'
|| relativePath === 'static/vendor/evalCore.min.js'
|| relativePath === 'code-compress/htmlminifier.min.js';
};
return gulp.src('apps/**/*.js')
.pipe(jsMerge())
.pipe(gulpIf(file => !shouldSkipProcessing(file), babel({
presets: [
['@babel/preset-env', { modules: false }]
]
})))
.pipe(gulpIf(file => !shouldSkipProcessing(file), uglifyjs({
compress: {
ecma: 2015
}
})))
.pipe(gulp.dest(outputDir));
}
// 合并 & 压缩 css
function processCss(outputDir = 'output-chrome/apps') {
// Keep shared CSS as @import instead of inlining Bootstrap/Codemirror into every tool page.
return gulp.src('apps/**/*.css').pipe(uglifycss()).pipe(gulp.dest(outputDir));
}
// 添加图片压缩任务
function compressImages(outputDir = 'output-chrome/apps') {
return gulp.src(path.join(outputDir, '**/*.{png,jpg,jpeg,gif,svg}'))
.pipe(imagemin([
imageminGifsicle({interlaced: true}),
imageminMozjpeg({quality: 75, progressive: true}),
imageminSvgo({
plugins: [
{removeViewBox: true},
{cleanupIDs: false}
]
})
]))
.pipe(gulp.dest(outputDir));
}
// 清理冗余文件,并且打包成zip,发布到chrome webstore
function zipPackage(outputRoot = 'output-chrome', cb) {
let pathOfMF = path.join(outputRoot, 'apps/manifest.json');
let manifest = JSON.parse(fs.readFileSync(pathOfMF, 'utf-8'));
manifest.name = manifest.name.replace('-Dev', '');
fs.writeFileSync(pathOfMF, JSON.stringify(manifest));
let pkgName = 'fehelper.zip';
if (outputRoot === 'output-firefox') {
pkgName = 'fehelper.xpi';
}
shell.exec(`cd ${outputRoot}/apps && rm -rf ../${pkgName} && zip -r ../${pkgName} ./* > /dev/null && cd ../../`);
let size = fs.statSync(`${outputRoot}/${pkgName}`).size;
size = pretty(size);
console.log('\n\n================================================================================');
console.log(' 当前版本:', manifest.version, '\t文件大小:', size);
if (outputRoot === 'output-chrome') {
console.log(' 去Chrome商店发布吧:https://chrome.google.com/webstore/devconsole');
} else if (outputRoot === 'output-edge') {
console.log(' 去Edge商店发布吧:https://partner.microsoft.com/zh-cn/dashboard/microsoftedge/overview');
} else if (outputRoot === 'output-firefox') {
console.log(' 去Firefox商店发布吧:https://addons.mozilla.org/zh-CN/developers/addon/fehelper-%E5%89%8D%E7%AB%AF%E5%8A%A9%E6%89%8B/edit');
}
console.log('================================================================================\n\n');
if (cb) cb();
}
// 设置静默标志
function setSilentDetect(cb) {
isSilentDetect = true;
cb();
}
function unsetSilentDetect(cb) {
isSilentDetect = false;
cb();
}
// 检测未使用的静态文件(参数化outputDir)
function detectUnusedFiles(outputDir = 'output-chrome/apps', cb) {
const allFiles = new Set();
const referencedFiles = new Set();
function shouldExcludeFile(filePath) {
if (filePath.includes('content-script.js') || filePath.includes('content-script.css')) return true;
if (filePath.includes('node_modules')) return true;
if (filePath.endsWith('fh-config.js')) return true;
return false;
}
function getAllFiles(dir) {
const files = fs.readdirSync(dir);
files.forEach(file => {
const fullPath = path.join(dir, file);
if (fs.statSync(fullPath).isDirectory()) {
if (file !== 'node_modules') {
getAllFiles(fullPath);
}
} else {
if (/\.(js|css|png|jpg|jpeg|gif|svg|woff2?|ttf|eot)$/i.test(file) && !shouldExcludeFile(fullPath)) {
const relativePath = path.relative(outputDir, fullPath);
allFiles.add(relativePath);
}
}
});
}
function findReferences(content, filePath) {
const fileDir = path.dirname(filePath);
const patterns = [
/['"`][^`'\"]*?([./\w-]+\.(?:js|css|png|jpg|jpeg|gif|svg|woff2?|ttf|eot))['"`]/g,
/url\(['"]?([./\w-]+(?:\.(?:png|jpg|jpeg|gif|svg|woff2?|ttf|eot))?)['"]?\)/gi,
/@import\s+['"]([^'\"]+\.css)['"];?/gi,
/(?:src|href)=['"](chrome-extension:\/\/[^/]+\/)?([^'"?#]+(?:\.(?:js|css|png|jpg|jpeg|gif|svg|woff2?|ttf|eot)))['"]/gi
];
patterns.forEach((pattern, index) => {
let match;
while ((match = pattern.exec(content)) !== null) {
let extractedPath = '';
if (index === 3) {
extractedPath = match[2];
} else {
extractedPath = match[1];
}
if (!extractedPath || typeof extractedPath !== 'string') continue;
if (shouldExcludeFile(extractedPath)) continue;
let finalPathToAdd = '';
const isChromeExt = index === 3 && match[1];
if (isChromeExt || extractedPath.startsWith('/')) {
finalPathToAdd = extractedPath.startsWith('/') ? extractedPath.slice(1) : extractedPath;
} else {
const absolutePath = path.resolve(fileDir, extractedPath);
finalPathToAdd = path.relative(outputDir, absolutePath);
}
if (finalPathToAdd && !shouldExcludeFile(finalPathToAdd)) {
referencedFiles.add(finalPathToAdd.replace(/\\/g, '/'));
}
}
});
}
function processManifest() {
const manifestPath = path.join(outputDir, 'manifest.json');
if (fs.existsSync(manifestPath)) {
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
const checkManifestField = (obj) => {
if (typeof obj === 'string' && /\.(js|css|png|jpg|jpeg|gif|svg)$/i.test(obj)) {
const normalizedPath = obj.startsWith('/') ? obj.slice(1) : obj;
if (!shouldExcludeFile(normalizedPath)) {
referencedFiles.add(normalizedPath);
}
} else if (Array.isArray(obj)) {
obj.forEach(item => checkManifestField(item));
} else if (typeof obj === 'object' && obj !== null) {
Object.values(obj).forEach(value => checkManifestField(value));
}
};
if (manifest.content_scripts) {
manifest.content_scripts.forEach(script => {
if (script.js) {
script.js.forEach(js => {
const normalizedPath = js.startsWith('/') ? js.slice(1) : js;
referencedFiles.add(normalizedPath);
});
}
if (script.css) {
script.css.forEach(css => {
const normalizedPath = css.startsWith('/') ? css.slice(1) : css;
referencedFiles.add(normalizedPath);
});
}
});
}
checkManifestField(manifest);
}
}
function runTests() {
if (!isSilentDetect) console.log('\n运行单元测试...');
assert.strictEqual(shouldExcludeFile('path/to/content-script.js'), true, 'Should exclude content-script.js');
assert.strictEqual(shouldExcludeFile('path/to/content-script.css'), true, 'Should exclude content-script.css');
assert.strictEqual(shouldExcludeFile('path/to/node_modules/file.js'), true, 'Should exclude node_modules files');
assert.strictEqual(shouldExcludeFile('path/to/normal.js'), false, 'Should not exclude normal files');
const testContent = `
<link rel="stylesheet" href="./style.css">
<script src="../js/script.js"></script>
<img src="/images/test.png">
<div style="background: url('./bg.jpg')">
<div style="font: url('./font.woff2')">
@import '../common.css';
<img src="chrome-extension://abcdefgh/static/icon.png">
`;
const testFilePath = path.join(outputDir, 'test/index.html');
referencedFiles.clear();
findReferences(testContent, testFilePath);
const refs = Array.from(referencedFiles);
assert(refs.includes('test/style.css'), 'Should handle relative path with ./');
assert(refs.includes('js/script.js'), 'Should handle relative path with ../');
assert(refs.includes('images/test.png'), 'Should handle absolute path');
assert(refs.includes('test/bg.jpg'), 'Should handle url() in CSS');
assert(refs.includes('test/font.woff2'), 'Should handle font url() in CSS');
assert(refs.includes('common.css'), 'Should handle @import in CSS');
assert(refs.includes('static/icon.png'), 'Should handle chrome-extension urls');
referencedFiles.clear();
if (!isSilentDetect) console.log('单元测试通过!');
}
try {
runTests();
getAllFiles(outputDir);
processManifest();
const filesToScan = fs.readdirSync(outputDir, { recursive: true })
.filter(file => !shouldExcludeFile(file));
filesToScan.forEach(file => {
const fullPath = path.join(outputDir, file);
if (fs.statSync(fullPath).isFile() && /\.(html|js|css|json)$/i.test(file)) {
const content = fs.readFileSync(fullPath, 'utf8');
findReferences(content, fullPath);
}
});
const unusedFiles = Array.from(allFiles).filter(file => !referencedFiles.has(file));
if (unusedFiles.length > 0) {
if (!isSilentDetect) console.log('\n发现以下未被引用的文件:');
if (!isSilentDetect) console.log('=====================================');
let totalUnusedSize = 0;
unusedFiles.forEach(file => {
if (!isSilentDetect) console.log(file);
try {
const fullPath = path.join(outputDir, file);
if (fs.existsSync(fullPath)) {
totalUnusedSize += fs.statSync(fullPath).size;
fs.unlinkSync(fullPath);
if (!isSilentDetect) console.log(` -> 已删除: ${file}`);
} else {
if (!isSilentDetect) console.warn(` -> 文件不存在,无法删除或统计大小: ${file}`);
}
} catch (err) {
if (!isSilentDetect) console.warn(`无法删除或获取文件大小: ${file}`, err);
}
});
if (!isSilentDetect) console.log('=====================================');
if (!isSilentDetect) console.log(`共清理 ${unusedFiles.length} 个未使用的文件,释放空间: ${pretty(totalUnusedSize)}`);
if (process.env.DEBUG && !isSilentDetect) {
console.log('\n调试信息:');
console.log('----------------------------------------');
console.log('所有文件:');
Array.from(allFiles).forEach(file => console.log(`- ${file}`));
console.log('----------------------------------------');
console.log('被引用的文件:');
Array.from(referencedFiles).forEach(file => console.log(`- ${file}`));
}
} else {
if (!isSilentDetect) console.log('\n没有发现未使用的文件!');
}
} catch (error) {
if (!isSilentDetect) console.error('检测过程中发生错误:', error);
}
cb && cb();
}
// Firefox前置处理
function firefoxPreprocess(cb) {
const destDir = 'output-firefox/apps';
buildManifest('firefox', destDir);
['background/background.js', 'options/index.js'].forEach(file => {
const filePath = path.join(destDir, file);
if (!fs.existsSync(filePath)) return;
const source = fs.readFileSync(filePath, 'utf-8');
const patched = source.replace(/chrome\.runtime\.requestUpdateCheck/g, `chrome.runtime[${FIREFOX_REQUEST_UPDATE_CHECK_KEY}]`);
if (patched !== source) {
fs.writeFileSync(filePath, patched);
}
});
FIREFOX_REMOVE_TOOLS.forEach(tool => {
const toolDir = path.join(destDir, tool);
if (fs.existsSync(toolDir)) {
shell.exec(`rm -rf ${toolDir}`);
}
});
cb();
}
// chrome前置处理
function chromePreprocess(cb) {
const destDir = 'output-chrome/apps';
buildManifest('chrome', destDir);
cb();
}
// edge前置处理
function edgePreprocess(cb) {
const destDir = 'output-edge/apps';
buildManifest('edge', destDir);
cb();
}
// 注册任务
// Chrome默认打包
function cleanChrome() { return cleanOutput('output-chrome'); }
function copyChrome() { return copyAssets('output-chrome/apps'); }
function cssChrome() { return processCss('output-chrome/apps'); }
function jsChrome() { return processJs('output-chrome/apps'); }
function htmlChrome() { return processHtml('output-chrome/apps'); }
function jsonChrome() { return processJson('output-chrome/apps'); }
function detectChrome(cb) { detectUnusedFiles('output-chrome/apps', cb); }
function zipChrome(cb) { zipPackage('output-chrome', cb); }
gulp.task('default',
gulp.series(
cleanChrome,
copyChrome,
gulp.parallel(cssChrome, jsChrome, htmlChrome, jsonChrome),
chromePreprocess,
setSilentDetect,
detectChrome,
unsetSilentDetect,
zipChrome
)
);
// ------------------------------------------------------------
// edge打包
function cleanEdge() { return cleanOutput('output-edge'); }
function copyEdge() { return copyAssets('output-edge/apps'); }
function cssEdge() { return processCss('output-edge/apps'); }
function jsEdge() { return processJs('output-edge/apps'); }
function htmlEdge() { return processHtml('output-edge/apps'); }
function jsonEdge() { return processJson('output-edge/apps'); }
function detectEdge(cb) { detectUnusedFiles('output-edge/apps', cb); }
function zipEdge(cb) { zipPackage('output-edge', cb); }
gulp.task('edge',
gulp.series(
cleanEdge,
copyEdge,
gulp.parallel(cssEdge, jsEdge, htmlEdge, jsonEdge),
edgePreprocess,
setSilentDetect,
detectEdge,
unsetSilentDetect,
zipEdge
)
);
// Firefox打包主任务
function cleanFirefox() { return cleanOutput('output-firefox'); }
function copyFirefox() { return copyAssets('output-firefox/apps'); }
function cssFirefox() { return processCss('output-firefox/apps'); }
function jsFirefox() { return processJs('output-firefox/apps'); }
function htmlFirefox() { return processHtml('output-firefox/apps'); }
function jsonFirefox() { return processJson('output-firefox/apps'); }
function detectFirefox(cb) { detectUnusedFiles('output-firefox/apps', cb); }
function zipFirefox(cb) { zipPackage('output-firefox', cb); }
gulp.task('firefox',
gulp.series(
cleanFirefox,
copyFirefox,
gulp.parallel(cssFirefox, jsFirefox, htmlFirefox, jsonFirefox),
firefoxPreprocess,
setSilentDetect,
detectFirefox,
unsetSilentDetect,
zipFirefox
)
);