forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnetwork.ts
More file actions
192 lines (168 loc) · 6.11 KB
/
Copy pathnetwork.ts
File metadata and controls
192 lines (168 loc) · 6.11 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
import {loadAsDataURL, loadAsText} from '../../utils/network';
import {getStringSize} from '../../utils/text';
import {getDuration} from '../../utils/time';
import {isXMLHttpRequestSupported, isFetchSupported} from '../../utils/platform';
declare const __TEST__: boolean;
interface RequestParams {
url: string;
timeout?: number;
}
interface FileLoader {
get: (fetchRequestParameters: FetchRequestParameters) => Promise<string | null>;
}
export async function readText(params: RequestParams): Promise<string> {
return new Promise((resolve, reject) => {
if (isXMLHttpRequestSupported) {
// Use XMLHttpRequest if it is available
const request = new XMLHttpRequest();
request.overrideMimeType('text/plain');
request.open('GET', params.url, true);
request.onload = () => {
if (request.status >= 200 && request.status < 300) {
resolve(request.responseText);
} else {
reject(new Error(`${request.status}: ${request.statusText}`));
}
};
request.onerror = () => reject(new Error(`${request.status}: ${request.statusText}`));
if (params.timeout) {
request.timeout = params.timeout;
request.ontimeout = () => reject(new Error('File loading stopped due to timeout'));
}
request.send();
} else if (isFetchSupported) {
// XMLHttpRequest is not available in Service Worker contexts like
// Manifest V3 background context
let abortController: AbortController;
let signal: AbortSignal | undefined;
let timedOut = false;
if (params.timeout) {
abortController = new AbortController();
signal = abortController.signal;
setTimeout(() => {
abortController.abort();
timedOut = true;
}, params.timeout);
}
fetch(params.url, {signal})
.then((response) => {
if (response.status >= 200 && (response.status < 300)) {
resolve(response.text());
} else {
reject(new Error(`${response.status}: ${response.statusText}`));
}
}).catch((error) => {
if (timedOut) {
reject(new Error('File loading stopped due to timeout'));
} else {
reject(error);
}
});
} else {
reject(new Error(`Neither XMLHttpRequest nor Fetch API are accessible!`));
}
});
}
interface CacheRecord {
expires: number;
size: number;
url: string;
value: string;
}
class LimitedCacheStorage {
// TODO: remove type cast after dependency update
private static readonly QUOTA_BYTES = ((!__TEST__ && (navigator as any).deviceMemory) || 4) * 16 * 1024 * 1024;
private static readonly TTL = getDuration({minutes: 10});
private static readonly ALARM_NAME = 'network';
private bytesInUse = 0;
private records = new Map<string, CacheRecord>();
private static alarmIsActive = false;
constructor() {
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === LimitedCacheStorage.ALARM_NAME) {
// We schedule only one-time alarms, so once it goes off,
// there are no more alarms scheduled.
LimitedCacheStorage.alarmIsActive = false;
this.removeExpiredRecords();
}
});
}
private static ensureAlarmIsScheduled(){
if (!this.alarmIsActive) {
chrome.alarms.create(LimitedCacheStorage.ALARM_NAME, {delayInMinutes: 1});
this.alarmIsActive = true;
}
}
has(url: string) {
return this.records.has(url);
}
get(url: string) {
if (this.records.has(url)) {
const record = this.records.get(url)!;
record.expires = Date.now() + LimitedCacheStorage.TTL;
this.records.delete(url);
this.records.set(url, record);
return record.value;
}
return null;
}
set(url: string, value: string) {
LimitedCacheStorage.ensureAlarmIsScheduled();
const size = getStringSize(value);
if (size > LimitedCacheStorage.QUOTA_BYTES) {
return;
}
for (const [url, record] of this.records) {
if (this.bytesInUse + size > LimitedCacheStorage.QUOTA_BYTES) {
this.records.delete(url);
this.bytesInUse -= record.size;
} else {
break;
}
}
const expires = Date.now() + LimitedCacheStorage.TTL;
this.records.set(url, {url, value, size, expires});
this.bytesInUse += size;
}
private removeExpiredRecords() {
const now = Date.now();
for (const [url, record] of this.records) {
if (record.expires < now) {
this.records.delete(url);
this.bytesInUse -= record.size;
} else {
break;
}
}
if (this.records.size !== 0) {
LimitedCacheStorage.ensureAlarmIsScheduled();
}
}
}
export interface FetchRequestParameters {
url: string;
responseType: 'data-url' | 'text';
mimeType?: string;
origin?: string;
}
export function createFileLoader(): FileLoader {
const caches = {
'data-url': new LimitedCacheStorage(),
'text': new LimitedCacheStorage(),
};
const loaders = {
'data-url': loadAsDataURL,
'text': loadAsText,
};
async function get({url, responseType, mimeType, origin}: FetchRequestParameters) {
const cache = caches[responseType];
const load = loaders[responseType];
if (cache.has(url)) {
return cache.get(url);
}
const data = await load(url, mimeType, origin);
cache.set(url, data);
return data;
}
return {get};
}