-
Notifications
You must be signed in to change notification settings - Fork 384
Expand file tree
/
Copy pathscript.ts
More file actions
1826 lines (1726 loc) · 68.7 KB
/
Copy pathscript.ts
File metadata and controls
1826 lines (1726 loc) · 68.7 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { fetchScriptBody, parseMetadata, prepareScriptByCode } from "@App/pkg/utils/script";
import { uuidv4 } from "@App/pkg/utils/uuid";
import type { Group } from "@Packages/message/server";
import Logger from "@App/app/logger/logger";
import LoggerCore from "@App/app/logger/core";
import {
checkSilenceUpdate,
getBrowserType,
getStorageName,
openInCurrentTab,
stringMatching,
} from "@App/pkg/utils/utils";
import { ltever } from "@App/pkg/utils/semver";
import type {
SCMetadata,
Script,
SCRIPT_RUN_STATUS,
ScriptDAO,
ScriptRunResource,
ScriptSite,
} from "@App/app/repo/scripts";
import { SELF_METADATA_ONLY_RUN_ON_URL } from "@App/app/repo/metadata";
import { SCRIPT_STATUS_DISABLE, SCRIPT_STATUS_ENABLE, ScriptCodeDAO } from "@App/app/repo/scripts";
import { type IMessageQueue } from "@Packages/message/message_queue";
import { type ScriptInfo, type InstallSource, createTempCodeEntry } from "@App/pkg/utils/scriptInstall";
import { type ResourceService } from "./resource";
import { type ValueService } from "./value";
import { compileScriptCode } from "../content/utils";
import { type SystemConfig } from "@App/pkg/config/config";
import type {
TScriptRunStatus,
TDeleteScript,
TEnableScript,
TInstallScript,
TSortedScript,
TInstallScriptParams,
} from "../queue";
import { CLOUD_SYNC_QUEUE_KEY } from "../queue";
import { buildScriptRunResourceBasic, selfMetadataUpdate } from "./utils";
import {
BatchUpdateListActionCode,
type TBatchUpdateListAction,
UpdateStatusCode,
type TBatchUpdateRecord,
type TBatchUpdateItemResult,
type TBatchUpdateResult,
} from "./types";
import { getSimilarityScore, ScriptUpdateCheck } from "./script_update_check";
import { LocalStorageDAO } from "@App/app/repo/localStorage";
import { CompiledResourceDAO } from "@App/app/repo/resource";
import { initRegularUpdateCheck, watchRegularUpdateCheck } from "./regular_updatecheck";
import { parseSkillScriptMetadata } from "@App/pkg/utils/skill_script";
import { stackAsyncTask } from "@App/pkg/utils/async_queue";
import { TempStorageDAO, TempStorageItemType } from "@App/app/repo/tempStorage";
import { EnableAgent } from "@App/app/const";
import { TrashScriptDAO } from "@App/app/repo/trash_script";
import type { TrashScript } from "@App/app/repo/trash_script";
import { SubscribeDAO } from "@App/app/repo/subscribe";
export type TCheckScriptUpdateOption = Partial<
{ checkType: "user"; noUpdateCheck?: number } | ({ checkType: "system" } & Record<string, any>)
>;
export type TOpenBatchUpdatePageOption = { q: string; dontCheckNow: boolean };
export type TScriptInstallParam = {
script: Script; // 脚本信息(包含脚本的基础元数据)
code: string; // 脚本源码内容
upsertBy?: InstallSource; // 安装/更新来源(用于标识脚本来源渠道)
createtime?: number; // 导入时指定的创建时间(时间戳,毫秒)
updatetime?: number; // 导入时指定的最后更新时间(时间戳,毫秒)
overwriteSelfMetadata?: boolean; // 备份导入时用备份中的自定义元数据覆盖本地配置
};
export type TScriptInstallReturn = {
update: boolean; // 是否为更新操作(true 表示更新,false 表示新增)
updatetime: number | undefined; // 实际生效的更新时间(时间戳,毫秒)
};
export type TRestoreResult = {
restored: string[];
conflicts: { uuid: string; name: string }[];
};
export class ScriptService {
logger: Logger;
scriptCodeDAO: ScriptCodeDAO = new ScriptCodeDAO();
localStorageDAO: LocalStorageDAO = new LocalStorageDAO();
compiledResourceDAO: CompiledResourceDAO = new CompiledResourceDAO();
trashScriptDAO: TrashScriptDAO = new TrashScriptDAO();
subscribeDAO: SubscribeDAO = new SubscribeDAO();
private readonly scriptUpdateCheck;
constructor(
private readonly systemConfig: SystemConfig,
private readonly group: Group,
private readonly mq: IMessageQueue,
private readonly valueService: ValueService,
private readonly resourceService: ResourceService,
private readonly scriptDAO: ScriptDAO
) {
this.logger = LoggerCore.logger().with({ service: "script" });
this.scriptCodeDAO.enableCache();
// 只给 SW 的长生命周期实例开启目录快照缓存;页面上下文中的短生命周期 DAO 按需读取 OPFS。
this.trashScriptDAO.enableCache();
this.scriptUpdateCheck = new ScriptUpdateCheck(systemConfig, group, mq, valueService, resourceService, scriptDAO);
}
listenerScriptInstall() {
// 初始化脚本安装监听
chrome.webNavigation.onBeforeNavigate.addListener(
(req: chrome.webNavigation.WebNavigationBaseCallbackDetails) => {
const lastError = chrome.runtime.lastError;
if (lastError) {
console.error("chrome.runtime.lastError in chrome.webNavigation.onBeforeNavigate:", lastError);
return;
}
// 处理url, 实现安装脚本
let targetUrl: string;
// 判断是否为 file:///*/*.user.js 或 file:///*/*.skill.js(skill 仅 agent 启用时)
if (
req.url.startsWith("file://") &&
(req.url.endsWith(".user.js") || (EnableAgent && req.url.endsWith(".skill.js")))
) {
targetUrl = req.url;
} else {
const reqUrl = new URL(req.url);
// 判断是否有hash
if (!reqUrl.hash) {
return undefined;
}
// 判断是否有url参数
const idx = reqUrl.hash.indexOf("url=");
if (idx < 0) {
return undefined;
}
// 获取url参数
targetUrl = reqUrl.hash.substring(idx + 4);
}
// 读取脚本url内容, 进行安装
const logger = this.logger.with({ url: targetUrl });
logger.debug("install script");
this.openInstallPageByUrl(targetUrl, { source: "user", byWebRequest: true })
.catch((e) => {
logger.error("install script error", Logger.E(e));
// 不再重定向当前url
chrome.declarativeNetRequest.updateDynamicRules(
{
removeRuleIds: [2],
addRules: [
{
id: 2,
priority: 1,
action: {
type: "allow" as chrome.declarativeNetRequest.RuleActionType,
},
condition: {
regexFilter: targetUrl,
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod],
},
},
],
},
() => {
if (chrome.runtime.lastError) {
console.error(
"chrome.runtime.lastError in chrome.declarativeNetRequest.updateDynamicRules:",
chrome.runtime.lastError
);
}
}
);
})
.finally(async () => {
try {
// 直接用 chrome.tabs.goBack,不再走 content script 消息通道:
// content.js 依赖 chrome.userScripts 注册,未开发者模式/脚本被禁用/命中黑名单时不会被注入,
// 消息发不到会静默失败;goBack 只依赖已必需的 tabs 权限,不受这些条件影响。
const currentTab = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
// 仅针对用户自行点击安装、且仍停留在该标签的场景;用户若已切到其他标签,不应把后台标签拉回历史记录
if (currentTab?.[0]?.id === req.tabId) {
// 回退到到安装页
await chrome.tabs.goBack(req.tabId);
}
} catch (e) {
console.error("chrome.tabs.goBack/query error:", e);
}
});
},
{
url: [
{ schemes: ["http", "https"], hostEquals: "docs.scriptcat.org", pathPrefix: "/docs/script_installation/" },
{ schemes: ["http", "https"], hostEquals: "docs.scriptcat.org", pathPrefix: "/en/docs/script_installation/" },
{ schemes: ["http", "https"], hostEquals: "www.tampermonkey.net", pathPrefix: "/script_installation.php" },
{ schemes: ["file"], pathSuffix: ".user.js" },
// Skill 安装入口仅在 agent 启用时拦截(正式版屏蔽)
...(EnableAgent
? [
{ schemes: ["file"], pathSuffix: ".skill.js" },
{ schemes: ["file"], pathSuffix: ".cat.md" },
]
: []),
],
}
);
// 兼容 chrome 内核 < 128 处理
const browserType = getBrowserType();
const addResponseHeaders = browserType.chrome && browserType.chromeVersion >= 128;
// Chrome 84+
const conditions: chrome.declarativeNetRequest.RuleCondition[] = [
{
regexFilter: "^([^?#]+?\\.user(\\.bg|\\.sub)?\\.js)", // Chrome 84+
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME], // Chrome 84+
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false, // Chrome 84+
excludedRequestDomains: ["github.com", "gitlab.com", "gitea.com", "bitbucket.org"], // Chrome 101+
},
{
regexFilter: "^(.+?\\.user(\\.bg|\\.sub)?\\.js&response-content-type=application%2Foctet-stream)",
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false,
requestDomains: ["githubusercontent.com"], // Chrome 101+
},
{
regexFilter:
"^(https?:\\/\\/github.com\\/[^\\s/?#]+\\/[^\\s/?#]+\\/releases/[^\\s/?#]+/download/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
// https://github.com/<user>/<repo>/releases/latest/download/file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false,
requestDomains: ["github.com"], // Chrome 101+
},
{
regexFilter:
"^(https?:\\/\\/gitlab\\.com\\/[^\\s/?#]+\\/[^\\s/?#]+\\/-\\/raw\\/[a-z0-9_/.-]+\\/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false,
requestDomains: ["gitlab.com"], // Chrome 101+
},
{
regexFilter: "^(https?:\\/\\/github\\.com\\/[^\\/]+\\/[^\\/]+\\/releases\\/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
// https://github.com/<user>/<repo>/releases/latest/download/file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false,
requestDomains: ["github.com"], // Chrome 101+
},
{
regexFilter: "^(https?://github.com/[^\\s/?#]+/[^\\s/?#]+/raw/[a-z]+/[^?#]+?.user(\\.bg|\\.sub)?.js)",
// https://github.com/<user>/<repo>/raw/refs/heads/main/.../file.user.js
// https://github.com/<user>/<repo>/raw/<branch>/.../file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false,
requestDomains: ["github.com"], // Chrome 101+
},
{
regexFilter:
"^(https?://gitlab\\.com/[^\\s/?#]+/[^\\s/?#]+/-/raw/[a-z0-9_/.-]+/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
// https://gitlab.com/<user>/<repo>/-/raw/<branch>/.../file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod],
isUrlFilterCaseSensitive: false,
requestDomains: ["gitlab.com"], // Chrome 101+
},
{
regexFilter:
"^(https?://gitea\\.com/[^\\s/?#]+/[^\\s/?#]+/raw/[a-z0-9_/.-]+/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
// https://gitea.com/<user>/<repo>/raw/<branch>/.../file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod],
isUrlFilterCaseSensitive: false,
requestDomains: ["gitea.com"], // Chrome 101+
},
{
regexFilter:
"^(https?://bitbucket\\.org/[^\\s/?#]+/[^\\s/?#]+/raw/[a-z0-9_/.-]+/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
// https://bitbucket.org/<user>/<repo>/raw/<branch>/.../file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod],
isUrlFilterCaseSensitive: false,
requestDomains: ["bitbucket.org"], // Chrome 101+
},
// Skill 包 (.cat.md) 安装检测,仅 agent 启用时拦截(正式版屏蔽)
...(EnableAgent
? [
{
regexFilter: "^([^?#]+?\\.cat\\.md)",
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod],
isUrlFilterCaseSensitive: false,
},
]
: []),
];
const installPageURL = chrome.runtime.getURL("src/install.html");
const rules = conditions.map((condition, idx) => {
Object.assign(condition, {
excludedTabIds: [chrome.tabs.TAB_ID_NONE],
});
if (addResponseHeaders) {
Object.assign(condition, {
responseHeaders: [
{
header: "Content-Type",
values: [
"text/javascript*",
"application/javascript*",
"text/html*",
"text/plain*",
"application/octet-stream*",
"application/force-download*",
"text/markdown*",
],
},
],
});
}
return {
id: 1000 + idx,
priority: 1,
action: {
type: "redirect" as chrome.declarativeNetRequest.RuleActionType,
redirect: {
// 直接 URL 入口不经过 UUID 暂存;byWebRequest 只在暂存链路中用于脚本身份匹配,
// 不能再作为安装页 history.back()/window.close() 的来源标记。
regexSubstitution: `${installPageURL}?url=\\1`,
},
},
condition: condition,
} as chrome.declarativeNetRequest.Rule;
});
// 重定向到脚本安装页
chrome.declarativeNetRequest.updateDynamicRules(
{
removeRuleIds: [1],
},
() => {
if (chrome.runtime.lastError) {
console.error(
"chrome.runtime.lastError in chrome.declarativeNetRequest.updateDynamicRules:",
chrome.runtime.lastError
);
}
}
);
chrome.declarativeNetRequest.updateSessionRules(
{
removeRuleIds: [...rules.map((rule) => rule.id)],
addRules: rules,
},
() => {
if (chrome.runtime.lastError) {
console.error(
"chrome.runtime.lastError in chrome.declarativeNetRequest.updateSessionRules:",
chrome.runtime.lastError
);
}
}
);
}
public async openInstallPageByUrl(
url: string,
options: { source: InstallSource; byWebRequest?: boolean }
): Promise<{ success: boolean; msg: string }> {
try {
const installPageUrl = await this.getInstallPageUrl(url, options);
if (!installPageUrl) throw new Error("getInstallPageUrl failed");
await openInCurrentTab(installPageUrl);
return { success: true, msg: "" };
} catch (err: any) {
this.logger.error("open install page failed", { source: options.source }, Logger.E(err));
return { success: false, msg: err.message };
}
}
public async getInstallPageUrl(
url: string,
options: { source: InstallSource; byWebRequest?: boolean }
): Promise<string> {
const uuid = uuidv4();
try {
await this.openUpdateOrInstallPage(uuid, url, options, false);
return `/src/install.html?uuid=${uuid}`;
} catch (err: any) {
this.logger.error("prepare install page failed", { source: options.source }, Logger.E(err));
return "";
}
}
// 直接通过url静默安装脚本
async installByUrl(url: string, source: InstallSource, subscribeUrl?: string) {
const uuid = uuidv4();
const code = await fetchScriptBody(url);
const { script } = await prepareScriptByCode(code, url, uuid);
script.subscribeUrl = subscribeUrl;
await this.installScript({
script,
code,
upsertBy: source,
});
return script;
}
// 直接通过code静默安装脚本
async installByCode(param: { uuid: string; code: string; upsertBy: InstallSource }) {
const { code, upsertBy, uuid } = param;
const { script } = await prepareScriptByCode(code, "", uuid, true);
await this.installScript({
script,
code,
upsertBy,
});
return script;
}
// 获取安装信息
async getInstallInfo(uuid: string) {
const entry = await new TempStorageDAO().get(uuid);
return <[boolean, ScriptInfo, Record<string, any>]>entry?.value;
}
publishInstallScript(scriptFull: Script, options: any) {
const { uuid, type, status, name, namespace, origin, checkUpdateUrl, downloadUrl } = scriptFull;
const script = { uuid, type, status, name, namespace, origin, checkUpdateUrl, downloadUrl } as TInstallScriptParams;
return this.mq.publish<TInstallScript>("installScript", { script, ...options });
}
// 安装脚本 / 更新脚本
async installScript(param: TScriptInstallParam): Promise<TScriptInstallReturn> {
param.upsertBy = param.upsertBy || "user";
const { script, upsertBy, createtime, updatetime } = param;
// 删 storage cache
const compiledResourceUpdatePromise = this.compiledResourceDAO.delete(script.uuid);
const logger = this.logger.with({
name: script.name,
uuid: script.uuid,
version: script.metadata.version?.[0] || "0.0",
upsertBy,
});
let update = false;
// 判断是否已经安装
const oldScript = await this.scriptDAO.get(script.uuid);
if (oldScript) {
// 执行更新逻辑
update = true;
if (!param.overwriteSelfMetadata) {
script.selfMetadata = oldScript.selfMetadata;
}
// 如果已安装的脚本是由 Subscribe 安装,即使是手动更新也不会影响跟 Subscribe 关联
if (oldScript.subscribeUrl && oldScript.origin) {
// origin 和 subscribeUrl 保持不变
// @downloadURL @updateURL 随脚本最新代码而更新
script.origin = oldScript.origin;
script.subscribeUrl = oldScript.subscribeUrl;
}
}
if (script.ignoreVersion) script.ignoreVersion = "";
if (createtime) {
script.createtime = createtime;
}
if (updatetime) {
script.updatetime = updatetime;
}
// 拖拉安装等同本地创建脚本
if (script.origin?.startsWith("file:///*from-local*/")) {
script.origin = "";
script.originDomain = "";
script.downloadUrl = "";
script.checkUpdateUrl = "";
}
// 现存的脚本:以最初的安装(即 createtime)为标准,回填 origin 用于更新检查。
// 如果最初是从网络安装,之后拖拉安装本机档案,则保留 origin 资讯。
// 如果本机安装的版本号较低,则会在下次更新检查时提醒有更新。那个时候,用户可以选择更新至网络上最新版本,或忽略并保留本机版本。
// 跳过 ScriptCat 旧版本 (1.0.0-beta.2 ~ 1.4.x,自 commit d9b0eeede1a8b114f79a43fade99d825323c63f6 @ 2025.07.23)
// 误写入的 file:///*from-local*/ 与 file://-/ 前缀
if (
oldScript &&
script.createtime === oldScript.createtime &&
oldScript.origin &&
!script.origin &&
!oldScript.origin.startsWith("file:///*from-local*/") &&
!oldScript.origin.startsWith("file://-/")
) {
script.origin = oldScript.origin;
script.originDomain = oldScript.originDomain;
script.downloadUrl = oldScript.downloadUrl;
script.checkUpdateUrl = oldScript.checkUpdateUrl;
}
// 同步复活 / vscode 推送 / 安装页复用回收站 uuid 均汇流至此。
// OPFS 是回收站脚本的唯一原件,必须等活跃元数据与代码都保存成功后再删除。
const trashedBeforeInstall = await this.trashScriptDAO.get(script.uuid);
if (
trashedBeforeInstall?.subscribeUrl &&
script.subscribeUrl === trashedBeforeInstall.subscribeUrl &&
!(await this.subscribeDAO.get(trashedBeforeInstall.subscribeUrl))
) {
delete script.subscribeUrl;
}
return (async () => {
if (trashedBeforeInstall) {
await this.scriptCodeDAO.save({
uuid: script.uuid,
code: param.code,
});
try {
await this.scriptDAO.save(script);
} catch (error) {
await this.scriptCodeDAO.delete(script.uuid);
throw error;
}
try {
await this.trashScriptDAO.delete(script.uuid);
} catch (error) {
await this.scriptDAO.delete(script.uuid);
await this.scriptCodeDAO.delete(script.uuid);
throw error;
}
} else {
await this.scriptDAO.save(script);
await this.scriptCodeDAO.save({
uuid: script.uuid,
code: param.code,
});
}
logger.info("install success");
// Cache更新 & 下载资源
await Promise.all([
compiledResourceUpdatePromise,
this.resourceService.updateResourceByTypes(script, ["require", "require-css", "resource"]),
]);
// 广播一下
// Runtime 会负责更新 CompiledResource
this.publishInstallScript(script, { update, upsertBy });
// 传回(由后台控制的)实际更新时间,让 editor 中的script能保持正确的更新时间
return { update, updatetime: script.updatetime };
})().catch((e: unknown) => {
logger.error("install error", Logger.E(e));
throw e;
});
}
/** 删除脚本 = 移入回收站。不销毁任何关联数据(value/资源/权限/图标/代码全部保留) */
async deleteScript(uuid: string, deleteBy?: InstallSource) {
return this.deleteScripts([uuid], deleteBy);
}
/** 删除脚本 = 移入回收站。彻底销毁走 purgeScripts */
async deleteScripts(uuids: string[], deleteBy: InstallSource = "user") {
const logger = this.logger.with({ uuids });
const scripts = (await this.scriptDAO.gets(uuids)).filter((s) => !!s);
if (!scripts.length) {
logger.error("scripts not found");
throw new Error("scripts not found");
}
if (!(await this.systemConfig.getTrashEnabled())) {
return this.destroyActiveScripts(scripts, deleteBy);
}
const deleteTime = Date.now();
try {
// 先写回收站,成功后再删活跃表。失败的最坏结果是两张表短暂都有(可被 upsert 清理自愈),
// 反过来的顺序失败一次就是脚本彻底消失。
const codes = await this.scriptCodeDAO.gets(uuids);
const codeByUuid = new Map(codes.filter((item) => item !== undefined).map((item) => [item.uuid, item.code]));
await Promise.all(
scripts.map((script) => {
const code = codeByUuid.get(script.uuid);
if (code === undefined) throw new Error(`script code not found: ${script.uuid}`);
return this.trashScriptDAO.save({ ...script, deleteTime, deleteBy }, code);
})
);
await this.scriptDAO.deletes(uuids);
await this.scriptCodeDAO.deletes(uuids);
// 编译缓存是可重建缓存(runtime.ts:394-398 取不到会自动重建),直接丢弃
await this.compiledResourceDAO.deletes(uuids);
logger.info("trash success");
const data = scripts.map((script) => ({
uuid: script.uuid,
storageName: getStorageName(script),
type: script.type,
deleteBy,
})) as TDeleteScript[];
this.mq.publish<TDeleteScript[]>("trashScripts", data);
return true;
} catch (e) {
logger.error("trash error", Logger.E(e));
throw e;
}
}
/**
* 回收站关闭时的删除:不经回收站直接销毁。
* 必须同时发出 trashScripts 与 deleteScripts —— 二者的订阅者是不相交的两半(停用 / 销毁),
* 且「彻底删除永远发生在进回收站之后」这条前提在关闭态不成立。只发后者会让 runtime 注销不掉、
* cron 停不下、云端删不掉,即脚本被删了却还在跑。
*/
private async destroyActiveScripts(scripts: Script[], deleteBy: InstallSource) {
const uuids = scripts.map((s) => s.uuid);
const logger = this.logger.with({ uuids });
try {
await this.scriptDAO.deletes(uuids);
await this.scriptCodeDAO.deletes(uuids);
await this.compiledResourceDAO.deletes(uuids);
logger.info("delete without trash success");
const data = scripts.map((script) => ({
uuid: script.uuid,
storageName: getStorageName(script),
type: script.type,
}));
this.mq.publish<TDeleteScript[]>("trashScripts", data.map((d) => ({ ...d, deleteBy })) as TDeleteScript[]);
this.mq.publish<TDeleteScript[]>("deleteScripts", data as TDeleteScript[]);
return true;
} catch (e) {
logger.error("delete without trash error", Logger.E(e));
throw e;
}
}
/** 彻底删除:从回收站移除并销毁全部关联数据。单条删除 / 清空回收站 / 到期自动清理共用此入口 */
async purgeScripts(uuids: string[]) {
const logger = this.logger.with({ uuids });
const scripts = (await this.trashScriptDAO.gets(uuids)).filter((s) => !!s);
if (!scripts.length) {
logger.error("trash scripts not found");
throw new Error("trash scripts not found");
}
return this.trashScriptDAO
.deletes(uuids)
.then(async () => {
await this.scriptCodeDAO.deletes(uuids);
await this.compiledResourceDAO.deletes(uuids);
logger.info("purge success");
const data = scripts.map((script) => ({
uuid: script.uuid,
storageName: getStorageName(script),
type: script.type,
})) as TDeleteScript[];
this.mq.publish<TDeleteScript[]>("deleteScripts", data);
return true;
})
.catch((e) => {
logger.error("purge error", Logger.E(e));
throw e;
});
}
/** 从回收站还原脚本。同 name+namespace 已被占用者拒绝还原并回报冲突 */
async restoreScripts(uuids: string[]): Promise<TRestoreResult> {
const logger = this.logger.with({ uuids });
const trashed = (await this.trashScriptDAO.gets(uuids)).filter((s) => !!s);
if (!trashed.length) {
logger.error("trash scripts not found");
throw new Error("trash scripts not found");
}
const restored: string[] = [];
const conflicts: { uuid: string; name: string }[] = [];
for (const item of trashed) {
const occupied = await this.scriptDAO.findByNameAndNamespace(item.name, item.namespace);
if (occupied) {
conflicts.push({ uuid: item.uuid, name: item.name });
continue;
}
const { deleteTime: _deleteTime, deleteBy: _deleteBy, ...script } = item;
// 订阅已不存在时解除关联,否则日后重新订阅该 URL 会因脚本不在列表中而再次删除它
if (script.subscribeUrl && !(await this.subscribeDAO.get(script.subscribeUrl))) {
delete script.subscribeUrl;
}
const code = await this.trashScriptDAO.getCode(item.uuid);
if (code === undefined) throw new Error(`trash script code not found: ${item.uuid}`);
// 先恢复代码再写活跃表;后续任一步失败都回滚活跃数据并保留 OPFS 原件。
await this.scriptCodeDAO.save({ uuid: item.uuid, code });
try {
await this.scriptDAO.save(script);
await this.trashScriptDAO.delete(item.uuid);
} catch (error) {
await this.scriptDAO.delete(item.uuid);
await this.scriptCodeDAO.delete(item.uuid);
throw error;
}
restored.push(item.uuid);
this.mq.publish<TInstallScript>("installScript", { script, update: false, upsertBy: "user" });
}
logger.info("restore done", { restored: restored.length, conflicts: conflicts.length });
return { restored, conflicts };
}
/** 清理回收站中超过保留期的脚本。返回清理条数 */
async cleanupExpiredTrash(): Promise<number> {
// 回收站关闭 = 一切自动行为停摆,残留条目只由用户手动清空
if (!(await this.systemConfig.getTrashEnabled())) {
return 0;
}
const retentionDays = await this.systemConfig.getTrashRetentionDays();
if (!retentionDays) {
return 0; // 0 = 永不自动清理
}
const deadline = Date.now() - retentionDays * 24 * 60 * 60 * 1000;
const all = await this.trashScriptDAO.all();
const expired = all.filter((item) => item.deleteTime < deadline).map((item) => item.uuid);
if (!expired.length) {
return 0;
}
try {
await this.purgeScripts(expired);
} catch (error) {
// 自动清理与用户手动清空并发时,目标已不存在已经满足清理目的;其他异常仍需暴露。
if (!(error instanceof Error) || error.message !== "trash scripts not found") throw error;
return 0;
}
this.logger.info("cleanup expired trash", { count: expired.length });
return expired.length;
}
/** 读取回收站全部条目,按删除时间倒序(最近删的在前) */
async getTrashScripts(): Promise<TrashScript[]> {
const all = await this.trashScriptDAO.all();
return all.sort((a, b) => b.deleteTime - a.deleteTime);
}
async enableScript(param: { uuid: string; enable: boolean }) {
const { uuid, enable } = param;
const logger = this.logger.with({ uuid, enable });
const script = await this.scriptDAO.get(uuid);
if (!script) {
logger.error("script not found");
throw new Error("script not found");
}
return this.scriptDAO
.update(uuid, {
status: enable ? SCRIPT_STATUS_ENABLE : SCRIPT_STATUS_DISABLE,
updatetime: Date.now(),
})
.then(() => {
logger.info(enable ? "enable success" : "disable success");
this.mq.publish<TEnableScript[]>("enableScripts", [{ uuid: uuid, enable: enable }]);
return {};
})
.catch((e) => {
logger.error(enable ? "enable error" : "disable error", Logger.E(e));
throw e;
});
}
async enableScripts(param: { uuids: string[]; enable: boolean }) {
const { uuids, enable } = param;
const logger = this.logger.with({ uuids, enable });
const scripts = await this.scriptDAO.gets(uuids);
const uuids2: string[] = [];
for (let i = 0, l = uuids.length; i < l; i++) {
const script = scripts[i];
if (script && script.uuid && script.uuid === uuids[i]) {
uuids2.push(script.uuid);
}
}
if (!uuids2.length) {
logger.error("scripts not found");
throw new Error("scripts not found");
}
return this.scriptDAO
.updates(uuids2, {
status: enable ? SCRIPT_STATUS_ENABLE : SCRIPT_STATUS_DISABLE,
updatetime: Date.now(),
})
.then(() => {
logger.info(enable ? "enable success" : "disable success");
this.mq.publish<TEnableScript[]>(
"enableScripts",
uuids2.map((uuid) => ({ uuid, enable }))
);
return {};
})
.catch((e) => {
logger.error(enable ? "enable error" : "disable error", Logger.E(e));
throw e;
});
}
async fetchInfo(uuid: string) {
const script = await this.scriptDAO.get(uuid);
if (!script) {
return null;
}
return script;
}
async updateRunStatus(params: { uuid: string; runStatus: SCRIPT_RUN_STATUS; error?: string; nextruntime?: number }) {
// 如果脚本删除了就不再更新状态
const script = await this.scriptDAO.get(params.uuid);
if (!script) {
return false;
}
if (
(await this.scriptDAO.update(params.uuid, {
runStatus: params.runStatus,
lastruntime: Date.now(),
error: params.error,
nextruntime: params.nextruntime,
})) === false
) {
throw new Error("update error");
}
this.mq.publish<TScriptRunStatus>("scriptRunStatus", params);
return true;
}
async getFilterResult(req: { value: string }) {
const OPTION_CASE_INSENSITIVE = true;
const scripts = await this.scriptDAO.all();
const scriptCodes = await Promise.all(
scripts.map((script) => this.scriptCodeDAO.get(script.uuid).catch((_) => undefined))
);
const keyword = req.value.toLocaleLowerCase();
// 空格分开关键字搜索
const keys = keyword.split(/\s+/).filter((e) => e.length);
const results: Partial<Record<string, string | boolean>>[] = [];
const codeCache: Partial<Record<string, string>> = {}; // temp cache
if (!keys.length) return results;
for (let i = 0, l = scripts.length; i < l; i++) {
const script = scripts[i];
const scriptCode = scriptCodes[i];
const uuid = script.uuid;
const result: Partial<Record<string, string | boolean>> = { uuid };
const searchName = (keyword: string) => {
if (OPTION_CASE_INSENSITIVE) {
return stringMatching(script.name.toLowerCase(), keyword.toLowerCase());
}
return stringMatching(script.name, keyword);
};
const searchCode = (keyword: string) => {
let c = codeCache[script.uuid];
if (!c) {
const code = scriptCode;
if (code && code.uuid === script.uuid) {
codeCache[script.uuid] = c = code.code;
c = code.code;
}
}
if (c) {
if (OPTION_CASE_INSENSITIVE) {
return stringMatching(c.toLowerCase(), keyword.toLowerCase());
}
return stringMatching(c, keyword);
}
return false;
};
let codeMatched = true;
let nameMatched = true;
for (const key of keys) {
if (codeMatched && !searchCode(key)) {
codeMatched = false;
}
if (nameMatched && !searchName(key)) {
nameMatched = false;
}
if (!codeMatched && !nameMatched) break;
}
result.code = codeMatched;
result.name = nameMatched;
if (result.name || result.code) {
result.auto = true;
}
results.push(result);
}
return results;
}
async getScriptRunResourceByUUID(uuid: string) {
const script = await this.fetchInfo(uuid);
if (!script) return null;
const scriptRes = await this.buildScriptRunResource(script);
scriptRes.code = compileScriptCode(scriptRes);
return scriptRes;
}
async buildScriptRunResource(script: Script): Promise<ScriptRunResource> {
const ret = buildScriptRunResourceBasic(script);
return Promise.all([
this.valueService.getScriptValue(ret),
this.resourceService.getScriptResourceValue(ret),
this.scriptCodeDAO.get(script.uuid),
]).then(([value, resource, code]) => {
if (!code) {
throw new Error("code is null");
}
ret.value = value;
ret.resource = resource;
ret.code = code.code;
return ret;
});
}
// ScriptMenuList 的 excludeUrl - 排除或回复
async excludeUrl({ uuid, excludePattern, remove }: { uuid: string; excludePattern: string; remove: boolean }) {
return stackAsyncTask("script-site-scope", async () => {
let script = await this.scriptDAO.get(uuid);
if (!script) {
throw new Error("script not found");
}
// 建立Set去掉重复(如有);用户覆盖整体替换作者规则,因此须把作者 @exclude 一并并入,
// 否则用户已有排除覆盖时会丢作者规则
const excludeSet = new Set([...(script.metadata?.exclude || []), ...(script.selfMetadata?.exclude || [])]);
if (remove) {
const deleted = excludeSet.delete(excludePattern);
if (!deleted) {
return; // scriptDAO 不用更新
}
} else {
excludeSet.add(excludePattern);
}
// 更新 script.selfMetadata.exclude
script = selfMetadataUpdate(script, "exclude", excludeSet);
try {
await this.scriptDAO.update(uuid, script);
// 广播一下
this.publishInstallScript(script, { update: true });
return true;
} catch (e) {
this.logger.error("exclude url error", Logger.E(e));
throw e;
}
});
}
async onlyRunOnUrl({ uuid, matchPattern }: { uuid: string; matchPattern: string }) {
return stackAsyncTask("script-site-scope", async () => {
let script = await this.scriptDAO.get(uuid);
if (!script) throw new Error("script not found");
script = selfMetadataUpdate(script, "match", new Set([matchPattern]));
script = selfMetadataUpdate(script, "include", new Set());
script = selfMetadataUpdate(script, SELF_METADATA_ONLY_RUN_ON_URL, new Set([matchPattern]));
await this.scriptDAO.update(uuid, script);
this.publishInstallScript(script, { update: true });
return true;
});
}
async allowUrl({
uuid,
matchPattern,
excludePattern,
}: {
uuid: string;
matchPattern: string;
excludePattern: string;
}) {
return stackAsyncTask("script-site-scope", async () => {
let script = await this.scriptDAO.get(uuid);
if (!script) throw new Error("script not found");
if (script.selfMetadata?.match !== undefined) {
script = selfMetadataUpdate(script, "match", new Set([...script.selfMetadata.match, matchPattern]));
script = selfMetadataUpdate(script, SELF_METADATA_ONLY_RUN_ON_URL, undefined);
}
if (script.selfMetadata?.exclude !== undefined) {
// 用户覆盖整体替换作者规则,因此移除当前项时把作者 @exclude 一并并入,避免丢作者规则
const excludeSet = new Set([...(script.metadata?.exclude || []), ...script.selfMetadata.exclude]);
excludeSet.delete(excludePattern);
script = selfMetadataUpdate(script, "exclude", excludeSet);
}
await this.scriptDAO.update(uuid, script);
this.publishInstallScript(script, { update: true });
return true;
});
}
async excludeFromMatch({ uuid, matchPattern }: { uuid: string; matchPattern: string }) {
return stackAsyncTask("script-site-scope", async () => {
let script = await this.scriptDAO.get(uuid);
if (!script) throw new Error("script not found");
if (script.selfMetadata?.match !== undefined) {
const matchSet = new Set(script.selfMetadata.match);
matchSet.delete(matchPattern);
script = selfMetadataUpdate(script, "match", matchSet);
script = selfMetadataUpdate(script, SELF_METADATA_ONLY_RUN_ON_URL, undefined);
}
// 用户覆盖整体替换作者规则,因此把作者 @exclude 一并并入用户覆盖,避免丢作者规则
const excludeSet = new Set([...(script.metadata?.exclude || []), ...(script.selfMetadata?.exclude || [])]);
excludeSet.add(matchPattern);
script = selfMetadataUpdate(script, "exclude", excludeSet);
await this.scriptDAO.update(uuid, script);
this.publishInstallScript(script, { update: true });
return true;
});
}
async resetExclude({ uuid, exclude }: { uuid: string; exclude: string[] | undefined }) {
return stackAsyncTask("script-site-scope", async () => {
let script = await this.scriptDAO.get(uuid);
if (!script) {