-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuserstyles.js
More file actions
1539 lines (1536 loc) · 56.3 KB
/
Copy pathuserstyles.js
File metadata and controls
1539 lines (1536 loc) · 56.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// Generated from src/modules/userstyles.ts; do not edit by hand.
// Run `node scripts/generate-ts-runtime-modules.mjs` or `npm run build:bg`.
// ============================================================================
const UserStylesEngine = (() => {
const module = { exports: {} };
const exports = module.exports;
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/modules/userstyles.ts
var userstyles_exports = {};
__export(userstyles_exports, {
UserStylesEngine: () => UserStylesEngine
});
module.exports = __toCommonJS(userstyles_exports);
var _UNSUPPORTED_PREPROCESSORS = /* @__PURE__ */ new Set(["less", "stylus", "styl"]);
var STORAGE_KEY = "sv_userstyles";
var VARS_STORAGE_KEY = "sv_userstyle_vars";
var META_REGEX = /\/\*\s*==UserStyle==\s*([\s\S]*?)==\/UserStyle==\s*\*\//;
var VAR_TYPES = ["color", "text", "number", "select", "checkbox", "range"];
var DIRECTIVE_REGEX = /^@(\S+)\s+(.*?)\s*$/;
var _styles = {};
var _customVars = {};
var _initialized = false;
var _registeredTabs = /* @__PURE__ */ new Map();
var _currentDocumentIds = /* @__PURE__ */ new Map();
var _draftPreviewTabs = /* @__PURE__ */ new Map();
var _injectingTabs = /* @__PURE__ */ new Set();
var PERSISTENT_REGISTRATION_PREFIX = "scriptvault-usercss-";
var _persistentRegistrationSupported = false;
var _persistentRegistrationChain = Promise.resolve(false);
var _pendingTabUrls = /* @__PURE__ */ new Map();
var _draftPreviewChain = Promise.resolve();
function _normalizeDocumentId(value) {
const id = typeof value === "string" ? value.trim() : "";
return id && id.length <= 256 ? id : void 0;
}
function _tabRegistryKey(tabId) {
return `tab:${tabId}`;
}
function _documentRegistryKey(tabId, documentId) {
return `document:${tabId}:${documentId}`;
}
function _documentIdForTab(tabId, explicitDocumentId) {
return _normalizeDocumentId(explicitDocumentId) ?? _currentDocumentIds.get(tabId);
}
function _registryKeyForTab(tabId, explicitDocumentId) {
const documentId = _normalizeDocumentId(explicitDocumentId);
if (documentId) {
const current2 = _currentDocumentIds.get(tabId);
if (current2 !== documentId) {
_deleteTabRegistries(tabId);
_currentDocumentIds.set(tabId, documentId);
}
return _documentRegistryKey(tabId, documentId);
}
const current = _currentDocumentIds.get(tabId);
return current ? _documentRegistryKey(tabId, current) : _tabRegistryKey(tabId);
}
function _injectionTarget(tabId, explicitDocumentId) {
const documentId = _documentIdForTab(tabId, explicitDocumentId);
return documentId ? { tabId, documentIds: [documentId] } : { tabId };
}
function _deleteTabRegistries(tabId) {
_registeredTabs.delete(_tabRegistryKey(tabId));
const prefix = `document:${tabId}:`;
for (const key of _registeredTabs.keys()) {
if (key.startsWith(prefix)) _registeredTabs.delete(key);
}
}
function _isFirefoxRuntime() {
try {
return /Firefox\//.test(String(globalThis.navigator?.userAgent || ""));
} catch {
return false;
}
}
async function _readCurrentDocumentId(tabId) {
if (!_isFirefoxRuntime()) return void 0;
const getFrame = chrome.webNavigation?.getFrame;
if (typeof getFrame !== "function") return void 0;
try {
const frame = await getFrame({ tabId, frameId: 0 });
return _normalizeDocumentId(frame?.documentId);
} catch {
return void 0;
}
}
async function _loadState() {
try {
const data = await chrome.storage.local.get([STORAGE_KEY, VARS_STORAGE_KEY]);
_styles = data[STORAGE_KEY] ?? {};
_customVars = data[VARS_STORAGE_KEY] ?? {};
} catch (e) {
console.error("[UserStylesEngine] Failed to load state:", e);
_styles = {};
_customVars = {};
}
}
async function _saveStyles() {
try {
await chrome.storage.local.set({ [STORAGE_KEY]: _styles });
} catch (e) {
console.error("[UserStylesEngine] Failed to save styles:", e);
}
}
async function _saveVars() {
try {
await chrome.storage.local.set({ [VARS_STORAGE_KEY]: _customVars });
} catch (e) {
console.error("[UserStylesEngine] Failed to save variables:", e);
}
}
function _stripQuotedValue(value) {
const trimmed = value.trim();
if (trimmed.length >= 2 && (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'"))) {
return trimmed.slice(1, -1);
}
return trimmed;
}
function _splitTopLevel(value, separator = ",") {
const parts = [];
let depth = 0;
let quote = "";
let start = 0;
for (let index = 0; index < value.length; index++) {
const char = value[index] ?? "";
if (quote) {
if (char === quote && value[index - 1] !== "\\") quote = "";
continue;
}
if (char === '"' || char === "'") {
quote = char;
} else if (char === "(") {
depth++;
} else if (char === ")") {
depth--;
} else if (char === separator && depth === 0) {
parts.push(value.slice(start, index).trim());
start = index + 1;
}
}
parts.push(value.slice(start).trim());
return parts;
}
function _detectColorSpace(value) {
const normalized = _stripQuotedValue(value).toLowerCase();
if (/^#[0-9a-f]+$/i.test(normalized)) return "hex";
if (/^rgba?\(/.test(normalized)) return "rgb";
if (/^hsla?\(/.test(normalized)) return "hsl";
if (/^oklch\(/.test(normalized)) return "oklch";
if (/^oklab\(/.test(normalized)) return "oklab";
if (/^[a-z][a-z0-9-]*$/i.test(normalized)) return "named";
return "css";
}
function _validateColorValue(value, label = "Color") {
if (typeof value !== "string") return `${label} must be a CSS color string.`;
const color = _stripQuotedValue(value);
if (!color) return `${label} cannot be empty.`;
if (color.length > 256) return `${label} must be 256 characters or fewer.`;
if (/[;{}\x00-\x1f\x7f]/.test(color)) return `${label} contains unsafe CSS characters.`;
if (/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color)) return "";
if (/^(?:transparent|currentcolor|canvas|canvastext|accentcolor|accentcolortext|[a-z]+)$/i.test(color)) return "";
const functional = color.match(/^([a-z][a-z0-9-]*)\(([\s\S]*)\)$/i);
if (!functional) return `${label} is not a supported CSS color.`;
const functionName = (functional[1] ?? "").toLowerCase();
const body = functional[2] ?? "";
const supported = /* @__PURE__ */ new Set([
"rgb",
"rgba",
"hsl",
"hsla",
"hwb",
"lab",
"lch",
"oklab",
"oklch",
"color",
"color-mix",
"light-dark",
"var"
]);
if (!supported.has(functionName)) return `${label} uses unsupported ${functionName}() syntax.`;
let depth = 0;
for (const char of body) {
if (char === "(") depth++;
if (char === ")") depth--;
if (depth < 0) return `${label} has unbalanced parentheses.`;
}
if (depth !== 0) return `${label} has unbalanced parentheses.`;
if (functionName === "light-dark") {
const choices = _splitTopLevel(body);
if (choices.length !== 2) return `${label} light-dark() requires light and dark colors.`;
return _validateColorValue(choices[0], `${label} light value`) || _validateColorValue(choices[1], `${label} dark value`);
}
if (functionName === "oklab" || functionName === "oklch") {
const components = body.split("/")[0]?.trim().split(/\s+/).filter(Boolean) ?? [];
if (components.length !== 3) return `${label} ${functionName}() requires three components.`;
}
if (functionName === "hsl" || functionName === "hsla") {
const components = body.includes(",") ? _splitTopLevel(body) : body.split("/")[0]?.trim().split(/\s+/).filter(Boolean) ?? [];
if (components.length < 3) return `${label} ${functionName}() requires hue, saturation, and lightness.`;
}
return "";
}
function _parseAdvancedColorValue(rawValue) {
const annotations = [];
const annotationRegex = /\s+@(group|light|dark)\s+/gi;
let match;
while ((match = annotationRegex.exec(rawValue)) !== null) {
annotations.push({
name: (match[1] ?? "").toLowerCase(),
start: match.index,
valueStart: annotationRegex.lastIndex
});
}
const base = _stripQuotedValue(rawValue.slice(0, annotations[0]?.start ?? rawValue.length));
let group = "";
let light = "";
let dark = "";
annotations.forEach((annotation, index) => {
const end = annotations[index + 1]?.start ?? rawValue.length;
const annotationValue = _stripQuotedValue(rawValue.slice(annotation.valueStart, end));
if (annotation.name === "group") group = annotationValue.replace(/^#/, "");
if (annotation.name === "light") light = annotationValue;
if (annotation.name === "dark") dark = annotationValue;
});
const colorSchemes = light || dark ? { light: light || base, dark: dark || base } : void 0;
return {
value: base,
...group ? { group } : {},
...colorSchemes ? { colorSchemes } : {}
};
}
function _parseVarDirective(type, rest) {
const nameMatch = rest.match(/^(\S+)\s+"([^"]*?)"\s+([\s\S]*)$/);
let varName;
let label;
let defaultVal;
if (nameMatch) {
varName = nameMatch[1] ?? "";
label = nameMatch[2] ?? "";
defaultVal = (nameMatch[3] ?? "").trim();
} else {
const simpleMatch = rest.match(/^(\S+)\s+(.*)$/);
if (!simpleMatch) return null;
varName = simpleMatch[1] ?? "";
label = varName;
defaultVal = (simpleMatch[2] ?? "").trim();
}
let options = null;
let group;
let colorSpace;
let colorSchemes;
switch (type) {
case "color":
{
const advanced = _parseAdvancedColorValue(String(defaultVal));
defaultVal = advanced.value;
group = advanced.group;
colorSchemes = advanced.colorSchemes;
colorSpace = _detectColorSpace(advanced.value);
}
break;
case "text":
if (/^"[\s\S]*"$/.test(defaultVal)) {
try {
defaultVal = JSON.parse(defaultVal);
} catch {
defaultVal = defaultVal.slice(1, -1);
}
}
break;
case "number":
defaultVal = parseFloat(defaultVal) || 0;
break;
case "checkbox":
defaultVal = defaultVal === "1" || defaultVal === "true";
break;
case "select": {
const braceMatch = defaultVal.match(/^\{([\s\S]*)\}$/);
if (braceMatch) {
const inner = braceMatch[1] ?? "";
try {
const parsed = JSON.parse(`{${inner}}`);
options = parsed;
defaultVal = Object.keys(parsed)[0] ?? "";
} catch {
const pairs = inner.split("|");
let firstKey = null;
const selectOptions = {};
for (const pair of pairs) {
const kv = pair.match(/^"?([^":]+)"?\s*:\s*"?([^"|]*)"?\s*$/);
if (kv) {
const key = (kv[1] ?? "").trim();
const val = (kv[2] ?? "").trim();
selectOptions[key] = val;
if (!firstKey) firstKey = key;
}
}
options = selectOptions;
defaultVal = firstKey ?? "";
}
}
break;
}
case "range": {
const arrMatch = defaultVal.match(/^\[([\s\S]*)\]$/);
if (arrMatch) {
const parts = (arrMatch[1] ?? "").split(",").map((s) => parseFloat(s.trim()));
options = {
min: parts[0] ?? 0,
max: parts[1] ?? 100,
step: parts[2] ?? 1
};
defaultVal = parts[3] ?? parts[0] ?? 0;
} else {
defaultVal = parseFloat(defaultVal) || 0;
options = { min: 0, max: 100, step: 1 };
}
break;
}
}
return {
type,
name: varName,
label,
default: defaultVal,
options,
...group ? { group } : {},
...colorSpace ? { colorSpace } : {},
...colorSchemes ? { colorSchemes } : {}
};
}
function parseUserCSS(code) {
const metaMatch = code.match(META_REGEX);
if (!metaMatch) {
return { error: "No ==UserStyle== metadata block found." };
}
const meta = {
name: "Unnamed Style",
namespace: "scriptvault",
version: "1.0.0",
description: "",
author: "",
license: "",
preprocessor: "default",
homepageURL: "",
supportURL: "",
updateURL: ""
};
const variables = [];
const matchPatterns = [];
const metaBlock = metaMatch[1] ?? "";
const lines = metaBlock.split("\n");
for (const line of lines) {
const trimmed = line.replace(/^\s*\*?\s*/, "").trim();
if (!trimmed || trimmed.startsWith("//")) continue;
const match = trimmed.match(DIRECTIVE_REGEX);
if (!match) continue;
const key = match[1] ?? "";
const value = match[2] ?? "";
if (key === "var") {
const varTypeMatch = value.match(/^(\S+)\s+([\s\S]+)$/);
if (varTypeMatch && VAR_TYPES.includes(varTypeMatch[1])) {
const parsed = _parseVarDirective(varTypeMatch[1], varTypeMatch[2] ?? "");
if (parsed) variables.push(parsed);
}
} else if (key === "match" && value) {
matchPatterns.push(value);
} else if (Object.prototype.hasOwnProperty.call(meta, key)) {
meta[key] = value;
}
}
const metaEnd = code.indexOf("==/UserStyle==");
const afterMeta = code.indexOf("*/", metaEnd);
let css = "";
if (afterMeta !== -1) {
css = code.substring(afterMeta + 2).trim();
}
const validation = validateUserCSSVariables(variables);
if (!validation.valid) {
return { error: validation.errors.join(" ") };
}
const result = {
meta,
variables,
match: matchPatterns.length ? matchPatterns : ["*://*/*"],
css
};
const preprocessor = (meta.preprocessor || "default").toLowerCase();
if (_UNSUPPORTED_PREPROCESSORS.has(preprocessor)) {
result.warning = `This style declares "@preprocessor ${meta.preprocessor}", which requires a ${preprocessor === "less" ? "Less" : "Stylus"} compiler that ScriptVault does not bundle. Its variables are substituted, but its ${preprocessor} syntax is not compiled and may not render correctly. Convert it to plain CSS (default/uso) for full support.`;
}
return result;
}
function _isColorSchemeValue(value) {
return !!value && typeof value === "object" && !Array.isArray(value) && typeof value.light === "string" && typeof value.dark === "string";
}
function _validateVariableValue(variable, value) {
if (variable.type === "color") {
if (_isColorSchemeValue(value)) {
return _validateColorValue(value.light, `${variable.label} light color`) || _validateColorValue(value.dark, `${variable.label} dark color`);
}
return _validateColorValue(value, variable.label || variable.name);
}
if (variable.type === "checkbox" && typeof value !== "boolean") {
return `${variable.label || variable.name} must be true or false.`;
}
if ((variable.type === "number" || variable.type === "range") && (typeof value !== "number" || !Number.isFinite(value))) {
return `${variable.label || variable.name} must be a finite number.`;
}
if (variable.type === "select" && variable.options && !Object.prototype.hasOwnProperty.call(variable.options, String(value))) {
return `${variable.label || variable.name} must use a configured option.`;
}
if (variable.type === "text" && typeof value === "string") {
if (value.length > 8192) {
return `${variable.label || variable.name} must be 8192 characters or fewer.`;
}
if (/[{}\x00-\x1f\x7f]/.test(value)) {
return `${variable.label || variable.name} contains unsafe CSS characters.`;
}
}
if (typeof value === "object") return `${variable.label || variable.name} has an invalid value.`;
return "";
}
function validateUserCSSVariables(variables, values = {}) {
const errors = [];
const names = /* @__PURE__ */ new Set();
const reservedNames = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
for (const variable of variables) {
if (!/^-?[_a-z][\w-]*$/i.test(variable.name) || reservedNames.has(variable.name.toLowerCase())) {
errors.push("UserCSS variable names must be non-empty CSS identifiers.");
continue;
}
if (names.has(variable.name)) {
errors.push(`Duplicate UserCSS variable: ${variable.name}.`);
continue;
}
names.add(variable.name);
if (variable.group && !/^[a-z0-9_-]{1,64}$/i.test(variable.group)) {
errors.push(`${variable.label || variable.name} has an invalid color group.`);
}
const defaultError = _validateVariableValue(variable, variable.colorSchemes ?? variable.default);
if (defaultError) errors.push(defaultError);
}
for (const [name, value] of Object.entries(values)) {
const variable = variables.find((candidate) => candidate.name === name);
if (!variable) {
errors.push(`Unknown UserCSS variable: ${name}.`);
continue;
}
const valueError = _validateVariableValue(variable, value);
if (valueError) errors.push(valueError);
}
return { valid: errors.length === 0, errors };
}
function _expandLinkedGroupValues(variables, values) {
const expanded = { ...values };
for (const [name, value] of Object.entries(values)) {
const source = variables.find((variable) => variable.name === name);
if (!source?.group || source.type !== "color") continue;
for (const linked of variables) {
if (linked.type === "color" && linked.group === source.group) {
expanded[linked.name] = value;
}
}
}
return expanded;
}
function _substituteVariables(css, variables, customValues, colorScheme = "auto") {
if (colorScheme === "auto" && variables.some((variable) => {
const configured = customValues && customValues[variable.name] !== void 0 ? customValues[variable.name] : variable.colorSchemes ?? variable.default;
return _isColorSchemeValue(configured);
})) {
const lightCSS = _substituteVariables(css, variables, customValues, "light");
const darkCSS = _substituteVariables(css, variables, customValues, "dark");
return `${lightCSS}
@media (prefers-color-scheme: dark) {
${darkCSS}
}`;
}
let result = css;
for (const v of variables) {
const configured = customValues && customValues[v.name] !== void 0 ? customValues[v.name] : v.colorSchemes ?? v.default;
let val;
if (_isColorSchemeValue(configured)) {
val = colorScheme === "dark" ? configured.dark : configured.light;
} else {
val = configured;
}
const replacement = String(val);
const placeholder = new RegExp(
"/\\*\\[\\[" + _escapeRegex(v.name) + "\\]\\]\\*/",
"g"
);
result = result.replace(placeholder, () => replacement);
const anglePlaceholder = new RegExp(
"<<" + _escapeRegex(v.name) + ">>",
"g"
);
result = result.replace(anglePlaceholder, () => replacement);
result = _replaceCssVarAliases(result, v.name, replacement);
}
return result;
}
function _replaceCssVarAliases(css, name, replacement) {
const open = new RegExp("var\\(\\s*--" + _escapeRegex(name) + "\\s*(?=[,)])", "g");
let result = "";
let lastIndex = 0;
let match;
while ((match = open.exec(css)) !== null) {
let depth = 1;
let end = match.index + match[0].length;
while (end < css.length && depth > 0) {
const char = css[end] ?? "";
if (char === "(") depth++;
else if (char === ")") depth--;
end++;
}
if (depth !== 0) break;
result += css.slice(lastIndex, match.index) + replacement;
lastIndex = end;
open.lastIndex = end;
}
return result + css.slice(lastIndex);
}
function _escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function _syncShadowStylesInDocument(styles) {
const pageGlobal = globalThis;
const pageDocument = pageGlobal.document;
if (!pageDocument) return;
const stateKey = "__scriptvaultUserStyleShadowState";
const state = pageGlobal[stateKey] ?? (pageGlobal[stateKey] = {
entries: /* @__PURE__ */ new Map(),
observers: /* @__PURE__ */ new Map(),
documentRoot: null,
scanning: false,
scanAgain: false
});
if (!state.observers) state.observers = /* @__PURE__ */ new Map();
const desired = /* @__PURE__ */ new Map();
for (const style of Array.isArray(styles) ? styles : []) {
if (style?.id && style.css) desired.set(String(style.id), String(style.css));
}
const removeEntry = (entry) => {
for (const node of entry.nodes.values()) {
try {
node.remove();
} catch {
}
}
entry.nodes.clear();
};
for (const [id, entry] of state.entries) {
if (!desired.has(id)) {
removeEntry(entry);
state.entries.delete(id);
}
}
for (const [id, css] of desired) {
const existing = state.entries.get(id);
if (existing) {
if (existing.css !== css) {
existing.css = css;
for (const node of existing.nodes.values()) node.textContent = css;
}
} else {
state.entries.set(id, { css, nodes: /* @__PURE__ */ new Map() });
}
}
const hasEntries = state.entries.size > 0;
const observedRoot = pageDocument.documentElement || pageDocument;
if (!hasEntries) {
for (const observer of state.observers.values()) observer?.disconnect?.();
state.observers.clear();
delete pageGlobal[stateKey];
return;
}
const Observer = pageGlobal.MutationObserver;
const observeRoot = (root) => {
if (typeof Observer !== "function" || !root?.nodeType || state.observers.has(root)) return;
const observer = new Observer(() => scheduleScan());
observer.observe(root, { childList: true, subtree: true });
state.observers.set(root, observer);
};
if (state.documentRoot !== observedRoot) {
for (const observer of state.observers.values()) observer?.disconnect?.();
state.observers.clear();
state.documentRoot = observedRoot;
}
observeRoot(observedRoot);
const applyToRoot = (shadowRoot, entry) => {
if (!shadowRoot?.appendChild) return;
const previous = entry.nodes.get(shadowRoot);
if (previous) {
if (previous.textContent !== entry.css) previous.textContent = entry.css;
return;
}
const styleNode = pageDocument.createElement("style");
styleNode.setAttribute("data-scriptvault-userstyle", "");
styleNode.textContent = entry.css;
try {
shadowRoot.appendChild(styleNode);
entry.nodes.set(shadowRoot, styleNode);
} catch {
}
};
const pruneDetachedRoots = () => {
for (const entry of state.entries.values()) {
for (const [shadowRoot, node] of entry.nodes) {
if (shadowRoot?.host?.isConnected) continue;
try {
node.remove();
} catch {
}
entry.nodes.delete(shadowRoot);
state.observers.get(shadowRoot)?.disconnect?.();
state.observers.delete(shadowRoot);
}
}
};
function scheduleScan() {
if (state.scanning) {
state.scanAgain = true;
return;
}
state.scanning = true;
state.scanAgain = false;
pruneDetachedRoots();
const roots = [pageDocument];
const seenRoots = /* @__PURE__ */ new Set();
let rootIndex = 0;
let hosts = [];
let hostIndex = 0;
const runChunk = () => {
let budget = 200;
while (budget-- > 0) {
if (hostIndex < hosts.length) {
const host = hosts[hostIndex++];
const shadowRoot = host?.shadowRoot;
if (!shadowRoot || seenRoots.has(shadowRoot)) continue;
seenRoots.add(shadowRoot);
roots.push(shadowRoot);
observeRoot(shadowRoot);
for (const entry of state.entries.values()) applyToRoot(shadowRoot, entry);
continue;
}
if (rootIndex >= roots.length) {
state.scanning = false;
if (state.scanAgain) {
state.scanAgain = false;
scheduleScan();
}
return;
}
const root = roots[rootIndex++];
try {
hosts = Array.from(root.querySelectorAll?.("*") ?? []);
} catch {
hosts = [];
}
hostIndex = 0;
}
const idle = pageGlobal.requestIdleCallback;
if (typeof idle === "function") idle(runChunk, { timeout: 100 });
else pageGlobal.setTimeout(runChunk, 0);
};
runChunk();
}
scheduleScan();
}
async function _syncShadowStylesToTab(tabId, url, extraStyles = [], documentId) {
const executeScript = chrome.scripting?.executeScript;
if (typeof executeScript !== "function") return;
let targetUrl = url;
if (!targetUrl) {
try {
targetUrl = (await chrome.tabs.get(tabId))?.url;
} catch {
targetUrl = void 0;
}
}
const desired = [];
if (targetUrl) {
for (const [styleId, style] of Object.entries(_styles)) {
if (!style.enabled || !_urlMatchesPatterns(targetUrl, style.match)) continue;
const css = _buildCSS(styleId);
if (css) desired.push({ id: styleId, css });
}
}
const draftCss = _draftPreviewTabs.get(tabId);
if (draftCss) desired.push({ id: "__draft__", css: draftCss });
desired.push(...extraStyles.filter((style) => style?.id && style.css));
try {
await executeScript({
target: _injectionTarget(tabId, documentId),
func: _syncShadowStylesInDocument,
args: [desired]
});
} catch {
}
}
function _buildCSS(styleId) {
const style = _styles[styleId];
if (!style) return "";
const vars = style.variables ?? [];
const custom = _customVars[styleId] ?? {};
return _substituteVariables(style.css, vars, custom);
}
function _persistentMatchPatterns(style) {
const patterns = Array.isArray(style.match) && style.match.length > 0 ? style.match : ["*://*/*"];
return patterns.map((pattern) => String(pattern || "").trim()).filter((pattern) => {
if (pattern === "<all_urls>") return true;
try {
_matchPatternToRegex(pattern);
return true;
} catch {
return false;
}
});
}
async function _syncPersistentRegistrationsNow() {
const scripting = chrome.scripting;
if (typeof scripting?.registerContentScripts !== "function" || typeof scripting?.unregisterContentScripts !== "function" || typeof scripting?.getRegisteredContentScripts !== "function") {
_persistentRegistrationSupported = false;
return false;
}
try {
const registered = await scripting.getRegisteredContentScripts();
const staleIds = (Array.isArray(registered) ? registered : []).map((entry) => entry?.id).filter((id) => typeof id === "string" && id.startsWith(PERSISTENT_REGISTRATION_PREFIX));
if (staleIds.length > 0) await scripting.unregisterContentScripts({ ids: staleIds });
let hasEnabledStyles = false;
for (const [styleId, style] of Object.entries(_styles)) {
if (!style.enabled) continue;
const css = _buildCSS(styleId);
const matches = _persistentMatchPatterns(style);
if (!css || matches.length === 0) continue;
hasEnabledStyles = true;
}
_persistentRegistrationSupported = !hasEnabledStyles;
return _persistentRegistrationSupported;
} catch (error) {
_persistentRegistrationSupported = false;
console.warn("[UserStylesEngine] Persistent document_start registration unavailable:", error instanceof Error ? error.message : String(error));
return false;
}
}
function _syncPersistentRegistrations() {
const queued = _persistentRegistrationChain.then(_syncPersistentRegistrationsNow, _syncPersistentRegistrationsNow);
_persistentRegistrationChain = queued.catch(() => false);
return queued;
}
function _buildDraftPreviewCSS(usercssCode, options = {}) {
const parsed = parseUserCSS(usercssCode);
if (parsed.error) return { error: parsed.error };
const variables = parsed.variables ?? [];
const defaults = {};
for (const variable of variables) {
defaults[variable.name] = variable.colorSchemes ?? variable.default;
}
const providedValues = options.values ?? {};
const validation = validateUserCSSVariables(variables, providedValues);
if (!validation.valid) return { error: validation.errors.join(" ") };
const values = { ...defaults, ..._expandLinkedGroupValues(variables, providedValues) };
const css = _substituteVariables(
parsed.css ?? "",
variables,
values,
options.colorScheme ?? "auto"
).trim();
if (!css) return { error: "UserCSS draft has no CSS to preview." };
return {
css,
match: parsed.match ?? ["*://*/*"],
styleName: parsed.meta?.name || "UserCSS draft"
};
}
async function _getPreviewTab(tabId) {
if (typeof tabId === "number") {
try {
return await chrome.tabs.get(tabId);
} catch {
return null;
}
}
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
return activeTab ?? null;
}
async function _removeDraftPreviewFromTab(tabId) {
const previousCss = _draftPreviewTabs.get(tabId);
if (!previousCss) return false;
try {
await chrome.scripting.removeCSS({
target: _injectionTarget(tabId),
css: previousCss
});
} catch {
}
_draftPreviewTabs.delete(tabId);
await _syncShadowStylesToTab(tabId);
return true;
}
function _enqueueDraftPreviewTask(task) {
const queued = _draftPreviewChain.then(task, task);
_draftPreviewChain = queued.catch(() => void 0);
return queued;
}
function clearDraftPreview(options = {}) {
return _enqueueDraftPreviewTask(() => _clearDraftPreviewNow(options));
}
async function _clearDraftPreviewNow(options = {}) {
if (typeof options.tabId === "number") {
const cleared2 = await _removeDraftPreviewFromTab(options.tabId);
return { success: true, cleared: cleared2 ? 1 : 0 };
}
let cleared = 0;
for (const tabId of Array.from(_draftPreviewTabs.keys())) {
if (await _removeDraftPreviewFromTab(tabId)) cleared++;
}
return { success: true, cleared };
}
function previewDraft(usercssCode, options = {}) {
return _enqueueDraftPreviewTask(() => _previewDraftNow(usercssCode, options));
}
async function _previewDraftNow(usercssCode, options = {}) {
const built = _buildDraftPreviewCSS(usercssCode, options);
if (built.error || !built.css || !built.match) return { error: built.error || "Unable to preview UserCSS draft." };
const tab = await _getPreviewTab(options.tabId);
if (tab?.id == null) return { error: "No active tab is available for preview." };
if (!_urlMatchesPatterns(tab.url, built.match)) {
return { error: "The UserCSS @match rules do not include the preview tab." };
}
await _removeDraftPreviewFromTab(tab.id);
try {
await chrome.scripting.insertCSS({
target: _injectionTarget(tab.id),
css: built.css
});
_draftPreviewTabs.set(tab.id, built.css);
await _syncShadowStylesToTab(tab.id, tab.url, [{ id: "__draft__", css: built.css }]);
return {
success: true,
tabId: tab.id,
tabUrl: tab.url || "",
styleName: built.styleName,
cssBytes: built.css.length
};
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
_draftPreviewTabs.delete(tab.id);
return { error: message || "Failed to inject UserCSS preview." };
}
}
async function registerStyle(style) {
if (!_initialized) await _loadState();
const variableValidation = validateUserCSSVariables(style.variables ?? []);
if (!variableValidation.valid) throw new Error(variableValidation.errors.join(" "));
const id = style.id ?? `usercss_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
const entry = {
id,
type: "usercss",
meta: style.meta ?? {},
variables: style.variables ?? [],
css: style.css ?? "",
rawCode: style.rawCode ?? "",
enabled: style.enabled !== false,
match: style.match ?? ["*://*/*"],
installDate: style.installDate ?? Date.now(),
updateDate: Date.now()
};
_styles[id] = entry;
await _saveStyles();
await _syncPersistentRegistrations();
if (entry.enabled) {
await _injectStyleToMatchingTabs(id);
}
return id;
}
async function unregisterStyle(styleId) {
if (!_initialized) await _loadState();
await _removeStyleFromAllTabs(styleId);
delete _styles[styleId];
delete _customVars[styleId];
await Promise.all([_saveStyles(), _saveVars()]);
await _syncPersistentRegistrations();
try {
const tabs = await chrome.tabs.query({});
for (const tab of tabs) {
if (tab.id != null) await _syncShadowStylesToTab(tab.id, tab.url);
}
} catch {
}
}
async function toggleStyle(styleId, enabled) {
if (!_initialized) await _loadState();
const style = _styles[styleId];
if (!style) return;
style.enabled = enabled;
await _saveStyles();
await _syncPersistentRegistrations();
if (enabled) {
await _injectStyleToMatchingTabs(styleId);
} else {
await _removeStyleFromAllTabs(styleId);
}
}
async function _injectStyleToMatchingTabs(styleId) {
const style = _styles[styleId];
if (!style?.enabled) return;
const css = _buildCSS(styleId);
if (!css) return;
try {
const tabs = await chrome.tabs.query({});
for (const tab of tabs) {
if (tab.id == null) continue;
if (_urlMatchesPatterns(tab.url, style.match)) {
const documentId = _documentIdForTab(tab.id);
const registryKey = _registryKeyForTab(tab.id, documentId);
const tabStyles = _registeredTabs.get(registryKey) ?? /* @__PURE__ */ new Map();
const previousCss = tabStyles.get(styleId);
if (previousCss !== css) {
try {
if (previousCss) {
try {
await chrome.scripting.removeCSS({
target: _injectionTarget(tab.id, documentId),
css: previousCss
});
} catch {
}
}
await chrome.scripting.insertCSS({
target: _injectionTarget(tab.id, documentId),
css
});
tabStyles.set(styleId, css);
_registeredTabs.set(registryKey, tabStyles);
} catch {
}
}
await _syncShadowStylesToTab(tab.id, tab.url, [], documentId);
}
}
} catch (e) {
console.error("[UserStylesEngine] Inject failed:", e);
}
}
async function _removeStyleFromAllTabs(styleId) {
const reconstructedCss = _buildCSS(styleId);
try {
const tabs = await chrome.tabs.query({});
for (const tab of tabs) {
if (tab.id == null) continue;
const documentId = _documentIdForTab(tab.id);
const registryKey = _registryKeyForTab(tab.id, documentId);
const tabStyles = _registeredTabs.get(registryKey);
const registeredCss = tabStyles?.get(styleId);
const cssToRemove = registeredCss ?? (reconstructedCss || void 0);
if (cssToRemove) {
try {
await chrome.scripting.removeCSS({
target: _injectionTarget(tab.id, documentId),
css: cssToRemove
});
} catch {
}
}
if (tabStyles) {
tabStyles.delete(styleId);
if (tabStyles.size === 0) {
_registeredTabs.delete(registryKey);
}
}
await _syncShadowStylesToTab(tab.id, tab.url, [], documentId);
}
} catch (e) {
console.error("[UserStylesEngine] Remove failed:", e);
}
}