-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjest.setup.ts
175 lines (149 loc) · 4.88 KB
/
jest.setup.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
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
import got from 'got';
import vm from 'vm';
import {JSDOM} from 'jsdom';
import fetch from 'cross-fetch';
import * as path from 'path';
Object.assign(process.env, require('dotenv').config());
if (!process.env.APIKEY) {
throw new Error('Define APIKEY env');
}
const REFERRER = process.env.REFERRER || 'http://mappable.localhost/';
const API_HOST = process.env.APIHOST || 'https://js.api.mappable.world/3.0/';
const API_URL = `${API_HOST}?apikey=${process.env.APIKEY}&lang=en_US`;
const NS = process.env.NAMESPACE || 'mappable';
const computeClientDimension = (element: HTMLElement, dimension: 'width' | 'height') => {
const path = [];
do {
const style = getComputedStyle(element);
const styleStr = `width: ${style.width}; height: ${style.height}`;
path.push(`<${element.tagName.toLowerCase()} class="${element.className}" style="${styleStr}">`);
if (!style[dimension]) break;
if (style[dimension] === '100%') {
element = element.parentElement;
continue;
}
if (style[dimension].endsWith('px')) {
return parseFloat(style[dimension]);
}
break;
// eslint-disable-next-line no-constant-condition
} while (true);
const pathFormatted = path
.reverse()
.map((x, i) => ' '.repeat(i) + x)
.join('\n');
throw new Error(`Cannot compute ${dimension}:\n${pathFormatted}`);
};
module.exports = async function () {
const dom = await JSDOM.fromFile(path.resolve(__dirname, 'index.html'), {
url: REFERRER
});
const appendChild = dom.window.document.head.appendChild.bind(dom.window.document.head);
dom.window.document.head.appendChild = <T extends Node>(script: T): T => {
if (isScript(script)) {
loadAndExecuteScript(script.src)
.then(() => script.dispatchEvent(new dom.window.Event('load')))
.catch((e) => console.log('Error', e));
}
return appendChild(script);
};
const context: any = {
...dom.window,
Node: dom.window.Node,
DOMException: class extends Error {
constructor(message: string, name: string) {
super(message);
this.name = name;
}
},
MouseEvent: dom.window.MouseEvent,
Image: dom.window.Image,
HTMLElement: dom.window.HTMLElement,
Element: dom.window.Element,
XMLHttpRequest: dom.window.XMLHttpRequest,
window: dom.window,
global: dom.window,
self: new Proxy(
{},
{
get(_, p) {
return Reflect.get(context, p);
},
set(_, p, newValue) {
Reflect.set(context, p, newValue);
return true;
}
}
),
domToJson,
console,
AbortController,
clearTimeout,
setTimeout,
performance,
URL,
URLSearchParams,
queueMicrotask: (cb: Function) => cb(),
requestAnimationFrame: (cb: Function) => cb(),
fetch: (url: string, query: object) =>
fetch(url, {
...query,
// agent: agent,
headers: {
referer: REFERRER
}
}),
ResizeObserver: function () {
return {
disconnect() {},
observe() {}
};
}
};
Object.defineProperties(dom.window.Element.prototype, {
clientWidth: {
get() {
return computeClientDimension(this, 'width');
}
},
clientHeight: {
get() {
return computeClientDimension(this, 'height');
}
}
});
async function loadAndExecuteScript(url: string) {
const data = await got(url, {
headers: {
Referer: REFERRER
}
});
await vm.runInNewContext(data.body, context);
}
await loadAndExecuteScript(API_URL);
await context[NS].ready;
Object.assign(global, context);
};
function isScript(node: Node): node is HTMLScriptElement {
return node.nodeName === 'SCRIPT';
}
function isElement(node: Node): node is Element {
return node.nodeType === Node.ELEMENT_NODE;
}
function domToJson(e: Node | ChildNode | null): TreeNode {
const result: TreeNode = {
nodeName: e.nodeName.toLowerCase(),
attributes: isElement(e)
? Array.from(e.attributes).reduce((acc, {name, value}) => {
acc[name] = value;
return acc;
}, {} as TreeNode['attributes'])
: {}
};
if (e.childNodes.length) {
result.children = Array.from(e.childNodes, (e) =>
e.nodeType === Node.TEXT_NODE ? e.textContent : domToJson(e)
);
}
return result;
}