@lynker-desktop/electron-sdk 0.0.9-alpha.6 → 0.0.9-alpha.60

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.
Files changed (68) hide show
  1. package/README.md +160 -1
  2. package/common/index.d.ts +96 -0
  3. package/common/index.d.ts.map +1 -1
  4. package/common/index.js.map +1 -1
  5. package/esm/common/index.d.ts +96 -0
  6. package/esm/common/index.d.ts.map +1 -1
  7. package/esm/common/index.js.map +1 -1
  8. package/esm/main/clipboard.d.ts +32 -0
  9. package/esm/main/clipboard.d.ts.map +1 -0
  10. package/esm/main/clipboard.js +963 -0
  11. package/esm/main/clipboard.js.map +1 -0
  12. package/esm/main/downloader.d.ts +186 -0
  13. package/esm/main/downloader.d.ts.map +1 -0
  14. package/esm/main/downloader.js +561 -0
  15. package/esm/main/downloader.js.map +1 -0
  16. package/esm/main/index.d.ts +18 -67
  17. package/esm/main/index.d.ts.map +1 -1
  18. package/esm/main/index.js +48 -202
  19. package/esm/main/index.js.map +1 -1
  20. package/esm/main/resource-cache.d.ts +215 -0
  21. package/esm/main/resource-cache.d.ts.map +1 -0
  22. package/esm/main/resource-cache.js +765 -0
  23. package/esm/main/resource-cache.js.map +1 -0
  24. package/esm/main/store.d.ts +8 -0
  25. package/esm/main/store.d.ts.map +1 -0
  26. package/esm/main/store.js +53 -0
  27. package/esm/main/store.js.map +1 -0
  28. package/esm/main/video-downloader.d.ts +39 -0
  29. package/esm/main/video-downloader.d.ts.map +1 -0
  30. package/esm/main/video-downloader.js +505 -0
  31. package/esm/main/video-downloader.js.map +1 -0
  32. package/esm/preload/index.js +19 -1
  33. package/esm/preload/index.js.map +1 -1
  34. package/esm/renderer/index.d.ts +8 -0
  35. package/esm/renderer/index.d.ts.map +1 -1
  36. package/esm/renderer/index.js +25 -0
  37. package/esm/renderer/index.js.map +1 -1
  38. package/main/clipboard.d.ts +32 -0
  39. package/main/clipboard.d.ts.map +1 -0
  40. package/main/clipboard.js +963 -0
  41. package/main/clipboard.js.map +1 -0
  42. package/main/downloader.d.ts +186 -0
  43. package/main/downloader.d.ts.map +1 -0
  44. package/main/downloader.js +561 -0
  45. package/main/downloader.js.map +1 -0
  46. package/main/index.d.ts +18 -67
  47. package/main/index.d.ts.map +1 -1
  48. package/main/index.js +51 -205
  49. package/main/index.js.map +1 -1
  50. package/main/resource-cache.d.ts +215 -0
  51. package/main/resource-cache.d.ts.map +1 -0
  52. package/main/resource-cache.js +765 -0
  53. package/main/resource-cache.js.map +1 -0
  54. package/main/store.d.ts +8 -0
  55. package/main/store.d.ts.map +1 -0
  56. package/main/store.js +53 -0
  57. package/main/store.js.map +1 -0
  58. package/main/video-downloader.d.ts +39 -0
  59. package/main/video-downloader.d.ts.map +1 -0
  60. package/main/video-downloader.js +510 -0
  61. package/main/video-downloader.js.map +1 -0
  62. package/package.json +9 -5
  63. package/preload/index.js +19 -1
  64. package/preload/index.js.map +1 -1
  65. package/renderer/index.d.ts +8 -0
  66. package/renderer/index.d.ts.map +1 -1
  67. package/renderer/index.js +25 -0
  68. package/renderer/index.js.map +1 -1
@@ -0,0 +1,765 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import md5 from 'md5';
4
+ import mime from 'mime-types';
5
+ import { ipcMain } from 'electron';
6
+ import { DownloaderHelper } from 'node-downloader-helper';
7
+
8
+ /**
9
+ * 默认文件扩展名
10
+ */
11
+ const DEFAULT_EXT = '.res';
12
+ /**
13
+ * 默认 MIME 类型
14
+ */
15
+ const DEFAULT_MIME_TYPE = 'application/octet-stream';
16
+ /**
17
+ * 最大重定向次数
18
+ */
19
+ const MAX_REDIRECTS = 5;
20
+ /**
21
+ * 默认配置
22
+ */
23
+ const DEFAULT_OPTIONS = {
24
+ cacheDir: '',
25
+ cacheTTL: 24 * 60 * 60 * 1000,
26
+ // 图片格式:png, jpg/jpeg, webp, gif, svg, ico, bmp, avif, heic, heif, tiff, tif
27
+ // 字体格式:woff, woff2, ttf, eot, otf
28
+ // 视频格式:mp4, webm, ogg, mov, avi, mkv, flv, m4v, 3gp
29
+ // 音频格式:mp3, wav, aac, m4a, flac, opus, wma
30
+ // 样式和脚本:css, js, json, xml, txt
31
+ // Web资源:wasm, map (source map)
32
+ // 文档格式:pdf
33
+ // 压缩文件:zip, 7z, rar, tar, gz, bz2
34
+ match: /\.(png|jpe?g|webp|gif|svg|ico|bmp|avif|heic|heif|tiff?|woff2?|ttf|eot|otf|mp4|webm|ogg|mov|avi|mkv|flv|m4v|3gp|mp3|wav|aac|m4a|flac|opus|wma|css|js|json|xml|txt|wasm|map|pdf|zip|7z|rar|tar|gz|bz2)(\?.*)?$/i,
35
+ allowedOrigins: null,
36
+ };
37
+ /**
38
+ * 资源缓存类:拦截并缓存静态资源,提升加载性能
39
+ */
40
+ class ResourceCache {
41
+ /**
42
+ * 构造函数
43
+ * @param session Electron session
44
+ * @param options 缓存配置
45
+ */
46
+ constructor(session, options) {
47
+ this.cacheHost = `${ResourceCache.scheme}://-`;
48
+ /** 正在下载的 URL 集合(避免重复下载) */
49
+ this._downloadingUrls = new Set();
50
+ if (!session)
51
+ throw new Error('ResourceCache: session is required');
52
+ this.session = session;
53
+ // 合并配置,保证类型安全
54
+ this.options = {
55
+ ...DEFAULT_OPTIONS,
56
+ ...options,
57
+ cacheDir: options.cacheDir,
58
+ cacheTTL: options.cacheTTL ?? DEFAULT_OPTIONS.cacheTTL,
59
+ match: options.match ?? DEFAULT_OPTIONS.match,
60
+ allowedOrigins: options.allowedOrigins ?? DEFAULT_OPTIONS.allowedOrigins,
61
+ };
62
+ if (!this.options.cacheDir) {
63
+ throw new Error('ResourceCache: cacheDir is required');
64
+ }
65
+ // 确保缓存目录存在
66
+ if (!fs.existsSync(this.options.cacheDir)) {
67
+ fs.mkdirSync(this.options.cacheDir, { recursive: true });
68
+ }
69
+ this._registerInterceptor();
70
+ // 异步清理过期缓存,不阻塞初始化
71
+ this._cleanOldCache().catch(err => {
72
+ console.log('初始化时清理过期缓存失败:', err);
73
+ });
74
+ ipcMain.handle('core:cache', async (event, options) => {
75
+ try {
76
+ switch (options.method) {
77
+ case 'clear':
78
+ return await this.clearCache();
79
+ case 'add': {
80
+ const { id } = options;
81
+ const sender = event.sender;
82
+ const urls = Array.isArray(options.urls) ? options.urls : options.urls ? [options.urls] : [];
83
+ const data = await this.addCacheUrls(urls, options.force ?? false, true, (data) => {
84
+ try {
85
+ if (sender) {
86
+ if (typeof sender?.send === 'function') {
87
+ sender?.send?.(`core:cache:progress`, {
88
+ id,
89
+ data
90
+ });
91
+ }
92
+ }
93
+ }
94
+ catch (error) {
95
+ console.log('发送缓存进度回调失败:', error);
96
+ }
97
+ });
98
+ return Array.isArray(options.urls) ? data : data[0];
99
+ }
100
+ case 'delete': {
101
+ const urls = Array.isArray(options.urls) ? options.urls : options.urls ? [options.urls] : [];
102
+ const data = await this.deleteCacheUrls(urls);
103
+ return Array.isArray(options.urls) ? data : data[0];
104
+ }
105
+ case 'stats':
106
+ return await this.getCacheStats();
107
+ default:
108
+ return undefined;
109
+ }
110
+ }
111
+ catch (error) {
112
+ return { success: false, error: error instanceof Error ? error.message : '未知错误' };
113
+ }
114
+ });
115
+ }
116
+ /**
117
+ * 获取缓存统计信息(异步版本,性能更好)
118
+ */
119
+ async getCacheStats() {
120
+ try {
121
+ const files = await fs.promises.readdir(this.options.cacheDir);
122
+ if (files.length === 0) {
123
+ return { size: 0, totalSize: 0 };
124
+ }
125
+ // 并行获取文件信息,提升性能
126
+ const fileInfos = await Promise.allSettled(files.map(async (file) => {
127
+ const filePath = path.join(this.options.cacheDir, file);
128
+ try {
129
+ const stats = await fs.promises.stat(filePath);
130
+ return { file, filePath, size: stats.size };
131
+ }
132
+ catch (error) {
133
+ return { file, filePath, size: 0, error };
134
+ }
135
+ }));
136
+ const validInfos = fileInfos
137
+ .filter((r) => r.status === 'fulfilled')
138
+ .map(r => r.value);
139
+ return {
140
+ size: validInfos.length,
141
+ totalSize: validInfos.reduce((sum, info) => sum + info.size, 0)
142
+ };
143
+ }
144
+ catch (error) {
145
+ console.log('获取缓存统计信息失败:', error);
146
+ return { size: 0, totalSize: 0 };
147
+ }
148
+ }
149
+ /**
150
+ * 获取资源匹配函数(带缓存,避免重复创建)
151
+ */
152
+ _getMatchFunction() {
153
+ if (this._cachedMatchFunction) {
154
+ return this._cachedMatchFunction;
155
+ }
156
+ const matcher = this.options.match;
157
+ if (typeof matcher === 'function') {
158
+ this._cachedMatchFunction = matcher;
159
+ }
160
+ else if (matcher instanceof RegExp) {
161
+ this._cachedMatchFunction = (url) => matcher.test(url);
162
+ }
163
+ else {
164
+ this._cachedMatchFunction = () => false;
165
+ }
166
+ return this._cachedMatchFunction;
167
+ }
168
+ /**
169
+ * 获取来源校验函数(带缓存,避免重复创建)
170
+ */
171
+ _getOriginAllowFunction() {
172
+ if (this._cachedOriginFunction) {
173
+ return this._cachedOriginFunction;
174
+ }
175
+ const origins = this.options.allowedOrigins;
176
+ if (!origins) {
177
+ this._cachedOriginFunction = () => true;
178
+ }
179
+ else if (typeof origins === 'function') {
180
+ this._cachedOriginFunction = origins;
181
+ }
182
+ else {
183
+ const prefixList = origins.map(o => o.toLowerCase());
184
+ this._cachedOriginFunction = (url) => {
185
+ try {
186
+ const origin = new URL(url).origin.toLowerCase();
187
+ return prefixList.some(prefix => origin.startsWith(prefix));
188
+ }
189
+ catch {
190
+ return false;
191
+ }
192
+ };
193
+ }
194
+ return this._cachedOriginFunction;
195
+ }
196
+ /**
197
+ * 获取缓存文件路径
198
+ * @param url 资源URL
199
+ * @param customExt 自定义文件扩展名(可选,用于 base64 URL)
200
+ */
201
+ getCachedPath(url, customExt) {
202
+ const md5Str = md5(url);
203
+ let ext = '.res';
204
+ if (customExt) {
205
+ // 如果提供了自定义扩展名,使用它
206
+ ext = customExt.startsWith('.') ? customExt : `.${customExt}`;
207
+ }
208
+ else {
209
+ // 尝试从 URL 中提取扩展名
210
+ try {
211
+ const urlObj = new URL(url);
212
+ ext = path.extname(urlObj.pathname) || DEFAULT_EXT;
213
+ }
214
+ catch {
215
+ // 如果 URL 解析失败(可能是 base64 data URL),使用默认扩展名
216
+ ext = DEFAULT_EXT;
217
+ }
218
+ }
219
+ return {
220
+ filePath: path.join(this.options.cacheDir, `${md5Str}${ext}`),
221
+ hostPath: `${this.cacheHost}/${md5Str}${ext}`,
222
+ };
223
+ }
224
+ /**
225
+ * 判断缓存是否有效(同步版本,用于拦截器)
226
+ * @param filePath 缓存文件路径
227
+ */
228
+ isCacheValid(filePath) {
229
+ try {
230
+ if (!fs.existsSync(filePath))
231
+ return false;
232
+ const stat = fs.statSync(filePath);
233
+ return Date.now() - stat.mtimeMs < this.options.cacheTTL;
234
+ }
235
+ catch {
236
+ return false;
237
+ }
238
+ }
239
+ /**
240
+ * 判断缓存是否有效(异步版本,性能更好)
241
+ * @param filePath 缓存文件路径
242
+ */
243
+ async isCacheValidAsync(filePath) {
244
+ try {
245
+ const stat = await fs.promises.stat(filePath);
246
+ return Date.now() - stat.mtimeMs < this.options.cacheTTL;
247
+ }
248
+ catch {
249
+ return false;
250
+ }
251
+ }
252
+ /**
253
+ * 下载资源到本地缓存(异步版本,返回 Promise)
254
+ * @param url 资源URL
255
+ * @param filePath 本地缓存路径
256
+ * @param redirectCount 当前重定向次数(内部使用)
257
+ * @param onProgress 下载进度回调函数(可选)
258
+ * @returns Promise<void> 下载完成或失败
259
+ */
260
+ downloadResourceAsync(url, filePath, redirectCount = 0, onProgress) {
261
+ // 检查是否正在下载,避免重复下载
262
+ if (this._downloadingUrls.has(url)) {
263
+ return Promise.reject(new Error(`资源正在下载中: ${url}`));
264
+ }
265
+ // 检查重定向次数限制
266
+ if (redirectCount >= MAX_REDIRECTS) {
267
+ return Promise.reject(new Error(`重定向次数超过限制 (${MAX_REDIRECTS}): ${url}`));
268
+ }
269
+ this._downloadingUrls.add(url);
270
+ return new Promise((resolve, reject) => {
271
+ const tempFilePath = `${filePath}.cache`;
272
+ const downloadDir = path.dirname(tempFilePath);
273
+ const downloadFileName = path.basename(tempFilePath);
274
+ // 确保目录存在
275
+ if (!fs.existsSync(downloadDir)) {
276
+ fs.mkdirSync(downloadDir, { recursive: true });
277
+ }
278
+ // 创建下载器实例
279
+ const dl = new DownloaderHelper(url, downloadDir, {
280
+ fileName: downloadFileName,
281
+ retry: { maxRetries: 3, delay: 1000 },
282
+ // 超时设置:10 分钟(600000 毫秒)
283
+ // 对于视频等大文件,需要更长的超时时间
284
+ // 如果 10 分钟内没有任何数据传输,才会超时
285
+ timeout: 600000,
286
+ override: true, // 覆盖已存在的文件
287
+ httpRequestOptions: {
288
+ // 允许重定向
289
+ followRedirect: true,
290
+ maxRedirects: MAX_REDIRECTS
291
+ }
292
+ });
293
+ // 监听下载进度
294
+ if (onProgress) {
295
+ dl.on('progress', (stats) => {
296
+ try {
297
+ // stats 包含: progress (百分比), downloaded (已下载字节), total (总字节), speed (速度)
298
+ onProgress({
299
+ url,
300
+ downloaded: stats.downloaded || 0,
301
+ total: stats.total || 0,
302
+ percentage: stats.progress !== undefined ? Math.round(stats.progress) : -1,
303
+ speed: stats.speed || 0
304
+ });
305
+ }
306
+ catch (error) {
307
+ // 忽略回调中的错误,避免影响下载
308
+ console.error('进度回调执行失败:', error);
309
+ }
310
+ });
311
+ }
312
+ // 监听下载完成
313
+ dl.on('end', () => {
314
+ this._downloadingUrls.delete(url);
315
+ // 将临时文件重命名为最终文件
316
+ fs.rename(tempFilePath, filePath, (renameErr) => {
317
+ if (renameErr) {
318
+ reject(new Error(`缓存文件重命名失败 from ${tempFilePath} to ${filePath}: ${renameErr.message}`));
319
+ }
320
+ else {
321
+ resolve();
322
+ }
323
+ });
324
+ });
325
+ // 监听下载错误
326
+ dl.on('error', (err) => {
327
+ this._downloadingUrls.delete(url);
328
+ // 清理临时文件
329
+ fs.promises.unlink(tempFilePath).catch(() => {
330
+ // 忽略删除失败
331
+ });
332
+ reject(err instanceof Error ? err : new Error(`下载失败: ${url}`));
333
+ });
334
+ // 监听下载停止(取消)
335
+ dl.on('stop', () => {
336
+ this._downloadingUrls.delete(url);
337
+ // 清理临时文件
338
+ fs.promises.unlink(tempFilePath).catch(() => {
339
+ // 忽略删除失败
340
+ });
341
+ reject(new Error(`下载已停止: ${url}`));
342
+ });
343
+ // 开始下载
344
+ dl.start().catch((err) => {
345
+ this._downloadingUrls.delete(url);
346
+ reject(err instanceof Error ? err : new Error(`启动下载失败: ${url}`));
347
+ });
348
+ });
349
+ }
350
+ /**
351
+ * 下载资源到本地缓存(同步版本,不返回 Promise,用于拦截器)
352
+ * @param url 资源URL
353
+ * @param filePath 本地缓存路径
354
+ */
355
+ downloadResource(url, filePath) {
356
+ // 异步执行,不等待完成
357
+ // 如果正在下载,跳过(避免重复下载)
358
+ if (this._downloadingUrls.has(url)) {
359
+ return;
360
+ }
361
+ this.downloadResourceAsync(url, filePath).catch(() => {
362
+ // 静默处理错误,避免日志过多
363
+ });
364
+ }
365
+ /**
366
+ * 从文件扩展名获取 MIME 类型
367
+ * @param ext 文件扩展名(带或不带点)
368
+ * @returns MIME 类型
369
+ */
370
+ _getMimeTypeFromExt(ext) {
371
+ const cleanExt = ext.replace(/^\./, '').toLowerCase();
372
+ const mimeType = mime.lookup(cleanExt);
373
+ return mimeType || DEFAULT_MIME_TYPE;
374
+ }
375
+ /**
376
+ * 检测并处理 base64 data URL
377
+ * @param url 资源URL
378
+ * @returns 如果是 base64 URL,返回 true、文件扩展名、MIME 类型和数据;否则返回 false
379
+ */
380
+ _isBase64DataUrl(url) {
381
+ if (!url.startsWith('data:')) {
382
+ return { isBase64: false };
383
+ }
384
+ try {
385
+ // 解析 data URL 格式:data:[<mediatype>][;base64],<data>
386
+ const commaIndex = url.indexOf(',');
387
+ if (commaIndex === -1) {
388
+ return { isBase64: false };
389
+ }
390
+ const header = url.substring(0, commaIndex);
391
+ const data = url.substring(commaIndex + 1);
392
+ // 检查是否包含 base64 标识
393
+ if (!header.includes('base64')) {
394
+ return { isBase64: false };
395
+ }
396
+ // 从 mediatype 中提取文件扩展名和 MIME 类型
397
+ // 例如:data:image/png;base64 -> png, image/png
398
+ // 例如:data:image/jpeg;base64 -> jpeg, image/jpeg
399
+ let ext = DEFAULT_EXT.replace(/^\./, '');
400
+ let mimeType = DEFAULT_MIME_TYPE;
401
+ const mimeMatch = header.match(/data:([^;]+)/);
402
+ if (mimeMatch && mimeMatch[1]) {
403
+ mimeType = mimeMatch[1];
404
+ // 使用 mime-types 包从 MIME 类型获取扩展名
405
+ const extension = mime.extension(mimeType);
406
+ if (extension) {
407
+ ext = extension;
408
+ }
409
+ }
410
+ return { isBase64: true, ext, mimeType, data };
411
+ }
412
+ catch (error) {
413
+ return { isBase64: false };
414
+ }
415
+ }
416
+ /**
417
+ * 保存 base64 数据到文件
418
+ * @param base64Data base64 编码的数据
419
+ * @param filePath 目标文件路径
420
+ */
421
+ async _saveBase64ToFile(base64Data, filePath) {
422
+ try {
423
+ // 解码 base64 数据
424
+ const buffer = Buffer.from(base64Data, 'base64');
425
+ // 使用 Promise 版本的 writeFile
426
+ // Buffer 继承自 Uint8Array,可以直接使用
427
+ await fs.promises.writeFile(filePath, buffer);
428
+ }
429
+ catch (error) {
430
+ throw new Error(`保存 base64 文件失败: ${error instanceof Error ? error.message : '未知错误'}`);
431
+ }
432
+ }
433
+ /**
434
+ * 手动缓存指定 URL 的资源
435
+ * @param url 要缓存的资源 URL(支持普通 URL 和 base64 data URL)
436
+ * @param force 是否强制重新下载,即使缓存有效(默认 false)
437
+ * @param ignoreOrigin 是否忽略来源检查(默认 false)
438
+ * @param onDownloadProgress 下载进度回调函数(可选)
439
+ * @returns Promise<{ filePath: string, hostPath: string, mimeType: string, size: number }> 返回缓存文件路径、主机路径、MIME 类型和文件大小
440
+ * @throws 如果 URL 不匹配缓存规则或来源不允许,会抛出错误
441
+ */
442
+ async cacheUrl(url, force = false, ignoreOrigin = false, onDownloadProgress) {
443
+ // 检查是否是 base64 data URL
444
+ const base64Info = this._isBase64DataUrl(url);
445
+ if (base64Info.isBase64) {
446
+ // 处理 base64 data URL
447
+ if (!base64Info.data || !base64Info.ext) {
448
+ throw new Error(`无效的 base64 data URL: ${url}`);
449
+ }
450
+ // 获取缓存路径(使用检测到的扩展名)
451
+ const cachePath = this.getCachedPath(url, base64Info.ext);
452
+ const mimeType = base64Info.mimeType || this._getMimeTypeFromExt(base64Info.ext);
453
+ // 如果缓存有效且不强制重新下载,直接返回
454
+ if (!force && await this.isCacheValidAsync(cachePath.filePath)) {
455
+ const stats = await fs.promises.stat(cachePath.filePath);
456
+ return {
457
+ ...cachePath,
458
+ mimeType,
459
+ size: stats.size
460
+ };
461
+ }
462
+ // 保存 base64 数据到文件
463
+ await this._saveBase64ToFile(base64Info.data, cachePath.filePath);
464
+ // 获取文件大小
465
+ const stats = await fs.promises.stat(cachePath.filePath);
466
+ return {
467
+ ...cachePath,
468
+ mimeType,
469
+ size: stats.size
470
+ };
471
+ }
472
+ // 处理普通 URL
473
+ const shouldCache = ignoreOrigin ? () => true : this._getMatchFunction();
474
+ const isAllowedOrigin = ignoreOrigin ? () => true : this._getOriginAllowFunction();
475
+ // 检查是否匹配缓存规则
476
+ if (!shouldCache(url)) {
477
+ throw new Error(`URL 不匹配缓存规则: ${url}`);
478
+ }
479
+ // 检查来源是否允许
480
+ if (!isAllowedOrigin(url)) {
481
+ throw new Error(`URL 来源不允许缓存: ${url}`);
482
+ }
483
+ // 获取缓存路径
484
+ const cachePath = this.getCachedPath(url);
485
+ // 从文件扩展名获取 MIME 类型
486
+ const ext = path.extname(cachePath.filePath).replace(/^\./, '') || DEFAULT_EXT.replace(/^\./, '');
487
+ const mimeType = this._getMimeTypeFromExt(ext);
488
+ // 如果缓存有效且不强制重新下载,直接返回
489
+ if (!force && await this.isCacheValidAsync(cachePath.filePath)) {
490
+ const stats = await fs.promises.stat(cachePath.filePath);
491
+ return {
492
+ ...cachePath,
493
+ mimeType,
494
+ size: stats.size
495
+ };
496
+ }
497
+ // 下载资源
498
+ await this.downloadResourceAsync(url, cachePath.filePath, 0, onDownloadProgress);
499
+ // 获取文件大小
500
+ const stats = await fs.promises.stat(cachePath.filePath);
501
+ return {
502
+ ...cachePath,
503
+ mimeType,
504
+ size: stats.size
505
+ };
506
+ }
507
+ /**
508
+ * 批量缓存多个 URL 的资源
509
+ * @param urls 要缓存的资源 URL 数组
510
+ * @param force 是否强制重新下载,即使缓存有效(默认 false)
511
+ * @param ignoreOrigin 是否忽略来源检查(默认 false)
512
+ * @param onProgress 进度回调函数(可选)
513
+ * @returns Promise<Array<{ url: string, success: boolean, filePath?: string, hostPath?: string, mimeType?: string, size?: number, error?: string }>> 返回每个 URL 的缓存结果
514
+ */
515
+ async addCacheUrls(urls, force = false, ignoreOrigin = false, onProgress) {
516
+ const total = urls.length;
517
+ const results = [];
518
+ let completed = 0;
519
+ // 存储每个 URL 的下载进度
520
+ const downloadProgressMap = new Map();
521
+ // 进度回调的包装函数,确保线程安全
522
+ const reportProgress = (url, success, result) => {
523
+ if (onProgress) {
524
+ completed++;
525
+ const downloadProgress = downloadProgressMap.get(url);
526
+ onProgress({
527
+ current: completed,
528
+ total,
529
+ url,
530
+ success,
531
+ result,
532
+ percentage: Math.round((completed / total) * 100),
533
+ downloadProgress: downloadProgress ? {
534
+ downloaded: downloadProgress.downloaded,
535
+ total: downloadProgress.total,
536
+ percentage: downloadProgress.percentage,
537
+ speed: downloadProgress.speed
538
+ } : undefined
539
+ });
540
+ }
541
+ };
542
+ // 并行处理所有 URL,但跟踪每个的完成状态
543
+ const promises = urls.map(async (url, index) => {
544
+ // 为每个 URL 创建下载进度回调
545
+ const onDownloadProgress = onProgress
546
+ ? (progress) => {
547
+ // 更新下载进度
548
+ downloadProgressMap.set(url, {
549
+ downloaded: progress.downloaded,
550
+ total: progress.total,
551
+ percentage: progress.percentage,
552
+ speed: progress.speed
553
+ });
554
+ // 实时报告下载进度(不增加 completed 计数)
555
+ if (onProgress) {
556
+ onProgress({
557
+ current: completed,
558
+ total,
559
+ url,
560
+ success: true, // 下载中视为进行中
561
+ result: undefined,
562
+ percentage: Math.round((completed / total) * 100),
563
+ downloadProgress: {
564
+ downloaded: progress.downloaded,
565
+ total: progress.total,
566
+ percentage: progress.percentage,
567
+ speed: progress.speed
568
+ }
569
+ });
570
+ }
571
+ }
572
+ : undefined;
573
+ try {
574
+ const result = await this.cacheUrl(url, force, ignoreOrigin, onDownloadProgress);
575
+ const item = {
576
+ url,
577
+ success: true,
578
+ filePath: result.filePath,
579
+ hostPath: result.hostPath,
580
+ mimeType: result.mimeType,
581
+ size: result.size
582
+ };
583
+ results[index] = item;
584
+ // 清除下载进度(已完成)
585
+ downloadProgressMap.delete(url);
586
+ // 调用进度回调
587
+ reportProgress(url, true, {
588
+ filePath: result.filePath,
589
+ hostPath: result.hostPath,
590
+ mimeType: result.mimeType,
591
+ size: result.size
592
+ });
593
+ return item;
594
+ }
595
+ catch (error) {
596
+ const item = {
597
+ url,
598
+ success: false,
599
+ error: error instanceof Error ? error.message : '未知错误'
600
+ };
601
+ results[index] = item;
602
+ // 清除下载进度(失败)
603
+ downloadProgressMap.delete(url);
604
+ // 调用进度回调
605
+ reportProgress(url, false, {
606
+ error: item.error
607
+ });
608
+ return item;
609
+ }
610
+ });
611
+ // 等待所有请求完成
612
+ await Promise.allSettled(promises);
613
+ return results;
614
+ }
615
+ /**
616
+ * 删除多个 URL 的资源
617
+ * @param urls 要删除的资源 URL 数组
618
+ * @returns Promise<Array<{ url: string, success: boolean, error?: string }>> 返回每个 URL 的删除结果
619
+ */
620
+ async deleteCacheUrls(urls) {
621
+ const results = await Promise.allSettled(urls.map(url => this.deleteUrl(url)));
622
+ return results.map((result, index) => {
623
+ const url = urls[index] || '';
624
+ if (result.status === 'fulfilled') {
625
+ return { url, success: true };
626
+ }
627
+ else {
628
+ return { url, success: false, error: result.reason?.message || '未知错误' };
629
+ }
630
+ });
631
+ }
632
+ /**
633
+ * 删除单个 URL 的资源(异步版本,性能更好)
634
+ * @param url 要删除的资源 URL
635
+ * @returns Promise<{ url: string, success: boolean, error?: string }> 返回删除结果
636
+ */
637
+ async deleteUrl(url) {
638
+ try {
639
+ const cachePath = this.getCachedPath(url);
640
+ try {
641
+ await fs.promises.unlink(cachePath.filePath);
642
+ return { url, success: true };
643
+ }
644
+ catch (error) {
645
+ if (error.code === 'ENOENT') {
646
+ return { url, success: false, error: '文件不存在' };
647
+ }
648
+ throw error;
649
+ }
650
+ }
651
+ catch (error) {
652
+ return {
653
+ url,
654
+ success: false,
655
+ error: error instanceof Error ? error.message : '未知错误'
656
+ };
657
+ }
658
+ }
659
+ /**
660
+ * 删除单个 URL 的资源(别名,保持向后兼容)
661
+ * @deprecated 使用 deleteUrl 代替
662
+ */
663
+ async deleteCache(url) {
664
+ return this.deleteUrl(url);
665
+ }
666
+ /**
667
+ * 清理过期缓存文件(异步并行处理,性能更好)
668
+ */
669
+ async _cleanOldCache() {
670
+ try {
671
+ const files = await fs.promises.readdir(this.options.cacheDir);
672
+ if (files.length === 0)
673
+ return;
674
+ const now = Date.now();
675
+ // 并行处理,提升性能
676
+ await Promise.allSettled(files.map(async (file) => {
677
+ const fullPath = path.join(this.options.cacheDir, file);
678
+ try {
679
+ const stat = await fs.promises.stat(fullPath);
680
+ if (now - stat.mtimeMs > this.options.cacheTTL) {
681
+ await fs.promises.unlink(fullPath);
682
+ }
683
+ }
684
+ catch {
685
+ // 忽略单个文件异常
686
+ }
687
+ }));
688
+ }
689
+ catch (error) {
690
+ // 忽略目录读取错误
691
+ console.log('清理过期缓存时发生错误:', error);
692
+ }
693
+ }
694
+ /**
695
+ * 清理所有缓存文件(完全异步版本,性能更好)
696
+ * @returns Promise<{ success: number, failed: number, totalSize: number }> 返回清理统计信息
697
+ */
698
+ async clearCache() {
699
+ try {
700
+ const files = await fs.promises.readdir(this.options.cacheDir);
701
+ if (files.length === 0) {
702
+ return { success: 0, failed: 0, totalSize: 0 };
703
+ }
704
+ // 并行获取所有文件信息(避免并行时的竞态条件)
705
+ const fileInfos = await Promise.allSettled(files.map(async (file) => {
706
+ const filePath = path.join(this.options.cacheDir, file);
707
+ try {
708
+ const stats = await fs.promises.stat(filePath);
709
+ return { file, filePath, size: stats.size };
710
+ }
711
+ catch (error) {
712
+ return { file, filePath, size: 0, error };
713
+ }
714
+ }));
715
+ const validInfos = fileInfos
716
+ .filter((r) => r.status === 'fulfilled')
717
+ .map(r => r.value);
718
+ // 计算总大小
719
+ const totalSize = validInfos.reduce((sum, info) => sum + info.size, 0);
720
+ // 并行删除文件,提升性能
721
+ const deleteResults = await Promise.allSettled(validInfos.map(async (info) => {
722
+ try {
723
+ await fs.promises.unlink(info.filePath);
724
+ return { success: true, file: info.file };
725
+ }
726
+ catch (error) {
727
+ throw error;
728
+ }
729
+ }));
730
+ // 统计成功和失败数量
731
+ const success = deleteResults.filter(r => r.status === 'fulfilled').length;
732
+ const failed = deleteResults.filter(r => r.status === 'rejected').length;
733
+ return { success, failed, totalSize };
734
+ }
735
+ catch (error) {
736
+ console.log('清理缓存时发生错误:', error);
737
+ throw error;
738
+ }
739
+ }
740
+ /**
741
+ * 注册 Electron 请求拦截器,实现资源缓存
742
+ */
743
+ _registerInterceptor() {
744
+ const shouldCache = this._getMatchFunction();
745
+ const isAllowedOrigin = this._getOriginAllowFunction();
746
+ this.session.webRequest.onBeforeRequest({ urls: ['http://*/*', 'https://*/*'] }, (details, callback) => {
747
+ const url = details.url;
748
+ // 不匹配或来源不允许,直接放行
749
+ if (details.method !== 'GET' || !shouldCache(url) || !isAllowedOrigin(url))
750
+ return callback({});
751
+ const cachePath = this.getCachedPath(url);
752
+ // 命中缓存,直接重定向到本地文件
753
+ if (this.isCacheValid(cachePath.filePath)) {
754
+ return callback({ redirectURL: cachePath.hostPath });
755
+ }
756
+ // 未命中则异步下载,当前请求正常放行
757
+ this.downloadResource(url, cachePath.filePath);
758
+ return callback({});
759
+ });
760
+ }
761
+ }
762
+ ResourceCache.scheme = 'cachefile';
763
+
764
+ export { ResourceCache };
765
+ //# sourceMappingURL=resource-cache.js.map