From dbed08a747c1b6dade7f2cfc30089dbfc0e2ac28 Mon Sep 17 00:00:00 2001 From: Refringe Date: Tue, 31 Dec 2024 05:11:08 -0500 Subject: [PATCH] Static Program Properties & Simplified Entry Points (#1010) Significant refactoring of globals and entry points. Oh my. - The global variables previously accessible throughout the codebase have been restructured as private static properties of the Program class. Public static getter methods have been added to allow read access to these properties throughout the codebase. - Entry points, which were dispersed across multiple files, have been consolidated and simplified into a static method on the Program class, making the entry logic easier to follow. - Removed unnecessary ~~globals~~ Program static properties. - Adjusted imports and references across the codebase to reflect the new structure. Try not to focus on the `gulpfile.mjs` changes, as it won't be around for much longer. *[winky face]* Co-authored-by: Chomp <27521899+chompDev@users.noreply.github.com> --- project/Server.code-workspace | 2 +- project/gulpfile.mjs | 36 +++++---- project/package.json | 1 + project/src/Program.ts | 80 ++++++++++++++++++- project/src/callbacks/ClientLogCallbacks.ts | 8 +- project/src/callbacks/ModCallbacks.ts | 3 +- project/src/controllers/GameController.ts | 9 +-- project/src/{ide => entry}/build.json | 1 + project/src/entry/run.ts | 7 ++ project/src/global.d.ts | 14 ---- project/src/ide/BleedingEdgeEntry.ts | 19 ----- project/src/ide/BleedingEdgeModsEntry.ts | 19 ----- project/src/ide/DebugEntry.ts | 19 ----- project/src/ide/ReleaseEntry.ts | 19 ----- project/src/ide/TestEntry.ts | 22 ----- project/src/loaders/PostDBModLoader.ts | 3 +- project/src/loaders/PostSptModLoader.ts | 3 +- project/src/loaders/PreSptModLoader.ts | 16 ++-- project/src/servers/ConfigServer.ts | 7 +- project/src/servers/WebSocketServer.ts | 3 +- project/src/servers/http/SptHttpListener.ts | 7 +- project/src/services/LocalisationService.ts | 5 +- project/src/services/ModCompilerService.ts | 4 +- project/src/utils/App.ts | 14 ++-- project/src/utils/DatabaseImporter.ts | 7 +- project/src/utils/Watermark.ts | 21 ++--- .../utils/logging/AbstractWinstonLogger.ts | 3 +- 27 files changed, 168 insertions(+), 184 deletions(-) rename project/src/{ide => entry}/build.json (70%) create mode 100644 project/src/entry/run.ts delete mode 100644 project/src/global.d.ts delete mode 100644 project/src/ide/BleedingEdgeEntry.ts delete mode 100644 project/src/ide/BleedingEdgeModsEntry.ts delete mode 100644 project/src/ide/DebugEntry.ts delete mode 100644 project/src/ide/ReleaseEntry.ts delete mode 100644 project/src/ide/TestEntry.ts diff --git a/project/Server.code-workspace b/project/Server.code-workspace index 42b4964d..77c6e1c0 100644 --- a/project/Server.code-workspace +++ b/project/Server.code-workspace @@ -27,7 +27,7 @@ { "name": "Debug", "type": "node", - "program": "${workspaceFolder}/src/ide/TestEntry.ts", + "program": "${workspaceFolder}/src/entry/run.ts", "runtimeVersion": "22.12.0", "runtimeExecutable": "tsx", "request": "launch", diff --git a/project/gulpfile.mjs b/project/gulpfile.mjs index 8893e7ff..29c9673e 100644 --- a/project/gulpfile.mjs +++ b/project/gulpfile.mjs @@ -29,10 +29,10 @@ const serverExeName = "SPT.Server.exe"; const serverExe = path.join(buildDir, serverExeName); const pkgConfig = "pkgconfig.json"; const entries = { - release: path.join("obj", "ide", "ReleaseEntry.js"), - debug: path.join("obj", "ide", "DebugEntry.js"), - bleeding: path.join("obj", "ide", "BleedingEdgeEntry.js"), - bleedingmods: path.join("obj", "ide", "BleedingEdgeModsEntry.js"), + release: "RELEASE", + debug: "DEBUG", + bleeding: "BLEEDING_EDGE", + bleedingmods: "BLEEDING_EDGE_MODS", }; const licenseFile = "../LICENSE.md"; @@ -64,7 +64,7 @@ const compile = async () => { // Packaging const fetchPackageImage = async () => { try { - const output = "./.pkg-cache/v6.2"; + const output = "./.pkg-cache/v3.5"; const fetchedPkg = await pkgfetch.need({ arch: targetArch, nodeRange: nodeVersion, @@ -153,7 +153,7 @@ const copyLicense = () => gulp.src([licenseFile]).pipe(rename("LICENSE-Server.tx /** * Writes the latest build data to the core.json and build.json configuration files. */ -const writeBuildDataToJSON = async () => { +const writeBuildDataToJSON = async (entryType) => { try { // Fetch the latest Git commit hash const gitResult = await exec("git rev-parse HEAD", { stdout: "pipe" }); @@ -168,12 +168,13 @@ const writeBuildDataToJSON = async () => { await fs.writeFile(coreJSONPath, JSON.stringify(coreParsed, null, 4)); // Write build.json - const buildJsonPath = path.join("obj", "ide", "build.json"); - const buildInfo = {}; + const buildJsonPath = path.join("obj", "entry", "build.json"); + const buildInfo = {}; + buildInfo.entryType = entryType; + buildInfo.sptVersion = coreParsed.sptVersion; buildInfo.commit = coreParsed.commit; buildInfo.buildTime = coreParsed.buildTime; - buildInfo.sptVersion = coreParsed.sptVersion; await fs.writeFile(buildJsonPath, JSON.stringify(buildInfo, null, 4)); } catch (error) { throw new Error(`Failed to write commit hash to core.json: ${error.message}`); @@ -191,7 +192,8 @@ const createHashFile = async () => { }; // Combine all tasks into addAssets -const addAssets = gulp.series(copyAssets, downloadPnpm, copyLicense, writeBuildDataToJSON, createHashFile); +const addAssets = (entryType) => + gulp.series(copyAssets, downloadPnpm, copyLicense, () => writeBuildDataToJSON(entryType), createHashFile); /** * Cleans the build directory. @@ -284,14 +286,14 @@ const loadRecursiveAsync = async (filepath) => { }; // Main Tasks Generation -const build = (packagingType) => { - const anonPackaging = () => packaging(entries[packagingType]); - anonPackaging.displayName = `packaging-${packagingType}`; +const build = (entryType) => { + const anonPackaging = () => packaging(entries[entryType]); + anonPackaging.displayName = `packaging-${entryType}`; const tasks = [ cleanBuild, validateJSONs, compile, - addAssets, + addAssets(entries[entryType]), fetchPackageImage, anonPackaging, updateBuildProperties, @@ -301,11 +303,11 @@ const build = (packagingType) => { }; // Packaging Arguments -const packaging = async (entry) => { +const packaging = async (entryType) => { const target = `${nodeVersion}-${targetPlatform}-${targetArch}`; try { await pkg.exec([ - entry, + path.join("obj", "entry", "run.js"), "--compress", "GZip", "--target", @@ -330,5 +332,5 @@ gulp.task("run:build", async () => await exec(serverExeName, { stdio, cwd: build gulp.task("run:profiler", async () => { await cleanCompiled(); await compile(); - await exec("node --prof --inspect --trace-warnings obj/ide/TestEntry.js", { stdio }); + await exec("node --prof --inspect --trace-warnings obj/entry/run.js", { stdio }); }); diff --git a/project/package.json b/project/package.json index 24f408fe..feea9cfd 100644 --- a/project/package.json +++ b/project/package.json @@ -61,6 +61,7 @@ "@pnpm/exe": "8.15.9", "@swc/cli": "~0.4", "@swc/core": "~1.7", + "@types/fs-extra": "11.0.4", "@types/i18n": "~0.13", "@types/node": "22.10.2", "@types/proper-lockfile": "~4.1", diff --git a/project/src/Program.ts b/project/src/Program.ts index 167cdc94..86dcf37b 100644 --- a/project/src/Program.ts +++ b/project/src/Program.ts @@ -1,16 +1,36 @@ import { ErrorHandler } from "@spt/ErrorHandler"; import { Container } from "@spt/di/Container"; +import buildInfo from "@spt/entry/build.json" assert { type: "json" }; import type { PreSptModLoader } from "@spt/loaders/PreSptModLoader"; import { App } from "@spt/utils/App"; import { Watermark } from "@spt/utils/Watermark"; import { container } from "tsyringe"; +export enum EntryType { + LOCAL = "LOCAL", + DEBUG = "DEBUG", + RELEASE = "RELEASE", + BLEEDING_EDGE = "BLEEDING_EDGE", + BLEEDING_EDGE_MODS = "BLEEDING_EDGE_MODS", +} + export class Program { + private static _ENTRY_TYPE: EntryType; + + private static _DEBUG: boolean; + private static _COMPILED: boolean; + private static _MODS: boolean; + + private static _SPT_VERSION: string; + private static _COMMIT: string; + private static _BUILD_TIME: number; + private errorHandler: ErrorHandler; + constructor() { - // set window properties process.stdout.setEncoding("utf8"); process.title = "SPT Server"; + this.errorHandler = new ErrorHandler(); } @@ -27,8 +47,62 @@ export class Program { Container.registerPostLoadTypes(container, childContainer); childContainer.resolve("App").load(); - } catch (err: any) { - this.errorHandler.handleCriticalError(err instanceof Error ? err : new Error(err)); + } catch (err: unknown) { + this.errorHandler.handleCriticalError(err instanceof Error ? err : new Error(String(err))); } } + + public static initialize(): void { + Program._ENTRY_TYPE = buildInfo.entryType as EntryType; + Program._SPT_VERSION = buildInfo.sptVersion ?? ""; + Program._COMMIT = buildInfo.commit ?? ""; + Program._BUILD_TIME = buildInfo.buildTime ?? 0; + + switch (Program._ENTRY_TYPE) { + case EntryType.RELEASE: + Program._DEBUG = false; + Program._COMPILED = true; + Program._MODS = true; + break; + case EntryType.BLEEDING_EDGE: + Program._DEBUG = true; + Program._COMPILED = true; + Program._MODS = false; + break; + case EntryType.DEBUG: + case EntryType.BLEEDING_EDGE_MODS: + Program._DEBUG = true; + Program._COMPILED = true; + Program._MODS = true; + break; + default: // EntryType.LOCAL + Program._DEBUG = true; + Program._COMPILED = false; + Program._MODS = true; + break; + } + } + + // Public Static Getters + public static get ENTRY_TYPE(): EntryType { + return Program._ENTRY_TYPE; + } + public static get DEBUG(): boolean { + return Program._DEBUG; + } + public static get COMPILED(): boolean { + return Program._COMPILED; + } + public static get MODS(): boolean { + return Program._MODS; + } + public static get SPT_VERSION(): string { + return Program._SPT_VERSION; + } + public static get COMMIT(): string { + return Program._COMMIT; + } + public static get BUILD_TIME(): number { + return Program._BUILD_TIME; + } } diff --git a/project/src/callbacks/ClientLogCallbacks.ts b/project/src/callbacks/ClientLogCallbacks.ts index 0936b89a..0d91d157 100644 --- a/project/src/callbacks/ClientLogCallbacks.ts +++ b/project/src/callbacks/ClientLogCallbacks.ts @@ -1,3 +1,4 @@ +import { EntryType, Program } from "@spt/Program"; import { ClientLogController } from "@spt/controllers/ClientLogController"; import { ModLoadOrder } from "@spt/loaders/ModLoadOrder"; import { INullResponseData } from "@spt/models/eft/httpResponse/INullResponseData"; @@ -34,7 +35,7 @@ export class ClientLogCallbacks { public releaseNotes(): string { const data: IRelease = this.configServer.getConfig(ConfigTypes.CORE).release; - data.betaDisclaimerText = globalThis.G_MODS_ENABLED + data.betaDisclaimerText = Program.MODS ? this.localisationService.getText("release-beta-disclaimer-mods-enabled") : this.localisationService.getText("release-beta-disclaimer"); @@ -47,8 +48,9 @@ export class ClientLogCallbacks { data.illegalPluginsExceptionText = this.localisationService.getText("release-illegal-plugins-exception"); data.releaseSummaryText = this.localisationService.getText("release-summary"); - data.isBeta = globalThis.G_WATERMARK_ENABLED; - data.isModdable = globalThis.G_MODS_ENABLED; + data.isBeta = + Program.ENTRY_TYPE === EntryType.BLEEDING_EDGE || Program.ENTRY_TYPE === EntryType.BLEEDING_EDGE_MODS; + data.isModdable = Program.MODS; data.isModded = this.modLoadOrder.getLoadOrder().length > 0; return this.httpResponse.noBody(data); diff --git a/project/src/callbacks/ModCallbacks.ts b/project/src/callbacks/ModCallbacks.ts index c6dce2c9..dbb25395 100644 --- a/project/src/callbacks/ModCallbacks.ts +++ b/project/src/callbacks/ModCallbacks.ts @@ -1,3 +1,4 @@ +import { Program } from "@spt/Program"; import { OnLoad } from "@spt/di/OnLoad"; import { PostSptModLoader } from "@spt/loaders/PostSptModLoader"; import { ConfigTypes } from "@spt/models/enums/ConfigTypes"; @@ -25,7 +26,7 @@ export class ModCallbacks implements OnLoad { } public async onLoad(): Promise { - if (globalThis.G_MODS_ENABLED) { + if (Program.MODS) { await this.postSptModLoader.load(); } } diff --git a/project/src/controllers/GameController.ts b/project/src/controllers/GameController.ts index 944650c5..5e1e01f8 100644 --- a/project/src/controllers/GameController.ts +++ b/project/src/controllers/GameController.ts @@ -1,3 +1,4 @@ +import { Program } from "@spt/Program"; import { ApplicationContext } from "@spt/context/ApplicationContext"; import { ContextVariableType } from "@spt/context/ContextVariableType"; import { HideoutHelper } from "@spt/helpers/HideoutHelper"; @@ -565,11 +566,9 @@ export class GameController { protected logProfileDetails(fullProfile: ISptProfile): void { this.logger.debug(`Profile made with: ${fullProfile.spt.version}`); - this.logger.debug( - `Server version: ${globalThis.G_SPTVERSION || this.coreConfig.sptVersion} ${globalThis.G_COMMIT}`, - ); - this.logger.debug(`Debug enabled: ${globalThis.G_DEBUG_CONFIGURATION}`); - this.logger.debug(`Mods enabled: ${globalThis.G_MODS_ENABLED}`); + this.logger.debug(`Server version: ${Program.SPT_VERSION || this.coreConfig.sptVersion} ${Program.COMMIT}`); + this.logger.debug(`Debug enabled: ${Program.DEBUG}`); + this.logger.debug(`Mods enabled: ${Program.MODS}`); } public getSurvey(sessionId: string): ISurveyResponseData { diff --git a/project/src/ide/build.json b/project/src/entry/build.json similarity index 70% rename from project/src/ide/build.json rename to project/src/entry/build.json index e02485fc..969969cd 100644 --- a/project/src/ide/build.json +++ b/project/src/entry/build.json @@ -1,4 +1,5 @@ { + "entryType": "LOCAL", "sptVersion": "", "commit": "", "buildTime": 0 diff --git a/project/src/entry/run.ts b/project/src/entry/run.ts new file mode 100644 index 00000000..5098ea15 --- /dev/null +++ b/project/src/entry/run.ts @@ -0,0 +1,7 @@ +import "reflect-metadata"; +import "source-map-support/register"; +import { Program } from "@spt/Program"; + +Program.initialize(); +const program = new Program(); +program.start(); diff --git a/project/src/global.d.ts b/project/src/global.d.ts deleted file mode 100644 index 6eed4137..00000000 --- a/project/src/global.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -export type {}; - -declare global { - var G_DEBUG_CONFIGURATION: boolean; - var G_RELEASE_CONFIGURATION: boolean; - var G_MODS_ENABLED: boolean; - var G_MODS_TRANSPILE_TS: boolean; - var G_LOG_REQUESTS: boolean; - var G_WATERMARK_ENABLED: boolean; - - var G_SPTVERSION: string; - var G_COMMIT: string; - var G_BUILDTIME: number; -} diff --git a/project/src/ide/BleedingEdgeEntry.ts b/project/src/ide/BleedingEdgeEntry.ts deleted file mode 100644 index 32a4111b..00000000 --- a/project/src/ide/BleedingEdgeEntry.ts +++ /dev/null @@ -1,19 +0,0 @@ -import "reflect-metadata"; -import "source-map-support/register"; - -import { Program } from "@spt/Program"; -import * as buildInfo from "./build.json"; - -globalThis.G_DEBUG_CONFIGURATION = true; -globalThis.G_RELEASE_CONFIGURATION = true; -globalThis.G_MODS_ENABLED = false; -globalThis.G_MODS_TRANSPILE_TS = true; -globalThis.G_LOG_REQUESTS = true; -globalThis.G_WATERMARK_ENABLED = true; - -globalThis.G_SPTVERSION = buildInfo.sptVersion; -globalThis.G_COMMIT = buildInfo.commit; -globalThis.G_BUILDTIME = buildInfo.buildTime; - -const program = new Program(); -program.start(); diff --git a/project/src/ide/BleedingEdgeModsEntry.ts b/project/src/ide/BleedingEdgeModsEntry.ts deleted file mode 100644 index 8595b53c..00000000 --- a/project/src/ide/BleedingEdgeModsEntry.ts +++ /dev/null @@ -1,19 +0,0 @@ -import "reflect-metadata"; -import "source-map-support/register"; - -import { Program } from "@spt/Program"; -import * as buildInfo from "./build.json"; - -globalThis.G_DEBUG_CONFIGURATION = true; -globalThis.G_RELEASE_CONFIGURATION = true; -globalThis.G_MODS_ENABLED = true; -globalThis.G_MODS_TRANSPILE_TS = true; -globalThis.G_LOG_REQUESTS = true; -globalThis.G_WATERMARK_ENABLED = true; - -globalThis.G_SPTVERSION = buildInfo.sptVersion; -globalThis.G_COMMIT = buildInfo.commit; -globalThis.G_BUILDTIME = buildInfo.buildTime; - -const program = new Program(); -program.start(); diff --git a/project/src/ide/DebugEntry.ts b/project/src/ide/DebugEntry.ts deleted file mode 100644 index 20e8136c..00000000 --- a/project/src/ide/DebugEntry.ts +++ /dev/null @@ -1,19 +0,0 @@ -import "reflect-metadata"; -import "source-map-support/register"; - -import { Program } from "@spt/Program"; -import * as buildInfo from "./build.json"; - -globalThis.G_DEBUG_CONFIGURATION = true; -globalThis.G_RELEASE_CONFIGURATION = true; -globalThis.G_MODS_ENABLED = true; -globalThis.G_MODS_TRANSPILE_TS = true; -globalThis.G_LOG_REQUESTS = true; -globalThis.G_WATERMARK_ENABLED = false; - -globalThis.G_SPTVERSION = buildInfo.sptVersion; -globalThis.G_COMMIT = buildInfo.commit; -globalThis.G_BUILDTIME = buildInfo.buildTime; - -const program = new Program(); -program.start(); diff --git a/project/src/ide/ReleaseEntry.ts b/project/src/ide/ReleaseEntry.ts deleted file mode 100644 index b16252bf..00000000 --- a/project/src/ide/ReleaseEntry.ts +++ /dev/null @@ -1,19 +0,0 @@ -import "reflect-metadata"; -import "source-map-support/register"; - -import { Program } from "@spt/Program"; -import * as buildInfo from "./build.json"; - -globalThis.G_DEBUG_CONFIGURATION = false; -globalThis.G_RELEASE_CONFIGURATION = true; -globalThis.G_MODS_ENABLED = true; -globalThis.G_MODS_TRANSPILE_TS = true; -globalThis.G_LOG_REQUESTS = false; -globalThis.G_WATERMARK_ENABLED = false; - -globalThis.G_SPTVERSION = buildInfo.sptVersion; -globalThis.G_COMMIT = buildInfo.commit; -globalThis.G_BUILDTIME = buildInfo.buildTime; - -const program = new Program(); -program.start(); diff --git a/project/src/ide/TestEntry.ts b/project/src/ide/TestEntry.ts deleted file mode 100644 index e6513e3a..00000000 --- a/project/src/ide/TestEntry.ts +++ /dev/null @@ -1,22 +0,0 @@ -import "reflect-metadata"; -import "source-map-support/register"; - -import { Program } from "@spt/Program"; -// target run:profiler doesnt work with this here -// since this is the Test entry we can just remove -// it and leave those empty -// import * as buildInfo from "./build.json"; - -globalThis.G_DEBUG_CONFIGURATION = true; -globalThis.G_RELEASE_CONFIGURATION = false; -globalThis.G_MODS_ENABLED = true; -globalThis.G_MODS_TRANSPILE_TS = false; -globalThis.G_LOG_REQUESTS = true; -globalThis.G_WATERMARK_ENABLED = false; - -globalThis.G_SPTVERSION = ""; -globalThis.G_COMMIT = ""; -globalThis.G_BUILDTIME = 0; - -const program = new Program(); -program.start(); diff --git a/project/src/loaders/PostDBModLoader.ts b/project/src/loaders/PostDBModLoader.ts index ca7ed104..324907b8 100644 --- a/project/src/loaders/PostDBModLoader.ts +++ b/project/src/loaders/PostDBModLoader.ts @@ -1,3 +1,4 @@ +import { Program } from "@spt/Program"; import { OnLoad } from "@spt/di/OnLoad"; import { BundleLoader } from "@spt/loaders/BundleLoader"; import { ModTypeCheck } from "@spt/loaders/ModTypeCheck"; @@ -21,7 +22,7 @@ export class PostDBModLoader implements OnLoad { ) {} public async onLoad(): Promise { - if (globalThis.G_MODS_ENABLED) { + if (Program.MODS) { this.container = this.preSptModLoader.getContainer(); await this.executeModsAsync(); this.addBundles(); diff --git a/project/src/loaders/PostSptModLoader.ts b/project/src/loaders/PostSptModLoader.ts index 448b9a4e..37d37676 100644 --- a/project/src/loaders/PostSptModLoader.ts +++ b/project/src/loaders/PostSptModLoader.ts @@ -1,3 +1,4 @@ +import { Program } from "@spt/Program"; import { ModTypeCheck } from "@spt/loaders/ModTypeCheck"; import { PreSptModLoader } from "@spt/loaders/PreSptModLoader"; import { IPostSptLoadMod } from "@spt/models/external/IPostSptLoadMod"; @@ -23,7 +24,7 @@ export class PostSptModLoader implements IModLoader { } public async load(): Promise { - if (globalThis.G_MODS_ENABLED) { + if (Program.MODS) { this.container = this.preSptModLoader.getContainer(); await this.executeModsAsync(); } diff --git a/project/src/loaders/PreSptModLoader.ts b/project/src/loaders/PreSptModLoader.ts index a96e5a76..4dc70c58 100644 --- a/project/src/loaders/PreSptModLoader.ts +++ b/project/src/loaders/PreSptModLoader.ts @@ -1,6 +1,7 @@ import { execSync } from "node:child_process"; import os from "node:os"; import path from "node:path"; +import { Program } from "@spt/Program"; import { ModLoadOrder } from "@spt/loaders/ModLoadOrder"; import { ModTypeCheck } from "@spt/loaders/ModTypeCheck"; import { IModDetails } from "@spt/models/eft/profile/ISptProfile"; @@ -49,7 +50,7 @@ export class PreSptModLoader implements IModLoader { } public async load(container: DependencyContainer): Promise { - if (globalThis.G_MODS_ENABLED) { + if (Program.MODS) { this.container = container; await this.importModsAsync(); await this.executeModsAsync(); @@ -285,7 +286,7 @@ export class PreSptModLoader implements IModLoader { * @returns True if compatible */ protected isModCombatibleWithSpt(mod: IPackageJsonData): boolean { - const sptVersion = globalThis.G_SPTVERSION || this.sptConfig.sptVersion; + const sptVersion = Program.SPT_VERSION || this.sptConfig.sptVersion; const modName = `${mod.author}-${mod.name}`; // Error and prevent loading If no sptVersion property exists @@ -396,8 +397,8 @@ export class PreSptModLoader implements IModLoader { const typeScriptFiles = this.vfs.getFilesOfType(`${modPath}src`, ".ts"); if (typeScriptFiles.length > 0) { - if (globalThis.G_MODS_TRANSPILE_TS) { - // compile ts into js if ts files exist and globalThis.G_MODS_TRANSPILE_TS is set to true + if (Program.COMPILED) { + // compile ts into js if ts files exist and the program is compiled await this.modCompilerService.compileMod(mod, modPath, typeScriptFiles); } else { // rename the mod entry point to .ts if it's set to .js because G_MODS_TRANSPILE_TS is set to false @@ -455,10 +456,7 @@ export class PreSptModLoader implements IModLoader { this.localisationService.getText("modloader-installing_external_dependencies_disabled", { name: pkg.name, author: pkg.author, - configPath: path.join( - globalThis.G_RELEASE_CONFIGURATION ? "SPT_Data/Server/configs" : "assets/configs", - "core.json", - ), + configPath: path.join(Program.COMPILED ? "SPT_Data/Server/configs" : "assets/configs", "core.json"), configOption: "autoInstallModDependencies", }), ); @@ -480,7 +478,7 @@ export class PreSptModLoader implements IModLoader { const pnpmPath = path.join( process.cwd(), - globalThis.G_RELEASE_CONFIGURATION ? "SPT_Data/Server/@pnpm/exe" : "node_modules/@pnpm/exe", + Program.COMPILED ? "SPT_Data/Server/@pnpm/exe" : "node_modules/@pnpm/exe", os.platform() === "win32" ? "pnpm.exe" : "pnpm", ); diff --git a/project/src/servers/ConfigServer.ts b/project/src/servers/ConfigServer.ts index 7c553317..763d482b 100644 --- a/project/src/servers/ConfigServer.ts +++ b/project/src/servers/ConfigServer.ts @@ -1,3 +1,4 @@ +import { Program } from "@spt/Program"; import { ConfigTypes } from "@spt/models/enums/ConfigTypes"; import { ILogger } from "@spt/models/spt/utils/ILogger"; import { JsonUtil } from "@spt/utils/JsonUtil"; @@ -33,7 +34,7 @@ export class ConfigServer { this.logger.debug("Importing configs..."); // Get all filepaths - const filepath = globalThis.G_RELEASE_CONFIGURATION ? "SPT_Data/Server/configs/" : "./assets/configs/"; + const filepath = Program.COMPILED ? "SPT_Data/Server/configs/" : "./assets/configs/"; const files = this.vfs.getFiles(filepath); // Add file content to result @@ -59,7 +60,7 @@ export class ConfigServer { } } - this.logger.info(`Commit hash: ${globalThis.G_COMMIT || "DEBUG"}`); - this.logger.info(`Build date: ${globalThis.G_BUILDTIME || "DEBUG"}`); + this.logger.info(`Commit hash: ${Program.COMMIT || "DEBUG"}`); + this.logger.info(`Build date: ${Program.BUILD_TIME || "DEBUG"}`); } } diff --git a/project/src/servers/WebSocketServer.ts b/project/src/servers/WebSocketServer.ts index d8cd3886..13d3bd4e 100644 --- a/project/src/servers/WebSocketServer.ts +++ b/project/src/servers/WebSocketServer.ts @@ -1,4 +1,5 @@ import http, { IncomingMessage } from "node:http"; +import { Program } from "@spt/Program"; import { HttpServerHelper } from "@spt/helpers/HttpServerHelper"; import type { ILogger } from "@spt/models/spt/utils/ILogger"; import { IWebSocketConnectionHandler } from "@spt/servers/ws/IWebSocketConnectionHandler"; @@ -48,7 +49,7 @@ export class WebSocketServer { return this.localisationService.getRandomTextThatMatchesPartialKey("server_start_meme_"); } - return globalThis.G_RELEASE_CONFIGURATION + return Program.COMPILED ? `${this.localisationService.getText("server_start_success")}!` : this.localisationService.getText("server_start_success"); } diff --git a/project/src/servers/http/SptHttpListener.ts b/project/src/servers/http/SptHttpListener.ts index 8d9c9063..e8dff0d6 100644 --- a/project/src/servers/http/SptHttpListener.ts +++ b/project/src/servers/http/SptHttpListener.ts @@ -1,5 +1,7 @@ import { IncomingHttpHeaders, IncomingMessage, ServerResponse } from "node:http"; +import util from "node:util"; import zlib from "node:zlib"; +import { EntryType, Program } from "@spt/Program"; import { Serializer } from "@spt/di/Serializer"; import { ILogger } from "@spt/models/spt/utils/ILogger"; import { HttpRouter } from "@spt/routers/HttpRouter"; @@ -8,7 +10,6 @@ import { LocalisationService } from "@spt/services/LocalisationService"; import { HttpResponseUtil } from "@spt/utils/HttpResponseUtil"; import { JsonUtil } from "@spt/utils/JsonUtil"; import { inject, injectAll, injectable } from "tsyringe"; -import util from "node:util"; const zlibInflate = util.promisify(zlib.inflate); const zlibDeflate = util.promisify(zlib.deflate); @@ -132,7 +133,7 @@ export class SptHttpListener implements IHttpListener { */ protected logRequest(req: IncomingMessage, output: string): void { // - if (globalThis.G_LOG_REQUESTS) { + if (Program.ENTRY_TYPE !== EntryType.RELEASE) { const log = new Response(req.method, output); this.requestsLogger.info(`RESPONSE=${this.jsonUtil.serialize(log)}`); } @@ -140,7 +141,7 @@ export class SptHttpListener implements IHttpListener { public async getResponse(sessionID: string, req: IncomingMessage, body: Buffer | undefined): Promise { const info = this.getBodyInfo(body, req.url); - if (globalThis.G_LOG_REQUESTS) { + if (Program.ENTRY_TYPE !== EntryType.RELEASE) { // Parse quest info into object const data = typeof info === "object" ? info : this.jsonUtil.deserialize(info); diff --git a/project/src/services/LocalisationService.ts b/project/src/services/LocalisationService.ts index bf10d6c5..f02424b8 100644 --- a/project/src/services/LocalisationService.ts +++ b/project/src/services/LocalisationService.ts @@ -1,4 +1,5 @@ import path from "node:path"; +import { Program } from "@spt/Program"; import { ILogger } from "@spt/models/spt/utils/ILogger"; import { DatabaseServer } from "@spt/servers/DatabaseServer"; import { LocaleService } from "@spt/services/LocaleService"; @@ -21,9 +22,7 @@ export class LocalisationService { ) { const localeFileDirectory = path.join( process.cwd(), - globalThis.G_RELEASE_CONFIGURATION - ? "SPT_Data/Server/database/locales/server" - : "./assets/database/locales/server", + Program.COMPILED ? "SPT_Data/Server/database/locales/server" : "./assets/database/locales/server", ); this.i18n = new I18n({ locales: this.localeService.getServerSupportedLocales(), diff --git a/project/src/services/ModCompilerService.ts b/project/src/services/ModCompilerService.ts index 858d59ce..25079c95 100644 --- a/project/src/services/ModCompilerService.ts +++ b/project/src/services/ModCompilerService.ts @@ -2,6 +2,7 @@ import fs from "node:fs"; import path from "node:path"; import { inject, injectable } from "tsyringe"; import { ScriptTarget, ModuleKind, ModuleResolutionKind, transpileModule, CompilerOptions } from "typescript"; +import { Program } from "@spt/Program"; import type { ILogger } from "@spt/models/spt/utils/ILogger"; import { ModHashCacheService } from "@spt/services/cache/ModHashCacheService"; import { VFS } from "@spt/utils/VFS"; @@ -94,8 +95,7 @@ export class ModCompilerService const text = fs.readFileSync(filePath).toString(); let replacedText: string; - if (globalThis.G_RELEASE_CONFIGURATION) - { + if (Program.COMPILED) { replacedText = text.replace(/(@spt)/g, `${baseDir}/obj`); for (const dependency of this.serverDependencies) { diff --git a/project/src/utils/App.ts b/project/src/utils/App.ts index 7c9f9082..17d00646 100644 --- a/project/src/utils/App.ts +++ b/project/src/utils/App.ts @@ -1,4 +1,5 @@ import os from "node:os"; +import { Program } from "@spt/Program"; import { OnLoad } from "@spt/di/OnLoad"; import { OnUpdate } from "@spt/di/OnUpdate"; import { ConfigTypes } from "@spt/models/enums/ConfigTypes"; @@ -6,11 +7,11 @@ import { ICoreConfig } from "@spt/models/spt/config/ICoreConfig"; import { ILogger } from "@spt/models/spt/utils/ILogger"; import { ConfigServer } from "@spt/servers/ConfigServer"; import { HttpServer } from "@spt/servers/HttpServer"; +import { DatabaseService } from "@spt/services/DatabaseService"; import { LocalisationService } from "@spt/services/LocalisationService"; import { EncodingUtil } from "@spt/utils/EncodingUtil"; import { TimeUtil } from "@spt/utils/TimeUtil"; import { inject, injectAll, injectable } from "tsyringe"; -import { DatabaseService } from "@spt/services/DatabaseService"; @injectable() export class App { @@ -40,13 +41,14 @@ export class App { this.logger.debug(`RAM: ${(os.totalmem() / 1024 / 1024 / 1024).toFixed(2)}GB`); this.logger.debug(`PATH: ${this.encodingUtil.toBase64(process.argv[0])}`); this.logger.debug(`PATH: ${this.encodingUtil.toBase64(process.execPath)}`); - this.logger.debug(`Server: ${globalThis.G_SPTVERSION || this.coreConfig.sptVersion}`); - if (globalThis.G_BUILDTIME) { - this.logger.debug(`Date: ${globalThis.G_BUILDTIME}`); + this.logger.debug(`Server: ${Program.SPT_VERSION || this.coreConfig.sptVersion}`); + + if (Program.BUILD_TIME) { + this.logger.debug(`Date: ${Program.BUILD_TIME}`); } - if (globalThis.G_COMMIT) { - this.logger.debug(`Commit: ${globalThis.G_COMMIT}`); + if (Program.COMMIT) { + this.logger.debug(`Commit: ${Program.COMMIT}`); } for (const onLoad of this.onLoadComponents) { diff --git a/project/src/utils/DatabaseImporter.ts b/project/src/utils/DatabaseImporter.ts index 53a8d1f8..58410dfd 100644 --- a/project/src/utils/DatabaseImporter.ts +++ b/project/src/utils/DatabaseImporter.ts @@ -1,3 +1,4 @@ +import { Program } from "@spt/Program"; import { OnLoad } from "@spt/di/OnLoad"; import { ConfigTypes } from "@spt/models/enums/ConfigTypes"; import { IHttpConfig } from "@spt/models/spt/config/IHttpConfig"; @@ -41,13 +42,13 @@ export class DatabaseImporter implements OnLoad { * @returns path to data */ public getSptDataPath(): string { - return globalThis.G_RELEASE_CONFIGURATION ? "SPT_Data/Server/" : "./assets/"; + return Program.COMPILED ? "SPT_Data/Server/" : "./assets/"; } public async onLoad(): Promise { this.filepath = this.getSptDataPath(); - if (globalThis.G_RELEASE_CONFIGURATION) { + if (Program.COMPILED) { try { // Reading the dynamic SHA1 file const file = "checks.dat"; @@ -104,7 +105,7 @@ export class DatabaseImporter implements OnLoad { protected onReadValidate(fileWithPath: string, data: string): void { // Validate files - if (globalThis.G_RELEASE_CONFIGURATION && this.hashedFile && !this.validateFile(fileWithPath, data)) { + if (Program.COMPILED && this.hashedFile && !this.validateFile(fileWithPath, data)) { this.valid = VaildationResult.FAILED; } } diff --git a/project/src/utils/Watermark.ts b/project/src/utils/Watermark.ts index 3773cd48..b68e94e0 100644 --- a/project/src/utils/Watermark.ts +++ b/project/src/utils/Watermark.ts @@ -1,3 +1,4 @@ +import { Program } from "@spt/Program"; import { ConfigTypes } from "@spt/models/enums/ConfigTypes"; import { ICoreConfig } from "@spt/models/spt/config/ICoreConfig"; import { LogTextColor } from "@spt/models/spt/logging/LogTextColor"; @@ -78,10 +79,10 @@ export class Watermark { this.text = [this.versionLabel]; this.text = [...this.text, ...description]; - if (globalThis.G_DEBUG_CONFIGURATION) { + if (Program.DEBUG) { this.text = this.text.concat([...warning]); } - if (!globalThis.G_MODS_ENABLED) { + if (!Program.MODS) { this.text = this.text.concat([...modding]); } @@ -104,8 +105,8 @@ export class Watermark { * @returns string */ public getVersionTag(withEftVersion = false): string { - const sptVersion = globalThis.G_SPTVERSION || this.sptConfig.sptVersion; - const versionTag = globalThis.G_DEBUG_CONFIGURATION + const sptVersion = Program.SPT_VERSION || this.sptConfig.sptVersion; + const versionTag = Program.DEBUG ? `${sptVersion} - ${this.localisationService.getText("bleeding_edge_build")}` : sptVersion; @@ -123,10 +124,10 @@ export class Watermark { * @returns string */ public getInGameVersionLabel(): string { - const sptVersion = globalThis.G_SPTVERSION || this.sptConfig.sptVersion; - const versionTag = globalThis.G_DEBUG_CONFIGURATION - ? `${sptVersion} - BLEEDINGEDGE ${globalThis.G_COMMIT?.slice(0, 6) ?? ""}` - : `${sptVersion} - ${globalThis.G_COMMIT?.slice(0, 6) ?? ""}`; + const sptVersion = Program.SPT_VERSION || this.sptConfig.sptVersion; + const versionTag = Program.DEBUG + ? `${sptVersion} - BLEEDINGEDGE ${Program.COMMIT?.slice(0, 6) ?? ""}` + : `${sptVersion} - ${Program.COMMIT?.slice(0, 6) ?? ""}`; return `${this.sptConfig.projectName} ${versionTag}`; } @@ -138,7 +139,9 @@ export class Watermark { /** Reset console cursor to top */ protected resetCursor(): void { - process.stdout.write("\u001B[2J\u001B[0;0f"); + if (!Program.COMPILED) { + process.stdout.write("\u001B[2J\u001B[0;0f"); + } } /** Draw the watermark */ diff --git a/project/src/utils/logging/AbstractWinstonLogger.ts b/project/src/utils/logging/AbstractWinstonLogger.ts index b496bf9d..428edaca 100644 --- a/project/src/utils/logging/AbstractWinstonLogger.ts +++ b/project/src/utils/logging/AbstractWinstonLogger.ts @@ -2,6 +2,7 @@ import crypto from "node:crypto"; import fs from "node:fs"; import path from "node:path"; import { promisify } from "node:util"; +import { Program } from "@spt/Program"; import { IDaum } from "@spt/models/eft/itemEvent/IItemEventRouterRequest"; import { LogBackgroundColor } from "@spt/models/spt/logging/LogBackgroundColor"; import { LogTextColor } from "@spt/models/spt/logging/LogTextColor"; @@ -37,7 +38,7 @@ export abstract class AbstractWinstonLogger implements ILogger { constructor(protected asyncQueue: IAsyncQueue) { this.filePath = path.join(this.getFilePath(), this.getFileName()); this.writeFilePromisify = promisify(fs.writeFile); - this.showDebugInConsole = globalThis.G_DEBUG_CONFIGURATION; + this.showDebugInConsole = Program.DEBUG; if (!fs.existsSync(this.getFilePath())) { fs.mkdirSync(this.getFilePath(), { recursive: true }); }