Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/plugins/default-browser-emulator/lib/DataLoader.ts
1029 views
1
import * as Fs from 'fs';
2
import IUserAgentOption from '@secret-agent/interfaces/IUserAgentOption';
3
import {
4
IDataBrowserEngineOptions,
5
IDataCore,
6
IDataUserAgentOptions,
7
} from '../interfaces/IBrowserData';
8
import BrowserData from './BrowserData';
9
10
export default class DataLoader implements IDataCore {
11
public readonly baseDir: string;
12
public readonly dataDir: string;
13
14
private readonly browserOsEmulatorsByVersion: {
15
[versionString: string]: { [os: string]: string[] };
16
} = {};
17
18
private readonly osDataDirs = new Set<string>();
19
20
constructor(baseDir: string) {
21
this.baseDir = baseDir;
22
this.dataDir = `${baseDir}/data`;
23
const browsers = Fs.readdirSync(this.dataDir);
24
for (const browser of browsers) {
25
if (browser.startsWith('as-') && Fs.statSync(`${this.dataDir}/${browser}`).isDirectory()) {
26
this.browserOsEmulatorsByVersion[browser] = {};
27
for (const osDir of Fs.readdirSync(`${this.dataDir}/${browser}`)) {
28
if (
29
osDir.startsWith('as-') &&
30
Fs.statSync(`${this.dataDir}/${browser}/${osDir}`).isDirectory()
31
) {
32
const isMac = osDir.startsWith('as-mac');
33
const version = osDir.replace('as-mac-os-', '').replace('as-windows-', '');
34
const name = isMac ? 'mac-os' : 'windows';
35
this.browserOsEmulatorsByVersion[browser][name] ??= [];
36
this.browserOsEmulatorsByVersion[browser][name].push(version);
37
this.osDataDirs.add(`${this.dataDir}/${browser}/${osDir}`);
38
}
39
}
40
}
41
}
42
}
43
44
public isSupportedEmulator(osDir: string): boolean {
45
return this.osDataDirs.has(osDir);
46
}
47
48
public get pkg(): any {
49
return loadData(`${this.baseDir}/package.json`);
50
}
51
52
public get browserEngineOptions(): IDataBrowserEngineOptions {
53
return loadData(`${this.dataDir}/browserEngineOptions.json`);
54
}
55
56
public get userAgentOptions(): IDataUserAgentOptions {
57
return loadData(`${this.dataDir}/userAgentOptions.json`);
58
}
59
60
public as(userAgentOption: IUserAgentOption) {
61
return new BrowserData(this, userAgentOption);
62
}
63
64
public getBrowserOperatingSystemVersions(browserId: string, osName: string): string[] {
65
if (!this.browserOsEmulatorsByVersion[`as-${browserId}`]) return [];
66
return this.browserOsEmulatorsByVersion[`as-${browserId}`][osName];
67
}
68
}
69
70
const cacheMap: { [path: string]: any } = {};
71
72
export function loadData(path: string) {
73
cacheMap[path] = cacheMap[path] || JSON.parse(Fs.readFileSync(path, 'utf8'));
74
return cacheMap[path];
75
}
76
77