/
index.ts
84 lines (80 loc) · 2.05 KB
/
index.ts
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
import { URL, URLSearchParams } from 'url';
import * as FileReader from 'filereader';
import * as WebCrypto from 'node-webcrypto-ossl';
import * as btoa from 'btoa';
import * as atob from 'atob';
import { performance } from 'perf_hooks';
import Blob from './blob';
import navigator from './navigator';
import XMLHttpRequestFactory from './xmlhttprequest';
import Worker from './worker';
import createTimers from './timers';
import createDate from './fakeDate';
import createFetch from './fetch';
export interface WindowConfig {
quiet?: boolean
fetchBaseDirectory?: string
timeMultiplier?: number
initialTime?: number
probe?: (key: string, value: any) => void
}
function createConsole(quiet: boolean) {
if (!quiet) {
return console;
} else {
const noop = () => {}
return {
log: noop,
warn: noop,
error: noop,
info: noop,
debug: noop,
trace: noop,
}
}
}
export default (config: WindowConfig) => ({
// types
Object,
URL,
URLSearchParams,
Blob,
FileReader,
Int8Array,
Uint8Array,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
ArrayBuffer,
DataView,
Math,
btoa,
atob,
// web apis
crypto: new WebCrypto(),
...createFetch(config.fetchBaseDirectory, config.probe),
Date: createDate(config.initialTime || Date.now(), config.timeMultiplier),
Worker,
XMLHttpRequest: XMLHttpRequestFactory(config.fetchBaseDirectory, config.probe),
// globals
console: createConsole(config.quiet),
navigator,
performance,
// timers
...createTimers(config.timeMultiplier),
// utility
_unloadHandlers: [],
addEventListener(on: string, fn) {
if (on === 'beforeunload') {
this._unloadHandlers.push(fn)
}
},
unload() {
this._unloadHandlers.forEach((fn) => fn());
config.probe && config.probe('timers.timeout.leaked', Math.floor(this._timeouts.size / 2));
config.probe && config.probe('timers.interval.leaked', this._intervals.size);
[...this._timeouts].forEach(t => this.clearTimeout(t));
[...this._intervals].forEach(t => this.clearInterval(t));
},
});