forked from DustinBrett/daedalOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglobals.ts
More file actions
84 lines (73 loc) · 2.13 KB
/
globals.ts
File metadata and controls
84 lines (73 loc) · 2.13 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
const DEFAULT_KEY = "DEFAULT";
const SET_KEY = "__setter__";
type SharedGlobal = {
[key: string]: unknown;
[DEFAULT_KEY]: unknown;
[SET_KEY]: string;
};
declare global {
interface Window {
Module: {
SDL2?: {
audioContext: AudioContext;
};
arguments?: string[];
canvas: HTMLCanvasElement;
postRun: () => void;
windowElement?: HTMLElement;
};
sharedGlobals?: Record<string, SharedGlobal>;
}
}
export const cleanUpGlobals = (globals: string[]): void =>
globals.forEach((globalKey) => {
const resetKey = (): void => {
Object.assign(window, { [globalKey]: undefined });
};
if (globalKey in window) {
try {
delete (window as never)[globalKey];
} finally {
resetKey();
}
}
});
export const shareGlobal = (
key: string,
callees: string,
assignTimeout: number
): void => {
setTimeout(() => {
if (window.sharedGlobals && key in window.sharedGlobals) {
window.sharedGlobals[key][SET_KEY] = DEFAULT_KEY;
}
}, assignTimeout);
window.sharedGlobals = window.sharedGlobals || {};
if (key in window.sharedGlobals) {
window.sharedGlobals[key][SET_KEY] = callees;
} else {
const defaultValue = window[key as keyof Window] as unknown;
window.sharedGlobals[key] = {
[DEFAULT_KEY]: defaultValue,
[SET_KEY]: callees,
};
Object.defineProperty(window, key, {
get() {
if (window.sharedGlobals && key in window.sharedGlobals) {
// eslint-disable-next-line unicorn/error-message
const { stack = "" } = new Error();
const match = Object.keys(window.sharedGlobals[key])
.filter((calleeKey) => ![DEFAULT_KEY, SET_KEY].includes(calleeKey))
.find((calleeKey) => new RegExp(calleeKey).test(stack));
return window.sharedGlobals[key][match || DEFAULT_KEY];
}
return defaultValue;
},
set(value: unknown) {
if (window.sharedGlobals && key in window.sharedGlobals) {
window.sharedGlobals[key][window.sharedGlobals[key][SET_KEY]] = value;
}
},
} as PropertyDescriptor);
}
};