-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathACEngineManager.ts
More file actions
378 lines (355 loc) · 15.6 KB
/
ACEngineManager.ts
File metadata and controls
378 lines (355 loc) · 15.6 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
import * as path from "path";
import * as fs from "fs";
import { ACConfigManager } from "./common/config/ACConfigManager.js";
import { fetch_get_text } from "./common/api-ext/Fetch.js";
import { IChecker } from "./common/engine/IChecker.js";
let ace;
let checker: IChecker;
export class ACEngineManager {
static customRulesets = []
static engineContent = null;
static async loadEngine(content) {
let config = await ACConfigManager.getConfigUnsupported();
let ENGINE_LOAD_MODE = config.engineMode;
if (ENGINE_LOAD_MODE === "DEFAULT") {
// ENGINE_LOAD_MODE = "REMOTE";
ENGINE_LOAD_MODE = "INJECT";
}
if (ENGINE_LOAD_MODE === "INJECT" && !ACEngineManager.engineContent) {
ACEngineManager.engineContent = await fetch_get_text(`${config.rulePack}/ace.js`);
}
if (ACEngineManager.isPuppeteer(content) || ACEngineManager.isPlaywright(content)) {
config.DEBUG && console.log("[INFO] aChecker.loadEngine detected Puppeteer/Playwright");
let page = content;
if (ENGINE_LOAD_MODE === "REMOTE") {
config.DEBUG && console.log("[INFO] engineMode REMOTE");
await page.evaluate((scriptUrl) => {
try {
var ace_backup_in_ibma;
if ('undefined' !== typeof(ace)) {
if (!ace || !ace.Checker)
ace_backup_in_ibma = ace;
ace = null;
}
if ('undefined' === typeof (ace) || ace === null) {
return new Promise<void>((resolve, reject) => {
let script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('aChecker', 'ACE');
script.setAttribute('src', scriptUrl);
script.addEventListener('load', function () {
globalThis.ace_ibma = ace;
if ('undefined' !== typeof(ace)) {
ace = ace_backup_in_ibma;
}
resolve();
});
script.addEventListener('error', function (evt) {
reject(new Error(`Unable to load engine into ${document.location.href}. This can happen if the page server sets a Content-Security-Policy that prevents ${scriptUrl} from loading.`))
});
let heads = document.getElementsByTagName('head');
if (heads.length > 0) { heads[0].appendChild(script); }
else if (document.body) { document.body.appendChild(script); }
else { Promise.reject("Invalid document"); }
})
}
} catch (e) {
return Promise.reject(e);
}
}, `${config.rulePack}/ace.js`);
} else if (ENGINE_LOAD_MODE === "INJECT") {
config.DEBUG && console.log("[INFO] engineMode INJECT");
let aceAlreadyExists = await page.evaluate(() => { try { return 'undefined' !== typeof(ace) } catch (e) { return false; } });
await page.evaluate(({ engineContent, aceAlreadyExists }) => {
try {
var ace_backup_in_ibma;
if (aceAlreadyExists) {
if (!ace || !ace.Checker)
ace_backup_in_ibma = ace;
ace = null;
}
if (!aceAlreadyExists || ace === null) {
return new Promise<void>((resolve, reject) => {
eval(engineContent);
globalThis.ace_ibma = ace;
if (aceAlreadyExists) {
ace = ace_backup_in_ibma;
}
resolve();
})
}
} catch (e) {
return Promise.reject(e);
}
}, {
engineContent: ACEngineManager.engineContent, aceAlreadyExists });
}
return ACEngineManager.loadEngineLocal();
} else if (ACEngineManager.isSelenium(content)) {
config.DEBUG && console.log("[INFO] aChecker.loadEngine detected Selenium");
try {
let browser = content;
let scriptStr;
if (ENGINE_LOAD_MODE === "REMOTE") {
scriptStr =
`let cb = arguments[arguments.length - 1];
try {
var ace_backup_in_ibma;
if ('undefined' !== typeof(ace)) {
if (!ace || !ace.Checker)
ace_backup_in_ibma = ace;
ace = null;
}
if ('undefined' === typeof (ace) || ace === null) {
let script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('aChecker', 'ACE');
script.setAttribute('src', '${config.rulePack}/ace.js');
script.addEventListener('load', function() {
globalThis.ace_ibma = ace;
if ('undefined' !== typeof(ace)) {
ace = ace_backup_in_ibma;
}
cb();
});
let heads = document.getElementsByTagName('head');
if (heads.length > 0) { heads[0].appendChild(script); }
else { document.body.appendChild(script); }
} else {
cb();
}
} catch (e) {
cb(e);
}
`
} else if (ENGINE_LOAD_MODE === "INJECT") {
// Selenium
scriptStr =
`let cb = arguments[arguments.length - 1];
try {
var ace_backup_in_ibma;
if ('undefined' !== typeof(ace)) {
if (!ace || !ace.Checker)
ace_backup_in_ibma = ace;
ace = null;
}
if ('undefined' === typeof (ace) || ace === null) {
eval(${JSON.stringify(ACEngineManager.engineContent)})
globalThis.ace_ibma = ace;
if ('undefined' !== typeof(ace)) {
ace = ace_backup_in_ibma;
}
cb();
} else {
cb();
}
} catch (e) {
cb(e);
}
`
}
let manage = browser.manage();
if (manage.timeouts) {
manage.timeouts().setScriptTimeout(60000);
} else if (manage.setTimeouts) {
manage.setTimeouts({
"script": 60000
})
}
return browser.executeAsyncScript(scriptStr).then(function (return_success) {
return ACEngineManager.loadEngineLocal();
}).catch(function (err) {
console.log(err);
});
} catch (e) {
console.log(e);
}
} else if (ACEngineManager.isWebDriverIO(content)) {
config.DEBUG && console.log("[INFO] aChecker.loadEngine detected WebDriverIO");
let page = content;
// ENGINE_LOAD_MODE = "REMOTE";
if (ENGINE_LOAD_MODE === "REMOTE") {
await page.executeAsync((scriptUrl, done) => {
try {
var ace_backup_in_ibma;
if ('undefined' !== typeof(ace)) {
if (!ace || !ace.Checker)
ace_backup_in_ibma = ace;
ace = null;
}
if ('undefined' === typeof (ace) || ace === null) {
new Promise<void>((resolve, reject) => {
let script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('aChecker', 'ACE');
script.setAttribute('src', scriptUrl);
script.addEventListener('load', function () {
globalThis.ace_ibma = ace;
if ('undefined' !== typeof(ace)) {
ace = ace_backup_in_ibma;
}
resolve();
});
script.addEventListener('error', function (evt) {
reject(new Error(`Unable to load engine into ${document.location.href}. This can happen if the page server sets a Content-Security-Policy that prevents ${scriptUrl} from loading.`))
});
let heads = document.getElementsByTagName('head');
if (heads.length > 0) { heads[0].appendChild(script); }
else if (document.body) { document.body.appendChild(script); }
else { Promise.reject("Invalid document"); }
}).then(done)
}
} catch (e) {
return Promise.reject(e);
}
}, `${config.rulePack}/ace.js`);
} else if (ENGINE_LOAD_MODE === "INJECT") {
await page.executeAsync((engineContent, done) => {
try {
var ace_backup_in_ibma;
if ('undefined' !== typeof(ace)) {
if (!ace || !ace.Checker)
ace_backup_in_ibma = ace;
ace = null;
}
if ('undefined' === typeof (ace) || ace === null) {
return new Promise<void>((resolve, reject) => {
eval(engineContent);
globalThis.ace_ibma = ace;
if ('undefined' !== typeof(ace)) {
ace = ace_backup_in_ibma;
}
resolve();
}).then(done);
}
} catch (e) {
return Promise.reject(e);
}
}, ACEngineManager.engineContent);
}
return ACEngineManager.loadEngineLocal();
} else {
config.DEBUG && console.log("[INFO] aChecker.loadEngine detected local");
if (globalThis.ace_ibma) {
return Promise.resolve();
} else {
return ACEngineManager.loadEngineLocal();
}
}
}
static localLoadPromise = null;
static async loadEngineLocal() {
if (globalThis.ace_ibma) {
return Promise.resolve();
}
if (!ACEngineManager.localLoadPromise) {
ACEngineManager.localLoadPromise = new Promise<void>(async (resolve, reject) => {
let config = await ACConfigManager.getConfigUnsupported();
const data = await fetch_get_text(`${config.rulePack}/ace-node.js`);
let engineDir = path.join(path.resolve(config.cacheFolder), "engine");
if (!fs.existsSync(engineDir)) {
fs.mkdirSync(engineDir, { recursive: true });
}
let fileSuffix = "";
if (!config.toolVersion) {
fileSuffix = config.ruleArchiveVersion;
} else {
fileSuffix = `${config.toolVersion}-${config.ruleArchiveVersion}`
}
fileSuffix = fileSuffix.replace(/\./g, "_");
const nodePath = path.join(engineDir, `ace-node-${fileSuffix}`);
if (fs.existsSync(`${nodePath}.js`)) {
const ace_ibma = require(nodePath);
checker = new ace_ibma.Checker();
return resolve();
} else {
fs.writeFile(nodePath + ".js", data, function (err) {
if (err) {
console.log(err);
reject(err);
} else {
try {
const ace_ibma = require(nodePath);
checker = new ace_ibma.Checker();
resolve();
} catch (e) {
console.log(e);
reject(e);
}
}
});
}
});
}
return ACEngineManager.localLoadPromise;
}
static isPuppeteer(content) {
if (content && content.constructor) {
return !!content.constructor.toString().match(/Function: Page/)
|| content.constructor.toString().includes("Puppeteer");
}
return false;
}
static isPlaywright(content) {
if (content && content.constructor) {
return !!content.constructor.toString().match(/class Page /);
}
return false;
}
static isSelenium(content) {
if (content && content.constructor) {
return content.constructor.toString().indexOf("Driver") !== -1 ||
// check required for selenium >= 3.0.1
(content.constructor.name && content.constructor.name.indexOf("Driver") !== -1);
}
return false;
}
static isWebDriverIO(content) {
if (content && content.constructor) {
return content.constructor.toString().indexOf("Browser") !== -1;
}
return false;
}
static addRuleset = (ruleset) => {
ACEngineManager.customRulesets.push(ruleset);
}
static getRuleset = async (rsId) => {
if (!checker) {
await ACEngineManager.loadEngineLocal();
}
return ACEngineManager.customRulesets.concat(checker.getGuidelines()).filter((function (rs) { return rs.id === rsId }))[0];
};
static getRulesets = async function () {
if (!checker) {
await ACEngineManager.loadEngineLocal();
}
return ACEngineManager.customRulesets.concat(checker.getGuidelines());
};
static getChecker() {
return checker;
}
static async loadChecker() {
if (!checker) {
await ACEngineManager.loadEngineLocal();
}
return checker;
}
static getRules = async function() {
if (!checker) {
await ACEngineManager.loadEngineLocal();
}
let retVal = [];
for (const ruleId in (checker as any).engine.ruleMap) {
retVal.push((checker as any).engine.ruleMap[ruleId]);
}
return retVal;
}
static getRulesSync = function() {
if (!checker) return null;
let retVal = [];
for (const ruleId in (checker as any).engine.ruleMap) {
retVal.push((checker as any).engine.ruleMap[ruleId]);
}
return retVal;
}
}