-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
776 lines (693 loc) · 107 KB
/
Copy pathmain.js
File metadata and controls
776 lines (693 loc) · 107 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
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository
*/
var F=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var Q=(a,t)=>{for(var e in t)F(a,e,{get:t[e],enumerable:!0})},ee=(a,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of X(t))!Z.call(a,i)&&i!==e&&F(a,i,{get:()=>t[i],enumerable:!(n=Y(t,i))||n.enumerable});return a};var te=a=>ee(F({},"__esModule",{value:!0}),a);var ce={};Q(ce,{default:()=>P});module.exports=te(ce);var u=require("obsidian"),q={scripts:[],automaticallyCheckForUpdates:!0,updateInterval:24,debug:!1,showRibbonIcon:!0},T=class extends u.PluginSettingTab{constructor(e,n){super(e,n);this.plugin=n}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"CheekyChimp \u8BBE\u7F6E"}),e.createEl("p",{text:"\u8FD9\u4E2A\u63D2\u4EF6\u5141\u8BB8\u4F60\u5728Obsidian\u7684\u5185\u90E8\u6D4F\u89C8\u5668\u4E2D\u4F7F\u7528\u7528\u6237\u811A\u672C\u3002"}),e.createEl("h3",{text:"\u5E38\u89C4\u8BBE\u7F6E"}),new u.Setting(e).setName("\u81EA\u52A8\u68C0\u67E5\u66F4\u65B0").setDesc("\u5B9A\u671F\u68C0\u67E5\u7528\u6237\u811A\u672C\u7684\u66F4\u65B0").addToggle(i=>i.setValue(this.plugin.settings.automaticallyCheckForUpdates).onChange(async r=>{this.plugin.settings.automaticallyCheckForUpdates=r,await this.plugin.saveSettings()})),new u.Setting(e).setName("\u66F4\u65B0\u68C0\u67E5\u95F4\u9694").setDesc("\u68C0\u67E5\u811A\u672C\u66F4\u65B0\u7684\u95F4\u9694(\u5C0F\u65F6)").addSlider(i=>i.setLimits(1,168,1).setValue(this.plugin.settings.updateInterval).setDynamicTooltip().onChange(async r=>{this.plugin.settings.updateInterval=r,await this.plugin.saveSettings()})),new u.Setting(e).setName("\u8C03\u8BD5\u6A21\u5F0F").setDesc("\u542F\u7528\u8C03\u8BD5\u65E5\u5FD7").addToggle(i=>i.setValue(this.plugin.settings.debug).onChange(async r=>{this.plugin.settings.debug=r,await this.plugin.saveSettings()})),new u.Setting(e).setName("\u663E\u793A\u8FB9\u680F\u56FE\u6807").setDesc("\u5728\u5DE6\u4FA7\u8FB9\u680F\u663E\u793ACheekyChimp\u56FE\u6807").addToggle(i=>i.setValue(this.plugin.settings.showRibbonIcon).onChange(async r=>{this.plugin.settings.showRibbonIcon=r,await this.plugin.saveSettings(),this.plugin.updateRibbonIconVisibility()})),e.createEl("h3",{text:"\u811A\u672C\u7BA1\u7406"}),new u.Setting(e).setName("\u5BFC\u5165\u811A\u672C").setDesc("\u4ECE\u6587\u4EF6\u5BFC\u5165\u7528\u6237\u811A\u672C").addButton(i=>i.setButtonText("\u5BFC\u5165").setCta().onClick(r=>{this.importScript(r)})),new u.Setting(e).setName("\u521B\u5EFA\u65B0\u811A\u672C").setDesc("\u521B\u5EFA\u4E00\u4E2A\u65B0\u7684\u7528\u6237\u811A\u672C").addButton(i=>i.setButtonText("\u521B\u5EFA").setCta().onClick(()=>{this.createScript()})),e.createEl("h3",{text:"\u5DF2\u5B89\u88C5\u7684\u811A\u672C"});let n=e.createDiv({cls:"cheekychimp-script-list"});this.plugin.settings.scripts.length===0?n.createEl("p",{text:'\u6CA1\u6709\u5DF2\u5B89\u88C5\u7684\u7528\u6237\u811A\u672C\u3002\u70B9\u51FB\u4E0A\u65B9\u7684"\u5BFC\u5165"\u6216"\u521B\u5EFA"\u6309\u94AE\u6765\u6DFB\u52A0\u811A\u672C\u3002'}):this.plugin.settings.scripts.forEach(i=>{this.createScriptItem(n,i)})}createScriptItem(e,n){let i=e.createDiv({cls:"cheekychimp-script-item"}),r=i.createDiv({cls:"cheekychimp-script-enabled"}),s=new u.Setting(r).setName("").addToggle(l=>l.setValue(n.enabled).onChange(async f=>{f?this.plugin.scriptManager.enableScript(n.id):this.plugin.scriptManager.disableScript(n.id),await this.plugin.saveSettings()})),o=i.createDiv({cls:"cheekychimp-script-name"}),m=o.createEl("div",{text:n.name,cls:"cheekychimp-script-name-text"});m.addEventListener("dblclick",()=>{let l=document.createElement("input");l.type="text",l.value=n.name,l.className="cheekychimp-script-name-edit",l.style.width="100%",m.replaceWith(l),l.focus(),l.select();let f=async()=>{let h=l.value.trim();if(h&&h!==n.name)try{let v=n.source,b=v.replace(/\/\/ @name\s+.*/,`// @name ${h}`);b!==v&&(this.plugin.scriptManager.updateScript(n.id,b),await this.plugin.saveSettings(),new u.Notice(`\u811A\u672C\u540D\u79F0\u5DF2\u66F4\u65B0\u4E3A "${h}"`),this.display())}catch(v){new u.Notice(`\u66F4\u65B0\u811A\u672C\u540D\u79F0\u5931\u8D25: ${v.message}`),l.replaceWith(m)}else l.replaceWith(m)};l.addEventListener("blur",f),l.addEventListener("keydown",h=>{h.key==="Enter"?f():h.key==="Escape"&&l.replaceWith(m)})}),n.description&&o.createEl("div",{text:n.description,cls:"cheekychimp-script-description"});let g=i.createDiv({cls:"cheekychimp-script-actions"}),p=new u.ButtonComponent(g).setIcon("pencil").setTooltip("\u7F16\u8F91").onClick(()=>{this.editScript(n)}),d=new u.ButtonComponent(g).setIcon("trash").setTooltip("\u5220\u9664").onClick(()=>{this.deleteScript(n)})}async importScript(e){let n=new u.Menu;n.addItem(i=>{i.setTitle("\u4ECE\u6587\u4EF6\u5BFC\u5165").setIcon("folder").onClick(()=>{this.importFromFile()})}),n.addItem(i=>{i.setTitle("\u4ECEURL\u5BFC\u5165").setIcon("link").onClick(()=>{this.importFromUrl()})}),n.addItem(i=>{i.setTitle("\u4ECE\u7C98\u8D34\u677F\u5BFC\u5165").setIcon("clipboard").onClick(()=>{this.importFromClipboard()})}),n.showAtMouseEvent(e)}async importFromFile(){let e=document.createElement("input");e.type="file",e.accept=".js,.user.js",e.style.display="none",document.body.appendChild(e),e.addEventListener("change",async n=>{let r=n.target.files;if(!r||r.length===0){document.body.removeChild(e);return}let s=r[0];try{let o=await this.readFileAsText(s);if(!o.includes("// ==UserScript==")||!o.includes("// ==/UserScript==")){new u.Notice("\u5BFC\u5165\u5931\u8D25\uFF1A\u65E0\u6548\u7684\u7528\u6237\u811A\u672C\u683C\u5F0F"),document.body.removeChild(e);return}let m=this.plugin.scriptManager.addScript(o);await this.plugin.saveSettings(),new u.Notice(`\u811A\u672C "${m.name}" \u5DF2\u5BFC\u5165`),this.display()}catch(o){new u.Notice(`\u5BFC\u5165\u811A\u672C\u5931\u8D25: ${o.message}`)}finally{document.body.removeChild(e)}}),e.click()}async importFromUrl(){new H(this.app,async n=>{try{new u.Notice(`\u6B63\u5728\u4ECE ${n} \u4E0B\u8F7D\u811A\u672C...`);let i=await fetch(n);if(!i.ok)throw new Error(`\u8BF7\u6C42\u5931\u8D25: ${i.status} ${i.statusText}`);let r=await i.text();if(!r.includes("// ==UserScript==")||!r.includes("// ==/UserScript=="))throw new Error("\u4E0D\u662F\u6709\u6548\u7684\u7528\u6237\u811A\u672C\u683C\u5F0F");let s=this.plugin.scriptManager.addScript(r);await this.plugin.saveSettings(),new u.Notice(`\u811A\u672C "${s.name}" \u5DF2\u5BFC\u5165`),this.display()}catch(i){new u.Notice(`\u5BFC\u5165\u811A\u672C\u5931\u8D25: ${i.message}`)}}).open()}async importFromClipboard(){new O(this.app,async n=>{try{if(!n.includes("// ==UserScript==")||!n.includes("// ==/UserScript=="))throw new Error("\u4E0D\u662F\u6709\u6548\u7684\u7528\u6237\u811A\u672C\u683C\u5F0F");let i=this.plugin.scriptManager.addScript(n);await this.plugin.saveSettings(),new u.Notice(`\u811A\u672C "${i.name}" \u5DF2\u5BFC\u5165`),this.display()}catch(i){new u.Notice(`\u5BFC\u5165\u811A\u672C\u5931\u8D25: ${i.message}`)}}).open()}readFileAsText(e){return new Promise((n,i)=>{let r=new FileReader;r.onload=s=>{s.target?n(s.target.result):i(new Error("\u8BFB\u53D6\u6587\u4EF6\u5931\u8D25"))},r.onerror=()=>{i(new Error("\u8BFB\u53D6\u6587\u4EF6\u5931\u8D25"))},r.readAsText(e)})}async createScript(){let e=`// ==UserScript==
// @name \u65B0\u811A\u672C
// @namespace obsidian-cheekychimp
// @version 0.1
// @description \u5728\u6B64\u5904\u586B\u5199\u811A\u672C\u63CF\u8FF0
// @author \u4F60\u7684\u540D\u5B57
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// \u4F60\u7684\u4EE3\u7801\u5728\u8FD9\u91CC...
console.log('Hello from Javascript!');
})();`;new _(this.app,e,async i=>{try{let r=this.plugin.scriptManager.addScript(i);await this.plugin.saveSettings(),new u.Notice(`\u811A\u672C "${r.name}" \u5DF2\u521B\u5EFA`),this.display()}catch(r){new u.Notice(`\u521B\u5EFA\u811A\u672C\u5931\u8D25: ${r.message}`)}}).open()}async editScript(e){new _(this.app,e.source,async i=>{try{this.plugin.scriptManager.updateScript(e.id,i),await this.plugin.saveSettings(),new u.Notice(`\u811A\u672C "${e.name}" \u5DF2\u66F4\u65B0`),this.display()}catch(r){new u.Notice(`\u66F4\u65B0\u811A\u672C\u5931\u8D25: ${r.message}`)}}).open()}async deleteScript(e){if(await new Promise(i=>{new B(this.app,`\u786E\u5B9A\u8981\u5220\u9664\u811A\u672C "${e.name}" \u5417\uFF1F`,i).open()}))try{this.plugin.scriptManager.removeScript(e.id),await this.plugin.saveSettings(),new u.Notice(`\u811A\u672C "${e.name}" \u5DF2\u5220\u9664`),this.display()}catch(i){new u.Notice(`\u5220\u9664\u811A\u672C\u5931\u8D25: ${i.message}`)}}},O=class extends u.Modal{constructor(e,n){super(e);this.content="";this.onSubmit=n}onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("cheekychimp-dialog"),e.createEl("h2",{text:"\u5BFC\u5165\u7528\u6237\u811A\u672C"}),e.createEl("p",{text:"\u7C98\u8D34\u7528\u6237\u811A\u672C\u5185\u5BB9:"}),e.createEl("textarea",{cls:"cheekychimp-editor"}).addEventListener("input",o=>{this.content=o.target.value});let i=e.createDiv({cls:"modal-button-container"});i.createEl("button",{text:"\u53D6\u6D88",cls:"mod-warning"}).addEventListener("click",()=>{this.close()}),i.createEl("button",{text:"\u5BFC\u5165",cls:"mod-cta"}).addEventListener("click",()=>{if(!this.content){new u.Notice("\u8BF7\u8F93\u5165\u811A\u672C\u5185\u5BB9");return}this.onSubmit(this.content),this.close()})}onClose(){let{contentEl:e}=this;e.empty()}},_=class extends u.Modal{constructor(e,n,i){super(e);this.content=n,this.onSubmit=i}onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("cheekychimp-dialog"),e.style.width="500px",e.style.maxWidth="80vw",e.createEl("h2",{text:"\u7F16\u8F91\u7528\u6237\u811A\u672C"});let n=e.createEl("textarea",{cls:"cheekychimp-editor"});n.value=this.content,n.style.width="100%",n.style.height="500px",n.style.minHeight="400px",n.style.fontSize="14px",n.style.fontFamily="monospace",n.style.padding="10px",n.style.boxSizing="border-box",n.addEventListener("input",o=>{this.content=o.target.value});let i=e.createDiv({cls:"modal-button-container"});i.createEl("button",{text:"\u53D6\u6D88",cls:"mod-warning"}).addEventListener("click",()=>{this.close()}),i.createEl("button",{text:"\u4FDD\u5B58",cls:"mod-cta"}).addEventListener("click",()=>{if(!this.content){new u.Notice("\u811A\u672C\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A");return}this.onSubmit(this.content),this.close()})}onClose(){let{contentEl:e}=this;e.empty()}},B=class extends u.Modal{constructor(e,n,i){super(e);this.message=n,this.onConfirm=i}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"\u786E\u8BA4"}),e.createEl("p",{text:this.message});let n=e.createDiv({cls:"modal-button-container"});n.createEl("button",{text:"\u53D6\u6D88",cls:"mod-warning"}).addEventListener("click",()=>{this.onConfirm(!1),this.close()}),n.createEl("button",{text:"\u786E\u8BA4",cls:"mod-cta"}).addEventListener("click",()=>{this.onConfirm(!0),this.close()})}onClose(){let{contentEl:e}=this;e.empty()}},H=class extends u.Modal{constructor(e,n){super(e);this.url="";this.onSubmit=n}onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("cheekychimp-dialog"),e.createEl("h2",{text:"\u4ECEURL\u5BFC\u5165\u7528\u6237\u811A\u672C"}),e.createEl("p",{text:"\u8F93\u5165\u7528\u6237\u811A\u672C\u7684URL:"});let n=new u.TextComponent(e);n.setPlaceholder("https://example.com/userscript.user.js"),n.inputEl.addClass("cheekychimp-url-input"),n.inputEl.style.width="100%",n.onChange(o=>{this.url=o});let i=e.createDiv({cls:"modal-button-container"});i.createEl("button",{text:"\u53D6\u6D88",cls:"mod-warning"}).addEventListener("click",()=>{this.close()}),i.createEl("button",{text:"\u5BFC\u5165",cls:"mod-cta"}).addEventListener("click",()=>{if(!this.url){new u.Notice("\u8BF7\u8F93\u5165\u6709\u6548\u7684URL");return}try{this.url.match(/^https?:\/\//)||(this.url="https://"+this.url),new URL(this.url)}catch(o){new u.Notice("\u8BF7\u8F93\u5165\u6709\u6548\u7684URL");return}this.onSubmit(this.url),this.close()})}onClose(){let{contentEl:e}=this;e.empty()}};var A=class{constructor(){this.id="",this.name="",this.namespace="",this.version="",this.description="",this.includes=[],this.matches=[],this.excludes=[],this.resources=[],this.requires=[],this.author="",this.homepage="",this.icon="",this.runAt="document-idle",this.enabled=!0,this.source="",this.lastUpdated=Date.now(),this.position=0}};var W=class{static getScriptId(t){var s;let e=Date.now().toString(36),n="",r=encodeURI(t).match(/[a-zA-Z0-9]/g);return r&&r.length>0?n=r.join(""):n=((s=btoa(t).match(/[a-zA-Z0-9]/g))==null?void 0:s.join(""))||"script",`${n}_${e}`}static parseScript(t){let e=new A;e.source=t;let n=t.indexOf(this.HEADER_START),i=t.indexOf(this.HEADER_END);if(n===-1||i===-1||i<=n)throw new Error("Invalid userscript: metadata block not found");let s=t.substring(n+this.HEADER_START.length,i).split(`
`),o=!1;for(let m of s){let g=m.trim();if(!g||!g.startsWith("//"))continue;let p=g.replace(/^\/\/\s*/,"").trim();if(!p.startsWith("@"))continue;let d=p.match(/@([a-zA-Z0-9_\-]+)\s+(.*)/);if(!d)continue;let[,l,f]=d,h=f.trim();switch(l){case"name":e.name=h,o=!0;break;case"namespace":e.namespace=h;break;case"version":e.version=h;break;case"description":e.description=h;break;case"author":e.author=h;break;case"homepage":case"website":case"source":e.homepage=h;break;case"icon":case"iconURL":case"defaulticon":e.icon=h;break;case"include":e.includes.push(h);break;case"match":e.matches.push(h);break;case"exclude":e.excludes.push(h);break;case"require":e.requires.push(h);break;case"resource":let v=h.match(/(\S+)\s+(.*)/);if(v){let[,b,C]=v;e.resources.push({name:b.trim(),url:C.trim()})}break;case"run-at":["document-start","document-end","document-idle"].includes(h)&&(e.runAt=h);break}}return(!o||!e.name)&&(e.name="\u672A\u547D\u540D\u811A\u672C",console.warn("\u811A\u672C\u6CA1\u6709\u540D\u79F0\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u540D\u79F0")),e.id=W.getScriptId(e.name),e}},I=W;I.HEADER_START="==UserScript==",I.HEADER_END="==/UserScript==";var j=class{constructor(){this.scripts=new Map;this.eventListeners={}}on(t,e){this.eventListeners[t]=e}getAllScripts(){return Array.from(this.scripts.values()).sort((t,e)=>t.position-e.position)}getScript(t){return this.scripts.get(t)}addScript(t){try{let e=I.parseScript(t);if(this.scripts.has(e.id))throw new Error(`Script with name '${e.name}' already exists`);return e.position=this.scripts.size,this.scripts.set(e.id,e),this.eventListeners.onScriptAdded&&this.eventListeners.onScriptAdded(e),e}catch(e){throw new Error(`Failed to add script: ${e.message}`)}}updateScript(t,e){if(!this.scripts.has(t))throw new Error(`Script with ID '${t}' not found`);try{let n=this.scripts.get(t),i=I.parseScript(e);return i.id=t,i.position=(n==null?void 0:n.position)||0,i.enabled=(n==null?void 0:n.enabled)||!0,i.lastUpdated=Date.now(),this.scripts.set(t,i),this.eventListeners.onScriptUpdated&&this.eventListeners.onScriptUpdated(i),i}catch(n){throw new Error(`Failed to update script: ${n.message}`)}}removeScript(t){if(!this.scripts.has(t))throw new Error(`Script with ID '${t}' not found`);this.scripts.delete(t),this.getAllScripts().forEach((n,i)=>{n.position=i}),this.eventListeners.onScriptRemoved&&this.eventListeners.onScriptRemoved(t)}enableScript(t){let e=this.scripts.get(t);if(!e)throw new Error(`Script with ID '${t}' not found`);e.enabled=!0,this.eventListeners.onScriptEnabled&&this.eventListeners.onScriptEnabled(t)}disableScript(t){let e=this.scripts.get(t);if(!e)throw new Error(`Script with ID '${t}' not found`);e.enabled=!1,this.eventListeners.onScriptDisabled&&this.eventListeners.onScriptDisabled(t)}findScriptsForUrl(t){let e=[];for(let n of this.getAllScripts()){if(!n.enabled)continue;let i=n.includes.length===0||n.includes.some(o=>this.matchUrlPattern(t,o)),r=n.excludes.some(o=>this.matchUrlPattern(t,o)),s=n.matches.length===0||n.matches.some(o=>this.matchUrlPattern(t,o));i&&!r&&s&&e.push(n)}return e.sort((n,i)=>n.position-i.position)}matchUrlPattern(t,e){if(e==="*")return!0;try{let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return n="^"+n+"$",new RegExp(n).test(t)}catch(n){return console.error(`Invalid pattern: ${e}`,n),!1}}loadScripts(t){this.scripts.clear(),t.forEach(e=>{this.scripts.set(e.id,e)})}moveScriptUp(t){let e=this.scripts.get(t);if(!e)throw new Error(`Script with ID '${t}' not found`);if(e.position===0)return;let n=this.getAllScripts().find(i=>i.position===e.position-1);n&&(n.position++,e.position--,this.eventListeners.onScriptUpdated&&(this.eventListeners.onScriptUpdated(e),this.eventListeners.onScriptUpdated(n)))}moveScriptDown(t){let e=this.scripts.get(t);if(!e)throw new Error(`Script with ID '${t}' not found`);let n=this.getAllScripts();if(e.position===n.length-1)return;let i=n.find(r=>r.position===e.position+1);i&&(i.position--,e.position++,this.eventListeners.onScriptUpdated&&(this.eventListeners.onScriptUpdated(e),this.eventListeners.onScriptUpdated(i)))}};var U=class{constructor(t){this.cache=new Map;this.plugin=t}async getValue(t,e){if(this.cache.has(t))return this.cache.get(t);let n=await this.plugin.loadData()||{},i=t in n?n[t]:e;return this.cache.set(t,i),i}async setValue(t,e){this.cache.set(t,e);let n=await this.plugin.loadData()||{};n[t]=e,await this.plugin.saveData(n)}async deleteValue(t){this.cache.delete(t);let e=await this.plugin.loadData()||{};t in e&&(delete e[t],await this.plugin.saveData(e))}async listValues(){let t=await this.plugin.loadData()||{};return Object.keys(t)}clearCache(){this.cache.clear()}};var V=class{constructor(){this.translations={zh:{plugin_name:"CheekyChimp",plugin_description:"Obsidian\u7528\u6237\u811A\u672C\u7BA1\u7406\u5668",settings:"\u8BBE\u7F6E",scripts_manager:"\u811A\u672C\u7BA1\u7406\u5668",add_script:"\u6DFB\u52A0\u811A\u672C",import_script:"\u5BFC\u5165\u811A\u672C",create_script:"\u521B\u5EFA\u811A\u672C",edit_script:"\u7F16\u8F91\u811A\u672C",delete_script:"\u5220\u9664\u811A\u672C",enable_script:"\u542F\u7528\u811A\u672C",disable_script:"\u7981\u7528\u811A\u672C",script_settings:"\u811A\u672C\u8BBE\u7F6E",active_scripts:"\u5DF2\u542F\u7528\u7684\u811A\u672C",no_active_scripts:"\u5F53\u524D\u6CA1\u6709\u542F\u7528\u7684\u811A\u672C",script_added:"\u811A\u672C\u5DF2\u6DFB\u52A0",script_updated:"\u811A\u672C\u5DF2\u66F4\u65B0",script_deleted:"\u811A\u672C\u5DF2\u5220\u9664",script_enabled:"\u811A\u672C\u5DF2\u542F\u7528",script_disabled:"\u811A\u672C\u5DF2\u7981\u7528",script_error:"\u811A\u672C\u9519\u8BEF",script_load_error:"\u52A0\u8F7D\u811A\u672C\u5931\u8D25",script_execute_error:"\u6267\u884C\u811A\u672C\u5931\u8D25",error_script_exists:"\u5DF2\u5B58\u5728\u540C\u540D\u811A\u672C",error_invalid_script:"\u65E0\u6548\u7684\u811A\u672C",error_script_not_found:"\u672A\u627E\u5230\u811A\u672C",error_cross_origin:"\u8DE8\u57DF\u8BF7\u6C42\u5931\u8D25",error_injection_failed:"\u6CE8\u5165\u811A\u672C\u5931\u8D25",confirm_delete:"\u786E\u5B9A\u8981\u5220\u9664\u6B64\u811A\u672C\u5417\uFF1F\u6B64\u64CD\u4F5C\u4E0D\u53EF\u64A4\u9500\u3002",confirm_yes:"\u662F",confirm_no:"\u5426",confirm_cancel:"\u53D6\u6D88",log_injecting:"\u6B63\u5728\u6CE8\u5165\u811A\u672C",log_injection_success:"\u811A\u672C\u6CE8\u5165\u6210\u529F",log_injection_failure:"\u811A\u672C\u6CE8\u5165\u5931\u8D25"},en:{plugin_name:"CheekyChimp",plugin_description:"UserScript Manager for Obsidian",settings:"Settings",scripts_manager:"Script Manager",add_script:"Add Script",import_script:"Import Script",create_script:"Create Script",edit_script:"Edit Script",delete_script:"Delete Script",enable_script:"Enable Script",disable_script:"Disable Script",script_settings:"Script Settings",active_scripts:"Active Scripts",no_active_scripts:"No active scripts",script_added:"Script added",script_updated:"Script updated",script_deleted:"Script deleted",script_enabled:"Script enabled",script_disabled:"Script disabled",script_error:"Script error",script_load_error:"Failed to load script",script_execute_error:"Failed to execute script",error_script_exists:"Script with the same name already exists",error_invalid_script:"Invalid script",error_script_not_found:"Script not found",error_cross_origin:"Cross-origin request failed",error_injection_failed:"Script injection failed",confirm_delete:"Are you sure you want to delete this script? This cannot be undone.",confirm_yes:"Yes",confirm_no:"No",confirm_cancel:"Cancel",log_injecting:"Injecting script",log_injection_success:"Script injection successful",log_injection_failure:"Script injection failed"}};this.currentLanguage="zh";this.detectLanguage()}detectLanguage(){try{let t=window.navigator.language;t.startsWith("zh")?this.currentLanguage="zh":this.currentLanguage="en",console.log(`CheekyChimp: \u68C0\u6D4B\u5230\u7CFB\u7EDF\u8BED\u8A00: ${t}, \u4F7F\u7528: ${this.currentLanguage}`)}catch(t){console.warn("CheekyChimp: \u65E0\u6CD5\u68C0\u6D4B\u7CFB\u7EDF\u8BED\u8A00\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BED\u8A00(zh)"),this.currentLanguage="zh"}}setLanguage(t){this.translations[t]?this.currentLanguage=t:(console.warn(`CheekyChimp: \u4E0D\u652F\u6301\u7684\u8BED\u8A00 ${t}, \u4F7F\u7528\u9ED8\u8BA4\u8BED\u8A00(zh)`),this.currentLanguage="zh")}getLanguage(){return this.currentLanguage}t(t,e){let i=(this.translations[this.currentLanguage]||this.translations.zh)[t]||t;return e&&Object.keys(e).forEach(r=>{i=i.replace(`{${r}}`,e[r])}),i}},k=new V;function c(a){return`[CheekyChimp:${a}]`}function ne(a){let t=new Set,e=/\/\/\s*@connect\s+([^\s]+)/g,n;for(;(n=e.exec(a))!==null;)t.add(n[1]);return a.includes("// @connect *")&&t.add("*"),Array.from(t)}function je(a,t){if(t.includes("*")||t.includes("localhost")||t.includes(a))return!0;for(let e of t){if(/^\d+\.\d+\.\d+\.\d+$/.test(e)){if(e===a)return!0;continue}if(a.endsWith("."+e))return!0}return!1}function Ue(a){let t=[];return t.push("// ==UserScript=="),t.push(`// @name ${a.name}`),a.namespace&&t.push(`// @namespace ${a.namespace}`),a.version&&t.push(`// @version ${a.version}`),a.description&&t.push(`// @description ${a.description}`),a.author&&t.push(`// @author ${a.author}`),a.includes.forEach(n=>{t.push(`// @include ${n}`)}),a.matches.forEach(n=>{t.push(`// @match ${n}`)}),a.excludes.forEach(n=>{t.push(`// @exclude ${n}`)}),a.requires.forEach(n=>{t.push(`// @require ${n}`)}),a.resources.forEach(n=>{t.push(`// @resource ${n.name} ${n.url}`)}),a.runAt&&t.push(`// @run-at ${a.runAt}`),ne(a.source).forEach(n=>{t.push(`// @connect ${n}`)}),t.push("// @grant unsafeWindow"),t.push("// @grant GM_getValue"),t.push("// @grant GM_setValue"),t.push("// @grant GM_deleteValue"),t.push("// @grant GM_listValues"),t.push("// @grant GM_getResourceText"),t.push("// @grant GM_getResourceURL"),t.push("// @grant GM_addStyle"),t.push("// @grant GM_registerMenuCommand"),t.push("// @grant GM_unregisterMenuCommand"),t.push("// @grant GM_xmlhttpRequest"),t.push("// @grant GM_openInTab"),t.push("// @grant GM_setClipboard"),t.push("// @grant GM_notification"),t.push("// ==/UserScript=="),t.join(`
`)}function Re(a,t){return!a.matches||a.matches.length===0||!a.enabled?!1:a.matches.some(e=>re(e,t))}function De(a){if(a==="*")return/.*/;if(a.includes("://"))return ie(a);let t=a.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${t}$`)}function ie(a){if(a==="*://*/*")return/^(http|https):\/\/.*/;let t=/^((\*|http|https|file|ftp):\/\/)((\*|(?:\*\.)?[^/*]+)?)\/(.*)$/.exec(a);if(!t)throw new Error(`\u65E0\u6548\u7684\u5339\u914D\u6A21\u5F0F: ${a}`);let[,,e,,n,i]=t,r="^";if(e==="*"?r+="(http|https)":r+=e,r+="://",n==="*")r+="[^/]*";else if(n.startsWith("*.")){let s=n.substring(2);r+="([^/]*\\.)?"+z(s)}else r+=z(n);return i==="*"?r+="(/.*)?":i===""?r+="/?":r+="/"+i.split("*").map(z).join(".*"),r+="$",new RegExp(r)}function z(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function re(a,t){if(a.startsWith("/")&&a.endsWith("/"))try{return new RegExp(a.slice(1,-1)).test(t)}catch(e){return console.error(`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${a}`,e),!1}try{let e=a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&").replace(/\\\*/g,".*").replace(/\\\?/g,".");return new RegExp(`^${e}$`).test(t)}catch(e){return console.error(`\u65E0\u6548\u7684\u5339\u914D\u6A21\u5F0F: ${a}`,e),!1}}function Ne(a=12){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=t.length,n="";for(let i=0;i<a;i++)n+=t.charAt(Math.floor(Math.random()*e));return n}function Pe(a,t){let e=Object.keys(t),n=Object.values(t);try{let i=new Function(...e,a);return()=>i.apply(null,n)}catch(i){return console.error(`${c("Utils")}: \u521B\u5EFA\u6C99\u76D2\u5931\u8D25:`,i),()=>{throw new Error(`\u6C99\u76D2\u521B\u5EFA\u5931\u8D25: ${i}`)}}}function Ge(a){try{let t=new URL(a);return{origin:t.origin,protocol:t.protocol,host:t.host,pathname:t.pathname}}catch(t){return console.warn(`${c("Utils")}: \u89E3\u6790URL\u5931\u8D25:`,t),{origin:"",protocol:"",host:"",pathname:""}}}function Fe(a){return a.runAt||"document-idle"}function Oe(a,t,e){return a?t?!e||e.length===0?(console.info("CheekyChimp: \u6CA1\u6709\u53EF\u6CE8\u5165\u7684\u811A\u672C"),!1):!0:(console.warn("CheekyChimp: \u6CE8\u5165\u5931\u8D25: URL\u4E3A\u7A7A"),!1):(console.warn("CheekyChimp: \u6CE8\u5165\u5931\u8D25: webview\u4E3A\u7A7A"),!1)}function Be(a){return{documentStart:a.filter(t=>t.runAt==="document-start"),documentEnd:a.filter(t=>t.runAt==="document-end"),documentIdle:a.filter(t=>t.runAt==="document-idle"||!t.runAt)}}var K=require("obsidian"),R=class{constructor(){this.commands=[];this.STORAGE_PREFIX="cheekychimp_menu_command:";this.GLOBAL_COMMAND_PROPERTY="_cheekyChimpCommands";this.loadAllCommands(),this.setupCommandEventListeners(),console.log(`${c("MenuCommandManager")}: \u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u5DF2\u52A0\u8F7D ${this.commands.length} \u4E2A\u547D\u4EE4`)}registerMenuCommand(t,e,n,i){try{let r=Date.now().toString(36)+Math.random().toString(36).substr(2,5),s={id:r,name:e,callback:n,accessKey:i,scriptId:t.id,scriptName:t.name};return this.commands.push(s),this.saveCommand(s),this.setupCommandEventListener(s),this.addToGlobalObject(s),console.log(`${c("MenuCommandManager")}: \u5DF2\u6CE8\u518C\u547D\u4EE4 "${e}" \u6765\u81EA\u811A\u672C "${t.name}"`),r}catch(r){return console.error(`${c("MenuCommandManager")}: \u6CE8\u518C\u547D\u4EE4 "${e}" \u5931\u8D25:`,r),-1}}unregisterMenuCommand(t,e){try{let n=this.commands.findIndex(i=>i.scriptId===t&&i.id===e);if(n>=0){let i=this.commands[n];return this.commands.splice(n,1),localStorage.removeItem(this.getStorageKey(i)),document.removeEventListener(`cheekychimp-command-${e}`,r=>{}),this.removeFromGlobalObject(i),console.log(`${c("MenuCommandManager")}: \u5DF2\u6CE8\u9500\u547D\u4EE4 ID: ${e}`),!0}return console.warn(`${c("MenuCommandManager")}: \u672A\u627E\u5230\u8981\u6CE8\u9500\u7684\u547D\u4EE4 ID: ${e}`),!1}catch(n){return console.error(`${c("MenuCommandManager")}: \u6CE8\u9500\u547D\u4EE4 ID: ${e} \u5931\u8D25:`,n),!1}}unregisterAllMenuCommands(t){try{let e=this.commands.filter(n=>n.scriptId===t);for(let n of e)this.unregisterMenuCommand(t,n.id);return console.log(`${c("MenuCommandManager")}: \u5DF2\u6CE8\u9500\u811A\u672C ID: ${t} \u7684\u6240\u6709\u547D\u4EE4`),!0}catch(e){return console.error(`${c("MenuCommandManager")}: \u6CE8\u9500\u811A\u672C ID: ${t} \u7684\u6240\u6709\u547D\u4EE4\u5931\u8D25:`,e),!1}}getScriptCommands(t){return this.commands.filter(e=>e.scriptId===t)}getAllCommands(){return[...this.commands]}executeCommand(t){try{let e=this.commands.find(n=>n.id===t);return e?(e.callback(),new K.Notice(`\u5DF2\u6267\u884C\u547D\u4EE4: ${e.name}`),!0):(console.warn(`${c("MenuCommandManager")}: \u672A\u627E\u5230\u8981\u6267\u884C\u7684\u547D\u4EE4 ID: ${t}`),!1)}catch(e){return console.error(`${c("MenuCommandManager")}: \u6267\u884C\u547D\u4EE4 ID: ${t} \u5931\u8D25:`,e),!1}}loadAllCommands(){try{this.commands=[];for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);if(e&&e.startsWith(this.STORAGE_PREFIX))try{let n=localStorage.getItem(e);if(n){let i=JSON.parse(n);this.commands.push(i)}}catch(n){console.warn(`${c("MenuCommandManager")}: \u52A0\u8F7D\u547D\u4EE4\u5931\u8D25:`,n)}}this.loadFromGlobalObject(),console.log(`${c("MenuCommandManager")}: \u5DF2\u52A0\u8F7D ${this.commands.length} \u4E2A\u4FDD\u5B58\u7684\u547D\u4EE4`)}catch(t){console.error(`${c("MenuCommandManager")}: \u52A0\u8F7D\u547D\u4EE4\u5931\u8D25:`,t)}}saveCommand(t){try{let e={...t};delete e.callback,localStorage.setItem(this.getStorageKey(t),JSON.stringify(e))}catch(e){console.error(`${c("MenuCommandManager")}: \u4FDD\u5B58\u547D\u4EE4\u5931\u8D25:`,e)}}getStorageKey(t){return`${this.STORAGE_PREFIX}${t.scriptId}:${t.id}`}setupCommandEventListener(t){let e=`cheekychimp-command-${t.id}`;document.removeEventListener(e,n=>{}),document.addEventListener(e,n=>{try{console.log(`${c("MenuCommandManager")}: \u6267\u884C\u547D\u4EE4 "${t.name}"`),t.callback()}catch(i){console.error(`${c("MenuCommandManager")}: \u6267\u884C\u547D\u4EE4 "${t.name}" \u5931\u8D25:`,i)}})}setupCommandEventListeners(){document.addEventListener("cheekychimp-command-registered",t=>{try{let e=t.detail;if(e&&e.scriptId&&e.commandId&&e.name&&e.callback){let n={id:e.commandId,name:e.name,callback:e.callback,accessKey:e.accessKey,scriptId:e.scriptId,scriptName:e.scriptName||"Unknown Script"};this.commands.some(r=>r.scriptId===n.scriptId&&r.id===n.id)||(this.commands.push(n),this.saveCommand(n),this.setupCommandEventListener(n))}}catch(e){console.error(`${c("MenuCommandManager")}: \u5904\u7406\u547D\u4EE4\u6CE8\u518C\u4E8B\u4EF6\u5931\u8D25:`,e)}})}loadFromGlobalObject(){try{let t=window[this.GLOBAL_COMMAND_PROPERTY];if(!t)return;for(let e in t){let n=t[e];if(Array.isArray(n)){for(let i of n)if(i&&i.id&&i.name&&typeof i.callback=="function"&&!this.commands.some(s=>s.scriptId===e&&s.id===i.id)){let s={id:i.id,name:i.name,callback:i.callback,accessKey:i.accessKey,scriptId:e,scriptName:"From Global Object"};this.commands.push(s),this.setupCommandEventListener(s)}}}}catch(t){console.error(`${c("MenuCommandManager")}: \u4ECE\u5168\u5C40\u5BF9\u8C61\u52A0\u8F7D\u547D\u4EE4\u5931\u8D25:`,t)}}addToGlobalObject(t){try{window[this.GLOBAL_COMMAND_PROPERTY]||(window[this.GLOBAL_COMMAND_PROPERTY]={}),window[this.GLOBAL_COMMAND_PROPERTY][t.scriptId]||(window[this.GLOBAL_COMMAND_PROPERTY][t.scriptId]=[]),window[this.GLOBAL_COMMAND_PROPERTY][t.scriptId].push({id:t.id,name:t.name,callback:t.callback,accessKey:t.accessKey})}catch(e){console.error(`${c("MenuCommandManager")}: \u6DFB\u52A0\u547D\u4EE4\u5230\u5168\u5C40\u5BF9\u8C61\u5931\u8D25:`,e)}}removeFromGlobalObject(t){try{let e=window[this.GLOBAL_COMMAND_PROPERTY];if(!e||!e[t.scriptId])return;let n=e[t.scriptId],i=n.findIndex(r=>r.id===t.id);i>=0&&n.splice(i,1)}catch(e){console.error(`${c("MenuCommandManager")}: \u4ECE\u5168\u5C40\u5BF9\u8C61\u79FB\u9664\u547D\u4EE4\u5931\u8D25:`,e)}}};var D=class{constructor(){this.commands=new Map;this.COMMANDS_VARIABLE="_gmMenuCommands";this.HELPER_VARIABLE="_gmMenuHelper";this.MENU_BUTTON_ID="cheekychimp-menu-button";console.log(`${c("MenuCommandInjector")}: \u521D\u59CB\u5316\u5B8C\u6210`)}injectMenuCommandSupport(t,e){try{let n=e;n.contentWindow&&n.contentDocument?this.injectIntoIframe(t,n):console.warn(`${c("MenuCommandInjector")}: \u4E0D\u652F\u6301\u7684\u5143\u7D20\u7C7B\u578B\uFF0C\u65E0\u6CD5\u6CE8\u5165\u83DC\u5355\u547D\u4EE4\u652F\u6301`)}catch(n){console.error(`${c("MenuCommandInjector")}: \u6CE8\u5165\u83DC\u5355\u547D\u4EE4\u652F\u6301\u5931\u8D25:`,n)}}injectIntoIframe(t,e){try{if(!e.contentDocument||!e.contentWindow){console.log(`${c("MenuCommandInjector")}: iframe\u5C1A\u672A\u52A0\u8F7D\u5B8C\u6210\uFF0C\u65E0\u6CD5\u6CE8\u5165\u83DC\u5355\u547D\u4EE4\u652F\u6301`);return}let n=`
(function() {
// \u68C0\u67E5\u662F\u5426\u5DF2\u5B58\u5728\u83DC\u5355\u52A9\u624B
if (window.${this.HELPER_VARIABLE}) {
console.log('[CheekyChimp] \u83DC\u5355\u547D\u4EE4\u52A9\u624B\u5DF2\u5B58\u5728\uFF0C\u8DF3\u8FC7\u6CE8\u5165');
return;
}
// \u521B\u5EFA\u5168\u5C40\u547D\u4EE4\u5B58\u50A8
if (!window.${this.COMMANDS_VARIABLE}) {
window.${this.COMMANDS_VARIABLE} = [];
}
// \u521B\u5EFA\u83DC\u5355\u52A9\u624B\u5BF9\u8C61
window.${this.HELPER_VARIABLE} = {
scriptId: '${t.id}',
scriptName: '${t.name.replace(/'/g,"\\'")}',
menuButtonId: '${this.MENU_BUTTON_ID}',
initialized: false,
/**
* \u521D\u59CB\u5316\u83DC\u5355\u52A9\u624B
*/
initialize: function() {
if (this.initialized) return;
try {
// \u76D1\u542C\u83DC\u5355\u6309\u94AE\u521B\u5EFA\u4E8B\u4EF6
document.addEventListener('cheekychimp-menu-button-created', this.setupMenuButton.bind(this));
// \u53D1\u9001\u811A\u672C\u4FE1\u606F\u5230\u7236\u7A97\u53E3
window.parent.postMessage({
type: 'cheekychimp-script-info',
scriptId: this.scriptId,
scriptName: this.scriptName
}, '*');
this.initialized = true;
console.log('[CheekyChimp] \u83DC\u5355\u547D\u4EE4\u52A9\u624B\u521D\u59CB\u5316\u5B8C\u6210');
} catch (error) {
console.error('[CheekyChimp] \u83DC\u5355\u547D\u4EE4\u52A9\u624B\u521D\u59CB\u5316\u5931\u8D25:', error);
}
},
/**
* \u6CE8\u518C\u83DC\u5355\u547D\u4EE4
*/
registerMenuCommand: function(name, callback, accessKey) {
try {
// \u751F\u6210\u552F\u4E00ID
const commandId = Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
// \u521B\u5EFA\u547D\u4EE4\u5BF9\u8C61
const command = {
id: commandId,
name: name,
callback: callback,
accessKey: accessKey,
scriptId: this.scriptId,
scriptName: this.scriptName
};
// \u6DFB\u52A0\u5230\u5168\u5C40\u5B58\u50A8
if (window.${this.COMMANDS_VARIABLE} && Array.isArray(window.${this.COMMANDS_VARIABLE})) {
window.${this.COMMANDS_VARIABLE}.push(command);
}
// \u901A\u77E5\u7236\u7A97\u53E3\u6709\u65B0\u547D\u4EE4
window.parent.postMessage({
type: 'cheekychimp-register-menu-command',
command: {
id: commandId,
name: name,
accessKey: accessKey,
scriptId: this.scriptId,
scriptName: this.scriptName
}
}, '*');
console.log('[CheekyChimp] \u5DF2\u6CE8\u518C\u83DC\u5355\u547D\u4EE4:', name);
return commandId;
} catch (error) {
console.error('[CheekyChimp] \u6CE8\u518C\u83DC\u5355\u547D\u4EE4\u5931\u8D25:', error);
return -1;
}
},
/**
* \u8BBE\u7F6E\u83DC\u5355\u6309\u94AE
*/
setupMenuButton: function(event) {
try {
const menuButtonId = event.detail?.buttonId || this.menuButtonId;
const button = document.getElementById(menuButtonId);
if (button) {
// \u6DFB\u52A0\u547D\u4EE4\u5230\u6309\u94AE\u7684\u6570\u636E\u5C5E\u6027
button.dataset.scriptIds = button.dataset.scriptIds ?
button.dataset.scriptIds + ',' + this.scriptId :
this.scriptId;
console.log('[CheekyChimp] \u5DF2\u5C06\u811A\u672C "' + this.scriptName + '" \u6DFB\u52A0\u5230\u83DC\u5355\u6309\u94AE');
}
} catch (error) {
console.error('[CheekyChimp] \u8BBE\u7F6E\u83DC\u5355\u6309\u94AE\u5931\u8D25:', error);
}
},
/**
* \u6267\u884C\u83DC\u5355\u547D\u4EE4
*/
executeCommand: function(commandId) {
try {
if (!window.${this.COMMANDS_VARIABLE}) return false;
const command = window.${this.COMMANDS_VARIABLE}.find(cmd => cmd.id === commandId);
if (command && typeof command.callback === 'function') {
console.log('[CheekyChimp] \u6267\u884C\u83DC\u5355\u547D\u4EE4:', command.name);
command.callback();
return true;
}
return false;
} catch (error) {
console.error('[CheekyChimp] \u6267\u884C\u83DC\u5355\u547D\u4EE4\u5931\u8D25:', error);
return false;
}
}
};
// \u521D\u59CB\u5316\u83DC\u5355\u52A9\u624B
window.${this.HELPER_VARIABLE}.initialize();
// \u6DFB\u52A0GM API\u517C\u5BB9\u6027\u63A5\u53E3
if (typeof GM === 'undefined') {
window.GM = {};
}
// \u6DFB\u52A0GM_registerMenuCommand\u51FD\u6570
if (typeof GM.registerMenuCommand === 'undefined') {
GM.registerMenuCommand = function(name, callback, accessKey) {
return window.${this.HELPER_VARIABLE}.registerMenuCommand(name, callback, accessKey);
};
}
if (typeof GM_registerMenuCommand === 'undefined') {
window.GM_registerMenuCommand = function(name, callback, accessKey) {
return window.${this.HELPER_VARIABLE}.registerMenuCommand(name, callback, accessKey);
};
}
// \u76D1\u542C\u6765\u81EA\u7236\u7A97\u53E3\u7684\u547D\u4EE4\u6267\u884C\u6D88\u606F
window.addEventListener('message', function(event) {
if (event.data && event.data.type === 'cheekychimp-execute-command') {
window.${this.HELPER_VARIABLE}.executeCommand(event.data.commandId);
}
});
console.log('[CheekyChimp] \u83DC\u5355\u547D\u4EE4\u652F\u6301\u5DF2\u6CE8\u5165\uFF0C\u811A\u672CID:', '${t.id}');
})();
`,i=e.contentDocument.createElement("script");i.textContent=n,e.contentDocument.head.appendChild(i),this.setupMessageListener(t,e),console.log(`${c("MenuCommandInjector")}: \u5DF2\u5411iframe\u6CE8\u5165\u83DC\u5355\u547D\u4EE4\u652F\u6301\uFF0C\u811A\u672C: ${t.name}`)}catch(n){console.error(`${c("MenuCommandInjector")}: \u5411iframe\u6CE8\u5165\u83DC\u5355\u547D\u4EE4\u652F\u6301\u5931\u8D25:`,n)}}setupMessageListener(t,e){window.addEventListener("message",n=>{try{if(n.source!==e.contentWindow)return;let i=n.data;if(!i||typeof i!="object")return;i.type==="cheekychimp-register-menu-command"&&i.command&&this.registerCommand(t,i.command),i.type==="cheekychimp-script-info"&&console.log(`${c("MenuCommandInjector")}: \u63A5\u6536\u5230\u811A\u672C\u4FE1\u606F:`,i.scriptName)}catch(i){console.error(`${c("MenuCommandInjector")}: \u5904\u7406iframe\u6D88\u606F\u5931\u8D25:`,i)}})}executeCommand(t,e){try{let n=t;return n.contentWindow?(n.contentWindow.postMessage({type:"cheekychimp-execute-command",commandId:e},"*"),!0):!1}catch(n){return console.error(`${c("MenuCommandInjector")}: \u53D1\u9001\u6267\u884C\u547D\u4EE4\u6D88\u606F\u5931\u8D25:`,n),!1}}registerCommand(t,e){try{if(!e.id||!e.name||!e.scriptId){console.warn(`${c("MenuCommandInjector")}: \u65E0\u6548\u7684\u547D\u4EE4\u5BF9\u8C61:`,e);return}this.commands.has(t.id)||this.commands.set(t.id,[]);let n=this.commands.get(t.id);n&&(n.push({id:e.id,name:e.name,callback:()=>{},accessKey:e.accessKey,scriptId:e.scriptId,scriptName:e.scriptName||t.name}),console.log(`${c("MenuCommandInjector")}: \u5DF2\u6CE8\u518C\u83DC\u5355\u547D\u4EE4: "${e.name}" \u6765\u81EA\u811A\u672C "${t.name}"`),document.dispatchEvent(new CustomEvent("cheekychimp-command-registered",{detail:{command:e,script:t}})))}catch(n){console.error(`${c("MenuCommandInjector")}: \u6CE8\u518C\u547D\u4EE4\u5931\u8D25:`,n)}}getCommands(t){return this.commands.get(t)||[]}getAllCommands(){let t=[];return this.commands.forEach(e=>{t.push(...e)}),t}getActiveScriptIds(){return Array.from(this.commands.keys())}clearCommands(t){this.commands.delete(t)}clearAllCommands(){this.commands.clear()}};var N=class{constructor(){this.MENU_BUTTON_ID="cheekychimp-menu-button";this.MENU_CONTAINER_ID="cheekychimp-menu-container";this.BUTTON_ICON="\u{1F435}";this.initialized=!1;this.menuButton=null;this.menuContainer=null;this.onExecuteCommand=null;console.log(`${c("ScriptMenuUI")}: \u521D\u59CB\u5316`)}initialize(t){if(!this.initialized)try{this.onExecuteCommand=t||null,this.createMenuButton(),this.createMenuContainer(),this.setupEventListeners(),this.initialized=!0,console.log(`${c("ScriptMenuUI")}: \u521D\u59CB\u5316\u5B8C\u6210`)}catch(e){console.error(`${c("ScriptMenuUI")}: \u521D\u59CB\u5316\u5931\u8D25:`,e)}}injectIntoIframe(t){try{if(!t.contentDocument||!t.contentWindow){console.log(`${c("ScriptMenuUI")}: iframe\u5C1A\u672A\u52A0\u8F7D\u5B8C\u6210\uFF0C\u65E0\u6CD5\u6CE8\u5165\u83DC\u5355UI`);return}this.injectStyles(t);let e=`
(function() {
// \u521B\u5EFA\u83DC\u5355\u6309\u94AE
function createMenuButton() {
// \u5148\u79FB\u9664\u53EF\u80FD\u5B58\u5728\u7684\u65E7\u6309\u94AE
const existingButton = document.getElementById('${this.MENU_BUTTON_ID}');
if (existingButton) existingButton.remove();
// \u521B\u5EFA\u65B0\u6309\u94AE
const button = document.createElement('div');
button.id = '${this.MENU_BUTTON_ID}';
button.innerHTML = '${this.BUTTON_ICON}';
button.title = 'CheekyChimp\u811A\u672C\u83DC\u5355';
button.classList.add('cheekychimp-menu-button');
// \u6DFB\u52A0\u5230\u9875\u9762
document.body.appendChild(button);
// \u53D1\u9001\u6309\u94AE\u521B\u5EFA\u4E8B\u4EF6
document.dispatchEvent(new CustomEvent('cheekychimp-menu-button-created', {
detail: { buttonId: '${this.MENU_BUTTON_ID}' }
}));
return button;
}
// \u521B\u5EFA\u83DC\u5355\u5BB9\u5668
function createMenuContainer() {
// \u5148\u79FB\u9664\u53EF\u80FD\u5B58\u5728\u7684\u65E7\u5BB9\u5668
const existingContainer = document.getElementById('${this.MENU_CONTAINER_ID}');
if (existingContainer) existingContainer.remove();
// \u521B\u5EFA\u65B0\u5BB9\u5668
const container = document.createElement('div');
container.id = '${this.MENU_CONTAINER_ID}';
container.classList.add('cheekychimp-menu-container');
// \u6DFB\u52A0\u5230\u9875\u9762
document.body.appendChild(container);
return container;
}
// \u7B49\u5F85DOM\u52A0\u8F7D\u5B8C\u6210
function onDomReady(callback) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', callback);
} else {
callback();
}
}
// \u521D\u59CB\u5316\u83DC\u5355UI
onDomReady(function() {
// \u786E\u4FDDbody\u5DF2\u7ECF\u5B58\u5728
if (!document.body) {
console.log('[CheekyChimp] \u9875\u9762body\u5C1A\u672A\u52A0\u8F7D\uFF0C\u65E0\u6CD5\u521B\u5EFA\u83DC\u5355');
return;
}
// \u521B\u5EFA\u83DC\u5355\u6309\u94AE\u548C\u5BB9\u5668
const button = createMenuButton();
const container = createMenuContainer();
// \u6DFB\u52A0\u70B9\u51FB\u4E8B\u4EF6
button.addEventListener('click', function(event) {
event.stopPropagation();
// \u901A\u77E5\u7236\u7A97\u53E3\u6253\u5F00\u83DC\u5355
window.parent.postMessage({
type: 'cheekychimp-menu-clicked',
position: {
top: button.getBoundingClientRect().bottom,
left: button.getBoundingClientRect().left,
right: button.getBoundingClientRect().right
}
}, '*');
});
console.log('[CheekyChimp] \u83DC\u5355UI\u5DF2\u6CE8\u5165');
});
})();
`,n=t.contentDocument.createElement("script");n.textContent=e,t.contentDocument.head.appendChild(n),console.log(`${c("ScriptMenuUI")}: \u83DC\u5355UI\u5DF2\u6CE8\u5165\u5230iframe`)}catch(e){console.error(`${c("ScriptMenuUI")}: \u6CE8\u5165\u83DC\u5355UI\u5230iframe\u5931\u8D25:`,e)}}injectStyles(t){try{if(!t.contentDocument)return;let e=t.contentDocument.createElement("style");e.textContent=`
/* \u83DC\u5355\u6309\u94AE\u6837\u5F0F */
.cheekychimp-menu-button {
position: fixed;
top: 20px;
right: 20px;
width: 36px;
height: 36px;
background-color: #3498db;
color: white;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
cursor: pointer;
z-index: 9999;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
user-select: none;
transition: all 0.3s ease;
}
.cheekychimp-menu-button:hover {
transform: scale(1.1);
background-color: #2980b9;
}
/* \u83DC\u5355\u5BB9\u5668\u6837\u5F0F */
.cheekychimp-menu-container {
position: fixed;
top: 60px;
right: 20px;
min-width: 200px;
max-width: 300px;
background-color: white;
border-radius: 8px;
box-shadow: 0 3px 10px rgba(0,0,0,0.2);
z-index: 9998;
display: none;
flex-direction: column;
max-height: 80vh;
overflow-y: auto;
padding: 5px 0;
}
/* \u83DC\u5355\u9879\u6837\u5F0F */
.cheekychimp-menu-item {
padding: 8px 15px;
cursor: pointer;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
transition: background-color 0.2s;
}
.cheekychimp-menu-item:hover {
background-color: #f0f0f0;
}
/* \u83DC\u5355\u6807\u9898\u6837\u5F0F */
.cheekychimp-menu-title {
padding: 5px 15px;
font-weight: bold;
color: #666;
background: #f5f5f5;
border-bottom: 1px solid #eee;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* \u5206\u9694\u7EBF\u6837\u5F0F */
.cheekychimp-menu-divider {
height: 1px;
background-color: #eee;
margin: 5px 0;
}
`,t.contentDocument.head.appendChild(e)}catch(e){console.error(`${c("ScriptMenuUI")}: \u6CE8\u5165\u6837\u5F0F\u5230iframe\u5931\u8D25:`,e)}}createMenuButton(){try{let t=document.getElementById(this.MENU_BUTTON_ID);t&&t.remove(),this.menuButton=document.createElement("div"),this.menuButton.id=this.MENU_BUTTON_ID,this.menuButton.innerHTML=this.BUTTON_ICON,this.menuButton.title="CheekyChimp\u811A\u672C\u83DC\u5355",this.menuButton.style.cssText=`
position: fixed;
top: 20px;
right: 20px;
width: 36px;
height: 36px;
background-color: #3498db;
color: white;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
cursor: pointer;
z-index: 9999;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
user-select: none;
transition: all 0.3s ease;
`,document.body.appendChild(this.menuButton)}catch(t){console.error(`${c("ScriptMenuUI")}: \u521B\u5EFA\u83DC\u5355\u6309\u94AE\u5931\u8D25:`,t)}}createMenuContainer(){try{let t=document.getElementById(this.MENU_CONTAINER_ID);t&&t.remove(),this.menuContainer=document.createElement("div"),this.menuContainer.id=this.MENU_CONTAINER_ID,this.menuContainer.style.cssText=`
position: fixed;
top: 60px;
right: 20px;
min-width: 200px;
max-width: 300px;
background-color: white;
border-radius: 8px;
box-shadow: 0 3px 10px rgba(0,0,0,0.2);
z-index: 9998;
display: none;
flex-direction: column;
max-height: 80vh;
overflow-y: auto;
padding: 5px 0;
`,document.body.appendChild(this.menuContainer)}catch(t){console.error(`${c("ScriptMenuUI")}: \u521B\u5EFA\u83DC\u5355\u5BB9\u5668\u5931\u8D25:`,t)}}setupEventListeners(){!this.menuButton||!this.menuContainer||(this.menuButton.addEventListener("click",()=>{if(this.menuContainer){let t=this.menuContainer.style.display==="flex";this.menuContainer.style.display=t?"none":"flex"}}),document.addEventListener("click",t=>{this.menuButton&&this.menuContainer&&t.target!==this.menuButton&&!this.menuButton.contains(t.target)&&t.target!==this.menuContainer&&!this.menuContainer.contains(t.target)&&(this.menuContainer.style.display="none")}))}updateMenu(t){var e,n;try{if(!this.menuContainer)return;this.menuContainer.innerHTML="";let i=new Set(t.map(d=>d.scriptId)).size;if(console.log(`${c("ScriptMenuUI")}: \u66F4\u65B0\u83DC\u5355\uFF0C\u5171${t.length}\u4E2A\u547D\u4EE4\uFF0C\u6765\u81EA${i}\u4E2A\u811A\u672C`),t.length===0){let d=document.createElement("div");d.style.cssText="padding: 12px 15px; color: #999; text-align: center;",d.textContent="\u6CA1\u6709\u53EF\u7528\u7684\u547D\u4EE4",this.menuContainer.appendChild(d);return}let r=document.createElement("div");r.style.cssText=`
padding: 10px 15px;
font-weight: bold;
color: #333;
background: #f8f8f8;
border-bottom: 1px solid #eee;
display: flex;
align-items: center;
justify-content: space-between;
`,r.innerHTML=`<span style="display:flex;align-items:center;">${this.BUTTON_ICON} <span style="margin-left:5px;">CheekyChimp</span></span>`;let s=document.createElement("span");s.style.cssText="font-size: 11px; color: #999; font-weight: normal;",s.textContent="v1.0",r.appendChild(s),this.menuContainer.appendChild(r);let o=new Map;t.forEach(d=>{var l;o.has(d.scriptId)||o.set(d.scriptId,[]),(l=o.get(d.scriptId))==null||l.push(d)}),[...o.keys()].sort((d,l)=>{let f=o.get(d),h=o.get(l);return!f||!h?0:(f[0].scriptName||"").localeCompare(h[0].scriptName||"")}).forEach((d,l)=>{var b,C;let f=o.get(d)||[];if(f.length===0)return;if(l>0){let S=document.createElement("div");S.style.cssText="height: 1px; background-color: #eee; margin: 5px 0;",(b=this.menuContainer)==null||b.appendChild(S)}let h=f[0].scriptName||"\u672A\u77E5\u811A\u672C",v=document.createElement("div");v.style.cssText=`
padding: 5px 15px;
font-weight: bold;
color: #666;
background: #f5f5f5;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`,v.textContent=`\u{1F4DC} ${h}`,v.title=h,(C=this.menuContainer)==null||C.appendChild(v),f.forEach(S=>{var $;let M=document.createElement("div");M.style.cssText=`
padding: 8px 15px 8px 25px;
cursor: pointer;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
transition: background-color 0.2s;
`,M.textContent=S.name,M.title=S.name,M.addEventListener("mouseenter",function(){this.style.backgroundColor="#f0f0f0"}),M.addEventListener("mouseleave",function(){this.style.backgroundColor="transparent"}),M.addEventListener("click",()=>{this.menuContainer&&(this.menuContainer.style.display="none"),this.executeCommand(S.id)}),($=this.menuContainer)==null||$.appendChild(M)})});let g=document.createElement("div");g.style.cssText="height: 1px; background-color: #eee; margin: 5px 0;",(e=this.menuContainer)==null||e.appendChild(g);let p=document.createElement("div");p.style.cssText=`
padding: 8px 15px;
color: #999;
font-size: 12px;
text-align: center;
cursor: pointer;
`,p.textContent="\u7BA1\u7406\u7528\u6237\u811A\u672C",p.addEventListener("click",()=>{document.dispatchEvent(new CustomEvent("cheekychimp-open-options")),this.menuContainer&&(this.menuContainer.style.display="none")}),(n=this.menuContainer)==null||n.appendChild(p)}catch(i){console.error(`${c("ScriptMenuUI")}: \u66F4\u65B0\u83DC\u5355\u5185\u5BB9\u5931\u8D25:`,i)}}executeCommand(t){try{this.onExecuteCommand&&this.onExecuteCommand(t),console.log(`${c("ScriptMenuUI")}: \u6267\u884C\u547D\u4EE4: ${t}`)}catch(e){console.error(`${c("ScriptMenuUI")}: \u6267\u884C\u547D\u4EE4\u5931\u8D25:`,e)}}showMenu(){this.menuContainer&&(this.menuContainer.style.display="flex")}hideMenu(){this.menuContainer&&(this.menuContainer.style.display="none")}isMenuVisible(){return this.menuContainer?this.menuContainer.style.display==="flex":!1}isInitialized(){return this.initialized}toggleMenu(){this.isMenuVisible()?this.hideMenu():this.showMenu()}};var se=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i))(se||{}),w=class{constructor(t=""){this.moduleName=t;this.moduleName=t}static setGlobalLogLevel(t){w.globalLogLevel=t}debug(t,...e){w.globalLogLevel<=0&&console.debug(this.formatMessage("DEBUG",t),...e)}info(t,...e){w.globalLogLevel<=1&&console.info(this.formatMessage("INFO",t),...e)}warn(t,...e){w.globalLogLevel<=2&&console.warn(this.formatMessage("WARN",t),...e)}error(t,...e){w.globalLogLevel<=3&&console.error(this.formatMessage("ERROR",t),...e)}formatMessage(t,e){let n=new Date().toISOString(),i=this.moduleName?`[${this.moduleName}]`:"";return`${w.LOG_PREFIX} ${n} ${t}${i}: ${e}`}},E=w;E.LOG_PREFIX="CheekyChimp",E.globalLogLevel=1;var oe=(i=>(i.LOG="log",i.WARN="warn",i.NOTIFY="notify",i.ERROR="error",i))(oe||{}),L=class{static handle(t,e,n="log"){let i=`${e}: ${t.message}`;switch(n){case"error":this.logger.error(i,t),this.showErrorNotification(i);break;case"notify":this.logger.warn(i,t),this.showErrorNotification(i);break;case"warn":this.logger.warn(i,t);break;case"log":default:this.logger.info(i);break}}static showErrorNotification(t){try{console.error(`CheekyChimp\u9519\u8BEF: ${t}`),typeof window!="undefined"&&typeof window.Notice=="function"&&new window.Notice(`CheekyChimp\u9519\u8BEF: ${t}`)}catch(e){console.error("\u663E\u793A\u9519\u8BEF\u901A\u77E5\u65F6\u51FA\u9519:",e)}}};L.logger=new E("ErrorHandler");var x=class{constructor(t,e,n){this.storage=t;this.scriptManager=e;this.settings={debug:!1,checkDuplicateInjection:!0,injectionMarkerPrefix:"cheekychimp-injected-",autoReinject:!0,maxRetries:3};this.injectedScripts=new Map;this.logger={info:(t,...e)=>{console.log(`[EnhancedScriptInjector] ${t}`,...e),this.settings.debug&&this.showDebugNotification(`INFO: ${t}`)},warn:(t,...e)=>{console.warn(`[EnhancedScriptInjector] ${t}`,...e),this.settings.debug&&this.showDebugNotification(`WARN: ${t}`,"warning")},error:(t,...e)=>{console.error(`[EnhancedScriptInjector] ${t}`,...e),this.settings.debug&&this.showDebugNotification(`ERROR: ${t}`,"error")},debug:(t,...e)=>{this.settings.debug&&console.debug(`[EnhancedScriptInjector] ${t}`,...e)}};n&&(this.settings={...this.settings,...n}),this.logger.info("\u589E\u5F3A\u7248\u6CE8\u5165\u5668\u521D\u59CB\u5316\u5B8C\u6210")}setSettings(t){this.settings={...this.settings,...t},this.logger.debug("\u5DF2\u66F4\u65B0\u6CE8\u5165\u5668\u8BBE\u7F6E",this.settings)}enableDebug(t=!0){this.settings.debug=t,this.logger.info(`\u8C03\u8BD5\u6A21\u5F0F${t?"\u5DF2\u542F\u7528":"\u5DF2\u7981\u7528"}`)}showDebugNotification(t,e="info"){console.log(`${e==="error"?"\u{1F534}":e==="warning"?"\u{1F7E0}":"\u{1F535}"} ${t}`)}async injectScripts(t,e,n){try{if(!n||n.length===0)return;this.logger.info(`\u4E3AURL [${e}] \u6CE8\u5165 ${n.length} \u4E2A\u811A\u672C`),this.setupSiteAdapter(t,e);let i=n.filter(o=>o.runAt==="document-start"),r=n.filter(o=>o.runAt==="document-end"),s=n.filter(o=>o.runAt==="document-idle"||!o.runAt);if(this.logger.debug(`\u5206\u7C7B\u811A\u672C: start=${i.length}, end=${r.length}, idle=${s.length}`),t instanceof HTMLIFrameElement){for(let o of i)await this.shouldInjectScript(t,o,e)&&await this.injectSingleScript(t,e,o);await this.setupContentLoadedListener(t,e,r),this.setupLoadListener(t,e,s)}else for(let o of n)await this.shouldInjectScript(t,o,e)&&await this.injectSingleScript(t,e,o)}catch(i){this.logger.error(`\u6CE8\u5165\u811A\u672C\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF: ${i.message}`)}}async injectScriptsForUrl(t,e){try{if(!e||!t){this.logger.warn("\u65E0\u6548\u7684URL\u6216element\u53C2\u6570");return}this.logger.info(`\u4E3AURL [${e}] \u67E5\u627E\u5339\u914D\u7684\u811A\u672C`);let n=this.scriptManager.findScriptsForUrl(e);if(!n.length){this.logger.info(`\u6CA1\u6709\u5339\u914DURL [${e}] \u7684\u811A\u672C`);return}await this.injectScripts(t,e,n)}catch(n){this.logger.error(`\u811A\u672C\u6CE8\u5165\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF: ${n.message}`)}}async shouldInjectScript(t,e,n,i=!1){if(!this.settings.checkDuplicateInjection||i)return!0;try{if(t instanceof HTMLIFrameElement&&t.contentDocument){let s=`${this.settings.injectionMarkerPrefix}${e.id}`;if(t.contentDocument.getElementById(s))return this.logger.debug(`\u811A\u672C ${e.name} \u5DF2\u6CE8\u5165\u5230 ${n}\uFF0C\u8DF3\u8FC7`),!1}let r=this.injectedScripts.get(n);return r&&r.has(e.id)?(this.logger.debug(`\u811A\u672C ${e.name} \u5DF2\u5728\u5185\u5B58\u4E2D\u6807\u8BB0\u4E3A\u6CE8\u5165\u5230 ${n}\uFF0C\u8DF3\u8FC7`),!1):!0}catch(r){return this.logger.warn(`\u68C0\u67E5\u811A\u672C\u6CE8\u5165\u72B6\u6001\u65F6\u51FA\u9519: ${r.message}\uFF0C\u5C06\u7EE7\u7EED\u6CE8\u5165`),!0}}async injectSingleScript(t,e,n,i=0){try{this.logger.debug(`\u5F00\u59CB\u6CE8\u5165\u811A\u672C "${n.name}" \u5230 ${e}`);let r=this.prepareScriptWithGMAPI(n,e),s=!1;if(t instanceof HTMLIFrameElement?s=await this.injectScriptToIframe(t,r,n):s=await this.injectScriptToWebview(t,r,n),s)return this.markScriptAsInjected(e,n.id),this.logger.info(`\u811A\u672C "${n.name}" \u6CE8\u5165\u6210\u529F`),!0;throw new Error("\u6CE8\u5165\u5931\u8D25")}catch(r){return this.logger.error(`\u811A\u672C "${n.name}" \u6CE8\u5165\u5931\u8D25: ${r.message}`),i<this.settings.maxRetries?(this.logger.debug(`\u5C1D\u8BD5\u91CD\u65B0\u6CE8\u5165\u811A\u672C "${n.name}"\uFF0C\u5C1D\u8BD5\u6B21\u6570: ${i+1}/${this.settings.maxRetries}`),await this.injectSingleScript(t,e,n,i+1)):!1}}markScriptAsInjected(t,e){var n;this.injectedScripts.has(t)||this.injectedScripts.set(t,new Set),(n=this.injectedScripts.get(t))==null||n.add(e)}async injectScriptToIframe(t,e,n){return new Promise(i=>{try{let r=()=>{try{if(t.contentWindow&&t.contentDocument){let s=`${this.settings.injectionMarkerPrefix}${n.id}`;if(t.contentDocument.getElementById(s)){this.logger.debug(`\u811A\u672C ${n.name} \u5DF2\u6709\u6807\u8BB0\uFF0C\u8DF3\u8FC7\u6CE8\u5165`),i(!0);return}let o=t.contentDocument.createElement("script");o.textContent=e,o.setAttribute("data-script-id",n.id),o.setAttribute("data-script-name",n.name),o.onload=()=>{this.addInjectionMarker(t,n),i(!0)},o.onerror=m=>{this.logger.error(`\u811A\u672C ${n.name} \u52A0\u8F7D\u5931\u8D25: ${m}`),i(!1)},t.contentDocument.head?t.contentDocument.head.appendChild(o):t.contentDocument.body?t.contentDocument.body.appendChild(o):t.contentDocument.documentElement.appendChild(o)}else setTimeout(r,100)}catch(s){this.logger.error(`\u51C6\u5907iframe\u65F6\u51FA\u9519: ${s.message}`),i(!1)}};r()}catch(r){this.logger.error(`\u5411iframe\u6CE8\u5165\u811A\u672C\u65F6\u51FA\u9519: ${r.message}`),i(!1)}})}addInjectionMarker(t,e){try{if(!t.contentDocument||!t.contentDocument.body)return;let n=t.contentDocument.createElement("div");n.id=`${this.settings.injectionMarkerPrefix}${e.id}`,n.style.display="none",n.dataset.scriptId=e.id,n.dataset.scriptName=e.name,n.dataset.injectionTime=Date.now().toString(),t.contentDocument.body.appendChild(n),this.logger.debug(`\u5DF2\u4E3A\u811A\u672C ${e.name} \u6DFB\u52A0\u6CE8\u5165\u6807\u8BB0`)}catch(n){this.logger.warn(`\u65E0\u6CD5\u6DFB\u52A0\u6CE8\u5165\u6807\u8BB0: ${n.message}`)}}async injectScriptToWebview(t,e,n){return new Promise(i=>{try{let r=t;if(typeof r.executeJavaScript=="function"){let s=`
(function() {
try {
// \u68C0\u67E5\u662F\u5426\u5DF2\u6CE8\u5165
if (document.getElementById('${this.settings.injectionMarkerPrefix}${n.id}')) {
console.log('\u811A\u672C\u5DF2\u6CE8\u5165\uFF0C\u8DF3\u8FC7');
return true;
}
// \u6267\u884C\u811A\u672C
${e}
// \u6DFB\u52A0\u6807\u8BB0
const marker = document.createElement('div');
marker.id = '${this.settings.injectionMarkerPrefix}${n.id}';
marker.style.display = 'none';
marker.dataset.scriptId = '${n.id}';
marker.dataset.scriptName = '${n.name}';
marker.dataset.injectionTime = '${Date.now()}';
document.body.appendChild(marker);
return true;
} catch(e) {
console.error('\u6267\u884C\u811A\u672C\u51FA\u9519:', e);
return false;
}
})();
`;r.executeJavaScript(s).then(o=>i(o)).catch(o=>{this.logger.error(`\u4F7F\u7528executeJavaScript\u6CE8\u5165\u5931\u8D25: ${o.message}`),this.injectWithFallbackMethod(t,e,n).then(i).catch(()=>i(!1))})}else if(r.contentWindow)try{let s=this.injectWithEval(r,e,n);i(s)}catch(s){this.logger.error(`\u4F7F\u7528contentWindow\u6CE8\u5165\u5931\u8D25: ${s.message}`),this.injectWithFallbackMethod(t,e,n).then(i).catch(()=>i(!1))}else this.injectWithFallbackMethod(t,e,n).then(i).catch(()=>i(!1))}catch(r){this.logger.error(`\u5411webview\u6CE8\u5165\u811A\u672C\u65F6\u51FA\u9519: ${r.message}`),i(!1)}})}injectWithEval(t,e,n){try{let i=`
document.getElementById('${this.settings.injectionMarkerPrefix}${n.id}') !== null
`;if(t.contentWindow.eval(i))return this.logger.debug(`\u811A\u672C ${n.name} \u5DF2\u6CE8\u5165\u5230contentWindow\uFF0C\u8DF3\u8FC7`),!0;t.contentWindow.eval(e);let s=`
const marker = document.createElement('div');
marker.id = '${this.settings.injectionMarkerPrefix}${n.id}';
marker.style.display = 'none';
marker.dataset.scriptId = '${n.id}';
marker.dataset.scriptName = '${n.name}';
marker.dataset.injectionTime = '${Date.now()}';
document.body.appendChild(marker);
`;return t.contentWindow.eval(s),!0}catch(i){return this.logger.error(`\u4F7F\u7528eval\u6CE8\u5165\u811A\u672C\u5931\u8D25: ${i.message}`),!1}}async injectWithFallbackMethod(t,e,n){try{let i=new Blob([e],{type:"text/javascript"}),r=URL.createObjectURL(i),s=t;return typeof s.send=="function"?(s.send("cheekychimp-inject-script",{scriptContent:e,scriptId:n.id,scriptName:n.name}),!0):new Promise(o=>{let m=document.createElement("iframe");m.style.display="none",m.onload=()=>{var g;try{let p=m.contentDocument||((g=m.contentWindow)==null?void 0:g.document);if(p){let d=p.createElement("script");d.textContent=`
(function() {
try {
// \u5C1D\u8BD5\u901A\u8FC7top\u6216parent\u8BBF\u95EE\u76EE\u6807webview
const targetWindow = top || parent;
if (targetWindow) {
const event = new CustomEvent('cheekychimp-inject', {
detail: {
script: ${JSON.stringify(e)},
scriptId: '${n.id}',
scriptName: '${n.name}'
}
});
targetWindow.dispatchEvent(event);
}
} catch(e) {
console.error('\u6865\u63A5\u6CE8\u5165\u5931\u8D25:', e);
}
})();
`,p.head.appendChild(d),setTimeout(()=>{document.body.removeChild(m)},5e3),o(!0)}else o(!1)}catch(p){this.logger.error(`\u6865\u63A5iframe\u6CE8\u5165\u5931\u8D25: ${p.message}`),o(!1)}},document.body.appendChild(m),setTimeout(()=>URL.revokeObjectURL(r),5e3)})}catch(i){return this.logger.error(`\u5907\u7528\u6CE8\u5165\u65B9\u6CD5\u5931\u8D25: ${i.message}`),!1}}setupSiteAdapter(t,e){try{e.includes("bilibili.com")&&(this.logger.info(`\u68C0\u6D4B\u5230\u54D4\u54E9\u54D4\u54E9\u7F51\u7AD9: ${e}`),this.setupBilibiliSupport(t))}catch(n){this.logger.error(`\u8BBE\u7F6E\u7AD9\u70B9\u9002\u914D\u5668\u51FA\u9519: ${n.message}`)}}setupBilibiliSupport(t){try{t instanceof HTMLIFrameElement&&(t.allowFullscreen=!0,t.setAttribute("allowfullscreen","true"),this.injectBilibiliStyles(t),this.logger.info("\u54D4\u54E9\u54D4\u54E9\u652F\u6301\u8BBE\u7F6E\u5B8C\u6210"))}catch(e){this.logger.error(`\u8BBE\u7F6E\u54D4\u54E9\u54D4\u54E9\u652F\u6301\u51FA\u9519: ${e.message}`)}}injectBilibiliStyles(t){try{if(!t.contentDocument)return;let e=t.contentDocument.createElement("style");e.textContent=`
/* \u4FEE\u590D\u5168\u5C4F\u6309\u94AE\u7684z-index\u95EE\u9898 */
.bilibili-player-video-btn-fullscreen,
.bilibili-player-video-web-fullscreen {
z-index: 100000 !important;
}
/* \u4FEE\u590D\u64AD\u653E\u5668\u63A7\u5236\u680F\u7684z-index\u95EE\u9898 */
.bilibili-player-video-control-wrap {
z-index: 100000 !important;
}
`,t.contentDocument.head.appendChild(e)}catch(e){this.logger.error(`\u6CE8\u5165\u54D4\u54E9\u54D4\u54E9\u6837\u5F0F\u51FA\u9519: ${e.message}`)}}async setupContentLoadedListener(t,e,n){if(!!n.length)try{if(t.contentDocument)if(t.contentDocument.readyState==="loading")t.contentDocument.addEventListener("DOMContentLoaded",async()=>{for(let i of n)await this.shouldInjectScript(t,i,e)&&await this.injectSingleScript(t,e,i)});else for(let i of n)await this.shouldInjectScript(t,i,e)&&await this.injectSingleScript(t,e,i);else t.addEventListener("load",async()=>{for(let i of n)await this.shouldInjectScript(t,i,e)&&await this.injectSingleScript(t,e,i)})}catch(i){this.logger.error(`\u8BBE\u7F6EContentLoaded\u76D1\u542C\u5668\u51FA\u9519: ${i.message}`)}}setupLoadListener(t,e,n){if(!!n.length)try{let i=async()=>{setTimeout(async()=>{for(let r of n)await this.shouldInjectScript(t,r,e)&&await this.injectSingleScript(t,e,r)},100)};t.addEventListener("load",i),t.contentDocument&&t.contentDocument.readyState==="complete"&&i()}catch(i){this.logger.error(`\u8BBE\u7F6ELoad\u76D1\u542C\u5668\u51FA\u9519: ${i.message}`)}}registerRefreshHandler(t,e){try{if(t instanceof HTMLIFrameElement)t.addEventListener("load",async()=>{this.settings.autoReinject&&(this.injectedScripts.delete(e),this.logger.debug(`\u68C0\u6D4B\u5230iframe\u5237\u65B0\uFF0C\u51C6\u5907\u91CD\u65B0\u6CE8\u5165\u811A\u672C: ${e}`),await this.injectScriptsForUrl(t,e))});else{let n=t;typeof n.addEventListener=="function"&&(n.addEventListener("did-navigate",async()=>{if(this.settings.autoReinject){let i=n.src||n.getAttribute("src")||e;this.injectedScripts.delete(e),this.logger.debug(`\u68C0\u6D4B\u5230webview\u5BFC\u822A\uFF0C\u51C6\u5907\u91CD\u65B0\u6CE8\u5165\u811A\u672C: ${i}`),await this.injectScriptsForUrl(t,i)}}),n.addEventListener("did-navigate-in-page",async()=>{this.settings.autoReinject&&(this.logger.debug(`\u68C0\u6D4B\u5230webview\u9875\u5185\u5BFC\u822A\uFF0C\u68C0\u67E5\u811A\u672C: ${e}`),await this.injectScriptsForUrl(t,e))}))}}catch(n){this.logger.error(`\u6CE8\u518C\u5237\u65B0\u5904\u7406\u7A0B\u5E8F\u51FA\u9519: ${n.message}`)}}async reinjectScripts(t,e){try{this.injectedScripts.delete(e),this.logger.info(`\u624B\u52A8\u91CD\u65B0\u6CE8\u5165\u811A\u672C\u5230: ${e}`);let n=this.scriptManager.findScriptsForUrl(e);if(!n.length){this.logger.info(`\u6CA1\u6709\u5339\u914DURL [${e}] \u7684\u811A\u672C`);return}for(let i of n)await this.injectSingleScript(t,e,i)}catch(n){this.logger.error(`\u624B\u52A8\u91CD\u65B0\u6CE8\u5165\u811A\u672C\u51FA\u9519: ${n.message}`)}}prepareScriptWithGMAPI(t,e){let n=this.buildGMAPI(t,e),i=this.buildGMInfo(t,e);return this.wrapScriptWithAPI(t.source,n,i)}buildGMInfo(t,e){return{script:{name:t.name,namespace:t.namespace,description:t.description,version:t.version,includes:t.includes,excludes:t.excludes,matches:t.matches,resources:t.resources,requires:t.requires},version:"0.1.0",scriptHandler:"Obsidian CheekyChimp (Enhanced)",scriptMetaStr:this.getScriptMetaStr(t)}}buildGMAPI(t,e){let n=this;return{GM_info:this.buildGMInfo(t,e),GM_getValue:(i,r)=>this.storage.getValue(`${t.id}:${i}`,r)||r,GM_setValue:(i,r)=>{this.storage.setValue(`${t.id}:${i}`,r)},GM_deleteValue:i=>{this.storage.deleteValue(`${t.id}:${i}`)},GM_listValues:()=>[],GM_getResourceText:i=>"",GM_getResourceURL:i=>"",GM_addStyle:i=>{},GM_xmlhttpRequest:i=>null,GM_registerMenuCommand:(i,r,s)=>0,GM_unregisterMenuCommand:i=>{},GM_openInTab:(i,r)=>null,GM_setClipboard:(i,r)=>{},GM_notification:(i,r)=>{},unsafeWindow:window,GM:{getValue:(i,r)=>Promise.resolve(n.storage.getValue(`${t.id}:${i}`,r)||r),setValue:(i,r)=>(n.storage.setValue(`${t.id}:${i}`,r),Promise.resolve()),deleteValue:i=>(n.storage.deleteValue(`${t.id}:${i}`),Promise.resolve()),listValues:()=>Promise.resolve([]),getResourceUrl:i=>Promise.resolve(""),xmlHttpRequest:i=>null,addStyle:i=>Promise.resolve(null),registerMenuCommand:(i,r,s)=>Promise.resolve(0)}}}wrapScriptWithAPI(t,e,n){let i="";n.script.requires&&n.script.requires.length>0&&(i=`
// \u52A0\u8F7D\u4F9D\u8D56\u811A\u672C
function loadDependencies() {
const deps = ${JSON.stringify(n.script.requires)};
let loaded = 0;
return new Promise((resolve) => {
if (deps.length === 0) {
resolve();
return;
}
deps.forEach((url) => {
const script = document.createElement('script');
script.src = url;
script.onload = () => {
loaded++;
if (loaded === deps.length) {
resolve();
}
};
script.onerror = () => {
console.error('[CheekyChimp Enhanced] \u52A0\u8F7D\u4F9D\u8D56\u5931\u8D25:', url);
loaded++;
if (loaded === deps.length) {
resolve();
}
};
document.head.appendChild(script);
});
});
}
// \u7B49\u5F85\u4F9D\u8D56\u52A0\u8F7D\u5B8C\u6210
await loadDependencies();
`);let r="";return r+=`
const GM_getValue = function(name, defaultValue) {
try {
const value = window.localStorage.getItem('CheekyChimp_' + '${n.script.name}_' + name);
return value === null ? defaultValue : JSON.parse(value);
} catch(e) {
console.error('[CheekyChimp Enhanced] GM_getValue\u9519\u8BEF:', e);
return defaultValue;
}
};
const GM_setValue = function(name, value) {
try {
window.localStorage.setItem('CheekyChimp_' + '${n.script.name}_' + name, JSON.stringify(value));
} catch(e) {
console.error('[CheekyChimp Enhanced] GM_setValue\u9519\u8BEF:', e);
}
};
const GM_deleteValue = function(name) {
try {
window.localStorage.removeItem('CheekyChimp_' + '${n.script.name}_' + name);
} catch(e) {
console.error('[CheekyChimp Enhanced] GM_deleteValue\u9519\u8BEF:', e);
}
};
const GM_listValues = function() {
try {
const values = [];
const prefix = 'CheekyChimp_' + '${n.script.name}_';
for (let i = 0; i < window.localStorage.length; i++) {
const key = window.localStorage.key(i);
if (key && key.startsWith(prefix)) {
values.push(key.substring(prefix.length));
}
}
return values;
} catch(e) {
console.error('[CheekyChimp Enhanced] GM_listValues\u9519\u8BEF:', e);
return [];
}
};
const GM_addStyle = function(css) {
try {
const style = document.createElement('style');
style.textContent = css;
document.head.appendChild(style);
return style;
} catch(e) {
console.error('[CheekyChimp Enhanced] GM_addStyle\u9519\u8BEF:', e);
}
};
// \u521B\u5EFA\u4E00\u4E2A\u6A21\u62DF\u7248\u7684XMLHttpRequest\u51FD\u6570
const GM_xmlhttpRequest = function(details) {
try {
const xhr = new XMLHttpRequest();
xhr.open(details.method || 'GET', details.url, true);
if (details.headers) {
for (const header in details.headers) {
xhr.setRequestHeader(header, details.headers[header]);
}
}
if (details.responseType) {
xhr.responseType = details.responseType;
}
xhr.onload = function() {
if (details.onload) {
details.onload({
responseText: xhr.responseText,
responseXML: xhr.responseXML,
readyState: xhr.readyState,
responseHeaders: xhr.getAllResponseHeaders(),
status: xhr.status,
statusText: xhr.statusText,
response: xhr.response
});
}
};
xhr.onerror = function() {
if (details.onerror) {
details.onerror({
error: 'Network error',
readyState: xhr.readyState,
status: xhr.status,
statusText: xhr.statusText
});
}
};
xhr.onabort = details.onabort;
xhr.ontimeout = details.ontimeout;
xhr.onprogress = details.onprogress;
if (details.data) {
xhr.send(details.data);
} else {
xhr.send();
}
return {
abort: function() {
xhr.abort();
}
};
} catch(e) {
console.error('[CheekyChimp Enhanced] GM_xmlhttpRequest\u9519\u8BEF:', e);
if (details.onerror) {
details.onerror({
error: e.toString(),
readyState: 0,
status: 0,
statusText: 'Error'
});
}
}
};
// \u5176\u4ED6GM\u51FD\u6570\u7684\u5B9E\u73B0
const GM_registerMenuCommand = function(name, fn) {
// \u5728\u5B9E\u9645\u5B9E\u73B0\u4E2D\uFF0C\u8FD9\u4F1A\u521B\u5EFA\u4E00\u4E2A\u83DC\u5355\u9879
console.log('[CheekyChimp Enhanced] \u6CE8\u518C\u83DC\u5355\u547D\u4EE4:', name);
return 1; // \u8FD4\u56DE\u4E00\u4E2A\u865A\u62DFID
};
const GM_unregisterMenuCommand = function(id) {
console.log('[CheekyChimp Enhanced] \u6CE8\u9500\u83DC\u5355\u547D\u4EE4:', id);
};
const GM_openInTab = function(url, options) {
try {
window.open(url, '_blank');
} catch(e) {
console.error('[CheekyChimp Enhanced] GM_openInTab\u9519\u8BEF:', e);
}
};
const GM_setClipboard = function(text) {
try {
// \u8FD9\u5728\u5B9E\u9645\u60C5\u51B5\u4E0B\u9700\u8981\u7279\u6B8A\u6743\u9650
console.log('[CheekyChimp Enhanced] \u8BBE\u7F6E\u526A\u8D34\u677F\u5185\u5BB9:', text);
} catch(e) {
console.error('[CheekyChimp Enhanced] GM_setClipboard\u9519\u8BEF:', e);
}
};
// \u8D44\u6E90\u8BBF\u95EE\u51FD\u6570
const GM_getResourceText = function(name) {
console.log('[CheekyChimp Enhanced] \u83B7\u53D6\u8D44\u6E90\u6587\u672C:', name);
return '';
};
const GM_getResourceURL = function(name) {
console.log('[CheekyChimp Enhanced] \u83B7\u53D6\u8D44\u6E90URL:', name);
return '';
};
// \u901A\u77E5\u51FD\u6570
const GM_notification = function(details) {
try {
console.log('[CheekyChimp Enhanced] \u663E\u793A\u901A\u77E5:', details.title || '\u901A\u77E5', details.text);
if (typeof Notification !== 'undefined') {
new Notification(details.title || '\u901A\u77E5', {
body: details.text,
icon: details.image
});
}
} catch(e) {
console.error('[CheekyChimp Enhanced] GM_notification\u9519\u8BEF:', e);
}
};
// \u73B0\u4EE3GM API
const GM = {
getValue: (name, defaultValue) => Promise.resolve(GM_getValue(name, defaultValue)),
setValue: (name, value) => {
GM_setValue(name, value);
return Promise.resolve();
},
deleteValue: (name) => {
GM_deleteValue(name);
return Promise.resolve();
},
listValues: () => Promise.resolve(GM_listValues()),
xmlHttpRequest: (details) => GM_xmlhttpRequest(details),
addStyle: (css) => Promise.resolve(GM_addStyle(css)),
registerMenuCommand: (name, fn) => Promise.resolve(GM_registerMenuCommand(name, fn))
};
`,`
(async function() {
try {
// \u5B9A\u4E49unsafeWindow
const unsafeWindow = window;
// \u8BBE\u7F6EGM_info
${`
const GM_info = ${JSON.stringify(n,null,2)};
`}
// \u5B9A\u4E49GM API
${r}
${i}
// \u4FDD\u5B58\u539F\u59CB\u63A7\u5236\u53F0
const originalConsole = {
log: console.log,
warn: console.warn,
error: console.error,
info: console.info,
debug: console.debug
};
// \u4FEE\u6539\u63A7\u5236\u53F0\u4EE5\u4FBF\u8BC6\u522B\u7528\u6237\u811A\u672C\u65E5\u5FD7
console = Object.assign({}, console, {
log: (...args) => originalConsole.log('[${n.script.name}]', ...args),
warn: (...args) => originalConsole.warn('[${n.script.name}]', ...args),
error: (...args) => originalConsole.error('[${n.script.name}]', ...args),
info: (...args) => originalConsole.info('[${n.script.name}]', ...args),
debug: (...args) => originalConsole.debug('[${n.script.name}]', ...args)
});
// \u6CE8\u5165\u7528\u6237\u811A\u672C
${t}
// \u6062\u590D\u539F\u59CB\u63A7\u5236\u53F0
console = originalConsole;
} catch(e) {
console.error('[CheekyChimp Enhanced] \u8FD0\u884C\u811A\u672C\u65F6\u51FA\u9519:', e);
}
})();
`}getScriptMetaStr(t){let e=[];return e.push("// ==UserScript=="),t.name&&e.push(`// @name ${t.name}`),t.namespace&&e.push(`// @namespace ${t.namespace}`),t.version&&e.push(`// @version ${t.version}`),t.description&&e.push(`// @description ${t.description}`),t.author&&e.push(`// @author ${t.author}`),t.homepage&&e.push(`// @homepage ${t.homepage}`),t.icon&&e.push(`// @icon ${t.icon}`),t.includes.forEach(n=>{e.push(`// @include ${n}`)}),t.matches.forEach(n=>{e.push(`// @match ${n}`)}),t.excludes.forEach(n=>{e.push(`// @exclude ${n}`)}),t.requires.forEach(n=>{e.push(`// @require ${n}`)}),t.resources.forEach(n=>{e.push(`// @resource ${n.name} ${n.url}`)}),t.runAt&&e.push(`// @run-at ${t.runAt}`),e.push("// ==/UserScript=="),e.join(`
`)}};var y=require("obsidian");function J(){console.log("[CheekyChimp] \u8BCA\u65AD\u4FE1\u606F:"),console.log(`- ErrorHandler \u5DF2\u52A0\u8F7D: ${typeof L!="undefined"}`),console.log(`- Logger \u5DF2\u52A0\u8F7D: ${typeof E!="undefined"}`),console.log("- \u4F18\u5316\u9879\u76EE\u7ED3\u6784\u6D4B\u8BD5...")}var ae=new E("CheekyChimp");ae.info("\u521D\u59CB\u5316CheekyChimp\u63D2\u4EF6"),J();var P=class extends y.Plugin{constructor(){super(...arguments);this.injectionRecords=new Map;this.hasAddedScriptCommands=!1;this.ribbonIconEl=null;this.clearWebviewInjectionRecords=e=>{try{if(e.target){let n=e.target,i=this.getWebviewId(n);this.clearInjectionRecords(i),console.log(`${c("WebviewManager")} \u5DF2\u6E05\u9664webview\u6CE8\u5165\u8BB0\u5F55: ${i}`);let r="";n instanceof HTMLIFrameElement?r=n.src||"":r=n.getAttribute("src")||"",r&&(console.log(`${c("WebviewManager")} \u9875\u9762\u5237\u65B0\u68C0\u6D4B\uFF0C\u51C6\u5907\u91CD\u65B0\u6CE8\u5165\u811A\u672C: ${r}`),setTimeout(()=>{this.injectScriptsForUrl(r,n)},500))}}catch(n){console.error(`${c("WebviewManager")} \u6E05\u9664\u6CE8\u5165\u8BB0\u5F55\u5931\u8D25:`,n)}}}async onload(){console.log("Loading CheekyChimp plugin"),J(),this.scriptStorage=new U(this),this.scriptManager=new j,this.menuCommandManager=new R,this.menuCommandInjector=new D,this.scriptMenuUI=new N,console.log("[CheekyChimp] \u4F7F\u7528\u589E\u5F3A\u7248\u811A\u672C\u6CE8\u5165\u5668"),this.scriptInjector=new x(this.scriptStorage,this.scriptManager,{debug:!0,autoReinject:!0}),console.log("[CheekyChimp] \u670D\u52A1\u521D\u59CB\u5316\u5B8C\u6210\uFF0CscriptInjector\u7C7B\u578B:",this.scriptInjector.constructor.name,"\u65B9\u6CD5:",Object.getOwnPropertyNames(Object.getPrototypeOf(this.scriptInjector))),await this.loadSettings(),this.settingTab=new T(this.app,this),this.addSettingTab(this.settingTab),this.scriptManager.loadScripts(this.settings.scripts),this.registerScriptManagerEvents(),this.registerWebViewHandlers(),this.registerRefreshHandlers(),(0,y.addIcon)("cheekychimp",`<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
<path fill="currentColor" d="M 108.11719 0 L 0 108.11914 L 0 403.88086 L 108.11719 512 L 403.88281 512 L 512 403.88086 L 512 108.11914 L 403.88281 0 L 108.11719 0 z M 196.56055 128 L 315.43945 128 C 324.4555 128 332 135.5445 332 144.56055 L 332 196.56055 L 384 196.56055 C 393.0161 196.56055 400.56055 204.10499 400.56055 213.12109 L 400.56055 298.87891 C 400.56055 307.89501 393.0161 315.43945 384 315.43945 L 332 315.43945 L 332 367.43945 C 332 376.4555 324.4555 384 315.43945 384 L 196.56055 384 C 187.5445 384 180 376.4555 180 367.43945 L 180 315.43945 L 128 315.43945 C 118.98389 315.43945 111.43945 307.89501 111.43945 298.87891 L 111.43945 213.12109 C 111.43945 204.10499 118.98389 196.56055 128 196.56055 L 180 196.56055 L 180 144.56055 C 180 135.5445 187.5445 128 196.56055 128 z"/>
</svg>`),this.updateRibbonIconVisibility(),this.editScriptHandler=e=>{var r;let i=(r=e.detail)==null?void 0:r.scriptId;i&&this.openScriptEditor(i)},this.createScriptHandler=e=>{var r;let i=(r=e.detail)==null?void 0:r.url;i&&this.createScriptForUrl(i)},document.addEventListener("cheekychimp-edit-script",this.editScriptHandler),document.addEventListener("cheekychimp-create-script",this.createScriptHandler)}onunload(){console.log("Unloading CheekyChimp plugin"),document.removeEventListener("cheekychimp-edit-script",this.editScriptHandler),document.removeEventListener("cheekychimp-create-script",this.createScriptHandler),this.ribbonIconEl&&(this.ribbonIconEl.remove(),this.ribbonIconEl=null)}async loadSettings(){this.settings=Object.assign({},q,await this.loadData())}async saveSettings(){this.settings.scripts=this.scriptManager.getAllScripts(),await this.saveData(this.settings)}openSettings(){if(this.app.setting){this.app.setting.open();try{this.app.setting.openTabById("cheekychimp")}catch(e){console.warn("\u65E0\u6CD5\u76F4\u63A5\u6253\u5F00CheekyChimp\u8BBE\u7F6E\u6807\u7B7E\uFF0C\u5C06\u6253\u5F00\u901A\u7528\u8BBE\u7F6E\u9875\u9762")}}else new y.Notice(k.t("error_open_settings"))}openScriptEditor(e){let n=this.scriptManager.getScript(e);n&&(this.openSettings(),new y.Notice(k.t("opening_script_editor",{name:n.name})))}createScriptForUrl(e){if(!e)return;let n=new URL(e).hostname,i=`// ==UserScript==
// @name Script for ${n}
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Add functionality to ${n}
// @author You
// @match ${e}
// @grant none
// ==/UserScript==
(function() {
'use strict';
// Add your code here...
console.log('CheekyChimp script running!');
})();`;try{let r=this.scriptManager.addScript(i);new y.Notice(k.t("script_created_for_domain",{domain:n})),this.openScriptEditor(r.id)}catch(r){console.error("\u521B\u5EFA\u811A\u672C\u5931\u8D25:",r),new y.Notice(k.t("error_creating_script"))}}registerScriptManagerEvents(){this.scriptManager.on("onScriptAdded",async()=>{await this.saveSettings()}),this.scriptManager.on("onScriptRemoved",async()=>{await this.saveSettings()}),this.scriptManager.on("onScriptUpdated",async()=>{await this.saveSettings()}),this.scriptManager.on("onScriptEnabled",async()=>{await this.saveSettings()}),this.scriptManager.on("onScriptDisabled",async()=>{await this.saveSettings()})}registerWebViewHandlers(){this.setupDOMObserver(),this.registerEvent(this.app.workspace.on("layout-change",()=>{this.checkForWebViews()})),this.checkForWebViews(),this.registerEvent(this.app.workspace.on("active-leaf-change",e=>{e&&this.handlePotentialWebViewLeaf(e)}))}setupDOMObserver(){new MutationObserver(n=>{n.forEach(i=>{i.addedNodes.forEach(r=>{(r.nodeName==="IFRAME"||r.nodeName==="WEBVIEW")&&this.setupIframe(r)})})}).observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src"]})}checkForWebViews(){this.app.workspace.iterateAllLeaves(e=>{this.handlePotentialWebViewLeaf(e)})}handlePotentialWebViewLeaf(e){!e||!e.view||setTimeout(()=>{let n=e.view.containerEl;if(!n)return;n.querySelectorAll("iframe, webview").forEach(r=>{(r instanceof HTMLIFrameElement||r instanceof HTMLElement)&&this.setupWebViewListeners(r)})},500)}setupWebViewListeners(e){if(e.hasAttribute("data-tampermonkey-processed"))return;e.setAttribute("data-tampermonkey-processed","true"),console.log("CheekyChimp: Webview detected",e.tagName);let n="";if(e instanceof HTMLIFrameElement){console.log("CheekyChimp: \u5904\u7406iframe\u5143\u7D20");try{n=e.src}catch(i){console.warn("CheekyChimp: \u65E0\u6CD5\u8BFB\u53D6iframe\u7684src\u5C5E\u6027",i),n=e.getAttribute("src")||""}e.addEventListener("load",()=>{try{let i="";try{i=e.src}catch(r){i=e.getAttribute("src")||""}i&&(console.log("CheekyChimp: iframe\u52A0\u8F7D\u5B8C\u6210\uFF0C\u6CE8\u5165\u811A\u672C\u5230",i),this.injectScriptsForUrl(i,e))}catch(i){console.error("CheekyChimp: \u5904\u7406iframe load\u4E8B\u4EF6\u51FA\u9519",i)}}),this.scriptInjector instanceof x&&this.scriptInjector.registerRefreshHandler(e,n),n&&(console.log("CheekyChimp: \u7ACB\u5373\u6CE8\u5165\u811A\u672C\u5230iframe:",n),this.injectScriptsForUrl(n,e))}else if(e.tagName==="WEBVIEW"||e.tagName==="IFRAME"){console.log("CheekyChimp: \u5904\u7406webview\u5143\u7D20");let i=e.getAttribute("src")||"";try{e.addEventListener("did-navigate",r=>{try{let s=r.url||e.getAttribute("src")||"";s&&(console.log("CheekyChimp: webview\u5BFC\u822A\u5230",s),this.injectScriptsForUrl(s,e))}catch(s){console.error("CheekyChimp: \u5904\u7406webview\u5BFC\u822A\u4E8B\u4EF6\u51FA\u9519",s)}}),e.addEventListener("load",()=>{try{let r=e.getAttribute("src")||"";r&&(console.log("CheekyChimp: webview\u52A0\u8F7D\u5B8C\u6210",r),this.injectScriptsForUrl(r,e))}catch(r){console.error("CheekyChimp: \u5904\u7406webview load\u4E8B\u4EF6\u51FA\u9519",r)}}),this.scriptInjector instanceof x&&this.scriptInjector.registerRefreshHandler(e,i)}catch(r){console.warn("CheekyChimp: \u6DFB\u52A0webview\u4E8B\u4EF6\u76D1\u542C\u5668\u5931\u8D25",r)}i&&(console.log("CheekyChimp: \u7ACB\u5373\u6CE8\u5165\u811A\u672C\u5230webview:",i),setTimeout(()=>{this.injectScriptsForUrl(i,e)},500))}else console.log("CheekyChimp: \u5904\u7406\u672A\u77E5\u5143\u7D20\uFF0C\u67E5\u627E\u5185\u90E8iframe"),e.querySelectorAll("iframe, webview").forEach(r=>{r instanceof HTMLElement&&(console.log("CheekyChimp: \u627E\u5230\u5185\u90E8webview\u5143\u7D20"),this.setupWebViewListeners(r))})}setupVisibilityPolling(e){let n="",i=e.src||"",r="",s="",o=0;if(e.hasAttribute("data-cheekychimp-polling"))return;e.setAttribute("data-cheekychimp-polling","true");let m=setInterval(()=>{try{if(!document.contains(e)){console.log(`${c("VisibilityPolling")} iframe\u5DF2\u4ECEDOM\u4E2D\u79FB\u9664\uFF0C\u505C\u6B62\u8F6E\u8BE2`),clearInterval(m);return}let g=e.src||"",p="",d="",l="";try{e.contentDocument&&e.contentWindow&&(p=e.contentDocument.documentElement.outerHTML||"",d=e.contentWindow.location.href,l=e.contentDocument.title)}catch(C){}let f=g!==i,h=p&&p!==n&&p.length>50,v=d&&d!==r,b=l&&l!==s;if(f||h||v||b){console.log(`${c("VisibilityPolling")} \u68C0\u6D4B\u5230iframe\u53D8\u5316:`,f?"\u5730\u5740\u53D8\u5316":"",h?"\u5185\u5BB9\u53D8\u5316":"",v?"\u5185\u90E8href\u53D8\u5316":"",b?"\u6807\u9898\u53D8\u5316":""),i=g,p&&(n=p),d&&(r=d),l&&(s=l);let C=this.getWebviewId(e);this.clearInjectionRecords(C),setTimeout(()=>{this.injectScriptsForUrl(g,e)},300),o=0}else if(o++,o>=30){console.log(`${c("VisibilityPolling")} \u5B9A\u671F\u68C0\u67E5\u662F\u5426\u9700\u8981\u91CD\u65B0\u6CE8\u5165\u811A\u672C`);let C=this.getWebviewId(e),S=e.src||"";if(S){let $=this.scriptManager.findScriptsForUrl(S).filter(G=>G.enabled).filter(G=>!this.isScriptInjected(C,G.id));$.length>0&&(console.log(`${c("VisibilityPolling")} \u53D1\u73B0 ${$.length} \u4E2A\u672A\u6CE8\u5165\u7684\u811A\u672C\uFF0C\u5C1D\u8BD5\u6CE8\u5165`),this.injectScriptsForUrl(S,e))}o=0}}catch(g){console.error(`${c("VisibilityPolling")} \u8F6E\u8BE2\u51FA\u9519:`,g),clearInterval(m)}},1e3);e.setAttribute("data-cheekychimp-polling-id",String(m))}clearInjectionRecords(e){try{this.injectionRecords.delete(e),console.log(`${c("InjectionManager")} \u5DF2\u6E05\u9664webview\u7684\u6240\u6709\u6CE8\u5165\u8BB0\u5F55: ${e}`)}catch(n){console.error(`${c("InjectionManager")} \u6E05\u9664\u6CE8\u5165\u8BB0\u5F55\u5931\u8D25:`,n)}}injectScriptsForUrl(e,n){let i=this.scriptManager.findScriptsForUrl(e);i.length>0&&(console.log(`CheekyChimp: Found ${i.length} scripts for ${e}`),this.scriptInjector.injectScripts(n,e,i))}isScriptInjected(e,n){try{let i=this.injectionRecords.get(e),r=(i==null?void 0:i.has(n))||!1;return r&&!this.verifyScriptInjection(e,n)?(this.removeInjectionRecord(e,n),!1):r}catch(i){return console.error(`${c("InjectionManager")} \u68C0\u67E5\u811A\u672C\u6CE8\u5165\u72B6\u6001\u5931\u8D25:`,i),!1}}verifyScriptInjection(e,n){try{return!0}catch(i){return console.warn(`${c("InjectionManager")} \u9A8C\u8BC1\u811A\u672C\u6CE8\u5165\u5931\u8D25:`,i),!1}}removeInjectionRecord(e,n){try{let i=this.injectionRecords.get(e);i&&(i.delete(n),console.log(`${c("InjectionManager")} \u5DF2\u79FB\u9664\u811A\u672C\u6CE8\u5165\u8BB0\u5F55: ${n}`))}catch(i){console.error(`${c("InjectionManager")} \u79FB\u9664\u6CE8\u5165\u8BB0\u5F55\u5931\u8D25:`,i)}}markScriptAsInjected(e,n){try{this.injectionRecords.has(e)||this.injectionRecords.set(e,new Set);let i=this.injectionRecords.get(e);i&&(i.add(n),console.log(`${c("InjectionManager")} \u5DF2\u6807\u8BB0\u811A\u672C\u4E3A\u5DF2\u6CE8\u5165: ${n}`))}catch(i){console.error(`${c("InjectionManager")} \u6807\u8BB0\u811A\u672C\u4E3A\u5DF2\u6CE8\u5165\u5931\u8D25:`,i)}}getWebviewId(e){try{if(e.hasAttribute("data-cheekychimp-id"))return e.getAttribute("data-cheekychimp-id")||"";let n=`cheekychimp-webview-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return e.setAttribute("data-cheekychimp-id",n),console.log(`${c("WebviewManager")} \u4E3Awebview\u751F\u6210\u65B0ID: ${n}`),n}catch(n){let i=e.id||`temp-${Date.now()}`;return console.warn(`${c("WebviewManager")} \u65E0\u6CD5\u8BBE\u7F6Ewebview ID\uFF0C\u4F7F\u7528\u56DE\u9000ID: ${i}`),i}}injectMenuCommandSupport(e,n){try{this.menuCommandInjector.injectMenuCommandSupport(e,n)}catch(i){console.error("[CheekyChimp] \u6CE8\u5165\u83DC\u5355\u547D\u4EE4\u652F\u6301\u5931\u8D25:",i)}}injectScriptMenuUI(e){try{let n=i=>{this.menuCommandInjector.executeCommand(e,i)};this.scriptMenuUI.injectIntoIframe(e),window.addEventListener("message",i=>{try{if(i.source!==e.contentWindow)return;let r=i.data;if(!r||typeof r!="object")return;r.type==="cheekychimp-menu-clicked"&&(this.updateScriptMenu(),this.scriptMenuUI.showMenu())}catch(r){console.error("[CheekyChimp] \u5904\u7406iframe\u6D88\u606F\u5931\u8D25:",r)}})}catch(n){console.error("[CheekyChimp] \u6CE8\u5165\u811A\u672C\u83DC\u5355UI\u5931\u8D25:",n)}}updateScriptMenu(){try{let e=this.menuCommandInjector.getAllCommands();this.scriptMenuUI.isInitialized()||this.scriptMenuUI.initialize(n=>{let i=e.find(r=>r.id===n);!i||this.app.workspace.iterateAllLeaves(r=>{let s=r.view.containerEl.querySelector("iframe");s&&this.menuCommandInjector.executeCommand(s,i.id)})}),this.scriptMenuUI.updateMenu(e)}catch(e){console.error("[CheekyChimp] \u66F4\u65B0\u811A\u672C\u83DC\u5355\u5931\u8D25:",e)}}addScriptCommandsToMenu(e){this.hasAddedScriptCommands=!1;try{let n=this.menuCommandInjector.getAllCommands();if(n.length>0){let o=new Map;n.forEach(p=>{var d;o.has(p.scriptId)||o.set(p.scriptId,[]),(d=o.get(p.scriptId))==null||d.push(p)});let m=[...o.keys()].sort((p,d)=>{let l=this.scriptManager.getScript(p),f=this.scriptManager.getScript(d);return((l==null?void 0:l.name)||"Unknown").localeCompare((f==null?void 0:f.name)||"Unknown")}),g=0;for(let p of m){let d=o.get(p)||[];if(d.length===0)continue;let l=this.scriptManager.getScript(p),f=(l==null?void 0:l.name)||d[0].scriptName||"\u672A\u77E5\u811A\u672C";g>0&&e.addSeparator(),e.addItem(h=>{h.setTitle(`\u{1F4DC} ${f}`).setDisabled(!0)}),d.forEach(h=>{e.addItem(v=>{v.setTitle(` \u25C6 ${h.name}`).onClick(()=>{try{this.app.workspace.iterateAllLeaves(b=>{let C=b.view.containerEl.querySelector("iframe");C&&this.menuCommandInjector.executeCommand(C,h.id)})}catch(b){console.error("\u6267\u884C\u547D\u4EE4\u5931\u8D25:",b),new y.Notice(`\u6267\u884C\u547D\u4EE4\u5931\u8D25: ${h.name}`)}})}),g++})}if(g>0){this.hasAddedScriptCommands=!0,console.log(`\u6210\u529F\u6DFB\u52A0 ${g} \u4E2A\u811A\u672C\u547D\u4EE4\u5230\u83DC\u5355`);return}}let i=this.scriptManager.getAllScripts().filter(o=>o.enabled),r=0;for(let o of i){let m=`tampermonkey_commands:${o.id}`;try{let p=localStorage.getItem(m);if(p){let d=JSON.parse(p);if(d&&d.length>0)for(let l of d)e.addItem(f=>{f.setTitle(l.name).onClick(()=>{let h=new CustomEvent(`cheekychimp-run-command-${l.id}`);document.dispatchEvent(h),new y.Notice(`\u6267\u884C\u547D\u4EE4: ${l.name}`)})}),r++}}catch(p){console.error("\u89E3\u6790\u811A\u672C\u547D\u4EE4\u5931\u8D25:",p)}let g=`cheekychimp_commands:${o.id}`;try{let p=localStorage.getItem(g);if(p){let d=JSON.parse(p);if(d&&d.length>0)for(let l of d)e.addItem(f=>{f.setTitle(l.name).onClick(()=>{let h=new CustomEvent(`cheekychimp-run-command-${l.id}`);document.dispatchEvent(h),new y.Notice(`\u6267\u884C\u547D\u4EE4: ${l.name}`)})}),r++}}catch(p){console.error("\u89E3\u6790CheekyChimp\u547D\u4EE4\u5931\u8D25:",p)}}r>0&&(this.hasAddedScriptCommands=!0),document.querySelectorAll("iframe, webview").forEach(o=>{try{if(o instanceof HTMLIFrameElement&&o.contentWindow)try{let m=o.contentWindow._gmMenuCommands;if(m&&m.length>0){for(let g of m)e.addItem(p=>{p.setTitle(g.name).onClick(()=>{try{g.callback(),new y.Notice(`\u6267\u884C\u547D\u4EE4: ${g.name}`)}catch(d){console.error("\u6267\u884C\u547D\u4EE4\u5931\u8D25:",d),new y.Notice(`\u6267\u884C\u547D\u4EE4\u5931\u8D25: ${g.name}`)}})}),r++;this.hasAddedScriptCommands=!0}}catch(m){}}catch(m){console.warn("\u8BBF\u95EEwebview\u5185\u5BB9\u65F6\u51FA\u9519:",m)}}),console.log("\u627E\u5230\u811A\u672C\u547D\u4EE4\u6570\u91CF:",r)}catch(n){console.error("\u6DFB\u52A0\u811A\u672C\u547D\u4EE4\u5230\u83DC\u5355\u5931\u8D25:",n)}}setupIframe(e){try{let n="";e.addEventListener("load",()=>{let r=e.src||"";if(r){let s=r+"_"+Date.now();console.log(`${c("WebviewManager")} iframe\u52A0\u8F7D\u6216\u5237\u65B0\uFF0CURL: ${r}`);let o=this.getWebviewId(e);this.clearInjectionRecords(o),setTimeout(()=>{this.injectScriptsForUrl(r,e)},300),n=s}});try{e.contentWindow&&e.contentDocument&&e.contentWindow.addEventListener("visibilitychange",()=>{if(e.contentWindow&&e.contentDocument&&!e.contentDocument.hidden){console.log(`${c("WebviewManager")} \u68C0\u6D4B\u5230iframe\u53EF\u89C1\u6027\u53D8\u5316\uFF0C\u53EF\u80FD\u9700\u8981\u91CD\u65B0\u6CE8\u5165`);let r=e.src||"";r&&this.refreshInjection(e,r)}})}catch(r){console.log(`${c("WebviewManager")} \u65E0\u6CD5\u6DFB\u52A0\u989D\u5916iframe\u4E8B\u4EF6\u76D1\u542C\u5668: ${r.message}`)}let i=e.src||"";i&&this.injectScriptsForUrl(i,e)}catch(n){console.error(`${c("WebviewManager")} \u8BBE\u7F6Eiframe\u76D1\u542C\u5668\u5931\u8D25:`,n)}}registerRefreshHandlers(){try{if(!(this.scriptInjector instanceof x)){console.log("\u4E0D\u662FEnhancedScriptInjector\uFF0C\u8DF3\u8FC7\u6CE8\u518C\u5237\u65B0\u5904\u7406\u7A0B\u5E8F");return}console.log("\u6CE8\u518C\u5237\u65B0\u5904\u7406\u7A0B\u5E8F\uFF0C\u786E\u4FDD\u9875\u9762\u5237\u65B0\u540E\u91CD\u65B0\u6CE8\u5165\u811A\u672C"),this.registerEvent(this.app.workspace.on("layout-change",()=>{console.log("\u68C0\u6D4B\u5230\u5E03\u5C40\u53D8\u5316\uFF0C\u67E5\u627Ewebview"),this.app.workspace.iterateAllLeaves(e=>{if(!e||!e.view)return;let n=e.view.containerEl;if(!n)return;n.querySelectorAll("iframe, webview").forEach(r=>{if(r instanceof HTMLIFrameElement){let s="";try{s=r.src}catch(o){s=r.getAttribute("src")||""}s&&(this.scriptInjector.registerRefreshHandler(r,s),console.log(`\u4E3Aiframe\u6CE8\u518C\u5237\u65B0\u5904\u7406\u7A0B\u5E8F: ${s}`))}else if(r instanceof HTMLElement){let s=r.getAttribute("src")||"";s&&(this.scriptInjector.registerRefreshHandler(r,s),console.log(`\u4E3Awebview\u6CE8\u518C\u5237\u65B0\u5904\u7406\u7A0B\u5E8F: ${s}`))}})})})),this.app.workspace.iterateAllLeaves(e=>{if(!e||!e.view)return;let n=e.view.containerEl;if(!n)return;n.querySelectorAll("iframe, webview").forEach(r=>{if(r instanceof HTMLIFrameElement){let s="";try{s=r.src}catch(o){s=r.getAttribute("src")||""}s&&(this.scriptInjector.registerRefreshHandler(r,s),console.log(`\u4E3Aiframe\u6CE8\u518C\u5237\u65B0\u5904\u7406\u7A0B\u5E8F: ${s}`))}else if(r instanceof HTMLElement){let s=r.getAttribute("src")||"";s&&(this.scriptInjector.registerRefreshHandler(r,s),console.log(`\u4E3Awebview\u6CE8\u518C\u5237\u65B0\u5904\u7406\u7A0B\u5E8F: ${s}`))}})})}catch(e){console.error("\u6CE8\u518C\u5237\u65B0\u5904\u7406\u7A0B\u5E8F\u65F6\u51FA\u9519:",e)}}refreshInjection(e,n){try{let i=this.getWebviewId(e);this.clearInjectionRecords(i),console.log(`${c("WebviewManager")} \u91CD\u65B0\u6CE8\u5165\u811A\u672C: ${n}`),this.injectScriptsForUrl(n,e)}catch(i){console.error(`${c("WebviewManager")} \u5237\u65B0\u811A\u672C\u6CE8\u5165\u5931\u8D25:`,i)}}importScriptFromFile(){let e=document.createElement("input");e.type="file",e.accept=".js,.user.js",e.style.display="none",document.body.appendChild(e),e.addEventListener("change",async n=>{let r=n.target.files;if(r&&r.length>0){let s=r[0];try{let o=await this.readFileContent(s),m=this.scriptManager.addScript(o);new y.Notice(`\u5DF2\u6210\u529F\u5BFC\u5165\u811A\u672C: ${m.name}`),this.openScriptEditor(m.id)}catch(o){console.error("\u5BFC\u5165\u811A\u672C\u5931\u8D25:",o),new y.Notice("\u5BFC\u5165\u811A\u672C\u5931\u8D25: "+(o instanceof Error?o.message:String(o)))}}document.body.removeChild(e)}),e.click()}async readFileContent(e){return new Promise((n,i)=>{let r=new FileReader;r.onload=s=>{s.target&&typeof s.target.result=="string"?n(s.target.result):i(new Error("\u8BFB\u53D6\u6587\u4EF6\u5185\u5BB9\u5931\u8D25"))},r.onerror=s=>{i(new Error("\u8BFB\u53D6\u6587\u4EF6\u51FA\u9519"))},r.readAsText(e)})}createNewScript(){let e=new y.Modal(this.app);e.titleEl.setText("\u521B\u5EFA\u65B0\u811A\u672C");let n=e.contentEl;n.empty(),n.createEl("p",{text:"\u8BF7\u8F93\u5165\u811A\u672C\u9002\u7528\u7684\u7F51\u5740:"});let r=n.createDiv().createEl("input",{type:"text",value:"https://example.com"});r.style.width="100%",r.style.marginBottom="10px";let s=n.createDiv();s.style.display="flex",s.style.justifyContent="flex-end",s.style.marginTop="10px";let o=s.createEl("button",{text:"\u53D6\u6D88"});o.style.marginRight="10px",o.addEventListener("click",()=>{e.close()});let m=s.createEl("button",{text:"\u521B\u5EFA"});m.addClass("mod-cta"),m.addEventListener("click",()=>{let g=r.value.trim();g?(this.createScriptWithEditor(g),e.close()):new y.Notice("\u8BF7\u8F93\u5165\u6709\u6548\u7684URL")}),e.open()}createScriptWithEditor(e){if(!!e)try{let n=new URL(e).hostname||e,i=`// ==UserScript==
// @name \u811A\u672C: ${n}
// @namespace http://obsidian.md/
// @version 0.1
// @description \u4E3A ${n} \u6DFB\u52A0\u529F\u80FD
// @author You
// @match ${e}
// @grant none
// ==/UserScript==
(function() {
'use strict';
// \u5728\u6B64\u6DFB\u52A0\u60A8\u7684\u4EE3\u7801...
console.log('CheekyChimp \u811A\u672C\u8FD0\u884C\u4E2D!');
})();`,r=this.scriptManager.addScript(i);new y.Notice(`\u5DF2\u521B\u5EFA\u811A\u672C: ${r.name}`),this.openScriptEditorDirectly(r.id)}catch(n){console.error("\u521B\u5EFA\u811A\u672C\u5931\u8D25:",n),new y.Notice("\u521B\u5EFA\u811A\u672C\u5931\u8D25: "+(n instanceof Error?n.message:String(n)))}}openScriptEditorDirectly(e){let n=this.scriptManager.getScript(e);if(!n){new y.Notice("\u627E\u4E0D\u5230\u811A\u672C");return}let i=new y.Modal(this.app);i.titleEl.setText(`\u7F16\u8F91\u811A\u672C: ${n.name}`);let r=i.contentEl;r.empty(),r.style.height="80vh",r.style.width="80vw",r.style.display="flex",r.style.flexDirection="column";let s=r.createDiv();s.style.marginBottom="10px",s.style.display="flex",s.style.justifyContent="space-between";let o=s.createDiv();o.createEl("span",{text:`ID: ${n.id}`}).style.marginRight="10px",o.createEl("span",{text:`\u7248\u672C: ${n.version||"\u672A\u77E5"}`}).style.marginRight="10px";let g=s.createDiv().createEl("label");g.setText("\u542F\u7528");let p=g.createEl("input",{type:"checkbox"});p.checked=n.enabled,p.style.marginLeft="5px",p.addEventListener("change",()=>{p.checked?this.scriptManager.enableScript(n.id):this.scriptManager.disableScript(n.id),new y.Notice(`\u811A\u672C ${n.name} \u5DF2${p.checked?"\u542F\u7528":"\u7981\u7528"}`)});let d=r.createDiv();d.style.flexGrow="1",d.style.border="1px solid var(--background-modifier-border)",d.style.borderRadius="4px";let l=d.createEl("textarea");l.value=n.source||"",l.style.width="100%",l.style.height="100%",l.style.resize="none",l.style.fontFamily="monospace",l.style.padding="10px",l.style.boxSizing="border-box";let f=r.createDiv();f.style.marginTop="10px",f.style.display="flex",f.style.justifyContent="flex-end";let h=f.createEl("button",{text:"\u53D6\u6D88"});h.style.marginRight="10px",h.addEventListener("click",()=>{i.close()});let v=f.createEl("button",{text:"\u4FDD\u5B58"});v.addClass("mod-cta"),v.addEventListener("click",()=>{try{this.scriptManager.updateScript(n.id,l.value),new y.Notice(`\u811A\u672C ${n.name} \u5DF2\u4FDD\u5B58`),i.close()}catch(b){console.error("\u4FDD\u5B58\u811A\u672C\u5931\u8D25:",b),new y.Notice("\u4FDD\u5B58\u811A\u672C\u5931\u8D25: "+(b instanceof Error?b.message:String(b)))}}),i.open()}updateRibbonIconVisibility(){this.ribbonIconEl&&(this.ribbonIconEl.remove(),this.ribbonIconEl=null),this.settings.showRibbonIcon&&(this.ribbonIconEl=this.addRibbonIcon("cheekychimp","CheekyChimp",e=>{let n=new y.Menu;n.addItem(r=>{r.setTitle("UserScript Menu").setDisabled(!0)}),n.addSeparator();let i=this.scriptManager.getAllScripts();if(this.addScriptCommandsToMenu(n),!this.hasAddedScriptCommands)if(i.length>0){let r=i.filter(o=>o.enabled);r.forEach(o=>{n.addItem(m=>{m.setTitle(o.name).setIcon("check").onClick(()=>{this.scriptManager.disableScript(o.id),new y.Notice(`\u5DF2\u7981\u7528\u811A\u672C: ${o.name}`)})})});let s=i.filter(o=>!o.enabled);s.length>0&&r.length>0&&n.addSeparator(),s.forEach(o=>{n.addItem(m=>{m.setTitle(o.name).setIcon("circle").onClick(()=>{this.scriptManager.enableScript(o.id),new y.Notice(`\u5DF2\u542F\u7528\u811A\u672C: ${o.name}`)})})})}else n.addItem(r=>{r.setTitle("\u6CA1\u6709\u5B89\u88C5\u811A\u672C").setDisabled(!0)});n.addSeparator(),n.addItem(r=>{r.setTitle("\u65B0\u5EFA\u811A\u672C").setIcon("plus").onClick(()=>{this.createNewScript()})}),n.addItem(r=>{r.setTitle("\u5BFC\u5165\u811A\u672C").setIcon("upload").onClick(()=>{this.importScriptFromFile()})}),n.addItem(r=>{r.setTitle("\u7BA1\u7406\u6240\u6709\u811A\u672C").setIcon("settings").onClick(()=>{this.openSettings()})}),n.showAtPosition({x:e.x,y:e.y})}))}};