-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathrollup.config.ts
323 lines (282 loc) · 9.06 KB
/
rollup.config.ts
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
import fs from 'node:fs';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import shell from 'shelljs';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import { babel } from '@rollup/plugin-babel';
import styles from 'rollup-plugin-styles';
import json from '@rollup/plugin-json';
import alias from '@rollup/plugin-alias';
import replace from '@rollup/plugin-replace';
import { watchExternal } from 'rollup-plugin-watch-external';
import type {
InputPluginOption,
OutputPluginOption,
RollupOptions,
} from 'rollup';
import { parse as parseMd } from 'marked';
import { inputPlugins, outputPlugins, solidSvg } from './src/rollup-plugin';
import { getMetaData, updateReadme } from './src/rollup-plugin/metaHeader';
const __dirname = dirname(fileURLToPath(import.meta.url));
const isDevMode = process.env.NODE_ENV === 'development';
const latestChangeHtml = await (() => {
const md = fs
.readFileSync(resolve(__dirname, `docs/.other/LatestChange.md`))
.toString();
const newMd = md
.match(/^### [^[].+?$|^\* .+?$/gm)!
.map((mdText) => {
switch (mdText[0]) {
case '#':
return mdText
.replaceAll('Features', '新增')
.replaceAll('Bug Fixes', '修复')
.replaceAll('Performance Improvements', '优化');
case '*':
return mdText.replaceAll(/(?<=^\* ):\w+?: |(?<=^.*)\(\[.*/g, '');
default:
return '';
}
})
.join('\n\n');
return parseMd(newMd);
})();
const { meta, createMetaHeader } = getMetaData(isDevMode);
const generateScopedName = '[local]___[hash:base64:5]';
/** 单独打包的代码 */
const packlist = [
'helper/languages',
'helper',
'request',
'components/Manga',
'components/IconButton',
'components/Fab',
'components/Toast',
'userscript/dmzjApi',
'userscript/detectAd',
'userscript/main',
'worker/ImageRecognition',
'worker/detectAd',
'userscript/otherSite',
'userscript/ehTagRules',
];
const babelConfig = {
presets: ['@babel/preset-env', '@babel/preset-typescript', 'solid'],
plugins: [
'@babel/plugin-transform-runtime',
[
'@babel/plugin-proposal-import-attributes-to-assertions',
{ deprecatedAssertSyntax: true },
],
],
};
const baseOptions = {
treeshake: true,
external: [
...Object.keys(meta.resource ?? {}),
...packlist,
'dmzjDecrypt',
'dmzjApi',
'main',
/^solid/,
],
input: '',
// 忽略使用 eval 的警告
onwarn: undefined as RollupOptions['onwarn'],
plugins: [] as InputPluginOption,
output: {
file: '',
format: 'cjs',
strict: false,
generatedCode: 'es2015',
extend: true,
plugins: [] as OutputPluginOption[],
},
} satisfies RollupOptions;
export const buildOptions = (
path: string,
watchFiles?: string[],
fn?: (options: typeof baseOptions) => RollupOptions,
): RollupOptions => {
const options = structuredClone(baseOptions);
options.input = path.startsWith('src')
? path
: resolve(__dirname, 'src', path);
options.plugins = [
replace({
values: {
isDevMode: `${isDevMode}`,
'process.env.NODE_ENV': isDevMode ? `'development'` : `'production'`,
'inject@LatestChange': latestChangeHtml,
},
preventAssignment: true,
}),
alias({
entries: {
helper: resolve(__dirname, 'src/helper'),
worker: resolve(__dirname, 'src/worker'),
},
}),
json({ namedExports: false, compact: true }),
nodeResolve({ browser: true, extensions: ['.js', '.ts', '.tsx'] }),
commonjs({ strictRequires: 'auto' }),
styles({ mode: 'extract', modules: { generateScopedName } }),
solidSvg(),
// ts({ transpiler: 'babel', transpileOnly: true, babelConfig }),
babel({
babelHelpers: 'runtime',
extensions: ['.ts', '.tsx'],
exclude: ['node_modules/**'],
...babelConfig,
}),
...inputPlugins,
watchFiles && isDevMode && watchExternal({ entries: watchFiles }),
];
Object.assign(options.output, {
file: `dist/${path.replace(/(\/index)?\.tsx?/, '')}.js`,
plugins: [
...outputPlugins,
{
name: 'selfPlugin',
renderChunk(rawCode) {
let code = rawCode;
switch (path) {
case 'index': {
updateReadme();
if (isDevMode)
code = `
console.time('脚本启动消耗时间');
${code}
console.timeEnd('脚本启动消耗时间');
`;
const importCode = fs
.readFileSync(`dist/userscript/import.js`)
.toString()
.replaceAll('require$1', 'require');
code = `${createMetaHeader(meta)}\n${importCode}\n${code}`;
break;
}
case 'dev':
code =
createMetaHeader({
...meta,
name: `${meta.name}Test`,
namespace: `${meta.namespace}Test`,
updateURL: undefined,
downloadURL: undefined,
}) + code;
break;
}
return code;
},
},
],
});
options.onwarn = (warning, warn) => {
if (warning.code !== 'EVAL') warn(warning);
};
return fn ? fn(options) : options;
};
// 清空 dist 文件夹
shell.rm('-rf', resolve(__dirname, 'dist/*'));
// 创建 dist 的文件服务器
if (isDevMode)
shell.exec('serve dist --cors -l 2405', { async: true, silent: true });
const optionList: RollupOptions[] = [
buildOptions('dev'),
...packlist.map((path) => buildOptions(path)),
...fs
.readdirSync('src/site', { withFileTypes: true })
.map((item) =>
buildOptions(
item.isFile() ? `site/${item.name}` : `site/${item.name}/index.tsx`,
),
),
buildOptions(
'userscript/import',
packlist.map((path) => `dist/${path}.js`),
(options) => {
options.output.plugins.unshift({
name: 'selfImport',
renderChunk(rawCode) {
return rawCode.replace(
/\s+\/\/ import list/,
packlist
.map((path) => {
if (path === 'userscript/main') return '';
return `\ncase '${path}':\ncode = \`inject('${path}')\`;\nbreak;`;
})
.join(''),
);
},
});
return options;
},
),
buildOptions('index', ['dist/**/*', '!dist/index.*js']),
];
if (!isDevMode)
optionList.push(
buildOptions('index', ['dist/**/*', '!dist/index.js'], (options) => {
options.output.file = 'dist/adguard.js';
Reflect.deleteProperty(options.output, 'dir');
options.output.plugins.push({
name: 'selfAdGuardPlugin',
renderChunk(rawCode) {
let code = rawCode;
// 不知道为啥俄罗斯访问不了 npmmirror
// https://github.com/hymbz/ComicReadScript/issues/170
// 或许和 unpkg 功能的白名单<https://github.com/cnpm/unpkg-white-list>有关
// <https://sleazyfork.org/zh-CN/scripts/374903/discussions/248665>
// 可能再过一段时间就能恢复?但总之目前只能先改用 jsdelivr
code = code.replaceAll(
/@resource .+? https:\/\/registry.npmmirror.com\/.+(?=\n)/g,
(text) =>
text
.replace('registry.npmmirror.com/', 'cdn.jsdelivr.net/npm/')
.replace(/(npm\/[^/]+)\//, '$1@')
.replace('files/', ''),
);
// AdGuard 无法支持简易阅读模式,所以改为只在支持网站上运行
const indexCode = fs.readFileSync(
resolve(__dirname, 'src/index.ts'),
'utf8',
);
const matchList = [
...indexCode.matchAll(/(?<=\n\s+case ').+?(?=':)/g),
]
.filter(([url]) => !url.includes('siteUrl#'))
.flatMap(([url]) => `// @match *://${url}/*`);
code = code.replace(
/\/\/ @match \s+ \*:\/\/\*\/\*/,
matchList.join('\n'),
);
// 删掉不支持的菜单 api
code = code.replaceAll(
/\/\/ @grant \s+ GM\.(registerMenuCommand|unregisterMenuCommand)\n/g,
'',
);
// 把菜单 api 的调用也改掉
code = code.replaceAll(
/await GM\.(registerMenuCommand|unregisterMenuCommand)/g,
'console.debug',
);
// 脚本更新链接也换掉
code = code.replaceAll(
'/raw/master/ComicRead.user.js',
'/raw/master/ComicRead-AdGuard.user.js',
);
// 不知道为啥会提示 'Access to function "GM_getValue" is not allowed.'
// 明明我用的是 GM.getValue。虽然好像对功能没有影响,但以防万一还是加上吧
code = code.replace(
/\n(?=\/\/ @grant)/,
'\n// @grant GM_getValue\n// @grant GM_setValue\n',
);
return code;
},
});
return options;
}),
);
export default optionList;