-
Notifications
You must be signed in to change notification settings - Fork 6
/
background.js
3977 lines (3395 loc) · 198 KB
/
background.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const dark_object = {
all_levels: {
install: function() {
{
let createInternalProperty = function(leType, atName,condition=true) {
// We can search in the code for unsafe looping use of the property, and replace it by the internal property with the regex [.](?<!(o|p)_ud_)innerHTML[\s+]*?[+]?= in VSCode
if(condition){
console.log("Creating internal property for",leType,atName)
var originalProperty = Object.getOwnPropertyDescriptor(leType.prototype, atName);
if (!originalProperty) {
console.error("No existing property for '", atName, "'", leType, leType.name, leType.prototype,condition)
return;
}
Object.defineProperty(leType.prototype, "p_ud_" + atName, originalProperty);
}
};
// Any level protected proptotypes for safe intenal use without ternaries or worries.
globalThis.CSS2Properties.prototype.p_ud_setProperty = globalThis.CSS2Properties.prototype.setProperty;
CSSStyleSheet.prototype.p_ud_replaceSync = CSSStyleSheet.prototype.replaceSync;
CSSStyleSheet.prototype.p_ud_insertRule = CSSStyleSheet.prototype.insertRule;
createInternalProperty(Element, "innerHTML");
createInternalProperty(ShadowRoot, "innerHTML");
createInternalProperty(globalThis.CSS2Properties, "backgroundColor");
createInternalProperty(Navigator, "serviceWorker", navigator.serviceWorker!=undefined);
} {
// Very special functions
String.prototype.hashCode = function(under = 100, over = 0) {
var hash = 0,
i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
hash += 2147483647 + 1;
hash %= under;
if (hash <= over) {
hash = (this + "z").hashCode(under, over)
}
return hash;
};
}
const CSS_COLOR_NAMES = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "DarkOrange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "RebeccaPurple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"]
let SHORTHANDS = ["all", "animation", "animation-range", "background", "border", "border-block", "border-block-end", "border-block-start", "border-bottom", "border-color", "border-image", "border-inline", "border-inline-end", "border-inline-start", "border-left", "border-radius", "border-right", "border-style", "border-top", "border-width", "column-rule", "columns", "contain-intrinsic-size", "container", "flex", "flex-flow", "font", "font-synthesis", "font-variant", "gap", "grid", "grid-area", "grid-column", "grid-row", "grid-template", "inset", "inset-block", "inset-inline", "list-style", "margin", "margin-block", "margin-inline", "mask", "mask-border", "offset", "outline", "overflow", "overscroll-behavior", "padding", "padding-block", "padding-inline", "place-content", "place-items", "place-self", "position-try", "scroll-margin", "scroll-margin-block", "scroll-margin-inline", "scroll-padding", "scroll-padding-block", "scroll-padding-inline", "scroll-timeline", "text-decoration", "text-emphasis", "text-wrap", "transition"]
window.uDark = {
shortHandRegex: new RegExp(`(?<![_a-z0-9-])(${SHORTHANDS.join("|")})([\s\t]*:)`, "gmi") , // The \t is probably not needed, as \s includes it
rgb_a_colorsRegex: /rgba?\([%0-9., \/a-z_+*-]+\)/gmi, // rgba vals with variables names and calcs involved NOTE: #rgba(255 255 255 / 0.1) is valid color rgba(255,255,255,30%) is valid color too
hsl_a_colorsRegex: /hsla?\(([%0-9., \/=a-z_+*-]|deg|turn|tetha)+\)/gmi, // hsla vals with variables names and calcs involved #rgba(255 255 255 / 0.1)
direct_window_export: true,
enable_idk_mode: true,
general_cache: new Map(),
userSettings: {},
imageSrcInfoMarker:"_uDark",
imageWorkerJsFile: "imageWorker.js",
regex_search_for_url: /url\("(.+?)(?<!\\)("\))/g,
regex_search_for_url_raw: /url\(('.+?(?<!\\)'|(".+?(?<!\\)")|[^\)'"]*)\)/gsi,
background_match: /background|sprite|(?<![a-z])(bg|box|panel|fond|fundo|bck)(?![a-z])/i,
logo_match: /nav|avatar|logo|icon|alert|notif|cart|menu|tooltip|dropdown|control/i,
chunk_stylesheets_idk_only_cors: false,
namedColorsRegex: (new RegExp(`(?<![_a-z0-9-])(${CSS_COLOR_NAMES.join("|")})(?![_a-z0-9-])`, "gmi")),
min_bright_fg: 0.65, // Text with luminance under this value will be brightened
max_bright_fg: 1, // Text over this value will be darkened
brightness_peak_editor_fg: 0.5, // Reduce the brightness of texts with intermediate luminace, tying to achieve better saturation
hueShiftfg: 0, // Hue shift for text, 0 is fno shift, 360 is full shift
min_bright_bg_trigger: 0.2, // backgrounds with luminace under this value will remain as is
min_bright_bg: 0.1, // background with value over min_bright_bg_trigger will be darkened from this value up to max_bright_bg
max_bright_bg: 0.4, // background with value over min_bright_bg_trigger will be darkened from min_bright_bg up to this value
str_protect: function(str, regexSearch, protectWith) {
// sore values into an array:
var values = str.match(regexSearch);
if (values) {
str = str.replace(regexSearch, protectWith);
}
return {
str,
values,
protectWith
};
},
str_unprotect: function(str, protection) {
if (protection.values) {
protection.values.forEach((value, index) => {
// I've learnt the hard way tto care about some $' or $1 the protected value:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement
// This is why we use a function to replace the protected value
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement
str = str.replace(protection.protectWith, ()=>value);
})
}
return str;
},
str_protect_numbered: function(str, regexSearch, protectWith, condition = true) {
// sore values into an array:
if (!condition) {
return false;
}
var values = str.match(regexSearch);
if (values) {
let index = 0;
str = str.replace(regexSearch, function(match, g1) {
return protectWith.replace("{index}", index++);
});
}
return {
str,
values,
protectWith
};
},
str_unprotect_numbered: function(str, protection, condition = true) {
if (protection.values && condition) {
protection.values.forEach((value, index) => {
// I've learnt the hard way tto care about some $' or $1 the protected value:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement
// This is why we use a function to replace the protected value
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement
str = str.replace(protection.protectWith.replace("{index}", index), ()=>value);
})
}
return str;
},
sRGBtoLin: (colorChannel) => {
// Send this function a decimal sRGB gamma encoded color value
// between 0.0 and 1.0, and it returns a linearized value.
if (colorChannel <= 0.04045) {
return colorChannel / 12.92;
} else {
return Math.pow(((colorChannel + 0.055) / 1.055), 2.4);
}
},
getLuminance: (r, g, b) => {
return (0.2126 * uDark.sRGBtoLin(r / 255) + 0.7152 * uDark.sRGBtoLin(g / 255) + 0.0722 * uDark.sRGBtoLin(b / 255));
},
getPerceivedLigtness: (r, g, b) => {
return uDark.YtoLstar(uDark.getLuminance(r, g, b));
},
YtoLstar: (Y) => {
// Send this function a luminance value between 0.0 and 1.0,
// and it returns L* which is "perceptual lightness"
if (Y <= (216 / 24389)) { // The CIE standard states 0.008856 but 216/24389 is the intent for 0.008856451679036
return Y * (24389 / 27); // The CIE standard states 903.3, but 24389/27 is the intent, making 903.296296296296296
} else {
return Math.pow(Y, (1 / 3)) * 116 - 16;
}
},
do_idk_mode_timed: function(duration, interval) {
if (!uDark.enable_idk_mode) {
return;
}
// Repeat IDK mode every n ms for a certain time
duration = duration || uDark.idk_mode_duration || 5000;
interval = interval || uDark.idk_mode_interval || 50;
clearInterval(uDark.do_idk_mode_interval)
let interval_id = setInterval(function() {
// console.log("IDK mode launched")
uDark.do_idk_mode();
}, interval)
uDark.do_idk_mode_interval = interval_id;
setTimeout(function() {
// console.log("IDK mode stopped after" ,duration,"ms and", (duration/interval)+" execs");
clearInterval(interval_id) // Use interval_id to avoid next intervals. If we use uDark.do_idk_mode_interval, it may clear the new interval_id we just created and stored in uDark.do_idk_mode_interval
}, duration)
return interval_id;
},
do_idk_mode: function() {
let editableStyleSheets = [...document.wrappedJSObject.styleSheets].filter(styleSheet => {
if (styleSheet.idk_mode_ok) {
return false; // This one is still OK
}
styleSheet.idk_mode_ok = true; // This attribute is lost if the stylesheet is edited, so we can ignore this CSS.
if (styleSheet.ownerNode.id == "UltimaDarkTempVariablesStyle") {
return false; // Created on the document of the content script and becomes a cors stylesheet. It's already IDK resolved
}
if (styleSheet.href) {
let styleSheetHref = (new URL(styleSheet.href))
let is_cross_domain = styleSheetHref.origin != document.location.origin;
return !is_cross_domain && !uDark.chunk_stylesheets_idk_only_cors; // If it is cross domain, we will do it via a message to the background script
} else if (styleSheet.ownerNode.classList.contains("ud-idk-vars")) {
return true;
}
return false; // Stylesheet has no href, it is a style element, and is not declared by background as needing IDK intervention.
});
editableStyleSheets.forEach(styleSheet => {
// console.log("Will edit",styleSheet)
uDark.edit_cssRules(styleSheet.cssRules, true);
});
},
search_container_logo: function(element, notableInfos) {
let parent = (element.parentNode || element)
parent = (parent.parentNode || parent)
return uDark.logo_match.test(parent.outerHTML + notableInfos.uDark_cssClass)
},
search_clickable_parent(documentElement, selectorText) {
return documentElement.querySelector(`a ${selectorText},button ${selectorText}`);
},
image_element_prepare_href: function(image, documentElement, src_override,options={}) // Adds notable infos to the image element href, used by the image edition feature
{
// Do not parse url preventing adding context to it or interpreting it as a relative url or correcting its content by any way
let imageTrueSrc = src_override || image.getAttribute("src")
if (uDark.userSettings.disable_image_edition || !imageTrueSrc) {
return imageTrueSrc;
}
if (!image.hasAttribute("data-ud-selector")) {
image.setAttribute("data-ud-selector", Math.random());
}
let selectorText = image.tagName+`[data-ud-selector='${image.getAttribute("data-ud-selector")}']`;
let notableInfos = {};
for (const attribute of image.attributes) {
if (attribute.value.length > 0 && !(/[.\/]/i).test(attribute.value) && !(["src","data", "data-ud-selector"]).includes(attribute.name)) {
notableInfos[attribute.name] = attribute.value;
}
}
if (imageTrueSrc.includes(uDark.imageSrcInfoMarker)) {
return imageTrueSrc;
}
if (uDark.search_clickable_parent(documentElement, selectorText)) {
notableInfos.inside_clickable = true;
}
if (uDark.search_container_logo(image, notableInfos)) {
notableInfos.logo_match = true;
}
let usedChar = uDark.imageSrcInfoMarker;
if (!imageTrueSrc.includes("#")) {
usedChar = "#"+usedChar;
}
imageTrueSrc = uDark.send_data_image_to_parser(imageTrueSrc, false, {...options, notableInfos, image});
return imageTrueSrc + usedChar + new URLSearchParams(notableInfos).toString();
},
valuePrototypeEditor: function(leType, atName, setter = false, conditon = false, aftermath = false,getter=false) {
console.log("Editing property :",leType,atName)
// if (conditon) {
// console.log("VAdding condtition to", leType, leType.name, conditon, conditon.toString())
// }
if (leType.concat) {
return leType.forEach(aType => uDark.valuePrototypeEditor(aType, atName, setter, conditon, aftermath, getter))
}
if (leType.wrappedJSObject) { // Cross compatibilty with content script
leType = leType.wrappedJSObject;
}
var originalProperty = Object.getOwnPropertyDescriptor(leType.prototype, atName);
if (!originalProperty) {
console.error("No existing property for '", atName, "'", leType, leType.name, leType.prototype)
return;
}
Object.defineProperty(leType.prototype, "o_ud_" + atName, originalProperty);
let override_get_set = {};
if(setter){
override_get_set.set = globalThis.exportFunction(function(value) { // getters must be exported like regular functions
var new_value = (!conditon || conditon(this, value)===true) ? setter(this, value) : value;
let call_result = originalProperty.set.call(this, new_value || value);
aftermath && aftermath(this, value, new_value);
return call_result;
}, window);
}
if(getter){
override_get_set.get = globalThis.exportFunction(function() { // getters must be exported like regular functions
// console.log("Getting", this, atName)
let call_result = originalProperty.get.call(this);
return getter(this, call_result);
}, window);
}
// uDark.general_cache["o_ud_"+atName]=originalSet
Object.defineProperty(leType.prototype, atName, override_get_set);
},
functionWrapper: function(leType, laFonction, fName, watcher = x => x, conditon = true, result_editor = x => x) {
console.log("Wrapping function :",leType,laFonction,fName)
let originalFunction = leType.prototype["o_ud_wrap_" + fName] = laFonction;
leType.prototype[fName] = function(...args) {
if (conditon===true || conditon(this, arguments) === true) {
let watcher_result = watcher(this, arguments);
let result = originalFunction.apply(...watcher_result)
return result_editor(result, this, watcher_result);
} else {
return (originalFunction.apply(this, arguments));
}
}
},
functionPrototypeEditor: function(leType, laFonction, watcher = x => x, conditon = x => x, result_editor = x => x,getter) {
// console.log(leType,leType.name,leType.prototype,laFonction,laFonction.name)
if (laFonction.concat) {
return laFonction.forEach(aFonction => {
uDark.functionPrototypeEditor(leType, aFonction, watcher, conditon, result_editor)
})
}
if (leType.wrappedJSObject) { // Cross compatibilty with content script
leType = leType.wrappedJSObject;
}
console.log("Editing function :",leType,laFonction)
// if (conditon) {
// console.log("Adding condtition to", leType, leType.name, laFonction, conditon, conditon.toString())
// }
leType.prototype.count=(leType.prototype.count||0)+1;
if(!Object.getOwnPropertyDescriptor(leType.prototype, laFonction.name))
{
console.log("No getter for '", leType,laFonction,new Error(),leType.prototype.count,document.location.href)
return;
}
let originalFunctionKey = "o_ud_" + laFonction.name
var originalFunction = globalThis.exportFunction(Object.getOwnPropertyDescriptor(leType.prototype, laFonction.name).value, window);
Object.defineProperty(leType.prototype, originalFunctionKey, {
value: originalFunction,
writable: true
});
Object.defineProperty(leType.prototype, laFonction.name, {
value: {
[laFonction.name]: globalThis.exportFunction(function() {
if (conditon===true || conditon(this, arguments)) {
// console.log("Setting",leType,laFonction,this,arguments[0],watcher(this, arguments)[0])
let watcher_result = watcher(this, arguments);
// console.log("watcher_result", this,originalFunction,watcher_result,originalFunctionKey,leType.prototype[originalFunctionKey],this[originalFunctionKey],this.getP);
let result = originalFunction.apply(this, watcher_result)
return result_editor(result, this, arguments, watcher_result);
} else {
return (originalFunction.apply(this, arguments));
}
}, window)
} [laFonction.name]
});
},
// At-rules : https://developer.mozilla.org/fr/docs/Web/CSS/At-rule
// @charset, @import or @namespace, followed by some space or \n, followed by some content, followed by ; or end of STRING
// Surpisingly and fortunately end of LINE does not delimits the end of the at-rule and forces devs & minifers either to add a ; or end of STRING
// which and fortunately simplifies a LOT the handling
// 'm' flag is not set on purpose to avoid matching $ as a line end, and keeping it at end of STRING
// Content must not be interupted while between quotes or parenthesis.
// It wont break on string ("te\"st") or this one('te\'st') or @import ('abc\)d;s'); thanks to
// priority matches (\\\)) and (\\') and (\\")
//-------------------v-Rule name----space or-CR--v-----v--Protected values-v----v-the content dot
cssAtRulesRegex: /@(charset|import|namespace)(\n|\s)+((\((\\\)|.)+?\))|("(\\"|.)+?")|('(\\'|.)+?')|.)+?(;|$)/gs,
edit_str_restore_imports_all_way: function(str, rules) {
// This regexp seems a bit complex
// because @import url("") can includes ";" which is also the css instruction separator like in following example
// @charset "UTF-8";@import url("https://use.typekit.net/lls1fmf.css");
// @import url("https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap");
// .primary-1{ color: rgb(133, 175, 255); }
// This code is sensible to some edge cases, like @rules put in a comment, or in a string, and this is why i now use the protect system
// It was breaking https://www.pascalgamedevelopment.com/content.php .
// It would be possible to fix this by adding a condition to the regex to avoid matching @rules in comments or strings, but it would be a bit more complex
// Or even protecting the @rules individually wit a numbered css class, but it would be a bit more complex too regarding the occurences of the @rules in strings or comments
let imports = str.match(uDark.cssAtRulesRegex) || [];
rules.unshift(...imports);
},
send_data_image_to_parser: function(str, details, options) {
// uDark.disable_data_image_edition=true;
if (str.trim().toLowerCase().startsWith('data:') && !uDark.userSettings.disable_image_edition && !uDark.disable_data_image_edition) {
let {b64,dataHeader,data,failure} = options.cut || uDark.decodeBase64DataURIifIsDataURI(str);
let imageData = data;
options.changed = true; // We have changed the image, notify calle, like edit_css_url action
options.is_data_image=true;
if (!failure && dataHeader.includes('svg')) // Synchronous edit for data SVGs images, we have some nice context and functions to work with
{ // This avoids loosing svg data including the size of the image, and the tags in the image
uDark.disable_svg_data_url_edition = false;
options.svgImage = true;
options.svgDataImage = true;
if (uDark.disable_svg_data_url_edition) {
return str;
}
options.get_document=true;
if(!b64){
// This replaces searches for unencoded % in image data, and replaces them by the equivalent %25.
// Some websites uses % in their svg data eg for percentage value, while not encoding them.
// This results in a probalby broken image, since we are in a dataURL image.
// UltimaDark team dont care too much about this,but it can lead to decodeURI errors. and therefore to a broken page.
imageData=imageData.replace(/%(?![0-9a-z]{2})/gi,"%25")
imageData=decodeURIComponent(imageData);
}
imageData = uDark.frontEditHTML(false, imageData, details, options).innerHTML;
let encoded=undefined;
// uDark.disable_reencode_data_svg_to_base64=true;
if (uDark.disable_reencode_data_svg_to_base64) {
if(b64){
dataHeader=dataHeader.replace("base64","")
};
encoded = dataHeader + encodeURIComponent(imageData)
} else if(uDark.respect_site_svgs_dataurls){
if(!b64){
imageData=encodeURIComponent(imageData);
}
let encoded = uDark.rencodeToURI(imageData, dataHeader, b64);
if(encoded.message){
console.warn(encoded)
encoded=encodeURIComponent(imageData);
}
str=encoded;
}
else{
if(!b64){
encoded=uDark.rencodeToURI(imageData, dataHeader.split(",").join(";base64,"), true);
}
else{
encoded=uDark.rencodeToURI(imageData, dataHeader, true);
}
if(encoded.message){
console.warn(encoded)
encoded=encodeURIComponent(imageData);
encoded=uDark.rencodeToURI(encoded, dataHeader.replace("base64",""), false);
}
}
str=encoded;
} else {
str = "https://data-image?base64IMG=" + str; // Sending other images to the parser via the worker,
if (options.image) {
options.image.removeAttribute("crossorigin"); // data images are not CORS with this domain, so we remove the attribute to avoid CORS errors
}
}
}
return str;
},
get_fill_for_svg_elem: function(fillElem, override_value = false, options = {}, class_name = "udark-fill", transform = true) {
let fillValue = override_value || fillElem.getAttribute("fill");
if (override_value == "none" || !uDark.is_color(fillValue)) {
fillValue = "#000000";
}
if (["animate"].includes(fillElem.tagName)) {
return fillValue
} // fill has another meaning for animate
let is_text = options.notableInfos.guessed_type == "logo" || ["text", "tspan"].includes(fillElem.tagName);
if (!is_text && ["path"].includes(fillElem.tagName)) {
let draw_path = fillElem.getAttribute("d");
// Lot of stop path in in path, it's probably a text
is_text = draw_path && ([...draw_path.matchAll(/Z/ig)].length >= 2 || draw_path.length > 170)
}
fillElem.setAttribute("udark-edit", true);
fillElem.setAttribute(class_name, `${options.notableInfos.guessed_type}${is_text?"-text":""}`);
if (transform) {
let edit_result = uDark.transform_color(fillValue, {
prefix_fg_vars: is_text
}, is_text ? uDark.revert_rgba_rgb_raw : uDark.rgba_rgb_raw)
return edit_result.new_value;
}
return is_text
},
frontEditSVG: function(svg, documentElement, details, options = {}) {
if (uDark.userSettings.disable_image_edition) {
return;
}
uDark.edit_styles_attributes(svg, details, options);
uDark.edit_styles_elements(svg, details, "ud-edited-background", options);
options = {
...options, // Do not edit the original object, it may be used by other functions by reference
notableInfos: options.notableInfos || {},
lighten: uDark.revert_rgba_rgb_raw,
darken: uDark.rgba_rgb_raw,
}
svg.setAttribute("udark-fill", true);
svg.setAttribute("udark-id", Math.random());
let svgUdarkId = svg.getAttribute("udark-id");
if (!options.notableInfos.inside_clickable) {
if (uDark.search_clickable_parent(documentElement, `svg[udark-id='${svgUdarkId}']`)) {
options.notableInfos.inside_clickable = true;
}
}
if (!options.notableInfos.logo_match) {
if (uDark.search_container_logo(svg, options.notableInfos)) {
options.notableInfos.logo_match = true;
}
}
if (options.notableInfos.logo_match || options.notableInfos.inside_clickable) {
options.notableInfos.guessed_type = "logo";
}
if (options.notableInfos.guessed_type == "logo") {
svg.setAttribute("fill", "white");
// svg.removeAttribute("fill");
// svg.setAttribute("fill", "currentColor");
if (options.remoteSVG || options.svgDataImage) // If there is no style element, we don't need to create one
{
let styleElem = document.createElement("style");
styleElem.id = "udark-styled";
styleElem.append(document.createTextNode(uDark.inject_css_override))
styleElem.append(document.createTextNode("svg{color:white}")) // Allows "currentColor" to take effect
svg.append(styleElem);
}
}
svg.querySelectorAll("[fill]:not([udark-fill])").forEach(fillElem => {
fillElem.setAttribute("fill", uDark.get_fill_for_svg_elem(fillElem, false, options))
})
svg.querySelectorAll("[stroke]:not([udark-stroke])").forEach(fillElem => {
fillElem.setAttribute("stroke", uDark.get_fill_for_svg_elem(fillElem, fillElem.getAttribute("stroke"), options).replace(/currentColor/i, "white"), "udark-stroke")
})
// svg.querySelectorAll("circle").forEach(fillElem => {
// fillElem.setAttribute("ud-brightness-"+fillElem.outerHTML.hashCode(60,35), true);
// fillElem.setAttribute("fill", "black");
// })
// let all_svg_elems=svg.querySelectorAll(":not(udark-edit)");
// all_svg_elems.forEach((fillElem,index) => {
// if(fillElem.hasAttribute("fill")){
// return;
// }
// let is_text=uDark.get_fill_for_svg_elem(fillElem, false,{notableInfos:{}},class_name="udark-gradient",transform=false)
// if(!is_text){
// fillElem.setAttribute("ud-brightness-"+Math.floor((uDark.min_bright_bg+(index/all_svg_elems.length))*100), true);
// }
// });
svg.setAttribute("udark-guess", options.notableInfos.guessed_type);
svg.setAttribute("udark-infos", new URLSearchParams(options.notableInfos).toString());
},
edit_styles_elements: function(parentElement, details, add_class = "ud-edited-background", options = {}) {
parentElement.querySelectorAll(`style:not(.${add_class})`).forEach(astyle => {
astyle.p_ud_innerHTML = uDark.edit_str(astyle.innerHTML, false, false, details, false, options);
// astyle.innerHTML='*{fill:red!important;}'
// According to https://stackoverflow.com/questions/55895361/how-do-i-change-the-innerhtml-of-a-global-style-element-with-cssrule ,
// it is not possible to edit a style element innerHTML with its cssStyleSheet alone
// As long as we are returing a STR, we have to edit the style element innerHTML;
if (options.hasUnresolvedVars_idk_vars) {
astyle.classList.add("ud-idk-vars"); // Allows IDK mode to edit this eligible style element
}
astyle.classList.add(add_class)
});
},
frontEditHTML: function(elem, strO, details, options = {}) {
// 1. Ignore <script> elements to prevent unintended modifications to JavaScript
let str = strO;
if (elem instanceof HTMLScriptElement) {
return strO;
}
// 2. Special handling for <style> and <svg> style elements (returns edited value directly)
if (elem instanceof HTMLStyleElement || elem instanceof SVGStyleElement) {
return uDark.edit_str(str, false, false, undefined, false, options);
}
str = str.protect_simple(/\b(head|html|body)\b/gi, "ud-tag-ptd-$1");
let parsedDocument = uDark.createDocumentFromHtml("<body>"+str+"</body>"
/* Re encapsulate str into a <body> is not an overkill : Exists something called unsafeHTML clid binding. I did not understood what it is, but it needs a body tag for proper parsing*/
);
const aDocument = parsedDocument.body;
// 4. Temporarily replace all SVG elements to avoid accidental style modifications
const svgElements = uDark.processSvgElements(aDocument, details);
// 5. Edit styles and attributes inline for background elements
uDark.edit_styles_attributes(aDocument, details);
uDark.edit_styles_elements(aDocument, details, "ud-edited-background");
// 8. Add a custom identifier to favicon links to manage cache
uDark.processLinks(aDocument);
// 9. Process image sources and prepare them for custom modifications
uDark.processImages(aDocument);
// 10. Recursively process iframes using the "srcdoc" attribute by applying the same editing logic
uDark.processIframes(aDocument, details, options);
// 11. Handle elements with color attributes (color, bgcolor) and ensure proper color handling
uDark.processColoredItems(aDocument);
// 13. Restore the original SVG elements that were temporarily replaced
uDark.restoreSvgElements(svgElements);
// 15. Remove the integrity attribute from elements and replace it with a custom attribute
uDark.restoreIntegrityAttributes(aDocument);
// 18. After all the edits, return the final HTML output
if(options.get_document){
return aDocument;
}
let resultEdited = aDocument.innerHTML.unprotect_simple("ud-tag-ptd-");
return resultEdited;
},
frontEditHTML_old: function(elem, strO, details, options = {}) {
// 1. Ignore <script> elements to prevent unintended modifications to JavaScript
let value = strO;
if (elem instanceof HTMLScriptElement) {
return value;
}
// 2. Special handling for <style> and <svg> style elements (returns edited value directly)
if (elem instanceof HTMLStyleElement || elem instanceof SVGStyleElement) {
return uDark.edit_str(value, false, false, undefined, false, options);
}
if (!value.includes("body")) {
// 3. Ensure the HTML is encapsulated within a <body> tag, especially for non-encapsulated HTML
value = "<body>" + value + "</body>";
}
// 2. The issue isn't with <noscript> itself, but with disallowed tags inside the <head>, including those nested within <noscript>. Many sites make this mistake.
// The tags allowed in the <head> are: <base>, <link>, <meta>, <style>, <title>, <script>, <noscript>, and <template>.
// When placed in the <head>, the <noscript> tag has strict limitations on what it can contain. It only allows <link>, <style>, and <meta> as child elements.
// In contrast, the <template> tag has no such restrictions. It can contain any type of elements, even when placed in the <head>.
// The <script> tag is also flexible, as it allows raw text content.
// The <style> tag is similarly unrestricted in terms of content, as it handles raw CSS text.
// I chose to use the <script> tag with `type="text/plain"` because, unlike <template>, it doesn't break the entire page if there's an unclosed tag inside it.
// If <template> contains an unclosed tag, the DOM parser won't find the closing </template> tag, causing the entire page to break.
// However, <noscript> and <script> tags are unaffected by this issue. That said, <noscript> can still be problematic in the <head> because its content may include disallowed elements.
value = value.replaceAll(/<noscript/g, "<script type='text/plain' secnoscript");
value = value.replaceAll(/<\/noscript/g, "</script");
// 5. Parse the HTML string into a DOM document
const aHtmlDocument = uDark.createDocumentFromHtml(value);
const documentElement = aHtmlDocument.documentElement;
// 6. Process meta tags to ensure proper charset handling
// uDark.processMetaTags(documentElement);
// 7. Restore or set the color-scheme meta tag for dark mode handling this is not usefull since we do all with css color-scheme attribute wich is prevalent
// <meta name="color-scheme" content="dark light"> Telling broswer order preference for colors
// Makes input type checkboxes and radio buttons to be darkened
// documentElement.querySelectorAll("meta[name='color-scheme']").forEach(udMetaDark => {
// udMetaDark.id = "ud-meta-dark";
// udMetaDark.name = "color-scheme";
// udMetaDark.content = "dark";
// });
// 8. Temporarily replace all SVG elements to avoid accidental style modifications
const svgElements = uDark.processSvgElements(documentElement, details);
// 9. Edit styles and attributes inline for foreground elements
uDark.edit_styles_attributes(documentElement, details);
uDark.edit_styles_elements(documentElement, details, "ud-edited-background");
// 11. Add a custom identifier to favicon links to manage cache
uDark.processLinks(documentElement);
// 12. Process image sources and prepare them for custom modifications
uDark.processImages(documentElement);
// 13. Recursively process iframes using the "srcdoc" attribute by applying the same editing logic
uDark.processIframes(documentElement, details, options);
// 14. Handle elements with color attributes (color, bgcolor) and ensure proper color handling
uDark.processColoredItems(documentElement);
// 15. Restore the original SVG elements that were temporarily replaced
uDark.restoreSvgElements(svgElements);
// 16. Restore <noscript> elements that were converted to something else
// uDark.restoreTemplateElements(documentElement);
uDark.restoreNoscriptElements(aHtmlDocument);
// 17. Remove the integrity attribute from elements and replace it with a custom attribute
uDark.restoreIntegrityAttributes(documentElement);
// 18. After all the edits, return the final HTML output
let resultEdited = value.includes("body") && !options.no_body ? documentElement.outerHTML : aHtmlDocument.body.innerHTML;
return resultEdited;
},
createDocumentFromHtml: function(html) {
// Use DOMParser to convert the HTML string into a DOM document
const parser = new DOMParser();
return parser.parseFromString(html, "text/html");
},
processSvgElements: function(documentElement, details) {
let svgElements = [];
// Temporarily replace all SVG elements to avoid accidental style modifications
documentElement.querySelectorAll("svg").forEach(svg => {
const tempReplace = document.createElement("svg_secured");
svgElements.push([svg, tempReplace]);
svg.replaceWith(tempReplace);
// Edit SVG styles separately, before main style editing
uDark.frontEditSVG(svg, documentElement, details);
});
return svgElements;
},
processMetaTags: function(documentElement) {
// Ensure that content-type meta tags are properly set to avoid charset issues
documentElement.querySelectorAll("meta[http-equiv]").forEach(m => {
if (m.httpEquiv && m.httpEquiv.toLowerCase().trim() === "content-type" && m.content.includes("charset")) {
m.content = "text/html; charset=utf-8";
}
});
},
edit_styles_attributes: function(parentElement, details, options = {}) {
parentElement.querySelectorAll("[style]").forEach(astyle => {
// console.log(details,astyle,astyle.innerHTML,astyle.innerHTML.includes(`button,[type="reset"],[type="button"],button:hover,[type="button"],[type="submit"],button:active:hover,[type="button"],[type="submi`))
astyle.setAttribute("style", uDark.edit_str(astyle.getAttribute("style"), false, false, details, false, {...options,nochunk:true}));
});
},
processLinks: function(documentElement) {
// Append a custom identifier to favicon links to manage cache more effectively
documentElement.querySelectorAll("link[rel*='icon' i][href]").forEach(link => {
link.setAttribute("href", link.getAttribute("href") + "#ud_favicon");
});
},
decodeBase64DataURIifIsDataURI: function(maybeBase64DataURI) {
maybeBase64DataURI=maybeBase64DataURI.trim();
if(!maybeBase64DataURI.startsWith("data:")){
return {b64:false,dataHeader:false,data:maybeBase64DataURI};
}
let commaIndex = maybeBase64DataURI.indexOf(","); // String.split is broken: It limits the number of elems in returned array instead of limiting the number of splits
let [dataHeader, data] = [maybeBase64DataURI.substring(0, commaIndex+1).toLowerCase().trim(), maybeBase64DataURI.substring(commaIndex + 1)]
if(!dataHeader.includes("base64")){
return {b64:false,dataHeader,data}
}
try{
return {b64:true,dataHeader,data:atob(data)}
}
catch{
console.warn("Error decoding base64 data URI",maybeBase64DataURI)
return {b64:true,dataHeader:false,data:false,failure:true}
}
},
rencodeToURI(data,dataHeader,base64=false){
if(!dataHeader)
{
return data;
}
if(base64){
try{
return dataHeader+ btoa(data);
}
catch{
return new Error("Error encoding base64 data URI",data)
}
}
return dataHeader+data;
},
processImages: function(documentElement) {
// Process image sources to prepare them for custom modifications
documentElement.querySelectorAll("img[src]").forEach(image => {
image.setAttribute("src", uDark.image_element_prepare_href(image, documentElement));
});
},
frontEditHTMLPossibleDataURL: function(elem,value,details,options,documentElement) {
let {b64,dataHeader,data,failure}=uDark.decodeBase64DataURIifIsDataURI(value||""); // Value can be null
if(!failure && dataHeader){
if(dataHeader.includes("image")){
return uDark.image_element_prepare_href(elem,documentElement||document,value,{...options,cut:{b64,dataHeader,data}});
}
else if(dataHeader.includes("html")){
data=uDark.frontEditHTML(elem, data, details, options)
return uDark.rencodeToURI(data,dataHeader,b64);
}
}
return value;
},
processIframes: function(documentElement, details, options) {
// Recursively process iframes that use the "srcdoc" attribute by applying the same HTML processing function
documentElement.querySelectorAll("iframe[srcdoc]").forEach(iframe => {
iframe.setAttribute("srcdoc", uDark.frontEditHTML(false, iframe.srcdoc, details));
});
documentElement.querySelectorAll("object[data],embed[src],iframe[src]").forEach(object => {
// Use GetAttribute to get the original value, as the src attribute may be changed by the context
let src=object.getAttribute("src");
let usedData = src?src: object.getAttribute("data") ;
object.setAttribute(src?"src":"data", uDark.frontEditHTMLPossibleDataURL(object, usedData, details,options,documentElement));
});
},
processColoredItems: function(documentElement) {
// Process elements with color or bgcolor attributes and ensure proper color handling
documentElement.querySelectorAll("[color],[bgcolor]").forEach(coloredItem => {
for (let [key, afunction] of Object.entries(uDark.attributes_function_map)) {
if (typeof afunction === "string") {
afunction = uDark.attributes_function_map[afunction];
}
let attributeValue = coloredItem.getAttribute(key);
if (attributeValue && attributeValue.startsWith("#") && attributeValue.length === 6) {
attributeValue += "0"; // Ensure colors are properly formatted
}
const possibleColor = uDark.is_color(attributeValue, true, true);
if (possibleColor) {
let callResult = afunction(...possibleColor, uDark.hex_val /* this kind of html4 attributes does not fully supports rgba vals, prefer use hex vals */, coloredItem);
if (callResult) {
coloredItem.setAttribute(key, callResult);
}
}
}
});
},
injectStylesIfNeeded: function(aDocument, details) {
// Inject custom CSS and the dark color scheme meta tag if this is the first data load
if (details.dataCount === 1) {
// Stopped using inject_css_suggested, as it was causing issues with some websites, like react ones that stats with a minimal body
const udMetaDark = aDocument.querySelector("meta[name='color-scheme']") || document.createElement("meta");
udMetaDark.id = "ud-meta-dark";
udMetaDark.name = "color-scheme";
udMetaDark.content = "dark";
headElem = aDocument.head || aDocument.querySelector("ud-tag-ptd-head") || aDocument;
headElem.prepend(udMetaDark);
}
},
restoreSvgElements: function(svgElements) {
// Restore the original SVG elements that were temporarily replaced
svgElements.forEach(([svg, tempReplace]) => {
tempReplace.replaceWith(svg);
});
},
restoreNoscriptElements: function(aDocument) {
// Restore <noscript> elements that were converted to <script>
aDocument.querySelectorAll("script[secnoscript]").forEach(script => {
let noScript = document.createElement("noscript");
for (let node of script.attributes) {
noScript.setAttribute(node.name, node.value)
}
let template = aDocument.createElement('template');
template.innerHTML = script.innerHTML;
noScript.append(template.content); // We cant put innerHTML directly in a noscript element, it would be html encoded. The template element is used to avoid this, it parse elements for us.
script.replaceWith(noScript);
});
},
restoreTemplateElements: function(aDocument) {
// Restore <noscript> elements that were converted to <template>
// Using replaceWith() instead of innerHTML to avoid issues with nested elements wich were HTMLencoded
aDocument.querySelectorAll("template[secnoscript]").forEach(template => {
let noScript=document.createElement("noscript");
for(let node of template.attributes){
noScript.setAttribute(node.name,node.value)
}
noScript.append(template.content);
template.replaceWith(noScript);
});
},
restoreIntegrityAttributes: function(aDocument) {
// Remove the integrity attribute from elements and store it as a custom attribute
aDocument.querySelectorAll("[integrity]").forEach(integrityElem => {
integrityElem.setAttribute("data-no-integ", integrityElem.getAttribute("integrity"));
integrityElem.removeAttribute("integrity");
integrityElem.setAttribute("onerror","uDark.linkIntegrityErrorEvent(this)"); // Fix for reloading the resource if it fails to load, happened on graphene.org
});
},
str_protect_simple: function(str, regex, protectWith, condition = true) {
if (condition) {
str = str.replaceAll(regex, protectWith)
}
return str;
},
str_unprotect_simple: function(str, protectedWith, condition = true) {
if (condition) {
str = str.replaceAll(protectedWith, "")
}
return str;
},
/*
Took comments from w3.org/csswg-drafts/css-syntax-3/#comments
First part: \/\*[^*]*\*+([^/*][^*]*\*+)*\/ — This matches valid CSS comments.
Second part: \/\*[^*]*\*+([^/*][^*]*\*+)* — This matches incomplete comments that look like they are improperly closed (badcomment1).
Third part: \/\*[^*]*(\*+[^/*][^*]*)* — This also matches another form of incomplete comments (badcomment2).
*/
exactAtRuleProtect: true,
matchAllCssCommentsRegex: /\/\*[^*]*\*+([^/*][^*]*\*+)*\/|\/\*[^*]*\*+([^/*][^*]*\*+)*|\/\*[^*]*(\*+[^/*][^*]*)*/g,
edit_str_nochunk:function(strO)
{
if(strO.join){
strO=strO.join("");
}
return uDark.edit_str(strO, false, false, undefined, false, {nochunk:true});
},
edit_str: function(strO, cssStyleSheet, verifyIntegrity = false, details, idk_mode = false, options = {}) {
let str = strO;
if (strO.includes("/*!sc*/")) { // TODO: Fix thins in abetter way; this is a temporary and specific fix;
console.log("SCSS detected", uDark.edit_str);
uDark.edit_str.last_debugged = {
strO,
cssStyleSheet,
verifyIntegrity,
details,
idk_mode,
options
};
return strO;
}
// Protection of imports
// Unfortunately, this could lead to a reparation of a broken css if the chunking splits the @import in two parts
// We might someday encounter this very improbable case, and have to check if the last rule is an unclosed @rule, while having some rules before it and reject the CSS chunk
// In the end the chunk would eventualy come back contatenated with the next chunk, and then we could edit it properly.
let import_protection = strO.protect_numbered(uDark.cssAtRulesRegex, "udarkAtRuleProtect{index} { }", uDark.exactAtRuleProtect)
str = import_protection.str;
str = str.protect_simple(uDark.shortHandRegex, "--ud-ptd-$1:");
if (!cssStyleSheet) {
cssStyleSheet = new CSSStyleSheet()
if(!options.nochunk){ // Avoiding a warning in the console when we know we are not chunking
let valueReplace = str + (verifyIntegrity ? "\n.integrity_rule{}" : "");
cssStyleSheet.p_ud_replaceSync(valueReplace);
}
} else if (!cssStyleSheet.rules.length) {
return strO; // Empty styles from domparser can't be edited as they are not "constructed"
}
let rejected_str = false;
// Protection of CSS shorthand properties,
// let protected_comments=str.protect(uDark.matchAllCssCommentsRegex,"");
// str=protected_comments.str;
let nochunk = options.nochunk||!verifyIntegrity && !cssStyleSheet.cssRules.length // if we want to check integrity, it means we have a chunked css
if (nochunk) {
// Here if :
// - We only have properties like background: white;
if (import_protection.values) {
return strO;
}
str = `z{${str}}`;
cssStyleSheet.p_ud_replaceSync(str);
uDark.edit_css(cssStyleSheet, idk_mode, details, options);
str = cssStyleSheet.cssRules[0].cssText.slice(4, -2);
} else {
/* This does not exist anymore, as we are repairing import locations in the CSS with the import protection, integrity will allways be verifiable.
// Exists the rare case where css only do imports, no rules with {} and integrity cant be verified because it does not close the import with a ";"
let returnAsIs = (!cssStyleSheet.cssRules.length && !strO.includes("{")); // More reliable than checking if it starts with an a @ at it may starts with a comment
// let returnAsIs = (!cssStyleSheet.cssRules.length && import_protection.values); // More reliable than checking if it starts with an a @ at it may starts with a comment
if (returnAsIs) {
console.log("Returning as is", strO);