tsyringe#singleton TypeScript Examples

The following examples show how to use tsyringe#singleton. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MTLSVerification.ts    From ADR-Gateway with MIT License 6 votes vote down vote up
@singleton()
@injectable()
class MTLSVerificationMiddleware {

    constructor(
        @inject("IClientCertificateVerifier") private certVerifier: IClientCertificateVerifier,
        @inject("Logger") private logger: winston.Logger
    ){}

    /**
     * This middleware ensures that the MTLS client certificate (as terminated by APIM) is valid and verified as a member of the CDR ecosystem.
     * @param req 
     * @param res 
     * @param next 
     */
    handle = async (req:express.Request,res:express.Response,next: NextFunction) => {
        // check client certificate
    
        try {
            (req as GatewayRequest).gatewayContext.clientCert = (req as GatewayRequest).gatewayContext.clientCert || {};
            (req as GatewayRequest).gatewayContext.clientCert.thumbprint = await this.certVerifier.verify(req,this.logger);
        } catch (err) {
            this.logger.error("Client certificate verification error",err);
            res.status(401).send();
            return;
        }
        
        next();
    };   

}
Example #2
Source File: OAuth2ScopeAuth.ts    From ADR-Gateway with MIT License 6 votes vote down vote up
@singleton()
class HokBoundTokenScopeVerificationFactory {
    constructor(@inject("Logger") private logger: winston.Logger, private consentManager: ConsentManager) {

    }
    
    make(scope:CdsScope) {
        let m = new HokBoundTokenScopeVerificationMiddleware(scope, this.logger, this.consentManager);
        return m;
    }
}
Example #3
Source File: executor-fake.ts    From vs-code-conan with MIT License 6 votes vote down vote up
@singleton()
export class ExecutorFake implements Executor {

    queue: Queue<Command>;
    command:string|undefined;
    constructor() {
        this.queue = new Queue<Command>();
    }
    
    processIsStillRunning():boolean {
        return false;
    }

    pushCommand(command: Command){
        this.command=command.executionCommand;
        this.queue.append(command);
    }

    executeShortCommand(command: string):string{
        if(command === "conan profile list"){
            return "default\ngcc";
        }
        return command;
    }

    normalizePathForExecution(filePath: string):string{
        return filePath;
    }
}
Example #4
Source File: storage-service.ts    From hexon with GNU General Public License v3.0 6 votes vote down vote up
@singleton()
export class StorageService implements IStorageService {
  private _db: JSONdb
  private _root: string = defaultRoot
  private _filename: string = defaultFilename
  constructor() {
    if (!existsSync(this._root)) mkdirSync(this._root)
    this._db = new JSONdb(resolve(this._root, this._filename))
  }

  get<T>(key: string) {
    return this._db.get(key) as unknown as T
  }

  set<T>(key: string, value: T) {
    this._db.set(key, value as unknown as object)
  }

  delete(key: string) {
    return this._db.delete(key)
  }
}
Example #5
Source File: MetadataUpdater.ts    From ADR-Gateway with MIT License 5 votes vote down vote up
@singleton()
class MetadataUpdater {
    constructor(private manager:MetadataUpdateLogManager) {}

    async log(): Promise<MetadataUpdateLog> {
        return await this.manager.update();
    }
}
Example #6
Source File: generator.ts    From vs-code-conan with MIT License 5 votes vote down vote up
@singleton()
@autoInjectable()
export class Generator {
    private system:System;
    private commands:Commands;
    private configFile:string;
    constructor(outputFile: string){
        this.system=container.resolve("System");
        this.commands=container.resolve(Commands);
        this.configFile = outputFile;
    }

    async generateConfigTemplate(){
        let conanfilesPython = await this.system.findAllFilesInWorkspace("conanfile.py");
        let conanfilesText = await this.system.findAllFilesInWorkspace("conanfile.txt");
        let profilesList =  this.commands.getAllProfiles();
        interface Config{
            profiles : ProfileJson[];
        }
        var config:Config = {} as Config;
        config.profiles = [];
        for (const profile of profilesList) {
            for (const conanfile of conanfilesPython) {
                let object: ProfileJson = this.createProfileJsonTemplate(profile, conanfile);
                config.profiles.push(object);
            }
            for (const conanfile of conanfilesText) {
                let object: ProfileJson = this.createProfileJsonTemplate(profile, conanfile);
                config.profiles.push(object);
            }
        }  
        this.system.writeFile(this.configFile, JSON.stringify(config, null, 4));
    }

    private createProfileJsonTemplate(profile: string, conanfile: URI):ProfileJson{
        var parentDirectory=path.basename(path.dirname(conanfile.path));
        
        if (parentDirectory === "") {
            parentDirectory = "root";
        }
        var name = parentDirectory;
        if(conanfile.path.endsWith("txt")){
            name += `-txt`;
        }
        if (profile !== "default") {
            name += `-${profile}`;
        }
        let conanfilePath = conanfile.path.replace(`${this.system.getWorkspaceRootPath()}`,"${workspaceFolder}");
        return {
            name: name,
            conanFile: conanfilePath,
            profile: profile,
            installArg: "",
            buildArg: "",
            createUser: "disroop",
            createChannel: "development",
            createArg: ""
        };
    }
}
Example #7
Source File: system-fake.ts    From vs-code-conan with MIT License 5 votes vote down vote up
@singleton()
export class SystemPluginFake implements System{

    warningMessage:string | undefined;
    fileContent:string|undefined;
    filePath:string|undefined;
    sysCallWorking: boolean = false;
    writeFileContent: string | undefined;
    writeFilePath: string | undefined;

    setFile( content:string){
        this.fileContent = content;
    }
    
    getWorkspaceRootPath():string {
        return '/root-workspace';
    }
    replaceWorkspaceRoot(filepath: string): string{
        if (filepath.startsWith(`\${workspaceFolder}/`)) {
            let rootFolder=this.getWorkspaceRootPath();
            filepath = filepath.replace(`\${workspaceFolder}/`, rootFolder);
        }
        return filepath;
    }
    addWorkspaceRoot(filepath:string):string{
        let rootFolder=this.getWorkspaceRootPath();
        return `${rootFolder}/${filepath}`;
    }
    showWarningMessage( message:string){
        this.warningMessage = message;
    }
    readFile( file:string) : Promise<string> {
        this.filePath = file;
        return new Promise<string>((res,rej) => {
            if(this.fileContent !== undefined) { 
                res(this.fileContent);
            }else{
                rej("{}");
            }
        });
    }

    log(_message:string){
    }

    focusLog(){
    }

    findAllFilesInWorkspace(filename:string): Promise<URI[]>{
        var rootWorkspace = this.getWorkspaceRootPath();
        return new Promise<URI[]>((res,rej) => {
            if(filename !== undefined) { 
                let uri = URI.file(`${rootWorkspace}/${filename}`);
                res([uri]);
            }else{
                rej("{}");
            }
        });
    }

    writeFile(filepath: string, content: string): void{
        this.writeFileContent = content;
        this.writeFilePath = filepath;
    }

    showCreateTemplateDialog(_error:Error, _generateTemplate: ()=>any, _cancelfunction: ()=>any){

    }

}
Example #8
Source File: CDSVersionCompliance.ts    From ADR-Gateway with MIT License 4 votes vote down vote up
@singleton()
class CDSVersionComplianceMiddleware {

    constructor(@inject("Logger") private logger: winston.Logger) {
    }

    /**
     * This middleware ensures that the Data Recipient responds to Endpoint Versioning parameters in a standards-compliant manner
     * See https://consumerdatastandardsaustralia.github.io/standards/#versioning for more information
     * @param req W
     * @param res 
     * @param next 
     */
    handle = (req:express.Request,res:express.Response,next: NextFunction) => {
        // check client certificate
    
        let xFapiId = req.headers['x-fapi-interaction-id'];

        if (typeof xFapiId == 'string') {
            res.setHeader('x-fapi-interaction-id',xFapiId);
        } else {
            res.setHeader('x-fapi-interaction-id',uuid.v4());
        }

        let xvOK:boolean = (():boolean => {
            // Accept request only if x-v = 1
            let xv = req.headers["x-v"];
            if (typeof xv == 'string') {
                if (xv != "1") {
                    return false;
                }
            } else {
                return false;
            }
    
            // Accept request only if x-min-v is 1 or not sent
            let xvMin = req.headers["x-min-v"];
            if (typeof xvMin == 'string') {
                if (xvMin != "1") {
                    return false;
                }
            } else if (typeof xvMin != 'undefined') {
                return false;
            }
    
            return true;
        })();

        let acceptTypesOK:boolean = (():boolean => {
            // Accept request only if x-v = 1
            let accept = req.headers['accept'];
            if (typeof accept == 'string') {
                if (accept != "application/json") {
                    return false;
                }
            }    
   
            return true;
        })();


        let contentTypesOK:boolean = (():boolean => {   
            // Accept request only if x-min-v is 1 or not sent
            let contentType = req.headers['content-type'];
            if (typeof contentType == 'string') {
                if (contentType != "application/json") {
                    return false;
                }
            }
    
            return true;
        })();
    
        if (!(xvOK && acceptTypesOK && contentTypesOK)) {
            if (!contentTypesOK) {
                res.statusCode = 400
                res.statusMessage = "Not Acceptable"
                res.send()    
            } else {
                res.statusCode = 406
                res.statusMessage = "Not Acceptable"
                res.send()    
            }
        } else {
            next();
        }        
    };   

}
Example #9
Source File: configurator.ts    From vs-code-conan with MIT License 4 votes vote down vote up
@singleton()
@autoInjectable()
export class Configurator {
    readonly file: string;
    private profiles: Map<string, Profile> | undefined;
    private workspaces: Map<string, Workspace> | undefined;
    private system:System;

    constructor(file: string) {
        this.file = file;
        this.system=container.resolve("System");
    }

    async update() {
        const data = await (this.system.readFile(this.file)).then(value => {
            return value;
        });
        let parser = new SettingsParser(data);
        this.profiles = parser.getProfiles();
        this.workspaces = parser.getWorkspaces();
    }

    private getConsoleProfile(strippedInstallArg: ProfileVariant, name: string): ConanProfile {
        let installProfile;
        if (strippedInstallArg.profileGeneric === undefined
            && strippedInstallArg.profileSpecific.build === undefined
            && strippedInstallArg.profileSpecific.host === undefined) {
            installProfile = this.getProfiles(name);
        }
        else {
            installProfile = Configurator.convertProfile(strippedInstallArg.profileGeneric, strippedInstallArg.profileSpecific);
        }
        return installProfile;
    }

    private static stripProfilesArg(argument: string): { argument: string, profile: ProfileVariant } {
        let argStripped = stripArgument(argument, "pr:b", "profile:build");
        let installBuildProfile = argStripped.foundValue;
        argStripped = stripArgument(argStripped.stripedArgument, "pr:h", "profile:host");
        let installHostProfile = argStripped.foundValue;
        argStripped = stripArgument(argStripped.stripedArgument, "pr", "profile");
        let profileGeneric = argStripped.foundValue;
        let profile: ProfileVariant = { profileGeneric, profileSpecific: { build: installBuildProfile, host: installHostProfile } };
        return { argument: argStripped.stripedArgument, profile };
    }

    private static stripInstallArg(profile: Profile | Workspace): InstallArgumentsExtracted {
        let installArgRaw;
        if(profile instanceof Profile){
            installArgRaw = profile.installArg;
        }
        else{
            installArgRaw = profile.arg;
        }
        let parsedProfile = Configurator.stripProfilesArg(installArgRaw);
        let installArg = stripArgument(parsedProfile.argument, "if", "install-folder");
        let installFolder = installArg.foundValue;
        let stripedArgument = installArg.stripedArgument;
        return { installArg: stripedArgument, profile: parsedProfile.profile, installFolder };
    }

    private static stripCreateArg(profile: Profile) {
        let parsedProfile = Configurator.stripProfilesArg(profile.createArg);
        return { createArg: parsedProfile.argument, profile: parsedProfile.profile };
    }

    private static stripBuildArg(profile: Profile) {
        let buildArg = stripArgument(profile.buildArg, "bf", "build-folder");
        return { buildArg: buildArg.stripedArgument, buildFolder: buildArg.foundValue };
    }

    private static appendKeysOfMap(array: Array<string>, map: Map<string, Profile | Workspace> | undefined): Array<string> {
        if (map) {
            array = array.concat(Array.from(map.keys()));
        }
        return array;
    }

    private static checkUniqueName(names: string[]): boolean {
        return new Set(names).size !== names.length;
    }

    private static convertProfile(profileGeneric: string | undefined, profileSpecific: ConanProfile) {
        if (profileGeneric && (profileSpecific.build || profileSpecific.host)) {
            throw new Error("Can't define profile with profile-host or profile-build.");
        }
        if (profileSpecific.build || profileSpecific.host) {
            let profileBuild = Configurator.replaceUndefinedDefault(profileSpecific.build);
            let profileHost = Configurator.replaceUndefinedDefault(profileSpecific.host);
            return { build: profileBuild, host: profileHost };
        }
        else {
            let profile = Configurator.replaceUndefinedDefault(profileGeneric);
            return { build: profile, host: profile };
        }
    }
    private getProfiles(name: string): ConanProfile {
        let profileConfig: BuildProfile = this.getProfileConfiguration(name);
        return Configurator.convertProfile(profileConfig.profile, { build: profileConfig.profileBuild, host: profileConfig.profileHost });
    }

    private getBuildFolder(name: string): string | undefined {
        let profileConfig: BuildProfile = this.getProfileConfiguration(name);
        return profileConfig.buildFolder;
    }

    private getProfileConfiguration(name: string) {
        let profileConfig:BuildProfile;
        if (this.profiles?.has(name)) {
            profileConfig = <BuildProfile>this.profiles.get(name);
        }
        else if (this.workspaces?.has(name)) {
            profileConfig = <BuildProfile>this.workspaces.get(name);
        }
        else {
            throw new Error("The profile configuration does not exist - " + name);
        }
        return profileConfig;
    }

    private static replaceUndefinedDefault(value: string | undefined): string {
        if (value === undefined) {
            return "default";
        }
        return value;
    }

    getWorkspace(name: string):WorkspaceArgument{
        let workspace = this.workspaces?.get(name);
        if (workspace) {
            let strippedInstallArgument = Configurator.stripInstallArg(workspace);
            let instProfile = this.getConsoleProfile(strippedInstallArgument.profile, name);
            let installFolder = strippedInstallArgument.installFolder ? strippedInstallArgument.installFolder : this.getBuildFolder(name);
            return {
                path: workspace.conanworkspacePath,
                installProfile: instProfile,
                installArguments: strippedInstallArgument.installArg,
                installFolder: installFolder
            };
        }
        throw Error("No workspace found with this name "+name+".");

    }
    getConan(name: string): ConanArgument {
        let profile = this.profiles?.get(name);
        if (profile) {
            let strippedInstallArg = Configurator.stripInstallArg(profile);
            let installProfile = this.getConsoleProfile(strippedInstallArg.profile, name);
            let strippedBuildArg = Configurator.stripBuildArg(profile);
            let strippedCreateArg = Configurator.stripCreateArg(profile);
            let createProfile = this.getConsoleProfile(strippedCreateArg.profile, name);
            let buildFolder = strippedBuildArg.buildFolder ? strippedBuildArg.buildFolder : this.getBuildFolder(name);
            let installFolder = strippedInstallArg.installFolder ? strippedInstallArg.installFolder : this.getBuildFolder(name);
            return {
                path: profile.conanfilePath,
                user: profile.createUser,
                channel: profile.createChannel,
                installProfile: installProfile,
                installArguments: strippedInstallArg.installArg,
                createArguments: strippedCreateArg.createArg,
                buildArguments: strippedBuildArg.buildArg,
                buildFolder: buildFolder,
                createProfile: createProfile,
                installFolder: installFolder
            };
        }
        throw Error("No profile found with this name "+name+".");

    }

    getAllNames(): string[] {
        let names: Array<string> = new Array<string>();
        names = Configurator.appendKeysOfMap(names, this.profiles);
        names = Configurator.appendKeysOfMap(names, this.workspaces);
        if (Configurator.checkUniqueName(names)) {
            throw new Error("Duplication of names in profile and workspace");
        }
        return names;
    }

    isWorkspace(name: string): boolean {
        if (this.workspaces){
            return this.workspaces.has(name);
        }
        return false;
    }
}
Example #10
Source File: node.ts    From vs-code-conan with MIT License 4 votes vote down vote up
@singleton()
@autoInjectable()
export class ExecutorNodeJs implements Executor {
    private subprocess: any;
    private queue: Queue<Command>;
    private system: System;
    constructor() {
        this.subprocess = null;
        this.queue = new Queue<Command>();
        this.system = container.resolve("System");
    }
    private executeConanCommand(command: string, resolve: any, reject: any) {
        this.system.log(`command: ${command}\n`);
        const spawn_opts: child.SpawnOptions = {
            stdio: [
                'pipe', // Use parent's stdin for child
                'pipe', // Pipe child's stdout to parent
                'pipe', // Pipe child's stderror to parent
            ],
            shell: true
        };
        this.subprocess = child.spawn(command, [], spawn_opts);

        this.subprocess.stdout.on("data", (data: string) => {
            this.system.log(`conan: ${data}`);
        });
        this.subprocess.stderr.on("data", (data: any) => {
            this.system.log(`stderr: ${data}`);
            this.clearCommandQueue();
        });

        this.subprocess.on('error', (error: { message: any; }) => {
            this.system.log(`error: ${error.message}`);
            reject(error.message);
            this.clearCommandQueue();
        });

        this.subprocess.on("close", (code: any) => {
            if (code !== null) {
                this.system.log(`child process exited with code ${code}`);
                resolve();
                this.dequeueCommand();
            }
            else {
                this.system.log(`conan: process cancelled!`);
                this.clearCommandQueue();
            }
            this.system.log("");
            this.subprocess = null;
        });
    }

    private clearCommandQueue() {
        while (this.queue.length > 0) {
            this.queue.removeHead();
        }
    }

    normalizePathForExecution(filePath: string): string {
        let normalizedPath = undefined;
        switch (process.platform) {
            case 'darwin': 
                normalizedPath = path.posix.normalize(filePath);
                break;
            case 'linux': 
                normalizedPath = path.posix.normalize(filePath);
                break;
            case 'win32': 
                normalizedPath = path.win32.normalize(filePath);
                if(normalizedPath.startsWith("\\")){
                    normalizedPath=normalizedPath.substring(1);
                }
                break;
        }
        if(normalizedPath===undefined){
            return filePath;
        }
        else{
            return normalizedPath;
        }
    }

    processIsStillRunning(): boolean {
        return this.subprocess !== null;
    }

    pushCommand(command: Command) {
        this.queue.append(command);
        if (!this.processIsStillRunning()) { this.dequeueCommand(); }
    }

    executeShortCommand(command: string): string {
        let [executed, commandOutput] = this.executeSyncCommand(command);
        if (executed) {
            return commandOutput;
        }
        throw Error(`Not able to execute command: ${command}. Process is still running!`);
    }

    private executeSyncCommand(command: string): [executed: boolean, stdout: string] {
        if (this.processIsStillRunning()) {
            return [false, ""];
        } else {
            return [true, child.execSync(command).toString()]; //NOSONAR this executes only a short command
        }
    }

    private dequeueCommand() {
        if (this.queue.length > 0) {
            let command = this.queue.dequeue();
            this.executeCommand(command);
        }
    }

    private executeCommand(command: Command) {
        vscode.window.withProgress({
            location: vscode.ProgressLocation.Notification,
            title: "Conan is working",
            cancellable: true
        }, (progress, token) => {
            token.onCancellationRequested(() => {
                var kill = require('tree-kill');
                kill(this.subprocess.pid);
            });
            progress.report({ message: `I am ${command.description}` });
            return new Promise((resolve, reject) => {
                this.executeConanCommand(command.executionCommand, resolve, reject);
            }).then(() => {
                this.system.focusLog();
            }).catch((err) => {
                vscode.window.showErrorMessage(err);
                this.system.focusLog();
            });
        });
    }
}
Example #11
Source File: plugin.ts    From vs-code-conan with MIT License 4 votes vote down vote up
@singleton()
export class SystemPlugin implements System {
    private readonly _outputLog: any;

    constructor() {
        this._outputLog = window.createOutputChannel("conan");
    }

    private getWorkspaceUri(): Uri{
        if (workspace.workspaceFolders !== undefined) {
            if (workspace.workspaceFolders.length === 1) {
                return workspace.workspaceFolders[0].uri;
            }
            else {
                throw new Error("Multiple workspaces are not supported");
            }
        }
        throw new Error("No workspace folders");
    }
    getWorkspaceRootPath(): string {
        return this.getWorkspaceUri().path;
    }

    replaceWorkspaceRoot(filepath:string):string{       
        if (filepath.startsWith(`\${workspaceFolder}/`)) {
            filepath = filepath.replace(`\${workspaceFolder}/`, "");
            filepath = this.addWorkspaceRoot(filepath);
        }
        return filepath;
    }

    addWorkspaceRoot(filepath:string):string{
        let rootUri = this.getWorkspaceUri();
        let uripath=Uri.joinPath(rootUri,filepath);
        return uripath.path;
    }
    
    showWarningMessage(message: string) {
        window.showWarningMessage(message);
    }
    async readFile(filepath: string): Promise<string> {
        return (await workspace.openTextDocument(filepath)).getText();
    }

    async fileExist(filepath: string): Promise<boolean> {
        try {
            await workspace.fs.stat(Uri.file(filepath));
        } catch {
            return false;
        }
        return true;
    }

    log(message: string) {
        this._outputLog.append(message);
    }

    focusLog() {
        this._outputLog.show();
    }

    async findAllFilesInWorkspace(filename:string): Promise<Uri[]>{
        return workspace.findFiles(`**/${filename}`);
    }

    async writeFile(filepath: string, content: string): Promise<void>{
        const finalUri = Uri.file(filepath);
        let enc = new TextEncoder(); 
        await workspace.fs.writeFile(finalUri,enc.encode(content));
    }

    showCreateTemplateDialog(error:Error, generateTemplate: ()=>any, cancel: ()=>any){
        window.showInformationMessage(error.message, ...[`Create template`, `Cancel`]).then(selection => {
            if(selection === "Create template"){
                generateTemplate();
            }
            else{
                cancel();
            }
        });
    }

}
Example #12
Source File: api.ts    From tarkov with MIT License 4 votes vote down vote up
@singleton()
export class Api {
  public prod: Got;
  public launcher: Got;
  public trading: Got;
  public ragfair: Got;

  public launcherVersion = '0.9.3.1057';
  public gameVersion = '0.12.3.6090';
  public unityVersion = '2018.4.13f1';

  private request = 0;

  public session = {
    queued: false,
    session: '',
  };

  private defaultOptions: ExtendOptions = {
    encoding: undefined,
    decompress: true,
    responseType: 'buffer',
    hooks: {
      beforeRequest: [
        (options: NormalOptions) => {
          delete options.headers['user-agent'];
          delete options.headers['content-type'];
          options.headers['Content-Type'] = 'application/json';
          options.bsgSession ? options.headers['Cookie'] = `PHPSESSID=${this.session.session}` : null;
          options.bsgAgent ? options.headers['User-Agent'] = `BSG Launcher ${this.launcherVersion}` : null;
          options.unityAgent ? options.headers['User-Agent'] = `UnityPlayer/${this.unityVersion} (UnityWebRequest/1.0, libcurl/7.52.0-DEV)` : null;
          options.unityAgent ? options.headers['X-Unity-Version'] = this.unityVersion : null;
          options.appVersion ? options.headers['App-Version'] = `EFT Client ${this.gameVersion}` : null;
          options.requestId ? options.headers['GClient-RequestId'] = `${this.request++}` : null;
        },
      ],
      afterResponse: [
        (response: any, retry: any) => {
          response = {
            ...response,
            body: JSON.parse(pako.inflate(response.body, { to: 'string' })),
          };

          if (response.body.err !== 0) {
            throw response.body;
          };

          return response;
        }
      ]
    },
    unityAgent: true,
    appVersion: true,
    requestId: true,
    bsgSession: true,
  };

  constructor() {
    this.prod = got.extend({
      prefixUrl: 'https://prod.escapefromtarkov.com',
      ...this.defaultOptions,
    });

    this.launcher = got.extend({
      prefixUrl: 'https://launcher.escapefromtarkov.com',
      bsgAgent: true,
      unityAgent: false,
      appVersion: false,
      requestId: false,
      bsgSession: false,
      ...this.defaultOptions,
    });

    this.trading = got.extend({
      prefixUrl: 'https://trading.escapefromtarkov.com',
      ...this.defaultOptions,
    });

    this.ragfair = got.extend({
      prefixUrl: 'https://ragfair.escapefromtarkov.com',
      ...this.defaultOptions,
    });

    // Load the latest launcher version
    this.getLauncherVersion();
    this.getGameVersion();
  }

  /**
   * Loads the latest launcher version into memory
   */
  private async getLauncherVersion() {
    this.launcher.post('launcher/GetLauncherDistrib')
      .then((result: any) => {
        const { Version } = result.body.data;

        if (this.launcherVersion !== Version) {
          console.log(`Updated launcher version from ${this.launcherVersion} to ${Version}`);
          this.launcherVersion = Version;
        }
      }, error => {
        throw error;
      });
  }

  private async getGameVersion() {
    this.launcher.post('launcher/GetPatchList', {
      searchParams: {
        launcherVersion: this.launcherVersion,
        branch: 'live',
      },
    })
      .then((result: any) => {
        const { Version } = result.body.data[0];

        if (this.gameVersion !== Version) {
          console.log(`Updated game version from ${this.gameVersion} to ${Version}`);
          this.gameVersion = Version;
        }
      }, error => {
        throw error;
      });
  }
}
Example #13
Source File: profile.ts    From tarkov with MIT License 4 votes vote down vote up
@singleton()
export class Profile {
  _id!: string;
  aid!: number;
  savage!: string;
  Info!: Info;
  Customization!: Customization;
  Health!: Health;
  Inventory!: Inventory;
  Skills!: Skills;
  Stats!: Stats;
  Encyclopedia!: {
    [key: string]: boolean;
  };
  ConditionCounters!: ConditionCounters;
  BackendCounters: any;
  InsuredItems!: any[];
  Hideout!: Hideout;
  Bonuses!: Bonus[];
  Notes!: Notes;
  Quests!: Quest[];
  TraderStandings!: TraderStandings;
  RagfairInfo!: RagfairInfo;
  WishList!: any[];

  roubleId = '5449016a4bdc2d6f028b456f';
  dollarId = '5696686a4bdc2da3298b456a';
  euroId = '569668774bdc2da2298b4568';
  api: Api;

  constructor() {
    this.api = container.resolve(Api);
  }

  async selectProfile(profile: ProfileData) {
    const body = JSON.stringify({ uid: profile._id });
    const result: ApiResponse<SelectedProfile> = await this.api.prod.post('client/game/profile/select', {
      body,
    });

    Object.assign(this, profile);
  }

  get items() {
    return this.Inventory.items;
  }

  get inventory() {
    return this.Inventory;
  }

  get skills() {
    return this.Skills;
  }

  getItem(itemId: string): ItemSearch {
    let amount = 0;
    const stacks = this.Inventory.items.filter(i => i._tpl === itemId);
    stacks.forEach(stack => amount += stack.upd.StackObjectsCount || 0);

    return {
      itemId,
      amount,
      stacks,
    };
  }

  getStack(stackId: string): Item | undefined {
    return this.Inventory.items.find(item => item._id === stackId);
  }

  getRoubles(): ItemSearch {
    return this.getItem(this.roubleId);
  }

  getDollars(): ItemSearch {
    return this.getItem(this.dollarId);
  }

  getEuros(): ItemSearch {
    return this.getItem(this.euroId);
  }

  updateItems(updatedItems: Item[] = []): void {
    this.Inventory.items = this.Inventory.items.map((item: Item) => {
      // Search if this inventory item has been updated
      const index = updatedItems.findIndex(i => i._id === item._id);
      if (index >= 0) {
        // Return the updated item instead of the old one
        return updatedItems[index];
      }

      // Not updated, return it's current value
      return item;
    });
  }

  addItems(items: Item[] = []): void {
    this.Inventory.items = [
      ...this.Inventory.items,
      ...items,
    ];
  }

  removeItems(removedItems: Item[] = []): void {
    this.Inventory.items = this.Inventory.items.filter((item: Item) => {
      // Search if this inventory item has been removed
      const index = removedItems.findIndex(i => i._id === item._id);

      // Return true if we should keep it, false if we should remove it.
      return index === -1;
    });
  }

  handleChanges(items: any) {
    if (items.new) {
      this.addItems(items.new);
    }

    if (items.change) {
      this.updateItems(items.change);
    }

    if (items.del) {
      this.removeItems(items.del);
    }
  }

}