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

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 +198 -0
  13. package/esm/main/downloader.d.ts.map +1 -0
  14. package/esm/main/downloader.js +582 -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 +793 -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 +198 -0
  43. package/main/downloader.d.ts.map +1 -0
  44. package/main/downloader.js +582 -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 +793 -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,793 @@
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 Map();
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
+ // 检查是否正在下载,如果正在下载则返回已存在的 Promise(允许多个请求等待同一个下载任务)
262
+ const existingDownload = this._downloadingUrls.get(url);
263
+ if (existingDownload) {
264
+ // 如果提供了新的进度回调,绑定到已存在的下载器上
265
+ if (onProgress && existingDownload.downloader) {
266
+ existingDownload.downloader.on('progress', (stats) => {
267
+ try {
268
+ onProgress({
269
+ url,
270
+ downloaded: stats.downloaded || 0,
271
+ total: stats.total || 0,
272
+ percentage: stats.progress !== undefined ? Math.round(stats.progress) : -1,
273
+ speed: stats.speed || 0
274
+ });
275
+ }
276
+ catch (error) {
277
+ // 忽略回调中的错误,避免影响下载
278
+ console.error('进度回调执行失败:', error);
279
+ }
280
+ });
281
+ }
282
+ return existingDownload.promise;
283
+ }
284
+ // 检查重定向次数限制
285
+ if (redirectCount >= MAX_REDIRECTS) {
286
+ return Promise.reject(new Error(`重定向次数超过限制 (${MAX_REDIRECTS}): ${url}`));
287
+ }
288
+ // 创建新的下载 Promise
289
+ const downloadPromise = new Promise((resolve, reject) => {
290
+ const tempFilePath = `${filePath}.cache`;
291
+ const downloadDir = path.dirname(tempFilePath);
292
+ const downloadFileName = path.basename(tempFilePath);
293
+ // 确保目录存在
294
+ if (!fs.existsSync(downloadDir)) {
295
+ fs.mkdirSync(downloadDir, { recursive: true });
296
+ }
297
+ // 创建下载器实例
298
+ const dl = new DownloaderHelper(url, downloadDir, {
299
+ fileName: downloadFileName,
300
+ retry: { maxRetries: 3, delay: 1000 },
301
+ // 超时设置:10 分钟(600000 毫秒)
302
+ // 对于视频等大文件,需要更长的超时时间
303
+ // 如果 10 分钟内没有任何数据传输,才会超时
304
+ timeout: 600000,
305
+ override: true, // 覆盖已存在的文件
306
+ httpRequestOptions: {
307
+ // 允许重定向
308
+ followRedirect: true,
309
+ maxRedirects: MAX_REDIRECTS
310
+ }
311
+ });
312
+ // 立即将 Promise 和下载器实例存储到 Map 中,供后续相同 URL 的请求复用
313
+ // 注意:必须在监听事件之前存储,以便后续请求可以绑定进度回调
314
+ this._downloadingUrls.set(url, { promise: downloadPromise, downloader: dl });
315
+ // 监听下载进度
316
+ if (onProgress) {
317
+ dl.on('progress', (stats) => {
318
+ try {
319
+ // stats 包含: progress (百分比), downloaded (已下载字节), total (总字节), speed (速度)
320
+ onProgress({
321
+ url,
322
+ downloaded: stats.downloaded || 0,
323
+ total: stats.total || 0,
324
+ percentage: stats.progress !== undefined ? Math.round(stats.progress) : -1,
325
+ speed: stats.speed || 0
326
+ });
327
+ }
328
+ catch (error) {
329
+ // 忽略回调中的错误,避免影响下载
330
+ console.error('进度回调执行失败:', error);
331
+ }
332
+ });
333
+ }
334
+ // 监听下载完成
335
+ dl.on('end', () => {
336
+ // 将临时文件重命名为最终文件
337
+ fs.rename(tempFilePath, filePath, (renameErr) => {
338
+ // 无论成功还是失败,都要从下载列表中删除
339
+ this._downloadingUrls.delete(url);
340
+ if (renameErr) {
341
+ reject(new Error(`缓存文件重命名失败 from ${tempFilePath} to ${filePath}: ${renameErr.message}`));
342
+ }
343
+ else {
344
+ resolve();
345
+ }
346
+ });
347
+ });
348
+ // 监听下载错误
349
+ dl.on('error', (err) => {
350
+ // 从下载列表中删除
351
+ this._downloadingUrls.delete(url);
352
+ // 清理临时文件
353
+ fs.promises.unlink(tempFilePath).catch(() => {
354
+ // 忽略删除失败
355
+ });
356
+ reject(err instanceof Error ? err : new Error(`下载失败: ${url}`));
357
+ });
358
+ // 监听下载停止(取消)
359
+ dl.on('stop', () => {
360
+ // 从下载列表中删除
361
+ this._downloadingUrls.delete(url);
362
+ // 清理临时文件
363
+ fs.promises.unlink(tempFilePath).catch(() => {
364
+ // 忽略删除失败
365
+ });
366
+ reject(new Error(`下载已停止: ${url}`));
367
+ });
368
+ // 开始下载
369
+ dl.start().catch((err) => {
370
+ // 从下载列表中删除
371
+ this._downloadingUrls.delete(url);
372
+ reject(err instanceof Error ? err : new Error(`启动下载失败: ${url}`));
373
+ });
374
+ });
375
+ return downloadPromise;
376
+ }
377
+ /**
378
+ * 下载资源到本地缓存(同步版本,不返回 Promise,用于拦截器)
379
+ * @param url 资源URL
380
+ * @param filePath 本地缓存路径
381
+ */
382
+ downloadResource(url, filePath) {
383
+ // 异步执行,不等待完成
384
+ // 如果正在下载,跳过(避免重复下载)
385
+ if (this._downloadingUrls.has(url)) {
386
+ return;
387
+ }
388
+ // 调用 downloadResourceAsync,它会自动处理重复下载的情况
389
+ this.downloadResourceAsync(url, filePath).catch(() => {
390
+ // 静默处理错误,避免日志过多
391
+ });
392
+ }
393
+ /**
394
+ * 从文件扩展名获取 MIME 类型
395
+ * @param ext 文件扩展名(带或不带点)
396
+ * @returns MIME 类型
397
+ */
398
+ _getMimeTypeFromExt(ext) {
399
+ const cleanExt = ext.replace(/^\./, '').toLowerCase();
400
+ const mimeType = mime.lookup(cleanExt);
401
+ return mimeType || DEFAULT_MIME_TYPE;
402
+ }
403
+ /**
404
+ * 检测并处理 base64 data URL
405
+ * @param url 资源URL
406
+ * @returns 如果是 base64 URL,返回 true、文件扩展名、MIME 类型和数据;否则返回 false
407
+ */
408
+ _isBase64DataUrl(url) {
409
+ if (!url.startsWith('data:')) {
410
+ return { isBase64: false };
411
+ }
412
+ try {
413
+ // 解析 data URL 格式:data:[<mediatype>][;base64],<data>
414
+ const commaIndex = url.indexOf(',');
415
+ if (commaIndex === -1) {
416
+ return { isBase64: false };
417
+ }
418
+ const header = url.substring(0, commaIndex);
419
+ const data = url.substring(commaIndex + 1);
420
+ // 检查是否包含 base64 标识
421
+ if (!header.includes('base64')) {
422
+ return { isBase64: false };
423
+ }
424
+ // 从 mediatype 中提取文件扩展名和 MIME 类型
425
+ // 例如:data:image/png;base64 -> png, image/png
426
+ // 例如:data:image/jpeg;base64 -> jpeg, image/jpeg
427
+ let ext = DEFAULT_EXT.replace(/^\./, '');
428
+ let mimeType = DEFAULT_MIME_TYPE;
429
+ const mimeMatch = header.match(/data:([^;]+)/);
430
+ if (mimeMatch && mimeMatch[1]) {
431
+ mimeType = mimeMatch[1];
432
+ // 使用 mime-types 包从 MIME 类型获取扩展名
433
+ const extension = mime.extension(mimeType);
434
+ if (extension) {
435
+ ext = extension;
436
+ }
437
+ }
438
+ return { isBase64: true, ext, mimeType, data };
439
+ }
440
+ catch (error) {
441
+ return { isBase64: false };
442
+ }
443
+ }
444
+ /**
445
+ * 保存 base64 数据到文件
446
+ * @param base64Data base64 编码的数据
447
+ * @param filePath 目标文件路径
448
+ */
449
+ async _saveBase64ToFile(base64Data, filePath) {
450
+ try {
451
+ // 解码 base64 数据
452
+ const buffer = Buffer.from(base64Data, 'base64');
453
+ // 使用 Promise 版本的 writeFile
454
+ // Buffer 继承自 Uint8Array,可以直接使用
455
+ await fs.promises.writeFile(filePath, buffer);
456
+ }
457
+ catch (error) {
458
+ throw new Error(`保存 base64 文件失败: ${error instanceof Error ? error.message : '未知错误'}`);
459
+ }
460
+ }
461
+ /**
462
+ * 手动缓存指定 URL 的资源
463
+ * @param url 要缓存的资源 URL(支持普通 URL 和 base64 data URL)
464
+ * @param force 是否强制重新下载,即使缓存有效(默认 false)
465
+ * @param ignoreOrigin 是否忽略来源检查(默认 false)
466
+ * @param onDownloadProgress 下载进度回调函数(可选)
467
+ * @returns Promise<{ filePath: string, hostPath: string, mimeType: string, size: number }> 返回缓存文件路径、主机路径、MIME 类型和文件大小
468
+ * @throws 如果 URL 不匹配缓存规则或来源不允许,会抛出错误
469
+ */
470
+ async cacheUrl(url, force = false, ignoreOrigin = false, onDownloadProgress) {
471
+ // 检查是否是 base64 data URL
472
+ const base64Info = this._isBase64DataUrl(url);
473
+ if (base64Info.isBase64) {
474
+ // 处理 base64 data URL
475
+ if (!base64Info.data || !base64Info.ext) {
476
+ throw new Error(`无效的 base64 data URL: ${url}`);
477
+ }
478
+ // 获取缓存路径(使用检测到的扩展名)
479
+ const cachePath = this.getCachedPath(url, base64Info.ext);
480
+ const mimeType = base64Info.mimeType || this._getMimeTypeFromExt(base64Info.ext);
481
+ // 如果缓存有效且不强制重新下载,直接返回
482
+ if (!force && await this.isCacheValidAsync(cachePath.filePath)) {
483
+ const stats = await fs.promises.stat(cachePath.filePath);
484
+ return {
485
+ ...cachePath,
486
+ mimeType,
487
+ size: stats.size
488
+ };
489
+ }
490
+ // 保存 base64 数据到文件
491
+ await this._saveBase64ToFile(base64Info.data, cachePath.filePath);
492
+ // 获取文件大小
493
+ const stats = await fs.promises.stat(cachePath.filePath);
494
+ return {
495
+ ...cachePath,
496
+ mimeType,
497
+ size: stats.size
498
+ };
499
+ }
500
+ // 处理普通 URL
501
+ const shouldCache = ignoreOrigin ? () => true : this._getMatchFunction();
502
+ const isAllowedOrigin = ignoreOrigin ? () => true : this._getOriginAllowFunction();
503
+ // 检查是否匹配缓存规则
504
+ if (!shouldCache(url)) {
505
+ throw new Error(`URL 不匹配缓存规则: ${url}`);
506
+ }
507
+ // 检查来源是否允许
508
+ if (!isAllowedOrigin(url)) {
509
+ throw new Error(`URL 来源不允许缓存: ${url}`);
510
+ }
511
+ // 获取缓存路径
512
+ const cachePath = this.getCachedPath(url);
513
+ // 从文件扩展名获取 MIME 类型
514
+ const ext = path.extname(cachePath.filePath).replace(/^\./, '') || DEFAULT_EXT.replace(/^\./, '');
515
+ const mimeType = this._getMimeTypeFromExt(ext);
516
+ // 如果缓存有效且不强制重新下载,直接返回
517
+ if (!force && await this.isCacheValidAsync(cachePath.filePath)) {
518
+ const stats = await fs.promises.stat(cachePath.filePath);
519
+ return {
520
+ ...cachePath,
521
+ mimeType,
522
+ size: stats.size
523
+ };
524
+ }
525
+ // 下载资源
526
+ await this.downloadResourceAsync(url, cachePath.filePath, 0, onDownloadProgress);
527
+ // 获取文件大小
528
+ const stats = await fs.promises.stat(cachePath.filePath);
529
+ return {
530
+ ...cachePath,
531
+ mimeType,
532
+ size: stats.size
533
+ };
534
+ }
535
+ /**
536
+ * 批量缓存多个 URL 的资源
537
+ * @param urls 要缓存的资源 URL 数组
538
+ * @param force 是否强制重新下载,即使缓存有效(默认 false)
539
+ * @param ignoreOrigin 是否忽略来源检查(默认 false)
540
+ * @param onProgress 进度回调函数(可选)
541
+ * @returns Promise<Array<{ url: string, success: boolean, filePath?: string, hostPath?: string, mimeType?: string, size?: number, error?: string }>> 返回每个 URL 的缓存结果
542
+ */
543
+ async addCacheUrls(urls, force = false, ignoreOrigin = false, onProgress) {
544
+ const total = urls.length;
545
+ const results = [];
546
+ let completed = 0;
547
+ // 存储每个 URL 的下载进度
548
+ const downloadProgressMap = new Map();
549
+ // 进度回调的包装函数,确保线程安全
550
+ const reportProgress = (url, success, result) => {
551
+ if (onProgress) {
552
+ completed++;
553
+ const downloadProgress = downloadProgressMap.get(url);
554
+ onProgress({
555
+ current: completed,
556
+ total,
557
+ url,
558
+ success,
559
+ result,
560
+ percentage: Math.round((completed / total) * 100),
561
+ downloadProgress: downloadProgress ? {
562
+ downloaded: downloadProgress.downloaded,
563
+ total: downloadProgress.total,
564
+ percentage: downloadProgress.percentage,
565
+ speed: downloadProgress.speed
566
+ } : undefined
567
+ });
568
+ }
569
+ };
570
+ // 并行处理所有 URL,但跟踪每个的完成状态
571
+ const promises = urls.map(async (url, index) => {
572
+ // 为每个 URL 创建下载进度回调
573
+ const onDownloadProgress = onProgress
574
+ ? (progress) => {
575
+ // 更新下载进度
576
+ downloadProgressMap.set(url, {
577
+ downloaded: progress.downloaded,
578
+ total: progress.total,
579
+ percentage: progress.percentage,
580
+ speed: progress.speed
581
+ });
582
+ // 实时报告下载进度(不增加 completed 计数)
583
+ if (onProgress) {
584
+ onProgress({
585
+ current: completed,
586
+ total,
587
+ url,
588
+ success: true, // 下载中视为进行中
589
+ result: undefined,
590
+ percentage: Math.round((completed / total) * 100),
591
+ downloadProgress: {
592
+ downloaded: progress.downloaded,
593
+ total: progress.total,
594
+ percentage: progress.percentage,
595
+ speed: progress.speed
596
+ }
597
+ });
598
+ }
599
+ }
600
+ : undefined;
601
+ try {
602
+ const result = await this.cacheUrl(url, force, ignoreOrigin, onDownloadProgress);
603
+ const item = {
604
+ url,
605
+ success: true,
606
+ filePath: result.filePath,
607
+ hostPath: result.hostPath,
608
+ mimeType: result.mimeType,
609
+ size: result.size
610
+ };
611
+ results[index] = item;
612
+ // 清除下载进度(已完成)
613
+ downloadProgressMap.delete(url);
614
+ // 调用进度回调
615
+ reportProgress(url, true, {
616
+ filePath: result.filePath,
617
+ hostPath: result.hostPath,
618
+ mimeType: result.mimeType,
619
+ size: result.size
620
+ });
621
+ return item;
622
+ }
623
+ catch (error) {
624
+ const item = {
625
+ url,
626
+ success: false,
627
+ error: error instanceof Error ? error.message : '未知错误'
628
+ };
629
+ results[index] = item;
630
+ // 清除下载进度(失败)
631
+ downloadProgressMap.delete(url);
632
+ // 调用进度回调
633
+ reportProgress(url, false, {
634
+ error: item.error
635
+ });
636
+ return item;
637
+ }
638
+ });
639
+ // 等待所有请求完成
640
+ await Promise.allSettled(promises);
641
+ return results;
642
+ }
643
+ /**
644
+ * 删除多个 URL 的资源
645
+ * @param urls 要删除的资源 URL 数组
646
+ * @returns Promise<Array<{ url: string, success: boolean, error?: string }>> 返回每个 URL 的删除结果
647
+ */
648
+ async deleteCacheUrls(urls) {
649
+ const results = await Promise.allSettled(urls.map(url => this.deleteUrl(url)));
650
+ return results.map((result, index) => {
651
+ const url = urls[index] || '';
652
+ if (result.status === 'fulfilled') {
653
+ return { url, success: true };
654
+ }
655
+ else {
656
+ return { url, success: false, error: result.reason?.message || '未知错误' };
657
+ }
658
+ });
659
+ }
660
+ /**
661
+ * 删除单个 URL 的资源(异步版本,性能更好)
662
+ * @param url 要删除的资源 URL
663
+ * @returns Promise<{ url: string, success: boolean, error?: string }> 返回删除结果
664
+ */
665
+ async deleteUrl(url) {
666
+ try {
667
+ const cachePath = this.getCachedPath(url);
668
+ try {
669
+ await fs.promises.unlink(cachePath.filePath);
670
+ return { url, success: true };
671
+ }
672
+ catch (error) {
673
+ if (error.code === 'ENOENT') {
674
+ return { url, success: false, error: '文件不存在' };
675
+ }
676
+ throw error;
677
+ }
678
+ }
679
+ catch (error) {
680
+ return {
681
+ url,
682
+ success: false,
683
+ error: error instanceof Error ? error.message : '未知错误'
684
+ };
685
+ }
686
+ }
687
+ /**
688
+ * 删除单个 URL 的资源(别名,保持向后兼容)
689
+ * @deprecated 使用 deleteUrl 代替
690
+ */
691
+ async deleteCache(url) {
692
+ return this.deleteUrl(url);
693
+ }
694
+ /**
695
+ * 清理过期缓存文件(异步并行处理,性能更好)
696
+ */
697
+ async _cleanOldCache() {
698
+ try {
699
+ const files = await fs.promises.readdir(this.options.cacheDir);
700
+ if (files.length === 0)
701
+ return;
702
+ const now = Date.now();
703
+ // 并行处理,提升性能
704
+ await Promise.allSettled(files.map(async (file) => {
705
+ const fullPath = path.join(this.options.cacheDir, file);
706
+ try {
707
+ const stat = await fs.promises.stat(fullPath);
708
+ if (now - stat.mtimeMs > this.options.cacheTTL) {
709
+ await fs.promises.unlink(fullPath);
710
+ }
711
+ }
712
+ catch {
713
+ // 忽略单个文件异常
714
+ }
715
+ }));
716
+ }
717
+ catch (error) {
718
+ // 忽略目录读取错误
719
+ console.log('清理过期缓存时发生错误:', error);
720
+ }
721
+ }
722
+ /**
723
+ * 清理所有缓存文件(完全异步版本,性能更好)
724
+ * @returns Promise<{ success: number, failed: number, totalSize: number }> 返回清理统计信息
725
+ */
726
+ async clearCache() {
727
+ try {
728
+ const files = await fs.promises.readdir(this.options.cacheDir);
729
+ if (files.length === 0) {
730
+ return { success: 0, failed: 0, totalSize: 0 };
731
+ }
732
+ // 并行获取所有文件信息(避免并行时的竞态条件)
733
+ const fileInfos = await Promise.allSettled(files.map(async (file) => {
734
+ const filePath = path.join(this.options.cacheDir, file);
735
+ try {
736
+ const stats = await fs.promises.stat(filePath);
737
+ return { file, filePath, size: stats.size };
738
+ }
739
+ catch (error) {
740
+ return { file, filePath, size: 0, error };
741
+ }
742
+ }));
743
+ const validInfos = fileInfos
744
+ .filter((r) => r.status === 'fulfilled')
745
+ .map(r => r.value);
746
+ // 计算总大小
747
+ const totalSize = validInfos.reduce((sum, info) => sum + info.size, 0);
748
+ // 并行删除文件,提升性能
749
+ const deleteResults = await Promise.allSettled(validInfos.map(async (info) => {
750
+ try {
751
+ await fs.promises.unlink(info.filePath);
752
+ return { success: true, file: info.file };
753
+ }
754
+ catch (error) {
755
+ throw error;
756
+ }
757
+ }));
758
+ // 统计成功和失败数量
759
+ const success = deleteResults.filter(r => r.status === 'fulfilled').length;
760
+ const failed = deleteResults.filter(r => r.status === 'rejected').length;
761
+ return { success, failed, totalSize };
762
+ }
763
+ catch (error) {
764
+ console.log('清理缓存时发生错误:', error);
765
+ throw error;
766
+ }
767
+ }
768
+ /**
769
+ * 注册 Electron 请求拦截器,实现资源缓存
770
+ */
771
+ _registerInterceptor() {
772
+ const shouldCache = this._getMatchFunction();
773
+ const isAllowedOrigin = this._getOriginAllowFunction();
774
+ this.session.webRequest.onBeforeRequest({ urls: ['http://*/*', 'https://*/*'] }, (details, callback) => {
775
+ const url = details.url;
776
+ // 不匹配或来源不允许,直接放行
777
+ if (details.method !== 'GET' || !shouldCache(url) || !isAllowedOrigin(url))
778
+ return callback({});
779
+ const cachePath = this.getCachedPath(url);
780
+ // 命中缓存,直接重定向到本地文件
781
+ if (this.isCacheValid(cachePath.filePath)) {
782
+ return callback({ redirectURL: cachePath.hostPath });
783
+ }
784
+ // 未命中则异步下载,当前请求正常放行
785
+ this.downloadResource(url, cachePath.filePath);
786
+ return callback({});
787
+ });
788
+ }
789
+ }
790
+ ResourceCache.scheme = 'cachefile';
791
+
792
+ export { ResourceCache };
793
+ //# sourceMappingURL=resource-cache.js.map