Path: blob/main/plugins/default-browser-emulator/lib/DataLoader.ts
1029 views
import * as Fs from 'fs';1import IUserAgentOption from '@secret-agent/interfaces/IUserAgentOption';2import {3IDataBrowserEngineOptions,4IDataCore,5IDataUserAgentOptions,6} from '../interfaces/IBrowserData';7import BrowserData from './BrowserData';89export default class DataLoader implements IDataCore {10public readonly baseDir: string;11public readonly dataDir: string;1213private readonly browserOsEmulatorsByVersion: {14[versionString: string]: { [os: string]: string[] };15} = {};1617private readonly osDataDirs = new Set<string>();1819constructor(baseDir: string) {20this.baseDir = baseDir;21this.dataDir = `${baseDir}/data`;22const browsers = Fs.readdirSync(this.dataDir);23for (const browser of browsers) {24if (browser.startsWith('as-') && Fs.statSync(`${this.dataDir}/${browser}`).isDirectory()) {25this.browserOsEmulatorsByVersion[browser] = {};26for (const osDir of Fs.readdirSync(`${this.dataDir}/${browser}`)) {27if (28osDir.startsWith('as-') &&29Fs.statSync(`${this.dataDir}/${browser}/${osDir}`).isDirectory()30) {31const isMac = osDir.startsWith('as-mac');32const version = osDir.replace('as-mac-os-', '').replace('as-windows-', '');33const name = isMac ? 'mac-os' : 'windows';34this.browserOsEmulatorsByVersion[browser][name] ??= [];35this.browserOsEmulatorsByVersion[browser][name].push(version);36this.osDataDirs.add(`${this.dataDir}/${browser}/${osDir}`);37}38}39}40}41}4243public isSupportedEmulator(osDir: string): boolean {44return this.osDataDirs.has(osDir);45}4647public get pkg(): any {48return loadData(`${this.baseDir}/package.json`);49}5051public get browserEngineOptions(): IDataBrowserEngineOptions {52return loadData(`${this.dataDir}/browserEngineOptions.json`);53}5455public get userAgentOptions(): IDataUserAgentOptions {56return loadData(`${this.dataDir}/userAgentOptions.json`);57}5859public as(userAgentOption: IUserAgentOption) {60return new BrowserData(this, userAgentOption);61}6263public getBrowserOperatingSystemVersions(browserId: string, osName: string): string[] {64if (!this.browserOsEmulatorsByVersion[`as-${browserId}`]) return [];65return this.browserOsEmulatorsByVersion[`as-${browserId}`][osName];66}67}6869const cacheMap: { [path: string]: any } = {};7071export function loadData(path: string) {72cacheMap[path] = cacheMap[path] || JSON.parse(Fs.readFileSync(path, 'utf8'));73return cacheMap[path];74}757677