From 27f7eb8caf68debbd74cef41aca37edabd83a4e5 Mon Sep 17 00:00:00 2001 From: TheSparta Date: Tue, 31 Oct 2023 16:15:27 +0000 Subject: [PATCH 01/41] Allow decorators on the constructor parameters --- project/biome.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/project/biome.json b/project/biome.json index ded78fca..9772227d 100644 --- a/project/biome.json +++ b/project/biome.json @@ -1,5 +1,10 @@ { "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", + "javascript": { + "parser": { + "unsafeParameterDecoratorsEnabled": true + } + }, "linter": { "enabled": true, "rules": { From 0308ae4bf79f9132197f6200c3cc4f7642254634 Mon Sep 17 00:00:00 2001 From: TheSparta Date: Tue, 31 Oct 2023 16:23:00 +0000 Subject: [PATCH 02/41] fixed lint/style/useEnumInitializers --- project/src/context/ContextVariableType.ts | 8 ++++---- project/src/utils/DatabaseImporter.ts | 10 +++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/project/src/context/ContextVariableType.ts b/project/src/context/ContextVariableType.ts index b838d193..86fea151 100644 --- a/project/src/context/ContextVariableType.ts +++ b/project/src/context/ContextVariableType.ts @@ -1,11 +1,11 @@ export enum ContextVariableType { /** Logged in users session id */ - SESSION_ID, + SESSION_ID = 0, /** Currently acive raid information */ - RAID_CONFIGURATION, + RAID_CONFIGURATION = 1, /** Timestamp when client first connected */ - CLIENT_START_TIMESTAMP, + CLIENT_START_TIMESTAMP = 2, /** When player is loading into map and loot is requested */ - REGISTER_PLAYER_REQUEST + REGISTER_PLAYER_REQUEST = 3 } \ No newline at end of file diff --git a/project/src/utils/DatabaseImporter.ts b/project/src/utils/DatabaseImporter.ts index 5eba10b5..8a88ec4d 100644 --- a/project/src/utils/DatabaseImporter.ts +++ b/project/src/utils/DatabaseImporter.ts @@ -197,8 +197,8 @@ export class DatabaseImporter implements OnLoad enum VaildationResult { - SUCCESS, - FAILED, - NOT_FOUND, - UNDEFINED -} \ No newline at end of file + SUCCESS = 0, + FAILED = 1, + NOT_FOUND = 2, + UNDEFINED = 3 +} From 40a9ed41028826f3ba012e0c3822e352628458aa Mon Sep 17 00:00:00 2001 From: TheSparta Date: Tue, 31 Oct 2023 16:23:39 +0000 Subject: [PATCH 03/41] fixed lint/complexity/noUselessConstructor --- project/src/di/Router.ts | 8 -------- project/src/routers/save_load/HealthSaveLoadRouter.ts | 5 ----- project/src/routers/save_load/InraidSaveLoadRouter.ts | 5 ----- project/src/routers/save_load/InsuranceSaveLoadRouter.ts | 5 ----- project/src/routers/save_load/ProfileSaveLoadRouter.ts | 5 ----- 5 files changed, 28 deletions(-) diff --git a/project/src/di/Router.ts b/project/src/di/Router.ts index 3db0e32d..397b5385 100644 --- a/project/src/di/Router.ts +++ b/project/src/di/Router.ts @@ -79,10 +79,6 @@ export class DynamicRouter extends Router // So instead I added the definition export class ItemEventRouterDefinition extends Router { - constructor() - { - super(); - } // eslint-disable-next-line @typescript-eslint/no-unused-vars public handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse { @@ -92,10 +88,6 @@ export class ItemEventRouterDefinition extends Router export class SaveLoadRouter extends Router { - constructor() - { - super(); - } // eslint-disable-next-line @typescript-eslint/no-unused-vars public handleLoad(profile: IAkiProfile): IAkiProfile { diff --git a/project/src/routers/save_load/HealthSaveLoadRouter.ts b/project/src/routers/save_load/HealthSaveLoadRouter.ts index 3ebb5506..9de28d57 100644 --- a/project/src/routers/save_load/HealthSaveLoadRouter.ts +++ b/project/src/routers/save_load/HealthSaveLoadRouter.ts @@ -6,11 +6,6 @@ import { IAkiProfile } from "@spt-aki/models/eft/profile/IAkiProfile"; @injectable() export class HealthSaveLoadRouter extends SaveLoadRouter { - constructor() - { - super(); - } - public override getHandledRoutes(): HandledRoute[] { return [ diff --git a/project/src/routers/save_load/InraidSaveLoadRouter.ts b/project/src/routers/save_load/InraidSaveLoadRouter.ts index 6b6c2441..46d84a59 100644 --- a/project/src/routers/save_load/InraidSaveLoadRouter.ts +++ b/project/src/routers/save_load/InraidSaveLoadRouter.ts @@ -6,11 +6,6 @@ import { IAkiProfile } from "@spt-aki/models/eft/profile/IAkiProfile"; @injectable() export class InraidSaveLoadRouter extends SaveLoadRouter { - constructor() - { - super(); - } - public override getHandledRoutes(): HandledRoute[] { return [ diff --git a/project/src/routers/save_load/InsuranceSaveLoadRouter.ts b/project/src/routers/save_load/InsuranceSaveLoadRouter.ts index fc1170e1..4137b8e1 100644 --- a/project/src/routers/save_load/InsuranceSaveLoadRouter.ts +++ b/project/src/routers/save_load/InsuranceSaveLoadRouter.ts @@ -6,11 +6,6 @@ import { IAkiProfile } from "@spt-aki/models/eft/profile/IAkiProfile"; @injectable() export class InsuranceSaveLoadRouter extends SaveLoadRouter { - constructor() - { - super(); - } - public override getHandledRoutes(): HandledRoute[] { return [ diff --git a/project/src/routers/save_load/ProfileSaveLoadRouter.ts b/project/src/routers/save_load/ProfileSaveLoadRouter.ts index af7725a1..75ae8d91 100644 --- a/project/src/routers/save_load/ProfileSaveLoadRouter.ts +++ b/project/src/routers/save_load/ProfileSaveLoadRouter.ts @@ -7,11 +7,6 @@ import { IAkiProfile } from "@spt-aki/models/eft/profile/IAkiProfile"; @injectable() export class ProfileSaveLoadRouter extends SaveLoadRouter { - constructor() - { - super(); - } - public override getHandledRoutes(): HandledRoute[] { return [ From 3eee163aae1d35bed6af10aa1b82c8b779336696 Mon Sep 17 00:00:00 2001 From: TheSparta Date: Tue, 31 Oct 2023 17:46:14 +0000 Subject: [PATCH 04/41] fixed lint/complexity/noForEach --- .../src/controllers/InsuranceController.ts | 32 +++++++++++-------- project/src/generators/LocationGenerator.ts | 5 ++- project/src/generators/LootGenerator.ts | 10 +++--- project/src/helpers/AssortHelper.ts | 8 ++++- project/src/helpers/InRaidHelper.ts | 10 +++--- project/src/loaders/PreAkiModLoader.ts | 9 ++++-- project/src/models/external/HttpFramework.ts | 4 +-- project/src/routers/HttpRouter.ts | 4 +-- .../src/services/BotGenerationCacheService.ts | 8 ++--- project/src/services/ProfileFixerService.ts | 8 ++--- project/src/services/RagfairOfferService.ts | 7 ++-- project/src/utils/RagfairOfferHolder.ts | 10 ++++-- project/src/utils/collections/queue/Queue.ts | 5 ++- 13 files changed, 74 insertions(+), 46 deletions(-) diff --git a/project/src/controllers/InsuranceController.ts b/project/src/controllers/InsuranceController.ts index 7f85703f..6393f9db 100644 --- a/project/src/controllers/InsuranceController.ts +++ b/project/src/controllers/InsuranceController.ts @@ -120,7 +120,7 @@ export class InsuranceController this.logger.debug(`Processing ${insuranceDetails.length} insurance packages, which includes a total of ${this.countAllInsuranceItems(insuranceDetails)} items, in profile ${sessionID}`); // Iterate over each of the insurance packages. - insuranceDetails.forEach(insured => + for (const insured of insuranceDetails) { // Find items that should be deleted from the insured items. const itemsToDelete = this.findItemsToDelete(insured); @@ -136,7 +136,7 @@ export class InsuranceController // Remove the fully processed insurance package from the profile. this.removeInsurancePackageFromProfile(sessionID, insured.messageContent.systemData); - }); + } } /** @@ -216,7 +216,10 @@ export class InsuranceController protected populateItemsMap(insured: Insurance): Map { const itemsMap = new Map(); - insured.items.forEach(item => itemsMap.set(item._id, item)); + for (const item of insured.items) + { + itemsMap.set(item._id, item); + } return itemsMap; } @@ -311,7 +314,10 @@ export class InsuranceController const allChildrenAreAttachments = directChildren.every(child => this.itemHelper.isAttachmentAttached(child)); if (allChildrenAreAttachments) { - itemAndChildren.forEach(item => toDelete.add(item._id)); + for (const item of itemAndChildren) + { + toDelete.add(item._id); + } } } } @@ -327,7 +333,7 @@ export class InsuranceController */ protected processAttachments(mainParentToAttachmentsMap: Map, itemsMap: Map, traderId: string, toDelete: Set): void { - mainParentToAttachmentsMap.forEach((attachmentItems, parentId) => + for (const [ parentId, attachmentItems ] of mainParentToAttachmentsMap) { // Log the parent item's name. const parentItem = itemsMap.get(parentId); @@ -336,7 +342,7 @@ export class InsuranceController // Process the attachments for this individual parent item. this.processAttachmentByParent(attachmentItems, traderId, toDelete); - }); + } } /** @@ -383,10 +389,10 @@ export class InsuranceController */ protected logAttachmentsDetails(attachments: EnrichedItem[]): void { - attachments.forEach(({ name, maxPrice }) => + for ( const attachment of attachments) { - this.logger.debug(`Child Item - Name: ${name}, Max Price: ${maxPrice}`); - }); + this.logger.debug(`Child Item - Name: ${attachment.name}, Max Price: ${attachment.maxPrice}`); + } } /** @@ -413,7 +419,7 @@ export class InsuranceController { const valuableToDelete = attachments.slice(0, successfulRolls).map(({ _id }) => _id); - valuableToDelete.forEach(attachmentsId => + for (const attachmentsId of valuableToDelete) { const valuableChild = attachments.find(({ _id }) => _id === attachmentsId); if (valuableChild) @@ -422,7 +428,7 @@ export class InsuranceController this.logger.debug(`Marked for removal - Child Item: ${name}, Max Price: ${maxPrice}`); toDelete.add(attachmentsId); } - }); + } } /** @@ -448,7 +454,7 @@ export class InsuranceController { const hideoutParentId = this.fetchHideoutItemParent(insured.items); - insured.items.forEach(item => + for (const item of insured.items) { // Check if the item's parent exists in the insured items list. const parentExists = insured.items.some(parentItem => parentItem._id === item.parentId); @@ -460,7 +466,7 @@ export class InsuranceController item.slotId = "hideout"; delete item.location; } - }); + } } /** diff --git a/project/src/generators/LocationGenerator.ts b/project/src/generators/LocationGenerator.ts index e8f6e9b3..5f185851 100644 --- a/project/src/generators/LocationGenerator.ts +++ b/project/src/generators/LocationGenerator.ts @@ -237,7 +237,10 @@ export class LocationGenerator // Create probability array with all possible container ids in this group and their relataive probability of spawning const containerDistribution = new ProbabilityObjectArray(this.mathUtil, this.jsonUtil); - containerIds.forEach(x => containerDistribution.push(new ProbabilityObject(x, containerData.containerIdsWithProbability[x]))); + for (const containerId of containerIds) + { + containerDistribution.push(new ProbabilityObject(containerId, containerData.containerIdsWithProbability[containerId])); + } chosenContainerIds.push(...containerDistribution.draw(containerData.chosenCount)); diff --git a/project/src/generators/LootGenerator.ts b/project/src/generators/LootGenerator.ts index f013c7d9..fe0a3b9f 100644 --- a/project/src/generators/LootGenerator.ts +++ b/project/src/generators/LootGenerator.ts @@ -54,13 +54,13 @@ export class LootGenerator const itemTypeCounts = this.initItemLimitCounter(options.itemLimits); const tables = this.databaseServer.getTables(); - const itemBlacklist = new Set(this.itemFilterService.getBlacklistedItems()); - - options.itemBlacklist.forEach(itemBlacklist.add, itemBlacklist); - + const itemBlacklist = new Set([...this.itemFilterService.getBlacklistedItems(), ...options.itemBlacklist]); if (!options.allowBossItems) { - this.itemFilterService.getBossItems().forEach(itemBlacklist.add, itemBlacklist); + for (const bossItem of this.itemFilterService.getBossItems()) + { + itemBlacklist.add(bossItem); + } } // Handle sealed weapon containers diff --git a/project/src/helpers/AssortHelper.ts b/project/src/helpers/AssortHelper.ts index 8026ab7b..43ac41bb 100644 --- a/project/src/helpers/AssortHelper.ts +++ b/project/src/helpers/AssortHelper.ts @@ -127,7 +127,13 @@ export class AssortHelper if (assort.barter_scheme[itemID] && flea) { - assort.barter_scheme[itemID].forEach(b => b.forEach(br => br.sptQuestLocked = true)); + for (const barterSchemes of assort.barter_scheme[itemID]) + { + for (const barterScheme of barterSchemes) + { + barterScheme.sptQuestLocked = true; + } + } return assort; } delete assort.barter_scheme[itemID]; diff --git a/project/src/helpers/InRaidHelper.ts b/project/src/helpers/InRaidHelper.ts index c2d7a707..a286c137 100644 --- a/project/src/helpers/InRaidHelper.ts +++ b/project/src/helpers/InRaidHelper.ts @@ -364,10 +364,10 @@ export class InRaidHelper && !(this.inRaidConfig.keepFiRSecureContainerOnDeath && this.itemHelper.itemIsInsideContainer(x, "SecuredContainer", postRaidProfile.Inventory.items)); }); - itemsToRemovePropertyFrom.forEach(item => + for (const item of itemsToRemovePropertyFrom) { delete item.upd.SpawnedInSession; - }); + } return postRaidProfile; } @@ -410,10 +410,10 @@ export class InRaidHelper { // Get inventory item ids to remove from players profile const itemIdsToDeleteFromProfile = this.getInventoryItemsLostOnDeath(pmcData).map(x => x._id); - itemIdsToDeleteFromProfile.forEach(x => + for (const itemId of itemIdsToDeleteFromProfile) { - this.inventoryHelper.removeItem(pmcData, x, sessionID); - }); + this.inventoryHelper.removeItem(pmcData, itemId, sessionID); + } // Remove contents of fast panel pmcData.Inventory.fastPanel = {}; diff --git a/project/src/loaders/PreAkiModLoader.ts b/project/src/loaders/PreAkiModLoader.ts index 8db771d1..630305c4 100644 --- a/project/src/loaders/PreAkiModLoader.ts +++ b/project/src/loaders/PreAkiModLoader.ts @@ -146,10 +146,10 @@ export class PreAkiModLoader implements IModLoader const modOrder = this.vfs.readFile(this.modOrderPath, { encoding: "utf8" }); try { - this.jsonUtil.deserialize(modOrder).order.forEach((mod: string, index: number) => + for (const [index, mod] of (this.jsonUtil.deserialize(modOrder).order as string[]).entries()) { this.order[mod] = index; - }); + } } catch (error) { @@ -210,7 +210,10 @@ export class PreAkiModLoader implements IModLoader validMods.sort((prev, next) => this.sortMods(prev, next, missingFromOrderJSON)); // log the missing mods from order.json - Object.keys(missingFromOrderJSON).forEach((missingMod) => (this.logger.debug(this.localisationService.getText("modloader-mod_order_missing_from_json", missingMod)))); + for (const missingMod of Object.keys(missingFromOrderJSON)) + { + this.logger.debug(this.localisationService.getText("modloader-mod_order_missing_from_json", missingMod)); + } // add mods for (const mod of validMods) diff --git a/project/src/models/external/HttpFramework.ts b/project/src/models/external/HttpFramework.ts index 8fabeac2..42a4c3d1 100644 --- a/project/src/models/external/HttpFramework.ts +++ b/project/src/models/external/HttpFramework.ts @@ -32,7 +32,7 @@ export const Listen = (basePath: string) => if (!handlersArray) return; // Add each flagged handler to the Record - handlersArray.forEach(({ handlerName, path, httpMethod }) => + for (const { handlerName, path, httpMethod } of handlersArray) { if (!this.handlers[httpMethod]) this.handlers[httpMethod] = {}; @@ -41,7 +41,7 @@ export const Listen = (basePath: string) => if (!path || path === "") this.handlers[httpMethod][`/${basePath}`] = this[handlerName]; this.handlers[httpMethod][`/${basePath}/${path}`] = this[handlerName]; } - }); + } // Cleanup the handlers list Base.prototype["handlers"] = []; diff --git a/project/src/routers/HttpRouter.ts b/project/src/routers/HttpRouter.ts index 407f2d7a..9267b590 100644 --- a/project/src/routers/HttpRouter.ts +++ b/project/src/routers/HttpRouter.ts @@ -15,7 +15,7 @@ export class HttpRouter protected groupBy(list: T[], keyGetter: (t:T) => string): Map { const map: Map = new Map(); - list.forEach((item) => + for (const item of list) { const key = keyGetter(item); const collection = map.get(key); @@ -27,7 +27,7 @@ export class HttpRouter { collection.push(item); } - }); + } return map; } diff --git a/project/src/services/BotGenerationCacheService.ts b/project/src/services/BotGenerationCacheService.ts index 2742a9bc..f77e64be 100644 --- a/project/src/services/BotGenerationCacheService.ts +++ b/project/src/services/BotGenerationCacheService.ts @@ -27,17 +27,17 @@ export class BotGenerationCacheService */ public storeBots(key: string, botsToStore: IBotBase[]): void { - botsToStore.forEach(e => + for (const bot of botsToStore) { if (this.storedBots.has(key)) { - this.storedBots.get(key).unshift(e); + this.storedBots.get(key).unshift(bot); } else { - this.storedBots.set(key, [e]); + this.storedBots.set(key, [bot]); } - }); + } } /** diff --git a/project/src/services/ProfileFixerService.ts b/project/src/services/ProfileFixerService.ts index 0a819231..de0a45d7 100644 --- a/project/src/services/ProfileFixerService.ts +++ b/project/src/services/ProfileFixerService.ts @@ -383,14 +383,14 @@ export class ProfileFixerService protected getActiveRepeatableQuests(repeatableQuests: IPmcDataRepeatableQuest[]): IRepeatableQuest[] { let activeQuests = []; - repeatableQuests?.forEach(x => + for (const repeatableQuest of repeatableQuests) { - if (x.activeQuests.length > 0) + if (repeatableQuest.activeQuests.length > 0) { // daily/weekly collection has active quests in them, add to array and return - activeQuests = activeQuests.concat(x.activeQuests); + activeQuests = activeQuests.concat(repeatableQuest.activeQuests); } - }); + } return activeQuests; } diff --git a/project/src/services/RagfairOfferService.ts b/project/src/services/RagfairOfferService.ts index 07feab5b..e67b659f 100644 --- a/project/src/services/RagfairOfferService.ts +++ b/project/src/services/RagfairOfferService.ts @@ -187,9 +187,10 @@ export class RagfairOfferService public expireStaleOffers(): void { const time = this.timeUtil.getTimestamp(); - this.ragfairOfferHandler - .getStaleOffers(time) - .forEach(o => this.processStaleOffer(o)); + for (const staleOffer of this.ragfairOfferHandler.getStaleOffers(time)) + { + this.processStaleOffer(staleOffer); + } } /** diff --git a/project/src/utils/RagfairOfferHolder.ts b/project/src/utils/RagfairOfferHolder.ts index 86861ded..75491e5f 100644 --- a/project/src/utils/RagfairOfferHolder.ts +++ b/project/src/utils/RagfairOfferHolder.ts @@ -51,7 +51,10 @@ export class RagfairOfferHolder public addOffers(offers: Array): void { - offers.forEach(o => this.addOffer(o)); + for (const offer of offers) + { + this.addOffer(offer); + } } public addOffer(offer: IRagfairOffer): void @@ -76,7 +79,10 @@ export class RagfairOfferHolder public removeOffers(offers: Array): void { - offers.forEach(o => this.removeOffer(o)); + for (const offer of offers) + { + this.removeOffer(offer); + } } public removeOfferByTrader(traderId: string): void diff --git a/project/src/utils/collections/queue/Queue.ts b/project/src/utils/collections/queue/Queue.ts index 607c08c5..4d632372 100644 --- a/project/src/utils/collections/queue/Queue.ts +++ b/project/src/utils/collections/queue/Queue.ts @@ -19,7 +19,10 @@ export class Queue public enqueueAll(elements: T[]): void { - elements.forEach(e => this.enqueue(e)); + for (const element of elements) + { + this.enqueue(element); + } } public dequeue(): T From 5b46e956c4c674ae6d454faf7238bdbec637f0bd Mon Sep 17 00:00:00 2001 From: TheSparta Date: Tue, 31 Oct 2023 22:52:09 +0000 Subject: [PATCH 05/41] fixed lint/complexity/useLiteralKeys --- project/src/callbacks/DialogueCallbacks.ts | 12 ++--- project/src/callbacks/ProfileCallbacks.ts | 22 ++++----- project/src/controllers/DialogueController.ts | 6 +-- project/src/controllers/HideoutController.ts | 13 +++-- .../src/controllers/InventoryController.ts | 2 +- project/src/controllers/LauncherController.ts | 2 +- project/src/controllers/MatchController.ts | 18 +++---- project/src/controllers/QuestController.ts | 9 ++-- .../generators/BotEquipmentModGenerator.ts | 8 ++-- .../src/generators/BotInventoryGenerator.ts | 28 +++++------ project/src/generators/BotWeaponGenerator.ts | 4 +- project/src/generators/LocationGenerator.ts | 2 +- .../src/generators/RagfairOfferGenerator.ts | 12 ++--- .../generators/RepeatableQuestGenerator.ts | 10 ++-- .../src/helpers/BotWeaponGeneratorHelper.ts | 2 +- project/src/helpers/HideoutHelper.ts | 2 +- project/src/helpers/HttpServerHelper.ts | 18 +++---- project/src/helpers/InventoryHelper.ts | 7 ++- project/src/helpers/ItemHelper.ts | 34 ++++++------- project/src/helpers/ProfileHelper.ts | 2 +- project/src/helpers/QuestHelper.ts | 16 ++++--- .../match/IGetRaidConfigurationRequestData.ts | 48 +++++++++---------- project/src/servers/WebSocketServer.ts | 2 +- project/src/services/MatchLocationService.ts | 32 ++++++------- project/src/utils/RandomUtil.ts | 8 ++-- project/src/utils/VFS.ts | 8 ++-- 26 files changed, 166 insertions(+), 161 deletions(-) diff --git a/project/src/callbacks/DialogueCallbacks.ts b/project/src/callbacks/DialogueCallbacks.ts index 63d15257..158c84dd 100644 --- a/project/src/callbacks/DialogueCallbacks.ts +++ b/project/src/callbacks/DialogueCallbacks.ts @@ -65,13 +65,13 @@ export class DialogueCallbacks implements OnUpdate DateTime: this.timeUtil.getTimestamp(), IsDeveloper: true, Regions: ["EUR"], - "VersionId": "bgkidft87ddd", - "Ip": "", - "Port": 0, - "Chats": [ + VersionId: "bgkidft87ddd", + Ip: "", + Port: 0, + Chats: [ { - "_id": "0", - "Members": 0 + _id: "0", + Members: 0 } ] }; diff --git a/project/src/callbacks/ProfileCallbacks.ts b/project/src/callbacks/ProfileCallbacks.ts index 0aba65d6..d461aa44 100644 --- a/project/src/callbacks/ProfileCallbacks.ts +++ b/project/src/callbacks/ProfileCallbacks.ts @@ -109,7 +109,7 @@ export class ProfileCallbacks return this.httpResponse.getBody(null, 256, "256 - "); } - return this.httpResponse.getBody({ "status": "ok" }); + return this.httpResponse.getBody({ status: "ok" }); } /** @@ -131,12 +131,12 @@ export class ProfileCallbacks maxPveCountExceeded: false, profiles: [ { - "profileid": `scav${sessionID}`, + profileid: `scav${sessionID}`, profileToken: null, - "status": "Free", - "sid": "", - "ip": "", - "port": 0, + status: "Free", + sid: "", + ip: "", + port: 0, version: "live", location: "bigmap", raidMode: "Online", @@ -145,12 +145,12 @@ export class ProfileCallbacks }, { - "profileid": `pmc${sessionID}`, + profileid: `pmc${sessionID}`, profileToken: null, - "status": "Free", - "sid": "", - "ip": "", - "port": 0 + status: "Free", + sid: "", + ip: "", + port: 0 } ] }; diff --git a/project/src/controllers/DialogueController.ts b/project/src/controllers/DialogueController.ts index 21c3a2f4..d50471a2 100644 --- a/project/src/controllers/DialogueController.ts +++ b/project/src/controllers/DialogueController.ts @@ -62,9 +62,9 @@ export class DialogueController { // Force a fake friend called SPT into friend list return { - "Friends": [this.getSptFriendData()], - "Ignore": [], - "InIgnoreList": [] + Friends: [this.getSptFriendData()], + Ignore: [], + InIgnoreList: [] }; } diff --git a/project/src/controllers/HideoutController.ts b/project/src/controllers/HideoutController.ts index e14c37d7..c7f58e1b 100644 --- a/project/src/controllers/HideoutController.ts +++ b/project/src/controllers/HideoutController.ts @@ -652,7 +652,10 @@ export class HideoutController let counterHoursCrafting = pmcData.BackendCounters[HideoutController.nameBackendCountersCrafting]; if (!counterHoursCrafting) { - pmcData.BackendCounters[HideoutController.nameBackendCountersCrafting] = { "id": HideoutController.nameBackendCountersCrafting, "value": 0 }; + pmcData.BackendCounters[HideoutController.nameBackendCountersCrafting] = { + id: HideoutController.nameBackendCountersCrafting, + value: 0 + }; counterHoursCrafting = pmcData.BackendCounters[HideoutController.nameBackendCountersCrafting]; } let hoursCrafting = counterHoursCrafting.value; @@ -856,10 +859,10 @@ export class HideoutController public handleQTEEventOutcome(sessionId: string, pmcData: IPmcData, request: IHandleQTEEventRequestData): IItemEventRouterResponse { // { - // "Action": "HideoutQuickTimeEvent", - // "results": [true, false, true, true, true, true, true, true, true, false, false, false, false, false, false], - // "id": "63b16feb5d012c402c01f6ef", - // "timestamp": 1672585349 + // Action: "HideoutQuickTimeEvent", + // results: [true, false, true, true, true, true, true, true, true, false, false, false, false, false, false], + // id: "63b16feb5d012c402c01f6ef", + // timestamp: 1672585349 // } // Skill changes are done in diff --git a/project/src/controllers/InventoryController.ts b/project/src/controllers/InventoryController.ts index 73ab6778..23f5a5b4 100644 --- a/project/src/controllers/InventoryController.ts +++ b/project/src/controllers/InventoryController.ts @@ -434,7 +434,7 @@ export class InventoryController { if (item._id && item._id === body.item) { - item.upd.Foldable = { "Folded": body.value }; + item.upd.Foldable = { Folded: body.value }; return this.eventOutputHolder.getOutput(sessionID); } } diff --git a/project/src/controllers/LauncherController.ts b/project/src/controllers/LauncherController.ts index 0e7bd5fb..6ead15e3 100644 --- a/project/src/controllers/LauncherController.ts +++ b/project/src/controllers/LauncherController.ts @@ -53,7 +53,7 @@ export class LauncherController protected getProfileDescriptions(): Record { return { - "Standard": this.localisationService.getText("launcher-profile_standard"), + Standard: this.localisationService.getText("launcher-profile_standard"), // eslint-disable-next-line @typescript-eslint/naming-convention "Left Behind": this.localisationService.getText("launcher-profile_leftbehind"), // eslint-disable-next-line @typescript-eslint/naming-convention diff --git a/project/src/controllers/MatchController.ts b/project/src/controllers/MatchController.ts index 319fe499..b0135193 100644 --- a/project/src/controllers/MatchController.ts +++ b/project/src/controllers/MatchController.ts @@ -109,17 +109,17 @@ export class MatchController // get list of players joining into the match output.profiles.push({ - "profileid": "TODO", + profileid: "TODO", profileToken: "TODO", - "status": "MatchWait", - "sid": "", - "ip": "", - "port": 0, - "version": "live", - "location": "TODO get location", + status: "MatchWait", + sid: "", + ip: "", + port: 0, + version: "live", + location: "TODO get location", raidMode: "Online", - "mode": "deathmatch", - "shortid": null, + mode: "deathmatch", + shortid: null, // eslint-disable-next-line @typescript-eslint/naming-convention additional_info: null }); diff --git a/project/src/controllers/QuestController.ts b/project/src/controllers/QuestController.ts index e5046c93..dd402187 100644 --- a/project/src/controllers/QuestController.ts +++ b/project/src/controllers/QuestController.ts @@ -740,7 +740,7 @@ export class QuestController let index = pmcData.Inventory.items.length; // Important: don't tell the client to remove the attachments, it will handle it - output.profileChanges[sessionID].items.del.push({ "_id": itemHandover.id }); + output.profileChanges[sessionID].items.del.push({ _id: itemHandover.id }); // Important: loop backward when removing items from the array we're looping on while (index-- > 0) @@ -805,8 +805,9 @@ export class QuestController } pmcData.BackendCounters[conditionId] = { - "id": conditionId, - "qid": questId, - "value": counterValue }; + id: conditionId, + qid: questId, + value: counterValue + }; } } \ No newline at end of file diff --git a/project/src/generators/BotEquipmentModGenerator.ts b/project/src/generators/BotEquipmentModGenerator.ts index eaffe1e6..04cb0194 100644 --- a/project/src/generators/BotEquipmentModGenerator.ts +++ b/project/src/generators/BotEquipmentModGenerator.ts @@ -613,10 +613,10 @@ export class BotEquipmentModGenerator protected createModItem(modId: string, modTpl: string, parentId: string, modSlot: string, modTemplate: ITemplateItem, botRole: string): Item { return { - "_id": modId, - "_tpl": modTpl, - "parentId": parentId, - "slotId": modSlot, + _id: modId, + _tpl: modTpl, + parentId: parentId, + slotId: modSlot, ...this.botGeneratorHelper.generateExtraPropertiesForItem(modTemplate, botRole) }; } diff --git a/project/src/generators/BotInventoryGenerator.ts b/project/src/generators/BotInventoryGenerator.ts index 7ff178ba..6da1395a 100644 --- a/project/src/generators/BotInventoryGenerator.ts +++ b/project/src/generators/BotInventoryGenerator.ts @@ -98,24 +98,24 @@ export class BotInventoryGenerator return { items: [ { - "_id": equipmentId, - "_tpl": equipmentTpl + _id: equipmentId, + _tpl: equipmentTpl }, { - "_id": stashId, - "_tpl": stashTpl + _id: stashId, + _tpl: stashTpl }, { - "_id": questRaidItemsId, - "_tpl": questRaidItemsTpl + _id: questRaidItemsId, + _tpl: questRaidItemsTpl }, { - "_id": questStashItemsId, - "_tpl": questStashItemsTpl + _id: questStashItemsId, + _tpl: questStashItemsTpl }, { - "_id": sortingTableId, - "_tpl": sortingTableTpl + _id: sortingTableId, + _tpl: sortingTableTpl } ], equipment: equipmentId, @@ -223,10 +223,10 @@ export class BotInventoryGenerator } const item = { - "_id": id, - "_tpl": equipmentItemTpl, - "parentId": inventory.equipment, - "slotId": equipmentSlot, + _id: id, + _tpl: equipmentItemTpl, + parentId: inventory.equipment, + slotId: equipmentSlot, ...this.botGeneratorHelper.generateExtraPropertiesForItem(itemTemplate[1], botRole) }; diff --git a/project/src/generators/BotWeaponGenerator.ts b/project/src/generators/BotWeaponGenerator.ts index 0708c56f..b3010744 100644 --- a/project/src/generators/BotWeaponGenerator.ts +++ b/project/src/generators/BotWeaponGenerator.ts @@ -261,8 +261,8 @@ export class BotWeaponGenerator const parentItem = preset._items[0]; preset._items[0] = { ...parentItem, ...{ - "parentId": weaponParentId, - "slotId": equipmentSlot, + parentId: weaponParentId, + slotId: equipmentSlot, ...this.botGeneratorHelper.generateExtraPropertiesForItem(itemTemplate, botRole) } }; diff --git a/project/src/generators/LocationGenerator.ts b/project/src/generators/LocationGenerator.ts index 5f185851..af25d0d3 100644 --- a/project/src/generators/LocationGenerator.ts +++ b/project/src/generators/LocationGenerator.ts @@ -372,7 +372,7 @@ export class LocationGenerator const rotation = result.rotation ? 1 : 0; items[0].slotId = "main"; - items[0].location = { "x": result.x, "y": result.y, "r": rotation }; + items[0].location = { x: result.x, y: result.y, r: rotation }; // Add loot to container before returning for (const item of items) diff --git a/project/src/generators/RagfairOfferGenerator.ts b/project/src/generators/RagfairOfferGenerator.ts index 6cf20278..612b71c2 100644 --- a/project/src/generators/RagfairOfferGenerator.ts +++ b/project/src/generators/RagfairOfferGenerator.ts @@ -635,36 +635,36 @@ export class RagfairOfferGenerator if (isRepairable && props.Durability > 0) { item.upd.Repairable = { - "Durability": props.Durability, - "MaxDurability": props.Durability + Durability: props.Durability, + MaxDurability: props.Durability }; } if (isMedkit && props.MaxHpResource > 0) { item.upd.MedKit = { - "HpResource": props.MaxHpResource + HpResource: props.MaxHpResource }; } if (isKey) { item.upd.Key = { - "NumberOfUsages": 0 + NumberOfUsages: 0 }; } if (isConsumable) { item.upd.FoodDrink = { - "HpPercent": props.MaxResource + HpPercent: props.MaxResource }; } if (isRepairKit) { item.upd.RepairKit = { - "Resource": props.MaxRepairResource + Resource: props.MaxRepairResource }; } diff --git a/project/src/generators/RepeatableQuestGenerator.ts b/project/src/generators/RepeatableQuestGenerator.ts index f85fe623..c0795a99 100644 --- a/project/src/generators/RepeatableQuestGenerator.ts +++ b/project/src/generators/RepeatableQuestGenerator.ts @@ -142,10 +142,10 @@ export class RepeatableQuestGenerator // a random combination of listed conditions can be required // possible conditions elements and their relative probability can be defined in QuestConfig.js // We use ProbabilityObjectArray to draw by relative probability. e.g. for targets: - // "targets": { - // "Savage": 7, - // "AnyPmc": 2, - // "bossBully": 0.5 + // targets: { + // Savage: 7, + // AnyPmc: 2, + // bossBully: 0.5 //} // higher is more likely. We define the difficulty to be the inverse of the relative probability. @@ -467,7 +467,7 @@ export class RepeatableQuestGenerator itemSelection = itemSelection.filter(x => this.itemHelper.getItemPrice(x[0]) < roublesBudget); // We also have the option to use whitelist and/or blacklist which is defined in repeatableQuests.json as - // [{"minPlayerLevel": 1, "itemIds": ["id1",...]}, {"minPlayerLevel": 15, "itemIds": ["id3",...]}] + // [{minPlayerLevel: 1, itemIds: ["id1",...]}, {minPlayerLevel: 15, itemIds: ["id3",...]}] if (repeatableConfig.questConfig.Completion.useWhitelist) { const itemWhitelist = this.databaseServer.getTables().templates.repeatableQuests.data.Completion.itemsWhitelist; diff --git a/project/src/helpers/BotWeaponGeneratorHelper.ts b/project/src/helpers/BotWeaponGeneratorHelper.ts index d84037c0..5493198c 100644 --- a/project/src/helpers/BotWeaponGeneratorHelper.ts +++ b/project/src/helpers/BotWeaponGeneratorHelper.ts @@ -118,7 +118,7 @@ export class BotWeaponGeneratorHelper const ammoItems = this.itemHelper.splitStack({ _id: this.hashUtil.generate(), _tpl: ammoTpl, - upd: { "StackObjectsCount": cartridgeCount } + upd: { StackObjectsCount: cartridgeCount } }); for (const ammoItem of ammoItems) diff --git a/project/src/helpers/HideoutHelper.ts b/project/src/helpers/HideoutHelper.ts index dba759df..7be211db 100644 --- a/project/src/helpers/HideoutHelper.ts +++ b/project/src/helpers/HideoutHelper.ts @@ -753,7 +753,7 @@ export class HideoutHelper _id: this.hashUtil.generate(), _tpl: "59faff1d86f7746c51718c9c", upd: { - "StackObjectsCount": 1 + StackObjectsCount: 1 } }); diff --git a/project/src/helpers/HttpServerHelper.ts b/project/src/helpers/HttpServerHelper.ts index 19a85a34..613bfa9e 100644 --- a/project/src/helpers/HttpServerHelper.ts +++ b/project/src/helpers/HttpServerHelper.ts @@ -10,15 +10,15 @@ export class HttpServerHelper protected httpConfig: IHttpConfig; protected mime = { - "css": "text/css", - "bin": "application/octet-stream", - "html": "text/html", - "jpg": "image/jpeg", - "js": "text/javascript", - "json": "application/json", - "png": "image/png", - "svg": "image/svg+xml", - "txt": "text/plain" + css: "text/css", + bin: "application/octet-stream", + html: "text/html", + jpg: "image/jpeg", + js: "text/javascript", + json: "application/json", + png: "image/png", + svg: "image/svg+xml", + txt: "text/plain" }; constructor( diff --git a/project/src/helpers/InventoryHelper.ts b/project/src/helpers/InventoryHelper.ts index 455f38f5..a8843b33 100644 --- a/project/src/helpers/InventoryHelper.ts +++ b/project/src/helpers/InventoryHelper.ts @@ -788,13 +788,12 @@ export class InventoryHelper protected getInventoryItemHash(inventoryItem: Item[]): InventoryHelper.InventoryItemHash { const inventoryItemHash: InventoryHelper.InventoryItemHash = { - "byItemId": {}, - "byParentId": {} + byItemId: {}, + byParentId: {} }; - for (let i = 0; i < inventoryItem.length; i++) + for (const item of inventoryItem) { - const item = inventoryItem[i]; inventoryItemHash.byItemId[item._id] = item; if (!("parentId" in item)) diff --git a/project/src/helpers/ItemHelper.ts b/project/src/helpers/ItemHelper.ts index 85d4a49b..d34785b8 100644 --- a/project/src/helpers/ItemHelper.ts +++ b/project/src/helpers/ItemHelper.ts @@ -192,27 +192,27 @@ class ItemHelper * AmmoBoxes contain StackSlots which need to be filled for the AmmoBox to have content. * Here's what a filled AmmoBox looks like: * { - * "_id": "b1bbe982daa00ac841d4ae4d", - * "_tpl": "57372c89245977685d4159b1", - * "parentId": "5fe49a0e2694b0755a504876", - * "slotId": "hideout", - * "location": { - * "x": 3, - * "y": 4, - * "r": 0 + * _id: "b1bbe982daa00ac841d4ae4d", + * _tpl: "57372c89245977685d4159b1", + * parentId: "5fe49a0e2694b0755a504876", + * slotId: "hideout", + * location: { + * x: 3, + * y: 4, + * r: 0 * }, - * "upd": { - * "StackObjectsCount": 1 + * upd: { + * StackObjectsCount: 1 * } * }, * { - * "_id": "b997b4117199033afd274a06", - * "_tpl": "56dff061d2720bb5668b4567", - * "parentId": "b1bbe982daa00ac841d4ae4d", - * "slotId": "cartridges", - * "location": 0, - * "upd": { - * "StackObjectsCount": 30 + * _id: "b997b4117199033afd274a06", + * _tpl: "56dff061d2720bb5668b4567", + * parentId: "b1bbe982daa00ac841d4ae4d", + * slotId: "cartridges", + * location: 0, + * upd: { + * StackObjectsCount: 30 * } * } * Given the AmmoBox Item (first object) this function generates the StackSlot (second object) and returns it. diff --git a/project/src/helpers/ProfileHelper.ts b/project/src/helpers/ProfileHelper.ts index 8ad71cd3..74576d48 100644 --- a/project/src/helpers/ProfileHelper.ts +++ b/project/src/helpers/ProfileHelper.ts @@ -211,7 +211,7 @@ export class ProfileHelper public getDefaultAkiDataObject(): any { return { - "version": this.getServerVersion() + version: this.getServerVersion() }; } diff --git a/project/src/helpers/QuestHelper.ts b/project/src/helpers/QuestHelper.ts index 2ea06add..f87daba9 100644 --- a/project/src/helpers/QuestHelper.ts +++ b/project/src/helpers/QuestHelper.ts @@ -532,7 +532,7 @@ export class QuestHelper { // this case is probably dead Code right now, since the only calling function // checks explicitly for Value > 0. - output.profileChanges[sessionID].items.del.push({ "_id": itemId }); + output.profileChanges[sessionID].items.del.push({ _id: itemId }); pmcData.Inventory.items.splice(inventoryItemIndex, 1); } } @@ -546,12 +546,14 @@ export class QuestHelper protected addItemStackSizeChangeIntoEventResponse(output: IItemEventRouterResponse, sessionId: string, item: Item): void { output.profileChanges[sessionId].items.change.push({ - "_id": item._id, - "_tpl": item._tpl, - "parentId": item.parentId, - "slotId": item.slotId, - "location": item.location, - "upd": { "StackObjectsCount": item.upd.StackObjectsCount } + _id: item._id, + _tpl: item._tpl, + parentId: item.parentId, + slotId: item.slotId, + location: item.location, + upd: { + StackObjectsCount: item.upd.StackObjectsCount + } }); } diff --git a/project/src/models/eft/match/IGetRaidConfigurationRequestData.ts b/project/src/models/eft/match/IGetRaidConfigurationRequestData.ts index f01a2697..87bc3791 100644 --- a/project/src/models/eft/match/IGetRaidConfigurationRequestData.ts +++ b/project/src/models/eft/match/IGetRaidConfigurationRequestData.ts @@ -13,32 +13,32 @@ export interface IGetRaidConfigurationRequestData } // { -// "keyId": "", -// "side": "Pmc", -// "location": "factory4_day", -// "timeVariant": "CURR", or "PAST" -// "raidMode": "Local", -// "metabolismDisabled": false, -// "playersSpawnPlace": "SamePlace", -// "timeAndWeatherSettings": { -// "isRandomTime": false, -// "isRandomWeather": false, -// "cloudinessType": "Clear", -// "rainType": "NoRain", -// "windType": "Light", -// "fogType": "NoFog", -// "timeFlowType": "x1", -// "hourOfDay": -1 +// keyId: "", +// side: "Pmc", +// location: "factory4_day", +// timeVariant: "CURR", or "PAST" +// raidMode: "Local", +// metabolismDisabled: false, +// playersSpawnPlace: "SamePlace", +// timeAndWeatherSettings: { +// isRandomTime: false, +// isRandomWeather: false, +// cloudinessType: "Clear", +// rainType: "NoRain", +// windType: "Light", +// fogType: "NoFog", +// timeFlowType: "x1", +// hourOfDay: -1 // }, -// "botSettings": { -// "isScavWars": false, -// "botAmount": "AsOnline" +// botSettings: { +// isScavWars: false, +// botAmount: "AsOnline" // }, -// "wavesSettings": { -// "botAmount": "AsOnline", -// "botDifficulty": "AsOnline", -// "isBosses": true, -// "isTaggedAndCursed": false +// wavesSettings: { +// botAmount: "AsOnline", +// botDifficulty: "AsOnline", +// isBosses: true, +// isTaggedAndCursed: false // } // } diff --git a/project/src/servers/WebSocketServer.ts b/project/src/servers/WebSocketServer.ts index 002b10c8..678c093d 100644 --- a/project/src/servers/WebSocketServer.ts +++ b/project/src/servers/WebSocketServer.ts @@ -40,7 +40,7 @@ export class WebSocketServer public setupWebSocket(httpServer: http.Server): void { const webSocketServer = new WebSocket.Server({ - "server": httpServer + server: httpServer }); webSocketServer.addListener("listening", () => diff --git a/project/src/services/MatchLocationService.ts b/project/src/services/MatchLocationService.ts index ad29293c..cba086c6 100644 --- a/project/src/services/MatchLocationService.ts +++ b/project/src/services/MatchLocationService.ts @@ -18,25 +18,25 @@ export class MatchLocationService const groupID = "test"; this.locations[info.location].groups[groupID] = { - "_id": groupID, - "owner": `pmc${sessionID}`, - "location": info.location, - "gameVersion": "live", - "region": "EUR", - "status": "wait", - "isSavage": false, - "timeShift": "CURR", - "dt": this.timeUtil.getTimestamp(), - "players": [ + _id: groupID, + owner: `pmc${sessionID}`, + location: info.location, + gameVersion: "live", + region: "EUR", + status: "wait", + isSavage: false, + timeShift: "CURR", + dt: this.timeUtil.getTimestamp(), + players: [ { - "_id": `pmc${sessionID}`, - "region": "EUR", - "ip": "127.0.0.1", - "savageId": `scav${sessionID}`, - "accessKeyId": "" + _id: `pmc${sessionID}`, + region: "EUR", + ip: "127.0.0.1", + savageId: `scav${sessionID}`, + accessKeyId: "" } ], - "customDataCenter": [] + customDataCenter: [] }; return this.locations[info.location].groups[groupID]; diff --git a/project/src/utils/RandomUtil.ts b/project/src/utils/RandomUtil.ts index 1ef6f403..e0cf76b1 100644 --- a/project/src/utils/RandomUtil.ts +++ b/project/src/utils/RandomUtil.ts @@ -365,16 +365,16 @@ export class RandomUtil if (max < min) { throw { - "name": "Invalid arguments", - "message": `Bounded random number generation max is smaller than min (${max} < ${min})` + name: "Invalid arguments", + message: `Bounded random number generation max is smaller than min (${max} < ${min})` }; } if (n < 1) { throw { - "name": "Invalid argument", - "message": `'n' must be 1 or greater (received ${n})` + name: "Invalid argument", + message: `'n' must be 1 or greater (received ${n})` }; } diff --git a/project/src/utils/VFS.ts b/project/src/utils/VFS.ts index d2ed724e..bf0f49ca 100644 --- a/project/src/utils/VFS.ts +++ b/project/src/utils/VFS.ts @@ -82,14 +82,14 @@ export class VFS public createDir(filepath: string): void { - fs.mkdirSync(filepath.substr(0, filepath.lastIndexOf("/")), { "recursive": true }); + fs.mkdirSync(filepath.substr(0, filepath.lastIndexOf("/")), { recursive: true }); } public async createDirAsync(filepath: string): Promise { const command = { uuid: crypto.randomUUID(), - cmd: async () => await this.mkdirPromisify(filepath.substr(0, filepath.lastIndexOf("/")), { "recursive": true }) + cmd: async () => await this.mkdirPromisify(filepath.substr(0, filepath.lastIndexOf("/")), { recursive: true }) }; await this.asyncQueue.waitFor(command); } @@ -167,7 +167,7 @@ export class VFS public writeFile(filepath: any, data = "", append = false, atomic = true): void { - const options = (append) ? { "flag": "a" } : { "flag": "w" }; + const options = append ? { flag: "a" } : { flag: "w" }; if (!this.exists(filepath)) { @@ -194,7 +194,7 @@ export class VFS public async writeFileAsync(filepath: any, data = "", append = false, atomic = true): Promise { - const options = (append) ? { "flag": "a" } : { "flag": "w" }; + const options = append ? { flag: "a" } : { flag: "w" }; if (!await this.exists(filepath)) { From 133c0f760de12b2dc78daeb1daa43771642b3ad8 Mon Sep 17 00:00:00 2001 From: TheSparta Date: Tue, 31 Oct 2023 22:54:59 +0000 Subject: [PATCH 06/41] fixed lint/suspicious/noGlobalIsNan --- project/src/helpers/ItemHelper.ts | 2 +- project/src/helpers/RagfairOfferHelper.ts | 4 ++-- project/src/helpers/RagfairSellHelper.ts | 2 +- project/src/services/ProfileFixerService.ts | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/project/src/helpers/ItemHelper.ts b/project/src/helpers/ItemHelper.ts index d34785b8..2de92170 100644 --- a/project/src/helpers/ItemHelper.ts +++ b/project/src/helpers/ItemHelper.ts @@ -854,7 +854,7 @@ class ItemHelper */ public isAttachmentAttached(item: Item): boolean { - return item.slotId !== "hideout" && item.slotId !== "main" && isNaN(Number(item.slotId)); + return item.slotId !== "hideout" && item.slotId !== "main" && Number.isNaN(Number(item.slotId)); } /** diff --git a/project/src/helpers/RagfairOfferHelper.ts b/project/src/helpers/RagfairOfferHelper.ts index 45f2e7d4..6543ad18 100644 --- a/project/src/helpers/RagfairOfferHelper.ts +++ b/project/src/helpers/RagfairOfferHelper.ts @@ -297,7 +297,7 @@ export class RagfairOfferHelper public increaseProfileRagfairRating(profile: IAkiProfile, amountToIncrementBy: number): void { profile.characters.pmc.RagfairInfo.isRatingGrowing = true; - if (isNaN(amountToIncrementBy)) + if (Number.isNaN(amountToIncrementBy)) { this.logger.warning(`Unable to increment ragfair rating, value was not a number: ${amountToIncrementBy}`); @@ -595,7 +595,7 @@ export class RagfairOfferHelper return false; } - if (isNaN(offer.requirementsCost)) + if (Number.isNaN(offer.requirementsCost)) { // don't include offers with null or NaN in it return false; diff --git a/project/src/helpers/RagfairSellHelper.ts b/project/src/helpers/RagfairSellHelper.ts index 43f95f93..12d0ba55 100644 --- a/project/src/helpers/RagfairSellHelper.ts +++ b/project/src/helpers/RagfairSellHelper.ts @@ -77,7 +77,7 @@ export class RagfairSellHelper const result: SellResult[] = []; // Value can sometimes be NaN for whatever reason, default to base chance if that happens - if (isNaN(sellChancePercent)) + if (Number.isNaN(sellChancePercent)) { this.logger.warning(`Sell chance was not a number: ${sellChancePercent}, defaulting to ${this.ragfairConfig.sell.chance.base} %`); sellChancePercent = this.ragfairConfig.sell.chance.base; diff --git a/project/src/services/ProfileFixerService.ts b/project/src/services/ProfileFixerService.ts index de0a45d7..24cf3994 100644 --- a/project/src/services/ProfileFixerService.ts +++ b/project/src/services/ProfileFixerService.ts @@ -970,7 +970,7 @@ export class ProfileFixerService public fixIncorrectAidValue(fullProfile: IAkiProfile): void { // Not a number, regenerate - if (isNaN(fullProfile.characters.pmc.aid)) + if (Number.isNaN(fullProfile.characters.pmc.aid)) { fullProfile.characters.pmc.sessionId = fullProfile.characters.pmc.aid; fullProfile.characters.pmc.aid = this.hashUtil.generateAccountId(); From e3c833a085060490aa06d3045041d6bb096e01aa Mon Sep 17 00:00:00 2001 From: TheSparta Date: Tue, 31 Oct 2023 23:13:20 +0000 Subject: [PATCH 07/41] fixed lint/style/useExponentiationOperator --- project/src/services/RagfairTaxService.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/project/src/services/RagfairTaxService.ts b/project/src/services/RagfairTaxService.ts index e4e6fb48..e29ba5f9 100644 --- a/project/src/services/RagfairTaxService.ts +++ b/project/src/services/RagfairTaxService.ts @@ -63,15 +63,15 @@ export class RagfairTaxService if (requirementsPrice >= itemWorth) { - requirementPriceMult = Math.pow(requirementPriceMult, 1.08); + requirementPriceMult = requirementPriceMult ** 1.08; } else { - itemPriceMult = Math.pow(itemPriceMult, 1.08); + itemPriceMult = itemPriceMult ** 1.08; } - itemPriceMult = Math.pow(4, itemPriceMult); - requirementPriceMult = Math.pow(4, requirementPriceMult); + itemPriceMult = 4 ** itemPriceMult; + requirementPriceMult = 4 ** requirementPriceMult; const hideoutFleaTaxDiscountBonus = pmcData.Bonuses.find(b => b.type === "RagfairCommission"); const taxDiscountPercent = hideoutFleaTaxDiscountBonus ? Math.abs(hideoutFleaTaxDiscountBonus.value) : 0; @@ -147,7 +147,7 @@ export class RagfairTaxService if ("Repairable" in item.upd && itemTemplate._props.armorClass > 0) { - const num2 = 0.01 * Math.pow(0.0, item.upd.Repairable.MaxDurability); + const num2 = 0.01 * (0.0 ** item.upd.Repairable.MaxDurability); worth = worth * ((item.upd.Repairable.MaxDurability / itemTemplate._props.Durability) - num2) - Math.floor(itemTemplate._props.RepairCost * (item.upd.Repairable.MaxDurability - item.upd.Repairable.Durability)); } From ed1557d26b656c028f8bb4caf42b961fa6af6c9e Mon Sep 17 00:00:00 2001 From: TheSparta Date: Tue, 31 Oct 2023 23:57:28 +0000 Subject: [PATCH 08/41] fixed suppressions/deprecatedSuppressionComment --- project/src/generators/BotEquipmentModGenerator.ts | 2 +- project/src/generators/RepeatableQuestGenerator.ts | 2 +- project/src/models/eft/dialog/IAcceptFriendRequestData.ts | 4 ++-- project/src/services/BotLootCacheService.ts | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/project/src/generators/BotEquipmentModGenerator.ts b/project/src/generators/BotEquipmentModGenerator.ts index 04cb0194..259d7acd 100644 --- a/project/src/generators/BotEquipmentModGenerator.ts +++ b/project/src/generators/BotEquipmentModGenerator.ts @@ -170,7 +170,7 @@ export class BotEquipmentModGenerator const compatibleModsPool = modPool[parentTemplate._id]; // Null guard against bad input weapon - // rome-ignore lint/complexity/useSimplifiedLogicExpression: + // biome-ignore lint/complexity/useSimplifiedLogicExpression: if (!parentTemplate._props.Slots.length && !parentTemplate._props.Cartridges?.length && !parentTemplate._props.Chambers?.length) diff --git a/project/src/generators/RepeatableQuestGenerator.ts b/project/src/generators/RepeatableQuestGenerator.ts index c0795a99..0b7d5372 100644 --- a/project/src/generators/RepeatableQuestGenerator.ts +++ b/project/src/generators/RepeatableQuestGenerator.ts @@ -1017,7 +1017,7 @@ export class RepeatableQuestGenerator } // Skip globally blacklisted items + boss items - // rome-ignore lint/complexity/useSimplifiedLogicExpression: + // biome-ignore lint/complexity/useSimplifiedLogicExpression: valid = !this.itemFilterService.isItemBlacklisted(tpl) && !this.itemFilterService.isBossItem(tpl); diff --git a/project/src/models/eft/dialog/IAcceptFriendRequestData.ts b/project/src/models/eft/dialog/IAcceptFriendRequestData.ts index f6c811d5..70d9355d 100644 --- a/project/src/models/eft/dialog/IAcceptFriendRequestData.ts +++ b/project/src/models/eft/dialog/IAcceptFriendRequestData.ts @@ -1,10 +1,10 @@ -// rome-ignore lint/suspicious/noEmptyInterface: +// biome-ignore lint/suspicious/noEmptyInterface: export interface IAcceptFriendRequestData extends IBaseFriendRequest { } -// rome-ignore lint/suspicious/noEmptyInterface: +// biome-ignore lint/suspicious/noEmptyInterface: export interface ICancelFriendRequestData extends IBaseFriendRequest { diff --git a/project/src/services/BotLootCacheService.ts b/project/src/services/BotLootCacheService.ts index 002b1a04..3e736c7c 100644 --- a/project/src/services/BotLootCacheService.ts +++ b/project/src/services/BotLootCacheService.ts @@ -186,7 +186,7 @@ export class BotLootCacheService // Get loot items (excluding magazines, bullets, grenades and healing items) const backpackLootItems = backpackLootTemplates.filter(template => - // rome-ignore lint/complexity/useSimplifiedLogicExpression: + // biome-ignore lint/complexity/useSimplifiedLogicExpression: !this.isBulletOrGrenade(template._props) && !this.isMagazine(template._props) //&& !this.isMedicalItem(template._props) // Disabled for now as followSanitar has a lot of med items as loot @@ -194,7 +194,7 @@ export class BotLootCacheService // Get pocket loot const pocketLootItems = pocketLootTemplates.filter(template => - // rome-ignore lint/complexity/useSimplifiedLogicExpression: + // biome-ignore lint/complexity/useSimplifiedLogicExpression: !this.isBulletOrGrenade(template._props) && !this.isMagazine(template._props) && !this.isMedicalItem(template._props) @@ -204,7 +204,7 @@ export class BotLootCacheService // Get vest loot items const vestLootItems = vestLootTemplates.filter(template => - // rome-ignore lint/complexity/useSimplifiedLogicExpression: + // biome-ignore lint/complexity/useSimplifiedLogicExpression: !this.isBulletOrGrenade(template._props) && !this.isMagazine(template._props) && !this.isMedicalItem(template._props) From d13bcc2ebacf74184fa86f27fb7798e155e8e6e8 Mon Sep 17 00:00:00 2001 From: TheSparta Date: Wed, 1 Nov 2023 14:33:33 +0000 Subject: [PATCH 09/41] fixed lint/style/noInferrableTypes --- project/src/helpers/BotGeneratorHelper.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project/src/helpers/BotGeneratorHelper.ts b/project/src/helpers/BotGeneratorHelper.ts index 3e37645a..21ae5ade 100644 --- a/project/src/helpers/BotGeneratorHelper.ts +++ b/project/src/helpers/BotGeneratorHelper.ts @@ -46,7 +46,7 @@ export class BotGeneratorHelper * @param botRole Used by weapons to randomize the durability values. Null for non-equipped items * @returns Item Upd object with extra properties */ - public generateExtraPropertiesForItem(itemTemplate: ITemplateItem, botRole: string = null): { upd?: Upd } + public generateExtraPropertiesForItem(itemTemplate: ITemplateItem, botRole?: string): { upd?: Upd } { // Get raid settings, if no raid, default to day const raidSettings = this.applicationContext.getLatestValue(ContextVariableType.RAID_CONFIGURATION)?.getValue(); From f2ef3efdacbf960eeb529c824b9bcfc5f6086fee Mon Sep 17 00:00:00 2001 From: TheSparta Date: Wed, 1 Nov 2023 14:39:44 +0000 Subject: [PATCH 10/41] fixed suppressions/unused --- .../src/models/eft/dialog/IAcceptFriendRequestData.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/project/src/models/eft/dialog/IAcceptFriendRequestData.ts b/project/src/models/eft/dialog/IAcceptFriendRequestData.ts index 70d9355d..0434369b 100644 --- a/project/src/models/eft/dialog/IAcceptFriendRequestData.ts +++ b/project/src/models/eft/dialog/IAcceptFriendRequestData.ts @@ -1,11 +1,9 @@ -// biome-ignore lint/suspicious/noEmptyInterface: -export interface IAcceptFriendRequestData extends IBaseFriendRequest +export interface IAcceptFriendRequestData extends IBaseFriendRequest { - + } -// biome-ignore lint/suspicious/noEmptyInterface: -export interface ICancelFriendRequestData extends IBaseFriendRequest +export interface ICancelFriendRequestData extends IBaseFriendRequest { } @@ -14,4 +12,4 @@ export interface IBaseFriendRequest { // eslint-disable-next-line @typescript-eslint/naming-convention request_id: string -} \ No newline at end of file +} From 98a793229c622351eeb3dfda43394f6ac804ee84 Mon Sep 17 00:00:00 2001 From: TheSparta Date: Wed, 1 Nov 2023 14:42:45 +0000 Subject: [PATCH 11/41] fixed lint/complexity/noUselessSwitchCase --- project/src/helpers/RagfairHelper.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/project/src/helpers/RagfairHelper.ts b/project/src/helpers/RagfairHelper.ts index 1a73cc0c..991bc61f 100644 --- a/project/src/helpers/RagfairHelper.ts +++ b/project/src/helpers/RagfairHelper.ts @@ -54,7 +54,6 @@ export class RagfairHelper case "5449016a4bdc2d6f028b456f": return "RUB"; - default: return ""; } @@ -216,13 +215,10 @@ export class RagfairHelper { case Money.EUROS: return "€"; - case Money.DOLLARS: return "$"; - - case Money.ROUBLES: - default: + default: // Money.ROUBLES return "₽"; } } -} \ No newline at end of file +} From 89cfc5c6eea4b0669369ca7ff544eb88a0672433 Mon Sep 17 00:00:00 2001 From: TheSparta Date: Wed, 1 Nov 2023 15:03:55 +0000 Subject: [PATCH 12/41] Turned off organizeImports and noStaticOnlyClass --- project/biome.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/project/biome.json b/project/biome.json index 9772227d..60e00327 100644 --- a/project/biome.json +++ b/project/biome.json @@ -5,6 +5,9 @@ "unsafeParameterDecoratorsEnabled": true } }, + "organizeImports": { + "enabled": false + }, "linter": { "enabled": true, "rules": { @@ -32,6 +35,7 @@ "noUnnecessaryContinue": "warn" }, "complexity": { + "noStaticOnlyClass": "off", "useSimplifiedLogicExpression": "warn", "useOptionalChain": "warn" } From 09a64b801a7aa87cf0c17acb24efc0f7b6fdb05c Mon Sep 17 00:00:00 2001 From: TheSparta Date: Wed, 1 Nov 2023 15:04:13 +0000 Subject: [PATCH 13/41] fixed lint/style/noNonNullAssertion --- project/src/loaders/ModLoadOrder.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project/src/loaders/ModLoadOrder.ts b/project/src/loaders/ModLoadOrder.ts index d9ce8056..469c0454 100644 --- a/project/src/loaders/ModLoadOrder.ts +++ b/project/src/loaders/ModLoadOrder.ts @@ -95,7 +95,7 @@ export class ModLoadOrder for (const loadBeforeMod of loadBefore) { - const loadBeforeModConfig = this.modsAvailable.get(loadBeforeMod)!; + const loadBeforeModConfig = this.modsAvailable.get(loadBeforeMod); loadBeforeModConfig.loadAfter ??= []; loadBeforeModConfig.loadAfter.push(mod); From a7334c198bfc6e203da622d8a1d55a8deca75ad3 Mon Sep 17 00:00:00 2001 From: TheSparta Date: Wed, 1 Nov 2023 23:59:12 +0000 Subject: [PATCH 14/41] Fixed check:circular script --- project/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project/package.json b/project/package.json index f6f37803..8a1b9a77 100644 --- a/project/package.json +++ b/project/package.json @@ -11,7 +11,7 @@ "node": "18.15.0" }, "scripts": { - "check:circular": "madge --circular --extensions ts ./src/", + "check:circular": "madge --circular --ts-config tsconfig.json --extensions ts ./src/", "lint": "biome ci src --formatter-enabled=false --max-diagnostics=200", "lint:fix": "eslint --fix --ext .ts src/**", "test": "vitest run", From f48e704bf10c1ee4b2a7580ce12dca86340cd2f6 Mon Sep 17 00:00:00 2001 From: TheSparta Date: Thu, 2 Nov 2023 00:01:15 +0000 Subject: [PATCH 15/41] import DependencyContainer type directly from tsyringe - Redundant re-export of DependencyContainer from tsyringe, caused madge to think it was a circular dependency due to the file name also being tsyringe, deleted the file and importing directly from tsyringe instead. --- project/src/models/external/IPostAkiLoadMod.ts | 2 +- project/src/models/external/IPostAkiLoadModAsync.ts | 2 +- project/src/models/external/IPostDBLoadMod.ts | 2 +- project/src/models/external/IPostDBLoadModAsync.ts | 2 +- project/src/models/external/IPreAkiLoadMod.ts | 2 +- project/src/models/external/IPreAkiLoadModAsync.ts | 2 +- project/src/models/external/tsyringe.ts | 2 -- 7 files changed, 6 insertions(+), 8 deletions(-) delete mode 100644 project/src/models/external/tsyringe.ts diff --git a/project/src/models/external/IPostAkiLoadMod.ts b/project/src/models/external/IPostAkiLoadMod.ts index 0558350e..4748a1da 100644 --- a/project/src/models/external/IPostAkiLoadMod.ts +++ b/project/src/models/external/IPostAkiLoadMod.ts @@ -1,4 +1,4 @@ -import { DependencyContainer } from "@spt-aki/models/external/tsyringe"; +import type { DependencyContainer } from "tsyringe"; export interface IPostAkiLoadMod { diff --git a/project/src/models/external/IPostAkiLoadModAsync.ts b/project/src/models/external/IPostAkiLoadModAsync.ts index 2a6419ac..62c16073 100644 --- a/project/src/models/external/IPostAkiLoadModAsync.ts +++ b/project/src/models/external/IPostAkiLoadModAsync.ts @@ -1,4 +1,4 @@ -import { DependencyContainer } from "@spt-aki/models/external/tsyringe"; +import type { DependencyContainer } from "tsyringe"; export interface IPostAkiLoadModAsync { diff --git a/project/src/models/external/IPostDBLoadMod.ts b/project/src/models/external/IPostDBLoadMod.ts index a42c899c..3d5231ef 100644 --- a/project/src/models/external/IPostDBLoadMod.ts +++ b/project/src/models/external/IPostDBLoadMod.ts @@ -1,4 +1,4 @@ -import { DependencyContainer } from "@spt-aki/models/external/tsyringe"; +import type { DependencyContainer } from "tsyringe"; export interface IPostDBLoadMod { diff --git a/project/src/models/external/IPostDBLoadModAsync.ts b/project/src/models/external/IPostDBLoadModAsync.ts index afe261bc..ab336308 100644 --- a/project/src/models/external/IPostDBLoadModAsync.ts +++ b/project/src/models/external/IPostDBLoadModAsync.ts @@ -1,4 +1,4 @@ -import { DependencyContainer } from "@spt-aki/models/external/tsyringe"; +import type { DependencyContainer } from "tsyringe"; export interface IPostDBLoadModAsync { diff --git a/project/src/models/external/IPreAkiLoadMod.ts b/project/src/models/external/IPreAkiLoadMod.ts index f78b9273..af37de75 100644 --- a/project/src/models/external/IPreAkiLoadMod.ts +++ b/project/src/models/external/IPreAkiLoadMod.ts @@ -1,4 +1,4 @@ -import { DependencyContainer } from "@spt-aki/models/external/tsyringe"; +import type { DependencyContainer } from "tsyringe"; export interface IPreAkiLoadMod { diff --git a/project/src/models/external/IPreAkiLoadModAsync.ts b/project/src/models/external/IPreAkiLoadModAsync.ts index 9ae3b1e1..f3aa6e5b 100644 --- a/project/src/models/external/IPreAkiLoadModAsync.ts +++ b/project/src/models/external/IPreAkiLoadModAsync.ts @@ -1,4 +1,4 @@ -import { DependencyContainer } from "@spt-aki/models/external/tsyringe"; +import type { DependencyContainer } from "tsyringe"; export interface IPreAkiLoadModAsync { diff --git a/project/src/models/external/tsyringe.ts b/project/src/models/external/tsyringe.ts deleted file mode 100644 index 11cc2351..00000000 --- a/project/src/models/external/tsyringe.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { DependencyContainer } from "tsyringe"; -export type { DependencyContainer } ; \ No newline at end of file From 8c8ccdc787feeb2e4013f2f9781c7ae8baa94e34 Mon Sep 17 00:00:00 2001 From: TheSparta Date: Tue, 7 Nov 2023 22:48:10 +0000 Subject: [PATCH 16/41] Removed rome from devDependencies --- project/package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/project/package.json b/project/package.json index 8a1b9a77..fda52be9 100644 --- a/project/package.json +++ b/project/package.json @@ -69,7 +69,6 @@ "pkg": "5.8.1", "pkg-fetch": "3.5.2", "resedit": "2.0.0", - "rome": "12.1.3", "ts-node-dev": "2.0.0", "tsconfig-paths": "4.2.0", "typedoc": "0.25.2", From fe614670b70b68a4899c2c38b80e3db4ea500535 Mon Sep 17 00:00:00 2001 From: Refringe Date: Fri, 10 Nov 2023 11:29:56 -0500 Subject: [PATCH 17/41] Implements dprint formatting library. --- .gitattributes | 2 +- project/.editorconfig | 9 +++ project/.eslintrc.json | 148 ++++++++++++++-------------------- project/.vscode/settings.json | 20 ----- project/Server.code-workspace | 27 ++++--- project/biome.json | 29 +++++-- project/dprint.json | 87 ++++++++++++++++++++ project/package.json | 3 + 8 files changed, 202 insertions(+), 123 deletions(-) create mode 100644 project/.editorconfig delete mode 100644 project/.vscode/settings.json create mode 100644 project/dprint.json diff --git a/.gitattributes b/.gitattributes index 982110c0..a32b9f86 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,7 +1,7 @@ ############################################################################### # Set default behavior to automatically normalize line endings. ############################################################################### -* text=auto +* text=auto eol=lf ############################################################################### # Set default behavior for command prompt diff. # diff --git a/project/.editorconfig b/project/.editorconfig new file mode 100644 index 00000000..a3284cad --- /dev/null +++ b/project/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 +indent_style = space +indent_size = 4 +max_line_length = 120 diff --git a/project/.eslintrc.json b/project/.eslintrc.json index 3653c8e7..a389b7d3 100644 --- a/project/.eslintrc.json +++ b/project/.eslintrc.json @@ -1,91 +1,65 @@ { - "root": true, - "parser": "@typescript-eslint/parser", - "plugins": [ - "@typescript-eslint" - ], - "env": { - "node": true - }, - "extends": [ - "eslint:recommended", - "plugin:@typescript-eslint/eslint-recommended", - "plugin:@typescript-eslint/recommended" - ], - "rules": { - "semi": [1, "always"], - "@typescript-eslint/no-explicit-any": 0, - "@typescript-eslint/no-unused-vars": 1, - "@typescript-eslint/no-empty-interface": 0, - "@typescript-eslint/no-namespace": 0, - "@typescript-eslint/comma-dangle": 1, - "@typescript-eslint/func-call-spacing": 2, - "@typescript-eslint/quotes": 1, - "@typescript-eslint/brace-style": [ - "error", - "allman" + "root": true, + "parser": "@typescript-eslint/parser", + "plugins": [ + "@typescript-eslint" ], - "@typescript-eslint/naming-convention": [ - "error", - { - "selector": "default", - "format": [ - "camelCase" + "env": { + "node": true + }, + "extends": [ + "plugin:@typescript-eslint/eslint-recommended" + ], + "rules": { + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/no-namespace": "off", + "@typescript-eslint/no-unused-vars": "error", + "@typescript-eslint/no-var-requires": "error", + "@typescript-eslint/explicit-module-boundary-types": ["error", { "allowArgumentsExplicitlyTypedAsAny": true }], + "@typescript-eslint/naming-convention": ["error", { + "selector": "import", + "format": ["camelCase", "PascalCase", "UPPER_CASE"] + }, { + "selector": "default", + "format": ["camelCase"], + "leadingUnderscore": "allow" + }, { + "selector": "typeLike", + "format": ["PascalCase"] + }, { + "selector": "objectLiteralProperty", + "format": ["PascalCase", "camelCase", "snake_case"], + "leadingUnderscore": "allow" + }, { + "selector": "typeProperty", + "format": ["PascalCase", "camelCase"], + "leadingUnderscore": "allow" + }, { + "selector": "enumMember", + "format": ["UPPER_CASE"] + }, { + "selector": "property", + "modifiers": ["readonly", "static"], + "format": ["UPPER_CASE"] + }] + }, + "overrides": [{ + "files": [ + "src/callbacks/**/*.js", + "src/controllers/**/*.js" ], - "leadingUnderscore": "allow" - }, - { - "selector": "typeLike", - "format": [ - "PascalCase" - ] - }, - { - "selector": "objectLiteralProperty", - "format": [ - "PascalCase", - "camelCase" + "rules": { + "no-unused-vars": "off", + "@typescript-eslint/no-unused-vars": "off" + } + }, { + "files": [ + "src/loaders/**/*.ts" ], - "leadingUnderscore": "allow" - }, - { - "selector": "typeProperty", - "format": [ - "PascalCase", - "camelCase" - ], - "leadingUnderscore": "allow" - }, - { - "selector": "enumMember", - "format": [ - "UPPER_CASE" - ] - } - ], - "@typescript-eslint/indent": [ - "error", - 4 - ], - "@typescript-eslint/no-unused-expressions": [ - "error", - { - "allowShortCircuit": false, - "allowTernary": false - } - ], - "@typescript-eslint/keyword-spacing": [ - "error", - { - "before": true, - "after": true - } - ], - "@typescript-eslint/explicit-module-boundary-types": [ - "warn", - { - "allowArgumentsExplicitlyTypedAsAny": true - } - ] - } -} \ No newline at end of file + "rules": { + "no-var-requires": "off", + "@typescript-eslint/no-var-requires": "off", + } + }] +} diff --git a/project/.vscode/settings.json b/project/.vscode/settings.json deleted file mode 100644 index 02965ef3..00000000 --- a/project/.vscode/settings.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "editor.defaultFormatter": "dbaeumer.vscode-eslint", - "eslint.format.enable": true, - "editor.codeActionsOnSave": { - "source.fixAll.eslint": true - }, - "[json]": { - "editor.defaultFormatter": "vscode.json-language-features", - "editor.detectIndentation": false, - "editor.tabSize": 4, - "editor.insertSpaces": true - }, - "cSpell.words": [ - "Baseclass", - "IIIA", - "medkit", - "Superfors", - "ULACH" - ] -} diff --git a/project/Server.code-workspace b/project/Server.code-workspace index 12291d34..9e60789a 100644 --- a/project/Server.code-workspace +++ b/project/Server.code-workspace @@ -5,18 +5,27 @@ } ], "extensions": { - "recommendations": ["dbaeumer.vscode-eslint"], + "recommendations": [ + "EditorConfig.EditorConfig", + "Jota0222.multi-formatter", + "dbaeumer.vscode-eslint", + "dprint.dprint", + "biomejs.biome" + ] }, "settings": { "window.title": "SPT-AKI Server", + "editor.formatOnSave": true, + "editor.defaultFormatter": "dprint.dprint", + "multiFormatter.formatterList": [ + "dprint.dprint", + "biomejs.biome" + ], "[typescript]": { - "editor.formatOnSave": true, - "editor.defaultFormatter": "dbaeumer.vscode-eslint" - }, - "eslint.validate": ["typescript"], - "editor.codeActionsOnSave": { - "source.organizeImports": false, - "source.fixAll.eslint": true + "editor.codeActionsOnSave": { + "quickfix.biome": false, + "source.organizeImports.biome": true + } } - }, + } } diff --git a/project/biome.json b/project/biome.json index 60e00327..8316dc82 100644 --- a/project/biome.json +++ b/project/biome.json @@ -6,7 +6,7 @@ } }, "organizeImports": { - "enabled": false + "enabled": true }, "linter": { "enabled": true, @@ -26,7 +26,7 @@ "noExplicitAny": "off", "noDoubleEquals": "warn", "noShadowRestrictedNames": "warn", - "noEmptyInterface":"off" + "noEmptyInterface": "off" }, "performance": { "noDelete": "off" @@ -39,13 +39,30 @@ "useSimplifiedLogicExpression": "warn", "useOptionalChain": "warn" } - }, + } + }, + "formatter": { + "enabled": false + }, + "files": { "ignore": [ "**/*.js", "**/*.json", - "**/*.mjs", + "**/*.d.ts", "**/Dockerfile.*", - "**/node_modules/**/*" + "**/.git/**/*", + "**/.vscode/**/*", + "**/node_modules/**/*", + "**/build/**/*", + "**/obj/**/*", + "**/dist/**/*", + "**/user/**/*", + "**/logs/**/*", + "**/assets/**/*", + "**/Aki_Data/**/*", + "**/types/**/*", + "**/tests/__cache__/**/*", + "**/tests/__coverage__/**/*" ] - } + } } diff --git a/project/dprint.json b/project/dprint.json new file mode 100644 index 00000000..8853221a --- /dev/null +++ b/project/dprint.json @@ -0,0 +1,87 @@ +{ + "incremental": false, + "lineWidth": 120, + "indentWidth": 4, + "newLineKind": "lf", + "useTabs": false, + "typescript": { + "semiColons": "always", + "quoteStyle": "alwaysDouble", + "quoteProps": "asNeeded", + "useBraces": "always", + "bracePosition": "nextLine", + "singleBodyPosition": "maintain", + "nextControlFlowPosition": "nextLine", + "trailingCommas": "onlyMultiLine", + "operatorPosition": "sameLine", + "preferHanging": false, + "preferSingleLine": false, + "arrowFunction.useParentheses": "force", + "binaryExpression.linePerExpression": false, + "memberExpression.linePerExpression": false, + "typeLiteral.separatorKind": "semiColon", + "enumDeclaration.memberSpacing": "newLine", + "spaceAround": false, + "spaceSurroundingProperties": false, + "objectExpression.spaceSurroundingProperties": false, + "objectPattern.spaceSurroundingProperties": false, + "typeLiteral.spaceSurroundingProperties": false, + "binaryExpression.spaceSurroundingBitwiseAndArithmeticOperator": true, + "commentLine.forceSpaceAfterSlashes": true, + "constructor.spaceBeforeParentheses": false, + "constructorType.spaceAfterNewKeyword": false, + "constructSignature.spaceAfterNewKeyword": false, + "doWhileStatement.spaceAfterWhileKeyword": true, + "exportDeclaration.spaceSurroundingNamedExports": false, + "forInStatement.spaceAfterForKeyword": true, + "forOfStatement.spaceAfterForKeyword": true, + "forStatement.spaceAfterForKeyword": true, + "forStatement.spaceAfterSemiColons": true, + "functionDeclaration.spaceBeforeParentheses": false, + "functionExpression.spaceBeforeParentheses": false, + "functionExpression.spaceAfterFunctionKeyword": false, + "getAccessor.spaceBeforeParentheses": false, + "ifStatement.spaceAfterIfKeyword": true, + "importDeclaration.spaceSurroundingNamedImports": true, + "method.spaceBeforeParentheses": false, + "setAccessor.spaceBeforeParentheses": false, + "taggedTemplate.spaceBeforeLiteral": false, + "typeAnnotation.spaceBeforeColon": false, + "typeAssertion.spaceBeforeExpression": false, + "whileStatement.spaceAfterWhileKeyword": true + }, + "json": { + "trailingCommas": "never", + "preferSingleLine": false + }, + "markdown": { + "textWrap": "always", + "emphasisKind": "underscores", + "strongKind": "asterisks" + }, + "dockerfile": {}, + "excludes": [ + "**/*.js", + "**/*.d.ts", + "**/*.swcrc", + "**/*-lock.json", + "**/.git/**/*", + "**/node_modules/**/*", + "**/build/**/*", + "**/obj/**/*", + "**/dist/**/*", + "**/user/**/*", + "**/logs/**/*", + "**/assets/**/*", + "**/Aki_Data/**/*", + "**/types/**/*", + "**/tests/__cache__/**/*", + "**/tests/__coverage__/**/*" + ], + "plugins": [ + "https://plugins.dprint.dev/typescript-0.88.3.wasm", + "https://plugins.dprint.dev/json-0.19.0.wasm", + "https://plugins.dprint.dev/markdown-0.16.2.wasm", + "https://plugins.dprint.dev/dockerfile-0.3.0.wasm" + ] +} diff --git a/project/package.json b/project/package.json index fda52be9..1893e3d4 100644 --- a/project/package.json +++ b/project/package.json @@ -14,6 +14,8 @@ "check:circular": "madge --circular --ts-config tsconfig.json --extensions ts ./src/", "lint": "biome ci src --formatter-enabled=false --max-diagnostics=200", "lint:fix": "eslint --fix --ext .ts src/**", + "style": "dprint check --incremental=false", + "style:fix": "dprint fmt --incremental=false", "test": "vitest run", "test:watch": "vitest", "test:coverage": "vitest run --coverage", @@ -61,6 +63,7 @@ "@vitest/coverage-istanbul": "1.0.0-beta.3", "@vitest/ui": "1.0.0-beta.3", "cross-env": "7.0.3", + "dprint": "0.42.5", "eslint": "8.51.0", "gulp": "4.0.2", "gulp-execa": "5.0.1", From 5f7bfdeb1a9a2c47967ac05d87db416603f2a5ab Mon Sep 17 00:00:00 2001 From: Refringe Date: Fri, 10 Nov 2023 13:25:58 -0500 Subject: [PATCH 18/41] Gets Biome and ESLint working for non-formatting linting. --- project/.eslintrc.json | 5 +---- project/Server.code-workspace | 17 +++++------------ 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/project/.eslintrc.json b/project/.eslintrc.json index a389b7d3..fc5a0d14 100644 --- a/project/.eslintrc.json +++ b/project/.eslintrc.json @@ -18,9 +18,6 @@ "@typescript-eslint/no-var-requires": "error", "@typescript-eslint/explicit-module-boundary-types": ["error", { "allowArgumentsExplicitlyTypedAsAny": true }], "@typescript-eslint/naming-convention": ["error", { - "selector": "import", - "format": ["camelCase", "PascalCase", "UPPER_CASE"] - }, { "selector": "default", "format": ["camelCase"], "leadingUnderscore": "allow" @@ -59,7 +56,7 @@ ], "rules": { "no-var-requires": "off", - "@typescript-eslint/no-var-requires": "off", + "@typescript-eslint/no-var-requires": "off" } }] } diff --git a/project/Server.code-workspace b/project/Server.code-workspace index 9e60789a..ce3449b0 100644 --- a/project/Server.code-workspace +++ b/project/Server.code-workspace @@ -7,9 +7,8 @@ "extensions": { "recommendations": [ "EditorConfig.EditorConfig", - "Jota0222.multi-formatter", - "dbaeumer.vscode-eslint", "dprint.dprint", + "dbaeumer.vscode-eslint", "biomejs.biome" ] }, @@ -17,15 +16,9 @@ "window.title": "SPT-AKI Server", "editor.formatOnSave": true, "editor.defaultFormatter": "dprint.dprint", - "multiFormatter.formatterList": [ - "dprint.dprint", - "biomejs.biome" - ], - "[typescript]": { - "editor.codeActionsOnSave": { - "quickfix.biome": false, - "source.organizeImports.biome": true - } - } + "editor.codeActionsOnSave": [ + "source.fixAll.eslint", + "source.organizeImports.biome" + ] } } From 12891ceac68db50155d22d01105305cefbca0d8d Mon Sep 17 00:00:00 2001 From: Refringe Date: Fri, 10 Nov 2023 15:16:21 -0500 Subject: [PATCH 19/41] Additional formatting configuration changes. --- project/.eslintrc.json | 26 +++++++++++++------------- project/.vscode/launch.json | 3 --- project/Server.code-workspace | 10 +++++++++- project/dprint.json | 1 - 4 files changed, 22 insertions(+), 18 deletions(-) diff --git a/project/.eslintrc.json b/project/.eslintrc.json index fc5a0d14..54b23e15 100644 --- a/project/.eslintrc.json +++ b/project/.eslintrc.json @@ -11,10 +11,10 @@ "plugin:@typescript-eslint/eslint-recommended" ], "rules": { - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-empty-interface": "off", "@typescript-eslint/no-namespace": "off", - "@typescript-eslint/no-unused-vars": "error", + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/no-explicit-any": "off", // We use a bunch of these. + "@typescript-eslint/no-unused-vars": "off", // Typescript compiler already checks--Will grey out variable. "@typescript-eslint/no-var-requires": "error", "@typescript-eslint/explicit-module-boundary-types": ["error", { "allowArgumentsExplicitlyTypedAsAny": true }], "@typescript-eslint/naming-convention": ["error", { @@ -42,21 +42,21 @@ }] }, "overrides": [{ - "files": [ - "src/callbacks/**/*.js", - "src/controllers/**/*.js" - ], - "rules": { - "no-unused-vars": "off", - "@typescript-eslint/no-unused-vars": "off" - } - }, { "files": [ "src/loaders/**/*.ts" ], "rules": { - "no-var-requires": "off", "@typescript-eslint/no-var-requires": "off" } + }, { + "files": [ + "**/vitest.config.ts" + ], + "rules": { + "@typescript-eslint/naming-convention": ["error", { + "selector": "objectLiteralProperty", + "format": null + }] + } }] } diff --git a/project/.vscode/launch.json b/project/.vscode/launch.json index a4a405ec..ebd31c51 100644 --- a/project/.vscode/launch.json +++ b/project/.vscode/launch.json @@ -1,7 +1,4 @@ { - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { diff --git a/project/Server.code-workspace b/project/Server.code-workspace index ce3449b0..38ce6f32 100644 --- a/project/Server.code-workspace +++ b/project/Server.code-workspace @@ -9,7 +9,8 @@ "EditorConfig.EditorConfig", "dprint.dprint", "dbaeumer.vscode-eslint", - "biomejs.biome" + "biomejs.biome", + "streetsidesoftware.code-spell-checker" ] }, "settings": { @@ -19,6 +20,13 @@ "editor.codeActionsOnSave": [ "source.fixAll.eslint", "source.organizeImports.biome" + ], + "cSpell.words": [ + "deathmatch", + "gethideout", + "profileid", + "requestid", + "scavcase" ] } } diff --git a/project/dprint.json b/project/dprint.json index 8853221a..287af9de 100644 --- a/project/dprint.json +++ b/project/dprint.json @@ -63,7 +63,6 @@ "excludes": [ "**/*.js", "**/*.d.ts", - "**/*.swcrc", "**/*-lock.json", "**/.git/**/*", "**/node_modules/**/*", From 90cdd6eea1408c02d1b6314cfb6ba421f88bfece Mon Sep 17 00:00:00 2001 From: Refringe Date: Fri, 10 Nov 2023 15:16:53 -0500 Subject: [PATCH 20/41] Auto-formatting of root-level files. --- project/Dockerfile | 5 ++- project/gulpfile.mjs | 69 ++++++++++++++++++++++++++----------- project/src/ErrorHandler.ts | 3 +- project/src/Program.ts | 9 +++-- project/typedoc.json | 2 +- project/vitest.config.ts | 15 ++++---- 6 files changed, 63 insertions(+), 40 deletions(-) diff --git a/project/Dockerfile b/project/Dockerfile index 9c98106e..a10df6f5 100644 --- a/project/Dockerfile +++ b/project/Dockerfile @@ -1,4 +1,4 @@ -FROM node:16-buster as builder +FROM node:16-buster AS builder WORKDIR /app @@ -9,7 +9,6 @@ COPY tsconfig.json tsconfig.base.json ./ COPY src ./src RUN yarn test:comp-linux - ############################################## FROM debian:buster @@ -18,4 +17,4 @@ COPY --from=builder /app/bundle /bin/Aki-server EXPOSE 6969 -CMD ["/bin/Aki-server"] \ No newline at end of file +CMD ["/bin/Aki-server"] diff --git a/project/gulpfile.mjs b/project/gulpfile.mjs index b468279c..26ba5a31 100644 --- a/project/gulpfile.mjs +++ b/project/gulpfile.mjs @@ -1,5 +1,3 @@ -/* eslint-disable @typescript-eslint/naming-convention */ - import gulp from "gulp"; import { exec } from "gulp-execa"; import rename from "gulp-rename"; @@ -10,7 +8,7 @@ import path from "node:path"; import pkg from "pkg"; import pkgfetch from "pkg-fetch"; import * as ResEdit from "resedit"; -import manifest from "./package.json" assert { type: "json" }; +import manifest from "./package.json" assert {type: "json"}; const nodeVersion = "node18"; // As of pkg-fetch v3.5, it's v18.15.0 const stdio = "inherit"; @@ -22,14 +20,14 @@ 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") + bleeding: path.join("obj", "ide", "BleedingEdgeEntry.js"), }; const licenseFile = "../LICENSE.md"; /** - * Transpiles the src files into javascript with swc + * Transpile src files into Javascript with SWC */ -const compile = async () => await exec("swc src -d obj", { stdio }); +const compile = async () => await exec("swc src -d obj", {stdio}); // Packaging const fetchPackageImage = async () => @@ -37,7 +35,12 @@ const fetchPackageImage = async () => try { const output = "./.pkg-cache/v3.5"; - const fetchedPkg = await pkgfetch.need({ arch: process.arch, nodeRange: nodeVersion, platform: process.platform, output }); + const fetchedPkg = await pkgfetch.need({ + arch: process.arch, + nodeRange: nodeVersion, + platform: process.platform, + output, + }); console.log(`fetched node binary at ${fetchedPkg}`); const builtPkg = fetchedPkg.replace("node", "built"); await fs.copyFile(fetchedPkg, builtPkg); @@ -66,7 +69,7 @@ const updateBuildProperties = async () => res.entries, 1, 1033, - iconFile.icons.map(item => item.data) + iconFile.icons.map((item) => item.data), ); const vi = ResEdit.Resource.VersionInfo.fromEntries(res.entries)[0]; @@ -77,8 +80,8 @@ const updateBuildProperties = async () => ProductName: manifest.author, FileDescription: manifest.description, CompanyName: manifest.name, - LegalCopyright: manifest.license - } + LegalCopyright: manifest.license, + }, ); vi.removeStringValue({lang: 1033, codepage: 1200}, "OriginalFilename"); vi.removeStringValue({lang: 1033, codepage: 1200}, "InternalName"); @@ -92,12 +95,16 @@ const updateBuildProperties = async () => /** * Copy various asset files to the destination directory */ -const copyAssets = () => gulp.src(["assets/**/*.json", "assets/**/*.json5", "assets/**/*.png", "assets/**/*.jpg", "assets/**/*.ico"]).pipe(gulp.dest(dataDir)); +const copyAssets = () => + gulp.src(["assets/**/*.json", "assets/**/*.json5", "assets/**/*.png", "assets/**/*.jpg", "assets/**/*.ico"]).pipe( + gulp.dest(dataDir), + ); /** * Copy executables from node_modules */ -const copyExecutables = () => gulp.src(["node_modules/@pnpm/exe/**/*"]).pipe(gulp.dest(path.join(dataDir, "@pnpm", "exe"))); +const copyExecutables = () => + gulp.src(["node_modules/@pnpm/exe/**/*"]).pipe(gulp.dest(path.join(dataDir, "@pnpm", "exe"))); /** * Rename and copy the license file @@ -116,7 +123,7 @@ const writeCommitHashToCoreJSON = async () => const parsed = JSON.parse(coreJSON); // Fetch the latest Git commit hash - const gitResult = await exec("git rev-parse HEAD", { stdout: "pipe" }); + const gitResult = await exec("git rev-parse HEAD", {stdout: "pipe"}); // Update the commit hash in the core.json object parsed.commit = gitResult.stdout.trim() || ""; @@ -150,12 +157,12 @@ const addAssets = gulp.series(copyAssets, copyExecutables, copyLicense, writeCom /** * Cleans the build directory. */ -const cleanBuild = async () => await fs.rm(buildDir, { recursive: true, force: true }); +const cleanBuild = async () => await fs.rm(buildDir, {recursive: true, force: true}); /** * Cleans the transpiled javascript directory. */ -const cleanCompiled = async () => await fs.rm("./obj", { recursive: true, force: true }); +const cleanCompiled = async () => await fs.rm("./obj", {recursive: true, force: true}); /** * Recursively builds an array of paths for json files. @@ -244,7 +251,7 @@ const loadRecursiveAsync = async (filepath) => // set all loadRecursive to be executed asynchronously const resEntries = Object.entries(result); - const resResolved = await Promise.all(resEntries.map(ent => ent[1])); + const resResolved = await Promise.all(resEntries.map((ent) => ent[1])); for (let resIdx = 0; resIdx < resResolved.length; resIdx++) { resEntries[resIdx][1] = resResolved[resIdx]; @@ -259,7 +266,16 @@ const build = (packagingType) => { const anonPackaging = () => packaging(entries[packagingType]); anonPackaging.displayName = `packaging-${packagingType}`; - const tasks = [cleanBuild, validateJSONs, compile, fetchPackageImage, anonPackaging, addAssets, updateBuildProperties, cleanCompiled]; + const tasks = [ + cleanBuild, + validateJSONs, + compile, + fetchPackageImage, + anonPackaging, + addAssets, + updateBuildProperties, + cleanCompiled, + ]; return gulp.series(tasks); }; @@ -269,7 +285,18 @@ const packaging = async (entry) => const target = `${nodeVersion}-${process.platform}-${process.arch}`; try { - await pkg.exec([entry, "--compress", "GZip", "--target", target, "--output", serverExe, "--config", pkgConfig, "--public"]); + await pkg.exec([ + entry, + "--compress", + "GZip", + "--target", + target, + "--output", + serverExe, + "--config", + pkgConfig, + "--public", + ]); } catch (error) { @@ -281,11 +308,11 @@ gulp.task("build:debug", build("debug")); gulp.task("build:release", build("release")); gulp.task("build:bleeding", build("bleeding")); -gulp.task("run:build", async () => await exec("Aki.Server.exe", { stdio, cwd: buildDir })); -gulp.task("run:debug", async () => await exec("ts-node-dev -r tsconfig-paths/register src/ide/TestEntry.ts", { stdio })); +gulp.task("run:build", async () => await exec("Aki.Server.exe", {stdio, cwd: buildDir})); +gulp.task("run:debug", async () => await exec("ts-node-dev -r tsconfig-paths/register src/ide/TestEntry.ts", {stdio})); 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/ide/TestEntry.js", {stdio}); }); diff --git a/project/src/ErrorHandler.ts b/project/src/ErrorHandler.ts index 917f7c37..81c1576d 100644 --- a/project/src/ErrorHandler.ts +++ b/project/src/ErrorHandler.ts @@ -14,7 +14,7 @@ export class ErrorHandler this.logger = new WinstonMainLogger(new AsyncQueue()); this.readLine = readline.createInterface({ input: process.stdin, - output: process.stdout + output: process.stdout, }); } @@ -27,7 +27,6 @@ export class ErrorHandler this.logger.error(`\nStacktrace:\n${err.stack}`); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars this.readLine.question("Press Enter to close the window", (_ans) => this.readLine.close()); this.readLine.on("close", () => process.exit(1)); } diff --git a/project/src/Program.ts b/project/src/Program.ts index dcea561c..7ea38751 100644 --- a/project/src/Program.ts +++ b/project/src/Program.ts @@ -1,23 +1,22 @@ import { container } from "tsyringe"; -import { ErrorHandler } from "@spt-aki/ErrorHandler"; import { Container } from "@spt-aki/di/Container"; +import { ErrorHandler } from "@spt-aki/ErrorHandler"; import type { PreAkiModLoader } from "@spt-aki/loaders/PreAkiModLoader"; import { App } from "@spt-aki/utils/App"; import { Watermark } from "@spt-aki/utils/Watermark"; export class Program { - private errorHandler: ErrorHandler; - constructor() + constructor() { // set window properties process.stdout.setEncoding("utf8"); process.title = "SPT-AKI Server"; this.errorHandler = new ErrorHandler(); } - + public async start(): Promise { try @@ -36,7 +35,7 @@ export class Program } catch (err: any) { - this.errorHandler.handleCriticalError((err instanceof Error ? err : new Error(err))); + this.errorHandler.handleCriticalError(err instanceof Error ? err : new Error(err)); } } } diff --git a/project/typedoc.json b/project/typedoc.json index 976e9c6d..840852b4 100644 --- a/project/typedoc.json +++ b/project/typedoc.json @@ -3,4 +3,4 @@ "sort": ["source-order"], "media": "media", "basePath": "server-docs" -} \ No newline at end of file +} diff --git a/project/vitest.config.ts b/project/vitest.config.ts index 8c8e19f3..44ba8b7f 100644 --- a/project/vitest.config.ts +++ b/project/vitest.config.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/naming-convention */ import path from "node:path"; import { defineConfig } from "vitest/config"; @@ -9,7 +8,7 @@ export default defineConfig({ root: "./", include: ["**/*.{test,spec}.?(c|m)[jt]s?(x)"], cache: { - dir: "./tests/__cache__" + dir: "./tests/__cache__", }, environment: "./tests/CustomEnvironment.ts", globals: true, @@ -20,18 +19,18 @@ export default defineConfig({ reportOnFailure: true, all: true, include: ["src"], - exclude: ["src/models/**", "tests/**"] + exclude: ["src/models/**", "tests/**"], }, pool: "threads", poolOptions: { threads: { singleThread: true, - isolate: false - } + isolate: false, + }, }, alias: { "@spt-aki": path.resolve(__dirname, "src"), - "@tests": path.resolve(__dirname, "tests") - } - } + "@tests": path.resolve(__dirname, "tests"), + }, + }, }); From ab7f41b924d72b0dee8dd709797bb05958978575 Mon Sep 17 00:00:00 2001 From: Refringe Date: Fri, 10 Nov 2023 15:19:56 -0500 Subject: [PATCH 21/41] Auto-formatting for callback classes. --- project/src/callbacks/BotCallbacks.ts | 16 +-- project/src/callbacks/BundleCallbacks.ts | 7 +- project/src/callbacks/ClientLogCallbacks.ts | 9 +- .../src/callbacks/CustomizationCallbacks.ts | 8 +- project/src/callbacks/DataCallbacks.ts | 86 ++++++++----- project/src/callbacks/DialogueCallbacks.ts | 114 +++++++++++------- project/src/callbacks/GameCallbacks.ts | 51 ++++---- project/src/callbacks/HandbookCallbacks.ts | 13 +- project/src/callbacks/HealthCallbacks.ts | 20 +-- project/src/callbacks/HideoutCallbacks.ts | 79 +++++++++--- project/src/callbacks/HttpCallbacks.ts | 10 +- project/src/callbacks/InraidCallbacks.ts | 15 ++- project/src/callbacks/InsuranceCallbacks.ts | 9 +- project/src/callbacks/InventoryCallbacks.ts | 54 +++++++-- project/src/callbacks/ItemEventCallbacks.ts | 24 ++-- project/src/callbacks/LauncherCallbacks.ts | 16 +-- project/src/callbacks/LocationCallbacks.ts | 21 ++-- project/src/callbacks/MatchCallbacks.ts | 49 ++++---- project/src/callbacks/ModCallbacks.ts | 9 +- project/src/callbacks/NoteCallbacks.ts | 5 +- project/src/callbacks/NotifierCallbacks.ts | 25 ++-- project/src/callbacks/PresetBuildCallbacks.ts | 37 ++++-- project/src/callbacks/PresetCallbacks.ts | 8 +- project/src/callbacks/ProfileCallbacks.ts | 57 ++++++--- project/src/callbacks/QuestCallbacks.ts | 30 +++-- project/src/callbacks/RagfairCallbacks.ts | 27 +++-- project/src/callbacks/RepairCallbacks.ts | 19 ++- project/src/callbacks/SaveCallbacks.ts | 9 +- project/src/callbacks/TradeCallbacks.ts | 24 +++- project/src/callbacks/TraderCallbacks.ts | 19 +-- project/src/callbacks/WeatherCallbacks.ts | 7 +- project/src/callbacks/WishlistCallbacks.ts | 7 +- 32 files changed, 556 insertions(+), 328 deletions(-) diff --git a/project/src/callbacks/BotCallbacks.ts b/project/src/callbacks/BotCallbacks.ts index 52a5d674..3867921a 100644 --- a/project/src/callbacks/BotCallbacks.ts +++ b/project/src/callbacks/BotCallbacks.ts @@ -12,15 +12,15 @@ export class BotCallbacks { constructor( @inject("BotController") protected botController: BotController, - @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil) - { } + @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, + ) + {} /** * Handle singleplayer/settings/bot/limit * Is called by client to define each bot roles wave limit * @returns string */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getBotLimit(url: string, info: IEmptyRequestData, sessionID: string): string { const splittedUrl = url.split("/"); @@ -32,7 +32,6 @@ export class BotCallbacks * Handle singleplayer/settings/bot/difficulty * @returns string */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getBotDifficulty(url: string, info: IEmptyRequestData, sessionID: string): string { const splittedUrl = url.split("/"); @@ -42,7 +41,6 @@ export class BotCallbacks { return this.httpResponse.noBody(this.botController.getBotCoreDifficulty()); } - return this.httpResponse.noBody(this.botController.getBotDifficulty(type, difficulty)); } @@ -50,7 +48,11 @@ export class BotCallbacks * Handle client/game/bot/generate * @returns IGetBodyResponseData */ - public generateBots(url: string, info: IGenerateBotsRequestData, sessionID: string): IGetBodyResponseData + public generateBots( + url: string, + info: IGenerateBotsRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.botController.generate(sessionID, info)); } @@ -72,4 +74,4 @@ export class BotCallbacks { return this.httpResponse.noBody(this.botController.getAiBotBrainTypes()); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/BundleCallbacks.ts b/project/src/callbacks/BundleCallbacks.ts index 20f23b8b..918b4617 100644 --- a/project/src/callbacks/BundleCallbacks.ts +++ b/project/src/callbacks/BundleCallbacks.ts @@ -18,13 +18,12 @@ export class BundleCallbacks @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("HttpFileUtil") protected httpFileUtil: HttpFileUtil, @inject("BundleLoader") protected bundleLoader: BundleLoader, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.httpConfig = this.configServer.getConfig(ConfigTypes.HTTP); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public sendBundle(sessionID: string, req: any, resp: any, body: any): any { this.logger.info(`[BUNDLE]: ${req.url}`); @@ -39,14 +38,12 @@ export class BundleCallbacks /** * Handle singleplayer/bundles */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getBundles(url: string, info: any, sessionID: string): string { - const local = (this.httpConfig.ip === "127.0.0.1" || this.httpConfig.ip === "localhost"); + const local = this.httpConfig.ip === "127.0.0.1" || this.httpConfig.ip === "localhost"; return this.httpResponse.noBody(this.bundleLoader.getBundles(local)); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getBundle(url: string, info: any, sessionID: string): string { return "BUNDLE"; diff --git a/project/src/callbacks/ClientLogCallbacks.ts b/project/src/callbacks/ClientLogCallbacks.ts index 79fa117c..c62e22cd 100644 --- a/project/src/callbacks/ClientLogCallbacks.ts +++ b/project/src/callbacks/ClientLogCallbacks.ts @@ -10,17 +10,16 @@ export class ClientLogCallbacks { constructor( @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, - @inject("ClientLogController") protected clientLogController: ClientLogController - ) - { } + @inject("ClientLogController") protected clientLogController: ClientLogController, + ) + {} /** * Handle /singleplayer/log */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public clientLog(url: string, info: IClientLogRequest, sessionID: string): INullResponseData { this.clientLogController.clientLog(info); return this.httpResponse.nullResponse(); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/CustomizationCallbacks.ts b/project/src/callbacks/CustomizationCallbacks.ts index 048fceb6..35c85210 100644 --- a/project/src/callbacks/CustomizationCallbacks.ts +++ b/project/src/callbacks/CustomizationCallbacks.ts @@ -18,9 +18,9 @@ export class CustomizationCallbacks constructor( @inject("CustomizationController") protected customizationController: CustomizationController, @inject("SaveServer") protected saveServer: SaveServer, - @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil + @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, ) - { } + {} /** * Handle client/trading/customization/storage @@ -30,7 +30,7 @@ export class CustomizationCallbacks { const result: IGetSuitsResponse = { _id: `pmc${sessionID}`, - suites: this.saveServer.getProfile(sessionID).suits + suites: this.saveServer.getProfile(sessionID).suits, }; return this.httpResponse.getBody(result); } @@ -62,4 +62,4 @@ export class CustomizationCallbacks { return this.customizationController.buyClothing(pmcData, body, sessionID); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/DataCallbacks.ts b/project/src/callbacks/DataCallbacks.ts index c8ba02f0..dd2d2f21 100644 --- a/project/src/callbacks/DataCallbacks.ts +++ b/project/src/callbacks/DataCallbacks.ts @@ -27,15 +27,14 @@ export class DataCallbacks @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("RagfairController") protected ragfairController: RagfairController, - @inject("HideoutController") protected hideoutController: HideoutController + @inject("HideoutController") protected hideoutController: HideoutController, ) - { } + {} /** * Handle client/settings * @returns ISettingsBase */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getSettings(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody(this.databaseServer.getTables().settings); @@ -45,7 +44,6 @@ export class DataCallbacks * Handle client/globals * @returns IGlobals */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getGlobals(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { this.databaseServer.getTables().globals.time = Date.now() / 1000; @@ -56,7 +54,6 @@ export class DataCallbacks * Handle client/items * @returns string */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getTemplateItems(url: string, info: IEmptyRequestData, sessionID: string): string { return this.httpResponse.getUnclearedBody(this.databaseServer.getTables().templates.items); @@ -66,8 +63,11 @@ export class DataCallbacks * Handle client/handbook/templates * @returns IHandbookBase */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getTemplateHandbook(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public getTemplateHandbook( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.databaseServer.getTables().templates.handbook); } @@ -76,8 +76,11 @@ export class DataCallbacks * Handle client/customization * @returns Record> + public getTemplateSuits( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData> { return this.httpResponse.getBody(this.databaseServer.getTables().templates.customization); } @@ -86,7 +89,6 @@ export class DataCallbacks * Handle client/account/customization * @returns string[] */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getTemplateCharacter(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody(this.databaseServer.getTables().templates.character); @@ -96,26 +98,38 @@ export class DataCallbacks * Handle client/hideout/settings * @returns IHideoutSettingsBase */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getHideoutSettings(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public getHideoutSettings( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.databaseServer.getTables().hideout.settings); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getHideoutAreas(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public getHideoutAreas( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.databaseServer.getTables().hideout.areas); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public gethideoutProduction(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public gethideoutProduction( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.databaseServer.getTables().hideout.production); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getHideoutScavcase(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public getHideoutScavcase( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.databaseServer.getTables().hideout.scavcase); } @@ -123,8 +137,11 @@ export class DataCallbacks /** * Handle client/languages */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getLocalesLanguages(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData> + public getLocalesLanguages( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData> { return this.httpResponse.getBody(this.databaseServer.getTables().locales.languages); } @@ -132,25 +149,26 @@ export class DataCallbacks /** * Handle client/menu/locale */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getLocalesMenu(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { - return this.httpResponse.getBody(this.databaseServer.getTables().locales.menu[url.replace("/client/menu/locale/", "")]); + return this.httpResponse.getBody( + this.databaseServer.getTables().locales.menu[url.replace("/client/menu/locale/", "")], + ); } /** * Handle client/locale */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getLocalesGlobal(url: string, info: IEmptyRequestData, sessionID: string): string { - return this.httpResponse.getUnclearedBody(this.databaseServer.getTables().locales.global[url.replace("/client/locale/", "")]); + return this.httpResponse.getUnclearedBody( + this.databaseServer.getTables().locales.global[url.replace("/client/locale/", "")], + ); } /** * Handle client/hideout/qte/list */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getQteList(url: string, info: IEmptyRequestData, sessionID: string): string { return this.httpResponse.getUnclearedBody(this.hideoutController.getQteList(sessionID)); @@ -161,22 +179,24 @@ export class DataCallbacks * Called when viewing a traders assorts * TODO - fully implement this */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getItemPrices(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public getItemPrices( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { const handbookPrices = this.ragfairController.getStaticPrices(); const response: IGetItemPricesResponse = { supplyNextTime: 1672236024, // todo: get trader refresh time? prices: handbookPrices, currencyCourses: { - // eslint-disable-next-line @typescript-eslint/naming-convention + /* eslint-disable @typescript-eslint/naming-convention */ "5449016a4bdc2d6f028b456f": handbookPrices[Money.ROUBLES], - // eslint-disable-next-line @typescript-eslint/naming-convention "569668774bdc2da2298b4568": handbookPrices[Money.EUROS], - // eslint-disable-next-line @typescript-eslint/naming-convention - "5696686a4bdc2da3298b456a": handbookPrices[Money.DOLLARS] - } + "5696686a4bdc2da3298b456a": handbookPrices[Money.DOLLARS], + /* eslint-enable @typescript-eslint/naming-convention */ + }, }; return this.httpResponse.getBody(response); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/DialogueCallbacks.ts b/project/src/callbacks/DialogueCallbacks.ts index 158c84dd..881a1fb3 100644 --- a/project/src/callbacks/DialogueCallbacks.ts +++ b/project/src/callbacks/DialogueCallbacks.ts @@ -3,7 +3,10 @@ import { inject, injectable } from "tsyringe"; import { DialogueController } from "@spt-aki/controllers/DialogueController"; import { OnUpdate } from "@spt-aki/di/OnUpdate"; import { IEmptyRequestData } from "@spt-aki/models/eft/common/IEmptyRequestData"; -import { IAcceptFriendRequestData, ICancelFriendRequestData } from "@spt-aki/models/eft/dialog/IAcceptFriendRequestData"; +import { + IAcceptFriendRequestData, + ICancelFriendRequestData, +} from "@spt-aki/models/eft/dialog/IAcceptFriendRequestData"; import { IChatServer } from "@spt-aki/models/eft/dialog/IChatServer"; import { IClearMailMessageRequest } from "@spt-aki/models/eft/dialog/IClearMailMessageRequest"; import { IDeleteFriendRequest } from "@spt-aki/models/eft/dialog/IDeleteFriendRequest"; @@ -36,16 +39,19 @@ export class DialogueCallbacks implements OnUpdate @inject("HashUtil") protected hashUtil: HashUtil, @inject("TimeUtil") protected timeUtil: TimeUtil, @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, - @inject("DialogueController") protected dialogueController: DialogueController + @inject("DialogueController") protected dialogueController: DialogueController, ) - { - } + {} /** * Handle client/friend/list * @returns IGetFriendListDataResponse */ - public getFriendList(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public getFriendList( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.dialogueController.getFriendList(sessionID)); } @@ -54,45 +60,58 @@ export class DialogueCallbacks implements OnUpdate * Handle client/chatServer/list * @returns IChatServer[] */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getChatServerList(url: string, info: IGetChatServerListRequestData, sessionID: string): IGetBodyResponseData + public getChatServerList( + url: string, + info: IGetChatServerListRequestData, + sessionID: string, + ): IGetBodyResponseData { - - const chatServer: IChatServer = - { - _id: this.hashUtil.generate(), - RegistrationId: 20, - DateTime: this.timeUtil.getTimestamp(), - IsDeveloper: true, - Regions: ["EUR"], - VersionId: "bgkidft87ddd", - Ip: "", - Port: 0, - Chats: [ - { - _id: "0", - Members: 0 - } - ] - }; + const chatServer: IChatServer = { + _id: this.hashUtil.generate(), + RegistrationId: 20, + DateTime: this.timeUtil.getTimestamp(), + IsDeveloper: true, + Regions: ["EUR"], + VersionId: "bgkidft87ddd", // TODO: Is this... correct? + Ip: "", + Port: 0, + Chats: [ + { + _id: "0", + Members: 0, + }, + ], + }; return this.httpResponse.getBody([chatServer]); } /** Handle client/mail/dialog/list */ - public getMailDialogList(url: string, info: IGetMailDialogListRequestData, sessionID: string): IGetBodyResponseData + public getMailDialogList( + url: string, + info: IGetMailDialogListRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.dialogueController.generateDialogueList(sessionID)); } /** Handle client/mail/dialog/view */ - public getMailDialogView(url: string, info: IGetMailDialogViewRequestData, sessionID: string): IGetBodyResponseData + public getMailDialogView( + url: string, + info: IGetMailDialogViewRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.dialogueController.generateDialogueView(info, sessionID)); } /** Handle client/mail/dialog/info */ - public getMailDialogInfo(url: string, info: IGetMailDialogInfoRequestData, sessionID: string): IGetBodyResponseData + public getMailDialogInfo( + url: string, + info: IGetMailDialogInfoRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.dialogueController.getDialogueInfo(info.dialogId, sessionID)); } @@ -129,7 +148,11 @@ export class DialogueCallbacks implements OnUpdate * Handle client/mail/dialog/getAllAttachments * @returns IGetAllAttachmentsResponse */ - public getAllAttachments(url: string, info: IGetAllAttachmentsRequestData, sessionID: string): IGetBodyResponseData + public getAllAttachments( + url: string, + info: IGetAllAttachmentsRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.dialogueController.getAllAttachments(info.dialogId, sessionID)); } @@ -141,7 +164,6 @@ export class DialogueCallbacks implements OnUpdate } /** Handle client/friend/request/list/outbox */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public listOutbox(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody([]); @@ -150,7 +172,6 @@ export class DialogueCallbacks implements OnUpdate /** * Handle client/friend/request/list/inbox */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public listInbox(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody([]); @@ -159,8 +180,11 @@ export class DialogueCallbacks implements OnUpdate /** * Handle client/friend/request/send */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public sendFriendRequest(url: string, request: IFriendRequestData, sessionID: string): IGetBodyResponseData + public sendFriendRequest( + url: string, + request: IFriendRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody({status: 0, requestid: "12345", retryAfter: 600}); } @@ -168,8 +192,11 @@ export class DialogueCallbacks implements OnUpdate /** * Handle client/friend/request/accept */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public acceptFriendRequest(url: string, request: IAcceptFriendRequestData, sessionID: string): IGetBodyResponseData + public acceptFriendRequest( + url: string, + request: IAcceptFriendRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(true); } @@ -177,46 +204,43 @@ export class DialogueCallbacks implements OnUpdate /** * Handle client/friend/request/cancel */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public cancelFriendRequest(url: string, request: ICancelFriendRequestData, sessionID: string): IGetBodyResponseData + public cancelFriendRequest( + url: string, + request: ICancelFriendRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(true); } /** Handle client/friend/delete */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public deleteFriend(url: string, request: IDeleteFriendRequest, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); } /** Handle client/friend/ignore/set */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public ignoreFriend(url: string, request: {uid: string}, sessionID: string): any + public ignoreFriend(url: string, request: {uid: string;}, sessionID: string): any { return this.httpResponse.nullResponse(); } /** Handle client/friend/ignore/remove */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public unIgnoreFriend(url: string, request: {uid: string}, sessionID: string): any + public unIgnoreFriend(url: string, request: {uid: string;}, sessionID: string): any { return this.httpResponse.nullResponse(); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public clearMail(url: string, request: IClearMailMessageRequest, sessionID: string): IGetBodyResponseData { return this.httpResponse.emptyArrayResponse(); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public removeMail(url: string, request: IRemoveMailMessageRequest, sessionID: string): IGetBodyResponseData { return this.httpResponse.emptyArrayResponse(); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public async onUpdate(timeSinceLastRun: number): Promise { this.dialogueController.update(); diff --git a/project/src/callbacks/GameCallbacks.ts b/project/src/callbacks/GameCallbacks.ts index 24c3131b..780c5aa7 100644 --- a/project/src/callbacks/GameCallbacks.ts +++ b/project/src/callbacks/GameCallbacks.ts @@ -20,13 +20,13 @@ import { HttpResponseUtil } from "@spt-aki/utils/HttpResponseUtil"; import { Watermark } from "@spt-aki/utils/Watermark"; @injectable() -class GameCallbacks implements OnLoad +export class GameCallbacks implements OnLoad { constructor( @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("Watermark") protected watermark: Watermark, @inject("SaveServer") protected saveServer: SaveServer, - @inject("GameController") protected gameController: GameController + @inject("GameController") protected gameController: GameController, ) {} @@ -44,7 +44,6 @@ class GameCallbacks implements OnLoad * Handle client/game/version/validate * @returns INullResponseData */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public versionValidate(url: string, info: IVersionValidateRequestData, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); @@ -60,8 +59,7 @@ class GameCallbacks implements OnLoad const startTimeStampMS = Date.parse(today); this.gameController.gameStart(url, info, sessionID, startTimeStampMS); return this.httpResponse.getBody({ - // eslint-disable-next-line @typescript-eslint/naming-convention - utc_time: startTimeStampMS / 1000 + utc_time: startTimeStampMS / 1000, }); } @@ -70,12 +68,15 @@ class GameCallbacks implements OnLoad * Save profiles on game close * @returns IGameLogoutResponseData */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public gameLogout(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public gameLogout( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { this.saveServer.save(); return this.httpResponse.getBody({ - status: "ok" + status: "ok", }); } @@ -83,7 +84,11 @@ class GameCallbacks implements OnLoad * Handle client/game/config * @returns IGameConfigResponse */ - public getGameConfig(url: string, info: IGameEmptyCrcRequestData, sessionID: string): IGetBodyResponseData + public getGameConfig( + url: string, + info: IGameEmptyCrcRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.gameController.getGameConfig(sessionID)); } @@ -91,7 +96,6 @@ class GameCallbacks implements OnLoad /** * Handle client/server/list */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getServer(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody(this.gameController.getServer(sessionID)); @@ -100,7 +104,11 @@ class GameCallbacks implements OnLoad /** * Handle client/match/group/current */ - public getCurrentGroup(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public getCurrentGroup( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.gameController.getCurrentGroup(sessionID)); } @@ -108,8 +116,11 @@ class GameCallbacks implements OnLoad /** * Handle client/checkVersion */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public validateGameVersion(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public validateGameVersion( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.gameController.getValidGameVersion(sessionID)); } @@ -118,8 +129,11 @@ class GameCallbacks implements OnLoad * Handle client/game/keepalive * @returns IGameKeepAliveResponse */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public gameKeepalive(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public gameKeepalive( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.gameController.getKeepAlive(sessionID)); } @@ -128,20 +142,15 @@ class GameCallbacks implements OnLoad * Handle singleplayer/settings/version * @returns string */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getVersion(url: string, info: IEmptyRequestData, sessionID: string): string { return this.httpResponse.noBody({ - Version: this.watermark.getInGameVersionLabel() + Version: this.watermark.getInGameVersionLabel(), }); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public reportNickname(url: string, info: IReportNicknameRequestData, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); } } - -export { GameCallbacks }; - diff --git a/project/src/callbacks/HandbookCallbacks.ts b/project/src/callbacks/HandbookCallbacks.ts index 602f2bda..7f60703c 100644 --- a/project/src/callbacks/HandbookCallbacks.ts +++ b/project/src/callbacks/HandbookCallbacks.ts @@ -7,16 +7,17 @@ import { OnLoad } from "@spt-aki/di/OnLoad"; export class HandbookCallbacks implements OnLoad { constructor( - @inject("HandbookController") protected handbookController: HandbookController + @inject("HandbookController") protected handbookController: HandbookController, ) - { - } - public async onLoad(): Promise + {} + + public async onLoad(): Promise { this.handbookController.load(); } - public getRoute(): string + + public getRoute(): string { return "aki-handbook"; } -} \ No newline at end of file +} diff --git a/project/src/callbacks/HealthCallbacks.ts b/project/src/callbacks/HealthCallbacks.ts index 7d8fdf5c..9fb41cb6 100644 --- a/project/src/callbacks/HealthCallbacks.ts +++ b/project/src/callbacks/HealthCallbacks.ts @@ -18,12 +18,13 @@ export class HealthCallbacks constructor( @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("ProfileHelper") protected profileHelper: ProfileHelper, - @inject("HealthController") protected healthController: HealthController) - { } + @inject("HealthController") protected healthController: HealthController, + ) + {} /** * Custom aki server request found in modules/HealthSynchronizer.cs - * @param url + * @param url * @param info HealthListener.Instance.CurrentHealth class * @param sessionID session id * @returns empty response, no data sent back to client @@ -36,7 +37,7 @@ export class HealthCallbacks /** * Custom aki server request found in modules/QTEPatch.cs - * @param url + * @param url * @param info HealthListener.Instance.CurrentHealth class * @param sessionID session id * @returns empty response, no data sent back to client @@ -44,9 +45,10 @@ export class HealthCallbacks public handleWorkoutEffects(url: string, info: IWorkoutData, sessionID: string): IGetBodyResponseData { this.healthController.applyWorkoutChanges( - this.profileHelper.getPmcProfile(sessionID), info, sessionID + this.profileHelper.getPmcProfile(sessionID), + info, + sessionID, ); - return this.httpResponse.emptyResponse(); } @@ -72,7 +74,11 @@ export class HealthCallbacks * Handle RestoreHealth * @returns IItemEventRouterResponse */ - public healthTreatment(pmcData: IPmcData, info: IHealthTreatmentRequestData, sessionID: string): IItemEventRouterResponse + public healthTreatment( + pmcData: IPmcData, + info: IHealthTreatmentRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.healthController.healthTreatment(pmcData, info, sessionID); } diff --git a/project/src/callbacks/HideoutCallbacks.ts b/project/src/callbacks/HideoutCallbacks.ts index 58581c8a..306a30e5 100644 --- a/project/src/callbacks/HideoutCallbacks.ts +++ b/project/src/callbacks/HideoutCallbacks.ts @@ -28,7 +28,7 @@ export class HideoutCallbacks implements OnUpdate constructor( @inject("HideoutController") protected hideoutController: HideoutController, // TODO: delay needed - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.hideoutConfig = this.configServer.getConfig(ConfigTypes.HIDEOUT); @@ -45,7 +45,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle HideoutUpgradeComplete event */ - public upgradeComplete(pmcData: IPmcData, body: IHideoutUpgradeCompleteRequestData, sessionID: string): IItemEventRouterResponse + public upgradeComplete( + pmcData: IPmcData, + body: IHideoutUpgradeCompleteRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.hideoutController.upgradeComplete(pmcData, body, sessionID); } @@ -53,7 +57,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle HideoutPutItemsInAreaSlots */ - public putItemsInAreaSlots(pmcData: IPmcData, body: IHideoutPutItemInRequestData, sessionID: string): IItemEventRouterResponse + public putItemsInAreaSlots( + pmcData: IPmcData, + body: IHideoutPutItemInRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.hideoutController.putItemsInAreaSlots(pmcData, body, sessionID); } @@ -61,7 +69,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle HideoutTakeItemsFromAreaSlots event */ - public takeItemsFromAreaSlots(pmcData: IPmcData, body: IHideoutTakeItemOutRequestData, sessionID: string): IItemEventRouterResponse + public takeItemsFromAreaSlots( + pmcData: IPmcData, + body: IHideoutTakeItemOutRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.hideoutController.takeItemsFromAreaSlots(pmcData, body, sessionID); } @@ -69,7 +81,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle HideoutToggleArea event */ - public toggleArea(pmcData: IPmcData, body: IHideoutToggleAreaRequestData, sessionID: string): IItemEventRouterResponse + public toggleArea( + pmcData: IPmcData, + body: IHideoutToggleAreaRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.hideoutController.toggleArea(pmcData, body, sessionID); } @@ -77,7 +93,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle HideoutSingleProductionStart event */ - public singleProductionStart(pmcData: IPmcData, body: IHideoutSingleProductionStartRequestData, sessionID: string): IItemEventRouterResponse + public singleProductionStart( + pmcData: IPmcData, + body: IHideoutSingleProductionStartRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.hideoutController.singleProductionStart(pmcData, body, sessionID); } @@ -85,7 +105,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle HideoutScavCaseProductionStart event */ - public scavCaseProductionStart(pmcData: IPmcData, body: IHideoutScavCaseStartRequestData, sessionID: string): IItemEventRouterResponse + public scavCaseProductionStart( + pmcData: IPmcData, + body: IHideoutScavCaseStartRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.hideoutController.scavCaseProductionStart(pmcData, body, sessionID); } @@ -93,7 +117,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle HideoutContinuousProductionStart */ - public continuousProductionStart(pmcData: IPmcData, body: IHideoutContinuousProductionStartRequestData, sessionID: string): IItemEventRouterResponse + public continuousProductionStart( + pmcData: IPmcData, + body: IHideoutContinuousProductionStartRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.hideoutController.continuousProductionStart(pmcData, body, sessionID); } @@ -101,7 +129,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle HideoutTakeProduction event */ - public takeProduction(pmcData: IPmcData, body: IHideoutTakeProductionRequestData, sessionID: string): IItemEventRouterResponse + public takeProduction( + pmcData: IPmcData, + body: IHideoutTakeProductionRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.hideoutController.takeProduction(pmcData, body, sessionID); } @@ -109,7 +141,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle HideoutQuickTimeEvent */ - public handleQTEEvent(pmcData: IPmcData, request: IHandleQTEEventRequestData, sessionId: string): IItemEventRouterResponse + public handleQTEEvent( + pmcData: IPmcData, + request: IHandleQTEEventRequestData, + sessionId: string, + ): IItemEventRouterResponse { return this.hideoutController.handleQTEEventOutcome(sessionId, pmcData, request); } @@ -117,7 +153,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle client/game/profile/items/moving - RecordShootingRangePoints */ - public recordShootingRangePoints(pmcData: IPmcData, request: IRecordShootingRangePoints, sessionId: string): IItemEventRouterResponse + public recordShootingRangePoints( + pmcData: IPmcData, + request: IRecordShootingRangePoints, + sessionId: string, + ): IItemEventRouterResponse { return this.hideoutController.recordShootingRangePoints(sessionId, pmcData, request); } @@ -125,7 +165,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle client/game/profile/items/moving - RecordShootingRangePoints */ - public improveArea(pmcData: IPmcData, request: IHideoutImproveAreaRequestData, sessionId: string): IItemEventRouterResponse + public improveArea( + pmcData: IPmcData, + request: IHideoutImproveAreaRequestData, + sessionId: string, + ): IItemEventRouterResponse { return this.hideoutController.improveArea(sessionId, pmcData, request); } @@ -133,7 +177,11 @@ export class HideoutCallbacks implements OnUpdate /** * Handle client/game/profile/items/moving - HideoutCancelProductionCommand */ - public cancelProduction(pmcData: IPmcData, request: IHideoutCancelProductionRequestData, sessionId: string): IItemEventRouterResponse + public cancelProduction( + pmcData: IPmcData, + request: IHideoutCancelProductionRequestData, + sessionId: string, + ): IItemEventRouterResponse { return this.hideoutController.cancelProduction(sessionId, pmcData, request); } @@ -145,12 +193,11 @@ export class HideoutCallbacks implements OnUpdate this.hideoutController.update(); return true; } - return false; } - public getRoute() :string + public getRoute(): string { return "aki-hideout"; } -} \ No newline at end of file +} diff --git a/project/src/callbacks/HttpCallbacks.ts b/project/src/callbacks/HttpCallbacks.ts index b0c18e19..0012f67c 100644 --- a/project/src/callbacks/HttpCallbacks.ts +++ b/project/src/callbacks/HttpCallbacks.ts @@ -7,22 +7,20 @@ import { HttpServer } from "@spt-aki/servers/HttpServer"; export class HttpCallbacks implements OnLoad { constructor( - @inject("HttpServer") protected httpServer: HttpServer + @inject("HttpServer") protected httpServer: HttpServer, ) - { - } - + {} + public async onLoad(): Promise { this.httpServer.load(); } - public getRoute(): string + public getRoute(): string { return "aki-http"; } - public getImage(): string { return ""; diff --git a/project/src/callbacks/InraidCallbacks.ts b/project/src/callbacks/InraidCallbacks.ts index a4d935cd..71d2dc22 100644 --- a/project/src/callbacks/InraidCallbacks.ts +++ b/project/src/callbacks/InraidCallbacks.ts @@ -14,14 +14,14 @@ export class InraidCallbacks { constructor( @inject("InraidController") protected inraidController: InraidController, - @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil + @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, ) - { } + {} /** * Handle client/location/getLocalloot * Store active map in profile + applicationContext - * @param url + * @param url * @param info register player request * @param sessionID Session id * @returns Null http response @@ -34,7 +34,7 @@ export class InraidCallbacks /** * Handle raid/profile/save - * @param url + * @param url * @param info Save progress request * @param sessionID Session id * @returns Null http response @@ -47,7 +47,7 @@ export class InraidCallbacks /** * Handle singleplayer/settings/raid/endstate - * @returns + * @returns */ public getRaidEndState(): string { @@ -58,7 +58,6 @@ export class InraidCallbacks * Handle singleplayer/settings/raid/menu * @returns JSON as string */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getRaidMenuSettings(): string { return this.httpResponse.noBody(this.inraidController.getInraidConfig().raidMenuSettings); @@ -66,7 +65,7 @@ export class InraidCallbacks /** * Handle singleplayer/settings/weapon/durability - * @returns + * @returns */ public getWeaponDurability(): string { @@ -81,4 +80,4 @@ export class InraidCallbacks { return this.httpResponse.noBody(this.inraidController.getAirdropConfig()); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/InsuranceCallbacks.ts b/project/src/callbacks/InsuranceCallbacks.ts index ec79c625..1af24868 100644 --- a/project/src/callbacks/InsuranceCallbacks.ts +++ b/project/src/callbacks/InsuranceCallbacks.ts @@ -22,7 +22,7 @@ export class InsuranceCallbacks implements OnUpdate @inject("InsuranceController") protected insuranceController: InsuranceController, @inject("InsuranceService") protected insuranceService: InsuranceService, @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.insuranceConfig = this.configServer.getConfig(ConfigTypes.INSURANCE); @@ -32,7 +32,11 @@ export class InsuranceCallbacks implements OnUpdate * Handle client/insurance/items/list/cost * @returns IGetInsuranceCostResponseData */ - public getInsuranceCost(url: string, info: IGetInsuranceCostRequestData, sessionID: string): IGetBodyResponseData + public getInsuranceCost( + url: string, + info: IGetInsuranceCostRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.insuranceController.cost(info, sessionID)); } @@ -53,7 +57,6 @@ export class InsuranceCallbacks implements OnUpdate this.insuranceController.processReturn(); return true; } - return false; } diff --git a/project/src/callbacks/InventoryCallbacks.ts b/project/src/callbacks/InventoryCallbacks.ts index f40d800d..876a20a1 100644 --- a/project/src/callbacks/InventoryCallbacks.ts +++ b/project/src/callbacks/InventoryCallbacks.ts @@ -25,9 +25,9 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve export class InventoryCallbacks { constructor( - @inject("InventoryController") protected inventoryController: InventoryController + @inject("InventoryController") protected inventoryController: InventoryController, ) - { } + {} /** Handle Move event */ public moveItem(pmcData: IPmcData, body: IInventoryMoveRequestData, sessionID: string): IItemEventRouterResponse @@ -52,7 +52,11 @@ export class InventoryCallbacks return this.inventoryController.mergeItem(pmcData, body, sessionID); } - public transferItem(pmcData: IPmcData, body: IInventoryTransferRequestData, sessionID: string): IItemEventRouterResponse + public transferItem( + pmcData: IPmcData, + body: IInventoryTransferRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.inventoryController.transferItem(pmcData, body, sessionID); } @@ -84,41 +88,69 @@ export class InventoryCallbacks return this.inventoryController.bindItem(pmcData, body, sessionID); } - public examineItem(pmcData: IPmcData, body: IInventoryExamineRequestData, sessionID: string): IItemEventRouterResponse + public examineItem( + pmcData: IPmcData, + body: IInventoryExamineRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.inventoryController.examineItem(pmcData, body, sessionID); } /** Handle ReadEncyclopedia */ - public readEncyclopedia(pmcData: IPmcData, body: IInventoryReadEncyclopediaRequestData, sessionID: string): IItemEventRouterResponse + public readEncyclopedia( + pmcData: IPmcData, + body: IInventoryReadEncyclopediaRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.inventoryController.readEncyclopedia(pmcData, body, sessionID); } /** Handle ApplyInventoryChanges */ - public sortInventory(pmcData: IPmcData, body: IInventorySortRequestData, sessionID: string): IItemEventRouterResponse + public sortInventory( + pmcData: IPmcData, + body: IInventorySortRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.inventoryController.sortInventory(pmcData, body, sessionID); } - public createMapMarker(pmcData: IPmcData, body: IInventoryCreateMarkerRequestData, sessionID: string): IItemEventRouterResponse + public createMapMarker( + pmcData: IPmcData, + body: IInventoryCreateMarkerRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.inventoryController.createMapMarker(pmcData, body, sessionID); } - public deleteMapMarker(pmcData: IPmcData, body: IInventoryDeleteMarkerRequestData, sessionID: string): IItemEventRouterResponse + public deleteMapMarker( + pmcData: IPmcData, + body: IInventoryDeleteMarkerRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.inventoryController.deleteMapMarker(pmcData, body, sessionID); } - public editMapMarker(pmcData: IPmcData, body: IInventoryEditMarkerRequestData, sessionID: string): IItemEventRouterResponse + public editMapMarker( + pmcData: IPmcData, + body: IInventoryEditMarkerRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.inventoryController.editMapMarker(pmcData, body, sessionID); } /** Handle OpenRandomLootContainer */ - public openRandomLootContainer(pmcData: IPmcData, body: IOpenRandomLootContainerRequestData, sessionID: string): IItemEventRouterResponse + public openRandomLootContainer( + pmcData: IPmcData, + body: IOpenRandomLootContainerRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.inventoryController.openRandomLootContainer(pmcData, body, sessionID); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/ItemEventCallbacks.ts b/project/src/callbacks/ItemEventCallbacks.ts index 448cffaa..41b16424 100644 --- a/project/src/callbacks/ItemEventCallbacks.ts +++ b/project/src/callbacks/ItemEventCallbacks.ts @@ -13,16 +13,25 @@ export class ItemEventCallbacks { constructor( @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, - @inject("ItemEventRouter") protected itemEventRouter: ItemEventRouter + @inject("ItemEventRouter") protected itemEventRouter: ItemEventRouter, ) - { } + {} - public handleEvents(url: string, info: IItemEventRouterRequest, sessionID: string): IGetBodyResponseData + public handleEvents( + url: string, + info: IItemEventRouterRequest, + sessionID: string, + ): IGetBodyResponseData { const eventResponse = this.itemEventRouter.handleEvents(info, sessionID); - const result = (eventResponse.warnings.length > 0) - ? this.httpResponse.getBody(eventResponse, this.getErrorCode(eventResponse.warnings), eventResponse.warnings[0].errmsg) // TODO: map 228 to its enum value - : this.httpResponse.getBody(eventResponse); + const result = (eventResponse.warnings.length > 0) ? + this.httpResponse.getBody( + eventResponse, + this.getErrorCode(eventResponse.warnings), + eventResponse.warnings[0].errmsg, + ) // TODO: map 228 to its enum value + : + this.httpResponse.getBody(eventResponse); return result; } @@ -33,7 +42,6 @@ export class ItemEventCallbacks { return Number(warnings[0].code); } - return BackendErrorCodes.UNKNOWN_ERROR; } -} \ No newline at end of file +} diff --git a/project/src/callbacks/LauncherCallbacks.ts b/project/src/callbacks/LauncherCallbacks.ts index 14bd5b57..dfaf0467 100644 --- a/project/src/callbacks/LauncherCallbacks.ts +++ b/project/src/callbacks/LauncherCallbacks.ts @@ -11,57 +11,51 @@ import { HttpResponseUtil } from "@spt-aki/utils/HttpResponseUtil"; import { Watermark } from "@spt-aki/utils/Watermark"; @injectable() -class LauncherCallbacks +export class LauncherCallbacks { constructor( @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("LauncherController") protected launcherController: LauncherController, @inject("SaveServer") protected saveServer: SaveServer, - @inject("Watermark") protected watermark: Watermark + @inject("Watermark") protected watermark: Watermark, ) - { } + {} public connect(): string { return this.httpResponse.noBody(this.launcherController.connect()); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public login(url: string, info: ILoginRequestData, sessionID: string): string { const output = this.launcherController.login(info); return (!output) ? "FAILED" : output; } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public register(url: string, info: IRegisterData, sessionID: string): "FAILED" | "OK" { const output = this.launcherController.register(info); return (!output) ? "FAILED" : "OK"; } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public get(url: string, info: ILoginRequestData, sessionID: string): string { const output = this.launcherController.find(this.launcherController.login(info)); return this.httpResponse.noBody(output); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public changeUsername(url: string, info: IChangeRequestData, sessionID: string): "FAILED" | "OK" { const output = this.launcherController.changeUsername(info); return (!output) ? "FAILED" : "OK"; } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public changePassword(url: string, info: IChangeRequestData, sessionID: string): "FAILED" | "OK" { const output = this.launcherController.changePassword(info); return (!output) ? "FAILED" : "OK"; } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public wipe(url: string, info: IRegisterData, sessionID: string): "FAILED" | "OK" { const output = this.launcherController.wipe(info); @@ -73,7 +67,6 @@ class LauncherCallbacks return this.httpResponse.noBody(this.watermark.getVersionTag()); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public ping(url: string, info: IEmptyRequestData, sessionID: string): string { return this.httpResponse.noBody("pong!"); @@ -99,6 +92,3 @@ class LauncherCallbacks return this.httpResponse.noBody(this.launcherController.getServerModsProfileUsed(sessionId)); } } - -export { LauncherCallbacks }; - diff --git a/project/src/callbacks/LocationCallbacks.ts b/project/src/callbacks/LocationCallbacks.ts index 79c77155..a0f0db11 100644 --- a/project/src/callbacks/LocationCallbacks.ts +++ b/project/src/callbacks/LocationCallbacks.ts @@ -13,26 +13,31 @@ export class LocationCallbacks { constructor( @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, - @inject("LocationController") protected locationController: LocationController + @inject("LocationController") protected locationController: LocationController, ) - { } + {} /** Handle client/locations */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getLocationData(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public getLocationData( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.locationController.generateAll(sessionID)); } /** Handle client/location/getLocalloot */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getLocation(url: string, info: IGetLocationRequestData, sessionID: string): IGetBodyResponseData + public getLocation( + url: string, + info: IGetLocationRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.locationController.get(sessionID, info)); } - + /** Handle client/location/getAirdropLoot */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getAirdropLoot(url: string, info: IEmptyRequestData, sessionID: string): string { return this.httpResponse.noBody(this.locationController.getAirdropLoot()); diff --git a/project/src/callbacks/MatchCallbacks.ts b/project/src/callbacks/MatchCallbacks.ts index 35e67fb2..6ed551a9 100644 --- a/project/src/callbacks/MatchCallbacks.ts +++ b/project/src/callbacks/MatchCallbacks.ts @@ -31,53 +31,50 @@ export class MatchCallbacks @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("MatchController") protected matchController: MatchController, - @inject("DatabaseServer") protected databaseServer: DatabaseServer + @inject("DatabaseServer") protected databaseServer: DatabaseServer, ) - { } + {} /** Handle client/match/updatePing */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public updatePing(url: string, info: IUpdatePingRequestData, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); } // Handle client/match/exit - // eslint-disable-next-line @typescript-eslint/no-unused-vars public exitMatch(url: string, info: IEmptyRequestData, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); } /** Handle client/match/group/exit_from_menu */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public exitToMenu(url: string, info: IEmptyRequestData, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public startGroupSearch(url: string, info: IEmptyRequestData, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public stopGroupSearch(url: string, info: IEmptyRequestData, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); } /** Handle client/match/group/invite/send */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public sendGroupInvite(url: string, info: ISendGroupInviteRequest, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody("2427943f23698ay9f2863735"); } /** Handle client/match/group/invite/accept */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public acceptGroupInvite(url: string, info: IAcceptGroupInviteRequest, sessionID: string): IGetBodyResponseData + public acceptGroupInvite( + url: string, + info: IAcceptGroupInviteRequest, + sessionID: string, + ): IGetBodyResponseData { const result = []; result.push({}); @@ -86,41 +83,40 @@ export class MatchCallbacks } /** Handle client/match/group/invite/cancel */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public cancelGroupInvite(url: string, info: ICancelGroupInviteRequest, sessionID: string): IGetBodyResponseData + public cancelGroupInvite( + url: string, + info: ICancelGroupInviteRequest, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(true); } + /** Handle client/match/group/transfer */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public transferGroup(url: string, info: ITransferGroupRequest, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody(true); } /** Handle client/match/group/invite/cancel-all */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public cancelAllGroupInvite(url: string, info: any, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); } /** @deprecated - not called on raid start/end or game start/exit */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public putMetrics(url: string, info: IPutMetricsRequestData, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); } /** Handle raid/profile/list */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getProfile(url: string, info: IGetProfileRequestData, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody(this.matchController.getProfile(info)); } // Handle client/match/available - // eslint-disable-next-line @typescript-eslint/no-unused-vars public serverAvailable(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { const output = this.matchController.getEnabled(); @@ -129,13 +125,16 @@ export class MatchCallbacks } /** Handle match/group/start_game */ - public joinMatch(url: string, info: IJoinMatchRequestData, sessionID: string): IGetBodyResponseData + public joinMatch( + url: string, + info: IJoinMatchRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.matchController.joinMatch(info, sessionID)); } /** Handle client/getMetricsConfig */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getMetrics(url: string, info: any, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody(this.jsonUtil.serialize(this.databaseServer.getTables().match.metrics)); @@ -144,9 +143,8 @@ export class MatchCallbacks /** * @deprecated - not called on raid start/end or game start/exit * Handle client/match/group/status - * @returns + * @returns */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getGroupStatus(url: string, info: IGetGroupStatusRequestData, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody(this.matchController.getGroupStatus(info)); @@ -159,7 +157,6 @@ export class MatchCallbacks } /** Handle client/match/group/delete */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public deleteGroup(url: string, info: any, sessionID: string): INullResponseData { this.matchController.deleteGroup(info); @@ -167,14 +164,12 @@ export class MatchCallbacks } // Handle client/match/group/leave - // eslint-disable-next-line @typescript-eslint/no-unused-vars public leaveGroup(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody(true); } /** Handle client/match/group/player/remove */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public removePlayerFromGroup(url: string, info: IRemovePlayerFromGroupRequest, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); @@ -188,7 +183,11 @@ export class MatchCallbacks } /** Handle client/raid/configuration */ - public getRaidConfiguration(url: string, info: IGetRaidConfigurationRequestData, sessionID: string): INullResponseData + public getRaidConfiguration( + url: string, + info: IGetRaidConfigurationRequestData, + sessionID: string, + ): INullResponseData { this.matchController.startOfflineRaid(info, sessionID); return this.httpResponse.nullResponse(); diff --git a/project/src/callbacks/ModCallbacks.ts b/project/src/callbacks/ModCallbacks.ts index 2ce67a72..9396cef9 100644 --- a/project/src/callbacks/ModCallbacks.ts +++ b/project/src/callbacks/ModCallbacks.ts @@ -11,7 +11,7 @@ import { HttpFileUtil } from "@spt-aki/utils/HttpFileUtil"; import { HttpResponseUtil } from "@spt-aki/utils/HttpResponseUtil"; @injectable() -class ModCallbacks implements OnLoad +export class ModCallbacks implements OnLoad { protected httpConfig: IHttpConfig; @@ -21,12 +21,12 @@ class ModCallbacks implements OnLoad @inject("HttpFileUtil") protected httpFileUtil: HttpFileUtil, @inject("PostAkiModLoader") protected postAkiModLoader: PostAkiModLoader, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.httpConfig = this.configServer.getConfig(ConfigTypes.HTTP); } - + public async onLoad(): Promise { if (globalThis.G_MODS_ENABLED) @@ -40,6 +40,3 @@ class ModCallbacks implements OnLoad return "aki-mods"; } } - -export { ModCallbacks }; - diff --git a/project/src/callbacks/NoteCallbacks.ts b/project/src/callbacks/NoteCallbacks.ts index b781e62b..0e3499ce 100644 --- a/project/src/callbacks/NoteCallbacks.ts +++ b/project/src/callbacks/NoteCallbacks.ts @@ -9,8 +9,9 @@ import { INoteActionData } from "@spt-aki/models/eft/notes/INoteActionData"; export class NoteCallbacks { constructor( - @inject("NoteController") protected noteController: NoteController) - { } + @inject("NoteController") protected noteController: NoteController, + ) + {} /** Handle AddNote event */ public addNote(pmcData: IPmcData, body: INoteActionData, sessionID: string): IItemEventRouterResponse diff --git a/project/src/callbacks/NotifierCallbacks.ts b/project/src/callbacks/NotifierCallbacks.ts index 361cb2ae..244846c8 100644 --- a/project/src/callbacks/NotifierCallbacks.ts +++ b/project/src/callbacks/NotifierCallbacks.ts @@ -17,8 +17,9 @@ export class NotifierCallbacks @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper, @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("JsonUtil") protected jsonUtil: JsonUtil, - @inject("NotifierController") protected notifierController: NotifierController) - { } + @inject("NotifierController") protected notifierController: NotifierController, + ) + {} /** * If we don't have anything to send, it's ok to not send anything back @@ -26,7 +27,6 @@ export class NotifierCallbacks * until we actually have something to send because otherwise we'd spam the client * and the client would abort the connection due to spam. */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public sendNotification(sessionID: string, req: any, resp: any, data: any): void { const splittedUrl = req.url.split("/"); @@ -43,14 +43,17 @@ export class NotifierCallbacks /** Handle push/notifier/get */ /** Handle push/notifier/getwebsocket */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getNotifier(url: string, info: any, sessionID: string): IGetBodyResponseData { return this.httpResponse.emptyArrayResponse(); } /** Handle client/notifier/channel/create */ - public createNotifierChannel(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public createNotifierChannel( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.notifierController.getChannel(sessionID)); } @@ -59,17 +62,19 @@ export class NotifierCallbacks * Handle client/game/profile/select * @returns ISelectProfileResponse */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public selectProfile(url: string, info: ISelectProfileRequestData, sessionID: string): IGetBodyResponseData + public selectProfile( + url: string, + info: ISelectProfileRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody({ - status: "ok" + status: "ok", }); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public notify(url: string, info: any, sessionID: string): string { return "NOTIFY"; } -} \ No newline at end of file +} diff --git a/project/src/callbacks/PresetBuildCallbacks.ts b/project/src/callbacks/PresetBuildCallbacks.ts index bda577e1..a7343333 100644 --- a/project/src/callbacks/PresetBuildCallbacks.ts +++ b/project/src/callbacks/PresetBuildCallbacks.ts @@ -15,17 +15,26 @@ export class PresetBuildCallbacks { constructor( @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, - @inject("PresetBuildController") protected presetBuildController: PresetBuildController) - { } + @inject("PresetBuildController") protected presetBuildController: PresetBuildController, + ) + {} /** Handle client/handbook/builds/my/list */ - public getHandbookUserlist(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public getHandbookUserlist( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.presetBuildController.getUserBuilds(sessionID)); } /** Handle SaveWeaponBuild event */ - public saveWeaponBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string): IItemEventRouterResponse + public saveWeaponBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.presetBuildController.saveWeaponBuild(pmcData, body, sessionID); } @@ -37,20 +46,32 @@ export class PresetBuildCallbacks } /** Handle RemoveWeaponBuild event*/ - public removeWeaponBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string): IItemEventRouterResponse + public removeWeaponBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.presetBuildController.removeWeaponBuild(pmcData, body, sessionID); } /** Handle SaveEquipmentBuild event */ - public saveEquipmentBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string): IItemEventRouterResponse + public saveEquipmentBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.presetBuildController.saveEquipmentBuild(pmcData, body, sessionID); } /** Handle RemoveEquipmentBuild event*/ - public removeEquipmentBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string): IItemEventRouterResponse + public removeEquipmentBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.presetBuildController.removeEquipmentBuild(pmcData, body, sessionID); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/PresetCallbacks.ts b/project/src/callbacks/PresetCallbacks.ts index 288c0399..3ded09d4 100644 --- a/project/src/callbacks/PresetCallbacks.ts +++ b/project/src/callbacks/PresetCallbacks.ts @@ -7,16 +7,16 @@ import { OnLoad } from "@spt-aki/di/OnLoad"; export class PresetCallbacks implements OnLoad { constructor( - @inject("PresetController") protected presetController: PresetController) - { - } + @inject("PresetController") protected presetController: PresetController, + ) + {} public async onLoad(): Promise { this.presetController.initialize(); } - public getRoute(): string + public getRoute(): string { return "aki-presets"; } diff --git a/project/src/callbacks/ProfileCallbacks.ts b/project/src/callbacks/ProfileCallbacks.ts index d461aa44..591f4e35 100644 --- a/project/src/callbacks/ProfileCallbacks.ts +++ b/project/src/callbacks/ProfileCallbacks.ts @@ -24,8 +24,9 @@ export class ProfileCallbacks constructor( @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("TimeUtil") protected timeUtil: TimeUtil, - @inject("ProfileController") protected profileController: ProfileController) - { } + @inject("ProfileController") protected profileController: ProfileController, + ) + {} /** * Handle client/game/profile/create @@ -33,7 +34,7 @@ export class ProfileCallbacks public createProfile(url: string, info: IProfileCreateRequestData, sessionID: string): IGetBodyResponseData { this.profileController.createProfile(info, sessionID); - return this.httpResponse.getBody({ uid: `pmc${sessionID}` }); + return this.httpResponse.getBody({uid: `pmc${sessionID}`}); } /** @@ -49,7 +50,7 @@ export class ProfileCallbacks * Handle client/game/profile/savage/regenerate * Handle the creation of a scav profile for player * Occurs post-raid and when profile first created immediately after character details are confirmed by player - * @param url + * @param url * @param info empty * @param sessionID Session id * @returns Profile object @@ -72,7 +73,11 @@ export class ProfileCallbacks * Handle client/game/profile/nickname/change event * Client allows player to adjust their profile name */ - public changeNickname(url: string, info: IProfileChangeNicknameRequestData, sessionID: string): IGetBodyResponseData + public changeNickname( + url: string, + info: IProfileChangeNicknameRequestData, + sessionID: string, + ): IGetBodyResponseData { const output = this.profileController.changeNickname(info, sessionID); @@ -88,14 +93,18 @@ export class ProfileCallbacks return this.httpResponse.getBody({ status: 0, - nicknamechangedate: this.timeUtil.getTimestamp() + nicknamechangedate: this.timeUtil.getTimestamp(), }); } /** * Handle client/game/profile/nickname/validate */ - public validateNickname(url: string, info: IValidateNicknameRequestData, sessionID: string): IGetBodyResponseData + public validateNickname( + url: string, + info: IValidateNicknameRequestData, + sessionID: string, + ): IGetBodyResponseData { const output = this.profileController.validateNickname(info, sessionID); @@ -109,13 +118,12 @@ export class ProfileCallbacks return this.httpResponse.getBody(null, 256, "256 - "); } - return this.httpResponse.getBody({ status: "ok" }); + return this.httpResponse.getBody({status: "ok"}); } /** * Handle client/game/profile/nickname/reserved */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getReservedNickname(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody("SPTarkov"); @@ -125,7 +133,11 @@ export class ProfileCallbacks * Handle client/profile/status * Called when creating a character when choosing a character face/voice */ - public getProfileStatus(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public getProfileStatus( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { const response: GetProfileStatusResponseData = { maxPveCountExceeded: false, @@ -141,8 +153,7 @@ export class ProfileCallbacks location: "bigmap", raidMode: "Online", mode: "deathmatch", - shortId: "xxx1x1" - + shortId: "xxx1x1", }, { profileid: `pmc${sessionID}`, @@ -150,9 +161,9 @@ export class ProfileCallbacks status: "Free", sid: "", ip: "", - port: 0 - } - ] + port: 0, + }, + ], }; return this.httpResponse.getBody(response); @@ -161,8 +172,11 @@ export class ProfileCallbacks /** * Handle client/profile/settings */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getProfileSettings(url: string, info: IGetProfileSettingsRequest, sessionId: string): IGetBodyResponseData + public getProfileSettings( + url: string, + info: IGetProfileSettingsRequest, + sessionId: string, + ): IGetBodyResponseData { return this.httpResponse.emptyResponse(); } @@ -170,7 +184,11 @@ export class ProfileCallbacks /** * Handle client/game/profile/search */ - public searchFriend(url: string, info: ISearchFriendRequestData, sessionID: string): IGetBodyResponseData + public searchFriend( + url: string, + info: ISearchFriendRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.profileController.getFriends(info, sessionID)); } @@ -186,9 +204,8 @@ export class ProfileCallbacks /** * Handle /launcher/profiles */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getAllMiniProfiles(url: string, info: IEmptyRequestData, sessionID: string): string { return this.httpResponse.noBody(this.profileController.getMiniProfiles()); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/QuestCallbacks.ts b/project/src/callbacks/QuestCallbacks.ts index a97a93f9..b2c76970 100644 --- a/project/src/callbacks/QuestCallbacks.ts +++ b/project/src/callbacks/QuestCallbacks.ts @@ -21,13 +21,18 @@ export class QuestCallbacks constructor( @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("QuestController") protected questController: QuestController, - @inject("RepeatableQuestController") protected repeatableQuestController: RepeatableQuestController) - { } + @inject("RepeatableQuestController") protected repeatableQuestController: RepeatableQuestController, + ) + {} /** * Handle RepeatableQuestChange event */ - public changeRepeatableQuest(pmcData: IPmcData, body: IRepeatableQuestChangeRequest, sessionID: string): IItemEventRouterResponse + public changeRepeatableQuest( + pmcData: IPmcData, + body: IRepeatableQuestChangeRequest, + sessionID: string, + ): IItemEventRouterResponse { return this.repeatableQuestController.changeRepeatableQuest(pmcData, body, sessionID); } @@ -41,14 +46,17 @@ export class QuestCallbacks { return this.questController.acceptRepeatableQuest(pmcData, body, sessionID); } - return this.questController.acceptQuest(pmcData, body, sessionID); } /** * Handle QuestComplete event */ - public completeQuest(pmcData: IPmcData, body: ICompleteQuestRequestData, sessionID: string): IItemEventRouterResponse + public completeQuest( + pmcData: IPmcData, + body: ICompleteQuestRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.questController.completeQuest(pmcData, body, sessionID); } @@ -56,7 +64,11 @@ export class QuestCallbacks /** * Handle QuestHandover event */ - public handoverQuest(pmcData: IPmcData, body: IHandoverQuestRequestData, sessionID: string): IItemEventRouterResponse + public handoverQuest( + pmcData: IPmcData, + body: IHandoverQuestRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.questController.handoverQuest(pmcData, body, sessionID); } @@ -72,7 +84,11 @@ export class QuestCallbacks /** * Handle client/repeatalbeQuests/activityPeriods */ - public activityPeriods(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public activityPeriods( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.repeatableQuestController.getClientRepeatableQuests(info, sessionID)); } diff --git a/project/src/callbacks/RagfairCallbacks.ts b/project/src/callbacks/RagfairCallbacks.ts index 6b95a323..4b5012ec 100644 --- a/project/src/callbacks/RagfairCallbacks.ts +++ b/project/src/callbacks/RagfairCallbacks.ts @@ -39,7 +39,7 @@ export class RagfairCallbacks implements OnLoad, OnUpdate @inject("RagfairServer") protected ragfairServer: RagfairServer, @inject("RagfairController") protected ragfairController: RagfairController, @inject("RagfairTaxService") protected ragfairTaxService: RagfairTaxService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); @@ -67,7 +67,6 @@ export class RagfairCallbacks implements OnLoad, OnUpdate return true; } - return false; } @@ -81,8 +80,11 @@ export class RagfairCallbacks implements OnLoad, OnUpdate } /** Handle client/ragfair/itemMarketPrice */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getMarketPrice(url: string, info: IGetMarketPriceRequestData, sessionID: string): IGetBodyResponseData + public getMarketPrice( + url: string, + info: IGetMarketPriceRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.ragfairController.getItemMinAvgMaxFleaPriceValues(info)); } @@ -93,7 +95,7 @@ export class RagfairCallbacks implements OnLoad, OnUpdate return this.ragfairController.addPlayerOffer(pmcData, info, sessionID); } - /** \Handle RagFairRemoveOffer event */ + /** Handle RagFairRemoveOffer event */ public removeOffer(pmcData: IPmcData, info: IRemoveOfferRequestData, sessionID: string): IItemEventRouterResponse { return this.ragfairController.removeOffer(info.offerId, sessionID); @@ -109,23 +111,28 @@ export class RagfairCallbacks implements OnLoad, OnUpdate * Handle /client/items/prices * Called when clicking an item to list on flea */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public getFleaPrices(url: string, request: IEmptyRequestData, sessionID: string): IGetBodyResponseData> + public getFleaPrices( + url: string, + request: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData> { return this.httpResponse.getBody(this.ragfairController.getAllFleaPrices()); } /** Handle client/reports/ragfair/send */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public sendReport(url: string, info: ISendRagfairReportRequestData, sessionID: string): INullResponseData { return this.httpResponse.nullResponse(); } - public storePlayerOfferTaxAmount(url: string, request: IStorePlayerOfferTaxAmountRequestData, sessionId: string): INullResponseData + public storePlayerOfferTaxAmount( + url: string, + request: IStorePlayerOfferTaxAmountRequestData, + sessionId: string, + ): INullResponseData { this.ragfairTaxService.storeClientOfferTaxValue(sessionId, request); return this.httpResponse.nullResponse(); } - } diff --git a/project/src/callbacks/RepairCallbacks.ts b/project/src/callbacks/RepairCallbacks.ts index 85f5c5ea..034f1d2f 100644 --- a/project/src/callbacks/RepairCallbacks.ts +++ b/project/src/callbacks/RepairCallbacks.ts @@ -10,8 +10,9 @@ import { ITraderRepairActionDataRequest } from "@spt-aki/models/eft/repair/ITrad export class RepairCallbacks { constructor( - @inject("RepairController") protected repairController: RepairController) - { } + @inject("RepairController") protected repairController: RepairController, + ) + {} /** * Handle TraderRepair event @@ -21,7 +22,11 @@ export class RepairCallbacks * @param sessionID Session id * @returns IItemEventRouterResponse */ - public traderRepair(pmcData: IPmcData, traderRepairRequest: ITraderRepairActionDataRequest, sessionID: string): IItemEventRouterResponse + public traderRepair( + pmcData: IPmcData, + traderRepairRequest: ITraderRepairActionDataRequest, + sessionID: string, + ): IItemEventRouterResponse { return this.repairController.traderRepair(sessionID, traderRepairRequest, pmcData); } @@ -34,8 +39,12 @@ export class RepairCallbacks * @param sessionID Session id * @returns IItemEventRouterResponse */ - public repair(pmcData: IPmcData, repairRequest: IRepairActionDataRequest, sessionID: string): IItemEventRouterResponse + public repair( + pmcData: IPmcData, + repairRequest: IRepairActionDataRequest, + sessionID: string, + ): IItemEventRouterResponse { return this.repairController.repairWithKit(sessionID, repairRequest, pmcData); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/SaveCallbacks.ts b/project/src/callbacks/SaveCallbacks.ts index 86e0dbd0..7af5ec16 100644 --- a/project/src/callbacks/SaveCallbacks.ts +++ b/project/src/callbacks/SaveCallbacks.ts @@ -14,18 +14,18 @@ export class SaveCallbacks implements OnLoad, OnUpdate constructor( @inject("SaveServer") protected saveServer: SaveServer, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.coreConfig = this.configServer.getConfig(ConfigTypes.CORE); } - + public async onLoad(): Promise { this.saveServer.load(); } - public getRoute(): string + public getRoute(): string { return "aki-save"; } @@ -38,7 +38,6 @@ export class SaveCallbacks implements OnLoad, OnUpdate this.saveServer.save(); return true; } - return false; } -} \ No newline at end of file +} diff --git a/project/src/callbacks/TradeCallbacks.ts b/project/src/callbacks/TradeCallbacks.ts index 1c39e280..9b9b8ce8 100644 --- a/project/src/callbacks/TradeCallbacks.ts +++ b/project/src/callbacks/TradeCallbacks.ts @@ -11,28 +11,40 @@ import { ISellScavItemsToFenceRequestData } from "@spt-aki/models/eft/trade/ISel export class TradeCallbacks { constructor( - @inject("TradeController") protected tradeController: TradeController + @inject("TradeController") protected tradeController: TradeController, ) - { } + {} /** * Handle client/game/profile/items/moving TradingConfirm event */ - public processTrade(pmcData: IPmcData, body: IProcessBaseTradeRequestData, sessionID: string): IItemEventRouterResponse + public processTrade( + pmcData: IPmcData, + body: IProcessBaseTradeRequestData, + sessionID: string, + ): IItemEventRouterResponse { // body can be IProcessBuyTradeRequestData or IProcessSellTradeRequestData return this.tradeController.confirmTrading(pmcData, body, sessionID); } /** Handle RagFairBuyOffer event */ - public processRagfairTrade(pmcData: IPmcData, body: IProcessRagfairTradeRequestData, sessionID: string): IItemEventRouterResponse + public processRagfairTrade( + pmcData: IPmcData, + body: IProcessRagfairTradeRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.tradeController.confirmRagfairTrading(pmcData, body, sessionID); } /** Handle SellAllFromSavage event */ - public sellAllFromSavage(pmcData: IPmcData, body: ISellScavItemsToFenceRequestData, sessionID: string): IItemEventRouterResponse + public sellAllFromSavage( + pmcData: IPmcData, + body: ISellScavItemsToFenceRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.tradeController.sellScavItemsToFence(pmcData, body, sessionID); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/TraderCallbacks.ts b/project/src/callbacks/TraderCallbacks.ts index 8d271616..607272b7 100644 --- a/project/src/callbacks/TraderCallbacks.ts +++ b/project/src/callbacks/TraderCallbacks.ts @@ -12,10 +12,11 @@ import { HttpResponseUtil } from "@spt-aki/utils/HttpResponseUtil"; export class TraderCallbacks implements OnLoad, OnUpdate { constructor( - @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, - @inject("TraderController") protected traderController: TraderController) // TODO: delay required - { - } + @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, // TODO: delay required + @inject("TraderController") protected traderController: TraderController, + ) + {} + public async onLoad(): Promise { this.traderController.load(); @@ -26,13 +27,17 @@ export class TraderCallbacks implements OnLoad, OnUpdate return this.traderController.update(); } - public getRoute(): string + public getRoute(): string { return "aki-traders"; } /** Handle client/trading/api/traderSettings */ - public getTraderSettings(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData + public getTraderSettings( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData { return this.httpResponse.getBody(this.traderController.getAllTraders(sessionID)); } @@ -50,4 +55,4 @@ export class TraderCallbacks implements OnLoad, OnUpdate const traderID = url.replace("/client/trading/api/getTraderAssort/", ""); return this.httpResponse.getBody(this.traderController.getAssort(sessionID, traderID)); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/WeatherCallbacks.ts b/project/src/callbacks/WeatherCallbacks.ts index 0067db90..6448e536 100644 --- a/project/src/callbacks/WeatherCallbacks.ts +++ b/project/src/callbacks/WeatherCallbacks.ts @@ -11,17 +11,16 @@ export class WeatherCallbacks { constructor( @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, - @inject("WeatherController") protected weatherController: WeatherController + @inject("WeatherController") protected weatherController: WeatherController, ) - { } + {} /** * Handle client/weather * @returns IWeatherData */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getWeather(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { return this.httpResponse.getBody(this.weatherController.generate()); } -} \ No newline at end of file +} diff --git a/project/src/callbacks/WishlistCallbacks.ts b/project/src/callbacks/WishlistCallbacks.ts index a13402d3..c4b659d7 100644 --- a/project/src/callbacks/WishlistCallbacks.ts +++ b/project/src/callbacks/WishlistCallbacks.ts @@ -9,8 +9,9 @@ import { IWishlistActionData } from "@spt-aki/models/eft/wishlist/IWishlistActio export class WishlistCallbacks { constructor( - @inject("WishlistController") protected wishlistController: WishlistController) - { } + @inject("WishlistController") protected wishlistController: WishlistController, + ) + {} /** Handle AddToWishList event */ public addToWishlist(pmcData: IPmcData, body: IWishlistActionData, sessionID: string): IItemEventRouterResponse @@ -23,4 +24,4 @@ export class WishlistCallbacks { return this.wishlistController.removeFromWishList(pmcData, body, sessionID); } -} \ No newline at end of file +} From 5fa8803f8c5d82854a10016328610e404ffd3f61 Mon Sep 17 00:00:00 2001 From: Refringe Date: Fri, 10 Nov 2023 15:23:51 -0500 Subject: [PATCH 22/41] Auto-formatting for context classes. --- project/src/context/ApplicationContext.ts | 37 ++++++++++++---------- project/src/context/ContextVariable.ts | 2 +- project/src/context/ContextVariableType.ts | 18 ++++------- 3 files changed, 29 insertions(+), 28 deletions(-) diff --git a/project/src/context/ApplicationContext.ts b/project/src/context/ApplicationContext.ts index bd8dc12f..28850cd5 100644 --- a/project/src/context/ApplicationContext.ts +++ b/project/src/context/ApplicationContext.ts @@ -5,29 +5,29 @@ import { ContextVariableType } from "@spt-aki/context/ContextVariableType"; import { LinkedList } from "@spt-aki/utils/collections/lists/LinkedList"; @injectable() -export class ApplicationContext +export class ApplicationContext { private variables = new Map>(); private static holderMaxSize = 10; /** - * Called like: - * - * const registerPlayerInfo = this.applicationContext.getLatestValue(ContextVariableType.REGISTER_PLAYER_REQUEST).getValue(); - * - * const activePlayerSessionId = this.applicationContext.getLatestValue(ContextVariableType.SESSION_ID).getValue(); - * - * const matchInfo = this.applicationContext.getLatestValue(ContextVariableType.MATCH_INFO).getValue(); - * @param type - * @returns + * @examples + * + * const registerPlayerInfo = this.applicationContext.getLatestValue(ContextVariableType.REGISTER_PLAYER_REQUEST) + * .getValue(); + * + * const activePlayerSessionId = this.applicationContext.getLatestValue(ContextVariableType.SESSION_ID) + * .getValue(); + * + * const matchInfo = this.applicationContext.getLatestValue(ContextVariableType.MATCH_INFO) + * .getValue(); */ - public getLatestValue(type: ContextVariableType): ContextVariable + public getLatestValue(type: ContextVariableType): ContextVariable { - if (this.variables.has(type)) + if (this.variables.has(type)) { return this.variables.get(type)?.getTail()?.getValue(); } - return undefined; } @@ -37,22 +37,27 @@ export class ApplicationContext { return this.variables.get(type).toList(); } - return undefined; } - public addValue(type: ContextVariableType, value: any): void + public addValue(type: ContextVariableType, value: any): void { let list: LinkedList; if (this.variables.has(type)) + { list = this.variables.get(type); + } else + { list = new LinkedList(); + } if (list.getSize() >= ApplicationContext.holderMaxSize) + { list.removeFirst(); + } list.add(new ContextVariable(value, type)); this.variables.set(type, list); } -} \ No newline at end of file +} diff --git a/project/src/context/ContextVariable.ts b/project/src/context/ContextVariable.ts index 8abc00d7..9dd5755d 100644 --- a/project/src/context/ContextVariable.ts +++ b/project/src/context/ContextVariable.ts @@ -27,4 +27,4 @@ export class ContextVariable { return this.type; } -} \ No newline at end of file +} diff --git a/project/src/context/ContextVariableType.ts b/project/src/context/ContextVariableType.ts index 86fea151..8d45403d 100644 --- a/project/src/context/ContextVariableType.ts +++ b/project/src/context/ContextVariableType.ts @@ -1,11 +1,7 @@ -export enum ContextVariableType - { - /** Logged in users session id */ - SESSION_ID = 0, - /** Currently acive raid information */ - RAID_CONFIGURATION = 1, - /** Timestamp when client first connected */ - CLIENT_START_TIMESTAMP = 2, - /** When player is loading into map and loot is requested */ - REGISTER_PLAYER_REQUEST = 3 -} \ No newline at end of file +export enum ContextVariableType +{ + SESSION_ID = 0, // Logged in users session id + RAID_CONFIGURATION = 1, // Currently active raid information + CLIENT_START_TIMESTAMP = 2, // Timestamp when client first connected + REGISTER_PLAYER_REQUEST = 3, // When player is loading into map and loot is requested +} From 87bb07cfd985f23ff7f8c39881304ad4fb405aa3 Mon Sep 17 00:00:00 2001 From: Refringe Date: Fri, 10 Nov 2023 16:49:29 -0500 Subject: [PATCH 23/41] Formatting for controller classes. --- project/Server.code-workspace | 53 +- project/src/controllers/BotController.ts | 91 ++-- .../src/controllers/ClientLogController.ts | 6 +- .../controllers/CustomizationController.ts | 62 ++- project/src/controllers/DialogueController.ts | 148 ++++-- project/src/controllers/GameController.ts | 207 ++++---- project/src/controllers/HandbookController.ts | 6 +- project/src/controllers/HealthController.ts | 50 +- project/src/controllers/HideoutController.ts | 486 ++++++++++++------ project/src/controllers/InraidController.ts | 107 ++-- .../src/controllers/InsuranceController.ts | 101 ++-- .../src/controllers/InventoryController.ts | 283 ++++++---- project/src/controllers/LauncherController.ts | 21 +- project/src/controllers/LocationController.ts | 31 +- project/src/controllers/MatchController.ts | 47 +- project/src/controllers/NoteController.ts | 8 +- project/src/controllers/NotifierController.ts | 5 +- .../src/controllers/PresetBuildController.ts | 88 +++- project/src/controllers/PresetController.ts | 4 +- project/src/controllers/ProfileController.ts | 83 +-- project/src/controllers/QuestController.ts | 315 +++++++++--- project/src/controllers/RagfairController.ts | 272 +++++++--- project/src/controllers/RepairController.ts | 31 +- .../controllers/RepeatableQuestController.ts | 134 +++-- project/src/controllers/TradeController.ts | 118 +++-- project/src/controllers/TraderController.ts | 13 +- project/src/controllers/WeatherController.ts | 6 +- project/src/controllers/WishlistController.ts | 8 +- 28 files changed, 1870 insertions(+), 914 deletions(-) diff --git a/project/Server.code-workspace b/project/Server.code-workspace index 38ce6f32..2c833b46 100644 --- a/project/Server.code-workspace +++ b/project/Server.code-workspace @@ -21,12 +21,63 @@ "source.fixAll.eslint", "source.organizeImports.biome" ], + "cSpell.language": "en-GB", "cSpell.words": [ + "armor", + "asonline", + "behaviour", + "biomejs", + "botreload", + "currexp", + "currlvl", + "dbaeumer", "deathmatch", + "dprint", + "edgeofdarkness", + "fulfill", "gethideout", + "gifter", + "hpresource", + "inraid", + "isvalid", + "leftbehind", + "leveled", + "loadout", + "maxlvl", + "medkit", + "MEDSTATION", + "nextlvl", + "offraid", + "peacefullzryachiyevent", + "preparetoescape", + "prevexp", "profileid", + "Protobuf", + "pscav", + "Ragfair", + "Regen", "requestid", - "scavcase" + "sanitise", + "Sanitised", + "scav", + "scavcase", + "scavs", + "Spawnpoint", + "spawnpoints", + "sptbear", + "sptdeveloper", + "spteasystart", + "sptusec", + "sptzerotohero", + "stackcount", + "statustimer", + "Tarkov", + "toggleable", + "tooshort", + "unrestartable", + "usec", + "userbuilds", + "Wishlist" ] } } diff --git a/project/src/controllers/BotController.ts b/project/src/controllers/BotController.ts index d13136a2..c10640b4 100644 --- a/project/src/controllers/BotController.ts +++ b/project/src/controllers/BotController.ts @@ -43,7 +43,7 @@ export class BotController @inject("ProfileHelper") protected profileHelper: ProfileHelper, @inject("ConfigServer") protected configServer: ConfigServer, @inject("ApplicationContext") protected applicationContext: ApplicationContext, - @inject("JsonUtil") protected jsonUtil: JsonUtil + @inject("JsonUtil") protected jsonUtil: JsonUtil, ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); @@ -51,29 +51,29 @@ export class BotController } /** - * Return the number of bot loadout varieties to be generated - * @param type bot Type we want the loadout gen count for + * Return the number of bot load-out varieties to be generated + * @param type bot Type we want the load-out gen count for * @returns number of bots to generate */ public getBotPresetGenerationLimit(type: string): number { - const value = this.botConfig.presetBatch[(type === "assaultGroup") - ? "assault" - : type]; + const value = this.botConfig.presetBatch[ + (type === "assaultGroup") ? + "assault" : + type + ]; if (!value) { this.logger.warning(`No value found for bot type ${type}, defaulting to 30`); - return value; } - return value; } /** * Handle singleplayer/settings/bot/difficulty - * Get the core.json difficulty settings from database\bots + * Get the core.json difficulty settings from database/bots * @returns IBotCore */ public getBotCoreDifficulty(): IBotCore @@ -90,10 +90,14 @@ export class BotController */ public getBotDifficulty(type: string, difficulty: string): Difficulty { - const raidConfig = this.applicationContext.getLatestValue(ContextVariableType.RAID_CONFIGURATION)?.getValue(); + const raidConfig = this.applicationContext.getLatestValue(ContextVariableType.RAID_CONFIGURATION)?.getValue< + IGetRaidConfigurationRequestData + >(); if (!raidConfig) { - this.logger.error(this.localisationService.getText("bot-missing_application_context", "RAID_CONFIGURATION")); + this.logger.error( + this.localisationService.getText("bot-missing_application_context", "RAID_CONFIGURATION"), + ); } // Check value chosen in pre-raid difficulty dropdown @@ -101,7 +105,9 @@ export class BotController const botDifficultyDropDownValue = raidConfig.wavesSettings.botDifficulty.toLowerCase(); if (botDifficultyDropDownValue !== "asonline") { - difficulty = this.botDifficultyHelper.convertBotDifficultyDropdownToBotDifficulty(botDifficultyDropDownValue); + difficulty = this.botDifficultyHelper.convertBotDifficultyDropdownToBotDifficulty( + botDifficultyDropDownValue, + ); } let difficultySettings: Difficulty; @@ -109,19 +115,31 @@ export class BotController switch (lowercasedBotType) { case this.pmcConfig.bearType.toLowerCase(): - difficultySettings = this.botDifficultyHelper.getPmcDifficultySettings("bear", difficulty, this.pmcConfig.usecType, this.pmcConfig.bearType); + difficultySettings = this.botDifficultyHelper.getPmcDifficultySettings( + "bear", + difficulty, + this.pmcConfig.usecType, + this.pmcConfig.bearType, + ); break; case this.pmcConfig.usecType.toLowerCase(): - difficultySettings = this.botDifficultyHelper.getPmcDifficultySettings("usec", difficulty, this.pmcConfig.usecType, this.pmcConfig.bearType); + difficultySettings = this.botDifficultyHelper.getPmcDifficultySettings( + "usec", + difficulty, + this.pmcConfig.usecType, + this.pmcConfig.bearType, + ); break; default: difficultySettings = this.botDifficultyHelper.getBotDifficultySettings(type, difficulty); - // Don't add pmcs to event enemies (e.g. gifter/peacefullzryachiyevent) + // Don't add PMCs to event enemies (e.g. gifter/peacefullzryachiyevent) if (!this.botConfig.botsToNotAddPMCsAsEnemiesTo.includes(type.toLowerCase())) { - this.botHelper.addBotToEnemyList(difficultySettings, [this.pmcConfig.bearType, this.pmcConfig.usecType], lowercasedBotType); + this.botHelper.addBotToEnemyList(difficultySettings, [ + this.pmcConfig.bearType, + this.pmcConfig.usecType, + ], lowercasedBotType); } - break; } @@ -149,7 +167,7 @@ export class BotController botRelativeLevelDeltaMax: this.pmcConfig.botRelativeLevelDeltaMax, botCountToGenerate: this.botConfig.presetBatch[condition.Role], botDifficulty: condition.Difficulty, - isPlayerScav: false + isPlayerScav: false, }; // Event bots need special actions to occur, set data up for them @@ -158,7 +176,9 @@ export class BotController { // Add eventRole data + reassign role property to be base type botGenerationDetails.eventRole = condition.Role; - botGenerationDetails.role = this.seasonalEventService.getBaseRoleForEventBot(botGenerationDetails.eventRole); + botGenerationDetails.role = this.seasonalEventService.getBaseRoleForEventBot( + botGenerationDetails.eventRole, + ); } // Custom map waves can have spt roles in them @@ -171,10 +191,10 @@ export class BotController // Loop over and make x bots for this condition let cacheKey = ""; - for (let i = 0; i < botGenerationDetails.botCountToGenerate; i ++) + for (let i = 0; i < botGenerationDetails.botCountToGenerate; i++) { const details = this.jsonUtil.clone(botGenerationDetails); - const botRole = (isEventBot) ? details.eventRole : details.role; + const botRole = isEventBot ? details.eventRole : details.role; // Roll chance to be pmc if type is allowed to be one const botConvertRateMinMax = this.pmcConfig.convertIntoPmcChance[botRole.toLowerCase()]; @@ -192,6 +212,7 @@ export class BotController } cacheKey = `${botRole}${details.botDifficulty}`; + // Check for bot in cache, add if not if (!this.botGenerationCacheService.cacheHasBotOfRole(cacheKey)) { @@ -200,6 +221,7 @@ export class BotController this.botGenerationCacheService.storeBots(cacheKey, botsToAddToCache); } } + // Get bot from cache, add to return array const botToReturn = this.botGenerationCacheService.getBot(cacheKey); @@ -217,13 +239,13 @@ export class BotController } /** - * Get the difficulty passed in, if its not "asoline", get selected difficulty from config - * @param requestedDifficulty - * @returns + * Get the difficulty passed in, if its not "asonline", get selected difficulty from config + * @param requestedDifficulty + * @returns */ public getPMCDifficulty(requestedDifficulty: string): string { - // maybe retrun a random difficulty... + // Maybe return a random difficulty... if (this.pmcConfig.difficulty.toLowerCase() === "asonline") { return requestedDifficulty; @@ -245,20 +267,27 @@ export class BotController public getBotCap(): number { const defaultMapCapId = "default"; - const raidConfig = this.applicationContext.getLatestValue(ContextVariableType.RAID_CONFIGURATION).getValue(); + const raidConfig = this.applicationContext.getLatestValue(ContextVariableType.RAID_CONFIGURATION).getValue< + IGetRaidConfigurationRequestData + >(); if (!raidConfig) { this.logger.warning(this.localisationService.getText("bot-missing_saved_match_info")); } - const mapName = (raidConfig) - ? raidConfig.location - : defaultMapCapId; + const mapName = raidConfig ? + raidConfig.location : + defaultMapCapId; let botCap = this.botConfig.maxBotCap[mapName.toLowerCase()]; if (!botCap) { - this.logger.warning(this.localisationService.getText("bot-no_bot_cap_found_for_location", raidConfig.location.toLowerCase())); + this.logger.warning( + this.localisationService.getText( + "bot-no_bot_cap_found_for_location", + raidConfig.location.toLowerCase(), + ), + ); botCap = this.botConfig.maxBotCap[defaultMapCapId]; } @@ -269,7 +298,7 @@ export class BotController { return { pmc: this.pmcConfig.pmcType, - assault: this.botConfig.assaultBrainType + assault: this.botConfig.assaultBrainType, }; } } diff --git a/project/src/controllers/ClientLogController.ts b/project/src/controllers/ClientLogController.ts index f8c0b6dc..0db5d170 100644 --- a/project/src/controllers/ClientLogController.ts +++ b/project/src/controllers/ClientLogController.ts @@ -9,9 +9,9 @@ import { inject, injectable } from "tsyringe"; export class ClientLogController { constructor( - @inject("WinstonLogger") protected logger: ILogger + @inject("WinstonLogger") protected logger: ILogger, ) - { } + {} /** * Handle /singleplayer/log @@ -54,4 +54,4 @@ export class ClientLogController this.logger.info(message); } } -} \ No newline at end of file +} diff --git a/project/src/controllers/CustomizationController.ts b/project/src/controllers/CustomizationController.ts index 4cf18ea9..62fafde6 100644 --- a/project/src/controllers/CustomizationController.ts +++ b/project/src/controllers/CustomizationController.ts @@ -17,7 +17,7 @@ export class CustomizationController { protected readonly clothingIds = { lowerParentId: "5cd944d01388ce000a659df9", - upperParentId: "5cd944ca1388ce03a44dc2a4" + upperParentId: "5cd944ca1388ce03a44dc2a4", }; constructor( @@ -26,7 +26,7 @@ export class CustomizationController @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("SaveServer") protected saveServer: SaveServer, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ProfileHelper") protected profileHelper: ProfileHelper + @inject("ProfileHelper") protected profileHelper: ProfileHelper, ) {} @@ -42,18 +42,22 @@ export class CustomizationController const templates = this.databaseServer.getTables().templates.customization; const suits = this.databaseServer.getTables().traders[traderID].suits; - // Get an inner join of clothing from templates.customization and ragmans suits array - const matchingSuits = suits.filter(x => x.suiteId in templates); + // Get an inner join of clothing from templates.customization and Ragman's suits array + const matchingSuits = suits.filter((x) => x.suiteId in templates); // Return all suits that have a side array containing the players side (usec/bear) - return matchingSuits.filter(x => templates[x.suiteId]._props.Side.includes(pmcData.Info.Side)); + return matchingSuits.filter((x) => templates[x.suiteId]._props.Side.includes(pmcData.Info.Side)); } /** * Handle CustomizationWear event * Equip one to many clothing items to player */ - public wearClothing(pmcData: IPmcData, wearClothingRequest: IWearClothingRequestData, sessionID: string): IItemEventRouterResponse + public wearClothing( + pmcData: IPmcData, + wearClothingRequest: IWearClothingRequestData, + sessionID: string, + ): IItemEventRouterResponse { for (const suitId of wearClothingRequest.suites) { @@ -85,7 +89,11 @@ export class CustomizationController * @param sessionId Session id * @returns IItemEventRouterResponse */ - public buyClothing(pmcData: IPmcData, buyClothingRequest: IBuyClothingRequestData, sessionId: string): IItemEventRouterResponse + public buyClothing( + pmcData: IPmcData, + buyClothingRequest: IBuyClothingRequestData, + sessionId: string, + ): IItemEventRouterResponse { const db = this.databaseServer.getTables(); const output = this.eventOutputHolder.getOutput(sessionId); @@ -93,7 +101,9 @@ export class CustomizationController const traderOffer = this.getTraderClothingOffer(sessionId, buyClothingRequest.offer); if (!traderOffer) { - this.logger.error(this.localisationService.getText("customisation-unable_to_find_suit_by_id", buyClothingRequest.offer)); + this.logger.error( + this.localisationService.getText("customisation-unable_to_find_suit_by_id", buyClothingRequest.offer), + ); return output; } @@ -102,7 +112,12 @@ export class CustomizationController if (this.outfitAlreadyPurchased(suitId, sessionId)) { const suitDetails = db.templates.customization[suitId]; - this.logger.error(this.localisationService.getText("customisation-item_already_purchased", {itemId: suitDetails._id, itemName: suitDetails._name})); + this.logger.error( + this.localisationService.getText("customisation-item_already_purchased", { + itemId: suitDetails._id, + itemName: suitDetails._name, + }), + ); return output; } @@ -118,7 +133,7 @@ export class CustomizationController protected getTraderClothingOffer(sessionId: string, offerId: string): ISuit { - return this.getAllTraderSuits(sessionId).find(x => x._id === offerId); + return this.getAllTraderSuits(sessionId).find((x) => x._id === offerId); } /** @@ -139,7 +154,12 @@ export class CustomizationController * @param clothingItems Clothing purchased * @param output Client response */ - protected payForClothingItems(sessionId: string, pmcData: IPmcData, clothingItems: ClothingItem[], output: IItemEventRouterResponse): void + protected payForClothingItems( + sessionId: string, + pmcData: IPmcData, + clothingItems: ClothingItem[], + output: IItemEventRouterResponse, + ): void { for (const sellItem of clothingItems) { @@ -154,12 +174,22 @@ export class CustomizationController * @param clothingItem Clothing item purchased * @param output Client response */ - protected payForClothingItem(sessionId: string, pmcData: IPmcData, clothingItem: ClothingItem, output: IItemEventRouterResponse): void + protected payForClothingItem( + sessionId: string, + pmcData: IPmcData, + clothingItem: ClothingItem, + output: IItemEventRouterResponse, + ): void { - const relatedItem = pmcData.Inventory.items.find(x => x._id === clothingItem.id); + const relatedItem = pmcData.Inventory.items.find((x) => x._id === clothingItem.id); if (!relatedItem) { - this.logger.error(this.localisationService.getText("customisation-unable_to_find_clothing_item_in_inventory", clothingItem.id)); + this.logger.error( + this.localisationService.getText( + "customisation-unable_to_find_clothing_item_in_inventory", + clothingItem.id, + ), + ); return; } @@ -179,7 +209,7 @@ export class CustomizationController parentId: relatedItem.parentId, slotId: relatedItem.slotId, location: relatedItem.location, - upd: { StackObjectsCount: relatedItem.upd.StackObjectsCount } + upd: {StackObjectsCount: relatedItem.upd.StackObjectsCount}, }); } } @@ -199,4 +229,4 @@ export class CustomizationController return result; } -} \ No newline at end of file +} diff --git a/project/src/controllers/DialogueController.ts b/project/src/controllers/DialogueController.ts index d50471a2..76bc8c09 100644 --- a/project/src/controllers/DialogueController.ts +++ b/project/src/controllers/DialogueController.ts @@ -37,7 +37,7 @@ export class DialogueController @inject("MailSendService") protected mailSendService: MailSendService, @inject("GiftService") protected giftService: GiftService, @inject("HashUtil") protected hashUtil: HashUtil, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.coreConfig = this.configServer.getConfig(ConfigTypes.CORE); @@ -57,14 +57,13 @@ export class DialogueController * Handle client/friend/list * @returns IGetFriendListDataResponse */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getFriendList(sessionID: string): IGetFriendListDataResponse { // Force a fake friend called SPT into friend list return { Friends: [this.getSptFriendData()], Ignore: [], - InIgnoreList: [] + InIgnoreList: [], }; } @@ -104,7 +103,7 @@ export class DialogueController new: dialogue.new, attachmentsNew: dialogue.attachmentsNew, pinned: dialogue.pinned, - Users: this.getDialogueUsers(dialogue, dialogue.type, sessionID) + Users: this.getDialogueUsers(dialogue, dialogue.type, sessionID), }; return result; @@ -121,7 +120,9 @@ export class DialogueController const profile = this.saveServer.getProfile(sessionID); // User to user messages are special in that they need the player to exist in them, add if they don't - if (messageType === MessageType.USER_MESSAGE && !dialog.Users?.find(x => x._id === profile.characters.pmc._id)) + if ( + messageType === MessageType.USER_MESSAGE && !dialog.Users?.find((x) => x._id === profile.characters.pmc._id) + ) { if (!dialog.Users) { @@ -134,8 +135,8 @@ export class DialogueController Level: profile.characters.pmc.Info.Level, Nickname: profile.characters.pmc.Info.Nickname, Side: profile.characters.pmc.Info.Side, - MemberCategory: profile.characters.pmc.Info.MemberCategory - } + MemberCategory: profile.characters.pmc.Info.MemberCategory, + }, }); } @@ -144,14 +145,17 @@ export class DialogueController /** * Handle client/mail/dialog/view - * Handle player clicking 'messenger' and seeing all the messages they've recieved + * Handle player clicking 'messenger' and seeing all the messages they've received * Set the content of the dialogue on the details panel, showing all the messages * for the specified dialogue. * @param request Get dialog request * @param sessionId Session id * @returns IGetMailDialogViewResponseData object */ - public generateDialogueView(request: IGetMailDialogViewRequestData, sessionId: string): IGetMailDialogViewResponseData + public generateDialogueView( + request: IGetMailDialogViewRequestData, + sessionId: string, + ): IGetMailDialogViewResponseData { const dialogueId = request.dialogId; const fullProfile = this.saveServer.getProfile(sessionId); @@ -163,17 +167,17 @@ export class DialogueController // Set number of new attachments, but ignore those that have expired. dialogue.attachmentsNew = this.getUnreadMessagesWithAttachmentsCount(sessionId, dialogueId); - return { + return { messages: dialogue.messages, profiles: this.getProfilesForMail(fullProfile, dialogue.Users), - hasMessagesWithRewards: this.messagesHaveUncollectedRewards(dialogue.messages) + hasMessagesWithRewards: this.messagesHaveUncollectedRewards(dialogue.messages), }; } /** * Get dialog from player profile, create if doesn't exist * @param profile Player profile - * @param request get dialog request (params used when dialog doesnt exist in profile) + * @param request get dialog request (params used when dialog doesn't exist in profile) * @returns Dialogue */ protected getDialogByIdFromProfile(profile: IAkiProfile, request: IGetMailDialogViewRequestData): Dialogue @@ -186,7 +190,7 @@ export class DialogueController pinned: false, messages: [], new: 0, - type: request.type + type: request.type, }; if (request.type === MessageType.USER_MESSAGE) @@ -211,8 +215,8 @@ export class DialogueController { result.push(...dialogUsers); - // Player doesnt exist, add them in before returning - if (!result.find(x => x._id === fullProfile.info.id)) + // Player doesn't exist, add them in before returning + if (!result.find((x) => x._id === fullProfile.info.id)) { const pmcProfile = fullProfile.characters.pmc; result.push({ @@ -221,8 +225,8 @@ export class DialogueController Nickname: pmcProfile.Info.Nickname, Side: pmcProfile.Info.Side, Level: pmcProfile.Info.Level, - MemberCategory: pmcProfile.Info.MemberCategory - } + MemberCategory: pmcProfile.Info.MemberCategory, + }, }); } } @@ -258,7 +262,7 @@ export class DialogueController */ protected messagesHaveUncollectedRewards(messages: Message[]): boolean { - return messages.some(x => x.items?.data?.length > 0); + return messages.some((x) => x.items?.data?.length > 0); } /** @@ -274,7 +278,6 @@ export class DialogueController if (!dialog) { this.logger.error(`No dialog in profile: ${sessionId} found with id: ${dialogueId}`); - return; } @@ -288,7 +291,6 @@ export class DialogueController if (!dialog) { this.logger.error(`No dialog in profile: ${sessionId} found with id: ${dialogueId}`); - return; } @@ -307,7 +309,6 @@ export class DialogueController if (!dialogs) { this.logger.error(`No dialog object in profile: ${sessionId}`); - return; } @@ -323,7 +324,7 @@ export class DialogueController * Get all uncollected items attached to mail in a particular dialog * @param dialogueId Dialog to get mail attachments from * @param sessionId Session id - * @returns + * @returns */ public getAllAttachments(dialogueId: string, sessionId: string): IGetAllAttachmentsResponse { @@ -332,25 +333,23 @@ export class DialogueController if (!dialog) { this.logger.error(`No dialog in profile: ${sessionId} found with id: ${dialogueId}`); - return; } // Removes corner 'new messages' tag dialog.attachmentsNew = 0; - + const activeMessages = this.getActiveMessagesFromDialog(sessionId, dialogueId); const messagesWithAttachments = this.getMessagesWithAttachments(activeMessages); - return { + return { messages: messagesWithAttachments, profiles: [], - hasMessagesWithRewards: this.messagesHaveUncollectedRewards(messagesWithAttachments) + hasMessagesWithRewards: this.messagesHaveUncollectedRewards(messagesWithAttachments), }; } /** client/mail/msg/send */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public sendMessage(sessionId: string, request: ISendMessageRequest): string { this.mailSendService.sendPlayerMessageToNpc(sessionId, request.dialogId, request.text); @@ -372,48 +371,97 @@ export class DialogueController protected handleChatWithSPTFriend(sessionId: string, request: ISendMessageRequest): void { const sender = this.profileHelper.getPmcProfile(sessionId); - const sptFriendUser = this.getSptFriendData(); - const giftSent = this.giftService.sendGiftToPlayer(sessionId, request.text); - if (giftSent === GiftSentResult.SUCCESS) + if (giftSent === GiftSentResult.SUCCESS) { - this.mailSendService.sendUserMessageToPlayer(sessionId, sptFriendUser, this.randomUtil.getArrayValue(["Hey! you got the right code!", "A secret code, how exciting!", "You found a gift code!"])); - + this.mailSendService.sendUserMessageToPlayer( + sessionId, + sptFriendUser, + this.randomUtil.getArrayValue([ + "Hey! you got the right code!", + "A secret code, how exciting!", + "You found a gift code!", + ]), + ); return; } - if (giftSent === GiftSentResult.FAILED_GIFT_ALREADY_RECEIVED) + if (giftSent === GiftSentResult.FAILED_GIFT_ALREADY_RECEIVED) { - this.mailSendService.sendUserMessageToPlayer(sessionId, sptFriendUser, this.randomUtil.getArrayValue(["Looks like you already used that code", "You already have that!!"])); - + this.mailSendService.sendUserMessageToPlayer( + sessionId, + sptFriendUser, + this.randomUtil.getArrayValue(["Looks like you already used that code", "You already have that!!"]), + ); return; } - if (request.text.toLowerCase().includes("love you")) + if (request.text.toLowerCase().includes("love you")) { - this.mailSendService.sendUserMessageToPlayer(sessionId, sptFriendUser, this.randomUtil.getArrayValue(["That's quite forward but i love you too in a purely chatbot-human way", "I love you too buddy :3!", "uwu", `love you too ${sender?.Info?.Nickname}`])); + this.mailSendService.sendUserMessageToPlayer( + sessionId, + sptFriendUser, + this.randomUtil.getArrayValue([ + "That's quite forward but i love you too in a purely chatbot-human way", + "I love you too buddy :3!", + "uwu", + `love you too ${sender?.Info?.Nickname}`, + ]), + ); } - if (request.text.toLowerCase() === "spt") + if (request.text.toLowerCase() === "spt") { - this.mailSendService.sendUserMessageToPlayer(sessionId, sptFriendUser, this.randomUtil.getArrayValue(["Its me!!", "spt? i've heard of that project"])); + this.mailSendService.sendUserMessageToPlayer( + sessionId, + sptFriendUser, + this.randomUtil.getArrayValue(["Its me!!", "spt? i've heard of that project"]), + ); } - if (["hello", "hi", "sup", "yo", "hey"].includes(request.text.toLowerCase())) + if (["hello", "hi", "sup", "yo", "hey"].includes(request.text.toLowerCase())) { - this.mailSendService.sendUserMessageToPlayer(sessionId, sptFriendUser, this.randomUtil.getArrayValue(["Howdy", "Hi", "Greetings", "Hello", "bonjor", "Yo", "Sup", "Heyyyyy", "Hey there", `Hello ${sender?.Info?.Nickname}`])); + this.mailSendService.sendUserMessageToPlayer( + sessionId, + sptFriendUser, + this.randomUtil.getArrayValue([ + "Howdy", + "Hi", + "Greetings", + "Hello", + "Bonjour", + "Yo", + "Sup", + "Heyyyyy", + "Hey there", + `Hello ${sender?.Info?.Nickname}`, + ]), + ); } - if (request.text.toLowerCase() === "nikita") + if (request.text.toLowerCase() === "nikita") { - this.mailSendService.sendUserMessageToPlayer(sessionId, sptFriendUser, this.randomUtil.getArrayValue(["I know that guy!", "Cool guy, he made EFT!", "Legend", "Remember when he said webel-webel-webel-webel, classic nikita moment"])); + this.mailSendService.sendUserMessageToPlayer( + sessionId, + sptFriendUser, + this.randomUtil.getArrayValue([ + "I know that guy!", + "Cool guy, he made EFT!", + "Legend", + "Remember when he said webel-webel-webel-webel, classic nikita moment", + ]), + ); } - if (request.text.toLowerCase() === "are you a bot") + if (request.text.toLowerCase() === "are you a bot") { - this.mailSendService.sendUserMessageToPlayer(sessionId, sptFriendUser, this.randomUtil.getArrayValue(["beep boop", "**sad boop**", "probably", "sometimes", "yeah lol"])); + this.mailSendService.sendUserMessageToPlayer( + sessionId, + sptFriendUser, + this.randomUtil.getArrayValue(["beep boop", "**sad boop**", "probably", "sometimes", "yeah lol"]), + ); } } @@ -425,8 +473,8 @@ export class DialogueController Level: 1, MemberCategory: MemberCategory.DEVELOPER, Nickname: this.coreConfig.sptFriendNickname, - Side: "Usec" - } + Side: "Usec", + }, }; } @@ -440,7 +488,7 @@ export class DialogueController { const timeNow = this.timeUtil.getTimestamp(); const dialogs = this.dialogueHelper.getDialogsForProfile(sessionId); - return dialogs[dialogueId].messages.filter(x => timeNow < (x.dt + x.maxStorageTime)); + return dialogs[dialogueId].messages.filter((x) => timeNow < (x.dt + x.maxStorageTime)); } /** @@ -450,7 +498,7 @@ export class DialogueController */ protected getMessagesWithAttachments(messages: Message[]): Message[] { - return messages.filter(x => x.items?.data?.length > 0); + return messages.filter((x) => x.items?.data?.length > 0); } /** @@ -497,4 +545,4 @@ export class DialogueController { return (this.timeUtil.getTimestamp()) > (message.dt + message.maxStorageTime); } -} \ No newline at end of file +} diff --git a/project/src/controllers/GameController.ts b/project/src/controllers/GameController.ts index 27f13b7a..cef02021 100644 --- a/project/src/controllers/GameController.ts +++ b/project/src/controllers/GameController.ts @@ -69,7 +69,7 @@ export class GameController @inject("ItemBaseClassService") protected itemBaseClassService: ItemBaseClassService, @inject("GiftService") protected giftService: GiftService, @inject("ApplicationContext") protected applicationContext: ApplicationContext, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.httpConfig = this.configServer.getConfig(ConfigTypes.HTTP); @@ -82,10 +82,10 @@ export class GameController public load(): void { - // Regenerate basecache now mods are loaded and game is starting - // Mods that add items and use the baseclass service generate the cache including their items, the next mod that add items gets left out,causing warnings + // Regenerate base cache now mods are loaded and game is starting + // Mods that add items and use the baseClass service generate the cache including their items, the next mod that + // add items gets left out,causing warnings this.itemBaseClassService.hydrateItemBaseClassCache(); - this.addCustomLooseLootPositions(); } @@ -121,9 +121,9 @@ export class GameController this.checkTraderRepairValuesExist(); - // repeatableQuests are stored by in profile.Quests due to the responses of the client (e.g. Quests in offraidData) - // Since we don't want to clutter the Quests list, we need to remove all completed (failed / successful) repeatable quests. - // We also have to remove the Counters from the repeatableQuests + // repeatableQuests are stored by in profile.Quests due to the responses of the client (e.g. Quests in + // offraidData). Since we don't want to clutter the Quests list, we need to remove all completed (failed or + // successful) repeatable quests. We also have to remove the Counters from the repeatableQuests if (sessionID) { const fullProfile = this.profileHelper.getFullProfile(sessionID); @@ -166,7 +166,7 @@ export class GameController this.profileFixerService.fixIncorrectAidValue(fullProfile); this.profileFixerService.migrateStatsToNewStructure(fullProfile); - + this.sendPraporGiftsToNewProfiles(pmcProfile); this.profileFixerService.checkForOrphanedModdedItems(sessionID, fullProfile); @@ -184,7 +184,7 @@ export class GameController this.hideoutHelper.unlockHideoutWallInProfile(pmcProfile); this.profileFixerService.addMissingIdsToBonuses(pmcProfile); } - + this.logProfileDetails(fullProfile); this.adjustLabsRaiderSpawnRate(); @@ -240,7 +240,9 @@ export class GameController const trader = this.databaseServer.getTables().traders[traderKey]; if (!trader?.base?.repair) { - this.logger.warning(`Trader ${trader.base._id} ${trader.base.name} is missing a repair object, adding in default values`); + this.logger.warning( + `Trader ${trader.base._id} ${trader.base.name} is missing a repair object, adding in default values`, + ); trader.base.repair = this.jsonUtil.clone(this.databaseServer.getTables().traders.ragfair.base.repair); return; @@ -248,8 +250,12 @@ export class GameController if (trader?.base?.repair?.quality) { - this.logger.warning(`Trader ${trader.base._id} ${trader.base.name} is missing a repair quality value, adding in default value`); - trader.base.repair.quality = this.jsonUtil.clone(this.databaseServer.getTables().traders.ragfair.base.repair.quality); + this.logger.warning( + `Trader ${trader.base._id} ${trader.base.name} is missing a repair quality value, adding in default value`, + ); + trader.base.repair.quality = this.jsonUtil.clone( + this.databaseServer.getTables().traders.ragfair.base.repair.quality, + ); } } } @@ -274,7 +280,9 @@ export class GameController for (const positionToAdd of positionsToAdd) { // Exists already, add new items to existing positions pool - const existingLootPosition = mapLooseLoot.spawnpoints.find(x => x.template.Id === positionToAdd.template.Id); + const existingLootPosition = mapLooseLoot.spawnpoints.find((x) => + x.template.Id === positionToAdd.template.Id + ); if (existingLootPosition) { existingLootPosition.template.Items.push(...positionToAdd.template.Items); @@ -283,7 +291,7 @@ export class GameController continue; } - // new postion, add entire object + // New position, add entire object mapLooseLoot.spawnpoints.push(positionToAdd); } } @@ -303,7 +311,7 @@ export class GameController const mapLootAdjustmentsDict = adjustments[mapId]; for (const lootKey in mapLootAdjustmentsDict) { - const lootPostionToAdjust = mapLooseLootData.spawnpoints.find(x => x.template.Id === lootKey); + const lootPostionToAdjust = mapLooseLootData.spawnpoints.find((x) => x.template.Id === lootKey); if (!lootPostionToAdjust) { this.logger.warning(`Unable to adjust loot position: ${lootKey} on map: ${mapId}`); @@ -314,24 +322,24 @@ export class GameController } } } - + protected setHideoutAreasAndCraftsTo40Secs(): void { - for (const hideoutProd of this.databaseServer.getTables().hideout.production) + for (const hideoutProd of this.databaseServer.getTables().hideout.production) { - if (hideoutProd.productionTime > 40) + if (hideoutProd.productionTime > 40) { hideoutProd.productionTime = 40; } } this.logger.warning("DEVELOPER: SETTING ALL HIDEOUT PRODUCTIONS TO 40 SECONDS"); - for (const hideoutArea of this.databaseServer.getTables().hideout.areas) + for (const hideoutArea of this.databaseServer.getTables().hideout.areas) { - for (const stageKey in hideoutArea.stages) + for (const stageKey in hideoutArea.stages) { const stage = hideoutArea.stages[stageKey]; - if (stage.constructionTime > 40) + if (stage.constructionTime > 40) { stage.constructionTime = 40; } @@ -339,9 +347,9 @@ export class GameController } this.logger.warning("DEVELOPER: SETTING ALL HIDEOUT AREAS TO 40 SECOND UPGRADES"); - for (const scavCaseCraft of this.databaseServer.getTables().hideout.scavcase) + for (const scavCaseCraft of this.databaseServer.getTables().hideout.scavcase) { - if (scavCaseCraft.ProductionTime > 40) + if (scavCaseCraft.ProductionTime > 40) { scavCaseCraft.ProductionTime = 40; } @@ -363,12 +371,14 @@ export class GameController const map: ILocationData = mapsDb[mapId]; if (!map) { - this.logger.warning(this.localisationService.getText("bot-unable_to_edit_limits_of_unknown_map", mapId)); + this.logger.warning( + this.localisationService.getText("bot-unable_to_edit_limits_of_unknown_map", mapId), + ); } for (const botToLimit of this.locationConfig.botTypeLimits[mapId]) { - const index = map.base.MinMaxBots.findIndex(x => x.WildSpawnType === botToLimit.type); + const index = map.base.MinMaxBots.findIndex((x) => x.WildSpawnType === botToLimit.type); if (index !== -1) { // Existing bot type found in MinMaxBots array, edit @@ -378,14 +388,12 @@ export class GameController } else { - map.base.MinMaxBots.push( - { - // Bot type not found, add new object - WildSpawnType: botToLimit.type, - min: botToLimit.min, - max: botToLimit.max - } - ); + // Bot type not found, add new object + map.base.MinMaxBots.push({ + WildSpawnType: botToLimit.type, + min: botToLimit.min, + max: botToLimit.max, + }); } } } @@ -412,12 +420,11 @@ export class GameController Trading: this.httpServerHelper.getBackendUrl(), Messaging: this.httpServerHelper.getBackendUrl(), Main: this.httpServerHelper.getBackendUrl(), - RagFair: this.httpServerHelper.getBackendUrl() + RagFair: this.httpServerHelper.getBackendUrl(), }, useProtobuf: false, - // eslint-disable-next-line @typescript-eslint/naming-convention utc_time: new Date().getTime() / 1000, - totalInGame: profile.Stats?.Eft?.TotalInGameTime ?? 0 + totalInGame: profile.Stats?.Eft?.TotalInGameTime ?? 0, }; return config; @@ -426,50 +433,43 @@ export class GameController /** * Handle client/server/list */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getServer(sessionId: string): IServerDetails[] { - return [ - { - ip: this.httpConfig.ip, - port: this.httpConfig.port - } - ]; + return [{ + ip: this.httpConfig.ip, + port: this.httpConfig.port, + }]; } /** * Handle client/match/group/current */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getCurrentGroup(sessionId: string): ICurrentGroupResponse { return { - squad: [] + squad: [], }; } /** * Handle client/checkVersion */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getValidGameVersion(sessionId: string): ICheckVersionResponse { return { isvalid: true, - latestVersion: this.coreConfig.compatibleTarkovVersion + latestVersion: this.coreConfig.compatibleTarkovVersion, }; } /** * Handle client/game/keepalive */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getKeepAlive(sessionId: string): IGameKeepAliveResponse { return { msg: "OK", - // eslint-disable-next-line @typescript-eslint/naming-convention - utc_time: new Date().getTime() / 1000 + utc_time: new Date().getTime() / 1000, }; } @@ -520,8 +520,8 @@ export class GameController /** * When player logs in, iterate over all active effects and reduce timer - * TODO - add body part HP regen - * @param pmcProfile + * // TODO: Add body part HP regeneration + * @param pmcProfile */ protected updateProfileHealthValues(pmcProfile: IPmcData): void { @@ -538,14 +538,23 @@ export class GameController let hpRegenPerHour = 456.6; // Set new values, whatever is smallest - energyRegenPerHour += pmcProfile.Bonuses.filter(x => x.type === "EnergyRegeneration").reduce((sum, curr) => sum + curr.value, 0); - hydrationRegenPerHour += pmcProfile.Bonuses.filter(x => x.type === "HydrationRegeneration").reduce((sum, curr) => sum + curr.value, 0); - hpRegenPerHour += pmcProfile.Bonuses.filter(x => x.type === "HealthRegeneration").reduce((sum, curr) => sum + curr.value, 0); + energyRegenPerHour += pmcProfile.Bonuses.filter((x) => x.type === "EnergyRegeneration").reduce( + (sum, curr) => sum + curr.value, + 0, + ); + hydrationRegenPerHour += pmcProfile.Bonuses.filter((x) => x.type === "HydrationRegeneration").reduce( + (sum, curr) => sum + curr.value, + 0, + ); + hpRegenPerHour += pmcProfile.Bonuses.filter((x) => x.type === "HealthRegeneration").reduce( + (sum, curr) => sum + curr.value, + 0, + ); if (pmcProfile.Health.Energy.Current !== pmcProfile.Health.Energy.Maximum) { // Set new value, whatever is smallest - pmcProfile.Health.Energy.Current += Math.round((energyRegenPerHour * (diffSeconds / 3600))); + pmcProfile.Health.Energy.Current += Math.round(energyRegenPerHour * (diffSeconds / 3600)); if (pmcProfile.Health.Energy.Current > pmcProfile.Health.Energy.Maximum) { pmcProfile.Health.Energy.Current = pmcProfile.Health.Energy.Maximum; @@ -554,7 +563,7 @@ export class GameController if (pmcProfile.Health.Hydration.Current !== pmcProfile.Health.Hydration.Maximum) { - pmcProfile.Health.Hydration.Current += Math.round((hydrationRegenPerHour * (diffSeconds / 3600))); + pmcProfile.Health.Hydration.Current += Math.round(hydrationRegenPerHour * (diffSeconds / 3600)); if (pmcProfile.Health.Hydration.Current > pmcProfile.Health.Hydration.Maximum) { pmcProfile.Health.Hydration.Current = pmcProfile.Health.Hydration.Maximum; @@ -565,17 +574,17 @@ export class GameController for (const bodyPartKey in pmcProfile.Health.BodyParts) { const bodyPart = pmcProfile.Health.BodyParts[bodyPartKey] as BodyPartHealth; - + // Check part hp if (bodyPart.Health.Current < bodyPart.Health.Maximum) { - bodyPart.Health.Current += Math.round((hpRegenPerHour * (diffSeconds / 3600))); + bodyPart.Health.Current += Math.round(hpRegenPerHour * (diffSeconds / 3600)); } if (bodyPart.Health.Current > bodyPart.Health.Maximum) { bodyPart.Health.Current = bodyPart.Health.Maximum; } - + // Look for effects if (Object.keys(bodyPart.Effects ?? {}).length > 0) { @@ -618,7 +627,9 @@ export class GameController const location: ILocationData = this.databaseServer.getTables().locations[locationKey]; if (!location.base) { - this.logger.warning(this.localisationService.getText("location-unable_to_fix_broken_waves_missing_base", locationKey)); + this.logger.warning( + this.localisationService.getText("location-unable_to_fix_broken_waves_missing_base", locationKey), + ); continue; } @@ -626,7 +637,9 @@ export class GameController { if ((wave.slots_max - wave.slots_min === 0)) { - this.logger.debug(`Fixed ${wave.WildSpawnType} Spawn: ${locationKey} wave: ${wave.number} of type: ${wave.WildSpawnType} in zone: ${wave.SpawnPoints} with Max Slots of ${wave.slots_max}`); + this.logger.debug( + `Fixed ${wave.WildSpawnType} Spawn: ${locationKey} wave: ${wave.number} of type: ${wave.WildSpawnType} in zone: ${wave.SpawnPoints} with Max Slots of ${wave.slots_max}`, + ); wave.slots_max++; } } @@ -673,7 +686,8 @@ export class GameController } /** - * Find and split waves with large numbers of bots into smaller waves - BSG appears to reduce the size of these waves to one bot when they're waiting to spawn for too long + * Find and split waves with large numbers of bots into smaller waves - BSG appears to reduce the size of these + * waves to one bot when they're waiting to spawn for too long */ protected splitBotWavesIntoSingleWaves(): void { @@ -689,18 +703,23 @@ export class GameController for (const wave of location.base.waves) { // Wave has size that makes it candidate for splitting - if (wave.slots_max - wave.slots_min >= this.locationConfig.splitWaveIntoSingleSpawnsSettings.waveSizeThreshold) + if ( + wave.slots_max - wave.slots_min >= + this.locationConfig.splitWaveIntoSingleSpawnsSettings.waveSizeThreshold + ) { // Get count of bots to be spawned in wave const waveSize = wave.slots_max - wave.slots_min; - + // Update wave to spawn single bot wave.slots_min = 1; wave.slots_max = 2; - + // Get index of wave const indexOfWaveToSplit = location.base.waves.indexOf(wave); - this.logger.debug(`Splitting map: ${location.base.Id} wave: ${indexOfWaveToSplit} with ${waveSize} bots`); + this.logger.debug( + `Splitting map: ${location.base.Id} wave: ${indexOfWaveToSplit} with ${waveSize} bots`, + ); // Add new waves to fill gap from bots we removed in above wave let wavesAddedCount = 0; @@ -716,20 +735,23 @@ export class GameController waveToAdd.number = index; } - // Place wave into array in just-edited postion + 1 + // Place wave into array in just-edited position + 1 location.base.waves.splice(index, 0, waveToAdd); wavesAddedCount++; } - // Update subsequent wave number property to accomodate the new waves - for (let index = indexOfWaveToSplit + wavesAddedCount + 1; index < location.base.waves.length; index++) + // Update subsequent wave number property to accommodate the new waves + for ( + let index = indexOfWaveToSplit + wavesAddedCount + 1; + index < location.base.waves.length; + index++ + ) { // Some waves have value of 0, leave them as-is if (location.base.waves[index].number !== 0) { location.base.waves[index].number += wavesAddedCount; } - } } } @@ -753,9 +775,13 @@ export class GameController for (const modKey in activeMods) { const modDetails = activeMods[modKey]; - if (fullProfile.aki.mods.some(x => x.author === modDetails.author - && x.name === modDetails.name - && x.version === modDetails.version)) + if ( + fullProfile.aki.mods.some((x) => + x.author === modDetails.author && + x.name === modDetails.name && + x.version === modDetails.version + ) + ) { // Exists already, skip continue; @@ -765,13 +791,13 @@ export class GameController author: modDetails.author, dateAdded: Date.now(), name: modDetails.name, - version: modDetails.version + version: modDetails.version, }); } } /** - * Check for any missing assorts inside each traders assort.json data, checking against traders qeustassort.json + * Check for any missing assorts inside each traders assort.json data, checking against traders questassort.json */ protected validateQuestAssortUnlocksExist(): void { @@ -788,19 +814,26 @@ export class GameController } // Merge started/success/fail quest assorts into one dictionary - const mergedQuestAssorts = { ...traderData.questassort["started"], ...traderData.questassort["success"], ...traderData.questassort["fail"]}; + const mergedQuestAssorts = { + ...traderData.questassort["started"], + ...traderData.questassort["success"], + ...traderData.questassort["fail"], + }; - // loop over all assorts for trader + // Loop over all assorts for trader for (const [assortKey, questKey] of Object.entries(mergedQuestAssorts)) { // Does assort key exist in trader assort file if (!traderAssorts.loyal_level_items[assortKey]) { - // reverse lookup of enum key by value + // Reverse lookup of enum key by value const messageValues = { traderName: Object.keys(Traders)[Object.values(Traders).indexOf(traderId)], - questName: quests[questKey]?.QuestName ?? "UNKNOWN"}; - this.logger.debug(this.localisationService.getText("assort-missing_quest_assort_unlock", messageValues)); + questName: quests[questKey]?.QuestName ?? "UNKNOWN", + }; + this.logger.debug( + this.localisationService.getText("assort-missing_quest_assort_unlock", messageValues), + ); } } } @@ -821,11 +854,11 @@ export class GameController { bots["bear"].firstName.push(playerName); } - + if (bots["usec"]) { bots["usec"].firstName.push(playerName); - } + } } } @@ -847,7 +880,7 @@ export class GameController */ protected removePraporTestMessage(): void { - // Iterate over all langauges (e.g. "en", "fr") + // Iterate over all languages (e.g. "en", "fr") for (const localeKey in this.databaseServer.getTables().locales.global) { this.databaseServer.getTables().locales.global[localeKey]["61687e2c3e526901fa76baf9"] = ""; @@ -860,7 +893,9 @@ export class GameController protected adjustLabsRaiderSpawnRate(): void { const labsBase = this.databaseServer.getTables().locations.laboratory.base; - const nonTriggerLabsBossSpawns = labsBase.BossLocationSpawn.filter(x => x.TriggerId === "" && x.TriggerName === ""); + const nonTriggerLabsBossSpawns = labsBase.BossLocationSpawn.filter((x) => + x.TriggerId === "" && x.TriggerName === "" + ); if (nonTriggerLabsBossSpawns) { for (const boss of nonTriggerLabsBossSpawns) @@ -878,4 +913,4 @@ export class GameController this.logger.debug(`Debug enabled: ${globalThis.G_DEBUG_CONFIGURATION}`); this.logger.debug(`Mods enabled: ${globalThis.G_MODS_ENABLED}`); } -} \ No newline at end of file +} diff --git a/project/src/controllers/HandbookController.ts b/project/src/controllers/HandbookController.ts index 96fdcdb2..d9a957da 100644 --- a/project/src/controllers/HandbookController.ts +++ b/project/src/controllers/HandbookController.ts @@ -8,12 +8,12 @@ export class HandbookController { constructor( @inject("DatabaseServer") protected databaseServer: DatabaseServer, - @inject("HandbookHelper") protected handbookHelper: HandbookHelper + @inject("HandbookHelper") protected handbookHelper: HandbookHelper, ) - { } + {} public load(): void { return; } -} \ No newline at end of file +} diff --git a/project/src/controllers/HealthController.ts b/project/src/controllers/HealthController.ts index 3060f102..5090b36f 100644 --- a/project/src/controllers/HealthController.ts +++ b/project/src/controllers/HealthController.ts @@ -31,7 +31,7 @@ export class HealthController @inject("InventoryHelper") protected inventoryHelper: InventoryHelper, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, - @inject("HealthHelper") protected healthHelper: HealthHelper + @inject("HealthHelper") protected healthHelper: HealthHelper, ) {} @@ -43,7 +43,13 @@ export class HealthController * @param addEffects Should effects found be added or removed from profile * @param deleteExistingEffects Should all prior effects be removed before apply new ones */ - public saveVitality(pmcData: IPmcData, info: ISyncHealthRequestData, sessionID: string, addEffects = true, deleteExistingEffects = true): void + public saveVitality( + pmcData: IPmcData, + info: ISyncHealthRequestData, + sessionID: string, + addEffects = true, + deleteExistingEffects = true, + ): void { this.healthHelper.saveVitality(pmcData, info, sessionID, addEffects, deleteExistingEffects); } @@ -60,10 +66,13 @@ export class HealthController const output = this.eventOutputHolder.getOutput(sessionID); // Update medkit used (hpresource) - const healingItemToUse = pmcData.Inventory.items.find(item => item._id === request.item); + const healingItemToUse = pmcData.Inventory.items.find((item) => item._id === request.item); if (!healingItemToUse) { - const errorMessage = this.localisationService.getText("health-healing_item_not_found", healingItemToUse._id); + const errorMessage = this.localisationService.getText( + "health-healing_item_not_found", + healingItemToUse._id, + ); this.logger.error(errorMessage); return this.httpResponse.appendErrorToOutput(output, errorMessage); @@ -82,8 +91,8 @@ export class HealthController else { // Get max healing from db - const maxhp = this.itemHelper.getItem(healingItemToUse._tpl)[1]._props.MaxHpResource; - healingItemToUse.upd.MedKit = { HpResource: maxhp - request.count }; // Subtract amout used from max + const maxHp = this.itemHelper.getItem(healingItemToUse._tpl)[1]._props.MaxHpResource; + healingItemToUse.upd.MedKit = {HpResource: maxHp - request.count}; // Subtract amount used from max } // Resource in medkit is spent, delete it @@ -108,11 +117,14 @@ export class HealthController let output = this.eventOutputHolder.getOutput(sessionID); let resourceLeft = 0; - const itemToConsume = pmcData.Inventory.items.find(x => x._id === request.item); + const itemToConsume = pmcData.Inventory.items.find((x) => x._id === request.item); if (!itemToConsume) { // Item not found, very bad - return this.httpResponse.appendErrorToOutput(output, this.localisationService.getText("health-unable_to_find_item_to_consume", request.item)); + return this.httpResponse.appendErrorToOutput( + output, + this.localisationService.getText("health-unable_to_find_item_to_consume", request.item), + ); } const consumedItemMaxResource = this.itemHelper.getItem(itemToConsume._tpl)[1]._props.MaxResource; @@ -120,7 +132,7 @@ export class HealthController { if (itemToConsume.upd.FoodDrink === undefined) { - itemToConsume.upd.FoodDrink = { HpPercent: consumedItemMaxResource - request.count }; + itemToConsume.upd.FoodDrink = {HpPercent: consumedItemMaxResource - request.count}; } else { @@ -138,7 +150,7 @@ export class HealthController return output; } - + /** * Handle RestoreHealth event * Occurs on post-raid healing page @@ -147,20 +159,21 @@ export class HealthController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public healthTreatment(pmcData: IPmcData, healthTreatmentRequest: IHealthTreatmentRequestData, sessionID: string): IItemEventRouterResponse + public healthTreatment( + pmcData: IPmcData, + healthTreatmentRequest: IHealthTreatmentRequestData, + sessionID: string, + ): IItemEventRouterResponse { let output = this.eventOutputHolder.getOutput(sessionID); const payMoneyRequest: IProcessBuyTradeRequestData = { Action: healthTreatmentRequest.Action, tid: Traders.THERAPIST, - // eslint-disable-next-line @typescript-eslint/naming-convention scheme_items: healthTreatmentRequest.items, type: "", - // eslint-disable-next-line @typescript-eslint/naming-convention item_id: "", count: 0, - // eslint-disable-next-line @typescript-eslint/naming-convention - scheme_id: 0 + scheme_id: 0, }; output = this.paymentService.payMoney(pmcData, payMoneyRequest, sessionID, output); @@ -175,7 +188,7 @@ export class HealthController const partRequest: BodyPart = healthTreatmentRequest.difference.BodyParts[bodyPartKey]; const profilePart = pmcData.Health.BodyParts[bodyPartKey]; - // Set profile bodypart to max + // Set profile body part to max profilePart.Health.Current = profilePart.Health.Maximum; // Check for effects to remove @@ -205,9 +218,8 @@ export class HealthController * applies skills from hideout workout. * @param pmcData Player profile * @param info Request data - * @param sessionID + * @param sessionID */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public applyWorkoutChanges(pmcData: IPmcData, info: IWorkoutData, sessionId: string): void { // https://dev.sp-tarkov.com/SPT-AKI/Server/issues/2674 @@ -215,4 +227,4 @@ export class HealthController // Health effects (fractures etc) are handled in /player/health/sync. pmcData.Skills.Common = info.skills.Common; } -} \ No newline at end of file +} diff --git a/project/src/controllers/HideoutController.ts b/project/src/controllers/HideoutController.ts index c7f58e1b..af7c6b62 100644 --- a/project/src/controllers/HideoutController.ts +++ b/project/src/controllers/HideoutController.ts @@ -69,7 +69,7 @@ export class HideoutController @inject("LocalisationService") protected localisationService: LocalisationService, @inject("ConfigServer") protected configServer: ConfigServer, @inject("JsonUtil") protected jsonUtil: JsonUtil, - @inject("FenceService") protected fenceService: FenceService + @inject("FenceService") protected fenceService: FenceService, ) { this.hideoutConfig = this.configServer.getConfig(ConfigTypes.HIDEOUT); @@ -83,15 +83,19 @@ export class HideoutController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public startUpgrade(pmcData: IPmcData, request: IHideoutUpgradeRequestData, sessionID: string): IItemEventRouterResponse + public startUpgrade( + pmcData: IPmcData, + request: IHideoutUpgradeRequestData, + sessionID: string, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionID); - const items = request.items.map(reqItem => + const items = request.items.map((reqItem) => { - const item = pmcData.Inventory.items.find(invItem => invItem._id === reqItem.id); + const item = pmcData.Inventory.items.find((invItem) => invItem._id === reqItem.id); return { inventoryItem: item, - requestedItem: reqItem + requestedItem: reqItem, }; }); @@ -100,14 +104,18 @@ export class HideoutController { if (!item.inventoryItem) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_item_in_inventory", item.requestedItem.id)); + this.logger.error( + this.localisationService.getText("hideout-unable_to_find_item_in_inventory", item.requestedItem.id), + ); return this.httpResponse.appendErrorToOutput(output); } - if (this.paymentHelper.isMoneyTpl(item.inventoryItem._tpl) - && item.inventoryItem.upd - && item.inventoryItem.upd.StackObjectsCount - && item.inventoryItem.upd.StackObjectsCount > item.requestedItem.count) + if ( + this.paymentHelper.isMoneyTpl(item.inventoryItem._tpl) && + item.inventoryItem.upd && + item.inventoryItem.upd.StackObjectsCount && + item.inventoryItem.upd.StackObjectsCount > item.requestedItem.count + ) { item.inventoryItem.upd.StackObjectsCount -= item.requestedItem.count; } @@ -118,17 +126,21 @@ export class HideoutController } // Construction time management - const hideoutArea = pmcData.Hideout.Areas.find(area => area.type === request.areaType); + const hideoutArea = pmcData.Hideout.Areas.find((area) => area.type === request.areaType); if (!hideoutArea) { this.logger.error(this.localisationService.getText("hideout-unable_to_find_area", request.areaType)); return this.httpResponse.appendErrorToOutput(output); } - const hideoutData = this.databaseServer.getTables().hideout.areas.find(area => area.type === request.areaType); + const hideoutData = this.databaseServer.getTables().hideout.areas.find((area) => + area.type === request.areaType + ); if (!hideoutData) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_area_in_database", request.areaType)); + this.logger.error( + this.localisationService.getText("hideout-unable_to_find_area_in_database", request.areaType), + ); return this.httpResponse.appendErrorToOutput(output); } @@ -152,12 +164,16 @@ export class HideoutController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public upgradeComplete(pmcData: IPmcData, request: HideoutUpgradeCompleteRequestData, sessionID: string): IItemEventRouterResponse + public upgradeComplete( + pmcData: IPmcData, + request: HideoutUpgradeCompleteRequestData, + sessionID: string, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionID); const db = this.databaseServer.getTables(); - const profileHideoutArea = pmcData.Hideout.Areas.find(area => area.type === request.areaType); + const profileHideoutArea = pmcData.Hideout.Areas.find((area) => area.type === request.areaType); if (!profileHideoutArea) { this.logger.error(this.localisationService.getText("hideout-unable_to_find_area", request.areaType)); @@ -169,10 +185,12 @@ export class HideoutController profileHideoutArea.completeTime = 0; profileHideoutArea.constructing = false; - const hideoutData = db.hideout.areas.find(area => area.type === profileHideoutArea.type); + const hideoutData = db.hideout.areas.find((area) => area.type === profileHideoutArea.type); if (!hideoutData) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_area_in_database", request.areaType)); + this.logger.error( + this.localisationService.getText("hideout-unable_to_find_area_in_database", request.areaType), + ); return this.httpResponse.appendErrorToOutput(output); } @@ -190,18 +208,32 @@ export class HideoutController // Upgrade includes a container improvement/addition if (hideoutStage?.container) { - this.addContainerImprovementToProfile(output, sessionID, pmcData, profileHideoutArea, hideoutData, hideoutStage); + this.addContainerImprovementToProfile( + output, + sessionID, + pmcData, + profileHideoutArea, + hideoutData, + hideoutStage, + ); } // Upgrading water collector / med station - if (profileHideoutArea.type === HideoutAreas.WATER_COLLECTOR || profileHideoutArea.type === HideoutAreas.MEDSTATION) + if ( + profileHideoutArea.type === HideoutAreas.WATER_COLLECTOR || + profileHideoutArea.type === HideoutAreas.MEDSTATION + ) { this.checkAndUpgradeWall(pmcData); } // Add Skill Points Per Area Upgrade - this.profileHelper.addSkillPointsToPlayer(pmcData, SkillTypes.HIDEOUT_MANAGEMENT, db.globals.config.SkillsSettings.HideoutManagement.SkillPointsPerAreaUpgrade); - + this.profileHelper.addSkillPointsToPlayer( + pmcData, + SkillTypes.HIDEOUT_MANAGEMENT, + db.globals.config.SkillsSettings.HideoutManagement.SkillPointsPerAreaUpgrade, + ); + return output; } @@ -211,11 +243,11 @@ export class HideoutController */ protected checkAndUpgradeWall(pmcData: IPmcData): void { - const medStation = pmcData.Hideout.Areas.find(area => area.type === HideoutAreas.MEDSTATION); - const waterCollector = pmcData.Hideout.Areas.find(area => area.type === HideoutAreas.WATER_COLLECTOR); + const medStation = pmcData.Hideout.Areas.find((area) => area.type === HideoutAreas.MEDSTATION); + const waterCollector = pmcData.Hideout.Areas.find((area) => area.type === HideoutAreas.WATER_COLLECTOR); if (medStation?.level >= 1 && waterCollector?.level >= 1) { - const wall = pmcData.Hideout.Areas.find(area => area.type === HideoutAreas.EMERGENCY_WALL); + const wall = pmcData.Hideout.Areas.find((area) => area.type === HideoutAreas.EMERGENCY_WALL); if (wall?.level === 0) { wall.level = 3; @@ -224,7 +256,6 @@ export class HideoutController } /** - * * @param pmcData Profile to edit * @param output Object to send back to client * @param sessionID Session/player id @@ -232,7 +263,14 @@ export class HideoutController * @param dbHideoutArea Hideout area being upgraded * @param hideoutStage Stage hideout area is being upgraded to */ - protected addContainerImprovementToProfile(output: IItemEventRouterResponse, sessionID: string, pmcData: IPmcData, profileParentHideoutArea: HideoutArea, dbHideoutArea: IHideoutArea, hideoutStage: Stage): void + protected addContainerImprovementToProfile( + output: IItemEventRouterResponse, + sessionID: string, + pmcData: IPmcData, + profileParentHideoutArea: HideoutArea, + dbHideoutArea: IHideoutArea, + hideoutStage: Stage, + ): void { // Add key/value to `hideoutAreaStashes` dictionary - used to link hideout area to inventory stash by its id if (!pmcData.Inventory.hideoutAreaStashes[dbHideoutArea.type]) @@ -247,7 +285,9 @@ export class HideoutController this.addContainerUpgradeToClientOutput(output, sessionID, dbHideoutArea.type, dbHideoutArea, hideoutStage); // Some areas like gun stand have a child area linked to it, it needs to do the same as above - const childDbArea = this.databaseServer.getTables().hideout.areas.find(x => x.parentArea === dbHideoutArea._id); + const childDbArea = this.databaseServer.getTables().hideout.areas.find((x) => + x.parentArea === dbHideoutArea._id + ); if (childDbArea) { // Add key/value to `hideoutAreaStashes` dictionary - used to link hideout area to inventory stash by its id @@ -257,7 +297,9 @@ export class HideoutController } // Set child area level to same as parent area - pmcData.Hideout.Areas.find(x => x.type === childDbArea.type).level = pmcData.Hideout.Areas.find(x => x.type === profileParentHideoutArea.type).level; + pmcData.Hideout.Areas.find((x) => x.type === childDbArea.type).level = pmcData.Hideout.Areas.find((x) => + x.type === profileParentHideoutArea.type + ).level; // Add/upgrade stash item in player inventory const childDbAreaStage = childDbArea.stages[profileParentHideoutArea.level]; @@ -276,38 +318,41 @@ export class HideoutController */ protected addUpdateInventoryItemToProfile(pmcData: IPmcData, dbHideoutData: IHideoutArea, hideoutStage: Stage): void { - const existingInventoryItem = pmcData.Inventory.items.find(x => x._id === dbHideoutData._id); - if (existingInventoryItem) + const existingInventoryItem = pmcData.Inventory.items.find((x) => x._id === dbHideoutData._id); + if (existingInventoryItem) { // Update existing items container tpl to point to new id (tpl) existingInventoryItem._tpl = hideoutStage.container; - return; } // Add new item as none exists - pmcData.Inventory.items.push({ _id: dbHideoutData._id, _tpl: hideoutStage.container }); + pmcData.Inventory.items.push({_id: dbHideoutData._id, _tpl: hideoutStage.container}); } /** - * * @param output Objet to send to client * @param sessionID Session/player id * @param areaType Hideout area that had stash added * @param hideoutDbData Hideout area that caused addition of stash * @param hideoutStage Hideout area upgraded to this */ - protected addContainerUpgradeToClientOutput(output: IItemEventRouterResponse, sessionID: string, areaType: HideoutAreas, hideoutDbData: IHideoutArea, hideoutStage: Stage): void + protected addContainerUpgradeToClientOutput( + output: IItemEventRouterResponse, + sessionID: string, + areaType: HideoutAreas, + hideoutDbData: IHideoutArea, + hideoutStage: Stage, + ): void { if (!output.profileChanges[sessionID].changedHideoutStashes) { output.profileChanges[sessionID].changedHideoutStashes = {}; } - output.profileChanges[sessionID].changedHideoutStashes[areaType] = - { + output.profileChanges[sessionID].changedHideoutStashes[areaType] = { Id: hideoutDbData._id, - Tpl: hideoutStage.container + Tpl: hideoutStage.container, }; } @@ -315,28 +360,37 @@ export class HideoutController * Handle HideoutPutItemsInAreaSlots * Create item in hideout slot item array, remove item from player inventory * @param pmcData Profile data - * @param addItemToHideoutRequest reqeust from client to place item in area slot + * @param addItemToHideoutRequest request from client to place item in area slot * @param sessionID Session id * @returns IItemEventRouterResponse object */ - public putItemsInAreaSlots(pmcData: IPmcData, addItemToHideoutRequest: IHideoutPutItemInRequestData, sessionID: string): IItemEventRouterResponse + public putItemsInAreaSlots( + pmcData: IPmcData, + addItemToHideoutRequest: IHideoutPutItemInRequestData, + sessionID: string, + ): IItemEventRouterResponse { let output = this.eventOutputHolder.getOutput(sessionID); - const itemsToAdd = Object.entries(addItemToHideoutRequest.items).map(kvp => + const itemsToAdd = Object.entries(addItemToHideoutRequest.items).map((kvp) => { - const item = pmcData.Inventory.items.find(invItem => invItem._id === kvp[1]["id"]); + const item = pmcData.Inventory.items.find((invItem) => invItem._id === kvp[1]["id"]); return { inventoryItem: item, requestedItem: kvp[1], - slot: kvp[0] + slot: kvp[0], }; }); - const hideoutArea = pmcData.Hideout.Areas.find(area => area.type === addItemToHideoutRequest.areaType); + const hideoutArea = pmcData.Hideout.Areas.find((area) => area.type === addItemToHideoutRequest.areaType); if (!hideoutArea) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_area_in_database", addItemToHideoutRequest.areaType)); + this.logger.error( + this.localisationService.getText( + "hideout-unable_to_find_area_in_database", + addItemToHideoutRequest.areaType, + ), + ); return this.httpResponse.appendErrorToOutput(output); } @@ -344,21 +398,26 @@ export class HideoutController { if (!item.inventoryItem) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_item_in_inventory", {itemId: item.requestedItem["id"], area: hideoutArea.type})); + this.logger.error( + this.localisationService.getText("hideout-unable_to_find_item_in_inventory", { + itemId: item.requestedItem["id"], + area: hideoutArea.type, + }), + ); return this.httpResponse.appendErrorToOutput(output); } // Add item to area.slots const destinationLocationIndex = Number(item.slot); - const hideoutSlotIndex = hideoutArea.slots.findIndex(x => x.locationIndex === destinationLocationIndex); + const hideoutSlotIndex = hideoutArea.slots.findIndex((x) => x.locationIndex === destinationLocationIndex); hideoutArea.slots[hideoutSlotIndex].item = [{ _id: item.inventoryItem._id, _tpl: item.inventoryItem._tpl, - upd: item.inventoryItem.upd + upd: item.inventoryItem.upd, }]; output = this.inventoryHelper.removeItem(pmcData, item.inventoryItem._id, sessionID, output); - } + } // Trigger a forced update this.hideoutHelper.updatePlayerHideout(sessionID); @@ -374,11 +433,15 @@ export class HideoutController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public takeItemsFromAreaSlots(pmcData: IPmcData, request: IHideoutTakeItemOutRequestData, sessionID: string): IItemEventRouterResponse + public takeItemsFromAreaSlots( + pmcData: IPmcData, + request: IHideoutTakeItemOutRequestData, + sessionID: string, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionID); - const hideoutArea = pmcData.Hideout.Areas.find(area => area.type === request.areaType); + const hideoutArea = pmcData.Hideout.Areas.find((area) => area.type === request.areaType); if (!hideoutArea) { this.logger.error(this.localisationService.getText("hideout-unable_to_find_area", request.areaType)); @@ -387,19 +450,30 @@ export class HideoutController if (!hideoutArea.slots || hideoutArea.slots.length === 0) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_item_to_remove_from_area", hideoutArea.type)); + this.logger.error( + this.localisationService.getText("hideout-unable_to_find_item_to_remove_from_area", hideoutArea.type), + ); return this.httpResponse.appendErrorToOutput(output); } // Handle areas that have resources that can be placed in/taken out of slots from the area - if ([HideoutAreas.AIR_FILTERING, HideoutAreas.WATER_COLLECTOR, HideoutAreas.GENERATOR, HideoutAreas.BITCOIN_FARM].includes(hideoutArea.type)) + if ( + [ + HideoutAreas.AIR_FILTERING, + HideoutAreas.WATER_COLLECTOR, + HideoutAreas.GENERATOR, + HideoutAreas.BITCOIN_FARM, + ].includes(hideoutArea.type) + ) { const response = this.removeResourceFromArea(sessionID, pmcData, request, output, hideoutArea); this.update(); return response; } - throw new Error(this.localisationService.getText("hideout-unhandled_remove_item_from_area_request", hideoutArea.type)); + throw new Error( + this.localisationService.getText("hideout-unhandled_remove_item_from_area_request", hideoutArea.type), + ); } /** @@ -411,22 +485,36 @@ export class HideoutController * @param hideoutArea Area fuel is being removed from * @returns IItemEventRouterResponse response */ - protected removeResourceFromArea(sessionID: string, pmcData: IPmcData, removeResourceRequest: IHideoutTakeItemOutRequestData, output: IItemEventRouterResponse, hideoutArea: HideoutArea): IItemEventRouterResponse + protected removeResourceFromArea( + sessionID: string, + pmcData: IPmcData, + removeResourceRequest: IHideoutTakeItemOutRequestData, + output: IItemEventRouterResponse, + hideoutArea: HideoutArea, + ): IItemEventRouterResponse { const slotIndexToRemove = removeResourceRequest.slots[0]; - const itemToReturn = hideoutArea.slots.find(x => x.locationIndex === slotIndexToRemove).item[0]; - + const itemToReturn = hideoutArea.slots.find((x) => x.locationIndex === slotIndexToRemove).item[0]; + const newReq = { items: [{ // eslint-disable-next-line @typescript-eslint/naming-convention item_id: itemToReturn._tpl, - count: 1 + count: 1, }], - tid: "ragfair" + tid: "ragfair", }; - output = this.inventoryHelper.addItem(pmcData, newReq, output, sessionID, null, !!itemToReturn.upd.SpawnedInSession, itemToReturn.upd); + output = this.inventoryHelper.addItem( + pmcData, + newReq, + output, + sessionID, + null, + !!itemToReturn.upd.SpawnedInSession, + itemToReturn.upd, + ); // If addItem returned with errors, drop out if (output.warnings && output.warnings.length > 0) @@ -435,7 +523,7 @@ export class HideoutController } // Remove items from slot, locationIndex remains - const hideoutSlotIndex = hideoutArea.slots.findIndex(x => x.locationIndex === slotIndexToRemove); + const hideoutSlotIndex = hideoutArea.slots.findIndex((x) => x.locationIndex === slotIndexToRemove); hideoutArea.slots[hideoutSlotIndex].item = undefined; return output; @@ -449,14 +537,18 @@ export class HideoutController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public toggleArea(pmcData: IPmcData, request: IHideoutToggleAreaRequestData, sessionID: string): IItemEventRouterResponse + public toggleArea( + pmcData: IPmcData, + request: IHideoutToggleAreaRequestData, + sessionID: string, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionID); // Force a production update (occur before area is toggled as it could be generator and doing it after generator enabled would cause incorrect calculaton of production progress) this.hideoutHelper.updatePlayerHideout(sessionID); - const hideoutArea = pmcData.Hideout.Areas.find(area => area.type === request.areaType); + const hideoutArea = pmcData.Hideout.Areas.find((area) => area.type === request.areaType); if (!hideoutArea) { this.logger.error(this.localisationService.getText("hideout-unable_to_find_area", request.areaType)); @@ -472,27 +564,31 @@ export class HideoutController * Handle HideoutSingleProductionStart event * Start production for an item from hideout area * @param pmcData Player profile - * @param body Start prodution of single item request + * @param body Start production of single item request * @param sessionID Session id * @returns IItemEventRouterResponse */ - public singleProductionStart(pmcData: IPmcData, body: IHideoutSingleProductionStartRequestData, sessionID: string): IItemEventRouterResponse + public singleProductionStart( + pmcData: IPmcData, + body: IHideoutSingleProductionStartRequestData, + sessionID: string, + ): IItemEventRouterResponse { // Start production this.registerProduction(pmcData, body, sessionID); // Find the recipe of the production - const recipe = this.databaseServer.getTables().hideout.production.find(p => p._id === body.recipeId); + const recipe = this.databaseServer.getTables().hideout.production.find((p) => p._id === body.recipeId); // Find the actual amount of items we need to remove because body can send weird data - const requirements = this.jsonUtil.clone(recipe.requirements.filter(i => i.type === "Item")); + const requirements = this.jsonUtil.clone(recipe.requirements.filter((i) => i.type === "Item")); const output = this.eventOutputHolder.getOutput(sessionID); for (const itemToDelete of body.items) { - const itemToCheck = pmcData.Inventory.items.find(i => i._id === itemToDelete.id); - const requirement = requirements.find(requirement => requirement.templateId === itemToCheck._tpl); + const itemToCheck = pmcData.Inventory.items.find((i) => i._id === itemToDelete.id); + const requirement = requirements.find((requirement) => requirement.templateId === itemToCheck._tpl); if (requirement.count <= 0) { continue; @@ -513,21 +609,32 @@ export class HideoutController * @param sessionID session id * @returns item event router response */ - public scavCaseProductionStart(pmcData: IPmcData, body: IHideoutScavCaseStartRequestData, sessionID: string): IItemEventRouterResponse + public scavCaseProductionStart( + pmcData: IPmcData, + body: IHideoutScavCaseStartRequestData, + sessionID: string, + ): IItemEventRouterResponse { let output = this.eventOutputHolder.getOutput(sessionID); for (const requestedItem of body.items) { - const inventoryItem = pmcData.Inventory.items.find(item => item._id === requestedItem.id); + const inventoryItem = pmcData.Inventory.items.find((item) => item._id === requestedItem.id); if (!inventoryItem) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_scavcase_requested_item_in_profile_inventory", requestedItem.id)); + this.logger.error( + this.localisationService.getText( + "hideout-unable_to_find_scavcase_requested_item_in_profile_inventory", + requestedItem.id, + ), + ); return this.httpResponse.appendErrorToOutput(output); } - if (inventoryItem.upd?.StackObjectsCount - && inventoryItem.upd.StackObjectsCount > requestedItem.count) + if ( + inventoryItem.upd?.StackObjectsCount && + inventoryItem.upd.StackObjectsCount > requestedItem.count + ) { inventoryItem.upd.StackObjectsCount -= requestedItem.count; } @@ -537,19 +644,25 @@ export class HideoutController } } - const recipe = this.databaseServer.getTables().hideout.scavcase.find(r => r._id === body.recipeId); + const recipe = this.databaseServer.getTables().hideout.scavcase.find((r) => r._id === body.recipeId); if (!recipe) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_scav_case_recipie_in_database", body.recipeId)); + this.logger.error( + this.localisationService.getText("hideout-unable_to_find_scav_case_recipie_in_database", body.recipeId), + ); return this.httpResponse.appendErrorToOutput(output); } - + // @Important: Here we need to be very exact: // - normal recipe: Production time value is stored in attribute "productionType" with small "p" // - scav case recipe: Production time value is stored in attribute "ProductionType" with capital "P" const modifiedScavCaseTime = this.getScavCaseTime(pmcData, recipe.ProductionTime); - pmcData.Hideout.Production[body.recipeId] = this.hideoutHelper.initProduction(body.recipeId, modifiedScavCaseTime, false); + pmcData.Hideout.Production[body.recipeId] = this.hideoutHelper.initProduction( + body.recipeId, + modifiedScavCaseTime, + false, + ); pmcData.Hideout.Production[body.recipeId].sptIsScavCase = true; return output; @@ -557,7 +670,7 @@ export class HideoutController /** * Adjust scav case time based on fence standing - * + * * @param pmcData Player profile * @param productionTime Time to complete scav case in seconds * @returns Adjusted scav case time in seconds @@ -569,7 +682,6 @@ export class HideoutController { return productionTime; } - return productionTime * fenceLevel.ScavCaseTimeModifier; } @@ -582,21 +694,24 @@ export class HideoutController protected addScavCaseRewardsToProfile(pmcData: IPmcData, rewards: Product[], recipeId: string): void { pmcData.Hideout.Production[`ScavCase${recipeId}`] = { - Products: rewards + Products: rewards, }; } /** * Start production of continuously created item * @param pmcData Player profile - * @param request Continious production request + * @param request Continuous production request * @param sessionID Session id * @returns IItemEventRouterResponse */ - public continuousProductionStart(pmcData: IPmcData, request: IHideoutContinuousProductionStartRequestData, sessionID: string): IItemEventRouterResponse + public continuousProductionStart( + pmcData: IPmcData, + request: IHideoutContinuousProductionStartRequestData, + sessionID: string, + ): IItemEventRouterResponse { this.registerProduction(pmcData, request, sessionID); - return this.eventOutputHolder.getOutput(sessionID); } @@ -608,7 +723,11 @@ export class HideoutController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public takeProduction(pmcData: IPmcData, request: IHideoutTakeProductionRequestData, sessionID: string): IItemEventRouterResponse + public takeProduction( + pmcData: IPmcData, + request: IHideoutTakeProductionRequestData, + sessionID: string, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionID); @@ -617,19 +736,24 @@ export class HideoutController return this.hideoutHelper.getBTC(pmcData, request, sessionID); } - const recipe = this.databaseServer.getTables().hideout.production.find(r => r._id === request.recipeId); + const recipe = this.databaseServer.getTables().hideout.production.find((r) => r._id === request.recipeId); if (recipe) { return this.handleRecipe(sessionID, recipe, pmcData, request, output); } - const scavCase = this.databaseServer.getTables().hideout.scavcase.find(r => r._id === request.recipeId); + const scavCase = this.databaseServer.getTables().hideout.scavcase.find((r) => r._id === request.recipeId); if (scavCase) { return this.handleScavCase(sessionID, pmcData, request, output); } - this.logger.error(this.localisationService.getText("hideout-unable_to_find_production_in_profile_by_recipie_id", request.recipeId)); + this.logger.error( + this.localisationService.getText( + "hideout-unable_to_find_production_in_profile_by_recipie_id", + request.recipeId, + ), + ); return this.httpResponse.appendErrorToOutput(output); } @@ -643,9 +767,15 @@ export class HideoutController * @param output Output object to update * @returns IItemEventRouterResponse */ - protected handleRecipe(sessionID: string, recipe: IHideoutProduction, pmcData: IPmcData, request: IHideoutTakeProductionRequestData, output: IItemEventRouterResponse): IItemEventRouterResponse + protected handleRecipe( + sessionID: string, + recipe: IHideoutProduction, + pmcData: IPmcData, + request: IHideoutTakeProductionRequestData, + output: IItemEventRouterResponse, + ): IItemEventRouterResponse { - // Variables for managemnet of skill + // Variables for management of skill let craftingExpAmount = 0; // ? move the logic of BackendCounters in new method? @@ -654,12 +784,11 @@ export class HideoutController { pmcData.BackendCounters[HideoutController.nameBackendCountersCrafting] = { id: HideoutController.nameBackendCountersCrafting, - value: 0 + value: 0, }; counterHoursCrafting = pmcData.BackendCounters[HideoutController.nameBackendCountersCrafting]; } let hoursCrafting = counterHoursCrafting.value; - // create item and throw it into profile let id = recipe.endProduct; @@ -672,18 +801,18 @@ export class HideoutController const newReq = { items: [{ - // eslint-disable-next-line @typescript-eslint/naming-convention item_id: id, - count: recipe.count + count: recipe.count, }], - tid: "ragfair" + tid: "ragfair", }; const entries = Object.entries(pmcData.Hideout.Production); let prodId: string; for (const x of entries) { - if (this.hideoutHelper.isProductionType(x[1])) // Production or ScavCase + // Production or ScavCase + if (this.hideoutHelper.isProductionType(x[1])) { if ((x[1] as Production).RecipeId === request.recipeId) { @@ -695,7 +824,12 @@ export class HideoutController if (prodId === undefined) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_production_in_profile_by_recipie_id", request.recipeId)); + this.logger.error( + this.localisationService.getText( + "hideout-unable_to_find_production_in_profile_by_recipie_id", + request.recipeId, + ), + ); return this.httpResponse.appendErrorToOutput(output); } @@ -712,9 +846,9 @@ export class HideoutController hoursCrafting += recipe.productionTime; if ((hoursCrafting / this.hideoutConfig.hoursForSkillCrafting) >= 1) { - const multiplierCrafting = Math.floor((hoursCrafting / this.hideoutConfig.hoursForSkillCrafting)); - craftingExpAmount += (1 * multiplierCrafting); - hoursCrafting -= (this.hideoutConfig.hoursForSkillCrafting * multiplierCrafting); + const multiplierCrafting = Math.floor(hoursCrafting / this.hideoutConfig.hoursForSkillCrafting); + craftingExpAmount += 1 * multiplierCrafting; + hoursCrafting -= this.hideoutConfig.hoursForSkillCrafting * multiplierCrafting; } // increment @@ -726,12 +860,21 @@ export class HideoutController // manager Hideout skill // ? use a configuration variable for the value? const globals = this.databaseServer.getTables().globals; - this.profileHelper.addSkillPointsToPlayer(pmcData, SkillTypes.HIDEOUT_MANAGEMENT, globals.config.SkillsSettings.HideoutManagement.SkillPointsPerCraft, true); - //manager Crafting skill + this.profileHelper.addSkillPointsToPlayer( + pmcData, + SkillTypes.HIDEOUT_MANAGEMENT, + globals.config.SkillsSettings.HideoutManagement.SkillPointsPerCraft, + true, + ); + // manager Crafting skill if (craftingExpAmount > 0) { this.profileHelper.addSkillPointsToPlayer(pmcData, SkillTypes.CRAFTING, craftingExpAmount); - this.profileHelper.addSkillPointsToPlayer(pmcData, SkillTypes.INTELLECT, 0.5 * (Math.round(craftingExpAmount / 15))); + this.profileHelper.addSkillPointsToPlayer( + pmcData, + SkillTypes.INTELLECT, + 0.5 * (Math.round(craftingExpAmount / 15)), + ); } area.lastRecipe = request.recipeId; counterHoursCrafting.value = hoursCrafting; @@ -747,7 +890,7 @@ export class HideoutController if (recipe.isEncoded) { const upd: Upd = { - RecodableComponent: { IsEncoded: true} + RecodableComponent: {IsEncoded: true}, }; return this.inventoryHelper.addItem(pmcData, newReq, output, sessionID, callback, true, upd); @@ -764,13 +907,19 @@ export class HideoutController * @param output Output object to update * @returns IItemEventRouterResponse */ - protected handleScavCase(sessionID: string, pmcData: IPmcData, request: IHideoutTakeProductionRequestData, output: IItemEventRouterResponse): IItemEventRouterResponse + protected handleScavCase( + sessionID: string, + pmcData: IPmcData, + request: IHideoutTakeProductionRequestData, + output: IItemEventRouterResponse, + ): IItemEventRouterResponse { const ongoingProductions = Object.entries(pmcData.Hideout.Production); let prodId: string; for (const production of ongoingProductions) { - if (this.hideoutHelper.isProductionType(production[1])) // Production or ScavCase + // Production or ScavCase + if (this.hideoutHelper.isProductionType(production[1])) { if ((production[1] as ScavCase).RecipeId === request.recipeId) { @@ -782,7 +931,12 @@ export class HideoutController if (prodId === undefined) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_production_in_profile_by_recipie_id", request.recipeId)); + this.logger.error( + this.localisationService.getText( + "hideout-unable_to_find_production_in_profile_by_recipie_id", + request.recipeId, + ), + ); return this.httpResponse.appendErrorToOutput(output); } @@ -795,28 +949,29 @@ export class HideoutController // Remove the old production from output object before its sent to client delete output.profileChanges[sessionID].production[request.recipeId]; - const itemsToAdd = pmcData.Hideout.Production[prodId].Products.map((x: { _tpl: string; upd?: { StackObjectsCount?: number; }; }) => - { - let id = x._tpl; - if (this.presetHelper.hasPreset(id)) + const itemsToAdd = pmcData.Hideout.Production[prodId].Products.map( + (x: {_tpl: string; upd?: {StackObjectsCount?: number;};}) => { - id = this.presetHelper.getDefaultPreset(id)._id; - } - const numOfItems = !x.upd?.StackObjectsCount - ? 1 - : x.upd.StackObjectsCount; - // eslint-disable-next-line @typescript-eslint/naming-convention - return { item_id: id, count: numOfItems }; - }); + let id = x._tpl; + if (this.presetHelper.hasPreset(id)) + { + id = this.presetHelper.getDefaultPreset(id)._id; + } + const numOfItems = !x.upd?.StackObjectsCount ? + 1 : + x.upd.StackObjectsCount; + + return {item_id: id, count: numOfItems}; + }, + ); const newReq = { items: itemsToAdd, - tid: "ragfair" + tid: "ragfair", }; const callback = () => { - // Null production data now it's complete - will be cleaned up later by update() process pmcData.Hideout.Production[prodId] = null; }; @@ -831,18 +986,21 @@ export class HideoutController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public registerProduction(pmcData: IPmcData, request: IHideoutSingleProductionStartRequestData | IHideoutContinuousProductionStartRequestData, sessionID: string): IItemEventRouterResponse + public registerProduction( + pmcData: IPmcData, + request: IHideoutSingleProductionStartRequestData | IHideoutContinuousProductionStartRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.hideoutHelper.registerProduction(pmcData, request, sessionID); } /** * Get quick time event list for hideout - * // TODO - implement this + * // TODO: Implement this * @param sessionId Session id * @returns IQteData array - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars + */ public getQteList(sessionId: string): IQteData[] { return this.databaseServer.getTables().hideout.qte; @@ -855,8 +1013,11 @@ export class HideoutController * @param pmcData Profile to adjust * @param request QTE result object */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public handleQTEEventOutcome(sessionId: string, pmcData: IPmcData, request: IHandleQTEEventRequestData): IItemEventRouterResponse + public handleQTEEventOutcome( + sessionId: string, + pmcData: IPmcData, + request: IHandleQTEEventRequestData, + ): IItemEventRouterResponse { // { // Action: "HideoutQuickTimeEvent", @@ -865,7 +1026,7 @@ export class HideoutController // timestamp: 1672585349 // } - // Skill changes are done in + // Skill changes are done in // /client/hideout/workout (applyWorkoutChanges). pmcData.Health.Energy.Current -= 50; @@ -890,22 +1051,28 @@ export class HideoutController * @param request shooting range score request * @returns IItemEventRouterResponse */ - public recordShootingRangePoints(sessionId: string, pmcData: IPmcData, request: IRecordShootingRangePoints): IItemEventRouterResponse + public recordShootingRangePoints( + sessionId: string, + pmcData: IPmcData, + request: IRecordShootingRangePoints, + ): IItemEventRouterResponse { - // Check if counter exists, add placeholder if it doesnt - if (!pmcData.Stats.Eft.OverallCounters.Items.find(x => x.Key.includes("ShootingRangePoints"))) + // Check if counter exists, add placeholder if it doesn't + if (!pmcData.Stats.Eft.OverallCounters.Items.find((x) => x.Key.includes("ShootingRangePoints"))) { pmcData.Stats.Eft.OverallCounters.Items.push({ Key: ["ShootingRangePoints"], - Value: 0 + Value: 0, }); } // Find counter by key and update value - const shootingRangeHighScore = pmcData.Stats.Eft.OverallCounters.Items.find(x => x.Key.includes("ShootingRangePoints")); + const shootingRangeHighScore = pmcData.Stats.Eft.OverallCounters.Items.find((x) => + x.Key.includes("ShootingRangePoints") + ); shootingRangeHighScore.Value = request.points; - // Check against live, maybe a response isnt necessary + // Check against live, maybe a response isn't necessary return this.eventOutputHolder.getOutput(sessionId); } @@ -915,17 +1082,21 @@ export class HideoutController * @param pmcData Profile to improve area in * @param request Improve area request data */ - public improveArea(sessionId: string, pmcData: IPmcData, request: IHideoutImproveAreaRequestData): IItemEventRouterResponse + public improveArea( + sessionId: string, + pmcData: IPmcData, + request: IHideoutImproveAreaRequestData, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionId); - // Create mapping of required item with corrisponding item from player inventory - const items = request.items.map(reqItem => + // Create mapping of required item with corresponding item from player inventory + const items = request.items.map((reqItem) => { - const item = pmcData.Inventory.items.find(invItem => invItem._id === reqItem.id); + const item = pmcData.Inventory.items.find((invItem) => invItem._id === reqItem.id); return { inventoryItem: item, - requestedItem: reqItem + requestedItem: reqItem, }; }); @@ -934,14 +1105,18 @@ export class HideoutController { if (!item.inventoryItem) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_item_in_inventory", item.requestedItem.id)); + this.logger.error( + this.localisationService.getText("hideout-unable_to_find_item_in_inventory", item.requestedItem.id), + ); return this.httpResponse.appendErrorToOutput(output); } - if (this.paymentHelper.isMoneyTpl(item.inventoryItem._tpl) - && item.inventoryItem.upd - && item.inventoryItem.upd.StackObjectsCount - && item.inventoryItem.upd.StackObjectsCount > item.requestedItem.count) + if ( + this.paymentHelper.isMoneyTpl(item.inventoryItem._tpl) && + item.inventoryItem.upd && + item.inventoryItem.upd.StackObjectsCount && + item.inventoryItem.upd.StackObjectsCount > item.requestedItem.count + ) { item.inventoryItem.upd.StackObjectsCount -= item.requestedItem.count; } @@ -951,21 +1126,23 @@ export class HideoutController } } - const profileHideoutArea = pmcData.Hideout.Areas.find(x => x.type === request.areaType); + const profileHideoutArea = pmcData.Hideout.Areas.find((x) => x.type === request.areaType); if (!profileHideoutArea) { this.logger.error(this.localisationService.getText("hideout-unable_to_find_area", request.areaType)); return this.httpResponse.appendErrorToOutput(output); } - const hideoutDbData = this.databaseServer.getTables().hideout.areas.find(x => x.type === request.areaType); + const hideoutDbData = this.databaseServer.getTables().hideout.areas.find((x) => x.type === request.areaType); if (!hideoutDbData) { - this.logger.error(this.localisationService.getText("hideout-unable_to_find_area_in_database", request.areaType)); + this.logger.error( + this.localisationService.getText("hideout-unable_to_find_area_in_database", request.areaType), + ); return this.httpResponse.appendErrorToOutput(output); } - // Add all improvemets to output object + // Add all improvements to output object const improvements = hideoutDbData.stages[profileHideoutArea.level].improvements; const timestamp = this.timeUtil.getTimestamp(); for (const improvement of improvements) @@ -975,10 +1152,13 @@ export class HideoutController output.profileChanges[sessionId].improvements = {}; } - const improvementDetails = {completed: false, improveCompleteTimestamp: timestamp + improvement.improvementTime}; + const improvementDetails = { + completed: false, + improveCompleteTimestamp: timestamp + improvement.improvementTime, + }; output.profileChanges[sessionId].improvements[improvement.id] = improvementDetails; pmcData.Hideout.Improvement[improvement.id] = improvementDetails; - } + } return output; } @@ -990,7 +1170,11 @@ export class HideoutController * @param request Cancel production request data * @returns IItemEventRouterResponse */ - public cancelProduction(sessionId: string, pmcData: IPmcData, request: IHideoutCancelProductionRequestData): IItemEventRouterResponse + public cancelProduction( + sessionId: string, + pmcData: IPmcData, + request: IHideoutCancelProductionRequestData, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionId); @@ -1006,7 +1190,7 @@ export class HideoutController // Null out production data so client gets informed when response send back pmcData.Hideout.Production[request.recipeId] = null; - // TODO - handle timestamp somehow? + // TODO: handle timestamp somehow? return output; } diff --git a/project/src/controllers/InraidController.ts b/project/src/controllers/InraidController.ts index beda6701..682134e3 100644 --- a/project/src/controllers/InraidController.ts +++ b/project/src/controllers/InraidController.ts @@ -56,7 +56,7 @@ export class InraidController @inject("InsuranceService") protected insuranceService: InsuranceService, @inject("InRaidHelper") protected inRaidHelper: InRaidHelper, @inject("ApplicationContext") protected applicationContext: ApplicationContext, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.airdropConfig = this.configServer.getConfig(ConfigTypes.AIRDROP); @@ -124,7 +124,12 @@ export class InraidController // Check for exit status this.markOrRemoveFoundInRaidItems(postRaidRequest); - postRaidRequest.profile.Inventory.items = this.itemHelper.replaceIDs(postRaidRequest.profile, postRaidRequest.profile.Inventory.items, serverPmcData.InsuredItems, postRaidRequest.profile.Inventory.fastPanel); + postRaidRequest.profile.Inventory.items = this.itemHelper.replaceIDs( + postRaidRequest.profile, + postRaidRequest.profile.Inventory.items, + serverPmcData.InsuredItems, + postRaidRequest.profile.Inventory.fastPanel, + ); this.inRaidHelper.addUpdToMoneyFromRaid(postRaidRequest.profile.Inventory.items); // Purge profile of equipment/container items @@ -146,22 +151,30 @@ export class InraidController if (locationName === "lighthouse" && postRaidRequest.profile.Info.Side.toLowerCase() === "usec") { // Decrement counter if it exists, don't go below 0 - const remainingCounter = serverPmcData?.Stats.Eft.OverallCounters.Items.find(x => x.Key.includes("UsecRaidRemainKills")); + const remainingCounter = serverPmcData?.Stats.Eft.OverallCounters.Items.find((x) => + x.Key.includes("UsecRaidRemainKills") + ); if (remainingCounter?.Value > 0) { - remainingCounter.Value --; + remainingCounter.Value--; } } if (isDead) { - this.pmcChatResponseService.sendKillerResponse(sessionID, serverPmcData, postRaidRequest.profile.Stats.Eft.Aggressor); + this.pmcChatResponseService.sendKillerResponse( + sessionID, + serverPmcData, + postRaidRequest.profile.Stats.Eft.Aggressor, + ); this.matchBotDetailsCacheService.clearCache(); serverPmcData = this.performPostRaidActionsWhenDead(postRaidRequest, serverPmcData, sessionID); } - const victims = postRaidRequest.profile.Stats.Eft.Victims.filter(x => ["sptbear", "sptusec"].includes(x.Role.toLowerCase())); + const victims = postRaidRequest.profile.Stats.Eft.Victims.filter((x) => + ["sptbear", "sptusec"].includes(x.Role.toLowerCase()) + ); if (victims?.length > 0) { this.pmcChatResponseService.sendVictimResponse(sessionID, victims, serverPmcData); @@ -175,26 +188,37 @@ export class InraidController /** * Make changes to pmc profile after they've died in raid, - * Alter bodypart hp, handle insurance, delete inventory items, remove carried quest items - * @param postRaidSaveRequest Post-raid save request + * Alter body part hp, handle insurance, delete inventory items, remove carried quest items + * @param postRaidSaveRequest Post-raid save request * @param pmcData Pmc profile * @param sessionID Session id * @returns Updated profile object */ - protected performPostRaidActionsWhenDead(postRaidSaveRequest: ISaveProgressRequestData, pmcData: IPmcData, sessionID: string): IPmcData + protected performPostRaidActionsWhenDead( + postRaidSaveRequest: ISaveProgressRequestData, + pmcData: IPmcData, + sessionID: string, + ): IPmcData { this.updatePmcHealthPostRaid(postRaidSaveRequest, pmcData); this.inRaidHelper.deleteInventory(pmcData, sessionID); if (this.inRaidHelper.removeQuestItemsOnDeath()) { - // Find and remove the completed condition from profile if player died, otherwise quest is stuck in limbo and quest items cannot be picked up again + // Find and remove the completed condition from profile if player died, otherwise quest is stuck in limbo + // and quest items cannot be picked up again const allQuests = this.questHelper.getQuestsFromDb(); - const activeQuestIdsInProfile = pmcData.Quests.filter(x => ![QuestStatus.AvailableForStart, QuestStatus.Success, QuestStatus.Expired].includes(x.status)).map(x => x.qid); + const activeQuestIdsInProfile = pmcData.Quests.filter((x) => + ![QuestStatus.AvailableForStart, QuestStatus.Success, QuestStatus.Expired].includes(x.status) + ).map((x) => x.qid); for (const questItem of postRaidSaveRequest.profile.Stats.Eft.CarriedQuestItems) { // Get quest/find condition for carried quest item - const questAndFindItemConditionId = this.questHelper.getFindItemConditionByQuestItem(questItem, activeQuestIdsInProfile, allQuests); + const questAndFindItemConditionId = this.questHelper.getFindItemConditionByQuestItem( + questItem, + activeQuestIdsInProfile, + allQuests, + ); if (questAndFindItemConditionId) { this.profileHelper.removeCompletedQuestConditionFromProfile(pmcData, questAndFindItemConditionId); @@ -209,7 +233,7 @@ export class InraidController } /** - * Adjust player characters bodypart hp post-raid + * Adjust player characters body part hp post-raid * @param postRaidSaveRequest post raid data * @param pmcData player profile */ @@ -234,13 +258,13 @@ export class InraidController /** * Reduce body part hp to % of max * @param pmcData profile to edit - * @param multipler multipler to apply to max health + * @param multiplier multiplier to apply to max health */ - protected reducePmcHealthToPercent(pmcData: IPmcData, multipler: number): void + protected reducePmcHealthToPercent(pmcData: IPmcData, multiplier: number): void { for (const bodyPart of Object.values(pmcData.Health.BodyParts)) { - (bodyPart).Health.Current = (bodyPart).Health.Maximum * multipler; + (bodyPart).Health.Current = (bodyPart).Health.Maximum * multiplier; } } @@ -269,7 +293,12 @@ export class InraidController // Check for exit status this.markOrRemoveFoundInRaidItems(postRaidRequest); - postRaidRequest.profile.Inventory.items = this.itemHelper.replaceIDs(postRaidRequest.profile, postRaidRequest.profile.Inventory.items, pmcData.InsuredItems, postRaidRequest.profile.Inventory.fastPanel); + postRaidRequest.profile.Inventory.items = this.itemHelper.replaceIDs( + postRaidRequest.profile, + postRaidRequest.profile.Inventory.items, + pmcData.InsuredItems, + postRaidRequest.profile.Inventory.fastPanel, + ); this.inRaidHelper.addUpdToMoneyFromRaid(postRaidRequest.profile.Inventory.items); this.handlePostRaidPlayerScavProcess(scavData, sessionID, postRaidRequest, pmcData, isDead); @@ -278,7 +307,7 @@ export class InraidController /** * Does provided profile contain any condition counters * @param profile Profile to check for condition counters - * @returns + * @returns */ protected profileHasConditionCounters(profile: IPmcData): boolean { @@ -286,7 +315,6 @@ export class InraidController { return false; } - return profile.ConditionCounters.Counters.length > 0; } @@ -294,7 +322,7 @@ export class InraidController { for (const quest of scavProfile.Quests) { - const pmcQuest = pmcProfile.Quests.find(x => x.qid === quest.qid); + const pmcQuest = pmcProfile.Quests.find((x) => x.qid === quest.qid); if (!pmcQuest) { this.logger.warning(`No PMC quest found for ID: ${quest.qid}`); @@ -303,9 +331,14 @@ export class InraidController // Post-raid status is enum word e.g. `Started` but pmc quest status is number e.g. 2 // Status values mismatch or statusTimers counts mismatch - if (quest.status !== QuestStatus[pmcQuest.status] || quest.statusTimers.length !== pmcQuest.statusTimers.length) + if ( + quest.status !== QuestStatus[pmcQuest.status] || + quest.statusTimers.length !== pmcQuest.statusTimers.length + ) { - this.logger.warning(`Quest: ${quest.qid} found in PMC profile has different status/statustimer. Scav: ${quest.status} vs PMC: ${pmcQuest.status}`); + this.logger.warning( + `Quest: ${quest.qid} found in PMC profile has different status/statustimer. Scav: ${quest.status} vs PMC: ${pmcQuest.status}`, + ); pmcQuest.status = QuestStatus[quest.status]; // Copy status timers over + fix bad enum key for each @@ -324,17 +357,20 @@ export class InraidController // Loop over all scav counters and add into pmc profile for (const scavCounter of scavProfile.ConditionCounters.Counters) { - this.logger.warning(`Processing counter: ${scavCounter.id} value:${scavCounter.value} quest:${scavCounter.qid}`); - const counterInPmcProfile = pmcProfile.ConditionCounters.Counters.find(x => x.id === scavCounter.id); + this.logger.warning( + `Processing counter: ${scavCounter.id} value:${scavCounter.value} quest:${scavCounter.qid}`, + ); + const counterInPmcProfile = pmcProfile.ConditionCounters.Counters.find((x) => x.id === scavCounter.id); if (!counterInPmcProfile) { // Doesn't exist yet, push it straight in pmcProfile.ConditionCounters.Counters.push(scavCounter); - continue; } - this.logger.warning(`Counter id: ${scavCounter.id} already exists in pmc profile! with value: ${counterInPmcProfile.value} for quest: ${counterInPmcProfile.qid}`); + this.logger.warning( + `Counter id: ${scavCounter.id} already exists in pmc profile! with value: ${counterInPmcProfile.value} for quest: ${counterInPmcProfile.qid}`, + ); // Only adjust counter value if its changed if (counterInPmcProfile.value !== scavCounter.value) @@ -363,7 +399,7 @@ export class InraidController { if (offraidData.exit !== PlayerRaidEndState.SURVIVED) { - // Remove FIR status if the player havn't survived + // Remove FIR status if the player hasn't survived offraidData.profile = this.inRaidHelper.removeSpawnedInSessionPropertyFromItems(offraidData.profile); } } @@ -376,7 +412,13 @@ export class InraidController * @param pmcData Pmc profile * @param isDead Is player dead */ - protected handlePostRaidPlayerScavProcess(scavData: IPmcData, sessionID: string, offraidData: ISaveProgressRequestData, pmcData: IPmcData, isDead: boolean): void + protected handlePostRaidPlayerScavProcess( + scavData: IPmcData, + sessionID: string, + offraidData: ISaveProgressRequestData, + pmcData: IPmcData, + isDead: boolean, + ): void { // Update scav profile inventory scavData = this.inRaidHelper.setInventory(sessionID, scavData, offraidData.profile); @@ -411,14 +453,17 @@ export class InraidController let fenceStanding = Number(pmcData.TradersInfo[fenceId].standing); this.logger.debug(`Old fence standing: ${fenceStanding}`); - fenceStanding = this.inRaidHelper.calculateFenceStandingChangeFromKills(fenceStanding, offraidData.profile.Stats.Eft.Victims); + fenceStanding = this.inRaidHelper.calculateFenceStandingChangeFromKills( + fenceStanding, + offraidData.profile.Stats.Eft.Victims, + ); // Successful extract with scav adds 0.01 standing if (offraidData.exit === PlayerRaidEndState.SURVIVED) { fenceStanding += this.inraidConfig.scavExtractGain; } - + // Make standing changes to pmc profile pmcData.TradersInfo[fenceId].standing = Math.min(Math.max(fenceStanding, -7), 15); // Ensure it stays between -7 and 15 this.logger.debug(`New fence standing: ${pmcData.TradersInfo[fenceId].standing}`); @@ -443,4 +488,4 @@ export class InraidController { return this.airdropConfig; } -} \ No newline at end of file +} diff --git a/project/src/controllers/InsuranceController.ts b/project/src/controllers/InsuranceController.ts index 6393f9db..271ad0bd 100644 --- a/project/src/controllers/InsuranceController.ts +++ b/project/src/controllers/InsuranceController.ts @@ -10,7 +10,7 @@ import { IGetInsuranceCostRequestData } from "@spt-aki/models/eft/insurance/IGet import { IGetInsuranceCostResponseData } from "@spt-aki/models/eft/insurance/IGetInsuranceCostResponseData"; import { IInsureRequestData } from "@spt-aki/models/eft/insurance/IInsureRequestData"; import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; -import { ISystemData, Insurance } from "@spt-aki/models/eft/profile/IAkiProfile"; +import { Insurance, ISystemData } from "@spt-aki/models/eft/profile/IAkiProfile"; import { IProcessBuyTradeRequestData } from "@spt-aki/models/eft/trade/IProcessBuyTradeRequestData"; import { ConfigTypes } from "@spt-aki/models/enums/ConfigTypes"; import { MessageType } from "@spt-aki/models/enums/MessageType"; @@ -24,9 +24,9 @@ import { SaveServer } from "@spt-aki/servers/SaveServer"; import { InsuranceService } from "@spt-aki/services/InsuranceService"; import { MailSendService } from "@spt-aki/services/MailSendService"; import { PaymentService } from "@spt-aki/services/PaymentService"; +import { MathUtil } from "@spt-aki/utils/MathUtil"; import { RandomUtil } from "@spt-aki/utils/RandomUtil"; import { TimeUtil } from "@spt-aki/utils/TimeUtil"; -import { MathUtil } from "@spt-aki/utils/MathUtil"; @injectable() export class InsuranceController @@ -48,7 +48,7 @@ export class InsuranceController @inject("PaymentService") protected paymentService: PaymentService, @inject("InsuranceService") protected insuranceService: InsuranceService, @inject("MailSendService") protected mailSendService: MailSendService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.insuranceConfig = this.configServer.getConfig(ConfigTypes.INSURANCE); @@ -58,7 +58,7 @@ export class InsuranceController * Process insurance items of all profiles prior to being given back to the player through the mail service. * * @returns void - */ + */ public processReturn(): void { // Process each installed profile. @@ -72,7 +72,7 @@ export class InsuranceController * Process insurance items of a single profile prior to being given back to the player through the mail service. * * @returns void - */ + */ public processReturnByProfile(sessionID: string): void { // Filter out items that don't need to be processed yet. @@ -117,7 +117,11 @@ export class InsuranceController */ protected processInsuredItems(insuranceDetails: Insurance[], sessionID: string): void { - this.logger.debug(`Processing ${insuranceDetails.length} insurance packages, which includes a total of ${this.countAllInsuranceItems(insuranceDetails)} items, in profile ${sessionID}`); + this.logger.debug( + `Processing ${insuranceDetails.length} insurance packages, which includes a total of ${ + this.countAllInsuranceItems(insuranceDetails) + } items, in profile ${sessionID}`, + ); // Iterate over each of the insurance packages. for (const insured of insuranceDetails) @@ -146,7 +150,7 @@ export class InsuranceController */ protected countAllInsuranceItems(insurance: Insurance[]): number { - return this.mathUtil.arraySum(insurance.map(ins => ins.items.length)); + return this.mathUtil.arraySum(insurance.map((ins) => ins.items.length)); } /** @@ -159,13 +163,15 @@ export class InsuranceController protected removeInsurancePackageFromProfile(sessionID: string, packageInfo: ISystemData): void { const profile = this.saveServer.getProfile(sessionID); - profile.insurance = profile.insurance.filter(insurance => + profile.insurance = profile.insurance.filter((insurance) => insurance.messageContent.systemData.date !== packageInfo.date || insurance.messageContent.systemData.time !== packageInfo.time || insurance.messageContent.systemData.location !== packageInfo.location ); - this.logger.debug(`Removed insurance package with date: ${packageInfo.date}, time: ${packageInfo.time}, and location: ${packageInfo.location} from profile ${sessionID}. Remaining packages: ${profile.insurance.length}`); + this.logger.debug( + `Removed insurance package with date: ${packageInfo.date}, time: ${packageInfo.time}, and location: ${packageInfo.location} from profile ${sessionID}. Remaining packages: ${profile.insurance.length}`, + ); } /** @@ -184,7 +190,9 @@ export class InsuranceController const parentAttachmentsMap = this.populateParentAttachmentsMap(insured, itemsMap); // Check to see if any regular items are present. - const hasRegularItems = Array.from(itemsMap.values()).some(item => !this.itemHelper.isAttachmentAttached(item)); + const hasRegularItems = Array.from(itemsMap.values()).some((item) => + !this.itemHelper.isAttachmentAttached(item) + ); // Process all items that are not attached, attachments. Those are handled separately, by value. if (hasRegularItems) @@ -238,12 +246,14 @@ export class InsuranceController for (const insuredItem of insured.items) { // Use the parent ID from the item to get the parent item. - const parentItem = insured.items.find(item => item._id === insuredItem.parentId); + const parentItem = insured.items.find((item) => item._id === insuredItem.parentId); // The parent (not the hideout) could not be found. Skip and warn. if (!parentItem && insuredItem.parentId !== this.fetchHideoutItemParent(insured.items)) { - this.logger.warning(`Could not find parent for insured item - ID: ${insuredItem._id}, Template: ${insuredItem._tpl}, Parent ID: ${insuredItem.parentId}`); + this.logger.warning( + `Could not find parent for insured item - ID: ${insuredItem._id}, Template: ${insuredItem._tpl}, Parent ID: ${insuredItem.parentId}`, + ); continue; } @@ -261,7 +271,9 @@ export class InsuranceController if (!mainParent) { // Odd. The parent couldn't be found. Skip this attachment and warn. - this.logger.warning(`Could not find main-parent for insured attachment - ID: ${insuredItem._id}, Template: ${insuredItem._tpl}, Parent ID: ${insuredItem.parentId}`); + this.logger.warning( + `Could not find main-parent for insured attachment - ID: ${insuredItem._id}, Template: ${insuredItem._tpl}, Parent ID: ${insuredItem.parentId}`, + ); continue; } @@ -310,8 +322,10 @@ export class InsuranceController // Check if the item has any children and mark those for deletion as well, but only if those // children are currently attached attachments. - const directChildren = insured.items.filter(item => item.parentId === insuredItem._id); - const allChildrenAreAttachments = directChildren.every(child => this.itemHelper.isAttachmentAttached(child)); + const directChildren = insured.items.filter((item) => item.parentId === insuredItem._id); + const allChildrenAreAttachments = directChildren.every((child) => + this.itemHelper.isAttachmentAttached(child) + ); if (allChildrenAreAttachments) { for (const item of itemAndChildren) @@ -331,9 +345,14 @@ export class InsuranceController * @param traderId The trader ID from the Insurance object. * @param toDelete A Set object to keep track of items marked for deletion. */ - protected processAttachments(mainParentToAttachmentsMap: Map, itemsMap: Map, traderId: string, toDelete: Set): void + protected processAttachments( + mainParentToAttachmentsMap: Map, + itemsMap: Map, + traderId: string, + toDelete: Set, + ): void { - for (const [ parentId, attachmentItems ] of mainParentToAttachmentsMap) + for (const [parentId, attachmentItems] of mainParentToAttachmentsMap) { // Log the parent item's name. const parentItem = itemsMap.get(parentId); @@ -375,10 +394,10 @@ export class InsuranceController */ protected sortAttachmentsByPrice(attachments: Item[]): EnrichedItem[] { - return attachments.map(item => ({ + return attachments.map((item) => ({ ...item, name: this.itemHelper.getItemName(item._tpl), - maxPrice: this.itemHelper.getItemMaxPrice(item._tpl) + maxPrice: this.itemHelper.getItemMaxPrice(item._tpl), })).sort((a, b) => b.maxPrice - a.maxPrice); } @@ -389,7 +408,7 @@ export class InsuranceController */ protected logAttachmentsDetails(attachments: EnrichedItem[]): void { - for ( const attachment of attachments) + for (const attachment of attachments) { this.logger.debug(`Child Item - Name: ${attachment.name}, Max Price: ${attachment.maxPrice}`); } @@ -404,7 +423,7 @@ export class InsuranceController */ protected countSuccessfulRolls(attachments: Item[], traderId: string): number { - const rolls = Array.from({ length: attachments.length }, () => this.rollForDelete(traderId)); + const rolls = Array.from({length: attachments.length}, () => this.rollForDelete(traderId)); return rolls.filter(Boolean).length; } @@ -415,16 +434,20 @@ export class InsuranceController * @param successfulRolls The number of successful rolls. * @param toDelete The array that accumulates the IDs of the items to be deleted. */ - protected attachmentDeletionByValue(attachments: EnrichedItem[], successfulRolls: number, toDelete: Set): void + protected attachmentDeletionByValue( + attachments: EnrichedItem[], + successfulRolls: number, + toDelete: Set, + ): void { - const valuableToDelete = attachments.slice(0, successfulRolls).map(({ _id }) => _id); + const valuableToDelete = attachments.slice(0, successfulRolls).map(({_id}) => _id); for (const attachmentsId of valuableToDelete) { - const valuableChild = attachments.find(({ _id }) => _id === attachmentsId); + const valuableChild = attachments.find(({_id}) => _id === attachmentsId); if (valuableChild) { - const { name, maxPrice } = valuableChild; + const {name, maxPrice} = valuableChild; this.logger.debug(`Marked for removal - Child Item: ${name}, Max Price: ${maxPrice}`); toDelete.add(attachmentsId); } @@ -440,7 +463,7 @@ export class InsuranceController */ protected removeItemsFromInsurance(insured: Insurance, toDelete: Set): void { - insured.items = insured.items.filter(item => !toDelete.has(item._id)); + insured.items = insured.items.filter((item) => !toDelete.has(item._id)); } /** @@ -457,7 +480,7 @@ export class InsuranceController for (const item of insured.items) { // Check if the item's parent exists in the insured items list. - const parentExists = insured.items.some(parentItem => parentItem._id === item.parentId); + const parentExists = insured.items.some((parentItem) => parentItem._id === item.parentId); // If the parent does not exist and the item is not already a 'hideout' item, adopt the orphaned item. if (!parentExists && item.parentId !== hideoutParentId && item.slotId !== "hideout") @@ -478,7 +501,7 @@ export class InsuranceController */ protected fetchHideoutItemParent(items: Item[]): string { - const hideoutItem = items.find(item => item.slotId === "hideout"); + const hideoutItem = items.find((item) => item.slotId === "hideout"); const hideoutParentId = hideoutItem ? hideoutItem?.parentId : ""; if (hideoutParentId === "") @@ -502,7 +525,8 @@ export class InsuranceController // successfully "failed" to return anything and an appropriate message should be sent to the player. if (insurance.items.length === 0) { - const insuranceFailedTemplates = this.databaseServer.getTables().traders[insurance.traderId].dialogue.insuranceFailed; + const insuranceFailedTemplates = + this.databaseServer.getTables().traders[insurance.traderId].dialogue.insuranceFailed; insurance.messageContent.templateId = this.randomUtil.getArrayValue(insuranceFailedTemplates); } @@ -514,7 +538,7 @@ export class InsuranceController insurance.messageContent.templateId, insurance.items, insurance.messageContent.maxStorageTime, - insurance.messageContent.systemData + insurance.messageContent.systemData, ); } @@ -544,7 +568,9 @@ export class InsuranceController // Log the roll with as much detail as possible. const itemName = insuredItem ? ` for "${this.itemHelper.getItemName(insuredItem._tpl)}"` : ""; const status = roll ? "Delete" : "Keep"; - this.logger.debug(`Rolling deletion${itemName} with ${trader} - Return ${traderReturnChance}% - Roll: ${returnChance} - Status: ${status}`); + this.logger.debug( + `Rolling deletion${itemName} with ${trader} - Return ${traderReturnChance}% - Roll: ${returnChance} - Status: ${status}`, + ); return roll; } @@ -575,21 +601,18 @@ export class InsuranceController { itemsToPay.push({ id: inventoryItemsHash[key]._id, - count: Math.round(this.insuranceService.getPremium(pmcData, inventoryItemsHash[key], body.tid)) + count: Math.round(this.insuranceService.getPremium(pmcData, inventoryItemsHash[key], body.tid)), }); } const options: IProcessBuyTradeRequestData = { - // eslint-disable-next-line @typescript-eslint/naming-convention scheme_items: itemsToPay, tid: body.tid, Action: "", type: "", - // eslint-disable-next-line @typescript-eslint/naming-convention item_id: "", count: 0, - // eslint-disable-next-line @typescript-eslint/naming-convention - scheme_id: 0 + scheme_id: 0, }; // pay for the item insurance @@ -604,7 +627,7 @@ export class InsuranceController { pmcData.InsuredItems.push({ tid: body.tid, - itemId: inventoryItemsHash[key]._id + itemId: inventoryItemsHash[key]._id, }); } @@ -645,7 +668,9 @@ export class InsuranceController this.logger.debug(`Item with id: ${itemId} missing from player inventory, skipping`); continue; } - items[inventoryItemsHash[itemId]._tpl] = Math.round(this.insuranceService.getPremium(pmcData, inventoryItemsHash[itemId], trader)); + items[inventoryItemsHash[itemId]._tpl] = Math.round( + this.insuranceService.getPremium(pmcData, inventoryItemsHash[itemId], trader), + ); } output[trader] = items; diff --git a/project/src/controllers/InventoryController.ts b/project/src/controllers/InventoryController.ts index 23f5a5b4..084787b1 100644 --- a/project/src/controllers/InventoryController.ts +++ b/project/src/controllers/InventoryController.ts @@ -62,21 +62,25 @@ export class InventoryController @inject("LocalisationService") protected localisationService: LocalisationService, @inject("LootGenerator") protected lootGenerator: LootGenerator, @inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder, - @inject("HttpResponseUtil") protected httpResponseUtil: HttpResponseUtil + @inject("HttpResponseUtil") protected httpResponseUtil: HttpResponseUtil, ) {} /** - * Move Item - * change location of item with parentId and slotId - * transfers items from one profile to another if fromOwner/toOwner is set in the body. - * otherwise, move is contained within the same profile_f. + * Move Item + * change location of item with parentId and slotId + * transfers items from one profile to another if fromOwner/toOwner is set in the body. + * otherwise, move is contained within the same profile_f. * @param pmcData Profile * @param moveRequest Move request data * @param sessionID Session id * @returns IItemEventRouterResponse */ - public moveItem(pmcData: IPmcData, moveRequest: IInventoryMoveRequestData, sessionID: string): IItemEventRouterResponse + public moveItem( + pmcData: IPmcData, + moveRequest: IInventoryMoveRequestData, + sessionID: string, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionID); @@ -89,14 +93,14 @@ export class InventoryController const ownerInventoryItems = this.inventoryHelper.getOwnerInventoryItems(moveRequest, sessionID); if (ownerInventoryItems.sameInventory) { - // Dont move items from trader to profile, this can happen when editing a traders preset weapons + // Don't move items from trader to profile, this can happen when editing a traders preset weapons if (moveRequest.fromOwner?.type === "Trader" && !ownerInventoryItems.isMail) { return this.getTraderExploitErrorResponse(output); } // Check for item in inventory before allowing internal transfer - const originalItemLocation = ownerInventoryItems.from.find(x => x._id === moveRequest.item); + const originalItemLocation = ownerInventoryItems.from.find((x) => x._id === moveRequest.item); if (!originalItemLocation) { // Internal item move but item never existed, possible dupe glitch @@ -123,14 +127,23 @@ export class InventoryController */ protected getTraderExploitErrorResponse(output: IItemEventRouterResponse): IItemEventRouterResponse { - return this.httpResponseUtil.appendErrorToOutput(output, this.localisationService.getText("inventory-edit_trader_item"), 228); + return this.httpResponseUtil.appendErrorToOutput( + output, + this.localisationService.getText("inventory-edit_trader_item"), + 228, + ); } /** - * Remove Item from Profile - * Deep tree item deletion, also removes items from insurance list - */ - public removeItem(pmcData: IPmcData, itemId: string, sessionID: string, output: IItemEventRouterResponse = undefined): IItemEventRouterResponse + * Remove Item from Profile + * Deep tree item deletion, also removes items from insurance list + */ + public removeItem( + pmcData: IPmcData, + itemId: string, + sessionID: string, + output: IItemEventRouterResponse = undefined, + ): IItemEventRouterResponse { return this.inventoryHelper.removeItem(pmcData, itemId, sessionID, output); } @@ -140,29 +153,46 @@ export class InventoryController * Implements functionality "Discard" from Main menu (Stash etc.) * Removes item from PMC Profile */ - public discardItem(pmcData: IPmcData, body: IInventoryRemoveRequestData, sessionID: string): IItemEventRouterResponse + public discardItem( + pmcData: IPmcData, + body: IInventoryRemoveRequestData, + sessionID: string, + ): IItemEventRouterResponse { if (body.fromOwner?.type === "Mail") { - return this.inventoryHelper.removeItemAndChildrenFromMailRewards(sessionID, body, this.eventOutputHolder.getOutput(sessionID)); + return this.inventoryHelper.removeItemAndChildrenFromMailRewards( + sessionID, + body, + this.eventOutputHolder.getOutput(sessionID), + ); } - - const profileToRemoveItemFrom = (!body.fromOwner || body.fromOwner.id === pmcData._id) - ? pmcData - : this.profileHelper.getFullProfile(sessionID).characters.scav; - return this.inventoryHelper.removeItem(profileToRemoveItemFrom, body.item, sessionID, this.eventOutputHolder.getOutput(sessionID)); + const profileToRemoveItemFrom = (!body.fromOwner || body.fromOwner.id === pmcData._id) ? + pmcData : + this.profileHelper.getFullProfile(sessionID).characters.scav; + + return this.inventoryHelper.removeItem( + profileToRemoveItemFrom, + body.item, + sessionID, + this.eventOutputHolder.getOutput(sessionID), + ); } /** * Split Item - * spliting 1 stack into 2 + * splitting 1 stack into 2 * @param pmcData Player profile (unused, getOwnerInventoryItems() gets profile) * @param request Split request * @param sessionID Session/player id * @returns IItemEventRouterResponse */ - public splitItem(pmcData: IPmcData, request: IInventorySplitRequestData, sessionID: string): IItemEventRouterResponse + public splitItem( + pmcData: IPmcData, + request: IInventorySplitRequestData, + sessionID: string, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionID); @@ -172,15 +202,16 @@ export class InventoryController // Handle cartridge edge-case if (!request.container.location && request.container.container === "cartridges") { - const matchingItems = inventoryItems.to.filter(x => x.parentId === request.container.id); + const matchingItems = inventoryItems.to.filter((x) => x.parentId === request.container.id); request.container.location = matchingItems.length; // Wrong location for first cartridge } - // The item being merged has three possible sources: pmc, scav or mail, getOwnerInventoryItems() handles getting correct one - const itemToSplit = inventoryItems.from.find(x => x._id === request.splitItem); + // The item being merged has three possible sources: pmc, scav or mail, getOwnerInventoryItems() handles getting + // correct one. + const itemToSplit = inventoryItems.from.find((x) => x._id === request.splitItem); if (!itemToSplit) { - const errorMessage = (`Unable to split stack as source item: ${request.splitItem} cannot be found`); + const errorMessage = `Unable to split stack as source item: ${request.splitItem} cannot be found`; this.logger.error(errorMessage); return this.httpResponseUtil.appendErrorToOutput(output, errorMessage); @@ -197,7 +228,7 @@ export class InventoryController output.profileChanges[sessionID].items.new.push({ _id: request.newItem, _tpl: itemToSplit._tpl, - upd: updatedUpd + upd: updatedUpd, }); // Update player inventory @@ -207,7 +238,7 @@ export class InventoryController parentId: request.container.id, slotId: request.container.container, location: request.container.location, - upd: updatedUpd + upd: updatedUpd, }); return output; @@ -229,20 +260,20 @@ export class InventoryController const inventoryItems = this.inventoryHelper.getOwnerInventoryItems(body, sessionID); // Get source item (can be from player or trader or mail) - const sourceItem = inventoryItems.from.find(x => x._id === body.item); + const sourceItem = inventoryItems.from.find((x) => x._id === body.item); if (!sourceItem) { - const errorMessage = (`Unable to merge stacks as source item: ${body.with} cannot be found`); + const errorMessage = `Unable to merge stacks as source item: ${body.with} cannot be found`; this.logger.error(errorMessage); return this.httpResponseUtil.appendErrorToOutput(output, errorMessage); } // Get item being merged into - const destinationItem = inventoryItems.to.find(x => x._id === body.with); + const destinationItem = inventoryItems.to.find((x) => x._id === body.with); if (!destinationItem) { - const errorMessage = (`Unable to merge stacks as destination item: ${body.with} cannot be found`); + const errorMessage = `Unable to merge stacks as destination item: ${body.with} cannot be found`; this.logger.error(errorMessage); return this.httpResponseUtil.appendErrorToOutput(output, errorMessage); @@ -250,29 +281,29 @@ export class InventoryController if (!(destinationItem.upd?.StackObjectsCount)) { - // No stackcount on destination, add one - destinationItem.upd = { StackObjectsCount: 1 }; + // No stack count on destination, add one + destinationItem.upd = {StackObjectsCount: 1}; } if (!sourceItem.upd) { sourceItem.upd = { - StackObjectsCount: 1 + StackObjectsCount: 1, }; } else if (!sourceItem.upd.StackObjectsCount) { - // Items pulled out of raid can have no stackcount if the stack should be 1 + // Items pulled out of raid can have no stack count if the stack should be 1 sourceItem.upd.StackObjectsCount = 1; } - destinationItem.upd.StackObjectsCount += sourceItem.upd.StackObjectsCount; // Add source stackcount to destination - output.profileChanges[sessionID].items.del.push({ _id: sourceItem._id }); // Inform client source item being deleted + destinationItem.upd.StackObjectsCount += sourceItem.upd.StackObjectsCount; // Add source stack count to destination + output.profileChanges[sessionID].items.del.push({_id: sourceItem._id}); // Inform client source item being deleted - const indexOfItemToRemove = inventoryItems.from.findIndex(x => x._id === sourceItem._id); + const indexOfItemToRemove = inventoryItems.from.findIndex((x) => x._id === sourceItem._id); if (indexOfItemToRemove === -1) { - const errorMessage = (`Unable to find item: ${sourceItem._id} to remove from sender inventory`); + const errorMessage = `Unable to find item: ${sourceItem._id} to remove from sender inventory`; this.logger.error(errorMessage); return this.httpResponseUtil.appendErrorToOutput(output, errorMessage); @@ -283,8 +314,8 @@ export class InventoryController } /** - * TODO: Adds no data to output to send to client, is this by design? - * TODO: should make use of getOwnerInventoryItems(), stack being transferred may not always be on pmc + * // TODO: Adds no data to output to send to client, is this by design? + * // TODO: should make use of getOwnerInventoryItems(), stack being transferred may not always be on pmc * Transfer items from one stack into another while keeping original stack * Used to take items from scav inventory into stash or to insert ammo into mags (shotgun ones) and reloading weapon by clicking "Reload" * @param pmcData Player profile @@ -292,7 +323,11 @@ export class InventoryController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public transferItem(pmcData: IPmcData, body: IInventoryTransferRequestData, sessionID: string): IItemEventRouterResponse + public transferItem( + pmcData: IPmcData, + body: IInventoryTransferRequestData, + sessionID: string, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionID); @@ -314,7 +349,7 @@ export class InventoryController if (sourceItem !== null && destinationItem !== null) { // Both items found, exit loop - break; + break; } } @@ -359,7 +394,7 @@ export class InventoryController } else { - Object.assign(destinationItem, { upd: { StackObjectsCount: 1 } }); + Object.assign(destinationItem, {upd: {StackObjectsCount: 1}}); } destinationItem.upd.StackObjectsCount = destinationStackCount + body.count; @@ -368,28 +403,28 @@ export class InventoryController } /** - * Swap Item - * its used for "reload" if you have weapon in hands and magazine is somewhere else in rig or backpack in equipment - * Also used to swap items using quick selection on character screen - */ + * Swap Item + * its used for "reload" if you have weapon in hands and magazine is somewhere else in rig or backpack in equipment + * Also used to swap items using quick selection on character screen + */ public swapItem(pmcData: IPmcData, request: IInventorySwapRequestData, sessionID: string): IItemEventRouterResponse { - const itemOne = pmcData.Inventory.items.find(x => x._id === request.item); + const itemOne = pmcData.Inventory.items.find((x) => x._id === request.item); if (!itemOne) { this.logger.error(`Unable to find item: ${request.item} to swap positions with: ${request.item2}`); } - const itemTwo = pmcData.Inventory.items.find(x => x._id === request.item2); + const itemTwo = pmcData.Inventory.items.find((x) => x._id === request.item2); if (!itemTwo) { this.logger.error(`Unable to find item: ${request.item2} to swap positions with: ${request.item}`); } - // to.id is the parentid + // to.id is the parentId itemOne.parentId = request.to.id; - - // to.container is the slotid + + // to.container is the slotId itemOne.slotId = request.to.container; // Request object has location data, add it in, otherwise remove existing location from object @@ -423,9 +458,11 @@ export class InventoryController public foldItem(pmcData: IPmcData, body: IInventoryFoldRequestData, sessionID: string): IItemEventRouterResponse { // Fix for folding weapons while on they're in the Scav inventory - if (body.fromOwner - && body.fromOwner.type === "Profile" - && body.fromOwner.id !== pmcData._id) + if ( + body.fromOwner && + body.fromOwner.type === "Profile" && + body.fromOwner.id !== pmcData._id + ) { pmcData = this.profileHelper.getScavProfile(sessionID); } @@ -434,19 +471,19 @@ export class InventoryController { if (item._id && item._id === body.item) { - item.upd.Foldable = { Folded: body.value }; + item.upd.Foldable = {Folded: body.value}; return this.eventOutputHolder.getOutput(sessionID); } } return { warnings: [], - profileChanges: {} + profileChanges: {}, }; } /** - * Toggles "Toggleable" items like night vision goggles and face shields. + * Toggles "toggleable" items like night vision goggles and face shields. * @param pmcData player profile * @param body Toggle request * @param sessionID Session id @@ -460,27 +497,31 @@ export class InventoryController pmcData = this.profileHelper.getScavProfile(sessionID); } - const itemToToggle = pmcData.Inventory.items.find(x => x._id === body.item); + const itemToToggle = pmcData.Inventory.items.find((x) => x._id === body.item); if (itemToToggle) { if (!itemToToggle.upd) { - this.logger.warning(this.localisationService.getText("inventory-item_to_toggle_missing_upd", itemToToggle._id)); + this.logger.warning( + this.localisationService.getText("inventory-item_to_toggle_missing_upd", itemToToggle._id), + ); itemToToggle.upd = {}; } - itemToToggle.upd.Togglable = { On: body.value }; + itemToToggle.upd.Togglable = {On: body.value}; return this.eventOutputHolder.getOutput(sessionID); } else { - this.logger.warning(this.localisationService.getText("inventory-unable_to_toggle_item_not_found", body.item)); + this.logger.warning( + this.localisationService.getText("inventory-unable_to_toggle_item_not_found", body.item), + ); } return { warnings: [], - profileChanges: {} + profileChanges: {}, }; } @@ -499,11 +540,11 @@ export class InventoryController { if ("upd" in item) { - item.upd.Tag = { Color: body.TagColor, Name: body.TagName }; + item.upd.Tag = {Color: body.TagColor, Name: body.TagName}; } else { - item.upd = { Tag: { Color: body.TagColor, Name: body.TagName } }; + item.upd = {Tag: {Color: body.TagColor, Name: body.TagName}}; } return this.eventOutputHolder.getOutput(sessionID); @@ -512,18 +553,22 @@ export class InventoryController return { warnings: [], - profileChanges: {} + profileChanges: {}, }; } /** * Bind an inventory item to the quick access menu at bottom of player screen * @param pmcData Player profile - * @param bindRequest Reqeust object + * @param bindRequest Request object * @param sessionID Session id * @returns IItemEventRouterResponse */ - public bindItem(pmcData: IPmcData, bindRequest: IInventoryBindRequestData, sessionID: string): IItemEventRouterResponse + public bindItem( + pmcData: IPmcData, + bindRequest: IInventoryBindRequestData, + sessionID: string, + ): IItemEventRouterResponse { for (const index in pmcData.Inventory.fastPanel) { @@ -538,7 +583,6 @@ export class InventoryController return this.eventOutputHolder.getOutput(sessionID); } - /** * Handles examining an item * @param pmcData player profile @@ -546,7 +590,11 @@ export class InventoryController * @param sessionID session id * @returns response */ - public examineItem(pmcData: IPmcData, body: IInventoryExamineRequestData, sessionID: string): IItemEventRouterResponse + public examineItem( + pmcData: IPmcData, + body: IInventoryExamineRequestData, + sessionID: string, + ): IItemEventRouterResponse { let itemId = ""; if ("fromOwner" in body) @@ -559,7 +607,7 @@ export class InventoryController { this.logger.error(this.localisationService.getText("inventory-examine_item_does_not_exist", body.item)); } - + // get hideout item if (body.fromOwner.type === "HideoutProduction") { @@ -606,9 +654,9 @@ export class InventoryController } /** - * Get the tplid of an item from the examine request object + * Get the tplId of an item from the examine request object * @param body response request - * @returns tplid + * @returns string */ protected getExaminedItemTpl(body: IInventoryExamineRequestData): string { @@ -618,49 +666,55 @@ export class InventoryController } else if (body.fromOwner.id === Traders.FENCE) { - // get tpl from fence assorts - return this.fenceService.getRawFenceAssorts().items.find(x => x._id === body.item)._tpl; + // Get tpl from fence assorts + return this.fenceService.getRawFenceAssorts().items.find((x) => x._id === body.item)._tpl; } - else if (body.fromOwner.type === "Trader") // not fence + else if (body.fromOwner.type === "Trader") { - // get tpl from trader assort - return this.databaseServer.getTables().traders[body.fromOwner.id].assort.items.find(item => item._id === body.item)._tpl; + // Not fence + // Get tpl from trader assort + return this.databaseServer.getTables().traders[body.fromOwner.id].assort.items.find((item) => + item._id === body.item + )._tpl; } else if (body.fromOwner.type === "RagFair") { - // try to get tplid from items.json first + // try to get tplId from items.json first const item = this.databaseServer.getTables().templates.items[body.item]; if (item) { return item._id; } - // try alternate way of getting offer if first approach fails + // Try alternate way of getting offer if first approach fails let offer = this.ragfairOfferService.getOfferByOfferId(body.item); if (!offer) { offer = this.ragfairOfferService.getOfferByOfferId(body.fromOwner.id); } - // try find examine item inside offer items array - const matchingItem = offer.items.find(x => x._id === body.item); + // Try find examine item inside offer items array + const matchingItem = offer.items.find((x) => x._id === body.item); if (matchingItem) { return matchingItem._tpl; - } + } - // unable to find item in database or ragfair + // Unable to find item in database or ragfair throw new Error(this.localisationService.getText("inventory-unable_to_find_item", body.item)); } } - public readEncyclopedia(pmcData: IPmcData, body: IInventoryReadEncyclopediaRequestData, sessionID: string): IItemEventRouterResponse + public readEncyclopedia( + pmcData: IPmcData, + body: IInventoryReadEncyclopediaRequestData, + sessionID: string, + ): IItemEventRouterResponse { for (const id of body.ids) { pmcData.Encyclopedia[id] = true; } - return this.eventOutputHolder.getOutput(sessionID); } @@ -672,15 +726,20 @@ export class InventoryController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public sortInventory(pmcData: IPmcData, request: IInventorySortRequestData, sessionID: string): IItemEventRouterResponse + public sortInventory( + pmcData: IPmcData, + request: IInventorySortRequestData, + sessionID: string, + ): IItemEventRouterResponse { - for (const change of request.changedItems) { - const inventoryItem = pmcData.Inventory.items.find(x => x._id === change._id); + const inventoryItem = pmcData.Inventory.items.find((x) => x._id === change._id); if (!inventoryItem) { - this.logger.error(`Unable to find inventory item: ${change._id} to auto-sort, YOU MUST RELOAD YOUR GAME`); + this.logger.error( + `Unable to find inventory item: ${change._id} to auto-sort, YOU MUST RELOAD YOUR GAME`, + ); continue; } @@ -707,13 +766,17 @@ export class InventoryController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public createMapMarker(pmcData: IPmcData, request: IInventoryCreateMarkerRequestData, sessionID: string): IItemEventRouterResponse + public createMapMarker( + pmcData: IPmcData, + request: IInventoryCreateMarkerRequestData, + sessionID: string, + ): IItemEventRouterResponse { // Get map from inventory - const mapItem = pmcData.Inventory.items.find(i => i._id === request.item); + const mapItem = pmcData.Inventory.items.find((i) => i._id === request.item); // add marker - mapItem.upd.Map = mapItem.upd.Map || { Markers: [] }; + mapItem.upd.Map = mapItem.upd.Map || {Markers: []}; request.mapMarker.Note = this.sanitiseMapMarkerText(request.mapMarker.Note); mapItem.upd.Map.Markers.push(request.mapMarker); @@ -731,10 +794,14 @@ export class InventoryController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public deleteMapMarker(pmcData: IPmcData, request: IInventoryDeleteMarkerRequestData, sessionID: string): IItemEventRouterResponse + public deleteMapMarker( + pmcData: IPmcData, + request: IInventoryDeleteMarkerRequestData, + sessionID: string, + ): IItemEventRouterResponse { // Get map from inventory - const mapItem = pmcData.Inventory.items.find(i => i._id === request.item); + const mapItem = pmcData.Inventory.items.find((i) => i._id === request.item); // remove marker const markers = mapItem.upd.Map.Markers.filter((marker) => @@ -756,13 +823,17 @@ export class InventoryController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public editMapMarker(pmcData: IPmcData, request: IInventoryEditMarkerRequestData, sessionID: string): IItemEventRouterResponse + public editMapMarker( + pmcData: IPmcData, + request: IInventoryEditMarkerRequestData, + sessionID: string, + ): IItemEventRouterResponse { // Get map from inventory - const mapItem = pmcData.Inventory.items.find(i => i._id === request.item); + const mapItem = pmcData.Inventory.items.find((i) => i._id === request.item); // edit marker - const indexOfExistingNote = mapItem.upd.Map.Markers.findIndex(m => m.X === request.X && m.Y === request.Y); + const indexOfExistingNote = mapItem.upd.Map.Markers.findIndex((m) => m.X === request.X && m.Y === request.Y); request.mapMarker.Note = this.sanitiseMapMarkerText(request.mapMarker.Note); mapItem.upd.Map.Markers[indexOfExistingNote] = request.mapMarker; @@ -791,15 +862,19 @@ export class InventoryController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public openRandomLootContainer(pmcData: IPmcData, body: IOpenRandomLootContainerRequestData, sessionID: string): IItemEventRouterResponse + public openRandomLootContainer( + pmcData: IPmcData, + body: IOpenRandomLootContainerRequestData, + sessionID: string, + ): IItemEventRouterResponse { - const openedItem = pmcData.Inventory.items.find(x => x._id === body.item); + const openedItem = pmcData.Inventory.items.find((x) => x._id === body.item); const containerDetails = this.itemHelper.getItem(openedItem._tpl); const isSealedWeaponBox = containerDetails[1]._name.includes("event_container_airdrop"); const newItemRequest: IAddItemRequestData = { tid: "RandomLootContainer", - items: [] + items: [], }; let foundInRaid = false; @@ -829,4 +904,4 @@ export class InventoryController return output; } -} \ No newline at end of file +} diff --git a/project/src/controllers/LauncherController.ts b/project/src/controllers/LauncherController.ts index 6ead15e3..748135ab 100644 --- a/project/src/controllers/LauncherController.ts +++ b/project/src/controllers/LauncherController.ts @@ -30,7 +30,7 @@ export class LauncherController @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("PreAkiModLoader") protected preAkiModLoader: PreAkiModLoader, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.coreConfig = this.configServer.getConfig(ConfigTypes.CORE); @@ -42,30 +42,26 @@ export class LauncherController backendUrl: this.httpServerHelper.getBackendUrl(), name: this.coreConfig.serverName, editions: Object.keys(this.databaseServer.getTables().templates.profiles), - profileDescriptions: this.getProfileDescriptions() + profileDescriptions: this.getProfileDescriptions(), }; } /** - * Get descriptive text for each of the profile edtions a player can choose - * @returns + * Get descriptive text for each of the profile editions a player can choose + * @returns */ protected getProfileDescriptions(): Record { return { + /* eslint-disable @typescript-eslint/naming-convention */ Standard: this.localisationService.getText("launcher-profile_standard"), - // eslint-disable-next-line @typescript-eslint/naming-convention "Left Behind": this.localisationService.getText("launcher-profile_leftbehind"), - // eslint-disable-next-line @typescript-eslint/naming-convention "Prepare To Escape": this.localisationService.getText("launcher-profile_preparetoescape"), - // eslint-disable-next-line @typescript-eslint/naming-convention "Edge Of Darkness": this.localisationService.getText("launcher-edgeofdarkness"), - // eslint-disable-next-line @typescript-eslint/naming-convention "SPT Easy start": this.localisationService.getText("launcher-profile_spteasystart"), - // eslint-disable-next-line @typescript-eslint/naming-convention "SPT Zero to hero": this.localisationService.getText("launcher-profile_sptzerotohero"), - // eslint-disable-next-line @typescript-eslint/naming-convention - "SPT Developer": this.localisationService.getText("launcher-profile_sptdeveloper") + "SPT Developer": this.localisationService.getText("launcher-profile_sptdeveloper"), + /* eslint-enable @typescript-eslint/naming-convention */ }; } @@ -115,12 +111,13 @@ export class LauncherController username: info.username, password: info.password, wipe: true, - edition: info.edition + edition: info.edition, }; this.saveServer.createProfile(newProfileDetails); this.saveServer.loadProfile(sessionID); this.saveServer.saveProfile(sessionID); + return sessionID; } diff --git a/project/src/controllers/LocationController.ts b/project/src/controllers/LocationController.ts index c46e6a43..df0c5671 100644 --- a/project/src/controllers/LocationController.ts +++ b/project/src/controllers/LocationController.ts @@ -41,7 +41,7 @@ export class LocationController @inject("LootGenerator") protected lootGenerator: LootGenerator, @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("TimeUtil") protected timeUtil: TimeUtil, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.airdropConfig = this.configServer.getConfig(ConfigTypes.AIRDROP); @@ -88,17 +88,23 @@ export class LocationController // Create containers and add loot to them const staticLoot = this.locationGenerator.generateStaticContainers(location.base, staticAmmoDist); output.Loot.push(...staticLoot); - - // Add dyanmic loot to output loot + + // Add dynamic loot to output loot const dynamicLootDist: ILooseLoot = this.jsonUtil.clone(location.looseLoot); - const dynamicSpawnPoints: SpawnpointTemplate[] = this.locationGenerator.generateDynamicLoot(dynamicLootDist, staticAmmoDist, name); + const dynamicSpawnPoints: SpawnpointTemplate[] = this.locationGenerator.generateDynamicLoot( + dynamicLootDist, + staticAmmoDist, + name, + ); for (const spawnPoint of dynamicSpawnPoints) { output.Loot.push(spawnPoint); } // Done generating, log results - this.logger.success(this.localisationService.getText("location-dynamic_items_spawned_success", dynamicSpawnPoints.length)); + this.logger.success( + this.localisationService.getText("location-dynamic_items_spawned_success", dynamicSpawnPoints.length), + ); this.logger.success(this.localisationService.getText("location-generated_success", name)); return output; @@ -110,7 +116,6 @@ export class LocationController * @param sessionId Players Id * @returns ILocationsGenerateAllResponse */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public generateAll(sessionId: string): ILocationsGenerateAllResponse { const locationsFromDb = this.databaseServer.getTables().locations; @@ -130,15 +135,15 @@ export class LocationController locations[mapBase._Id] = mapBase; } - return { + return { locations: locations, - paths: locationsFromDb.base.paths + paths: locationsFromDb.base.paths, }; } /** * Handle client/location/getAirdropLoot - * Get loot for an airdop container + * Get loot for an airdrop container * Generates it randomly based on config/airdrop.json values * @returns Array of LootItem objects */ @@ -174,7 +179,9 @@ export class LocationController let lootSettingsByType = this.airdropConfig.loot[airdropType]; if (!lootSettingsByType) { - this.logger.error(this.localisationService.getText("location-unable_to_find_airdrop_drop_config_of_type", airdropType)); + this.logger.error( + this.localisationService.getText("location-unable_to_find_airdrop_drop_config_of_type", airdropType), + ); lootSettingsByType = this.airdropConfig.loot[AirdropTypeEnum.MIXED]; } @@ -187,7 +194,7 @@ export class LocationController itemLimits: lootSettingsByType.itemLimits, itemStackLimits: lootSettingsByType.itemStackLimits, armorLevelWhitelist: lootSettingsByType.armorLevelWhitelist, - allowBossItems: lootSettingsByType.allowBossItems + allowBossItems: lootSettingsByType.allowBossItems, }; } -} \ No newline at end of file +} diff --git a/project/src/controllers/MatchController.ts b/project/src/controllers/MatchController.ts index b0135193..0baefa00 100644 --- a/project/src/controllers/MatchController.ts +++ b/project/src/controllers/MatchController.ts @@ -56,7 +56,7 @@ export class MatchController @inject("BotGenerationCacheService") protected botGenerationCacheService: BotGenerationCacheService, @inject("MailSendService") protected mailSendService: MailSendService, @inject("LootGenerator") protected lootGenerator: LootGenerator, - @inject("ApplicationContext") protected applicationContext: ApplicationContext + @inject("ApplicationContext") protected applicationContext: ApplicationContext, ) { this.matchConfig = this.configServer.getConfig(ConfigTypes.MATCH); @@ -99,12 +99,11 @@ export class MatchController } /** Handle match/group/start_game */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public joinMatch(info: IJoinMatchRequestData, sessionId: string): IJoinMatchResult { const output: IJoinMatchResult = { maxPveCountExceeded: false, - profiles: [] + profiles: [], }; // get list of players joining into the match @@ -120,20 +119,18 @@ export class MatchController raidMode: "Online", mode: "deathmatch", shortid: null, - // eslint-disable-next-line @typescript-eslint/naming-convention - additional_info: null + additional_info: null, }); return output; } /** Handle client/match/group/status */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getGroupStatus(info: IGetGroupStatusRequestData): any { return { players: [], - maxPveCountExceeded: false + maxPveCountExceeded: false, }; } @@ -147,15 +144,17 @@ export class MatchController // Store request data for access during bot generation this.applicationContext.addValue(ContextVariableType.RAID_CONFIGURATION, request); - //TODO: add code to strip PMC of equipment now they've started the raid + // TODO: add code to strip PMC of equipment now they've started the raid - // Set pmcs to difficulty set in pre-raid screen if override in bot config isnt enabled + // Set PMCs to difficulty set in pre-raid screen if override in bot config isn't enabled if (!this.pmcConfig.useDifficultyOverride) { - this.pmcConfig.difficulty = this.convertDifficultyDropdownIntoBotDifficulty(request.wavesSettings.botDifficulty); + this.pmcConfig.difficulty = this.convertDifficultyDropdownIntoBotDifficulty( + request.wavesSettings.botDifficulty, + ); } - // Store the profile as-is for later use on the post-raid exp screen + // Store the profile as-is for later use on the post-raid exp screen const currentProfile = this.saveServer.getProfile(sessionID); this.profileSnapshotService.storeProfileSnapshot(sessionID, currentProfile); } @@ -178,7 +177,7 @@ export class MatchController /** Handle client/match/offline/end */ public endOfflineRaid(info: IEndOfflineRaidRequestData, sessionId: string): void - { + { const pmcData: IPmcData = this.profileHelper.getPmcProfile(sessionId); const extractName = info.exitName; @@ -223,7 +222,7 @@ export class MatchController // Generate reward for taking coop extract const loot = this.lootGenerator.createRandomLoot(this.traderConfig.fence.coopExtractGift); const mailableLoot: Item[] = []; - + const parentId = this.hashUtil.generate(); for (const item of loot) { @@ -235,9 +234,9 @@ export class MatchController parentId: parentId, upd: { StackObjectsCount: item.stackCount, - SpawnedInSession: true - } - } + SpawnedInSession: true, + }, + }, ); } @@ -248,7 +247,7 @@ export class MatchController MessageType.MESSAGE_WITH_ITEMS, this.randomUtil.getArrayValue(this.traderConfig.fence.coopExtractGift.messageLocaleIds), mailableLoot, - this.timeUtil.getHoursAsSeconds(this.traderConfig.fence.coopExtractGift.giftExpiryHours) + this.timeUtil.getHoursAsSeconds(this.traderConfig.fence.coopExtractGift.giftExpiryHours), ); } @@ -292,25 +291,27 @@ export class MatchController const fenceId: string = Traders.FENCE; this.updateFenceStandingInProfile(pmcData, fenceId, extractName); - + this.traderHelper.lvlUp(fenceId, pmcData); pmcData.TradersInfo[fenceId].loyaltyLevel = Math.max(pmcData.TradersInfo[fenceId].loyaltyLevel, 1); - this.logger.debug(`Car extract: ${extractName} used, total times taken: ${pmcData.CarExtractCounts[extractName]}`); + this.logger.debug( + `Car extract: ${extractName} used, total times taken: ${pmcData.CarExtractCounts[extractName]}`, + ); } /** * Update players fence trader standing value in profile * @param pmcData Player profile * @param fenceId Id of fence trader - * @param extractName Name of extract used + * @param extractName Name of extract used */ protected updateFenceStandingInProfile(pmcData: IPmcData, fenceId: string, extractName: string): void { let fenceStanding = Number(pmcData.TradersInfo[fenceId].standing); - // Not exact replica of Live behaviour - // Simplified for now, no real reason to do the whole (unconfirmed) extra 0.01 standing per day regeneration mechanic + // Not exact replica of Live behaviour... Simplified for now. No real reason to do the whole (unconfirmed) + // extra 0.01 standing per day regeneration mechanic. const baseGain: number = this.inraidConfig.carExtractBaseStandingGain; const extractCount: number = pmcData.CarExtractCounts[extractName]; @@ -321,4 +322,4 @@ export class MatchController this.logger.debug(`Old vs new fence standing: ${pmcData.TradersInfo[fenceId].standing}, ${newFenceStanding}`); pmcData.TradersInfo[fenceId].standing = newFenceStanding; } -} \ No newline at end of file +} diff --git a/project/src/controllers/NoteController.ts b/project/src/controllers/NoteController.ts index 8b0c37b1..4f6fcc16 100644 --- a/project/src/controllers/NoteController.ts +++ b/project/src/controllers/NoteController.ts @@ -10,15 +10,15 @@ import { EventOutputHolder } from "@spt-aki/routers/EventOutputHolder"; export class NoteController { constructor( - @inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder + @inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder, ) - { } + {} public addNote(pmcData: IPmcData, body: INoteActionData, sessionID: string): IItemEventRouterResponse { const newNote: Note = { Time: body.note.Time, - Text: body.note.Text + Text: body.note.Text, }; pmcData.Notes.Notes.push(newNote); @@ -39,4 +39,4 @@ export class NoteController pmcData.Notes.Notes.splice(body.index, 1); return this.eventOutputHolder.getOutput(sessionID); } -} \ No newline at end of file +} diff --git a/project/src/controllers/NotifierController.ts b/project/src/controllers/NotifierController.ts index ab4d9bdd..60ad5e83 100644 --- a/project/src/controllers/NotifierController.ts +++ b/project/src/controllers/NotifierController.ts @@ -14,7 +14,7 @@ export class NotifierController constructor( @inject("NotifierHelper") protected notifierHelper: NotifierHelper, @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper, - @inject("NotificationService") protected notificationService: NotificationService + @inject("NotificationService") protected notificationService: NotificationService, ) {} @@ -82,11 +82,10 @@ export class NotifierController { return { server: this.httpServerHelper.buildUrl(), - // eslint-disable-next-line @typescript-eslint/naming-convention channel_id: sessionID, url: "", notifierServer: this.getServer(sessionID), - ws: this.notifierHelper.getWebSocketServer(sessionID) + ws: this.notifierHelper.getWebSocketServer(sessionID), }; } } diff --git a/project/src/controllers/PresetBuildController.ts b/project/src/controllers/PresetBuildController.ts index e3f4ca9d..9a42b95f 100644 --- a/project/src/controllers/PresetBuildController.ts +++ b/project/src/controllers/PresetBuildController.ts @@ -23,9 +23,9 @@ export class PresetBuildController @inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("ItemHelper") protected itemHelper: ItemHelper, - @inject("SaveServer") protected saveServer: SaveServer + @inject("SaveServer") protected saveServer: SaveServer, ) - { } + {} /** Handle client/handbook/builds/my/list */ public getUserBuilds(sessionID: string): IUserBuilds @@ -35,21 +35,27 @@ export class PresetBuildController { profile.userbuilds = { equipmentBuilds: [], - weaponBuilds: [] + weaponBuilds: [], }; } // Ensure the secure container in the default presets match what the player has equipped - const defaultEquipmentPresets = this.jsonUtil.clone(this.databaseServer.getTables().templates.defaultEquipmentPresets); - const playerSecureContainer = profile.characters.pmc.Inventory.items?.find(x => x.slotId === "SecuredContainer"); - const firstDefaultItemsSecureContainer = defaultEquipmentPresets[0]?.items?.find(x => x.slotId === "SecuredContainer"); + const defaultEquipmentPresets = this.jsonUtil.clone( + this.databaseServer.getTables().templates.defaultEquipmentPresets, + ); + const playerSecureContainer = profile.characters.pmc.Inventory.items?.find((x) => + x.slotId === "SecuredContainer" + ); + const firstDefaultItemsSecureContainer = defaultEquipmentPresets[0]?.items?.find((x) => + x.slotId === "SecuredContainer" + ); if (playerSecureContainer && playerSecureContainer?._tpl !== firstDefaultItemsSecureContainer?._tpl) { - // Default equipment presets' secure container tpl doesnt match players secure container tpl + // Default equipment presets' secure container tpl doesn't match players secure container tpl for (const defaultPreset of defaultEquipmentPresets) { // Find presets secure container - const secureContainer = defaultPreset.items.find(x => x.slotId === "SecuredContainer"); + const secureContainer = defaultPreset.items.find((x) => x.slotId === "SecuredContainer"); if (secureContainer) { secureContainer._tpl = playerSecureContainer._tpl; @@ -65,9 +71,13 @@ export class PresetBuildController } /** Handle SaveWeaponBuild event */ - public saveWeaponBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionId: string): IItemEventRouterResponse + public saveWeaponBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionId: string, + ): IItemEventRouterResponse { - // TODO - could be merged into saveBuild, maybe + // TODO: Could be merged into saveBuild, maybe const output = this.eventOutputHolder.getOutput(sessionId); // Replace duplicate Id's. The first item is the base item. @@ -82,15 +92,19 @@ export class PresetBuildController name: body.name, root: body.root, items: body.items, - type: "weapon" + type: "weapon", }; const savedWeaponBuilds = this.saveServer.getProfile(sessionId).userbuilds.weaponBuilds; - const existingBuild = savedWeaponBuilds.find(x => x.id === body.id); + const existingBuild = savedWeaponBuilds.find((x) => x.id === body.id); if (existingBuild) { // exists, replace - this.saveServer.getProfile(sessionId).userbuilds.weaponBuilds.splice(savedWeaponBuilds.indexOf(existingBuild), 1, newBuild); + this.saveServer.getProfile(sessionId).userbuilds.weaponBuilds.splice( + savedWeaponBuilds.indexOf(existingBuild), + 1, + newBuild, + ); } else { @@ -105,12 +119,21 @@ export class PresetBuildController } /** Handle SaveEquipmentBuild event */ - public saveEquipmentBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string): IItemEventRouterResponse + public saveEquipmentBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.saveBuild(pmcData, body, sessionID, "equipmentBuilds"); } - protected saveBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string, buildType: string): IItemEventRouterResponse + protected saveBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + buildType: string, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionID); const existingSavedBuilds: any[] = this.saveServer.getProfile(sessionID).userbuilds[buildType]; @@ -125,14 +148,18 @@ export class PresetBuildController buildType: "Custom", root: body.root, fastPanel: [], - items: body.items + items: body.items, }; - const existingBuild = existingSavedBuilds.find(x => x.name === body.name); + const existingBuild = existingSavedBuilds.find((x) => x.name === body.name); if (existingBuild) { // Already exists, replace - this.saveServer.getProfile(sessionID).userbuilds[buildType].splice(existingSavedBuilds.indexOf(existingBuild), 1, newBuild); + this.saveServer.getProfile(sessionID).userbuilds[buildType].splice( + existingSavedBuilds.indexOf(existingBuild), + 1, + newBuild, + ); } else { @@ -152,26 +179,34 @@ export class PresetBuildController } /** Handle RemoveWeaponBuild event*/ - public removeWeaponBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string): IItemEventRouterResponse + public removeWeaponBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + ): IItemEventRouterResponse { - // todo - does this get called? + // TODO: Does this get called? return this.removePlayerBuild(pmcData, body.id, sessionID); } /** Handle RemoveEquipmentBuild event*/ - public removeEquipmentBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string): IItemEventRouterResponse + public removeEquipmentBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + ): IItemEventRouterResponse { - // todo - does this get called? + // TODO: Does this get called? return this.removePlayerBuild(pmcData, body.id, sessionID); } - + protected removePlayerBuild(pmcData: IPmcData, id: string, sessionID: string): IItemEventRouterResponse { const weaponBuilds = this.saveServer.getProfile(sessionID).userbuilds.weaponBuilds; const equipmentBuilds = this.saveServer.getProfile(sessionID).userbuilds.equipmentBuilds; // Check for id in weapon array first - const matchingWeaponBuild = weaponBuilds.find(x => x.id === id); + const matchingWeaponBuild = weaponBuilds.find((x) => x.id === id); if (matchingWeaponBuild) { weaponBuilds.splice(weaponBuilds.indexOf(matchingWeaponBuild), 1); @@ -180,7 +215,7 @@ export class PresetBuildController } // Id not found in weapons, try equipment - const matchingEquipmentBuild = equipmentBuilds.find(x => x.id === id); + const matchingEquipmentBuild = equipmentBuilds.find((x) => x.id === id); if (matchingEquipmentBuild) { equipmentBuilds.splice(equipmentBuilds.indexOf(matchingEquipmentBuild), 1); @@ -191,8 +226,7 @@ export class PresetBuildController { this.logger.error(`Unable to delete preset, cannot find ${id} in weapon or equipment presets`); } - return this.eventOutputHolder.getOutput(sessionID); } -} \ No newline at end of file +} diff --git a/project/src/controllers/PresetController.ts b/project/src/controllers/PresetController.ts index 0ab8f8ed..ceaa0b12 100644 --- a/project/src/controllers/PresetController.ts +++ b/project/src/controllers/PresetController.ts @@ -9,9 +9,9 @@ export class PresetController { constructor( @inject("PresetHelper") protected presetHelper: PresetHelper, - @inject("DatabaseServer") protected databaseServer: DatabaseServer + @inject("DatabaseServer") protected databaseServer: DatabaseServer, ) - { } + {} public initialize(): void { diff --git a/project/src/controllers/ProfileController.ts b/project/src/controllers/ProfileController.ts index b8ba3455..521e5f0c 100644 --- a/project/src/controllers/ProfileController.ts +++ b/project/src/controllers/ProfileController.ts @@ -47,9 +47,9 @@ export class ProfileController @inject("TraderHelper") protected traderHelper: TraderHelper, @inject("DialogueHelper") protected dialogueHelper: DialogueHelper, @inject("QuestHelper") protected questHelper: QuestHelper, - @inject("ProfileHelper") protected profileHelper: ProfileHelper + @inject("ProfileHelper") protected profileHelper: ProfileHelper, ) - { } + {} /** * Handle /launcher/profiles @@ -76,7 +76,7 @@ export class ProfileController const pmc = profile.characters.pmc; // make sure character completed creation - if (!((pmc?.Info?.Level))) + if (!(pmc?.Info?.Level)) { return { username: profile.info.username, @@ -87,7 +87,7 @@ export class ProfileController prevexp: 0, nextlvl: 0, maxlvl: maxlvl, - akiData: this.profileHelper.getDefaultAkiDataObject() + akiData: this.profileHelper.getDefaultAkiDataObject(), }; } @@ -102,7 +102,7 @@ export class ProfileController prevexp: (currlvl === 0) ? 0 : this.profileHelper.getExperience(currlvl), nextlvl: nextlvl, maxlvl: maxlvl, - akiData: profile.aki + akiData: profile.aki, }; return result; @@ -122,7 +122,8 @@ export class ProfileController public createProfile(info: IProfileCreateRequestData, sessionID: string): void { const account = this.saveServer.getProfile(sessionID).info; - const profile: TemplateSide = this.databaseServer.getTables().templates.profiles[account.edition][info.side.toLowerCase()]; + const profile: TemplateSide = + this.databaseServer.getTables().templates.profiles[account.edition][info.side.toLowerCase()]; const pmcData = profile.character; // Delete existing profile @@ -148,11 +149,16 @@ export class ProfileController if (!pmcData.UnlockedInfo) { - pmcData.UnlockedInfo = { unlockedProductionRecipe: [] }; + pmcData.UnlockedInfo = {unlockedProductionRecipe: []}; } // Change item id's to be unique - pmcData.Inventory.items = this.itemHelper.replaceIDs(pmcData, pmcData.Inventory.items, null, pmcData.Inventory.fastPanel); + pmcData.Inventory.items = this.itemHelper.replaceIDs( + pmcData, + pmcData.Inventory.items, + null, + pmcData.Inventory.fastPanel, + ); pmcData.Inventory.hideoutAreaStashes = {}; // Create profile @@ -160,7 +166,7 @@ export class ProfileController info: account, characters: { pmc: pmcData, - scav: {} as IPmcData + scav: {} as IPmcData, }, suits: profile.suits, userbuilds: profile.userbuilds, @@ -169,7 +175,7 @@ export class ProfileController vitality: {} as Vitality, inraid: {} as Inraid, insurance: [], - traderPurchases: {} + traderPurchases: {}, }; this.profileFixerService.checkForAndFixPmcProfileIssues(profileDetails.characters.pmc); @@ -185,7 +191,11 @@ export class ProfileController // Profile is flagged as wanting quests set to ready to hand in and collect rewards if (profile.trader.setQuestsAvailableForFinish) { - this.questHelper.addAllQuestsToProfile(profileDetails.characters.pmc, [QuestStatus.AvailableForStart, QuestStatus.Started, QuestStatus.AvailableForFinish]); + this.questHelper.addAllQuestsToProfile(profileDetails.characters.pmc, [ + QuestStatus.AvailableForStart, + QuestStatus.Started, + QuestStatus.AvailableForFinish, + ]); // Make unused response so applyQuestReward works const response = this.eventOutputHolder.getOutput(sessionID); @@ -219,7 +229,9 @@ export class ProfileController } else { - this.logger.warning(this.localisationService.getText("profile-unable_to_find_profile_by_id_cannot_delete", sessionID)); + this.logger.warning( + this.localisationService.getText("profile-unable_to_find_profile_by_id_cannot_delete", sessionID), + ); } } @@ -230,16 +242,29 @@ export class ProfileController * @param sessionID Session id * @param response Event router response */ - protected givePlayerStartingQuestRewards(profileDetails: IAkiProfile, sessionID: string, response: IItemEventRouterResponse): void + protected givePlayerStartingQuestRewards( + profileDetails: IAkiProfile, + sessionID: string, + response: IItemEventRouterResponse, + ): void { - for (const quest of profileDetails.characters.pmc.Quests) + for (const quest of profileDetails.characters.pmc.Quests) { const questFromDb = this.questHelper.getQuestFromDb(quest.qid, profileDetails.characters.pmc); // Get messageId of text to send to player as text message in game // Copy of code from QuestController.acceptQuest() - const messageId = this.questHelper.getMessageIdForQuestStart(questFromDb.startedMessageText, questFromDb.description); - const itemRewards = this.questHelper.applyQuestReward(profileDetails.characters.pmc, quest.qid, QuestStatus.Started, sessionID, response); + const messageId = this.questHelper.getMessageIdForQuestStart( + questFromDb.startedMessageText, + questFromDb.description, + ); + const itemRewards = this.questHelper.applyQuestReward( + profileDetails.characters.pmc, + quest.qid, + QuestStatus.Started, + sessionID, + response, + ); this.mailSendService.sendLocalisedNpcMessageToPlayer( sessionID, @@ -247,7 +272,8 @@ export class ProfileController MessageType.QUEST_START, messageId, itemRewards, - this.timeUtil.getHoursAsSeconds(100)); + this.timeUtil.getHoursAsSeconds(100), + ); } } @@ -266,7 +292,7 @@ export class ProfileController /** * Generate a player scav object * PMC profile MUST exist first before pscav can be generated - * @param sessionID + * @param sessionID * @returns IPmcData object */ public generatePlayerScav(sessionID: string): IPmcData @@ -323,18 +349,15 @@ export class ProfileController /** * Handle client/game/profile/search */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public getFriends(info: ISearchFriendRequestData, sessionID: string): ISearchFriendResponse[] { - return [ - { - _id: this.hashUtil.generate(), - Info: { - Level: 1, - Side: "Bear", - Nickname: info.nickname - } - } - ]; + return [{ + _id: this.hashUtil.generate(), + Info: { + Level: 1, + Side: "Bear", + Nickname: info.nickname, + }, + }]; } -} \ No newline at end of file +} diff --git a/project/src/controllers/QuestController.ts b/project/src/controllers/QuestController.ts index dd402187..3ce39b96 100644 --- a/project/src/controllers/QuestController.ts +++ b/project/src/controllers/QuestController.ts @@ -57,7 +57,7 @@ export class QuestController @inject("LocaleService") protected localeService: LocaleService, @inject("SeasonalEventService") protected seasonalEventService: SeasonalEventService, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.questConfig = this.configServer.getConfig(ConfigTypes.QUEST); @@ -79,7 +79,7 @@ export class QuestController for (const quest of allQuests) { // Player already accepted the quest, show it regardless of status - const questInProfile = profile.Quests.find(x => x.qid === quest._id); + const questInProfile = profile.Quests.find((x) => x.qid === quest._id); if (questInProfile) { quest.sptStatus = questInProfile.status; @@ -105,8 +105,12 @@ export class QuestController } const questRequirements = this.questConditionHelper.getQuestConditions(quest.conditions.AvailableForStart); - const loyaltyRequirements = this.questConditionHelper.getLoyaltyConditions(quest.conditions.AvailableForStart); - const standingRequirements = this.questConditionHelper.getStandingConditions(quest.conditions.AvailableForStart); + const loyaltyRequirements = this.questConditionHelper.getLoyaltyConditions( + quest.conditions.AvailableForStart, + ); + const standingRequirements = this.questConditionHelper.getStandingConditions( + quest.conditions.AvailableForStart, + ); // Quest has no conditions, standing or loyalty conditions, add to visible quest list if (questRequirements.length === 0 && loyaltyRequirements.length === 0 && standingRequirements.length === 0) @@ -122,14 +126,14 @@ export class QuestController for (const conditionToFulfil of questRequirements) { // If the previous quest isn't in the user profile, it hasn't been completed or started - const prerequisiteQuest = profile.Quests.find(pq => pq.qid === conditionToFulfil._props.target); + const prerequisiteQuest = profile.Quests.find((pq) => pq.qid === conditionToFulfil._props.target); if (!prerequisiteQuest) { haveCompletedPreviousQuest = false; break; } - // Prereq does not have its status requirement fulfilled + // Prerequisite does not have its status requirement fulfilled if (!conditionToFulfil._props.status.includes(prerequisiteQuest.status)) { haveCompletedPreviousQuest = false; @@ -144,7 +148,11 @@ export class QuestController const unlockTime = previousQuestCompleteTime + conditionToFulfil._props.availableAfter; if (unlockTime > this.timeUtil.getTimestamp()) { - this.logger.debug(`Quest ${quest.QuestName} is locked for another ${unlockTime - this.timeUtil.getTimestamp()} seconds`); + this.logger.debug( + `Quest ${quest.QuestName} is locked for another ${ + unlockTime - this.timeUtil.getTimestamp() + } seconds`, + ); } } } @@ -207,7 +215,7 @@ export class QuestController } // All conditions passed / has no level requirement, valid - return true; + return true; } /** @@ -221,19 +229,28 @@ export class QuestController const isHalloweenEventActive = this.seasonalEventService.halloweenEventEnabled(); // Not christmas + quest is for christmas - if (!isChristmasEventActive && this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.CHRISTMAS)) + if ( + !isChristmasEventActive && + this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.CHRISTMAS) + ) { return false; } // Not halloween + quest is for halloween - if (!isHalloweenEventActive && this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.HALLOWEEN)) + if ( + !isHalloweenEventActive && + this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.HALLOWEEN) + ) { return false; } // Should non-season event quests be shown to player - if (!this.questConfig.showNonSeasonalEventQuests && this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.NONE)) + if ( + !this.questConfig.showNonSeasonalEventQuests && + this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.NONE) + ) { return false; } @@ -274,7 +291,11 @@ export class QuestController * @param sessionID Session id * @returns client response */ - public acceptQuest(pmcData: IPmcData, acceptedQuest: IAcceptQuestRequestData, sessionID: string): IItemEventRouterResponse + public acceptQuest( + pmcData: IPmcData, + acceptedQuest: IAcceptQuestRequestData, + sessionID: string, + ): IItemEventRouterResponse { const acceptQuestResponse = this.eventOutputHolder.getOutput(sessionID); @@ -282,7 +303,7 @@ export class QuestController const newQuest = this.questHelper.getQuestReadyForProfile(pmcData, startedState, acceptedQuest); // Does quest exist in profile - if (pmcData.Quests.find(x => x.qid === acceptedQuest.qid)) + if (pmcData.Quests.find((x) => x.qid === acceptedQuest.qid)) { // Update existing this.questHelper.updateQuestState(pmcData, QuestStatus.Started, acceptedQuest.qid); @@ -297,8 +318,17 @@ export class QuestController // Note that for starting quests, the correct locale field is "description", not "startedMessageText". const questFromDb = this.questHelper.getQuestFromDb(acceptedQuest.qid, pmcData); // Get messageId of text to send to player as text message in game - const messageId = this.questHelper.getMessageIdForQuestStart(questFromDb.startedMessageText, questFromDb.description); - const startedQuestRewards = this.questHelper.applyQuestReward(pmcData, acceptedQuest.qid, QuestStatus.Started, sessionID, acceptQuestResponse); + const messageId = this.questHelper.getMessageIdForQuestStart( + questFromDb.startedMessageText, + questFromDb.description, + ); + const startedQuestRewards = this.questHelper.applyQuestReward( + pmcData, + acceptedQuest.qid, + QuestStatus.Started, + sessionID, + acceptQuestResponse, + ); this.mailSendService.sendLocalisedNpcMessageToPlayer( sessionID, @@ -306,9 +336,11 @@ export class QuestController MessageType.QUEST_START, messageId, startedQuestRewards, - this.timeUtil.getHoursAsSeconds(this.questConfig.redeemTime)); + this.timeUtil.getHoursAsSeconds(this.questConfig.redeemTime), + ); - acceptQuestResponse.profileChanges[sessionID].quests = this.questHelper.getNewlyAccessibleQuestsWhenStartingQuest(acceptedQuest.qid, sessionID); + acceptQuestResponse.profileChanges[sessionID].quests = this.questHelper + .getNewlyAccessibleQuestsWhenStartingQuest(acceptedQuest.qid, sessionID); return acceptQuestResponse; } @@ -322,24 +354,36 @@ export class QuestController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public acceptRepeatableQuest(pmcData: IPmcData, acceptedQuest: IAcceptQuestRequestData, sessionID: string): IItemEventRouterResponse + public acceptRepeatableQuest( + pmcData: IPmcData, + acceptedQuest: IAcceptQuestRequestData, + sessionID: string, + ): IItemEventRouterResponse { const acceptQuestResponse = this.eventOutputHolder.getOutput(sessionID); const desiredQuestState = QuestStatus.Started; const newQuest = this.questHelper.getQuestReadyForProfile(pmcData, desiredQuestState, acceptedQuest); pmcData.Quests.push(newQuest); - + const repeatableQuestProfile = this.getRepeatableQuestFromProfile(pmcData, acceptedQuest); if (!repeatableQuestProfile) { - this.logger.error(this.localisationService.getText("repeatable-accepted_repeatable_quest_not_found_in_active_quests", acceptedQuest.qid)); + this.logger.error( + this.localisationService.getText( + "repeatable-accepted_repeatable_quest_not_found_in_active_quests", + acceptedQuest.qid, + ), + ); throw new Error(this.localisationService.getText("repeatable-unable_to_accept_quest_see_log")); } // Some scav quests need to be added to scav profile for them to show up in-raid - if (repeatableQuestProfile.side === "Scav" && ["PickUp", "Exploration", "Elimination"].includes(repeatableQuestProfile.type)) + if ( + repeatableQuestProfile.side === "Scav" && + ["PickUp", "Exploration", "Elimination"].includes(repeatableQuestProfile.type) + ) { const fullProfile = this.profileHelper.getFullProfile(sessionID); if (!fullProfile.characters.scav.Quests) @@ -351,46 +395,67 @@ export class QuestController } const locale = this.localeService.getLocaleDb(); - const questStartedMessageKey = this.questHelper.getMessageIdForQuestStart(repeatableQuestProfile.startedMessageText, repeatableQuestProfile.description); + const questStartedMessageKey = this.questHelper.getMessageIdForQuestStart( + repeatableQuestProfile.startedMessageText, + repeatableQuestProfile.description, + ); // Can be started text or description text based on above function result let questStartedMessageText = locale[questStartedMessageKey]; - // TODO: remove this whole if statement, possibly not required? + // TODO: Remove this whole if statement, possibly not required? if (!questStartedMessageText) { - this.logger.debug(`Unable to accept quest ${acceptedQuest.qid}, cannot find the quest started message text with id ${questStartedMessageKey}. attempting to find it in en locale instead`); + this.logger.debug( + `Unable to accept quest ${acceptedQuest.qid}, cannot find the quest started message text with id ${questStartedMessageKey}. attempting to find it in en locale instead`, + ); - // For some reason non-en locales dont have repeatable quest ids, fall back to en and grab it if possible + // For some reason non-en locales don't have repeatable quest ids, fall back to en and grab it if possible const enLocale = this.databaseServer.getTables().locales.global["en"]; questStartedMessageText = enLocale[repeatableQuestProfile.startedMessageText]; if (!questStartedMessageText) { - this.logger.error(this.localisationService.getText("repeatable-unable_to_accept_quest_starting_message_not_found", {questId: acceptedQuest.qid, messageId: questStartedMessageKey})); + this.logger.error( + this.localisationService.getText("repeatable-unable_to_accept_quest_starting_message_not_found", { + questId: acceptedQuest.qid, + messageId: questStartedMessageKey, + }), + ); - return this.httpResponseUtil.appendErrorToOutput(acceptQuestResponse, this.localisationService.getText("repeatable-unable_to_accept_quest_see_log")); + return this.httpResponseUtil.appendErrorToOutput( + acceptQuestResponse, + this.localisationService.getText("repeatable-unable_to_accept_quest_see_log"), + ); } } - const questRewards = this.questHelper.getQuestRewardItems(repeatableQuestProfile, desiredQuestState); + const questRewards = this.questHelper.getQuestRewardItems( + repeatableQuestProfile, + desiredQuestState, + ); this.mailSendService.sendLocalisedNpcMessageToPlayer( sessionID, this.traderHelper.getTraderById(repeatableQuestProfile.traderId), MessageType.QUEST_START, questStartedMessageKey, questRewards, - this.timeUtil.getHoursAsSeconds(this.questConfig.redeemTime)); + this.timeUtil.getHoursAsSeconds(this.questConfig.redeemTime), + ); - const repeatableSettings = pmcData.RepeatableQuests.find(x => x.name === repeatableQuestProfile.sptRepatableGroupName); + const repeatableSettings = pmcData.RepeatableQuests.find((x) => + x.name === repeatableQuestProfile.sptRepatableGroupName + ); const change = {}; change[repeatableQuestProfile._id] = repeatableSettings.changeRequirement[repeatableQuestProfile._id]; const responseData: IPmcDataRepeatableQuest = { - id: repeatableSettings.id ?? this.questConfig.repeatableQuests.find(x => x.name === repeatableQuestProfile.sptRepatableGroupName).id, + id: repeatableSettings.id ?? + this.questConfig.repeatableQuests.find((x) => x.name === repeatableQuestProfile.sptRepatableGroupName) + .id, name: repeatableSettings.name, endTime: repeatableSettings.endTime, changeRequirement: change, activeQuests: [repeatableQuestProfile], - inactiveQuests: [] + inactiveQuests: [], }; acceptQuestResponse.profileChanges[sessionID].repeatableQuests = [responseData]; @@ -407,12 +472,12 @@ export class QuestController { for (const repeatableQuest of pmcData.RepeatableQuests) { - const matchingQuest = repeatableQuest.activeQuests.find(x => x._id === acceptedQuest.qid); + const matchingQuest = repeatableQuest.activeQuests.find((x) => x._id === acceptedQuest.qid); if (matchingQuest) { this.logger.debug(`Accepted repeatable quest ${acceptedQuest.qid} from ${repeatableQuest.name}`); matchingQuest.sptRepatableGroupName = repeatableQuest.name; - + return matchingQuest; } } @@ -430,7 +495,11 @@ export class QuestController * @param sessionID Session id * @returns ItemEvent client response */ - public completeQuest(pmcData: IPmcData, body: ICompleteQuestRequestData, sessionID: string): IItemEventRouterResponse + public completeQuest( + pmcData: IPmcData, + body: ICompleteQuestRequestData, + sessionID: string, + ): IItemEventRouterResponse { const completeQuestResponse = this.eventOutputHolder.getOutput(sessionID); @@ -442,7 +511,13 @@ export class QuestController const newQuestState = QuestStatus.Success; this.questHelper.updateQuestState(pmcData, newQuestState, completedQuestId); - const questRewards = this.questHelper.applyQuestReward(pmcData, body.qid, newQuestState, sessionID, completeQuestResponse); + const questRewards = this.questHelper.applyQuestReward( + pmcData, + body.qid, + newQuestState, + sessionID, + completeQuestResponse, + ); // Check for linked failed + unrestartable quests const questsToFail = this.getQuestsFailedByCompletingQuest(completedQuestId); @@ -456,8 +531,8 @@ export class QuestController // Add diff of quests before completion vs after for client response const questDelta = this.questHelper.getDeltaQuests(beforeQuests, this.getClientQuests(sessionID)); - - // Check newly available + failed quests for timegates and add them to profile + + // Check newly available + failed quests for time gates and add them to profile this.addTimeLockedQuestsToProfile(pmcData, [...questDelta, ...questsToFail], body.qid); // Inform client of quest changes @@ -466,10 +541,12 @@ export class QuestController // Check if it's a repeatable quest. If so, remove from Quests and repeatable.activeQuests list + move to repeatable.inactiveQuests for (const currentRepeatable of pmcData.RepeatableQuests) { - const repeatableQuest = currentRepeatable.activeQuests.find(x => x._id === completedQuestId); + const repeatableQuest = currentRepeatable.activeQuests.find((x) => x._id === completedQuestId); if (repeatableQuest) { - currentRepeatable.activeQuests = currentRepeatable.activeQuests.filter(x => x._id !== completedQuestId); + currentRepeatable.activeQuests = currentRepeatable.activeQuests.filter((x) => + x._id !== completedQuestId + ); currentRepeatable.inactiveQuests.push(repeatableQuest); // Need to remove redundant scav quest object as its no longer necessary, is tracked in pmc profile @@ -498,31 +575,39 @@ export class QuestController protected removeQuestFromScavProfile(sessionId: string, questIdToRemove: string): void { const fullProfile = this.profileHelper.getFullProfile(sessionId); - const repeatableInScavProfile = fullProfile.characters.scav.Quests.find(x => x.qid === questIdToRemove); + const repeatableInScavProfile = fullProfile.characters.scav.Quests.find((x) => x.qid === questIdToRemove); if (!repeatableInScavProfile) { - this.logger.warning(`Unable to remove quest: ${questIdToRemove} from profile as scav profile cannot be found`); + this.logger.warning( + `Unable to remove quest: ${questIdToRemove} from profile as scav profile cannot be found`, + ); return; } - fullProfile.characters.scav.Quests.splice(fullProfile.characters.scav.Quests.indexOf(repeatableInScavProfile), 1); + fullProfile.characters.scav.Quests.splice( + fullProfile.characters.scav.Quests.indexOf(repeatableInScavProfile), + 1, + ); } /** * Return quests that have different statuses - * @param preQuestStatusus Quests before + * @param preQuestStatuses Quests before * @param postQuestStatuses Quests after * @returns QuestStatusChange array */ - protected getQuestsWithDifferentStatuses(preQuestStatusus: IQuestStatus[], postQuestStatuses: IQuestStatus[]): IQuestStatus[] + protected getQuestsWithDifferentStatuses( + preQuestStatuses: IQuestStatus[], + postQuestStatuses: IQuestStatus[], + ): IQuestStatus[] { const result: IQuestStatus[] = []; for (const quest of postQuestStatuses) { // Add quest if status differs or quest not found - const preQuest = preQuestStatusus.find(x => x.qid === quest.qid); + const preQuest = preQuestStatuses.find((x) => x.qid === quest.qid); if (!preQuest || preQuest.status !== quest.status) { result.push(quest); @@ -544,7 +629,12 @@ export class QuestController * @param completedQuestId Completed quest id * @param questRewards Rewards given to player */ - protected sendSuccessDialogMessageOnQuestComplete(sessionID: string, pmcData: IPmcData, completedQuestId: string, questRewards: Reward[]): void + protected sendSuccessDialogMessageOnQuestComplete( + sessionID: string, + pmcData: IPmcData, + completedQuestId: string, + questRewards: Reward[], + ): void { const quest = this.questHelper.getQuestFromDb(completedQuestId, pmcData); @@ -554,7 +644,8 @@ export class QuestController MessageType.QUEST_SUCCESS, quest.successMessageText, questRewards, - this.timeUtil.getHoursAsSeconds(this.questConfig.redeemTime)); + this.timeUtil.getHoursAsSeconds(this.questConfig.redeemTime), + ); } /** @@ -568,15 +659,18 @@ export class QuestController // Iterate over quests, look for quests with right criteria for (const quest of quests) { - // If quest has prereq of completed quest + availableAfter value > 0 (quest has wait time) - const nextQuestWaitCondition = quest.conditions.AvailableForStart.find(x => x._props.target === completedQuestId && x._props.availableAfter > 0); + // If quest has prerequisite of completed quest + availableAfter value > 0 (quest has wait time) + const nextQuestWaitCondition = quest.conditions.AvailableForStart.find((x) => + x._props.target === completedQuestId && x._props.availableAfter > 0 + ); if (nextQuestWaitCondition) { // Now + wait time - const availableAfterTimestamp = this.timeUtil.getTimestamp() + nextQuestWaitCondition._props.availableAfter; + const availableAfterTimestamp = this.timeUtil.getTimestamp() + + nextQuestWaitCondition._props.availableAfter; // Update quest in profile with status of AvailableAfter - const existingQuestInProfile = pmcData.Quests.find(x => x.qid === quest._id); + const existingQuestInProfile = pmcData.Quests.find((x) => x.qid === quest._id); if (existingQuestInProfile) { existingQuestInProfile.availableAfter = availableAfterTimestamp; @@ -592,10 +686,9 @@ export class QuestController startTime: 0, status: QuestStatus.AvailableAfter, statusTimers: { - // eslint-disable-next-line @typescript-eslint/naming-convention - "9": this.timeUtil.getTimestamp() + "9": this.timeUtil.getTimestamp(), // eslint-disable-line @typescript-eslint/naming-convention }, - availableAfter: availableAfterTimestamp + availableAfter: availableAfterTimestamp, }); } } @@ -617,7 +710,7 @@ export class QuestController return false; } - return x.conditions.Fail.some(y => y._props.target === completedQuestId); + return x.conditions.Fail.some((y) => y._props.target === completedQuestId); }); } @@ -629,23 +722,28 @@ export class QuestController * @param questsToFail quests to fail * @param output Client output */ - protected failQuests(sessionID: string, pmcData: IPmcData, questsToFail: IQuest[], output: IItemEventRouterResponse): void + protected failQuests( + sessionID: string, + pmcData: IPmcData, + questsToFail: IQuest[], + output: IItemEventRouterResponse, + ): void { for (const questToFail of questsToFail) { // Skip failing a quest that has a fail status of something other than success - if (questToFail.conditions.Fail?.some(x => x._props.status?.some(y => y !== QuestStatus.Success))) + if (questToFail.conditions.Fail?.some((x) => x._props.status?.some((y) => y !== QuestStatus.Success))) { continue; } - const isActiveQuestInPlayerProfile = pmcData.Quests.find(y => y.qid === questToFail._id); + const isActiveQuestInPlayerProfile = pmcData.Quests.find((y) => y.qid === questToFail._id); if (isActiveQuestInPlayerProfile) { const failBody: IFailQuestRequestData = { Action: "QuestComplete", qid: questToFail._id, - removeExcessItems: true + removeExcessItems: true, }; this.questHelper.failQuest(pmcData, failBody, sessionID, output); } @@ -657,7 +755,7 @@ export class QuestController qid: questToFail._id, startTime: this.timeUtil.getTimestamp(), statusTimers: statusTimers, - status: QuestStatus.Fail + status: QuestStatus.Fail, }; pmcData.Quests.push(questData); } @@ -671,7 +769,11 @@ export class QuestController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public handoverQuest(pmcData: IPmcData, handoverQuestRequest: IHandoverQuestRequestData, sessionID: string): IItemEventRouterResponse + public handoverQuest( + pmcData: IPmcData, + handoverQuestRequest: IHandoverQuestRequestData, + sessionID: string, + ): IItemEventRouterResponse { const quest = this.questHelper.getQuestFromDb(handoverQuestRequest.qid, pmcData); const handoverQuestTypes = ["HandoverItem", "WeaponAssembly"]; @@ -684,20 +786,33 @@ export class QuestController let handoverRequirements: AvailableForConditions; for (const condition of quest.conditions.AvailableForFinish) { - if (condition._props.id === handoverQuestRequest.conditionId && handoverQuestTypes.includes(condition._parent)) + if ( + condition._props.id === handoverQuestRequest.conditionId && + handoverQuestTypes.includes(condition._parent) + ) { handedInCount = Number.parseInt(condition._props.value); isItemHandoverQuest = condition._parent === handoverQuestTypes[0]; handoverRequirements = condition; - const profileCounter = (handoverQuestRequest.conditionId in pmcData.BackendCounters) - ? pmcData.BackendCounters[handoverQuestRequest.conditionId].value - : 0; + const profileCounter = (handoverQuestRequest.conditionId in pmcData.BackendCounters) ? + pmcData.BackendCounters[handoverQuestRequest.conditionId].value : + 0; handedInCount -= profileCounter; if (handedInCount <= 0) { - this.logger.error(this.localisationService.getText("repeatable-quest_handover_failed_condition_already_satisfied", {questId: handoverQuestRequest.qid, conditionId: handoverQuestRequest.conditionId, profileCounter: profileCounter, value: handedInCount})); + this.logger.error( + this.localisationService.getText( + "repeatable-quest_handover_failed_condition_already_satisfied", + { + questId: handoverQuestRequest.qid, + conditionId: handoverQuestRequest.conditionId, + profileCounter: profileCounter, + value: handedInCount, + }, + ), + ); return output; } @@ -710,15 +825,20 @@ export class QuestController { return this.showRepeatableQuestInvalidConditionError(handoverQuestRequest, output); } - + let totalItemCountToRemove = 0; for (const itemHandover of handoverQuestRequest.items) { - const matchingItemInProfile = pmcData.Inventory.items.find(x => x._id === itemHandover.id); + const matchingItemInProfile = pmcData.Inventory.items.find((x) => x._id === itemHandover.id); if (!handoverRequirements._props.target.includes(matchingItemInProfile._tpl)) { - // Item handed in by player doesnt match what was requested - return this.showQuestItemHandoverMatchError(handoverQuestRequest, matchingItemInProfile, handoverRequirements, output); + // Item handed in by player doesn't match what was requested + return this.showQuestItemHandoverMatchError( + handoverQuestRequest, + matchingItemInProfile, + handoverRequirements, + output, + ); } // Remove the right quantity of given items @@ -727,7 +847,13 @@ export class QuestController if (itemHandover.count - itemCountToRemove > 0) { // Remove single item with no children - this.questHelper.changeItemStack(pmcData, itemHandover.id, itemHandover.count - itemCountToRemove, sessionID, output); + this.questHelper.changeItemStack( + pmcData, + itemHandover.id, + itemHandover.count - itemCountToRemove, + sessionID, + output, + ); if (totalItemCountToRemove === handedInCount) { break; @@ -740,7 +866,7 @@ export class QuestController let index = pmcData.Inventory.items.length; // Important: don't tell the client to remove the attachments, it will handle it - output.profileChanges[sessionID].items.del.push({ _id: itemHandover.id }); + output.profileChanges[sessionID].items.del.push({_id: itemHandover.id}); // Important: loop backward when removing items from the array we're looping on while (index-- > 0) @@ -753,7 +879,12 @@ export class QuestController } } - this.updateProfileBackendCounterValue(pmcData, handoverQuestRequest.conditionId, handoverQuestRequest.qid, totalItemCountToRemove); + this.updateProfileBackendCounterValue( + pmcData, + handoverQuestRequest.conditionId, + handoverQuestRequest.qid, + totalItemCountToRemove, + ); return output; } @@ -764,9 +895,15 @@ export class QuestController * @param output Response to send to user * @returns IItemEventRouterResponse */ - protected showRepeatableQuestInvalidConditionError(handoverQuestRequest: IHandoverQuestRequestData, output: IItemEventRouterResponse): IItemEventRouterResponse + protected showRepeatableQuestInvalidConditionError( + handoverQuestRequest: IHandoverQuestRequestData, + output: IItemEventRouterResponse, + ): IItemEventRouterResponse { - const errorMessage = this.localisationService.getText("repeatable-quest_handover_failed_condition_invalid", { questId: handoverQuestRequest.qid, conditionId: handoverQuestRequest.conditionId }); + const errorMessage = this.localisationService.getText("repeatable-quest_handover_failed_condition_invalid", { + questId: handoverQuestRequest.qid, + conditionId: handoverQuestRequest.conditionId, + }); this.logger.error(errorMessage); return this.httpResponseUtil.appendErrorToOutput(output, errorMessage); @@ -780,9 +917,18 @@ export class QuestController * @param output Response to send to user * @returns IItemEventRouterResponse */ - protected showQuestItemHandoverMatchError(handoverQuestRequest: IHandoverQuestRequestData, itemHandedOver: Item, handoverRequirements: AvailableForConditions, output: IItemEventRouterResponse): IItemEventRouterResponse + protected showQuestItemHandoverMatchError( + handoverQuestRequest: IHandoverQuestRequestData, + itemHandedOver: Item, + handoverRequirements: AvailableForConditions, + output: IItemEventRouterResponse, + ): IItemEventRouterResponse { - const errorMessage = this.localisationService.getText("quest-handover_wrong_item", { questId: handoverQuestRequest.qid, handedInTpl: itemHandedOver._tpl, requiredTpl: handoverRequirements._props.target[0] }); + const errorMessage = this.localisationService.getText("quest-handover_wrong_item", { + questId: handoverQuestRequest.qid, + handedInTpl: itemHandedOver._tpl, + requiredTpl: handoverRequirements._props.target[0], + }); this.logger.error(errorMessage); return this.httpResponseUtil.appendErrorToOutput(output, errorMessage); @@ -796,7 +942,12 @@ export class QuestController * @param questId quest id counter is associated with * @param counterValue value to increment the backend counter with */ - protected updateProfileBackendCounterValue(pmcData: IPmcData, conditionId: string, questId: string, counterValue: number): void + protected updateProfileBackendCounterValue( + pmcData: IPmcData, + conditionId: string, + questId: string, + counterValue: number, + ): void { if (pmcData.BackendCounters[conditionId] !== undefined) { @@ -804,10 +955,10 @@ export class QuestController return; } - pmcData.BackendCounters[conditionId] = { + pmcData.BackendCounters[conditionId] = { id: conditionId, qid: questId, - value: counterValue + value: counterValue, }; } -} \ No newline at end of file +} diff --git a/project/src/controllers/RagfairController.ts b/project/src/controllers/RagfairController.ts index 0fd7c298..313c30bb 100644 --- a/project/src/controllers/RagfairController.ts +++ b/project/src/controllers/RagfairController.ts @@ -76,7 +76,7 @@ export class RagfairController @inject("RagfairRequiredItemsService") protected ragfairRequiredItemsService: RagfairRequiredItemsService, @inject("RagfairOfferGenerator") protected ragfairOfferGenerator: RagfairOfferGenerator, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); @@ -89,7 +89,7 @@ export class RagfairController const result: IGetOffersResult = { offers: [], offersCount: searchRequest.limit, - selectedCategory: searchRequest.handbookId + selectedCategory: searchRequest.handbookId, }; const pmcProfile = this.profileHelper.getPmcProfile(sessionID); @@ -106,7 +106,11 @@ export class RagfairController this.addIndexValueToOffers(result.offers); // Sort offers - result.offers = this.ragfairSortHelper.sortOffers(result.offers, searchRequest.sortType, searchRequest.sortDirection); + result.offers = this.ragfairSortHelper.sortOffers( + result.offers, + searchRequest.sortType, + searchRequest.sortDirection, + ); // Match offers with quests and lock unfinished quests const profile = this.profileHelper.getFullProfile(sessionID); @@ -114,13 +118,13 @@ export class RagfairController { if (offer.user.memberType === MemberCategory.TRADER) { - // for the items, check the barter schemes. The method getDisplayableAssorts sets a flag sptQuestLocked to true if the quest - // is not completed yet + // for the items, check the barter schemes. The method getDisplayableAssorts sets a flag sptQuestLocked + // to true if the quest is not completed yet if (this.ragfairOfferHelper.traderOfferItemQuestLocked(offer, traderAssorts)) { offer.locked = true; } - + // Update offers BuyRestrictionCurrent/BuyRestrictionMax values this.setTraderOfferPurchaseLimits(offer, profile); this.setTraderOfferStackSize(offer); @@ -132,10 +136,10 @@ export class RagfairController result.offersCount = result.offers.length; // Handle paging before returning results only if searching for general items, not preset items - if (searchRequest.buildCount === 0) + if (searchRequest.buildCount === 0) { const start = searchRequest.page * searchRequest.limit; - const end = Math.min(((searchRequest.page + 1) * searchRequest.limit), result.offers.length); + const end = Math.min((searchRequest.page + 1) * searchRequest.limit, result.offers.length); result.offers = result.offers.slice(start, end); } return result; @@ -149,7 +153,12 @@ export class RagfairController * @param pmcProfile Player profile * @returns array of offers */ - protected getOffersForSearchType(searchRequest: ISearchRequestData, itemsToAdd: string[], traderAssorts: Record, pmcProfile: IPmcData): IRagfairOffer[] + protected getOffersForSearchType( + searchRequest: ISearchRequestData, + itemsToAdd: string[], + traderAssorts: Record, + pmcProfile: IPmcData, + ): IRagfairOffer[] { // Searching for items in preset menu if (searchRequest.buildCount) @@ -165,14 +174,14 @@ export class RagfairController * Get categories for the type of search being performed, linked/required/all * @param searchRequest Client search request data * @param offers ragfair offers to get categories for - * @returns record with tpls + counts + * @returns record with templates + counts */ protected getSpecificCategories(searchRequest: ISearchRequestData, offers: IRagfairOffer[]): Record { // Linked/required search categories if (this.isLinkedSearch(searchRequest) || this.isRequiredSearch(searchRequest)) { - return this.ragfairServer.getBespokeCategories(offers); + return this.ragfairServer.getBespokeCategories(offers); } // Get all categories @@ -187,11 +196,16 @@ export class RagfairController /** * Add Required offers to offers result * @param searchRequest Client search request data - * @param assorts + * @param assorts * @param pmcProfile Player profile * @param result Result object being sent back to client */ - protected addRequiredOffersToResult(searchRequest: ISearchRequestData, assorts: Record, pmcProfile: IPmcData, result: IGetOffersResult): void + protected addRequiredOffersToResult( + searchRequest: ISearchRequestData, + assorts: Record, + pmcProfile: IPmcData, + result: IGetOffersResult, + ): void { const requiredOffers = this.ragfairRequiredItemsService.getRequiredItemsById(searchRequest.neededSearchId); for (const requiredOffer of requiredOffers) @@ -214,7 +228,7 @@ export class RagfairController for (const offer of offers) { offer.intId = ++counter; - offer.items[0].parentId = ""; //without this it causes error: "Item deserialization error: No parent with id hideout found for item x" + offer.items[0].parentId = ""; // Without this it causes error: "Item deserialization error: No parent with id hideout found for item x" } } @@ -239,12 +253,12 @@ export class RagfairController const traderAssorts = this.traderHelper.getTraderAssortsByTraderId(offer.user.id).items; const assortId = offer.items[0]._id; - const assortData = traderAssorts.find(x => x._id === assortId); + const assortData = traderAssorts.find((x) => x._id === assortId); // Use value stored in profile, otherwise use value directly from in-memory trader assort data - offer.buyRestrictionCurrent = profile.traderPurchases[offer.user.id][assortId] - ? profile.traderPurchases[offer.user.id][assortId].count - : assortData.upd.BuyRestrictionCurrent; + offer.buyRestrictionCurrent = profile.traderPurchases[offer.user.id][assortId] ? + profile.traderPurchases[offer.user.id][assortId].count : + assortData.upd.BuyRestrictionCurrent; offer.buyRestrictionMax = assortData.upd.BuyRestrictionMax; } @@ -258,10 +272,15 @@ export class RagfairController const firstItem = offer.items[0]; const traderAssorts = this.traderHelper.getTraderAssortsByTraderId(offer.user.id).items; - const assortPurchased = traderAssorts.find(x => x._id === offer.items[0]._id); + const assortPurchased = traderAssorts.find((x) => x._id === offer.items[0]._id); if (!assortPurchased) { - this.logger.warning(this.localisationService.getText("ragfair-unable_to_adjust_stack_count_assort_not_found", {offerId: offer.items[0]._id, traderId: offer.user.id})); + this.logger.warning( + this.localisationService.getText("ragfair-unable_to_adjust_stack_count_assort_not_found", { + offerId: offer.items[0]._id, + traderId: offer.user.id, + }), + ); return; } @@ -292,7 +311,7 @@ export class RagfairController /** * Called when creating an offer on flea, fills values in top right corner - * @param getPriceRequest + * @param getPriceRequest * @returns min/avg/max values for an item based on flea offers available */ public getItemMinAvgMaxFleaPriceValues(getPriceRequest: IGetMarketPriceRequestData): IGetItemPriceResult @@ -301,7 +320,7 @@ export class RagfairController let offers = this.ragfairOfferService.getOffersOfType(getPriceRequest.templateId); // Offers exist for item, get averages of what's listed - if (typeof(offers) === "object" && offers.length > 0) + if (typeof offers === "object" && offers.length > 0) { offers = this.ragfairSortHelper.sortOffers(offers, RagfairSort.PRICE); const min = offers[0].requirementsCost; // Get first item from array as its pre-sorted @@ -310,10 +329,11 @@ export class RagfairController return { avg: (min + max) / 2, min: min, - max: max + max: max, }; } - else // No offers listed, get price from live ragfair price list prices.json + // No offers listed, get price from live ragfair price list prices.json + else { const templatesDb = this.databaseServer.getTables().templates; @@ -327,7 +347,7 @@ export class RagfairController return { avg: tplPrice, min: tplPrice, - max: tplPrice + max: tplPrice, }; } } @@ -339,7 +359,11 @@ export class RagfairController * @param sessionID Session id * @returns IItemEventRouterResponse */ - public addPlayerOffer(pmcData: IPmcData, offerRequest: IAddOfferRequestData, sessionID: string): IItemEventRouterResponse + public addPlayerOffer( + pmcData: IPmcData, + offerRequest: IAddOfferRequestData, + sessionID: string, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionID); @@ -351,7 +375,11 @@ export class RagfairController // Get an array of items from player inventory to list on flea const getItemsFromInventoryErrorMessage = ""; - const itemsInInventoryToList = this.getItemsToListOnFleaFromInventory(pmcData, offerRequest.items, getItemsFromInventoryErrorMessage); + const itemsInInventoryToList = this.getItemsToListOnFleaFromInventory( + pmcData, + offerRequest.items, + getItemsFromInventoryErrorMessage, + ); if (!itemsInInventoryToList) { this.httpResponse.appendErrorToOutput(output, getItemsFromInventoryErrorMessage); @@ -360,32 +388,52 @@ export class RagfairController // Checks are done, create the offer const playerListedPriceInRub = this.calculateRequirementsPriceInRub(offerRequest.requirements); const fullProfile = this.saveServer.getProfile(sessionID); - const offer = this.createPlayerOffer(fullProfile, offerRequest.requirements, this.ragfairHelper.mergeStackable(itemsInInventoryToList), offerRequest.sellInOnePiece, playerListedPriceInRub); + const offer = this.createPlayerOffer( + fullProfile, + offerRequest.requirements, + this.ragfairHelper.mergeStackable(itemsInInventoryToList), + offerRequest.sellInOnePiece, + playerListedPriceInRub, + ); const rootItem = offer.items[0]; const qualityMultiplier = this.itemHelper.getItemQualityModifier(rootItem); - const averageOfferPrice = this.ragfairPriceService.getFleaPriceForItem(rootItem._tpl) * rootItem.upd.StackObjectsCount * qualityMultiplier; - const itemStackCount = (offerRequest.sellInOnePiece) - ? 1 - : rootItem.upd.StackObjectsCount; + const averageOfferPrice = this.ragfairPriceService.getFleaPriceForItem(rootItem._tpl) * + rootItem.upd.StackObjectsCount * qualityMultiplier; + const itemStackCount = (offerRequest.sellInOnePiece) ? + 1 : + rootItem.upd.StackObjectsCount; // Get averaged price of a single item being listed - const averageSingleItemPrice = (offerRequest.sellInOnePiece) - ? averageOfferPrice / rootItem.upd.StackObjectsCount // Packs are a single offer made of many items - : averageOfferPrice / itemStackCount; - + const averageSingleItemPrice = (offerRequest.sellInOnePiece) ? + averageOfferPrice / rootItem.upd.StackObjectsCount // Packs are a single offer made of many items + : + averageOfferPrice / itemStackCount; + // Get averaged price of listing - const averagePlayerListedPriceInRub = (offerRequest.sellInOnePiece) - ? playerListedPriceInRub / rootItem.upd.StackObjectsCount - : playerListedPriceInRub; + const averagePlayerListedPriceInRub = (offerRequest.sellInOnePiece) ? + playerListedPriceInRub / rootItem.upd.StackObjectsCount : + playerListedPriceInRub; // Packs are reduced to the average price of a single item in the pack vs the averaged single price of an item - const sellChancePercent = this.ragfairSellHelper.calculateSellChance(averageSingleItemPrice, averagePlayerListedPriceInRub, qualityMultiplier); + const sellChancePercent = this.ragfairSellHelper.calculateSellChance( + averageSingleItemPrice, + averagePlayerListedPriceInRub, + qualityMultiplier, + ); offer.sellResult = this.ragfairSellHelper.rollForSale(sellChancePercent, itemStackCount); // Subtract flea market fee from stash if (this.ragfairConfig.sell.fees) { - const taxFeeChargeFailed = this.chargePlayerTaxFee(sessionID, rootItem, pmcData, playerListedPriceInRub, itemStackCount, offerRequest, output); + const taxFeeChargeFailed = this.chargePlayerTaxFee( + sessionID, + rootItem, + pmcData, + playerListedPriceInRub, + itemStackCount, + offerRequest, + output, + ); if (taxFeeChargeFailed) { return output; @@ -415,24 +463,41 @@ export class RagfairController * @param output IItemEventRouterResponse * @returns True if charging tax to player failed */ - protected chargePlayerTaxFee(sessionID: string, rootItem: Item, pmcData: IPmcData, requirementsPriceInRub: number, itemStackCount: number, offerRequest: IAddOfferRequestData, output: IItemEventRouterResponse): boolean + protected chargePlayerTaxFee( + sessionID: string, + rootItem: Item, + pmcData: IPmcData, + requirementsPriceInRub: number, + itemStackCount: number, + offerRequest: IAddOfferRequestData, + output: IItemEventRouterResponse, + ): boolean { // Get tax from cache hydrated earlier by client, if that's missing fall back to server calculation (inaccurate) const storedClientTaxValue = this.ragfairTaxService.getStoredClientOfferTaxValueById(offerRequest.items[0]); - const tax = storedClientTaxValue - ? storedClientTaxValue.fee - : this.ragfairTaxService.calculateTax(rootItem, pmcData, requirementsPriceInRub, itemStackCount, offerRequest.sellInOnePiece); + const tax = storedClientTaxValue ? + storedClientTaxValue.fee : + this.ragfairTaxService.calculateTax( + rootItem, + pmcData, + requirementsPriceInRub, + itemStackCount, + offerRequest.sellInOnePiece, + ); this.logger.debug(`Offer tax to charge: ${tax}, pulled from client: ${(!!storedClientTaxValue)}`); - //cleanup of cache now we've used the tax value from it + // cleanup of cache now we've used the tax value from it this.ragfairTaxService.clearStoredOfferTaxById(offerRequest.items[0]); const buyTradeRequest = this.createBuyTradeRequestObject("RUB", tax); output = this.paymentService.payMoney(pmcData, buyTradeRequest, sessionID, output); if (output.warnings.length > 0) { - output = this.httpResponse.appendErrorToOutput(output, this.localisationService.getText("ragfair-unable_to_pay_commission_fee", tax)); + output = this.httpResponse.appendErrorToOutput( + output, + this.localisationService.getText("ragfair-unable_to_pay_commission_fee", tax), + ); return true; } @@ -454,7 +519,7 @@ export class RagfairController return false; } - + if (!offerRequest.requirements) { errorMessage = this.localisationService.getText("ragfair-unable_to_place_offer_with_no_requirements"); @@ -462,13 +527,13 @@ export class RagfairController return false; } - + return true; } /** * Get the handbook price in roubles for the items being listed - * @param requirements + * @param requirements * @returns Rouble price */ protected calculateRequirementsPriceInRub(requirements: Requirement[]): number @@ -477,37 +542,44 @@ export class RagfairController for (const item of requirements) { const requestedItemTpl = item._tpl; - + if (this.paymentHelper.isMoneyTpl(requestedItemTpl)) { requirementsPriceInRub += this.handbookHelper.inRUB(item.count, requestedItemTpl); } else { - requirementsPriceInRub += this.ragfairPriceService.getDynamicPriceForItem(requestedItemTpl) * item.count; + requirementsPriceInRub += this.ragfairPriceService.getDynamicPriceForItem(requestedItemTpl) * + item.count; } } - + return requirementsPriceInRub; } /** - * Using item ids from flea offer request, find corrispnding items from player inventory and return as array + * Using item ids from flea offer request, find corresponding items from player inventory and return as array * @param pmcData Player profile * @param itemIdsFromFleaOfferRequest Ids from request * @param errorMessage if item is not found, add error message to this parameter * @returns Array of items from player inventory */ - protected getItemsToListOnFleaFromInventory(pmcData: IPmcData, itemIdsFromFleaOfferRequest: string[], errorMessage: string): Item[] + protected getItemsToListOnFleaFromInventory( + pmcData: IPmcData, + itemIdsFromFleaOfferRequest: string[], + errorMessage: string, + ): Item[] { const itemsToReturn = []; // Count how many items are being sold and multiply the requested amount accordingly for (const itemId of itemIdsFromFleaOfferRequest) { - let item = pmcData.Inventory.items.find(i => i._id === itemId); + let item = pmcData.Inventory.items.find((i) => i._id === itemId); if (!item) { - errorMessage = this.localisationService.getText("ragfair-unable_to_find_item_in_inventory", {id: itemId}); + errorMessage = this.localisationService.getText("ragfair-unable_to_find_item_in_inventory", { + id: itemId, + }); this.logger.error(errorMessage); return null; @@ -528,28 +600,34 @@ export class RagfairController return itemsToReturn; } - public createPlayerOffer(profile: IAkiProfile, requirements: Requirement[], items: Item[], sellInOnePiece: boolean, amountToSend: number): IRagfairOffer + public createPlayerOffer( + profile: IAkiProfile, + requirements: Requirement[], + items: Item[], + sellInOnePiece: boolean, + amountToSend: number, + ): IRagfairOffer { const loyalLevel = 1; - const formattedItems: Item[] = items.map(item => + const formattedItems: Item[] = items.map((item) => { - const isChild = items.find(it => it._id === item.parentId); + const isChild = items.find((it) => it._id === item.parentId); return { _id: item._id, _tpl: item._tpl, - parentId: (isChild) ? item.parentId : "hideout", - slotId: (isChild) ? item.slotId : "hideout", - upd: item.upd + parentId: isChild ? item.parentId : "hideout", + slotId: isChild ? item.slotId : "hideout", + upd: item.upd, }; }); - const formattedRequirements: IBarterScheme[] = requirements.map(item => + const formattedRequirements: IBarterScheme[] = requirements.map((item) => { return { _tpl: item._tpl, count: item.count, - onlyFunctional: item.onlyFunctional + onlyFunctional: item.onlyFunctional, }; }); @@ -559,7 +637,7 @@ export class RagfairController formattedItems, formattedRequirements, loyalLevel, - sellInOnePiece + sellInOnePiece, ); } @@ -586,21 +664,32 @@ export class RagfairController const offers = pmcData.RagfairInfo.offers; if (!offers) { - this.logger.warning(this.localisationService.getText("ragfair-unable_to_remove_offer_not_found_in_profile", {profileId: sessionID, offerId: offerId})); + this.logger.warning( + this.localisationService.getText("ragfair-unable_to_remove_offer_not_found_in_profile", { + profileId: sessionID, + offerId: offerId, + }), + ); pmcData.RagfairInfo.offers = []; } - const index = offers.findIndex(offer => offer._id === offerId); + const index = offers.findIndex((offer) => offer._id === offerId); if (index === -1) { - this.logger.error(this.localisationService.getText("ragfair-offer_not_found_in_profile", {offerId: offerId})); - return this.httpResponse.appendErrorToOutput(this.eventOutputHolder.getOutput(sessionID), this.localisationService.getText("ragfair-offer_not_found_in_profile_short")); + this.logger.error( + this.localisationService.getText("ragfair-offer_not_found_in_profile", {offerId: offerId}), + ); + return this.httpResponse.appendErrorToOutput( + this.eventOutputHolder.getOutput(sessionID), + this.localisationService.getText("ragfair-offer_not_found_in_profile_short"), + ); } - const differenceInSeconds = (offers[index].endTime - this.timeUtil.getTimestamp()); - if (differenceInSeconds > this.ragfairConfig.sell.expireSeconds)// expireSeconds Default is 71 seconds + const differenceInSeconds = offers[index].endTime - this.timeUtil.getTimestamp(); + if (differenceInSeconds > this.ragfairConfig.sell.expireSeconds) { + // expireSeconds Default is 71 seconds const newEndTime = this.ragfairConfig.sell.expireSeconds + this.timeUtil.getTimestamp(); offers[index].endTime = Math.round(newEndTime); } @@ -613,26 +702,42 @@ export class RagfairController let output = this.eventOutputHolder.getOutput(sessionID); const pmcData = this.saveServer.getProfile(sessionID).characters.pmc; const offers = pmcData.RagfairInfo.offers; - const index = offers.findIndex(offer => offer._id === info.offerId); + const index = offers.findIndex((offer) => offer._id === info.offerId); const secondsToAdd = info.renewalTime * TimeUtil.oneHourAsSeconds; if (index === -1) { - this.logger.warning(this.localisationService.getText("ragfair-offer_not_found_in_profile", {offerId: info.offerId})); - return this.httpResponse.appendErrorToOutput(this.eventOutputHolder.getOutput(sessionID), this.localisationService.getText("ragfair-offer_not_found_in_profile_short")); + this.logger.warning( + this.localisationService.getText("ragfair-offer_not_found_in_profile", {offerId: info.offerId}), + ); + return this.httpResponse.appendErrorToOutput( + this.eventOutputHolder.getOutput(sessionID), + this.localisationService.getText("ragfair-offer_not_found_in_profile_short"), + ); } // MOD: Pay flea market fee if (this.ragfairConfig.sell.fees) { - const count = offers[index].sellInOnePiece ? 1 : offers[index].items.reduce((sum, item) => sum += item.upd.StackObjectsCount, 0); - const tax = this.ragfairTaxService.calculateTax(offers[index].items[0], this.profileHelper.getPmcProfile(sessionID), offers[index].requirementsCost, count, offers[index].sellInOnePiece); + const count = offers[index].sellInOnePiece ? + 1 : + offers[index].items.reduce((sum, item) => sum += item.upd.StackObjectsCount, 0); + const tax = this.ragfairTaxService.calculateTax( + offers[index].items[0], + this.profileHelper.getPmcProfile(sessionID), + offers[index].requirementsCost, + count, + offers[index].sellInOnePiece, + ); const request = this.createBuyTradeRequestObject("RUB", tax); output = this.paymentService.payMoney(pmcData, request, sessionID, output); if (output.warnings.length > 0) { - return this.httpResponse.appendErrorToOutput(output, this.localisationService.getText("ragfair-unable_to_pay_commission_fee")); + return this.httpResponse.appendErrorToOutput( + output, + this.localisationService.getText("ragfair-unable_to_pay_commission_fee"), + ); } } @@ -652,19 +757,16 @@ export class RagfairController return { tid: "ragfair", Action: "TradingConfirm", - // eslint-disable-next-line @typescript-eslint/naming-convention scheme_items: [ { id: this.paymentHelper.getCurrency(currency), - count: Math.round(value) - } + count: Math.round(value), + }, ], type: "", - // eslint-disable-next-line @typescript-eslint/naming-convention item_id: "", count: 0, - // eslint-disable-next-line @typescript-eslint/naming-convention - scheme_id: 0 + scheme_id: 0, }; } -} \ No newline at end of file +} diff --git a/project/src/controllers/RepairController.ts b/project/src/controllers/RepairController.ts index 37fc25a6..0c5607f0 100644 --- a/project/src/controllers/RepairController.ts +++ b/project/src/controllers/RepairController.ts @@ -27,9 +27,9 @@ export class RepairController @inject("TraderHelper") protected traderHelper: TraderHelper, @inject("PaymentService") protected paymentService: PaymentService, @inject("RepairHelper") protected repairHelper: RepairHelper, - @inject("RepairService") protected repairService: RepairService + @inject("RepairService") protected repairService: RepairService, ) - { } + {} /** * Handle TraderRepair event @@ -39,16 +39,27 @@ export class RepairController * @param pmcData player profile * @returns item event router action */ - public traderRepair(sessionID: string, body: ITraderRepairActionDataRequest, pmcData: IPmcData): IItemEventRouterResponse + public traderRepair( + sessionID: string, + body: ITraderRepairActionDataRequest, + pmcData: IPmcData, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionID); - + // find the item to repair for (const repairItem of body.repairItems) { const repairDetails = this.repairService.repairItemByTrader(sessionID, pmcData, repairItem, body.tid); - this.repairService.payForRepair(sessionID, pmcData, repairItem._id, repairDetails.repairCost, body.tid, output); + this.repairService.payForRepair( + sessionID, + pmcData, + repairItem._id, + repairDetails.repairCost, + body.tid, + output, + ); if (output.warnings.length > 0) { @@ -78,7 +89,13 @@ export class RepairController const output = this.eventOutputHolder.getOutput(sessionID); // repair item - const repairDetails = this.repairService.repairItemByKit(sessionID, pmcData, body.repairKitsInfo, body.target, output); + const repairDetails = this.repairService.repairItemByKit( + sessionID, + pmcData, + body.repairKitsInfo, + body.target, + output, + ); this.repairService.addBuffToItem(repairDetails, pmcData); @@ -90,4 +107,4 @@ export class RepairController return output; } -} \ No newline at end of file +} diff --git a/project/src/controllers/RepeatableQuestController.ts b/project/src/controllers/RepeatableQuestController.ts index e9337c0a..531fae50 100644 --- a/project/src/controllers/RepeatableQuestController.ts +++ b/project/src/controllers/RepeatableQuestController.ts @@ -7,7 +7,11 @@ import { RagfairServerHelper } from "@spt-aki/helpers/RagfairServerHelper"; import { RepeatableQuestHelper } from "@spt-aki/helpers/RepeatableQuestHelper"; import { IEmptyRequestData } from "@spt-aki/models/eft/common/IEmptyRequestData"; import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; -import { IChangeRequirement, IPmcDataRepeatableQuest, IRepeatableQuest } from "@spt-aki/models/eft/common/tables/IRepeatableQuests"; +import { + IChangeRequirement, + IPmcDataRepeatableQuest, + IRepeatableQuest, +} from "@spt-aki/models/eft/common/tables/IRepeatableQuests"; import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; import { IRepeatableQuestChangeRequest } from "@spt-aki/models/eft/quests/IRepeatableQuestChangeRequest"; import { ConfigTypes } from "@spt-aki/models/enums/ConfigTypes"; @@ -50,13 +54,12 @@ export class RepeatableQuestController @inject("RepeatableQuestGenerator") protected repeatableQuestGenerator: RepeatableQuestGenerator, @inject("RepeatableQuestHelper") protected repeatableQuestHelper: RepeatableQuestHelper, @inject("QuestHelper") protected questHelper: QuestHelper, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.questConfig = this.configServer.getConfig(ConfigTypes.QUEST); } - /** * Handle client/repeatalbeQuests/activityPeriods * Returns an array of objects in the format of repeatable quests to the client. @@ -69,8 +72,8 @@ export class RepeatableQuestController * } * * The method checks if the player level requirement for repeatable quests (e.g. daily lvl5, weekly lvl15) is met and if the previously active quests - * are still valid. This ischecked by endTime persisted in profile accordning to the resetTime configured for each repeatable kind (daily, weekly) - * in QuestCondig.js + * are still valid. This is checked by endTime persisted in profile according to the resetTime configured for each repeatable kind (daily, weekly) + * in QuestConfig.js * * If the condition is met, new repeatableQuests are created, old quests (which are persisted in the profile.RepeatableQuests[i].activeQuests) are * moved to profile.RepeatableQuests[i].inactiveQuests. This memory is required to get rid of old repeatable quest data in the profile, otherwise @@ -78,26 +81,28 @@ export class RepeatableQuestController * (if the are on "Succeed" but not "Completed" we keep them, to allow the player to complete them and get the rewards) * The new quests generated are again persisted in profile.RepeatableQuests * - * * @param {string} sessionId Player's session id - * @returns {array} array of "repeatableQuestObjects" as descibed above + * @returns {array} array of "repeatableQuestObjects" as described above */ public getClientRepeatableQuests(_info: IEmptyRequestData, sessionID: string): IPmcDataRepeatableQuest[] { const returnData: Array = []; const pmcData = this.profileHelper.getPmcProfile(sessionID); const time = this.timeUtil.getTimestamp(); - const scavQuestUnlocked = pmcData?.Hideout?.Areas?.find(hideoutArea => hideoutArea.type === HideoutAreas.INTEL_CENTER)?.level >= 1; - + const scavQuestUnlocked = + pmcData?.Hideout?.Areas?.find((hideoutArea) => hideoutArea.type === HideoutAreas.INTEL_CENTER)?.level >= 1; + // Daily / weekly / Daily_Savage for (const repeatableConfig of this.questConfig.repeatableQuests) { // get daily/weekly data from profile, add empty object if missing const currentRepeatableQuestType = this.getRepeatableQuestSubTypeFromProfile(repeatableConfig, pmcData); - - if (repeatableConfig.side === "Pmc" - && pmcData.Info.Level >= repeatableConfig.minPlayerLevel - || repeatableConfig.side === "Scav" && scavQuestUnlocked) + + if ( + repeatableConfig.side === "Pmc" && + pmcData.Info.Level >= repeatableConfig.minPlayerLevel || + repeatableConfig.side === "Scav" && scavQuestUnlocked + ) { if (time > currentRepeatableQuestType.endTime - 1) { @@ -110,22 +115,24 @@ export class RepeatableQuestController // after a raid (the client seems to keep quests internally and we want to get rid of old repeatable quests) // and remove them from the PMC's Quests and RepeatableQuests[i].activeQuests const questsToKeep = []; - //for (let i = 0; i < currentRepeatable.activeQuests.length; i++) + // for (let i = 0; i < currentRepeatable.activeQuests.length; i++) for (const activeQuest of currentRepeatableQuestType.activeQuests) { // check if the quest is ready to be completed, if so, don't remove it - const quest = pmcData.Quests.filter(q => q.qid === activeQuest._id); + const quest = pmcData.Quests.filter((q) => q.qid === activeQuest._id); if (quest.length > 0) { if (quest[0].status === QuestStatus.AvailableForFinish) { questsToKeep.push(activeQuest); - this.logger.debug(`Keeping repeatable quest ${activeQuest._id} in activeQuests since it is available to AvailableForFinish`); + this.logger.debug( + `Keeping repeatable quest ${activeQuest._id} in activeQuests since it is available to AvailableForFinish`, + ); continue; } } this.profileFixerService.removeDanglingConditionCounters(pmcData); - pmcData.Quests = pmcData.Quests.filter(q => q.qid !== activeQuest._id); + pmcData.Quests = pmcData.Quests.filter((q) => q.qid !== activeQuest._id); currentRepeatableQuestType.inactiveQuests.push(activeQuest); } currentRepeatableQuestType.activeQuests = questsToKeep; @@ -144,12 +151,14 @@ export class RepeatableQuestController pmcData.Info.Level, pmcData.TradersInfo, questTypePool, - repeatableConfig + repeatableConfig, ); lifeline++; if (lifeline > 10) { - this.logger.debug("We were stuck in repeatable quest generation. This should never happen. Please report"); + this.logger.debug( + "We were stuck in repeatable quest generation. This should never happen. Please report", + ); break; } } @@ -174,7 +183,7 @@ export class RepeatableQuestController { currentRepeatableQuestType.changeRequirement[quest._id] = { changeCost: quest.changeCost, - changeStandingCost: this.randomUtil.getArrayValue([0, 0.01]) + changeStandingCost: this.randomUtil.getArrayValue([0, 0.01]), }; } @@ -184,7 +193,7 @@ export class RepeatableQuestController endTime: currentRepeatableQuestType.endTime, activeQuests: currentRepeatableQuestType.activeQuests, inactiveQuests: currentRepeatableQuestType.inactiveQuests, - changeRequirement: currentRepeatableQuestType.changeRequirement + changeRequirement: currentRepeatableQuestType.changeRequirement, }); } @@ -199,10 +208,15 @@ export class RepeatableQuestController */ protected getQuestCount(repeatableConfig: IRepeatableQuestConfig, pmcData: IPmcData): number { - if (repeatableConfig.name.toLowerCase() === "daily" && this.profileHelper.hasEliteSkillLevel(SkillTypes.CHARISMA, pmcData)) + if ( + repeatableConfig.name.toLowerCase() === "daily" && + this.profileHelper.hasEliteSkillLevel(SkillTypes.CHARISMA, pmcData) + ) { // Elite charisma skill gives extra daily quest(s) - return repeatableConfig.numQuests + this.databaseServer.getTables().globals.config.SkillsSettings.Charisma.BonusSettings.EliteBonusSettings.RepeatableQuestExtraCount; + return repeatableConfig.numQuests + + this.databaseServer.getTables().globals.config.SkillsSettings.Charisma.BonusSettings.EliteBonusSettings + .RepeatableQuestExtraCount; } return repeatableConfig.numQuests; @@ -214,10 +228,13 @@ export class RepeatableQuestController * @param pmcData Profile to search * @returns IPmcDataRepeatableQuest */ - protected getRepeatableQuestSubTypeFromProfile(repeatableConfig: IRepeatableQuestConfig, pmcData: IPmcData): IPmcDataRepeatableQuest + protected getRepeatableQuestSubTypeFromProfile( + repeatableConfig: IRepeatableQuestConfig, + pmcData: IPmcData, + ): IPmcDataRepeatableQuest { // Get from profile, add if missing - let repeatableQuestDetails = pmcData.RepeatableQuests.find(x => x.name === repeatableConfig.name); + let repeatableQuestDetails = pmcData.RepeatableQuests.find((x) => x.name === repeatableConfig.name); if (!repeatableQuestDetails) { repeatableQuestDetails = { @@ -226,7 +243,7 @@ export class RepeatableQuestController activeQuests: [], inactiveQuests: [], endTime: 0, - changeRequirement: {} + changeRequirement: {}, }; // Add base object that holds repeatable data to profile @@ -297,16 +314,16 @@ export class RepeatableQuestController // Target is boss if (probabilityObject.data.isBoss) { - questPool.pool.Elimination.targets[probabilityObject.key] = { locations: ["any"] }; + questPool.pool.Elimination.targets[probabilityObject.key] = {locations: ["any"]}; } else { const possibleLocations = Object.keys(repeatableConfig.locations); - // Set possible locations for elimination task, ift arget is savage, exclude labs from locations - questPool.pool.Elimination.targets[probabilityObject.key] = (probabilityObject.key === "Savage") - ? { locations: possibleLocations.filter(x => x !== "laboratory")} - : { locations: possibleLocations }; + // Set possible locations for elimination task, if target is savage, exclude labs from locations + questPool.pool.Elimination.targets[probabilityObject.key] = (probabilityObject.key === "Savage") ? + {locations: possibleLocations.filter((x) => x !== "laboratory")} : + {locations: possibleLocations}; } } @@ -319,15 +336,15 @@ export class RepeatableQuestController types: repeatableConfig.types.slice(), pool: { Exploration: { - locations: {} + locations: {}, }, Elimination: { - targets: {} + targets: {}, }, Pickup: { - locations: {} - } - } + locations: {}, + }, + }, }; } @@ -355,7 +372,11 @@ export class RepeatableQuestController /** * Handle RepeatableQuestChange event */ - public changeRepeatableQuest(pmcData: IPmcData, changeRequest: IRepeatableQuestChangeRequest, sessionID: string): IItemEventRouterResponse + public changeRepeatableQuest( + pmcData: IPmcData, + changeRequest: IRepeatableQuestChangeRequest, + sessionID: string, + ): IItemEventRouterResponse { let repeatableToChange: IPmcDataRepeatableQuest; let changeRequirement: IChangeRequirement; @@ -367,24 +388,29 @@ export class RepeatableQuestController for (const currentRepeatablePool of pmcData.RepeatableQuests) { // Check for existing quest in (daily/weekly/scav arrays) - const questToReplace = currentRepeatablePool.activeQuests.find(x => x._id === changeRequest.qid); + const questToReplace = currentRepeatablePool.activeQuests.find((x) => x._id === changeRequest.qid); if (!questToReplace) { continue; } - + // Save for later standing loss calculation replacedQuestTraderId = questToReplace.traderId; // Update active quests to exclude the quest we're replacing - currentRepeatablePool.activeQuests = currentRepeatablePool.activeQuests.filter(x => x._id !== changeRequest.qid); + currentRepeatablePool.activeQuests = currentRepeatablePool.activeQuests.filter((x) => + x._id !== changeRequest.qid + ); // Get cost to replace existing quest changeRequirement = this.jsonUtil.clone(currentRepeatablePool.changeRequirement[changeRequest.qid]); delete currentRepeatablePool.changeRequirement[changeRequest.qid]; - // TODO: somehow we need to reduce the questPool by the currently active quests (for all repeatables) - - const repeatableConfig = this.questConfig.repeatableQuests.find(x => x.name === currentRepeatablePool.name); + + // TODO: somehow we need to reduce the questPool by the currently active quests (for all repeatable) + + const repeatableConfig = this.questConfig.repeatableQuests.find((x) => + x.name === currentRepeatablePool.name + ); const questTypePool = this.generateQuestPool(repeatableConfig, pmcData.Info.Level); const newRepeatableQuest = this.attemptToGenerateRepeatableQuest(pmcData, questTypePool, repeatableConfig); if (newRepeatableQuest) @@ -394,16 +420,19 @@ export class RepeatableQuestController currentRepeatablePool.activeQuests.push(newRepeatableQuest); currentRepeatablePool.changeRequirement[newRepeatableQuest._id] = { changeCost: newRepeatableQuest.changeCost, - changeStandingCost: this.randomUtil.getArrayValue([0, 0.01]) + changeStandingCost: this.randomUtil.getArrayValue([0, 0.01]), }; const fullProfile = this.profileHelper.getFullProfile(sessionID); // Find quest we're replacing in pmc profile quests array and remove it this.questHelper.findAndRemoveQuestFromArrayIfExists(questToReplace._id, pmcData.Quests); - + // Find quest we're replacing in scav profile quests array and remove it - this.questHelper.findAndRemoveQuestFromArrayIfExists(questToReplace._id, fullProfile.characters.scav?.Quests ?? []); + this.questHelper.findAndRemoveQuestFromArrayIfExists( + questToReplace._id, + fullProfile.characters.scav?.Quests ?? [], + ); } // Found and replaced the quest in current repeatable @@ -442,7 +471,11 @@ export class RepeatableQuestController return output; } - protected attemptToGenerateRepeatableQuest(pmcData: IPmcData, questTypePool: IQuestTypePool, repeatableConfig: IRepeatableQuestConfig): IRepeatableQuest + protected attemptToGenerateRepeatableQuest( + pmcData: IPmcData, + questTypePool: IQuestTypePool, + repeatableConfig: IRepeatableQuestConfig, + ): IRepeatableQuest { let newRepeatableQuest: IRepeatableQuest = null; let attemptsToGenerateQuest = 0; @@ -452,16 +485,17 @@ export class RepeatableQuestController pmcData.Info.Level, pmcData.TradersInfo, questTypePool, - repeatableConfig + repeatableConfig, ); attemptsToGenerateQuest++; if (attemptsToGenerateQuest > 10) { - this.logger.debug("We were stuck in repeatable quest generation. This should never happen. Please report"); + this.logger.debug( + "We were stuck in repeatable quest generation. This should never happen. Please report", + ); break; } } - return newRepeatableQuest; } } diff --git a/project/src/controllers/TradeController.ts b/project/src/controllers/TradeController.ts index c891fd97..db399e4b 100644 --- a/project/src/controllers/TradeController.ts +++ b/project/src/controllers/TradeController.ts @@ -29,7 +29,7 @@ import { HttpResponseUtil } from "@spt-aki/utils/HttpResponseUtil"; import { JsonUtil } from "@spt-aki/utils/JsonUtil"; @injectable() -class TradeController +export class TradeController { protected ragfairConfig: IRagfairConfig; protected traderConfig: ITraderConfig; @@ -46,7 +46,7 @@ class TradeController @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("RagfairPriceService") protected ragfairPriceService: RagfairPriceService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); @@ -54,34 +54,56 @@ class TradeController } /** Handle TradingConfirm event */ - public confirmTrading(pmcData: IPmcData, request: IProcessBaseTradeRequestData, sessionID: string): IItemEventRouterResponse + public confirmTrading( + pmcData: IPmcData, + request: IProcessBaseTradeRequestData, + sessionID: string, + ): IItemEventRouterResponse { return this.confirmTradingInternal(pmcData, request, sessionID, this.traderConfig.purchasesAreFoundInRaid); } /** Handle RagFairBuyOffer event */ - public confirmRagfairTrading(pmcData: IPmcData, body: IProcessRagfairTradeRequestData, sessionID: string): IItemEventRouterResponse + public confirmRagfairTrading( + pmcData: IPmcData, + body: IProcessRagfairTradeRequestData, + sessionID: string, + ): IItemEventRouterResponse { let output = this.eventOutputHolder.getOutput(sessionID); for (const offer of body.offers) { const fleaOffer = this.ragfairServer.getOffer(offer.id); - if (!fleaOffer) + if (!fleaOffer) { - return this.httpResponse.appendErrorToOutput(output, `Offer with ID ${offer.id} not found`, BackendErrorCodes.OFFERNOTFOUND); + return this.httpResponse.appendErrorToOutput( + output, + `Offer with ID ${offer.id} not found`, + BackendErrorCodes.OFFERNOTFOUND, + ); } if (offer.count === 0) { - const errorMessage = this.localisationService.getText("ragfair-unable_to_purchase_0_count_item", this.itemHelper.getItem(fleaOffer.items[0]._tpl)[1]._name); + const errorMessage = this.localisationService.getText( + "ragfair-unable_to_purchase_0_count_item", + this.itemHelper.getItem(fleaOffer.items[0]._tpl)[1]._name, + ); return this.httpResponse.appendErrorToOutput(output, errorMessage, BackendErrorCodes.OFFEROUTOFSTOCK); } // Skip buying items when player doesn't have necessary loyalty - if (fleaOffer.user.memberType === MemberCategory.TRADER && fleaOffer.loyaltyLevel > pmcData.TradersInfo[fleaOffer.user.id].loyaltyLevel) + if ( + fleaOffer.user.memberType === MemberCategory.TRADER && + fleaOffer.loyaltyLevel > pmcData.TradersInfo[fleaOffer.user.id].loyaltyLevel + ) { - this.logger.debug(`Unable to buy item: ${fleaOffer.items[0]._tpl} from trader: ${fleaOffer.user.id} as loyalty level too low, skipping`); + this.logger.debug( + `Unable to buy item: ${ + fleaOffer.items[0]._tpl + } from trader: ${fleaOffer.user.id} as loyalty level too low, skipping`, + ); continue; } @@ -91,17 +113,21 @@ class TradeController Action: "TradingConfirm", type: "buy_from_trader", tid: (fleaOffer.user.memberType !== MemberCategory.TRADER) ? "ragfair" : fleaOffer.user.id, - // eslint-disable-next-line @typescript-eslint/naming-convention item_id: fleaOffer.root, count: offer.count, - // eslint-disable-next-line @typescript-eslint/naming-convention scheme_id: 0, - // eslint-disable-next-line @typescript-eslint/naming-convention - scheme_items: offer.items + scheme_items: offer.items, }; - // confirmTrading() must occur prior to removing the offer stack, otherwise item inside offer doesn't exist for confirmTrading() to use - output = this.confirmTradingInternal(pmcData, buyData, sessionID, this.ragfairConfig.dynamic.purchasesAreFoundInRaid, fleaOffer.items[0].upd); + // confirmTrading() must occur prior to removing the offer stack, otherwise item inside offer doesn't exist + // for confirmTrading() to use + output = this.confirmTradingInternal( + pmcData, + buyData, + sessionID, + this.ragfairConfig.dynamic.purchasesAreFoundInRaid, + fleaOffer.items[0].upd, + ); if (fleaOffer.user.memberType !== MemberCategory.TRADER) { // remove player item offer stack @@ -113,30 +139,42 @@ class TradeController } /** Handle SellAllFromSavage event */ - public sellScavItemsToFence(pmcData: IPmcData, body: ISellScavItemsToFenceRequestData, sessionId: string): IItemEventRouterResponse + public sellScavItemsToFence( + pmcData: IPmcData, + body: ISellScavItemsToFenceRequestData, + sessionId: string, + ): IItemEventRouterResponse { const scavProfile = this.profileHelper.getFullProfile(sessionId)?.characters?.scav; if (!scavProfile) { - return this.httpResponse.appendErrorToOutput(this.eventOutputHolder.getOutput(sessionId), `Profile ${body.fromOwner.id} has no scav account`); + return this.httpResponse.appendErrorToOutput( + this.eventOutputHolder.getOutput(sessionId), + `Profile ${body.fromOwner.id} has no scav account`, + ); } return this.sellInventoryToTrader(sessionId, scavProfile, pmcData, Traders.FENCE); } /** - * Sell all sellable items to a trader from inventory + * Sell all items (that can be sold) to a trader from inventory * WILL DELETE ITEMS FROM INVENTORY + CHILDREN OF ITEMS SOLD * @param sessionId Session id - * @param profileWithItemsToSell Profile with items to be sold to trader + * @param profileWithItemsToSell Profile with items to be sold to trader * @param profileThatGetsMoney Profile that gets the money after selling items * @param trader Trader to sell items to * @returns IItemEventRouterResponse */ - protected sellInventoryToTrader(sessionId: string, profileWithItemsToSell: IPmcData, profileThatGetsMoney: IPmcData, trader: Traders): IItemEventRouterResponse + protected sellInventoryToTrader( + sessionId: string, + profileWithItemsToSell: IPmcData, + profileThatGetsMoney: IPmcData, + trader: Traders, + ): IItemEventRouterResponse { const handbookPrices = this.ragfairPriceService.getAllStaticPrices(); - // TODO, apply trader sell bonuses? + // TODO: apply trader sell bonuses? const traderDetails = this.traderHelper.getTrader(trader, sessionId); // Prep request object @@ -145,16 +183,23 @@ class TradeController type: "sell_to_trader", tid: trader, price: 0, - items: [] + items: [], }; // Get all base items that scav has (primaryweapon/backpack/pockets etc) // Add items that trader will buy (only sell items that have the container as parent) to request object - const containerAndEquipmentItems = profileWithItemsToSell.Inventory.items.filter(x => x.parentId === profileWithItemsToSell.Inventory.equipment); + const containerAndEquipmentItems = profileWithItemsToSell.Inventory.items.filter((x) => + x.parentId === profileWithItemsToSell.Inventory.equipment + ); for (const itemToSell of containerAndEquipmentItems) { // Increment sell price in request - sellRequest.price += this.getPriceOfItemAndChildren(itemToSell._id, profileWithItemsToSell.Inventory.items, handbookPrices, traderDetails); + sellRequest.price += this.getPriceOfItemAndChildren( + itemToSell._id, + profileWithItemsToSell.Inventory.items, + handbookPrices, + traderDetails, + ); // Add item details to request // eslint-disable-next-line @typescript-eslint/naming-convention @@ -172,7 +217,12 @@ class TradeController * @param traderDetails Trader being sold to to perform buy category check against * @returns Rouble price */ - protected getPriceOfItemAndChildren(parentItemId: string, items: Item[], handbookPrices: Record, traderDetails: ITraderBase): number + protected getPriceOfItemAndChildren( + parentItemId: string, + items: Item[], + handbookPrices: Record, + traderDetails: ITraderBase, + ): number { const itemWithChildren = this.itemHelper.findAndReturnChildrenAsItems(items, parentItemId); @@ -180,9 +230,12 @@ class TradeController for (const itemToSell of itemWithChildren) { const itemDetails = this.itemHelper.getItem(itemToSell._tpl); - if (!(itemDetails[0] && this.itemHelper.isOfBaseclasses(itemDetails[1]._id, traderDetails.items_buy.category))) + if ( + !(itemDetails[0] && + this.itemHelper.isOfBaseclasses(itemDetails[1]._id, traderDetails.items_buy.category)) + ) { - // Skip if tpl isnt item OR item doesn't fulfill match traders buy categories + // Skip if tpl isn't item OR item doesn't fulfill match traders buy categories continue; } @@ -193,7 +246,13 @@ class TradeController return totalPrice; } - protected confirmTradingInternal(pmcData: IPmcData, body: IProcessBaseTradeRequestData, sessionID: string, foundInRaid = false, upd: Upd = null): IItemEventRouterResponse + protected confirmTradingInternal( + pmcData: IPmcData, + body: IProcessBaseTradeRequestData, + sessionID: string, + foundInRaid = false, + upd: Upd = null, + ): IItemEventRouterResponse { // buying if (body.type === "buy_from_trader") @@ -212,6 +271,3 @@ class TradeController return null; } } - -export { TradeController }; - diff --git a/project/src/controllers/TraderController.ts b/project/src/controllers/TraderController.ts index de7fc77d..29301929 100644 --- a/project/src/controllers/TraderController.ts +++ b/project/src/controllers/TraderController.ts @@ -23,12 +23,13 @@ export class TraderController @inject("ProfileHelper") protected profileHelper: ProfileHelper, @inject("TraderHelper") protected traderHelper: TraderHelper, @inject("TraderAssortService") protected traderAssortService: TraderAssortService, - @inject("TraderPurchasePersisterService") protected traderPurchasePersisterService: TraderPurchasePersisterService, + @inject("TraderPurchasePersisterService") protected traderPurchasePersisterService: + TraderPurchasePersisterService, @inject("FenceService") protected fenceService: FenceService, @inject("FenceBaseAssortGenerator") protected fenceBaseAssortGenerator: FenceBaseAssortGenerator, - @inject("JsonUtil") protected jsonUtil: JsonUtil + @inject("JsonUtil") protected jsonUtil: JsonUtil, ) - { } + {} /** * Runs when onLoad event is fired @@ -93,7 +94,7 @@ export class TraderController } const trader = this.databaseServer.getTables().traders[traderId]; - + // trader needs to be refreshed if (this.traderAssortHelper.traderAssortsHaveExpired(traderId)) { @@ -132,7 +133,7 @@ export class TraderController } } - return traders.sort((a, b) => this.sortByTraderId(a,b)); + return traders.sort((a, b) => this.sortByTraderId(a, b)); } /** @@ -167,4 +168,4 @@ export class TraderController { return this.traderAssortHelper.getAssort(sessionId, traderId); } -} \ No newline at end of file +} diff --git a/project/src/controllers/WeatherController.ts b/project/src/controllers/WeatherController.ts index 216424f6..eca193db 100644 --- a/project/src/controllers/WeatherController.ts +++ b/project/src/controllers/WeatherController.ts @@ -15,7 +15,7 @@ export class WeatherController constructor( @inject("WeatherGenerator") protected weatherGenerator: WeatherGenerator, @inject("WinstonLogger") protected logger: ILogger, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.weatherConfig = this.configServer.getConfig(ConfigTypes.WEATHER); @@ -28,7 +28,7 @@ export class WeatherController acceleration: 0, time: "", date: "", - weather: null + weather: null, }; result = this.weatherGenerator.calculateGameTime(result); @@ -45,4 +45,4 @@ export class WeatherController { return this.weatherGenerator.getInRaidTime(new Date()); } -} \ No newline at end of file +} diff --git a/project/src/controllers/WishlistController.ts b/project/src/controllers/WishlistController.ts index eaa7d8e4..aae3f9e5 100644 --- a/project/src/controllers/WishlistController.ts +++ b/project/src/controllers/WishlistController.ts @@ -9,16 +9,16 @@ import { EventOutputHolder } from "@spt-aki/routers/EventOutputHolder"; export class WishlistController { constructor( - @inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder + @inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder, ) - { } + {} /** Handle AddToWishList */ public addToWishList(pmcData: IPmcData, body: IWishlistActionData, sessionID: string): IItemEventRouterResponse { for (const item in pmcData.WishList) { - // don't add the item + // Don't add the item if (pmcData.WishList[item] === body.templateId) { return this.eventOutputHolder.getOutput(sessionID); @@ -43,4 +43,4 @@ export class WishlistController return this.eventOutputHolder.getOutput(sessionID); } -} \ No newline at end of file +} From 3ef51e771b97b5d2ec55c627c29e040bb01d6fa6 Mon Sep 17 00:00:00 2001 From: Refringe Date: Fri, 10 Nov 2023 16:58:55 -0500 Subject: [PATCH 24/41] Formatting of DI classes. --- project/Server.code-workspace | 2 + project/src/di/Container.ts | 742 +++++++++++++++++----------------- project/src/di/OnLoad.ts | 4 +- project/src/di/OnUpdate.ts | 6 +- project/src/di/Router.ts | 63 ++- project/src/di/Serializer.ts | 6 +- 6 files changed, 419 insertions(+), 404 deletions(-) diff --git a/project/Server.code-workspace b/project/Server.code-workspace index 2c833b46..b989ba88 100644 --- a/project/Server.code-workspace +++ b/project/Server.code-workspace @@ -74,9 +74,11 @@ "Tarkov", "toggleable", "tooshort", + "Ubgl", "unrestartable", "usec", "userbuilds", + "weapongen", "Wishlist" ] } diff --git a/project/src/di/Container.ts b/project/src/di/Container.ts index 41e578d3..9e13eb14 100644 --- a/project/src/di/Container.ts +++ b/project/src/di/Container.ts @@ -69,17 +69,17 @@ import { BotWeaponGenerator } from "@spt-aki/generators/BotWeaponGenerator"; import { FenceBaseAssortGenerator } from "@spt-aki/generators/FenceBaseAssortGenerator"; import { LocationGenerator } from "@spt-aki/generators/LocationGenerator"; import { LootGenerator } from "@spt-aki/generators/LootGenerator"; -import { PMCLootGenerator } from "@spt-aki/generators/PMCLootGenerator"; import { PlayerScavGenerator } from "@spt-aki/generators/PlayerScavGenerator"; +import { PMCLootGenerator } from "@spt-aki/generators/PMCLootGenerator"; import { RagfairAssortGenerator } from "@spt-aki/generators/RagfairAssortGenerator"; import { RagfairOfferGenerator } from "@spt-aki/generators/RagfairOfferGenerator"; import { RepeatableQuestGenerator } from "@spt-aki/generators/RepeatableQuestGenerator"; import { ScavCaseRewardGenerator } from "@spt-aki/generators/ScavCaseRewardGenerator"; -import { WeatherGenerator } from "@spt-aki/generators/WeatherGenerator"; import { BarrelInventoryMagGen } from "@spt-aki/generators/weapongen/implementations/BarrelInventoryMagGen"; import { ExternalInventoryMagGen } from "@spt-aki/generators/weapongen/implementations/ExternalInventoryMagGen"; import { InternalMagazineInventoryMagGen } from "@spt-aki/generators/weapongen/implementations/InternalMagazineInventoryMagGen"; import { UbglExternalMagGen } from "@spt-aki/generators/weapongen/implementations/UbglExternalMagGen"; +import { WeatherGenerator } from "@spt-aki/generators/WeatherGenerator"; import { AssortHelper } from "@spt-aki/helpers/AssortHelper"; import { BotDifficultyHelper } from "@spt-aki/helpers/BotDifficultyHelper"; import { BotGeneratorHelper } from "@spt-aki/helpers/BotGeneratorHelper"; @@ -124,10 +124,6 @@ import { PostAkiModLoader } from "@spt-aki/loaders/PostAkiModLoader"; import { PostDBModLoader } from "@spt-aki/loaders/PostDBModLoader"; import { PreAkiModLoader } from "@spt-aki/loaders/PreAkiModLoader"; import { IAsyncQueue } from "@spt-aki/models/spt/utils/IAsyncQueue"; -import { EventOutputHolder } from "@spt-aki/routers/EventOutputHolder"; -import { HttpRouter } from "@spt-aki/routers/HttpRouter"; -import { ImageRouter } from "@spt-aki/routers/ImageRouter"; -import { ItemEventRouter } from "@spt-aki/routers/ItemEventRouter"; import { BotDynamicRouter } from "@spt-aki/routers/dynamic/BotDynamicRouter"; import { BundleDynamicRouter } from "@spt-aki/routers/dynamic/BundleDynamicRouter"; import { CustomizationDynamicRouter } from "@spt-aki/routers/dynamic/CustomizationDynamicRouter"; @@ -137,6 +133,9 @@ import { InraidDynamicRouter } from "@spt-aki/routers/dynamic/InraidDynamicRoute import { LocationDynamicRouter } from "@spt-aki/routers/dynamic/LocationDynamicRouter"; import { NotifierDynamicRouter } from "@spt-aki/routers/dynamic/NotifierDynamicRouter"; import { TraderDynamicRouter } from "@spt-aki/routers/dynamic/TraderDynamicRouter"; +import { EventOutputHolder } from "@spt-aki/routers/EventOutputHolder"; +import { HttpRouter } from "@spt-aki/routers/HttpRouter"; +import { ImageRouter } from "@spt-aki/routers/ImageRouter"; import { CustomizationItemEventRouter } from "@spt-aki/routers/item_events/CustomizationItemEventRouter"; import { HealthItemEventRouter } from "@spt-aki/routers/item_events/HealthItemEventRouter"; import { HideoutItemEventRouter } from "@spt-aki/routers/item_events/HideoutItemEventRouter"; @@ -149,6 +148,7 @@ import { RagfairItemEventRouter } from "@spt-aki/routers/item_events/RagfairItem import { RepairItemEventRouter } from "@spt-aki/routers/item_events/RepairItemEventRouter"; import { TradeItemEventRouter } from "@spt-aki/routers/item_events/TradeItemEventRouter"; import { WishlistItemEventRouter } from "@spt-aki/routers/item_events/WishlistItemEventRouter"; +import { ItemEventRouter } from "@spt-aki/routers/ItemEventRouter"; import { HealthSaveLoadRouter } from "@spt-aki/routers/save_load/HealthSaveLoadRouter"; import { InraidSaveLoadRouter } from "@spt-aki/routers/save_load/InraidSaveLoadRouter"; import { InsuranceSaveLoadRouter } from "@spt-aki/routers/save_load/InsuranceSaveLoadRouter"; @@ -179,11 +179,11 @@ import { TraderStaticRouter } from "@spt-aki/routers/static/TraderStaticRouter"; import { WeatherStaticRouter } from "@spt-aki/routers/static/WeatherStaticRouter"; import { ConfigServer } from "@spt-aki/servers/ConfigServer"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; +import { AkiHttpListener } from "@spt-aki/servers/http/AkiHttpListener"; import { HttpServer } from "@spt-aki/servers/HttpServer"; import { RagfairServer } from "@spt-aki/servers/RagfairServer"; import { SaveServer } from "@spt-aki/servers/SaveServer"; import { WebSocketServer } from "@spt-aki/servers/WebSocketServer"; -import { AkiHttpListener } from "@spt-aki/servers/http/AkiHttpListener"; import { BotEquipmentFilterService } from "@spt-aki/services/BotEquipmentFilterService"; import { BotEquipmentModPoolService } from "@spt-aki/services/BotEquipmentModPoolService"; import { BotGenerationCacheService } from "@spt-aki/services/BotGenerationCacheService"; @@ -201,6 +201,13 @@ import { LocalisationService } from "@spt-aki/services/LocalisationService"; import { MailSendService } from "@spt-aki/services/MailSendService"; import { MatchBotDetailsCacheService } from "@spt-aki/services/MatchBotDetailsCacheService"; import { MatchLocationService } from "@spt-aki/services/MatchLocationService"; +import { CustomItemService } from "@spt-aki/services/mod/CustomItemService"; +import { DynamicRouterModService } from "@spt-aki/services/mod/dynamicRouter/DynamicRouterModService"; +import { HttpListenerModService } from "@spt-aki/services/mod/httpListener/HttpListenerModService"; +import { ImageRouteService } from "@spt-aki/services/mod/image/ImageRouteService"; +import { OnLoadModService } from "@spt-aki/services/mod/onLoad/OnLoadModService"; +import { OnUpdateModService } from "@spt-aki/services/mod/onUpdate/OnUpdateModService"; +import { StaticRouterModService } from "@spt-aki/services/mod/staticRouter/StaticRouterModService"; import { ModCompilerService } from "@spt-aki/services/ModCompilerService"; import { NotificationService } from "@spt-aki/services/NotificationService"; import { OpenZoneService } from "@spt-aki/services/OpenZoneService"; @@ -219,13 +226,6 @@ import { RepairService } from "@spt-aki/services/RepairService"; import { SeasonalEventService } from "@spt-aki/services/SeasonalEventService"; import { TraderAssortService } from "@spt-aki/services/TraderAssortService"; import { TraderPurchasePersisterService } from "@spt-aki/services/TraderPurchasePersisterService"; -import { CustomItemService } from "@spt-aki/services/mod/CustomItemService"; -import { DynamicRouterModService } from "@spt-aki/services/mod/dynamicRouter/DynamicRouterModService"; -import { HttpListenerModService } from "@spt-aki/services/mod/httpListener/HttpListenerModService"; -import { ImageRouteService } from "@spt-aki/services/mod/image/ImageRouteService"; -import { OnLoadModService } from "@spt-aki/services/mod/onLoad/OnLoadModService"; -import { OnUpdateModService } from "@spt-aki/services/mod/onUpdate/OnUpdateModService"; -import { StaticRouterModService } from "@spt-aki/services/mod/staticRouter/StaticRouterModService"; import { App } from "@spt-aki/utils/App"; import { AsyncQueue } from "@spt-aki/utils/AsyncQueue"; import { DatabaseImporter } from "@spt-aki/utils/DatabaseImporter"; @@ -235,428 +235,448 @@ import { HttpFileUtil } from "@spt-aki/utils/HttpFileUtil"; import { HttpResponseUtil } from "@spt-aki/utils/HttpResponseUtil"; import { ImporterUtil } from "@spt-aki/utils/ImporterUtil"; import { JsonUtil } from "@spt-aki/utils/JsonUtil"; +import { WinstonMainLogger } from "@spt-aki/utils/logging/WinstonMainLogger"; +import { WinstonRequestLogger } from "@spt-aki/utils/logging/WinstonRequestLogger"; import { MathUtil } from "@spt-aki/utils/MathUtil"; import { ObjectId } from "@spt-aki/utils/ObjectId"; import { RandomUtil } from "@spt-aki/utils/RandomUtil"; import { TimeUtil } from "@spt-aki/utils/TimeUtil"; import { VFS } from "@spt-aki/utils/VFS"; import { Watermark, WatermarkLocale } from "@spt-aki/utils/Watermark"; -import { WinstonMainLogger } from "@spt-aki/utils/logging/WinstonMainLogger"; -import { WinstonRequestLogger } from "@spt-aki/utils/logging/WinstonRequestLogger"; /** * Handle the registration of classes to be used by the Dependency Injection code */ export class Container { - - public static registerPostLoadTypes(container: DependencyContainer, childContainer: DependencyContainer):void + public static registerPostLoadTypes(container: DependencyContainer, childContainer: DependencyContainer): void { container.register("AkiHttpListener", AkiHttpListener, {lifecycle: Lifecycle.Singleton}); childContainer.registerType("HttpListener", "AkiHttpListener"); } - public static registerTypes(depContainer: DependencyContainer): void + public static registerTypes(con: DependencyContainer): void { - depContainer.register("ApplicationContext", ApplicationContext, { lifecycle: Lifecycle.Singleton }); - Container.registerUtils(depContainer); - - Container.registerRouters(depContainer); - - Container.registerGenerators(depContainer); - - Container.registerHelpers(depContainer); - - Container.registerLoaders(depContainer); - - Container.registerCallbacks(depContainer); - - Container.registerServers(depContainer); - - Container.registerServices(depContainer); - - Container.registerControllers(depContainer); + con.register("ApplicationContext", ApplicationContext, {lifecycle: Lifecycle.Singleton}); + Container.registerUtils(con); + Container.registerRouters(con); + Container.registerGenerators(con); + Container.registerHelpers(con); + Container.registerLoaders(con); + Container.registerCallbacks(con); + Container.registerServers(con); + Container.registerServices(con); + Container.registerControllers(con); } - public static registerListTypes(depContainer: DependencyContainer): void + public static registerListTypes(con: DependencyContainer): void { - depContainer.register("OnLoadModService", { useValue: new OnLoadModService(depContainer) }); - depContainer.register("HttpListenerModService", { useValue: new HttpListenerModService(depContainer) }); - depContainer.register("OnUpdateModService", { useValue: new OnUpdateModService(depContainer) }); - depContainer.register("DynamicRouterModService", { useValue: new DynamicRouterModService(depContainer) }); - depContainer.register("StaticRouterModService", { useValue: new StaticRouterModService(depContainer) }); + con.register("OnLoadModService", {useValue: new OnLoadModService(con)}); + con.register("HttpListenerModService", {useValue: new HttpListenerModService(con)}); + con.register("OnUpdateModService", {useValue: new OnUpdateModService(con)}); + con.register("DynamicRouterModService", {useValue: new DynamicRouterModService(con)}); + con.register("StaticRouterModService", {useValue: new StaticRouterModService(con)}); - depContainer.registerType("OnLoad", "DatabaseImporter"); - depContainer.registerType("OnLoad", "PostDBModLoader"); - depContainer.registerType("OnLoad", "HandbookCallbacks"); - depContainer.registerType("OnLoad", "HttpCallbacks"); - depContainer.registerType("OnLoad", "PresetCallbacks"); - depContainer.registerType("OnLoad", "SaveCallbacks"); - depContainer.registerType("OnLoad", "TraderCallbacks"); // must occur prior to RagfairCallbacks - depContainer.registerType("OnLoad", "RagfairPriceService"); - depContainer.registerType("OnLoad", "RagfairCallbacks"); - depContainer.registerType("OnLoad", "ModCallbacks"); - depContainer.registerType("OnLoad", "GameCallbacks"); - depContainer.registerType("OnUpdate", "DialogueCallbacks"); - depContainer.registerType("OnUpdate", "HideoutCallbacks"); - depContainer.registerType("OnUpdate", "TraderCallbacks"); - depContainer.registerType("OnUpdate", "RagfairCallbacks"); - depContainer.registerType("OnUpdate", "InsuranceCallbacks"); - depContainer.registerType("OnUpdate", "SaveCallbacks"); + con.registerType("OnLoad", "DatabaseImporter"); + con.registerType("OnLoad", "PostDBModLoader"); + con.registerType("OnLoad", "HandbookCallbacks"); + con.registerType("OnLoad", "HttpCallbacks"); + con.registerType("OnLoad", "PresetCallbacks"); + con.registerType("OnLoad", "SaveCallbacks"); + con.registerType("OnLoad", "TraderCallbacks"); // Must occur prior to RagfairCallbacks + con.registerType("OnLoad", "RagfairPriceService"); + con.registerType("OnLoad", "RagfairCallbacks"); + con.registerType("OnLoad", "ModCallbacks"); + con.registerType("OnLoad", "GameCallbacks"); + con.registerType("OnUpdate", "DialogueCallbacks"); + con.registerType("OnUpdate", "HideoutCallbacks"); + con.registerType("OnUpdate", "TraderCallbacks"); + con.registerType("OnUpdate", "RagfairCallbacks"); + con.registerType("OnUpdate", "InsuranceCallbacks"); + con.registerType("OnUpdate", "SaveCallbacks"); - depContainer.registerType("StaticRoutes", "BotStaticRouter"); - depContainer.registerType("StaticRoutes", "ClientLogStaticRouter"); - depContainer.registerType("StaticRoutes", "CustomizationStaticRouter"); - depContainer.registerType("StaticRoutes", "DataStaticRouter"); - depContainer.registerType("StaticRoutes", "DialogStaticRouter"); - depContainer.registerType("StaticRoutes", "GameStaticRouter"); - depContainer.registerType("StaticRoutes", "HealthStaticRouter"); - depContainer.registerType("StaticRoutes", "InraidStaticRouter"); - depContainer.registerType("StaticRoutes", "InsuranceStaticRouter"); - depContainer.registerType("StaticRoutes", "ItemEventStaticRouter"); - depContainer.registerType("StaticRoutes", "LauncherStaticRouter"); - depContainer.registerType("StaticRoutes", "LocationStaticRouter"); - depContainer.registerType("StaticRoutes", "WeatherStaticRouter"); - depContainer.registerType("StaticRoutes", "MatchStaticRouter"); - depContainer.registerType("StaticRoutes", "QuestStaticRouter"); - depContainer.registerType("StaticRoutes", "RagfairStaticRouter"); - depContainer.registerType("StaticRoutes", "PresetStaticRouter"); - depContainer.registerType("StaticRoutes", "BundleStaticRouter"); - depContainer.registerType("StaticRoutes", "NotifierStaticRouter"); - depContainer.registerType("StaticRoutes", "ProfileStaticRouter"); - depContainer.registerType("StaticRoutes", "TraderStaticRouter"); - depContainer.registerType("DynamicRoutes", "BotDynamicRouter"); - depContainer.registerType("DynamicRoutes", "BundleDynamicRouter"); - depContainer.registerType("DynamicRoutes", "CustomizationDynamicRouter"); - depContainer.registerType("DynamicRoutes", "DataDynamicRouter"); - depContainer.registerType("DynamicRoutes", "HttpDynamicRouter"); - depContainer.registerType("DynamicRoutes", "InraidDynamicRouter"); - depContainer.registerType("DynamicRoutes", "LocationDynamicRouter"); - depContainer.registerType("DynamicRoutes", "NotifierDynamicRouter"); - depContainer.registerType("DynamicRoutes", "TraderDynamicRouter"); + con.registerType("StaticRoutes", "BotStaticRouter"); + con.registerType("StaticRoutes", "ClientLogStaticRouter"); + con.registerType("StaticRoutes", "CustomizationStaticRouter"); + con.registerType("StaticRoutes", "DataStaticRouter"); + con.registerType("StaticRoutes", "DialogStaticRouter"); + con.registerType("StaticRoutes", "GameStaticRouter"); + con.registerType("StaticRoutes", "HealthStaticRouter"); + con.registerType("StaticRoutes", "InraidStaticRouter"); + con.registerType("StaticRoutes", "InsuranceStaticRouter"); + con.registerType("StaticRoutes", "ItemEventStaticRouter"); + con.registerType("StaticRoutes", "LauncherStaticRouter"); + con.registerType("StaticRoutes", "LocationStaticRouter"); + con.registerType("StaticRoutes", "WeatherStaticRouter"); + con.registerType("StaticRoutes", "MatchStaticRouter"); + con.registerType("StaticRoutes", "QuestStaticRouter"); + con.registerType("StaticRoutes", "RagfairStaticRouter"); + con.registerType("StaticRoutes", "PresetStaticRouter"); + con.registerType("StaticRoutes", "BundleStaticRouter"); + con.registerType("StaticRoutes", "NotifierStaticRouter"); + con.registerType("StaticRoutes", "ProfileStaticRouter"); + con.registerType("StaticRoutes", "TraderStaticRouter"); + con.registerType("DynamicRoutes", "BotDynamicRouter"); + con.registerType("DynamicRoutes", "BundleDynamicRouter"); + con.registerType("DynamicRoutes", "CustomizationDynamicRouter"); + con.registerType("DynamicRoutes", "DataDynamicRouter"); + con.registerType("DynamicRoutes", "HttpDynamicRouter"); + con.registerType("DynamicRoutes", "InraidDynamicRouter"); + con.registerType("DynamicRoutes", "LocationDynamicRouter"); + con.registerType("DynamicRoutes", "NotifierDynamicRouter"); + con.registerType("DynamicRoutes", "TraderDynamicRouter"); - depContainer.registerType("IERouters", "CustomizationItemEventRouter"); - depContainer.registerType("IERouters", "HealthItemEventRouter"); - depContainer.registerType("IERouters", "HideoutItemEventRouter"); - depContainer.registerType("IERouters", "InsuranceItemEventRouter"); - depContainer.registerType("IERouters", "InventoryItemEventRouter"); - depContainer.registerType("IERouters", "NoteItemEventRouter"); - depContainer.registerType("IERouters", "PresetBuildItemEventRouter"); - depContainer.registerType("IERouters", "QuestItemEventRouter"); - depContainer.registerType("IERouters", "RagfairItemEventRouter"); - depContainer.registerType("IERouters", "RepairItemEventRouter"); - depContainer.registerType("IERouters", "TradeItemEventRouter"); - depContainer.registerType("IERouters", "WishlistItemEventRouter"); + con.registerType("IERouters", "CustomizationItemEventRouter"); + con.registerType("IERouters", "HealthItemEventRouter"); + con.registerType("IERouters", "HideoutItemEventRouter"); + con.registerType("IERouters", "InsuranceItemEventRouter"); + con.registerType("IERouters", "InventoryItemEventRouter"); + con.registerType("IERouters", "NoteItemEventRouter"); + con.registerType("IERouters", "PresetBuildItemEventRouter"); + con.registerType("IERouters", "QuestItemEventRouter"); + con.registerType("IERouters", "RagfairItemEventRouter"); + con.registerType("IERouters", "RepairItemEventRouter"); + con.registerType("IERouters", "TradeItemEventRouter"); + con.registerType("IERouters", "WishlistItemEventRouter"); - depContainer.registerType("Serializer", "ImageSerializer"); - depContainer.registerType("Serializer", "BundleSerializer"); - depContainer.registerType("Serializer", "NotifySerializer"); - depContainer.registerType("SaveLoadRouter", "HealthSaveLoadRouter"); - depContainer.registerType("SaveLoadRouter", "InraidSaveLoadRouter"); - depContainer.registerType("SaveLoadRouter", "InsuranceSaveLoadRouter"); - depContainer.registerType("SaveLoadRouter", "ProfileSaveLoadRouter"); + con.registerType("Serializer", "ImageSerializer"); + con.registerType("Serializer", "BundleSerializer"); + con.registerType("Serializer", "NotifySerializer"); + con.registerType("SaveLoadRouter", "HealthSaveLoadRouter"); + con.registerType("SaveLoadRouter", "InraidSaveLoadRouter"); + con.registerType("SaveLoadRouter", "InsuranceSaveLoadRouter"); + con.registerType("SaveLoadRouter", "ProfileSaveLoadRouter"); } - private static registerUtils(depContainer: DependencyContainer): void + private static registerUtils(con: DependencyContainer): void { // Utils - depContainer.register("App", App, { lifecycle: Lifecycle.Singleton }); - depContainer.register("DatabaseImporter", DatabaseImporter, { lifecycle: Lifecycle.Singleton }); - depContainer.register("HashUtil", HashUtil, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ImporterUtil", ImporterUtil, { lifecycle: Lifecycle.Singleton }); - depContainer.register("HttpResponseUtil", HttpResponseUtil); - depContainer.register("EncodingUtil", EncodingUtil, { lifecycle: Lifecycle.Singleton }); - depContainer.register("JsonUtil", JsonUtil); - depContainer.register("WinstonLogger", WinstonMainLogger, { lifecycle: Lifecycle.Singleton }); - depContainer.register("RequestsLogger", WinstonRequestLogger, { lifecycle: Lifecycle.Singleton }); - depContainer.register("MathUtil", MathUtil, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ObjectId", ObjectId); - depContainer.register("RandomUtil", RandomUtil, { lifecycle: Lifecycle.Singleton }); - depContainer.register("TimeUtil", TimeUtil, { lifecycle: Lifecycle.Singleton }); - depContainer.register("VFS", VFS, { lifecycle: Lifecycle.Singleton }); - depContainer.register("WatermarkLocale", WatermarkLocale, { lifecycle: Lifecycle.Singleton }); - depContainer.register("Watermark", Watermark, { lifecycle: Lifecycle.Singleton }); - depContainer.register("AsyncQueue", AsyncQueue, { lifecycle: Lifecycle.Singleton }); - depContainer.register("HttpFileUtil", HttpFileUtil, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ModLoadOrder", ModLoadOrder, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ModTypeCheck", ModTypeCheck, { lifecycle: Lifecycle.Singleton }); + con.register("App", App, {lifecycle: Lifecycle.Singleton}); + con.register("DatabaseImporter", DatabaseImporter, {lifecycle: Lifecycle.Singleton}); + con.register("HashUtil", HashUtil, {lifecycle: Lifecycle.Singleton}); + con.register("ImporterUtil", ImporterUtil, {lifecycle: Lifecycle.Singleton}); + con.register("HttpResponseUtil", HttpResponseUtil); + con.register("EncodingUtil", EncodingUtil, {lifecycle: Lifecycle.Singleton}); + con.register("JsonUtil", JsonUtil); + con.register("WinstonLogger", WinstonMainLogger, {lifecycle: Lifecycle.Singleton}); + con.register("RequestsLogger", WinstonRequestLogger, {lifecycle: Lifecycle.Singleton}); + con.register("MathUtil", MathUtil, {lifecycle: Lifecycle.Singleton}); + con.register("ObjectId", ObjectId); + con.register("RandomUtil", RandomUtil, {lifecycle: Lifecycle.Singleton}); + con.register("TimeUtil", TimeUtil, {lifecycle: Lifecycle.Singleton}); + con.register("VFS", VFS, {lifecycle: Lifecycle.Singleton}); + con.register("WatermarkLocale", WatermarkLocale, {lifecycle: Lifecycle.Singleton}); + con.register("Watermark", Watermark, {lifecycle: Lifecycle.Singleton}); + con.register("AsyncQueue", AsyncQueue, {lifecycle: Lifecycle.Singleton}); + con.register("HttpFileUtil", HttpFileUtil, {lifecycle: Lifecycle.Singleton}); + con.register("ModLoadOrder", ModLoadOrder, {lifecycle: Lifecycle.Singleton}); + con.register("ModTypeCheck", ModTypeCheck, {lifecycle: Lifecycle.Singleton}); } - private static registerRouters(depContainer: DependencyContainer): void + private static registerRouters(con: DependencyContainer): void { // Routers - depContainer.register("HttpRouter", HttpRouter, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ImageRouter", ImageRouter); - depContainer.register("EventOutputHolder", EventOutputHolder, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ItemEventRouter", ItemEventRouter); + con.register("HttpRouter", HttpRouter, {lifecycle: Lifecycle.Singleton}); + con.register("ImageRouter", ImageRouter); + con.register("EventOutputHolder", EventOutputHolder, {lifecycle: Lifecycle.Singleton}); + con.register("ItemEventRouter", ItemEventRouter); // Dynamic routes - depContainer.register("BotDynamicRouter", { useClass: BotDynamicRouter }); - depContainer.register("BundleDynamicRouter", { useClass: BundleDynamicRouter }); - depContainer.register("CustomizationDynamicRouter", { useClass: CustomizationDynamicRouter }); - depContainer.register("DataDynamicRouter", { useClass: DataDynamicRouter }); - depContainer.register("HttpDynamicRouter", { useClass: HttpDynamicRouter }); - depContainer.register("InraidDynamicRouter", { useClass: InraidDynamicRouter }); - depContainer.register("LocationDynamicRouter", { useClass: LocationDynamicRouter }); - depContainer.register("NotifierDynamicRouter", { useClass: NotifierDynamicRouter }); - depContainer.register("TraderDynamicRouter", { useClass: TraderDynamicRouter }); + con.register("BotDynamicRouter", {useClass: BotDynamicRouter}); + con.register("BundleDynamicRouter", {useClass: BundleDynamicRouter}); + con.register("CustomizationDynamicRouter", {useClass: CustomizationDynamicRouter}); + con.register("DataDynamicRouter", {useClass: DataDynamicRouter}); + con.register("HttpDynamicRouter", {useClass: HttpDynamicRouter}); + con.register("InraidDynamicRouter", {useClass: InraidDynamicRouter}); + con.register("LocationDynamicRouter", {useClass: LocationDynamicRouter}); + con.register("NotifierDynamicRouter", {useClass: NotifierDynamicRouter}); + con.register("TraderDynamicRouter", {useClass: TraderDynamicRouter}); // Item event routes - depContainer.register("CustomizationItemEventRouter", { useClass: CustomizationItemEventRouter }); - depContainer.register("HealthItemEventRouter", { useClass: HealthItemEventRouter }); - depContainer.register("HideoutItemEventRouter", { useClass: HideoutItemEventRouter }); - depContainer.register("InsuranceItemEventRouter", { useClass: InsuranceItemEventRouter }); - depContainer.register("InventoryItemEventRouter", { useClass: InventoryItemEventRouter }); - depContainer.register("NoteItemEventRouter", { useClass: NoteItemEventRouter }); - depContainer.register("PresetBuildItemEventRouter", { useClass: PresetBuildItemEventRouter }); - depContainer.register("QuestItemEventRouter", { useClass: QuestItemEventRouter }); - depContainer.register("RagfairItemEventRouter", { useClass: RagfairItemEventRouter }); - depContainer.register("RepairItemEventRouter", { useClass: RepairItemEventRouter }); - depContainer.register("TradeItemEventRouter", { useClass: TradeItemEventRouter }); - depContainer.register("WishlistItemEventRouter", { useClass: WishlistItemEventRouter }); + con.register("CustomizationItemEventRouter", { + useClass: CustomizationItemEventRouter, + }); + con.register("HealthItemEventRouter", {useClass: HealthItemEventRouter}); + con.register("HideoutItemEventRouter", {useClass: HideoutItemEventRouter}); + con.register("InsuranceItemEventRouter", {useClass: InsuranceItemEventRouter}); + con.register("InventoryItemEventRouter", {useClass: InventoryItemEventRouter}); + con.register("NoteItemEventRouter", {useClass: NoteItemEventRouter}); + con.register("PresetBuildItemEventRouter", {useClass: PresetBuildItemEventRouter}); + con.register("QuestItemEventRouter", {useClass: QuestItemEventRouter}); + con.register("RagfairItemEventRouter", {useClass: RagfairItemEventRouter}); + con.register("RepairItemEventRouter", {useClass: RepairItemEventRouter}); + con.register("TradeItemEventRouter", {useClass: TradeItemEventRouter}); + con.register("WishlistItemEventRouter", {useClass: WishlistItemEventRouter}); // save load routes - depContainer.register("HealthSaveLoadRouter", { useClass: HealthSaveLoadRouter }); - depContainer.register("InraidSaveLoadRouter", { useClass: InraidSaveLoadRouter }); - depContainer.register("InsuranceSaveLoadRouter", { useClass: InsuranceSaveLoadRouter }); - depContainer.register("ProfileSaveLoadRouter", { useClass: ProfileSaveLoadRouter }); + con.register("HealthSaveLoadRouter", {useClass: HealthSaveLoadRouter}); + con.register("InraidSaveLoadRouter", {useClass: InraidSaveLoadRouter}); + con.register("InsuranceSaveLoadRouter", {useClass: InsuranceSaveLoadRouter}); + con.register("ProfileSaveLoadRouter", {useClass: ProfileSaveLoadRouter}); // Route serializers - depContainer.register("BundleSerializer", { useClass: BundleSerializer }); - depContainer.register("ImageSerializer", { useClass: ImageSerializer }); - depContainer.register("NotifySerializer", { useClass: NotifySerializer }); + con.register("BundleSerializer", {useClass: BundleSerializer}); + con.register("ImageSerializer", {useClass: ImageSerializer}); + con.register("NotifySerializer", {useClass: NotifySerializer}); // Static routes - depContainer.register("BotStaticRouter", { useClass: BotStaticRouter }); - depContainer.register("BundleStaticRouter", { useClass: BundleStaticRouter }); - depContainer.register("ClientLogStaticRouter", { useClass: ClientLogStaticRouter }); - depContainer.register("CustomizationStaticRouter", { useClass: CustomizationStaticRouter }); - depContainer.register("DataStaticRouter", { useClass: DataStaticRouter }); - depContainer.register("DialogStaticRouter", { useClass: DialogStaticRouter }); - depContainer.register("GameStaticRouter", { useClass: GameStaticRouter }); - depContainer.register("HealthStaticRouter", { useClass: HealthStaticRouter }); - depContainer.register("InraidStaticRouter", { useClass: InraidStaticRouter }); - depContainer.register("InsuranceStaticRouter", { useClass: InsuranceStaticRouter }); - depContainer.register("ItemEventStaticRouter", { useClass: ItemEventStaticRouter }); - depContainer.register("LauncherStaticRouter", { useClass: LauncherStaticRouter }); - depContainer.register("LocationStaticRouter", { useClass: LocationStaticRouter }); - depContainer.register("MatchStaticRouter", { useClass: MatchStaticRouter }); - depContainer.register("NotifierStaticRouter", { useClass: NotifierStaticRouter }); - depContainer.register("PresetStaticRouter", { useClass: PresetStaticRouter }); - depContainer.register("ProfileStaticRouter", { useClass: ProfileStaticRouter }); - depContainer.register("QuestStaticRouter", { useClass: QuestStaticRouter }); - depContainer.register("RagfairStaticRouter", { useClass: RagfairStaticRouter }); - depContainer.register("TraderStaticRouter", { useClass: TraderStaticRouter }); - depContainer.register("WeatherStaticRouter", { useClass: WeatherStaticRouter }); + con.register("BotStaticRouter", {useClass: BotStaticRouter}); + con.register("BundleStaticRouter", {useClass: BundleStaticRouter}); + con.register("ClientLogStaticRouter", {useClass: ClientLogStaticRouter}); + con.register("CustomizationStaticRouter", {useClass: CustomizationStaticRouter}); + con.register("DataStaticRouter", {useClass: DataStaticRouter}); + con.register("DialogStaticRouter", {useClass: DialogStaticRouter}); + con.register("GameStaticRouter", {useClass: GameStaticRouter}); + con.register("HealthStaticRouter", {useClass: HealthStaticRouter}); + con.register("InraidStaticRouter", {useClass: InraidStaticRouter}); + con.register("InsuranceStaticRouter", {useClass: InsuranceStaticRouter}); + con.register("ItemEventStaticRouter", {useClass: ItemEventStaticRouter}); + con.register("LauncherStaticRouter", {useClass: LauncherStaticRouter}); + con.register("LocationStaticRouter", {useClass: LocationStaticRouter}); + con.register("MatchStaticRouter", {useClass: MatchStaticRouter}); + con.register("NotifierStaticRouter", {useClass: NotifierStaticRouter}); + con.register("PresetStaticRouter", {useClass: PresetStaticRouter}); + con.register("ProfileStaticRouter", {useClass: ProfileStaticRouter}); + con.register("QuestStaticRouter", {useClass: QuestStaticRouter}); + con.register("RagfairStaticRouter", {useClass: RagfairStaticRouter}); + con.register("TraderStaticRouter", {useClass: TraderStaticRouter}); + con.register("WeatherStaticRouter", {useClass: WeatherStaticRouter}); } - private static registerGenerators(depContainer: DependencyContainer): void + private static registerGenerators(con: DependencyContainer): void { // Generators - depContainer.register("BotGenerator", BotGenerator); - depContainer.register("BotWeaponGenerator", BotWeaponGenerator); - depContainer.register("BotLootGenerator", BotLootGenerator); - depContainer.register("BotInventoryGenerator", BotInventoryGenerator); - depContainer.register("LocationGenerator", { useClass: LocationGenerator }); - depContainer.register("PMCLootGenerator", PMCLootGenerator, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ScavCaseRewardGenerator", ScavCaseRewardGenerator, { lifecycle: Lifecycle.Singleton }); - depContainer.register("RagfairAssortGenerator", { useClass: RagfairAssortGenerator }); - depContainer.register("RagfairOfferGenerator", { useClass: RagfairOfferGenerator }); - depContainer.register("WeatherGenerator", { useClass: WeatherGenerator }); - depContainer.register("PlayerScavGenerator", { useClass: PlayerScavGenerator }); - depContainer.register("LootGenerator", { useClass: LootGenerator }); - depContainer.register("FenceBaseAssortGenerator", { useClass: FenceBaseAssortGenerator }); - depContainer.register("BotLevelGenerator", { useClass: BotLevelGenerator }); - depContainer.register("BotEquipmentModGenerator", { useClass: BotEquipmentModGenerator }); - depContainer.register("RepeatableQuestGenerator", { useClass: RepeatableQuestGenerator }); - - - depContainer.register("BarrelInventoryMagGen", { useClass: BarrelInventoryMagGen }); - depContainer.register("ExternalInventoryMagGen", { useClass: ExternalInventoryMagGen }); - depContainer.register("InternalMagazineInventoryMagGen", { useClass: InternalMagazineInventoryMagGen }); - depContainer.register("UbglExternalMagGen", { useClass: UbglExternalMagGen }); - - depContainer.registerType("InventoryMagGen", "BarrelInventoryMagGen"); - depContainer.registerType("InventoryMagGen", "ExternalInventoryMagGen"); - depContainer.registerType("InventoryMagGen", "InternalMagazineInventoryMagGen"); - depContainer.registerType("InventoryMagGen", "UbglExternalMagGen"); + con.register("BotGenerator", BotGenerator); + con.register("BotWeaponGenerator", BotWeaponGenerator); + con.register("BotLootGenerator", BotLootGenerator); + con.register("BotInventoryGenerator", BotInventoryGenerator); + con.register("LocationGenerator", {useClass: LocationGenerator}); + con.register("PMCLootGenerator", PMCLootGenerator, {lifecycle: Lifecycle.Singleton}); + con.register("ScavCaseRewardGenerator", ScavCaseRewardGenerator, { + lifecycle: Lifecycle.Singleton, + }); + con.register("RagfairAssortGenerator", {useClass: RagfairAssortGenerator}); + con.register("RagfairOfferGenerator", {useClass: RagfairOfferGenerator}); + con.register("WeatherGenerator", {useClass: WeatherGenerator}); + con.register("PlayerScavGenerator", {useClass: PlayerScavGenerator}); + con.register("LootGenerator", {useClass: LootGenerator}); + con.register("FenceBaseAssortGenerator", {useClass: FenceBaseAssortGenerator}); + con.register("BotLevelGenerator", {useClass: BotLevelGenerator}); + con.register("BotEquipmentModGenerator", {useClass: BotEquipmentModGenerator}); + con.register("RepeatableQuestGenerator", {useClass: RepeatableQuestGenerator}); + con.register("BarrelInventoryMagGen", {useClass: BarrelInventoryMagGen}); + con.register("ExternalInventoryMagGen", {useClass: ExternalInventoryMagGen}); + con.register("InternalMagazineInventoryMagGen", { + useClass: InternalMagazineInventoryMagGen, + }); + con.register("UbglExternalMagGen", {useClass: UbglExternalMagGen}); + con.registerType("InventoryMagGen", "BarrelInventoryMagGen"); + con.registerType("InventoryMagGen", "ExternalInventoryMagGen"); + con.registerType("InventoryMagGen", "InternalMagazineInventoryMagGen"); + con.registerType("InventoryMagGen", "UbglExternalMagGen"); } - private static registerHelpers(depContainer: DependencyContainer): void + private static registerHelpers(con: DependencyContainer): void { // Helpers - depContainer.register("AssortHelper", { useClass: AssortHelper }); - depContainer.register("BotHelper", { useClass: BotHelper }); - depContainer.register("BotGeneratorHelper", { useClass: BotGeneratorHelper }); - depContainer.register("ContainerHelper", ContainerHelper); - depContainer.register("DialogueHelper", { useClass: DialogueHelper }); - depContainer.register("DurabilityLimitsHelper", { useClass: DurabilityLimitsHelper }); - depContainer.register("GameEventHelper", GameEventHelper); - depContainer.register("HandbookHelper", HandbookHelper, { lifecycle: Lifecycle.Singleton }); - depContainer.register("HealthHelper", { useClass: HealthHelper }); - depContainer.register("HideoutHelper", { useClass: HideoutHelper }); - depContainer.register("InRaidHelper", { useClass: InRaidHelper }); - depContainer.register("InventoryHelper", { useClass: InventoryHelper }); - depContainer.register("PaymentHelper", PaymentHelper); - depContainer.register("ItemHelper", { useClass: ItemHelper }); - depContainer.register("PresetHelper", PresetHelper, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ProfileHelper", { useClass: ProfileHelper }); - depContainer.register("QuestHelper", { useClass: QuestHelper }); - depContainer.register("QuestConditionHelper", QuestConditionHelper); - depContainer.register("RagfairHelper", { useClass: RagfairHelper }); - depContainer.register("RagfairSortHelper", { useClass: RagfairSortHelper }); - depContainer.register("RagfairSellHelper", { useClass: RagfairSellHelper }); - depContainer.register("RagfairOfferHelper", { useClass: RagfairOfferHelper }); - depContainer.register("RagfairServerHelper", { useClass: RagfairServerHelper }); - depContainer.register("RepairHelper", { useClass: RepairHelper }); - depContainer.register("TraderHelper", TraderHelper); - depContainer.register("TraderAssortHelper", TraderAssortHelper, { lifecycle: Lifecycle.Singleton }); - depContainer.register("TradeHelper", { useClass: TradeHelper }); - depContainer.register("NotifierHelper", { useClass: NotifierHelper }); - depContainer.register("UtilityHelper", UtilityHelper); - depContainer.register("WeightedRandomHelper", { useClass: WeightedRandomHelper }); - depContainer.register("HttpServerHelper", { useClass: HttpServerHelper }); - depContainer.register("NotificationSendHelper", { useClass: NotificationSendHelper }); - depContainer.register("SecureContainerHelper", { useClass: SecureContainerHelper }); - depContainer.register("ProbabilityHelper", { useClass: ProbabilityHelper }); - depContainer.register("BotWeaponGeneratorHelper", { useClass: BotWeaponGeneratorHelper }); - depContainer.register("BotDifficultyHelper", { useClass: BotDifficultyHelper }); - depContainer.register("RepeatableQuestHelper", { useClass: RepeatableQuestHelper }); + con.register("AssortHelper", {useClass: AssortHelper}); + con.register("BotHelper", {useClass: BotHelper}); + con.register("BotGeneratorHelper", {useClass: BotGeneratorHelper}); + con.register("ContainerHelper", ContainerHelper); + con.register("DialogueHelper", {useClass: DialogueHelper}); + con.register("DurabilityLimitsHelper", {useClass: DurabilityLimitsHelper}); + con.register("GameEventHelper", GameEventHelper); + con.register("HandbookHelper", HandbookHelper, {lifecycle: Lifecycle.Singleton}); + con.register("HealthHelper", {useClass: HealthHelper}); + con.register("HideoutHelper", {useClass: HideoutHelper}); + con.register("InRaidHelper", {useClass: InRaidHelper}); + con.register("InventoryHelper", {useClass: InventoryHelper}); + con.register("PaymentHelper", PaymentHelper); + con.register("ItemHelper", {useClass: ItemHelper}); + con.register("PresetHelper", PresetHelper, {lifecycle: Lifecycle.Singleton}); + con.register("ProfileHelper", {useClass: ProfileHelper}); + con.register("QuestHelper", {useClass: QuestHelper}); + con.register("QuestConditionHelper", QuestConditionHelper); + con.register("RagfairHelper", {useClass: RagfairHelper}); + con.register("RagfairSortHelper", {useClass: RagfairSortHelper}); + con.register("RagfairSellHelper", {useClass: RagfairSellHelper}); + con.register("RagfairOfferHelper", {useClass: RagfairOfferHelper}); + con.register("RagfairServerHelper", {useClass: RagfairServerHelper}); + con.register("RepairHelper", {useClass: RepairHelper}); + con.register("TraderHelper", TraderHelper); + con.register("TraderAssortHelper", TraderAssortHelper, {lifecycle: Lifecycle.Singleton}); + con.register("TradeHelper", {useClass: TradeHelper}); + con.register("NotifierHelper", {useClass: NotifierHelper}); + con.register("UtilityHelper", UtilityHelper); + con.register("WeightedRandomHelper", {useClass: WeightedRandomHelper}); + con.register("HttpServerHelper", {useClass: HttpServerHelper}); + con.register("NotificationSendHelper", {useClass: NotificationSendHelper}); + con.register("SecureContainerHelper", {useClass: SecureContainerHelper}); + con.register("ProbabilityHelper", {useClass: ProbabilityHelper}); + con.register("BotWeaponGeneratorHelper", {useClass: BotWeaponGeneratorHelper}); + con.register("BotDifficultyHelper", {useClass: BotDifficultyHelper}); + con.register("RepeatableQuestHelper", {useClass: RepeatableQuestHelper}); } - private static registerLoaders(depContainer: DependencyContainer): void + private static registerLoaders(con: DependencyContainer): void { // Loaders - depContainer.register("BundleLoader", BundleLoader, { lifecycle: Lifecycle.Singleton }); - depContainer.register("PreAkiModLoader", PreAkiModLoader, { lifecycle: Lifecycle.Singleton }); - depContainer.register("PostAkiModLoader", PostAkiModLoader, { lifecycle: Lifecycle.Singleton }); + con.register("BundleLoader", BundleLoader, {lifecycle: Lifecycle.Singleton}); + con.register("PreAkiModLoader", PreAkiModLoader, {lifecycle: Lifecycle.Singleton}); + con.register("PostAkiModLoader", PostAkiModLoader, {lifecycle: Lifecycle.Singleton}); } - private static registerCallbacks(depContainer: DependencyContainer): void + private static registerCallbacks(con: DependencyContainer): void { // Callbacks - depContainer.register("BotCallbacks", { useClass: BotCallbacks }); - depContainer.register("BundleCallbacks", { useClass: BundleCallbacks }); - depContainer.register("ClientLogCallbacks", { useClass: ClientLogCallbacks }); - depContainer.register("CustomizationCallbacks", { useClass: CustomizationCallbacks }); - depContainer.register("DataCallbacks", { useClass: DataCallbacks }); - depContainer.register("DialogueCallbacks", { useClass: DialogueCallbacks }); - depContainer.register("GameCallbacks", { useClass: GameCallbacks }); - depContainer.register("HandbookCallbacks", { useClass: HandbookCallbacks }); - depContainer.register("HealthCallbacks", { useClass: HealthCallbacks }); - depContainer.register("HideoutCallbacks", { useClass: HideoutCallbacks }); - depContainer.register("HttpCallbacks", { useClass: HttpCallbacks }); - depContainer.register("InraidCallbacks", { useClass: InraidCallbacks }); - depContainer.register("InsuranceCallbacks", { useClass: InsuranceCallbacks }); - depContainer.register("InventoryCallbacks", { useClass: InventoryCallbacks }); - depContainer.register("ItemEventCallbacks", { useClass: ItemEventCallbacks }); - depContainer.register("LauncherCallbacks", { useClass: LauncherCallbacks }); - depContainer.register("LocationCallbacks", { useClass: LocationCallbacks }); - depContainer.register("MatchCallbacks", { useClass: MatchCallbacks }); - depContainer.register("ModCallbacks", { useClass: ModCallbacks }); - depContainer.register("PostDBModLoader", { useClass: PostDBModLoader }); - depContainer.register("NoteCallbacks", { useClass: NoteCallbacks }); - depContainer.register("NotifierCallbacks", { useClass: NotifierCallbacks }); - depContainer.register("PresetBuildCallbacks", { useClass: PresetBuildCallbacks }); - depContainer.register("PresetCallbacks", { useClass: PresetCallbacks }); - depContainer.register("ProfileCallbacks", { useClass: ProfileCallbacks }); - depContainer.register("QuestCallbacks", { useClass: QuestCallbacks }); - depContainer.register("RagfairCallbacks", { useClass: RagfairCallbacks }); - depContainer.register("RepairCallbacks", { useClass: RepairCallbacks }); - depContainer.register("SaveCallbacks", { useClass: SaveCallbacks }); - depContainer.register("TradeCallbacks", { useClass: TradeCallbacks }); - depContainer.register("TraderCallbacks", { useClass: TraderCallbacks }); - depContainer.register("WeatherCallbacks", { useClass: WeatherCallbacks }); - depContainer.register("WishlistCallbacks", { useClass: WishlistCallbacks }); + con.register("BotCallbacks", {useClass: BotCallbacks}); + con.register("BundleCallbacks", {useClass: BundleCallbacks}); + con.register("ClientLogCallbacks", {useClass: ClientLogCallbacks}); + con.register("CustomizationCallbacks", {useClass: CustomizationCallbacks}); + con.register("DataCallbacks", {useClass: DataCallbacks}); + con.register("DialogueCallbacks", {useClass: DialogueCallbacks}); + con.register("GameCallbacks", {useClass: GameCallbacks}); + con.register("HandbookCallbacks", {useClass: HandbookCallbacks}); + con.register("HealthCallbacks", {useClass: HealthCallbacks}); + con.register("HideoutCallbacks", {useClass: HideoutCallbacks}); + con.register("HttpCallbacks", {useClass: HttpCallbacks}); + con.register("InraidCallbacks", {useClass: InraidCallbacks}); + con.register("InsuranceCallbacks", {useClass: InsuranceCallbacks}); + con.register("InventoryCallbacks", {useClass: InventoryCallbacks}); + con.register("ItemEventCallbacks", {useClass: ItemEventCallbacks}); + con.register("LauncherCallbacks", {useClass: LauncherCallbacks}); + con.register("LocationCallbacks", {useClass: LocationCallbacks}); + con.register("MatchCallbacks", {useClass: MatchCallbacks}); + con.register("ModCallbacks", {useClass: ModCallbacks}); + con.register("PostDBModLoader", {useClass: PostDBModLoader}); + con.register("NoteCallbacks", {useClass: NoteCallbacks}); + con.register("NotifierCallbacks", {useClass: NotifierCallbacks}); + con.register("PresetBuildCallbacks", {useClass: PresetBuildCallbacks}); + con.register("PresetCallbacks", {useClass: PresetCallbacks}); + con.register("ProfileCallbacks", {useClass: ProfileCallbacks}); + con.register("QuestCallbacks", {useClass: QuestCallbacks}); + con.register("RagfairCallbacks", {useClass: RagfairCallbacks}); + con.register("RepairCallbacks", {useClass: RepairCallbacks}); + con.register("SaveCallbacks", {useClass: SaveCallbacks}); + con.register("TradeCallbacks", {useClass: TradeCallbacks}); + con.register("TraderCallbacks", {useClass: TraderCallbacks}); + con.register("WeatherCallbacks", {useClass: WeatherCallbacks}); + con.register("WishlistCallbacks", {useClass: WishlistCallbacks}); } - private static registerServices(depContainer: DependencyContainer): void + private static registerServices(con: DependencyContainer): void { // Services - depContainer.register("ImageRouteService", ImageRouteService, { lifecycle: Lifecycle.Singleton }); + con.register("ImageRouteService", ImageRouteService, {lifecycle: Lifecycle.Singleton}); - depContainer.register("FenceService", FenceService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("PlayerService", { useClass: PlayerService }); - depContainer.register("PaymentService", { useClass: PaymentService }); - depContainer.register("InsuranceService", InsuranceService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("TraderAssortService", TraderAssortService, { lifecycle: Lifecycle.Singleton }); + con.register("FenceService", FenceService, {lifecycle: Lifecycle.Singleton}); + con.register("PlayerService", {useClass: PlayerService}); + con.register("PaymentService", {useClass: PaymentService}); + con.register("InsuranceService", InsuranceService, {lifecycle: Lifecycle.Singleton}); + con.register("TraderAssortService", TraderAssortService, {lifecycle: Lifecycle.Singleton}); - depContainer.register("RagfairPriceService", RagfairPriceService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("RagfairCategoriesService", RagfairCategoriesService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("RagfairOfferService", RagfairOfferService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("RagfairLinkedItemService", RagfairLinkedItemService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("RagfairRequiredItemsService", RagfairRequiredItemsService, { lifecycle: Lifecycle.Singleton }); + con.register("RagfairPriceService", RagfairPriceService, {lifecycle: Lifecycle.Singleton}); + con.register("RagfairCategoriesService", RagfairCategoriesService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("RagfairOfferService", RagfairOfferService, {lifecycle: Lifecycle.Singleton}); + con.register("RagfairLinkedItemService", RagfairLinkedItemService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("RagfairRequiredItemsService", RagfairRequiredItemsService, { + lifecycle: Lifecycle.Singleton, + }); - depContainer.register("NotificationService", NotificationService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("MatchLocationService", MatchLocationService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ModCompilerService", ModCompilerService); - depContainer.register("HashCacheService", HashCacheService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("LocaleService", LocaleService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ProfileFixerService", ProfileFixerService); - depContainer.register("RepairService", RepairService); - depContainer.register("BotLootCacheService", BotLootCacheService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("CustomItemService", CustomItemService); - depContainer.register("BotEquipmentFilterService", BotEquipmentFilterService); - depContainer.register("ProfileSnapshotService", ProfileSnapshotService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ItemFilterService", ItemFilterService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("BotGenerationCacheService", BotGenerationCacheService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("LocalisationService", LocalisationService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("CustomLocationWaveService", CustomLocationWaveService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("OpenZoneService", OpenZoneService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ItemBaseClassService", ItemBaseClassService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("BotEquipmentModPoolService", BotEquipmentModPoolService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("BotWeaponModLimitService", BotWeaponModLimitService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("SeasonalEventService", SeasonalEventService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("MatchBotDetailsCacheService", MatchBotDetailsCacheService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("RagfairTaxService", RagfairTaxService, { lifecycle: Lifecycle.Singleton }); - depContainer.register("TraderPurchasePersisterService", TraderPurchasePersisterService); - depContainer.register("PmcChatResponseService", PmcChatResponseService); - depContainer.register("GiftService", GiftService); - depContainer.register("MailSendService", MailSendService); + con.register("NotificationService", NotificationService, {lifecycle: Lifecycle.Singleton}); + con.register("MatchLocationService", MatchLocationService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("ModCompilerService", ModCompilerService); + con.register("HashCacheService", HashCacheService, {lifecycle: Lifecycle.Singleton}); + con.register("LocaleService", LocaleService, {lifecycle: Lifecycle.Singleton}); + con.register("ProfileFixerService", ProfileFixerService); + con.register("RepairService", RepairService); + con.register("BotLootCacheService", BotLootCacheService, {lifecycle: Lifecycle.Singleton}); + con.register("CustomItemService", CustomItemService); + con.register("BotEquipmentFilterService", BotEquipmentFilterService); + con.register("ProfileSnapshotService", ProfileSnapshotService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("ItemFilterService", ItemFilterService, {lifecycle: Lifecycle.Singleton}); + con.register("BotGenerationCacheService", BotGenerationCacheService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("LocalisationService", LocalisationService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("CustomLocationWaveService", CustomLocationWaveService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("OpenZoneService", OpenZoneService, {lifecycle: Lifecycle.Singleton}); + con.register("ItemBaseClassService", ItemBaseClassService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("BotEquipmentModPoolService", BotEquipmentModPoolService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("BotWeaponModLimitService", BotWeaponModLimitService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("SeasonalEventService", SeasonalEventService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("MatchBotDetailsCacheService", MatchBotDetailsCacheService, { + lifecycle: Lifecycle.Singleton, + }); + con.register("RagfairTaxService", RagfairTaxService, {lifecycle: Lifecycle.Singleton}); + con.register("TraderPurchasePersisterService", TraderPurchasePersisterService); + con.register("PmcChatResponseService", PmcChatResponseService); + con.register("GiftService", GiftService); + con.register("MailSendService", MailSendService); } - private static registerServers(depContainer: DependencyContainer): void + private static registerServers(con: DependencyContainer): void { // Servers - depContainer.register("DatabaseServer", DatabaseServer, { lifecycle: Lifecycle.Singleton }); - depContainer.register("HttpServer", HttpServer, { lifecycle: Lifecycle.Singleton }); - depContainer.register("WebSocketServer", WebSocketServer, { lifecycle: Lifecycle.Singleton }); - depContainer.register("RagfairServer", RagfairServer); - depContainer.register("SaveServer", SaveServer, { lifecycle: Lifecycle.Singleton }); - depContainer.register("ConfigServer", ConfigServer, { lifecycle: Lifecycle.Singleton }); + con.register("DatabaseServer", DatabaseServer, {lifecycle: Lifecycle.Singleton}); + con.register("HttpServer", HttpServer, {lifecycle: Lifecycle.Singleton}); + con.register("WebSocketServer", WebSocketServer, {lifecycle: Lifecycle.Singleton}); + con.register("RagfairServer", RagfairServer); + con.register("SaveServer", SaveServer, {lifecycle: Lifecycle.Singleton}); + con.register("ConfigServer", ConfigServer, {lifecycle: Lifecycle.Singleton}); } - private static registerControllers(depContainer: DependencyContainer): void + private static registerControllers(con: DependencyContainer): void { // Controllers - depContainer.register("BotController", { useClass: BotController }); - depContainer.register("ClientLogController", { useClass: ClientLogController }); - depContainer.register("CustomizationController", { useClass: CustomizationController }); - depContainer.register("DialogueController", { useClass: DialogueController }); - depContainer.register("GameController", { useClass: GameController }); - depContainer.register("HandbookController", { useClass: HandbookController }); - depContainer.register("HealthController", { useClass: HealthController }); - depContainer.register("HideoutController", { useClass: HideoutController }); - depContainer.register("InraidController", { useClass: InraidController }); - depContainer.register("InsuranceController", { useClass: InsuranceController }); - depContainer.register("InventoryController", { useClass: InventoryController }); - depContainer.register("LauncherController", { useClass: LauncherController }); - depContainer.register("LocationController", { useClass: LocationController }); - depContainer.register("MatchController", MatchController); - depContainer.register("NoteController", { useClass: NoteController }); - depContainer.register("NotifierController", { useClass: NotifierController }); - depContainer.register("PresetBuildController", { useClass: PresetBuildController }); - depContainer.register("PresetController", { useClass: PresetController }); - depContainer.register("ProfileController", { useClass: ProfileController }); - depContainer.register("QuestController", { useClass: QuestController }); - depContainer.register("RagfairController", { useClass: RagfairController }); - depContainer.register("RepairController", { useClass: RepairController }); - depContainer.register("RepeatableQuestController", { useClass: RepeatableQuestController }); - depContainer.register("TradeController", { useClass: TradeController }); - depContainer.register("TraderController", { useClass: TraderController }); - depContainer.register("WeatherController", { useClass: WeatherController }); - depContainer.register("WishlistController", WishlistController); + con.register("BotController", {useClass: BotController}); + con.register("ClientLogController", {useClass: ClientLogController}); + con.register("CustomizationController", {useClass: CustomizationController}); + con.register("DialogueController", {useClass: DialogueController}); + con.register("GameController", {useClass: GameController}); + con.register("HandbookController", {useClass: HandbookController}); + con.register("HealthController", {useClass: HealthController}); + con.register("HideoutController", {useClass: HideoutController}); + con.register("InraidController", {useClass: InraidController}); + con.register("InsuranceController", {useClass: InsuranceController}); + con.register("InventoryController", {useClass: InventoryController}); + con.register("LauncherController", {useClass: LauncherController}); + con.register("LocationController", {useClass: LocationController}); + con.register("MatchController", MatchController); + con.register("NoteController", {useClass: NoteController}); + con.register("NotifierController", {useClass: NotifierController}); + con.register("PresetBuildController", {useClass: PresetBuildController}); + con.register("PresetController", {useClass: PresetController}); + con.register("ProfileController", {useClass: ProfileController}); + con.register("QuestController", {useClass: QuestController}); + con.register("RagfairController", {useClass: RagfairController}); + con.register("RepairController", {useClass: RepairController}); + con.register("RepeatableQuestController", {useClass: RepeatableQuestController}); + con.register("TradeController", {useClass: TradeController}); + con.register("TraderController", {useClass: TraderController}); + con.register("WeatherController", {useClass: WeatherController}); + con.register("WishlistController", WishlistController); } } diff --git a/project/src/di/OnLoad.ts b/project/src/di/OnLoad.ts index 55631f4f..139f89b3 100644 --- a/project/src/di/OnLoad.ts +++ b/project/src/di/OnLoad.ts @@ -1,5 +1,5 @@ -export interface OnLoad +export interface OnLoad { onLoad(): Promise; getRoute(): string; -} \ No newline at end of file +} diff --git a/project/src/di/OnUpdate.ts b/project/src/di/OnUpdate.ts index 24dcdab9..57362acf 100644 --- a/project/src/di/OnUpdate.ts +++ b/project/src/di/OnUpdate.ts @@ -1,7 +1,5 @@ -export interface OnUpdate +export interface OnUpdate { - // eslint-disable-next-line @typescript-eslint/no-unused-vars onUpdate(timeSinceLastRun: number): Promise; - getRoute(): string; -} \ No newline at end of file +} diff --git a/project/src/di/Router.ts b/project/src/di/Router.ts index 397b5385..ae36542e 100644 --- a/project/src/di/Router.ts +++ b/project/src/di/Router.ts @@ -2,12 +2,11 @@ import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; import { IAkiProfile } from "@spt-aki/models/eft/profile/IAkiProfile"; -export class Router +export class Router { - protected handledRoutes: HandledRoute[] = []; - public getTopLevelRoute(): string + public getTopLevelRoute(): string { return "aki"; } @@ -17,98 +16,96 @@ export class Router throw new Error("This method needs to be overrode by the router classes"); } - protected getInternalHandledRoutes(): HandledRoute[] + protected getInternalHandledRoutes(): HandledRoute[] { - if (this.handledRoutes.length === 0) + if (this.handledRoutes.length === 0) { this.handledRoutes = this.getHandledRoutes(); } return this.handledRoutes; } - public canHandle(url: string, partialMatch = false): boolean + public canHandle(url: string, partialMatch = false): boolean { if (partialMatch) { - return this.getInternalHandledRoutes().filter(r => r.dynamic).some(r => url.includes(r.route)); + return this.getInternalHandledRoutes().filter((r) => r.dynamic).some((r) => url.includes(r.route)); } - else + else { - return this.getInternalHandledRoutes().filter(r => !r.dynamic).some(r => r.route === url); + return this.getInternalHandledRoutes().filter((r) => !r.dynamic).some((r) => r.route === url); } } } -export class StaticRouter extends Router +export class StaticRouter extends Router { - constructor(private routes: RouteAction[]) + constructor(private routes: RouteAction[]) { super(); } - public handleStatic(url: string, info: any, sessionID: string, output: string): any + public handleStatic(url: string, info: any, sessionID: string, output: string): any { - return this.routes.find(route => route.url === url).action(url, info, sessionID, output); + return this.routes.find((route) => route.url === url).action(url, info, sessionID, output); } - public override getHandledRoutes(): HandledRoute[] - { - return this.routes.map(route => new HandledRoute(route.url, false)); + public override getHandledRoutes(): HandledRoute[] + { + return this.routes.map((route) => new HandledRoute(route.url, false)); } } -export class DynamicRouter extends Router +export class DynamicRouter extends Router { - constructor(private routes: RouteAction[]) + constructor(private routes: RouteAction[]) { super(); } - public handleDynamic(url: string, info: any, sessionID: string, output: string): any + public handleDynamic(url: string, info: any, sessionID: string, output: string): any { - return this.routes.find(r => url.includes(r.url)).action(url, info, sessionID, output); + return this.routes.find((r) => url.includes(r.url)).action(url, info, sessionID, output); } - public override getHandledRoutes(): HandledRoute[] - { - return this.routes.map(route => new HandledRoute(route.url, true)); + public override getHandledRoutes(): HandledRoute[] + { + return this.routes.map((route) => new HandledRoute(route.url, true)); } } // The name of this class should be ItemEventRouter, but that name is taken, // So instead I added the definition -export class ItemEventRouterDefinition extends Router +export class ItemEventRouterDefinition extends Router { - // eslint-disable-next-line @typescript-eslint/no-unused-vars public handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse { throw new Error("This method needs to be overrode by the router classes"); } } -export class SaveLoadRouter extends Router +export class SaveLoadRouter extends Router { - // eslint-disable-next-line @typescript-eslint/no-unused-vars public handleLoad(profile: IAkiProfile): IAkiProfile { throw new Error("This method needs to be overrode by the router classes"); } } -export class HandledRoute +export class HandledRoute { constructor( public route: string, - public dynamic: boolean + public dynamic: boolean, ) {} } -export class RouteAction +export class RouteAction { constructor( public url: string, - public action: (url: string, info: any, sessionID: string, output: string) => any - ) + public action: (url: string, info: any, sessionID: string, output: string) => any, + ) {} -} \ No newline at end of file +} diff --git a/project/src/di/Serializer.ts b/project/src/di/Serializer.ts index 38b2fe5c..33b79e72 100644 --- a/project/src/di/Serializer.ts +++ b/project/src/di/Serializer.ts @@ -1,16 +1,14 @@ import { IncomingMessage, ServerResponse } from "node:http"; -export class Serializer +export class Serializer { - // eslint-disable-next-line @typescript-eslint/no-unused-vars public serialize(sessionID: string, req: IncomingMessage, resp: ServerResponse, body: any): void { throw new Error("Should be extended and overrode"); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public canHandle(something: string): boolean { throw new Error("Should be extended and overrode"); } -} \ No newline at end of file +} From 320c8b7d4842de7ffc38cc14b213e1d5ec8754d0 Mon Sep 17 00:00:00 2001 From: Refringe Date: Fri, 10 Nov 2023 17:21:20 -0500 Subject: [PATCH 25/41] Formatting for test classes. --- project/Server.code-workspace | 64 +- project/tests/CustomEnvironment.ts | 17 +- .../__factories__/ProfileInsurance.factory.ts | 16 +- .../__fixture__/profileInsurance.fixture.ts | 2644 ++++++++--------- project/tests/__mocks__/WinstonLogger.mock.ts | 24 +- .../controllers/InsuranceController.test.ts | 331 ++- project/tests/generators/BotGenerator.test.ts | 34 +- .../generators/BotLevelGenerator.test.ts | 17 +- project/tests/helpers/BotHelper.test.ts | 2 +- project/tests/helpers/HandbookHelper.test.ts | 2 +- project/tests/helpers/InRaidHelper.test.ts | 39 +- project/tests/helpers/ItemHelper.test.ts | 199 +- .../services/ItemBaseClassService.test.ts | 9 +- project/tests/services/PaymentService.test.ts | 96 +- project/tests/services/PlayerService.test.ts | 18 +- project/tests/utils/TimeUtil.test.ts | 2 +- 16 files changed, 1765 insertions(+), 1749 deletions(-) diff --git a/project/Server.code-workspace b/project/Server.code-workspace index b989ba88..1758f080 100644 --- a/project/Server.code-workspace +++ b/project/Server.code-workspace @@ -9,8 +9,7 @@ "EditorConfig.EditorConfig", "dprint.dprint", "dbaeumer.vscode-eslint", - "biomejs.biome", - "streetsidesoftware.code-spell-checker" + "biomejs.biome" ] }, "settings": { @@ -18,68 +17,7 @@ "editor.formatOnSave": true, "editor.defaultFormatter": "dprint.dprint", "editor.codeActionsOnSave": [ - "source.fixAll.eslint", "source.organizeImports.biome" - ], - "cSpell.language": "en-GB", - "cSpell.words": [ - "armor", - "asonline", - "behaviour", - "biomejs", - "botreload", - "currexp", - "currlvl", - "dbaeumer", - "deathmatch", - "dprint", - "edgeofdarkness", - "fulfill", - "gethideout", - "gifter", - "hpresource", - "inraid", - "isvalid", - "leftbehind", - "leveled", - "loadout", - "maxlvl", - "medkit", - "MEDSTATION", - "nextlvl", - "offraid", - "peacefullzryachiyevent", - "preparetoescape", - "prevexp", - "profileid", - "Protobuf", - "pscav", - "Ragfair", - "Regen", - "requestid", - "sanitise", - "Sanitised", - "scav", - "scavcase", - "scavs", - "Spawnpoint", - "spawnpoints", - "sptbear", - "sptdeveloper", - "spteasystart", - "sptusec", - "sptzerotohero", - "stackcount", - "statustimer", - "Tarkov", - "toggleable", - "tooshort", - "Ubgl", - "unrestartable", - "usec", - "userbuilds", - "weapongen", - "Wishlist" ] } } diff --git a/project/tests/CustomEnvironment.ts b/project/tests/CustomEnvironment.ts index 1f50af92..0307444e 100644 --- a/project/tests/CustomEnvironment.ts +++ b/project/tests/CustomEnvironment.ts @@ -1,20 +1,17 @@ import "reflect-metadata"; import { container, DependencyContainer, Lifecycle } from "tsyringe"; -// For the Vitest Custom Environment. -import type { Environment } from "vitest"; import { Container } from "@spt-aki/di/Container"; - -// Required for importing the database. -import path from "node:path"; import { IDatabaseTables } from "@spt-aki/models/spt/server/IDatabaseTables"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; import { ImporterUtil } from "@spt-aki/utils/ImporterUtil"; +import path from "node:path"; +import type { Environment } from "vitest"; -// Manually mock for the logger. +// Manually mock the logger. import { WinstonLogger } from "@tests/__mocks__/WinstonLogger.mock"; -export default { +export default { name: "spt-aki-server", transformMode: "ssr", async setup() @@ -24,16 +21,16 @@ export default { Container.registerListTypes(container); // Override registration to the container. - container.register("WinstonLogger", WinstonLogger, { lifecycle: Lifecycle.Singleton }); + container.register("WinstonLogger", WinstonLogger, {lifecycle: Lifecycle.Singleton}); // Import the database. await importDatabase(container); return { async teardown() - {} + {}, }; - } + }, }; /** diff --git a/project/tests/__factories__/ProfileInsurance.factory.ts b/project/tests/__factories__/ProfileInsurance.factory.ts index 991d7363..88e8d501 100644 --- a/project/tests/__factories__/ProfileInsurance.factory.ts +++ b/project/tests/__factories__/ProfileInsurance.factory.ts @@ -1,11 +1,12 @@ import "reflect-metadata"; import { container } from "tsyringe"; -import { format } from "date-fns"; -import { profileInsuranceFixture } from "@tests/__fixture__/profileInsurance.fixture"; -import { Insurance } from "@spt-aki/models/eft/profile/IAkiProfile"; -import { ItemHelper } from "@spt-aki/helpers/ItemHelper"; -type DateInput = number | number[] | { [index: number]: number }; +import { ItemHelper } from "@spt-aki/helpers/ItemHelper"; +import { Insurance } from "@spt-aki/models/eft/profile/IAkiProfile"; +import { profileInsuranceFixture } from "@tests/__fixture__/profileInsurance.fixture"; +import { format } from "date-fns"; + +type DateInput = number | number[] | {[index: number]: number;}; export class ProfileInsuranceFactory { @@ -61,7 +62,7 @@ export class ProfileInsuranceFactory this.profileInsuranceFixture = this.profileInsuranceFixture.map((insurance) => { - insurance.items = insurance.items.filter(item => !itemHelper.isAttachmentAttached(item)); + insurance.items = insurance.items.filter((item) => !itemHelper.isAttachmentAttached(item)); return insurance; }); @@ -78,8 +79,7 @@ export class ProfileInsuranceFactory this.profileInsuranceFixture = this.profileInsuranceFixture.map((insurance) => { - insurance.items = insurance.items.filter(item => itemHelper.isAttachmentAttached(item)); - + insurance.items = insurance.items.filter((item) => itemHelper.isAttachmentAttached(item)); return insurance; }); diff --git a/project/tests/__fixture__/profileInsurance.fixture.ts b/project/tests/__fixture__/profileInsurance.fixture.ts index cff789be..de0b4f19 100644 --- a/project/tests/__fixture__/profileInsurance.fixture.ts +++ b/project/tests/__fixture__/profileInsurance.fixture.ts @@ -2,1411 +2,1411 @@ import { Insurance } from "@spt-aki/models/eft/profile/IAkiProfile"; export const profileInsuranceFixture: Insurance[] = [ { - "scheduledTime": 1698945140, - "traderId": "54cb50c76803fa8b248b4571", // Prapor - "messageContent": { - "templateId": "58fe0e4586f774728248ca13 4", - "type": 8, - "maxStorageTime": 345600, - "text": "", - "profileChangeEvents": [], - "systemData": { - "date": "01.11.2023", - "time": "10:51", - "location": "factory4_day" - } + scheduledTime: 1698945140, + traderId: "54cb50c76803fa8b248b4571", // Prapor + messageContent: { + templateId: "58fe0e4586f774728248ca13 4", + type: 8, + maxStorageTime: 345600, + text: "", + profileChangeEvents: [], + systemData: { + date: "01.11.2023", + time: "10:51", + location: "factory4_day", + }, }, - "items": [ + items: [ { - "_id": "3679078e05f5b14466d6a730", - "_tpl": "5d6d3716a4b9361bc8618872", - "parentId": "5fe49444ae6628187a2e77b8", - "slotId": "hideout", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 55, - "MaxDurability": 55 - } - } - }, - { - "_id": "911a0f04d5d9c7e239807ae0", - "_tpl": "5644bd2b4bdc2d3b4c8b4572", - "parentId": "5fe49444ae6628187a2e77b8", - "slotId": "hideout", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 97.7862549, - "MaxDurability": 100 - } - } - }, - { - "_id": "695b13896108f765e8985698", - "_tpl": "5648a69d4bdc2ded0b8b457b", - "parentId": "5fe49444ae6628187a2e77b8", - "slotId": "hideout", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "bb49d6ceb3e87d8563a06455", - "_tpl": "5df8a4d786f77412672a1e3b", - "parentId": "5fe49444ae6628187a2e77b8", - "slotId": "hideout", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "631f8492de748dec852f7ddf", - "_tpl": "64abd93857958b4249003418", - "parentId": "5fe49444ae6628187a2e77b8", - "slotId": "hideout", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 49.2865, - "MaxDurability": 60 - } - } - }, - { - "_id": "a2b0c716162c5e31ec28c55a", - "_tpl": "5a16b8a9fcdbcb00165aa6ca", - "parentId": "3679078e05f5b14466d6a730", - "slotId": "mod_nvg", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "dc565f750342cb2d19eeda06", - "_tpl": "5d6d3be5a4b9361bc73bc763", - "parentId": "3679078e05f5b14466d6a730", - "slotId": "mod_equipment_001", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 29.33, - "MaxDurability": 29.33 - } - } - }, - { - "_id": "e9ff62601669d9e2ea9c2fbb", - "_tpl": "5d6d3943a4b9360dbc46d0cc", - "parentId": "3679078e05f5b14466d6a730", - "slotId": "mod_equipment_002", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "ac134d7cf6c9d8e25edd0015", - "_tpl": "5c11046cd174af02a012e42b", - "parentId": "a2b0c716162c5e31ec28c55a", - "slotId": "mod_nvg", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "22274b895ecc80d51c3cba1c", - "_tpl": "5c110624d174af029e69734c", - "parentId": "ac134d7cf6c9d8e25edd0015", - "slotId": "mod_nvg", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 + _id: "3679078e05f5b14466d6a730", + _tpl: "5d6d3716a4b9361bc8618872", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 55, + MaxDurability: 55, }, - "Togglable": { - "On": true - } - } - }, - { - "_id": "c9278dd8251e99578bf7a274", - "_tpl": "59c6633186f7740cf0493bb9", - "parentId": "911a0f04d5d9c7e239807ae0", - "slotId": "mod_gas_block", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "677c209ebb45445ebb42c405", - "_tpl": "5649ab884bdc2ded0b8b457f", - "parentId": "911a0f04d5d9c7e239807ae0", - "slotId": "mod_muzzle", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "8ada5c9cc26585281577c6eb", - "_tpl": "5649ae4a4bdc2d1b2b8b4588", - "parentId": "911a0f04d5d9c7e239807ae0", - "slotId": "mod_pistol_grip", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "4bd10f89836fd9f86aedcac1", - "_tpl": "5649af094bdc2df8348b4586", - "parentId": "911a0f04d5d9c7e239807ae0", - "slotId": "mod_reciever", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "8b1327270791b142ac341b03", - "_tpl": "5649d9a14bdc2d79388b4580", - "parentId": "911a0f04d5d9c7e239807ae0", - "slotId": "mod_sight_rear", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "566335b3df586f34b47f5e35", - "_tpl": "5649b2314bdc2d79388b4576", - "parentId": "911a0f04d5d9c7e239807ae0", - "slotId": "mod_stock", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "da8cde1b3024c336f6e06152", - "_tpl": "55d482194bdc2d1d4e8b456b", - "parentId": "911a0f04d5d9c7e239807ae0", - "slotId": "mod_magazine", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "1e0b177df108c0c117028812", - "_tpl": "57cffddc24597763133760c6", - "parentId": "c9278dd8251e99578bf7a274", - "slotId": "mod_handguard", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "bc041c0011d76f714b898400", - "_tpl": "57cffcd624597763133760c5", - "parentId": "1e0b177df108c0c117028812", - "slotId": "mod_mount_003", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "9f8d7880a6e0a47a211ec5d3", - "_tpl": "58491f3324597764bc48fa02", - "parentId": "8b1327270791b142ac341b03", - "slotId": "mod_scope", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "402b4086535a50ef7d9cef88", - "_tpl": "5649be884bdc2d79388b4577", - "parentId": "566335b3df586f34b47f5e35", - "slotId": "mod_stock", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "db2ef9442178910eba985b51", - "_tpl": "58d2946386f774496974c37e", - "parentId": "402b4086535a50ef7d9cef88", - "slotId": "mod_stock_000", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "3c32b7d47ad80e83749fa906", - "_tpl": "58d2912286f7744e27117493", - "parentId": "db2ef9442178910eba985b51", - "slotId": "mod_stock", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "574a9b5535585255cde19570", - "_tpl": "55d482194bdc2d1d4e8b456b", - "parentId": "695b13896108f765e8985698", - "slotId": "1", - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true }, - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } }, { - "_id": "696835b2badfb96623ea887c", - "_tpl": "55d482194bdc2d1d4e8b456b", - "parentId": "695b13896108f765e8985698", - "slotId": "2", - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true + _id: "911a0f04d5d9c7e239807ae0", + _tpl: "5644bd2b4bdc2d3b4c8b4572", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 97.7862549, + MaxDurability: 100, + }, }, - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } }, { - "_id": "c2d5e23c7886e8ff02010731", - "_tpl": "55d482194bdc2d1d4e8b456b", - "parentId": "695b13896108f765e8985698", - "slotId": "3", - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true + _id: "695b13896108f765e8985698", + _tpl: "5648a69d4bdc2ded0b8b457b", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: { + StackObjectsCount: 1, }, - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } }, { - "_id": "306de2f475a559610a4f6f1d", - "_tpl": "55d482194bdc2d1d4e8b456b", - "parentId": "695b13896108f765e8985698", - "slotId": "4", - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true + _id: "bb49d6ceb3e87d8563a06455", + _tpl: "5df8a4d786f77412672a1e3b", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: { + StackObjectsCount: 1, }, - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } }, { - "_id": "eb0445b49a97e84e27d47f3c", - "_tpl": "5aa2ba71e5b5b000137b758f", - "parentId": "695b13896108f765e8985698", - "slotId": "5", - "upd": { - "StackObjectsCount": 1 + _id: "631f8492de748dec852f7ddf", + _tpl: "64abd93857958b4249003418", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 49.2865, + MaxDurability: 60, + }, }, - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true - } }, { - "_id": "fad89a5bdfd23e3248123346", - "_tpl": "5fc5396e900b1d5091531e72", - "parentId": "695b13896108f765e8985698", - "slotId": "6", - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true + _id: "a2b0c716162c5e31ec28c55a", + _tpl: "5a16b8a9fcdbcb00165aa6ca", + parentId: "3679078e05f5b14466d6a730", + slotId: "mod_nvg", + upd: { + StackObjectsCount: 1, }, - "upd": { - "StackObjectsCount": 1 - } }, { - "_id": "b16c2a938954cd69c687c51a", - "_tpl": "5b4736b986f77405cb415c10", - "parentId": "695b13896108f765e8985698", - "slotId": "7", - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true + _id: "dc565f750342cb2d19eeda06", + _tpl: "5d6d3be5a4b9361bc73bc763", + parentId: "3679078e05f5b14466d6a730", + slotId: "mod_equipment_001", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 29.33, + MaxDurability: 29.33, + }, }, - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } }, { - "_id": "a2b3019ac8d340eeb068d429", - "_tpl": "5ea18c84ecf1982c7712d9a2", - "parentId": "695b13896108f765e8985698", - "slotId": "10", - "location": { - "x": 0, - "y": 0, - "r": "Vertical", - "isSearched": true + _id: "e9ff62601669d9e2ea9c2fbb", + _tpl: "5d6d3943a4b9360dbc46d0cc", + parentId: "3679078e05f5b14466d6a730", + slotId: "mod_equipment_002", + upd: { + StackObjectsCount: 1, }, - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 29, - "MaxDurability": 33 - } - } }, { - "_id": "0b3c5d183e8b506d655f85c4", - "_tpl": "644a3df63b0b6f03e101e065", - "parentId": "fad89a5bdfd23e3248123346", - "slotId": "mod_tactical", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "757211a0b648fe27b0475ded", - "_tpl": "59f8a37386f7747af3328f06", - "parentId": "b16c2a938954cd69c687c51a", - "slotId": "mod_foregrip", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "870a887c63ca30fb15736b3d", - "_tpl": "62a1b7fbc30cfa1d366af586", - "parentId": "bb49d6ceb3e87d8563a06455", - "slotId": "main", - "upd": { - "StackObjectsCount": 1 + _id: "ac134d7cf6c9d8e25edd0015", + _tpl: "5c11046cd174af02a012e42b", + parentId: "a2b0c716162c5e31ec28c55a", + slotId: "mod_nvg", + upd: { + StackObjectsCount: 1, }, - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true - } }, { - "_id": "f3de631a1bb2b74bd0160d9a", - "_tpl": "5d6d3be5a4b9361bc73bc763", - "parentId": "bb49d6ceb3e87d8563a06455", - "slotId": "main", - "location": { - "x": 5, - "y": 0, - "r": "Vertical", - "isSearched": true + _id: "22274b895ecc80d51c3cba1c", + _tpl: "5c110624d174af029e69734c", + parentId: "ac134d7cf6c9d8e25edd0015", + slotId: "mod_nvg", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + Togglable: { + On: true, + }, }, - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 22.41, - "MaxDurability": 22.41 - } - } }, { - "_id": "351180f3248d45c71cb2ebdc", - "_tpl": "57c44b372459772d2b39b8ce", - "parentId": "870a887c63ca30fb15736b3d", - "slotId": "main", - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true + _id: "c9278dd8251e99578bf7a274", + _tpl: "59c6633186f7740cf0493bb9", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_gas_block", + upd: { + StackObjectsCount: 1, }, - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } }, { - "_id": "7237f722106866f2df8dc8d1", - "_tpl": "56e33680d2720be2748b4576", - "parentId": "870a887c63ca30fb15736b3d", - "slotId": "main", - "location": { - "x": 0, - "y": 3, - "r": "Horizontal", - "isSearched": true + _id: "677c209ebb45445ebb42c405", + _tpl: "5649ab884bdc2ded0b8b457f", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_muzzle", + upd: { + StackObjectsCount: 1, }, - "upd": { - "StackObjectsCount": 1 - } }, { - "_id": "d0cf00aff56ea520cdd94330", - "_tpl": "57c44dd02459772d2e0ae249", - "parentId": "351180f3248d45c71cb2ebdc", - "slotId": "mod_muzzle", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "5119653b2c66d57ee219e26f", - "_tpl": "57c44f4f2459772d2c627113", - "parentId": "351180f3248d45c71cb2ebdc", - "slotId": "mod_reciever", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "ed1ac0183a8af587110aa74e", - "_tpl": "5a9e81fba2750c00164f6b11", - "parentId": "351180f3248d45c71cb2ebdc", - "slotId": "mod_magazine", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "310a7d1bb07ae0e522f3f8e3", - "_tpl": "5a69a2ed8dc32e000d46d1f1", - "parentId": "351180f3248d45c71cb2ebdc", - "slotId": "mod_pistol_grip", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "8a7e3489197b3b98126447fd", - "_tpl": "6130ca3fd92c473c77020dbd", - "parentId": "351180f3248d45c71cb2ebdc", - "slotId": "mod_charge", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "e818616e11ae07aa05388759", - "_tpl": "5dff8db859400025ea5150d4", - "parentId": "351180f3248d45c71cb2ebdc", - "slotId": "mod_mount_000", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "768812984debf2756bece089", - "_tpl": "57c44e7b2459772d28133248", - "parentId": "d0cf00aff56ea520cdd94330", - "slotId": "mod_sight_rear", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "67c610585ed668baf4604931", - "_tpl": "59eb7ebe86f7740b373438ce", - "parentId": "d0cf00aff56ea520cdd94330", - "slotId": "mod_mount_000", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "80e9dffa49bfe263ab0128c7", - "_tpl": "6267c6396b642f77f56f5c1c", - "parentId": "67c610585ed668baf4604931", - "slotId": "mod_tactical_000", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "dee323443ce23ba8c54b9f1c", - "_tpl": "5cc9c20cd7f00c001336c65d", - "parentId": "67c610585ed668baf4604931", - "slotId": "mod_tactical_001", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "3008088022dd55f1c99e5a32", - "_tpl": "5c1cd46f2e22164bef5cfedb", - "parentId": "67c610585ed668baf4604931", - "slotId": "mod_foregrip", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "71e9f8d005c72940d857fe64", - "_tpl": "59d790f486f77403cb06aec6", - "parentId": "80e9dffa49bfe263ab0128c7", - "slotId": "mod_flashlight", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "8c610c6cc67115a5fc1662ff", - "_tpl": "56eabf3bd2720b75698b4569", - "parentId": "310a7d1bb07ae0e522f3f8e3", - "slotId": "mod_stock_000", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "9bf01177f0c1e346b2d65373", - "_tpl": "58d2912286f7744e27117493", - "parentId": "8c610c6cc67115a5fc1662ff", - "slotId": "mod_stock", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "7dd43ffa6e03c2da6cddc56e", - "_tpl": "6171407e50224f204c1da3c5", - "parentId": "e818616e11ae07aa05388759", - "slotId": "mod_scope", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "fa9da4ccf3630cb173c293f9", - "_tpl": "5b3b99475acfc432ff4dcbee", - "parentId": "7dd43ffa6e03c2da6cddc56e", - "slotId": "mod_scope_000", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "6e2727806fb12e12123e9a57", - "_tpl": "616554fe50224f204c1da2aa", - "parentId": "7dd43ffa6e03c2da6cddc56e", - "slotId": "mod_scope_001", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "2c868d4676adc934f897e9a7", - "_tpl": "61605d88ffa6e502ac5e7eeb", - "parentId": "7dd43ffa6e03c2da6cddc56e", - "slotId": "mod_scope_002", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "1b159fdc14c350f8a4a7e19e", - "_tpl": "58d39b0386f77443380bf13c", - "parentId": "6e2727806fb12e12123e9a57", - "slotId": "mod_scope", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "7691790ffc5290da292cab99", - "_tpl": "61657230d92c473c770213d7", - "parentId": "1b159fdc14c350f8a4a7e19e", - "slotId": "mod_scope", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "012a11e7dcb1280a1ab9d2f6", - "_tpl": "618168b350224f204c1da4d8", - "parentId": "7237f722106866f2df8dc8d1", - "slotId": "main", - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true + _id: "8ada5c9cc26585281577c6eb", + _tpl: "5649ae4a4bdc2d1b2b8b4588", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_pistol_grip", + upd: { + StackObjectsCount: 1, }, - "upd": { - "StackObjectsCount": 1 - } }, { - "_id": "38ca7415a458c4d22ba2f3c3", - "_tpl": "6130c43c67085e45ef1405a1", - "parentId": "012a11e7dcb1280a1ab9d2f6", - "slotId": "mod_muzzle", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } + _id: "4bd10f89836fd9f86aedcac1", + _tpl: "5649af094bdc2df8348b4586", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_reciever", + upd: { + StackObjectsCount: 1, + }, }, { - "_id": "c5a0621ebf856ce1b0945efc", - "_tpl": "61816fcad92c473c770215cc", - "parentId": "012a11e7dcb1280a1ab9d2f6", - "slotId": "mod_sight_front", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } + _id: "8b1327270791b142ac341b03", + _tpl: "5649d9a14bdc2d79388b4580", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_sight_rear", + upd: { + StackObjectsCount: 1, + }, }, { - "_id": "a74677b17c1c49edc002df9b", - "_tpl": "5dfa3d2b0dee1b22f862eade", - "parentId": "38ca7415a458c4d22ba2f3c3", - "slotId": "mod_muzzle", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - } - ] + _id: "566335b3df586f34b47f5e35", + _tpl: "5649b2314bdc2d79388b4576", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_stock", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "da8cde1b3024c336f6e06152", + _tpl: "55d482194bdc2d1d4e8b456b", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_magazine", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "1e0b177df108c0c117028812", + _tpl: "57cffddc24597763133760c6", + parentId: "c9278dd8251e99578bf7a274", + slotId: "mod_handguard", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "bc041c0011d76f714b898400", + _tpl: "57cffcd624597763133760c5", + parentId: "1e0b177df108c0c117028812", + slotId: "mod_mount_003", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "9f8d7880a6e0a47a211ec5d3", + _tpl: "58491f3324597764bc48fa02", + parentId: "8b1327270791b142ac341b03", + slotId: "mod_scope", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "402b4086535a50ef7d9cef88", + _tpl: "5649be884bdc2d79388b4577", + parentId: "566335b3df586f34b47f5e35", + slotId: "mod_stock", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "db2ef9442178910eba985b51", + _tpl: "58d2946386f774496974c37e", + parentId: "402b4086535a50ef7d9cef88", + slotId: "mod_stock_000", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "3c32b7d47ad80e83749fa906", + _tpl: "58d2912286f7744e27117493", + parentId: "db2ef9442178910eba985b51", + slotId: "mod_stock", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "574a9b5535585255cde19570", + _tpl: "55d482194bdc2d1d4e8b456b", + parentId: "695b13896108f765e8985698", + slotId: "1", + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "696835b2badfb96623ea887c", + _tpl: "55d482194bdc2d1d4e8b456b", + parentId: "695b13896108f765e8985698", + slotId: "2", + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "c2d5e23c7886e8ff02010731", + _tpl: "55d482194bdc2d1d4e8b456b", + parentId: "695b13896108f765e8985698", + slotId: "3", + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "306de2f475a559610a4f6f1d", + _tpl: "55d482194bdc2d1d4e8b456b", + parentId: "695b13896108f765e8985698", + slotId: "4", + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "eb0445b49a97e84e27d47f3c", + _tpl: "5aa2ba71e5b5b000137b758f", + parentId: "695b13896108f765e8985698", + slotId: "5", + upd: { + StackObjectsCount: 1, + }, + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + }, + { + _id: "fad89a5bdfd23e3248123346", + _tpl: "5fc5396e900b1d5091531e72", + parentId: "695b13896108f765e8985698", + slotId: "6", + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "b16c2a938954cd69c687c51a", + _tpl: "5b4736b986f77405cb415c10", + parentId: "695b13896108f765e8985698", + slotId: "7", + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "a2b3019ac8d340eeb068d429", + _tpl: "5ea18c84ecf1982c7712d9a2", + parentId: "695b13896108f765e8985698", + slotId: "10", + location: { + x: 0, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 29, + MaxDurability: 33, + }, + }, + }, + { + _id: "0b3c5d183e8b506d655f85c4", + _tpl: "644a3df63b0b6f03e101e065", + parentId: "fad89a5bdfd23e3248123346", + slotId: "mod_tactical", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "757211a0b648fe27b0475ded", + _tpl: "59f8a37386f7747af3328f06", + parentId: "b16c2a938954cd69c687c51a", + slotId: "mod_foregrip", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "870a887c63ca30fb15736b3d", + _tpl: "62a1b7fbc30cfa1d366af586", + parentId: "bb49d6ceb3e87d8563a06455", + slotId: "main", + upd: { + StackObjectsCount: 1, + }, + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + }, + { + _id: "f3de631a1bb2b74bd0160d9a", + _tpl: "5d6d3be5a4b9361bc73bc763", + parentId: "bb49d6ceb3e87d8563a06455", + slotId: "main", + location: { + x: 5, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 22.41, + MaxDurability: 22.41, + }, + }, + }, + { + _id: "351180f3248d45c71cb2ebdc", + _tpl: "57c44b372459772d2b39b8ce", + parentId: "870a887c63ca30fb15736b3d", + slotId: "main", + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "7237f722106866f2df8dc8d1", + _tpl: "56e33680d2720be2748b4576", + parentId: "870a887c63ca30fb15736b3d", + slotId: "main", + location: { + x: 0, + y: 3, + r: "Horizontal", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "d0cf00aff56ea520cdd94330", + _tpl: "57c44dd02459772d2e0ae249", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_muzzle", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "5119653b2c66d57ee219e26f", + _tpl: "57c44f4f2459772d2c627113", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_reciever", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "ed1ac0183a8af587110aa74e", + _tpl: "5a9e81fba2750c00164f6b11", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_magazine", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "310a7d1bb07ae0e522f3f8e3", + _tpl: "5a69a2ed8dc32e000d46d1f1", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_pistol_grip", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "8a7e3489197b3b98126447fd", + _tpl: "6130ca3fd92c473c77020dbd", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_charge", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "e818616e11ae07aa05388759", + _tpl: "5dff8db859400025ea5150d4", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_mount_000", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "768812984debf2756bece089", + _tpl: "57c44e7b2459772d28133248", + parentId: "d0cf00aff56ea520cdd94330", + slotId: "mod_sight_rear", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "67c610585ed668baf4604931", + _tpl: "59eb7ebe86f7740b373438ce", + parentId: "d0cf00aff56ea520cdd94330", + slotId: "mod_mount_000", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "80e9dffa49bfe263ab0128c7", + _tpl: "6267c6396b642f77f56f5c1c", + parentId: "67c610585ed668baf4604931", + slotId: "mod_tactical_000", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "dee323443ce23ba8c54b9f1c", + _tpl: "5cc9c20cd7f00c001336c65d", + parentId: "67c610585ed668baf4604931", + slotId: "mod_tactical_001", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "3008088022dd55f1c99e5a32", + _tpl: "5c1cd46f2e22164bef5cfedb", + parentId: "67c610585ed668baf4604931", + slotId: "mod_foregrip", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "71e9f8d005c72940d857fe64", + _tpl: "59d790f486f77403cb06aec6", + parentId: "80e9dffa49bfe263ab0128c7", + slotId: "mod_flashlight", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "8c610c6cc67115a5fc1662ff", + _tpl: "56eabf3bd2720b75698b4569", + parentId: "310a7d1bb07ae0e522f3f8e3", + slotId: "mod_stock_000", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "9bf01177f0c1e346b2d65373", + _tpl: "58d2912286f7744e27117493", + parentId: "8c610c6cc67115a5fc1662ff", + slotId: "mod_stock", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "7dd43ffa6e03c2da6cddc56e", + _tpl: "6171407e50224f204c1da3c5", + parentId: "e818616e11ae07aa05388759", + slotId: "mod_scope", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "fa9da4ccf3630cb173c293f9", + _tpl: "5b3b99475acfc432ff4dcbee", + parentId: "7dd43ffa6e03c2da6cddc56e", + slotId: "mod_scope_000", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "6e2727806fb12e12123e9a57", + _tpl: "616554fe50224f204c1da2aa", + parentId: "7dd43ffa6e03c2da6cddc56e", + slotId: "mod_scope_001", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "2c868d4676adc934f897e9a7", + _tpl: "61605d88ffa6e502ac5e7eeb", + parentId: "7dd43ffa6e03c2da6cddc56e", + slotId: "mod_scope_002", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "1b159fdc14c350f8a4a7e19e", + _tpl: "58d39b0386f77443380bf13c", + parentId: "6e2727806fb12e12123e9a57", + slotId: "mod_scope", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "7691790ffc5290da292cab99", + _tpl: "61657230d92c473c770213d7", + parentId: "1b159fdc14c350f8a4a7e19e", + slotId: "mod_scope", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "012a11e7dcb1280a1ab9d2f6", + _tpl: "618168b350224f204c1da4d8", + parentId: "7237f722106866f2df8dc8d1", + slotId: "main", + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "38ca7415a458c4d22ba2f3c3", + _tpl: "6130c43c67085e45ef1405a1", + parentId: "012a11e7dcb1280a1ab9d2f6", + slotId: "mod_muzzle", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "c5a0621ebf856ce1b0945efc", + _tpl: "61816fcad92c473c770215cc", + parentId: "012a11e7dcb1280a1ab9d2f6", + slotId: "mod_sight_front", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "a74677b17c1c49edc002df9b", + _tpl: "5dfa3d2b0dee1b22f862eade", + parentId: "38ca7415a458c4d22ba2f3c3", + slotId: "mod_muzzle", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + ], }, { - "scheduledTime": 1698945140, - "traderId": "54cb57776803fa99248b456e", // Therapist - "messageContent": { - "templateId": "58fe0e3486f77471f772c3f2 2", - "type": 8, - "maxStorageTime": 518400, - "text": "", - "profileChangeEvents": [], - "systemData": { - "date": "01.11.2023", - "time": "11:18", - "location": "factory4_day" - } + scheduledTime: 1698945140, + traderId: "54cb57776803fa99248b456e", // Therapist + messageContent: { + templateId: "58fe0e3486f77471f772c3f2 2", + type: 8, + maxStorageTime: 518400, + text: "", + profileChangeEvents: [], + systemData: { + date: "01.11.2023", + time: "11:18", + location: "factory4_day", + }, }, - "items": [ + items: [ { - "_id": "5ae1c2b99a0a339adc620148", - "_tpl": "5cebec38d7f00c00110a652a", - "parentId": "ad018df9da0cbf2726394ef1", - "slotId": "mod_mount_000", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "30f4bcb87bcc4604e27c02c1", - "_tpl": "5cc70146e4a949000d73bf6b", - "parentId": "ad018df9da0cbf2726394ef1", - "slotId": "mod_mount_001", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "ad018df9da0cbf2726394ef1", - "_tpl": "5cc70102e4a949035e43ba74", - "parentId": "3bc4ff5bd99f165dc75cbd25", - "slotId": "main", - "upd": { - "StackObjectsCount": 1 + _id: "5ae1c2b99a0a339adc620148", + _tpl: "5cebec38d7f00c00110a652a", + parentId: "ad018df9da0cbf2726394ef1", + slotId: "mod_mount_000", + upd: { + StackObjectsCount: 1, }, - "location": { - "x": 3, - "y": 0, - "r": "Horizontal", - "isSearched": true - } }, { - "_id": "12c243bd6b3e486e61325f81", - "_tpl": "5cc82d76e24e8d00134b4b83", - "parentId": "5fe49444ae6628187a2e77b8", - "slotId": "hideout", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 99.93771, - "MaxDurability": 100 - } - } + _id: "30f4bcb87bcc4604e27c02c1", + _tpl: "5cc70146e4a949000d73bf6b", + parentId: "ad018df9da0cbf2726394ef1", + slotId: "mod_mount_001", + upd: { + StackObjectsCount: 1, + }, }, { - "_id": "760652d86ee78eed513e0ad7", - "_tpl": "5ab8f39486f7745cd93a1cca", - "parentId": "5fe49444ae6628187a2e77b8", - "slotId": "hideout", - "upd": { - "StackObjectsCount": 1 - } + _id: "ad018df9da0cbf2726394ef1", + _tpl: "5cc70102e4a949035e43ba74", + parentId: "3bc4ff5bd99f165dc75cbd25", + slotId: "main", + upd: { + StackObjectsCount: 1, + }, + location: { + x: 3, + y: 0, + r: "Horizontal", + isSearched: true, + }, }, { - "_id": "61ab4afefac354dfc64c7874", - "_tpl": "5b432d215acfc4771e1c6624", - "parentId": "5fe49444ae6628187a2e77b8", - "slotId": "hideout", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 30, - "MaxDurability": 30 - } - } - }, - { - "_id": "285e9d9ae196ae4e336cd04f", - "_tpl": "5d5d87f786f77427997cfaef", - "parentId": "5fe49444ae6628187a2e77b8", - "slotId": "hideout", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 75, - "MaxDurability": 80 - } - } - }, - { - "_id": "3bc4ff5bd99f165dc75cbd25", - "_tpl": "5f5e467b0bc58666c37e7821", - "parentId": "5fe49444ae6628187a2e77b8", - "slotId": "hideout", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "6bf5d8ee81a3c9aec21bbbad", - "_tpl": "5d5fca1ea4b93635fd598c07", - "parentId": "5fe49444ae6628187a2e77b8", - "slotId": "hideout", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "2371438cf809b5e483bf5d85", - "_tpl": "5cc70093e4a949033c734312", - "parentId": "12c243bd6b3e486e61325f81", - "slotId": "mod_magazine", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "7f890346ea5b2cbc68c3170f", - "_tpl": "5cc700b9e4a949000f0f0f25", - "parentId": "12c243bd6b3e486e61325f81", - "slotId": "mod_stock", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "12fb79a9c4929009ff8d89e1", - "_tpl": "5cc700ede4a949033c734315", - "parentId": "12c243bd6b3e486e61325f81", - "slotId": "mod_reciever", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "d4c5274082ed716e19447f46", - "_tpl": "5cc701d7e4a94900100ac4e7", - "parentId": "12c243bd6b3e486e61325f81", - "slotId": "mod_barrel", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "d819dd4d2b13de10e9d6d805", - "_tpl": "5cc6ea85e4a949000e1ea3c3", - "parentId": "12c243bd6b3e486e61325f81", - "slotId": "mod_charge", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "fc9a664cacc477c4e725a81a", - "_tpl": "5cc700d4e4a949000f0f0f28", - "parentId": "7f890346ea5b2cbc68c3170f", - "slotId": "mod_stock_000", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "372891c593cf14e176b93ce2", - "_tpl": "5cc7012ae4a949001252b43e", - "parentId": "12fb79a9c4929009ff8d89e1", - "slotId": "mod_mount_000", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "bd196435a57bdc433df1e49d", - "_tpl": "5cc7012ae4a949001252b43e", - "parentId": "12fb79a9c4929009ff8d89e1", - "slotId": "mod_mount_001", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "ea3349d29797354d835c2192", - "_tpl": "58491f3324597764bc48fa02", - "parentId": "12fb79a9c4929009ff8d89e1", - "slotId": "mod_scope", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "4ccf7c74ca7d2167deb0ae5c", - "_tpl": "626becf9582c3e319310b837", - "parentId": "372891c593cf14e176b93ce2", - "slotId": "mod_tactical", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "adfd3640fc93daf21c721ca6", - "_tpl": "5cc9c20cd7f00c001336c65d", - "parentId": "bd196435a57bdc433df1e49d", - "slotId": "mod_tactical", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "deeb36b1812790b0145d2532", - "_tpl": "5a16badafcdbcb001865f72d", - "parentId": "61ab4afefac354dfc64c7874", - "slotId": "mod_equipment_000", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 12, - "MaxDurability": 25 - } - } - }, - { - "_id": "4c0e0548df904c384569190c", - "_tpl": "5ea058e01dbce517f324b3e2", - "parentId": "61ab4afefac354dfc64c7874", - "slotId": "mod_nvg", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 3, - "MaxDurability": 39 - } - } - }, - { - "_id": "da82c293cabc705b30fef93a", - "_tpl": "5a398ab9c4a282000c5a9842", - "parentId": "61ab4afefac354dfc64c7874", - "slotId": "mod_mount", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "b8fc94611def6e9ba534a8b3", - "_tpl": "5a16b8a9fcdbcb00165aa6ca", - "parentId": "4c0e0548df904c384569190c", - "slotId": "mod_nvg", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "20d6193c1f399e6326ebbc10", - "_tpl": "5a16b93dfcdbcbcae6687261", - "parentId": "b8fc94611def6e9ba534a8b3", - "slotId": "mod_nvg", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - }, - { - "_id": "065c4f13b2bd8be266e1e809", - "_tpl": "57235b6f24597759bf5a30f1", - "parentId": "20d6193c1f399e6326ebbc10", - "slotId": "mod_nvg", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 + _id: "12c243bd6b3e486e61325f81", + _tpl: "5cc82d76e24e8d00134b4b83", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 99.93771, + MaxDurability: 100, }, - "Togglable": { - "On": true - } - } - }, - { - "_id": "1883b955ab202fa099809278", - "_tpl": "57d17c5e2459775a5c57d17d", - "parentId": "da82c293cabc705b30fef93a", - "slotId": "mod_flashlight", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "e3c9e50ce31900c950b4ff6f", - "_tpl": "5cc70093e4a949033c734312", - "parentId": "285e9d9ae196ae4e336cd04f", - "slotId": "1", - "location": { - "x": 0, - "y": 0, - "r": "Vertical", - "isSearched": true }, - "upd": { - "StackObjectsCount": 1 - } }, { - "_id": "193259b5eb848af4d036bee5", - "_tpl": "5cc70093e4a949033c734312", - "parentId": "285e9d9ae196ae4e336cd04f", - "slotId": "2", - "location": { - "x": 0, - "y": 0, - "r": "Vertical", - "isSearched": true + _id: "760652d86ee78eed513e0ad7", + _tpl: "5ab8f39486f7745cd93a1cca", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: { + StackObjectsCount: 1, }, - "upd": { - "StackObjectsCount": 1 - } }, { - "_id": "f97ce69443f63bbe8f8097a7", - "_tpl": "5cc70093e4a949033c734312", - "parentId": "285e9d9ae196ae4e336cd04f", - "slotId": "3", - "location": { - "x": 0, - "y": 0, - "r": "Vertical", - "isSearched": true - }, - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "5d1c154a8abcfa934e477ac4", - "_tpl": "5cc70093e4a949033c734312", - "parentId": "285e9d9ae196ae4e336cd04f", - "slotId": "4", - "location": { - "x": 0, - "y": 0, - "r": "Vertical", - "isSearched": true - }, - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "289f7af841690c5388095477", - "_tpl": "5cc70093e4a949033c734312", - "parentId": "285e9d9ae196ae4e336cd04f", - "slotId": "5", - "location": { - "x": 0, - "y": 0, - "r": "Vertical", - "isSearched": true - }, - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "3e6d578165b61aef9865f677", - "_tpl": "5cc70093e4a949033c734312", - "parentId": "285e9d9ae196ae4e336cd04f", - "slotId": "6", - "location": { - "x": 0, - "y": 0, - "r": "Vertical", - "isSearched": true - }, - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "338682523f8504f97f84f3ab", - "_tpl": "5cc70093e4a949033c734312", - "parentId": "285e9d9ae196ae4e336cd04f", - "slotId": "7", - "location": { - "x": 0, - "y": 0, - "r": "Vertical", - "isSearched": true - }, - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "6d18ac01aa04b16e4f0d5d2f", - "_tpl": "5cc70093e4a949033c734312", - "parentId": "285e9d9ae196ae4e336cd04f", - "slotId": "8", - "location": { - "x": 0, - "y": 0, - "r": "Vertical", - "isSearched": true - }, - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "ac4ed54d61daa0c5219f8522", - "_tpl": "5cc70093e4a949033c734312", - "parentId": "285e9d9ae196ae4e336cd04f", - "slotId": "9", - "location": { - "x": 0, - "y": 0, - "r": "Vertical", - "isSearched": true - }, - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "2460460ef3d3df5c1ce07edb", - "_tpl": "5cc70093e4a949033c734312", - "parentId": "285e9d9ae196ae4e336cd04f", - "slotId": "10", - "location": { - "x": 0, - "y": 0, - "r": "Vertical", - "isSearched": true - }, - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "3aeb18aac0b532f34255f162", - "_tpl": "5cc70146e4a949000d73bf6b", - "parentId": "285e9d9ae196ae4e336cd04f", - "slotId": "11", - "upd": { - "StackObjectsCount": 1 - }, - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true - } - }, - { - "_id": "bdb46107abbf1d92edaaf14e", - "_tpl": "6272379924e29f06af4d5ecb", - "parentId": "3aeb18aac0b532f34255f162", - "slotId": "mod_tactical", - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "0caadd8507a36d9ea871e88e", - "_tpl": "5ab8f04f86f774585f4237d8", - "parentId": "3bc4ff5bd99f165dc75cbd25", - "slotId": "main", - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true - }, - "upd": { - "StackObjectsCount": 1 - } - }, - { - "_id": "240046eebc9040c1d7e58611", - "_tpl": "5ac66d015acfc400180ae6e4", - "parentId": "0caadd8507a36d9ea871e88e", - "slotId": "main", - "location": { - "x": 0, - "y": 0, - "r": "Horizontal", - "isSearched": true - }, - "upd": { - "StackObjectsCount": 1, - "sptPresetId": "5acf7dfc86f774401e19c390", - "Repairable": { - "Durability": 32, - "MaxDurability": 59 + _id: "61ab4afefac354dfc64c7874", + _tpl: "5b432d215acfc4771e1c6624", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 30, + MaxDurability: 30, }, - "Foldable": { - "Folded": true - } - } + }, }, { - "_id": "70b23c628fa17699d9a71e94", - "_tpl": "59c6633186f7740cf0493bb9", - "parentId": "240046eebc9040c1d7e58611", - "slotId": "mod_gas_block", - "upd": { - "StackObjectsCount": 1, - "sptPresetId": "5acf7dfc86f774401e19c390", - "Repairable": { - "Durability": 32, - "MaxDurability": 59 - } - } + _id: "285e9d9ae196ae4e336cd04f", + _tpl: "5d5d87f786f77427997cfaef", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 75, + MaxDurability: 80, + }, + }, }, { - "_id": "7cc2e24dc6bc0716bdddc472", - "_tpl": "5943ee5a86f77413872d25ec", - "parentId": "240046eebc9040c1d7e58611", - "slotId": "mod_muzzle", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } + _id: "3bc4ff5bd99f165dc75cbd25", + _tpl: "5f5e467b0bc58666c37e7821", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: { + StackObjectsCount: 1, + }, }, { - "_id": "7a51ebbad703082660d59d27", - "_tpl": "5649ade84bdc2d1b2b8b4587", - "parentId": "240046eebc9040c1d7e58611", - "slotId": "mod_pistol_grip", - "upd": { - "StackObjectsCount": 1, - "sptPresetId": "5acf7dfc86f774401e19c390", - "Repairable": { - "Durability": 32, - "MaxDurability": 59 - } - } + _id: "6bf5d8ee81a3c9aec21bbbad", + _tpl: "5d5fca1ea4b93635fd598c07", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: { + StackObjectsCount: 1, + }, }, { - "_id": "b481bc57436ed9a0c3abe7f3", - "_tpl": "5d2c76ed48f03532f2136169", - "parentId": "240046eebc9040c1d7e58611", - "slotId": "mod_reciever", - "upd": { - "StackObjectsCount": 1 - } + _id: "2371438cf809b5e483bf5d85", + _tpl: "5cc70093e4a949033c734312", + parentId: "12c243bd6b3e486e61325f81", + slotId: "mod_magazine", + upd: { + StackObjectsCount: 1, + }, }, { - "_id": "5774ef80597c7f91bff40dbb", - "_tpl": "5ac50c185acfc400163398d4", - "parentId": "240046eebc9040c1d7e58611", - "slotId": "mod_stock", - "upd": { - "StackObjectsCount": 1, - "sptPresetId": "5acf7dfc86f774401e19c390", - "Repairable": { - "Durability": 32, - "MaxDurability": 59 - } - } + _id: "7f890346ea5b2cbc68c3170f", + _tpl: "5cc700b9e4a949000f0f0f25", + parentId: "12c243bd6b3e486e61325f81", + slotId: "mod_stock", + upd: { + StackObjectsCount: 1, + }, }, { - "_id": "8b7c8e6ba172ac390c99a2ae", - "_tpl": "5ac66c5d5acfc4001718d314", - "parentId": "240046eebc9040c1d7e58611", - "slotId": "mod_magazine", - "upd": { - "StackObjectsCount": 1 - } + _id: "12fb79a9c4929009ff8d89e1", + _tpl: "5cc700ede4a949033c734315", + parentId: "12c243bd6b3e486e61325f81", + slotId: "mod_reciever", + upd: { + StackObjectsCount: 1, + }, }, { - "_id": "1ed3a416b1fc7adbed1160df", - "_tpl": "6130ca3fd92c473c77020dbd", - "parentId": "240046eebc9040c1d7e58611", - "slotId": "mod_charge", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } + _id: "d4c5274082ed716e19447f46", + _tpl: "5cc701d7e4a94900100ac4e7", + parentId: "12c243bd6b3e486e61325f81", + slotId: "mod_barrel", + upd: { + StackObjectsCount: 1, + }, }, { - "_id": "bbe087661947c0d9c1cde146", - "_tpl": "5648b1504bdc2d9d488b4584", - "parentId": "70b23c628fa17699d9a71e94", - "slotId": "mod_handguard", - "upd": { - "StackObjectsCount": 1, - "sptPresetId": "5acf7dfc86f774401e19c390", - "Repairable": { - "Durability": 32, - "MaxDurability": 59 - } - } + _id: "d819dd4d2b13de10e9d6d805", + _tpl: "5cc6ea85e4a949000e1ea3c3", + parentId: "12c243bd6b3e486e61325f81", + slotId: "mod_charge", + upd: { + StackObjectsCount: 1, + }, }, { - "_id": "724388f8110434efccd79b3a", - "_tpl": "544a3a774bdc2d3a388b4567", - "parentId": "b481bc57436ed9a0c3abe7f3", - "slotId": "mod_scope", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } + _id: "fc9a664cacc477c4e725a81a", + _tpl: "5cc700d4e4a949000f0f0f28", + parentId: "7f890346ea5b2cbc68c3170f", + slotId: "mod_stock_000", + upd: { + StackObjectsCount: 1, + }, }, { - "_id": "8581038b0f795618a3d26c94", - "_tpl": "58d268fc86f774111273f8c2", - "parentId": "724388f8110434efccd79b3a", - "slotId": "mod_scope", - "upd": { - "StackObjectsCount": 1, - "Repairable": { - "Durability": 100, - "MaxDurability": 100 - } - } - } - ] - } + _id: "372891c593cf14e176b93ce2", + _tpl: "5cc7012ae4a949001252b43e", + parentId: "12fb79a9c4929009ff8d89e1", + slotId: "mod_mount_000", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "bd196435a57bdc433df1e49d", + _tpl: "5cc7012ae4a949001252b43e", + parentId: "12fb79a9c4929009ff8d89e1", + slotId: "mod_mount_001", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "ea3349d29797354d835c2192", + _tpl: "58491f3324597764bc48fa02", + parentId: "12fb79a9c4929009ff8d89e1", + slotId: "mod_scope", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "4ccf7c74ca7d2167deb0ae5c", + _tpl: "626becf9582c3e319310b837", + parentId: "372891c593cf14e176b93ce2", + slotId: "mod_tactical", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "adfd3640fc93daf21c721ca6", + _tpl: "5cc9c20cd7f00c001336c65d", + parentId: "bd196435a57bdc433df1e49d", + slotId: "mod_tactical", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "deeb36b1812790b0145d2532", + _tpl: "5a16badafcdbcb001865f72d", + parentId: "61ab4afefac354dfc64c7874", + slotId: "mod_equipment_000", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 12, + MaxDurability: 25, + }, + }, + }, + { + _id: "4c0e0548df904c384569190c", + _tpl: "5ea058e01dbce517f324b3e2", + parentId: "61ab4afefac354dfc64c7874", + slotId: "mod_nvg", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 3, + MaxDurability: 39, + }, + }, + }, + { + _id: "da82c293cabc705b30fef93a", + _tpl: "5a398ab9c4a282000c5a9842", + parentId: "61ab4afefac354dfc64c7874", + slotId: "mod_mount", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "b8fc94611def6e9ba534a8b3", + _tpl: "5a16b8a9fcdbcb00165aa6ca", + parentId: "4c0e0548df904c384569190c", + slotId: "mod_nvg", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "20d6193c1f399e6326ebbc10", + _tpl: "5a16b93dfcdbcbcae6687261", + parentId: "b8fc94611def6e9ba534a8b3", + slotId: "mod_nvg", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "065c4f13b2bd8be266e1e809", + _tpl: "57235b6f24597759bf5a30f1", + parentId: "20d6193c1f399e6326ebbc10", + slotId: "mod_nvg", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + Togglable: { + On: true, + }, + }, + }, + { + _id: "1883b955ab202fa099809278", + _tpl: "57d17c5e2459775a5c57d17d", + parentId: "da82c293cabc705b30fef93a", + slotId: "mod_flashlight", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "e3c9e50ce31900c950b4ff6f", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "1", + location: { + x: 0, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "193259b5eb848af4d036bee5", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "2", + location: { + x: 0, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "f97ce69443f63bbe8f8097a7", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "3", + location: { + x: 0, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "5d1c154a8abcfa934e477ac4", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "4", + location: { + x: 0, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "289f7af841690c5388095477", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "5", + location: { + x: 0, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "3e6d578165b61aef9865f677", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "6", + location: { + x: 0, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "338682523f8504f97f84f3ab", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "7", + location: { + x: 0, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "6d18ac01aa04b16e4f0d5d2f", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "8", + location: { + x: 0, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "ac4ed54d61daa0c5219f8522", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "9", + location: { + x: 0, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "2460460ef3d3df5c1ce07edb", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "10", + location: { + x: 0, + y: 0, + r: "Vertical", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "3aeb18aac0b532f34255f162", + _tpl: "5cc70146e4a949000d73bf6b", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "11", + upd: { + StackObjectsCount: 1, + }, + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + }, + { + _id: "bdb46107abbf1d92edaaf14e", + _tpl: "6272379924e29f06af4d5ecb", + parentId: "3aeb18aac0b532f34255f162", + slotId: "mod_tactical", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "0caadd8507a36d9ea871e88e", + _tpl: "5ab8f04f86f774585f4237d8", + parentId: "3bc4ff5bd99f165dc75cbd25", + slotId: "main", + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "240046eebc9040c1d7e58611", + _tpl: "5ac66d015acfc400180ae6e4", + parentId: "0caadd8507a36d9ea871e88e", + slotId: "main", + location: { + x: 0, + y: 0, + r: "Horizontal", + isSearched: true, + }, + upd: { + StackObjectsCount: 1, + sptPresetId: "5acf7dfc86f774401e19c390", + Repairable: { + Durability: 32, + MaxDurability: 59, + }, + Foldable: { + Folded: true, + }, + }, + }, + { + _id: "70b23c628fa17699d9a71e94", + _tpl: "59c6633186f7740cf0493bb9", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_gas_block", + upd: { + StackObjectsCount: 1, + sptPresetId: "5acf7dfc86f774401e19c390", + Repairable: { + Durability: 32, + MaxDurability: 59, + }, + }, + }, + { + _id: "7cc2e24dc6bc0716bdddc472", + _tpl: "5943ee5a86f77413872d25ec", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_muzzle", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "7a51ebbad703082660d59d27", + _tpl: "5649ade84bdc2d1b2b8b4587", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_pistol_grip", + upd: { + StackObjectsCount: 1, + sptPresetId: "5acf7dfc86f774401e19c390", + Repairable: { + Durability: 32, + MaxDurability: 59, + }, + }, + }, + { + _id: "b481bc57436ed9a0c3abe7f3", + _tpl: "5d2c76ed48f03532f2136169", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_reciever", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "5774ef80597c7f91bff40dbb", + _tpl: "5ac50c185acfc400163398d4", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_stock", + upd: { + StackObjectsCount: 1, + sptPresetId: "5acf7dfc86f774401e19c390", + Repairable: { + Durability: 32, + MaxDurability: 59, + }, + }, + }, + { + _id: "8b7c8e6ba172ac390c99a2ae", + _tpl: "5ac66c5d5acfc4001718d314", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_magazine", + upd: { + StackObjectsCount: 1, + }, + }, + { + _id: "1ed3a416b1fc7adbed1160df", + _tpl: "6130ca3fd92c473c77020dbd", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_charge", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "bbe087661947c0d9c1cde146", + _tpl: "5648b1504bdc2d9d488b4584", + parentId: "70b23c628fa17699d9a71e94", + slotId: "mod_handguard", + upd: { + StackObjectsCount: 1, + sptPresetId: "5acf7dfc86f774401e19c390", + Repairable: { + Durability: 32, + MaxDurability: 59, + }, + }, + }, + { + _id: "724388f8110434efccd79b3a", + _tpl: "544a3a774bdc2d3a388b4567", + parentId: "b481bc57436ed9a0c3abe7f3", + slotId: "mod_scope", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + { + _id: "8581038b0f795618a3d26c94", + _tpl: "58d268fc86f774111273f8c2", + parentId: "724388f8110434efccd79b3a", + slotId: "mod_scope", + upd: { + StackObjectsCount: 1, + Repairable: { + Durability: 100, + MaxDurability: 100, + }, + }, + }, + ], + }, ]; diff --git a/project/tests/__mocks__/WinstonLogger.mock.ts b/project/tests/__mocks__/WinstonLogger.mock.ts index 8e4b2f35..5733d4d6 100644 --- a/project/tests/__mocks__/WinstonLogger.mock.ts +++ b/project/tests/__mocks__/WinstonLogger.mock.ts @@ -6,26 +6,30 @@ import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; export class WinstonLogger implements ILogger { writeToLogFile(data: string | Daum): void - { } + {} log(data: string | Record | Error, color: string, backgroundColor?: string): void - { } + {} - logWithColor(data: string | Record, textColor: LogTextColor, backgroundColor?: LogBackgroundColor): void - { } + logWithColor( + data: string | Record, + textColor: LogTextColor, + backgroundColor?: LogBackgroundColor, + ): void + {} error(data: string): void - { } + {} warning(data: string): void - { } + {} success(data: string): void - { } + {} info(data: string): void - { } + {} - debug(data: string| Record, onlyShowInConsole?: boolean): void - { } + debug(data: string | Record, onlyShowInConsole?: boolean): void + {} } diff --git a/project/tests/controllers/InsuranceController.test.ts b/project/tests/controllers/InsuranceController.test.ts index 97db6a71..70326f3e 100644 --- a/project/tests/controllers/InsuranceController.test.ts +++ b/project/tests/controllers/InsuranceController.test.ts @@ -1,16 +1,16 @@ /* eslint-disable @typescript-eslint/naming-convention */ import "reflect-metadata"; import { container } from "tsyringe"; -import { vi, afterEach, describe, expect, it, beforeEach } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { InsuranceController } from "@spt-aki/controllers/InsuranceController"; import { ProfileInsuranceFactory } from "@tests/__factories__/ProfileInsurance.factory"; -import { MessageType } from "@spt-aki/models/enums/MessageType"; +import { ItemHelper } from "@spt-aki/helpers/ItemHelper"; import { TraderHelper } from "@spt-aki/helpers/TraderHelper"; import { Item } from "@spt-aki/models/eft/common/tables/IItem"; import { Insurance } from "@spt-aki/models/eft/profile/IAkiProfile"; -import { ItemHelper } from "@spt-aki/helpers/ItemHelper"; +import { MessageType } from "@spt-aki/models/enums/MessageType"; describe("InsuranceController", () => { @@ -36,10 +36,12 @@ describe("InsuranceController", () => const session2 = "session2"; const profiles = { [session1]: {}, - [session2]: {} + [session2]: {}, }; const getProfilesSpy = vi.spyOn(insuranceController.saveServer, "getProfiles").mockReturnValue(profiles); - const processReturnByProfileSpy = vi.spyOn(insuranceController, "processReturnByProfile").mockReturnValue(vi.fn()); + const processReturnByProfileSpy = vi.spyOn(insuranceController, "processReturnByProfile").mockReturnValue( + vi.fn(), + ); // Execute the method. insuranceController.processReturn(); @@ -55,7 +57,8 @@ describe("InsuranceController", () => it("should not attempt to process profiles if no profiles exist", () => { - const processReturnByProfileSpy = vi.spyOn(insuranceController, "processReturnByProfile").mockImplementation(vi.fn()); + const processReturnByProfileSpy = vi.spyOn(insuranceController, "processReturnByProfile") + .mockImplementation(vi.fn()); // Execute the method. insuranceController.processReturn(); @@ -119,7 +122,9 @@ describe("InsuranceController", () => // Verify that the correct methods were called. expect(mockGetProfile).toBeCalledTimes(1); - expect(mockLoggerDebug).toBeCalledWith(`Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`); + expect(mockLoggerDebug).toBeCalledWith( + `Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`, + ); expect(insuredFiltered.length).toBe(insuranceFixture.length); }); @@ -141,7 +146,9 @@ describe("InsuranceController", () => // Verify that the correct methods were called. expect(mockGetProfile).toBeCalledTimes(1); - expect(mockLoggerDebug).toBeCalledWith(`Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`); + expect(mockLoggerDebug).toBeCalledWith( + `Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`, + ); expect(insuredFiltered.length).toBe(insuranceFixture.length - 1); // Should be 1 less than the original fixture. }); @@ -157,11 +164,16 @@ describe("InsuranceController", () => // Execute the method, passing in a time that's two hours in the past. The function should use this past // date as the target to judge if an insurance package is ready to be sent or not. - const insuredFiltered = insuranceController.filterInsuredItems(sessionID, Math.floor((Date.now() / 1000) - (2 * 60 * 60))); + const insuredFiltered = insuranceController.filterInsuredItems( + sessionID, + Math.floor((Date.now() / 1000) - (2 * 60 * 60)), + ); // Verify that the correct methods were called. expect(mockGetProfile).toBeCalledTimes(1); - expect(mockLoggerDebug).toBeCalledWith(`Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`); + expect(mockLoggerDebug).toBeCalledWith( + `Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`, + ); // Verify that the returned array is empty. expect(insuredFiltered.length).toBe(0); @@ -186,7 +198,11 @@ describe("InsuranceController", () => insuranceController.processInsuredItems(insuranceFixture, sessionId); // Verify that the log was written. - expect(mockLoggerDebug).toBeCalledWith(`Processing ${insuranceFixture.length} insurance packages, which includes a total of ${insuranceController.countAllInsuranceItems(insuranceFixture)} items, in profile ${sessionId}`); + expect(mockLoggerDebug).toBeCalledWith( + `Processing ${insuranceFixture.length} insurance packages, which includes a total of ${ + insuranceController.countAllInsuranceItems(insuranceFixture) + } items, in profile ${sessionId}`, + ); }); it("should call processing methods once per insurance package", () => @@ -195,11 +211,19 @@ describe("InsuranceController", () => const packageCount = insuranceFixture.length; // Spy on the processing methods. - const mockFindItemsToDelete = vi.spyOn(insuranceController, "findItemsToDelete").mockImplementation(vi.fn()); - const mockRemoveItemsFromInsurance = vi.spyOn(insuranceController, "removeItemsFromInsurance").mockImplementation(vi.fn()); - const mockAdoptOrphanedItems = vi.spyOn(insuranceController, "adoptOrphanedItems").mockImplementation(vi.fn()); + const mockFindItemsToDelete = vi.spyOn(insuranceController, "findItemsToDelete").mockImplementation( + vi.fn(), + ); + const mockRemoveItemsFromInsurance = vi.spyOn(insuranceController, "removeItemsFromInsurance") + .mockImplementation(vi.fn()); + const mockAdoptOrphanedItems = vi.spyOn(insuranceController, "adoptOrphanedItems").mockImplementation( + vi.fn(), + ); const mockSendMail = vi.spyOn(insuranceController, "sendMail").mockImplementation(vi.fn()); - const mockRemoveInsurancePackageFromProfile = vi.spyOn(insuranceController, "removeInsurancePackageFromProfile").mockImplementation(vi.fn()); + const mockRemoveInsurancePackageFromProfile = vi.spyOn( + insuranceController, + "removeInsurancePackageFromProfile", + ).mockImplementation(vi.fn()); // Execute the method. insuranceController.processInsuredItems(insuranceFixture, sessionId); @@ -219,22 +243,22 @@ describe("InsuranceController", () => { const insurance = [ { - "_id": "1", - "upd": 1234567890, - "items": [ - { "_id": "1", "parentId": "1", "slotId": "1" }, - { "_id": "2", "parentId": "1", "slotId": "2" } - ] + _id: "1", + upd: 1234567890, + items: [ + {_id: "1", parentId: "1", slotId: "1"}, + {_id: "2", parentId: "1", slotId: "2"}, + ], }, { - "_id": "2", - "upd": 1234567890, - "items": [ - { "_id": "3", "parentId": "2", "slotId": "1" }, - { "_id": "4", "parentId": "2", "slotId": "2" }, - { "_id": "5", "parentId": "2", "slotId": "3" } - ] - } + _id: "2", + upd: 1234567890, + items: [ + {_id: "3", parentId: "2", slotId: "1"}, + {_id: "4", parentId: "2", slotId: "2"}, + {_id: "5", parentId: "2", slotId: "3"}, + ], + }, ]; const expectedCount = 5; // 2 items in the first package + 3 items in the second package. @@ -261,15 +285,15 @@ describe("InsuranceController", () => { const insurance = [ { - "_id": "1", - "upd": 1234567890, - "items": [] + _id: "1", + upd: 1234567890, + items: [], }, { - "_id": "2", - "upd": 1234567890, - "items": [] - } + _id: "2", + upd: 1234567890, + items: [], + }, ]; const expectedCount = 0; @@ -289,7 +313,7 @@ describe("InsuranceController", () => const packageToRemove = { date: "01.11.2023", time: "10:51", - location: "factory4_day" + location: "factory4_day", }; const profile = { insurance: [ @@ -298,20 +322,20 @@ describe("InsuranceController", () => systemData: { date: "01.11.2023", time: "11:18", - location: "factory4_day" - } - } + location: "factory4_day", + }, + }, }, { // This one should be removed messageContent: { systemData: { date: "01.11.2023", time: "10:51", - location: "factory4_day" - } - } - } - ] + location: "factory4_day", + }, + }, + }, + ], }; // Mock the getProfile method to return the above profile. @@ -325,7 +349,7 @@ describe("InsuranceController", () => expect(profile.insurance[0].messageContent.systemData).toStrictEqual({ date: "01.11.2023", time: "11:18", - location: "factory4_day" + location: "factory4_day", }); }); @@ -335,7 +359,7 @@ describe("InsuranceController", () => const packageToRemove = { date: "01.11.2023", time: "10:51", - location: "factory4_day" + location: "factory4_day", }; const profile = { insurance: [ @@ -344,11 +368,11 @@ describe("InsuranceController", () => systemData: { date: "01.11.2023", time: "10:51", - location: "factory4_day" - } - } - } - ] + location: "factory4_day", + }, + }, + }, + ], }; // Mock the getProfile method to return the above profile. @@ -361,7 +385,9 @@ describe("InsuranceController", () => insuranceController.removeInsurancePackageFromProfile(sessionID, packageToRemove); // Verify that the log was written. - expect(mockLoggerDebug).toBeCalledWith(`Removed insurance package with date: ${packageToRemove.date}, time: ${packageToRemove.time}, and location: ${packageToRemove.location} from profile ${sessionID}. Remaining packages: ${profile.insurance.length}`); + expect(mockLoggerDebug).toBeCalledWith( + `Removed insurance package with date: ${packageToRemove.date}, time: ${packageToRemove.time}, and location: ${packageToRemove.location} from profile ${sessionID}. Remaining packages: ${profile.insurance.length}`, + ); }); it("should not remove any packages if the specified package is not found", () => @@ -370,7 +396,7 @@ describe("InsuranceController", () => const packageToRemove = { date: "01.11.2023", time: "10:51", - location: "factory4_day" + location: "factory4_day", }; const profile = { insurance: [ @@ -379,11 +405,11 @@ describe("InsuranceController", () => systemData: { date: "02.11.2023", time: "10:50", - location: "factory4_night" - } - } - } - ] + location: "factory4_night", + }, + }, + }, + ], }; // Mock the getProfile method to return the above profile. @@ -399,7 +425,6 @@ describe("InsuranceController", () => describe("findItemsToDelete", () => { - it("should handle an empty insurance package", () => { const insurancePackage = insuranceFixture[0]; @@ -423,12 +448,14 @@ describe("InsuranceController", () => const mockPopulateItemsMap = vi.spyOn(insuranceController, "populateItemsMap"); const mockPopulateParentAttachmentsMap = vi.spyOn(insuranceController, "populateParentAttachmentsMap"); const mockIsAttachmentAttached = vi.spyOn(insuranceController.itemHelper, "isAttachmentAttached"); - const mockProcessAttachments = vi.spyOn(insuranceController, "processAttachments").mockImplementation(vi.fn()); + const mockProcessAttachments = vi.spyOn(insuranceController, "processAttachments").mockImplementation( + vi.fn(), + ); // Add all items to the toDelete set. Not realistic, but it's fine for this test. const mockProcessRegularItems = vi.fn((insured, toDelete) => { - insured.items.forEach(item => toDelete.add(item._id)); + insured.items.forEach((item) => toDelete.add(item._id)); }); vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems); @@ -444,7 +471,7 @@ describe("InsuranceController", () => // Verify that the result is correct. expect(result.size).toBe(numberOfItems); - expect(result).toEqual(new Set(insured.items.map(item => item._id))); + expect(result).toEqual(new Set(insured.items.map((item) => item._id))); }); it("should ignore orphaned attachments", () => @@ -463,7 +490,9 @@ describe("InsuranceController", () => { return new Map(); }); - vi.spyOn(insuranceController, "populateParentAttachmentsMap").mockImplementation(mockPopulateParentAttachmentsMap); + vi.spyOn(insuranceController, "populateParentAttachmentsMap").mockImplementation( + mockPopulateParentAttachmentsMap, + ); // Execute the method. const result = insuranceController.findItemsToDelete(insured); @@ -491,12 +520,12 @@ describe("InsuranceController", () => // Add all items to the toDelete set. Not realistic, but it's fine for this test. const mockProcessRegularItems = vi.fn((insured, toDelete) => { - insured.items.forEach(item => toDelete.add(item._id)); + insured.items.forEach((item) => toDelete.add(item._id)); }); vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems); const mockProcessAttachments = vi.fn((parentAttachmentsMap, itemsMap, traderId, toDelete) => { - insured.items.forEach(item => toDelete.add(item._id)); + insured.items.forEach((item) => toDelete.add(item._id)); }); vi.spyOn(insuranceController, "processAttachments").mockImplementation(mockProcessAttachments); @@ -511,7 +540,7 @@ describe("InsuranceController", () => // Verify that the result is correct. expect(result.size).toBe(numberOfItems); - expect(result).toEqual(new Set(insured.items.map(item => item._id))); + expect(result).toEqual(new Set(insured.items.map((item) => item._id))); }); it("should return an empty set if no items are to be deleted", () => @@ -523,8 +552,12 @@ describe("InsuranceController", () => const mockPopulateParentAttachmentsMap = vi.spyOn(insuranceController, "populateParentAttachmentsMap"); // Don't add any items to the toDelete set. - const mockProcessRegularItems = vi.spyOn(insuranceController, "processRegularItems").mockImplementation(vi.fn()); - const mockProcessAttachments = vi.spyOn(insuranceController, "processAttachments").mockImplementation(vi.fn()); + const mockProcessRegularItems = vi.spyOn(insuranceController, "processRegularItems").mockImplementation( + vi.fn(), + ); + const mockProcessAttachments = vi.spyOn(insuranceController, "processAttachments").mockImplementation( + vi.fn(), + ); // Execute the method. const result = insuranceController.findItemsToDelete(insured); @@ -551,12 +584,12 @@ describe("InsuranceController", () => // Add all items to the toDelete set. Not realistic, but it's fine for this test. const mockProcessRegularItems = vi.fn((insured, toDelete) => { - insured.items.forEach(item => toDelete.add(item._id)); + insured.items.forEach((item) => toDelete.add(item._id)); }); vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems); const mockProcessAttachments = vi.fn((parentAttachmentsMap, itemsMap, traderId, toDelete) => { - insured.items.forEach(item => toDelete.add(item._id)); + insured.items.forEach((item) => toDelete.add(item._id)); }); vi.spyOn(insuranceController, "processAttachments").mockImplementation(mockProcessAttachments); @@ -595,12 +628,12 @@ describe("InsuranceController", () => "da8cde1b3024c336f6e06152", "bc041c0011d76f714b898400", "9f8d7880a6e0a47a211ec5d3", - "db2ef9442178910eba985b51" + "db2ef9442178910eba985b51", ]; - validAttachmentTemplates.forEach(value => + validAttachmentTemplates.forEach((value) => { // Verify that each template is present in the array of attachments. - expect(gun.some(item => item._id === value)).toBe(true); + expect(gun.some((item) => item._id === value)).toBe(true); }); }); @@ -625,11 +658,11 @@ describe("InsuranceController", () => "1e0b177df108c0c117028812", "c9278dd8251e99578bf7a274", "402b4086535a50ef7d9cef88", - "566335b3df586f34b47f5e35" + "566335b3df586f34b47f5e35", ]; - invalidAttachmentTemplates.forEach(value => + invalidAttachmentTemplates.forEach((value) => { - expect(gun.every(item => item._id !== value)).toBe(true); + expect(gun.every((item) => item._id !== value)).toBe(true); }); }); @@ -655,12 +688,12 @@ describe("InsuranceController", () => "dc565f750342cb2d19eeda06", "e9ff62601669d9e2ea9c2fbb", "ac134d7cf6c9d8e25edd0015", - "22274b895ecc80d51c3cba1c" + "22274b895ecc80d51c3cba1c", ]; - validAttachmentTemplates.forEach(value => + validAttachmentTemplates.forEach((value) => { // Verify that each template is present in the array of attachments. - expect(gun.some(item => item._id === value)).toBe(true); + expect(gun.some((item) => item._id === value)).toBe(true); }); }); @@ -678,7 +711,7 @@ describe("InsuranceController", () => expect(result.size).toBe(6); // There are 6 base-level items in this insurance package. const gun = result.get("351180f3248d45c71cb2ebdc"); - expect(insured.items.find(item => item._id === "351180f3248d45c71cb2ebdc").slotId).toBe("main"); + expect(insured.items.find((item) => item._id === "351180f3248d45c71cb2ebdc").slotId).toBe("main"); expect(gun.length).toBe(14); // This AS VAL has 14 valid attachments. }); @@ -727,7 +760,10 @@ describe("InsuranceController", () => // Mock helper methods. const mockIsAttachmentAttached = vi.spyOn(insuranceController.itemHelper, "isAttachmentAttached"); - const mockFindAndReturnChildrenAsItems = vi.spyOn(insuranceController.itemHelper, "findAndReturnChildrenAsItems"); + const mockFindAndReturnChildrenAsItems = vi.spyOn( + insuranceController.itemHelper, + "findAndReturnChildrenAsItems", + ); // Mock rollForDelete to return true for all items. Not realistic, but it's fine for this test. const mockRollForDelete = vi.spyOn(insuranceController, "rollForDelete").mockReturnValue(true); @@ -741,7 +777,7 @@ describe("InsuranceController", () => expect(mockRollForDelete).toHaveBeenCalledTimes(numberOfItems); // Verify that all items were added to the toDelete set. - expect(toDelete).toEqual(new Set(insured.items.map(item => item._id))); + expect(toDelete).toEqual(new Set(insured.items.map((item) => item._id))); }); it("should not roll attached attachments", () => @@ -783,7 +819,7 @@ describe("InsuranceController", () => insuranceController.processRegularItems(insured, toDelete); // Verify that all items were added to the toDelete set. - expect(toDelete).toEqual(new Set(insured.items.map(item => item._id))); + expect(toDelete).toEqual(new Set(insured.items.map((item) => item._id))); }); }); @@ -827,7 +863,9 @@ describe("InsuranceController", () => const parentItem = itemsMap.get(parentId); if (parentItem) { - const expectedMessage = `Processing attachments for parent item: ${itemHelper.getItemName(parentItem._tpl)}`; + const expectedMessage = `Processing attachments for parent item: ${ + itemHelper.getItemName(parentItem._tpl) + }`; expect(mockLoggerDebug).toHaveBeenCalledWith(expectedMessage); } } @@ -911,14 +949,16 @@ describe("InsuranceController", () => const attachments = parentToAttachmentMap.values().next().value; // Set the maxPrice of the first two attachments to null. - vi.spyOn(insuranceController.itemHelper, "getItemMaxPrice").mockReturnValueOnce(null).mockReturnValueOnce(null); + vi.spyOn(insuranceController.itemHelper, "getItemMaxPrice").mockReturnValueOnce(null).mockReturnValueOnce( + null, + ); // Execute the method. const sortedAttachments = insuranceController.sortAttachmentsByPrice(attachments); // Verify that the attachments with null maxPrice are at the bottom of the list const nullPriceAttachments = sortedAttachments.slice(-2); - nullPriceAttachments.forEach(attachment => + nullPriceAttachments.forEach((attachment) => { expect(attachment.maxPrice).toBeNull(); }); @@ -936,8 +976,8 @@ describe("InsuranceController", () => it("should log details for each attachment", () => { const attachments = [ - { _id: "item1", name: "Item 1", maxPrice: 100 }, - { _id: "item2", name: "Item 2", maxPrice: 200 } + {_id: "item1", name: "Item 1", maxPrice: 100}, + {_id: "item2", name: "Item 2", maxPrice: 200}, ]; // Mock the logger.debug function. @@ -1096,9 +1136,9 @@ describe("InsuranceController", () => insuranceController.removeItemsFromInsurance(insured, toDelete); // Ensure that the items in the toDelete set are not present in the insured items array. - toDelete.forEach(toDeleteId => + toDelete.forEach((toDeleteId) => { - expect(insured.items.some(item => item._id === toDeleteId)).toBe(false); + expect(insured.items.some((item) => item._id === toDeleteId)).toBe(false); }); }); @@ -1120,7 +1160,7 @@ describe("InsuranceController", () => const insured = insuranceFixture[0]; const originalCount = insured.items.length; const toDelete = new Set(); - insured.items.forEach(item => toDelete.add(item._id)); + insured.items.forEach((item) => toDelete.add(item._id)); // All of the items should be added to the toDelete set. expect(originalCount).toBe(toDelete.size); @@ -1146,7 +1186,9 @@ describe("InsuranceController", () => insured.items[0].slotId = "main"; // Should not be "hideout". // Iterate over the items and find an individual orphaned item. - const orphanedItem = insured.items.find(item => !insured.items.some(parent => parent._id === item.parentId)); + const orphanedItem = insured.items.find((item) => + !insured.items.some((parent) => parent._id === item.parentId) + ); // Setup tests to verify that the orphaned item we added is in fact orphaned. expect(orphanedItem.parentId).toBe(insured.items[0].parentId); @@ -1184,7 +1226,9 @@ describe("InsuranceController", () => insured.items[0].location = {x: 1, y: 2, r: 3, isSearched: true}; // Should be removed. // Iterate over the items and find an individual orphaned item. - const orphanedItem = insured.items.find(item => !insured.items.some(parent => parent._id === item.parentId)); + const orphanedItem = insured.items.find((item) => + !insured.items.some((parent) => parent._id === item.parentId) + ); // Setup tests to verify that the orphaned item we added is in fact orphaned. expect(orphanedItem.parentId).toBe(insured.items[0].parentId); @@ -1275,7 +1319,7 @@ describe("InsuranceController", () => insuranceFailedTpl, insurance.items, insurance.messageContent.maxStorageTime, - insurance.messageContent.systemData + insurance.messageContent.systemData, ); }); @@ -1309,7 +1353,7 @@ describe("InsuranceController", () => insurance.messageContent.templateId, insurance.items, insurance.messageContent.maxStorageTime, - insurance.messageContent.systemData + insurance.messageContent.systemData, ); }); }); @@ -1322,8 +1366,8 @@ describe("InsuranceController", () => const traderId = "54cb57776803fa99248b456e"; // Therapist (85% return chance) insuranceController.insuranceConfig = { returnChancePercent: { - [traderId]: 85 // Force 85% return chance - } + [traderId]: 85, // Force 85% return chance + }, }; // Execute the method. @@ -1339,8 +1383,8 @@ describe("InsuranceController", () => const traderId = "54cb57776803fa99248b456e"; // Therapist (85% return chance) insuranceController.insuranceConfig = { returnChancePercent: { - [traderId]: 85 // Force 85% return chance - } + [traderId]: 85, // Force 85% return chance + }, }; // Execute the method. @@ -1356,8 +1400,8 @@ describe("InsuranceController", () => const traderId = "54cb57776803fa99248b456e"; // Therapist (85% return chance) insuranceController.insuranceConfig = { returnChancePercent: { - [traderId]: 85 // Force 85% return chance - } + [traderId]: 85, // Force 85% return chance + }, }; // Execute the method. @@ -1394,7 +1438,13 @@ describe("InsuranceController", () => describe("insure", () => { - let pmcData: any, body: any, sessionId: string, insuranceController: any, mockGetPremium: any, mockPayMoney: any, mockGetOutput: any; + let pmcData: any, + body: any, + sessionId: string, + insuranceController: any, + mockGetPremium: any, + mockPayMoney: any, + mockGetOutput: any; beforeEach(() => { @@ -1404,15 +1454,15 @@ describe("InsuranceController", () => pmcData = { Inventory: { items: [ - { _id: "item1", otherProps: "value1" }, - { _id: "item2", otherProps: "value2" } - ] + {_id: "item1", otherProps: "value1"}, + {_id: "item2", otherProps: "value2"}, + ], }, - InsuredItems: [] + InsuredItems: [], }; body = { items: ["item1", "item2"], - tid: "someTraderId" + tid: "someTraderId", }; sessionId = "session-id"; @@ -1420,11 +1470,11 @@ describe("InsuranceController", () => mockGetPremium = vi.spyOn(insuranceController.insuranceService, "getPremium").mockReturnValue(100); mockPayMoney = vi.spyOn(insuranceController.paymentService, "payMoney").mockReturnValue({ warnings: [], - otherProperty: "property-value" + otherProperty: "property-value", }); mockGetOutput = vi.spyOn(insuranceController.eventOutputHolder, "getOutput").mockReturnValue({ warnings: [], - otherProperty: "property-value" + otherProperty: "property-value", }); }); @@ -1439,20 +1489,21 @@ describe("InsuranceController", () => pmcData, { scheme_items: [ - { id: "item1", count: 100 }, - { id: "item2", count: 100 } + {id: "item1", count: 100}, + {id: "item2", count: 100}, ], tid: "someTraderId", Action: "", type: "", item_id: "", count: 0, - scheme_id: 0 + scheme_id: 0, }, - sessionId, { + sessionId, + { warnings: [], - otherProperty: "property-value" - } + otherProperty: "property-value", + }, ); }); @@ -1479,15 +1530,15 @@ describe("InsuranceController", () => // Define the expected payment options structure based on the setup data. const expectedPaymentOptions = { scheme_items: [ - { id: "item1", count: 100 }, - { id: "item2", count: 100 } + {id: "item1", count: 100}, + {id: "item2", count: 100}, ], tid: body.tid, Action: "", type: "", item_id: "", count: 0, - scheme_id: 0 + scheme_id: 0, }; // Verify that the paymentService's payMoney method was called once with the expected parameters. @@ -1498,7 +1549,7 @@ describe("InsuranceController", () => pmcData, expectedPaymentOptions, sessionId, - mockGetOutput.mock.results[0].value + mockGetOutput.mock.results[0].value, ); }); @@ -1508,7 +1559,7 @@ describe("InsuranceController", () => insuranceController.insure(pmcData, body, sessionId); // Verify that the InsuredItems array has been populated with the correct items. - const insuredItemIds = pmcData.InsuredItems.map(insuredItem => insuredItem.itemId); + const insuredItemIds = pmcData.InsuredItems.map((insuredItem) => insuredItem.itemId); expect(insuredItemIds).toContain("item1"); expect(insuredItemIds).toContain("item2"); @@ -1523,9 +1574,9 @@ describe("InsuranceController", () => warnings: [{ index: 0, errmsg: "Not enough money to complete transaction", - code: 500 + code: 500, }], - otherProperty: "property-value" + otherProperty: "property-value", }; mockPayMoney.mockReturnValue(expectedPayMoneyReturn); @@ -1546,9 +1597,9 @@ describe("InsuranceController", () => warnings: [{ index: 0, errmsg: "Not enough money to complete transaction", - code: 500 + code: 500, }], - otherProperty: "property-value" + otherProperty: "property-value", }; mockPayMoney.mockReturnValue(expectedPayMoneyReturn); @@ -1573,17 +1624,17 @@ describe("InsuranceController", () => vi.spyOn(insuranceController.profileHelper, "getPmcProfile").mockReturnValue({ Inventory: { items: [ - { _id: "itemId1", _tpl: "itemTpl1", otherProperty: "property-value1" }, - { _id: "itemId2", _tpl: "itemTpl2", otherProperty: "property-value2" }, - { _id: "itemId3", _tpl: "itemTpl3", otherProperty: "property-value3" } - ] - } + {_id: "itemId1", _tpl: "itemTpl1", otherProperty: "property-value1"}, + {_id: "itemId2", _tpl: "itemTpl2", otherProperty: "property-value2"}, + {_id: "itemId3", _tpl: "itemTpl3", otherProperty: "property-value3"}, + ], + }, }); }); it("should return an empty object if no traders and items are specified", () => { - const request = { traders: [], items: [] }; + const request = {traders: [], items: []}; const expected = {}; const result = insuranceController.cost(request, sessionId); @@ -1593,8 +1644,8 @@ describe("InsuranceController", () => it("should return an empty object if no items are specified", () => { - const request = { traders: ["prapor"], items: [] }; - const expected = { prapor: {} }; + const request = {traders: ["prapor"], items: []}; + const expected = {prapor: {}}; const result = insuranceController.cost(request, sessionId); @@ -1603,7 +1654,7 @@ describe("InsuranceController", () => it("should return an empty object if no trader is specified but items are", () => { - const request = { traders: [], items: ["itemId1", "itemId2"] }; + const request = {traders: [], items: ["itemId1", "itemId2"]}; const expected = {}; const result = insuranceController.cost(request, sessionId); @@ -1615,11 +1666,11 @@ describe("InsuranceController", () => { const request = { traders: ["prapor", "therapist"], - items: ["itemId1", "itemId2", "itemId3"] + items: ["itemId1", "itemId2", "itemId3"], }; const expected = { - prapor: { itemTpl1: 100, itemTpl2: 200, itemTpl3: 300 }, - therapist: { itemTpl1: 150, itemTpl2: 250, itemTpl3: 350 } + prapor: {itemTpl1: 100, itemTpl2: 200, itemTpl3: 300}, + therapist: {itemTpl1: 150, itemTpl2: 250, itemTpl3: 350}, }; // Mock the InsuranceService.getPremium method to return the expected values. @@ -1643,11 +1694,11 @@ describe("InsuranceController", () => items: [ "itemId1", "itemId2", - "itemId4" // Doesn't exist in the player's inventory. - ] + "itemId4", // Doesn't exist in the player's inventory. + ], }; const expected = { - prapor: { itemTpl1: 100, itemTpl2: 200 } + prapor: {itemTpl1: 100, itemTpl2: 200}, }; // Mock the InsuranceService.getPremium method to return the expected values. diff --git a/project/tests/generators/BotGenerator.test.ts b/project/tests/generators/BotGenerator.test.ts index 381189c9..7545a69d 100644 --- a/project/tests/generators/BotGenerator.test.ts +++ b/project/tests/generators/BotGenerator.test.ts @@ -1,9 +1,9 @@ /* eslint-disable @typescript-eslint/naming-convention */ import "reflect-metadata"; -import { container } from "tsyringe"; -import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; import { BotGenerator } from "@spt-aki/generators/BotGenerator"; import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; +import { container } from "tsyringe"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; describe("BotGenerator", () => { @@ -62,15 +62,15 @@ describe("BotGenerator", () => const mockPlayerProfile = { Info: { Nickname: "Player Nickname", - Level: 1 - } + Level: 1, + }, }; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); const botJsonTemplate = { firstName: ["test"], - lastName: [] + lastName: [], }; const sessionId = "sessionId"; @@ -88,14 +88,14 @@ describe("BotGenerator", () => const mockPlayerProfile = { Info: { Nickname: "Player Nickname", - Level: 1 - } + Level: 1, + }, }; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); const botJsonTemplate = { firstName: ["test"], - lastName: [] + lastName: [], }; const sessionId = "sessionId"; @@ -114,15 +114,15 @@ describe("BotGenerator", () => const mockPlayerProfile = { Info: { Nickname: "Player", - Level: 1 - } + Level: 1, + }, }; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); vi.spyOn(botGenerator.localisationService, "getRandomTextThatMatchesPartialKey").mockReturnValue("test"); const botJsonTemplate = { firstName: ["Player"], - lastName: [] + lastName: [], }; const sessionId = "sessionId"; @@ -140,14 +140,14 @@ describe("BotGenerator", () => const mockPlayerProfile = { Info: { Nickname: "Player", - Level: 1 - } + Level: 1, + }, }; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); const botJsonTemplate = { firstName: ["test"], - lastName: [] + lastName: [], }; const sessionId = "sessionId"; @@ -167,14 +167,14 @@ describe("BotGenerator", () => const mockPlayerProfile = { Info: { Nickname: "Player", - Level: 1 - } + Level: 1, + }, }; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); const botJsonTemplate = { firstName: ["test"], - lastName: [] + lastName: [], }; const sessionId = "sessionId"; diff --git a/project/tests/generators/BotLevelGenerator.test.ts b/project/tests/generators/BotLevelGenerator.test.ts index 11a96e03..dc04eef4 100644 --- a/project/tests/generators/BotLevelGenerator.test.ts +++ b/project/tests/generators/BotLevelGenerator.test.ts @@ -1,6 +1,6 @@ import "reflect-metadata"; import { container } from "tsyringe"; -import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { BotLevelGenerator } from "@spt-aki/generators/BotLevelGenerator"; import { MinMax } from "@spt-aki/models/common/MinMax"; @@ -29,7 +29,7 @@ describe("BotLevelGenerator", () => { const levelDetails: MinMax = { min: 5, - max: 10 + max: 10, }; const botGenerationDetails: BotGenerationDetails = { @@ -40,7 +40,7 @@ describe("BotLevelGenerator", () => botRelativeLevelDeltaMax: 0, botCountToGenerate: 0, botDifficulty: "", - isPlayerScav: false + isPlayerScav: false, }; const result = botLevelGenerator.generateBotLevel(levelDetails, botGenerationDetails, null); @@ -55,7 +55,7 @@ describe("BotLevelGenerator", () => { const levelDetails: MinMax = { min: 5, - max: 10 + max: 10, }; const expTable = databaseServer.getTables().globals.config.exp.level.exp_table; @@ -69,14 +69,19 @@ describe("BotLevelGenerator", () => { const levelDetails: MinMax = { min: 100, - max: 100 + max: 100, }; const expTable = databaseServer.getTables().globals.config.exp.level.exp_table; const playerLevel = 100; const relativeDeltaMax = 5; - const result = botLevelGenerator.getHighestRelativeBotLevel(playerLevel, relativeDeltaMax, levelDetails, expTable); + const result = botLevelGenerator.getHighestRelativeBotLevel( + playerLevel, + relativeDeltaMax, + levelDetails, + expTable, + ); expect(result).toBe(79); }); diff --git a/project/tests/helpers/BotHelper.test.ts b/project/tests/helpers/BotHelper.test.ts index f9a12537..9e48473b 100644 --- a/project/tests/helpers/BotHelper.test.ts +++ b/project/tests/helpers/BotHelper.test.ts @@ -1,6 +1,6 @@ import "reflect-metadata"; import { container } from "tsyringe"; -import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { BotHelper } from "@spt-aki/helpers/BotHelper"; diff --git a/project/tests/helpers/HandbookHelper.test.ts b/project/tests/helpers/HandbookHelper.test.ts index bf1cb7bc..0747f1a7 100644 --- a/project/tests/helpers/HandbookHelper.test.ts +++ b/project/tests/helpers/HandbookHelper.test.ts @@ -1,6 +1,6 @@ import "reflect-metadata"; import { container } from "tsyringe"; -import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { HandbookHelper } from "@spt-aki/helpers/HandbookHelper"; import { Money } from "@spt-aki/models/enums/Money"; diff --git a/project/tests/helpers/InRaidHelper.test.ts b/project/tests/helpers/InRaidHelper.test.ts index 091d430d..a6c65bd0 100644 --- a/project/tests/helpers/InRaidHelper.test.ts +++ b/project/tests/helpers/InRaidHelper.test.ts @@ -1,6 +1,6 @@ import "reflect-metadata"; import { container } from "tsyringe"; -import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { InRaidHelper } from "@spt-aki/helpers/InRaidHelper"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; @@ -27,12 +27,12 @@ describe("InRaidHelper", () => const postRaidPlayerVictims = [ { Side: "Savage", - Role: "assault" + Role: "assault", }, { Side: "Savage", - Role: "assault" - } + Role: "assault", + }, ]; // Kills const databaseServer = container.resolve("DatabaseServer"); @@ -49,12 +49,12 @@ describe("InRaidHelper", () => const postRaidPlayerVictims = [ { Side: "Usec", - Role: "sptUsec" + Role: "sptUsec", }, { Side: "Bear", - Role: "sptBear" - } + Role: "sptBear", + }, ]; // Kills const databaseServer = container.resolve("DatabaseServer"); @@ -72,29 +72,32 @@ describe("InRaidHelper", () => const postRaidPlayerVictims = [ { Side: "Usec", - Role: "sptUsec" + Role: "sptUsec", }, { Side: "savage", - Role: "assault" + Role: "assault", }, { Side: "savage", - Role: "bossBoar" + Role: "bossBoar", }, { Side: "savage", - Role: "assault" - } + Role: "assault", + }, ]; // Kills const databaseServer = container.resolve("DatabaseServer"); const usecStandingChangeOnKill = databaseServer.getTables().bots.types.bear.experience.standingForKill; const scavStandingChangeOnKill = databaseServer.getTables().bots.types.assault.experience.standingForKill; - const bossBoarStandingChangeOnKill = databaseServer.getTables().bots.types.bossboar.experience.standingForKill; + const bossBoarStandingChangeOnKill = + databaseServer.getTables().bots.types.bossboar.experience.standingForKill; const result = inraidHelper.calculateFenceStandingChangeFromKills(fenceStanding, postRaidPlayerVictims); - expect(result).toBe(usecStandingChangeOnKill + (scavStandingChangeOnKill * 2) + bossBoarStandingChangeOnKill); + expect(result).toBe( + usecStandingChangeOnKill + (scavStandingChangeOnKill * 2) + bossBoarStandingChangeOnKill, + ); expect(result).lessThan(0); }); @@ -104,12 +107,14 @@ describe("InRaidHelper", () => const postRaidPlayerVictims = [ { Side: "savage", - Role: "testRole" - } + Role: "testRole", + }, ]; // Kills // Fake getFenceStandingChangeForKillAsScav() returning null - vi.spyOn(inraidHelper, "getFenceStandingChangeForKillAsScav").mockReturnValueOnce(null).mockReturnValueOnce(null); + vi.spyOn(inraidHelper, "getFenceStandingChangeForKillAsScav").mockReturnValueOnce(null).mockReturnValueOnce( + null, + ); const result = inraidHelper.calculateFenceStandingChangeFromKills(fenceStanding, postRaidPlayerVictims); expect(result).toBe(0); }); diff --git a/project/tests/helpers/ItemHelper.test.ts b/project/tests/helpers/ItemHelper.test.ts index 32d13ace..e86ae492 100644 --- a/project/tests/helpers/ItemHelper.test.ts +++ b/project/tests/helpers/ItemHelper.test.ts @@ -1,12 +1,12 @@ import "reflect-metadata"; import { container } from "tsyringe"; -import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { ItemHelper } from "@spt-aki/helpers/ItemHelper"; import { Item, Repairable } from "@spt-aki/models/eft/common/tables/IItem"; +import { ITemplateItem } from "@spt-aki/models/eft/common/tables/ITemplateItem"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; import { HashUtil } from "@spt-aki/utils/HashUtil"; -import { ITemplateItem } from "@spt-aki/models/eft/common/tables/ITemplateItem"; describe("ItemHelper", () => { @@ -251,7 +251,7 @@ describe("ItemHelper", () => { const initialItem: Item = { _id: "", - _tpl: "" + _tpl: "", }; const fixedItem = itemHelper.fixItemStackCount(initialItem); @@ -264,7 +264,7 @@ describe("ItemHelper", () => const initialItem: Item = { _id: "", _tpl: "", - upd: {} + upd: {}, }; const fixedItem = itemHelper.fixItemStackCount(initialItem); @@ -278,8 +278,8 @@ describe("ItemHelper", () => _id: "", _tpl: "", upd: { - StackObjectsCount: 5 - } + StackObjectsCount: 5, + }, }; const fixedItem = itemHelper.fixItemStackCount(initialItem); @@ -324,7 +324,6 @@ describe("ItemHelper", () => // Restore the original behavior loggerWarningSpy.mockRestore(); }); - }); describe("getItems", () => @@ -420,7 +419,7 @@ describe("ItemHelper", () => const itemId = container.resolve("HashUtil").generate(); const item: Item = { _id: itemId, - _tpl: "590c657e86f77412b013051d" // "Grizzly medical kit" + _tpl: "590c657e86f77412b013051d", // "Grizzly medical kit" }; const result = itemHelper.getItemQualityModifier(item); @@ -433,8 +432,8 @@ describe("ItemHelper", () => const itemId = container.resolve("HashUtil").generate(); const item: Item = { _id: itemId, - _tpl: "590c657e86f77412b013051d", // "Grizzly medical kit" - upd: {} + _tpl: "590c657e86f77412b013051d", // "Grizzly medical kit" + upd: {}, }; const result = itemHelper.getItemQualityModifier(item); @@ -447,12 +446,12 @@ describe("ItemHelper", () => const itemId = container.resolve("HashUtil").generate(); const item: Item = { _id: itemId, - _tpl: "590c657e86f77412b013051d", // "Grizzly medical kit" + _tpl: "590c657e86f77412b013051d", // "Grizzly medical kit" upd: { MedKit: { - HpResource: 900 // 1800 total - } - } + HpResource: 900, // 1800 total + }, + }, }; const result = itemHelper.getItemQualityModifier(item); @@ -460,7 +459,7 @@ describe("ItemHelper", () => expect(result).toBe(0.5); }); - it("should return correct value for a reparable helmet", () => + it("should return correct value for a repairable helmet", () => { const itemId = container.resolve("HashUtil").generate(); const item: Item = { @@ -469,9 +468,9 @@ describe("ItemHelper", () => upd: { Repairable: { Durability: 19, - MaxDurability: 38 - } - } + MaxDurability: 38, + }, + }, }; const result = itemHelper.getItemQualityModifier(item); @@ -488,9 +487,9 @@ describe("ItemHelper", () => upd: { Repairable: { Durability: 20, - MaxDurability: 100 - } - } + MaxDurability: 100, + }, + }, }; const result = itemHelper.getItemQualityModifier(item); @@ -506,9 +505,9 @@ describe("ItemHelper", () => _tpl: "5448fee04bdc2dbc018b4567", // "Bottle of water (0.6L)" upd: { FoodDrink: { - HpPercent: 30 // Not actually a percentage, but value of max 60. - } - } + HpPercent: 30, // Not actually a percentage, but value of max 60. + }, + }, }; const result = itemHelper.getItemQualityModifier(item); @@ -524,9 +523,9 @@ describe("ItemHelper", () => _tpl: "5780cf7f2459777de4559322", // "Dorm room 314 marked key" upd: { Key: { - NumberOfUsages: 5 - } - } + NumberOfUsages: 5, + }, + }, }; const result = itemHelper.getItemQualityModifier(item); @@ -543,9 +542,9 @@ describe("ItemHelper", () => upd: { Resource: { Value: 50, // How much fuel is left in the tank. - UnitsConsumed: 50 // How much fuel has been used in the generator. - } - } + UnitsConsumed: 50, // How much fuel has been used in the generator. + }, + }, }; const result = itemHelper.getItemQualityModifier(item); @@ -561,9 +560,9 @@ describe("ItemHelper", () => _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" upd: { RepairKit: { - Resource: 600 - } - } + Resource: 600, + }, + }, }; const result = itemHelper.getItemQualityModifier(item); @@ -579,9 +578,9 @@ describe("ItemHelper", () => _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" upd: { RepairKit: { - Resource: 0 - } - } + Resource: 0, + }, + }, }; const result = itemHelper.getItemQualityModifier(item); @@ -594,14 +593,14 @@ describe("ItemHelper", () => { it("should return the correct quality value for armor items", () => { - const armor = itemHelper.getItem("5648a7494bdc2d9d488b4583")[1]; // "PACA Soft Armor" + const armor = itemHelper.getItem("5648a7494bdc2d9d488b4583")[1]; // "PACA Soft Armor" const repairable: Repairable = { Durability: 25, - MaxDurability: 50 + MaxDurability: 50, }; const item: Item = { // Not used for armor, but required for the method. _id: "", - _tpl: "" + _tpl: "", }; // Cast the method to any to allow access to private/protected method. @@ -612,14 +611,14 @@ describe("ItemHelper", () => it("should not use the Repairable MaxDurability property for armor", () => { - const armor = itemHelper.getItem("5648a7494bdc2d9d488b4583")[1]; // "PACA Soft Armor" + const armor = itemHelper.getItem("5648a7494bdc2d9d488b4583")[1]; // "PACA Soft Armor" const repairable: Repairable = { Durability: 25, - MaxDurability: 1000 // This should be ignored. + MaxDurability: 1000, // This should be ignored. }; const item: Item = { // Not used for armor, but required for the method. _id: "", - _tpl: "" + _tpl: "", }; // Cast the method to any to allow access to private/protected method. @@ -630,14 +629,14 @@ describe("ItemHelper", () => it("should return the correct quality value for weapon items", () => { - const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" + const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" const repairable: Repairable = { Durability: 50, - MaxDurability: 100 + MaxDurability: 100, }; const item: Item = { _id: "", - _tpl: "" + _tpl: "", }; // Cast the method to any to allow access to private/protected method. @@ -648,15 +647,15 @@ describe("ItemHelper", () => it("should fall back to using Repairable MaxDurability for weapon items", () => { - const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" + const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" weapon._props.MaxDurability = undefined; // Remove the MaxDurability property. const repairable: Repairable = { Durability: 50, - MaxDurability: 200 // This should be used now. + MaxDurability: 200, // This should be used now. }; const item: Item = { _id: "", - _tpl: "" + _tpl: "", }; // Cast the method to any to allow access to private/protected method. @@ -667,15 +666,15 @@ describe("ItemHelper", () => it("should return 1 if durability value is invalid", () => { - const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" + const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" weapon._props.MaxDurability = undefined; // Remove the MaxDurability property. const repairable: Repairable = { Durability: 50, - MaxDurability: undefined // Remove the MaxDurability property value... Technically an invalid Type. + MaxDurability: undefined, // Remove the MaxDurability property value... Technically an invalid Type. }; const item: Item = { _id: "", - _tpl: "" + _tpl: "", }; // Mock the logger's error method to prevent it from being actually called. @@ -691,15 +690,15 @@ describe("ItemHelper", () => it("should not divide by zero", () => { - const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" + const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" weapon._props.MaxDurability = undefined; // Remove the MaxDurability property. const repairable: Repairable = { Durability: 50, - MaxDurability: 0 // This is a problem. + MaxDurability: 0, // This is a problem. }; const item: Item = { _id: "", - _tpl: "" + _tpl: "", }; // Cast the method to any to allow access to private/protected method. @@ -710,15 +709,15 @@ describe("ItemHelper", () => it("should log an error if durability is invalid", () => { - const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" + const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" weapon._props.MaxDurability = undefined; // Remove the MaxDurability property. const repairable: Repairable = { Durability: 50, - MaxDurability: undefined // Remove the MaxDurability property value... Technically an invalid Type. + MaxDurability: undefined, // Remove the MaxDurability property value... Technically an invalid Type. }; const item: Item = { _id: "", - _tpl: "" + _tpl: "", }; const loggerErrorSpy = vi.spyOn((itemHelper as any).logger, "error"); @@ -735,9 +734,9 @@ describe("ItemHelper", () => it("should return an array containing only the parent ID when no children are found", () => { const items: Item[] = [ - { _id: "1", _tpl: "", parentId: null }, - { _id: "2", _tpl: "", parentId: null }, - { _id: "3", _tpl: "", parentId: "2" } + {_id: "1", _tpl: "", parentId: null}, + {_id: "2", _tpl: "", parentId: null}, + {_id: "3", _tpl: "", parentId: "2"}, ]; const result = itemHelper.findAndReturnChildrenByItems(items, "1"); expect(result).toEqual(["1"]); @@ -746,9 +745,9 @@ describe("ItemHelper", () => it("should return array of child IDs when single-level children are found", () => { const items: Item[] = [ - { _id: "1", _tpl: "", parentId: null }, - { _id: "2", _tpl: "", parentId: "1" }, - { _id: "3", _tpl: "", parentId: "1" } + {_id: "1", _tpl: "", parentId: null}, + {_id: "2", _tpl: "", parentId: "1"}, + {_id: "3", _tpl: "", parentId: "1"}, ]; const result = itemHelper.findAndReturnChildrenByItems(items, "1"); expect(result).toEqual(["2", "3", "1"]); @@ -757,10 +756,10 @@ describe("ItemHelper", () => it("should return array of child IDs when multi-level children are found", () => { const items: Item[] = [ - { _id: "1", _tpl: "", parentId: null }, - { _id: "2", _tpl: "", parentId: "1" }, - { _id: "3", _tpl: "", parentId: "2" }, - { _id: "4", _tpl: "", parentId: "3" } + {_id: "1", _tpl: "", parentId: null}, + {_id: "2", _tpl: "", parentId: "1"}, + {_id: "3", _tpl: "", parentId: "2"}, + {_id: "4", _tpl: "", parentId: "3"}, ]; const result = itemHelper.findAndReturnChildrenByItems(items, "1"); expect(result).toEqual(["4", "3", "2", "1"]); @@ -769,8 +768,8 @@ describe("ItemHelper", () => it("should return an array containing only the parent ID when parent ID does not exist in items", () => { const items: Item[] = [ - { _id: "1", _tpl: "", parentId: null }, - { _id: "2", _tpl: "", parentId: "1" } + {_id: "1", _tpl: "", parentId: null}, + {_id: "2", _tpl: "", parentId: "1"}, ]; const result = itemHelper.findAndReturnChildrenByItems(items, "3"); expect(result).toEqual(["3"]); @@ -785,7 +784,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" - upd: {} + upd: {}, }; const result = itemHelper.getItemStackSize(item); expect(result).toBe(1); @@ -796,7 +795,7 @@ describe("ItemHelper", () => const itemId = container.resolve("HashUtil").generate(); const item: Item = { _id: itemId, - _tpl: "591094e086f7747caa7bb2ef" // "Body armor repair kit" + _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" }; const result = itemHelper.getItemStackSize(item); expect(result).toBe(1); @@ -809,8 +808,8 @@ describe("ItemHelper", () => _id: itemId, _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" upd: { - StackObjectsCount: 5 - } + StackObjectsCount: 5, + }, }; const result = itemHelper.getItemStackSize(item); expect(result).toBe(5); @@ -827,8 +826,8 @@ describe("ItemHelper", () => _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" upd: { BuyRestrictionCurrent: 0, - BuyRestrictionMax: 1 - } + BuyRestrictionMax: 1, + }, }; const result = itemHelper.hasBuyRestrictions(item); expect(result).toBe(true); @@ -840,7 +839,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" - upd: {} + upd: {}, }; const result = itemHelper.hasBuyRestrictions(item); expect(result).toBe(false); @@ -851,7 +850,7 @@ describe("ItemHelper", () => const itemId = container.resolve("HashUtil").generate(); const item: Item = { _id: itemId, - _tpl: "591094e086f7747caa7bb2ef" // "Body armor repair kit" + _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" }; const result = itemHelper.hasBuyRestrictions(item); expect(result).toBe(false); @@ -881,12 +880,12 @@ describe("ItemHelper", () => describe("addCartridgesToAmmoBox", () => { - it("should return an array with 1xammoBox and 1xcartridge item", () => + it("should return an array with 1x ammoBox and 1x cartridge item", () => { const itemId = container.resolve("HashUtil").generate(); const ammoBox: Item[] = [{ _id: itemId, - _tpl: "5c12619186f7743f871c8a32" // "9x39mm SPP gs ammo pack (8 pcs)" + _tpl: "5c12619186f7743f871c8a32", // "9x39mm SPP gs ammo pack (8 pcs)" }]; const databaseServer = container.resolve("DatabaseServer"); @@ -897,12 +896,12 @@ describe("ItemHelper", () => expect(ammoBox[1].upd.StackObjectsCount).toBe(8); }); - it("should return an array with 1xammoBox and 2xcartridge items", () => + it("should return an array with 1x ammoBox and 2x cartridge items", () => { const itemId = container.resolve("HashUtil").generate(); const ammoBox: Item[] = [{ _id: itemId, - _tpl: "5737292724597765e5728562" // "5.45x39mm BP gs ammo pack (120 pcs)"" + _tpl: "5737292724597765e5728562", // "5.45x39mm BP gs ammo pack (120 pcs)"" }]; const databaseServer = container.resolve("DatabaseServer"); @@ -919,7 +918,7 @@ describe("ItemHelper", () => const itemId = container.resolve("HashUtil").generate(); const ammoBox: Item[] = [{ _id: itemId, - _tpl: "5737292724597765e5728562" // "5.45x39mm BP gs ammo pack (120 pcs)"" + _tpl: "5737292724597765e5728562", // "5.45x39mm BP gs ammo pack (120 pcs)"" }]; const databaseServer = container.resolve("DatabaseServer"); @@ -934,7 +933,7 @@ describe("ItemHelper", () => const itemId = container.resolve("HashUtil").generate(); const ammoBox: Item[] = [{ _id: itemId, - _tpl: "5737292724597765e5728562" // "5.45x39mm BP gs ammo pack (120 pcs)"" + _tpl: "5737292724597765e5728562", // "5.45x39mm BP gs ammo pack (120 pcs)"" }]; const databaseServer = container.resolve("DatabaseServer"); @@ -1015,8 +1014,8 @@ describe("ItemHelper", () => _id: container.resolve("HashUtil").generate(), _tpl: "59e690b686f7746c9f75e848", // m995 upd: { - StackObjectsCount: 80 // Default is 60 - } + StackObjectsCount: 80, // Default is 60 + }, }; const result = itemHelper.splitStack(stackableItem); // "Roubles" @@ -1029,8 +1028,8 @@ describe("ItemHelper", () => _id: container.resolve("HashUtil").generate(), _tpl: "59e690b686f7746c9f75e848", // m995 upd: { - StackObjectsCount: 80 // Default is 60 - } + StackObjectsCount: 80, // Default is 60 + }, }; const result = itemHelper.splitStack(stackableItem); // "Roubles" const itemCount = result.reduce((sum, curr) => sum + curr.upd.StackObjectsCount, 0); @@ -1043,8 +1042,8 @@ describe("ItemHelper", () => _id: container.resolve("HashUtil").generate(), _tpl: "59e690b686f7746c9f75e848", // m995 upd: { - StackObjectsCount: 60 // Default is 60 - } + StackObjectsCount: 60, // Default is 60 + }, }; const result = itemHelper.splitStack(stackableItem); // "Roubles" const itemCount = result.reduce((sum, curr) => sum + curr.upd.StackObjectsCount, 0); @@ -1057,7 +1056,7 @@ describe("ItemHelper", () => const stackableItem: Item = { _id: container.resolve("HashUtil").generate(), _tpl: "59e690b686f7746c9f75e848", // m995 - upd: {} + upd: {}, }; const result = itemHelper.splitStack(stackableItem); // "Roubles" expect(result.length).toBe(1); @@ -1067,7 +1066,7 @@ describe("ItemHelper", () => { const stackableItem: Item = { _id: container.resolve("HashUtil").generate(), - _tpl: "59e690b686f7746c9f75e848" // m995 + _tpl: "59e690b686f7746c9f75e848", // m995 }; const result = itemHelper.splitStack(stackableItem); // "Roubles" expect(result.length).toBe(1); @@ -1085,7 +1084,7 @@ describe("ItemHelper", () => "5736026a245977644601dc61", "573603562459776430731618", "573603c924597764442bd9cb", - "5735fdcd2459776445391d61" + "5735fdcd2459776445391d61", ]; const mockTemplateItem = { _id: "571a29dc2459771fb2755a6a", @@ -1094,11 +1093,11 @@ describe("ItemHelper", () => Cartridges: [{ _props: { filters: [{ - Filter: validAmmoItems - }] - } - }] - } + Filter: validAmmoItems, + }], + }, + }], + }, }; vi.spyOn((itemHelper as any).randomUtil, "getArrayValue").mockReturnValue(validAmmoItems[0]); @@ -1113,9 +1112,9 @@ describe("ItemHelper", () => const fakeTemplateItem = { _props: { Cartridges: [ - {} - ] - } + {}, + ], + }, }; const result = itemHelper.getRandomCompatibleCaliberTemplateId(fakeTemplateItem as ITemplateItem); diff --git a/project/tests/services/ItemBaseClassService.test.ts b/project/tests/services/ItemBaseClassService.test.ts index d94f9503..d2dbe193 100644 --- a/project/tests/services/ItemBaseClassService.test.ts +++ b/project/tests/services/ItemBaseClassService.test.ts @@ -1,8 +1,8 @@ /* eslint-disable @typescript-eslint/naming-convention */ import "reflect-metadata"; -import { container } from "tsyringe"; -import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; import { ItemBaseClassService } from "@spt-aki/services/ItemBaseClassService"; +import { container } from "tsyringe"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; describe("ItemBaseClassService", () => { @@ -64,7 +64,10 @@ describe("ItemBaseClassService", () => // Remove item from base cache delete itemBaseClassService.itemBaseClassesCache[salewaTpl]; - const result = itemBaseClassService.itemHasBaseClass(salewaTpl, ["543be5664bdc2dd4348b4569", "54009119af1c881c07000029"]); // "Meds" and "Item" type + const result = itemBaseClassService.itemHasBaseClass(salewaTpl, [ + "543be5664bdc2dd4348b4569", + "54009119af1c881c07000029", + ]); // "Meds" and "Item" type expect(result).toBe(true); }); diff --git a/project/tests/services/PaymentService.test.ts b/project/tests/services/PaymentService.test.ts index 8a5f8dd5..33275d68 100644 --- a/project/tests/services/PaymentService.test.ts +++ b/project/tests/services/PaymentService.test.ts @@ -1,16 +1,16 @@ /* eslint-disable @typescript-eslint/naming-convention */ import "reflect-metadata"; import { container } from "tsyringe"; -import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { PaymentService } from "@spt-aki/services/PaymentService"; import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; -import { IProcessBuyTradeRequestData } from "@spt-aki/models/eft/trade/IProcessBuyTradeRequestData"; -import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; -import { HashUtil } from "@spt-aki/utils/HashUtil"; -import { ITraderBase } from "@spt-aki/models/eft/common/tables/ITrader"; import { Item } from "@spt-aki/models/eft/common/tables/IItem"; +import { ITraderBase } from "@spt-aki/models/eft/common/tables/ITrader"; +import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; +import { IProcessBuyTradeRequestData } from "@spt-aki/models/eft/trade/IProcessBuyTradeRequestData"; +import { HashUtil } from "@spt-aki/utils/HashUtil"; describe("PaymentService", () => { @@ -44,8 +44,8 @@ describe("PaymentService", () => _id: costItemId, _tpl: costItemTpl, upd: { - StackObjectsCount: costAmount * 4 // More than enough. - } + StackObjectsCount: costAmount * 4, // More than enough. + }, } as Item; // Object representing the player's PMC inventory. @@ -54,12 +54,12 @@ describe("PaymentService", () => [traderId]: { salesSum: 0, unlocked: true, - disabled: false - } + disabled: false, + }, }, Inventory: { - items: [moneyItem] - } + items: [moneyItem], + }, } as unknown as IPmcData; // Buy a factory map from Therapist... although it doesn't really matter what the item is as there's no @@ -74,9 +74,9 @@ describe("PaymentService", () => scheme_items: [ { id: costItemId, - count: costAmount - } - ] + count: costAmount, + }, + ], } as IProcessBuyTradeRequestData; // Inconsequential profile ID @@ -90,10 +90,10 @@ describe("PaymentService", () => items: { new: [], change: [], - del: [] - } - } - } + del: [], + }, + }, + }, } as unknown as IItemEventRouterResponse; // Mock the logger debug method to return void. @@ -101,13 +101,14 @@ describe("PaymentService", () => {}); // Mock the trader helper to return a trader with the currency of Roubles. - const traderHelperGetTraderSpy = vi.spyOn((paymentService as any).traderHelper, "getTrader").mockReturnValue({ - tid: traderId, - currency: "RUB" - } as unknown as ITraderBase); + const traderHelperGetTraderSpy = vi.spyOn((paymentService as any).traderHelper, "getTrader") + .mockReturnValue({ + tid: traderId, + currency: "RUB", + } as unknown as ITraderBase); // Mock the addPaymentToOutput method to subtract the item cost from the money stack. - const addPaymentToOutputSpy = vi.spyOn((paymentService as any), "addPaymentToOutput").mockImplementation(() => + const addPaymentToOutputSpy = vi.spyOn(paymentService as any, "addPaymentToOutput").mockImplementation(() => { moneyItem.upd.StackObjectsCount -= costAmount; return { @@ -115,18 +116,25 @@ describe("PaymentService", () => profileChanges: { [sessionID]: { items: { - change: [moneyItem] - } - } - } + change: [moneyItem], + }, + }, + }, }; }); // Mock the traderHelper lvlUp method to return void. - const traderHelperLvlUpSpy = vi.spyOn((paymentService as any).traderHelper, "lvlUp").mockImplementation(() => - {}); + const traderHelperLvlUpSpy = vi.spyOn((paymentService as any).traderHelper, "lvlUp").mockImplementation( + () => + {}, + ); - const output = paymentService.payMoney(pmcData, processBuyTradeRequestData, sessionID, itemEventRouterResponse); + const output = paymentService.payMoney( + pmcData, + processBuyTradeRequestData, + sessionID, + itemEventRouterResponse, + ); // Check for absence of output warnings. expect(output.warnings).toHaveLength(0); @@ -139,7 +147,13 @@ describe("PaymentService", () => // Check if mocked methods were called as expected. expect(traderHelperGetTraderSpy).toBeCalledTimes(1); - expect(addPaymentToOutputSpy).toBeCalledWith(expect.anything(), costItemTpl, costAmount, sessionID, expect.anything()); + expect(addPaymentToOutputSpy).toBeCalledWith( + expect.anything(), + costItemTpl, + costAmount, + sessionID, + expect.anything(), + ); expect(traderHelperLvlUpSpy).toBeCalledTimes(1); }); }); @@ -151,14 +165,14 @@ describe("PaymentService", () => const hashUtil = container.resolve("HashUtil"); const stashItem: Item = { _id: "stashid", - _tpl: "55d7217a4bdc2d86028b456d" // standard stash id + _tpl: "55d7217a4bdc2d86028b456d", // standard stash id }; const inventoryItemToFind: Item = { _id: hashUtil.generate(), _tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar parentId: stashItem._id, - slotId: "hideout" + slotId: "hideout", }; const playerInventory = [stashItem, inventoryItemToFind]; @@ -172,20 +186,20 @@ describe("PaymentService", () => const hashUtil = container.resolve("HashUtil"); const stashItem: Item = { _id: "stashId", - _tpl: "55d7217a4bdc2d86028b456d" // standard stash id + _tpl: "55d7217a4bdc2d86028b456d", // standard stash id }; const foodBagToHoldItemToFind: Item = { _id: hashUtil.generate(), _tpl: "5c093db286f7740a1b2617e3", parentId: stashItem._id, - slotId: "hideout" + slotId: "hideout", }; const inventoryItemToFind: Item = { _id: hashUtil.generate(), _tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar - parentId: foodBagToHoldItemToFind._id + parentId: foodBagToHoldItemToFind._id, }; const playerInventory = [stashItem, foodBagToHoldItemToFind, inventoryItemToFind]; @@ -199,14 +213,14 @@ describe("PaymentService", () => const hashUtil = container.resolve("HashUtil"); const stashItem: Item = { _id: "stashId", - _tpl: "55d7217a4bdc2d86028b456d" // standard stash id + _tpl: "55d7217a4bdc2d86028b456d", // standard stash id }; const inventoryItemToFind: Item = { _id: hashUtil.generate(), _tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar parentId: stashItem._id, - slotId: "hideout" + slotId: "hideout", }; const playerInventory = [stashItem, inventoryItemToFind]; @@ -220,16 +234,16 @@ describe("PaymentService", () => const hashUtil = container.resolve("HashUtil"); const stashItem: Item = { _id: "stashId", - _tpl: "55d7217a4bdc2d86028b456d" // standard stash id + _tpl: "55d7217a4bdc2d86028b456d", // standard stash id }; const inventoryItemToFind: Item = { _id: hashUtil.generate(), _tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar parentId: stashItem._id, - slotId: "hideout" + slotId: "hideout", }; - const playerInventory = [ inventoryItemToFind]; + const playerInventory = [inventoryItemToFind]; const result = paymentService.isInStash("notCorrectId", playerInventory, stashItem._id); diff --git a/project/tests/services/PlayerService.test.ts b/project/tests/services/PlayerService.test.ts index 1fb36d05..6c731861 100644 --- a/project/tests/services/PlayerService.test.ts +++ b/project/tests/services/PlayerService.test.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import "reflect-metadata"; import { container } from "tsyringe"; -import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { PlayerService } from "@spt-aki/services/PlayerService"; @@ -26,8 +26,8 @@ describe("PlayerService", () => { const playerProfile = { Info: { - Experience: 0 // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels - } + Experience: 0, // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels + }, }; const result = playerService.calculateLevel(playerProfile as IPmcData); @@ -39,8 +39,8 @@ describe("PlayerService", () => { const playerProfile = { Info: { - Experience: 999 // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels - } + Experience: 999, // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels + }, }; const result = playerService.calculateLevel(playerProfile as IPmcData); @@ -52,8 +52,8 @@ describe("PlayerService", () => { const playerProfile = { Info: { - Experience: 609066 // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels - } + Experience: 609066, // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels + }, }; const result = playerService.calculateLevel(playerProfile as IPmcData); @@ -65,8 +65,8 @@ describe("PlayerService", () => { const playerProfile = { Info: { - Experience: 68206066 // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels - } + Experience: 68206066, // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels + }, }; const result = playerService.calculateLevel(playerProfile as IPmcData); diff --git a/project/tests/utils/TimeUtil.test.ts b/project/tests/utils/TimeUtil.test.ts index 112b0aa9..03e026b5 100644 --- a/project/tests/utils/TimeUtil.test.ts +++ b/project/tests/utils/TimeUtil.test.ts @@ -1,6 +1,6 @@ import "reflect-metadata"; import { container } from "tsyringe"; -import { vi, afterEach, describe, expect, it, beforeEach } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { TimeUtil } from "@spt-aki/utils/TimeUtil"; From d3e5418fc806ef350a82ac2f60ddbdd04f2786f6 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:05:05 -0500 Subject: [PATCH 26/41] Formatting for generator classes. --- .../generators/BotEquipmentModGenerator.ts | 395 ++++++++++++----- project/src/generators/BotGenerator.ts | 181 +++++--- .../src/generators/BotInventoryGenerator.ts | 225 +++++++--- project/src/generators/BotLevelGenerator.ts | 33 +- project/src/generators/BotLootGenerator.ts | 198 ++++++--- project/src/generators/BotWeaponGenerator.ts | 292 ++++++++++--- .../generators/FenceBaseAssortGenerator.ts | 22 +- project/src/generators/LocationGenerator.ts | 369 +++++++++++----- project/src/generators/LootGenerator.ts | 147 ++++--- project/src/generators/PMCLootGenerator.ts | 55 +-- project/src/generators/PlayerScavGenerator.ts | 36 +- .../src/generators/RagfairAssortGenerator.ts | 27 +- .../src/generators/RagfairOfferGenerator.ts | 220 ++++++---- .../generators/RepeatableQuestGenerator.ts | 409 ++++++++++++------ .../src/generators/ScavCaseRewardGenerator.ts | 121 ++++-- project/src/generators/WeatherGenerator.ts | 52 ++- .../generators/weapongen/IInventoryMagGen.ts | 2 +- .../generators/weapongen/InventoryMagGen.ts | 21 +- .../implementations/BarrelInventoryMagGen.ts | 29 +- .../ExternalInventoryMagGen.ts | 50 ++- .../InternalMagazineInventoryMagGen.ts | 24 +- .../implementations/UbglExternalMagGen.ts | 25 +- 22 files changed, 2049 insertions(+), 884 deletions(-) diff --git a/project/src/generators/BotEquipmentModGenerator.ts b/project/src/generators/BotEquipmentModGenerator.ts index 259d7acd..d572694c 100644 --- a/project/src/generators/BotEquipmentModGenerator.ts +++ b/project/src/generators/BotEquipmentModGenerator.ts @@ -46,12 +46,12 @@ export class BotEquipmentModGenerator @inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("BotEquipmentModPoolService") protected botEquipmentModPoolService: BotEquipmentModPoolService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); } - + /** * Check mods are compatible and add to array * @param equipment Equipment item to add mods to @@ -63,7 +63,15 @@ export class BotEquipmentModGenerator * @param forceSpawn should this mod be forced to spawn * @returns Item + compatible mods as an array */ - public generateModsForEquipment(equipment: Item[], modPool: Mods, parentId: string, parentTemplate: ITemplateItem, modSpawnChances: ModsChances, botRole: string, forceSpawn = false): Item[] + public generateModsForEquipment( + equipment: Item[], + modPool: Mods, + parentId: string, + parentTemplate: ITemplateItem, + modSpawnChances: ModsChances, + botRole: string, + forceSpawn = false, + ): Item[] { const compatibleModsPool = modPool[parentTemplate._id]; @@ -73,7 +81,13 @@ export class BotEquipmentModGenerator const itemSlot = this.getModItemSlot(modSlot, parentTemplate); if (!itemSlot) { - this.logger.error(this.localisationService.getText("bot-mod_slot_missing_from_item", {modSlot: modSlot, parentId: parentTemplate._id, parentName: parentTemplate._name})); + this.logger.error( + this.localisationService.getText("bot-mod_slot_missing_from_item", { + modSlot: modSlot, + parentId: parentTemplate._id, + parentName: parentTemplate._name, + }), + ); continue; } @@ -83,27 +97,33 @@ export class BotEquipmentModGenerator } // Ensure submods for nvgs all spawn together - forceSpawn = (modSlot === "mod_nvg") - ? true - : false; + forceSpawn = (modSlot === "mod_nvg") ? + true : + false; let modTpl: string; let found = false; - + // Find random mod and check its compatible - const exhaustableModPool = new ExhaustableArray(compatibleModsPool[modSlot], this.randomUtil, this.jsonUtil); + const exhaustableModPool = new ExhaustableArray( + compatibleModsPool[modSlot], + this.randomUtil, + this.jsonUtil, + ); while (exhaustableModPool.hasValues()) { modTpl = exhaustableModPool.getRandomValue(); - if (!this.botGeneratorHelper.isItemIncompatibleWithCurrentItems(equipment, modTpl, modSlot).incompatible) + if ( + !this.botGeneratorHelper.isItemIncompatibleWithCurrentItems(equipment, modTpl, modSlot).incompatible + ) { found = true; break; } } - // Combatible item not found but slot REQUIRES item, get random item from db - const parentSlot = parentTemplate._props.Slots.find(i => i._name === modSlot); + // Compatible item not found but slot REQUIRES item, get random item from db + const parentSlot = parentTemplate._props.Slots.find((i) => i._name === modSlot); if (!found && parentSlot !== undefined && parentSlot._required) { modTpl = this.getModTplFromItemDb(modTpl, parentSlot, modSlot, equipment); @@ -113,7 +133,7 @@ export class BotEquipmentModGenerator // Compatible item not found + not required if (!found && parentSlot !== undefined && !parentSlot._required) { - // Dont add item + // Don't add item continue; } @@ -128,8 +148,16 @@ export class BotEquipmentModGenerator if (Object.keys(modPool).includes(modTpl)) { - // Call self recursivly - this.generateModsForEquipment(equipment, modPool, modId, modTemplate[1], modSpawnChances, botRole, forceSpawn); + // Call self recursively + this.generateModsForEquipment( + equipment, + modPool, + modId, + modTemplate[1], + modSpawnChances, + botRole, + forceSpawn, + ); } } @@ -146,8 +174,8 @@ export class BotEquipmentModGenerator * @param modSpawnChances Mod spawn chances * @param ammoTpl Ammo tpl to use when generating magazines/cartridges * @param botRole Role of bot weapon is generated for - * @param botLevel lvel of the bot weapon is being generated for - * @param modLimits limits placed on certian mod types per gun + * @param botLevel Level of the bot weapon is being generated for + * @param modLimits limits placed on certain mod types per gun * @param botEquipmentRole role of bot when accessing bot.json equipment config settings * @returns Weapon + mods array */ @@ -162,7 +190,8 @@ export class BotEquipmentModGenerator botRole: string, botLevel: number, modLimits: BotModLimits, - botEquipmentRole: string): Item[] + botEquipmentRole: string, + ): Item[] { const pmcProfile = this.profileHelper.getPmcProfile(sessionId); @@ -171,17 +200,27 @@ export class BotEquipmentModGenerator // Null guard against bad input weapon // biome-ignore lint/complexity/useSimplifiedLogicExpression: - if (!parentTemplate._props.Slots.length - && !parentTemplate._props.Cartridges?.length - && !parentTemplate._props.Chambers?.length) + if ( + !parentTemplate._props.Slots.length && + !parentTemplate._props.Cartridges?.length && + !parentTemplate._props.Chambers?.length + ) { - this.logger.error(this.localisationService.getText("bot-unable_to_add_mods_to_weapon_missing_ammo_slot", {weaponName: parentTemplate._name, weaponId: parentTemplate._id})); + this.logger.error( + this.localisationService.getText("bot-unable_to_add_mods_to_weapon_missing_ammo_slot", { + weaponName: parentTemplate._name, + weaponId: parentTemplate._id, + }), + ); return weapon; } const botEquipConfig = this.botConfig.equipment[botEquipmentRole]; - const botEquipBlacklist = this.botEquipmentFilterService.getBotEquipmentBlacklist(botEquipmentRole, pmcProfile.Info.Level); + const botEquipBlacklist = this.botEquipmentFilterService.getBotEquipmentBlacklist( + botEquipmentRole, + pmcProfile.Info.Level, + ); const botWeaponSightWhitelist = this.botEquipmentFilterService.getBotWeaponSightWhitelist(botEquipmentRole); const randomisationSettings = this.botHelper.getBotRandomizationDetails(botLevel, botEquipConfig); @@ -193,7 +232,14 @@ export class BotEquipmentModGenerator const modsParentSlot = this.getModItemSlot(modSlot, parentTemplate); if (!modsParentSlot) { - this.logger.error(this.localisationService.getText("bot-weapon_missing_mod_slot", {modSlot: modSlot, weaponId: parentTemplate._id, weaponName: parentTemplate._name, botRole: botRole})); + this.logger.error( + this.localisationService.getText("bot-weapon_missing_mod_slot", { + modSlot: modSlot, + weaponId: parentTemplate._id, + weaponName: parentTemplate._name, + botRole: botRole, + }), + ); continue; } @@ -205,10 +251,19 @@ export class BotEquipmentModGenerator } const isRandomisableSlot = randomisationSettings?.randomisedWeaponModSlots?.includes(modSlot) ?? false; - const modToAdd = this.chooseModToPutIntoSlot(modSlot, isRandomisableSlot, botWeaponSightWhitelist, botEquipBlacklist, compatibleModsPool, weapon, ammoTpl, parentTemplate); + const modToAdd = this.chooseModToPutIntoSlot( + modSlot, + isRandomisableSlot, + botWeaponSightWhitelist, + botEquipBlacklist, + compatibleModsPool, + weapon, + ammoTpl, + parentTemplate, + ); // Compatible mod not found - if (!modToAdd || typeof (modToAdd) === "undefined") + if (!modToAdd || typeof modToAdd === "undefined") { continue; } @@ -220,7 +275,15 @@ export class BotEquipmentModGenerator const modToAddTemplate = modToAdd[1]; // Skip adding mod to weapon if type limit reached - if (this.botWeaponModLimitService.weaponModHasReachedLimit(botEquipmentRole, modToAddTemplate, modLimits, parentTemplate, weapon)) + if ( + this.botWeaponModLimitService.weaponModHasReachedLimit( + botEquipmentRole, + modToAddTemplate, + modLimits, + parentTemplate, + weapon, + ) + ) { continue; } @@ -234,7 +297,7 @@ export class BotEquipmentModGenerator "mod_scope_000", "mod_scope_001", "mod_scope_002", - "mod_scope_003" + "mod_scope_003", ]; this.adjustSlotSpawnChances(modSpawnChances, scopeSlots, 100); @@ -252,7 +315,7 @@ export class BotEquipmentModGenerator const muzzleSlots = [ "mod_muzzle", "mod_muzzle_000", - "mod_muzzle_001" + "mod_muzzle_001", ]; // Make chance of muzzle devices 95%, nearly certain but not guaranteed this.adjustSlotSpawnChances(modSpawnChances, muzzleSlots, 95); @@ -267,7 +330,10 @@ export class BotEquipmentModGenerator // Handguard mod can take a sub handguard mod + weapon has no UBGL (takes same slot) // Force spawn chance to be 100% to ensure it gets added - if (modSlot === "mod_handguard" && modToAddTemplate._props.Slots.find(x => x._name === "mod_handguard") && !weapon.find(x => x.slotId === "mod_launcher")) + if ( + modSlot === "mod_handguard" && modToAddTemplate._props.Slots.find((x) => x._name === "mod_handguard") && + !weapon.find((x) => x.slotId === "mod_launcher") + ) { // Needed for handguards with lower modSpawnChances.mod_handguard = 100; @@ -275,7 +341,10 @@ export class BotEquipmentModGenerator // If stock mod can take a sub stock mod, force spawn chance to be 100% to ensure sub-stock gets added // Or if mod_stock is configured to be forced on - if (modSlot === "mod_stock" && (modToAddTemplate._props.Slots.find(x => x._name.includes("mod_stock") || botEquipConfig.forceStock))) + if ( + modSlot === "mod_stock" && + (modToAddTemplate._props.Slots.find((x) => x._name.includes("mod_stock") || botEquipConfig.forceStock)) + ) { // Stock mod can take additional stocks, could be a locking device, force 100% chance const stockSlots = ["mod_stock", "mod_stock_000", "mod_stock_akms"]; @@ -283,10 +352,12 @@ export class BotEquipmentModGenerator } const modId = this.hashUtil.generate(); - weapon.push(this.createModItem(modId, modToAddTemplate._id, weaponParentId, modSlot, modToAddTemplate, botRole)); - + weapon.push( + this.createModItem(modId, modToAddTemplate._id, weaponParentId, modSlot, modToAddTemplate, botRole), + ); + // I first thought we could use the recursive generateModsForItems as previously for cylinder magazines. - // However, the recursion doesnt go over the slots of the parent mod but over the modPool which is given by the bot config + // However, the recursion doesn't go over the slots of the parent mod but over the modPool which is given by the bot config // where we decided to keep cartridges instead of camoras. And since a CylinderMagazine only has one cartridge entry and // this entry is not to be filled, we need a special handling for the CylinderMagazine const modParentItem = this.databaseServer.getTables().templates.items[modToAddTemplate._parent]; @@ -312,8 +383,20 @@ export class BotEquipmentModGenerator } if (containsModInPool) { - // Call self recursivly to add mods to this mod - this.generateModsForWeapon(sessionId, weapon, modPool, modId, modToAddTemplate, modSpawnChances, ammoTpl, botRole, botLevel, modLimits, botEquipmentRole); + // Call self recursively to add mods to this mod + this.generateModsForWeapon( + sessionId, + weapon, + modPool, + modId, + modToAddTemplate, + modSpawnChances, + ammoTpl, + botRole, + botLevel, + modLimits, + botEquipmentRole, + ); } } } @@ -328,8 +411,8 @@ export class BotEquipmentModGenerator */ protected modIsFrontOrRearSight(modSlot: string, tpl: string): boolean { - if (modSlot === "mod_gas_block" && tpl === "5ae30e795acfc408fb139a0b") // M4A1 front sight with gas block - { + if (modSlot === "mod_gas_block" && tpl === "5ae30e795acfc408fb139a0b") + { // M4A1 front sight with gas block return true; } @@ -344,15 +427,27 @@ export class BotEquipmentModGenerator */ protected modSlotCanHoldScope(modSlot: string, modsParentId: string): boolean { - return ["mod_scope", "mod_mount", "mod_mount_000", "mod_scope_000", "mod_scope_001", "mod_scope_002", "mod_scope_003"].includes(modSlot.toLowerCase()) - && modsParentId === BaseClasses.MOUNT; + return [ + "mod_scope", + "mod_mount", + "mod_mount_000", + "mod_scope_000", + "mod_scope_001", + "mod_scope_002", + "mod_scope_003", + ].includes(modSlot.toLowerCase()) && + modsParentId === BaseClasses.MOUNT; } /** * Set mod spawn chances to defined amount * @param modSpawnChances Chance dictionary to update */ - protected adjustSlotSpawnChances(modSpawnChances: ModsChances, modSlotsToAdjust: string[], newChancePercent: number): void + protected adjustSlotSpawnChances( + modSpawnChances: ModsChances, + modSlotsToAdjust: string[], + newChancePercent: number, + ): void { if (!modSpawnChances) { @@ -418,7 +513,7 @@ export class BotEquipmentModGenerator sortedKeys.push(modRecieverKey); unsortedKeys.splice(unsortedKeys.indexOf(modRecieverKey), 1); } - + if (unsortedKeys.includes(modPistolGrip)) { sortedKeys.push(modPistolGrip); @@ -467,11 +562,11 @@ export class BotEquipmentModGenerator case "patron_in_weapon": case "patron_in_weapon_000": case "patron_in_weapon_001": - return parentTemplate._props.Chambers.find(c => c._name.includes(modSlot)); + return parentTemplate._props.Chambers.find((c) => c._name.includes(modSlot)); case "cartridges": - return parentTemplate._props.Cartridges.find(c => c._name === modSlot); + return parentTemplate._props.Cartridges.find((c) => c._name === modSlot); default: - return parentTemplate._props.Slots.find(s => s._name === modSlot); + return parentTemplate._props.Slots.find((s) => s._name === modSlot); } } @@ -486,8 +581,9 @@ export class BotEquipmentModGenerator protected shouldModBeSpawned(itemSlot: Slot, modSlot: string, modSpawnChances: ModsChances): boolean { const modSpawnChance = itemSlot._required || this.getAmmoContainers().includes(modSlot) // Required OR it is ammo - ? 100 - : modSpawnChances[modSlot]; + ? + 100 : + modSpawnChances[modSlot]; if (modSpawnChance === 100) { @@ -498,7 +594,6 @@ export class BotEquipmentModGenerator } /** - * * @param modSlot Slot mod will fit into * @param isRandomisableSlot Will generate a randomised mod pool if true * @param modsParent Parent slot the item will be a part of @@ -517,12 +612,13 @@ export class BotEquipmentModGenerator itemModPool: Record, weapon: Item[], ammoTpl: string, - parentTemplate: ITemplateItem): [boolean, ITemplateItem] + parentTemplate: ITemplateItem, + ): [boolean, ITemplateItem] { let modTpl: string; let found = false; - const parentSlot = parentTemplate._props.Slots.find(i => i._name === modSlot); - + const parentSlot = parentTemplate._props.Slots.find((i) => i._name === modSlot); + // It's ammo, use predefined ammo parameter if (this.getAmmoContainers().includes(modSlot) && modSlot !== "mod_magazine") { @@ -539,27 +635,37 @@ export class BotEquipmentModGenerator // Ensure there's a pool of mods to pick from if (!(itemModPool[modSlot] || parentSlot._required)) { - this.logger.debug(`Mod pool for slot: ${modSlot} on item: ${parentTemplate._name} was empty, skipping mod`); + this.logger.debug( + `Mod pool for slot: ${modSlot} on item: ${parentTemplate._name} was empty, skipping mod`, + ); return null; } // Filter out non-whitelisted scopes, use full modpool if filtered pool would have no elements - if (modSlot.includes("mod_scope") && botWeaponSightWhitelist) + if (modSlot.includes("mod_scope") && botWeaponSightWhitelist) { // scope pool has more than one scope if (itemModPool[modSlot].length > 1) { - itemModPool[modSlot] = this.filterSightsByWeaponType(weapon[0], itemModPool[modSlot], botWeaponSightWhitelist); + itemModPool[modSlot] = this.filterSightsByWeaponType( + weapon[0], + itemModPool[modSlot], + botWeaponSightWhitelist, + ); } } - + // Pick random mod and check it's compatible const exhaustableModPool = new ExhaustableArray(itemModPool[modSlot], this.randomUtil, this.jsonUtil); - let modCompatibilityResult: {incompatible: boolean, reason: string} = {incompatible: false, reason: ""}; + let modCompatibilityResult: {incompatible: boolean; reason: string;} = {incompatible: false, reason: ""}; while (exhaustableModPool.hasValues()) { modTpl = exhaustableModPool.getRandomValue(); - modCompatibilityResult = this.botGeneratorHelper.isItemIncompatibleWithCurrentItems(weapon, modTpl, modSlot); + modCompatibilityResult = this.botGeneratorHelper.isItemIncompatibleWithCurrentItems( + weapon, + modTpl, + modSlot, + ); if (!modCompatibilityResult.incompatible) { found = true; @@ -592,7 +698,11 @@ export class BotEquipmentModGenerator { if (parentSlot._required) { - this.logger.warning(`Required slot unable to be filled, ${modSlot} on ${parentTemplate._name} ${parentTemplate._id} for weapon: ${weapon[0]._tpl}`); + this.logger.warning( + `Required slot unable to be filled, ${modSlot} on ${parentTemplate._name} ${parentTemplate._id} for weapon: ${ + weapon[0]._tpl + }`, + ); } return null; @@ -607,21 +717,27 @@ export class BotEquipmentModGenerator * @param modTpl _tpl * @param parentId parentId * @param modSlot slotId - * @param modTemplate Used to add additional properites in the upd object + * @param modTemplate Used to add additional properties in the upd object * @returns Item object */ - protected createModItem(modId: string, modTpl: string, parentId: string, modSlot: string, modTemplate: ITemplateItem, botRole: string): Item + protected createModItem( + modId: string, + modTpl: string, + parentId: string, + modSlot: string, + modTemplate: ITemplateItem, + botRole: string, + ): Item { return { _id: modId, _tpl: modTpl, parentId: parentId, slotId: modSlot, - ...this.botGeneratorHelper.generateExtraPropertiesForItem(modTemplate, botRole) + ...this.botGeneratorHelper.generateExtraPropertiesForItem(modTemplate, botRole), }; } - /** * Get a list of containers that hold ammo * e.g. mod_magazine / patron_in_weapon_000 @@ -635,14 +751,14 @@ export class BotEquipmentModGenerator /** * Get a random mod from an items compatible mods Filter array * @param modTpl ???? default value to return if nothing found - * @param parentSlot item mod will go into, used to get combatible items + * @param parentSlot item mod will go into, used to get compatible items * @param modSlot Slot to get mod to fill * @param items items to ensure picked mod is compatible with * @returns item tpl */ protected getModTplFromItemDb(modTpl: string, parentSlot: Slot, modSlot: string, items: Item[]): string { - // Find combatible mods and make an array of them + // Find compatible mods and make an array of them const allowedItems = parentSlot._props.filters[0].Filter; // Find mod item that fits slot from sorted mod array @@ -669,12 +785,22 @@ export class BotEquipmentModGenerator * @param parentTemplate template of the mods parent item * @returns true if valid */ - protected isModValidForSlot(modToAdd: [boolean, ITemplateItem], itemSlot: Slot, modSlot: string, parentTemplate: ITemplateItem): boolean + protected isModValidForSlot( + modToAdd: [boolean, ITemplateItem], + itemSlot: Slot, + modSlot: string, + parentTemplate: ITemplateItem, + ): boolean { // Mod lacks template item if (!modToAdd[1]) { - this.logger.error(this.localisationService.getText("bot-no_item_template_found_when_adding_mod", {modId: modToAdd[1]._id, modSlot: modSlot})); + this.logger.error( + this.localisationService.getText("bot-no_item_template_found_when_adding_mod", { + modId: modToAdd[1]._id, + modSlot: modSlot, + }), + ); this.logger.debug(`Item -> ${parentTemplate._id}; Slot -> ${modSlot}`); return false; @@ -686,16 +812,31 @@ export class BotEquipmentModGenerator // Slot must be filled, show warning if (itemSlot._required) { - this.logger.warning(this.localisationService.getText("bot-unable_to_add_mod_item_invalid", {itemName: modToAdd[1]._name, modSlot: modSlot, parentItemName: parentTemplate._name})); + this.logger.warning( + this.localisationService.getText("bot-unable_to_add_mod_item_invalid", { + itemName: modToAdd[1]._name, + modSlot: modSlot, + parentItemName: parentTemplate._name, + }), + ); } return false; } - // If mod id doesnt exist in slots filter list and mod id doesnt have any of the slots filters as a base class, mod isn't valid for the slot - if (!(itemSlot._props.filters[0].Filter.includes(modToAdd[1]._id) || this.itemHelper.isOfBaseclasses(modToAdd[1]._id, itemSlot._props.filters[0].Filter))) + // If mod id doesn't exist in slots filter list and mod id doesn't have any of the slots filters as a base class, mod isn't valid for the slot + if ( + !(itemSlot._props.filters[0].Filter.includes(modToAdd[1]._id) || + this.itemHelper.isOfBaseclasses(modToAdd[1]._id, itemSlot._props.filters[0].Filter)) + ) { - this.logger.warning(this.localisationService.getText("bot-mod_not_in_slot_filter_list", {modId: modToAdd[1]._id, modSlot: modSlot, parentName: parentTemplate._name})); + this.logger.warning( + this.localisationService.getText("bot-mod_not_in_slot_filter_list", { + modId: modToAdd[1]._id, + modSlot: modSlot, + parentName: parentTemplate._name, + }), + ); return false; } @@ -703,26 +844,39 @@ export class BotEquipmentModGenerator return true; } - /** * Find mod tpls of a provided type and add to modPool * @param desiredSlotName slot to look up and add we are adding tpls for (e.g mod_scope) * @param modTemplate db object for modItem we get compatible mods from * @param modPool Pool of mods we are adding to */ - protected addCompatibleModsForProvidedMod(desiredSlotName: string, modTemplate: ITemplateItem, modPool: Mods, botEquipBlacklist: EquipmentFilterDetails): void + protected addCompatibleModsForProvidedMod( + desiredSlotName: string, + modTemplate: ITemplateItem, + modPool: Mods, + botEquipBlacklist: EquipmentFilterDetails, + ): void { - const desiredSlotObject = modTemplate._props.Slots.find(x => x._name.includes(desiredSlotName)); + const desiredSlotObject = modTemplate._props.Slots.find((x) => x._name.includes(desiredSlotName)); if (desiredSlotObject) { const supportedSubMods = desiredSlotObject._props.filters[0].Filter; if (supportedSubMods) { // Filter mods - let filteredMods = this.filterWeaponModsByBlacklist(supportedSubMods, botEquipBlacklist, desiredSlotName); + let filteredMods = this.filterWeaponModsByBlacklist( + supportedSubMods, + botEquipBlacklist, + desiredSlotName, + ); if (filteredMods.length === 0) { - this.logger.warning(this.localisationService.getText("bot-unable_to_filter_mods_all_blacklisted", {slotName: desiredSlotObject._name, itemName: modTemplate._name})); + this.logger.warning( + this.localisationService.getText("bot-unable_to_filter_mods_all_blacklisted", { + slotName: desiredSlotObject._name, + itemName: modTemplate._name, + }), + ); filteredMods = supportedSubMods; } @@ -736,7 +890,6 @@ export class BotEquipmentModGenerator } } - /** * Get the possible items that fit a slot * @param parentItemId item tpl to get compatible items for @@ -744,14 +897,22 @@ export class BotEquipmentModGenerator * @param botEquipBlacklist equipment that should not be picked * @returns array of compatible items for that slot */ - protected getDynamicModPool(parentItemId: string, modSlot: string, botEquipBlacklist: EquipmentFilterDetails): string[] + protected getDynamicModPool( + parentItemId: string, + modSlot: string, + botEquipBlacklist: EquipmentFilterDetails, + ): string[] { - const modsFromDynamicPool = this.jsonUtil.clone(this.botEquipmentModPoolService.getCompatibleModsForWeaponSlot(parentItemId, modSlot)); + const modsFromDynamicPool = this.jsonUtil.clone( + this.botEquipmentModPoolService.getCompatibleModsForWeaponSlot(parentItemId, modSlot), + ); const filteredMods = this.filterWeaponModsByBlacklist(modsFromDynamicPool, botEquipBlacklist, modSlot); if (filteredMods.length === 0) { - this.logger.warning(this.localisationService.getText("bot-unable_to_filter_mod_slot_all_blacklisted", modSlot)); + this.logger.warning( + this.localisationService.getText("bot-unable_to_filter_mod_slot_all_blacklisted", modSlot), + ); return modsFromDynamicPool; } @@ -765,18 +926,24 @@ export class BotEquipmentModGenerator * @param modSlot slot mods belong to * @returns Filtered array of mod tpls */ - protected filterWeaponModsByBlacklist(allowedMods: string[], botEquipBlacklist: EquipmentFilterDetails, modSlot: string): string[] + protected filterWeaponModsByBlacklist( + allowedMods: string[], + botEquipBlacklist: EquipmentFilterDetails, + modSlot: string, + ): string[] { if (!botEquipBlacklist) { return allowedMods; } - + let result: string[] = []; - // Get item blacklist and mod equipmet blackist as one array - const blacklist = this.itemFilterService.getBlacklistedItems().concat(botEquipBlacklist.equipment[modSlot] || []); - result = allowedMods.filter(x => !blacklist.includes(x)); + // Get item blacklist and mod equipment blacklist as one array + const blacklist = this.itemFilterService.getBlacklistedItems().concat( + botEquipBlacklist.equipment[modSlot] || [], + ); + result = allowedMods.filter((x) => !blacklist.includes(x)); return result; } @@ -796,8 +963,13 @@ export class BotEquipmentModGenerator let itemModPool = modPool[parentTemplate._id]; if (!itemModPool) { - this.logger.warning(this.localisationService.getText("bot-unable_to_fill_camora_slot_mod_pool_empty", {weaponId: parentTemplate._id, weaponName: parentTemplate._name})); - const camoraSlots = parentTemplate._props.Slots.filter(x => x._name.startsWith("camora")); + this.logger.warning( + this.localisationService.getText("bot-unable_to_fill_camora_slot_mod_pool_empty", { + weaponId: parentTemplate._id, + weaponName: parentTemplate._name, + }), + ); + const camoraSlots = parentTemplate._props.Slots.filter((x) => x._name.startsWith("camora")); // Attempt to generate camora slots for item modPool[parentTemplate._id] = {}; @@ -818,7 +990,11 @@ export class BotEquipmentModGenerator else if (camoraFirstSlot in itemModPool) { modSlot = camoraFirstSlot; - exhaustableModPool = new ExhaustableArray(this.mergeCamoraPoolsTogether(itemModPool), this.randomUtil, this.jsonUtil); + exhaustableModPool = new ExhaustableArray( + this.mergeCamoraPoolsTogether(itemModPool), + this.randomUtil, + this.jsonUtil, + ); } else { @@ -854,17 +1030,17 @@ export class BotEquipmentModGenerator _id: modId, _tpl: modTpl, parentId: parentId, - slotId: modSlotId + slotId: modSlotId, }); } } /** - * Take a record of camoras and merge the compatable shells into one array + * Take a record of camoras and merge the compatible shells into one array * @param camorasWithShells camoras we want to merge into one array - * @returns string array of shells fro luitple camora sources + * @returns string array of shells for multiple camora sources */ - protected mergeCamoraPoolsTogether(camorasWithShells: Record ): string[] + protected mergeCamoraPoolsTogether(camorasWithShells: Record): string[] { const poolResult: string[] = []; for (const camoraKey in camorasWithShells) @@ -889,10 +1065,14 @@ export class BotEquipmentModGenerator * e.g. filter out rifle scopes from SMGs * @param weapon Weapon scopes will be added to * @param scopes Full scope pool - * @param botWeaponSightWhitelist Whitelist of scope types by weapon base type + * @param botWeaponSightWhitelist Whitelist of scope types by weapon base type * @returns Array of scope tpls that have been filtered to just ones allowed for that weapon type */ - protected filterSightsByWeaponType(weapon: Item, scopes: string[], botWeaponSightWhitelist: Record): string[] + protected filterSightsByWeaponType( + weapon: Item, + scopes: string[], + botWeaponSightWhitelist: Record, + ): string[] { const weaponDetails = this.itemHelper.getItem(weapon._tpl); @@ -900,7 +1080,11 @@ export class BotEquipmentModGenerator const whitelistedSightTypes = botWeaponSightWhitelist[weaponDetails[1]._parent]; if (!whitelistedSightTypes) { - this.logger.debug(`Unable to find whitelist for weapon type: ${weaponDetails[1]._parent} ${weaponDetails[1]._name}, skipping sight filtering`); + this.logger.debug( + `Unable to find whitelist for weapon type: ${weaponDetails[1]._parent} ${ + weaponDetails[1]._name + }, skipping sight filtering`, + ); return scopes; } @@ -920,14 +1104,23 @@ export class BotEquipmentModGenerator // Edge case, what if item is a mount for a scope and not directly a scope? // Check item is mount + has child items const itemDetails = this.itemHelper.getItem(item)[1]; - if (this.itemHelper.isOfBaseclass(item, BaseClasses.MOUNT) && itemDetails._props.Slots.length > 0 ) + if (this.itemHelper.isOfBaseclass(item, BaseClasses.MOUNT) && itemDetails._props.Slots.length > 0) { // Check to see if mount has a scope slot (only include primary slot, ignore the rest like the backup sight slots) // Should only find 1 as there's currently no items with a mod_scope AND a mod_scope_000 - const scopeSlot = itemDetails._props.Slots.filter(x => ["mod_scope", "mod_scope_000"].includes(x._name)); + const scopeSlot = itemDetails._props.Slots.filter((x) => + ["mod_scope", "mod_scope_000"].includes(x._name) + ); // Mods scope slot found must allow ALL whitelisted scope types OR be a mount - if (scopeSlot?.every(x => x._props.filters[0].Filter.every(x => this.itemHelper.isOfBaseclasses(x, whitelistedSightTypes) || this.itemHelper.isOfBaseclass(x, BaseClasses.MOUNT)))) + if ( + scopeSlot?.every((x) => + x._props.filters[0].Filter.every((x) => + this.itemHelper.isOfBaseclasses(x, whitelistedSightTypes) || + this.itemHelper.isOfBaseclass(x, BaseClasses.MOUNT) + ) + ) + ) { // Add mod to allowed list filteredScopesAndMods.push(item); @@ -935,14 +1128,16 @@ export class BotEquipmentModGenerator } } - // No mods added to return list after filtering has occured, send back the original mod list + // No mods added to return list after filtering has occurred, send back the original mod list if (!filteredScopesAndMods || filteredScopesAndMods.length === 0) { - this.logger.debug(`Scope whitelist too restrictive for: ${weapon._tpl} ${weaponDetails[1]._name}, skipping filter`); + this.logger.debug( + `Scope whitelist too restrictive for: ${weapon._tpl} ${weaponDetails[1]._name}, skipping filter`, + ); return scopes; } return filteredScopesAndMods; } -} \ No newline at end of file +} diff --git a/project/src/generators/BotGenerator.ts b/project/src/generators/BotGenerator.ts index 74b73e29..f43bf0b3 100644 --- a/project/src/generators/BotGenerator.ts +++ b/project/src/generators/BotGenerator.ts @@ -8,9 +8,12 @@ import { ProfileHelper } from "@spt-aki/helpers/ProfileHelper"; import { WeightedRandomHelper } from "@spt-aki/helpers/WeightedRandomHelper"; import { Common, - IBaseJsonSkills, IBaseSkill, IBotBase, Info, Health as PmcHealth, - Skills as botSkills + IBaseJsonSkills, + IBaseSkill, + IBotBase, + Info, + Skills as botSkills, } from "@spt-aki/models/eft/common/tables/IBotBase"; import { Appearance, Health, IBotType } from "@spt-aki/models/eft/common/tables/IBotType"; import { Item, Upd } from "@spt-aki/models/eft/common/tables/IItem"; @@ -53,7 +56,7 @@ export class BotGenerator @inject("BotDifficultyHelper") protected botDifficultyHelper: BotDifficultyHelper, @inject("SeasonalEventService") protected seasonalEventService: SeasonalEventService, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); @@ -65,7 +68,7 @@ export class BotGenerator * @param role e.g. assault / pmcbot * @param difficulty easy/normal/hard/impossible * @param botTemplate base bot template to use (e.g. assault/pmcbot) - * @returns + * @returns */ public generatePlayerScav(sessionId: string, role: string, difficulty: string, botTemplate: IBotType): IBotBase { @@ -82,7 +85,7 @@ export class BotGenerator botRelativeLevelDeltaMax: 0, botCountToGenerate: 1, botDifficulty: difficulty, - isPlayerScav: true + isPlayerScav: true, }; bot = this.generateBot(sessionId, bot, botTemplate, botGenDetails); @@ -93,12 +96,13 @@ export class BotGenerator /** * Create x number of bots of the type/side/difficulty defined in botGenerationDetails * @param sessionId Session id - * @param botGenerationDetails details on how to generate bots + * @param botGenerationDetails details on how to generate bots * @returns array of bots */ public prepareAndGenerateBots( sessionId: string, - botGenerationDetails: BotGenerationDetails): IBotBase[] + botGenerationDetails: BotGenerationDetails, + ): IBotBase[] { const output: IBotBase[] = []; for (let i = 0; i < botGenerationDetails.botCountToGenerate; i++) @@ -108,19 +112,24 @@ export class BotGenerator bot.Info.Settings.Role = botGenerationDetails.role; bot.Info.Side = botGenerationDetails.side; bot.Info.Settings.BotDifficulty = botGenerationDetails.botDifficulty; - + // Get raw json data for bot (Cloned) const botJsonTemplate = this.jsonUtil.clone(this.botHelper.getBotTemplate( - (botGenerationDetails.isPmc) - ? bot.Info.Side - : botGenerationDetails.role)); + (botGenerationDetails.isPmc) ? + bot.Info.Side : + botGenerationDetails.role, + )); bot = this.generateBot(sessionId, bot, botJsonTemplate, botGenerationDetails); - + output.push(bot); } - this.logger.debug(`Generated ${botGenerationDetails.botCountToGenerate} ${output[0].Info.Settings.Role} (${botGenerationDetails.eventRole}) bots`); + this.logger.debug( + `Generated ${botGenerationDetails.botCountToGenerate} ${ + output[0].Info.Settings.Role + } (${botGenerationDetails.eventRole}) bots`, + ); return output; } @@ -142,21 +151,43 @@ export class BotGenerator * @param botGenerationDetails details on how to generate the bot * @returns IBotBase object */ - protected generateBot(sessionId: string, bot: IBotBase, botJsonTemplate: IBotType, botGenerationDetails: BotGenerationDetails): IBotBase + protected generateBot( + sessionId: string, + bot: IBotBase, + botJsonTemplate: IBotType, + botGenerationDetails: BotGenerationDetails, + ): IBotBase { const botRole = botGenerationDetails.role.toLowerCase(); - const botLevel = this.botLevelGenerator.generateBotLevel(botJsonTemplate.experience.level, botGenerationDetails, bot); + const botLevel = this.botLevelGenerator.generateBotLevel( + botJsonTemplate.experience.level, + botGenerationDetails, + bot, + ); if (!botGenerationDetails.isPlayerScav) { - this.botEquipmentFilterService.filterBotEquipment(sessionId, botJsonTemplate, botLevel.level, botGenerationDetails); + this.botEquipmentFilterService.filterBotEquipment( + sessionId, + botJsonTemplate, + botLevel.level, + botGenerationDetails, + ); } - bot.Info.Nickname = this.generateBotNickname(botJsonTemplate, botGenerationDetails.isPlayerScav, botRole, sessionId); + bot.Info.Nickname = this.generateBotNickname( + botJsonTemplate, + botGenerationDetails.isPlayerScav, + botRole, + sessionId, + ); if (!this.seasonalEventService.christmasEventEnabled()) { - this.seasonalEventService.removeChristmasItemsFromBotInventory(botJsonTemplate.inventory, botGenerationDetails.role); + this.seasonalEventService.removeChristmasItemsFromBotInventory( + botJsonTemplate.inventory, + botGenerationDetails.role, + ); } // Remove hideout data if bot is not a PMC or pscav @@ -167,7 +198,10 @@ export class BotGenerator bot.Info.Experience = botLevel.exp; bot.Info.Level = botLevel.level; - bot.Info.Settings.Experience = this.randomUtil.getInt(botJsonTemplate.experience.reward.min, botJsonTemplate.experience.reward.max); + bot.Info.Settings.Experience = this.randomUtil.getInt( + botJsonTemplate.experience.reward.min, + botJsonTemplate.experience.reward.max, + ); bot.Info.Settings.StandingForKill = botJsonTemplate.experience.standingForKill; bot.Info.Voice = this.randomUtil.getArrayValue(botJsonTemplate.appearance.voice); bot.Health = this.generateHealth(botJsonTemplate.health, bot.Info.Side === "Savage"); @@ -175,7 +209,13 @@ export class BotGenerator this.setBotAppearance(bot, botJsonTemplate.appearance, botGenerationDetails); - bot.Inventory = this.botInventoryGenerator.generateInventory(sessionId, botJsonTemplate, botRole, botGenerationDetails.isPmc, botLevel.level); + bot.Inventory = this.botInventoryGenerator.generateInventory( + sessionId, + botJsonTemplate, + botRole, + botGenerationDetails.isPmc, + botLevel.level, + ); if (this.botHelper.isBotPmc(botRole)) { @@ -205,7 +245,6 @@ export class BotGenerator * @param appearance Appearance settings to choose from * @param botGenerationDetails Generation details */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars protected setBotAppearance(bot: IBotBase, appearance: Appearance, botGenerationDetails: BotGenerationDetails): void { bot.Customization.Head = this.randomUtil.getArrayValue(appearance.head); @@ -216,17 +255,24 @@ export class BotGenerator /** * Create a bot nickname - * @param botJsonTemplate x.json from database + * @param botJsonTemplate x.json from database * @param isPlayerScav Will bot be player scav * @param botRole role of bot e.g. assault * @returns Nickname for bot */ - protected generateBotNickname(botJsonTemplate: IBotType, isPlayerScav: boolean, botRole: string, sessionId: string): string + protected generateBotNickname( + botJsonTemplate: IBotType, + isPlayerScav: boolean, + botRole: string, + sessionId: string, + ): string { - let name = `${this.randomUtil.getArrayValue(botJsonTemplate.firstName)} ${this.randomUtil.getArrayValue(botJsonTemplate.lastName) || ""}`; + let name = `${this.randomUtil.getArrayValue(botJsonTemplate.firstName)} ${ + this.randomUtil.getArrayValue(botJsonTemplate.lastName) || "" + }`; name = name.trim(); const playerProfile = this.profileHelper.getPmcProfile(sessionId); - + // Simulate bot looking like a Player scav with the pmc name in brackets if (botRole === "assault" && this.randomUtil.getChance100(this.botConfig.chanceAssaultScavHasPlayerScavName)) { @@ -237,7 +283,7 @@ export class BotGenerator const pmcNames = [ ...this.databaseServer.getTables().bots.types["usec"].firstName, - ...this.databaseServer.getTables().bots.types["bear"].firstName + ...this.databaseServer.getTables().bots.types["bear"].firstName, ]; return `${name} (${this.randomUtil.getArrayValue(pmcNames)})`; @@ -253,7 +299,6 @@ export class BotGenerator { if (this.randomUtil.getChance100(this.pmcConfig.addPrefixToSameNamePMCAsPlayerChance)) { - const prefix = this.localisationService.getRandomTextThatMatchesPartialKey("pmc-name_prefix_"); name = `${prefix} ${name}`; } @@ -268,7 +313,10 @@ export class BotGenerator */ protected logPmcGeneratedCount(output: IBotBase[]): void { - const pmcCount = output.reduce((acc, cur) => cur.Info.Side === "Bear" || cur.Info.Side === "Usec" ? ++acc : acc, 0); + const pmcCount = output.reduce( + (acc, cur) => cur.Info.Side === "Bear" || cur.Info.Side === "Usec" ? ++acc : acc, + 0, + ); this.logger.debug(`Generated ${output.length} total bots. Replaced ${pmcCount} with PMCs`); } @@ -280,68 +328,68 @@ export class BotGenerator */ protected generateHealth(healthObj: Health, playerScav = false): PmcHealth { - const bodyParts = (playerScav) - ? healthObj.BodyParts[0] - : this.randomUtil.getArrayValue(healthObj.BodyParts); + const bodyParts = playerScav ? + healthObj.BodyParts[0] : + this.randomUtil.getArrayValue(healthObj.BodyParts); const newHealth: PmcHealth = { Hydration: { Current: this.randomUtil.getInt(healthObj.Hydration.min, healthObj.Hydration.max), - Maximum: healthObj.Hydration.max + Maximum: healthObj.Hydration.max, }, Energy: { Current: this.randomUtil.getInt(healthObj.Energy.min, healthObj.Energy.max), - Maximum: healthObj.Energy.max + Maximum: healthObj.Energy.max, }, Temperature: { Current: this.randomUtil.getInt(healthObj.Temperature.min, healthObj.Temperature.max), - Maximum: healthObj.Temperature.max + Maximum: healthObj.Temperature.max, }, BodyParts: { Head: { Health: { Current: this.randomUtil.getInt(bodyParts.Head.min, bodyParts.Head.max), - Maximum: Math.round(bodyParts.Head.max) - } + Maximum: Math.round(bodyParts.Head.max), + }, }, Chest: { Health: { Current: this.randomUtil.getInt(bodyParts.Chest.min, bodyParts.Chest.max), - Maximum: Math.round(bodyParts.Chest.max) - } + Maximum: Math.round(bodyParts.Chest.max), + }, }, Stomach: { Health: { Current: this.randomUtil.getInt(bodyParts.Stomach.min, bodyParts.Stomach.max), - Maximum: Math.round(bodyParts.Stomach.max) - } + Maximum: Math.round(bodyParts.Stomach.max), + }, }, LeftArm: { Health: { Current: this.randomUtil.getInt(bodyParts.LeftArm.min, bodyParts.LeftArm.max), - Maximum: Math.round(bodyParts.LeftArm.max) - } + Maximum: Math.round(bodyParts.LeftArm.max), + }, }, RightArm: { Health: { Current: this.randomUtil.getInt(bodyParts.RightArm.min, bodyParts.RightArm.max), - Maximum: Math.round(bodyParts.RightArm.max) - } + Maximum: Math.round(bodyParts.RightArm.max), + }, }, LeftLeg: { Health: { Current: this.randomUtil.getInt(bodyParts.LeftLeg.min, bodyParts.LeftLeg.max), - Maximum: Math.round(bodyParts.LeftLeg.max) - } + Maximum: Math.round(bodyParts.LeftLeg.max), + }, }, RightLeg: { Health: { Current: this.randomUtil.getInt(bodyParts.RightLeg.min, bodyParts.RightLeg.max), - Maximum: Math.round(bodyParts.RightLeg.max) - } - } + Maximum: Math.round(bodyParts.RightLeg.max), + }, + }, }, - UpdateTime: this.timeUtil.getTimestamp() + UpdateTime: this.timeUtil.getTimestamp(), }; return newHealth; @@ -350,14 +398,14 @@ export class BotGenerator /** * Get a bots skills with randomsied progress value between the min and max values * @param botSkills Skills that should have their progress value randomised - * @returns + * @returns */ protected generateSkills(botSkills: IBaseJsonSkills): botSkills { const skillsToReturn: botSkills = { Common: this.getSkillsWithRandomisedProgressValue(botSkills.Common, true), Mastering: this.getSkillsWithRandomisedProgressValue(botSkills.Mastering, false), - Points: 0 + Points: 0, }; return skillsToReturn; @@ -369,7 +417,10 @@ export class BotGenerator * @param isCommonSkills Are the skills 'common' skills * @returns Skills with randomised progress values as an array */ - protected getSkillsWithRandomisedProgressValue(skills: Record, isCommonSkills: boolean): IBaseSkill[] + protected getSkillsWithRandomisedProgressValue( + skills: Record, + isCommonSkills: boolean, + ): IBaseSkill[] { if (Object.keys(skills ?? []).length === 0) { @@ -384,22 +435,22 @@ export class BotGenerator { return null; } - + // All skills have id and progress props const skillToAdd: IBaseSkill = { Id: skillKey, - Progress: this.randomUtil.getInt(skill.min, skill.max) + Progress: this.randomUtil.getInt(skill.min, skill.max), }; - + // Common skills have additional props if (isCommonSkills) { (skillToAdd as Common).PointsEarnedDuringSession = 0; (skillToAdd as Common).LastAccess = 0; } - + return skillToAdd; - }).filter(x => x !== null); + }).filter((x) => x !== null); } /** @@ -422,7 +473,7 @@ export class BotGenerator const defaultInventory = "55d7217a4bdc2d86028b456d"; const itemsByParentHash: Record = {}; const inventoryItemHash: Record = {}; - + // Generate inventoryItem list let inventoryId = ""; for (const item of profile.Inventory.items) @@ -482,7 +533,9 @@ export class BotGenerator } botInfo.GameVersion = this.weightedRandomHelper.getWeightedValue(this.pmcConfig.gameVersionWeight); - botInfo.MemberCategory = Number.parseInt(this.weightedRandomHelper.getWeightedValue(this.pmcConfig.accountTypeWeight)); + botInfo.MemberCategory = Number.parseInt( + this.weightedRandomHelper.getWeightedValue(this.pmcConfig.accountTypeWeight), + ); } /** @@ -505,8 +558,8 @@ export class BotGenerator KillerAccountId: "Unknown", KillerProfileId: "Unknown", KillerName: "Unknown", - WeaponName: "Unknown" - } + WeaponName: "Unknown", + }, }; const inventoryItem: Item = { @@ -515,11 +568,11 @@ export class BotGenerator parentId: bot.Inventory.equipment, slotId: "Dogtag", location: undefined, - upd: upd + upd: upd, }; bot.Inventory.items.push(inventoryItem); return bot; } -} \ No newline at end of file +} diff --git a/project/src/generators/BotInventoryGenerator.ts b/project/src/generators/BotInventoryGenerator.ts index 6da1395a..e6f49862 100644 --- a/project/src/generators/BotInventoryGenerator.ts +++ b/project/src/generators/BotInventoryGenerator.ts @@ -39,7 +39,7 @@ export class BotInventoryGenerator @inject("LocalisationService") protected localisationService: LocalisationService, @inject("BotEquipmentModPoolService") protected botEquipmentModPoolService: BotEquipmentModPoolService, @inject("BotEquipmentModGenerator") protected botEquipmentModGenerator: BotEquipmentModGenerator, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); @@ -54,7 +54,13 @@ export class BotInventoryGenerator * @param botLevel Level of bot being generated * @returns PmcInventory object with equipment/weapons/loot */ - public generateInventory(sessionId: string, botJsonTemplate: IBotType, botRole: string, isPmc: boolean, botLevel: number): PmcInventory + public generateInventory( + sessionId: string, + botJsonTemplate: IBotType, + botRole: string, + isPmc: boolean, + botLevel: number, + ): PmcInventory { const templateInventory = botJsonTemplate.inventory; const equipmentChances = botJsonTemplate.chances; @@ -66,7 +72,16 @@ export class BotInventoryGenerator this.generateAndAddEquipmentToBot(templateInventory, equipmentChances, botRole, botInventory, botLevel); // Roll weapon spawns (primary/secondary/holster) and generate a weapon for each roll that passed - this.generateAndAddWeaponsToBot(templateInventory, equipmentChances, sessionId, botInventory, botRole, isPmc, itemGenerationLimitsMinMax, botLevel); + this.generateAndAddWeaponsToBot( + templateInventory, + equipmentChances, + sessionId, + botInventory, + botRole, + isPmc, + itemGenerationLimitsMinMax, + botLevel, + ); // Pick loot and add to bots containers (rig/backpack/pockets/secure) this.botLootGenerator.generateLoot(sessionId, botJsonTemplate, isPmc, botRole, botInventory, botLevel); @@ -99,24 +114,24 @@ export class BotInventoryGenerator items: [ { _id: equipmentId, - _tpl: equipmentTpl + _tpl: equipmentTpl, }, { _id: stashId, - _tpl: stashTpl + _tpl: stashTpl, }, { _id: questRaidItemsId, - _tpl: questRaidItemsTpl + _tpl: questRaidItemsTpl, }, { _id: questStashItemsId, - _tpl: questStashItemsTpl + _tpl: questStashItemsTpl, }, { _id: sortingTableId, - _tpl: sortingTableTpl - } + _tpl: sortingTableTpl, + }, ], equipment: equipmentId, stash: stashId, @@ -124,7 +139,7 @@ export class BotInventoryGenerator questStashItems: questStashItemsId, sortingTable: sortingTableId, hideoutAreaStashes: {}, - fastPanel: {} + fastPanel: {}, }; } @@ -136,7 +151,13 @@ export class BotInventoryGenerator * @param botInventory Inventory to add equipment to * @param botLevel Level of bot */ - protected generateAndAddEquipmentToBot(templateInventory: Inventory, equipmentChances: Chances, botRole: string, botInventory: PmcInventory, botLevel: number): void + protected generateAndAddEquipmentToBot( + templateInventory: Inventory, + equipmentChances: Chances, + botRole: string, + botInventory: PmcInventory, + botLevel: number, + ): void { // These will be handled later const excludedSlots: string[] = [ @@ -147,7 +168,7 @@ export class BotInventoryGenerator EquipmentSlots.TACTICAL_VEST, EquipmentSlots.FACE_COVER, EquipmentSlots.HEADWEAR, - EquipmentSlots.EARPIECE + EquipmentSlots.EARPIECE, ]; const botEquipConfig = this.botConfig.equipment[this.botGeneratorHelper.getBotEquipmentRole(botRole)]; @@ -155,21 +176,69 @@ export class BotInventoryGenerator for (const equipmentSlot in templateInventory.equipment) { - // Weapons have special generation and will be generated seperately; ArmorVest should be generated after TactivalVest + // Weapons have special generation and will be generated separately; ArmorVest should be generated after TactivalVest if (excludedSlots.includes(equipmentSlot)) { continue; } - this.generateEquipment(equipmentSlot, templateInventory.equipment[equipmentSlot], templateInventory.mods, equipmentChances, botRole, botInventory, randomistionDetails); + this.generateEquipment( + equipmentSlot, + templateInventory.equipment[equipmentSlot], + templateInventory.mods, + equipmentChances, + botRole, + botInventory, + randomistionDetails, + ); } // Generate below in specific order - this.generateEquipment(EquipmentSlots.FACE_COVER, templateInventory.equipment.FaceCover, templateInventory.mods, equipmentChances, botRole, botInventory, randomistionDetails); - this.generateEquipment(EquipmentSlots.HEADWEAR, templateInventory.equipment.Headwear, templateInventory.mods, equipmentChances, botRole, botInventory, randomistionDetails); - this.generateEquipment(EquipmentSlots.EARPIECE, templateInventory.equipment.Earpiece, templateInventory.mods, equipmentChances, botRole, botInventory, randomistionDetails); - this.generateEquipment(EquipmentSlots.TACTICAL_VEST, templateInventory.equipment.TacticalVest, templateInventory.mods, equipmentChances, botRole, botInventory, randomistionDetails); - this.generateEquipment(EquipmentSlots.ARMOR_VEST, templateInventory.equipment.ArmorVest, templateInventory.mods, equipmentChances, botRole, botInventory, randomistionDetails); + this.generateEquipment( + EquipmentSlots.FACE_COVER, + templateInventory.equipment.FaceCover, + templateInventory.mods, + equipmentChances, + botRole, + botInventory, + randomistionDetails, + ); + this.generateEquipment( + EquipmentSlots.HEADWEAR, + templateInventory.equipment.Headwear, + templateInventory.mods, + equipmentChances, + botRole, + botInventory, + randomistionDetails, + ); + this.generateEquipment( + EquipmentSlots.EARPIECE, + templateInventory.equipment.Earpiece, + templateInventory.mods, + equipmentChances, + botRole, + botInventory, + randomistionDetails, + ); + this.generateEquipment( + EquipmentSlots.TACTICAL_VEST, + templateInventory.equipment.TacticalVest, + templateInventory.mods, + equipmentChances, + botRole, + botInventory, + randomistionDetails, + ); + this.generateEquipment( + EquipmentSlots.ARMOR_VEST, + templateInventory.equipment.ArmorVest, + templateInventory.mods, + equipmentChances, + botRole, + botInventory, + randomistionDetails, + ); } /** @@ -189,14 +258,18 @@ export class BotInventoryGenerator spawnChances: Chances, botRole: string, inventory: PmcInventory, - randomisationDetails: RandomisationDetails): void + randomisationDetails: RandomisationDetails, + ): void { - const spawnChance = ([EquipmentSlots.POCKETS, EquipmentSlots.SECURED_CONTAINER] as string[]).includes(equipmentSlot) - ? 100 - : spawnChances.equipment[equipmentSlot]; + const spawnChance = + ([EquipmentSlots.POCKETS, EquipmentSlots.SECURED_CONTAINER] as string[]).includes(equipmentSlot) ? + 100 : + spawnChances.equipment[equipmentSlot]; if (typeof spawnChance === "undefined") { - this.logger.warning(this.localisationService.getText("bot-no_spawn_chance_defined_for_equipment_slot", equipmentSlot)); + this.logger.warning( + this.localisationService.getText("bot-no_spawn_chance_defined_for_equipment_slot", equipmentSlot), + ); return; } @@ -216,7 +289,13 @@ export class BotInventoryGenerator return; } - if (this.botGeneratorHelper.isItemIncompatibleWithCurrentItems(inventory.items, equipmentItemTpl, equipmentSlot).incompatible) + if ( + this.botGeneratorHelper.isItemIncompatibleWithCurrentItems( + inventory.items, + equipmentItemTpl, + equipmentSlot, + ).incompatible + ) { // Bad luck - randomly picked item was not compatible with current gear return; @@ -227,19 +306,35 @@ export class BotInventoryGenerator _tpl: equipmentItemTpl, parentId: inventory.equipment, slotId: equipmentSlot, - ...this.botGeneratorHelper.generateExtraPropertiesForItem(itemTemplate[1], botRole) + ...this.botGeneratorHelper.generateExtraPropertiesForItem(itemTemplate[1], botRole), }; // use dynamic mod pool if enabled in config const botEquipmentRole = this.botGeneratorHelper.getBotEquipmentRole(botRole); - if (this.botConfig.equipment[botEquipmentRole] && randomisationDetails?.randomisedArmorSlots?.includes(equipmentSlot)) + if ( + this.botConfig.equipment[botEquipmentRole] && + randomisationDetails?.randomisedArmorSlots?.includes(equipmentSlot) + ) { - modPool[equipmentItemTpl] = this.getFilteredDynamicModsForItem(equipmentItemTpl, this.botConfig.equipment[botEquipmentRole].blacklist); + modPool[equipmentItemTpl] = this.getFilteredDynamicModsForItem( + equipmentItemTpl, + this.botConfig.equipment[botEquipmentRole].blacklist, + ); } - if (typeof(modPool[equipmentItemTpl]) !== "undefined" || Object.keys(modPool[equipmentItemTpl] || {}).length > 0) + if ( + typeof (modPool[equipmentItemTpl]) !== "undefined" || + Object.keys(modPool[equipmentItemTpl] || {}).length > 0 + ) { - const items = this.botEquipmentModGenerator.generateModsForEquipment([item], modPool, id, itemTemplate[1], spawnChances.mods, botRole); + const items = this.botEquipmentModGenerator.generateModsForEquipment( + [item], + modPool, + id, + itemTemplate[1], + spawnChances.mods, + botRole, + ); inventory.items.push(...items); } else @@ -251,17 +346,20 @@ export class BotInventoryGenerator /** * Get all possible mods for item and filter down based on equipment blacklist from bot.json config - * @param itemTpl Item mod pool is being retreived and filtered + * @param itemTpl Item mod pool is being retrieved and filtered * @param equipmentBlacklist blacklist to filter mod pool with * @returns Filtered pool of mods */ - protected getFilteredDynamicModsForItem(itemTpl: string, equipmentBlacklist: EquipmentFilterDetails[]): Record + protected getFilteredDynamicModsForItem( + itemTpl: string, + equipmentBlacklist: EquipmentFilterDetails[], + ): Record { const modPool = this.botEquipmentModPoolService.getModsForGearSlot(itemTpl); for (const modSlot of Object.keys(modPool ?? [])) { const blacklistedMods = equipmentBlacklist[0]?.equipment[modSlot] || []; - const filteredMods = modPool[modSlot].filter(x => !blacklistedMods.includes(x)); + const filteredMods = modPool[modSlot].filter((x) => !blacklistedMods.includes(x)); if (filteredMods.length > 0) { @@ -283,7 +381,16 @@ export class BotInventoryGenerator * @param botLevel level of bot having weapon generated * @param itemGenerationLimitsMinMax Limits for items the bot can have */ - protected generateAndAddWeaponsToBot(templateInventory: Inventory, equipmentChances: Chances, sessionId: string, botInventory: PmcInventory, botRole: string, isPmc: boolean, itemGenerationLimitsMinMax: Generation, botLevel: number): void + protected generateAndAddWeaponsToBot( + templateInventory: Inventory, + equipmentChances: Chances, + sessionId: string, + botInventory: PmcInventory, + botRole: string, + isPmc: boolean, + itemGenerationLimitsMinMax: Generation, + botLevel: number, + ): void { const weaponSlotsToFill = this.getDesiredWeaponsForBot(equipmentChances); for (const weaponSlot of weaponSlotsToFill) @@ -291,7 +398,17 @@ export class BotInventoryGenerator // Add weapon to bot if true and bot json has something to put into the slot if (weaponSlot.shouldSpawn && Object.keys(templateInventory.equipment[weaponSlot.slot]).length) { - this.addWeaponAndMagazinesToInventory(sessionId, weaponSlot, templateInventory, botInventory, equipmentChances, botRole, isPmc, itemGenerationLimitsMinMax, botLevel); + this.addWeaponAndMagazinesToInventory( + sessionId, + weaponSlot, + templateInventory, + botInventory, + equipmentChances, + botRole, + isPmc, + itemGenerationLimitsMinMax, + botLevel, + ); } } } @@ -301,26 +418,27 @@ export class BotInventoryGenerator * @param equipmentChances Chances bot has certain equipment * @returns What slots bot should have weapons generated for */ - protected getDesiredWeaponsForBot(equipmentChances: Chances): { slot: EquipmentSlots; shouldSpawn: boolean; }[] + protected getDesiredWeaponsForBot(equipmentChances: Chances): {slot: EquipmentSlots; shouldSpawn: boolean;}[] { const shouldSpawnPrimary = this.randomUtil.getChance100(equipmentChances.equipment.FirstPrimaryWeapon); return [ { slot: EquipmentSlots.FIRST_PRIMARY_WEAPON, - shouldSpawn: shouldSpawnPrimary + shouldSpawn: shouldSpawnPrimary, }, { slot: EquipmentSlots.SECOND_PRIMARY_WEAPON, - shouldSpawn: shouldSpawnPrimary - ? this.randomUtil.getChance100(equipmentChances.equipment.SecondPrimaryWeapon) - : false + shouldSpawn: shouldSpawnPrimary ? + this.randomUtil.getChance100(equipmentChances.equipment.SecondPrimaryWeapon) : + false, }, { slot: EquipmentSlots.HOLSTER, - shouldSpawn: shouldSpawnPrimary - ? this.randomUtil.getChance100(equipmentChances.equipment.Holster) // Primary weapon = roll for chance at pistol - : true // No primary = force pistol - } + shouldSpawn: shouldSpawnPrimary ? + this.randomUtil.getChance100(equipmentChances.equipment.Holster) // Primary weapon = roll for chance at pistol + : + true, // No primary = force pistol + }, ]; } @@ -333,18 +451,19 @@ export class BotInventoryGenerator * @param equipmentChances Chances bot can have equipment equipped * @param botRole assault/pmcBot/bossTagilla etc * @param isPmc Is the bot being generated as a pmc - * @param itemGenerationWeights + * @param itemGenerationWeights */ protected addWeaponAndMagazinesToInventory( sessionId: string, - weaponSlot: { slot: EquipmentSlots; shouldSpawn: boolean; }, + weaponSlot: {slot: EquipmentSlots; shouldSpawn: boolean;}, templateInventory: Inventory, botInventory: PmcInventory, equipmentChances: Chances, botRole: string, isPmc: boolean, itemGenerationWeights: Generation, - botLevel: number): void + botLevel: number, + ): void { const generatedWeapon = this.botWeaponGenerator.generateRandomWeapon( sessionId, @@ -354,10 +473,16 @@ export class BotInventoryGenerator equipmentChances.mods, botRole, isPmc, - botLevel); + botLevel, + ); botInventory.items.push(...generatedWeapon.weapon); - this.botWeaponGenerator.addExtraMagazinesToInventory(generatedWeapon, itemGenerationWeights.items.magazines, botInventory, botRole); + this.botWeaponGenerator.addExtraMagazinesToInventory( + generatedWeapon, + itemGenerationWeights.items.magazines, + botInventory, + botRole, + ); } -} \ No newline at end of file +} diff --git a/project/src/generators/BotLevelGenerator.ts b/project/src/generators/BotLevelGenerator.ts index cc205912..8b2be669 100644 --- a/project/src/generators/BotLevelGenerator.ts +++ b/project/src/generators/BotLevelGenerator.ts @@ -15,9 +15,9 @@ export class BotLevelGenerator constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("RandomUtil") protected randomUtil: RandomUtil, - @inject("DatabaseServer") protected databaseServer: DatabaseServer + @inject("DatabaseServer") protected databaseServer: DatabaseServer, ) - { } + {} /** * Return a randomised bot level and exp value @@ -26,12 +26,20 @@ export class BotLevelGenerator * @param bot being level is being generated for * @returns IRandomisedBotLevelResult object */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public generateBotLevel(levelDetails: MinMax, botGenerationDetails: BotGenerationDetails, bot: IBotBase): IRandomisedBotLevelResult + public generateBotLevel( + levelDetails: MinMax, + botGenerationDetails: BotGenerationDetails, + bot: IBotBase, + ): IRandomisedBotLevelResult { const expTable = this.databaseServer.getTables().globals.config.exp.level.exp_table; - const highestLevel = this.getHighestRelativeBotLevel(botGenerationDetails.playerLevel, botGenerationDetails.botRelativeLevelDeltaMax, levelDetails, expTable); - + const highestLevel = this.getHighestRelativeBotLevel( + botGenerationDetails.playerLevel, + botGenerationDetails.botRelativeLevelDeltaMax, + levelDetails, + expTable, + ); + // Get random level based on the exp table. let exp = 0; const level = this.randomUtil.getInt(1, highestLevel); @@ -47,16 +55,21 @@ export class BotLevelGenerator exp += this.randomUtil.getInt(0, expTable[level].exp - 1); } - return { level, exp }; + return {level, exp}; } /** - * Get the highest level a bot can be relative to the players level, but no futher than the max size from globals.exp_table + * Get the highest level a bot can be relative to the players level, but no further than the max size from globals.exp_table * @param playerLevel Players current level * @param relativeDeltaMax max delta above player level to go * @returns highest level possible for bot */ - protected getHighestRelativeBotLevel(playerLevel: number, relativeDeltaMax: number, levelDetails: MinMax, expTable: IExpTable[]): number + protected getHighestRelativeBotLevel( + playerLevel: number, + relativeDeltaMax: number, + levelDetails: MinMax, + expTable: IExpTable[], + ): number { const maxPossibleLevel = Math.min(levelDetails.max, expTable.length); @@ -68,4 +81,4 @@ export class BotLevelGenerator return level; } -} \ No newline at end of file +} diff --git a/project/src/generators/BotLootGenerator.ts b/project/src/generators/BotLootGenerator.ts index e3b6594f..4125fd5c 100644 --- a/project/src/generators/BotLootGenerator.ts +++ b/project/src/generators/BotLootGenerator.ts @@ -30,7 +30,7 @@ export class BotLootGenerator { protected botConfig: IBotConfig; protected pmcConfig: IPmcConfig; - + constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("HashUtil") protected hashUtil: HashUtil, @@ -44,7 +44,7 @@ export class BotLootGenerator @inject("WeightedRandomHelper") protected weightedRandomHelper: WeightedRandomHelper, @inject("BotLootCacheService") protected botLootCacheService: BotLootCacheService, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); @@ -60,15 +60,24 @@ export class BotLootGenerator * @param botInventory Inventory to add loot to * @param botLevel Level of bot */ - public generateLoot(sessionId: string, botJsonTemplate: IBotType, isPmc: boolean, botRole: string, botInventory: PmcInventory, botLevel: number): void + public generateLoot( + sessionId: string, + botJsonTemplate: IBotType, + isPmc: boolean, + botRole: string, + botInventory: PmcInventory, + botLevel: number, + ): void { // Limits on item types to be added as loot const itemCounts = botJsonTemplate.generation.items; - + const backpackLootCount = this.weightedRandomHelper.getWeightedValue(itemCounts.backpackLoot.weights); const pocketLootCount = this.weightedRandomHelper.getWeightedValue(itemCounts.pocketLoot.weights); const vestLootCount = this.weightedRandomHelper.getWeightedValue(itemCounts.vestLoot.weights); - const specialLootItemCount = this.weightedRandomHelper.getWeightedValue(itemCounts.specialItems.weights); + const specialLootItemCount = this.weightedRandomHelper.getWeightedValue( + itemCounts.specialItems.weights, + ); const healingItemCount = this.weightedRandomHelper.getWeightedValue(itemCounts.healing.weights); const drugItemCount = this.weightedRandomHelper.getWeightedValue(itemCounts.drugs.weights); const stimItemCount = this.weightedRandomHelper.getWeightedValue(itemCounts.stims.weights); @@ -88,7 +97,8 @@ export class BotLootGenerator containersBotHasAvailable, specialLootItemCount, botInventory, - botRole); + botRole, + ); // Healing items / Meds this.addLootFromPool( @@ -99,7 +109,8 @@ export class BotLootGenerator botRole, false, 0, - isPmc); + isPmc, + ); // Drugs this.addLootFromPool( @@ -110,7 +121,8 @@ export class BotLootGenerator botRole, false, 0, - isPmc); + isPmc, + ); // Stims this.addLootFromPool( @@ -121,7 +133,8 @@ export class BotLootGenerator botRole, true, 0, - isPmc); + isPmc, + ); // Grenades this.addLootFromPool( @@ -132,8 +145,8 @@ export class BotLootGenerator botRole, false, 0, - isPmc); - + isPmc, + ); // Backpack - generate loot if they have one if (containersBotHasAvailable.includes(EquipmentSlots.BACKPACK)) @@ -141,7 +154,16 @@ export class BotLootGenerator // Add randomly generated weapon to PMC backpacks if (isPmc && this.randomUtil.getChance100(this.pmcConfig.looseWeaponInBackpackChancePercent)) { - this.addLooseWeaponsToInventorySlot(sessionId, botInventory, EquipmentSlots.BACKPACK, botJsonTemplate.inventory, botJsonTemplate.chances.mods, botRole, isPmc, botLevel); + this.addLooseWeaponsToInventorySlot( + sessionId, + botInventory, + EquipmentSlots.BACKPACK, + botJsonTemplate.inventory, + botJsonTemplate.chances.mods, + botRole, + isPmc, + botLevel, + ); } this.addLootFromPool( @@ -152,9 +174,10 @@ export class BotLootGenerator botRole, true, this.pmcConfig.maxBackpackLootTotalRub, - isPmc); + isPmc, + ); } - + // TacticalVest - generate loot if they have one if (containersBotHasAvailable.includes(EquipmentSlots.TACTICAL_VEST)) { @@ -167,10 +190,10 @@ export class BotLootGenerator botRole, true, this.pmcConfig.maxVestLootTotalRub, - isPmc); + isPmc, + ); } - // Pockets this.addLootFromPool( this.botLootCacheService.getLootFromCache(botRole, isPmc, LootCacheType.POCKET, botJsonTemplate), @@ -180,7 +203,8 @@ export class BotLootGenerator botRole, true, this.pmcConfig.maxPocketLootTotalRub, - isPmc); + isPmc, + ); } /** @@ -192,13 +216,12 @@ export class BotLootGenerator { const result = [EquipmentSlots.POCKETS]; - if (botInventory.items.find(x => x.slotId === EquipmentSlots.TACTICAL_VEST)) + if (botInventory.items.find((x) => x.slotId === EquipmentSlots.TACTICAL_VEST)) { - result.push(EquipmentSlots.TACTICAL_VEST); } - if (botInventory.items.find(x => x.slotId === EquipmentSlots.BACKPACK)) + if (botInventory.items.find((x) => x.slotId === EquipmentSlots.BACKPACK)) { result.push(EquipmentSlots.BACKPACK); } @@ -222,7 +245,8 @@ export class BotLootGenerator botRole, false, 0, - true); + true, + ); const surv12 = this.itemHelper.getItem("5d02797c86f774203f38e30a")[1]; this.addLootFromPool( @@ -233,7 +257,8 @@ export class BotLootGenerator botRole, false, 0, - true); + true, + ); const morphine = this.itemHelper.getItem("544fb3f34bdc2d03748b456a")[1]; this.addLootFromPool( @@ -244,7 +269,8 @@ export class BotLootGenerator botRole, false, 0, - true); + true, + ); const afak = this.itemHelper.getItem("60098ad7c2240c0fe85c570a")[1]; this.addLootFromPool( @@ -255,7 +281,8 @@ export class BotLootGenerator botRole, false, 0, - true); + true, + ); } /** @@ -290,14 +317,15 @@ export class BotLootGenerator botRole: string, useLimits = false, totalValueLimitRub = 0, - isPmc = false): void + isPmc = false, + ): void { // Loot pool has items if (pool.length) { let currentTotalRub = 0; const itemLimits: Record = {}; - const itemSpawnLimits: Record> = {}; + const itemSpawnLimits: Record> = {}; let fitItemIntoContainerAttempts = 0; for (let i = 0; i < totalItemCount; i++) { @@ -306,7 +334,7 @@ export class BotLootGenerator const itemsToAdd: Item[] = [{ _id: id, _tpl: itemToAddTemplate._id, - ...this.botGeneratorHelper.generateExtraPropertiesForItem(itemToAddTemplate, botRole) + ...this.botGeneratorHelper.generateExtraPropertiesForItem(itemToAddTemplate, botRole), }]; if (useLimits) @@ -321,11 +349,19 @@ export class BotLootGenerator itemSpawnLimits[botRole] = this.getItemSpawnLimitsForBotType(isPmc, botRole); } - if (this.itemHasReachedSpawnLimit(itemToAddTemplate, botRole, isPmc, itemLimits, itemSpawnLimits[botRole])) + if ( + this.itemHasReachedSpawnLimit( + itemToAddTemplate, + botRole, + isPmc, + itemLimits, + itemSpawnLimits[botRole], + ) + ) { i--; continue; - } + } } // Fill ammo box @@ -345,13 +381,21 @@ export class BotLootGenerator } // Attempt to add item to container(s) - const itemAddedResult = this.botWeaponGeneratorHelper.addItemWithChildrenToEquipmentSlot(equipmentSlots, id, itemToAddTemplate._id, itemsToAdd, inventoryToAddItemsTo); + const itemAddedResult = this.botWeaponGeneratorHelper.addItemWithChildrenToEquipmentSlot( + equipmentSlots, + id, + itemToAddTemplate._id, + itemsToAdd, + inventoryToAddItemsTo, + ); if (itemAddedResult === ItemAddedResult.NO_SPACE) { fitItemIntoContainerAttempts++; if (fitItemIntoContainerAttempts >= 4) { - this.logger.debug(`Failed to place item ${i} of ${totalItemCount} item into ${botRole} container: ${equipmentSlots}, ${fitItemIntoContainerAttempts} times, skipping`); + this.logger.debug( + `Failed to place item ${i} of ${totalItemCount} item into ${botRole} container: ${equipmentSlots}, ${fitItemIntoContainerAttempts} times, skipping`, + ); break; } @@ -383,16 +427,48 @@ export class BotLootGenerator * @param botRole bots role .e.g. pmcBot * @param isPmc are we generating for a pmc */ - protected addLooseWeaponsToInventorySlot(sessionId: string, botInventory: PmcInventory, equipmentSlot: string, templateInventory: Inventory, modChances: ModsChances, botRole: string, isPmc: boolean, botLevel: number): void + protected addLooseWeaponsToInventorySlot( + sessionId: string, + botInventory: PmcInventory, + equipmentSlot: string, + templateInventory: Inventory, + modChances: ModsChances, + botRole: string, + isPmc: boolean, + botLevel: number, + ): void { - const chosenWeaponType = this.randomUtil.getArrayValue([EquipmentSlots.FIRST_PRIMARY_WEAPON, EquipmentSlots.FIRST_PRIMARY_WEAPON, EquipmentSlots.FIRST_PRIMARY_WEAPON, EquipmentSlots.HOLSTER]); - const randomisedWeaponCount = this.randomUtil.getInt(this.pmcConfig.looseWeaponInBackpackLootMinMax.min, this.pmcConfig.looseWeaponInBackpackLootMinMax.max); + const chosenWeaponType = this.randomUtil.getArrayValue([ + EquipmentSlots.FIRST_PRIMARY_WEAPON, + EquipmentSlots.FIRST_PRIMARY_WEAPON, + EquipmentSlots.FIRST_PRIMARY_WEAPON, + EquipmentSlots.HOLSTER, + ]); + const randomisedWeaponCount = this.randomUtil.getInt( + this.pmcConfig.looseWeaponInBackpackLootMinMax.min, + this.pmcConfig.looseWeaponInBackpackLootMinMax.max, + ); if (randomisedWeaponCount > 0) { for (let i = 0; i < randomisedWeaponCount; i++) { - const generatedWeapon = this.botWeaponGenerator.generateRandomWeapon(sessionId, chosenWeaponType, templateInventory, botInventory.equipment, modChances, botRole, isPmc, botLevel); - this.botWeaponGeneratorHelper.addItemWithChildrenToEquipmentSlot([equipmentSlot], generatedWeapon.weapon[0]._id, generatedWeapon.weapon[0]._tpl, [...generatedWeapon.weapon], botInventory); + const generatedWeapon = this.botWeaponGenerator.generateRandomWeapon( + sessionId, + chosenWeaponType, + templateInventory, + botInventory.equipment, + modChances, + botRole, + isPmc, + botLevel, + ); + this.botWeaponGeneratorHelper.addItemWithChildrenToEquipmentSlot( + [equipmentSlot], + generatedWeapon.weapon[0]._id, + generatedWeapon.weapon[0]._tpl, + [...generatedWeapon.weapon], + botInventory, + ); } } } @@ -405,7 +481,12 @@ export class BotLootGenerator */ protected getRandomItemFromPoolByRole(pool: ITemplateItem[], botRole: string): ITemplateItem { - const itemIndex = this.randomUtil.getBiasedRandomNumber(0, pool.length - 1, pool.length - 1, this.getBotLootNValueByRole(botRole)); + const itemIndex = this.randomUtil.getBiasedRandomNumber( + 0, + pool.length - 1, + pool.length - 1, + this.getBotLootNValueByRole(botRole), + ); return pool[itemIndex]; } @@ -432,7 +513,7 @@ export class BotLootGenerator * All values are set to 0 * @param isPmc Is the bot a pmc * @param botRole Role the bot has - * @param limitCount + * @param limitCount */ protected initItemLimitArray(isPmc: boolean, botRole: string, limitCount: Record): void { @@ -443,7 +524,7 @@ export class BotLootGenerator limitCount[limit] = 0; } } - + /** * Check if an item has reached its bot-specific spawn limit * @param itemTemplate Item we check to see if its reached spawn limit @@ -453,7 +534,13 @@ export class BotLootGenerator * @param itemSpawnLimits The limits this bot is allowed to have * @returns true if item has reached spawn limit */ - protected itemHasReachedSpawnLimit(itemTemplate: ITemplateItem, botRole: string, isPmc: boolean, limitCount: Record, itemSpawnLimits: Record): boolean + protected itemHasReachedSpawnLimit( + itemTemplate: ITemplateItem, + botRole: string, + isPmc: boolean, + limitCount: Record, + itemSpawnLimits: Record, + ): boolean { // PMCs and scavs have different sections of bot config for spawn limits if (!!itemSpawnLimits && itemSpawnLimits.length === 0) @@ -484,7 +571,13 @@ export class BotLootGenerator // Prevent edge-case of small loot pools + code trying to add limited item over and over infinitely if (limitCount[idToCheckFor] > itemSpawnLimits[idToCheckFor] * 10) { - this.logger.debug(this.localisationService.getText("bot-item_spawn_limit_reached_skipping_item", {botRole: botRole, itemName: itemTemplate._name, attempts: limitCount[idToCheckFor]})); + this.logger.debug( + this.localisationService.getText("bot-item_spawn_limit_reached_skipping_item", { + botRole: botRole, + itemName: itemTemplate._name, + attempts: limitCount[idToCheckFor], + }), + ); return false; } @@ -505,9 +598,9 @@ export class BotLootGenerator { // PMCs have a different stack max size const minStackSize = itemTemplate._props.StackMinRandom; - const maxStackSize = (isPmc) - ? this.pmcConfig.dynamicLoot.moneyStackLimits[itemTemplate._id] - : itemTemplate._props.StackMaxRandom; + const maxStackSize = isPmc ? + this.pmcConfig.dynamicLoot.moneyStackLimits[itemTemplate._id] : + itemTemplate._props.StackMaxRandom; const randomSize = this.randomUtil.getInt(minStackSize, maxStackSize); if (!moneyItem.upd) @@ -515,7 +608,7 @@ export class BotLootGenerator moneyItem.upd = {}; } - moneyItem.upd.StackObjectsCount = randomSize; + moneyItem.upd.StackObjectsCount = randomSize; } /** @@ -526,16 +619,16 @@ export class BotLootGenerator */ protected randomiseAmmoStackSize(isPmc: boolean, itemTemplate: ITemplateItem, ammoItem: Item): void { - const randomSize = itemTemplate._props.StackMaxSize === 1 - ? 1 - : this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); + const randomSize = itemTemplate._props.StackMaxSize === 1 ? + 1 : + this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); if (!ammoItem.upd) { ammoItem.upd = {}; } - ammoItem.upd.StackObjectsCount = randomSize ; + ammoItem.upd.StackObjectsCount = randomSize; } /** @@ -557,7 +650,9 @@ export class BotLootGenerator return this.botConfig.itemSpawnLimits[botRole.toLowerCase()]; } - this.logger.warning(this.localisationService.getText("bot-unable_to_find_spawn_limits_fallback_to_defaults", botRole)); + this.logger.warning( + this.localisationService.getText("bot-unable_to_find_spawn_limits_fallback_to_defaults", botRole), + ); return this.botConfig.itemSpawnLimits["default"]; } @@ -570,7 +665,6 @@ export class BotLootGenerator */ protected getMatchingIdFromSpawnLimits(itemTemplate: ITemplateItem, spawnLimits: Record): string { - if (itemTemplate._id in spawnLimits) { return itemTemplate._id; @@ -585,4 +679,4 @@ export class BotLootGenerator // parentId and tplid not found return undefined; } -} \ No newline at end of file +} diff --git a/project/src/generators/BotWeaponGenerator.ts b/project/src/generators/BotWeaponGenerator.ts index b3010744..db97c19f 100644 --- a/project/src/generators/BotWeaponGenerator.ts +++ b/project/src/generators/BotWeaponGenerator.ts @@ -51,7 +51,7 @@ export class BotWeaponGenerator @inject("BotEquipmentModGenerator") protected botEquipmentModGenerator: BotEquipmentModGenerator, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("RepairService") protected repairService: RepairService, - @injectAll("InventoryMagGen") protected inventoryMagGenComponents: IInventoryMagGen[] + @injectAll("InventoryMagGen") protected inventoryMagGenComponents: IInventoryMagGen[], ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); @@ -64,16 +64,35 @@ export class BotWeaponGenerator * Pick a random weapon based on weightings and generate a functional weapon * @param equipmentSlot Primary/secondary/holster * @param botTemplateInventory e.g. assault.json - * @param weaponParentId - * @param modChances + * @param weaponParentId + * @param modChances * @param botRole role of bot, e.g. assault/followerBully * @param isPmc Is weapon generated for a pmc * @returns GenerateWeaponResult object */ - public generateRandomWeapon(sessionId: string, equipmentSlot: string, botTemplateInventory: Inventory, weaponParentId: string, modChances: ModsChances, botRole: string, isPmc: boolean, botLevel: number): GenerateWeaponResult + public generateRandomWeapon( + sessionId: string, + equipmentSlot: string, + botTemplateInventory: Inventory, + weaponParentId: string, + modChances: ModsChances, + botRole: string, + isPmc: boolean, + botLevel: number, + ): GenerateWeaponResult { const weaponTpl = this.pickWeightedWeaponTplFromPool(equipmentSlot, botTemplateInventory); - return this.generateWeaponByTpl(sessionId, weaponTpl, equipmentSlot, botTemplateInventory, weaponParentId, modChances, botRole, isPmc, botLevel); + return this.generateWeaponByTpl( + sessionId, + weaponTpl, + equipmentSlot, + botTemplateInventory, + weaponParentId, + modChances, + botRole, + isPmc, + botLevel, + ); } /** @@ -99,8 +118,17 @@ export class BotWeaponGenerator * @param isPmc Is weapon being generated for a pmc * @returns GenerateWeaponResult object */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public generateWeaponByTpl(sessionId: string, weaponTpl: string, equipmentSlot: string, botTemplateInventory: Inventory, weaponParentId: string, modChances: ModsChances, botRole: string, isPmc: boolean, botLevel: number): GenerateWeaponResult + public generateWeaponByTpl( + sessionId: string, + weaponTpl: string, + equipmentSlot: string, + botTemplateInventory: Inventory, + weaponParentId: string, + modChances: ModsChances, + botRole: string, + isPmc: boolean, + botLevel: number, + ): GenerateWeaponResult { const modPool = botTemplateInventory.mods; const weaponItemTemplate = this.itemHelper.getItem(weaponTpl)[1]; @@ -123,7 +151,13 @@ export class BotWeaponGenerator const ammoTpl = this.getWeightedCompatibleAmmo(botTemplateInventory.Ammo, weaponItemTemplate); // Create with just base weapon item - let weaponWithModsArray = this.constructWeaponBaseArray(weaponTpl, weaponParentId, equipmentSlot, weaponItemTemplate, botRole); + let weaponWithModsArray = this.constructWeaponBaseArray( + weaponTpl, + weaponParentId, + equipmentSlot, + weaponItemTemplate, + botRole, + ); // Chance to add randomised weapon enhancement if (isPmc && this.randomUtil.getChance100(this.pmcConfig.weaponHasEnhancementChancePercent)) @@ -137,32 +171,52 @@ export class BotWeaponGenerator { const botEquipmentRole = this.botGeneratorHelper.getBotEquipmentRole(botRole); const modLimits = this.botWeaponModLimitService.getWeaponModLimits(botEquipmentRole); - weaponWithModsArray = this.botEquipmentModGenerator.generateModsForWeapon(sessionId, weaponWithModsArray, modPool, weaponWithModsArray[0]._id, weaponItemTemplate, modChances, ammoTpl, botRole, botLevel, modLimits, botEquipmentRole); + weaponWithModsArray = this.botEquipmentModGenerator.generateModsForWeapon( + sessionId, + weaponWithModsArray, + modPool, + weaponWithModsArray[0]._id, + weaponItemTemplate, + modChances, + ammoTpl, + botRole, + botLevel, + modLimits, + botEquipmentRole, + ); } // Use weapon preset from globals.json if weapon isnt valid if (!this.isWeaponValid(weaponWithModsArray, botRole)) { // Weapon is bad, fall back to weapons preset - weaponWithModsArray = this.getPresetWeaponMods(weaponTpl, equipmentSlot, weaponParentId, weaponItemTemplate, botRole); + weaponWithModsArray = this.getPresetWeaponMods( + weaponTpl, + equipmentSlot, + weaponParentId, + weaponItemTemplate, + botRole, + ); } // Fill existing magazines to full and sync ammo type - for (const magazine of weaponWithModsArray.filter(x => x.slotId === this.modMagazineSlotId)) + for (const magazine of weaponWithModsArray.filter((x) => x.slotId === this.modMagazineSlotId)) { this.fillExistingMagazines(weaponWithModsArray, magazine, ammoTpl); } // Add cartridge to gun chamber if weapon has slot for it - if (weaponItemTemplate._props.Chambers?.length === 1 - && weaponItemTemplate._props.Chambers[0]?._name === "patron_in_weapon" - && weaponItemTemplate._props.Chambers[0]?._props?.filters[0]?.Filter?.includes(ammoTpl)) + if ( + weaponItemTemplate._props.Chambers?.length === 1 && + weaponItemTemplate._props.Chambers[0]?._name === "patron_in_weapon" && + weaponItemTemplate._props.Chambers[0]?._props?.filters[0]?.Filter?.includes(ammoTpl) + ) { this.addCartridgeToChamber(weaponWithModsArray, ammoTpl, "patron_in_weapon"); } // Fill UBGL if found - const ubglMod = weaponWithModsArray.find(x => x.slotId === "mod_launcher"); + const ubglMod = weaponWithModsArray.find((x) => x.slotId === "mod_launcher"); let ubglAmmoTpl: string = undefined; if (ubglMod) { @@ -176,7 +230,7 @@ export class BotWeaponGenerator chosenAmmoTpl: ammoTpl, chosenUbglAmmoTpl: ubglAmmoTpl, weaponMods: modPool, - weaponTemplate: weaponItemTemplate + weaponTemplate: weaponItemTemplate, }; } @@ -189,7 +243,7 @@ export class BotWeaponGenerator protected addCartridgeToChamber(weaponWithModsArray: Item[], ammoTpl: string, desiredSlotId: string): void { // Check for slot first - const existingItemWithSlot = weaponWithModsArray.find(x => x.slotId === desiredSlotId); + const existingItemWithSlot = weaponWithModsArray.find((x) => x.slotId === desiredSlotId); if (!existingItemWithSlot) { // Not found, add fresh @@ -198,14 +252,14 @@ export class BotWeaponGenerator _tpl: ammoTpl, parentId: weaponWithModsArray[0]._id, slotId: desiredSlotId, - upd: {StackObjectsCount: 1} + upd: {StackObjectsCount: 1}, }); } else { // Already exists, update values existingItemWithSlot.upd = { - StackObjectsCount: 1 + StackObjectsCount: 1, }; existingItemWithSlot._tpl = ammoTpl; } @@ -216,19 +270,25 @@ export class BotWeaponGenerator * add additional properties based on weapon type * @param weaponTpl Weapon tpl to create item with * @param weaponParentId Weapons parent id - * @param equipmentSlot e.g. primary/secondary/holster + * @param equipmentSlot e.g. primary/secondary/holster * @param weaponItemTemplate db template for weapon * @param botRole for durability values * @returns Base weapon item in array */ - protected constructWeaponBaseArray(weaponTpl: string, weaponParentId: string, equipmentSlot: string, weaponItemTemplate: ITemplateItem, botRole: string): Item[] + protected constructWeaponBaseArray( + weaponTpl: string, + weaponParentId: string, + equipmentSlot: string, + weaponItemTemplate: ITemplateItem, + botRole: string, + ): Item[] { return [{ _id: this.hashUtil.generate(), _tpl: weaponTpl, parentId: weaponParentId, slotId: equipmentSlot, - ...this.botGeneratorHelper.generateExtraPropertiesForItem(weaponItemTemplate, botRole) + ...this.botGeneratorHelper.generateExtraPropertiesForItem(weaponItemTemplate, botRole), }]; } @@ -239,10 +299,18 @@ export class BotWeaponGenerator * @param weaponParentId Value used for the parentid * @returns array of weapon mods */ - protected getPresetWeaponMods(weaponTpl: string, equipmentSlot: string, weaponParentId: string, itemTemplate: ITemplateItem, botRole: string): Item[] + protected getPresetWeaponMods( + weaponTpl: string, + equipmentSlot: string, + weaponParentId: string, + itemTemplate: ITemplateItem, + botRole: string, + ): Item[] { // Invalid weapon generated, fallback to preset - this.logger.warning(this.localisationService.getText("bot-weapon_generated_incorrect_using_default", weaponTpl)); + this.logger.warning( + this.localisationService.getText("bot-weapon_generated_incorrect_using_default", weaponTpl), + ); const weaponMods = []; // TODO: Right now, preset weapons trigger a lot of warnings regarding missing ammo in magazines & such @@ -260,11 +328,12 @@ export class BotWeaponGenerator { const parentItem = preset._items[0]; preset._items[0] = { - ...parentItem, ...{ + ...parentItem, + ...{ parentId: weaponParentId, slotId: equipmentSlot, - ...this.botGeneratorHelper.generateExtraPropertiesForItem(itemTemplate, botRole) - } + ...this.botGeneratorHelper.generateExtraPropertiesForItem(itemTemplate, botRole), + }, }; weaponMods.push(...preset._items); } @@ -304,17 +373,30 @@ export class BotWeaponGenerator const allowedTpls = modSlot._props.filters[0].Filter; const slotName = modSlot._name; - const weaponSlotItem = weaponItemArray.find(x => x.parentId === mod._id && x.slotId === slotName); + const weaponSlotItem = weaponItemArray.find((x) => x.parentId === mod._id && x.slotId === slotName); if (!weaponSlotItem) { - this.logger.warning(this.localisationService.getText("bot-weapons_required_slot_missing_item", {modSlot: modSlot._name, modName: modDbTemplate._name, slotId: mod.slotId, botRole: botRole})); + this.logger.warning( + this.localisationService.getText("bot-weapons_required_slot_missing_item", { + modSlot: modSlot._name, + modName: modDbTemplate._name, + slotId: mod.slotId, + botRole: botRole, + }), + ); return false; } if (!allowedTpls.includes(weaponSlotItem._tpl)) { - this.logger.warning(this.localisationService.getText("bot-weapon_contains_invalid_item", {modSlot: modSlot._name, modName: modDbTemplate._name, weaponTpl: weaponSlotItem._tpl})); + this.logger.warning( + this.localisationService.getText("bot-weapon_contains_invalid_item", { + modSlot: modSlot._name, + modName: modDbTemplate._name, + weaponTpl: weaponSlotItem._tpl, + }), + ); return false; } @@ -332,12 +414,17 @@ export class BotWeaponGenerator * @param inventory Inventory to add magazines to * @param botRole The bot type we're getting generating extra mags for */ - public addExtraMagazinesToInventory(generatedWeaponResult: GenerateWeaponResult, magWeights: GenerationData, inventory: PmcInventory, botRole: string): void + public addExtraMagazinesToInventory( + generatedWeaponResult: GenerateWeaponResult, + magWeights: GenerationData, + inventory: PmcInventory, + botRole: string, + ): void { const weaponAndMods = generatedWeaponResult.weapon; const weaponTemplate = generatedWeaponResult.weaponTemplate; const magazineTpl = this.getMagazineTplFromWeaponTemplate(weaponAndMods, weaponTemplate, botRole); - + const magTemplate = this.itemHelper.getItem(magazineTpl)[1]; if (!magTemplate) { @@ -349,7 +436,9 @@ export class BotWeaponGenerator const ammoTemplate = this.itemHelper.getItem(generatedWeaponResult.chosenAmmoTpl)[1]; if (!ammoTemplate) { - this.logger.error(this.localisationService.getText("bot-unable_to_find_ammo_item", generatedWeaponResult.chosenAmmoTpl)); + this.logger.error( + this.localisationService.getText("bot-unable_to_find_ammo_item", generatedWeaponResult.chosenAmmoTpl), + ); return; } @@ -360,11 +449,24 @@ export class BotWeaponGenerator this.addUbglGrenadesToBotInventory(weaponAndMods, generatedWeaponResult, inventory); } - const inventoryMagGenModel = new InventoryMagGen(magWeights, magTemplate, weaponTemplate, ammoTemplate, inventory); - this.inventoryMagGenComponents.find(v => v.canHandleInventoryMagGen(inventoryMagGenModel)).process(inventoryMagGenModel); + const inventoryMagGenModel = new InventoryMagGen( + magWeights, + magTemplate, + weaponTemplate, + ammoTemplate, + inventory, + ); + this.inventoryMagGenComponents.find((v) => v.canHandleInventoryMagGen(inventoryMagGenModel)).process( + inventoryMagGenModel, + ); // Add x stacks of bullets to SecuredContainer (bots use a magic mag packing skill to reload instantly) - this.addAmmoToSecureContainer(this.botConfig.secureContainerAmmoStackCount, generatedWeaponResult.chosenAmmoTpl, ammoTemplate._props.StackMaxSize, inventory); + this.addAmmoToSecureContainer( + this.botConfig.secureContainerAmmoStackCount, + generatedWeaponResult.chosenAmmoTpl, + ammoTemplate._props.StackMaxSize, + inventory, + ); } /** @@ -373,25 +475,37 @@ export class BotWeaponGenerator * @param generatedWeaponResult result of weapon generation * @param inventory bot inventory to add grenades to */ - protected addUbglGrenadesToBotInventory(weaponMods: Item[], generatedWeaponResult: GenerateWeaponResult, inventory: PmcInventory): void + protected addUbglGrenadesToBotInventory( + weaponMods: Item[], + generatedWeaponResult: GenerateWeaponResult, + inventory: PmcInventory, + ): void { // Find ubgl mod item + get details of it from db - const ubglMod = weaponMods.find(x => x.slotId === "mod_launcher"); + const ubglMod = weaponMods.find((x) => x.slotId === "mod_launcher"); const ubglDbTemplate = this.itemHelper.getItem(ubglMod._tpl)[1]; // Define min/max of how many grenades bot will have - const ubglMinMax:GenerationData = { + const ubglMinMax: GenerationData = { // eslint-disable-next-line @typescript-eslint/naming-convention weights: {"1": 1, "2": 1}, - whitelist: [] + whitelist: [], }; // get ammo template from db const ubglAmmoDbTemplate = this.itemHelper.getItem(generatedWeaponResult.chosenUbglAmmoTpl)[1]; // Add greandes to bot inventory - const ubglAmmoGenModel = new InventoryMagGen(ubglMinMax, ubglDbTemplate, ubglDbTemplate, ubglAmmoDbTemplate, inventory); - this.inventoryMagGenComponents.find(v => v.canHandleInventoryMagGen(ubglAmmoGenModel)).process(ubglAmmoGenModel); + const ubglAmmoGenModel = new InventoryMagGen( + ubglMinMax, + ubglDbTemplate, + ubglDbTemplate, + ubglAmmoDbTemplate, + inventory, + ); + this.inventoryMagGenComponents.find((v) => v.canHandleInventoryMagGen(ubglAmmoGenModel)).process( + ubglAmmoGenModel, + ); // Store extra grenades in secure container this.addAmmoToSecureContainer(5, generatedWeaponResult.chosenUbglAmmoTpl, 20, inventory); @@ -404,17 +518,27 @@ export class BotWeaponGenerator * @param stackSize Size of the ammo stack to add * @param inventory Player inventory */ - protected addAmmoToSecureContainer(stackCount: number, ammoTpl: string, stackSize: number, inventory: PmcInventory): void + protected addAmmoToSecureContainer( + stackCount: number, + ammoTpl: string, + stackSize: number, + inventory: PmcInventory, + ): void { for (let i = 0; i < stackCount; i++) { const id = this.hashUtil.generate(); - this.botWeaponGeneratorHelper.addItemWithChildrenToEquipmentSlot([EquipmentSlots.SECURED_CONTAINER], id, ammoTpl, [{ - _id: id, - _tpl: ammoTpl, - upd: { StackObjectsCount: stackSize } - }], - inventory); + this.botWeaponGeneratorHelper.addItemWithChildrenToEquipmentSlot( + [EquipmentSlots.SECURED_CONTAINER], + id, + ammoTpl, + [{ + _id: id, + _tpl: ammoTpl, + upd: {StackObjectsCount: stackSize}, + }], + inventory, + ); } } @@ -425,9 +549,13 @@ export class BotWeaponGenerator * @param botRole the bot type we are getting the magazine for * @returns magazine tpl string */ - protected getMagazineTplFromWeaponTemplate(weaponMods: Item[], weaponTemplate: ITemplateItem, botRole: string): string + protected getMagazineTplFromWeaponTemplate( + weaponMods: Item[], + weaponTemplate: ITemplateItem, + botRole: string, + ): string { - const magazine = weaponMods.find(m => m.slotId === this.modMagazineSlotId); + const magazine = weaponMods.find((m) => m.slotId === this.modMagazineSlotId); if (!magazine) { // Edge case - magazineless chamber loaded weapons dont have magazines, e.g. mp18 @@ -441,11 +569,15 @@ export class BotWeaponGenerator if (!weaponTemplate._props.isChamberLoad) { // Shouldn't happen - this.logger.warning(this.localisationService.getText("bot-weapon_missing_magazine_or_chamber", weaponTemplate._id)); + this.logger.warning( + this.localisationService.getText("bot-weapon_missing_magazine_or_chamber", weaponTemplate._id), + ); } const defaultMagTplId = this.botWeaponGeneratorHelper.getWeaponsDefaultMagazineTpl(weaponTemplate); - this.logger.debug(`[${botRole}] Unable to find magazine for weapon ${weaponTemplate._id} ${weaponTemplate._name}, using mag template default ${defaultMagTplId}.`); + this.logger.debug( + `[${botRole}] Unable to find magazine for weapon ${weaponTemplate._id} ${weaponTemplate._name}, using mag template default ${defaultMagTplId}.`, + ); return defaultMagTplId; } @@ -459,23 +591,42 @@ export class BotWeaponGenerator * @param weaponTemplate the weapon we want to pick ammo for * @returns an ammo tpl that works with the desired gun */ - protected getWeightedCompatibleAmmo(ammo: Record>, weaponTemplate: ITemplateItem): string + protected getWeightedCompatibleAmmo( + ammo: Record>, + weaponTemplate: ITemplateItem, + ): string { const desiredCaliber = this.getWeaponCaliber(weaponTemplate); const compatibleCartridges = ammo[desiredCaliber]; if (!compatibleCartridges || compatibleCartridges?.length === 0) { - this.logger.debug(this.localisationService.getText("bot-no_caliber_data_for_weapon_falling_back_to_default", {weaponId: weaponTemplate._id, weaponName: weaponTemplate._name, defaultAmmo: weaponTemplate._props.defAmmo})); + this.logger.debug( + this.localisationService.getText("bot-no_caliber_data_for_weapon_falling_back_to_default", { + weaponId: weaponTemplate._id, + weaponName: weaponTemplate._name, + defaultAmmo: weaponTemplate._props.defAmmo, + }), + ); // Immediately returns, as default ammo is guaranteed to be compatible return weaponTemplate._props.defAmmo; } const chosenAmmoTpl = this.weightedRandomHelper.getWeightedValue(compatibleCartridges); - if (weaponTemplate._props.Chambers[0] && !weaponTemplate._props.Chambers[0]._props.filters[0].Filter.includes(chosenAmmoTpl)) + if ( + weaponTemplate._props.Chambers[0] && + !weaponTemplate._props.Chambers[0]._props.filters[0].Filter.includes(chosenAmmoTpl) + ) { - this.logger.debug(this.localisationService.getText("bot-incompatible_ammo_for_weapon_falling_back_to_default", {chosenAmmo: chosenAmmoTpl, weaponId: weaponTemplate._id, weaponName: weaponTemplate._name, defaultAmmo: weaponTemplate._props.defAmmo})); + this.logger.debug( + this.localisationService.getText("bot-incompatible_ammo_for_weapon_falling_back_to_default", { + chosenAmmo: chosenAmmoTpl, + weaponId: weaponTemplate._id, + weaponName: weaponTemplate._name, + defaultAmmo: weaponTemplate._props.defAmmo, + }), + ); // Incompatible ammo found, return default (can happen with .366 and 7.62x39 weapons) return weaponTemplate._props.defAmmo; @@ -503,7 +654,9 @@ export class BotWeaponGenerator if (weaponTemplate._props.LinkedWeapon) { - const ammoInChamber = this.itemHelper.getItem(weaponTemplate._props.Chambers[0]._props.filters[0].Filter[0]); + const ammoInChamber = this.itemHelper.getItem( + weaponTemplate._props.Chambers[0]._props.filters[0].Filter[0], + ); if (!ammoInChamber[0]) { return; @@ -559,9 +712,9 @@ export class BotWeaponGenerator parentId: ubglMod._id, slotId: "patron_in_weapon", upd: { - StackObjectsCount: 1 - } - } + StackObjectsCount: 1, + }, + }, ); } @@ -573,9 +726,16 @@ export class BotWeaponGenerator * @param newStackSize how many cartridges should go into the magazine * @param magazineTemplate magazines db template */ - protected addOrUpdateMagazinesChildWithAmmo(weaponWithMods: Item[], magazine: Item, chosenAmmoTpl: string, magazineTemplate: ITemplateItem): void + protected addOrUpdateMagazinesChildWithAmmo( + weaponWithMods: Item[], + magazine: Item, + chosenAmmoTpl: string, + magazineTemplate: ITemplateItem, + ): void { - const magazineCartridgeChildItem = weaponWithMods.find(m => m.parentId === magazine._id && m.slotId === "cartridges"); + const magazineCartridgeChildItem = weaponWithMods.find((m) => + m.parentId === magazine._id && m.slotId === "cartridges" + ); if (magazineCartridgeChildItem) { // Delete the existing cartridge object and create fresh below @@ -603,7 +763,7 @@ export class BotWeaponGenerator // for CylinderMagazine we exchange the ammo in the "camoras". // This might not be necessary since we already filled the camoras with a random whitelisted and compatible ammo type, // but I'm not sure whether this is also used elsewhere - const camoras = weaponMods.filter(x => x.parentId === magazineId && x.slotId.startsWith("camora")); + const camoras = weaponMods.filter((x) => x.parentId === magazineId && x.slotId.startsWith("camora")); for (const camora of camoras) { camora._tpl = ammoTpl; @@ -613,8 +773,8 @@ export class BotWeaponGenerator } else { - camora.upd = { StackObjectsCount: 1 }; + camora.upd = {StackObjectsCount: 1}; } } } -} \ No newline at end of file +} diff --git a/project/src/generators/FenceBaseAssortGenerator.ts b/project/src/generators/FenceBaseAssortGenerator.ts index 3e0e43a2..905c7fa9 100644 --- a/project/src/generators/FenceBaseAssortGenerator.ts +++ b/project/src/generators/FenceBaseAssortGenerator.ts @@ -27,7 +27,7 @@ export class FenceBaseAssortGenerator @inject("ItemHelper") protected itemHelper: ItemHelper, @inject("ItemFilterService") protected itemFilterService: ItemFilterService, @inject("SeasonalEventService") protected seasonalEventService: SeasonalEventService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.traderConfig = this.configServer.getConfig(ConfigTypes.TRADER); @@ -43,7 +43,7 @@ export class FenceBaseAssortGenerator const baseFenceAssort = this.databaseServer.getTables().traders[Traders.FENCE].assort; const dbItems = Object.values(this.databaseServer.getTables().templates.items); - for (const item of dbItems.filter(x => this.isValidFenceItem(x))) + for (const item of dbItems.filter((x) => this.isValidFenceItem(x))) { // Skip blacklisted items if (this.itemFilterService.isItemBlacklisted(item._id)) @@ -65,8 +65,10 @@ export class FenceBaseAssortGenerator // Skip items on fence ignore list if (this.traderConfig.fence.blacklist.length > 0) { - if (this.traderConfig.fence.blacklist.includes(item._id) - || this.itemHelper.isOfBaseclasses(item._id, this.traderConfig.fence.blacklist)) + if ( + this.traderConfig.fence.blacklist.includes(item._id) || + this.itemHelper.isOfBaseclasses(item._id, this.traderConfig.fence.blacklist) + ) { continue; } @@ -80,8 +82,10 @@ export class FenceBaseAssortGenerator // Create barter scheme object const barterSchemeToAdd: IBarterScheme = { - count: Math.round(this.handbookHelper.getTemplatePrice(item._id) * this.traderConfig.fence.itemPriceMult), - _tpl: Money.ROUBLES + count: Math.round( + this.handbookHelper.getTemplatePrice(item._id) * this.traderConfig.fence.itemPriceMult, + ), + _tpl: Money.ROUBLES, }; // Add barter data to base @@ -95,8 +99,8 @@ export class FenceBaseAssortGenerator slotId: "hideout", upd: { StackObjectsCount: 9999999, - UnlimitedCount: true - } + UnlimitedCount: true, + }, }; // Add item to base @@ -121,4 +125,4 @@ export class FenceBaseAssortGenerator return false; } -} \ No newline at end of file +} diff --git a/project/src/generators/LocationGenerator.ts b/project/src/generators/LocationGenerator.ts index af25d0d3..a43d738f 100644 --- a/project/src/generators/LocationGenerator.ts +++ b/project/src/generators/LocationGenerator.ts @@ -6,9 +6,14 @@ import { PresetHelper } from "@spt-aki/helpers/PresetHelper"; import { RagfairServerHelper } from "@spt-aki/helpers/RagfairServerHelper"; import { IContainerMinMax, IStaticContainer } from "@spt-aki/models/eft/common/ILocation"; import { ILocationBase } from "@spt-aki/models/eft/common/ILocationBase"; -import { ILooseLoot, Spawnpoint, SpawnpointTemplate, SpawnpointsForced } from "@spt-aki/models/eft/common/ILooseLoot"; +import { ILooseLoot, Spawnpoint, SpawnpointsForced, SpawnpointTemplate } from "@spt-aki/models/eft/common/ILooseLoot"; import { Item } from "@spt-aki/models/eft/common/tables/IItem"; -import { IStaticAmmoDetails, IStaticContainerData, IStaticForcedProps, IStaticLootDetails } from "@spt-aki/models/eft/common/tables/ILootBase"; +import { + IStaticAmmoDetails, + IStaticContainerData, + IStaticForcedProps, + IStaticLootDetails, +} from "@spt-aki/models/eft/common/tables/ILootBase"; import { BaseClasses } from "@spt-aki/models/enums/BaseClasses"; import { ConfigTypes } from "@spt-aki/models/enums/ConfigTypes"; import { Money } from "@spt-aki/models/enums/Money"; @@ -25,17 +30,17 @@ import { ProbabilityObject, ProbabilityObjectArray, RandomUtil } from "@spt-aki/ export interface IContainerItem { - items: Item[] - width: number - height: number + items: Item[]; + width: number; + height: number; } export interface IContainerGroupCount { /** Containers this group has + probabilty to spawn */ - containerIdsWithProbability: Record + containerIdsWithProbability: Record; /** How many containers the map should spawn with this group id */ - chosenCount: number + chosenCount: number; } @injectable() @@ -56,7 +61,7 @@ export class LocationGenerator @inject("ContainerHelper") protected containerHelper: ContainerHelper, @inject("PresetHelper") protected presetHelper: PresetHelper, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.locationConfig = this.configServer.getConfig(ConfigTypes.LOCATION); @@ -68,7 +73,10 @@ export class LocationGenerator * @param staticAmmoDist Static ammo distribution - database.loot.staticAmmo * @returns Array of container objects */ - public generateStaticContainers(locationBase: ILocationBase, staticAmmoDist: Record): SpawnpointTemplate[] + public generateStaticContainers( + locationBase: ILocationBase, + staticAmmoDist: Record, + ): SpawnpointTemplate[] { const result: SpawnpointTemplate[] = []; const locationId = locationBase.Id.toLowerCase(); @@ -84,7 +92,9 @@ export class LocationGenerator // Add mounted weapons to output loot result.push(...staticWeaponsOnMap ?? []); - const allStaticContainersOnMap = this.jsonUtil.clone(db.loot.staticContainers[locationBase.Name]?.staticContainers); + const allStaticContainersOnMap = this.jsonUtil.clone( + db.loot.staticContainers[locationBase.Name]?.staticContainers, + ); if (!allStaticContainersOnMap) { this.logger.error(`Unable to find static container data for map: ${locationBase.Name}`); @@ -105,23 +115,40 @@ export class LocationGenerator const staticLootDist = db.loot.staticLoot; const guaranteedContainers = this.getGuaranteedContainers(allStaticContainersOnMap); staticContainerCount += guaranteedContainers.length; - + // Add loot to guaranteed containers and add to result for (const container of guaranteedContainers) { - const containerWithLoot = this.addLootToContainer(container, staticForcedOnMap, staticLootDist, staticAmmoDist, locationId); + const containerWithLoot = this.addLootToContainer( + container, + staticForcedOnMap, + staticLootDist, + staticAmmoDist, + locationId, + ); result.push(containerWithLoot.template); } this.logger.success(`Added ${guaranteedContainers.length} guaranteed containers`); // randomisation is turned off globally or just turned off for this map - if (!this.locationConfig.containerRandomisationSettings.enabled || !this.locationConfig.containerRandomisationSettings.maps[locationId]) + if ( + !this.locationConfig.containerRandomisationSettings.enabled || + !this.locationConfig.containerRandomisationSettings.maps[locationId] + ) { - this.logger.debug(`Container randomisation disabled, Adding ${staticRandomisableContainersOnMap.length} containers to ${locationBase.Name}`); + this.logger.debug( + `Container randomisation disabled, Adding ${staticRandomisableContainersOnMap.length} containers to ${locationBase.Name}`, + ); for (const container of staticRandomisableContainersOnMap) { - const containerWithLoot = this.addLootToContainer(container, staticForcedOnMap, staticLootDist, staticAmmoDist, locationId); + const containerWithLoot = this.addLootToContainer( + container, + staticForcedOnMap, + staticLootDist, + staticAmmoDist, + locationId, + ); result.push(containerWithLoot.template); } @@ -129,7 +156,7 @@ export class LocationGenerator } // Group containers by their groupId - const staticContainerGroupData: IStaticContainer = db.locations[locationId].statics; + const staticContainerGroupData: IStaticContainer = db.locations[locationId].statics; const mapping = this.getGroupIdToContainerMappings(staticContainerGroupData, staticRandomisableContainersOnMap); // For each of the container groups, choose from the pool of containers, hydrate container with loot and add to result array @@ -145,7 +172,9 @@ export class LocationGenerator if (Object.keys(data.containerIdsWithProbability).length === 0) { - this.logger.debug(`Group: ${groupId} has no containers with < 100% spawn chance to choose from, skipping`); + this.logger.debug( + `Group: ${groupId} has no containers with < 100% spawn chance to choose from, skipping`, + ); continue; } @@ -178,48 +207,72 @@ export class LocationGenerator for (const chosenContainerId of chosenContainerIds) { // Look up container object from full list of containers on map - const containerObject = staticRandomisableContainersOnMap.find(x => x.template.Id === chosenContainerId); + const containerObject = staticRandomisableContainersOnMap.find((x) => + x.template.Id === chosenContainerId + ); if (!containerObject) { - this.logger.debug(`Container: ${chosenContainerIds[chosenContainerId]} not found in staticRandomisableContainersOnMap, this is bad`); + this.logger.debug( + `Container: ${ + chosenContainerIds[chosenContainerId] + } not found in staticRandomisableContainersOnMap, this is bad`, + ); continue; } // Add loot to container and push into result object - const containerWithLoot = this.addLootToContainer(containerObject, staticForcedOnMap, staticLootDist, staticAmmoDist, locationId); + const containerWithLoot = this.addLootToContainer( + containerObject, + staticForcedOnMap, + staticLootDist, + staticAmmoDist, + locationId, + ); result.push(containerWithLoot.template); staticContainerCount++; } } - this.logger.success(this.localisationService.getText("location-containers_generated_success", staticContainerCount)); + this.logger.success( + this.localisationService.getText("location-containers_generated_success", staticContainerCount), + ); return result; } /** * Get containers with a non-100% chance to spawn OR are NOT on the container type randomistion blacklist - * @param staticContainers + * @param staticContainers * @returns IStaticContainerData array */ protected getRandomisableContainersOnMap(staticContainers: IStaticContainerData[]): IStaticContainerData[] { return staticContainers - .filter(x => x.probability !== 1 && !x.template.IsAlwaysSpawn && !this.locationConfig.containerRandomisationSettings.containerTypesToNotRandomise.includes(x.template.Items[0]._tpl)); + .filter((x) => + x.probability !== 1 && !x.template.IsAlwaysSpawn && + !this.locationConfig.containerRandomisationSettings.containerTypesToNotRandomise.includes( + x.template.Items[0]._tpl, + ) + ); } /** * Get containers with 100% spawn rate or have a type on the randomistion ignore list - * @param staticContainersOnMap + * @param staticContainersOnMap * @returns IStaticContainerData array */ protected getGuaranteedContainers(staticContainersOnMap: IStaticContainerData[]): IStaticContainerData[] { - return staticContainersOnMap.filter(x => x.probability === 1 || x.template.IsAlwaysSpawn || this.locationConfig.containerRandomisationSettings.containerTypesToNotRandomise.includes(x.template.Items[0]._tpl)); + return staticContainersOnMap.filter((x) => + x.probability === 1 || x.template.IsAlwaysSpawn || + this.locationConfig.containerRandomisationSettings.containerTypesToNotRandomise.includes( + x.template.Items[0]._tpl, + ) + ); } /** - * Choose a number of containers based on their probabilty value to fulfil the desired count in containerData.chosenCount + * Choose a number of containers based on their probability value to fulfil the desired count in containerData.chosenCount * @param groupId Name of the group the containers are being collected for * @param containerData Containers and probability values for a groupId * @returns List of chosen container Ids @@ -231,15 +284,19 @@ export class LocationGenerator const containerIds = Object.keys(containerData.containerIdsWithProbability); if (containerData.chosenCount > containerIds.length) { - this.logger.debug(`Group: ${groupId} wants ${containerData.chosenCount} containers but pool only has ${containerIds.length}, add what's available`); + this.logger.debug( + `Group: ${groupId} wants ${containerData.chosenCount} containers but pool only has ${containerIds.length}, add what's available`, + ); return containerIds; } - // Create probability array with all possible container ids in this group and their relataive probability of spawning + // Create probability array with all possible container ids in this group and their relative probability of spawning const containerDistribution = new ProbabilityObjectArray(this.mathUtil, this.jsonUtil); for (const containerId of containerIds) { - containerDistribution.push(new ProbabilityObject(containerId, containerData.containerIdsWithProbability[containerId])); + containerDistribution.push( + new ProbabilityObject(containerId, containerData.containerIdsWithProbability[containerId]), + ); } chosenContainerIds.push(...containerDistribution.draw(containerData.chosenCount)); @@ -254,7 +311,8 @@ export class LocationGenerator */ protected getGroupIdToContainerMappings( staticContainerGroupData: IStaticContainer | Record, - staticContainersOnMap: IStaticContainerData[]): Record + staticContainersOnMap: IStaticContainerData[], + ): Record { // Create dictionary of all group ids and choose a count of containers the map will spawn of that group const mapping: Record = {}; @@ -266,9 +324,15 @@ export class LocationGenerator mapping[groupId] = { containerIdsWithProbability: {}, chosenCount: this.randomUtil.getInt( - Math.round(groupData.minContainers * this.locationConfig.containerRandomisationSettings.containerGroupMinSizeMultiplier), - Math.round(groupData.maxContainers * this.locationConfig.containerRandomisationSettings.containerGroupMaxSizeMultiplier) - ) + Math.round( + groupData.minContainers * + this.locationConfig.containerRandomisationSettings.containerGroupMinSizeMultiplier, + ), + Math.round( + groupData.maxContainers * + this.locationConfig.containerRandomisationSettings.containerGroupMaxSizeMultiplier, + ), + ), }; } } @@ -290,7 +354,9 @@ export class LocationGenerator if (container.probability === 1) { - this.logger.debug(`Container ${container.template.Id} with group ${groupData.groupId} had 100% chance to spawn was picked as random container, skipping`); + this.logger.debug( + `Container ${container.template.Id} with group ${groupData.groupId} had 100% chance to spawn was picked as random container, skipping`, + ); continue; } mapping[groupData.groupId].containerIdsWithProbability[container.template.Id] = container.probability; @@ -314,7 +380,8 @@ export class LocationGenerator staticForced: IStaticForcedProps[], staticLootDist: Record, staticAmmoDist: Record, - locationName: string): IStaticContainerData + locationName: string, + ): IStaticContainerData { const container = this.jsonUtil.clone(staticContainer); const containerTpl = container.template.Items[0]._tpl; @@ -333,7 +400,7 @@ export class LocationGenerator const containerLootPool = this.getPossibleLootItemsForContainer(containerTpl, staticLootDist); // Some containers need to have items forced into it (quest keys etc) - const tplsForced = staticForced.filter(x => x.containerId === container.template.Id).map(x => x.itemTpl); + const tplsForced = staticForced.filter((x) => x.containerId === container.template.Id).map((x) => x.itemTpl); // Draw random loot // Money spawn more than once in container @@ -341,7 +408,11 @@ export class LocationGenerator const locklist = [Money.ROUBLES, Money.DOLLARS, Money.EUROS]; // Choose items to add to container, factor in weighting + lock money down - const chosenTpls = containerLootPool.draw(itemCountToAdd, this.locationConfig.allowDuplicateItemsInStaticContainers, locklist); + const chosenTpls = containerLootPool.draw( + itemCountToAdd, + this.locationConfig.allowDuplicateItemsInStaticContainers, + locklist, + ); // Add forced loot to chosen item pool const tplsToAddToContainer = tplsForced.concat(chosenTpls); @@ -368,11 +439,18 @@ export class LocationGenerator continue; } - containerMap = this.containerHelper.fillContainerMapWithItem(containerMap, result.x, result.y, width, height, result.rotation); + containerMap = this.containerHelper.fillContainerMapWithItem( + containerMap, + result.x, + result.y, + width, + height, + result.rotation, + ); const rotation = result.rotation ? 1 : 0; items[0].slotId = "main"; - items[0].location = { x: result.x, y: result.y, r: rotation }; + items[0].location = {x: result.x, y: result.y, r: rotation}; // Add loot to container before returning for (const item of items) @@ -409,15 +487,19 @@ export class LocationGenerator * @param locationName Map name (to get per-map multiplier for from config) * @returns item count */ - protected getWeightedCountOfContainerItems(containerTypeId: string, staticLootDist: Record, locationName: string): number + protected getWeightedCountOfContainerItems( + containerTypeId: string, + staticLootDist: Record, + locationName: string, + ): number { - // Create probability array to calcualte the total count of lootable items inside container + // Create probability array to calculate the total count of lootable items inside container const itemCountArray = new ProbabilityObjectArray(this.mathUtil, this.jsonUtil); for (const itemCountDistribution of staticLootDist[containerTypeId].itemcountDistribution) { // Add each count of items into array itemCountArray.push( - new ProbabilityObject(itemCountDistribution.count, itemCountDistribution.relativeProbability) + new ProbabilityObject(itemCountDistribution.count, itemCountDistribution.relativeProbability), ); } @@ -427,11 +509,14 @@ export class LocationGenerator /** * Get all possible loot items that can be placed into a container * Do not add seasonal items if found + current date is inside seasonal event - * @param containerTypeId Contianer to get possible loot for + * @param containerTypeId Container to get possible loot for * @param staticLootDist staticLoot.json - * @returns ProbabilityObjectArray of item tpls + probabilty + * @returns ProbabilityObjectArray of item tpls + probability */ - protected getPossibleLootItemsForContainer(containerTypeId: string, staticLootDist: Record): ProbabilityObjectArray + protected getPossibleLootItemsForContainer( + containerTypeId: string, + staticLootDist: Record, + ): ProbabilityObjectArray { const seasonalEventActive = this.seasonalEventService.seasonalEventEnabled(); const seasonalItemTplBlacklist = this.seasonalEventService.getInactiveSeasonalEventItems(); @@ -446,7 +531,7 @@ export class LocationGenerator } itemDistribution.push( - new ProbabilityObject(icd.tpl, icd.relativeProbability) + new ProbabilityObject(icd.tpl, icd.relativeProbability), ); } @@ -465,12 +550,16 @@ export class LocationGenerator /** * Create array of loose + forced loot using probability system - * @param dynamicLootDist - * @param staticAmmoDist + * @param dynamicLootDist + * @param staticAmmoDist * @param locationName Location to generate loot for * @returns Array of spawn points with loot in them */ - public generateDynamicLoot(dynamicLootDist: ILooseLoot, staticAmmoDist: Record, locationName: string): SpawnpointTemplate[] + public generateDynamicLoot( + dynamicLootDist: ILooseLoot, + staticAmmoDist: Record, + locationName: string, + ): SpawnpointTemplate[] { const loot: SpawnpointTemplate[] = []; @@ -478,14 +567,14 @@ export class LocationGenerator this.addForcedLoot(loot, dynamicLootDist.spawnpointsForced, locationName); const allDynamicSpawnpoints = dynamicLootDist.spawnpoints; - - //Draw from random distribution + + // Draw from random distribution const desiredSpawnpointCount = Math.round( this.getLooseLootMultiplerForLocation(locationName) * - this.randomUtil.randn( - dynamicLootDist.spawnpointCount.mean, - dynamicLootDist.spawnpointCount.std - ) + this.randomUtil.randn( + dynamicLootDist.spawnpointCount.mean, + dynamicLootDist.spawnpointCount.std, + ), ); // Positions not in forced but have 100% chance to spawn @@ -496,7 +585,7 @@ export class LocationGenerator for (const spawnpoint of allDynamicSpawnpoints) { - // Point is blacklsited, skip + // Point is blacklisted, skip if (blacklistedSpawnpoints?.includes(spawnpoint.template.Id)) { this.logger.debug(`Ignoring loose loot location: ${spawnpoint.template.Id}`); @@ -510,7 +599,7 @@ export class LocationGenerator } spawnpointArray.push( - new ProbabilityObject(spawnpoint.template.Id, spawnpoint.probability, spawnpoint) + new ProbabilityObject(spawnpoint.template.Id, spawnpoint.probability, spawnpoint), ); } @@ -525,13 +614,19 @@ export class LocationGenerator } // Filter out duplicate locationIds - chosenSpawnpoints = [...new Map(chosenSpawnpoints.map(x => [x.locationId, x])).values()]; + chosenSpawnpoints = [...new Map(chosenSpawnpoints.map((x) => [x.locationId, x])).values()]; // Do we have enough items in pool to fulfill requirement const tooManySpawnPointsRequested = (desiredSpawnpointCount - chosenSpawnpoints.length) > 0; if (tooManySpawnPointsRequested) { - this.logger.debug(this.localisationService.getText("location-spawn_point_count_requested_vs_found", {requested: desiredSpawnpointCount+guaranteedLoosePoints.length, found: chosenSpawnpoints.length, mapName: locationName})); + this.logger.debug( + this.localisationService.getText("location-spawn_point_count_requested_vs_found", { + requested: desiredSpawnpointCount + guaranteedLoosePoints.length, + found: chosenSpawnpoints.length, + mapName: locationName, + }), + ); } // Iterate over spawnpoints @@ -541,29 +636,37 @@ export class LocationGenerator { if (!spawnPoint.template) { - this.logger.warning(this.localisationService.getText("location-missing_dynamic_template", spawnPoint.locationId)); + this.logger.warning( + this.localisationService.getText("location-missing_dynamic_template", spawnPoint.locationId), + ); continue; } if (!spawnPoint.template.Items || spawnPoint.template.Items.length === 0) { - this.logger.error(this.localisationService.getText("location-spawnpoint_missing_items", spawnPoint.template.Id)); - + this.logger.error( + this.localisationService.getText("location-spawnpoint_missing_items", spawnPoint.template.Id), + ); + continue; } const itemArray = new ProbabilityObjectArray(this.mathUtil, this.jsonUtil); for (const itemDist of spawnPoint.itemDistribution) { - if (!seasonalEventActive && seasonalItemTplBlacklist.includes(spawnPoint.template.Items.find(x => x._id === itemDist.composedKey.key)._tpl)) + if ( + !seasonalEventActive && seasonalItemTplBlacklist.includes( + spawnPoint.template.Items.find((x) => x._id === itemDist.composedKey.key)._tpl, + ) + ) { // Skip seasonal event items if they're not enabled continue; } itemArray.push( - new ProbabilityObject(itemDist.composedKey.key, itemDist.relativeProbability) + new ProbabilityObject(itemDist.composedKey.key, itemDist.relativeProbability), ); } @@ -587,7 +690,11 @@ export class LocationGenerator * @param forcedSpawnPoints forced loot to add * @param name of map currently generating forced loot for */ - protected addForcedLoot(loot: SpawnpointTemplate[], forcedSpawnPoints: SpawnpointsForced[], locationName: string): void + protected addForcedLoot( + loot: SpawnpointTemplate[], + forcedSpawnPoints: SpawnpointsForced[], + locationName: string, + ): void { const lootToForceSingleAmountOnMap = this.locationConfig.forcedLootSingleSpawnById[locationName]; if (lootToForceSingleAmountOnMap) @@ -596,27 +703,32 @@ export class LocationGenerator for (const itemTpl of lootToForceSingleAmountOnMap) { // Get all spawn positions for item tpl in forced loot array - const items = forcedSpawnPoints.filter(x => x.template.Items[0]._tpl === itemTpl); + const items = forcedSpawnPoints.filter((x) => x.template.Items[0]._tpl === itemTpl); if (!items || items.length === 0) { - this.logger.debug(`Unable to adjust loot item ${itemTpl} as it does not exist inside ${locationName} forced loot.`); + this.logger.debug( + `Unable to adjust loot item ${itemTpl} as it does not exist inside ${locationName} forced loot.`, + ); continue; } // Create probability array of all spawn positions for this spawn id - const spawnpointArray = new ProbabilityObjectArray(this.mathUtil, this.jsonUtil); + const spawnpointArray = new ProbabilityObjectArray( + this.mathUtil, + this.jsonUtil, + ); for (const si of items) { // use locationId as template.Id is the same across all items spawnpointArray.push( - new ProbabilityObject(si.locationId, si.probability, si) + new ProbabilityObject(si.locationId, si.probability, si), ); } - + // Choose 1 out of all found spawn positions for spawn id and add to loot array for (const spawnPointLocationId of spawnpointArray.draw(1, false)) { - const itemToAdd = items.find(x => x.locationId === spawnPointLocationId); + const itemToAdd = items.find((x) => x.locationId === spawnPointLocationId); const lootItem = itemToAdd.template; lootItem.Root = this.objectId.generate(); lootItem.Items[0]._id = lootItem.Root; @@ -656,29 +768,36 @@ export class LocationGenerator * @param staticAmmoDist ammo distributions * @returns IContainerItem */ - protected createDynamicLootItem(chosenComposedKey: string, spawnPoint: Spawnpoint, staticAmmoDist: Record): IContainerItem + protected createDynamicLootItem( + chosenComposedKey: string, + spawnPoint: Spawnpoint, + staticAmmoDist: Record, + ): IContainerItem { - const chosenItem = spawnPoint.template.Items.find(x => x._id === chosenComposedKey); + const chosenItem = spawnPoint.template.Items.find((x) => x._id === chosenComposedKey); const chosenTpl = chosenItem._tpl; // Item array to return const itemWithMods: Item[] = []; // Money/Ammo - don't rely on items in spawnPoint.template.Items so we can randomise it ourselves - if (this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.MONEY) || this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.AMMO)) + if ( + this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.MONEY) || + this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.AMMO) + ) { const itemTemplate = this.itemHelper.getItem(chosenTpl)[1]; - const stackCount = itemTemplate._props.StackMaxSize === 1 - ? 1 - : this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); + const stackCount = itemTemplate._props.StackMaxSize === 1 ? + 1 : + this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); itemWithMods.push( { _id: this.objectId.generate(), _tpl: chosenTpl, - upd: { StackObjectsCount: stackCount } - } + upd: {StackObjectsCount: stackCount}, + }, ); } else if (this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.AMMO_BOX)) @@ -687,7 +806,7 @@ export class LocationGenerator const ammoBoxTemplate = this.itemHelper.getItem(chosenTpl)[1]; const ammoBoxItem: Item[] = [{ _id: this.objectId.generate(), - _tpl: chosenTpl + _tpl: chosenTpl, }]; this.itemHelper.addCartridgesToAmmoBox(ammoBoxItem, ammoBoxTemplate); itemWithMods.push(...ammoBoxItem); @@ -698,15 +817,24 @@ export class LocationGenerator const magazineTemplate = this.itemHelper.getItem(chosenTpl)[1]; const magazineItem: Item[] = [{ _id: this.objectId.generate(), - _tpl: chosenTpl + _tpl: chosenTpl, }]; - this.itemHelper.fillMagazineWithRandomCartridge(magazineItem, magazineTemplate, staticAmmoDist, null, this.locationConfig.minFillLooseMagazinePercent / 100); + this.itemHelper.fillMagazineWithRandomCartridge( + magazineItem, + magazineTemplate, + staticAmmoDist, + null, + this.locationConfig.minFillLooseMagazinePercent / 100, + ); itemWithMods.push(...magazineItem); } else { // Get item + children and add into array we return - const itemWithChildren = this.itemHelper.findAndReturnChildrenAsItems(spawnPoint.template.Items, chosenItem._id); + const itemWithChildren = this.itemHelper.findAndReturnChildrenAsItems( + spawnPoint.template.Items, + chosenItem._id, + ); // We need to reparent to ensure ids are unique this.reparentItemAndChildren(itemWithChildren); @@ -720,7 +848,7 @@ export class LocationGenerator return { items: itemWithMods, width: size.width, - height: size.height + height: size.height, }; } @@ -757,14 +885,18 @@ export class LocationGenerator { if (this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.WEAPON)) { - return items.find(v => v._tpl === chosenTpl && v.parentId === undefined); + return items.find((v) => v._tpl === chosenTpl && v.parentId === undefined); } - return items.find(x => x._tpl === chosenTpl); + return items.find((x) => x._tpl === chosenTpl); } // TODO: rewrite, BIG yikes - protected createStaticLootItem(tpl: string, staticAmmoDist: Record, parentId: string = undefined): IContainerItem + protected createStaticLootItem( + tpl: string, + staticAmmoDist: Record, + parentId: string = undefined, + ): IContainerItem { const itemTemplate = this.itemHelper.getItem(tpl)[1]; let width = itemTemplate._props.Width; @@ -772,8 +904,8 @@ export class LocationGenerator let items: Item[] = [ { _id: this.objectId.generate(), - _tpl: tpl - } + _tpl: tpl, + }, ]; // Use passed in parentId as override for new item @@ -782,13 +914,16 @@ export class LocationGenerator items[0].parentId = parentId; } - if (this.itemHelper.isOfBaseclass(tpl, BaseClasses.MONEY) || this.itemHelper.isOfBaseclass(tpl, BaseClasses.AMMO)) + if ( + this.itemHelper.isOfBaseclass(tpl, BaseClasses.MONEY) || + this.itemHelper.isOfBaseclass(tpl, BaseClasses.AMMO) + ) { // Edge case - some ammos e.g. flares or M406 grenades shouldn't be stacked - const stackCount = itemTemplate._props.StackMaxSize === 1 - ? 1 - : this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); - items[0].upd = { StackObjectsCount: stackCount }; + const stackCount = itemTemplate._props.StackMaxSize === 1 ? + 1 : + this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); + items[0].upd = {StackObjectsCount: stackCount}; } // No spawn point, use default template else if (this.itemHelper.isOfBaseclass(tpl, BaseClasses.WEAPON)) @@ -806,21 +941,30 @@ export class LocationGenerator // this item already broke it once without being reproducible tpl = "5839a40f24597726f856b511"; AKS-74UB Default // 5ea03f7400685063ec28bfa8 // ppsh default // 5ba26383d4351e00334c93d9 //mp7_devgru - this.logger.warning(this.localisationService.getText("location-preset_not_found", {tpl: tpl, defaultId: defaultPreset._id, defaultName: defaultPreset._name, parentId: parentId})); + this.logger.warning( + this.localisationService.getText("location-preset_not_found", { + tpl: tpl, + defaultId: defaultPreset._id, + defaultName: defaultPreset._name, + parentId: parentId, + }), + ); throw error; } } else { - // RSP30 (62178be9d0050232da3485d9/624c0b3340357b5f566e8766/6217726288ed9f0845317459) doesnt have any default presets and kills this code below as it has no chidren to reparent + // RSP30 (62178be9d0050232da3485d9/624c0b3340357b5f566e8766/6217726288ed9f0845317459) doesn't have any default presets and kills this code below as it has no children to reparent this.logger.debug(`createItem() No preset found for weapon: ${tpl}`); } const rootItem = items[0]; if (!rootItem) { - this.logger.error(this.localisationService.getText("location-missing_root_item", {tpl: tpl, parentId: parentId})); + this.logger.error( + this.localisationService.getText("location-missing_root_item", {tpl: tpl, parentId: parentId}), + ); throw new Error(this.localisationService.getText("location-critical_error_see_log")); } @@ -830,21 +974,25 @@ export class LocationGenerator if (children?.length > 0) { items = this.ragfairServerHelper.reparentPresets(rootItem, children); - } + } } catch (error) { - this.logger.error(this.localisationService.getText("location-unable_to_reparent_item", {tpl: tpl, parentId: parentId})); + this.logger.error( + this.localisationService.getText("location-unable_to_reparent_item", { + tpl: tpl, + parentId: parentId, + }), + ); throw error; } - // Here we should use generalized BotGenerators functions e.g. fillExistingMagazines in the future since // it can handle revolver ammo (it's not restructured to be used here yet.) // General: Make a WeaponController for Ragfair preset stuff and the generating weapons and ammo stuff from // BotGenerator - const magazine = items.filter(x => x.slotId === "mod_magazine")[0]; + const magazine = items.filter((x) => x.slotId === "mod_magazine")[0]; // some weapon presets come without magazine; only fill the mag if it exists if (magazine) { @@ -853,7 +1001,12 @@ export class LocationGenerator // Create array with just magazine const magazineWithCartridges = [magazine]; - this.itemHelper.fillMagazineWithRandomCartridge(magazineWithCartridges, magTemplate, staticAmmoDist, weaponTemplate._props.ammoCaliber); + this.itemHelper.fillMagazineWithRandomCartridge( + magazineWithCartridges, + magTemplate, + staticAmmoDist, + weaponTemplate._props.ammoCaliber, + ); // Replace existing magazine with above array items.splice(items.indexOf(magazine), 1, ...magazineWithCartridges); @@ -872,7 +1025,13 @@ export class LocationGenerator { // Create array with just magazine const magazineWithCartridges = [items[0]]; - this.itemHelper.fillMagazineWithRandomCartridge(magazineWithCartridges, itemTemplate, staticAmmoDist, null, this.locationConfig.minFillStaticMagazinePercent / 100); + this.itemHelper.fillMagazineWithRandomCartridge( + magazineWithCartridges, + itemTemplate, + staticAmmoDist, + null, + this.locationConfig.minFillStaticMagazinePercent / 100, + ); // Replace existing magazine with above array items.splice(items.indexOf(items[0]), 1, ...magazineWithCartridges); @@ -881,7 +1040,7 @@ export class LocationGenerator return { items: items, width: width, - height: height + height: height, }; } -} \ No newline at end of file +} diff --git a/project/src/generators/LootGenerator.ts b/project/src/generators/LootGenerator.ts index fe0a3b9f..7658f480 100644 --- a/project/src/generators/LootGenerator.ts +++ b/project/src/generators/LootGenerator.ts @@ -20,8 +20,8 @@ import { HashUtil } from "@spt-aki/utils/HashUtil"; import { RandomUtil } from "@spt-aki/utils/RandomUtil"; type ItemLimit = { - current: number, - max: number + current: number; + max: number; }; @injectable() @@ -38,7 +38,7 @@ export class LootGenerator @inject("WeightedRandomHelper") protected weightedRandomHelper: WeightedRandomHelper, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("RagfairLinkedItemService") protected ragfairLinkedItemService: RagfairLinkedItemService, - @inject("ItemFilterService") protected itemFilterService: ItemFilterService + @inject("ItemFilterService") protected itemFilterService: ItemFilterService, ) {} @@ -54,7 +54,10 @@ export class LootGenerator const itemTypeCounts = this.initItemLimitCounter(options.itemLimits); const tables = this.databaseServer.getTables(); - const itemBlacklist = new Set([...this.itemFilterService.getBlacklistedItems(), ...options.itemBlacklist]); + const itemBlacklist = new Set([ + ...this.itemFilterService.getBlacklistedItems(), + ...options.itemBlacklist, + ]); if (!options.allowBossItems) { for (const bossItem of this.itemFilterService.getBossItems()) @@ -64,12 +67,17 @@ export class LootGenerator } // Handle sealed weapon containers - const desiredWeaponCrateCount = this.randomUtil.getInt(options.weaponCrateCount.min, options.weaponCrateCount.max); + const desiredWeaponCrateCount = this.randomUtil.getInt( + options.weaponCrateCount.min, + options.weaponCrateCount.max, + ); if (desiredWeaponCrateCount > 0) { // Get list of all sealed containers from db - const sealedWeaponContainerPool = Object.values(tables.templates.items).filter(x => x._name.includes("event_container_airdrop")); - + const sealedWeaponContainerPool = Object.values(tables.templates.items).filter((x) => + x._name.includes("event_container_airdrop") + ); + for (let index = 0; index < desiredWeaponCrateCount; index++) { // Choose one at random + add to results array @@ -78,16 +86,18 @@ export class LootGenerator id: this.hashUtil.generate(), tpl: chosenSealedContainer._id, isPreset: false, - stackCount: 1 + stackCount: 1, }); } } // Get items from items.json that have a type of item + not in global blacklist + basetype is in whitelist - const items = Object.entries(tables.templates.items).filter(x => !itemBlacklist.has(x[1]._id) - && x[1]._type.toLowerCase() === "item" - && !x[1]._props.QuestItem - && options.itemTypeWhitelist.includes(x[1]._parent)); + const items = Object.entries(tables.templates.items).filter((x) => + !itemBlacklist.has(x[1]._id) && + x[1]._type.toLowerCase() === "item" && + !x[1]._props.QuestItem && + options.itemTypeWhitelist.includes(x[1]._parent) + ); const randomisedItemCount = this.randomUtil.getInt(options.itemCount.min, options.itemCount.max); for (let index = 0; index < randomisedItemCount; index++) @@ -95,10 +105,12 @@ export class LootGenerator if (!this.findAndAddRandomItemToLoot(items, itemTypeCounts, options, result)) { index--; - } + } } - const globalDefaultPresets = Object.entries(tables.globals.ItemPresets).filter(x => x[1]._encyclopedia !== undefined); + const globalDefaultPresets = Object.entries(tables.globals.ItemPresets).filter((x) => + x[1]._encyclopedia !== undefined + ); const randomisedPresetCount = this.randomUtil.getInt(options.presetCount.min, options.presetCount.max); const itemBlacklistArray = Array.from(itemBlacklist); for (let index = 0; index < randomisedPresetCount; index++) @@ -124,7 +136,7 @@ export class LootGenerator { itemTypeCounts[itemTypeId] = { current: 0, - max: limits[itemTypeId] + max: limits[itemTypeId], }; } @@ -141,9 +153,10 @@ export class LootGenerator */ protected findAndAddRandomItemToLoot( items: [string, ITemplateItem][], - itemTypeCounts: Record, + itemTypeCounts: Record, options: LootRequest, - result: LootItem[]): boolean + result: LootItem[], + ): boolean { const randomItem = this.randomUtil.getArrayValue(items)[1]; @@ -157,16 +170,18 @@ export class LootGenerator id: this.hashUtil.generate(), tpl: randomItem._id, isPreset: false, - stackCount: 1 + stackCount: 1, }; // Check if armor has level in allowed whitelist - if (randomItem._parent === BaseClasses.ARMOR - || randomItem._parent === BaseClasses.VEST) + if ( + randomItem._parent === BaseClasses.ARMOR || + randomItem._parent === BaseClasses.VEST + ) { if (!options.armorLevelWhitelist.includes(Number(randomItem._props.armorClass))) { - return false; + return false; } } @@ -175,7 +190,7 @@ export class LootGenerator { newLootItem.stackCount = this.getRandomisedStackCount(randomItem, options); } - + newLootItem.tpl = randomItem._id; result.push(newLootItem); @@ -219,9 +234,10 @@ export class LootGenerator */ protected findAndAddRandomPresetToLoot( globalDefaultPresets: [string, IPreset][], - itemTypeCounts: Record, + itemTypeCounts: Record, itemBlacklist: string[], - result: LootItem[]): boolean + result: LootItem[], + ): boolean { // Choose random preset and get details from item.json using encyclopedia value (encyclopedia === tplId) const randomPreset = this.randomUtil.getArrayValue(globalDefaultPresets)[1]; @@ -264,9 +280,9 @@ export class LootGenerator const newLootItem: LootItem = { tpl: randomPreset._items[0]._tpl, isPreset: true, - stackCount: 1 + stackCount: 1, }; - + result.push(newLootItem); if (itemLimitCount) @@ -274,7 +290,7 @@ export class LootGenerator // increment item count as its in limit array itemLimitCount.current++; } - + // item added okay return true; } @@ -289,19 +305,23 @@ export class LootGenerator const itemsToReturn: AddItem[] = []; // choose a weapon to give to the player (weighted) - const chosenWeaponTpl = this.weightedRandomHelper.getWeightedValue(containerSettings.weaponRewardWeight); + const chosenWeaponTpl = this.weightedRandomHelper.getWeightedValue( + containerSettings.weaponRewardWeight, + ); const weaponDetailsDb = this.itemHelper.getItem(chosenWeaponTpl); if (!weaponDetailsDb[0]) { - this.logger.error(this.localisationService.getText("loot-non_item_picked_as_sealed_weapon_crate_reward", chosenWeaponTpl)); + this.logger.error( + this.localisationService.getText("loot-non_item_picked_as_sealed_weapon_crate_reward", chosenWeaponTpl), + ); return itemsToReturn; } - + // Get weapon preset - default or choose a random one from all possible - let chosenWeaponPreset = containerSettings.defaultPresetsOnly - ? this.presetHelper.getDefaultPreset(chosenWeaponTpl) - : this.randomUtil.getArrayValue(this.presetHelper.getPresets(chosenWeaponTpl)); + let chosenWeaponPreset = containerSettings.defaultPresetsOnly ? + this.presetHelper.getDefaultPreset(chosenWeaponTpl) : + this.randomUtil.getArrayValue(this.presetHelper.getPresets(chosenWeaponTpl)); if (!chosenWeaponPreset) { @@ -314,12 +334,14 @@ export class LootGenerator count: 1, // eslint-disable-next-line @typescript-eslint/naming-convention item_id: chosenWeaponPreset._id, - isPreset: true + isPreset: true, }); // Get items related to chosen weapon const linkedItemsToWeapon = this.ragfairLinkedItemService.getLinkedDbItems(chosenWeaponTpl); - itemsToReturn.push(...this.getSealedContainerWeaponModRewards(containerSettings, linkedItemsToWeapon, chosenWeaponPreset)); + itemsToReturn.push( + ...this.getSealedContainerWeaponModRewards(containerSettings, linkedItemsToWeapon, chosenWeaponPreset), + ); // Handle non-weapon mod reward types itemsToReturn.push(...this.getSealedContainerNonWeaponModRewards(containerSettings, weaponDetailsDb[1])); @@ -333,7 +355,10 @@ export class LootGenerator * @param weaponDetailsDb Details for the weapon to reward player * @returns AddItem array */ - protected getSealedContainerNonWeaponModRewards(containerSettings: ISealedAirdropContainerSettings, weaponDetailsDb: ITemplateItem): AddItem[] + protected getSealedContainerNonWeaponModRewards( + containerSettings: ISealedAirdropContainerSettings, + weaponDetailsDb: ITemplateItem, + ): AddItem[] { const rewards: AddItem[] = []; @@ -351,15 +376,15 @@ export class LootGenerator if (rewardTypeId === BaseClasses.AMMO_BOX) { // Get ammoboxes from db - const ammoBoxesDetails = containerSettings.ammoBoxWhitelist.map(x => + const ammoBoxesDetails = containerSettings.ammoBoxWhitelist.map((x) => { const itemDetails = this.itemHelper.getItem(x); return itemDetails[1]; }); - + // Need to find boxes that matches weapons caliber const weaponCaliber = weaponDetailsDb._props.ammoCaliber; - const ammoBoxesMatchingCaliber = ammoBoxesDetails.filter(x => x._props.ammoCaliber === weaponCaliber); + const ammoBoxesMatchingCaliber = ammoBoxesDetails.filter((x) => x._props.ammoCaliber === weaponCaliber); if (ammoBoxesMatchingCaliber.length === 0) { this.logger.debug(`No ammo box with caliber ${weaponCaliber} found, skipping`); @@ -373,7 +398,7 @@ export class LootGenerator count: rewardCount, // eslint-disable-next-line @typescript-eslint/naming-convention item_id: chosenAmmoBox._id, - isPreset: false + isPreset: false, }); continue; @@ -381,11 +406,13 @@ export class LootGenerator // Get all items of the desired type + not quest items + not globally blacklisted const rewardItemPool = Object.values(this.databaseServer.getTables().templates.items) - .filter(x => x._parent === rewardTypeId - && x._type.toLowerCase() === "item" - && !this.itemFilterService.isItemBlacklisted(x._id) - && (!containerSettings.allowBossItems && !this.itemFilterService.isBossItem(x._id)) - && !x._props.QuestItem); + .filter((x) => + x._parent === rewardTypeId && + x._type.toLowerCase() === "item" && + !this.itemFilterService.isItemBlacklisted(x._id) && + (!containerSettings.allowBossItems && !this.itemFilterService.isBossItem(x._id)) && + !x._props.QuestItem + ); if (rewardItemPool.length === 0) { @@ -398,7 +425,7 @@ export class LootGenerator { // choose a random item from pool const chosenRewardItem = this.randomUtil.getArrayValue(rewardItemPool); - this.addOrIncrementItemToArray(chosenRewardItem._id, rewards); + this.addOrIncrementItemToArray(chosenRewardItem._id, rewards); } } @@ -412,7 +439,11 @@ export class LootGenerator * @param chosenWeaponPreset The weapon preset given to player as reward * @returns AddItem array */ - protected getSealedContainerWeaponModRewards(containerSettings: ISealedAirdropContainerSettings, linkedItemsToWeapon: ITemplateItem[], chosenWeaponPreset: IPreset): AddItem[] + protected getSealedContainerWeaponModRewards( + containerSettings: ISealedAirdropContainerSettings, + linkedItemsToWeapon: ITemplateItem[], + chosenWeaponPreset: IPreset, + ): AddItem[] { const modRewards: AddItem[] = []; for (const rewardTypeId in containerSettings.weaponModRewardLimits) @@ -426,16 +457,20 @@ export class LootGenerator continue; } - // Get items that fulfil reward type critera from items that fit on gun - const relatedItems = linkedItemsToWeapon.filter(x => x._parent === rewardTypeId && !this.itemFilterService.isItemBlacklisted(x._id)); + // Get items that fulfil reward type criteria from items that fit on gun + const relatedItems = linkedItemsToWeapon.filter((x) => + x._parent === rewardTypeId && !this.itemFilterService.isItemBlacklisted(x._id) + ); if (!relatedItems || relatedItems.length === 0) { - this.logger.debug(`No items found to fulfil reward type ${rewardTypeId} for weapon: ${chosenWeaponPreset._name}, skipping type`); + this.logger.debug( + `No items found to fulfil reward type ${rewardTypeId} for weapon: ${chosenWeaponPreset._name}, skipping type`, + ); continue; } // Find a random item of the desired type and add as reward - for (let index = 0; index < rewardCount; index++) + for (let index = 0; index < rewardCount; index++) { const chosenItem = this.randomUtil.drawRandomFromList(relatedItems); this.addOrIncrementItemToArray(chosenItem[0]._id, modRewards); @@ -447,7 +482,7 @@ export class LootGenerator /** * Handle event-related loot containers - currently just the halloween jack-o-lanterns that give food rewards - * @param rewardContainerDetails + * @param rewardContainerDetails * @returns AddItem array */ public getRandomLootContainerLoot(rewardContainerDetails: RewardDetails): AddItem[] @@ -458,7 +493,9 @@ export class LootGenerator for (let index = 0; index < rewardContainerDetails.rewardCount; index++) { // Pick random reward from pool, add to request object - const chosenRewardItemTpl = this.weightedRandomHelper.getWeightedValue(rewardContainerDetails.rewardTplPool); + const chosenRewardItemTpl = this.weightedRandomHelper.getWeightedValue( + rewardContainerDetails.rewardTplPool, + ); this.addOrIncrementItemToArray(chosenRewardItemTpl, itemsToReturn); } @@ -473,7 +510,7 @@ export class LootGenerator */ protected addOrIncrementItemToArray(itemTplToAdd: string, resultsArray: AddItem[]): void { - const existingItemIndex = resultsArray.findIndex(x => x.item_id === itemTplToAdd); + const existingItemIndex = resultsArray.findIndex((x) => x.item_id === itemTplToAdd); if (existingItemIndex > -1) { // Exists in array already, increment count @@ -485,4 +522,4 @@ export class LootGenerator resultsArray.push({item_id: itemTplToAdd, count: 1, isPreset: false}); } } -} \ No newline at end of file +} diff --git a/project/src/generators/PMCLootGenerator.ts b/project/src/generators/PMCLootGenerator.ts index 2e146d44..2b6c11a8 100644 --- a/project/src/generators/PMCLootGenerator.ts +++ b/project/src/generators/PMCLootGenerator.ts @@ -10,11 +10,10 @@ import { ItemFilterService } from "@spt-aki/services/ItemFilterService"; import { SeasonalEventService } from "@spt-aki/services/SeasonalEventService"; /** - * Handle the generation of dynamic PMC loot in pockets and backpacks + * Handle the generation of dynamic PMC loot in pockets and backpacks * and the removal of blacklisted items */ @injectable() - export class PMCLootGenerator { protected pocketLootPool: string[] = []; @@ -27,7 +26,7 @@ export class PMCLootGenerator @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("ConfigServer") protected configServer: ConfigServer, @inject("ItemFilterService") protected itemFilterService: ItemFilterService, - @inject("SeasonalEventService") protected seasonalEventService: SeasonalEventService + @inject("SeasonalEventService") protected seasonalEventService: SeasonalEventService, ) { this.pmcConfig = this.configServer.getConfig(ConfigTypes.PMC); @@ -47,7 +46,7 @@ export class PMCLootGenerator const allowedItemTypes = this.pmcConfig.pocketLoot.whitelist; const pmcItemBlacklist = this.pmcConfig.pocketLoot.blacklist; const itemBlacklist = this.itemFilterService.getBlacklistedItems(); - + // Blacklist seasonal items if not inside seasonal event // Blacklist seasonal items if not inside seasonal event if (!this.seasonalEventService.seasonalEventEnabled()) @@ -56,14 +55,16 @@ export class PMCLootGenerator itemBlacklist.push(...this.seasonalEventService.getInactiveSeasonalEventItems()); } - const itemsToAdd = Object.values(items).filter(item => allowedItemTypes.includes(item._parent) - && this.itemHelper.isValidItem(item._id) - && !pmcItemBlacklist.includes(item._id) - && !itemBlacklist.includes(item._id) - && item._props.Width === 1 - && item._props.Height === 1); + const itemsToAdd = Object.values(items).filter((item) => + allowedItemTypes.includes(item._parent) && + this.itemHelper.isValidItem(item._id) && + !pmcItemBlacklist.includes(item._id) && + !itemBlacklist.includes(item._id) && + item._props.Width === 1 && + item._props.Height === 1 + ); - this.pocketLootPool = itemsToAdd.map(x => x._id); + this.pocketLootPool = itemsToAdd.map((x) => x._id); } return this.pocketLootPool; @@ -83,7 +84,7 @@ export class PMCLootGenerator const allowedItemTypes = this.pmcConfig.vestLoot.whitelist; const pmcItemBlacklist = this.pmcConfig.vestLoot.blacklist; const itemBlacklist = this.itemFilterService.getBlacklistedItems(); - + // Blacklist seasonal items if not inside seasonal event // Blacklist seasonal items if not inside seasonal event if (!this.seasonalEventService.seasonalEventEnabled()) @@ -92,13 +93,15 @@ export class PMCLootGenerator itemBlacklist.push(...this.seasonalEventService.getInactiveSeasonalEventItems()); } - const itemsToAdd = Object.values(items).filter(item => allowedItemTypes.includes(item._parent) - && this.itemHelper.isValidItem(item._id) - && !pmcItemBlacklist.includes(item._id) - && !itemBlacklist.includes(item._id) - && this.itemFitsInto2By2Slot(item)); + const itemsToAdd = Object.values(items).filter((item) => + allowedItemTypes.includes(item._parent) && + this.itemHelper.isValidItem(item._id) && + !pmcItemBlacklist.includes(item._id) && + !itemBlacklist.includes(item._id) && + this.itemFitsInto2By2Slot(item) + ); - this.vestLootPool = itemsToAdd.map(x => x._id); + this.vestLootPool = itemsToAdd.map((x) => x._id); } return this.vestLootPool; @@ -129,7 +132,7 @@ export class PMCLootGenerator const allowedItemTypes = this.pmcConfig.backpackLoot.whitelist; const pmcItemBlacklist = this.pmcConfig.backpackLoot.blacklist; const itemBlacklist = this.itemFilterService.getBlacklistedItems(); - + // blacklist event items if not inside seasonal event if (!this.seasonalEventService.seasonalEventEnabled()) { @@ -137,14 +140,16 @@ export class PMCLootGenerator itemBlacklist.push(...this.seasonalEventService.getInactiveSeasonalEventItems()); } - const itemsToAdd = Object.values(items).filter(item => allowedItemTypes.includes(item._parent) - && this.itemHelper.isValidItem(item._id) - && !pmcItemBlacklist.includes(item._id) - && !itemBlacklist.includes(item._id)); + const itemsToAdd = Object.values(items).filter((item) => + allowedItemTypes.includes(item._parent) && + this.itemHelper.isValidItem(item._id) && + !pmcItemBlacklist.includes(item._id) && + !itemBlacklist.includes(item._id) + ); - this.backpackLootPool = itemsToAdd.map(x => x._id); + this.backpackLootPool = itemsToAdd.map((x) => x._id); } return this.backpackLootPool; } -} \ No newline at end of file +} diff --git a/project/src/generators/PlayerScavGenerator.ts b/project/src/generators/PlayerScavGenerator.ts index 3e870523..69f1b849 100644 --- a/project/src/generators/PlayerScavGenerator.ts +++ b/project/src/generators/PlayerScavGenerator.ts @@ -47,7 +47,7 @@ export class PlayerScavGenerator @inject("BotLootCacheService") protected botLootCacheService: BotLootCacheService, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("BotGenerator") protected botGenerator: BotGenerator, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.playerScavConfig = this.configServer.getConfig(ConfigTypes.PLAYERSCAV); @@ -66,9 +66,9 @@ export class PlayerScavGenerator const existingScavData = this.jsonUtil.clone(profile.characters.scav); // scav profile can be empty on first profile creation - const scavKarmaLevel = ((Object.keys(existingScavData).length === 0)) - ? 0 - : this.getScavKarmaLevel(pmcData); + const scavKarmaLevel = (Object.keys(existingScavData).length === 0) ? + 0 : + this.getScavKarmaLevel(pmcData); // use karma level to get correct karmaSettings const playerScavKarmaSettings = this.playerScavConfig.karmaLevel[scavKarmaLevel]; @@ -83,7 +83,12 @@ export class PlayerScavGenerator const baseBotNode: IBotType = this.constructBotBaseTemplate(playerScavKarmaSettings.botTypeForLoot); this.adjustBotTemplateWithKarmaSpecificSettings(playerScavKarmaSettings, baseBotNode); - let scavData = this.botGenerator.generatePlayerScav(sessionID, playerScavKarmaSettings.botTypeForLoot.toLowerCase(), "easy", baseBotNode); + let scavData = this.botGenerator.generatePlayerScav( + sessionID, + playerScavKarmaSettings.botTypeForLoot.toLowerCase(), + "easy", + baseBotNode, + ); // Remove cached bot data after scav was generated this.botLootCacheService.clearCache(); @@ -113,7 +118,6 @@ export class PlayerScavGenerator scavData.Notes = existingScavData.Notes ?? {Notes: []}; scavData.WishList = existingScavData.WishList ?? []; - // Add an extra labs card to pscav backpack based on config chance if (this.randomUtil.getChance100(playerScavKarmaSettings.labsAccessCardChancePercent)) { @@ -121,9 +125,15 @@ export class PlayerScavGenerator const itemsToAdd: Item[] = [{ _id: this.hashUtil.generate(), _tpl: labsCard._id, - ...this.botGeneratorHelper.generateExtraPropertiesForItem(labsCard) + ...this.botGeneratorHelper.generateExtraPropertiesForItem(labsCard), }]; - this.botWeaponGeneratorHelper.addItemWithChildrenToEquipmentSlot(["TacticalVest", "Pockets", "Backpack"], itemsToAdd[0]._id, labsCard._id, itemsToAdd, scavData.Inventory); + this.botWeaponGeneratorHelper.addItemWithChildrenToEquipmentSlot( + ["TacticalVest", "Pockets", "Backpack"], + itemsToAdd[0]._id, + labsCard._id, + itemsToAdd, + scavData.Inventory, + ); } // Remove secure container @@ -251,7 +261,7 @@ export class PlayerScavGenerator return { Common: [], Mastering: [], - Points: 0 + Points: 0, }; } @@ -292,7 +302,7 @@ export class PlayerScavGenerator * take into account scav cooldown bonus * @param scavData scav profile * @param pmcData pmc profile - * @returns + * @returns */ protected setScavCooldownTimer(scavData: IPmcData, pmcData: IPmcData): IPmcData { @@ -314,7 +324,7 @@ export class PlayerScavGenerator const fenceInfo = this.fenceService.getFenceInfo(pmcData); modifier *= fenceInfo.SavageCooldownModifier; scavLockDuration *= modifier; - + const fullProfile = this.profileHelper.getFullProfile(pmcData?.sessionId); if (fullProfile?.info?.edition?.toLowerCase?.().startsWith?.(AccountTypes.SPT_DEVELOPER)) { @@ -323,7 +333,7 @@ export class PlayerScavGenerator } scavData.Info.SavageLockTime = (Date.now() / 1000) + scavLockDuration; - + return scavData; } -} \ No newline at end of file +} diff --git a/project/src/generators/RagfairAssortGenerator.ts b/project/src/generators/RagfairAssortGenerator.ts index 2da09e56..65e301f0 100644 --- a/project/src/generators/RagfairAssortGenerator.ts +++ b/project/src/generators/RagfairAssortGenerator.ts @@ -24,7 +24,7 @@ export class RagfairAssortGenerator @inject("ItemHelper") protected itemHelper: ItemHelper, @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("SeasonalEventService") protected seasonalEventService: SeasonalEventService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); @@ -62,9 +62,9 @@ export class RagfairAssortGenerator const results: Item[] = []; const items = this.itemHelper.getItems(); - const weaponPresets = (this.ragfairConfig.dynamic.showDefaultPresetsOnly) - ? this.getDefaultPresets() - : this.getPresets(); + const weaponPresets = (this.ragfairConfig.dynamic.showDefaultPresetsOnly) ? + this.getDefaultPresets() : + this.getPresets(); const ragfairItemInvalidBaseTypes: string[] = [ BaseClasses.LOOT_CONTAINER, // safe, barrel cache etc @@ -72,7 +72,7 @@ export class RagfairAssortGenerator BaseClasses.SORTING_TABLE, BaseClasses.INVENTORY, BaseClasses.STATIONARY_CONTAINER, - BaseClasses.POCKETS + BaseClasses.POCKETS, ]; const seasonalEventActive = this.seasonalEventService.seasonalEventEnabled(); @@ -84,7 +84,10 @@ export class RagfairAssortGenerator continue; } - if (this.ragfairConfig.dynamic.removeSeasonalItemsWhenNotInEvent && !seasonalEventActive && seasonalItemTplBlacklist.includes(item._id)) + if ( + this.ragfairConfig.dynamic.removeSeasonalItemsWhenNotInEvent && !seasonalEventActive && + seasonalItemTplBlacklist.includes(item._id) + ) { continue; } @@ -99,7 +102,7 @@ export class RagfairAssortGenerator return results; } - + /** * Get presets from globals.json * @returns Preset object array @@ -116,9 +119,9 @@ export class RagfairAssortGenerator */ protected getDefaultPresets(): IPreset[] { - return this.getPresets().filter(x => x._encyclopedia); + return this.getPresets().filter((x) => x._encyclopedia); } - + /** * Create a base assort item and return it with populated values + 999999 stack count + unlimited count = true * @param tplId tplid to add to item @@ -134,8 +137,8 @@ export class RagfairAssortGenerator slotId: "hideout", upd: { StackObjectsCount: 99999999, - UnlimitedCount: true - } + UnlimitedCount: true, + }, }; } -} \ No newline at end of file +} diff --git a/project/src/generators/RagfairOfferGenerator.ts b/project/src/generators/RagfairOfferGenerator.ts index 612b71c2..5f08253e 100644 --- a/project/src/generators/RagfairOfferGenerator.ts +++ b/project/src/generators/RagfairOfferGenerator.ts @@ -33,7 +33,7 @@ import { TimeUtil } from "@spt-aki/utils/TimeUtil"; export class RagfairOfferGenerator { protected ragfairConfig: IRagfairConfig; - protected allowedFleaPriceItemsForBarter: { tpl: string; price: number; }[]; + protected allowedFleaPriceItemsForBarter: {tpl: string; price: number;}[]; constructor( @inject("WinstonLogger") protected logger: ILogger, @@ -54,7 +54,7 @@ export class RagfairOfferGenerator @inject("RagfairCategoriesService") protected ragfairCategoriesService: RagfairCategoriesService, @inject("FenceService") protected fenceService: FenceService, @inject("ItemHelper") protected itemHelper: ItemHelper, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); @@ -70,7 +70,14 @@ export class RagfairOfferGenerator * @param sellInOnePiece Flags sellInOnePiece to be true * @returns IRagfairOffer */ - public createFleaOffer(userID: string, time: number, items: Item[], barterScheme: IBarterScheme[], loyalLevel: number, sellInOnePiece = false): IRagfairOffer + public createFleaOffer( + userID: string, + time: number, + items: Item[], + barterScheme: IBarterScheme[], + loyalLevel: number, + sellInOnePiece = false, + ): IRagfairOffer { const offer = this.createOffer(userID, time, items, barterScheme, loyalLevel, sellInOnePiece); this.ragfairOfferService.addOffer(offer); @@ -88,7 +95,14 @@ export class RagfairOfferGenerator * @param sellInOnePiece Set StackObjectsCount to 1 * @returns IRagfairOffer */ - protected createOffer(userID: string, time: number, items: Item[], barterScheme: IBarterScheme[], loyalLevel: number, sellInOnePiece = false): IRagfairOffer + protected createOffer( + userID: string, + time: number, + items: Item[], + barterScheme: IBarterScheme[], + loyalLevel: number, + sellInOnePiece = false, + ): IRagfairOffer { const isTrader = this.ragfairServerHelper.isTrader(userID); @@ -98,13 +112,13 @@ export class RagfairOfferGenerator const requirement: OfferRequirement = { _tpl: barter._tpl, count: +barter.count.toFixed(2), - onlyFunctional: barter.onlyFunctional ?? false + onlyFunctional: barter.onlyFunctional ?? false, }; offerRequirements.push(requirement); } - const itemCount = items.filter(x => x.slotId === "hideout").length; + const itemCount = items.filter((x) => x.slotId === "hideout").length; const roublePrice = Math.round(this.convertOfferRequirementsIntoRoubles(offerRequirements)); const offer: IRagfairOffer = { @@ -112,13 +126,13 @@ export class RagfairOfferGenerator intId: 0, user: { id: this.getTraderId(userID), - memberType: (userID === "ragfair") - ? MemberCategory.DEFAULT - : this.ragfairServerHelper.getMemberType(userID), + memberType: (userID === "ragfair") ? + MemberCategory.DEFAULT : + this.ragfairServerHelper.getMemberType(userID), nickname: this.ragfairServerHelper.getNickname(userID), rating: this.getRating(userID), isRatingGrowing: this.getRatingGrowing(userID), - avatar: this.getAvatarUrl(isTrader, userID) + avatar: this.getAvatarUrl(isTrader, userID), }, root: items[0]._id, items: this.jsonUtil.clone(items), @@ -134,7 +148,7 @@ export class RagfairOfferGenerator locked: false, unlimitedCount: false, notAvailable: false, - CurrentItemCount: itemCount + CurrentItemCount: itemCount, }; return offer; @@ -150,9 +164,9 @@ export class RagfairOfferGenerator let roublePrice = 0; for (const requirement of offerRequirements) { - roublePrice += this.paymentHelper.isMoneyTpl(requirement._tpl) - ? Math.round(this.calculateRoublePrice(requirement.count, requirement._tpl)) - : this.ragfairPriceService.getFleaPriceForItem(requirement._tpl) * requirement.count; // get flea price for barter offer items + roublePrice += this.paymentHelper.isMoneyTpl(requirement._tpl) ? + Math.round(this.calculateRoublePrice(requirement.count, requirement._tpl)) : + this.ragfairPriceService.getFleaPriceForItem(requirement._tpl) * requirement.count; // get flea price for barter offer items } return roublePrice; @@ -249,7 +263,7 @@ export class RagfairOfferGenerator return true; } - // generated offer + // generated offer // 50/50 growing/falling return this.randomUtil.getBool(); } @@ -275,7 +289,13 @@ export class RagfairOfferGenerator } // Generated fake-player offer - return Math.round(time + this.randomUtil.getInt(this.ragfairConfig.dynamic.endTimeSeconds.min, this.ragfairConfig.dynamic.endTimeSeconds.max)); + return Math.round( + time + + this.randomUtil.getInt( + this.ragfairConfig.dynamic.endTimeSeconds.min, + this.ragfairConfig.dynamic.endTimeSeconds.max, + ), + ); } /** @@ -287,28 +307,34 @@ export class RagfairOfferGenerator const config = this.ragfairConfig.dynamic; // get assort items from param if they exist, otherwise grab freshly generated assorts - const assortItemsToProcess: Item[] = (expiredOffers) - ? expiredOffers - : this.ragfairAssortGenerator.getAssortItems(); + const assortItemsToProcess: Item[] = expiredOffers ? + expiredOffers : + this.ragfairAssortGenerator.getAssortItems(); // Store all functions to create an offer for every item and pass into Promise.all to run async const assorOffersForItemsProcesses = []; for (const assortItemIndex in assortItemsToProcess) { - assorOffersForItemsProcesses.push(this.createOffersForItems(assortItemIndex, assortItemsToProcess, expiredOffers, config)); + assorOffersForItemsProcesses.push( + this.createOffersForItems(assortItemIndex, assortItemsToProcess, expiredOffers, config), + ); } await Promise.all(assorOffersForItemsProcesses); } /** - * * @param assortItemIndex Index of assort item * @param assortItemsToProcess Item array containing index * @param expiredOffers Currently expired offers on flea * @param config Ragfair dynamic config */ - protected async createOffersForItems(assortItemIndex: string, assortItemsToProcess: Item[], expiredOffers: Item[], config: Dynamic): Promise + protected async createOffersForItems( + assortItemIndex: string, + assortItemsToProcess: Item[], + expiredOffers: Item[], + config: Dynamic, + ): Promise { const assortItem = assortItemsToProcess[assortItemIndex]; const itemDetails = this.itemHelper.getItem(assortItem._tpl); @@ -322,15 +348,21 @@ export class RagfairOfferGenerator } // Get item + sub-items if preset, otherwise just get item - const items: Item[] = (isPreset) - ? this.ragfairServerHelper.getPresetItems(assortItem) - : [...[assortItem], ...this.itemHelper.findAndReturnChildrenByAssort(assortItem._id, this.ragfairAssortGenerator.getAssortItems())]; + const items: Item[] = isPreset ? + this.ragfairServerHelper.getPresetItems(assortItem) : + [ + ...[assortItem], + ...this.itemHelper.findAndReturnChildrenByAssort( + assortItem._id, + this.ragfairAssortGenerator.getAssortItems(), + ), + ]; // Get number of offers to create // Limit to 1 offer when processing expired - const offerCount = (expiredOffers) - ? 1 - : Math.round(this.randomUtil.getInt(config.offerItemCount.min, config.offerItemCount.max)); + const offerCount = expiredOffers ? + 1 : + Math.round(this.randomUtil.getInt(config.offerItemCount.min, config.offerItemCount.max)); // Store all functions to create offers for this item and pass into Promise.all to run async const assortSingleOfferProcesses = []; @@ -342,7 +374,6 @@ export class RagfairOfferGenerator await Promise.all(assortSingleOfferProcesses); } - /** * Create one flea offer for a specific item * @param items Item to create offer for @@ -350,23 +381,30 @@ export class RagfairOfferGenerator * @param itemDetails raw db item details * @returns Item array */ - protected async createSingleOfferForItem(items: Item[], isPreset: boolean, itemDetails: [boolean, ITemplateItem]): Promise + protected async createSingleOfferForItem( + items: Item[], + isPreset: boolean, + itemDetails: [boolean, ITemplateItem], + ): Promise { // Set stack size to random value items[0].upd.StackObjectsCount = this.ragfairServerHelper.calculateDynamicStackCount(items[0]._tpl, isPreset); - + const isBarterOffer = this.randomUtil.getChance100(this.ragfairConfig.dynamic.barter.chancePercent); - const isPackOffer = this.randomUtil.getChance100(this.ragfairConfig.dynamic.pack.chancePercent) - && !isBarterOffer - && items.length === 1 - && this.itemHelper.isOfBaseclasses(items[0]._tpl, this.ragfairConfig.dynamic.pack.itemTypeWhitelist); + const isPackOffer = this.randomUtil.getChance100(this.ragfairConfig.dynamic.pack.chancePercent) && + !isBarterOffer && + items.length === 1 && + this.itemHelper.isOfBaseclasses(items[0]._tpl, this.ragfairConfig.dynamic.pack.itemTypeWhitelist); const randomUserId = this.hashUtil.generate(); let barterScheme: IBarterScheme[]; if (isPackOffer) { // Set pack size - const stackSize = this.randomUtil.getInt(this.ragfairConfig.dynamic.pack.itemCountMin, this.ragfairConfig.dynamic.pack.itemCountMax); + const stackSize = this.randomUtil.getInt( + this.ragfairConfig.dynamic.pack.itemCountMin, + this.ragfairConfig.dynamic.pack.itemCountMax, + ); items[0].upd.StackObjectsCount = stackSize; // Don't randomise pack items @@ -391,7 +429,8 @@ export class RagfairOfferGenerator items, barterScheme, 1, - isPreset || isPackOffer); // sellAsOnePiece + isPreset || isPackOffer, + ); // sellAsOnePiece this.ragfairCategoriesService.incrementCategory(offer); } @@ -413,7 +452,12 @@ export class RagfairOfferGenerator // Trader assorts / assort items are missing if (!assorts?.items?.length) { - this.logger.error(this.localisationService.getText("ragfair-no_trader_assorts_cant_generate_flea_offers", trader.base.nickname)); + this.logger.error( + this.localisationService.getText( + "ragfair-no_trader_assorts_cant_generate_flea_offers", + trader.base.nickname, + ), + ); return; } @@ -444,14 +488,20 @@ export class RagfairOfferGenerator } const isPreset = this.presetHelper.isPreset(item._id); - const items: Item[] = (isPreset) - ? this.ragfairServerHelper.getPresetItems(item) - : [...[item], ...this.itemHelper.findAndReturnChildrenByAssort(item._id, assorts.items)]; + const items: Item[] = isPreset ? + this.ragfairServerHelper.getPresetItems(item) : + [...[item], ...this.itemHelper.findAndReturnChildrenByAssort(item._id, assorts.items)]; const barterScheme = assorts.barter_scheme[item._id]; if (!barterScheme) { - this.logger.warning(this.localisationService.getText("ragfair-missing_barter_scheme", {itemId: item._id, tpl: item._tpl, name: trader.base.nickname})); + this.logger.warning( + this.localisationService.getText("ragfair-missing_barter_scheme", { + itemId: item._id, + tpl: item._tpl, + name: trader.base.nickname, + }), + ); continue; } @@ -473,11 +523,11 @@ export class RagfairOfferGenerator * @param userID id of owner of item * @param itemWithMods Item and mods, get condition of first item (only first array item is used) * @param itemDetails db details of first item - * @returns + * @returns */ protected randomiseItemUpdProperties(userID: string, itemWithMods: Item[], itemDetails: ITemplateItem): Item[] { - // Add any missing properties to first item in array + // Add any missing properties to first item in array itemWithMods[0] = this.addMissingConditions(itemWithMods[0]); if (!(this.ragfairServerHelper.isPlayer(userID) || this.ragfairServerHelper.isTrader(userID))) @@ -508,9 +558,9 @@ export class RagfairOfferGenerator { // Get keys from condition config dictionary const configConditions = Object.keys(this.ragfairConfig.dynamic.condition); - for (const baseClass of configConditions) + for (const baseClass of configConditions) { - if (this.itemHelper.isOfBaseclass(tpl, baseClass)) + if (this.itemHelper.isOfBaseclass(tpl, baseClass)) { return baseClass; } @@ -527,7 +577,10 @@ export class RagfairOfferGenerator */ protected randomiseItemCondition(conditionSettingsId: string, item: Item, itemDetails: ITemplateItem): void { - const multiplier = this.randomUtil.getFloat(this.ragfairConfig.dynamic.condition[conditionSettingsId].min, this.ragfairConfig.dynamic.condition[conditionSettingsId].max); + const multiplier = this.randomUtil.getFloat( + this.ragfairConfig.dynamic.condition[conditionSettingsId].min, + this.ragfairConfig.dynamic.condition[conditionSettingsId].max, + ); // Armor or weapons if (item.upd.Repairable) @@ -571,7 +624,7 @@ export class RagfairOfferGenerator return; } - if (item.upd.RepairKit) + if (item.upd.RepairKit) { // randomize repair kit (armor/weapon) uses item.upd.RepairKit.Resource = Math.round(itemDetails._props.MaxRepairResource * multiplier) || 1; @@ -585,7 +638,7 @@ export class RagfairOfferGenerator const remainingFuel = Math.round(totalCapacity * multiplier); item.upd.Resource = { UnitsConsumed: totalCapacity - remainingFuel, - Value: remainingFuel + Value: remainingFuel, }; } } @@ -600,7 +653,9 @@ export class RagfairOfferGenerator item.upd.Repairable.Durability = Math.round(item.upd.Repairable.Durability * multiplier) || 1; // randomize max durability, store to a temporary value so we can still compare the max durability - let tempMaxDurability = Math.round(this.randomUtil.getFloat(item.upd.Repairable.Durability - 5, item.upd.Repairable.MaxDurability + 5)) || item.upd.Repairable.Durability; + let tempMaxDurability = Math.round( + this.randomUtil.getFloat(item.upd.Repairable.Durability - 5, item.upd.Repairable.MaxDurability + 5), + ) || item.upd.Repairable.Durability; // clamp values to max/current if (tempMaxDurability >= item.upd.Repairable.MaxDurability) @@ -626,45 +681,45 @@ export class RagfairOfferGenerator protected addMissingConditions(item: Item): Item { const props = this.itemHelper.getItem(item._tpl)[1]._props; - const isRepairable = ("Durability" in props); - const isMedkit = ("MaxHpResource" in props); - const isKey = ("MaximumNumberOfUsage" in props); - const isConsumable = (props.MaxResource > 1 && "foodUseTime" in props); - const isRepairKit = ("MaxRepairResource" in props); + const isRepairable = "Durability" in props; + const isMedkit = "MaxHpResource" in props; + const isKey = "MaximumNumberOfUsage" in props; + const isConsumable = props.MaxResource > 1 && "foodUseTime" in props; + const isRepairKit = "MaxRepairResource" in props; if (isRepairable && props.Durability > 0) { item.upd.Repairable = { Durability: props.Durability, - MaxDurability: props.Durability + MaxDurability: props.Durability, }; } if (isMedkit && props.MaxHpResource > 0) { item.upd.MedKit = { - HpResource: props.MaxHpResource + HpResource: props.MaxHpResource, }; } - if (isKey) + if (isKey) { item.upd.Key = { - NumberOfUsages: 0 + NumberOfUsages: 0, }; } - if (isConsumable) + if (isConsumable) { item.upd.FoodDrink = { - HpPercent: props.MaxResource + HpPercent: props.MaxResource, }; } - if (isRepairKit) + if (isRepairKit) { item.upd.RepairKit = { - Resource: props.MaxRepairResource + Resource: props.MaxRepairResource, }; } @@ -679,7 +734,11 @@ export class RagfairOfferGenerator protected createBarterBarterScheme(offerItems: Item[]): IBarterScheme[] { // get flea price of item being sold - const priceOfItemOffer = this.ragfairPriceService.getDynamicOfferPriceForOffer(offerItems, Money.ROUBLES, false); + const priceOfItemOffer = this.ragfairPriceService.getDynamicOfferPriceForOffer( + offerItems, + Money.ROUBLES, + false, + ); // Dont make items under a designated rouble value into barter offers if (priceOfItemOffer < this.ragfairConfig.dynamic.barter.minRoubleCostToBecomeBarter) @@ -688,7 +747,10 @@ export class RagfairOfferGenerator } // Get a randomised number of barter items to list offer for - const barterItemCount = this.randomUtil.getInt(this.ragfairConfig.dynamic.barter.itemCountMin, this.ragfairConfig.dynamic.barter.itemCountMax); + const barterItemCount = this.randomUtil.getInt( + this.ragfairConfig.dynamic.barter.itemCountMin, + this.ragfairConfig.dynamic.barter.itemCountMax, + ); // Get desired cost of individual item offer will be listed for e.g. offer = 15k, item count = 3, desired item cost = 5k const desiredItemCost = Math.round(priceOfItemOffer / barterItemCount); @@ -699,7 +761,10 @@ export class RagfairOfferGenerator const fleaPrices = this.getFleaPricesAsArray(); // Filter possible barters to items that match the price range + not itself - const filtered = fleaPrices.filter(x => x.price >= desiredItemCost - offerCostVariance && x.price <= desiredItemCost + offerCostVariance && x.tpl !== offerItems[0]._tpl); + const filtered = fleaPrices.filter((x) => + x.price >= desiredItemCost - offerCostVariance && x.price <= desiredItemCost + offerCostVariance && + x.tpl !== offerItems[0]._tpl + ); // No items on flea have a matching price, fall back to currency if (filtered.length === 0) @@ -713,8 +778,8 @@ export class RagfairOfferGenerator return [ { count: barterItemCount, - _tpl: randomItem.tpl - } + _tpl: randomItem.tpl, + }, ]; } @@ -722,18 +787,20 @@ export class RagfairOfferGenerator * Get an array of flea prices + item tpl, cached in generator class inside `allowedFleaPriceItemsForBarter` * @returns array with tpl/price values */ - protected getFleaPricesAsArray(): { tpl: string; price: number; }[] + protected getFleaPricesAsArray(): {tpl: string; price: number;}[] { // Generate if needed if (!this.allowedFleaPriceItemsForBarter) { const fleaPrices = this.databaseServer.getTables().templates.prices; - const fleaArray = Object.entries(fleaPrices).map(([tpl, price]) => ({ tpl: tpl, price: price })); + const fleaArray = Object.entries(fleaPrices).map(([tpl, price]) => ({tpl: tpl, price: price})); // Only get item prices for items that also exist in items.json - const filteredItems = fleaArray.filter(x => this.itemHelper.getItem(x.tpl)[0]); + const filteredItems = fleaArray.filter((x) => this.itemHelper.getItem(x.tpl)[0]); - this.allowedFleaPriceItemsForBarter = filteredItems.filter(x => !this.itemHelper.isOfBaseclasses(x.tpl, this.ragfairConfig.dynamic.barter.itemTypeBlacklist)); + this.allowedFleaPriceItemsForBarter = filteredItems.filter((x) => + !this.itemHelper.isOfBaseclasses(x.tpl, this.ragfairConfig.dynamic.barter.itemTypeBlacklist) + ); } return this.allowedFleaPriceItemsForBarter; @@ -749,13 +816,14 @@ export class RagfairOfferGenerator protected createCurrencyBarterScheme(offerItems: Item[], isPackOffer: boolean, multipler = 1): IBarterScheme[] { const currency = this.ragfairServerHelper.getDynamicOfferCurrency(); - const price = this.ragfairPriceService.getDynamicOfferPriceForOffer(offerItems, currency, isPackOffer) * multipler; + const price = this.ragfairPriceService.getDynamicOfferPriceForOffer(offerItems, currency, isPackOffer) * + multipler; return [ { count: price, - _tpl: currency - } + _tpl: currency, + }, ]; } -} \ No newline at end of file +} diff --git a/project/src/generators/RepeatableQuestGenerator.ts b/project/src/generators/RepeatableQuestGenerator.ts index 0b7d5372..40f608c2 100644 --- a/project/src/generators/RepeatableQuestGenerator.ts +++ b/project/src/generators/RepeatableQuestGenerator.ts @@ -15,16 +15,25 @@ import { IEliminationCondition, IEquipmentConditionProps, IExploration, - IExplorationCondition, IKillConditionProps, + IExplorationCondition, + IKillConditionProps, IPickup, - IRepeatableQuest, IReward, IRewards + IRepeatableQuest, + IReward, + IRewards, } from "@spt-aki/models/eft/common/tables/IRepeatableQuests"; import { ITemplateItem } from "@spt-aki/models/eft/common/tables/ITemplateItem"; import { BaseClasses } from "@spt-aki/models/enums/BaseClasses"; import { ConfigTypes } from "@spt-aki/models/enums/ConfigTypes"; import { Money } from "@spt-aki/models/enums/Money"; import { Traders } from "@spt-aki/models/enums/Traders"; -import { IBaseQuestConfig, IBossInfo, IEliminationConfig, IQuestConfig, IRepeatableQuestConfig } from "@spt-aki/models/spt/config/IQuestConfig"; +import { + IBaseQuestConfig, + IBossInfo, + IEliminationConfig, + IQuestConfig, + IRepeatableQuestConfig, +} from "@spt-aki/models/spt/config/IQuestConfig"; import { IQuestTypePool } from "@spt-aki/models/spt/repeatable/IQuestTypePool"; import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; import { EventOutputHolder } from "@spt-aki/routers/EventOutputHolder"; @@ -66,7 +75,7 @@ export class RepeatableQuestGenerator @inject("ObjectId") protected objectId: ObjectId, @inject("ItemFilterService") protected itemFilterService: ItemFilterService, @inject("RepeatableQuestHelper") protected repeatableQuestHelper: RepeatableQuestHelper, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.questConfig = this.configServer.getConfig(ConfigTypes.QUEST); @@ -85,15 +94,17 @@ export class RepeatableQuestGenerator pmcLevel: number, pmcTraderInfo: Record, questTypePool: IQuestTypePool, - repeatableConfig: IRepeatableQuestConfig + repeatableConfig: IRepeatableQuestConfig, ): IRepeatableQuest { const questType = this.randomUtil.drawRandomFromList(questTypePool.types)[0]; // get traders from whitelist and filter by quest type availability - let traders = repeatableConfig.traderWhitelist.filter(x => x.questTypes.includes(questType)).map(x => x.traderId); + let traders = repeatableConfig.traderWhitelist.filter((x) => x.questTypes.includes(questType)).map((x) => + x.traderId + ); // filter out locked traders - traders = traders.filter(x => pmcTraderInfo[x].unlocked); + traders = traders.filter((x) => pmcTraderInfo[x].unlocked); const traderId = this.randomUtil.drawRandomFromList(traders)[0]; switch (questType) @@ -123,15 +134,19 @@ export class RepeatableQuestGenerator pmcLevel: number, traderId: string, questTypePool: IQuestTypePool, - repeatableConfig: IRepeatableQuestConfig + repeatableConfig: IRepeatableQuestConfig, ): IElimination { const eliminationConfig = this.repeatableQuestHelper.getEliminationConfigByPmcLevel(pmcLevel, repeatableConfig); const locationsConfig = repeatableConfig.locations; let targetsConfig = this.repeatableQuestHelper.probabilityObjectArray(eliminationConfig.targets); const bodypartsConfig = this.repeatableQuestHelper.probabilityObjectArray(eliminationConfig.bodyParts); - const weaponCategoryRequirementConfig = this.repeatableQuestHelper.probabilityObjectArray(eliminationConfig.weaponCategoryRequirements); - const weaponRequirementConfig = this.repeatableQuestHelper.probabilityObjectArray(eliminationConfig.weaponRequirements); + const weaponCategoryRequirementConfig = this.repeatableQuestHelper.probabilityObjectArray( + eliminationConfig.weaponCategoryRequirements, + ); + const weaponRequirementConfig = this.repeatableQuestHelper.probabilityObjectArray( + eliminationConfig.weaponRequirements, + ); // the difficulty of the quest varies in difficulty depending on the condition // possible conditions are @@ -146,7 +161,7 @@ export class RepeatableQuestGenerator // Savage: 7, // AnyPmc: 2, // bossBully: 0.5 - //} + // } // higher is more likely. We define the difficulty to be the inverse of the relative probability. // We want to generate a reward which is scaled by the difficulty of this mission. To get a upper bound with which we scale @@ -165,18 +180,26 @@ export class RepeatableQuestGenerator const maxKillDifficulty = eliminationConfig.maxKills; - function difficultyWeighing(target: number, bodyPart: number, dist: number, kill: number, weaponRequirement: number): number + function difficultyWeighing( + target: number, + bodyPart: number, + dist: number, + kill: number, + weaponRequirement: number, + ): number { return Math.sqrt(Math.sqrt(target) + bodyPart + dist + weaponRequirement) * kill; } - targetsConfig = targetsConfig.filter(x => Object.keys(questTypePool.pool.Elimination.targets).includes(x.key)); - if (targetsConfig.length === 0 || targetsConfig.every(x => x.data.isBoss)) + targetsConfig = targetsConfig.filter((x) => + Object.keys(questTypePool.pool.Elimination.targets).includes(x.key) + ); + if (targetsConfig.length === 0 || targetsConfig.every((x) => x.data.isBoss)) { // There are no more targets left for elimination; delete it as a possible quest type // also if only bosses are left we need to leave otherwise it's a guaranteed boss elimination // -> then it would not be a quest with low probability anymore - questTypePool.types = questTypePool.types.filter(t => t !== "Elimination"); + questTypePool.types = questTypePool.types.filter((t) => t !== "Elimination"); return null; } @@ -188,18 +211,23 @@ export class RepeatableQuestGenerator // we use any as location if "any" is in the pool and we do not hit the specific location random // we use any also if the random condition is not met in case only "any" was in the pool let locationKey = "any"; - if (locations.includes("any") && (eliminationConfig.specificLocationProb < Math.random() || locations.length <= 1)) + if ( + locations.includes("any") && + (eliminationConfig.specificLocationProb < Math.random() || locations.length <= 1) + ) { locationKey = "any"; delete questTypePool.pool.Elimination.targets[targetKey]; } else { - locations = locations.filter(l => l !== "any"); + locations = locations.filter((l) => l !== "any"); if (locations.length > 0) { locationKey = this.randomUtil.drawRandomFromList(locations)[0]; - questTypePool.pool.Elimination.targets[targetKey].locations = locations.filter(l => l !== locationKey); + questTypePool.pool.Elimination.targets[targetKey].locations = locations.filter((l) => + l !== locationKey + ); if (questTypePool.pool.Elimination.targets[targetKey].locations.length === 0) { delete questTypePool.pool.Elimination.targets[targetKey]; @@ -243,15 +271,17 @@ export class RepeatableQuestGenerator if (targetsConfig.data(targetKey).isBoss) { // get all boss spawn information - const bossSpawns = Object.values(this.databaseServer.getTables().locations).filter(x => "base" in x && "Id" in x.base).map( - (x) => ({ Id: x.base.Id, BossSpawn: x.base.BossLocationSpawn }) + const bossSpawns = Object.values(this.databaseServer.getTables().locations).filter((x) => + "base" in x && "Id" in x.base + ).map( + (x) => ({Id: x.base.Id, BossSpawn: x.base.BossLocationSpawn}), ); // filter for the current boss to spawn on map const thisBossSpawns = bossSpawns.map( - (x) => ({ Id: x.Id, BossSpawn: x.BossSpawn.filter(e => e.BossName === targetKey) }) - ).filter(x => x.BossSpawn.length > 0); + (x) => ({Id: x.Id, BossSpawn: x.BossSpawn.filter((e) => e.BossName === targetKey)}), + ).filter((x) => x.BossSpawn.length > 0); // remove blacklisted locations - const allowedSpawns = thisBossSpawns.filter(x => !eliminationConfig.distLocationBlacklist.includes(x.Id)); + const allowedSpawns = thisBossSpawns.filter((x) => !eliminationConfig.distLocationBlacklist.includes(x.Id)); // if the boss spawns on nom-blacklisted locations and the current location is allowed we can generate a distance kill requirement isDistanceRequirementAllowed = isDistanceRequirementAllowed && (allowedSpawns.length > 0); } @@ -259,7 +289,10 @@ export class RepeatableQuestGenerator if (eliminationConfig.distProb > Math.random() && isDistanceRequirementAllowed) { // random distance with lower values more likely; simple distribution for starters... - distance = Math.floor(Math.abs(Math.random() - Math.random()) * (1 + eliminationConfig.maxDist - eliminationConfig.minDist) + eliminationConfig.minDist); + distance = Math.floor( + Math.abs(Math.random() - Math.random()) * (1 + eliminationConfig.maxDist - eliminationConfig.minDist) + + eliminationConfig.minDist, + ); distance = Math.ceil(distance / 5) * 5; distanceDifficulty = maxDistDifficulty * distance / eliminationConfig.maxDist; } @@ -296,7 +329,7 @@ export class RepeatableQuestGenerator bodyPartDifficulty / maxBodyPartsDifficulty, distanceDifficulty / maxDistDifficulty, killDifficulty / maxKillDifficulty, - (allowedWeaponsCategory || allowedWeapon) ? 1 : 0 + (allowedWeaponsCategory || allowedWeapon) ? 1 : 0, ); // Aforementioned issue makes it a bit crazy since now all easier quests give significantly lower rewards than Completion / Exploration @@ -305,7 +338,7 @@ export class RepeatableQuestGenerator const difficulty = this.mathUtil.mapToRange(curDifficulty, minDifficulty, maxDifficulty, 0.5, 2); const quest = this.generateRepeatableTemplate("Elimination", traderId, repeatableConfig.side) as IElimination; - + // ASSUMPTION: All fence quests are for scavs if (traderId === Traders.FENCE) { @@ -319,14 +352,30 @@ export class RepeatableQuestGenerator // Only add specific location condition if specific map selected if (locationKey !== "any") { - availableForFinishCondition._props.counter.conditions.push(this.generateEliminationLocation(locationsConfig[locationKey])); + availableForFinishCondition._props.counter.conditions.push( + this.generateEliminationLocation(locationsConfig[locationKey]), + ); } - availableForFinishCondition._props.counter.conditions.push(this.generateEliminationCondition(targetKey, bodyPartsToClient, distance, allowedWeapon, allowedWeaponsCategory)); + availableForFinishCondition._props.counter.conditions.push( + this.generateEliminationCondition( + targetKey, + bodyPartsToClient, + distance, + allowedWeapon, + allowedWeaponsCategory, + ), + ); availableForFinishCondition._props.value = desiredKillCount; availableForFinishCondition._props.id = this.objectId.generate(); quest.location = this.getQuestLocationByMapId(locationKey); - quest.rewards = this.generateReward(pmcLevel, Math.min(difficulty, 1), traderId, repeatableConfig, eliminationConfig); + quest.rewards = this.generateReward( + pmcLevel, + Math.min(difficulty, 1), + traderId, + repeatableConfig, + eliminationConfig, + ); return quest; } @@ -338,7 +387,11 @@ export class RepeatableQuestGenerator * @param eliminationConfig Config * @returns Number of AI to kill */ - protected getEliminationKillCount(targetKey: string, targetsConfig: ProbabilityObjectArray, eliminationConfig: IEliminationConfig): number + protected getEliminationKillCount( + targetKey: string, + targetsConfig: ProbabilityObjectArray, + eliminationConfig: IEliminationConfig, + ): number { if (targetsConfig.data(targetKey).isBoss) { @@ -366,11 +419,11 @@ export class RepeatableQuestGenerator _props: { target: location, id: this.objectId.generate(), - dynamicLocale: true + dynamicLocale: true, }, - _parent: "Location" + _parent: "Location", }; - + return propsObject; } @@ -383,13 +436,19 @@ export class RepeatableQuestGenerator * @param allowedWeaponCategory What category of weapon must be used - undefined = any * @returns IEliminationCondition object */ - protected generateEliminationCondition(target: string, targetedBodyParts: string[], distance: number, allowedWeapon: string, allowedWeaponCategory: string): IEliminationCondition + protected generateEliminationCondition( + target: string, + targetedBodyParts: string[], + distance: number, + allowedWeapon: string, + allowedWeaponCategory: string, + ): IEliminationCondition { const killConditionProps: IKillConditionProps = { target: target, value: 1, id: this.objectId.generate(), - dynamicLocale: true + dynamicLocale: true, }; if (target.startsWith("boss")) @@ -409,7 +468,7 @@ export class RepeatableQuestGenerator { killConditionProps.distance = { compareMethod: ">=", - value: distance + value: distance, }; } @@ -427,7 +486,7 @@ export class RepeatableQuestGenerator return { _props: killConditionProps, - _parent: "Kills" + _parent: "Kills", }; } @@ -442,7 +501,7 @@ export class RepeatableQuestGenerator protected generateCompletionQuest( pmcLevel: number, traderId: string, - repeatableConfig: IRepeatableQuestConfig + repeatableConfig: IRepeatableQuestConfig, ): ICompletion { const completionConfig = repeatableConfig.questConfig.Completion; @@ -456,48 +515,64 @@ export class RepeatableQuestGenerator numberDistinctItems = 2; } - const quest = this.generateRepeatableTemplate("Completion", traderId,repeatableConfig.side) as ICompletion; + const quest = this.generateRepeatableTemplate("Completion", traderId, repeatableConfig.side) as ICompletion; // Filter the items.json items to items the player must retrieve to complete queist: shouldn't be a quest item or "non-existant" let itemSelection = this.getRewardableItems(repeatableConfig); // Be fair, don't let the items be more expensive than the reward - let roublesBudget = Math.floor(this.mathUtil.interp1(pmcLevel, levelsConfig, roublesConfig) * this.randomUtil.getFloat(0.5, 1)); + let roublesBudget = Math.floor( + this.mathUtil.interp1(pmcLevel, levelsConfig, roublesConfig) * this.randomUtil.getFloat(0.5, 1), + ); roublesBudget = Math.max(roublesBudget, 5000); - itemSelection = itemSelection.filter(x => this.itemHelper.getItemPrice(x[0]) < roublesBudget); + itemSelection = itemSelection.filter((x) => this.itemHelper.getItemPrice(x[0]) < roublesBudget); // We also have the option to use whitelist and/or blacklist which is defined in repeatableQuests.json as // [{minPlayerLevel: 1, itemIds: ["id1",...]}, {minPlayerLevel: 15, itemIds: ["id3",...]}] if (repeatableConfig.questConfig.Completion.useWhitelist) { - const itemWhitelist = this.databaseServer.getTables().templates.repeatableQuests.data.Completion.itemsWhitelist; + const itemWhitelist = + this.databaseServer.getTables().templates.repeatableQuests.data.Completion.itemsWhitelist; // Filter and concatenate the arrays according to current player level - const itemIdsWhitelisted = itemWhitelist.filter(p => p.minPlayerLevel <= pmcLevel).reduce((a, p) => a.concat(p.itemIds), []); - itemSelection = itemSelection.filter(x => + const itemIdsWhitelisted = itemWhitelist.filter((p) => p.minPlayerLevel <= pmcLevel).reduce( + (a, p) => a.concat(p.itemIds), + [], + ); + itemSelection = itemSelection.filter((x) => { // Whitelist can contain item tpls and item base type ids - return (itemIdsWhitelisted.some(v => this.itemHelper.isOfBaseclass(x[0], v)) || itemIdsWhitelisted.includes(x[0])); + return (itemIdsWhitelisted.some((v) => this.itemHelper.isOfBaseclass(x[0], v)) || + itemIdsWhitelisted.includes(x[0])); }); // check if items are missing - //const flatList = itemSelection.reduce((a, il) => a.concat(il[0]), []); - //const missing = itemIdsWhitelisted.filter(l => !flatList.includes(l)); + // const flatList = itemSelection.reduce((a, il) => a.concat(il[0]), []); + // const missing = itemIdsWhitelisted.filter(l => !flatList.includes(l)); } if (repeatableConfig.questConfig.Completion.useBlacklist) { - const itemBlacklist = this.databaseServer.getTables().templates.repeatableQuests.data.Completion.itemsBlacklist; + const itemBlacklist = + this.databaseServer.getTables().templates.repeatableQuests.data.Completion.itemsBlacklist; // we filter and concatenate the arrays according to current player level - const itemIdsBlacklisted = itemBlacklist.filter(p => p.minPlayerLevel <= pmcLevel).reduce((a, p) => a.concat(p.itemIds), []); - itemSelection = itemSelection.filter(x => + const itemIdsBlacklisted = itemBlacklist.filter((p) => p.minPlayerLevel <= pmcLevel).reduce( + (a, p) => a.concat(p.itemIds), + [], + ); + itemSelection = itemSelection.filter((x) => { - return itemIdsBlacklisted.every(v => !this.itemHelper.isOfBaseclass(x[0], v)) || !itemIdsBlacklisted.includes(x[0]); + return itemIdsBlacklisted.every((v) => !this.itemHelper.isOfBaseclass(x[0], v)) || + !itemIdsBlacklisted.includes(x[0]); }); } if (itemSelection.length === 0) { - this.logger.error(this.localisationService.getText("repeatable-completion_quest_whitelist_too_small_or_blacklist_too_restrictive")); + this.logger.error( + this.localisationService.getText( + "repeatable-completion_quest_whitelist_too_small_or_blacklist_too_restrictive", + ), + ); return null; } @@ -532,7 +607,7 @@ export class RepeatableQuestGenerator if (roublesBudget > 0) { // reduce the list possible items to fulfill the new budget constraint - itemSelection = itemSelection.filter(x => this.itemHelper.getItemPrice(x[0]) < roublesBudget); + itemSelection = itemSelection.filter((x) => this.itemHelper.getItemPrice(x[0]) < roublesBudget); if (itemSelection.length === 0) { break; @@ -561,12 +636,18 @@ export class RepeatableQuestGenerator { let minDurability = 0; let onlyFoundInRaid = true; - if (this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.WEAPON) || this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.ARMOR)) + if ( + this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.WEAPON) || + this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.ARMOR) + ) { minDurability = 80; } - if (this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.DOG_TAG_USEC) || this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.DOG_TAG_BEAR)) + if ( + this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.DOG_TAG_USEC) || + this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.DOG_TAG_BEAR) + ) { onlyFoundInRaid = false; } @@ -583,10 +664,10 @@ export class RepeatableQuestGenerator minDurability: minDurability, maxDurability: 100, dogtagLevel: 0, - onlyFoundInRaid: onlyFoundInRaid + onlyFoundInRaid: onlyFoundInRaid, }, _parent: "HandoverItem", - dynamicLocale: true + dynamicLocale: true, }; } @@ -603,7 +684,7 @@ export class RepeatableQuestGenerator pmcLevel: number, traderId: string, questTypePool: IQuestTypePool, - repeatableConfig: IRepeatableQuestConfig + repeatableConfig: IRepeatableQuestConfig, ): IExploration { const explorationConfig = repeatableConfig.questConfig.Exploration; @@ -611,7 +692,7 @@ export class RepeatableQuestGenerator if (Object.keys(questTypePool.pool.Exploration.locations).length === 0) { // there are no more locations left for exploration; delete it as a possible quest type - questTypePool.types = questTypePool.types.filter(t => t !== "Exploration"); + questTypePool.types = questTypePool.types.filter((t) => t !== "Exploration"); return null; } @@ -625,7 +706,7 @@ export class RepeatableQuestGenerator const numExtracts = this.randomUtil.randInt(1, explorationConfig.maxExtracts + 1); - const quest = this.generateRepeatableTemplate("Exploration", traderId,repeatableConfig.side) as IExploration; + const quest = this.generateRepeatableTemplate("Exploration", traderId, repeatableConfig.side) as IExploration; const exitStatusCondition: IExplorationCondition = { _parent: "ExitStatus", @@ -633,23 +714,23 @@ export class RepeatableQuestGenerator id: this.objectId.generate(), dynamicLocale: true, status: [ - "Survived" - ] - } + "Survived", + ], + }, }; const locationCondition: IExplorationCondition = { _parent: "Location", _props: { id: this.objectId.generate(), dynamicLocale: true, - target: locationTarget - } + target: locationTarget, + }, }; quest.conditions.AvailableForFinish[0]._props.counter.id = this.objectId.generate(); quest.conditions.AvailableForFinish[0]._props.counter.conditions = [ exitStatusCondition, - locationCondition + locationCondition, ]; quest.conditions.AvailableForFinish[0]._props.value = numExtracts; quest.conditions.AvailableForFinish[0]._props.id = this.objectId.generate(); @@ -659,11 +740,15 @@ export class RepeatableQuestGenerator { // Filter by whitelist, it's also possible that the field "PassageRequirement" does not exist (e.g. Shoreline) // Scav exits are not listed at all in locations.base currently. If that changes at some point, additional filtering will be required - const mapExits = (this.databaseServer.getTables().locations[locationKey.toLowerCase()].base as ILocationBase).exits; + const mapExits = + (this.databaseServer.getTables().locations[locationKey.toLowerCase()].base as ILocationBase).exits; const possibleExists = mapExits.filter( - x => (!("PassageRequirement" in x) - || repeatableConfig.questConfig.Exploration.specificExits.passageRequirementWhitelist.includes(x.PassageRequirement)) - && x.Chance > 0 + (x) => + (!("PassageRequirement" in x) || + repeatableConfig.questConfig.Exploration.specificExits.passageRequirementWhitelist.includes( + x.PassageRequirement, + )) && + x.Chance > 0, ); const exit = this.randomUtil.drawRandomFromList(possibleExists, 1)[0]; const exitCondition = this.generateExplorationExitCondition(exit); @@ -682,7 +767,7 @@ export class RepeatableQuestGenerator pmcLevel: number, traderId: string, questTypePool: IQuestTypePool, - repeatableConfig: IRepeatableQuestConfig + repeatableConfig: IRepeatableQuestConfig, ): IPickup { const pickupConfig = repeatableConfig.questConfig.Pickup; @@ -690,21 +775,28 @@ export class RepeatableQuestGenerator const quest = this.generateRepeatableTemplate("Pickup", traderId, repeatableConfig.side) as IPickup; const itemTypeToFetchWithCount = this.randomUtil.getArrayValue(pickupConfig.ItemTypeToFetchWithMaxCount); - const itemCountToFetch = this.randomUtil.randInt(itemTypeToFetchWithCount.minPickupCount, itemTypeToFetchWithCount.maxPickupCount + 1); + const itemCountToFetch = this.randomUtil.randInt( + itemTypeToFetchWithCount.minPickupCount, + itemTypeToFetchWithCount.maxPickupCount + 1, + ); // Choose location - doesnt seem to work for anything other than 'any' - //const locationKey: string = this.randomUtil.drawRandomFromDict(questTypePool.pool.Pickup.locations)[0]; - //const locationTarget = questTypePool.pool.Pickup.locations[locationKey]; + // const locationKey: string = this.randomUtil.drawRandomFromDict(questTypePool.pool.Pickup.locations)[0]; + // const locationTarget = questTypePool.pool.Pickup.locations[locationKey]; - const findCondition = quest.conditions.AvailableForFinish.find(x => x._parent === "FindItem"); + const findCondition = quest.conditions.AvailableForFinish.find((x) => x._parent === "FindItem"); findCondition._props.target = [itemTypeToFetchWithCount.itemType]; findCondition._props.value = itemCountToFetch; - const counterCreatorCondition = quest.conditions.AvailableForFinish.find(x => x._parent === "CounterCreator"); - //const locationCondition = counterCreatorCondition._props.counter.conditions.find(x => x._parent === "Location"); - //(locationCondition._props as ILocationConditionProps).target = [...locationTarget]; + const counterCreatorCondition = quest.conditions.AvailableForFinish.find((x) => x._parent === "CounterCreator"); + // const locationCondition = counterCreatorCondition._props.counter.conditions.find(x => x._parent === "Location"); + // (locationCondition._props as ILocationConditionProps).target = [...locationTarget]; - const equipmentCondition = counterCreatorCondition._props.counter.conditions.find(x => x._parent === "Equipment"); - (equipmentCondition._props as IEquipmentConditionProps).equipmentInclusive = [[itemTypeToFetchWithCount.itemType]]; + const equipmentCondition = counterCreatorCondition._props.counter.conditions.find((x) => + x._parent === "Equipment" + ); + (equipmentCondition._props as IEquipmentConditionProps).equipmentInclusive = [[ + itemTypeToFetchWithCount.itemType, + ]]; // Add rewards quest.rewards = this.generateReward(pmcLevel, 1, traderId, repeatableConfig, pickupConfig); @@ -736,8 +828,8 @@ export class RepeatableQuestGenerator _props: { exitName: exit.Name, id: this.objectId.generate(), - dynamicLocale: true - } + dynamicLocale: true, + }, }; } @@ -766,7 +858,7 @@ export class RepeatableQuestGenerator difficulty: number, traderId: string, repeatableConfig: IRepeatableQuestConfig, - questConfig: IBaseQuestConfig + questConfig: IBaseQuestConfig, ): IRewards { // difficulty could go from 0.2 ... -> for lowest diffuculty receive 0.2*nominal reward @@ -786,11 +878,22 @@ export class RepeatableQuestGenerator } // rewards are generated based on pmcLevel, difficulty and a random spread - const rewardXP = Math.floor(difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, xpConfig) * this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig)); - const rewardRoubles = Math.floor(difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, roublesConfig) * this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig)); - const rewardNumItems = this.randomUtil.randInt(1, Math.round(this.mathUtil.interp1(pmcLevel, levelsConfig, itemsConfig)) + 1); - const rewardReputation = Math.round(100 * difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, reputationConfig) - * this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig)) / 100; + const rewardXP = Math.floor( + difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, xpConfig) * + this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig), + ); + const rewardRoubles = Math.floor( + difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, roublesConfig) * + this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig), + ); + const rewardNumItems = this.randomUtil.randInt( + 1, + Math.round(this.mathUtil.interp1(pmcLevel, levelsConfig, itemsConfig)) + 1, + ); + const rewardReputation = Math.round( + 100 * difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, reputationConfig) * + this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig), + ) / 100; const skillRewardChance = this.mathUtil.interp1(pmcLevel, levelsConfig, skillRewardChanceConfig); const skillPointReward = this.mathUtil.interp1(pmcLevel, levelsConfig, skillPointRewardConfig); @@ -804,16 +907,18 @@ export class RepeatableQuestGenerator { value: rewardXP, type: "Experience", - index: 0 - } + index: 0, + }, ], - Fail: [] + Fail: [], }; if (traderId === Traders.PEACEKEEPER) { // convert to equivalent dollars - rewards.Success.push(this.generateRewardItem(Money.EUROS, this.handbookHelper.fromRUB(rewardRoubles, Money.EUROS), 1)); + rewards.Success.push( + this.generateRewardItem(Money.EUROS, this.handbookHelper.fromRUB(rewardRoubles, Money.EUROS), 1), + ); } else { @@ -837,14 +942,20 @@ export class RepeatableQuestGenerator } // If we provide ammo we don't want to provide just one bullet - value = this.randomUtil.randInt(repeatableConfig.rewardAmmoStackMinSize, itemSelected._props.StackMaxSize); + value = this.randomUtil.randInt( + repeatableConfig.rewardAmmoStackMinSize, + itemSelected._props.StackMaxSize, + ); } else if (this.itemHelper.isOfBaseclass(itemSelected._id, BaseClasses.WEAPON)) { const defaultPreset = this.presetHelper.getDefaultPreset(itemSelected._id); if (defaultPreset) { - children = this.ragfairServerHelper.reparentPresets(defaultPreset._items[0], defaultPreset._items); + children = this.ragfairServerHelper.reparentPresets( + defaultPreset._items[0], + defaultPreset._items, + ); } } rewards.Success.push(this.generateRewardItem(itemSelected._id, value, index, children)); @@ -859,7 +970,9 @@ export class RepeatableQuestGenerator if (roublesBudget > 0) { // Filter possible reward items to only items with a price below the remaining budget - chosenRewardItems = chosenRewardItems.filter(x => this.itemHelper.getStaticItemPrice(x._id) < roublesBudget); + chosenRewardItems = chosenRewardItems.filter((x) => + this.itemHelper.getStaticItemPrice(x._id) < roublesBudget + ); if (chosenRewardItems.length === 0) { break; // No reward items left, exit @@ -879,7 +992,7 @@ export class RepeatableQuestGenerator target: traderId, value: rewardReputation, type: "TraderStanding", - index: index + index: index, }; rewards.Success.push(reward); } @@ -891,7 +1004,7 @@ export class RepeatableQuestGenerator target: this.randomUtil.getArrayValue(questConfig.possibleSkillRewards), value: skillPointReward, type: "Skill", - index: index + index: index, }; rewards.Success.push(reward); } @@ -905,17 +1018,29 @@ export class RepeatableQuestGenerator * @param roublesBudget Total value of items to return * @returns Array of reward items that fit budget */ - protected chooseRewardItemsWithinBudget(repeatableConfig: IRepeatableQuestConfig, roublesBudget: number): ITemplateItem[] + protected chooseRewardItemsWithinBudget( + repeatableConfig: IRepeatableQuestConfig, + roublesBudget: number, + ): ITemplateItem[] { // First filter for type and baseclass to avoid lookup in handbook for non-available items const rewardableItems = this.getRewardableItems(repeatableConfig); const minPrice = Math.min(25000, 0.5 * roublesBudget); - let itemSelection = rewardableItems.filter(x => this.itemHelper.getItemPrice(x[0]) < roublesBudget && this.itemHelper.getItemPrice(x[0]) > minPrice).map(x => x[1]); + let itemSelection = rewardableItems.filter((x) => + this.itemHelper.getItemPrice(x[0]) < roublesBudget && this.itemHelper.getItemPrice(x[0]) > minPrice + ).map((x) => x[1]); if (itemSelection.length === 0) { - this.logger.warning(this.localisationService.getText("repeatable-no_reward_item_found_in_price_range", {minPrice: minPrice, roublesBudget: roublesBudget})); + this.logger.warning( + this.localisationService.getText("repeatable-no_reward_item_found_in_price_range", { + minPrice: minPrice, + roublesBudget: roublesBudget, + }), + ); // In case we don't find any items in the price range - itemSelection = rewardableItems.filter(x => this.itemHelper.getItemPrice(x[0]) < roublesBudget).map(x => x[1]); + itemSelection = rewardableItems.filter((x) => this.itemHelper.getItemPrice(x[0]) < roublesBudget).map((x) => + x[1] + ); } return itemSelection; @@ -936,7 +1061,7 @@ export class RepeatableQuestGenerator target: id, value: value, type: "Item", - index: index + index: index, }; const rootItem = { @@ -944,8 +1069,8 @@ export class RepeatableQuestGenerator _tpl: tpl, upd: { StackObjectsCount: value, - SpawnedInSession: true - } + SpawnedInSession: true, + }, }; if (preset) @@ -960,7 +1085,7 @@ export class RepeatableQuestGenerator } /** - * Picks rewardable items from items.json. This means they need to fit into the inventory and they shouldn't be keys (debatable) + * Picks rewardable items from items.json. This means they need to fit into the inventory and they shouldn't be keys (debatable) * @param repeatableQuestConfig Config file * @returns List of rewardable items [[_tpl, itemTemplate],...] */ @@ -970,7 +1095,6 @@ export class RepeatableQuestGenerator // also check if the price is greater than 0; there are some items whose price can not be found // those are not in the game yet (e.g. AGS grenade launcher) return Object.entries(this.databaseServer.getTables().templates.items).filter( - // eslint-disable-next-line @typescript-eslint/no-unused-vars ([tpl, itemTemplate]) => { // Base "Item" item has no parent, ignore it @@ -980,7 +1104,7 @@ export class RepeatableQuestGenerator } return this.isValidRewardItem(tpl, repeatableQuestConfig); - } + }, ); } @@ -999,8 +1123,10 @@ export class RepeatableQuestGenerator } // Item is on repeatable or global blacklist - if (repeatableQuestConfig.rewardBlacklist.includes(tpl) - || this.itemFilterService.isItemBlacklisted(tpl)) + if ( + repeatableQuestConfig.rewardBlacklist.includes(tpl) || + this.itemFilterService.isItemBlacklisted(tpl) + ) { return false; } @@ -1011,15 +1137,23 @@ export class RepeatableQuestGenerator return false; } - if (this.itemHelper.isOfBaseclasses(tpl, [BaseClasses.DOG_TAG_USEC, BaseClasses.DOG_TAG_BEAR, BaseClasses.MOUNT, BaseClasses.KEY, BaseClasses.ARMBAND])) + if ( + this.itemHelper.isOfBaseclasses(tpl, [ + BaseClasses.DOG_TAG_USEC, + BaseClasses.DOG_TAG_BEAR, + BaseClasses.MOUNT, + BaseClasses.KEY, + BaseClasses.ARMBAND, + ]) + ) { return false; } // Skip globally blacklisted items + boss items // biome-ignore lint/complexity/useSimplifiedLogicExpression: - valid = !this.itemFilterService.isItemBlacklisted(tpl) - && !this.itemFilterService.isBossItem(tpl); + valid = !this.itemFilterService.isItemBlacklisted(tpl) && + !this.itemFilterService.isBossItem(tpl); return valid; } @@ -1030,36 +1164,59 @@ export class RepeatableQuestGenerator * * @param {string} type Quest type: "Elimination", "Completion" or "Extraction" * @param {string} traderId Trader from which the quest will be provided - * @param {string} side Scav daily or pmc daily/weekly quest + * @param {string} side Scav daily or pmc daily/weekly quest * @returns {object} Object which contains the base elements for repeatable quests of the requests type * (needs to be filled with reward and conditions by called to make a valid quest) */ // @Incomplete: define Type for "type". protected generateRepeatableTemplate(type: string, traderId: string, side: string): IRepeatableQuest { - const quest = this.jsonUtil.clone(this.databaseServer.getTables().templates.repeatableQuests.templates[type]); + const quest = this.jsonUtil.clone( + this.databaseServer.getTables().templates.repeatableQuests.templates[type], + ); quest._id = this.objectId.generate(); quest.traderId = traderId; /* in locale, these id correspond to the text of quests template ids -pmc : Elimination = 616052ea3054fc0e2c24ce6e / Completion = 61604635c725987e815b1a46 / Exploration = 616041eb031af660100c9967 - template ids -scav : Elimination = 62825ef60e88d037dc1eb428 / Completion = 628f588ebb558574b2260fe5 / Exploration = 62825ef60e88d037dc1eb42c + template ids -scav : Elimination = 62825ef60e88d037dc1eb428 / Completion = 628f588ebb558574b2260fe5 / Exploration = 62825ef60e88d037dc1eb42c */ // Get template id from config based on side and type of quest quest.templateId = this.questConfig.questTemplateIds[side.toLowerCase()][type.toLowerCase()]; - quest.name = quest.name.replace("{traderId}", traderId).replace("{templateId}",quest.templateId); - quest.note = quest.note.replace("{traderId}", traderId).replace("{templateId}",quest.templateId); - quest.description = quest.description.replace("{traderId}", traderId).replace("{templateId}",quest.templateId); - quest.successMessageText = quest.successMessageText.replace("{traderId}", traderId).replace("{templateId}",quest.templateId); - quest.failMessageText = quest.failMessageText.replace("{traderId}", traderId).replace("{templateId}",quest.templateId); - quest.startedMessageText = quest.startedMessageText.replace("{traderId}", traderId).replace("{templateId}",quest.templateId); - quest.changeQuestMessageText = quest.changeQuestMessageText.replace("{traderId}", traderId).replace("{templateId}",quest.templateId); - quest.acceptPlayerMessage = quest.acceptPlayerMessage.replace("{traderId}", traderId).replace("{templateId}",quest.templateId); - quest.declinePlayerMessage = quest.declinePlayerMessage.replace("{traderId}", traderId).replace("{templateId}",quest.templateId); - quest.completePlayerMessage = quest.completePlayerMessage.replace("{traderId}", traderId).replace("{templateId}",quest.templateId); + quest.name = quest.name.replace("{traderId}", traderId).replace("{templateId}", quest.templateId); + quest.note = quest.note.replace("{traderId}", traderId).replace("{templateId}", quest.templateId); + quest.description = quest.description.replace("{traderId}", traderId).replace("{templateId}", quest.templateId); + quest.successMessageText = quest.successMessageText.replace("{traderId}", traderId).replace( + "{templateId}", + quest.templateId, + ); + quest.failMessageText = quest.failMessageText.replace("{traderId}", traderId).replace( + "{templateId}", + quest.templateId, + ); + quest.startedMessageText = quest.startedMessageText.replace("{traderId}", traderId).replace( + "{templateId}", + quest.templateId, + ); + quest.changeQuestMessageText = quest.changeQuestMessageText.replace("{traderId}", traderId).replace( + "{templateId}", + quest.templateId, + ); + quest.acceptPlayerMessage = quest.acceptPlayerMessage.replace("{traderId}", traderId).replace( + "{templateId}", + quest.templateId, + ); + quest.declinePlayerMessage = quest.declinePlayerMessage.replace("{traderId}", traderId).replace( + "{templateId}", + quest.templateId, + ); + quest.completePlayerMessage = quest.completePlayerMessage.replace("{traderId}", traderId).replace( + "{templateId}", + quest.templateId, + ); return quest; } -} \ No newline at end of file +} diff --git a/project/src/generators/ScavCaseRewardGenerator.ts b/project/src/generators/ScavCaseRewardGenerator.ts index bf39a911..bb130a30 100644 --- a/project/src/generators/ScavCaseRewardGenerator.ts +++ b/project/src/generators/ScavCaseRewardGenerator.ts @@ -10,7 +10,8 @@ import { ConfigTypes } from "@spt-aki/models/enums/ConfigTypes"; import { Money } from "@spt-aki/models/enums/Money"; import { IScavCaseConfig } from "@spt-aki/models/spt/config/IScavCaseConfig"; import { - RewardCountAndPriceDetails, ScavCaseRewardCountsAndPrices + RewardCountAndPriceDetails, + ScavCaseRewardCountsAndPrices, } from "@spt-aki/models/spt/hideout/ScavCaseRewardCountsAndPrices"; import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; import { ConfigServer } from "@spt-aki/servers/ConfigServer"; @@ -20,7 +21,7 @@ import { RagfairPriceService } from "@spt-aki/services/RagfairPriceService"; import { HashUtil } from "@spt-aki/utils/HashUtil"; import { RandomUtil } from "@spt-aki/utils/RandomUtil"; -/** +/** * Handle the creation of randomised scav case rewards */ @injectable() @@ -38,12 +39,12 @@ export class ScavCaseRewardGenerator @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("RagfairPriceService") protected ragfairPriceService: RagfairPriceService, @inject("ItemFilterService") protected itemFilterService: ItemFilterService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.scavCaseConfig = this.configServer.getConfig(ConfigTypes.SCAVCASE); } - + /** * Create an array of rewards that will be given to the player upon completing their scav case build * @param recipeId recipe of the scav case craft @@ -54,7 +55,7 @@ export class ScavCaseRewardGenerator this.cacheDbItems(); // Get scavcase details from hideout/scavcase.json - const scavCaseDetails = this.databaseServer.getTables().hideout.scavcase.find(r => r._id === recipeId); + const scavCaseDetails = this.databaseServer.getTables().hideout.scavcase.find((r) => r._id === recipeId); const rewardItemCounts = this.getScavCaseRewardCountsAndPrices(scavCaseDetails); // Get items that fit the price criteria as set by the scavCase config @@ -63,9 +64,17 @@ export class ScavCaseRewardGenerator const superRarePricedItems = this.getFilteredItemsByPrice(this.dbItemsCache, rewardItemCounts.Superrare); // Get randomly picked items from each item collction, the count range of which is defined in hideout/scavcase.json - const randomlyPickedCommonRewards = this.pickRandomRewards(commonPricedItems, rewardItemCounts.Common, "common"); + const randomlyPickedCommonRewards = this.pickRandomRewards( + commonPricedItems, + rewardItemCounts.Common, + "common", + ); const randomlyPickedRareRewards = this.pickRandomRewards(rarePricedItems, rewardItemCounts.Rare, "rare"); - const randomlyPickedSuperRareRewards = this.pickRandomRewards(superRarePricedItems, rewardItemCounts.Superrare, "superrare"); + const randomlyPickedSuperRareRewards = this.pickRandomRewards( + superRarePricedItems, + rewardItemCounts.Superrare, + "superrare", + ); // Add randomised stack sizes to ammo and money rewards const commonRewards = this.randomiseContainerItemRewards(randomlyPickedCommonRewards, "common"); @@ -95,11 +104,13 @@ export class ScavCaseRewardGenerator { return false; } - + // Skip item if item id is on blacklist - if ((item._type !== "Item") - || this.scavCaseConfig.rewardItemBlacklist.includes(item._id) - || this.itemFilterService.isItemBlacklisted(item._id)) + if ( + (item._type !== "Item") || + this.scavCaseConfig.rewardItemBlacklist.includes(item._id) || + this.itemFilterService.isItemBlacklisted(item._id) + ) { return false; } @@ -108,13 +119,13 @@ export class ScavCaseRewardGenerator { return false; } - + // Skip item if parent id is blacklisted if (this.itemHelper.isOfBaseclasses(item._id, this.scavCaseConfig.rewardItemParentBlacklist)) { return false; } - + return true; }); } @@ -139,13 +150,13 @@ export class ScavCaseRewardGenerator { return false; } - + // Skip ammo that doesn't stack as high as value in config if (item._props.StackMaxSize < this.scavCaseConfig.ammoRewards.minStackSize) { return false; } - + return true; }); } @@ -155,27 +166,31 @@ export class ScavCaseRewardGenerator * Pick a number of items to be rewards, the count is defined by the values in `itemFilters` param * @param items item pool to pick rewards from * @param itemFilters how the rewards should be filtered down (by item count) - * @returns + * @returns */ - protected pickRandomRewards(items: ITemplateItem[], itemFilters: RewardCountAndPriceDetails, rarity: string): ITemplateItem[] + protected pickRandomRewards( + items: ITemplateItem[], + itemFilters: RewardCountAndPriceDetails, + rarity: string, + ): ITemplateItem[] { const result: ITemplateItem[] = []; - + let rewardWasMoney = false; let rewardWasAmmo = false; const randomCount = this.randomUtil.getInt(itemFilters.minCount, itemFilters.maxCount); for (let i = 0; i < randomCount; i++) { - if (this.rewardShouldBeMoney() && !rewardWasMoney) // Only allow one reward to be money - { + if (this.rewardShouldBeMoney() && !rewardWasMoney) + { // Only allow one reward to be money result.push(this.getRandomMoney()); if (!this.scavCaseConfig.allowMultipleMoneyRewardsPerRarity) { rewardWasMoney = true; } } - else if (this.rewardShouldBeAmmo() && !rewardWasAmmo) // Only allow one reward to be ammo - { + else if (this.rewardShouldBeAmmo() && !rewardWasAmmo) + { // Only allow one reward to be ammo result.push(this.getRandomAmmo(rarity)); if (!this.scavCaseConfig.allowMultipleAmmoRewardsPerRarity) { @@ -214,10 +229,9 @@ export class ScavCaseRewardGenerator */ protected getRandomMoney(): ITemplateItem { - const money: ITemplateItem[] = []; - money.push(this.databaseServer.getTables().templates.items["5449016a4bdc2d6f028b456f"]); //rub - money.push(this.databaseServer.getTables().templates.items["569668774bdc2da2298b4568"]); //euro + money.push(this.databaseServer.getTables().templates.items["5449016a4bdc2d6f028b456f"]); // rub + money.push(this.databaseServer.getTables().templates.items["569668774bdc2da2298b4568"]); // euro money.push(this.databaseServer.getTables().templates.items["5696686a4bdc2da3298b456a"]); // dollar return this.randomUtil.getArrayValue(money); @@ -234,8 +248,10 @@ export class ScavCaseRewardGenerator { // Is ammo handbook price between desired range const handbookPrice = this.ragfairPriceService.getStaticPriceForItem(ammo._id); - if (handbookPrice >= this.scavCaseConfig.ammoRewards.ammoRewardValueRangeRub[rarity].min - && handbookPrice <= this.scavCaseConfig.ammoRewards.ammoRewardValueRangeRub[rarity].max) + if ( + handbookPrice >= this.scavCaseConfig.ammoRewards.ammoRewardValueRangeRub[rarity].min && + handbookPrice <= this.scavCaseConfig.ammoRewards.ammoRewardValueRangeRub[rarity].max + ) { return true; } @@ -266,7 +282,7 @@ export class ScavCaseRewardGenerator const resultItem = { _id: this.hashUtil.generate(), _tpl: item._id, - upd: undefined + upd: undefined, }; this.addStackCountToAmmoAndMoney(item, resultItem, rarity); @@ -288,29 +304,37 @@ export class ScavCaseRewardGenerator * @param item money or ammo item * @param resultItem money or ammo item with a randomise stack size */ - protected addStackCountToAmmoAndMoney(item: ITemplateItem, resultItem: { _id: string; _tpl: string; upd: Upd; }, rarity: string): void + protected addStackCountToAmmoAndMoney( + item: ITemplateItem, + resultItem: {_id: string; _tpl: string; upd: Upd;}, + rarity: string, + ): void { if (item._parent === BaseClasses.AMMO || item._parent === BaseClasses.MONEY) { resultItem.upd = { - StackObjectsCount: this.getRandomAmountRewardForScavCase(item, rarity) + StackObjectsCount: this.getRandomAmountRewardForScavCase(item, rarity), }; } } - + /** - * * @param dbItems all items from the items.json * @param itemFilters controls how the dbItems will be filtered and returned (handbook price) * @returns filtered dbItems array */ - protected getFilteredItemsByPrice(dbItems: ITemplateItem[], itemFilters: RewardCountAndPriceDetails): ITemplateItem[] + protected getFilteredItemsByPrice( + dbItems: ITemplateItem[], + itemFilters: RewardCountAndPriceDetails, + ): ITemplateItem[] { return dbItems.filter((item) => { const handbookPrice = this.ragfairPriceService.getStaticPriceForItem(item._id); - if (handbookPrice >= itemFilters.minPriceRub - && handbookPrice <= itemFilters.maxPriceRub) + if ( + handbookPrice >= itemFilters.minPriceRub && + handbookPrice <= itemFilters.maxPriceRub + ) { return true; } @@ -330,12 +354,11 @@ export class ScavCaseRewardGenerator // Create reward min/max counts for each type for (const rewardType of rewardTypes) { - result[rewardType] = - { + result[rewardType] = { minCount: scavCaseDetails.EndProducts[rewardType].min, maxCount: scavCaseDetails.EndProducts[rewardType].max, minPriceRub: this.scavCaseConfig.rewardItemValueRangeRub[rewardType.toLowerCase()].min, - maxPriceRub: this.scavCaseConfig.rewardItemValueRangeRub[rewardType.toLowerCase()].max + maxPriceRub: this.scavCaseConfig.rewardItemValueRangeRub[rewardType.toLowerCase()].max, }; } @@ -353,23 +376,35 @@ export class ScavCaseRewardGenerator let amountToGive = 1; if (itemToCalculate._parent === BaseClasses.AMMO) { - amountToGive = this.randomUtil.getInt(this.scavCaseConfig.ammoRewards.minStackSize, itemToCalculate._props.StackMaxSize); + amountToGive = this.randomUtil.getInt( + this.scavCaseConfig.ammoRewards.minStackSize, + itemToCalculate._props.StackMaxSize, + ); } else if (itemToCalculate._parent === BaseClasses.MONEY) { switch (itemToCalculate._id) { case Money.ROUBLES: - amountToGive = this.randomUtil.getInt(this.scavCaseConfig.moneyRewards.rubCount[rarity].min, this.scavCaseConfig.moneyRewards.rubCount[rarity].max); + amountToGive = this.randomUtil.getInt( + this.scavCaseConfig.moneyRewards.rubCount[rarity].min, + this.scavCaseConfig.moneyRewards.rubCount[rarity].max, + ); break; case Money.EUROS: - amountToGive = this.randomUtil.getInt(this.scavCaseConfig.moneyRewards.eurCount[rarity].min, this.scavCaseConfig.moneyRewards.eurCount[rarity].max); + amountToGive = this.randomUtil.getInt( + this.scavCaseConfig.moneyRewards.eurCount[rarity].min, + this.scavCaseConfig.moneyRewards.eurCount[rarity].max, + ); break; case Money.DOLLARS: - amountToGive = this.randomUtil.getInt(this.scavCaseConfig.moneyRewards.usdCount[rarity].min, this.scavCaseConfig.moneyRewards.usdCount[rarity].max); + amountToGive = this.randomUtil.getInt( + this.scavCaseConfig.moneyRewards.usdCount[rarity].min, + this.scavCaseConfig.moneyRewards.usdCount[rarity].max, + ); break; } } return amountToGive; } -} \ No newline at end of file +} diff --git a/project/src/generators/WeatherGenerator.ts b/project/src/generators/WeatherGenerator.ts index 52c8f49b..80288400 100644 --- a/project/src/generators/WeatherGenerator.ts +++ b/project/src/generators/WeatherGenerator.ts @@ -23,7 +23,7 @@ export class WeatherGenerator @inject("RandomUtil") protected randomUtil: RandomUtil, @inject("TimeUtil") protected timeUtil: TimeUtil, @inject("ApplicationContext") protected applicationContext: ApplicationContext, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.weatherConfig = this.configServer.getConfig(ConfigTypes.WEATHER); @@ -62,16 +62,17 @@ export class WeatherGenerator /** * Get the current in-raid time * @param currentDate (new Date()) - * @returns Date object of current in-raid time + * @returns Date object of current in-raid time */ public getInRaidTime(currentDate: Date): Date { // Get timestamp of when client conneted to server - const gameStartTimeStampMS = this.applicationContext.getLatestValue(ContextVariableType.CLIENT_START_TIMESTAMP).getValue(); + const gameStartTimeStampMS = this.applicationContext.getLatestValue(ContextVariableType.CLIENT_START_TIMESTAMP) + .getValue(); // Get delta between now and when client connected to server in milliseconds - const deltaMSFromNow = (Date.now() - gameStartTimeStampMS); - const acceleratedMS = (deltaMSFromNow * (this.weatherConfig.acceleration - 1)); // For some reason nodejs moves faster than client time, reducing acceleration by 1 when client is 7 helps + const deltaMSFromNow = Date.now() - gameStartTimeStampMS; + const acceleratedMS = deltaMSFromNow * (this.weatherConfig.acceleration - 1); // For some reason nodejs moves faster than client time, reducing acceleration by 1 when client is 7 helps const clientAcceleratedDate = new Date(currentDate.valueOf() + acceleratedMS); return clientAcceleratedDate; @@ -105,15 +106,15 @@ export class WeatherGenerator wind_gustiness: this.getRandomFloat("windGustiness"), rain: rain, // eslint-disable-next-line @typescript-eslint/naming-convention - rain_intensity: (rain > 1) - ? this.getRandomFloat("rainIntensity") - : 0, + rain_intensity: (rain > 1) ? + this.getRandomFloat("rainIntensity") : + 0, fog: this.getWeightedFog(), temp: this.getRandomFloat("temp"), pressure: this.getRandomFloat("pressure"), time: "", date: "", - timestamp: 0 + timestamp: 0, }; this.setCurrentDateTime(result); @@ -139,32 +140,49 @@ export class WeatherGenerator protected getWeightedWindDirection(): WindDirection { - return this.weightedRandomHelper.weightedRandom(this.weatherConfig.weather.windDirection.values, this.weatherConfig.weather.windDirection.weights).item; + return this.weightedRandomHelper.weightedRandom( + this.weatherConfig.weather.windDirection.values, + this.weatherConfig.weather.windDirection.weights, + ).item; } protected getWeightedClouds(): number { - return this.weightedRandomHelper.weightedRandom(this.weatherConfig.weather.clouds.values, this.weatherConfig.weather.clouds.weights).item; + return this.weightedRandomHelper.weightedRandom( + this.weatherConfig.weather.clouds.values, + this.weatherConfig.weather.clouds.weights, + ).item; } protected getWeightedWindSpeed(): number { - return this.weightedRandomHelper.weightedRandom(this.weatherConfig.weather.windSpeed.values, this.weatherConfig.weather.windSpeed.weights).item; + return this.weightedRandomHelper.weightedRandom( + this.weatherConfig.weather.windSpeed.values, + this.weatherConfig.weather.windSpeed.weights, + ).item; } protected getWeightedFog(): number { - return this.weightedRandomHelper.weightedRandom(this.weatherConfig.weather.fog.values, this.weatherConfig.weather.fog.weights).item; + return this.weightedRandomHelper.weightedRandom( + this.weatherConfig.weather.fog.values, + this.weatherConfig.weather.fog.weights, + ).item; } protected getWeightedRain(): number { - return this.weightedRandomHelper.weightedRandom(this.weatherConfig.weather.rain.values, this.weatherConfig.weather.rain.weights).item; + return this.weightedRandomHelper.weightedRandom( + this.weatherConfig.weather.rain.values, + this.weatherConfig.weather.rain.weights, + ).item; } protected getRandomFloat(node: string): number { - return parseFloat(this.randomUtil.getFloat(this.weatherConfig.weather[node].min, - this.weatherConfig.weather[node].max).toPrecision(3)); + return parseFloat( + this.randomUtil.getFloat(this.weatherConfig.weather[node].min, this.weatherConfig.weather[node].max) + .toPrecision(3), + ); } -} \ No newline at end of file +} diff --git a/project/src/generators/weapongen/IInventoryMagGen.ts b/project/src/generators/weapongen/IInventoryMagGen.ts index ac710ae1..86a1becb 100644 --- a/project/src/generators/weapongen/IInventoryMagGen.ts +++ b/project/src/generators/weapongen/IInventoryMagGen.ts @@ -5,4 +5,4 @@ export interface IInventoryMagGen getPriority(): number; canHandleInventoryMagGen(inventoryMagGen: InventoryMagGen): boolean; process(inventoryMagGen: InventoryMagGen): void; -} \ No newline at end of file +} diff --git a/project/src/generators/weapongen/InventoryMagGen.ts b/project/src/generators/weapongen/InventoryMagGen.ts index 5584b747..21ae076f 100644 --- a/project/src/generators/weapongen/InventoryMagGen.ts +++ b/project/src/generators/weapongen/InventoryMagGen.ts @@ -2,40 +2,39 @@ import { Inventory } from "@spt-aki/models/eft/common/tables/IBotBase"; import { GenerationData } from "@spt-aki/models/eft/common/tables/IBotType"; import { ITemplateItem } from "@spt-aki/models/eft/common/tables/ITemplateItem"; -export class InventoryMagGen +export class InventoryMagGen { constructor( private magCounts: GenerationData, private magazineTemplate: ITemplateItem, private weaponTemplate: ITemplateItem, private ammoTemplate: ITemplateItem, - private pmcInventory: Inventory - ) - { - } + private pmcInventory: Inventory, + ) + {} - public getMagCount(): GenerationData + public getMagCount(): GenerationData { return this.magCounts; } - public getMagazineTemplate(): ITemplateItem + public getMagazineTemplate(): ITemplateItem { return this.magazineTemplate; } - public getWeaponTemplate(): ITemplateItem + public getWeaponTemplate(): ITemplateItem { return this.weaponTemplate; } - public getAmmoTemplate(): ITemplateItem + public getAmmoTemplate(): ITemplateItem { return this.ammoTemplate; } - public getPmcInventory(): Inventory + public getPmcInventory(): Inventory { return this.pmcInventory; } -} \ No newline at end of file +} diff --git a/project/src/generators/weapongen/implementations/BarrelInventoryMagGen.ts b/project/src/generators/weapongen/implementations/BarrelInventoryMagGen.ts index 83fb5fd5..2628d5f5 100644 --- a/project/src/generators/weapongen/implementations/BarrelInventoryMagGen.ts +++ b/project/src/generators/weapongen/implementations/BarrelInventoryMagGen.ts @@ -8,36 +8,43 @@ import { RandomUtil } from "@spt-aki/utils/RandomUtil"; @injectable() export class BarrelInventoryMagGen implements IInventoryMagGen { - constructor( @inject("RandomUtil") protected randomUtil: RandomUtil, - @inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper + @inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper, ) - { } + {} - getPriority(): number + getPriority(): number { return 50; } - canHandleInventoryMagGen(inventoryMagGen: InventoryMagGen): boolean + canHandleInventoryMagGen(inventoryMagGen: InventoryMagGen): boolean { return inventoryMagGen.getWeaponTemplate()._props.ReloadMode === "OnlyBarrel"; } - - process(inventoryMagGen: InventoryMagGen): void + + process(inventoryMagGen: InventoryMagGen): void { // Can't be done by _props.ammoType as grenade launcher shoots grenades with ammoType of "buckshot" let randomisedAmmoStackSize: number; - if (inventoryMagGen.getAmmoTemplate()._props.StackMaxRandom === 1) // doesnt stack + if (inventoryMagGen.getAmmoTemplate()._props.StackMaxRandom === 1) { + // doesnt stack randomisedAmmoStackSize = this.randomUtil.getInt(3, 6); } else { - randomisedAmmoStackSize = this.randomUtil.getInt(inventoryMagGen.getAmmoTemplate()._props.StackMinRandom, inventoryMagGen.getAmmoTemplate()._props.StackMaxRandom); + randomisedAmmoStackSize = this.randomUtil.getInt( + inventoryMagGen.getAmmoTemplate()._props.StackMinRandom, + inventoryMagGen.getAmmoTemplate()._props.StackMaxRandom, + ); } - this.botWeaponGeneratorHelper.addAmmoIntoEquipmentSlots(inventoryMagGen.getAmmoTemplate()._id, randomisedAmmoStackSize, inventoryMagGen.getPmcInventory()); + this.botWeaponGeneratorHelper.addAmmoIntoEquipmentSlots( + inventoryMagGen.getAmmoTemplate()._id, + randomisedAmmoStackSize, + inventoryMagGen.getPmcInventory(), + ); } -} \ No newline at end of file +} diff --git a/project/src/generators/weapongen/implementations/ExternalInventoryMagGen.ts b/project/src/generators/weapongen/implementations/ExternalInventoryMagGen.ts index e5d2bda7..11f06b55 100644 --- a/project/src/generators/weapongen/implementations/ExternalInventoryMagGen.ts +++ b/project/src/generators/weapongen/implementations/ExternalInventoryMagGen.ts @@ -12,60 +12,71 @@ import { LocalisationService } from "@spt-aki/services/LocalisationService"; @injectable() export class ExternalInventoryMagGen implements IInventoryMagGen { - constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("ItemHelper") protected itemHelper: ItemHelper, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper + @inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper, ) - { } + {} - getPriority(): number + getPriority(): number { return 99; } - - // eslint-disable-next-line @typescript-eslint/no-unused-vars - canHandleInventoryMagGen(inventoryMagGen: InventoryMagGen): boolean + + canHandleInventoryMagGen(inventoryMagGen: InventoryMagGen): boolean { return true; // Fallback, if code reaches here it means no other implementation can handle this type of magazine } - process(inventoryMagGen: InventoryMagGen): void + process(inventoryMagGen: InventoryMagGen): void { let magTemplate = inventoryMagGen.getMagazineTemplate(); let magazineTpl = magTemplate._id; - const randomizedMagazineCount = Number(this.botWeaponGeneratorHelper.getRandomizedMagazineCount(inventoryMagGen.getMagCount())); + const randomizedMagazineCount = Number( + this.botWeaponGeneratorHelper.getRandomizedMagazineCount(inventoryMagGen.getMagCount()), + ); for (let i = 0; i < randomizedMagazineCount; i++) { - const magazineWithAmmo = this.botWeaponGeneratorHelper.createMagazineWithAmmo(magazineTpl, inventoryMagGen.getAmmoTemplate()._id, magTemplate); + const magazineWithAmmo = this.botWeaponGeneratorHelper.createMagazineWithAmmo( + magazineTpl, + inventoryMagGen.getAmmoTemplate()._id, + magTemplate, + ); const ableToFitMagazinesIntoBotInventory = this.botWeaponGeneratorHelper.addItemWithChildrenToEquipmentSlot( [EquipmentSlots.TACTICAL_VEST, EquipmentSlots.POCKETS], magazineWithAmmo[0]._id, magazineTpl, magazineWithAmmo, - inventoryMagGen.getPmcInventory()); + inventoryMagGen.getPmcInventory(), + ); if (ableToFitMagazinesIntoBotInventory === ItemAddedResult.NO_SPACE && i < randomizedMagazineCount) { - /* We were unable to fit at least the minimum amount of magazines, - * so we fallback to default magazine and try again. - * Temporary workaround to Killa spawning with no extras if he spawns with a drum mag */ - - if (magazineTpl === this.botWeaponGeneratorHelper.getWeaponsDefaultMagazineTpl(inventoryMagGen.getWeaponTemplate())) + // We were unable to fit at least the minimum amount of magazines, so we fallback to default magazine + // and try again. Temporary workaround to Killa spawning with no extras if he spawns with a drum mag. + // TODO: Fix this properly + if ( + magazineTpl === + this.botWeaponGeneratorHelper.getWeaponsDefaultMagazineTpl(inventoryMagGen.getWeaponTemplate()) + ) { // We were already on default - stop here to prevent infinite looping break; } // Get default magazine tpl, reset loop counter by 1 and try again - magazineTpl = this.botWeaponGeneratorHelper.getWeaponsDefaultMagazineTpl(inventoryMagGen.getWeaponTemplate()); + magazineTpl = this.botWeaponGeneratorHelper.getWeaponsDefaultMagazineTpl( + inventoryMagGen.getWeaponTemplate(), + ); magTemplate = this.itemHelper.getItem(magazineTpl)[1]; if (!magTemplate) { - this.logger.error(this.localisationService.getText("bot-unable_to_find_default_magazine_item", magazineTpl)); + this.logger.error( + this.localisationService.getText("bot-unable_to_find_default_magazine_item", magazineTpl), + ); break; } @@ -78,5 +89,4 @@ export class ExternalInventoryMagGen implements IInventoryMagGen } } } - -} \ No newline at end of file +} diff --git a/project/src/generators/weapongen/implementations/InternalMagazineInventoryMagGen.ts b/project/src/generators/weapongen/implementations/InternalMagazineInventoryMagGen.ts index 9840dae9..800013bd 100644 --- a/project/src/generators/weapongen/implementations/InternalMagazineInventoryMagGen.ts +++ b/project/src/generators/weapongen/implementations/InternalMagazineInventoryMagGen.ts @@ -7,25 +7,31 @@ import { BotWeaponGeneratorHelper } from "@spt-aki/helpers/BotWeaponGeneratorHel @injectable() export class InternalMagazineInventoryMagGen implements IInventoryMagGen { - constructor( - @inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper + @inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper, ) - { } + {} - public getPriority(): number + public getPriority(): number { return 0; } - public canHandleInventoryMagGen(inventoryMagGen: InventoryMagGen): boolean + public canHandleInventoryMagGen(inventoryMagGen: InventoryMagGen): boolean { return inventoryMagGen.getMagazineTemplate()._props.ReloadMagType === "InternalMagazine"; } - public process(inventoryMagGen: InventoryMagGen): void + public process(inventoryMagGen: InventoryMagGen): void { - const bulletCount = this.botWeaponGeneratorHelper.getRandomizedBulletCount(inventoryMagGen.getMagCount(), inventoryMagGen.getMagazineTemplate()); - this.botWeaponGeneratorHelper.addAmmoIntoEquipmentSlots(inventoryMagGen.getAmmoTemplate()._id, bulletCount, inventoryMagGen.getPmcInventory()); + const bulletCount = this.botWeaponGeneratorHelper.getRandomizedBulletCount( + inventoryMagGen.getMagCount(), + inventoryMagGen.getMagazineTemplate(), + ); + this.botWeaponGeneratorHelper.addAmmoIntoEquipmentSlots( + inventoryMagGen.getAmmoTemplate()._id, + bulletCount, + inventoryMagGen.getPmcInventory(), + ); } -} \ No newline at end of file +} diff --git a/project/src/generators/weapongen/implementations/UbglExternalMagGen.ts b/project/src/generators/weapongen/implementations/UbglExternalMagGen.ts index cb050c60..1821eafc 100644 --- a/project/src/generators/weapongen/implementations/UbglExternalMagGen.ts +++ b/project/src/generators/weapongen/implementations/UbglExternalMagGen.ts @@ -9,25 +9,32 @@ import { EquipmentSlots } from "@spt-aki/models/enums/EquipmentSlots"; @injectable() export class UbglExternalMagGen implements IInventoryMagGen { - constructor( - @inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper + @inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper, ) - { } + {} - public getPriority(): number + public getPriority(): number { return 1; } - public canHandleInventoryMagGen(inventoryMagGen: InventoryMagGen): boolean + public canHandleInventoryMagGen(inventoryMagGen: InventoryMagGen): boolean { return inventoryMagGen.getWeaponTemplate()._parent === BaseClasses.UBGL; } - public process(inventoryMagGen: InventoryMagGen): void + public process(inventoryMagGen: InventoryMagGen): void { - const bulletCount = this.botWeaponGeneratorHelper.getRandomizedBulletCount(inventoryMagGen.getMagCount(), inventoryMagGen.getMagazineTemplate()); - this.botWeaponGeneratorHelper.addAmmoIntoEquipmentSlots(inventoryMagGen.getAmmoTemplate()._id, bulletCount, inventoryMagGen.getPmcInventory(), [EquipmentSlots.TACTICAL_VEST]); + const bulletCount = this.botWeaponGeneratorHelper.getRandomizedBulletCount( + inventoryMagGen.getMagCount(), + inventoryMagGen.getMagazineTemplate(), + ); + this.botWeaponGeneratorHelper.addAmmoIntoEquipmentSlots( + inventoryMagGen.getAmmoTemplate()._id, + bulletCount, + inventoryMagGen.getPmcInventory(), + [EquipmentSlots.TACTICAL_VEST], + ); } -} \ No newline at end of file +} From 8586447d21e9b4d5db59eb9a32c8d540a69adba8 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:07:59 -0500 Subject: [PATCH 27/41] Formatting for helper classes. --- project/src/helpers/AssortHelper.ts | 31 +- project/src/helpers/BotDifficultyHelper.ts | 46 ++- project/src/helpers/BotGeneratorHelper.ts | 247 ++++++++----- project/src/helpers/BotHelper.ts | 32 +- .../src/helpers/BotWeaponGeneratorHelper.ts | 63 +++- project/src/helpers/ContainerHelper.ts | 23 +- project/src/helpers/DialogueHelper.ts | 58 ++- project/src/helpers/DurabilityLimitsHelper.ts | 28 +- project/src/helpers/GameEventHelper.ts | 5 +- project/src/helpers/HandbookHelper.ts | 12 +- project/src/helpers/HealthHelper.ts | 56 ++- project/src/helpers/HideoutHelper.ts | 274 +++++++++----- project/src/helpers/HttpServerHelper.ts | 8 +- project/src/helpers/InRaidHelper.ts | 85 +++-- project/src/helpers/InventoryHelper.ts | 341 ++++++++++++------ project/src/helpers/ItemHelper.ts | 131 ++++--- project/src/helpers/NotificationSendHelper.ts | 25 +- project/src/helpers/NotifierHelper.ts | 21 +- project/src/helpers/PaymentHelper.ts | 16 +- project/src/helpers/PresetHelper.ts | 8 +- project/src/helpers/ProbabilityHelper.ts | 8 +- project/src/helpers/ProfileHelper.ts | 79 ++-- project/src/helpers/QuestConditionHelper.ts | 31 +- project/src/helpers/QuestHelper.ts | 236 ++++++++---- project/src/helpers/RagfairHelper.ts | 18 +- project/src/helpers/RagfairOfferHelper.ts | 108 ++++-- project/src/helpers/RagfairSellHelper.ts | 45 ++- project/src/helpers/RagfairServerHelper.ts | 34 +- project/src/helpers/RagfairSortHelper.ts | 18 +- project/src/helpers/RepairHelper.ts | 71 ++-- project/src/helpers/RepeatableQuestHelper.ts | 17 +- project/src/helpers/SecureContainerHelper.ts | 17 +- project/src/helpers/TradeHelper.ts | 37 +- project/src/helpers/TraderAssortHelper.ts | 36 +- project/src/helpers/TraderHelper.ts | 94 ++--- project/src/helpers/UtilityHelper.ts | 4 +- project/src/helpers/WeightedRandomHelper.ts | 10 +- 37 files changed, 1533 insertions(+), 840 deletions(-) diff --git a/project/src/helpers/AssortHelper.ts b/project/src/helpers/AssortHelper.ts index 43ac41bb..04148c2c 100644 --- a/project/src/helpers/AssortHelper.ts +++ b/project/src/helpers/AssortHelper.ts @@ -12,25 +12,30 @@ import { LocalisationService } from "@spt-aki/services/LocalisationService"; @injectable() export class AssortHelper { - constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("ItemHelper") protected itemHelper: ItemHelper, @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("QuestHelper") protected questHelper: QuestHelper + @inject("QuestHelper") protected questHelper: QuestHelper, ) - { } + {} /** - * Remove assorts from a trader that have not been unlocked yet (via player completing corrisponding quest) + * Remove assorts from a trader that have not been unlocked yet (via player completing corresponding quest) * @param pmcProfile Player profile * @param traderId Traders id the assort belongs to * @param traderAssorts All assort items from same trader * @param mergedQuestAssorts Dict of quest assort to quest id unlocks for all traders (key = started/failed/complete) * @returns Assort items minus locked quest assorts */ - public stripLockedQuestAssort(pmcProfile: IPmcData, traderId: string, traderAssorts: ITraderAssort, mergedQuestAssorts: Record>, flea = false): ITraderAssort + public stripLockedQuestAssort( + pmcProfile: IPmcData, + traderId: string, + traderAssorts: ITraderAssort, + mergedQuestAssorts: Record>, + flea = false, + ): ITraderAssort { // Trader assort does not always contain loyal_level_items if (!traderAssorts.loyal_level_items) @@ -67,20 +72,26 @@ export class AssortHelper * @param assortId Assort to look for linked quest id * @returns quest id + array of quest status the assort should show for */ - protected getQuestIdAndStatusThatShowAssort(mergedQuestAssorts: Record>, assortId: string): { questId: string; status: QuestStatus[]; } + protected getQuestIdAndStatusThatShowAssort( + mergedQuestAssorts: Record>, + assortId: string, + ): {questId: string; status: QuestStatus[];} { if (assortId in mergedQuestAssorts.started) { // Assort unlocked by starting quest, assort is visible to player when : started or ready to hand in + handed in - return { questId: mergedQuestAssorts.started[assortId], status: [QuestStatus.Started, QuestStatus.AvailableForFinish, QuestStatus.Success]}; + return { + questId: mergedQuestAssorts.started[assortId], + status: [QuestStatus.Started, QuestStatus.AvailableForFinish, QuestStatus.Success], + }; } else if (assortId in mergedQuestAssorts.success) { - return { questId: mergedQuestAssorts.success[assortId], status: [QuestStatus.Success]}; + return {questId: mergedQuestAssorts.success[assortId], status: [QuestStatus.Success]}; } else if (assortId in mergedQuestAssorts.fail) { - return { questId: mergedQuestAssorts.fail[assortId], status: [QuestStatus.Fail]}; + return {questId: mergedQuestAssorts.fail[assortId], status: [QuestStatus.Fail]}; } return undefined; @@ -152,4 +163,4 @@ export class AssortHelper return assort; } -} \ No newline at end of file +} diff --git a/project/src/helpers/BotDifficultyHelper.ts b/project/src/helpers/BotDifficultyHelper.ts index 83688c7e..59c4a9bb 100644 --- a/project/src/helpers/BotDifficultyHelper.ts +++ b/project/src/helpers/BotDifficultyHelper.ts @@ -23,22 +23,27 @@ export class BotDifficultyHelper @inject("RandomUtil") protected randomUtil: RandomUtil, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("BotHelper") protected botHelper: BotHelper, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.pmcConfig = this.configServer.getConfig(ConfigTypes.PMC); } - public getPmcDifficultySettings(pmcType: "bear"|"usec", difficulty: string, usecType: string, bearType: string): Difficulty + public getPmcDifficultySettings( + pmcType: "bear" | "usec", + difficulty: string, + usecType: string, + bearType: string, + ): Difficulty { const difficultySettings = this.getDifficultySettings(pmcType, difficulty); - const friendlyType = pmcType === "bear" - ? bearType - : usecType; - const enemyType = pmcType === "bear" - ? usecType - : bearType; + const friendlyType = pmcType === "bear" ? + bearType : + usecType; + const enemyType = pmcType === "bear" ? + usecType : + bearType; this.botHelper.addBotToEnemyList(difficultySettings, this.pmcConfig.enemyTypes, friendlyType); // Add generic bot types to enemy list this.botHelper.addBotToEnemyList(difficultySettings, [enemyType, friendlyType], ""); // add same/opposite side to enemy list @@ -61,14 +66,23 @@ export class BotDifficultyHelper { // get fallback this.logger.warning(this.localisationService.getText("bot-unable_to_get_bot_fallback_to_assault", type)); - this.databaseServer.getTables().bots.types[type] = this.jsonUtil.clone(this.databaseServer.getTables().bots.types.assault); + this.databaseServer.getTables().bots.types[type] = this.jsonUtil.clone( + this.databaseServer.getTables().bots.types.assault, + ); } const difficultySettings = this.botHelper.getBotTemplate(type).difficulty[difficulty]; if (!difficultySettings) { - this.logger.warning(this.localisationService.getText("bot-unable_to_get_bot_difficulty_fallback_to_assault", {botType: type, difficulty: difficulty})); - this.databaseServer.getTables().bots.types[type].difficulty[difficulty] = this.jsonUtil.clone(this.databaseServer.getTables().bots.types.assault.difficulty[difficulty]); + this.logger.warning( + this.localisationService.getText("bot-unable_to_get_bot_difficulty_fallback_to_assault", { + botType: type, + difficulty: difficulty, + }), + ); + this.databaseServer.getTables().bots.types[type].difficulty[difficulty] = this.jsonUtil.clone( + this.databaseServer.getTables().bots.types.assault.difficulty[difficulty], + ); } return this.jsonUtil.clone(difficultySettings); @@ -77,14 +91,14 @@ export class BotDifficultyHelper /** * Get difficulty settings for a PMC * @param type "usec" / "bear" - * @param difficulty what difficulty to retrieve + * @param difficulty what difficulty to retrieve * @returns Difficulty object */ protected getDifficultySettings(type: string, difficulty: string): Difficulty { - let difficultySetting = this.pmcConfig.difficulty.toLowerCase() === "asonline" - ? difficulty - : this.pmcConfig.difficulty.toLowerCase(); + let difficultySetting = this.pmcConfig.difficulty.toLowerCase() === "asonline" ? + difficulty : + this.pmcConfig.difficulty.toLowerCase(); difficultySetting = this.convertBotDifficultyDropdownToBotDifficulty(difficultySetting); @@ -117,4 +131,4 @@ export class BotDifficultyHelper { return this.randomUtil.getArrayValue(["easy", "normal", "hard", "impossible"]); } -} \ No newline at end of file +} diff --git a/project/src/helpers/BotGeneratorHelper.ts b/project/src/helpers/BotGeneratorHelper.ts index 21ae5ade..eab60729 100644 --- a/project/src/helpers/BotGeneratorHelper.ts +++ b/project/src/helpers/BotGeneratorHelper.ts @@ -19,7 +19,7 @@ import { JsonUtil } from "@spt-aki/utils/JsonUtil"; import { RandomUtil } from "@spt-aki/utils/RandomUtil"; @injectable() -export class BotGeneratorHelper +export class BotGeneratorHelper { protected botConfig: IBotConfig; protected pmcConfig: IPmcConfig; @@ -32,8 +32,8 @@ export class BotGeneratorHelper @inject("ItemHelper") protected itemHelper: ItemHelper, @inject("ApplicationContext") protected applicationContext: ApplicationContext, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer - ) + @inject("ConfigServer") protected configServer: ConfigServer, + ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); this.pmcConfig = this.configServer.getConfig(ConfigTypes.PMC); @@ -46,93 +46,113 @@ export class BotGeneratorHelper * @param botRole Used by weapons to randomize the durability values. Null for non-equipped items * @returns Item Upd object with extra properties */ - public generateExtraPropertiesForItem(itemTemplate: ITemplateItem, botRole?: string): { upd?: Upd } + public generateExtraPropertiesForItem(itemTemplate: ITemplateItem, botRole?: string): {upd?: Upd;} { // Get raid settings, if no raid, default to day - const raidSettings = this.applicationContext.getLatestValue(ContextVariableType.RAID_CONFIGURATION)?.getValue(); + const raidSettings = this.applicationContext.getLatestValue(ContextVariableType.RAID_CONFIGURATION)?.getValue< + IGetRaidConfigurationRequestData + >(); const raidIsNight = raidSettings?.timeVariant === "PAST"; const itemProperties: Upd = {}; - if (itemTemplate._props.MaxDurability) + if (itemTemplate._props.MaxDurability) { - if (itemTemplate._props.weapClass) // Is weapon - { + if (itemTemplate._props.weapClass) + { // Is weapon itemProperties.Repairable = this.generateWeaponRepairableProperties(itemTemplate, botRole); } - else if (itemTemplate._props.armorClass) // Is armor - { + else if (itemTemplate._props.armorClass) + { // Is armor itemProperties.Repairable = this.generateArmorRepairableProperties(itemTemplate, botRole); } } - if (itemTemplate._props.HasHinge) + if (itemTemplate._props.HasHinge) { - itemProperties.Togglable = { On: true }; + itemProperties.Togglable = {On: true}; } - if (itemTemplate._props.Foldable) + if (itemTemplate._props.Foldable) { - itemProperties.Foldable = { Folded: false }; + itemProperties.Foldable = {Folded: false}; } - if (itemTemplate._props.weapFireType?.length) + if (itemTemplate._props.weapFireType?.length) { - if (itemTemplate._props.weapFireType.includes("fullauto")) + if (itemTemplate._props.weapFireType.includes("fullauto")) { - itemProperties.FireMode = { FireMode: "fullauto" }; + itemProperties.FireMode = {FireMode: "fullauto"}; } - else + else { - itemProperties.FireMode = { FireMode: this.randomUtil.getArrayValue(itemTemplate._props.weapFireType) }; + itemProperties.FireMode = {FireMode: this.randomUtil.getArrayValue(itemTemplate._props.weapFireType)}; } } - if (itemTemplate._props.MaxHpResource) + if (itemTemplate._props.MaxHpResource) { - itemProperties.MedKit = { HpResource: this.getRandomizedResourceValue(itemTemplate._props.MaxHpResource, this.botConfig.lootItemResourceRandomization[botRole]?.meds) }; + itemProperties.MedKit = { + HpResource: this.getRandomizedResourceValue( + itemTemplate._props.MaxHpResource, + this.botConfig.lootItemResourceRandomization[botRole]?.meds, + ), + }; } - if (itemTemplate._props.MaxResource && itemTemplate._props.foodUseTime) + if (itemTemplate._props.MaxResource && itemTemplate._props.foodUseTime) { - itemProperties.FoodDrink = { HpPercent: this.getRandomizedResourceValue(itemTemplate._props.MaxResource, this.botConfig.lootItemResourceRandomization[botRole]?.food) }; + itemProperties.FoodDrink = { + HpPercent: this.getRandomizedResourceValue( + itemTemplate._props.MaxResource, + this.botConfig.lootItemResourceRandomization[botRole]?.food, + ), + }; } if (itemTemplate._parent === BaseClasses.FLASHLIGHT) { // Get chance from botconfig for bot type - const lightLaserActiveChance = raidIsNight - ? this.getBotEquipmentSettingFromConfig(botRole, "lightIsActiveNightChancePercent", 50) - : this.getBotEquipmentSettingFromConfig(botRole, "lightIsActiveDayChancePercent", 25); - itemProperties.Light = { IsActive: (this.randomUtil.getChance100(lightLaserActiveChance)), SelectedMode: 0 }; + const lightLaserActiveChance = raidIsNight ? + this.getBotEquipmentSettingFromConfig(botRole, "lightIsActiveNightChancePercent", 50) : + this.getBotEquipmentSettingFromConfig(botRole, "lightIsActiveDayChancePercent", 25); + itemProperties.Light = {IsActive: (this.randomUtil.getChance100(lightLaserActiveChance)), SelectedMode: 0}; } else if (itemTemplate._parent === BaseClasses.TACTICAL_COMBO) { // Get chance from botconfig for bot type, use 50% if no value found - const lightLaserActiveChance = this.getBotEquipmentSettingFromConfig(botRole, "laserIsActiveChancePercent", 50); - itemProperties.Light = { IsActive: (this.randomUtil.getChance100(lightLaserActiveChance)), SelectedMode: 0 }; + const lightLaserActiveChance = this.getBotEquipmentSettingFromConfig( + botRole, + "laserIsActiveChancePercent", + 50, + ); + itemProperties.Light = {IsActive: (this.randomUtil.getChance100(lightLaserActiveChance)), SelectedMode: 0}; } - if (itemTemplate._parent === BaseClasses.NIGHTVISION) + if (itemTemplate._parent === BaseClasses.NIGHTVISION) { // Get chance from botconfig for bot type - const nvgActiveChance = raidIsNight - ? this.getBotEquipmentSettingFromConfig(botRole, "nvgIsActiveChanceNightPercent", 90) - : this.getBotEquipmentSettingFromConfig(botRole, "nvgIsActiveChanceDayPercent", 15); - itemProperties.Togglable = { On: (this.randomUtil.getChance100(nvgActiveChance)) }; + const nvgActiveChance = raidIsNight ? + this.getBotEquipmentSettingFromConfig(botRole, "nvgIsActiveChanceNightPercent", 90) : + this.getBotEquipmentSettingFromConfig(botRole, "nvgIsActiveChanceDayPercent", 15); + itemProperties.Togglable = {On: (this.randomUtil.getChance100(nvgActiveChance))}; } // Togglable face shield - if (itemTemplate._props.HasHinge && itemTemplate._props.FaceShieldComponent) + if (itemTemplate._props.HasHinge && itemTemplate._props.FaceShieldComponent) { // Get chance from botconfig for bot type, use 75% if no value found - const faceShieldActiveChance = this.getBotEquipmentSettingFromConfig(botRole, "faceShieldIsActiveChancePercent", 75); - itemProperties.Togglable = { On: (this.randomUtil.getChance100(faceShieldActiveChance)) }; + const faceShieldActiveChance = this.getBotEquipmentSettingFromConfig( + botRole, + "faceShieldIsActiveChancePercent", + 75, + ); + itemProperties.Togglable = {On: (this.randomUtil.getChance100(faceShieldActiveChance))}; } - return Object.keys(itemProperties).length - ? { upd: itemProperties } - : {}; + return Object.keys(itemProperties).length ? + {upd: itemProperties} : + {}; } /** @@ -153,8 +173,10 @@ export class BotGeneratorHelper return maxResource; } - return this.randomUtil.getInt(this.randomUtil.getPercentOfValue(randomizationValues.resourcePercent, maxResource, 0), maxResource); - + return this.randomUtil.getInt( + this.randomUtil.getPercentOfValue(randomizationValues.resourcePercent, maxResource, 0), + maxResource, + ); } /** @@ -164,22 +186,38 @@ export class BotGeneratorHelper * @param defaultValue default value for the chance of activation if the botrole or bot equipment role is null * @returns Percent chance to be active */ - protected getBotEquipmentSettingFromConfig(botRole: string, setting: keyof EquipmentFilters, defaultValue: number): number + protected getBotEquipmentSettingFromConfig( + botRole: string, + setting: keyof EquipmentFilters, + defaultValue: number, + ): number { - if (!botRole) + if (!botRole) { return defaultValue; } const botEquipmentSettings = this.botConfig.equipment[this.getBotEquipmentRole(botRole)]; if (!botEquipmentSettings) { - this.logger.warning(this.localisationService.getText("bot-missing_equipment_settings", {botRole: botRole, setting: setting, defaultValue: defaultValue})); + this.logger.warning( + this.localisationService.getText("bot-missing_equipment_settings", { + botRole: botRole, + setting: setting, + defaultValue: defaultValue, + }), + ); return defaultValue; } - if (botEquipmentSettings[setting] === undefined || typeof botEquipmentSettings[setting] !== "number") + if (botEquipmentSettings[setting] === undefined || typeof botEquipmentSettings[setting] !== "number") { - this.logger.warning(this.localisationService.getText("bot-missing_equipment_settings_property", {botRole: botRole, setting: setting, defaultValue: defaultValue})); + this.logger.warning( + this.localisationService.getText("bot-missing_equipment_settings_property", { + botRole: botRole, + setting: setting, + defaultValue: defaultValue, + }), + ); return defaultValue; } @@ -193,14 +231,18 @@ export class BotGeneratorHelper * @param botRole type of bot being generated for * @returns Repairable object */ - protected generateWeaponRepairableProperties(itemTemplate: ITemplateItem, botRole: string): Repairable + protected generateWeaponRepairableProperties(itemTemplate: ITemplateItem, botRole: string): Repairable { const maxDurability = this.durabilityLimitsHelper.getRandomizedMaxWeaponDurability(itemTemplate, botRole); - const currentDurability = this.durabilityLimitsHelper.getRandomizedWeaponDurability(itemTemplate, botRole, maxDurability); + const currentDurability = this.durabilityLimitsHelper.getRandomizedWeaponDurability( + itemTemplate, + botRole, + maxDurability, + ); return { Durability: currentDurability, - MaxDurability: maxDurability + MaxDurability: maxDurability, }; } @@ -210,7 +252,7 @@ export class BotGeneratorHelper * @param botRole type of bot being generated for * @returns Repairable object */ - protected generateArmorRepairableProperties(itemTemplate: ITemplateItem, botRole: string): Repairable + protected generateArmorRepairableProperties(itemTemplate: ITemplateItem, botRole: string): Repairable { let maxDurability: number; let currentDurability: number; @@ -219,15 +261,19 @@ export class BotGeneratorHelper maxDurability = itemTemplate._props.MaxDurability; currentDurability = itemTemplate._props.MaxDurability; } - else + else { maxDurability = this.durabilityLimitsHelper.getRandomizedMaxArmorDurability(itemTemplate, botRole); - currentDurability = this.durabilityLimitsHelper.getRandomizedArmorDurability(itemTemplate, botRole, maxDurability); + currentDurability = this.durabilityLimitsHelper.getRandomizedArmorDurability( + itemTemplate, + botRole, + maxDurability, + ); } return { Durability: currentDurability, - MaxDurability: maxDurability + MaxDurability: maxDurability, }; } @@ -238,54 +284,81 @@ export class BotGeneratorHelper * @param equipmentSlot Slot the item will be placed into * @returns false if no incompatibilities, also has incompatibility reason */ - public isItemIncompatibleWithCurrentItems(items: Item[], tplToCheck: string, equipmentSlot: string): { incompatible: boolean, reason: string } + public isItemIncompatibleWithCurrentItems( + items: Item[], + tplToCheck: string, + equipmentSlot: string, + ): {incompatible: boolean; reason: string;} { // Skip slots that have no incompatibilities - if (["Scabbard", "Backpack", "SecureContainer", "Holster", "ArmBand"].includes(equipmentSlot)) + if (["Scabbard", "Backpack", "SecureContainer", "Holster", "ArmBand"].includes(equipmentSlot)) { - return { incompatible: false, reason: "" }; + return {incompatible: false, reason: ""}; } // TODO: Can probably be optimized to cache itemTemplates as items are added to inventory - const equippedItems = items.map(i => this.databaseServer.getTables().templates.items[i._tpl]); + const equippedItems = items.map((i) => this.databaseServer.getTables().templates.items[i._tpl]); const item = this.itemHelper.getItem(tplToCheck); const itemToCheck = item[1]; if (!item[0]) { - this.logger.warning(this.localisationService.getText("bot-invalid_item_compatibility_check", {itemTpl: tplToCheck, slot: equipmentSlot})); + this.logger.warning( + this.localisationService.getText("bot-invalid_item_compatibility_check", { + itemTpl: tplToCheck, + slot: equipmentSlot, + }), + ); } if (!itemToCheck._props) { - this.logger.warning(this.localisationService.getText("bot-compatibility_check_missing_props", {id: itemToCheck._id, name: itemToCheck._name, slot: equipmentSlot})); + this.logger.warning( + this.localisationService.getText("bot-compatibility_check_missing_props", { + id: itemToCheck._id, + name: itemToCheck._name, + slot: equipmentSlot, + }), + ); } // Does an equipped item have a property that blocks the desired item - check for prop "BlocksX" .e.g BlocksEarpiece / BlocksFaceCover - let blockingItem = equippedItems.find(x => x._props[`Blocks${equipmentSlot}`]); - if (blockingItem) + let blockingItem = equippedItems.find((x) => x._props[`Blocks${equipmentSlot}`]); + if (blockingItem) { - //this.logger.warning(`1 incompatibility found between - ${itemToEquip[1]._name} and ${blockingItem._name} - ${equipmentSlot}`); - return { incompatible: true, reason: `${tplToCheck} ${itemToCheck._name} in slot: ${equipmentSlot} blocked by: ${blockingItem._id} ${blockingItem._name}` }; + // this.logger.warning(`1 incompatibility found between - ${itemToEquip[1]._name} and ${blockingItem._name} - ${equipmentSlot}`); + return { + incompatible: true, + reason: + `${tplToCheck} ${itemToCheck._name} in slot: ${equipmentSlot} blocked by: ${blockingItem._id} ${blockingItem._name}`, + }; } // Check if any of the current inventory templates have the incoming item defined as incompatible - blockingItem = equippedItems.find(x => x._props.ConflictingItems?.includes(tplToCheck)); - if (blockingItem) + blockingItem = equippedItems.find((x) => x._props.ConflictingItems?.includes(tplToCheck)); + if (blockingItem) { - //this.logger.warning(`2 incompatibility found between - ${itemToEquip[1]._name} and ${blockingItem._props.Name} - ${equipmentSlot}`); - return { incompatible: true, reason: `${tplToCheck} ${itemToCheck._name} in slot: ${equipmentSlot} blocked by: ${blockingItem._id} ${blockingItem._name}` }; + // this.logger.warning(`2 incompatibility found between - ${itemToEquip[1]._name} and ${blockingItem._props.Name} - ${equipmentSlot}`); + return { + incompatible: true, + reason: + `${tplToCheck} ${itemToCheck._name} in slot: ${equipmentSlot} blocked by: ${blockingItem._id} ${blockingItem._name}`, + }; } // Check if the incoming item has any inventory items defined as incompatible - const blockingInventoryItem = items.find(x => itemToCheck._props.ConflictingItems?.includes(x._tpl)); - if (blockingInventoryItem) + const blockingInventoryItem = items.find((x) => itemToCheck._props.ConflictingItems?.includes(x._tpl)); + if (blockingInventoryItem) { - //this.logger.warning(`3 incompatibility found between - ${itemToEquip[1]._name} and ${blockingInventoryItem._tpl} - ${equipmentSlot}`) - return { incompatible: true, reason: `${tplToCheck} blocks existing item ${blockingInventoryItem._tpl} in slot ${blockingInventoryItem.slotId}` }; + // this.logger.warning(`3 incompatibility found between - ${itemToEquip[1]._name} and ${blockingInventoryItem._tpl} - ${equipmentSlot}`) + return { + incompatible: true, + reason: + `${tplToCheck} blocks existing item ${blockingInventoryItem._tpl} in slot ${blockingInventoryItem.slotId}`, + }; } - return { incompatible: false, reason: "" }; + return {incompatible: false, reason: ""}; } /** @@ -293,11 +366,13 @@ export class BotGeneratorHelper * @param botRole Role to convert * @returns Equipment role (e.g. pmc / assault / bossTagilla) */ - public getBotEquipmentRole(botRole: string): string + public getBotEquipmentRole(botRole: string): string { - return ([this.pmcConfig.usecType.toLowerCase(), this.pmcConfig.bearType.toLowerCase()].includes(botRole.toLowerCase())) - ? "pmc" - : botRole; + return ([this.pmcConfig.usecType.toLowerCase(), this.pmcConfig.bearType.toLowerCase()].includes( + botRole.toLowerCase(), + )) ? + "pmc" : + botRole; } } @@ -309,15 +384,15 @@ export class ExhaustableArray constructor( private itemPool: T[], private randomUtil: RandomUtil, - private jsonUtil: JsonUtil - ) + private jsonUtil: JsonUtil, + ) { this.pool = this.jsonUtil.clone(itemPool); } - public getRandomValue(): T + public getRandomValue(): T { - if (!this.pool?.length) + if (!this.pool?.length) { return null; } @@ -328,9 +403,9 @@ export class ExhaustableArray return toReturn; } - public getFirstValue(): T + public getFirstValue(): T { - if (!this.pool?.length) + if (!this.pool?.length) { return null; } @@ -340,13 +415,13 @@ export class ExhaustableArray return toReturn; } - public hasValues(): boolean + public hasValues(): boolean { - if (this.pool?.length) + if (this.pool?.length) { return true; } return false; } -} \ No newline at end of file +} diff --git a/project/src/helpers/BotHelper.ts b/project/src/helpers/BotHelper.ts index bdcfca4e..71f718b7 100644 --- a/project/src/helpers/BotHelper.ts +++ b/project/src/helpers/BotHelper.ts @@ -24,15 +24,13 @@ export class BotHelper @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("RandomUtil") protected randomUtil: RandomUtil, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); this.pmcConfig = this.configServer.getConfig(ConfigTypes.PMC); } - - /** * Get a template object for the specified botRole from bots.types db * @param role botRole to get template for @@ -71,7 +69,7 @@ export class BotHelper public isBotBoss(botRole: string): boolean { - return this.botConfig.bosses.some(x => x.toLowerCase() === botRole?.toLowerCase()); + return this.botConfig.bosses.some((x) => x.toLowerCase() === botRole?.toLowerCase()); } public isBotFollower(botRole: string): boolean @@ -187,13 +185,15 @@ export class BotHelper public rollChanceToBePmc(role: string, botConvertMinMax: MinMax): boolean { - return role.toLowerCase() in this.pmcConfig.convertIntoPmcChance - && this.randomUtil.getChance100(this.randomUtil.getInt(botConvertMinMax.min, botConvertMinMax.max)); + return role.toLowerCase() in this.pmcConfig.convertIntoPmcChance && + this.randomUtil.getChance100(this.randomUtil.getInt(botConvertMinMax.min, botConvertMinMax.max)); } public botRoleIsPmc(botRole: string): boolean { - return [this.pmcConfig.usecType.toLowerCase(), this.pmcConfig.bearType.toLowerCase()].includes(botRole.toLowerCase()); + return [this.pmcConfig.usecType.toLowerCase(), this.pmcConfig.bearType.toLowerCase()].includes( + botRole.toLowerCase(), + ); } /** @@ -209,8 +209,8 @@ export class BotHelper { return null; } - - return botEquipConfig.randomisation.find(x => botLevel >= x.levelRange.min && botLevel <= x.levelRange.max); + + return botEquipConfig.randomisation.find((x) => botLevel >= x.levelRange.min && botLevel <= x.levelRange.max); } /** @@ -219,9 +219,9 @@ export class BotHelper */ public getRandomizedPmcRole(): string { - return (this.randomUtil.getChance100(this.pmcConfig.isUsec)) - ? this.pmcConfig.usecType - : this.pmcConfig.bearType; + return (this.randomUtil.getChance100(this.pmcConfig.isUsec)) ? + this.pmcConfig.usecType : + this.pmcConfig.bearType; } /** @@ -248,8 +248,8 @@ export class BotHelper */ protected getRandomizedPmcSide(): string { - return (this.randomUtil.getChance100(this.pmcConfig.isUsec)) - ? "Usec" - : "Bear"; + return (this.randomUtil.getChance100(this.pmcConfig.isUsec)) ? + "Usec" : + "Bear"; } -} \ No newline at end of file +} diff --git a/project/src/helpers/BotWeaponGeneratorHelper.ts b/project/src/helpers/BotWeaponGeneratorHelper.ts index 5493198c..3a0631e1 100644 --- a/project/src/helpers/BotWeaponGeneratorHelper.ts +++ b/project/src/helpers/BotWeaponGeneratorHelper.ts @@ -29,9 +29,9 @@ export class BotWeaponGeneratorHelper @inject("InventoryHelper") protected inventoryHelper: InventoryHelper, @inject("WeightedRandomHelper") protected weightedRandomHelper: WeightedRandomHelper, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ContainerHelper") protected containerHelper: ContainerHelper + @inject("ContainerHelper") protected containerHelper: ContainerHelper, ) - { } + {} /** * Get a randomized number of bullets for a specific magazine @@ -61,7 +61,7 @@ export class BotWeaponGeneratorHelper /* Get the amount of bullets that would fit in the internal magazine * and multiply by how many magazines were supposed to be created */ - return chamberBulletCount * randomizedMagazineCount; + return chamberBulletCount * randomizedMagazineCount; } /** @@ -71,8 +71,8 @@ export class BotWeaponGeneratorHelper */ public getRandomizedMagazineCount(magCounts: GenerationData): number { - //const range = magCounts.max - magCounts.min; - //return this.randomUtil.getBiasedRandomNumber(magCounts.min, magCounts.max, Math.round(range * 0.75), 4); + // const range = magCounts.max - magCounts.min; + // return this.randomUtil.getBiasedRandomNumber(magCounts.min, magCounts.max, Math.round(range * 0.75), 4); return this.weightedRandomHelper.getWeightedValue(magCounts.weights); } @@ -98,7 +98,7 @@ export class BotWeaponGeneratorHelper { const magazine: Item[] = [{ _id: this.hashUtil.generate(), - _tpl: magazineTpl + _tpl: magazineTpl, }]; this.itemHelper.fillMagazineWithCartridge(magazine, magTemplate, ammoTpl, 1); @@ -113,12 +113,17 @@ export class BotWeaponGeneratorHelper * @param inventory bot inventory to add cartridges to * @param equipmentSlotsToAddTo what equipment slots should bullets be added into */ - public addAmmoIntoEquipmentSlots(ammoTpl: string, cartridgeCount: number, inventory: Inventory, equipmentSlotsToAddTo: EquipmentSlots[] = [EquipmentSlots.TACTICAL_VEST, EquipmentSlots.POCKETS] ): void + public addAmmoIntoEquipmentSlots( + ammoTpl: string, + cartridgeCount: number, + inventory: Inventory, + equipmentSlotsToAddTo: EquipmentSlots[] = [EquipmentSlots.TACTICAL_VEST, EquipmentSlots.POCKETS], + ): void { const ammoItems = this.itemHelper.splitStack({ _id: this.hashUtil.generate(), _tpl: ammoTpl, - upd: { StackObjectsCount: cartridgeCount } + upd: {StackObjectsCount: cartridgeCount}, }); for (const ammoItem of ammoItems) @@ -128,7 +133,8 @@ export class BotWeaponGeneratorHelper ammoItem._id, ammoItem._tpl, [ammoItem], - inventory); + inventory, + ); if (result === ItemAddedResult.NO_SPACE) { @@ -151,22 +157,32 @@ export class BotWeaponGeneratorHelper * TODO - move into BotGeneratorHelper, this is not the class for it * Adds an item with all its children into specified equipmentSlots, wherever it fits. * @param equipmentSlots Slot to add item+children into - * @param parentId - * @param parentTpl + * @param parentId + * @param parentTpl * @param itemWithChildren Item to add * @param inventory Inventory to add item+children into * @returns a `boolean` indicating item was added */ - public addItemWithChildrenToEquipmentSlot(equipmentSlots: string[], parentId: string, parentTpl: string, itemWithChildren: Item[], inventory: Inventory): ItemAddedResult + public addItemWithChildrenToEquipmentSlot( + equipmentSlots: string[], + parentId: string, + parentTpl: string, + itemWithChildren: Item[], + inventory: Inventory, + ): ItemAddedResult { for (const slot of equipmentSlots) { // Get container to put item into - const container = inventory.items.find(i => i.slotId === slot); + const container = inventory.items.find((i) => i.slotId === slot); if (!container) { // Desired equipment container (e.g. backpack) not found - this.logger.debug(`Unable to add item: ${itemWithChildren[0]._tpl} to: ${slot}, slot missing/bot generated without equipment`); + this.logger.debug( + `Unable to add item: ${ + itemWithChildren[0]._tpl + } to: ${slot}, slot missing/bot generated without equipment`, + ); continue; } @@ -202,10 +218,12 @@ export class BotWeaponGeneratorHelper } // Get all base level items in backpack - const containerItems = inventory.items.filter(i => i.parentId === container._id && i.slotId === slotGrid._name); + const containerItems = inventory.items.filter((i) => + i.parentId === container._id && i.slotId === slotGrid._name + ); // Get a copy of base level items we can iterate over - const containerItemsToCheck = containerItems.filter(x => x.slotId === slotGrid._name); + const containerItemsToCheck = containerItems.filter((x) => x.slotId === slotGrid._name); for (const item of containerItemsToCheck) { // Look for children on items, insert into array if found @@ -218,14 +236,19 @@ export class BotWeaponGeneratorHelper } // Get rid of items free/used spots in current grid - const slotGridMap = this.inventoryHelper.getContainerMap(slotGrid._props.cellsH, slotGrid._props.cellsV, containerItems, container._id); + const slotGridMap = this.inventoryHelper.getContainerMap( + slotGrid._props.cellsH, + slotGrid._props.cellsV, + containerItems, + container._id, + ); // Try to fit item into grid const findSlotResult = this.containerHelper.findSlotForItem(slotGridMap, itemSize[0], itemSize[1]); // Open slot found, add item to inventory if (findSlotResult.success) { - const parentItem = itemWithChildren.find(i => i._id === parentId); + const parentItem = itemWithChildren.find((i) => i._id === parentId); // Set items parent to container id parentItem.parentId = container._id; @@ -233,7 +256,7 @@ export class BotWeaponGeneratorHelper parentItem.location = { x: findSlotResult.x, y: findSlotResult.y, - r: findSlotResult.rotation ? 1 : 0 + r: findSlotResult.rotation ? 1 : 0, }; inventory.items.push(...itemWithChildren); @@ -284,4 +307,4 @@ export class BotWeaponGeneratorHelper return true; } -} \ No newline at end of file +} diff --git a/project/src/helpers/ContainerHelper.ts b/project/src/helpers/ContainerHelper.ts index bb88c4bc..cfd16c6b 100644 --- a/project/src/helpers/ContainerHelper.ts +++ b/project/src/helpers/ContainerHelper.ts @@ -43,7 +43,7 @@ export class ContainerHelper /** * Try to rotate if there is enough room for the item * Only occupies one grid of items, no rotation required - * */ + */ if (!foundSlot && itemWidth * itemHeight > 1) { foundSlot = this.locateSlot(container2D, containerX, containerY, x, y, itemHeight, itemWidth); @@ -77,7 +77,15 @@ export class ContainerHelper * @param itemH Items height * @returns True - slot found */ - protected locateSlot(container2D: number[][], containerX: number, containerY: number, x: number, y: number, itemW: number, itemH: number): boolean + protected locateSlot( + container2D: number[][], + containerX: number, + containerY: number, + x: number, + y: number, + itemW: number, + itemH: number, + ): boolean { let foundSlot = true; @@ -124,7 +132,14 @@ export class ContainerHelper * @param rotate is item rotated * @returns Location to place item */ - public fillContainerMapWithItem(container2D: number[][], x: number, y: number, itemW: number, itemH: number, rotate: boolean): number[][] + public fillContainerMapWithItem( + container2D: number[][], + x: number, + y: number, + itemW: number, + itemH: number, + rotate: boolean, + ): number[][] { const itemWidth = rotate ? itemH : itemW; const itemHeight = rotate ? itemW : itemH; @@ -146,4 +161,4 @@ export class ContainerHelper return container2D; } -} \ No newline at end of file +} diff --git a/project/src/helpers/DialogueHelper.ts b/project/src/helpers/DialogueHelper.ts index c54a8e4c..49ac0d91 100644 --- a/project/src/helpers/DialogueHelper.ts +++ b/project/src/helpers/DialogueHelper.ts @@ -4,7 +4,13 @@ import { ItemHelper } from "@spt-aki/helpers/ItemHelper"; import { NotificationSendHelper } from "@spt-aki/helpers/NotificationSendHelper"; import { NotifierHelper } from "@spt-aki/helpers/NotifierHelper"; import { Item } from "@spt-aki/models/eft/common/tables/IItem"; -import { Dialogue, Message, MessageContent, MessageItems, MessagePreview } from "@spt-aki/models/eft/profile/IAkiProfile"; +import { + Dialogue, + Message, + MessageContent, + MessageItems, + MessagePreview, +} from "@spt-aki/models/eft/profile/IAkiProfile"; import { MessageType } from "@spt-aki/models/enums/MessageType"; import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; @@ -24,9 +30,9 @@ export class DialogueHelper @inject("NotifierHelper") protected notifierHelper: NotifierHelper, @inject("NotificationSendHelper") protected notificationSendHelper: NotificationSendHelper, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ItemHelper") protected itemHelper: ItemHelper + @inject("ItemHelper") protected itemHelper: ItemHelper, ) - { } + {} /** * @deprecated Use MailSendService.sendMessage() or helpers @@ -35,7 +41,7 @@ export class DialogueHelper { const result: MessageContent = { templateId: templateId, - type: messageType + type: messageType, }; if (maxStoreTime) @@ -49,7 +55,13 @@ export class DialogueHelper /** * @deprecated Use MailSendService.sendMessage() or helpers */ - public addDialogueMessage(dialogueID: string, messageContent: MessageContent, sessionID: string, rewards: Item[] = [], messageType = MessageType.NPC_TRADER): void + public addDialogueMessage( + dialogueID: string, + messageContent: MessageContent, + sessionID: string, + rewards: Item[] = [], + messageType = MessageType.NPC_TRADER, + ): void { const dialogueData = this.saveServer.getProfile(sessionID).dialogues; const isNewDialogue = !(dialogueID in dialogueData); @@ -63,7 +75,7 @@ export class DialogueHelper messages: [], pinned: false, new: 0, - attachmentsNew: 0 + attachmentsNew: 0, }; dialogueData[dialogueID] = dialogue; @@ -79,7 +91,7 @@ export class DialogueHelper const stashId = this.hashUtil.generate(); items = { stash: stashId, - data: [] + data: [], }; rewards = this.itemHelper.replaceIDs(null, rewards); @@ -95,7 +107,12 @@ export class DialogueHelper if (!itemTemplate) { // Can happen when modded items are insured + mod is removed - this.logger.error(this.localisationService.getText("dialog-missing_item_template", {tpl: reward._tpl, type: MessageType[messageContent.type]})); + this.logger.error( + this.localisationService.getText("dialog-missing_item_template", { + tpl: reward._tpl, + type: MessageType[messageContent.type], + }), + ); continue; } @@ -132,7 +149,9 @@ export class DialogueHelper items: items, maxStorageTime: messageContent.maxStorageTime, systemData: messageContent.systemData ? messageContent.systemData : undefined, - profileChangeEvents: (messageContent.profileChangeEvents?.length === 0) ? messageContent.profileChangeEvents : undefined + profileChangeEvents: (messageContent.profileChangeEvents?.length === 0) ? + messageContent.profileChangeEvents : + undefined, }; if (!message.templateId) @@ -145,7 +164,10 @@ export class DialogueHelper // Offer Sold notifications are now separate from the main notification if (messageContent.type === MessageType.FLEAMARKET_MESSAGE && messageContent.ragfair) { - const offerSoldMessage = this.notifierHelper.createRagfairOfferSoldNotification(message, messageContent.ragfair); + const offerSoldMessage = this.notifierHelper.createRagfairOfferSoldNotification( + message, + messageContent.ragfair, + ); this.notificationSendHelper.sendMessage(sessionID, offerSoldMessage); message.type = MessageType.MESSAGE_WITH_ITEMS; // Should prevent getting the same notification popup twice } @@ -156,7 +178,7 @@ export class DialogueHelper /** * Get the preview contents of the last message in a dialogue. - * @param dialogue + * @param dialogue * @returns MessagePreview */ public getMessagePreview(dialogue: Dialogue): MessagePreview @@ -167,7 +189,7 @@ export class DialogueHelper dt: message?.dt, type: message?.type, templateId: message?.templateId, - uid: dialogue._id + uid: dialogue._id, }; if (message?.text) @@ -185,17 +207,17 @@ export class DialogueHelper /** * Get the item contents for a particular message. - * @param messageID - * @param sessionID + * @param messageID + * @param sessionID * @param itemId Item being moved to inventory - * @returns + * @returns */ public getMessageItemContents(messageID: string, sessionID: string, itemId: string): Item[] { const dialogueData = this.saveServer.getProfile(sessionID).dialogues; for (const dialogueId in dialogueData) { - const message = dialogueData[dialogueId].messages.find(x => x._id === messageID); + const message = dialogueData[dialogueId].messages.find((x) => x._id === messageID); if (!message) { continue; @@ -211,7 +233,7 @@ export class DialogueHelper // Check reward count when item being moved isn't in reward list // if count is 0, it means after this move the reward array will be empty and all rewards collected - const rewardItemCount = message.items.data.filter(x => x._id !== itemId ); + const rewardItemCount = message.items.data.filter((x) => x._id !== itemId); if (rewardItemCount.length === 0) { message.rewardCollected = true; @@ -240,4 +262,4 @@ export class DialogueHelper return profile.dialogues; } -} \ No newline at end of file +} diff --git a/project/src/helpers/DurabilityLimitsHelper.ts b/project/src/helpers/DurabilityLimitsHelper.ts index 61d8edc9..f888d30c 100644 --- a/project/src/helpers/DurabilityLimitsHelper.ts +++ b/project/src/helpers/DurabilityLimitsHelper.ts @@ -15,7 +15,7 @@ export class DurabilityLimitsHelper constructor( @inject("RandomUtil") protected randomUtil: RandomUtil, @inject("BotHelper") protected botHelper: BotHelper, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); @@ -172,12 +172,14 @@ export class DurabilityLimitsHelper const maxDelta = this.getMaxWeaponDeltaFromConfig(botRole); const delta = this.randomUtil.getInt(minDelta, maxDelta); const result = maxDurability - delta; - const durabilityValueMinLimit = Math.round((this.getMinWeaponLimitPercentFromConfig(botRole) / 100) * maxDurability); + const durabilityValueMinLimit = Math.round( + (this.getMinWeaponLimitPercentFromConfig(botRole) / 100) * maxDurability, + ); // Dont let weapon dura go below the percent defined in config - return (result >= durabilityValueMinLimit) - ? result - : durabilityValueMinLimit; + return (result >= durabilityValueMinLimit) ? + result : + durabilityValueMinLimit; } protected generateArmorDurability(botRole: string, maxDurability: number): number @@ -186,12 +188,14 @@ export class DurabilityLimitsHelper const maxDelta = this.getMaxArmorDeltaFromConfig(botRole); const delta = this.randomUtil.getInt(minDelta, maxDelta); const result = maxDurability - delta; - const durabilityValueMinLimit = Math.round((this.getMinArmorLimitPercentFromConfig(botRole) / 100) * maxDurability); + const durabilityValueMinLimit = Math.round( + (this.getMinArmorLimitPercentFromConfig(botRole) / 100) * maxDurability, + ); // Dont let armor dura go below the percent defined in config - return (result >= durabilityValueMinLimit) - ? result - : durabilityValueMinLimit; + return (result >= durabilityValueMinLimit) ? + result : + durabilityValueMinLimit; } protected getMinWeaponDeltaFromConfig(botRole: string): number @@ -234,7 +238,7 @@ export class DurabilityLimitsHelper return this.botConfig.durability.default.armor.maxDelta; } - protected getMinArmorLimitPercentFromConfig (botRole: string): number + protected getMinArmorLimitPercentFromConfig(botRole: string): number { if (this.botConfig.durability[botRole]) { @@ -244,7 +248,7 @@ export class DurabilityLimitsHelper return this.botConfig.durability.default.armor.minLimitPercent; } - protected getMinWeaponLimitPercentFromConfig (botRole: string): number + protected getMinWeaponLimitPercentFromConfig(botRole: string): number { if (this.botConfig.durability[botRole]) { @@ -253,4 +257,4 @@ export class DurabilityLimitsHelper return this.botConfig.durability.default.weapon.minLimitPercent; } -} \ No newline at end of file +} diff --git a/project/src/helpers/GameEventHelper.ts b/project/src/helpers/GameEventHelper.ts index 14f3097e..b6b677c2 100644 --- a/project/src/helpers/GameEventHelper.ts +++ b/project/src/helpers/GameEventHelper.ts @@ -12,10 +12,9 @@ export class GameEventHelper constructor( @inject("DatabaseServer") protected databaseServer: DatabaseServer, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.seasonalEventConfig = this.configServer.getConfig(ConfigTypes.SEASONAL_EVENT); } - -} \ No newline at end of file +} diff --git a/project/src/helpers/HandbookHelper.ts b/project/src/helpers/HandbookHelper.ts index b674daeb..bc93a88d 100644 --- a/project/src/helpers/HandbookHelper.ts +++ b/project/src/helpers/HandbookHelper.ts @@ -29,7 +29,7 @@ export class LookupCollection @injectable() export class HandbookHelper -{ +{ protected lookupCacheGenerated = false; protected handbookPriceCache = new LookupCollection(); @@ -89,7 +89,7 @@ export class HandbookHelper return this.handbookPriceCache.items.byId.get(tpl); } - const handbookItem = this.databaseServer.getTables().templates.handbook.Items.find(x => x.Id === tpl); + const handbookItem = this.databaseServer.getTables().templates.handbook.Items.find((x) => x.Id === tpl); if (!handbookItem) { const newValue = 0; @@ -103,7 +103,7 @@ export class HandbookHelper /** * Get all items in template with the given parent category - * @param parentId + * @param parentId * @returns string array */ public templatesWithParent(parentId: string): string[] @@ -113,7 +113,7 @@ export class HandbookHelper /** * Does category exist in handbook cache - * @param category + * @param category * @returns true if exists in cache */ public isCategory(category: string): boolean @@ -123,7 +123,7 @@ export class HandbookHelper /** * Get all items associated with a categories parent - * @param categoryParent + * @param categoryParent * @returns string array */ public childrenCategories(categoryParent: string): string[] @@ -164,4 +164,4 @@ export class HandbookHelper const price = this.getTemplatePrice(currencyTypeTo); return price ? Math.round(roubleCurrencyCount / price) : 0; } -} \ No newline at end of file +} diff --git a/project/src/helpers/HealthHelper.ts b/project/src/helpers/HealthHelper.ts index d1443f94..7a67f1f2 100644 --- a/project/src/helpers/HealthHelper.ts +++ b/project/src/helpers/HealthHelper.ts @@ -21,7 +21,7 @@ export class HealthHelper @inject("WinstonLogger") protected logger: ILogger, @inject("TimeUtil") protected timeUtil: TimeUtil, @inject("SaveServer") protected saveServer: SaveServer, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.healthConfig = this.configServer.getConfig(ConfigTypes.HEALTH); @@ -36,11 +36,11 @@ export class HealthHelper { const profile = this.saveServer.getProfile(sessionID); - if (!profile.vitality) // Occurs on newly created profiles - { + if (!profile.vitality) + { // Occurs on newly created profiles profile.vitality = { health: null, - effects: null + effects: null, }; } profile.vitality.health = { @@ -53,7 +53,7 @@ export class HealthHelper LeftArm: 0, RightArm: 0, LeftLeg: 0, - RightLeg: 0 + RightLeg: 0, }; profile.vitality.effects = { @@ -63,7 +63,7 @@ export class HealthHelper LeftArm: {}, RightArm: {}, LeftLeg: {}, - RightLeg: {} + RightLeg: {}, }; return profile; @@ -77,7 +77,13 @@ export class HealthHelper * @param addEffects Should effects be added or removed (default - add) * @param deleteExistingEffects Should all prior effects be removed before apply new ones */ - public saveVitality(pmcData: IPmcData, request: ISyncHealthRequestData, sessionID: string, addEffects = true, deleteExistingEffects = true): void + public saveVitality( + pmcData: IPmcData, + request: ISyncHealthRequestData, + sessionID: string, + addEffects = true, + deleteExistingEffects = true, + ): void { const postRaidBodyParts = request.Health; // post raid health settings const profile = this.saveServer.getProfile(sessionID); @@ -96,20 +102,26 @@ export class HealthHelper { profileEffects[bodyPart] = postRaidBodyParts[bodyPart].Effects; } - if (request.IsAlive === true) // is player alive, not is limb alive - { + if (request.IsAlive === true) + { // is player alive, not is limb alive profileHealth[bodyPart] = postRaidBodyParts[bodyPart].Current; } else { - profileHealth[bodyPart] = pmcData.Health.BodyParts[bodyPart].Health.Maximum * this.healthConfig.healthMultipliers.death; + profileHealth[bodyPart] = pmcData.Health.BodyParts[bodyPart].Health.Maximum * + this.healthConfig.healthMultipliers.death; } } // Add effects to body parts if (addEffects) { - this.saveEffects(pmcData, sessionID, this.jsonUtil.clone(this.saveServer.getProfile(sessionID).vitality.effects), deleteExistingEffects); + this.saveEffects( + pmcData, + sessionID, + this.jsonUtil.clone(this.saveServer.getProfile(sessionID).vitality.effects), + deleteExistingEffects, + ); } // Adjust hydration/energy/temp and limb hp @@ -159,7 +171,10 @@ export class HealthHelper if (target === 0) { // Blacked body part - target = Math.round(pmcData.Health.BodyParts[healthModifier].Health.Maximum * this.healthConfig.healthMultipliers.blacked); + target = Math.round( + pmcData.Health.BodyParts[healthModifier].Health.Maximum * + this.healthConfig.healthMultipliers.blacked, + ); } pmcData.Health.BodyParts[healthModifier].Health.Current = Math.round(target); @@ -176,7 +191,12 @@ export class HealthHelper * @param bodyPartsWithEffects dict of body parts with effects that should be added to profile * @param addEffects Should effects be added back to profile */ - protected saveEffects(pmcData: IPmcData, sessionId: string, bodyPartsWithEffects: Effects, deleteExistingEffects = true): void + protected saveEffects( + pmcData: IPmcData, + sessionId: string, + bodyPartsWithEffects: Effects, + deleteExistingEffects = true, + ): void { if (!this.healthConfig.save.effects) { @@ -208,7 +228,9 @@ export class HealthHelper // Sometimes the value can be Infinity instead of -1, blame HealthListener.cs in modules if (time === "Infinity") { - this.logger.warning(`Effect ${effectType} found with value of Infinity, changed to -1, this is an issue with HealthListener.cs`); + this.logger.warning( + `Effect ${effectType} found with value of Infinity, changed to -1, this is an issue with HealthListener.cs`, + ); time = -1; } this.addEffect(pmcData, bodyPart, effectType, time); @@ -236,7 +258,7 @@ export class HealthHelper profileBodyPart.Effects = {}; } - profileBodyPart.Effects[effectType] = { Time: duration }; + profileBodyPart.Effects[effectType] = {Time: duration}; // Delete empty property to prevent client bugs if (this.isEmpty(profileBodyPart.Effects)) @@ -245,7 +267,7 @@ export class HealthHelper } } - protected isEmpty(map: Record): boolean + protected isEmpty(map: Record): boolean { for (const key in map) { @@ -257,4 +279,4 @@ export class HealthHelper return true; } -} \ No newline at end of file +} diff --git a/project/src/helpers/HideoutHelper.ts b/project/src/helpers/HideoutHelper.ts index 7be211db..cf88cb96 100644 --- a/project/src/helpers/HideoutHelper.ts +++ b/project/src/helpers/HideoutHelper.ts @@ -48,7 +48,7 @@ export class HideoutHelper @inject("InventoryHelper") protected inventoryHelper: InventoryHelper, @inject("PlayerService") protected playerService: PlayerService, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.hideoutConfig = this.configServer.getConfig(ConfigTypes.HIDEOUT); @@ -61,9 +61,13 @@ export class HideoutHelper * @param sessionID Session id * @returns client response */ - public registerProduction(pmcData: IPmcData, body: IHideoutSingleProductionStartRequestData | IHideoutContinuousProductionStartRequestData, sessionID: string): IItemEventRouterResponse + public registerProduction( + pmcData: IPmcData, + body: IHideoutSingleProductionStartRequestData | IHideoutContinuousProductionStartRequestData, + sessionID: string, + ): IItemEventRouterResponse { - const recipe = this.databaseServer.getTables().hideout.production.find(p => p._id === body.recipeId); + const recipe = this.databaseServer.getTables().hideout.production.find((p) => p._id === body.recipeId); if (!recipe) { this.logger.error(this.localisationService.getText("hideout-missing_recipe_in_db", body.recipeId)); @@ -71,7 +75,8 @@ export class HideoutHelper return this.httpResponse.appendErrorToOutput(this.eventOutputHolder.getOutput(sessionID)); } - const modifiedProductionTime = recipe.productionTime - this.getCraftingSkillProductionTimeReduction(pmcData, recipe.productionTime); + const modifiedProductionTime = recipe.productionTime - + this.getCraftingSkillProductionTimeReduction(pmcData, recipe.productionTime); // @Important: Here we need to be very exact: // - normal recipe: Production time value is stored in attribute "productionType" with small "p" @@ -80,7 +85,11 @@ export class HideoutHelper { pmcData.Hideout.Production = {}; } - pmcData.Hideout.Production[body.recipeId] = this.initProduction(body.recipeId, modifiedProductionTime, recipe.needFuelForAllProductionTime); + pmcData.Hideout.Production[body.recipeId] = this.initProduction( + body.recipeId, + modifiedProductionTime, + recipe.needFuelForAllProductionTime, + ); } /** @@ -100,14 +109,14 @@ export class HideoutHelper Interrupted: false, NeedFuelForAllProductionTime: needFuelForAllProductionTime, // Used when sending to client needFuelForAllProductionTime: needFuelForAllProductionTime, // used when stored in production.json - SkipTime: 0 + SkipTime: 0, }; } /** * Is the provided object a Production type - * @param productive - * @returns + * @param productive + * @returns */ public isProductionType(productive: Productive): productive is Production { @@ -124,12 +133,15 @@ export class HideoutHelper // Handle additional changes some bonuses need before being added switch (bonus.type) { - case "StashSize": { + case "StashSize": + { // Find stash item and adjust tpl to new tpl from bonus - const stashItem = pmcData.Inventory.items.find(x => x._id === pmcData.Inventory.stash); + const stashItem = pmcData.Inventory.items.find((x) => x._id === pmcData.Inventory.stash); if (!stashItem) { - this.logger.warning(`Unable to apply StashSize bonus, stash with id: ${pmcData.Inventory.stash} not found`); + this.logger.warning( + `Unable to apply StashSize bonus, stash with id: ${pmcData.Inventory.stash} not found`, + ); } stashItem._tpl = bonus.templateId; @@ -140,7 +152,7 @@ export class HideoutHelper pmcData.Health.Energy.Maximum += bonus.value; break; case "TextBonus": - //Delete values before they're added to profile + // Delete values before they're added to profile delete bonus.value; delete bonus.passive; delete bonus.production; @@ -173,15 +185,19 @@ export class HideoutHelper * @param pmcData Player profile * @returns Properties */ - protected getHideoutProperties(pmcData: IPmcData): { btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean; } + protected getHideoutProperties( + pmcData: IPmcData, + ): {btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean;} { - const bitcoinFarm = pmcData.Hideout.Areas.find(x => x.type === HideoutAreas.BITCOIN_FARM); - const bitcoinCount = bitcoinFarm?.slots.filter(slot => slot.item).length ?? 0; // Get slots with an item property + const bitcoinFarm = pmcData.Hideout.Areas.find((x) => x.type === HideoutAreas.BITCOIN_FARM); + const bitcoinCount = bitcoinFarm?.slots.filter((slot) => slot.item).length ?? 0; // Get slots with an item property const hideoutProperties = { btcFarmCGs: bitcoinCount, - isGeneratorOn: pmcData.Hideout.Areas.find(x => x.type === HideoutAreas.GENERATOR)?.active ?? false, - waterCollectorHasFilter: this.doesWaterCollectorHaveFilter(pmcData.Hideout.Areas.find(x => x.type === HideoutAreas.WATER_COLLECTOR)) + isGeneratorOn: pmcData.Hideout.Areas.find((x) => x.type === HideoutAreas.GENERATOR)?.active ?? false, + waterCollectorHasFilter: this.doesWaterCollectorHaveFilter( + pmcData.Hideout.Areas.find((x) => x.type === HideoutAreas.WATER_COLLECTOR), + ), }; return hideoutProperties; @@ -189,23 +205,27 @@ export class HideoutHelper protected doesWaterCollectorHaveFilter(waterCollector: HideoutArea): boolean { - if (waterCollector.level === 3) // can put filters in from L3 - { + if (waterCollector.level === 3) + { // can put filters in from L3 // Has filter in at least one slot - return waterCollector.slots.some(x => x.item); + return waterCollector.slots.some((x) => x.item); } - + // No Filter return false; } - + /** * Update progress timer for water collector * @param pmcData profile to update * @param productionId id of water collection production to update * @param hideoutProperties Hideout properties */ - protected updateWaterCollectorProductionTimer(pmcData: IPmcData, productionId: string, hideoutProperties: { btcFarmCGs?: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean; }): void + protected updateWaterCollectorProductionTimer( + pmcData: IPmcData, + productionId: string, + hideoutProperties: {btcFarmCGs?: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean;}, + ): void { const timeElapsed = this.getTimeElapsedSinceLastServerTick(pmcData, hideoutProperties.isGeneratorOn); if (hideoutProperties.waterCollectorHasFilter) @@ -219,7 +239,10 @@ export class HideoutHelper * @param pmcData Profile to check for productions and update * @param hideoutProperties Hideout properties */ - protected updateProductionTimers(pmcData: IPmcData, hideoutProperties: { btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean; }): void + protected updateProductionTimers( + pmcData: IPmcData, + hideoutProperties: {btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean;}, + ): void { const recipes = this.databaseServer.getTables().hideout.production; @@ -255,12 +278,16 @@ export class HideoutHelper if (prodId === HideoutHelper.bitcoinFarm) { - pmcData.Hideout.Production[prodId] = this.updateBitcoinFarm(pmcData, hideoutProperties.btcFarmCGs, hideoutProperties.isGeneratorOn); + pmcData.Hideout.Production[prodId] = this.updateBitcoinFarm( + pmcData, + hideoutProperties.btcFarmCGs, + hideoutProperties.isGeneratorOn, + ); continue; } // Other recipes not covered by above - const recipe = recipes.find(r => r._id === prodId); + const recipe = recipes.find((r) => r._id === prodId); if (!recipe) { this.logger.error(this.localisationService.getText("hideout-missing_recipe_for_area", prodId)); @@ -277,9 +304,14 @@ export class HideoutHelper * @param pmcData Player profile * @param prodId Production id being crafted * @param recipe Recipe data being crafted - * @param hideoutProperties + * @param hideoutProperties */ - protected updateProductionProgress(pmcData: IPmcData, prodId: string, recipe: IHideoutProduction, hideoutProperties: { btcFarmCGs?: number; isGeneratorOn: boolean; waterCollectorHasFilter?: boolean; }): void + protected updateProductionProgress( + pmcData: IPmcData, + prodId: string, + recipe: IHideoutProduction, + hideoutProperties: {btcFarmCGs?: number; isGeneratorOn: boolean; waterCollectorHasFilter?: boolean;}, + ): void { // Production is complete, no need to do any calculations if (this.doesProgressMatchProductionTime(pmcData, prodId)) @@ -321,7 +353,8 @@ export class HideoutHelper */ protected updateScavCaseProductionTimer(pmcData: IPmcData, productionId: string): void { - const timeElapsed = (this.timeUtil.getTimestamp() - pmcData.Hideout.Production[productionId].StartTimestamp) - pmcData.Hideout.Production[productionId].Progress; + const timeElapsed = (this.timeUtil.getTimestamp() - pmcData.Hideout.Production[productionId].StartTimestamp) - + pmcData.Hideout.Production[productionId].Progress; pmcData.Hideout.Production[productionId].Progress += timeElapsed; } @@ -331,7 +364,11 @@ export class HideoutHelper * @param pmcData Profile to update areas of * @param hideoutProperties hideout properties */ - protected updateAreasWithResources(sessionID: string, pmcData: IPmcData, hideoutProperties: { btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean; }): void + protected updateAreasWithResources( + sessionID: string, + pmcData: IPmcData, + hideoutProperties: {btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean;}, + ): void { for (const area of pmcData.Hideout.Areas) { @@ -361,9 +398,10 @@ export class HideoutHelper { // 1 resource last 14 min 27 sec, 1/14.45/60 = 0.00115 // 10-10-2021 From wiki, 1 resource last 12 minutes 38 seconds, 1/12.63333/60 = 0.00131 - let fuelDrainRate = this.databaseServer.getTables().hideout.settings.generatorFuelFlowRate * this.hideoutConfig.runIntervalSeconds; + let fuelDrainRate = this.databaseServer.getTables().hideout.settings.generatorFuelFlowRate * + this.hideoutConfig.runIntervalSeconds; // implemented moddable bonus for fuel consumption bonus instead of using solar power variable as before - const fuelBonus = pmcData.Bonuses.find(b => b.type === "FuelConsumption"); + const fuelBonus = pmcData.Bonuses.find((b) => b.type === "FuelConsumption"); const fuelBonusPercent = 1.0 - (fuelBonus ? Math.abs(fuelBonus.value) : 0) / 100; fuelDrainRate *= fuelBonusPercent; // Hideout management resource consumption bonus: @@ -376,9 +414,9 @@ export class HideoutHelper { if (generatorArea.slots[i].item) { - let resourceValue = (generatorArea.slots[i].item[0].upd?.Resource) - ? generatorArea.slots[i].item[0].upd.Resource.Value - : null; + let resourceValue = (generatorArea.slots[i].item[0].upd?.Resource) ? + generatorArea.slots[i].item[0].upd.Resource.Value : + null; if (resourceValue === 0) { continue; @@ -386,9 +424,9 @@ export class HideoutHelper else if (!resourceValue) { const fuelItem = HideoutHelper.expeditionaryFuelTank; - resourceValue = generatorArea.slots[i].item[0]._tpl === fuelItem - ? 60 - fuelDrainRate - : 100 - fuelDrainRate; + resourceValue = generatorArea.slots[i].item[0]._tpl === fuelItem ? + 60 - fuelDrainRate : + 100 - fuelDrainRate; pointsConsumed = fuelDrainRate; } else @@ -400,7 +438,7 @@ export class HideoutHelper resourceValue = Math.round(resourceValue * 10000) / 10000; pointsConsumed = Math.round(pointsConsumed * 10000) / 10000; - //check unit consumed for increment skill point + // check unit consumed for increment skill point if (pmcData && Math.floor(pointsConsumed / 10) >= 1) { this.profileHelper.addSkillPointsToPlayer(pmcData, SkillTypes.HIDEOUT_MANAGEMENT, 1); @@ -432,7 +470,12 @@ export class HideoutHelper } } - protected updateWaterCollector(sessionId: string, pmcData: IPmcData, area: HideoutArea, isGeneratorOn: boolean): void + protected updateWaterCollector( + sessionId: string, + pmcData: IPmcData, + area: HideoutArea, + isGeneratorOn: boolean, + ): void { // Skip water collector when not level 3 (cant collect until 3) if (area.level !== 3) @@ -454,7 +497,7 @@ export class HideoutHelper recipeId: HideoutHelper.waterCollector, Action: "HideoutSingleProductionStart", items: [], - timestamp: this.timeUtil.getTimestamp() + timestamp: this.timeUtil.getTimestamp(), }; this.registerProduction(pmcData, recipe, sessionId); @@ -469,14 +512,24 @@ export class HideoutHelper * @param pmcData Player profile * @returns Updated HideoutArea object */ - protected updateWaterFilters(waterFilterArea: HideoutArea, production: Production, isGeneratorOn: boolean, pmcData: IPmcData): HideoutArea + protected updateWaterFilters( + waterFilterArea: HideoutArea, + production: Production, + isGeneratorOn: boolean, + pmcData: IPmcData, + ): HideoutArea { let filterDrainRate = this.getWaterFilterDrainRate(pmcData); const productionTime = this.getTotalProductionTimeSeconds(HideoutHelper.waterCollector); const secondsSinceServerTick = this.getTimeElapsedSinceLastServerTick(pmcData, isGeneratorOn); - - filterDrainRate = this.adjustWaterFilterDrainRate(secondsSinceServerTick, productionTime, production.Progress, filterDrainRate); - + + filterDrainRate = this.adjustWaterFilterDrainRate( + secondsSinceServerTick, + productionTime, + production.Progress, + filterDrainRate, + ); + // Production hasn't completed let pointsConsumed = 0; if (production.Progress < productionTime) @@ -489,9 +542,9 @@ export class HideoutHelper if (waterFilterArea.slots[i].item) { // How many units of filter are left - let resourceValue = (waterFilterArea.slots[i].item[0].upd?.Resource) - ? waterFilterArea.slots[i].item[0].upd.Resource.Value - : null; + let resourceValue = (waterFilterArea.slots[i].item[0].upd?.Resource) ? + waterFilterArea.slots[i].item[0].upd.Resource.Value : + null; if (!resourceValue) { // None left @@ -500,7 +553,8 @@ export class HideoutHelper } else { - pointsConsumed = (waterFilterArea.slots[i].item[0].upd.Resource.UnitsConsumed || 0) + filterDrainRate; + pointsConsumed = (waterFilterArea.slots[i].item[0].upd.Resource.UnitsConsumed || 0) + + filterDrainRate; resourceValue -= filterDrainRate; } @@ -537,19 +591,25 @@ export class HideoutHelper } /** - * Get an adjusted water filter drain rate based on time elapsed since last run, + * Get an adjusted water filter drain rate based on time elapsed since last run, * handle edge case when craft time has gone on longer than total production time * @param secondsSinceServerTick Time passed * @param totalProductionTime Total time collecting water - * @param productionProgress how far water collector has progressed - * @param baseFilterDrainRate Base drain rate - * @returns + * @param productionProgress how far water collector has progressed + * @param baseFilterDrainRate Base drain rate + * @returns */ - protected adjustWaterFilterDrainRate(secondsSinceServerTick: number, totalProductionTime: number, productionProgress: number, baseFilterDrainRate: number): number + protected adjustWaterFilterDrainRate( + secondsSinceServerTick: number, + totalProductionTime: number, + productionProgress: number, + baseFilterDrainRate: number, + ): number { - const drainRateMultiplier = secondsSinceServerTick > totalProductionTime - ? (totalProductionTime - productionProgress) // more time passed than prod time, get total minus the current progress - : secondsSinceServerTick; + const drainRateMultiplier = secondsSinceServerTick > totalProductionTime ? + (totalProductionTime - productionProgress) // more time passed than prod time, get total minus the current progress + : + secondsSinceServerTick; // Multiply drain rate by calculated multiplier baseFilterDrainRate *= drainRateMultiplier; @@ -578,16 +638,16 @@ export class HideoutHelper */ protected getTotalProductionTimeSeconds(prodId: string): number { - const recipe = this.databaseServer.getTables().hideout.production.find(prod => prod._id === prodId); + const recipe = this.databaseServer.getTables().hideout.production.find((prod) => prod._id === prodId); return (recipe.productionTime || 0); } /** * Create a upd object using passed in parameters - * @param stackCount - * @param resourceValue - * @param resourceUnitsConsumed + * @param stackCount + * @param resourceValue + * @param resourceUnitsConsumed * @returns Upd */ protected getAreaUpdObject(stackCount: number, resourceValue: number, resourceUnitsConsumed: number): Upd @@ -596,8 +656,8 @@ export class HideoutHelper StackObjectsCount: stackCount, Resource: { Value: resourceValue, - UnitsConsumed: resourceUnitsConsumed - } + UnitsConsumed: resourceUnitsConsumed, + }, }; } @@ -608,7 +668,8 @@ export class HideoutHelper Lasts for 17 hours 38 minutes and 49 seconds (23 hours 31 minutes and 45 seconds with elite hideout management skill), 300/17.64694/60/60 = 0.004722 */ - let filterDrainRate = this.databaseServer.getTables().hideout.settings.airFilterUnitFlowRate * this.hideoutConfig.runIntervalSeconds; + let filterDrainRate = this.databaseServer.getTables().hideout.settings.airFilterUnitFlowRate * + this.hideoutConfig.runIntervalSeconds; // Hideout management resource consumption bonus: const hideoutManagementConsumptionBonus = 1.0 - this.getHideoutManagementConsumptionBonus(pmcData); filterDrainRate *= hideoutManagementConsumptionBonus; @@ -618,9 +679,9 @@ export class HideoutHelper { if (airFilterArea.slots[i].item) { - let resourceValue = (airFilterArea.slots[i].item[0].upd?.Resource) - ? airFilterArea.slots[i].item[0].upd.Resource.Value - : null; + let resourceValue = (airFilterArea.slots[i].item[0].upd?.Resource) ? + airFilterArea.slots[i].item[0].upd.Resource.Value : + null; if (!resourceValue) { resourceValue = 300 - filterDrainRate; @@ -634,7 +695,7 @@ export class HideoutHelper resourceValue = Math.round(resourceValue * 10000) / 10000; pointsConsumed = Math.round(pointsConsumed * 10000) / 10000; - //check unit consumed for increment skill point + // check unit consumed for increment skill point if (pmcData && Math.floor(pointsConsumed / 10) >= 1) { this.profileHelper.addSkillPointsToPlayer(pmcData, SkillTypes.HIDEOUT_MANAGEMENT, 1); @@ -647,8 +708,8 @@ export class HideoutHelper StackObjectsCount: 1, Resource: { Value: resourceValue, - UnitsConsumed: pointsConsumed - } + UnitsConsumed: pointsConsumed, + }, }; this.logger.debug(`Air filter: ${resourceValue} filter left on slot ${i + 1}`); break; // Break here to avoid updating all filters @@ -662,11 +723,13 @@ export class HideoutHelper } } } - + protected updateBitcoinFarm(pmcData: IPmcData, btcFarmCGs: number, isGeneratorOn: boolean): Production { const btcProd = pmcData.Hideout.Production[HideoutHelper.bitcoinFarm]; - const bitcoinProdData = this.databaseServer.getTables().hideout.production.find(p => p._id === "5d5c205bd582a50d042a3c0e"); + const bitcoinProdData = this.databaseServer.getTables().hideout.production.find((p) => + p._id === "5d5c205bd582a50d042a3c0e" + ); const coinSlotCount = this.getBTCSlots(pmcData); // Full on bitcoins, halt progress @@ -718,7 +781,8 @@ export class HideoutHelper } */ // BSG finally fixed their settings, they now get loaded from the settings and used in the client - const coinCraftTimeSeconds = bitcoinProdData.productionTime / (1 + (btcFarmCGs - 1) * this.databaseServer.getTables().hideout.settings.gpuBoostRate); + const coinCraftTimeSeconds = bitcoinProdData.productionTime / + (1 + (btcFarmCGs - 1) * this.databaseServer.getTables().hideout.settings.gpuBoostRate); while (btcProd.Progress > coinCraftTimeSeconds) { if (btcProd.Products.length < coinSlotCount) @@ -753,8 +817,8 @@ export class HideoutHelper _id: this.hashUtil.generate(), _tpl: "59faff1d86f7746c51718c9c", upd: { - StackObjectsCount: 1 - } + StackObjectsCount: 1, + }, }); btcProd.Progress -= coinCraftTimeSeconds; @@ -767,13 +831,17 @@ export class HideoutHelper * @param recipe Hideout production recipe being crafted we need the ticks for * @returns Amount of time elapsed in seconds */ - protected getTimeElapsedSinceLastServerTick(pmcData: IPmcData, isGeneratorOn: boolean, recipe: IHideoutProduction = null): number + protected getTimeElapsedSinceLastServerTick( + pmcData: IPmcData, + isGeneratorOn: boolean, + recipe: IHideoutProduction = null, + ): number { // Reduce time elapsed (and progress) when generator is off let timeElapsed = this.timeUtil.getTimestamp() - pmcData.Hideout.sptUpdateLastRunTimestamp; - if (recipe?.areaType === HideoutAreas.LAVATORY) // Lavatory works at 100% when power is on / off - { + if (recipe?.areaType === HideoutAreas.LAVATORY) + { // Lavatory works at 100% when power is on / off return timeElapsed; } @@ -792,7 +860,9 @@ export class HideoutHelper */ protected getBTCSlots(pmcData: IPmcData): number { - const bitcoinProduction = this.databaseServer.getTables().hideout.production.find(p => p._id === HideoutHelper.bitcoinFarm); + const bitcoinProduction = this.databaseServer.getTables().hideout.production.find((p) => + p._id === HideoutHelper.bitcoinFarm + ); const productionSlots = bitcoinProduction?.productionLimitCount || 3; const hasManagementSkillSlots = this.profileHelper.hasEliteSkillLevel(SkillTypes.HIDEOUT_MANAGEMENT, pmcData); const managementSlotsCount = this.getBitcoinMinerContainerSlotSize() || 2; @@ -805,7 +875,8 @@ export class HideoutHelper */ protected getBitcoinMinerContainerSlotSize(): number { - return this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots.BitcoinFarm.Container; + return this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots.BitcoinFarm + .Container; } /** @@ -826,11 +897,13 @@ export class HideoutHelper // at level 1 you already get 0.5%, so it goes up until level 50. For some reason the wiki // says that it caps at level 51 with 25% but as per dump data that is incorrect apparently let roundedLevel = Math.floor(hideoutManagementSkill.Progress / 100); - roundedLevel = (roundedLevel === 51) - ? roundedLevel - 1 - : roundedLevel; + roundedLevel = (roundedLevel === 51) ? + roundedLevel - 1 : + roundedLevel; - return (roundedLevel * this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.ConsumptionReductionPerLevel) / 100; + return (roundedLevel * + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement + .ConsumptionReductionPerLevel) / 100; } /** @@ -841,7 +914,7 @@ export class HideoutHelper */ protected getCraftingSkillProductionTimeReduction(pmcData: IPmcData, productionTime: number): number { - const craftingSkill = pmcData.Skills.Common.find(x=> x.Id === SkillTypes.CRAFTING); + const craftingSkill = pmcData.Skills.Common.find((x) => x.Id === SkillTypes.CRAFTING); if (!craftingSkill) { return productionTime; @@ -865,7 +938,11 @@ export class HideoutHelper * @param sessionId Session id * @returns IItemEventRouterResponse */ - public getBTC(pmcData: IPmcData, request: IHideoutTakeProductionRequestData, sessionId: string): IItemEventRouterResponse + public getBTC( + pmcData: IPmcData, + request: IHideoutTakeProductionRequestData, + sessionId: string, + ): IItemEventRouterResponse { const output = this.eventOutputHolder.getOutput(sessionId); @@ -875,7 +952,7 @@ export class HideoutHelper { const errorMsg = this.localisationService.getText("hideout-no_bitcoins_to_collect"); this.logger.error(errorMsg); - + return this.httpResponse.appendErrorToOutput(output, errorMsg); } @@ -911,9 +988,9 @@ export class HideoutHelper items: [{ // eslint-disable-next-line @typescript-eslint/naming-convention item_id: HideoutHelper.bitcoin, - count: pmcData.Hideout.Production[HideoutHelper.bitcoinFarm].Products.length + count: pmcData.Hideout.Production[HideoutHelper.bitcoinFarm].Products.length, }], - tid: "ragfair" + tid: "ragfair", }; } @@ -923,9 +1000,9 @@ export class HideoutHelper */ public unlockHideoutWallInProfile(pmcProfile: IPmcData): void { - const waterCollector = pmcProfile.Hideout.Areas.find(x => x.type === HideoutAreas.WATER_COLLECTOR); - const medStation = pmcProfile.Hideout.Areas.find(x => x.type === HideoutAreas.MEDSTATION); - const wall = pmcProfile.Hideout.Areas.find(x => x.type === HideoutAreas.EMERGENCY_WALL); + const waterCollector = pmcProfile.Hideout.Areas.find((x) => x.type === HideoutAreas.WATER_COLLECTOR); + const medStation = pmcProfile.Hideout.Areas.find((x) => x.type === HideoutAreas.MEDSTATION); + const wall = pmcProfile.Hideout.Areas.find((x) => x.type === HideoutAreas.EMERGENCY_WALL); // No collector or med station, skip if (!(waterCollector && medStation)) @@ -947,9 +1024,9 @@ export class HideoutHelper */ protected hideoutImprovementIsComplete(improvement: IHideoutImprovement): boolean { - return improvement?.completed - ? true - : false; + return improvement?.completed ? + true : + false; } /** @@ -961,10 +1038,13 @@ export class HideoutHelper for (const improvementId in pmcProfile.Hideout.Improvement) { const improvementDetails = pmcProfile.Hideout.Improvement[improvementId]; - if (improvementDetails.completed === false && improvementDetails.improveCompleteTimestamp < this.timeUtil.getTimestamp()) + if ( + improvementDetails.completed === false && + improvementDetails.improveCompleteTimestamp < this.timeUtil.getTimestamp() + ) { improvementDetails.completed = true; } } } -} \ No newline at end of file +} diff --git a/project/src/helpers/HttpServerHelper.ts b/project/src/helpers/HttpServerHelper.ts index 613bfa9e..e6db7dee 100644 --- a/project/src/helpers/HttpServerHelper.ts +++ b/project/src/helpers/HttpServerHelper.ts @@ -18,11 +18,11 @@ export class HttpServerHelper json: "application/json", png: "image/png", svg: "image/svg+xml", - txt: "text/plain" + txt: "text/plain", }; constructor( - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.httpConfig = this.configServer.getConfig(ConfigTypes.HTTP); @@ -60,7 +60,7 @@ export class HttpServerHelper public sendTextJson(resp: any, output: any): void { // eslint-disable-next-line @typescript-eslint/naming-convention - resp.writeHead(200, "OK", { "Content-Type": this.mime["json"] }); + resp.writeHead(200, "OK", {"Content-Type": this.mime["json"]}); resp.end(output); } -} \ No newline at end of file +} diff --git a/project/src/helpers/InRaidHelper.ts b/project/src/helpers/InRaidHelper.ts index a286c137..bc4d02c5 100644 --- a/project/src/helpers/InRaidHelper.ts +++ b/project/src/helpers/InRaidHelper.ts @@ -39,7 +39,7 @@ export class InRaidHelper @inject("PaymentHelper") protected paymentHelper: PaymentHelper, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("ProfileFixerService") protected profileFixerService: ProfileFixerService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.lostOnDeathConfig = this.configServer.getConfig(ConfigTypes.LOST_ON_DEATH); @@ -95,8 +95,13 @@ export class InRaidHelper { return acc + standingForKill; } - this.logger.warning(this.localisationService.getText("inraid-missing_standing_for_kill", {victimSide: victim.Side, victimRole: victim.Role})); - + this.logger.warning( + this.localisationService.getText("inraid-missing_standing_for_kill", { + victimSide: victim.Side, + victimRole: victim.Role, + }), + ); + return acc; }, existingFenceStanding); @@ -116,7 +121,7 @@ export class InRaidHelper // Scavs and bosses return botTypes[victim.Role.toLowerCase()]?.experience?.standingForKill; } - + // PMCs - get by bear/usec return botTypes[victim.Side.toLowerCase()]?.experience?.standingForKill; } @@ -131,7 +136,11 @@ export class InRaidHelper * @param sessionID Session id * @returns Reset profile object */ - public updateProfileBaseStats(profileData: IPmcData, saveProgressRequest: ISaveProgressRequestData, sessionID: string): IPmcData + public updateProfileBaseStats( + profileData: IPmcData, + saveProgressRequest: ISaveProgressRequestData, + sessionID: string, + ): IPmcData { // remove old skill fatigue this.resetSkillPointsEarnedDuringRaid(saveProgressRequest.profile); @@ -168,7 +177,9 @@ export class InRaidHelper if (matchingPreRaidCounter.value !== postRaidValue) { - this.logger.error(`Backendcounter: ${backendCounterKey} value is different post raid, old: ${matchingPreRaidCounter.value} new: ${postRaidValue}`); + this.logger.error( + `Backendcounter: ${backendCounterKey} value is different post raid, old: ${matchingPreRaidCounter.value} new: ${postRaidValue}`, + ); } } @@ -199,7 +210,6 @@ export class InRaidHelper return profileData; } - /** * Look for quests not are now status = fail that were not failed pre-raid and run the failQuest() function * @param sessionId Player id @@ -207,7 +217,12 @@ export class InRaidHelper * @param preRaidQuests Quests prior to starting raid * @param postRaidQuests Quest after raid */ - protected processFailedQuests(sessionId: string, pmcData: IPmcData, preRaidQuests: IQuestStatus[], postRaidQuests: IQuestStatus[]): void + protected processFailedQuests( + sessionId: string, + pmcData: IPmcData, + preRaidQuests: IQuestStatus[], + postRaidQuests: IQuestStatus[], + ): void { if (!preRaidQuests) { @@ -219,7 +234,7 @@ export class InRaidHelper for (const postRaidQuest of postRaidQuests) { // Find matching pre-raid quest - const preRaidQuest = preRaidQuests?.find(x => x.qid === postRaidQuest.qid); + const preRaidQuest = preRaidQuests?.find((x) => x.qid === postRaidQuest.qid); if (preRaidQuest) { // Post-raid quest is failed but wasn't pre-raid @@ -230,12 +245,11 @@ export class InRaidHelper const failBody: IFailQuestRequestData = { Action: "QuestComplete", qid: postRaidQuest.qid, - removeExcessItems: true + removeExcessItems: true, }; this.questHelper.failQuest(pmcData, failBody, sessionId); } } - } } @@ -252,7 +266,10 @@ export class InRaidHelper * @param saveProgressRequest post-raid request * @param profileData player profile on server */ - protected transferPostRaidLimbEffectsToProfile(saveProgressRequest: ISaveProgressRequestData, profileData: IPmcData): void + protected transferPostRaidLimbEffectsToProfile( + saveProgressRequest: ISaveProgressRequestData, + profileData: IPmcData, + ): void { // Iterate over each body part for (const bodyPartId in saveProgressRequest.profile.Health.BodyParts) @@ -287,7 +304,10 @@ export class InRaidHelper * @param tradersServerProfile Server * @param tradersClientProfile Client */ - protected applyTraderStandingAdjustments(tradersServerProfile: Record, tradersClientProfile: Record): void + protected applyTraderStandingAdjustments( + tradersServerProfile: Record, + tradersClientProfile: Record, + ): void { for (const traderId in tradersClientProfile) { @@ -356,12 +376,13 @@ export class InRaidHelper public removeSpawnedInSessionPropertyFromItems(postRaidProfile: IPostRaidPmcData): IPostRaidPmcData { const dbItems = this.databaseServer.getTables().templates.items; - const itemsToRemovePropertyFrom = postRaidProfile.Inventory.items.filter(x => + const itemsToRemovePropertyFrom = postRaidProfile.Inventory.items.filter((x) => { // Has upd object + upd.SpawnedInSession property + not a quest item - return "upd" in x && "SpawnedInSession" in x.upd - && !dbItems[x._tpl]._props.QuestItem - && !(this.inRaidConfig.keepFiRSecureContainerOnDeath && this.itemHelper.itemIsInsideContainer(x, "SecuredContainer", postRaidProfile.Inventory.items)); + return "upd" in x && "SpawnedInSession" in x.upd && + !dbItems[x._tpl]._props.QuestItem && + !(this.inRaidConfig.keepFiRSecureContainerOnDeath && + this.itemHelper.itemIsInsideContainer(x, "SecuredContainer", postRaidProfile.Inventory.items)); }); for (const item of itemsToRemovePropertyFrom) @@ -409,7 +430,7 @@ export class InRaidHelper public deleteInventory(pmcData: IPmcData, sessionID: string): void { // Get inventory item ids to remove from players profile - const itemIdsToDeleteFromProfile = this.getInventoryItemsLostOnDeath(pmcData).map(x => x._id); + const itemIdsToDeleteFromProfile = this.getInventoryItemsLostOnDeath(pmcData).map((x) => x._id); for (const itemId of itemIdsToDeleteFromProfile) { this.inventoryHelper.removeItem(pmcData, itemId, sessionID); @@ -426,30 +447,30 @@ export class InRaidHelper */ protected getInventoryItemsLostOnDeath(pmcProfile: IPmcData): Item[] { - const inventoryItems = pmcProfile.Inventory.items ?? []; + const inventoryItems = pmcProfile.Inventory.items ?? []; const equipment = pmcProfile?.Inventory?.equipment; const questRaidItems = pmcProfile?.Inventory?.questRaidItems; - return inventoryItems.filter(x => + return inventoryItems.filter((x) => { // Keep items flagged as kept after death if (this.isItemKeptAfterDeath(pmcProfile, x)) { return false; } - + // Remove normal items or quest raid items if (x.parentId === equipment || x.parentId === questRaidItems) { return true; } - + // Pocket items are not lost on death if (x.slotId.startsWith("pocket")) { return true; } - + return false; }); } @@ -461,13 +482,13 @@ export class InRaidHelper */ protected getBaseItemsInRigPocketAndBackpack(pmcData: IPmcData): Item[] { - const rig = pmcData.Inventory.items.find(x => x.slotId === "TacticalVest"); - const pockets = pmcData.Inventory.items.find(x => x.slotId === "Pockets"); - const backpack = pmcData.Inventory.items.find(x => x.slotId === "Backpack"); + const rig = pmcData.Inventory.items.find((x) => x.slotId === "TacticalVest"); + const pockets = pmcData.Inventory.items.find((x) => x.slotId === "Pockets"); + const backpack = pmcData.Inventory.items.find((x) => x.slotId === "Backpack"); - const baseItemsInRig = pmcData.Inventory.items.filter(x => x.parentId === rig?._id); - const baseItemsInPockets = pmcData.Inventory.items.filter(x => x.parentId === pockets?._id); - const baseItemsInBackpack = pmcData.Inventory.items.filter(x => x.parentId === backpack?._id); + const baseItemsInRig = pmcData.Inventory.items.filter((x) => x.parentId === rig?._id); + const baseItemsInPockets = pmcData.Inventory.items.filter((x) => x.parentId === pockets?._id); + const baseItemsInBackpack = pmcData.Inventory.items.filter((x) => x.parentId === backpack?._id); return [...baseItemsInRig, ...baseItemsInPockets, ...baseItemsInBackpack]; } @@ -539,7 +560,7 @@ export class InRaidHelper "pocket1", "pocket2", "pocket3", - "pocket4" + "pocket4", ]; let inventoryItems: Item[] = []; @@ -574,7 +595,7 @@ export class InRaidHelper // Add these new found items to our list of inventory items inventoryItems = [ ...inventoryItems, - ...foundItems + ...foundItems, ]; // Now find the children of these items @@ -583,4 +604,4 @@ export class InRaidHelper return inventoryItems; } -} \ No newline at end of file +} diff --git a/project/src/helpers/InventoryHelper.ts b/project/src/helpers/InventoryHelper.ts index a8843b33..793a80b1 100644 --- a/project/src/helpers/InventoryHelper.ts +++ b/project/src/helpers/InventoryHelper.ts @@ -32,11 +32,11 @@ import { JsonUtil } from "@spt-aki/utils/JsonUtil"; export interface OwnerInventoryItems { /** Inventory items from source */ - from: Item[] + from: Item[]; /** Inventory items at destination */ - to: Item[] - sameInventory: boolean, - isMail: boolean + to: Item[]; + sameInventory: boolean; + isMail: boolean; } @injectable() @@ -58,7 +58,7 @@ export class InventoryHelper @inject("ContainerHelper") protected containerHelper: ContainerHelper, @inject("ProfileHelper") protected profileHelper: ProfileHelper, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.inventoryConfig = this.configServer.getConfig(ConfigTypes.INVENTORY); @@ -76,7 +76,16 @@ export class InventoryHelper * @param useSortingTable Allow items to go into sorting table when stash has no space * @returns IItemEventRouterResponse */ - public addItem(pmcData: IPmcData, request: IAddItemRequestData, output: IItemEventRouterResponse, sessionID: string, callback: () => void, foundInRaid = false, addUpd = null, useSortingTable = false): IItemEventRouterResponse + public addItem( + pmcData: IPmcData, + request: IAddItemRequestData, + output: IItemEventRouterResponse, + sessionID: string, + callback: () => void, + foundInRaid = false, + addUpd = null, + useSortingTable = false, + ): IItemEventRouterResponse { const itemLib: Item[] = []; // TODO: what is the purpose of this property const itemsToAdd: IAddItemTempObject[] = []; @@ -85,19 +94,21 @@ export class InventoryHelper { if (requestItem.item_id in this.databaseServer.getTables().globals.ItemPresets) { - const presetItems = this.jsonUtil.clone(this.databaseServer.getTables().globals.ItemPresets[requestItem.item_id]._items); + const presetItems = this.jsonUtil.clone( + this.databaseServer.getTables().globals.ItemPresets[requestItem.item_id]._items, + ); itemLib.push(...presetItems); requestItem.isPreset = true; requestItem.item_id = presetItems[0]._id; } else if (this.paymentHelper.isMoneyTpl(requestItem.item_id)) { - itemLib.push({ _id: requestItem.item_id, _tpl: requestItem.item_id }); + itemLib.push({_id: requestItem.item_id, _tpl: requestItem.item_id}); } else if (request.tid === Traders.FENCE) { const fenceItems = this.fenceService.getRawFenceAssorts().items; - const itemIndex = fenceItems.findIndex(i => i._id === requestItem.item_id); + const itemIndex = fenceItems.findIndex((i) => i._id === requestItem.item_id); if (itemIndex === -1) { this.logger.debug(`Tried to buy item ${requestItem.item_id} from fence that no longer exists`); @@ -105,20 +116,25 @@ export class InventoryHelper return this.httpResponse.appendErrorToOutput(output, message); } - const purchasedItemWithChildren = this.itemHelper.findAndReturnChildrenAsItems(fenceItems, requestItem.item_id); + const purchasedItemWithChildren = this.itemHelper.findAndReturnChildrenAsItems( + fenceItems, + requestItem.item_id, + ); addUpd = purchasedItemWithChildren[0].upd; // Must persist the fence upd properties (e.g. durability/currentHp) itemLib.push(...purchasedItemWithChildren); } else if (request.tid === "RandomLootContainer") { - itemLib.push({ _id: requestItem.item_id, _tpl: requestItem.item_id }); + itemLib.push({_id: requestItem.item_id, _tpl: requestItem.item_id}); } else { // Only grab the relevant trader items and add unique values const traderItems = this.traderAssortHelper.getAssort(sessionID, request.tid).items; const relevantItems = this.itemHelper.findAndReturnChildrenAsItems(traderItems, requestItem.item_id); - const toAdd = relevantItems.filter(traderItem => !itemLib.some(item => traderItem._id === item._id)); // what's this + const toAdd = relevantItems.filter((traderItem) => + !itemLib.some((item) => traderItem._id === item._id) + ); // what's this itemLib.push(...toAdd); } @@ -133,7 +149,15 @@ export class InventoryHelper for (const itemToAdd of itemsToAdd) { - const errorOutput = this.placeItemInInventory(itemToAdd, stashFS2D, sortingTableFS2D, itemLib, pmcData.Inventory, useSortingTable, output); + const errorOutput = this.placeItemInInventory( + itemToAdd, + stashFS2D, + sortingTableFS2D, + itemLib, + pmcData.Inventory, + useSortingTable, + output, + ); if (errorOutput) { return errorOutput; @@ -151,9 +175,9 @@ export class InventoryHelper catch (err) { // Callback failed - const message = typeof err === "string" - ? err - : this.localisationService.getText("http-unknown_error"); + const message = typeof err === "string" ? + err : + this.localisationService.getText("http-unknown_error"); return this.httpResponse.appendErrorToOutput(output, message); } @@ -163,7 +187,7 @@ export class InventoryHelper { let idForItemToAdd = this.hashUtil.generate(); const toDo: string[][] = [[itemToAdd.itemRef._id, idForItemToAdd]]; // WHAT IS THIS?! - let upd: Upd = { StackObjectsCount: itemToAdd.count }; + let upd: Upd = {StackObjectsCount: itemToAdd.count}; // If item being added is preset, load preset's upd data too. if (itemToAdd.isPreset) @@ -191,7 +215,7 @@ export class InventoryHelper // add ragfair upd properties if (addUpd) { - upd = { ...addUpd, ...upd }; + upd = {...addUpd, ...upd}; } // Hideout items need to be marked as found in raid @@ -200,7 +224,7 @@ export class InventoryHelper { upd.SpawnedInSession = true; } - + // Remove invalid properties prior to adding to inventory if (upd.UnlimitedCount !== undefined) { @@ -222,8 +246,8 @@ export class InventoryHelper _tpl: itemToAdd.itemRef._tpl, parentId: itemToAdd.containerId, slotId: "hideout", - location: { x: itemToAdd.location.x, y: itemToAdd.location.y, r: itemToAdd.location.rotation ? 1 : 0 }, - upd: this.jsonUtil.clone(upd) + location: {x: itemToAdd.location.x, y: itemToAdd.location.y, r: itemToAdd.location.rotation ? 1 : 0}, + upd: this.jsonUtil.clone(upd), }); pmcData.Inventory.items.push({ @@ -231,8 +255,8 @@ export class InventoryHelper _tpl: itemToAdd.itemRef._tpl, parentId: itemToAdd.containerId, slotId: "hideout", - location: { x: itemToAdd.location.x, y: itemToAdd.location.y, r: itemToAdd.location.rotation ? 1 : 0 }, - upd: this.jsonUtil.clone(upd) // Clone upd to prevent multi-purchases of same item referencing same upd object in memory + location: {x: itemToAdd.location.x, y: itemToAdd.location.y, r: itemToAdd.location.rotation ? 1 : 0}, + upd: this.jsonUtil.clone(upd), // Clone upd to prevent multi-purchases of same item referencing same upd object in memory }); if (this.itemHelper.isOfBaseclass(itemToAdd.itemRef._tpl, BaseClasses.AMMO_BOX)) @@ -255,7 +279,7 @@ export class InventoryHelper // If its from ItemPreset, load preset's upd data too. if (itemToAdd.isPreset) { - upd = { StackObjectsCount: itemToAdd.count }; + upd = {StackObjectsCount: itemToAdd.count}; for (const updID in itemLib[tmpKey].upd) { @@ -278,8 +302,9 @@ export class InventoryHelper location: { x: itemToAdd.location.x, y: itemToAdd.location.y, - r: "Horizontal" }, - upd: this.jsonUtil.clone(upd) + r: "Horizontal", + }, + upd: this.jsonUtil.clone(upd), }); pmcData.Inventory.items.push({ @@ -290,8 +315,9 @@ export class InventoryHelper location: { x: itemToAdd.location.x, y: itemToAdd.location.y, - r: "Horizontal" }, - upd: this.jsonUtil.clone(upd) + r: "Horizontal", + }, + upd: this.jsonUtil.clone(upd), }); } else @@ -310,7 +336,7 @@ export class InventoryHelper parentId: toDo[0][1], slotId: slotID, ...itemLocation, - upd: this.jsonUtil.clone(upd) + upd: this.jsonUtil.clone(upd), }); pmcData.Inventory.items.push({ @@ -319,7 +345,7 @@ export class InventoryHelper parentId: toDo[0][1], slotId: itemLib[tmpKey].slotId, ...itemLocation, - upd: this.jsonUtil.clone(upd) + upd: this.jsonUtil.clone(upd), }); this.logger.debug(`Added ${itemLib[tmpKey]._tpl} with id: ${idForItemToAdd} to inventory`); } @@ -340,13 +366,21 @@ export class InventoryHelper * @param itemToAdd Item to add to inventory * @param stashFS2D Two dimentional stash map * @param sortingTableFS2D Two dimentional sorting table stash map - * @param itemLib + * @param itemLib * @param pmcData Player profile * @param useSortingTable Should sorting table be used for overflow items when no inventory space for item * @param output Client output object * @returns Client error output if placing item failed */ - protected placeItemInInventory(itemToAdd: IAddItemTempObject, stashFS2D: number[][], sortingTableFS2D: number[][], itemLib: Item[], playerInventory: Inventory, useSortingTable: boolean, output: IItemEventRouterResponse): IItemEventRouterResponse + protected placeItemInInventory( + itemToAdd: IAddItemTempObject, + stashFS2D: number[][], + sortingTableFS2D: number[][], + itemLib: Item[], + playerInventory: Inventory, + useSortingTable: boolean, + output: IItemEventRouterResponse, + ): IItemEventRouterResponse { const itemSize = this.getItemSize(itemToAdd.itemRef._tpl, itemToAdd.itemRef._id, itemLib); @@ -360,16 +394,26 @@ export class InventoryHelper try { - stashFS2D = this.containerHelper.fillContainerMapWithItem(stashFS2D, findSlotResult.x, findSlotResult.y, itemSizeX, itemSizeY, false); // TODO: rotation not passed in, bad? + stashFS2D = this.containerHelper.fillContainerMapWithItem( + stashFS2D, + findSlotResult.x, + findSlotResult.y, + itemSizeX, + itemSizeY, + false, + ); // TODO: rotation not passed in, bad? } catch (err) { - const errorText = typeof err === "string" - ? ` -> ${err}` - : ""; + const errorText = typeof err === "string" ? + ` -> ${err}` : + ""; this.logger.error(this.localisationService.getText("inventory-fill_container_failed", errorText)); - return this.httpResponse.appendErrorToOutput(output, this.localisationService.getText("inventory-no_stash_space")); + return this.httpResponse.appendErrorToOutput( + output, + this.localisationService.getText("inventory-no_stash_space"), + ); } // Store details for object, incuding container item will be placed in itemToAdd.containerId = playerInventory.stash; @@ -377,7 +421,7 @@ export class InventoryHelper x: findSlotResult.x, y: findSlotResult.y, r: findSlotResult.rotation ? 1 : 0, - rotation: findSlotResult.rotation + rotation: findSlotResult.rotation, }; // Success! exit @@ -387,19 +431,33 @@ export class InventoryHelper // Space not found in main stash, use sorting table if (useSortingTable) { - const findSortingSlotResult = this.containerHelper.findSlotForItem(sortingTableFS2D, itemSize[0], itemSize[1]); + const findSortingSlotResult = this.containerHelper.findSlotForItem( + sortingTableFS2D, + itemSize[0], + itemSize[1], + ); const itemSizeX = findSortingSlotResult.rotation ? itemSize[1] : itemSize[0]; const itemSizeY = findSortingSlotResult.rotation ? itemSize[0] : itemSize[1]; try { - sortingTableFS2D = this.containerHelper.fillContainerMapWithItem(sortingTableFS2D, findSortingSlotResult.x, findSortingSlotResult.y, itemSizeX, itemSizeY, false); // TODO: rotation not passed in, bad? + sortingTableFS2D = this.containerHelper.fillContainerMapWithItem( + sortingTableFS2D, + findSortingSlotResult.x, + findSortingSlotResult.y, + itemSizeX, + itemSizeY, + false, + ); // TODO: rotation not passed in, bad? } catch (err) { const errorText = typeof err === "string" ? ` -> ${err}` : ""; this.logger.error(this.localisationService.getText("inventory-fill_container_failed", errorText)); - return this.httpResponse.appendErrorToOutput(output, this.localisationService.getText("inventory-no_stash_space")); + return this.httpResponse.appendErrorToOutput( + output, + this.localisationService.getText("inventory-no_stash_space"), + ); } // Store details for object, incuding container item will be placed in @@ -408,12 +466,15 @@ export class InventoryHelper x: findSortingSlotResult.x, y: findSortingSlotResult.y, r: findSortingSlotResult.rotation ? 1 : 0, - rotation: findSortingSlotResult.rotation + rotation: findSortingSlotResult.rotation, }; } else { - return this.httpResponse.appendErrorToOutput(output, this.localisationService.getText("inventory-no_stash_space")); + return this.httpResponse.appendErrorToOutput( + output, + this.localisationService.getText("inventory-no_stash_space"), + ); } } @@ -427,7 +488,14 @@ export class InventoryHelper * @param output object to send to client * @param foundInRaid should ammo be FiR */ - protected hydrateAmmoBoxWithAmmo(pmcData: IPmcData, itemToAdd: IAddItemTempObject, parentId: string, sessionID: string, output: IItemEventRouterResponse, foundInRaid: boolean): void + protected hydrateAmmoBoxWithAmmo( + pmcData: IPmcData, + itemToAdd: IAddItemTempObject, + parentId: string, + sessionID: string, + output: IItemEventRouterResponse, + foundInRaid: boolean, + ): void { const itemInfo = this.itemHelper.getItem(itemToAdd.itemRef._tpl)[1]; const stackSlots = itemInfo._props.StackSlots; @@ -450,7 +518,7 @@ export class InventoryHelper parentId: parentId, slotId: "cartridges", location: location, - upd: { StackObjectsCount: ammoStackSize } + upd: {StackObjectsCount: ammoStackSize}, }; if (foundInRaid) @@ -472,7 +540,6 @@ export class InventoryHelper } /** - * * @param assortItems Items to add to inventory * @param requestItem Details of purchased item to add to inventory * @param result Array split stacks are added to @@ -488,18 +555,21 @@ export class InventoryHelper const itemToAdd: IAddItemTempObject = { itemRef: item, count: requestItem.count, - isPreset: requestItem.isPreset }; + isPreset: requestItem.isPreset, + }; // Split stacks if the size is higher than allowed by items StackMaxSize property let maxStackCount = 1; if (requestItem.count > itemDetails._props.StackMaxSize) { let remainingCountOfItemToAdd = requestItem.count; - const calc = requestItem.count - (Math.floor(requestItem.count / itemDetails._props.StackMaxSize) * itemDetails._props.StackMaxSize); + const calc = requestItem.count - + (Math.floor(requestItem.count / itemDetails._props.StackMaxSize) * + itemDetails._props.StackMaxSize); - maxStackCount = (calc > 0) - ? maxStackCount + Math.floor(remainingCountOfItemToAdd / itemDetails._props.StackMaxSize) - : Math.floor(remainingCountOfItemToAdd / itemDetails._props.StackMaxSize); + maxStackCount = (calc > 0) ? + maxStackCount + Math.floor(remainingCountOfItemToAdd / itemDetails._props.StackMaxSize) : + Math.floor(remainingCountOfItemToAdd / itemDetails._props.StackMaxSize); // Iterate until totalCountOfPurchasedItem is 0 for (let i = 0; i < maxStackCount; i++) @@ -542,7 +612,12 @@ export class InventoryHelper * @param output Existing IItemEventRouterResponse object to append data to, creates new one by default if not supplied * @returns IItemEventRouterResponse */ - public removeItem(profile: IPmcData, itemId: string, sessionID: string, output: IItemEventRouterResponse = undefined): IItemEventRouterResponse + public removeItem( + profile: IPmcData, + itemId: string, + sessionID: string, + output: IItemEventRouterResponse = undefined, + ): IItemEventRouterResponse { if (!itemId) { @@ -559,14 +634,14 @@ export class InventoryHelper // We have output object, inform client of item deletion if (output) { - output.profileChanges[sessionID].items.del.push({ _id: itemId }); + output.profileChanges[sessionID].items.del.push({_id: itemId}); } for (const childId of itemToRemoveWithChildren) { // We expect that each inventory item and each insured item has unique "_id", respective "itemId". // Therefore we want to use a NON-Greedy function and escape the iteration as soon as we find requested item. - const inventoryIndex = inventoryItems.findIndex(item => item._id === childId); + const inventoryIndex = inventoryItems.findIndex((item) => item._id === childId); if (inventoryIndex > -1) { inventoryItems.splice(inventoryIndex, 1); @@ -574,10 +649,12 @@ export class InventoryHelper if (inventoryIndex === -1) { - this.logger.warning(`Unable to remove item with Id: ${childId} as it was not found in inventory ${profile._id}`); + this.logger.warning( + `Unable to remove item with Id: ${childId} as it was not found in inventory ${profile._id}`, + ); } - const insuredIndex = insuredItems.findIndex(item => item.itemId === childId); + const insuredIndex = insuredItems.findIndex((item) => item.itemId === childId); if (insuredIndex > -1) { insuredItems.splice(insuredIndex, 1); @@ -587,7 +664,11 @@ export class InventoryHelper return output; } - public removeItemAndChildrenFromMailRewards(sessionId: string, removeRequest: IInventoryRemoveRequestData, output: IItemEventRouterResponse): IItemEventRouterResponse + public removeItemAndChildrenFromMailRewards( + sessionId: string, + removeRequest: IInventoryRemoveRequestData, + output: IItemEventRouterResponse, + ): IItemEventRouterResponse { const fullProfile = this.profileHelper.getFullProfile(sessionId); @@ -595,18 +676,23 @@ export class InventoryHelper const dialogs = Object.values(fullProfile.dialogues); for (const dialog of dialogs) { - const messageWithReward = dialog.messages.find(x => x._id === removeRequest.fromOwner.id); + const messageWithReward = dialog.messages.find((x) => x._id === removeRequest.fromOwner.id); if (messageWithReward) { // Find item + any possible children and remove them from mails items array - const itemWithChildern = this.itemHelper.findAndReturnChildrenAsItems(messageWithReward.items.data, removeRequest.item); + const itemWithChildern = this.itemHelper.findAndReturnChildrenAsItems( + messageWithReward.items.data, + removeRequest.item, + ); for (const itemToDelete of itemWithChildern) { // Get index of item to remove from reward array + remove it const indexOfItemToRemove = messageWithReward.items.data.indexOf(itemToDelete); if (indexOfItemToRemove === -1) { - this.logger.error(`Unable to remove item: ${removeRequest.item} from mail: ${removeRequest.fromOwner.id} as item could not be found, restart client immediately to prevent data corruption`); + this.logger.error( + `Unable to remove item: ${removeRequest.item} from mail: ${removeRequest.fromOwner.id} as item could not be found, restart client immediately to prevent data corruption`, + ); continue; } messageWithReward.items.data.splice(indexOfItemToRemove, 1); @@ -622,10 +708,18 @@ export class InventoryHelper return output; } - public removeItemByCount(pmcData: IPmcData, itemId: string, count: number, sessionID: string, output: IItemEventRouterResponse = undefined): IItemEventRouterResponse + public removeItemByCount( + pmcData: IPmcData, + itemId: string, + count: number, + sessionID: string, + output: IItemEventRouterResponse = undefined, + ): IItemEventRouterResponse { if (!itemId) + { return output; + } const itemsToReduce = this.itemHelper.findAndReturnChildrenAsItems(pmcData.Inventory.items, itemId); let remainingCount = count; @@ -644,11 +738,15 @@ export class InventoryHelper itemToReduce.upd.StackObjectsCount -= remainingCount; remainingCount = 0; if (output) + { output.profileChanges[sessionID].items.change.push(itemToReduce); + } } if (remainingCount === 0) + { break; + } } return output; @@ -666,7 +764,11 @@ export class InventoryHelper // note from 2027: there IS a thing i didn't explore and that is Merges With Children // -> Prepares item Width and height returns [sizeX, sizeY] - protected getSizeByInventoryItemHash(itemTpl: string, itemID: string, inventoryItemHash: InventoryHelper.InventoryItemHash): number[] + protected getSizeByInventoryItemHash( + itemTpl: string, + itemID: string, + inventoryItemHash: InventoryHelper.InventoryItemHash, + ): number[] { const toDo = [itemID]; const result = this.itemHelper.getItem(itemTpl); @@ -681,7 +783,10 @@ export class InventoryHelper // Item found but no _props property if (tmpItem && !tmpItem._props) { - this.localisationService.getText("inventory-item_missing_props_property", {itemTpl: itemTpl, itemName: tmpItem?._name}); + this.localisationService.getText("inventory-item_missing_props_property", { + itemTpl: itemTpl, + itemName: tmpItem?._name, + }); } // No item object or getItem() returned false @@ -711,11 +816,11 @@ export class InventoryHelper const skipThisItems: string[] = [ BaseClasses.BACKPACK, BaseClasses.SEARCHABLE_ITEM, - BaseClasses.SIMPLE_CONTAINER + BaseClasses.SIMPLE_CONTAINER, ]; const rootFolded = rootItem.upd?.Foldable && rootItem.upd.Foldable.Folded === true; - //The item itself is collapsible + // The item itself is collapsible if (foldableWeapon && (foldedSlot === undefined || foldedSlot === "") && rootFolded) { outX -= tmpItem._props.SizeReduceRight; @@ -729,7 +834,7 @@ export class InventoryHelper { for (const item of inventoryItemHash.byParentId[toDo[0]]) { - //Filtering child items outside of mod slots, such as those inside containers, without counting their ExtraSize attribute + // Filtering child items outside of mod slots, such as those inside containers, without counting their ExtraSize attribute if (item.slotId.indexOf("mod_") < 0) { continue; @@ -741,7 +846,12 @@ export class InventoryHelper const itemResult = this.itemHelper.getItem(item._tpl); if (!itemResult[0]) { - this.logger.error(this.localisationService.getText("inventory-get_item_size_item_not_found_by_tpl", item._tpl)); + this.logger.error( + this.localisationService.getText( + "inventory-get_item_size_item_not_found_by_tpl", + item._tpl, + ), + ); } const itm = itemResult[1]; @@ -781,7 +891,7 @@ export class InventoryHelper return [ outX + sizeLeft + sizeRight + forcedLeft + forcedRight, - outY + sizeUp + sizeDown + forcedUp + forcedDown + outY + sizeUp + sizeDown + forcedUp + forcedDown, ]; } @@ -789,7 +899,7 @@ export class InventoryHelper { const inventoryItemHash: InventoryHelper.InventoryItemHash = { byItemId: {}, - byParentId: {} + byParentId: {}, }; for (const item of inventoryItem) @@ -832,8 +942,14 @@ export class InventoryHelper const tmpSize = this.getSizeByInventoryItemHash(item._tpl, item._id, inventoryItemHash); const iW = tmpSize[0]; // x const iH = tmpSize[1]; // y - const fH = (((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" || (item.location as Location).rotation === "Vertical") ? iW : iH); - const fW = (((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" || (item.location as Location).rotation === "Vertical") ? iH : iW); + const fH = ((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" || + (item.location as Location).rotation === "Vertical") ? + iW : + iH; + const fW = ((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" || + (item.location as Location).rotation === "Vertical") ? + iH : + iW; const fillTo = (item.location as Location).x + fW; for (let y = 0; y < fH; y++) @@ -844,7 +960,12 @@ export class InventoryHelper } catch (e) { - this.logger.error(this.localisationService.getText("inventory-unable_to_fill_container", {id: item._id, error: e})); + this.logger.error( + this.localisationService.getText("inventory-unable_to_fill_container", { + id: item._id, + error: e, + }), + ); } } } @@ -860,7 +981,10 @@ export class InventoryHelper * @param sessionId Session id / playerid * @returns OwnerInventoryItems with inventory of player/scav to adjust */ - public getOwnerInventoryItems(request: IInventoryMoveRequestData | IInventorySplitRequestData | IInventoryMergeRequestData, sessionId: string): OwnerInventoryItems + public getOwnerInventoryItems( + request: IInventoryMoveRequestData | IInventorySplitRequestData | IInventoryMergeRequestData, + sessionId: string, + ): OwnerInventoryItems { let isSameInventory = false; const pmcItems = this.profileHelper.getPmcProfile(sessionId).Inventory.items; @@ -878,9 +1002,9 @@ export class InventoryHelper else if (request.fromOwner.type.toLocaleLowerCase() === "mail") { // Split requests dont use 'use' but 'splitItem' property - const item = "splitItem" in request - ? request.splitItem - : request.item; + const item = "splitItem" in request ? + request.splitItem : + request.item; fromInventoryItems = this.dialogueHelper.getMessageItemContents(request.fromOwner.id, sessionId, item); fromType = "mail"; } @@ -908,7 +1032,7 @@ export class InventoryHelper from: fromInventoryItems, to: toInventoryItems, sameInventory: isSameInventory, - isMail: fromType === "mail" + isMail: fromType === "mail", }; } @@ -921,7 +1045,12 @@ export class InventoryHelper protected getStashSlotMap(pmcData: IPmcData, sessionID: string): number[][] { const playerStashSize = this.getPlayerStashSize(sessionID); - return this.getContainerMap(playerStashSize[0], playerStashSize[1], pmcData.Inventory.items, pmcData.Inventory.stash); + return this.getContainerMap( + playerStashSize[0], + playerStashSize[1], + pmcData.Inventory.items, + pmcData.Inventory.stash, + ); } protected getSortingTableSlotMap(pmcData: IPmcData): number[][] @@ -936,7 +1065,7 @@ export class InventoryHelper */ protected getPlayerStashSize(sessionID: string): Record { - //this sets automatically a stash size from items.json (its not added anywhere yet cause we still use base stash) + // this sets automatically a stash size from items.json (its not added anywhere yet cause we still use base stash) const stashTPL = this.getStashType(sessionID); if (!stashTPL) { @@ -948,12 +1077,12 @@ export class InventoryHelper this.logger.error(this.localisationService.getText("inventory-stash_not_found", stashTPL)); } - const stashX = stashItemDetails[1]._props.Grids[0]._props.cellsH !== 0 - ? stashItemDetails[1]._props.Grids[0]._props.cellsH - : 10; - const stashY = stashItemDetails[1]._props.Grids[0]._props.cellsV !== 0 - ? stashItemDetails[1]._props.Grids[0]._props.cellsV - : 66; + const stashX = stashItemDetails[1]._props.Grids[0]._props.cellsH !== 0 ? + stashItemDetails[1]._props.Grids[0]._props.cellsH : + 10; + const stashY = stashItemDetails[1]._props.Grids[0]._props.cellsV !== 0 ? + stashItemDetails[1]._props.Grids[0]._props.cellsV : + 66; return [stashX, stashY]; } @@ -965,7 +1094,7 @@ export class InventoryHelper protected getStashType(sessionID: string): string { const pmcData = this.profileHelper.getPmcProfile(sessionID); - const stashObj = pmcData.Inventory.items.find(item => item._id === pmcData.Inventory.stash); + const stashObj = pmcData.Inventory.items.find((item) => item._id === pmcData.Inventory.stash); if (!stashObj) { this.logger.error(this.localisationService.getText("inventory-unable_to_find_stash")); @@ -987,7 +1116,7 @@ export class InventoryHelper const idsToMove = this.itemHelper.findAndReturnChildrenByItems(fromItems, body.item); for (const itemId of idsToMove) { - const itemToMove = fromItems.find(x => x._id === itemId); + const itemToMove = fromItems.find((x) => x._id === itemId); if (!itemToMove) { this.logger.error(`Unable to find item to move: ${itemId}`); @@ -1022,16 +1151,20 @@ export class InventoryHelper /** * Internal helper function to move item within the same profile_f. * @param pmcData profile to edit - * @param inventoryItems - * @param moveRequest + * @param inventoryItems + * @param moveRequest * @returns True if move was successful */ - public moveItemInternal(pmcData: IPmcData, inventoryItems: Item[], moveRequest: IInventoryMoveRequestData): {success: boolean, errorMessage?: string} + public moveItemInternal( + pmcData: IPmcData, + inventoryItems: Item[], + moveRequest: IInventoryMoveRequestData, + ): {success: boolean; errorMessage?: string;} { this.handleCartridges(inventoryItems, moveRequest); // Find item we want to 'move' - const matchingInventoryItem = inventoryItems.find(x => x._id === moveRequest.item); + const matchingInventoryItem = inventoryItems.find((x) => x._id === moveRequest.item); if (!matchingInventoryItem) { const errorMesage = `Unable to move item: ${moveRequest.item}, cannot find in inventory`; @@ -1040,12 +1173,19 @@ export class InventoryHelper return {success: false, errorMessage: errorMesage}; } - this.logger.debug(`${moveRequest.Action} item: ${moveRequest.item} from slotid: ${matchingInventoryItem.slotId} to container: ${moveRequest.to.container}`); + this.logger.debug( + `${moveRequest.Action} item: ${moveRequest.item} from slotid: ${matchingInventoryItem.slotId} to container: ${moveRequest.to.container}`, + ); // don't move shells from camora to cartridges (happens when loading shells into mts-255 revolver shotgun) if (matchingInventoryItem.slotId.includes("camora_") && moveRequest.to.container === "cartridges") { - this.logger.warning(this.localisationService.getText("inventory-invalid_move_to_container", {slotId: matchingInventoryItem.slotId, container: moveRequest.to.container})); + this.logger.warning( + this.localisationService.getText("inventory-invalid_move_to_container", { + slotId: matchingInventoryItem.slotId, + container: moveRequest.to.container, + }), + ); return {success: true}; } @@ -1059,7 +1199,6 @@ export class InventoryHelper if ("location" in moveRequest.to) { matchingInventoryItem.location = moveRequest.to.location; - } else { @@ -1085,8 +1224,8 @@ export class InventoryHelper if (pmcData.Inventory.fastPanel[itemKey] === itemBeingMoved._id) { // Get moved items parent - const itemParent = pmcData.Inventory.items.find(x => x._id === itemBeingMoved.parentId); - + const itemParent = pmcData.Inventory.items.find((x) => x._id === itemBeingMoved.parentId); + // Empty out id if item is moved to a container other than pocket/rig if (itemParent && !(itemParent.slotId?.startsWith("Pockets") || itemParent.slotId === "TacticalVest")) { @@ -1099,8 +1238,8 @@ export class InventoryHelper } /** - * Internal helper function to handle cartridges in inventory if any of them exist. - */ + * Internal helper function to handle cartridges in inventory if any of them exist. + */ protected handleCartridges(items: Item[], body: IInventoryMoveRequestData): void { // -> Move item to different place - counts with equipping filling magazine etc @@ -1140,7 +1279,7 @@ namespace InventoryHelper { export interface InventoryItemHash { - byItemId: Record - byParentId: Record + byItemId: Record; + byParentId: Record; } -} \ No newline at end of file +} diff --git a/project/src/helpers/ItemHelper.ts b/project/src/helpers/ItemHelper.ts index 2de92170..f0451687 100644 --- a/project/src/helpers/ItemHelper.ts +++ b/project/src/helpers/ItemHelper.ts @@ -29,7 +29,7 @@ class ItemHelper BaseClasses.SORTING_TABLE, BaseClasses.INVENTORY, BaseClasses.STATIONARY_CONTAINER, - BaseClasses.POCKETS + BaseClasses.POCKETS, ]; constructor( @@ -44,7 +44,7 @@ class ItemHelper @inject("ItemBaseClassService") protected itemBaseClassService: ItemBaseClassService, @inject("ItemFilterService") protected itemFilterService: ItemFilterService, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("LocaleService") protected localeService: LocaleService + @inject("LocaleService") protected localeService: LocaleService, ) {} @@ -68,11 +68,11 @@ class ItemHelper } // Is item valid - return !itemDetails[1]._props.QuestItem - && itemDetails[1]._type === "Item" - && invalidBaseTypes.every(x => !this.isOfBaseclass(tpl, x)) - && this.getItemPrice(tpl) > 0 - && !this.itemFilterService.isItemBlacklisted(tpl); + return !itemDetails[1]._props.QuestItem && + itemDetails[1]._type === "Item" && + invalidBaseTypes.every((x) => !this.isOfBaseclass(tpl, x)) && + this.getItemPrice(tpl) > 0 && + !this.itemFilterService.isItemBlacklisted(tpl); } /** @@ -177,7 +177,7 @@ class ItemHelper if (item.upd === undefined) { item.upd = { - StackObjectsCount: 1 + StackObjectsCount: 1, }; } @@ -244,8 +244,8 @@ class ItemHelper slotId: slotId, location: 0, upd: { - StackObjectsCount: count - } + StackObjectsCount: count, + }, }; stackSlotItems.push(stackSlotItem); } @@ -352,7 +352,6 @@ class ItemHelper return result; } - /** * Get a quality value based on a repairable items (weapon/armor) current state between current and max durability * @param itemDetails Db details for item we want quality value for @@ -365,7 +364,9 @@ class ItemHelper // Edge case, max durability is below durability if (repairable.Durability > repairable.MaxDurability) { - this.logger.warning(`Max durability: ${repairable.MaxDurability} for item id: ${item._id} was below Durability: ${repairable.Durability}, adjusting values to match`); + this.logger.warning( + `Max durability: ${repairable.MaxDurability} for item id: ${item._id} was below Durability: ${repairable.Durability}, adjusting values to match`, + ); repairable.MaxDurability = repairable.Durability; } @@ -377,9 +378,9 @@ class ItemHelper // Weapon // Get max dura from props, if it isnt there use repairable max dura value - const maxDurability = (itemDetails._props.MaxDurability) - ? itemDetails._props.MaxDurability - : repairable.MaxDurability; + const maxDurability = (itemDetails._props.MaxDurability) ? + itemDetails._props.MaxDurability : + repairable.MaxDurability; const durability = repairable.Durability / maxDurability; if (!durability) @@ -434,7 +435,7 @@ class ItemHelper continue; } - if (childItem.parentId === baseItemId && !list.find(item => childItem._id === item._id)) + if (childItem.parentId === baseItemId && !list.find((item) => childItem._id === item._id)) { list.push(...this.findAndReturnChildrenAsItems(items, childItem._id)); } @@ -455,7 +456,7 @@ class ItemHelper for (const itemFromAssort of assort) { - if (itemFromAssort.parentId === itemIdToFind && !list.find(item => itemFromAssort._id === item._id)) + if (itemFromAssort.parentId === itemIdToFind && !list.find((item) => itemFromAssort._id === item._id)) { list.push(itemFromAssort); list = list.concat(this.findAndReturnChildrenByAssort(itemFromAssort._id, assort)); @@ -472,8 +473,10 @@ class ItemHelper */ public hasBuyRestrictions(itemToCheck: Item): boolean { - if (itemToCheck.upd?.BuyRestrictionCurrent !== undefined - && itemToCheck.upd?.BuyRestrictionMax !== undefined) + if ( + itemToCheck.upd?.BuyRestrictionCurrent !== undefined && + itemToCheck.upd?.BuyRestrictionMax !== undefined + ) { return true; } @@ -571,18 +574,18 @@ class ItemHelper public findBarterItems(by: "tpl" | "id", items: Item[], barterItemId: string): Item[] { // find required items to take after buying (handles multiple items) - const barterIDs = typeof barterItemId === "string" - ? [barterItemId] - : barterItemId; + const barterIDs = typeof barterItemId === "string" ? + [barterItemId] : + barterItemId; let barterItems: Item[] = []; for (const barterID of barterIDs) { - const filterResult = items.filter(item => + const filterResult = items.filter((item) => { - return by === "tpl" - ? (item._tpl === barterID) - : (item._id === barterID); + return by === "tpl" ? + (item._tpl === barterID) : + (item._id === barterID); }); barterItems = Object.assign(barterItems, filterResult); @@ -615,17 +618,19 @@ class ItemHelper { // Insured items shouldn't be renamed // only works for pmcs. - if (insuredItems?.find(insuredItem => insuredItem.itemId === item._id)) + if (insuredItems?.find((insuredItem) => insuredItem.itemId === item._id)) { continue; } // Do not replace important ID's - if (item._id === pmcData.Inventory.equipment - || item._id === pmcData.Inventory.questRaidItems - || item._id === pmcData.Inventory.questStashItems - || item._id === pmcData.Inventory.sortingTable - || item._id === pmcData.Inventory.stash) + if ( + item._id === pmcData.Inventory.equipment || + item._id === pmcData.Inventory.questRaidItems || + item._id === pmcData.Inventory.questStashItems || + item._id === pmcData.Inventory.sortingTable || + item._id === pmcData.Inventory.stash + ) { continue; } @@ -804,7 +809,9 @@ class ItemHelper let isRequiredSlot = false; if (parentTemplate[0] && parentTemplate[1]?._props?.Slots) { - isRequiredSlot = parentTemplate[1]._props.Slots.some(slot => slot._name === item.slotId && slot._required); + isRequiredSlot = parentTemplate[1]._props.Slots.some((slot) => + slot._name === item.slotId && slot._required + ); } return itemTemplate[0] && parentTemplate[0] && !(isNotRaidModdable || isRequiredSlot); @@ -865,7 +872,7 @@ class ItemHelper */ public getItemSize(items: Item[], rootItemId: string): ItemHelper.ItemSize { - const rootTemplate = this.getItem(items.filter(x => x._id === rootItemId)[0]._tpl)[1]; + const rootTemplate = this.getItem(items.filter((x) => x._id === rootItemId)[0]._tpl)[1]; const width = rootTemplate._props.Width; const height = rootTemplate._props.Height; @@ -897,13 +904,15 @@ class ItemHelper sizeUp = sizeUp < itemTemplate._props.ExtraSizeUp ? itemTemplate._props.ExtraSizeUp : sizeUp; sizeDown = sizeDown < itemTemplate._props.ExtraSizeDown ? itemTemplate._props.ExtraSizeDown : sizeDown; sizeLeft = sizeLeft < itemTemplate._props.ExtraSizeLeft ? itemTemplate._props.ExtraSizeLeft : sizeLeft; - sizeRight = sizeRight < itemTemplate._props.ExtraSizeRight ? itemTemplate._props.ExtraSizeRight : sizeRight; + sizeRight = sizeRight < itemTemplate._props.ExtraSizeRight ? + itemTemplate._props.ExtraSizeRight : + sizeRight; } } return { width: width + sizeLeft + sizeRight + forcedLeft + forcedRight, - height: height + sizeUp + sizeDown + forcedUp + forcedDown + height: height + sizeUp + sizeDown + forcedUp + forcedDown, }; } @@ -945,15 +954,15 @@ class ItemHelper while (currentStoredCartridgeCount < ammoBoxMaxCartridgeCount) { const remainingSpace = ammoBoxMaxCartridgeCount - currentStoredCartridgeCount; - const cartridgeCountToAdd = (remainingSpace < maxPerStack) - ? remainingSpace - : maxPerStack; + const cartridgeCountToAdd = (remainingSpace < maxPerStack) ? + remainingSpace : + maxPerStack; // Add cartridge item into items array ammoBox.push(this.createCartridges(ammoBox[0]._id, cartridgeTpl, cartridgeCountToAdd, location)); currentStoredCartridgeCount += cartridgeCountToAdd; - location ++; + location++; } } @@ -967,7 +976,7 @@ class ItemHelper public itemIsInsideContainer(item: Item, desiredContainerSlotId: string, items: Item[]): boolean { // Get items parent - const parent = items.find(x => x._id === item.parentId); + const parent = items.find((x) => x._id === item.parentId); if (!parent) { // No parent, end of line, not inside container @@ -997,7 +1006,7 @@ class ItemHelper magTemplate: ITemplateItem, staticAmmoDist: Record, caliber: string = undefined, - minSizePercent = 0.25 + minSizePercent = 0.25, ): void { // no caliber defined, choose one at random @@ -1028,7 +1037,7 @@ class ItemHelper magazine: Item[], magTemplate: ITemplateItem, cartridgeTpl: string, - minSizePercent = 0.25 + minSizePercent = 0.25, ): void { // Get cartrdge properties and max allowed stack size @@ -1037,7 +1046,10 @@ class ItemHelper // Get max number of cartridges in magazine, choose random value between min/max const magazineCartridgeMaxCount = magTemplate._props.Cartridges[0]._max_count; - const desiredStackCount = this.randomUtil.getInt(Math.round(minSizePercent * magazineCartridgeMaxCount), magazineCartridgeMaxCount); + const desiredStackCount = this.randomUtil.getInt( + Math.round(minSizePercent * magazineCartridgeMaxCount), + magazineCartridgeMaxCount, + ); // Loop over cartridge count and add stacks to magazine let currentStoredCartridgeCount = 0; @@ -1045,9 +1057,9 @@ class ItemHelper while (currentStoredCartridgeCount < desiredStackCount) { // Get stack size of cartridges - let cartridgeCountToAdd = (desiredStackCount <= cartridgeMaxStackSize) - ? desiredStackCount - : cartridgeMaxStackSize; + let cartridgeCountToAdd = (desiredStackCount <= cartridgeMaxStackSize) ? + desiredStackCount : + cartridgeMaxStackSize; // Ensure we don't go over the max stackcount size const remainingSpace = desiredStackCount - currentStoredCartridgeCount; @@ -1060,7 +1072,7 @@ class ItemHelper magazine.push(this.createCartridges(magazine[0]._id, cartridgeTpl, cartridgeCountToAdd, location)); currentStoredCartridgeCount += cartridgeCountToAdd; - location ++; + location++; } } @@ -1075,11 +1087,11 @@ class ItemHelper const calibers = [ ...new Set( ammoTpls.filter( - (x: string) => this.getItem(x)[0] + (x: string) => this.getItem(x)[0], ).map( - (x: string) => this.getItem(x)[1]._props.Caliber - ) - ) + (x: string) => this.getItem(x)[1]._props.Caliber, + ), + ), ]; return this.randomUtil.drawRandomFromList(calibers)[0]; } @@ -1096,7 +1108,7 @@ class ItemHelper for (const icd of staticAmmoDist[caliber]) { ammoArray.push( - new ProbabilityObject(icd.tpl, icd.relativeProbability) + new ProbabilityObject(icd.tpl, icd.relativeProbability), ); } return ammoArray.draw(1)[0]; @@ -1118,7 +1130,7 @@ class ItemHelper parentId: parentId, slotId: "cartridges", location: location, - upd: { StackObjectsCount: stackCount } + upd: {StackObjectsCount: stackCount}, }; } @@ -1149,7 +1161,9 @@ class ItemHelper public getItemTplsOfBaseType(desiredBaseType: string): string[] { - return Object.values(this.databaseServer.getTables().templates.items).filter(x => x._parent === desiredBaseType).map(x =>x._id); + return Object.values(this.databaseServer.getTables().templates.items).filter((x) => + x._parent === desiredBaseType + ).map((x) => x._id); } } @@ -1157,10 +1171,9 @@ namespace ItemHelper { export interface ItemSize { - width: number - height: number + width: number; + height: number; } } -export { ItemHelper }; - +export {ItemHelper}; diff --git a/project/src/helpers/NotificationSendHelper.ts b/project/src/helpers/NotificationSendHelper.ts index 32e81201..f70a6290 100644 --- a/project/src/helpers/NotificationSendHelper.ts +++ b/project/src/helpers/NotificationSendHelper.ts @@ -16,14 +16,14 @@ export class NotificationSendHelper @inject("WebSocketServer") protected webSocketServer: WebSocketServer, @inject("HashUtil") protected hashUtil: HashUtil, @inject("SaveServer") protected saveServer: SaveServer, - @inject("NotificationService") protected notificationService: NotificationService + @inject("NotificationService") protected notificationService: NotificationService, ) {} /** * Send notification message to the appropriate channel - * @param sessionID - * @param notificationMessage + * @param sessionID + * @param notificationMessage */ public sendMessage(sessionID: string, notificationMessage: INotification): void { @@ -44,7 +44,12 @@ export class NotificationSendHelper * @param messageText Text to send player * @param messageType Underlying type of message being sent */ - public sendMessageToPlayer(sessionId: string, senderDetails: IUserDialogInfo, messageText: string, messageType: MessageType): void + public sendMessageToPlayer( + sessionId: string, + senderDetails: IUserDialogInfo, + messageText: string, + messageType: MessageType, + ): void { const dialog = this.getDialog(sessionId, messageType, senderDetails); @@ -57,7 +62,7 @@ export class NotificationSendHelper text: messageText, hasRewards: undefined, rewardCollected: undefined, - items: undefined + items: undefined, }; dialog.messages.push(message); @@ -65,7 +70,7 @@ export class NotificationSendHelper type: NotificationType.NEW_MESSAGE, eventId: message._id, dialogId: message.uid, - message: message + message: message, }; this.sendMessage(sessionId, notification); } @@ -80,7 +85,9 @@ export class NotificationSendHelper protected getDialog(sessionId: string, messageType: MessageType, senderDetails: IUserDialogInfo): Dialogue { // Use trader id if sender is trader, otherwise use nickname - const key = (senderDetails.info.MemberCategory === MemberCategory.TRADER) ? senderDetails._id : senderDetails.info.Nickname; + const key = (senderDetails.info.MemberCategory === MemberCategory.TRADER) ? + senderDetails._id : + senderDetails.info.Nickname; const dialogueData = this.saveServer.getProfile(sessionId).dialogues; const isNewDialogue = !(key in dialogueData); let dialogue: Dialogue = dialogueData[key]; @@ -95,11 +102,11 @@ export class NotificationSendHelper pinned: false, new: 0, attachmentsNew: 0, - Users: (senderDetails.info.MemberCategory === MemberCategory.TRADER) ? undefined : [senderDetails] + Users: (senderDetails.info.MemberCategory === MemberCategory.TRADER) ? undefined : [senderDetails], }; dialogueData[key] = dialogue; } return dialogue; } -} \ No newline at end of file +} diff --git a/project/src/helpers/NotifierHelper.ts b/project/src/helpers/NotifierHelper.ts index d4acdf13..4f340086 100644 --- a/project/src/helpers/NotifierHelper.ts +++ b/project/src/helpers/NotifierHelper.ts @@ -12,11 +12,11 @@ export class NotifierHelper */ protected defaultNotification: INotification = { type: NotificationType.PING, - eventId: "ping" + eventId: "ping", }; constructor( - @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper + @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper, ) {} @@ -29,22 +29,25 @@ export class NotifierHelper * Create a new notification that displays the "Your offer was sold!" prompt and removes sold offer from "My Offers" on clientside * @param dialogueMessage Message from dialog that was sent * @param ragfairData Ragfair data to attach to notification - * @returns + * @returns */ - public createRagfairOfferSoldNotification(dialogueMessage: Message, ragfairData: MessageContentRagfair): INotification + public createRagfairOfferSoldNotification( + dialogueMessage: Message, + ragfairData: MessageContentRagfair, + ): INotification { return { type: NotificationType.RAGFAIR_OFFER_SOLD, eventId: dialogueMessage._id, dialogId: dialogueMessage.uid, - ...ragfairData + ...ragfairData, }; } /** * Create a new notification with the specified dialogueMessage object - * @param dialogueMessage - * @returns + * @param dialogueMessage + * @returns */ public createNewMessageNotification(dialogueMessage: Message): INotification { @@ -52,7 +55,7 @@ export class NotifierHelper type: NotificationType.NEW_MESSAGE, eventId: dialogueMessage._id, dialogId: dialogueMessage.uid, - message: dialogueMessage + message: dialogueMessage, }; } @@ -60,4 +63,4 @@ export class NotifierHelper { return `${this.httpServerHelper.getWebsocketUrl()}/notifierServer/getwebsocket/${sessionID}`; } -} \ No newline at end of file +} diff --git a/project/src/helpers/PaymentHelper.ts b/project/src/helpers/PaymentHelper.ts index e49e4521..a835ab31 100644 --- a/project/src/helpers/PaymentHelper.ts +++ b/project/src/helpers/PaymentHelper.ts @@ -11,7 +11,7 @@ export class PaymentHelper protected inventoryConfig: IInventoryConfig; constructor( - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.inventoryConfig = this.configServer.getConfig(ConfigTypes.INVENTORY); @@ -24,14 +24,16 @@ export class PaymentHelper */ public isMoneyTpl(tpl: string): boolean { - return [Money.DOLLARS, Money.EUROS, Money.ROUBLES, ...this.inventoryConfig.customMoneyTpls].some(element => element === tpl); + return [Money.DOLLARS, Money.EUROS, Money.ROUBLES, ...this.inventoryConfig.customMoneyTpls].some((element) => + element === tpl + ); } /** - * Gets currency TPL from TAG - * @param {string} currency - * @returns string - */ + * Gets currency TPL from TAG + * @param {string} currency + * @returns string + */ public getCurrency(currency: string): string { switch (currency) @@ -46,4 +48,4 @@ export class PaymentHelper return ""; } } -} \ No newline at end of file +} diff --git a/project/src/helpers/PresetHelper.ts b/project/src/helpers/PresetHelper.ts index f48b8767..c973fd98 100644 --- a/project/src/helpers/PresetHelper.ts +++ b/project/src/helpers/PresetHelper.ts @@ -12,9 +12,9 @@ export class PresetHelper constructor( @inject("JsonUtil") protected jsonUtil: JsonUtil, - @inject("DatabaseServer") protected databaseServer: DatabaseServer + @inject("DatabaseServer") protected databaseServer: DatabaseServer, ) - { } + {} public hydratePresetStore(input: Record): void { @@ -26,7 +26,7 @@ export class PresetHelper if (!this.defaultPresets) { this.defaultPresets = Object.values(this.databaseServer.getTables().globals.ItemPresets) - .filter(x => x._encyclopedia !== undefined) + .filter((x) => x._encyclopedia !== undefined) .reduce((acc, cur) => { acc[cur._id] = cur; @@ -112,4 +112,4 @@ export class PresetHelper return ""; } -} \ No newline at end of file +} diff --git a/project/src/helpers/ProbabilityHelper.ts b/project/src/helpers/ProbabilityHelper.ts index f00963e3..f2815447 100644 --- a/project/src/helpers/ProbabilityHelper.ts +++ b/project/src/helpers/ProbabilityHelper.ts @@ -8,9 +8,9 @@ export class ProbabilityHelper { constructor( @inject("WinstonLogger") protected logger: ILogger, - @inject("RandomUtil") protected randomUtil: RandomUtil + @inject("RandomUtil") protected randomUtil: RandomUtil, ) - { } + {} /** * Chance to roll a number out of 100 @@ -20,6 +20,6 @@ export class ProbabilityHelper */ public rollChance(chance: number, scale = 1): boolean { - return (this.randomUtil.getInt(1, 100 * scale)/ (1 * scale)) <= chance; + return (this.randomUtil.getInt(1, 100 * scale) / (1 * scale)) <= chance; } -} \ No newline at end of file +} diff --git a/project/src/helpers/ProfileHelper.ts b/project/src/helpers/ProfileHelper.ts index 74576d48..f852b50c 100644 --- a/project/src/helpers/ProfileHelper.ts +++ b/project/src/helpers/ProfileHelper.ts @@ -27,9 +27,9 @@ export class ProfileHelper @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("ItemHelper") protected itemHelper: ItemHelper, @inject("ProfileSnapshotService") protected profileSnapshotService: ProfileSnapshotService, - @inject("LocalisationService") protected localisationService: LocalisationService + @inject("LocalisationService") protected localisationService: LocalisationService, ) - { } + {} /** * Remove/reset a completed quest condtion from players profile quest data @@ -41,7 +41,7 @@ export class ProfileHelper for (const questId in questConditionId) { const conditionId = questConditionId[questId]; - const profileQuest = pmcData.Quests.find(x => x.qid === questId); + const profileQuest = pmcData.Quests.find((x) => x.qid === questId); // Find index of condition in array const index = profileQuest.completedConditions.indexOf(conditionId); @@ -51,7 +51,7 @@ export class ProfileHelper profileQuest.completedConditions.splice(index, 1); } } - } + } /** * Get all profiles from server @@ -97,7 +97,12 @@ export class ProfileHelper * @param scavProfile post-raid scav profile * @returns updated profile array */ - protected postRaidXpWorkaroundFix(sessionId: string, output: IPmcData[], pmcProfile: IPmcData, scavProfile: IPmcData): IPmcData[] + protected postRaidXpWorkaroundFix( + sessionId: string, + output: IPmcData[], + pmcProfile: IPmcData, + scavProfile: IPmcData, + ): IPmcData[] { const clonedPmc = this.jsonUtil.clone(pmcProfile); const clonedScav = this.jsonUtil.clone(scavProfile); @@ -119,7 +124,7 @@ export class ProfileHelper /** * Check if a nickname is used by another profile loaded by the server - * @param nicknameRequest + * @param nicknameRequest * @param sessionID Session id * @returns True if already used */ @@ -133,8 +138,10 @@ export class ProfileHelper continue; } - if (!this.sessionIdMatchesProfileId(profile.info.id, sessionID) - && this.nicknameMatches(profile.characters.pmc.Info.LowerNickname, nicknameRequest.nickname)) + if ( + !this.sessionIdMatchesProfileId(profile.info.id, sessionID) && + this.nicknameMatches(profile.characters.pmc.Info.LowerNickname, nicknameRequest.nickname) + ) { return true; } @@ -211,7 +218,7 @@ export class ProfileHelper public getDefaultAkiDataObject(): any { return { - version: this.getServerVersion() + version: this.getServerVersion(), }; } @@ -221,10 +228,10 @@ export class ProfileHelper { return undefined; } - + return this.saveServer.getProfile(sessionID); } - + public getPmcProfile(sessionID: string): IPmcData { const fullProfile = this.getFullProfile(sessionID); @@ -232,10 +239,10 @@ export class ProfileHelper { return undefined; } - + return this.saveServer.getProfile(sessionID).characters.pmc; } - + public getScavProfile(sessionID: string): IPmcData { return this.saveServer.getProfile(sessionID).characters.scav; @@ -253,24 +260,24 @@ export class ProfileHelper DamageHistory: { LethalDamagePart: "Head", LethalDamage: undefined, - BodyParts: [] + BodyParts: [], }, DroppedItems: [], ExperienceBonusMult: 0, FoundInRaidItems: [], LastPlayerState: undefined, LastSessionDate: 0, - OverallCounters: { Items: [] }, - SessionCounters: { Items: [] }, + OverallCounters: {Items: []}, + SessionCounters: {Items: []}, SessionExperienceMult: 0, SurvivorClass: "Unknown", TotalInGameTime: 0, TotalSessionExperience: 0, - Victims: [] - } + Victims: [], + }, }; } - + protected isWiped(sessionID: string): boolean { return this.saveServer.getProfile(sessionID).info.wipe; @@ -289,14 +296,17 @@ export class ProfileHelper public removeSecureContainer(profile: IPmcData): IPmcData { const items = profile.Inventory.items; - const secureContainer = items.find(x => x.slotId === "SecuredContainer"); + const secureContainer = items.find((x) => x.slotId === "SecuredContainer"); if (secureContainer) { // Find and remove container + children - const childItemsInSecureContainer = this.itemHelper.findAndReturnChildrenByItems(items, secureContainer._id); + const childItemsInSecureContainer = this.itemHelper.findAndReturnChildrenByItems( + items, + secureContainer._id, + ); // Remove child items + secure container - profile.Inventory.items = items.filter(x => !childItemsInSecureContainer.includes(x._id)); + profile.Inventory.items = items.filter((x) => !childItemsInSecureContainer.includes(x._id)); } return profile; @@ -340,7 +350,7 @@ export class ProfileHelper return false; } - return !!profile.aki.receivedGifts.find(x => x.giftId === giftId); + return !!profile.aki.receivedGifts.find((x) => x.giftId === giftId); } /** @@ -350,7 +360,7 @@ export class ProfileHelper */ public incrementStatCounter(counters: CounterKeyValue[], keyToIncrement: string): void { - const stat = counters.find(x => x.Key.includes(keyToIncrement)); + const stat = counters.find((x) => x.Key.includes(keyToIncrement)); if (stat) { stat.Value++; @@ -371,7 +381,7 @@ export class ProfileHelper return false; } - const profileSkill = profileSkills.find(x => x.Id === skillType); + const profileSkill = profileSkills.find((x) => x.Id === skillType); if (!profileSkill) { this.logger.warning(`Unable to check for elite skill ${skillType}, not found in profile`); @@ -387,13 +397,20 @@ export class ProfileHelper * @param pointsToAdd Points to add * @param pmcProfile Player profile with skill * @param useSkillProgressRateMultipler Skills are multiplied by a value in globals, default is off to maintain compatibility with legacy code - * @returns + * @returns */ - public addSkillPointsToPlayer(pmcProfile: IPmcData, skill: SkillTypes, pointsToAdd: number, useSkillProgressRateMultipler = false): void + public addSkillPointsToPlayer( + pmcProfile: IPmcData, + skill: SkillTypes, + pointsToAdd: number, + useSkillProgressRateMultipler = false, + ): void { if (!pointsToAdd || pointsToAdd < 0) { - this.logger.error(this.localisationService.getText("player-attempt_to_increment_skill_with_negative_value", skill)); + this.logger.error( + this.localisationService.getText("player-attempt_to_increment_skill_with_negative_value", skill), + ); return; } @@ -405,7 +422,7 @@ export class ProfileHelper return; } - const profileSkill = profileSkills.find(x => x.Id === skill); + const profileSkill = profileSkills.find((x) => x.Id === skill); if (!profileSkill) { this.logger.error(this.localisationService.getText("quest-no_skill_found", skill)); @@ -426,7 +443,7 @@ export class ProfileHelper public getSkillFromProfile(pmcData: IPmcData, skill: SkillTypes): Common { - const skillToReturn = pmcData.Skills.Common.find(x => x.Id === skill); + const skillToReturn = pmcData.Skills.Common.find((x) => x.Id === skill); if (!skillToReturn) { this.logger.warning(`Profile ${pmcData.sessionId} does not have a skill named: ${skill}`); @@ -435,4 +452,4 @@ export class ProfileHelper return skillToReturn; } -} \ No newline at end of file +} diff --git a/project/src/helpers/QuestConditionHelper.ts b/project/src/helpers/QuestConditionHelper.ts index f964551f..b47ba161 100644 --- a/project/src/helpers/QuestConditionHelper.ts +++ b/project/src/helpers/QuestConditionHelper.ts @@ -1,4 +1,3 @@ - import { injectable } from "tsyringe"; import { AvailableForConditions } from "@spt-aki/models/eft/common/tables/IQuest"; @@ -6,29 +5,45 @@ import { AvailableForConditions } from "@spt-aki/models/eft/common/tables/IQuest @injectable() export class QuestConditionHelper { - public getQuestConditions(q: AvailableForConditions[], furtherFilter: (a: AvailableForConditions) => AvailableForConditions[] = null): AvailableForConditions[] + public getQuestConditions( + q: AvailableForConditions[], + furtherFilter: (a: AvailableForConditions) => AvailableForConditions[] = null, + ): AvailableForConditions[] { return this.filterConditions(q, "Quest", furtherFilter); } - public getLevelConditions(q: AvailableForConditions[], furtherFilter: (a: AvailableForConditions) => AvailableForConditions[] = null): AvailableForConditions[] + public getLevelConditions( + q: AvailableForConditions[], + furtherFilter: (a: AvailableForConditions) => AvailableForConditions[] = null, + ): AvailableForConditions[] { return this.filterConditions(q, "Level", furtherFilter); } - public getLoyaltyConditions(q: AvailableForConditions[], furtherFilter: (a: AvailableForConditions) => AvailableForConditions[] = null): AvailableForConditions[] + public getLoyaltyConditions( + q: AvailableForConditions[], + furtherFilter: (a: AvailableForConditions) => AvailableForConditions[] = null, + ): AvailableForConditions[] { return this.filterConditions(q, "TraderLoyalty", furtherFilter); } - public getStandingConditions(q: AvailableForConditions[], furtherFilter: (a: AvailableForConditions) => AvailableForConditions[] = null): AvailableForConditions[] + public getStandingConditions( + q: AvailableForConditions[], + furtherFilter: (a: AvailableForConditions) => AvailableForConditions[] = null, + ): AvailableForConditions[] { return this.filterConditions(q, "TraderStanding", furtherFilter); } - protected filterConditions(q: AvailableForConditions[], questType: string, furtherFilter: (a: AvailableForConditions) => AvailableForConditions[] = null): AvailableForConditions[] + protected filterConditions( + q: AvailableForConditions[], + questType: string, + furtherFilter: (a: AvailableForConditions) => AvailableForConditions[] = null, + ): AvailableForConditions[] { - const filteredQuests = q.filter(c => + const filteredQuests = q.filter((c) => { if (c._parent === questType) { @@ -43,4 +58,4 @@ export class QuestConditionHelper return filteredQuests; } -} \ No newline at end of file +} diff --git a/project/src/helpers/QuestHelper.ts b/project/src/helpers/QuestHelper.ts index f87daba9..18893d95 100644 --- a/project/src/helpers/QuestHelper.ts +++ b/project/src/helpers/QuestHelper.ts @@ -53,25 +53,25 @@ export class QuestHelper @inject("LocalisationService") protected localisationService: LocalisationService, @inject("TraderHelper") protected traderHelper: TraderHelper, @inject("MailSendService") protected mailSendService: MailSendService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.questConfig = this.configServer.getConfig(ConfigTypes.QUEST); } /** - * Get status of a quest in player profile by its id - * @param pmcData Profile to search - * @param questId Quest id to look up - * @returns QuestStatus enum - */ + * Get status of a quest in player profile by its id + * @param pmcData Profile to search + * @param questId Quest id to look up + * @returns QuestStatus enum + */ public getQuestStatus(pmcData: IPmcData, questId: string): QuestStatus { - const quest = pmcData.Quests?.find(q => q.qid === questId); + const quest = pmcData.Quests?.find((q) => q.qid === questId); - return quest - ? quest.status - : QuestStatus.Locked; + return quest ? + quest.status : + QuestStatus.Locked; } /** @@ -97,7 +97,12 @@ export class QuestHelper case "=": return playerLevel === condition._props.value; default: - this.logger.error(this.localisationService.getText("quest-unable_to_find_compare_condition", condition._props.compareMethod)); + this.logger.error( + this.localisationService.getText( + "quest-unable_to_find_compare_condition", + condition._props.compareMethod, + ), + ); return false; } } @@ -181,7 +186,7 @@ export class QuestHelper /** * Get quest name by quest id * @param questId id to get - * @returns + * @returns */ public getQuestNameFromLocale(questId: string): string { @@ -189,7 +194,6 @@ export class QuestHelper return this.localeService.getLocaleDb()[questNameKey]; } - /** * Check if trader has sufficient loyalty to fulfill quest requirement * @param questProperties Quest props @@ -242,7 +246,7 @@ export class QuestHelper return current !== required; case "==": return current === required; - + default: this.logger.error(this.localisationService.getText("quest-compare_operator_unhandled", compareMethod)); @@ -274,9 +278,11 @@ export class QuestHelper // separate base item and mods, fix stacks if (item._id === reward.target) { - if ((item.parentId !== undefined) && (item.parentId === "hideout") - && (item.upd !== undefined) && (item.upd.StackObjectsCount !== undefined) - && (item.upd.StackObjectsCount > 1)) + if ( + (item.parentId !== undefined) && (item.parentId === "hideout") && + (item.upd !== undefined) && (item.upd.StackObjectsCount !== undefined) && + (item.upd.StackObjectsCount > 1) + ) { item.upd.StackObjectsCount = 1; } @@ -307,7 +313,7 @@ export class QuestHelper items.push(this.jsonUtil.clone(mod)); } - rewardItems = rewardItems.concat( this.ragfairServerHelper.reparentPresets(target, items)); + rewardItems = rewardItems.concat(this.ragfairServerHelper.reparentPresets(target, items)); } return rewardItems; @@ -323,9 +329,11 @@ export class QuestHelper { // Iterate over all rewards with the desired status, flatten out items that have a type of Item const questRewards = quest.rewards[QuestStatus[status]] - .flatMap((reward: Reward) => reward.type === "Item" - ? this.processReward(reward) - : []); + .flatMap((reward: Reward) => + reward.type === "Item" ? + this.processReward(reward) : + [] + ); return questRewards; } @@ -336,9 +344,13 @@ export class QuestHelper * @param newState State the new quest should be in when returned * @param acceptedQuest Details of accepted quest from client */ - public getQuestReadyForProfile(pmcData: IPmcData, newState: QuestStatus, acceptedQuest: IAcceptQuestRequestData): IQuestStatus + public getQuestReadyForProfile( + pmcData: IPmcData, + newState: QuestStatus, + acceptedQuest: IAcceptQuestRequestData, + ): IQuestStatus { - const existingQuest = pmcData.Quests.find(q => q.qid === acceptedQuest.qid); + const existingQuest = pmcData.Quests.find((q) => q.qid === acceptedQuest.qid); if (existingQuest) { // Quest exists, update its status @@ -360,12 +372,12 @@ export class QuestHelper qid: acceptedQuest.qid, startTime: this.timeUtil.getTimestamp(), status: newState, - statusTimers: {} + statusTimers: {}, }; - + // Check if quest has a prereq to be placed in a 'pending' state const questDbData = this.getQuestFromDb(acceptedQuest.qid, pmcData); - const waitTime = questDbData.conditions.AvailableForStart.find(x => x._props.availableAfter > 0); + const waitTime = questDbData.conditions.AvailableForStart.find((x) => x._props.availableAfter > 0); if (waitTime && acceptedQuest.type !== "repeatable") { // Quest should be put into 'pending' state @@ -392,18 +404,18 @@ export class QuestHelper { // Get quest acceptance data from profile const profile: IPmcData = this.profileHelper.getPmcProfile(sessionID); - const startedQuestInProfile = profile.Quests.find(x => x.qid === startedQuestId); + const startedQuestInProfile = profile.Quests.find((x) => x.qid === startedQuestId); - // Get quests that + // Get quests that const eligibleQuests = this.getQuestsFromDb().filter((quest) => { // Quest is accessible to player when the accepted quest passed into param is started // e.g. Quest A passed in, quest B is looped over and has requirement of A to be started, include it - const acceptedQuestCondition = quest.conditions.AvailableForStart.find(x => + const acceptedQuestCondition = quest.conditions.AvailableForStart.find((x) => { - return x._parent === "Quest" - && x._props.target === startedQuestId - && x._props.status[0] === QuestStatus.Started; + return x._parent === "Quest" && + x._props.target === startedQuestId && + x._props.status[0] === QuestStatus.Started; }); // Not found, skip quest @@ -412,7 +424,9 @@ export class QuestHelper return false; } - const standingRequirements = this.questConditionHelper.getStandingConditions(quest.conditions.AvailableForStart); + const standingRequirements = this.questConditionHelper.getStandingConditions( + quest.conditions.AvailableForStart, + ); for (const condition of standingRequirements) { if (!this.traderStandingRequirementCheck(condition._props, profile)) @@ -421,7 +435,9 @@ export class QuestHelper } } - const loyaltyRequirements = this.questConditionHelper.getLoyaltyConditions(quest.conditions.AvailableForStart); + const loyaltyRequirements = this.questConditionHelper.getLoyaltyConditions( + quest.conditions.AvailableForStart, + ); for (const condition of loyaltyRequirements) { if (!this.traderLoyaltyLevelRequirementCheck(condition._props, profile)) @@ -431,7 +447,8 @@ export class QuestHelper } // Include if quest found in profile and is started or ready to hand in - return startedQuestInProfile && ([QuestStatus.Started, QuestStatus.AvailableForFinish].includes(startedQuestInProfile.status)); + return startedQuestInProfile && + ([QuestStatus.Started, QuestStatus.AvailableForFinish].includes(startedQuestInProfile.status)); }); return this.getQuestsWithOnlyLevelRequirementStartCondition(eligibleQuests); @@ -446,17 +463,18 @@ export class QuestHelper public failedUnlocked(failedQuestId: string, sessionId: string): IQuest[] { const profile = this.profileHelper.getPmcProfile(sessionId); - const profileQuest = profile.Quests.find(x => x.qid === failedQuestId); + const profileQuest = profile.Quests.find((x) => x.qid === failedQuestId); const quests = this.getQuestsFromDb().filter((q) => { const acceptedQuestCondition = q.conditions.AvailableForStart.find( - c => + (c) => { - return c._parent === "Quest" - && c._props.target === failedQuestId - && c._props.status[0] === QuestStatus.Fail; - }); + return c._parent === "Quest" && + c._props.target === failedQuestId && + c._props.status[0] === QuestStatus.Fail; + }, + ); if (!acceptedQuestCondition) { @@ -490,7 +508,9 @@ export class QuestHelper { if (this.paymentHelper.isMoneyTpl(reward.items[0]._tpl)) { - reward.items[0].upd.StackObjectsCount += Math.round(reward.items[0].upd.StackObjectsCount * multiplier / 100); + reward.items[0].upd.StackObjectsCount += Math.round( + reward.items[0].upd.StackObjectsCount * multiplier / 100, + ); } } } @@ -507,9 +527,15 @@ export class QuestHelper * @param sessionID Session id * @param output ItemEvent router response */ - public changeItemStack(pmcData: IPmcData, itemId: string, newStackSize: number, sessionID: string, output: IItemEventRouterResponse): void + public changeItemStack( + pmcData: IPmcData, + itemId: string, + newStackSize: number, + sessionID: string, + output: IItemEventRouterResponse, + ): void { - const inventoryItemIndex = pmcData.Inventory.items.findIndex(item => item._id === itemId); + const inventoryItemIndex = pmcData.Inventory.items.findIndex((item) => item._id === itemId); if (inventoryItemIndex < 0) { this.logger.error(this.localisationService.getText("quest-item_not_found_in_inventory", itemId)); @@ -532,7 +558,7 @@ export class QuestHelper { // this case is probably dead Code right now, since the only calling function // checks explicitly for Value > 0. - output.profileChanges[sessionID].items.del.push({ _id: itemId }); + output.profileChanges[sessionID].items.del.push({_id: itemId}); pmcData.Inventory.items.splice(inventoryItemIndex, 1); } } @@ -543,7 +569,11 @@ export class QuestHelper * @param sessionId Session id * @param item Item that was adjusted */ - protected addItemStackSizeChangeIntoEventResponse(output: IItemEventRouterResponse, sessionId: string, item: Item): void + protected addItemStackSizeChangeIntoEventResponse( + output: IItemEventRouterResponse, + sessionId: string, + item: Item, + ): void { output.profileChanges[sessionId].items.change.push({ _id: item._id, @@ -552,8 +582,8 @@ export class QuestHelper slotId: item.slotId, location: item.location, upd: { - StackObjectsCount: item.upd.StackObjectsCount - } + StackObjectsCount: item.upd.StackObjectsCount, + }, }); } @@ -580,7 +610,7 @@ export class QuestHelper public getQuestWithOnlyLevelRequirementStartCondition(quest: IQuest): IQuest { quest = this.jsonUtil.clone(quest); - quest.conditions.AvailableForStart = quest.conditions.AvailableForStart.filter(q => q._parent === "Level"); + quest.conditions.AvailableForStart = quest.conditions.AvailableForStart.filter((q) => q._parent === "Level"); return quest; } @@ -593,7 +623,12 @@ export class QuestHelper * @param output Client output * @returns Item event router response */ - public failQuest(pmcData: IPmcData, failRequest: IFailQuestRequestData, sessionID: string, output: IItemEventRouterResponse = null): IItemEventRouterResponse + public failQuest( + pmcData: IPmcData, + failRequest: IFailQuestRequestData, + sessionID: string, + output: IItemEventRouterResponse = null, + ): IItemEventRouterResponse { // Prepare response to send back client if (!output) @@ -613,7 +648,7 @@ export class QuestHelper MessageType.QUEST_FAIL, quest.failMessageText, questRewards, - this.timeUtil.getHoursAsSeconds(this.questConfig.redeemTime) + this.timeUtil.getHoursAsSeconds(this.questConfig.redeemTime), ); output.profileChanges[sessionID].quests.push(this.failedUnlocked(failRequest.qid, sessionID)); @@ -647,7 +682,7 @@ export class QuestHelper // Check daily/weekly objects for (const repeatableType of pmcData.RepeatableQuests) { - quest = repeatableType.activeQuests.find(x => x._id === questId); + quest = repeatableType.activeQuests.find((x) => x._id === questId); if (quest) { break; @@ -668,7 +703,10 @@ export class QuestHelper { // blank or is a guid, use description instead const startedMessageText = this.getQuestLocaleIdFromDb(startedMessageTextId); - if (!startedMessageText || startedMessageText.trim() === "" || startedMessageText.toLowerCase() === "test" || startedMessageText.length === 24) + if ( + !startedMessageText || startedMessageText.trim() === "" || startedMessageText.toLowerCase() === "test" || + startedMessageText.length === 24 + ) { return questDescriptionId; } @@ -696,7 +734,7 @@ export class QuestHelper public updateQuestState(pmcData: IPmcData, newQuestState: QuestStatus, questId: string): void { // Find quest in profile, update status to desired status - const questToUpdate = pmcData.Quests.find(quest => quest.qid === questId); + const questToUpdate = pmcData.Quests.find((quest) => quest.qid === questId); if (questToUpdate) { questToUpdate.status = newQuestState; @@ -713,8 +751,14 @@ export class QuestHelper * @param questResponse Response to send back to client * @returns Array of reward objects */ - public applyQuestReward(pmcData: IPmcData, questId: string, state: QuestStatus, sessionId: string, questResponse: IItemEventRouterResponse): Reward[] - { + public applyQuestReward( + pmcData: IPmcData, + questId: string, + state: QuestStatus, + sessionId: string, + questResponse: IItemEventRouterResponse, + ): Reward[] + { let questDetails = this.getQuestFromDb(questId, pmcData); if (!questDetails) { @@ -722,7 +766,7 @@ export class QuestHelper return []; } - + // Check for and apply intel center money bonus if it exists const questMoneyRewardBonus = this.getQuestMoneyRewardBonus(pmcData); if (questMoneyRewardBonus > 0) @@ -738,7 +782,11 @@ export class QuestHelper switch (reward.type) { case QuestRewardType.SKILL: - this.profileHelper.addSkillPointsToPlayer(pmcData, reward.target as SkillTypes, Number(reward.value)); + this.profileHelper.addSkillPointsToPlayer( + pmcData, + reward.target as SkillTypes, + Number(reward.value), + ); break; case QuestRewardType.EXPERIENCE: this.profileHelper.addExperienceToPmc(sessionId, parseInt(reward.value)); // this must occur first as the output object needs to take the modified profile exp value @@ -759,10 +807,22 @@ export class QuestHelper this.logger.debug("Not implemented stash rows reward yet"); break; case QuestRewardType.PRODUCTIONS_SCHEME: - this.findAndAddHideoutProductionIdToProfile(pmcData, reward, questDetails, sessionId, questResponse); + this.findAndAddHideoutProductionIdToProfile( + pmcData, + reward, + questDetails, + sessionId, + questResponse, + ); break; default: - this.logger.error(this.localisationService.getText("quest-reward_type_not_handled", {rewardType: reward.type, questId: questId, questName: questDetails.QuestName})); + this.logger.error( + this.localisationService.getText("quest-reward_type_not_handled", { + rewardType: reward.type, + questId: questId, + questName: questDetails.QuestName, + }), + ); break; } } @@ -779,19 +839,31 @@ export class QuestHelper * @param sessionID Session id * @param response Response to send back to client */ - protected findAndAddHideoutProductionIdToProfile(pmcData: IPmcData, craftUnlockReward: Reward, questDetails: IQuest, sessionID: string, response: IItemEventRouterResponse): void + protected findAndAddHideoutProductionIdToProfile( + pmcData: IPmcData, + craftUnlockReward: Reward, + questDetails: IQuest, + sessionID: string, + response: IItemEventRouterResponse, + ): void { // Get hideout crafts and find those that match by areatype/required level/end product tpl - hope for just one match const hideoutProductions = this.databaseServer.getTables().hideout.production; - const matchingProductions = hideoutProductions.filter(x => - x.areaType === Number.parseInt(craftUnlockReward.traderId) - && x.requirements.some(x => x.requiredLevel === craftUnlockReward.loyaltyLevel) - && x.endProduct === craftUnlockReward.items[0]._tpl); + const matchingProductions = hideoutProductions.filter((x) => + x.areaType === Number.parseInt(craftUnlockReward.traderId) && + x.requirements.some((x) => x.requiredLevel === craftUnlockReward.loyaltyLevel) && + x.endProduct === craftUnlockReward.items[0]._tpl + ); // More/less than 1 match, above filtering wasn't strict enough if (matchingProductions.length !== 1) { - this.logger.error(this.localisationService.getText("quest-unable_to_find_matching_hideout_production", {questName: questDetails.QuestName, matchCount: matchingProductions.length})); + this.logger.error( + this.localisationService.getText("quest-unable_to_find_matching_hideout_production", { + questName: questDetails.QuestName, + matchCount: matchingProductions.length, + }), + ); return; } @@ -810,7 +882,7 @@ export class QuestHelper protected getQuestMoneyRewardBonus(pmcData: IPmcData): number { // Check player has intel center - const moneyRewardBonuses = pmcData.Bonuses.filter(x => x.type === "QuestMoneyReward"); + const moneyRewardBonuses = pmcData.Bonuses.filter((x) => x.type === "QuestMoneyReward"); if (!moneyRewardBonuses) { return 0; @@ -823,7 +895,7 @@ export class QuestHelper const hideoutManagementSkill = this.profileHelper.getSkillFromProfile(pmcData, SkillTypes.HIDEOUT_MANAGEMENT); if (hideoutManagementSkill) { - moneyRewardBonus *= (1 + (hideoutManagementSkill.Progress / 10000)); // 5100 becomes 0.51, add 1 to it, 1.51, multiply the moneyreward bonus by it (e.g. 15 x 51) + moneyRewardBonus *= 1 + (hideoutManagementSkill.Progress / 10000); // 5100 becomes 0.51, add 1 to it, 1.51, multiply the moneyreward bonus by it (e.g. 15 x 51) } return moneyRewardBonus; @@ -835,19 +907,27 @@ export class QuestHelper * @param questIds Quests to search through for the findItem condition * @returns quest id with 'FindItem' condition id */ - public getFindItemConditionByQuestItem(itemTpl: string, questIds: string[], allQuests: IQuest[]): Record + public getFindItemConditionByQuestItem( + itemTpl: string, + questIds: string[], + allQuests: IQuest[], + ): Record { const result: Record = {}; for (const questId of questIds) { - const questInDb = allQuests.find(x => x._id === questId); + const questInDb = allQuests.find((x) => x._id === questId); if (!questInDb) { - this.logger.warning(`Unable to find quest: ${questId} in db, cannot get 'FindItem' condition, skipping`); + this.logger.warning( + `Unable to find quest: ${questId} in db, cannot get 'FindItem' condition, skipping`, + ); continue; } - const condition = questInDb.conditions.AvailableForFinish.find(c => c._parent === "FindItem" && c._props?.target?.includes(itemTpl)); + const condition = questInDb.conditions.AvailableForFinish.find((c) => + c._parent === "FindItem" && c._props?.target?.includes(itemTpl) + ); if (condition) { result[questId] = condition._props.id; @@ -872,7 +952,7 @@ export class QuestHelper { // Quest from db matches quests in profile, skip const questData = quests[questKey]; - if (pmcProfile.Quests.find(x => x.qid === questData._id)) + if (pmcProfile.Quests.find((x) => x.qid === questData._id)) { continue; } @@ -889,13 +969,13 @@ export class QuestHelper status: statuses[statuses.length - 1], statusTimers: statusesDict, completedConditions: [], - availableAfter: 0 + availableAfter: 0, }; - if (pmcProfile.Quests.some(x => x.qid === questKey)) + if (pmcProfile.Quests.some((x) => x.qid === questKey)) { // Update existing - const existingQuest = pmcProfile.Quests.find(x => x.qid === questKey); + const existingQuest = pmcProfile.Quests.find((x) => x.qid === questKey); existingQuest.status = questRecordToAdd.status; existingQuest.statusTimers = questRecordToAdd.statusTimers; } @@ -909,10 +989,10 @@ export class QuestHelper public findAndRemoveQuestFromArrayIfExists(questId: string, quests: IQuestStatus[]): void { - const pmcQuestToReplaceStatus = quests.find(x => x.qid === questId); + const pmcQuestToReplaceStatus = quests.find((x) => x.qid === questId); if (pmcQuestToReplaceStatus) { quests.splice(quests.indexOf(pmcQuestToReplaceStatus, 1)); } } -} \ No newline at end of file +} diff --git a/project/src/helpers/RagfairHelper.ts b/project/src/helpers/RagfairHelper.ts index 991bc61f..e8790996 100644 --- a/project/src/helpers/RagfairHelper.ts +++ b/project/src/helpers/RagfairHelper.ts @@ -31,17 +31,17 @@ export class RagfairHelper @inject("ItemHelper") protected itemHelper: ItemHelper, @inject("RagfairLinkedItemService") protected ragfairLinkedItemService: RagfairLinkedItemService, @inject("UtilityHelper") protected utilityHelper: UtilityHelper, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); } /** - * Gets currency TAG from TPL - * @param {string} currency - * @returns string - */ + * Gets currency TAG from TPL + * @param {string} currency + * @returns string + */ public getCurrencyTag(currency: string): string { switch (currency) @@ -73,9 +73,9 @@ export class RagfairHelper if (info.linkedSearchId) { const data = this.ragfairLinkedItemService.getLinkedItems(info.linkedSearchId); - result = !data - ? [] - : [...data]; + result = !data ? + [] : + [...data]; } // Case: category @@ -185,7 +185,7 @@ export class RagfairHelper for (let item of items) { item = this.itemHelper.fixItemStackCount(item); - const isChild = items.find(it => it._id === item.parentId); + const isChild = items.find((it) => it._id === item.parentId); if (!isChild) { diff --git a/project/src/helpers/RagfairOfferHelper.ts b/project/src/helpers/RagfairOfferHelper.ts index 6543ad18..9de15133 100644 --- a/project/src/helpers/RagfairOfferHelper.ts +++ b/project/src/helpers/RagfairOfferHelper.ts @@ -60,7 +60,7 @@ export class RagfairOfferHelper @inject("LocaleService") protected localeService: LocaleService, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("MailSendService") protected mailSendService: MailSendService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); @@ -75,9 +75,16 @@ export class RagfairOfferHelper * @param pmcProfile Player profile * @returns Offers the player should see */ - public getValidOffers(searchRequest: ISearchRequestData, itemsToAdd: string[], traderAssorts: Record, pmcProfile: IPmcData): IRagfairOffer[] + public getValidOffers( + searchRequest: ISearchRequestData, + itemsToAdd: string[], + traderAssorts: Record, + pmcProfile: IPmcData, + ): IRagfairOffer[] { - return this.ragfairOfferService.getOffers().filter(x => this.isDisplayableOffer(searchRequest, itemsToAdd, traderAssorts, x, pmcProfile)); + return this.ragfairOfferService.getOffers().filter((x) => + this.isDisplayableOffer(searchRequest, itemsToAdd, traderAssorts, x, pmcProfile) + ); } /** @@ -88,7 +95,12 @@ export class RagfairOfferHelper * @param pmcProfile Player profile * @returns IRagfairOffer array */ - public getOffersForBuild(searchRequest: ISearchRequestData, itemsToAdd: string[], traderAssorts: Record, pmcProfile: IPmcData): IRagfairOffer[] + public getOffersForBuild( + searchRequest: ISearchRequestData, + itemsToAdd: string[], + traderAssorts: Record, + pmcProfile: IPmcData, + ): IRagfairOffer[] { const offersMap = new Map(); const offers: IRagfairOffer[] = []; @@ -137,13 +149,13 @@ export class RagfairOfferHelper if (possibleOffers.length > 1) { const lockedOffers = this.getLoyaltyLockedOffers(possibleOffers, pmcProfile); - + // Exclude locked offers + above loyalty locked offers if at least 1 was found - const availableOffers = possibleOffers.filter(x => !(x.locked || lockedOffers.includes(x._id))); + const availableOffers = possibleOffers.filter((x) => !(x.locked || lockedOffers.includes(x._id))); if (availableOffers.length > 0) { possibleOffers = availableOffers; - } + } } const offer = this.ragfairSortHelper.sortOffers(possibleOffers, RagfairSort.PRICE, 0)[0]; @@ -174,7 +186,9 @@ export class RagfairOfferHelper */ public traderOfferItemQuestLocked(offer: IRagfairOffer, traderAssorts: Record): boolean { - return offer.items?.some(i => traderAssorts[offer.user.id].barter_scheme[i._id]?.some(bs1 => bs1?.some(bs2 => bs2.sptQuestLocked))); + return offer.items?.some((i) => + traderAssorts[offer.user.id].barter_scheme[i._id]?.some((bs1) => bs1?.some((bs2) => bs2.sptQuestLocked)) + ); } /** @@ -182,7 +196,7 @@ export class RagfairOfferHelper * @param offer Offer to check stock of * @returns true if out of stock */ - protected traderOutOfStock(offer: IRagfairOffer): boolean + protected traderOutOfStock(offer: IRagfairOffer): boolean { if (offer?.items?.length === 0) { @@ -200,17 +214,21 @@ export class RagfairOfferHelper protected traderBuyRestrictionReached(offer: IRagfairOffer): boolean { const traderAssorts = this.traderHelper.getTraderAssortsByTraderId(offer.user.id).items; - const assortData = traderAssorts.find(x => x._id === offer.items[0]._id); + const assortData = traderAssorts.find((x) => x._id === offer.items[0]._id); // No trader assort data if (!assortData) { - this.logger.warning(`Unable to find trader: ${offer.user.nickname} assort for item: ${this.itemHelper.getItemName(offer.items[0]._tpl)} ${offer.items[0]._tpl}, cannot check if buy restriction reached`); + this.logger.warning( + `Unable to find trader: ${offer.user.nickname} assort for item: ${ + this.itemHelper.getItemName(offer.items[0]._tpl) + } ${offer.items[0]._tpl}, cannot check if buy restriction reached`, + ); return false; } // No restriction values - // Can't use !assortData.upd.BuyRestrictionX as value could be 0 + // Can't use !assortData.upd.BuyRestrictionX as value could be 0 if (assortData.upd.BuyRestrictionMax === undefined || assortData.upd.BuyRestrictionCurrent === undefined) { return false; @@ -279,7 +297,10 @@ export class RagfairOfferHelper boughtAmount = offer.sellResult[0].amount; } - this.increaseProfileRagfairRating(this.saveServer.getProfile(sessionID), offer.summaryCost / totalItemsCount * boughtAmount); + this.increaseProfileRagfairRating( + this.saveServer.getProfile(sessionID), + offer.summaryCost / totalItemsCount * boughtAmount, + ); this.completeOffer(sessionID, offer, boughtAmount); offer.sellResult.splice(0, 1); @@ -331,7 +352,7 @@ export class RagfairOfferHelper protected deleteOfferById(sessionID: string, offerId: string): void { const profileRagfairInfo = this.saveServer.getProfile(sessionID).characters.pmc.RagfairInfo; - const index = profileRagfairInfo.offers.findIndex(o => o._id === offerId); + const index = profileRagfairInfo.offers.findIndex((o) => o._id === offerId); profileRagfairInfo.offers.splice(index, 1); // Also delete from ragfair this.ragfairOfferService.removeOfferById(offerId); @@ -357,7 +378,7 @@ export class RagfairOfferHelper else { offer.items[0].upd.StackObjectsCount -= boughtAmount; - const rootItems = offer.items.filter(i => i.parentId === "hideout"); + const rootItems = offer.items.filter((i) => i.parentId === "hideout"); rootItems.splice(0, 1); let removeCount = boughtAmount; @@ -384,11 +405,12 @@ export class RagfairOfferHelper while (foundNewItems) { foundNewItems = false; - - // eslint-disable-next-line @typescript-eslint/no-unused-vars + for (const id of idsToRemove) { - const newIds = offer.items.filter(i => !idsToRemove.includes(i._id) && idsToRemove.includes(i.parentId)).map(i => i._id); + const newIds = offer.items.filter((i) => + !idsToRemove.includes(i._id) && idsToRemove.includes(i.parentId) + ).map((i) => i._id); if (newIds.length > 0) { foundNewItems = true; @@ -399,7 +421,7 @@ export class RagfairOfferHelper if (idsToRemove.length > 0) { - offer.items = offer.items.filter(i => !idsToRemove.includes(i._id)); + offer.items = offer.items.filter((i) => !idsToRemove.includes(i._id)); } } @@ -410,7 +432,7 @@ export class RagfairOfferHelper const requestedItem: Item = { _id: this.hashUtil.generate(), _tpl: requirement._tpl, - upd: { StackObjectsCount: requirement.count * boughtAmount } + upd: {StackObjectsCount: requirement.count * boughtAmount}, }; const stacks = this.itemHelper.splitStack(requestedItem); @@ -436,7 +458,7 @@ export class RagfairOfferHelper const ragfairDetails = { offerId: offer._id, count: offer.sellInOnePiece ? offerStackCount : boughtAmount, // pack-offers NEED to the full item count otherwise it only removes 1 from the pack, leaving phantom offer on client ui - handbookId: itemTpl + handbookId: itemTpl, }; this.mailSendService.sendDirectNpcMessageToPlayer( @@ -447,7 +469,8 @@ export class RagfairOfferHelper itemsToSend, this.timeUtil.getHoursAsSeconds(this.questConfig.redeemTime), null, - ragfairDetails); + ragfairDetails, + ); return this.eventOutputHolder.getOutput(sessionID); } @@ -465,14 +488,19 @@ export class RagfairOfferHelper const soldMessageLocaleGuid = globalLocales[RagfairOfferHelper.goodSoldTemplate]; if (!soldMessageLocaleGuid) { - this.logger.error(this.localisationService.getText("ragfair-unable_to_find_locale_by_key", RagfairOfferHelper.goodSoldTemplate)); + this.logger.error( + this.localisationService.getText( + "ragfair-unable_to_find_locale_by_key", + RagfairOfferHelper.goodSoldTemplate, + ), + ); } // Used to replace tokens in sold message sent to player const tplVars: ISystemData = { soldItem: globalLocales[`${itemTpl} Name`] || itemTpl, buyerNickname: this.ragfairServerHelper.getNickname(this.hashUtil.generate()), - itemCount: boughtAmount + itemCount: boughtAmount, }; const offerSoldMessageText = soldMessageLocaleGuid.replace(/{\w+}/g, (matched) => @@ -492,14 +520,23 @@ export class RagfairOfferHelper * @param pmcProfile Player profile * @returns True = should be shown to player */ - public isDisplayableOffer(searchRequest: ISearchRequestData, itemsToAdd: string[], traderAssorts: Record, offer: IRagfairOffer, pmcProfile: IPmcData): boolean + public isDisplayableOffer( + searchRequest: ISearchRequestData, + itemsToAdd: string[], + traderAssorts: Record, + offer: IRagfairOffer, + pmcProfile: IPmcData, + ): boolean { const item = offer.items[0]; const money = offer.requirements[0]._tpl; const isTraderOffer = offer.user.memberType === MemberCategory.TRADER; const isDefaultUserOffer = offer.user.memberType === MemberCategory.DEFAULT; - if (pmcProfile.Info.Level < this.databaseServer.getTables().globals.config.RagFair.minUserLevel && isDefaultUserOffer) + if ( + pmcProfile.Info.Level < this.databaseServer.getTables().globals.config.RagFair.minUserLevel && + isDefaultUserOffer + ) { // Skip item if player is < global unlock level (default is 15) and item is from a dynamically generated source return false; @@ -512,7 +549,7 @@ export class RagfairOfferHelper } // Performing a required search and offer doesn't have requirement for item - if (searchRequest.neededSearchId && !offer.requirements.some(x => x._tpl === searchRequest.neededSearchId)) + if (searchRequest.neededSearchId && !offer.requirements.some((x) => x._tpl === searchRequest.neededSearchId)) { return false; } @@ -559,7 +596,10 @@ export class RagfairOfferHelper return false; } - if (( item.upd.MedKit || item.upd.Repairable ) && !this.itemQualityInRange(item, searchRequest.conditionFrom, searchRequest.conditionTo)) + if ( + (item.upd.MedKit || item.upd.Repairable) && + !this.itemQualityInRange(item, searchRequest.conditionFrom, searchRequest.conditionTo) + ) { return false; } @@ -612,10 +652,12 @@ export class RagfairOfferHelper return false; } - if (!traderAssorts[offer.user.id].items.find((item) => - { - return item._id === offer.root; - })) + if ( + !traderAssorts[offer.user.id].items.find((item) => + { + return item._id === offer.root; + }) + ) { // skip (quest) locked items return false; @@ -649,4 +691,4 @@ export class RagfairOfferHelper return true; } -} \ No newline at end of file +} diff --git a/project/src/helpers/RagfairSellHelper.ts b/project/src/helpers/RagfairSellHelper.ts index 12d0ba55..bbe9777c 100644 --- a/project/src/helpers/RagfairSellHelper.ts +++ b/project/src/helpers/RagfairSellHelper.ts @@ -17,7 +17,7 @@ export class RagfairSellHelper @inject("WinstonLogger") protected logger: ILogger, @inject("RandomUtil") protected randomUtil: RandomUtil, @inject("TimeUtil") protected timeUtil: TimeUtil, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); @@ -30,15 +30,20 @@ export class RagfairSellHelper * @param qualityMultiplier Quality multipler of item being sold * @returns percent value */ - public calculateSellChance(averageOfferPriceRub: number, playerListedPriceRub: number, qualityMultiplier: number): number + public calculateSellChance( + averageOfferPriceRub: number, + playerListedPriceRub: number, + qualityMultiplier: number, + ): number { const baseSellChancePercent = this.ragfairConfig.sell.chance.base * qualityMultiplier; const listedPriceAboveAverage = playerListedPriceRub > averageOfferPriceRub; // Get sell chance multiplier - const multiplier = (listedPriceAboveAverage) - ? this.ragfairConfig.sell.chance.overpriced // Player price is over average listing price - : this.getSellMultiplierWhenPlayerPriceIsBelowAverageListingPrice(averageOfferPriceRub, playerListedPriceRub); + const multiplier = listedPriceAboveAverage ? + this.ragfairConfig.sell.chance.overpriced // Player price is over average listing price + : + this.getSellMultiplierWhenPlayerPriceIsBelowAverageListingPrice(averageOfferPriceRub, playerListedPriceRub); return Math.round(baseSellChancePercent * (averageOfferPriceRub / playerListedPriceRub * multiplier)); } @@ -49,11 +54,14 @@ export class RagfairSellHelper * @param averageOfferPriceRub Price of average offer in roubles * @returns percent value */ - protected getSellMultiplierWhenPlayerPriceIsBelowAverageListingPrice(averageOfferPriceRub: number, playerListedPriceRub: number): number + protected getSellMultiplierWhenPlayerPriceIsBelowAverageListingPrice( + averageOfferPriceRub: number, + playerListedPriceRub: number, + ): number { - return (playerListedPriceRub < averageOfferPriceRub) - ? this.ragfairConfig.sell.chance.underpriced - : 1; + return (playerListedPriceRub < averageOfferPriceRub) ? + this.ragfairConfig.sell.chance.underpriced : + 1; } /** @@ -75,14 +83,16 @@ export class RagfairSellHelper let sellTime = startTime; let remainingCount = itemSellCount; const result: SellResult[] = []; - + // Value can sometimes be NaN for whatever reason, default to base chance if that happens if (Number.isNaN(sellChancePercent)) { - this.logger.warning(`Sell chance was not a number: ${sellChancePercent}, defaulting to ${this.ragfairConfig.sell.chance.base} %`); + this.logger.warning( + `Sell chance was not a number: ${sellChancePercent}, defaulting to ${this.ragfairConfig.sell.chance.base} %`, + ); sellChancePercent = this.ragfairConfig.sell.chance.base; } - + this.logger.debug(`Rolling to sell: ${itemSellCount} items (chance: ${sellChancePercent}%)`); // No point rolling for a sale on a 0% chance item, exit early @@ -90,18 +100,21 @@ export class RagfairSellHelper { return result; } - + while (remainingCount > 0 && sellTime < endTime) { const boughtAmount = this.randomUtil.getInt(1, remainingCount); if (this.randomUtil.getChance100(sellChancePercent)) { // Passed roll check, item will be sold - sellTime += Math.max(Math.round(chance / 100 * this.ragfairConfig.sell.time.max * 60), this.ragfairConfig.sell.time.min * 60); + sellTime += Math.max( + Math.round(chance / 100 * this.ragfairConfig.sell.time.max * 60), + this.ragfairConfig.sell.time.min * 60, + ); result.push({ sellTime: sellTime, - amount: boughtAmount + amount: boughtAmount, }); this.logger.debug(`Offer will sell at: ${new Date(sellTime * 1000).toLocaleTimeString("en-US")}`); @@ -116,4 +129,4 @@ export class RagfairSellHelper return result; } -} \ No newline at end of file +} diff --git a/project/src/helpers/RagfairServerHelper.ts b/project/src/helpers/RagfairServerHelper.ts index 9ff80555..06fc2646 100644 --- a/project/src/helpers/RagfairServerHelper.ts +++ b/project/src/helpers/RagfairServerHelper.ts @@ -48,7 +48,7 @@ export class RagfairServerHelper @inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("MailSendService") protected mailSendService: MailSendService, @inject("ItemFilterService") protected itemFilterService: ItemFilterService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); @@ -57,7 +57,7 @@ export class RagfairServerHelper /** * Is item valid / on blacklist / quest item - * @param itemDetails + * @param itemDetails * @returns boolean */ public isItemValidRagfairItem(itemDetails: [boolean, ITemplateItem]): boolean @@ -95,7 +95,10 @@ export class RagfairServerHelper } // Don't include damaged ammo packs - if (this.ragfairConfig.dynamic.blacklist.damagedAmmoPacks && itemDetails[1]._parent === BaseClasses.AMMO_BOX && itemDetails[1]._name.includes("_damaged")) + if ( + this.ragfairConfig.dynamic.blacklist.damagedAmmoPacks && itemDetails[1]._parent === BaseClasses.AMMO_BOX && + itemDetails[1]._name.includes("_damaged") + ) { return false; } @@ -120,7 +123,7 @@ export class RagfairServerHelper /** * is supplied id a trader - * @param traderId + * @param traderId * @returns True if id was a trader */ public isTrader(traderId: string): boolean @@ -155,7 +158,7 @@ export class RagfairServerHelper MessageType.MESSAGE_WITH_ITEMS, RagfairServerHelper.goodsReturnedTemplate, returnedItems, - this.timeUtil.getHoursAsSeconds(this.questConfig.redeemTime) + this.timeUtil.getHoursAsSeconds(this.questConfig.redeemTime), ); } @@ -171,7 +174,10 @@ export class RagfairServerHelper } // Item Types to return one of - if (isWeaponPreset || this.itemHelper.isOfBaseclasses(itemDetails[1]._id, this.ragfairConfig.dynamic.showAsSingleStack)) + if ( + isWeaponPreset || + this.itemHelper.isOfBaseclasses(itemDetails[1]._id, this.ragfairConfig.dynamic.showAsSingleStack) + ) { return 1; } @@ -185,7 +191,9 @@ export class RagfairServerHelper return Math.round(this.randomUtil.getInt(config.nonStackableCount.min, config.nonStackableCount.max)); } - const stackPercent = Math.round(this.randomUtil.getInt(config.stackablePercent.min, config.stackablePercent.max)); + const stackPercent = Math.round( + this.randomUtil.getInt(config.stackablePercent.min, config.stackablePercent.max), + ); return Math.round((maxStackCount / 100) * stackPercent); } @@ -263,7 +271,9 @@ export class RagfairServerHelper { if (this.databaseServer.getTables().globals.ItemPresets[itemId]._items[0]._tpl === item._tpl) { - const presetItems = this.jsonUtil.clone(this.databaseServer.getTables().globals.ItemPresets[itemId]._items); + const presetItems = this.jsonUtil.clone( + this.databaseServer.getTables().globals.ItemPresets[itemId]._items, + ); presets.push(this.reparentPresets(item, presetItems)); } } @@ -274,7 +284,7 @@ export class RagfairServerHelper /** * Generate new unique ids for the children while preserving hierarchy * @param item base item - * @param preset + * @param preset * @returns Item array with new IDs */ public reparentPresets(item: Item, preset: Item[]): Item[] @@ -296,11 +306,11 @@ export class RagfairServerHelper idMappings[mod.parentId] = this.hashUtil.generate(); } - mod._id = idMappings[mod._id]; + mod._id = idMappings[mod._id]; if (mod.parentId !== undefined) { - mod.parentId = idMappings[mod.parentId]; + mod.parentId = idMappings[mod.parentId]; } } @@ -309,4 +319,4 @@ export class RagfairServerHelper return preset; } -} \ No newline at end of file +} diff --git a/project/src/helpers/RagfairSortHelper.ts b/project/src/helpers/RagfairSortHelper.ts index 2e41203b..22450fe8 100644 --- a/project/src/helpers/RagfairSortHelper.ts +++ b/project/src/helpers/RagfairSortHelper.ts @@ -10,15 +10,15 @@ export class RagfairSortHelper { constructor( @inject("DatabaseServer") protected databaseServer: DatabaseServer, - @inject("LocaleService") protected localeService: LocaleService + @inject("LocaleService") protected localeService: LocaleService, ) - { } + {} /** * Sort a list of ragfair offers by something (id/rating/offer name/price/expiry time) * @param offers Offers to sort * @param type How to sort it - * @param direction Ascending/descending + * @param direction Ascending/descending * @returns Sorted offers */ public sortOffers(offers: IRagfairOffer[], type: RagfairSort, direction = 0): IRagfairOffer[] @@ -75,16 +75,18 @@ export class RagfairSortHelper const nameA = locale[`${tplA} Name`] || tplA; const nameB = locale[`${tplB} Name`] || tplB; - return (nameA < nameB) - ? -1 - : (nameA > nameB) ? 1 : 0; + return (nameA < nameB) ? + -1 : + (nameA > nameB) ? + 1 : + 0; } /** * Order two offers by rouble price value * @param a Offer a * @param b Offer b - * @returns + * @returns */ protected sortOffersByPrice(a: IRagfairOffer, b: IRagfairOffer): number { @@ -95,4 +97,4 @@ export class RagfairSortHelper { return a.endTime - b.endTime; } -} \ No newline at end of file +} diff --git a/project/src/helpers/RepairHelper.ts b/project/src/helpers/RepairHelper.ts index 9b1a07bd..84b9fe5d 100644 --- a/project/src/helpers/RepairHelper.ts +++ b/project/src/helpers/RepairHelper.ts @@ -21,7 +21,7 @@ export class RepairHelper @inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("RandomUtil") protected randomUtil: RandomUtil, @inject("DatabaseServer") protected databaseServer: DatabaseServer, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.repairConfig = this.configServer.getConfig(ConfigTypes.REPAIR); @@ -44,7 +44,7 @@ export class RepairHelper amountToRepair: number, useRepairKit: boolean, traderQualityMultipler: number, - applyMaxDurabilityDegradation = true + applyMaxDurabilityDegradation = true, ): void { this.logger.debug(`Adding ${amountToRepair} to ${itemToRepairDetails._name} using kit: ${useRepairKit}`); @@ -70,20 +70,30 @@ export class RepairHelper // Construct object to return itemToRepair.upd.Repairable = { Durability: newCurrentDurability, - MaxDurability: newCurrentMaxDurability + MaxDurability: newCurrentMaxDurability, }; // when modders set the repair coefficient to 0 it means that they dont want to lose durability on items // the code below generates a random degradation on the weapon durability if (applyMaxDurabilityDegradation) { - const randomisedWearAmount = (isArmor) - ? this.getRandomisedArmorRepairDegradationValue(itemToRepairDetails._props.ArmorMaterial, useRepairKit, itemCurrentMaxDurability, traderQualityMultipler) - : this.getRandomisedWeaponRepairDegradationValue(itemToRepairDetails._props, useRepairKit, itemCurrentMaxDurability, traderQualityMultipler); - + const randomisedWearAmount = isArmor ? + this.getRandomisedArmorRepairDegradationValue( + itemToRepairDetails._props.ArmorMaterial, + useRepairKit, + itemCurrentMaxDurability, + traderQualityMultipler, + ) : + this.getRandomisedWeaponRepairDegradationValue( + itemToRepairDetails._props, + useRepairKit, + itemCurrentMaxDurability, + traderQualityMultipler, + ); + // Apply wear to durability itemToRepair.upd.Repairable.MaxDurability -= randomisedWearAmount; - + // After adjusting max durability with degradation, ensure current dura isnt above max if (itemToRepair.upd.Repairable.Durability > itemToRepair.upd.Repairable.MaxDurability) { @@ -98,32 +108,42 @@ export class RepairHelper } } - protected getRandomisedArmorRepairDegradationValue(armorMaterial: string, isRepairKit: boolean, armorMax: number, traderQualityMultipler: number): number + protected getRandomisedArmorRepairDegradationValue( + armorMaterial: string, + isRepairKit: boolean, + armorMax: number, + traderQualityMultipler: number, + ): number { const armorMaterialSettings = this.databaseServer.getTables().globals.config.ArmorMaterials[armorMaterial]; - const minMultiplier = isRepairKit - ? armorMaterialSettings.MinRepairKitDegradation - : armorMaterialSettings.MinRepairDegradation; + const minMultiplier = isRepairKit ? + armorMaterialSettings.MinRepairKitDegradation : + armorMaterialSettings.MinRepairDegradation; - const maxMultiplier = isRepairKit - ? armorMaterialSettings.MaxRepairKitDegradation - : armorMaterialSettings.MaxRepairDegradation; + const maxMultiplier = isRepairKit ? + armorMaterialSettings.MaxRepairKitDegradation : + armorMaterialSettings.MaxRepairDegradation; const duraLossPercent = this.randomUtil.getFloat(minMultiplier, maxMultiplier); - const duraLossMultipliedByTraderMultiplier = (duraLossPercent * armorMax) * traderQualityMultipler; + const duraLossMultipliedByTraderMultiplier = (duraLossPercent * armorMax) * traderQualityMultipler; return Number(duraLossMultipliedByTraderMultiplier.toFixed(2)); } - protected getRandomisedWeaponRepairDegradationValue(itemProps: Props, isRepairKit: boolean, weaponMax: number, traderQualityMultipler: number): number + protected getRandomisedWeaponRepairDegradationValue( + itemProps: Props, + isRepairKit: boolean, + weaponMax: number, + traderQualityMultipler: number, + ): number { - const minRepairDeg = (isRepairKit) - ? itemProps.MinRepairKitDegradation - : itemProps.MinRepairDegradation; - let maxRepairDeg = (isRepairKit) - ? itemProps.MaxRepairKitDegradation - : itemProps.MaxRepairDegradation; + const minRepairDeg = isRepairKit ? + itemProps.MinRepairKitDegradation : + itemProps.MinRepairDegradation; + let maxRepairDeg = isRepairKit ? + itemProps.MaxRepairKitDegradation : + itemProps.MaxRepairDegradation; // WORKAROUND: Some items are always 0 when repairkit is true if (maxRepairDeg === 0) @@ -132,7 +152,7 @@ export class RepairHelper } const duraLossPercent = this.randomUtil.getFloat(minRepairDeg, maxRepairDeg); - const duraLossMultipliedByTraderMultiplier = (duraLossPercent * weaponMax) * traderQualityMultipler; + const duraLossMultipliedByTraderMultiplier = (duraLossPercent * weaponMax) * traderQualityMultipler; return Number(duraLossMultipliedByTraderMultiplier.toFixed(2)); } @@ -151,5 +171,4 @@ export class RepairHelper return parentNode._id === BaseClasses.WEAPON; } - -} \ No newline at end of file +} diff --git a/project/src/helpers/RepeatableQuestHelper.ts b/project/src/helpers/RepeatableQuestHelper.ts index dabf30cd..24182c84 100644 --- a/project/src/helpers/RepeatableQuestHelper.ts +++ b/project/src/helpers/RepeatableQuestHelper.ts @@ -15,7 +15,7 @@ export class RepeatableQuestHelper constructor( @inject("MathUtil") protected mathUtil: MathUtil, @inject("JsonUtil") protected jsonUtil: JsonUtil, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.questConfig = this.configServer.getConfig(ConfigTypes.QUEST); @@ -27,9 +27,14 @@ export class RepeatableQuestHelper * @param repeatableConfig Main repeatable config * @returns IEliminationConfig */ - public getEliminationConfigByPmcLevel(pmcLevel: number, repeatableConfig: IRepeatableQuestConfig): IEliminationConfig + public getEliminationConfigByPmcLevel( + pmcLevel: number, + repeatableConfig: IRepeatableQuestConfig, + ): IEliminationConfig { - return repeatableConfig.questConfig.Elimination.find(x => pmcLevel >= x.levelRange.min && pmcLevel <= x.levelRange.max); + return repeatableConfig.questConfig.Elimination.find((x) => + pmcLevel >= x.levelRange.min && pmcLevel <= x.levelRange.max + ); } public probabilityObjectArray(configArrayInput: ProbabilityObject[]): ProbabilityObjectArray @@ -38,8 +43,10 @@ export class RepeatableQuestHelper const probabilityArray = new ProbabilityObjectArray(this.mathUtil, this.jsonUtil); for (const configObject of configArray) { - probabilityArray.push(new ProbabilityObject(configObject.key, configObject.relativeProbability, configObject.data)); + probabilityArray.push( + new ProbabilityObject(configObject.key, configObject.relativeProbability, configObject.data), + ); } return probabilityArray; } -} \ No newline at end of file +} diff --git a/project/src/helpers/SecureContainerHelper.ts b/project/src/helpers/SecureContainerHelper.ts index bce992cb..a62f51b1 100644 --- a/project/src/helpers/SecureContainerHelper.ts +++ b/project/src/helpers/SecureContainerHelper.ts @@ -5,24 +5,23 @@ import { Item } from "@spt-aki/models/eft/common/tables/IItem"; export interface OwnerInventoryItems { - from: Item[] - to: Item[] - sameInventory: boolean, - isMail: boolean + from: Item[]; + to: Item[]; + sameInventory: boolean; + isMail: boolean; } @injectable() export class SecureContainerHelper { - constructor( - @inject("ItemHelper") protected itemHelper: ItemHelper + @inject("ItemHelper") protected itemHelper: ItemHelper, ) - { } + {} public getSecureContainerItems(items: Item[]): string[] { - const secureContainer = items.find(x => x.slotId === "SecuredContainer"); + const secureContainer = items.find((x) => x.slotId === "SecuredContainer"); // No container found, drop out if (!secureContainer) @@ -33,6 +32,6 @@ export class SecureContainerHelper const itemsInSecureContainer = this.itemHelper.findAndReturnChildrenByItems(items, secureContainer._id); // Return all items returned and exclude the secure container item itself - return itemsInSecureContainer.filter(x => x !== secureContainer._id); + return itemsInSecureContainer.filter((x) => x !== secureContainer._id); } } diff --git a/project/src/helpers/TradeHelper.ts b/project/src/helpers/TradeHelper.ts index e92f3b77..c4b0d3c1 100644 --- a/project/src/helpers/TradeHelper.ts +++ b/project/src/helpers/TradeHelper.ts @@ -34,7 +34,7 @@ export class TradeHelper @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("InventoryHelper") protected inventoryHelper: InventoryHelper, @inject("RagfairServer") protected ragfairServer: RagfairServer, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.traderConfig = this.configServer.getConfig(ConfigTypes.TRADER); @@ -47,9 +47,15 @@ export class TradeHelper * @param sessionID Session id * @param foundInRaid Should item be found in raid * @param upd optional item details used when buying from flea - * @returns + * @returns */ - public buyItem(pmcData: IPmcData, buyRequestData: IProcessBuyTradeRequestData, sessionID: string, foundInRaid: boolean, upd: Upd): IItemEventRouterResponse + public buyItem( + pmcData: IPmcData, + buyRequestData: IProcessBuyTradeRequestData, + sessionID: string, + foundInRaid: boolean, + upd: Upd, + ): IItemEventRouterResponse { let output = this.eventOutputHolder.getOutput(sessionID); @@ -58,10 +64,10 @@ export class TradeHelper { // eslint-disable-next-line @typescript-eslint/naming-convention item_id: buyRequestData.item_id, - count: buyRequestData.count - } + count: buyRequestData.count, + }, ], - tid: buyRequestData.tid + tid: buyRequestData.tid, }; const callback = () => @@ -71,13 +77,13 @@ export class TradeHelper if (isRagfair) { const allOffers = this.ragfairServer.getOffers(); - const offersWithItem = allOffers.find(x => x.items[0]._id === buyRequestData.item_id); + const offersWithItem = allOffers.find((x) => x.items[0]._id === buyRequestData.item_id); itemPurchased = offersWithItem.items[0]; } else { const traderAssorts = this.traderHelper.getTraderAssortsByTraderId(buyRequestData.tid).items; - itemPurchased = traderAssorts.find(x => x._id === buyRequestData.item_id); + itemPurchased = traderAssorts.find((x) => x._id === buyRequestData.item_id); } // Ensure purchase does not exceed trader item limit @@ -130,7 +136,12 @@ export class TradeHelper * @param sessionID Session id * @returns IItemEventRouterResponse */ - public sellItem(profileWithItemsToSell: IPmcData, profileToReceiveMoney: IPmcData, sellRequest: IProcessSellTradeRequestData, sessionID: string): IItemEventRouterResponse + public sellItem( + profileWithItemsToSell: IPmcData, + profileToReceiveMoney: IPmcData, + sellRequest: IProcessSellTradeRequestData, + sessionID: string, + ): IItemEventRouterResponse { let output = this.eventOutputHolder.getOutput(sessionID); @@ -140,7 +151,7 @@ export class TradeHelper const itemIdToFind = itemToBeRemoved.id.replace(/\s+/g, ""); // Strip out whitespace // Find item in player inventory, or show error to player if not found - const matchingItemInInventory = profileWithItemsToSell.Inventory.items.find(x => x._id === itemIdToFind); + const matchingItemInInventory = profileWithItemsToSell.Inventory.items.find((x) => x._id === itemIdToFind); if (!matchingItemInInventory) { const errorMessage = `Unable to sell item ${itemToBeRemoved.id}, cannot be found in player inventory`; @@ -179,7 +190,9 @@ export class TradeHelper { if ((assortBeingPurchased.upd.BuyRestrictionCurrent + count) > assortBeingPurchased.upd?.BuyRestrictionMax) { - throw new Error(`Unable to purchase ${count} items, this would exceed your purchase limit of ${assortBeingPurchased.upd.BuyRestrictionMax} from the trader this refresh`); + throw new Error( + `Unable to purchase ${count} items, this would exceed your purchase limit of ${assortBeingPurchased.upd.BuyRestrictionMax} from the trader this refresh`, + ); } } -} \ No newline at end of file +} diff --git a/project/src/helpers/TraderAssortHelper.ts b/project/src/helpers/TraderAssortHelper.ts index 15a39dc7..535d48e6 100644 --- a/project/src/helpers/TraderAssortHelper.ts +++ b/project/src/helpers/TraderAssortHelper.ts @@ -29,7 +29,7 @@ export class TraderAssortHelper protected mergedQuestAssorts: Record> = { started: {}, success: {}, - fail: {} + fail: {}, }; protected createdMergedQuestAssorts = false; @@ -46,10 +46,11 @@ export class TraderAssortHelper @inject("RagfairOfferGenerator") protected ragfairOfferGenerator: RagfairOfferGenerator, @inject("TraderAssortService") protected traderAssortService: TraderAssortService, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("TraderPurchasePersisterService") protected traderPurchasePersisterService: TraderPurchasePersisterService, + @inject("TraderPurchasePersisterService") protected traderPurchasePersisterService: + TraderPurchasePersisterService, @inject("TraderHelper") protected traderHelper: TraderHelper, @inject("FenceService") protected fenceService: FenceService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.traderConfig = this.configServer.getConfig(ConfigTypes.TRADER); @@ -81,7 +82,7 @@ export class TraderAssortHelper // Strip assorts player should not see yet if (!flea) - { + { trader.assort = this.assortHelper.stripLockedLoyaltyAssort(pmcProfile, traderId, trader.assort); } @@ -89,21 +90,28 @@ export class TraderAssortHelper trader.assort.nextResupply = trader.base.nextResupply; // Adjust displayed assort counts based on values stored in profile - const assortPurchasesfromTrader = this.traderPurchasePersisterService.getProfileTraderPurchases(sessionId, traderId); + const assortPurchasesfromTrader = this.traderPurchasePersisterService.getProfileTraderPurchases( + sessionId, + traderId, + ); for (const assortId in assortPurchasesfromTrader) { // Find assort we want to update current buy count of - const assortToAdjust = trader.assort.items.find(x => x._id === assortId); + const assortToAdjust = trader.assort.items.find((x) => x._id === assortId); if (!assortToAdjust) { - this.logger.debug(`Cannot find trader: ${trader.base.nickname} assort: ${assortId} to adjust BuyRestrictionCurrent value, skipping`); + this.logger.debug( + `Cannot find trader: ${trader.base.nickname} assort: ${assortId} to adjust BuyRestrictionCurrent value, skipping`, + ); continue; } if (!assortToAdjust.upd) { - this.logger.debug(`Unable to adjust assort ${assortToAdjust._id} item: ${assortToAdjust._tpl} BuyRestrictionCurrent value, assort has an undefined upd object`); + this.logger.debug( + `Unable to adjust assort ${assortToAdjust._id} item: ${assortToAdjust._tpl} BuyRestrictionCurrent value, assort has an undefined upd object`, + ); continue; } @@ -117,7 +125,13 @@ export class TraderAssortHelper this.hydrateMergedQuestAssorts(); this.createdMergedQuestAssorts = true; } - trader.assort = this.assortHelper.stripLockedQuestAssort(pmcProfile, traderId, trader.assort, this.mergedQuestAssorts, flea); + trader.assort = this.assortHelper.stripLockedQuestAssort( + pmcProfile, + traderId, + trader.assort, + this.mergedQuestAssorts, + flea, + ); // Multiply price if multiplier is other than 1 if (this.traderConfig.traderPriceMultipler !== 1) @@ -234,7 +248,7 @@ export class TraderAssortHelper barter_scheme: {}, // eslint-disable-next-line @typescript-eslint/naming-convention loyal_level_items: {}, - nextResupply: null + nextResupply: null, }; } -} \ No newline at end of file +} diff --git a/project/src/helpers/TraderHelper.ts b/project/src/helpers/TraderHelper.ts index 2557b866..19056e3c 100644 --- a/project/src/helpers/TraderHelper.ts +++ b/project/src/helpers/TraderHelper.ts @@ -42,14 +42,14 @@ export class TraderHelper @inject("FenceService") protected fenceService: FenceService, @inject("TimeUtil") protected timeUtil: TimeUtil, @inject("RandomUtil") protected randomUtil: RandomUtil, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.traderConfig = this.configServer.getConfig(ConfigTypes.TRADER); } /** - * Get a trader base object, update profile to reflect players current standing in profile + * Get a trader base object, update profile to reflect players current standing in profile * when trader not found in profile * @param traderID Traders Id to get * @param sessionID Players id @@ -62,7 +62,7 @@ export class TraderHelper { this.logger.error(`No profile with sessionId: ${sessionID}`); } - + // Profile has traderInfo dict (profile beyond creation stage) but no requested trader in profile if (pmcData.TradersInfo && !(traderID in pmcData.TradersInfo)) { @@ -70,7 +70,7 @@ export class TraderHelper this.resetTrader(sessionID, traderID); this.lvlUp(traderID, pmcData); } - + const trader = this.databaseServer.getTables().traders?.[traderID]?.base; if (!trader) { @@ -87,9 +87,9 @@ export class TraderHelper */ public getTraderAssortsByTraderId(traderId: string): ITraderAssort { - return traderId === Traders.FENCE - ? this.fenceService.getRawFenceAssorts() - : this.databaseServer.getTables().traders[traderId].assort; + return traderId === Traders.FENCE ? + this.fenceService.getRawFenceAssorts() : + this.databaseServer.getTables().traders[traderId].assort; } /** @@ -109,7 +109,7 @@ export class TraderHelper } // Find specific assort in traders data - const purchasedAssort = traderAssorts.items.find(x => x._id === assortId); + const purchasedAssort = traderAssorts.items.find((x) => x._id === assortId); if (!purchasedAssort) { this.logger.debug(`No assort ${assortId} on trader: ${traderId} found`); @@ -130,15 +130,17 @@ export class TraderHelper { const account = this.saveServer.getProfile(sessionID); const pmcData = this.profileHelper.getPmcProfile(sessionID); - const rawProfileTemplate: ProfileTraderTemplate = this.databaseServer.getTables().templates.profiles[account.info.edition][pmcData.Info.Side.toLowerCase()].trader; + const rawProfileTemplate: ProfileTraderTemplate = + this.databaseServer.getTables().templates.profiles[account.info.edition][pmcData.Info.Side.toLowerCase()] + .trader; pmcData.TradersInfo[traderID] = { disabled: false, loyaltyLevel: rawProfileTemplate.initialLoyaltyLevel, salesSum: rawProfileTemplate.initialSalesSum, - standing: this.getStartingStanding(traderID, rawProfileTemplate), + standing: this.getStartingStanding(traderID, rawProfileTemplate), nextResupply: this.databaseServer.getTables().traders[traderID].base.nextResupply, - unlocked: this.databaseServer.getTables().traders[traderID].base.unlockedByDefault + unlocked: this.databaseServer.getTables().traders[traderID].base.unlockedByDefault, }; if (traderID === Traders.JAEGER) @@ -197,9 +199,9 @@ export class TraderHelper { const newStanding = currentStanding + standingToAdd; - return newStanding < 0 - ? 0 - : newStanding; + return newStanding < 0 ? + 0 : + newStanding; } /** @@ -224,10 +226,12 @@ export class TraderHelper { const loyalty = loyaltyLevels[level]; - if ((loyalty.minLevel <= pmcData.Info.Level - && loyalty.minSalesSum <= pmcData.TradersInfo[traderID].salesSum - && loyalty.minStanding <= pmcData.TradersInfo[traderID].standing) - && targetLevel < 4) + if ( + (loyalty.minLevel <= pmcData.Info.Level && + loyalty.minSalesSum <= pmcData.TradersInfo[traderID].salesSum && + loyalty.minStanding <= pmcData.TradersInfo[traderID].standing) && + targetLevel < 4 + ) { // level reached targetLevel++; @@ -257,15 +261,20 @@ export class TraderHelper */ public getTraderUpdateSeconds(traderId: string): number { - const traderDetails = this.traderConfig.updateTime.find(x => x.traderId === traderId); + const traderDetails = this.traderConfig.updateTime.find((x) => x.traderId === traderId); if (!traderDetails) { - this.logger.warning(this.localisationService.getText("trader-missing_trader_details_using_default_refresh_time", {traderId: traderId, updateTime: this.traderConfig.updateTimeDefault})); - this.traderConfig.updateTime.push( // create temporary entry to prevent logger spam + this.logger.warning( + this.localisationService.getText("trader-missing_trader_details_using_default_refresh_time", { + traderId: traderId, + updateTime: this.traderConfig.updateTimeDefault, + }), + ); + this.traderConfig.updateTime.push( // create temporary entry to prevent logger spam { traderId: traderId, - seconds: this.traderConfig.updateTimeDefault - } + seconds: this.traderConfig.updateTimeDefault, + }, ); } else @@ -298,7 +307,10 @@ export class TraderHelper * @param newPurchaseDetails New item assort id + count */ // eslint-disable-next-line @typescript-eslint/naming-convention - public addTraderPurchasesToPlayerProfile(sessionID: string, newPurchaseDetails: { items: { item_id: string; count: number; }[]; tid: string; }): void + public addTraderPurchasesToPlayerProfile( + sessionID: string, + newPurchaseDetails: {items: {item_id: string; count: number;}[]; tid: string;}, + ): void { const profile = this.profileHelper.getFullProfile(sessionID); const traderId = newPurchaseDetails.tid; @@ -320,10 +332,9 @@ export class TraderHelper const currentTime = this.timeUtil.getTimestamp(); if (!profile.traderPurchases[traderId][purchasedItem.item_id]) { - profile.traderPurchases[traderId][purchasedItem.item_id] = - { + profile.traderPurchases[traderId][purchasedItem.item_id] = { count: purchasedItem.count, - purchaseTimestamp: currentTime + purchaseTimestamp: currentTime, }; continue; @@ -369,15 +380,15 @@ export class TraderHelper } // Get all item assorts that have parentid of hideout (base item and not a mod of other item) - for (const item of traderAssorts.items.filter(x => x.parentId === "hideout")) + for (const item of traderAssorts.items.filter((x) => x.parentId === "hideout")) { // Get barter scheme (contains cost of item) const barterScheme = traderAssorts.barter_scheme[item._id][0][0]; // Convert into roubles - const roubleAmount = barterScheme._tpl === Money.ROUBLES - ? barterScheme.count - : this.handbookHelper.inRUB(barterScheme.count, barterScheme._tpl); + const roubleAmount = barterScheme._tpl === Money.ROUBLES ? + barterScheme.count : + this.handbookHelper.inRUB(barterScheme.count, barterScheme._tpl); // Existing price smaller in dict than current iteration, overwrite if (this.highestTraderPriceItems[item._tpl] ?? 0 < roubleAmount) @@ -409,7 +420,6 @@ export class TraderHelper return this.highestTraderBuyPriceItems[tpl]; } - // Find highest trader price for item for (const traderName in Traders) { @@ -423,7 +433,9 @@ export class TraderHelper const traderBuyBackPricePercent = relevantLoyaltyData.buy_price_coef; const itemHandbookPrice = this.handbookHelper.getTemplatePrice(tpl); - const priceTraderBuysItemAt = Math.round(this.randomUtil.getPercentOfValue(traderBuyBackPricePercent, itemHandbookPrice)); + const priceTraderBuysItemAt = Math.round( + this.randomUtil.getPercentOfValue(traderBuyBackPricePercent, itemHandbookPrice), + ); // Set new item to 1 rouble as default if (!this.highestTraderBuyPriceItems[tpl]) @@ -449,7 +461,7 @@ export class TraderHelper */ public getTraderById(traderId: string): Traders { - const keys = Object.keys(Traders).filter(x => Traders[x] === traderId); + const keys = Object.keys(Traders).filter((x) => Traders[x] === traderId); if (keys.length === 0) { @@ -462,16 +474,16 @@ export class TraderHelper } /** - * Validates that the provided traderEnumValue exists in the Traders enum. If the value is valid, it returns the - * same enum value, effectively serving as a trader ID; otherwise, it logs an error and returns an empty string. + * Validates that the provided traderEnumValue exists in the Traders enum. If the value is valid, it returns the + * same enum value, effectively serving as a trader ID; otherwise, it logs an error and returns an empty string. * This method provides a runtime check to prevent undefined behavior when using the enum as a dictionary key. - * + * * For example, instead of this: * `const traderId = Traders[Traders.PRAPOR];` - * + * * You can use safely use this: * `const traderId = this.traderHelper.getValidTraderIdByEnumValue(Traders.PRAPOR);` - * + * * @param traderEnumValue The trader enum value to validate * @returns The validated trader enum value as a string, or an empty string if invalid */ @@ -483,7 +495,7 @@ export class TraderHelper return ""; } - + return Traders[traderEnumValue]; } @@ -506,4 +518,4 @@ export class TraderHelper { return Object.values(Traders).some((x) => x === traderId); } -} \ No newline at end of file +} diff --git a/project/src/helpers/UtilityHelper.ts b/project/src/helpers/UtilityHelper.ts index 8093354f..6e10d619 100644 --- a/project/src/helpers/UtilityHelper.ts +++ b/project/src/helpers/UtilityHelper.ts @@ -5,6 +5,6 @@ export class UtilityHelper { public arrayIntersect(a: T[], b: T[]): T[] { - return a.filter(x => b.includes(x)); + return a.filter((x) => b.includes(x)); } -} \ No newline at end of file +} diff --git a/project/src/helpers/WeightedRandomHelper.ts b/project/src/helpers/WeightedRandomHelper.ts index 17d639d0..5b6178a4 100644 --- a/project/src/helpers/WeightedRandomHelper.ts +++ b/project/src/helpers/WeightedRandomHelper.ts @@ -9,7 +9,7 @@ export class WeightedRandomHelper * @param {tplId: weighting[]} itemArray * @returns tplId */ - public getWeightedInventoryItem(itemArray: { [tplId: string]: unknown; } | ArrayLike): string + public getWeightedInventoryItem(itemArray: {[tplId: string]: unknown;} | ArrayLike): string { const itemKeys = Object.keys(itemArray); const weights = Object.values(itemArray); @@ -18,7 +18,7 @@ export class WeightedRandomHelper return chosenItem.item; } - public getWeightedValue(itemArray: { [key: string]: unknown; } | ArrayLike): T + public getWeightedValue(itemArray: {[key: string]: unknown;} | ArrayLike): T { const itemKeys = Object.keys(itemArray); const weights = Object.values(itemArray); @@ -41,7 +41,7 @@ export class WeightedRandomHelper * @param {number[]} weights * @returns {{item: any, index: number}} */ - public weightedRandom(items: string | any[], weights: string | any[]): { item: any; index: number; } + public weightedRandom(items: string | any[], weights: string | any[]): {item: any; index: number;} { if (items.length !== weights.length) { @@ -79,9 +79,9 @@ export class WeightedRandomHelper { return { item: items[itemIndex], - index: itemIndex + index: itemIndex, }; } } } -} \ No newline at end of file +} From 3f2d36a2fc11ac38c76a208559f17b0656b28110 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:10:44 -0500 Subject: [PATCH 28/41] Formatting for loader classes. --- project/src/loaders/BundleLoader.ts | 18 +-- project/src/loaders/ModLoadOrder.ts | 15 ++- project/src/loaders/ModTypeCheck.ts | 16 ++- project/src/loaders/PostAkiModLoader.ts | 21 ++-- project/src/loaders/PostDBModLoader.ts | 28 +++-- project/src/loaders/PreAkiModLoader.ts | 139 ++++++++++++++++-------- 6 files changed, 153 insertions(+), 84 deletions(-) diff --git a/project/src/loaders/BundleLoader.ts b/project/src/loaders/BundleLoader.ts index b14e5b9b..b2e40f6f 100644 --- a/project/src/loaders/BundleLoader.ts +++ b/project/src/loaders/BundleLoader.ts @@ -1,4 +1,3 @@ - import { inject, injectable } from "tsyringe"; import { HttpServerHelper } from "@spt-aki/helpers/HttpServerHelper"; @@ -31,9 +30,9 @@ export class BundleLoader constructor( @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper, @inject("VFS") protected vfs: VFS, - @inject("JsonUtil") protected jsonUtil: JsonUtil + @inject("JsonUtil") protected jsonUtil: JsonUtil, ) - { } + {} /** * Handle singleplayer/bundles @@ -65,7 +64,8 @@ export class BundleLoader public addBundles(modpath: string): void { - const manifest = this.jsonUtil.deserialize(this.vfs.readFile(`${modpath}bundles.json`)).manifest; + const manifest = + this.jsonUtil.deserialize(this.vfs.readFile(`${modpath}bundles.json`)).manifest; for (const bundle of manifest) { @@ -75,7 +75,7 @@ export class BundleLoader } } - public addBundle(key: string, b: BundleInfo): void + public addBundle(key: string, b: BundleInfo): void { this.bundles[key] = b; } @@ -83,11 +83,11 @@ export class BundleLoader export interface BundleManifest { - manifest: Array + manifest: Array; } export interface BundleManifestEntry { - key: string - path: string -} \ No newline at end of file + key: string; + path: string; +} diff --git a/project/src/loaders/ModLoadOrder.ts b/project/src/loaders/ModLoadOrder.ts index 469c0454..c874ac01 100644 --- a/project/src/loaders/ModLoadOrder.ts +++ b/project/src/loaders/ModLoadOrder.ts @@ -13,9 +13,9 @@ export class ModLoadOrder constructor( @inject("WinstonLogger") protected logger: ILogger, - @inject("LocalisationService") protected localisationService: LocalisationService + @inject("LocalisationService") protected localisationService: LocalisationService, ) - { } + {} public setModList(mods: Record): void { @@ -25,8 +25,8 @@ export class ModLoadOrder const visited = new Set(); - //invert loadBefore into loadAfter on specified mods - for (const [ modName, modConfig ] of this.modsAvailable) + // invert loadBefore into loadAfter on specified mods + for (const [modName, modConfig] of this.modsAvailable) { if ((modConfig.loadBefore ?? []).length > 0) { @@ -143,7 +143,12 @@ export class ModLoadOrder { if (this.modsAvailable.get(modAfter)?.loadAfter?.includes(mod)) { - throw new Error(this.localisationService.getText("modloader-load_order_conflict", {modOneName: mod, modTwoName: modAfter})); + throw new Error( + this.localisationService.getText("modloader-load_order_conflict", { + modOneName: mod, + modTwoName: modAfter, + }), + ); } dependencies.add(modAfter); diff --git a/project/src/loaders/ModTypeCheck.ts b/project/src/loaders/ModTypeCheck.ts index 2edc06de..12f302b5 100644 --- a/project/src/loaders/ModTypeCheck.ts +++ b/project/src/loaders/ModTypeCheck.ts @@ -10,7 +10,6 @@ import { IPreAkiLoadModAsync } from "@spt-aki/models/external/IPreAkiLoadModAsyn @injectable() export class ModTypeCheck { - /** * Use defined safe guard to check if the mod is a IPreAkiLoadMod * @returns boolean @@ -19,7 +18,7 @@ export class ModTypeCheck { return mod?.preAkiLoad; } - + /** * Use defined safe guard to check if the mod is a IPostAkiLoadMod * @returns boolean @@ -28,7 +27,7 @@ export class ModTypeCheck { return mod?.postAkiLoad; } - + /** * Use defined safe guard to check if the mod is a IPostDBLoadMod * @returns boolean @@ -46,7 +45,7 @@ export class ModTypeCheck { return mod?.preAkiLoadAsync; } - + /** * Use defined safe guard to check if the mod is a IPostAkiLoadModAsync * @returns boolean @@ -55,7 +54,7 @@ export class ModTypeCheck { return mod?.postAkiLoadAsync; } - + /** * Use defined safe guard to check if the mod is a IPostDBLoadModAsync * @returns boolean @@ -71,12 +70,11 @@ export class ModTypeCheck */ public isPostV3Compatible(mod: any): boolean { - return this.isPreAkiLoad(mod) || - this.isPostAkiLoad(mod) || + return this.isPreAkiLoad(mod) || + this.isPostAkiLoad(mod) || this.isPostDBAkiLoad(mod) || this.isPreAkiLoadAsync(mod) || this.isPostAkiLoadAsync(mod) || this.isPostDBAkiLoadAsync(mod); - } -} \ No newline at end of file +} diff --git a/project/src/loaders/PostAkiModLoader.ts b/project/src/loaders/PostAkiModLoader.ts index deb30055..a04b4c2c 100644 --- a/project/src/loaders/PostAkiModLoader.ts +++ b/project/src/loaders/PostAkiModLoader.ts @@ -19,9 +19,9 @@ export class PostAkiModLoader implements IModLoader @inject("VFS") protected vfs: VFS, @inject("PreAkiModLoader") protected preAkiModLoader: PreAkiModLoader, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ModTypeCheck") protected modTypeCheck: ModTypeCheck + @inject("ModTypeCheck") protected modTypeCheck: ModTypeCheck, ) - { } + {} public getModPath(mod: string): string { @@ -43,20 +43,27 @@ export class PostAkiModLoader implements IModLoader for (const modName of mods) { // // import class - const filepath = `${this.preAkiModLoader.getModPath(modName)}${this.preAkiModLoader.getImportedModDetails()[modName].main}`; + const filepath = `${this.preAkiModLoader.getModPath(modName)}${ + this.preAkiModLoader.getImportedModDetails()[modName].main + }`; const modpath = `${process.cwd()}/${filepath}`; // eslint-disable-next-line @typescript-eslint/no-var-requires const mod = require(modpath); if (this.modTypeCheck.isPostAkiLoadAsync(mod.mod)) { - try + try { await (mod.mod as IPostAkiLoadModAsync).postAkiLoadAsync(container); } - catch (err) + catch (err) { - this.logger.error(this.localisationService.getText("modloader-async_mod_error", `${err?.message ?? ""}\n${err.stack ?? ""}`)); + this.logger.error( + this.localisationService.getText( + "modloader-async_mod_error", + `${err?.message ?? ""}\n${err.stack ?? ""}`, + ), + ); } } @@ -80,4 +87,4 @@ export class PostAkiModLoader implements IModLoader } } } -} \ No newline at end of file +} diff --git a/project/src/loaders/PostDBModLoader.ts b/project/src/loaders/PostDBModLoader.ts index 8b324792..86e80e0c 100644 --- a/project/src/loaders/PostDBModLoader.ts +++ b/project/src/loaders/PostDBModLoader.ts @@ -15,10 +15,10 @@ export class PostDBModLoader implements OnLoad @inject("WinstonLogger") protected logger: ILogger, @inject("PreAkiModLoader") protected preAkiModLoader: PreAkiModLoader, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ModTypeCheck") protected modTypeCheck: ModTypeCheck + @inject("ModTypeCheck") protected modTypeCheck: ModTypeCheck, ) - { } - + {} + public async onLoad(): Promise { if (globalThis.G_MODS_ENABLED) @@ -26,13 +26,12 @@ export class PostDBModLoader implements OnLoad await this.executeMods(this.preAkiModLoader.getContainer()); } } - + public getRoute(): string { return "aki-mods"; } - public getModPath(mod: string): string { return this.preAkiModLoader.getModPath(mod); @@ -43,21 +42,28 @@ export class PostDBModLoader implements OnLoad const mods = this.preAkiModLoader.sortModsLoadOrder(); for (const modName of mods) { - // // import class - const filepath = `${this.preAkiModLoader.getModPath(modName)}${this.preAkiModLoader.getImportedModDetails()[modName].main}`; + // import class + const filepath = `${this.preAkiModLoader.getModPath(modName)}${ + this.preAkiModLoader.getImportedModDetails()[modName].main + }`; const modpath = `${process.cwd()}/${filepath}`; // eslint-disable-next-line @typescript-eslint/no-var-requires const mod = require(modpath); if (this.modTypeCheck.isPostDBAkiLoadAsync(mod.mod)) { - try + try { await (mod.mod as IPostDBLoadModAsync).postDBLoadAsync(container); } - catch (err) + catch (err) { - this.logger.error(this.localisationService.getText("modloader-async_mod_error", `${err?.message ?? ""}\n${err.stack ?? ""}`)); + this.logger.error( + this.localisationService.getText( + "modloader-async_mod_error", + `${err?.message ?? ""}\n${err.stack ?? ""}`, + ), + ); } } @@ -67,4 +73,4 @@ export class PostDBModLoader implements OnLoad } } } -} \ No newline at end of file +} diff --git a/project/src/loaders/PreAkiModLoader.ts b/project/src/loaders/PreAkiModLoader.ts index 630305c4..3568eb83 100644 --- a/project/src/loaders/PreAkiModLoader.ts +++ b/project/src/loaders/PreAkiModLoader.ts @@ -43,7 +43,7 @@ export class PreAkiModLoader implements IModLoader @inject("LocalisationService") protected localisationService: LocalisationService, @inject("ConfigServer") protected configServer: ConfigServer, @inject("ModLoadOrder") protected modLoadOrder: ModLoadOrder, - @inject("ModTypeCheck") protected modTypeCheck: ModTypeCheck + @inject("ModTypeCheck") protected modTypeCheck: ModTypeCheck, ) { this.akiConfig = this.configServer.getConfig(ConfigTypes.CORE); @@ -96,10 +96,10 @@ export class PreAkiModLoader implements IModLoader for (const modName in modsGroupedByName) { const modDatas = modsGroupedByName[modName]; - const modVersions = modDatas.map(x => x.version); + const modVersions = modDatas.map((x) => x.version); const highestVersion = semver.maxSatisfying(modVersions, "*"); - const chosenVersion = modDatas.find(x => x.name === modName && x.version === highestVersion); + const chosenVersion = modDatas.find((x) => x.name === modName && x.version === highestVersion); if (!chosenVersion) { continue; @@ -130,28 +130,28 @@ export class PreAkiModLoader implements IModLoader * array of mod folder names */ const mods: string[] = this.vfs.getDirs(this.basepath); - + this.logger.info(this.localisationService.getText("modloader-loading_mods", mods.length)); // Mod order - if (!this.vfs.exists(this.modOrderPath)) + if (!this.vfs.exists(this.modOrderPath)) { this.logger.info(this.localisationService.getText("modloader-mod_order_missing")); // Write file with empty order array to disk this.vfs.writeFile(this.modOrderPath, this.jsonUtil.serializeAdvanced({order: []}, null, 4)); } - else + else { - const modOrder = this.vfs.readFile(this.modOrderPath, { encoding: "utf8" }); - try + const modOrder = this.vfs.readFile(this.modOrderPath, {encoding: "utf8"}); + try { for (const [index, mod] of (this.jsonUtil.deserialize(modOrder).order as string[]).entries()) { this.order[mod] = index; } } - catch (error) + catch (error) { this.logger.error(this.localisationService.getText("modloader-mod_order_error")); } @@ -175,7 +175,10 @@ export class PreAkiModLoader implements IModLoader } // if the mod has library dependencies check if these dependencies are bundled in the server, if not install them - if (modToValidate.dependencies && Object.keys(modToValidate.dependencies).length > 0 && !this.vfs.exists(`${this.basepath}${modFolderName}/node_modules`)) + if ( + modToValidate.dependencies && Object.keys(modToValidate.dependencies).length > 0 && + !this.vfs.exists(`${this.basepath}${modFolderName}/node_modules`) + ) { this.autoInstallDependencies(`${this.basepath}${modFolderName}`, modToValidate); } @@ -222,7 +225,7 @@ export class PreAkiModLoader implements IModLoader if (this.shouldSkipMod(pkg)) { - this.logger.warning(this.localisationService.getText("modloader-skipped_mod", { mod: mod })); + this.logger.warning(this.localisationService.getText("modloader-skipped_mod", {mod: mod})); continue; } @@ -236,15 +239,15 @@ export class PreAkiModLoader implements IModLoader { const previndex = this.order[prev]; const nextindex = this.order[next]; - + // mod is not on the list, move the mod to last - if (previndex === undefined) + if (previndex === undefined) { missingFromOrderJSON[prev] = true; return 1; } - else if (nextindex === undefined) + else if (nextindex === undefined) { missingFromOrderJSON[next] = true; @@ -283,7 +286,7 @@ export class PreAkiModLoader implements IModLoader /** * Returns an array of valid mods. - * + * * @param mods mods to validate * @returns array of mod folder names */ @@ -391,14 +394,19 @@ export class PreAkiModLoader implements IModLoader // Perform async load of mod if (this.modTypeCheck.isPreAkiLoadAsync(requiredMod.mod)) { - try + try { await (requiredMod.mod as IPreAkiLoadModAsync).preAkiLoadAsync(container); globalThis[mod] = requiredMod; } - catch (err) + catch (err) { - this.logger.error(this.localisationService.getText("modloader-async_mod_error", `${err?.message ?? ""}\n${err.stack ?? ""}`)); + this.logger.error( + this.localisationService.getText( + "modloader-async_mod_error", + `${err?.message ?? ""}\n${err.stack ?? ""}`, + ), + ); } continue; @@ -457,7 +465,7 @@ export class PreAkiModLoader implements IModLoader else { // rename the mod entry point to .ts if it's set to .js because G_MODS_TRANSPILE_TS is set to false - pkg.main = (pkg.main).replace(".js", ".ts"); + pkg.main = pkg.main.replace(".js", ".ts"); } } @@ -466,14 +474,20 @@ export class PreAkiModLoader implements IModLoader // Add mod to imported list this.imported[mod] = {...pkg, dependencies: pkg.modDependencies}; - this.logger.info(this.localisationService.getText("modloader-loaded_mod", {name: pkg.name, version: pkg.version, author: pkg.author})); + this.logger.info( + this.localisationService.getText("modloader-loaded_mod", { + name: pkg.name, + version: pkg.version, + author: pkg.author, + }), + ); } /** * Checks if a given mod should be loaded or skipped. - * + * * @param pkg mod package.json data - * @returns + * @returns */ protected shouldSkipMod(pkg: IPackageJsonData): boolean { @@ -509,12 +523,17 @@ export class PreAkiModLoader implements IModLoader // If this feature flag is set to false, we warn the user he has a mod that requires extra dependencies and might not work, point them in the right direction on how to enable this feature. if (!this.akiConfig.features.autoInstallModDependencies) { - this.logger.warning(this.localisationService.getText("modloader-installing_external_dependencies_disabled", { - name: pkg.name, - author: pkg.author, - configPath: path.join(globalThis.G_RELEASE_CONFIGURATION ? "Aki_Data/Server/configs" : "assets/configs", "core.json"), - configOption: "autoInstallModDependencies" - })); + this.logger.warning( + this.localisationService.getText("modloader-installing_external_dependencies_disabled", { + name: pkg.name, + author: pkg.author, + configPath: path.join( + globalThis.G_RELEASE_CONFIGURATION ? "Aki_Data/Server/configs" : "assets/configs", + "core.json", + ), + configOption: "autoInstallModDependencies", + }), + ); this.skippedMods.add(`${pkg.author}-${pkg.name}`); return; @@ -524,12 +543,21 @@ export class PreAkiModLoader implements IModLoader this.vfs.rename(`${modPath}/package.json`, `${modPath}/package.json.bak`); this.vfs.writeFile(`${modPath}/package.json`, "{}"); - this.logger.info(this.localisationService.getText("modloader-installing_external_dependencies", {name: pkg.name, author: pkg.author})); + this.logger.info( + this.localisationService.getText("modloader-installing_external_dependencies", { + name: pkg.name, + author: pkg.author, + }), + ); - const pnpmPath = path.join(process.cwd(), (globalThis.G_RELEASE_CONFIGURATION ? "Aki_Data/Server/@pnpm/exe" : "node_modules/@pnpm/exe"), (os.platform() === "win32" ? "pnpm.exe" : "pnpm")); + const pnpmPath = path.join( + process.cwd(), + globalThis.G_RELEASE_CONFIGURATION ? "Aki_Data/Server/@pnpm/exe" : "node_modules/@pnpm/exe", + os.platform() === "win32" ? "pnpm.exe" : "pnpm", + ); let command = `${pnpmPath} install `; command += dependenciesToInstall.map(([depName, depVersion]) => `${depName}@${depVersion}`).join(" "); - execSync(command, { cwd: modPath }); + execSync(command, {cwd: modPath}); // Delete the new blank package.json then rename the backup back to the original name this.vfs.removeFile(`${modPath}/package.json`); @@ -545,18 +573,30 @@ export class PreAkiModLoader implements IModLoader const modName = `${pkg.author}-${pkg.name}`; - for (const [modDependency, requiredVersion ] of Object.entries(pkg.modDependencies)) + for (const [modDependency, requiredVersion] of Object.entries(pkg.modDependencies)) { // Raise dependency version incompatible if the dependency is not found in the mod list if (!loadedMods.has(modDependency)) { - this.logger.error(this.localisationService.getText("modloader-missing_dependency", {mod: modName, modDependency: modDependency})); + this.logger.error( + this.localisationService.getText("modloader-missing_dependency", { + mod: modName, + modDependency: modDependency, + }), + ); return false; } if (!semver.satisfies(loadedMods.get(modDependency).version, requiredVersion)) { - this.logger.error(this.localisationService.getText("modloader-outdated_dependency", {mod: modName, modDependency: modDependency, currentVersion: loadedMods.get(modDependency).version, requiredVersion: requiredVersion})); + this.logger.error( + this.localisationService.getText("modloader-outdated_dependency", { + mod: modName, + modDependency: modDependency, + currentVersion: loadedMods.get(modDependency).version, + requiredVersion: requiredVersion, + }), + ); return false; } } @@ -577,7 +617,13 @@ export class PreAkiModLoader implements IModLoader // Raise dependency version incompatible if any incompatible mod is found if (loadedMods.has(incompatibleModName)) { - this.logger.error(this.localisationService.getText("modloader-incompatible_mod_found", {author: mod.author, modName: mod.name, incompatibleModName: incompatibleModName})); + this.logger.error( + this.localisationService.getText("modloader-incompatible_mod_found", { + author: mod.author, + modName: mod.name, + incompatibleModName: incompatibleModName, + }), + ); return false; } } @@ -599,7 +645,7 @@ export class PreAkiModLoader implements IModLoader const modIsCalledSrc = modName.toLowerCase() === "src"; const modIsCalledDb = modName.toLowerCase() === "db"; const hasBepinExFolderStructure = this.vfs.exists(`${modPath}/plugins`); - const containsDll = this.vfs.getFiles(`${modPath}`).find(x => x.includes(".dll")); + const containsDll = this.vfs.getFiles(`${modPath}`).find((x) => x.includes(".dll")); if (modIsCalledSrc || modIsCalledDb || modIsCalledUser) { @@ -629,7 +675,12 @@ export class PreAkiModLoader implements IModLoader { if (!(check in config)) { - this.logger.error(this.localisationService.getText("modloader-missing_package_json_property", {modName: modName, prop: check})); + this.logger.error( + this.localisationService.getText("modloader-missing_package_json_property", { + modName: modName, + prop: check, + }), + ); issue = true; } } @@ -642,23 +693,23 @@ export class PreAkiModLoader implements IModLoader if ("main" in config) { - if (config.main.split(".").pop() !== "js") // expects js file as entry - { + if (config.main.split(".").pop() !== "js") + { // expects js file as entry this.logger.error(this.localisationService.getText("modloader-main_property_not_js", modName)); issue = true; } - if (!this.vfs.exists(`${modPath}/${config.main}`)) { - // If TS file exists with same name, dont perform check as we'll generate JS from TS file const tsFileName = config.main.replace(".js", ".ts"); const tsFileExists = this.vfs.exists(`${modPath}/${tsFileName}`); if (!tsFileExists) { - this.logger.error(this.localisationService.getText("modloader-main_property_points_to_nothing", modName)); + this.logger.error( + this.localisationService.getText("modloader-main_property_points_to_nothing", modName), + ); issue = true; } } @@ -666,7 +717,9 @@ export class PreAkiModLoader implements IModLoader if (config.incompatibilities && !Array.isArray(config.incompatibilities)) { - this.logger.error(this.localisationService.getText("modloader-incompatibilities_not_string_array", modName)); + this.logger.error( + this.localisationService.getText("modloader-incompatibilities_not_string_array", modName), + ); issue = true; } From d62ccce3ca9145089dcb743e2ce486df3138d647 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:11:36 -0500 Subject: [PATCH 29/41] Formatting for models. --- project/src/models/common/MinMax.ts | 8 +- .../eft/bot/IGenerateBotsRequestData.ts | 14 +- .../eft/bot/IRandomisedBotLevelResult.ts | 6 +- .../models/eft/common/IEmptyRequestData.ts | 3 +- project/src/models/eft/common/IGlobals.ts | 2394 ++++++++--------- project/src/models/eft/common/ILocation.ts | 20 +- .../src/models/eft/common/ILocationBase.ts | 450 ++-- .../common/ILocationsSourceDestinationBase.ts | 14 +- project/src/models/eft/common/ILooseLoot.ts | 58 +- .../models/eft/common/IMetricsTableData.ts | 14 +- project/src/models/eft/common/IPmcData.ts | 4 +- project/src/models/eft/common/Ixyz.ts | 3 +- .../request/IBaseInteractionRequestData.ts | 16 +- .../src/models/eft/common/tables/IBotBase.ts | 608 +++-- .../src/models/eft/common/tables/IBotCore.ts | 266 +- .../src/models/eft/common/tables/IBotType.ts | 294 +- .../eft/common/tables/ICustomizationItem.ts | 52 +- .../models/eft/common/tables/IHandbookBase.ts | 28 +- project/src/models/eft/common/tables/IItem.ts | 261 +- .../eft/common/tables/ILocationsBase.ts | 18 +- .../src/models/eft/common/tables/ILootBase.ts | 84 +- .../src/models/eft/common/tables/IMatch.ts | 16 +- .../eft/common/tables/IProfileTemplate.ts | 36 +- .../src/models/eft/common/tables/IQuest.ts | 208 +- .../eft/common/tables/IRepeatableQuests.ts | 432 ++- .../models/eft/common/tables/ITemplateItem.ts | 938 +++---- .../src/models/eft/common/tables/ITrader.ts | 170 +- .../customization/IBuyClothingRequestData.ts | 16 +- .../eft/customization/IGetSuitsResponse.ts | 6 +- .../customization/IWearClothingRequestData.ts | 8 +- .../eft/dialog/IAcceptFriendRequestData.ts | 4 +- project/src/models/eft/dialog/IChatServer.ts | 24 +- .../eft/dialog/IClearMailMessageRequest.ts | 4 +- .../models/eft/dialog/IDeleteFriendRequest.ts | 4 +- .../models/eft/dialog/IFriendRequestData.ts | 6 +- .../eft/dialog/IFriendRequestSendResponse.ts | 8 +- .../dialog/IGetAllAttachmentsRequestData.ts | 6 +- .../eft/dialog/IGetAllAttachmentsResponse.ts | 8 +- .../dialog/IGetChatServerListRequestData.ts | 4 +- .../eft/dialog/IGetFriendListDataResponse.ts | 8 +- .../dialog/IGetMailDialogInfoRequestData.ts | 3 +- .../dialog/IGetMailDialogListRequestData.ts | 8 +- .../dialog/IGetMailDialogViewRequestData.ts | 12 +- .../dialog/IGetMailDialogViewResponseData.ts | 10 +- .../eft/dialog/IPinDialogRequestData.ts | 6 +- .../eft/dialog/IRemoveDialogRequestData.ts | 5 +- .../eft/dialog/IRemoveMailMessageRequest.ts | 4 +- .../models/eft/dialog/ISendMessageRequest.ts | 10 +- .../eft/dialog/ISetDialogReadRequestData.ts | 4 +- .../models/eft/game/ICheckVersionResponse.ts | 6 +- .../models/eft/game/ICurrentGroupResponse.ts | 22 +- .../models/eft/game/IGameConfigResponse.ts | 38 +- .../eft/game/IGameEmptyCrcRequestData.ts | 6 +- .../models/eft/game/IGameKeepAliveResponse.ts | 6 +- .../eft/game/IGameLogoutResponseData.ts | 4 +- .../src/models/eft/game/IGameStartResponse.ts | 4 +- .../models/eft/game/IGetItemPricesResponse.ts | 8 +- .../eft/game/IReportNicknameRequestData.ts | 4 +- project/src/models/eft/game/IServerDetails.ts | 6 +- .../eft/game/IVersionValidateRequestData.ts | 20 +- project/src/models/eft/health/Effect.ts | 6 +- .../eft/health/IHealthTreatmentRequestData.ts | 50 +- .../eft/health/IOffraidEatRequestData.ts | 12 +- .../eft/health/IOffraidHealRequestData.ts | 20 +- .../eft/health/ISyncHealthRequestData.ts | 36 +- project/src/models/eft/health/IWorkoutData.ts | 8 +- .../HideoutUpgradeCompleteRequestData.ts | 10 +- .../eft/hideout/IHandleQTEEventRequestData.ts | 10 +- .../src/models/eft/hideout/IHideoutArea.ts | 124 +- .../IHideoutCancelProductionRequestData.ts | 8 +- ...outContinuousProductionStartRequestData.ts | 10 +- .../hideout/IHideoutImproveAreaRequestData.ts | 16 +- .../models/eft/hideout/IHideoutProduction.ts | 46 +- .../hideout/IHideoutPutItemInRequestData.ts | 18 +- .../models/eft/hideout/IHideoutScavCase.ts | 30 +- .../IHideoutScavCaseStartRequestData.ts | 24 +- .../eft/hideout/IHideoutSettingsBase.ts | 12 +- ...HideoutSingleProductionStartRequestData.ts | 18 +- .../hideout/IHideoutTakeItemOutRequestData.ts | 12 +- .../IHideoutTakeProductionRequestData.ts | 10 +- .../hideout/IHideoutToggleAreaRequestData.ts | 12 +- .../IHideoutUpgradeCompleteRequestData.ts | 10 +- .../eft/hideout/IHideoutUpgradeRequestData.ts | 18 +- project/src/models/eft/hideout/IQteData.ts | 54 +- .../eft/hideout/IRecordShootingRangePoints.ts | 6 +- .../eft/httpResponse/IGetBodyResponseData.ts | 10 +- .../eft/httpResponse/INullResponseData.ts | 10 +- .../models/eft/inRaid/IInsuredItemsData.ts | 12 +- .../eft/inRaid/IRegisterPlayerRequestData.ts | 10 +- .../eft/inRaid/ISaveProgressRequestData.ts | 14 +- .../insurance/IGetInsuranceCostRequestData.ts | 8 +- .../IGetInsuranceCostResponseData.ts | 2 +- .../eft/insurance/IInsureRequestData.ts | 10 +- .../eft/inventory/IAddItemRequestData.ts | 2 +- .../eft/inventory/IAddItemTempObject.ts | 12 +- .../eft/inventory/IInventoryAddRequestData.ts | 15 +- .../IInventoryBaseActionRequestData.ts | 49 +- .../inventory/IInventoryBindRequestData.ts | 10 +- .../IInventoryCreateMarkerRequestData.ts | 20 +- .../IInventoryDeleteMarkerRequestData.ts | 12 +- .../IInventoryEditMarkerRequestData.ts | 24 +- .../inventory/IInventoryExamineRequestData.ts | 10 +- .../inventory/IInventoryFoldRequestData.ts | 10 +- .../inventory/IInventoryMergeRequestData.ts | 10 +- .../inventory/IInventoryMoveRequestData.ts | 10 +- .../IInventoryReadEncyclopediaRequestData.ts | 8 +- .../inventory/IInventoryRemoveRequestData.ts | 8 +- .../inventory/IInventorySortRequestData.ts | 32 +- .../inventory/IInventorySplitRequestData.ts | 18 +- .../inventory/IInventorySwapRequestData.ts | 18 +- .../eft/inventory/IInventoryTagRequestData.ts | 12 +- .../inventory/IInventoryToggleRequestData.ts | 10 +- .../IInventoryTransferRequestData.ts | 12 +- .../IOpenRandomLootContainerRequestData.ts | 12 +- .../eft/itemEvent/IItemEventRouterBase.ts | 106 +- .../eft/itemEvent/IItemEventRouterRequest.ts | 39 +- .../eft/itemEvent/IItemEventRouterResponse.ts | 2 +- .../models/eft/launcher/IChangeRequestData.ts | 4 +- .../launcher/IGetMiniProfileRequestData.ts | 8 +- .../models/eft/launcher/ILoginRequestData.ts | 6 +- .../src/models/eft/launcher/IMiniProfile.ts | 26 +- .../src/models/eft/launcher/IRegisterData.ts | 4 +- .../models/eft/launcher/IRemoveProfileData.ts | 2 +- .../models/eft/location/IAirdropLootResult.ts | 6 +- .../eft/location/IGetLocationRequestData.ts | 10 +- .../eft/match/IAcceptGroupInviteRequest.ts | 4 +- .../eft/match/IAcceptGroupInviteResponse.ts | 26 +- .../eft/match/ICancelGroupInviteRequest.ts | 4 +- .../eft/match/ICreateGroupRequestData.ts | 8 +- .../eft/match/IEndOfflineRaidRequestData.ts | 10 +- .../eft/match/IGetGroupStatusRequestData.ts | 14 +- .../eft/match/IGetProfileRequestData.ts | 2 +- .../match/IGetRaidConfigurationRequestData.ts | 54 +- .../models/eft/match/IJoinMatchRequestData.ts | 12 +- .../src/models/eft/match/IJoinMatchResult.ts | 30 +- .../eft/match/IPutMetricsRequestData.ts | 18 +- .../match/IRemovePlayerFromGroupRequest.ts | 4 +- .../eft/match/ISendGroupInviteRequest.ts | 6 +- .../models/eft/match/ITransferGroupRequest.ts | 4 +- .../eft/match/IUpdatePingRequestData.ts | 4 +- .../src/models/eft/notes/INoteActionData.ts | 10 +- project/src/models/eft/notifier/INotifier.ts | 23 +- .../eft/notifier/ISelectProfileRequestData.ts | 6 +- .../eft/notifier/ISelectProfileResponse.ts | 4 +- .../IPlayerIncrementSkillLevelRequestData.ts | 36 +- .../IPresetBuildActionRequestData.ts | 14 +- .../presetBuild/IRemoveBuildRequestData.ts | 6 +- .../profile/GetProfileStatusResponseData.ts | 30 +- project/src/models/eft/profile/IAkiProfile.ts | 300 +-- .../models/eft/profile/IConnectResponse.ts | 10 +- .../eft/profile/IGetProfileSettingsRequest.ts | 4 +- .../IProfileChangeNicknameRequestData.ts | 6 +- .../profile/IProfileChangeVoiceRequestData.ts | 6 +- .../eft/profile/IProfileCreateRequestData.ts | 12 +- .../eft/profile/ISearchFriendRequestData.ts | 4 +- .../eft/profile/ISearchFriendResponse.ts | 13 +- .../profile/IValidateNicknameRequestData.ts | 6 +- .../eft/quests/IAcceptQuestRequestData.ts | 10 +- .../eft/quests/ICompleteQuestRequestData.ts | 10 +- .../eft/quests/IFailQuestRequestData.ts | 10 +- .../eft/quests/IHandoverQuestRequestData.ts | 18 +- .../eft/quests/IListQuestsRequestData.ts | 6 +- .../quests/IRepeatableQuestChangeRequest.ts | 6 +- .../eft/ragfair/IAddOfferRequestData.ts | 24 +- .../eft/ragfair/IExtendOfferRequestData.ts | 8 +- .../models/eft/ragfair/IGetItemPriceResult.ts | 4 +- .../eft/ragfair/IGetMarketPriceRequestData.ts | 4 +- .../models/eft/ragfair/IGetOffersResult.ts | 12 +- .../src/models/eft/ragfair/IRagfairOffer.ts | 72 +- .../eft/ragfair/IRemoveOfferRequestData.ts | 8 +- .../models/eft/ragfair/ISearchRequestData.ts | 56 +- .../ragfair/ISendRagfairReportRequestData.ts | 4 +- .../IStorePlayerOfferTaxAmountRequestData.ts | 10 +- .../repair/IBaseRepairActionDataRequest.ts | 4 +- .../eft/repair/IRepairActionDataRequest.ts | 12 +- .../repair/ITraderRepairActionDataRequest.ts | 14 +- .../eft/trade/IProcessBaseTradeRequestData.ts | 10 +- .../eft/trade/IProcessBuyTradeRequestData.ts | 25 +- .../trade/IProcessRagfairTradeRequestData.ts | 22 +- .../eft/trade/IProcessSellTradeRequestData.ts | 22 +- .../trade/ISellScavItemsToFenceRequestData.ts | 8 +- .../src/models/eft/weather/IWeatherData.ts | 6 +- .../eft/wishlist/IWishlistActionData.ts | 7 +- project/src/models/enums/AccountTypes.ts | 6 +- project/src/models/enums/AirdropType.ts | 6 +- project/src/models/enums/AmmoTypes.ts | 104 +- project/src/models/enums/BackendErrorCodes.ts | 8 +- project/src/models/enums/BaseClasses.ts | 48 +- project/src/models/enums/BotAmount.ts | 6 +- project/src/models/enums/BotDifficulty.ts | 6 +- project/src/models/enums/ConfigTypes.ts | 6 +- project/src/models/enums/ContainerTypes.ts | 12 +- project/src/models/enums/ELocationName.ts | 8 +- .../src/models/enums/EquipmentBuildType.ts | 6 +- project/src/models/enums/EquipmentSlots.ts | 6 +- project/src/models/enums/ExitStatis.ts | 6 +- project/src/models/enums/GiftSenderType.ts | 6 +- project/src/models/enums/GiftSentResult.ts | 6 +- project/src/models/enums/HideoutAreas.ts | 8 +- .../src/models/enums/HideoutEventActions.ts | 6 +- project/src/models/enums/ItemAddedResult.ts | 6 +- project/src/models/enums/ItemEventActions.ts | 6 +- project/src/models/enums/MemberCategory.ts | 5 +- project/src/models/enums/MessageType.ts | 7 +- project/src/models/enums/Money.ts | 6 +- .../src/models/enums/PlayerRaidEndState.ts | 6 +- project/src/models/enums/QuestRewardType.ts | 6 +- project/src/models/enums/QuestStatus.ts | 6 +- project/src/models/enums/QuestTypeEnum.ts | 7 +- project/src/models/enums/RagfairSort.ts | 6 +- project/src/models/enums/RaidMode.ts | 6 +- project/src/models/enums/SeasonalEventType.ts | 6 +- project/src/models/enums/SkillTypes.ts | 6 +- project/src/models/enums/Traders.ts | 8 +- project/src/models/enums/WeaponSkillTypes.ts | 6 +- project/src/models/enums/WeaponTypes.ts | 86 +- project/src/models/enums/WeatherType.ts | 6 +- .../src/models/enums/WildSpawnTypeNumber.ts | 6 +- project/src/models/enums/WindDirection.ts | 6 +- project/src/models/external/HttpFramework.ts | 44 +- .../src/models/external/IPostAkiLoadMod.ts | 2 +- .../models/external/IPostAkiLoadModAsync.ts | 2 +- project/src/models/external/IPostDBLoadMod.ts | 2 +- .../models/external/IPostDBLoadModAsync.ts | 2 +- project/src/models/external/IPreAkiLoadMod.ts | 2 +- .../models/external/IPreAkiLoadModAsync.ts | 2 +- project/src/models/spt/bindings/Route.ts | 4 +- .../models/spt/bots/BotGenerationDetails.ts | 20 +- .../models/spt/bots/GenerateWeaponResult.ts | 2 +- project/src/models/spt/bots/IBotLootCache.ts | 25 +- .../models/spt/callbacks/IBundleCallbacks.ts | 6 +- .../spt/callbacks/ICustomizationCallbacks.ts | 2 +- .../models/spt/callbacks/IDataCallbacks.ts | 24 +- .../spt/callbacks/IDialogueCallbacks.ts | 24 +- .../models/spt/callbacks/IGameCallbacks.ts | 6 +- .../models/spt/callbacks/IHideoutCallbacks.ts | 44 +- .../spt/callbacks/IInventoryCallbacks.ts | 24 +- .../spt/callbacks/IItemEventCallbacks.ts | 6 +- .../spt/callbacks/INotifierCallbacks.ts | 8 +- .../spt/callbacks/IPresetBuildCallbacks.ts | 24 +- .../models/spt/callbacks/IProfileCallbacks.ts | 6 +- .../models/spt/callbacks/IQuestCallbacks.ts | 12 +- .../models/spt/callbacks/IRagfairCallbacks.ts | 8 +- .../models/spt/callbacks/ITradeCallbacks.ts | 6 +- .../models/spt/callbacks/ITraderCallbacks.ts | 15 +- .../src/models/spt/config/IAirdropConfig.ts | 55 +- project/src/models/spt/config/IBaseConfig.ts | 4 +- project/src/models/spt/config/IBotConfig.ts | 166 +- .../src/models/spt/config/IBotDurability.ts | 82 +- project/src/models/spt/config/ICoreConfig.ts | 4 +- project/src/models/spt/config/IGiftsConfig.ts | 26 +- .../src/models/spt/config/IHealthConfig.ts | 20 +- .../src/models/spt/config/IHideoutConfig.ts | 8 +- project/src/models/spt/config/IHttpConfig.ts | 14 +- .../src/models/spt/config/IInRaidConfig.ts | 40 +- .../src/models/spt/config/IInsuranceConfig.ts | 12 +- .../src/models/spt/config/IInventoryConfig.ts | 32 +- project/src/models/spt/config/IItemConfig.ts | 8 +- .../src/models/spt/config/ILocaleConfig.ts | 8 +- .../src/models/spt/config/ILocationConfig.ts | 92 +- project/src/models/spt/config/ILootConfig.ts | 6 +- .../models/spt/config/ILostOnDeathConfig.ts | 32 +- project/src/models/spt/config/IMatchConfig.ts | 6 +- .../models/spt/config/IPlayerScavConfig.ts | 30 +- .../src/models/spt/config/IPmChatResponse.ts | 14 +- project/src/models/spt/config/IPmcConfig.ts | 70 +- project/src/models/spt/config/IQuestConfig.ts | 208 +- .../src/models/spt/config/IRagfairConfig.ts | 148 +- .../src/models/spt/config/IRepairConfig.ts | 52 +- .../src/models/spt/config/IScavCaseConfig.ts | 46 +- .../models/spt/config/ISeasonalEventConfig.ts | 32 +- .../src/models/spt/config/ITraderConfig.ts | 64 +- .../src/models/spt/config/IWeatherConfig.ts | 32 +- .../models/spt/controllers/IBotController.ts | 2 +- .../models/spt/dialog/ISendMessageDetails.ts | 24 +- .../models/spt/generators/IBotGenerator.ts | 8 +- .../spt/generators/ILocationGenerator.ts | 21 +- .../spt/generators/IRagfairOfferGenerator.ts | 10 +- .../hideout/ScavCaseRewardCountsAndPrices.ts | 16 +- .../models/spt/logging/IClientLogRequest.ts | 14 +- .../models/spt/logging/LogBackgroundColor.ts | 6 +- project/src/models/spt/logging/LogLevel.ts | 8 +- .../src/models/spt/logging/LogTextColor.ts | 6 +- project/src/models/spt/logging/SptLogger.ts | 12 +- project/src/models/spt/mod/IModLoader.ts | 2 +- project/src/models/spt/mod/NewItemDetails.ts | 6 +- .../spt/ragfair/IRagfairServerPrices.ts | 8 +- .../models/spt/repeatable/IQuestTypePool.ts | 40 +- .../src/models/spt/server/IDatabaseTables.ts | 60 +- project/src/models/spt/server/ILocaleBase.ts | 12 +- project/src/models/spt/server/ILocations.ts | 42 +- project/src/models/spt/server/IServerBase.ts | 8 +- .../src/models/spt/server/ISettingsBase.ts | 84 +- .../src/models/spt/services/CustomPreset.ts | 6 +- .../spt/services/CustomTraderAssortData.ts | 6 +- project/src/models/spt/services/LootItem.ts | 2 +- .../src/models/spt/services/LootRequest.ts | 20 +- project/src/models/spt/utils/IAsyncQueue.ts | 6 +- project/src/models/spt/utils/ICommand.ts | 8 +- project/src/models/spt/utils/ILogger.ts | 10 +- 300 files changed, 5824 insertions(+), 5679 deletions(-) diff --git a/project/src/models/common/MinMax.ts b/project/src/models/common/MinMax.ts index 782821e8..2b5efbad 100644 --- a/project/src/models/common/MinMax.ts +++ b/project/src/models/common/MinMax.ts @@ -1,5 +1,5 @@ -export interface MinMax +export interface MinMax { - max: number - min: number -} \ No newline at end of file + max: number; + min: number; +} diff --git a/project/src/models/eft/bot/IGenerateBotsRequestData.ts b/project/src/models/eft/bot/IGenerateBotsRequestData.ts index 236d49e7..86097fcc 100644 --- a/project/src/models/eft/bot/IGenerateBotsRequestData.ts +++ b/project/src/models/eft/bot/IGenerateBotsRequestData.ts @@ -1,12 +1,12 @@ -export interface IGenerateBotsRequestData +export interface IGenerateBotsRequestData { - conditions: Condition[] + conditions: Condition[]; } -export interface Condition +export interface Condition { /** e.g. assault/pmcBot/bossKilla */ - Role: string - Limit: number - Difficulty: string -} \ No newline at end of file + Role: string; + Limit: number; + Difficulty: string; +} diff --git a/project/src/models/eft/bot/IRandomisedBotLevelResult.ts b/project/src/models/eft/bot/IRandomisedBotLevelResult.ts index 5b60979c..b0571202 100644 --- a/project/src/models/eft/bot/IRandomisedBotLevelResult.ts +++ b/project/src/models/eft/bot/IRandomisedBotLevelResult.ts @@ -1,5 +1,5 @@ export interface IRandomisedBotLevelResult { - level: number, - exp: number -} \ No newline at end of file + level: number; + exp: number; +} diff --git a/project/src/models/eft/common/IEmptyRequestData.ts b/project/src/models/eft/common/IEmptyRequestData.ts index 498b1ede..0cd4f101 100644 --- a/project/src/models/eft/common/IEmptyRequestData.ts +++ b/project/src/models/eft/common/IEmptyRequestData.ts @@ -1,4 +1,3 @@ export interface IEmptyRequestData { - -} \ No newline at end of file +} diff --git a/project/src/models/eft/common/IGlobals.ts b/project/src/models/eft/common/IGlobals.ts index 608f1501..c60a61aa 100644 --- a/project/src/models/eft/common/IGlobals.ts +++ b/project/src/models/eft/common/IGlobals.ts @@ -2,1683 +2,1679 @@ import { Ixyz } from "@spt-aki/models/eft/common/Ixyz"; import { Item } from "@spt-aki/models/eft/common/tables/IItem"; -export interface IGlobals +export interface IGlobals { - time: number - config: IConfig - bot_presets: IBotPreset[] - AudioSettings: IAudioSettings - BotWeaponScatterings: IBotWeaponScattering[] - ItemPresets: Record + time: number; + config: IConfig; + bot_presets: IBotPreset[]; + AudioSettings: IAudioSettings; + BotWeaponScatterings: IBotWeaponScattering[]; + ItemPresets: Record; } -export interface IConfig +export interface IConfig { - content: IContent - AimPunchMagnitude: number - WeaponSkillProgressRate: number - SkillAtrophy: boolean - exp: IExp - t_base_looting: number - t_base_lockpicking: number - armor: IArmor - SessionsToShowHotKeys: number - MaxBotsAliveOnMap: number - SavagePlayCooldown: number - SavagePlayCooldownNdaFree: number - MarksmanAccuracy: number - SavagePlayCooldownDevelop: number - TODSkyDate: string - Mastering: IMastering[] - GlobalItemPriceModifier: number - TradingUnlimitedItems: boolean - MaxLoyaltyLevelForAll: boolean - GlobalLootChanceModifier: number - GraphicSettings: IGraphicSettings - TimeBeforeDeploy: number - TimeBeforeDeployLocal: number - TradingSetting: number, - TradingSettings: ITradingSettings, - ItemsCommonSettings: IItemsCommonSettings - LoadTimeSpeedProgress: number - BaseLoadTime: number - BaseUnloadTime: number - BaseCheckTime: number - Customization: ICustomization - UncheckOnShot: boolean - BotsEnabled: boolean - BufferZone: IBufferZone - ArmorMaterials: IArmorMaterials - LegsOverdamage: number - HandsOverdamage: number - StomachOverdamage: number - Health: IHealth - rating: IRating - tournament: ITournament - RagFair: IRagFair - handbook: IHandbook - FractureCausedByFalling: IProbability - FractureCausedByBulletHit: IProbability - WAVE_COEF_LOW: number - WAVE_COEF_MID: number - WAVE_COEF_HIGH: number - WAVE_COEF_HORDE: number - Stamina: IStamina - StaminaRestoration: IStaminaRestoration - StaminaDrain: IStaminaDrain - RequirementReferences: IRequirementReferences - RestrictionsInRaid: IRestrictionsInRaid[] - SkillMinEffectiveness: number - SkillFatiguePerPoint: number - SkillFreshEffectiveness: number - SkillFreshPoints: number - SkillPointsBeforeFatigue: number - SkillFatigueReset: number - DiscardLimitsEnabled: boolean - EventSettings: IEventSettings - EventType: string[] - WalkSpeed: Ixyz - SprintSpeed: Ixyz - SquadSettings: ISquadSettings - SkillEnduranceWeightThreshold: number - TeamSearchingTimeout: number - Insurance: IInsurance - SkillExpPerLevel: number - GameSearchingTimeout: number - WallContusionAbsorption: Ixyz - WeaponFastDrawSettings: IWeaponFastDrawSettings - SkillsSettings: ISkillsSettings - AzimuthPanelShowsPlayerOrientation: boolean - Aiming: IAiming - Malfunction: IMalfunction - Overheat: IOverheat - FenceSettings: IFenceSettings - TestValue: number - Inertia: IInertia - Ballistic: IBallistic - RepairSettings: IRepairSettings + content: IContent; + AimPunchMagnitude: number; + WeaponSkillProgressRate: number; + SkillAtrophy: boolean; + exp: IExp; + t_base_looting: number; + t_base_lockpicking: number; + armor: IArmor; + SessionsToShowHotKeys: number; + MaxBotsAliveOnMap: number; + SavagePlayCooldown: number; + SavagePlayCooldownNdaFree: number; + MarksmanAccuracy: number; + SavagePlayCooldownDevelop: number; + TODSkyDate: string; + Mastering: IMastering[]; + GlobalItemPriceModifier: number; + TradingUnlimitedItems: boolean; + MaxLoyaltyLevelForAll: boolean; + GlobalLootChanceModifier: number; + GraphicSettings: IGraphicSettings; + TimeBeforeDeploy: number; + TimeBeforeDeployLocal: number; + TradingSetting: number; + TradingSettings: ITradingSettings; + ItemsCommonSettings: IItemsCommonSettings; + LoadTimeSpeedProgress: number; + BaseLoadTime: number; + BaseUnloadTime: number; + BaseCheckTime: number; + Customization: ICustomization; + UncheckOnShot: boolean; + BotsEnabled: boolean; + BufferZone: IBufferZone; + ArmorMaterials: IArmorMaterials; + LegsOverdamage: number; + HandsOverdamage: number; + StomachOverdamage: number; + Health: IHealth; + rating: IRating; + tournament: ITournament; + RagFair: IRagFair; + handbook: IHandbook; + FractureCausedByFalling: IProbability; + FractureCausedByBulletHit: IProbability; + WAVE_COEF_LOW: number; + WAVE_COEF_MID: number; + WAVE_COEF_HIGH: number; + WAVE_COEF_HORDE: number; + Stamina: IStamina; + StaminaRestoration: IStaminaRestoration; + StaminaDrain: IStaminaDrain; + RequirementReferences: IRequirementReferences; + RestrictionsInRaid: IRestrictionsInRaid[]; + SkillMinEffectiveness: number; + SkillFatiguePerPoint: number; + SkillFreshEffectiveness: number; + SkillFreshPoints: number; + SkillPointsBeforeFatigue: number; + SkillFatigueReset: number; + DiscardLimitsEnabled: boolean; + EventSettings: IEventSettings; + EventType: string[]; + WalkSpeed: Ixyz; + SprintSpeed: Ixyz; + SquadSettings: ISquadSettings; + SkillEnduranceWeightThreshold: number; + TeamSearchingTimeout: number; + Insurance: IInsurance; + SkillExpPerLevel: number; + GameSearchingTimeout: number; + WallContusionAbsorption: Ixyz; + WeaponFastDrawSettings: IWeaponFastDrawSettings; + SkillsSettings: ISkillsSettings; + AzimuthPanelShowsPlayerOrientation: boolean; + Aiming: IAiming; + Malfunction: IMalfunction; + Overheat: IOverheat; + FenceSettings: IFenceSettings; + TestValue: number; + Inertia: IInertia; + Ballistic: IBallistic; + RepairSettings: IRepairSettings; } export interface IWeaponFastDrawSettings { - HandShakeCurveFrequency: number - HandShakeCurveIntensity: number - HandShakeMaxDuration: number - HandShakeTremorIntensity: number - WeaponFastSwitchMaxSpeedMult: number - WeaponFastSwitchMinSpeedMult: number - WeaponPistolFastSwitchMaxSpeedMult: number - WeaponPistolFastSwitchMinSpeedMult: number + HandShakeCurveFrequency: number; + HandShakeCurveIntensity: number; + HandShakeMaxDuration: number; + HandShakeTremorIntensity: number; + WeaponFastSwitchMaxSpeedMult: number; + WeaponFastSwitchMinSpeedMult: number; + WeaponPistolFastSwitchMaxSpeedMult: number; + WeaponPistolFastSwitchMinSpeedMult: number; } export interface IEventSettings { - EventActive: boolean - EventTime: number - EventWeather: IEventWeather - ExitTimeMultiplier: number - StaminaMultiplier: number - SummonFailedWeather: IEventWeather - SummonSuccessWeather: IEventWeather - WeatherChangeTime: number + EventActive: boolean; + EventTime: number; + EventWeather: IEventWeather; + ExitTimeMultiplier: number; + StaminaMultiplier: number; + SummonFailedWeather: IEventWeather; + SummonSuccessWeather: IEventWeather; + WeatherChangeTime: number; } export interface IEventWeather { - Cloudness: number - Hour: number - Minute: number - Rain: number - RainRandomness: number - ScaterringFogDensity: number - TopWindDirection: Ixyz - Wind: number - WindDirection: number + Cloudness: number; + Hour: number; + Minute: number; + Rain: number; + RainRandomness: number; + ScaterringFogDensity: number; + TopWindDirection: Ixyz; + Wind: number; + WindDirection: number; } export interface IGraphicSettings { - ExperimentalFogInCity: boolean + ExperimentalFogInCity: boolean; } export interface IBufferZone { - CustomerAccessTime: number - CustomerCriticalTimeStart: number - CustomerKickNotifTime: number + CustomerAccessTime: number; + CustomerCriticalTimeStart: number; + CustomerKickNotifTime: number; } export interface IItemsCommonSettings { - ItemRemoveAfterInterruptionTime: number + ItemRemoveAfterInterruptionTime: number; } export interface ITradingSettings { - BuyoutRestrictions: IBuyoutRestrictions + BuyoutRestrictions: IBuyoutRestrictions; } export interface IBuyoutRestrictions { - MinDurability: number - MinFoodDrinkResource: number - MinMedsResource: number + MinDurability: number; + MinFoodDrinkResource: number; + MinMedsResource: number; } -export interface IContent +export interface IContent { - ip: string - port: number - root: string + ip: string; + port: number; + root: string; } -export interface IExp +export interface IExp { - heal: IHeal - match_end: IMatchEnd - kill: IKill - level: ILevel - loot_attempts: ILootAttempt[] - expForLockedDoorOpen: number - expForLockedDoorBreach: number - triggerMult: number + heal: IHeal; + match_end: IMatchEnd; + kill: IKill; + level: ILevel; + loot_attempts: ILootAttempt[]; + expForLockedDoorOpen: number; + expForLockedDoorBreach: number; + triggerMult: number; } -export interface IHeal +export interface IHeal { - expForHeal: number - expForHydration: number - expForEnergy: number + expForHeal: number; + expForHydration: number; + expForEnergy: number; } -export interface IMatchEnd +export interface IMatchEnd { - README: string - survived_exp_requirement: number - survived_seconds_requirement: number - survived_exp_reward: number - mia_exp_reward: number - runner_exp_reward: number - leftMult: number - miaMult: number - survivedMult: number - runnerMult: number - killedMult: number + README: string; + survived_exp_requirement: number; + survived_seconds_requirement: number; + survived_exp_reward: number; + mia_exp_reward: number; + runner_exp_reward: number; + leftMult: number; + miaMult: number; + survivedMult: number; + runnerMult: number; + killedMult: number; } -export interface IKill +export interface IKill { - combo: ICombo[] - victimLevelExp: number - headShotMult: number - expOnDamageAllHealth: number - longShotDistance: number - bloodLossToLitre: number - botExpOnDamageAllHealth: number - botHeadShotMult: number - victimBotLevelExp: number - pmcExpOnDamageAllHealth: number - pmcHeadShotMult: number + combo: ICombo[]; + victimLevelExp: number; + headShotMult: number; + expOnDamageAllHealth: number; + longShotDistance: number; + bloodLossToLitre: number; + botExpOnDamageAllHealth: number; + botHeadShotMult: number; + victimBotLevelExp: number; + pmcExpOnDamageAllHealth: number; + pmcHeadShotMult: number; } -export interface ICombo +export interface ICombo { - percent: number + percent: number; } -export interface ILevel +export interface ILevel { - exp_table: IExpTable[] - trade_level: number - savage_level: number - clan_level: number - mastering1: number - mastering2: number + exp_table: IExpTable[]; + trade_level: number; + savage_level: number; + clan_level: number; + mastering1: number; + mastering2: number; } -export interface IExpTable +export interface IExpTable { - exp: number + exp: number; } -export interface ILootAttempt +export interface ILootAttempt { - k_exp: number + k_exp: number; } -export interface IArmor +export interface IArmor { - class: IClass[] + class: IClass[]; } -export interface IClass +export interface IClass { - resistance: number + resistance: number; } -export interface IMastering +export interface IMastering { - Name: string - Templates: string[] - Level2: number - Level3: number + Name: string; + Templates: string[]; + Level2: number; + Level3: number; } -export interface ICustomization +export interface ICustomization { - SavageHead: ISavageHead - SavageBody: ISavageBody - SavageFeet: ISavageFeet - CustomizationVoice: ICustomizationVoice[] - BodyParts: IBodyParts + SavageHead: ISavageHead; + SavageBody: ISavageBody; + SavageFeet: ISavageFeet; + CustomizationVoice: ICustomizationVoice[]; + BodyParts: IBodyParts; } -export interface ISavageHead +export interface ISavageHead { - wild_head_1: IWildHead - wild_head_2: IWildHead - wild_head_3: IWildHead - Wild_Dealmaker_head: IWildHead - Wild_Killa_head: IWildHead - bear_head: IWildHead - bear_head_1: IWildHead - usec_head_1: IWildHead - Head_BOSS_Glukhar: IWildHead - Wild_Head_nonMesh: IWildHead - Head_BOSS_Sanitar: IWildHead - wild_head_drozd: IWildHead - wild_head_misha: IWildHead - head_cultist_01: IWildHead - head_cultist_02: IWildHead - head_cultist_03: IWildHead - DefaultUsecHead: IWildHead - usec_head_3: IWildHead - usec_head_4: IWildHead - usec_head_5: IWildHead + wild_head_1: IWildHead; + wild_head_2: IWildHead; + wild_head_3: IWildHead; + Wild_Dealmaker_head: IWildHead; + Wild_Killa_head: IWildHead; + bear_head: IWildHead; + bear_head_1: IWildHead; + usec_head_1: IWildHead; + Head_BOSS_Glukhar: IWildHead; + Wild_Head_nonMesh: IWildHead; + Head_BOSS_Sanitar: IWildHead; + wild_head_drozd: IWildHead; + wild_head_misha: IWildHead; + head_cultist_01: IWildHead; + head_cultist_02: IWildHead; + head_cultist_03: IWildHead; + DefaultUsecHead: IWildHead; + usec_head_3: IWildHead; + usec_head_4: IWildHead; + usec_head_5: IWildHead; } -export interface IWildHead +export interface IWildHead { - head: string - isNotRandom: boolean - NotRandom: boolean + head: string; + isNotRandom: boolean; + NotRandom: boolean; } -export interface ISavageBody +export interface ISavageBody { - wild_body: IWildBody - wild_body_1: IWildBody - wild_body_2: IWildBody - wild_body_3: IWildBody - Wild_Dealmaker_body: IWildBody - wild_security_body_1: IWildBody - wild_security_body_2: IWildBody - wild_Killa_body: IWildBody - wild_pmcBot_body: IWildBody - wild_Shturman_body: IWildBody - wild_Gluhar_body: IWildBody - Tshirt_security_TshirtTatu_01: IWildBody - Tshirt_security_TshirtTatu_02: IWildBody - Top_security_Husky: IWildBody - Top_security_Gorka4: IWildBody - scav_kit_upper_meteor: IWildBody - wild_body_russia1: IWildBody - Top_BOSS_Sanitar: IWildBody - wild_body_motocross: IWildBody - top_cultist_01: IWildBody - top_cultist_02: IWildBody - wild_body_rainparka: IWildBody - wild_body_underarmour: IWildBody - top_boss_tagilla: IWildBody - DefaultUsecBody: IWildBody - usec_upper_acu: IWildBody - usec_upper_commando: IWildBody - usec_upper_aggressor: IWildBody - usec_upper_hoody: IWildBody - usec_upper_pcuironsight: IWildBody - usec_top_beltstaff: IWildBody - usec_upper_flexion: IWildBody - usec_upper_tier3: IWildBody - usec_upper_pcsmulticam: IWildBody - usec_upper_tier_2: IWildBody - usec_upper_infiltrator: IWildBody - user_upper_NightPatrol: IWildBody - wild_body_bomber: IWildBody - wild_top_yellowcoat: IWildBody + wild_body: IWildBody; + wild_body_1: IWildBody; + wild_body_2: IWildBody; + wild_body_3: IWildBody; + Wild_Dealmaker_body: IWildBody; + wild_security_body_1: IWildBody; + wild_security_body_2: IWildBody; + wild_Killa_body: IWildBody; + wild_pmcBot_body: IWildBody; + wild_Shturman_body: IWildBody; + wild_Gluhar_body: IWildBody; + Tshirt_security_TshirtTatu_01: IWildBody; + Tshirt_security_TshirtTatu_02: IWildBody; + Top_security_Husky: IWildBody; + Top_security_Gorka4: IWildBody; + scav_kit_upper_meteor: IWildBody; + wild_body_russia1: IWildBody; + Top_BOSS_Sanitar: IWildBody; + wild_body_motocross: IWildBody; + top_cultist_01: IWildBody; + top_cultist_02: IWildBody; + wild_body_rainparka: IWildBody; + wild_body_underarmour: IWildBody; + top_boss_tagilla: IWildBody; + DefaultUsecBody: IWildBody; + usec_upper_acu: IWildBody; + usec_upper_commando: IWildBody; + usec_upper_aggressor: IWildBody; + usec_upper_hoody: IWildBody; + usec_upper_pcuironsight: IWildBody; + usec_top_beltstaff: IWildBody; + usec_upper_flexion: IWildBody; + usec_upper_tier3: IWildBody; + usec_upper_pcsmulticam: IWildBody; + usec_upper_tier_2: IWildBody; + usec_upper_infiltrator: IWildBody; + user_upper_NightPatrol: IWildBody; + wild_body_bomber: IWildBody; + wild_top_yellowcoat: IWildBody; } -export interface IWildBody +export interface IWildBody { - body: string - hands: string - isNotRandom: boolean + body: string; + hands: string; + isNotRandom: boolean; } -export interface ISavageFeet +export interface ISavageFeet { - wild_feet: IWildFeet - wild_feet_1: IWildFeet - wild_feet_2: IWildFeet - Wild_Dealmaker_feet: IWildFeet - wild_security_feet_1: IWildFeet - Wild_Killa_feet: IWildFeet - wild_pmcBot_feet: IWildFeet - Pants_BOSS_Glukhar: IWildFeet - Pants_BOSS_Shturman: IWildFeet - Pants_security_Gorka4: IWildFeet - Pants_security_Flora: IWildFeet - scav_kit_lower_sklon: IWildFeet - Pants_BOSS_Sanitar: IWildFeet - wild_feet_sweatpants: IWildFeet - wild_feet_wasatch: IWildFeet - wild_feet_slimPants: IWildFeet - pants_cultist_01: IWildFeet - pants_cultist_02: IWildFeet - wild_feet_scavelite_taclite: IWildFeet - pants_boss_tagilla: IWildFeet - wild_feet_bomber: IWildFeet - wild_pants_yellowcoat: IWildFeet + wild_feet: IWildFeet; + wild_feet_1: IWildFeet; + wild_feet_2: IWildFeet; + Wild_Dealmaker_feet: IWildFeet; + wild_security_feet_1: IWildFeet; + Wild_Killa_feet: IWildFeet; + wild_pmcBot_feet: IWildFeet; + Pants_BOSS_Glukhar: IWildFeet; + Pants_BOSS_Shturman: IWildFeet; + Pants_security_Gorka4: IWildFeet; + Pants_security_Flora: IWildFeet; + scav_kit_lower_sklon: IWildFeet; + Pants_BOSS_Sanitar: IWildFeet; + wild_feet_sweatpants: IWildFeet; + wild_feet_wasatch: IWildFeet; + wild_feet_slimPants: IWildFeet; + pants_cultist_01: IWildFeet; + pants_cultist_02: IWildFeet; + wild_feet_scavelite_taclite: IWildFeet; + pants_boss_tagilla: IWildFeet; + wild_feet_bomber: IWildFeet; + wild_pants_yellowcoat: IWildFeet; } -export interface IWildFeet +export interface IWildFeet { - feet: string - isNotRandom: boolean - NotRandom: boolean + feet: string; + isNotRandom: boolean; + NotRandom: boolean; } -export interface ICustomizationVoice +export interface ICustomizationVoice { - voice: string - side: string[] - isNotRandom: boolean + voice: string; + side: string[]; + isNotRandom: boolean; } -export interface IBodyParts +export interface IBodyParts { - Head: string - Body: string - Feet: string - Hands: string + Head: string; + Body: string; + Feet: string; + Hands: string; } -export interface IArmorMaterials +export interface IArmorMaterials { - UHMWPE: IArmorType - Aramid: IArmorType - Combined: IArmorType - Titan: IArmorType - Aluminium: IArmorType - ArmoredSteel: IArmorType - Ceramic: IArmorType - Glass: IArmorType + UHMWPE: IArmorType; + Aramid: IArmorType; + Combined: IArmorType; + Titan: IArmorType; + Aluminium: IArmorType; + ArmoredSteel: IArmorType; + Ceramic: IArmorType; + Glass: IArmorType; } -export interface IArmorType +export interface IArmorType { - Destructibility: number - MinRepairDegradation: number - MaxRepairDegradation: number - ExplosionDestructibility: number - MinRepairKitDegradation: number - MaxRepairKitDegradation: number + Destructibility: number; + MinRepairDegradation: number; + MaxRepairDegradation: number; + ExplosionDestructibility: number; + MinRepairKitDegradation: number; + MaxRepairKitDegradation: number; } -export interface IHealth +export interface IHealth { - Falling: IFalling - Effects: IEffects - HealPrice: IHealPrice - ProfileHealthSettings: IProfileHealthSettings + Falling: IFalling; + Effects: IEffects; + HealPrice: IHealPrice; + ProfileHealthSettings: IProfileHealthSettings; } -export interface IFalling +export interface IFalling { - DamagePerMeter: number - SafeHeight: number + DamagePerMeter: number; + SafeHeight: number; } -export interface IEffects +export interface IEffects { - Existence: IExistence - Dehydration: IDehydration - BreakPart: IBreakPart - Contusion: IContusion - Disorientation: IDisorientation - Exhaustion: IExhaustion - LowEdgeHealth: ILowEdgeHealth - RadExposure: IRadExposure - Stun: IStun - Intoxication: Intoxication - Regeneration: IRegeneration - Wound: IWound - Berserk: IBerserk - Flash: IFlash - MedEffect: IMedEffect - Pain: IPain - PainKiller: IPainKiller - SandingScreen: ISandingScreen - MildMusclePain: IMusclePainEffect - SevereMusclePain: IMusclePainEffect - Stimulator: IStimulator - Tremor: ITremor - ChronicStaminaFatigue: IChronicStaminaFatigue - Fracture: IFracture - HeavyBleeding: IHeavyBleeding - LightBleeding: ILightBleeding - BodyTemperature: IBodyTemperature + Existence: IExistence; + Dehydration: IDehydration; + BreakPart: IBreakPart; + Contusion: IContusion; + Disorientation: IDisorientation; + Exhaustion: IExhaustion; + LowEdgeHealth: ILowEdgeHealth; + RadExposure: IRadExposure; + Stun: IStun; + Intoxication: Intoxication; + Regeneration: IRegeneration; + Wound: IWound; + Berserk: IBerserk; + Flash: IFlash; + MedEffect: IMedEffect; + Pain: IPain; + PainKiller: IPainKiller; + SandingScreen: ISandingScreen; + MildMusclePain: IMusclePainEffect; + SevereMusclePain: IMusclePainEffect; + Stimulator: IStimulator; + Tremor: ITremor; + ChronicStaminaFatigue: IChronicStaminaFatigue; + Fracture: IFracture; + HeavyBleeding: IHeavyBleeding; + LightBleeding: ILightBleeding; + BodyTemperature: IBodyTemperature; } -export interface IExistence +export interface IExistence { - EnergyLoopTime: number - HydrationLoopTime: number - EnergyDamage: number - HydrationDamage: number - DestroyedStomachEnergyTimeFactor: number - DestroyedStomachHydrationTimeFactor: number + EnergyLoopTime: number; + HydrationLoopTime: number; + EnergyDamage: number; + HydrationDamage: number; + DestroyedStomachEnergyTimeFactor: number; + DestroyedStomachHydrationTimeFactor: number; } -export interface IDehydration +export interface IDehydration { - DefaultDelay: number - DefaultResidueTime: number - BleedingHealth: number - BleedingLoopTime: number - BleedingLifeTime: number - DamageOnStrongDehydration: number - StrongDehydrationLoopTime: number + DefaultDelay: number; + DefaultResidueTime: number; + BleedingHealth: number; + BleedingLoopTime: number; + BleedingLifeTime: number; + DamageOnStrongDehydration: number; + StrongDehydrationLoopTime: number; } -export interface IBreakPart +export interface IBreakPart { - DefaultDelay: number - DefaultResidueTime: number - HealExperience: number - OfflineDurationMin: number - OfflineDurationMax: number - RemovePrice: number - RemovedAfterDeath: boolean - BulletHitProbability: IProbability - FallingProbability: IProbability + DefaultDelay: number; + DefaultResidueTime: number; + HealExperience: number; + OfflineDurationMin: number; + OfflineDurationMax: number; + RemovePrice: number; + RemovedAfterDeath: boolean; + BulletHitProbability: IProbability; + FallingProbability: IProbability; } -export interface IContusion +export interface IContusion { - Dummy: number + Dummy: number; } -export interface IDisorientation +export interface IDisorientation { - Dummy: number + Dummy: number; } -export interface IExhaustion +export interface IExhaustion { - DefaultDelay: number - DefaultResidueTime: number - Damage: number - DamageLoopTime: number + DefaultDelay: number; + DefaultResidueTime: number; + Damage: number; + DamageLoopTime: number; } -export interface ILowEdgeHealth +export interface ILowEdgeHealth { - DefaultDelay: number - DefaultResidueTime: number - StartCommonHealth: number + DefaultDelay: number; + DefaultResidueTime: number; + StartCommonHealth: number; } -export interface IRadExposure +export interface IRadExposure { - Damage: number - DamageLoopTime: number + Damage: number; + DamageLoopTime: number; } -export interface IStun +export interface IStun { - Dummy: number + Dummy: number; } -export interface Intoxication +export interface Intoxication { - DefaultDelay: number - DefaultResidueTime: number - DamageHealth: number - HealthLoopTime: number - OfflineDurationMin: number - OfflineDurationMax: number - RemovedAfterDeath: boolean - HealExperience: number - RemovePrice: number + DefaultDelay: number; + DefaultResidueTime: number; + DamageHealth: number; + HealthLoopTime: number; + OfflineDurationMin: number; + OfflineDurationMax: number; + RemovedAfterDeath: boolean; + HealExperience: number; + RemovePrice: number; } -export interface IRegeneration +export interface IRegeneration { - LoopTime: number - MinimumHealthPercentage: number - Energy: number - Hydration: number - BodyHealth: IBodyHealth - Influences: IInfluences + LoopTime: number; + MinimumHealthPercentage: number; + Energy: number; + Hydration: number; + BodyHealth: IBodyHealth; + Influences: IInfluences; } -export interface IBodyHealth +export interface IBodyHealth { - Head: IBodyHealthValue - Chest: IBodyHealthValue - Stomach: IBodyHealthValue - LeftArm: IBodyHealthValue - RightArm: IBodyHealthValue - LeftLeg: IBodyHealthValue - RightLeg: IBodyHealthValue + Head: IBodyHealthValue; + Chest: IBodyHealthValue; + Stomach: IBodyHealthValue; + LeftArm: IBodyHealthValue; + RightArm: IBodyHealthValue; + LeftLeg: IBodyHealthValue; + RightLeg: IBodyHealthValue; } -export interface IBodyHealthValue +export interface IBodyHealthValue { - Value: number + Value: number; } -export interface IInfluences +export interface IInfluences { - LightBleeding: IInfluence - HeavyBleeding: IInfluence - Fracture: IInfluence - RadExposure: IInfluence - Intoxication: IInfluence + LightBleeding: IInfluence; + HeavyBleeding: IInfluence; + Fracture: IInfluence; + RadExposure: IInfluence; + Intoxication: IInfluence; } -export interface IInfluence +export interface IInfluence { - HealthSlowDownPercentage: number - EnergySlowDownPercentage: number - HydrationSlowDownPercentage: number + HealthSlowDownPercentage: number; + EnergySlowDownPercentage: number; + HydrationSlowDownPercentage: number; } -export interface IWound +export interface IWound { - WorkingTime: number - ThresholdMin: number - ThresholdMax: number + WorkingTime: number; + ThresholdMin: number; + ThresholdMax: number; } -export interface IBerserk +export interface IBerserk { - DefaultDelay: number - WorkingTime: number - DefaultResidueTime: number + DefaultDelay: number; + WorkingTime: number; + DefaultResidueTime: number; } -export interface IFlash +export interface IFlash { - Dummy: number + Dummy: number; } -export interface IMedEffect +export interface IMedEffect { - LoopTime: number - StartDelay: number - DrinkStartDelay: number - FoodStartDelay: number - DrugsStartDelay: number - MedKitStartDelay: number - MedicalStartDelay: number - StimulatorStartDelay: number + LoopTime: number; + StartDelay: number; + DrinkStartDelay: number; + FoodStartDelay: number; + DrugsStartDelay: number; + MedKitStartDelay: number; + MedicalStartDelay: number; + StimulatorStartDelay: number; } -export interface IPain +export interface IPain { - TremorDelay: number - HealExperience: number + TremorDelay: number; + HealExperience: number; } -export interface IPainKiller +export interface IPainKiller { - Dummy: number + Dummy: number; } -export interface ISandingScreen +export interface ISandingScreen { - Dummy: number + Dummy: number; } export interface IMusclePainEffect { - GymEffectivity: number - OfflineDurationMax: number - OfflineDurationMin: number - TraumaChance: number + GymEffectivity: number; + OfflineDurationMax: number; + OfflineDurationMin: number; + TraumaChance: number; } -export interface IStimulator +export interface IStimulator { - BuffLoopTime: number - Buffs: IBuffs + BuffLoopTime: number; + Buffs: IBuffs; } -export interface IBuffs +export interface IBuffs { - BuffsSJ1TGLabs: IBuff[] - BuffsSJ6TGLabs: IBuff[] - BuffsPropital: IBuff[] - BuffsZagustin: IBuff[] - BuffseTGchange: IBuff[] - BuffsAdrenaline: IBuff[] - BuffsGoldenStarBalm: IBuff[] - Buffs_drink_aquamari: IBuff[] - Buffs_drink_maxenergy: IBuff[] - Buffs_drink_milk: IBuff[] - Buffs_drink_tarcola: IBuff[] - Buffs_drink_hotrod: IBuff[] - Buffs_drink_juice_army: IBuff[] - Buffs_drink_water: IBuff[] - Buffs_food_borodinskiye: IBuff[] - Buffs_food_condensed_milk: IBuff[] - Buffs_food_emelya: IBuff[] - Buffs_food_mayonez: IBuff[] - Buffs_food_mre: IBuff[] - Buffs_food_sugar: IBuff[] - Buffs_drink_vodka: IBuff[] - Buffs_drink_jack: IBuff[] - Buffs_drink_moonshine: IBuff[] - Buffs_drink_purewater: IBuff[] - Buffs_3bTG: IBuff[] - Buffs_AHF1M: IBuff[] - Buffs_L1: IBuff[] - Buffs_MULE: IBuff[] - Buffs_Meldonin: IBuff[] - Buffs_Obdolbos: IBuff[] - Buffs_P22: IBuff[] - Buffs_KultistsToxin: IBuff[] - Buffs_BodyTemperature: IBuff[] - Buffs_Antidote: IBuff[] - Buffs_melee_bleed: IBuff[] - Buffs_melee_blunt: IBuff[] - Buffs_hultafors: IBuff[] - Buffs_drink_vodka_BAD: IBuff[] - Buffs_food_alyonka: IBuff[] - Buffs_food_slippers: IBuff[] - Buffs_knife: IBuff[] + BuffsSJ1TGLabs: IBuff[]; + BuffsSJ6TGLabs: IBuff[]; + BuffsPropital: IBuff[]; + BuffsZagustin: IBuff[]; + BuffseTGchange: IBuff[]; + BuffsAdrenaline: IBuff[]; + BuffsGoldenStarBalm: IBuff[]; + Buffs_drink_aquamari: IBuff[]; + Buffs_drink_maxenergy: IBuff[]; + Buffs_drink_milk: IBuff[]; + Buffs_drink_tarcola: IBuff[]; + Buffs_drink_hotrod: IBuff[]; + Buffs_drink_juice_army: IBuff[]; + Buffs_drink_water: IBuff[]; + Buffs_food_borodinskiye: IBuff[]; + Buffs_food_condensed_milk: IBuff[]; + Buffs_food_emelya: IBuff[]; + Buffs_food_mayonez: IBuff[]; + Buffs_food_mre: IBuff[]; + Buffs_food_sugar: IBuff[]; + Buffs_drink_vodka: IBuff[]; + Buffs_drink_jack: IBuff[]; + Buffs_drink_moonshine: IBuff[]; + Buffs_drink_purewater: IBuff[]; + Buffs_3bTG: IBuff[]; + Buffs_AHF1M: IBuff[]; + Buffs_L1: IBuff[]; + Buffs_MULE: IBuff[]; + Buffs_Meldonin: IBuff[]; + Buffs_Obdolbos: IBuff[]; + Buffs_P22: IBuff[]; + Buffs_KultistsToxin: IBuff[]; + Buffs_BodyTemperature: IBuff[]; + Buffs_Antidote: IBuff[]; + Buffs_melee_bleed: IBuff[]; + Buffs_melee_blunt: IBuff[]; + Buffs_hultafors: IBuff[]; + Buffs_drink_vodka_BAD: IBuff[]; + Buffs_food_alyonka: IBuff[]; + Buffs_food_slippers: IBuff[]; + Buffs_knife: IBuff[]; } -export interface IBuff +export interface IBuff { - BuffType: string - Chance: number - Delay: number - Duration: number - Value: number - AbsoluteValue: boolean - SkillName: string + BuffType: string; + Chance: number; + Delay: number; + Duration: number; + Value: number; + AbsoluteValue: boolean; + SkillName: string; } -export interface ITremor +export interface ITremor { - DefaultDelay: number - DefaultResidueTime: number + DefaultDelay: number; + DefaultResidueTime: number; } -export interface IChronicStaminaFatigue +export interface IChronicStaminaFatigue { - EnergyRate: number - WorkingTime: number - TicksEvery: number - EnergyRatePerStack: number + EnergyRate: number; + WorkingTime: number; + TicksEvery: number; + EnergyRatePerStack: number; } -export interface IFracture +export interface IFracture { - DefaultDelay: number - DefaultResidueTime: number - HealExperience: number - OfflineDurationMin: number - OfflineDurationMax: number - RemovePrice: number - RemovedAfterDeath: boolean - BulletHitProbability: IProbability - FallingProbability: IProbability + DefaultDelay: number; + DefaultResidueTime: number; + HealExperience: number; + OfflineDurationMin: number; + OfflineDurationMax: number; + RemovePrice: number; + RemovedAfterDeath: boolean; + BulletHitProbability: IProbability; + FallingProbability: IProbability; } -export interface IHeavyBleeding +export interface IHeavyBleeding { - DefaultDelay: number - DefaultResidueTime: number - DamageEnergy: number - DamageHealth: number - EnergyLoopTime: number - HealthLoopTime: number - DamageHealthDehydrated: number - HealthLoopTimeDehydrated: number - LifeTimeDehydrated: number - EliteVitalityDuration: number - HealExperience: number - OfflineDurationMin: number - OfflineDurationMax: number - RemovePrice: number - RemovedAfterDeath: boolean - Probability: IProbability + DefaultDelay: number; + DefaultResidueTime: number; + DamageEnergy: number; + DamageHealth: number; + EnergyLoopTime: number; + HealthLoopTime: number; + DamageHealthDehydrated: number; + HealthLoopTimeDehydrated: number; + LifeTimeDehydrated: number; + EliteVitalityDuration: number; + HealExperience: number; + OfflineDurationMin: number; + OfflineDurationMax: number; + RemovePrice: number; + RemovedAfterDeath: boolean; + Probability: IProbability; } -export interface IProbability +export interface IProbability { - FunctionType: string - K: number - B: number - Threshold: number + FunctionType: string; + K: number; + B: number; + Threshold: number; } -export interface ILightBleeding +export interface ILightBleeding { - DefaultDelay: number - DefaultResidueTime: number - DamageEnergy: number - DamageHealth: number - EnergyLoopTime: number - HealthLoopTime: number - DamageHealthDehydrated: number - HealthLoopTimeDehydrated: number - LifeTimeDehydrated: number - EliteVitalityDuration: number - HealExperience: number - OfflineDurationMin: number - OfflineDurationMax: number - RemovePrice: number - RemovedAfterDeath: boolean - Probability: IProbability + DefaultDelay: number; + DefaultResidueTime: number; + DamageEnergy: number; + DamageHealth: number; + EnergyLoopTime: number; + HealthLoopTime: number; + DamageHealthDehydrated: number; + HealthLoopTimeDehydrated: number; + LifeTimeDehydrated: number; + EliteVitalityDuration: number; + HealExperience: number; + OfflineDurationMin: number; + OfflineDurationMax: number; + RemovePrice: number; + RemovedAfterDeath: boolean; + Probability: IProbability; } -export interface IBodyTemperature +export interface IBodyTemperature { - DefaultBuildUpTime: number - DefaultResidueTime: number - LoopTime: number + DefaultBuildUpTime: number; + DefaultResidueTime: number; + LoopTime: number; } -export interface IHealPrice +export interface IHealPrice { - HealthPointPrice: number - HydrationPointPrice: number - EnergyPointPrice: number - TrialLevels: number - TrialRaids: number + HealthPointPrice: number; + HydrationPointPrice: number; + EnergyPointPrice: number; + TrialLevels: number; + TrialRaids: number; } -export interface IProfileHealthSettings +export interface IProfileHealthSettings { - BodyPartsSettings: IBodyPartsSettings - HealthFactorsSettings: IHealthFactorsSettings - DefaultStimulatorBuff: string + BodyPartsSettings: IBodyPartsSettings; + HealthFactorsSettings: IHealthFactorsSettings; + DefaultStimulatorBuff: string; } -export interface IBodyPartsSettings +export interface IBodyPartsSettings { - Head: IBodyPartsSetting - Chest: IBodyPartsSetting - Stomach: IBodyPartsSetting - LeftArm: IBodyPartsSetting - RightArm: IBodyPartsSetting - LeftLeg: IBodyPartsSetting - RightLeg: IBodyPartsSetting + Head: IBodyPartsSetting; + Chest: IBodyPartsSetting; + Stomach: IBodyPartsSetting; + LeftArm: IBodyPartsSetting; + RightArm: IBodyPartsSetting; + LeftLeg: IBodyPartsSetting; + RightLeg: IBodyPartsSetting; } -export interface IBodyPartsSetting +export interface IBodyPartsSetting { - Minimum: number - Maximum: number - Default: number - OverDamageReceivedMultiplier: number + Minimum: number; + Maximum: number; + Default: number; + OverDamageReceivedMultiplier: number; } -export interface IHealthFactorsSettings +export interface IHealthFactorsSettings { - Energy: IHealthFactorSetting - Hydration: IHealthFactorSetting - Temperature: IHealthFactorSetting - Poisoning: IHealthFactorSetting - Radiation: IHealthFactorSetting + Energy: IHealthFactorSetting; + Hydration: IHealthFactorSetting; + Temperature: IHealthFactorSetting; + Poisoning: IHealthFactorSetting; + Radiation: IHealthFactorSetting; } -export interface IHealthFactorSetting +export interface IHealthFactorSetting { - Minimum: number - Maximum: number - Default: number + Minimum: number; + Maximum: number; + Default: number; } -export interface IRating +export interface IRating { - levelRequired: number - limit: number - categories: ICategories + levelRequired: number; + limit: number; + categories: ICategories; } -export interface ICategories +export interface ICategories { - experience: boolean - kd: boolean - surviveRatio: boolean - avgEarnings: boolean - pmcKills: boolean - raidCount: boolean - longestShot: boolean - timeOnline: boolean - inventoryFullCost: boolean - ragFairStanding: boolean + experience: boolean; + kd: boolean; + surviveRatio: boolean; + avgEarnings: boolean; + pmcKills: boolean; + raidCount: boolean; + longestShot: boolean; + timeOnline: boolean; + inventoryFullCost: boolean; + ragFairStanding: boolean; } -export interface ITournament +export interface ITournament { - categories: ITournamentCategories - limit: number - levelRequired: number + categories: ITournamentCategories; + limit: number; + levelRequired: number; } -export interface ITournamentCategories +export interface ITournamentCategories { - dogtags: boolean + dogtags: boolean; } -export interface IRagFair +export interface IRagFair { - enabled: boolean - priceStabilizerEnabled: boolean - includePveTraderSales: boolean - priceStabilizerStartIntervalInHours: number - minUserLevel: number - communityTax: number - communityItemTax: number - communityRequirementTax: number - offerPriorityCost: number - offerDurationTimeInHour: number - offerDurationTimeInHourAfterRemove: number - priorityTimeModifier: number - maxRenewOfferTimeInHour: number - renewPricePerHour: number - maxActiveOfferCount: IMaxActiveOfferCount[] - balancerRemovePriceCoefficient: number - balancerMinPriceCount: number - balancerAveragePriceCoefficient: number - delaySinceOfferAdd: number - uniqueBuyerTimeoutInDays: number - ratingSumForIncrease: number - ratingIncreaseCount: number - ratingSumForDecrease: number - ratingDecreaseCount: number - maxSumForIncreaseRatingPerOneSale: number - maxSumForDecreaseRatingPerOneSale: number - maxSumForRarity: IMaxSumForRarity - ChangePriceCoef: number - balancerUserItemSaleCooldownEnabled: boolean - balancerUserItemSaleCooldown: number - youSellOfferMaxStorageTimeInHour: number - yourOfferDidNotSellMaxStorageTimeInHour: number - isOnlyFoundInRaidAllowed: boolean - sellInOnePiece: number + enabled: boolean; + priceStabilizerEnabled: boolean; + includePveTraderSales: boolean; + priceStabilizerStartIntervalInHours: number; + minUserLevel: number; + communityTax: number; + communityItemTax: number; + communityRequirementTax: number; + offerPriorityCost: number; + offerDurationTimeInHour: number; + offerDurationTimeInHourAfterRemove: number; + priorityTimeModifier: number; + maxRenewOfferTimeInHour: number; + renewPricePerHour: number; + maxActiveOfferCount: IMaxActiveOfferCount[]; + balancerRemovePriceCoefficient: number; + balancerMinPriceCount: number; + balancerAveragePriceCoefficient: number; + delaySinceOfferAdd: number; + uniqueBuyerTimeoutInDays: number; + ratingSumForIncrease: number; + ratingIncreaseCount: number; + ratingSumForDecrease: number; + ratingDecreaseCount: number; + maxSumForIncreaseRatingPerOneSale: number; + maxSumForDecreaseRatingPerOneSale: number; + maxSumForRarity: IMaxSumForRarity; + ChangePriceCoef: number; + balancerUserItemSaleCooldownEnabled: boolean; + balancerUserItemSaleCooldown: number; + youSellOfferMaxStorageTimeInHour: number; + yourOfferDidNotSellMaxStorageTimeInHour: number; + isOnlyFoundInRaidAllowed: boolean; + sellInOnePiece: number; } -export interface IMaxActiveOfferCount +export interface IMaxActiveOfferCount { - from: number - to: number - count: number + from: number; + to: number; + count: number; } -export interface IMaxSumForRarity +export interface IMaxSumForRarity { - Common: IRarityMaxSum - Rare: IRarityMaxSum - Superrare: IRarityMaxSum - Not_exist: IRarityMaxSum + Common: IRarityMaxSum; + Rare: IRarityMaxSum; + Superrare: IRarityMaxSum; + Not_exist: IRarityMaxSum; } -export interface IRarityMaxSum +export interface IRarityMaxSum { - value: number + value: number; } -export interface IHandbook +export interface IHandbook { - defaultCategory: string + defaultCategory: string; } - -export interface IStamina +export interface IStamina { - Capacity: number - SprintDrainRate: number - BaseRestorationRate: number - JumpConsumption: number - GrenadeHighThrow: number - GrenadeLowThrow: number - AimDrainRate: number - AimRangeFinderDrainRate: number - OxygenCapacity: number - OxygenRestoration: number - WalkOverweightLimits: Ixyz - BaseOverweightLimits: Ixyz - SprintOverweightLimits: Ixyz - WalkSpeedOverweightLimits: Ixyz - CrouchConsumption: Ixyz - WalkConsumption: Ixyz - StandupConsumption: Ixyz - TransitionSpeed: Ixyz - SprintAccelerationLowerLimit: number - SprintSpeedLowerLimit: number - SprintSensitivityLowerLimit: number - AimConsumptionByPose: Ixyz - RestorationMultiplierByPose: Ixyz - OverweightConsumptionByPose: Ixyz - AimingSpeedMultiplier: number - WalkVisualEffectMultiplier: number - WeaponFastSwitchConsumption: number - HandsCapacity: number - HandsRestoration: number - ProneConsumption: number - BaseHoldBreathConsumption: number - SoundRadius: Ixyz - ExhaustedMeleeSpeed: number - FatigueRestorationRate: number - FatigueAmountToCreateEffect: number - ExhaustedMeleeDamageMultiplier: number - FallDamageMultiplier: number - SafeHeightOverweight: number - SitToStandConsumption: number - StaminaExhaustionCausesJiggle: boolean - StaminaExhaustionStartsBreathSound: boolean - StaminaExhaustionRocksCamera: boolean - HoldBreathStaminaMultiplier: Ixyz - PoseLevelIncreaseSpeed: Ixyz - PoseLevelDecreaseSpeed: Ixyz - PoseLevelConsumptionPerNotch: Ixyz + Capacity: number; + SprintDrainRate: number; + BaseRestorationRate: number; + JumpConsumption: number; + GrenadeHighThrow: number; + GrenadeLowThrow: number; + AimDrainRate: number; + AimRangeFinderDrainRate: number; + OxygenCapacity: number; + OxygenRestoration: number; + WalkOverweightLimits: Ixyz; + BaseOverweightLimits: Ixyz; + SprintOverweightLimits: Ixyz; + WalkSpeedOverweightLimits: Ixyz; + CrouchConsumption: Ixyz; + WalkConsumption: Ixyz; + StandupConsumption: Ixyz; + TransitionSpeed: Ixyz; + SprintAccelerationLowerLimit: number; + SprintSpeedLowerLimit: number; + SprintSensitivityLowerLimit: number; + AimConsumptionByPose: Ixyz; + RestorationMultiplierByPose: Ixyz; + OverweightConsumptionByPose: Ixyz; + AimingSpeedMultiplier: number; + WalkVisualEffectMultiplier: number; + WeaponFastSwitchConsumption: number; + HandsCapacity: number; + HandsRestoration: number; + ProneConsumption: number; + BaseHoldBreathConsumption: number; + SoundRadius: Ixyz; + ExhaustedMeleeSpeed: number; + FatigueRestorationRate: number; + FatigueAmountToCreateEffect: number; + ExhaustedMeleeDamageMultiplier: number; + FallDamageMultiplier: number; + SafeHeightOverweight: number; + SitToStandConsumption: number; + StaminaExhaustionCausesJiggle: boolean; + StaminaExhaustionStartsBreathSound: boolean; + StaminaExhaustionRocksCamera: boolean; + HoldBreathStaminaMultiplier: Ixyz; + PoseLevelIncreaseSpeed: Ixyz; + PoseLevelDecreaseSpeed: Ixyz; + PoseLevelConsumptionPerNotch: Ixyz; } -export interface IStaminaRestoration +export interface IStaminaRestoration { - LowerLeftPoint: number - LowerRightPoint: number - LeftPlatoPoint: number - RightPlatoPoint: number - RightLimit: number - ZeroValue: number + LowerLeftPoint: number; + LowerRightPoint: number; + LeftPlatoPoint: number; + RightPlatoPoint: number; + RightLimit: number; + ZeroValue: number; } -export interface IStaminaDrain +export interface IStaminaDrain { - LowerLeftPoint: number - LowerRightPoint: number - LeftPlatoPoint: number - RightPlatoPoint: number - RightLimit: number - ZeroValue: number + LowerLeftPoint: number; + LowerRightPoint: number; + LeftPlatoPoint: number; + RightPlatoPoint: number; + RightLimit: number; + ZeroValue: number; } -export interface IRequirementReferences +export interface IRequirementReferences { - Alpinist: IAlpinist[] + Alpinist: IAlpinist[]; } -export interface IAlpinist +export interface IAlpinist { - Requirement: string - Id: string - Count: number - RequiredSlot: string - RequirementTip: string + Requirement: string; + Id: string; + Count: number; + RequiredSlot: string; + RequirementTip: string; } -export interface IRestrictionsInRaid +export interface IRestrictionsInRaid { - TemplateId: string - Value: number + TemplateId: string; + Value: number; } -export interface ISquadSettings +export interface ISquadSettings { - CountOfRequestsToOnePlayer: number - SecondsForExpiredRequest: number - SendRequestDelaySeconds: number + CountOfRequestsToOnePlayer: number; + SecondsForExpiredRequest: number; + SendRequestDelaySeconds: number; } -export interface IInsurance +export interface IInsurance { - MaxStorageTimeInHour: number + MaxStorageTimeInHour: number; } -export interface ISkillsSettings +export interface ISkillsSettings { - SkillProgressRate: number - WeaponSkillProgressRate: number - WeaponSkillRecoilBonusPerLevel: number - HideoutManagement: IHideoutManagement - Crafting: ICrafting - Metabolism: IMetabolism - Immunity: Immunity - Endurance: IEndurance - Strength: IStrength - Vitality: IVitality - Health: IHealthSkillProgress - StressResistance: IStressResistance - Throwing: IThrowing - RecoilControl: IRecoilControl - Pistol: IWeaponSkills - Revolver: IWeaponSkills - SMG: any[] - Assault: IWeaponSkills - Shotgun: IWeaponSkills - Sniper: IWeaponSkills - LMG: any[] - HMG: any[] - Launcher: any[] - AttachedLauncher: any[] - Melee: IMeleeSkill - DMR: IWeaponSkills - BearAssaultoperations: any[] - BearAuthority: any[] - BearAksystems: any[] - BearHeavycaliber: any[] - BearRawpower: any[] - UsecArsystems: any[] - UsecDeepweaponmodding_Settings: any[] - UsecLongrangeoptics_Settings: any[] - UsecNegotiations: any[] - UsecTactics: any[] - BotReload: any[] - CovertMovement: ICovertMovement - FieldMedicine: any[] - Search: ISearch - Sniping: any[] - ProneMovement: any[] - FirstAid: any[] - LightVests: IArmorSkills - HeavyVests: IArmorSkills - WeaponModding: any[] - AdvancedModding: any[] - NightOps: any[] - SilentOps: any[] - Lockpicking: any[] - WeaponTreatment: IWeaponTreatment - MagDrills: IMagDrills - Freetrading: any[] - Auctions: any[] - Cleanoperations: any[] - Barter: any[] - Shadowconnections: any[] - Taskperformance: any[] - Perception: IPerception - Intellect: Intellect - Attention: IAttention - Charisma: ICharisma - Memory: IMemory - Surgery: ISurgery - AimDrills: IAimDrills - BotSound: any[] - TroubleShooting: ITroubleShooting + SkillProgressRate: number; + WeaponSkillProgressRate: number; + WeaponSkillRecoilBonusPerLevel: number; + HideoutManagement: IHideoutManagement; + Crafting: ICrafting; + Metabolism: IMetabolism; + Immunity: Immunity; + Endurance: IEndurance; + Strength: IStrength; + Vitality: IVitality; + Health: IHealthSkillProgress; + StressResistance: IStressResistance; + Throwing: IThrowing; + RecoilControl: IRecoilControl; + Pistol: IWeaponSkills; + Revolver: IWeaponSkills; + SMG: any[]; + Assault: IWeaponSkills; + Shotgun: IWeaponSkills; + Sniper: IWeaponSkills; + LMG: any[]; + HMG: any[]; + Launcher: any[]; + AttachedLauncher: any[]; + Melee: IMeleeSkill; + DMR: IWeaponSkills; + BearAssaultoperations: any[]; + BearAuthority: any[]; + BearAksystems: any[]; + BearHeavycaliber: any[]; + BearRawpower: any[]; + UsecArsystems: any[]; + UsecDeepweaponmodding_Settings: any[]; + UsecLongrangeoptics_Settings: any[]; + UsecNegotiations: any[]; + UsecTactics: any[]; + BotReload: any[]; + CovertMovement: ICovertMovement; + FieldMedicine: any[]; + Search: ISearch; + Sniping: any[]; + ProneMovement: any[]; + FirstAid: any[]; + LightVests: IArmorSkills; + HeavyVests: IArmorSkills; + WeaponModding: any[]; + AdvancedModding: any[]; + NightOps: any[]; + SilentOps: any[]; + Lockpicking: any[]; + WeaponTreatment: IWeaponTreatment; + MagDrills: IMagDrills; + Freetrading: any[]; + Auctions: any[]; + Cleanoperations: any[]; + Barter: any[]; + Shadowconnections: any[]; + Taskperformance: any[]; + Perception: IPerception; + Intellect: Intellect; + Attention: IAttention; + Charisma: ICharisma; + Memory: IMemory; + Surgery: ISurgery; + AimDrills: IAimDrills; + BotSound: any[]; + TroubleShooting: ITroubleShooting; } export interface IMeleeSkill { - BuffSettings: IBuffSettings + BuffSettings: IBuffSettings; } export interface IArmorSkills { - BuffMaxCount: number - BuffSettings: IBuffSettings - Counters: IArmorCounters - MoveSpeedPenaltyReductionHVestsReducePerLevel: number - RicochetChanceHVestsCurrentDurabilityThreshold: number - RicochetChanceHVestsEliteLevel: number - RicochetChanceHVestsMaxDurabilityThreshold: number - MeleeDamageLVestsReducePerLevel: number - MoveSpeedPenaltyReductionLVestsReducePerLevel: number - WearAmountRepairLVestsReducePerLevel: number - WearChanceRepairLVestsReduceEliteLevel: number + BuffMaxCount: number; + BuffSettings: IBuffSettings; + Counters: IArmorCounters; + MoveSpeedPenaltyReductionHVestsReducePerLevel: number; + RicochetChanceHVestsCurrentDurabilityThreshold: number; + RicochetChanceHVestsEliteLevel: number; + RicochetChanceHVestsMaxDurabilityThreshold: number; + MeleeDamageLVestsReducePerLevel: number; + MoveSpeedPenaltyReductionLVestsReducePerLevel: number; + WearAmountRepairLVestsReducePerLevel: number; + WearChanceRepairLVestsReduceEliteLevel: number; } export interface IArmorCounters { - armorDurability: ISkillCounter + armorDurability: ISkillCounter; } -export interface IHideoutManagement +export interface IHideoutManagement { - SkillPointsPerAreaUpgrade: number - SkillPointsPerCraft: number - ConsumptionReductionPerLevel: number - SkillBoostPercent: number - SkillPointsRate: ISkillPointsRate - EliteSlots: IEliteSlots + SkillPointsPerAreaUpgrade: number; + SkillPointsPerCraft: number; + ConsumptionReductionPerLevel: number; + SkillBoostPercent: number; + SkillPointsRate: ISkillPointsRate; + EliteSlots: IEliteSlots; } -export interface ISkillPointsRate +export interface ISkillPointsRate { - Generator: ISkillPointRate - AirFilteringUnit: ISkillPointRate - WaterCollector: ISkillPointRate - SolarPower: ISkillPointRate + Generator: ISkillPointRate; + AirFilteringUnit: ISkillPointRate; + WaterCollector: ISkillPointRate; + SolarPower: ISkillPointRate; } -export interface ISkillPointRate +export interface ISkillPointRate { - ResourceSpent: number - PointsGained: number + ResourceSpent: number; + PointsGained: number; } -export interface IEliteSlots +export interface IEliteSlots { - Generator: IEliteSlot - AirFilteringUnit: IEliteSlot - WaterCollector: IEliteSlot - BitcoinFarm: IEliteSlot + Generator: IEliteSlot; + AirFilteringUnit: IEliteSlot; + WaterCollector: IEliteSlot; + BitcoinFarm: IEliteSlot; } -export interface IEliteSlot +export interface IEliteSlot { - Slots: number - Container: number + Slots: number; + Container: number; } -export interface ICrafting +export interface ICrafting { - PointsPerCraftingCycle: number - CraftingCycleHours: number - PointsPerUniqueCraftCycle: number - UniqueCraftsPerCycle: number - CraftTimeReductionPerLevel: number - ProductionTimeReductionPerLevel: number - EliteExtraProductions: number - CraftingPointsToInteligence: number + PointsPerCraftingCycle: number; + CraftingCycleHours: number; + PointsPerUniqueCraftCycle: number; + UniqueCraftsPerCycle: number; + CraftTimeReductionPerLevel: number; + ProductionTimeReductionPerLevel: number; + EliteExtraProductions: number; + CraftingPointsToInteligence: number; } -export interface IMetabolism +export interface IMetabolism { - HydrationRecoveryRate: number - EnergyRecoveryRate: number - IncreasePositiveEffectDurationRate: number - DecreaseNegativeEffectDurationRate: number - DecreasePoisonDurationRate: number + HydrationRecoveryRate: number; + EnergyRecoveryRate: number; + IncreasePositiveEffectDurationRate: number; + DecreaseNegativeEffectDurationRate: number; + DecreasePoisonDurationRate: number; } -export interface Immunity +export interface Immunity { - ImmunityMiscEffects: number - ImmunityPoisonBuff: number - ImmunityPainKiller: number - HealthNegativeEffect: number - StimulatorNegativeBuff: number + ImmunityMiscEffects: number; + ImmunityPoisonBuff: number; + ImmunityPainKiller: number; + HealthNegativeEffect: number; + StimulatorNegativeBuff: number; } -export interface IEndurance +export interface IEndurance { - MovementAction: number - SprintAction: number - GainPerFatigueStack: number - DependentSkillRatios: IDependentSkillRatio[] - QTELevelMultipliers: Record> + MovementAction: number; + SprintAction: number; + GainPerFatigueStack: number; + DependentSkillRatios: IDependentSkillRatio[]; + QTELevelMultipliers: Record>; } -export interface IStrength +export interface IStrength { - DependentSkillRatios: IDependentSkillRatio[] - SprintActionMin: number - SprintActionMax: number - MovementActionMin: number - MovementActionMax: number - PushUpMin: number - PushUpMax: number - QTELevelMultipliers: IQTELevelMultiplier[] - FistfightAction: number - ThrowAction: number + DependentSkillRatios: IDependentSkillRatio[]; + SprintActionMin: number; + SprintActionMax: number; + MovementActionMin: number; + MovementActionMax: number; + PushUpMin: number; + PushUpMax: number; + QTELevelMultipliers: IQTELevelMultiplier[]; + FistfightAction: number; + ThrowAction: number; } export interface IDependentSkillRatio { - Ratio: number - SkillId: string + Ratio: number; + SkillId: string; } export interface IQTELevelMultiplier { - Level: number - Multiplier: number + Level: number; + Multiplier: number; } -export interface IVitality +export interface IVitality { - DamageTakenAction: number - HealthNegativeEffect: number + DamageTakenAction: number; + HealthNegativeEffect: number; } -export interface IHealthSkillProgress +export interface IHealthSkillProgress { - SkillProgress: number + SkillProgress: number; } -export interface IStressResistance +export interface IStressResistance { - HealthNegativeEffect: number - LowHPDuration: number + HealthNegativeEffect: number; + LowHPDuration: number; } -export interface IThrowing +export interface IThrowing { - ThrowAction: number + ThrowAction: number; } -export interface IRecoilControl +export interface IRecoilControl { - RecoilAction: number - RecoilBonusPerLevel: number + RecoilAction: number; + RecoilBonusPerLevel: number; } -export interface IWeaponSkills +export interface IWeaponSkills { - WeaponReloadAction: number - WeaponShotAction: number - WeaponFixAction: number - WeaponChamberAction: number + WeaponReloadAction: number; + WeaponShotAction: number; + WeaponFixAction: number; + WeaponChamberAction: number; } -export interface ICovertMovement +export interface ICovertMovement { - MovementAction: number + MovementAction: number; } -export interface ISearch +export interface ISearch { - SearchAction: number - FindAction: number + SearchAction: number; + FindAction: number; } -export interface IWeaponTreatment +export interface IWeaponTreatment { - BuffMaxCount: number - BuffSettings: IBuffSettings - Counters: IWeaponTreatmentCounters - DurLossReducePerLevel: number - SkillPointsPerRepair: number - Filter: any[] - WearAmountRepairGunsReducePerLevel: number - WearChanceRepairGunsReduceEliteLevel: number + BuffMaxCount: number; + BuffSettings: IBuffSettings; + Counters: IWeaponTreatmentCounters; + DurLossReducePerLevel: number; + SkillPointsPerRepair: number; + Filter: any[]; + WearAmountRepairGunsReducePerLevel: number; + WearChanceRepairGunsReduceEliteLevel: number; } export interface IWeaponTreatmentCounters { - firearmsDurability: ISkillCounter + firearmsDurability: ISkillCounter; } export interface IBuffSettings { - CommonBuffChanceLevelBonus: number - CommonBuffMinChanceValue: number - CurrentDurabilityLossToRemoveBuff?: number - MaxDurabilityLossToRemoveBuff?: number - RareBuffChanceCoff: number - ReceivedDurabilityMaxPercent: number + CommonBuffChanceLevelBonus: number; + CommonBuffMinChanceValue: number; + CurrentDurabilityLossToRemoveBuff?: number; + MaxDurabilityLossToRemoveBuff?: number; + RareBuffChanceCoff: number; + ReceivedDurabilityMaxPercent: number; } -export interface IMagDrills +export interface IMagDrills { - RaidLoadedAmmoAction: number - RaidUnloadedAmmoAction: number - MagazineCheckAction: number + RaidLoadedAmmoAction: number; + RaidUnloadedAmmoAction: number; + MagazineCheckAction: number; } -export interface IPerception +export interface IPerception { - DependentSkillRatios: ISkillRatio[] - OnlineAction: number - UniqueLoot: number + DependentSkillRatios: ISkillRatio[]; + OnlineAction: number; + UniqueLoot: number; } export interface ISkillRatio { - Ratio: number - SkillId: string + Ratio: number; + SkillId: string; } -export interface Intellect +export interface Intellect { - Counters: IIntellectCounters - ExamineAction: number - SkillProgress: number - RepairAction: number - WearAmountReducePerLevel: number - WearChanceReduceEliteLevel: number - RepairPointsCostReduction: number + Counters: IIntellectCounters; + ExamineAction: number; + SkillProgress: number; + RepairAction: number; + WearAmountReducePerLevel: number; + WearChanceReduceEliteLevel: number; + RepairPointsCostReduction: number; } export interface IIntellectCounters { - armorDurability: ISkillCounter - firearmsDurability: ISkillCounter - meleeWeaponDurability: ISkillCounter + armorDurability: ISkillCounter; + firearmsDurability: ISkillCounter; + meleeWeaponDurability: ISkillCounter; } export interface ISkillCounter { - divisor: number - points: number + divisor: number; + points: number; } -export interface IAttention +export interface IAttention { - DependentSkillRatios: ISkillRatio[] - ExamineWithInstruction: number - FindActionFalse: number - FindActionTrue: number + DependentSkillRatios: ISkillRatio[]; + ExamineWithInstruction: number; + FindActionFalse: number; + FindActionTrue: number; } -export interface ICharisma +export interface ICharisma { - BonusSettings: IBonusSettings - Counters: ICharismaSkillCounters - SkillProgressInt: number - SkillProgressAtn: number - SkillProgressPer: number + BonusSettings: IBonusSettings; + Counters: ICharismaSkillCounters; + SkillProgressInt: number; + SkillProgressAtn: number; + SkillProgressPer: number; } export interface ICharismaSkillCounters { - insuranceCost: ISkillCounter - repairCost: ISkillCounter - repeatableQuestCompleteCount: ISkillCounter - restoredHealthCost: ISkillCounter - scavCaseCost: ISkillCounter + insuranceCost: ISkillCounter; + repairCost: ISkillCounter; + repeatableQuestCompleteCount: ISkillCounter; + restoredHealthCost: ISkillCounter; + scavCaseCost: ISkillCounter; } export interface IBonusSettings { - EliteBonusSettings: IEliteBonusSettings - LevelBonusSettings: ILevelBonusSettings + EliteBonusSettings: IEliteBonusSettings; + LevelBonusSettings: ILevelBonusSettings; } export interface IEliteBonusSettings { - FenceStandingLossDiscount: number - RepeatableQuestExtraCount: number - ScavCaseDiscount: number + FenceStandingLossDiscount: number; + RepeatableQuestExtraCount: number; + ScavCaseDiscount: number; } - + export interface ILevelBonusSettings { - HealthRestoreDiscount: number - HealthRestoreTraderDiscount: number - InsuranceDiscount: number - InsuranceTraderDiscount: number - PaidExitDiscount: number - RepeatableQuestChangeDiscount: number + HealthRestoreDiscount: number; + HealthRestoreTraderDiscount: number; + InsuranceDiscount: number; + InsuranceTraderDiscount: number; + PaidExitDiscount: number; + RepeatableQuestChangeDiscount: number; } -export interface IMemory +export interface IMemory { - AnySkillUp: number - SkillProgress: number + AnySkillUp: number; + SkillProgress: number; } -export interface ISurgery +export interface ISurgery { - SurgeryAction: number - SkillProgress: number + SurgeryAction: number; + SkillProgress: number; } -export interface IAimDrills +export interface IAimDrills { - WeaponShotAction: number + WeaponShotAction: number; } -export interface ITroubleShooting +export interface ITroubleShooting { - MalfRepairSpeedBonusPerLevel: number - SkillPointsPerMalfFix: number - EliteDurabilityChanceReduceMult: number - EliteAmmoChanceReduceMult: number - EliteMagChanceReduceMult: number + MalfRepairSpeedBonusPerLevel: number; + SkillPointsPerMalfFix: number; + EliteDurabilityChanceReduceMult: number; + EliteAmmoChanceReduceMult: number; + EliteMagChanceReduceMult: number; } -export interface IAiming +export interface IAiming { - ProceduralIntensityByPose: Ixyz - AimProceduralIntensity: number - HeavyWeight: number - LightWeight: number - MaxTimeHeavy: number - MinTimeHeavy: number - MaxTimeLight: number - MinTimeLight: number - RecoilScaling: number - RecoilDamping: number - CameraSnapGlobalMult: number - RecoilXIntensityByPose: Ixyz - RecoilYIntensityByPose: Ixyz - RecoilZIntensityByPose: Ixyz - RecoilCrank: boolean - RecoilHandDamping: number - RecoilConvergenceMult: number - RecoilVertBonus: number - RecoilBackBonus: number + ProceduralIntensityByPose: Ixyz; + AimProceduralIntensity: number; + HeavyWeight: number; + LightWeight: number; + MaxTimeHeavy: number; + MinTimeHeavy: number; + MaxTimeLight: number; + MinTimeLight: number; + RecoilScaling: number; + RecoilDamping: number; + CameraSnapGlobalMult: number; + RecoilXIntensityByPose: Ixyz; + RecoilYIntensityByPose: Ixyz; + RecoilZIntensityByPose: Ixyz; + RecoilCrank: boolean; + RecoilHandDamping: number; + RecoilConvergenceMult: number; + RecoilVertBonus: number; + RecoilBackBonus: number; } - -export interface IMalfunction +export interface IMalfunction { - AmmoMalfChanceMult: number - MagazineMalfChanceMult: number - MalfRepairHardSlideMult: number - MalfRepairOneHandBrokenMult: number - MalfRepairTwoHandsBrokenMult: number - AllowMalfForBots: boolean - ShowGlowAttemptsCount: number - OutToIdleSpeedMultForPistol: number - IdleToOutSpeedMultOnMalf: number - TimeToQuickdrawPistol: number - DurRangeToIgnoreMalfs: Ixyz - DurFeedWt: number - DurMisfireWt: number - DurJamWt: number - DurSoftSlideWt: number - DurHardSlideMinWt: number - DurHardSlideMaxWt: number - AmmoMisfireWt: number - AmmoFeedWt: number - AmmoJamWt: number - OverheatFeedWt: number - OverheatJamWt: number - OverheatSoftSlideWt: number - OverheatHardSlideMinWt: number - OverheatHardSlideMaxWt: number + AmmoMalfChanceMult: number; + MagazineMalfChanceMult: number; + MalfRepairHardSlideMult: number; + MalfRepairOneHandBrokenMult: number; + MalfRepairTwoHandsBrokenMult: number; + AllowMalfForBots: boolean; + ShowGlowAttemptsCount: number; + OutToIdleSpeedMultForPistol: number; + IdleToOutSpeedMultOnMalf: number; + TimeToQuickdrawPistol: number; + DurRangeToIgnoreMalfs: Ixyz; + DurFeedWt: number; + DurMisfireWt: number; + DurJamWt: number; + DurSoftSlideWt: number; + DurHardSlideMinWt: number; + DurHardSlideMaxWt: number; + AmmoMisfireWt: number; + AmmoFeedWt: number; + AmmoJamWt: number; + OverheatFeedWt: number; + OverheatJamWt: number; + OverheatSoftSlideWt: number; + OverheatHardSlideMinWt: number; + OverheatHardSlideMaxWt: number; } - -export interface IOverheat +export interface IOverheat { - MinOverheat: number - MaxOverheat: number - OverheatProblemsStart: number - ModHeatFactor: number - ModCoolFactor: number - MinWearOnOverheat: number - MaxWearOnOverheat: number - MinWearOnMaxOverheat: number - MaxWearOnMaxOverheat: number - OverheatWearLimit: number - MaxCOIIncreaseMult: number - MinMalfChance: number - MaxMalfChance: number - DurReduceMinMult: number - DurReduceMaxMult: number - BarrelMoveRndDuration: number - BarrelMoveMaxMult: number - FireratePitchMult: number - FirerateReduceMinMult: number - FirerateReduceMaxMult: number - FirerateOverheatBorder: number - EnableSlideOnMaxOverheat: boolean - StartSlideOverheat: number - FixSlideOverheat: number - AutoshotMinOverheat: number - AutoshotChance: number - AutoshotPossibilityDuration: number - MaxOverheatCoolCoef: number + MinOverheat: number; + MaxOverheat: number; + OverheatProblemsStart: number; + ModHeatFactor: number; + ModCoolFactor: number; + MinWearOnOverheat: number; + MaxWearOnOverheat: number; + MinWearOnMaxOverheat: number; + MaxWearOnMaxOverheat: number; + OverheatWearLimit: number; + MaxCOIIncreaseMult: number; + MinMalfChance: number; + MaxMalfChance: number; + DurReduceMinMult: number; + DurReduceMaxMult: number; + BarrelMoveRndDuration: number; + BarrelMoveMaxMult: number; + FireratePitchMult: number; + FirerateReduceMinMult: number; + FirerateReduceMaxMult: number; + FirerateOverheatBorder: number; + EnableSlideOnMaxOverheat: boolean; + StartSlideOverheat: number; + FixSlideOverheat: number; + AutoshotMinOverheat: number; + AutoshotChance: number; + AutoshotPossibilityDuration: number; + MaxOverheatCoolCoef: number; } -export interface IFenceSettings +export interface IFenceSettings { - FenceId: string - Levels: Record - paidExitStandingNumerator: number + FenceId: string; + Levels: Record; + paidExitStandingNumerator: number; } -export interface IFenceLevel -{ - SavageCooldownModifier: number - ScavCaseTimeModifier: number - PaidExitCostModifier: number - BotFollowChance: number - ScavEquipmentSpawnChanceModifier: number - PriceModifier: number - HostileBosses: boolean - HostileScavs: boolean - ScavAttackSupport: boolean - ExfiltrationPriceModifier: number - AvailableExits: number - BotApplySilenceChance: number - BotGetInCoverChance: number - BotHelpChance: number - BotSpreadoutChance: number - BotStopChance: number -} - -export interface IInertia +export interface IFenceLevel { - InertiaLimits: Ixyz - InertiaLimitsStep: number - ExitMovementStateSpeedThreshold: Ixyz - WalkInertia: Ixyz - FallThreshold: number - SpeedLimitAfterFallMin: Ixyz - SpeedLimitAfterFallMax: Ixyz - SpeedLimitDurationMin: Ixyz - SpeedLimitDurationMax: Ixyz - SpeedInertiaAfterJump: Ixyz - BaseJumpPenaltyDuration: number - DurationPower: number - BaseJumpPenalty: number - PenaltyPower: number - InertiaTiltCurveMin: Ixyz - InertiaTiltCurveMax: Ixyz - InertiaBackwardCoef: Ixyz - TiltInertiaMaxSpeed: Ixyz - TiltStartSideBackSpeed: Ixyz - TiltMaxSideBackSpeed: Ixyz - TiltAcceleration: Ixyz - AverageRotationFrameSpan: number - SprintSpeedInertiaCurveMin: Ixyz - SprintSpeedInertiaCurveMax: Ixyz - SprintBrakeInertia: Ixyz - SprintTransitionMotionPreservation: Ixyz - WeaponFlipSpeed: Ixyz - PreSprintAccelerationLimits: Ixyz - SprintAccelerationLimits: Ixyz - SideTime: Ixyz - DiagonalTime: Ixyz - MaxTimeWithoutInput: Ixyz - MinDirectionBlendTime: number - MoveTimeRange: Ixyz - ProneDirectionAccelerationRange: Ixyz - ProneSpeedAccelerationRange: Ixyz - MinMovementAccelerationRangeRight: Ixyz - MaxMovementAccelerationRangeRight: Ixyz + SavageCooldownModifier: number; + ScavCaseTimeModifier: number; + PaidExitCostModifier: number; + BotFollowChance: number; + ScavEquipmentSpawnChanceModifier: number; + PriceModifier: number; + HostileBosses: boolean; + HostileScavs: boolean; + ScavAttackSupport: boolean; + ExfiltrationPriceModifier: number; + AvailableExits: number; + BotApplySilenceChance: number; + BotGetInCoverChance: number; + BotHelpChance: number; + BotSpreadoutChance: number; + BotStopChance: number; } -export interface IBallistic +export interface IInertia { - GlobalDamageDegradationCoefficient: number + InertiaLimits: Ixyz; + InertiaLimitsStep: number; + ExitMovementStateSpeedThreshold: Ixyz; + WalkInertia: Ixyz; + FallThreshold: number; + SpeedLimitAfterFallMin: Ixyz; + SpeedLimitAfterFallMax: Ixyz; + SpeedLimitDurationMin: Ixyz; + SpeedLimitDurationMax: Ixyz; + SpeedInertiaAfterJump: Ixyz; + BaseJumpPenaltyDuration: number; + DurationPower: number; + BaseJumpPenalty: number; + PenaltyPower: number; + InertiaTiltCurveMin: Ixyz; + InertiaTiltCurveMax: Ixyz; + InertiaBackwardCoef: Ixyz; + TiltInertiaMaxSpeed: Ixyz; + TiltStartSideBackSpeed: Ixyz; + TiltMaxSideBackSpeed: Ixyz; + TiltAcceleration: Ixyz; + AverageRotationFrameSpan: number; + SprintSpeedInertiaCurveMin: Ixyz; + SprintSpeedInertiaCurveMax: Ixyz; + SprintBrakeInertia: Ixyz; + SprintTransitionMotionPreservation: Ixyz; + WeaponFlipSpeed: Ixyz; + PreSprintAccelerationLimits: Ixyz; + SprintAccelerationLimits: Ixyz; + SideTime: Ixyz; + DiagonalTime: Ixyz; + MaxTimeWithoutInput: Ixyz; + MinDirectionBlendTime: number; + MoveTimeRange: Ixyz; + ProneDirectionAccelerationRange: Ixyz; + ProneSpeedAccelerationRange: Ixyz; + MinMovementAccelerationRangeRight: Ixyz; + MaxMovementAccelerationRangeRight: Ixyz; +} + +export interface IBallistic +{ + GlobalDamageDegradationCoefficient: number; } export interface IRepairSettings { - ItemEnhancementSettings: IItemEnhancementSettings - MinimumLevelToApplyBuff: number - RepairStrategies: IRepairStrategies - armorClassDivisor: number - durabilityPointCostArmor: number - durabilityPointCostGuns: number + ItemEnhancementSettings: IItemEnhancementSettings; + MinimumLevelToApplyBuff: number; + RepairStrategies: IRepairStrategies; + armorClassDivisor: number; + durabilityPointCostArmor: number; + durabilityPointCostGuns: number; } export interface IItemEnhancementSettings { - DamageReduction: IPriceModifier - MalfunctionProtections: IPriceModifier - WeaponSpread: IPriceModifier + DamageReduction: IPriceModifier; + MalfunctionProtections: IPriceModifier; + WeaponSpread: IPriceModifier; } export interface IPriceModifier { - PriceModifier: number + PriceModifier: number; } export interface IRepairStrategies { - Armor: IRepairStrategy - Firearms: IRepairStrategy + Armor: IRepairStrategy; + Firearms: IRepairStrategy; } export interface IRepairStrategy { - BuffTypes: string[] - Filter: string[] + BuffTypes: string[]; + Filter: string[]; } -export interface IBotPreset +export interface IBotPreset { - UseThis: boolean - Role: string - BotDifficulty: string - VisibleAngle: number - VisibleDistance: number - ScatteringPerMeter: number - HearingSense: number - SCATTERING_DIST_MODIF: number - MAX_AIMING_UPGRADE_BY_TIME: number - FIRST_CONTACT_ADD_SEC: number - COEF_IF_MOVE: number + UseThis: boolean; + Role: string; + BotDifficulty: string; + VisibleAngle: number; + VisibleDistance: number; + ScatteringPerMeter: number; + HearingSense: number; + SCATTERING_DIST_MODIF: number; + MAX_AIMING_UPGRADE_BY_TIME: number; + FIRST_CONTACT_ADD_SEC: number; + COEF_IF_MOVE: number; } export interface IAudioSettings { - AudioGroupPresets: IAudioGroupPreset[] + AudioGroupPresets: IAudioGroupPreset[]; } export interface IAudioGroupPreset { - AngleToAllowBinaural: number - DisabledBinauralByDistance: boolean - DistanceToAllowBinaural: number - GroupType: number - HeightToAllowBinaural: number - Name: string - OcclusionEnabled: boolean - OcclusionIntensity: number - OverallVolume: number - + AngleToAllowBinaural: number; + DisabledBinauralByDistance: boolean; + DistanceToAllowBinaural: number; + GroupType: number; + HeightToAllowBinaural: number; + Name: string; + OcclusionEnabled: boolean; + OcclusionIntensity: number; + OverallVolume: number; } -export interface IBotWeaponScattering +export interface IBotWeaponScattering { - Name: string - PriorityScatter1meter: number - PriorityScatter10meter: number - PriorityScatter100meter: number + Name: string; + PriorityScatter1meter: number; + PriorityScatter10meter: number; + PriorityScatter100meter: number; } -export interface IPreset +export interface IPreset { - _id: string - _type: string - _changeWeaponName: boolean - _name: string - _parent: string - _items: Item[] + _id: string; + _type: string; + _changeWeaponName: boolean; + _name: string; + _parent: string; + _items: Item[]; /** Default presets have this property */ - _encyclopedia?: string -} \ No newline at end of file + _encyclopedia?: string; +} diff --git a/project/src/models/eft/common/ILocation.ts b/project/src/models/eft/common/ILocation.ts index 57f22d9b..6c787905 100644 --- a/project/src/models/eft/common/ILocation.ts +++ b/project/src/models/eft/common/ILocation.ts @@ -1,28 +1,28 @@ import { ILocationBase } from "@spt-aki/models/eft/common/ILocationBase"; import { ILooseLoot } from "@spt-aki/models/eft/common/ILooseLoot"; -export interface ILocation +export interface ILocation { - base: ILocationBase + base: ILocationBase; looseLoot: ILooseLoot; - statics: IStaticContainer + statics: IStaticContainer; } export interface IStaticContainer { - containersGroups: Record - containers: Record< string, IContainerData> + containersGroups: Record; + containers: Record; } export interface IContainerMinMax { - minContainers: number - maxContainers: number - current?: number - chosenCount?: number + minContainers: number; + maxContainers: number; + current?: number; + chosenCount?: number; } export interface IContainerData { - groupId: string + groupId: string; } diff --git a/project/src/models/eft/common/ILocationBase.ts b/project/src/models/eft/common/ILocationBase.ts index f4e5e5ad..8bb63ea9 100644 --- a/project/src/models/eft/common/ILocationBase.ts +++ b/project/src/models/eft/common/ILocationBase.ts @@ -2,271 +2,269 @@ import { MinMax } from "@spt-aki/models/common/MinMax"; import { Ixyz } from "@spt-aki/models/eft/common/Ixyz"; /* eslint-disable @typescript-eslint/naming-convention */ -export interface ILocationBase +export interface ILocationBase { - AccessKeys: string[] - AirdropParameters: AirdropParameter[] - Area: number - AveragePlayTime: number - AveragePlayerLevel: number - Banners: Banner[] - BossLocationSpawn: BossLocationSpawn[] - BotAssault: number - BotEasy: number - BotHard: number - BotImpossible: number - BotLocationModifier: BotLocationModifier - BotMarksman: number - BotMax: number - BotMaxPlayer: number - BotMaxTimePlayer: number - BotNormal: number - BotSpawnCountStep: number - BotSpawnPeriodCheck: number - BotSpawnTimeOffMax: number - BotSpawnTimeOffMin: number - BotSpawnTimeOnMax: number - BotSpawnTimeOnMin: number - BotStart: number - BotStop: number - Description: string - DisabledForScav: boolean - DisabledScavExits: string - Enabled: boolean - EnableCoop: boolean - GlobalLootChanceModifier: number - GlobalContainerChanceModifier: number - IconX: number - IconY: number - Id: string - Insurance: boolean - IsSecret: boolean - Locked: boolean - Loot: any[] - MatchMakerMinPlayersByWaitTime: MinPlayerWaitTime[] - MaxBotPerZone: number - MaxDistToFreePoint: number - MaxPlayers: number - MinDistToExitPoint: number - MinDistToFreePoint: number - MinMaxBots: MinMaxBot[] - MinPlayers: number - MaxCoopGroup: number - Name: string - NonWaveGroupScenario: INonWaveGroupScenario - NewSpawn: boolean - OcculsionCullingEnabled: boolean - OldSpawn: boolean - OpenZones: string - Preview: Preview - PlayersRequestCount: number - RequiredPlayerLevel?: number - RequiredPlayerLevelMin?: number - RequiredPlayerLevelMax?: number - MinPlayerLvlAccessKeys: number - PmcMaxPlayersInGroup: number - ScavMaxPlayersInGroup: number - Rules: string - SafeLocation: boolean - Scene: Scene - SpawnPointParams: SpawnPointParam[] - UnixDateTime: number - _Id: string - doors: any[] - EscapeTimeLimit: number - EscapeTimeLimitCoop: number - exit_access_time: number - exit_count: number - exit_time: number - exits: Exit[] - filter_ex: string[] - limits: ILimit[] - matching_min_seconds: number - GenerateLocalLootCache: boolean - maxItemCountInLocation: MaxItemCountInLocation[] - sav_summon_seconds: number - tmp_location_field_remove_me: number - users_gather_seconds: number - users_spawn_seconds_n: number - users_spawn_seconds_n2: number - users_summon_seconds: number - waves: Wave[] + AccessKeys: string[]; + AirdropParameters: AirdropParameter[]; + Area: number; + AveragePlayTime: number; + AveragePlayerLevel: number; + Banners: Banner[]; + BossLocationSpawn: BossLocationSpawn[]; + BotAssault: number; + BotEasy: number; + BotHard: number; + BotImpossible: number; + BotLocationModifier: BotLocationModifier; + BotMarksman: number; + BotMax: number; + BotMaxPlayer: number; + BotMaxTimePlayer: number; + BotNormal: number; + BotSpawnCountStep: number; + BotSpawnPeriodCheck: number; + BotSpawnTimeOffMax: number; + BotSpawnTimeOffMin: number; + BotSpawnTimeOnMax: number; + BotSpawnTimeOnMin: number; + BotStart: number; + BotStop: number; + Description: string; + DisabledForScav: boolean; + DisabledScavExits: string; + Enabled: boolean; + EnableCoop: boolean; + GlobalLootChanceModifier: number; + GlobalContainerChanceModifier: number; + IconX: number; + IconY: number; + Id: string; + Insurance: boolean; + IsSecret: boolean; + Locked: boolean; + Loot: any[]; + MatchMakerMinPlayersByWaitTime: MinPlayerWaitTime[]; + MaxBotPerZone: number; + MaxDistToFreePoint: number; + MaxPlayers: number; + MinDistToExitPoint: number; + MinDistToFreePoint: number; + MinMaxBots: MinMaxBot[]; + MinPlayers: number; + MaxCoopGroup: number; + Name: string; + NonWaveGroupScenario: INonWaveGroupScenario; + NewSpawn: boolean; + OcculsionCullingEnabled: boolean; + OldSpawn: boolean; + OpenZones: string; + Preview: Preview; + PlayersRequestCount: number; + RequiredPlayerLevel?: number; + RequiredPlayerLevelMin?: number; + RequiredPlayerLevelMax?: number; + MinPlayerLvlAccessKeys: number; + PmcMaxPlayersInGroup: number; + ScavMaxPlayersInGroup: number; + Rules: string; + SafeLocation: boolean; + Scene: Scene; + SpawnPointParams: SpawnPointParam[]; + UnixDateTime: number; + _Id: string; + doors: any[]; + EscapeTimeLimit: number; + EscapeTimeLimitCoop: number; + exit_access_time: number; + exit_count: number; + exit_time: number; + exits: Exit[]; + filter_ex: string[]; + limits: ILimit[]; + matching_min_seconds: number; + GenerateLocalLootCache: boolean; + maxItemCountInLocation: MaxItemCountInLocation[]; + sav_summon_seconds: number; + tmp_location_field_remove_me: number; + users_gather_seconds: number; + users_spawn_seconds_n: number; + users_spawn_seconds_n2: number; + users_summon_seconds: number; + waves: Wave[]; } export interface INonWaveGroupScenario { - Chance: number - Enabled: boolean, - MaxToBeGroup: number - MinToBeGroup: number + Chance: number; + Enabled: boolean; + MaxToBeGroup: number; + MinToBeGroup: number; } export interface ILimit extends MinMax { - items: any[] + items: any[]; +} -} - -export interface AirdropParameter +export interface AirdropParameter { - AirdropPointDeactivateDistance: number - MinPlayersCountToSpawnAirdrop: number - PlaneAirdropChance: number - PlaneAirdropCooldownMax: number - PlaneAirdropCooldownMin: number - PlaneAirdropEnd: number - PlaneAirdropMax: number - PlaneAirdropStartMax: number - PlaneAirdropStartMin: number - UnsuccessfulTryPenalty: number + AirdropPointDeactivateDistance: number; + MinPlayersCountToSpawnAirdrop: number; + PlaneAirdropChance: number; + PlaneAirdropCooldownMax: number; + PlaneAirdropCooldownMin: number; + PlaneAirdropEnd: number; + PlaneAirdropMax: number; + PlaneAirdropStartMax: number; + PlaneAirdropStartMin: number; + UnsuccessfulTryPenalty: number; } - -export interface Banner + +export interface Banner { - id: string - pic: Pic + id: string; + pic: Pic; } - -export interface Pic + +export interface Pic { - path: string - rcid: string + path: string; + rcid: string; } - -export interface BossLocationSpawn + +export interface BossLocationSpawn { - BossChance: number - BossDifficult: string - BossEscortAmount: string - BossEscortDifficult: string - BossEscortType: string - BossName: string - BossPlayer: boolean - BossZone: string - RandomTimeSpawn: boolean - Time: number - TriggerId: string - TriggerName: string - Delay?: number - ForceSpawn?: boolean - IgnoreMaxBots?: boolean - Supports?: BossSupport[] - sptId?: string + BossChance: number; + BossDifficult: string; + BossEscortAmount: string; + BossEscortDifficult: string; + BossEscortType: string; + BossName: string; + BossPlayer: boolean; + BossZone: string; + RandomTimeSpawn: boolean; + Time: number; + TriggerId: string; + TriggerName: string; + Delay?: number; + ForceSpawn?: boolean; + IgnoreMaxBots?: boolean; + Supports?: BossSupport[]; + sptId?: string; } export interface BossSupport { - BossEscortAmount: string - BossEscortDifficult: string[] - BossEscortType: string + BossEscortAmount: string; + BossEscortDifficult: string[]; + BossEscortType: string; } - -export interface BotLocationModifier + +export interface BotLocationModifier { - AccuracySpeed: number - DistToActivate: number - DistToPersueAxemanCoef: number - DistToSleep: number - GainSight: number - KhorovodChance: number - MagnetPower: number - MarksmanAccuratyCoef: number - Scattering: number - VisibleDistance: number + AccuracySpeed: number; + DistToActivate: number; + DistToPersueAxemanCoef: number; + DistToSleep: number; + GainSight: number; + KhorovodChance: number; + MagnetPower: number; + MarksmanAccuratyCoef: number; + Scattering: number; + VisibleDistance: number; } - + export interface MinMaxBot extends MinMax { - WildSpawnType: WildSpawnType | string + WildSpawnType: WildSpawnType | string; } export interface MinPlayerWaitTime { - minPlayers: number - time: number -} - -export interface Preview -{ - path: string - rcid: string -} - -export interface Scene -{ - path: string - rcid: string -} - -export interface SpawnPointParam -{ - BotZoneName: string - Categories: string[] - ColliderParams: ColliderParams - CorePointId: number - DelayToCanSpawnSec: number - Id: string - Infiltration: string - Position: Ixyz - Rotation: number - Sides: string[] -} - -export interface ColliderParams -{ - _parent: string - _props: Props -} - -export interface Props -{ - Center: Ixyz - Radius: number + minPlayers: number; + time: number; } - -export interface Exit +export interface Preview { - Chance: number - Count: number - EntryPoints: string - ExfiltrationTime: number - ExfiltrationType: string - RequiredSlot?: string - Id: string - MaxTime: number - MinTime: number - Name: string - PassageRequirement: string - PlayersCount: number - RequirementTip: string + path: string; + rcid: string; } - -export interface MaxItemCountInLocation + +export interface Scene { - TemplateId: string - Value: number + path: string; + rcid: string; } - -export interface Wave + +export interface SpawnPointParam { - BotPreset: string - BotSide: string - SpawnPoints: string - WildSpawnType: WildSpawnType - isPlayers: boolean - number: number - slots_max: number - slots_min: number - time_max: number - time_min: number - sptId?: string - ChanceGroup?: number + BotZoneName: string; + Categories: string[]; + ColliderParams: ColliderParams; + CorePointId: number; + DelayToCanSpawnSec: number; + Id: string; + Infiltration: string; + Position: Ixyz; + Rotation: number; + Sides: string[]; +} + +export interface ColliderParams +{ + _parent: string; + _props: Props; +} + +export interface Props +{ + Center: Ixyz; + Radius: number; +} + +export interface Exit +{ + Chance: number; + Count: number; + EntryPoints: string; + ExfiltrationTime: number; + ExfiltrationType: string; + RequiredSlot?: string; + Id: string; + MaxTime: number; + MinTime: number; + Name: string; + PassageRequirement: string; + PlayersCount: number; + RequirementTip: string; +} + +export interface MaxItemCountInLocation +{ + TemplateId: string; + Value: number; +} + +export interface Wave +{ + BotPreset: string; + BotSide: string; + SpawnPoints: string; + WildSpawnType: WildSpawnType; + isPlayers: boolean; + number: number; + slots_max: number; + slots_min: number; + time_max: number; + time_min: number; + sptId?: string; + ChanceGroup?: number; } export enum WildSpawnType - { +{ ASSAULT = "assault", MARKSMAN = "marksman", - PMCBOT = "pmcbot" -} \ No newline at end of file + PMCBOT = "pmcbot", +} diff --git a/project/src/models/eft/common/ILocationsSourceDestinationBase.ts b/project/src/models/eft/common/ILocationsSourceDestinationBase.ts index aa9ac14e..e55949b5 100644 --- a/project/src/models/eft/common/ILocationsSourceDestinationBase.ts +++ b/project/src/models/eft/common/ILocationsSourceDestinationBase.ts @@ -1,13 +1,13 @@ import { ILocations } from "@spt-aki/models/spt/server/ILocations"; -export interface ILocationsGenerateAllResponse +export interface ILocationsGenerateAllResponse { - locations: ILocations - paths: Path[] + locations: ILocations; + paths: Path[]; } -export interface Path +export interface Path { - Source: string - Destination: string -} \ No newline at end of file + Source: string; + Destination: string; +} diff --git a/project/src/models/eft/common/ILooseLoot.ts b/project/src/models/eft/common/ILooseLoot.ts index b18e41fe..8790c795 100644 --- a/project/src/models/eft/common/ILooseLoot.ts +++ b/project/src/models/eft/common/ILooseLoot.ts @@ -1,56 +1,56 @@ import { Ixyz } from "@spt-aki/models/eft/common/Ixyz"; import { Item } from "@spt-aki/models/eft/common/tables/IItem"; -export interface ILooseLoot +export interface ILooseLoot { spawnpointCount: SpawnpointCount; spawnpointsForced: SpawnpointsForced[]; spawnpoints: Spawnpoint[]; } -export interface SpawnpointCount +export interface SpawnpointCount { - mean: number - std: number + mean: number; + std: number; } -export interface SpawnpointsForced +export interface SpawnpointsForced { - locationId: string - probability: number - template: SpawnpointTemplate + locationId: string; + probability: number; + template: SpawnpointTemplate; } -export interface SpawnpointTemplate +export interface SpawnpointTemplate { - Id: string - IsContainer: boolean - useGravity: boolean - randomRotation: boolean - Position: Ixyz - Rotation: Ixyz - IsAlwaysSpawn: boolean - IsGroupPosition: boolean - GroupPositions: any[] - Root: string - Items: Item[] + Id: string; + IsContainer: boolean; + useGravity: boolean; + randomRotation: boolean; + Position: Ixyz; + Rotation: Ixyz; + IsAlwaysSpawn: boolean; + IsGroupPosition: boolean; + GroupPositions: any[]; + Root: string; + Items: Item[]; } -export interface Spawnpoint +export interface Spawnpoint { - locationId: string - probability: number - template: SpawnpointTemplate - itemDistribution: ItemDistribution[] + locationId: string; + probability: number; + template: SpawnpointTemplate; + itemDistribution: ItemDistribution[]; } -export interface ItemDistribution +export interface ItemDistribution { - composedKey: ComposedKey - relativeProbability: number + composedKey: ComposedKey; + relativeProbability: number; } export interface ComposedKey { - key: string + key: string; } diff --git a/project/src/models/eft/common/IMetricsTableData.ts b/project/src/models/eft/common/IMetricsTableData.ts index cf059691..c2da53e9 100644 --- a/project/src/models/eft/common/IMetricsTableData.ts +++ b/project/src/models/eft/common/IMetricsTableData.ts @@ -1,8 +1,8 @@ -export interface IMetricsTableData +export interface IMetricsTableData { - Keys: number[] - NetProcessingBins: number[] - RenderBins: number[] - GameUpdateBins: number[] - MemoryMeasureInterval: number -} \ No newline at end of file + Keys: number[]; + NetProcessingBins: number[]; + RenderBins: number[]; + GameUpdateBins: number[]; + MemoryMeasureInterval: number; +} diff --git a/project/src/models/eft/common/IPmcData.ts b/project/src/models/eft/common/IPmcData.ts index ec0fb4cf..84219b79 100644 --- a/project/src/models/eft/common/IPmcData.ts +++ b/project/src/models/eft/common/IPmcData.ts @@ -6,5 +6,5 @@ export interface IPmcData extends IBotBase export interface IPostRaidPmcData extends IBotBase { /** Only found in profile we get from client post raid */ - EftStats: IEftStats -} \ No newline at end of file + EftStats: IEftStats; +} diff --git a/project/src/models/eft/common/Ixyz.ts b/project/src/models/eft/common/Ixyz.ts index 3b5023f6..8b43d332 100644 --- a/project/src/models/eft/common/Ixyz.ts +++ b/project/src/models/eft/common/Ixyz.ts @@ -1,5 +1,4 @@ - -export interface Ixyz +export interface Ixyz { x: number; y: number; diff --git a/project/src/models/eft/common/request/IBaseInteractionRequestData.ts b/project/src/models/eft/common/request/IBaseInteractionRequestData.ts index 20c57fdd..84a80d8e 100644 --- a/project/src/models/eft/common/request/IBaseInteractionRequestData.ts +++ b/project/src/models/eft/common/request/IBaseInteractionRequestData.ts @@ -1,12 +1,12 @@ -export interface IBaseInteractionRequestData +export interface IBaseInteractionRequestData { - Action: string - fromOwner?: OwnerInfo - toOwner?: OwnerInfo + Action: string; + fromOwner?: OwnerInfo; + toOwner?: OwnerInfo; } -export interface OwnerInfo +export interface OwnerInfo { - id: string - type: string -} \ No newline at end of file + id: string; + type: string; +} diff --git a/project/src/models/eft/common/tables/IBotBase.ts b/project/src/models/eft/common/tables/IBotBase.ts index f279df12..9be6afc1 100644 --- a/project/src/models/eft/common/tables/IBotBase.ts +++ b/project/src/models/eft/common/tables/IBotBase.ts @@ -5,514 +5,512 @@ import { HideoutAreas } from "@spt-aki/models/enums/HideoutAreas"; import { MemberCategory } from "@spt-aki/models/enums/MemberCategory"; import { QuestStatus } from "@spt-aki/models/enums/QuestStatus"; -export interface IBotBase +export interface IBotBase { - - _id: string - aid: number + _id: string; + aid: number; /** SPT property - use to store player id - TODO - move to AID ( account id as guid of choice) */ - sessionId: string - savage?: string - Info: Info - Customization: Customization - Health: Health - Inventory: Inventory - Skills: Skills - Stats: Stats - Encyclopedia: Record - ConditionCounters: ConditionCounters - BackendCounters: Record - InsuredItems: InsuredItem[] - Hideout: Hideout - Quests: IQuestStatus[] - TradersInfo: Record - UnlockedInfo: IUnlockedInfo - RagfairInfo: RagfairInfo - RepeatableQuests: IPmcDataRepeatableQuest[] - Bonuses: Bonus[] - Notes: Notes - CarExtractCounts: CarExtractCounts - SurvivorClass: SurvivorClass - WishList: string[] + sessionId: string; + savage?: string; + Info: Info; + Customization: Customization; + Health: Health; + Inventory: Inventory; + Skills: Skills; + Stats: Stats; + Encyclopedia: Record; + ConditionCounters: ConditionCounters; + BackendCounters: Record; + InsuredItems: InsuredItem[]; + Hideout: Hideout; + Quests: IQuestStatus[]; + TradersInfo: Record; + UnlockedInfo: IUnlockedInfo; + RagfairInfo: RagfairInfo; + RepeatableQuests: IPmcDataRepeatableQuest[]; + Bonuses: Bonus[]; + Notes: Notes; + CarExtractCounts: CarExtractCounts; + SurvivorClass: SurvivorClass; + WishList: string[]; /** SPT specific property used during bot generation in raid */ - sptIsPmc?: boolean + sptIsPmc?: boolean; } export interface IUnlockedInfo { - unlockedProductionRecipe: string[] + unlockedProductionRecipe: string[]; } -export interface Info +export interface Info { - EntryPoint: string - Nickname: string - LowerNickname: string - Side: string - SquadInviteRestriction: boolean - Voice: string - Level: number - Experience: number - RegistrationDate: number - GameVersion: string - AccountType: number - MemberCategory: MemberCategory - lockedMoveCommands: boolean - SavageLockTime: number - LastTimePlayedAsSavage: number - Settings: Settings - NicknameChangeDate: number - NeedWipeOptions: any[] - lastCompletedWipe: LastCompleted - Bans: IBan[] - BannedState: boolean - BannedUntil: number - IsStreamerModeAvailable: boolean - lastCompletedEvent?: LastCompleted + EntryPoint: string; + Nickname: string; + LowerNickname: string; + Side: string; + SquadInviteRestriction: boolean; + Voice: string; + Level: number; + Experience: number; + RegistrationDate: number; + GameVersion: string; + AccountType: number; + MemberCategory: MemberCategory; + lockedMoveCommands: boolean; + SavageLockTime: number; + LastTimePlayedAsSavage: number; + Settings: Settings; + NicknameChangeDate: number; + NeedWipeOptions: any[]; + lastCompletedWipe: LastCompleted; + Bans: IBan[]; + BannedState: boolean; + BannedUntil: number; + IsStreamerModeAvailable: boolean; + lastCompletedEvent?: LastCompleted; } -export interface Settings +export interface Settings { - Role: string - BotDifficulty: string - Experience: number - StandingForKill: number - AggressorBonus: number + Role: string; + BotDifficulty: string; + Experience: number; + StandingForKill: number; + AggressorBonus: number; } export interface IBan { - type: BanType - dateTime: number + type: BanType; + dateTime: number; } export enum BanType - { +{ CHAT = 0, RAGFAIR = 1, VOIP = 2, TRADING = 3, ONLINE = 4, FRIENDS = 5, - CHANGE_NICKNAME = 6 + CHANGE_NICKNAME = 6, } -export interface Customization +export interface Customization { - Head: string - Body: string - Feet: string - Hands: string + Head: string; + Body: string; + Feet: string; + Hands: string; } -export interface Health +export interface Health { - Hydration: CurrentMax - Energy: CurrentMax - Temperature: CurrentMax - BodyParts: BodyPartsHealth - UpdateTime: number + Hydration: CurrentMax; + Energy: CurrentMax; + Temperature: CurrentMax; + BodyParts: BodyPartsHealth; + UpdateTime: number; } -export interface BodyPartsHealth +export interface BodyPartsHealth { - Head: BodyPartHealth - Chest: BodyPartHealth - Stomach: BodyPartHealth - LeftArm: BodyPartHealth - RightArm: BodyPartHealth - LeftLeg: BodyPartHealth - RightLeg: BodyPartHealth + Head: BodyPartHealth; + Chest: BodyPartHealth; + Stomach: BodyPartHealth; + LeftArm: BodyPartHealth; + RightArm: BodyPartHealth; + LeftLeg: BodyPartHealth; + RightLeg: BodyPartHealth; } -export interface BodyPartHealth +export interface BodyPartHealth { - Health: CurrentMax - Effects?: Record + Health: CurrentMax; + Effects?: Record; } export interface BodyPartEffectProperties { - Time: number + Time: number; } -export interface CurrentMax +export interface CurrentMax { - Current: number - Maximum: number + Current: number; + Maximum: number; } -export interface Inventory +export interface Inventory { - items: Item[] - equipment: string - stash: string - sortingTable: string - questRaidItems: string - questStashItems: string + items: Item[]; + equipment: string; + stash: string; + sortingTable: string; + questRaidItems: string; + questStashItems: string; /** Key is hideout area enum numeric as string e.g. "24", value is area _id */ - hideoutAreaStashes: Record - fastPanel: Record + hideoutAreaStashes: Record; + fastPanel: Record; } export interface IBaseJsonSkills { - Common: Record - Mastering: Record - Points: number + Common: Record; + Mastering: Record; + Points: number; } -export interface Skills +export interface Skills { - Common: Common[] - Mastering: Mastering[] - Points: number + Common: Common[]; + Mastering: Mastering[]; + Points: number; } export interface IBaseSkill { - Id: string - Progress: number - max?: number - min?: number + Id: string; + Progress: number; + max?: number; + min?: number; } export interface Common extends IBaseSkill { - PointsEarnedDuringSession?: number - LastAccess?: number + PointsEarnedDuringSession?: number; + LastAccess?: number; } export interface Mastering extends IBaseSkill {} -export interface Stats +export interface Stats { - Eft: IEftStats + Eft: IEftStats; } export interface IEftStats { - CarriedQuestItems: string[] - Victims: Victim[] - TotalSessionExperience: number - LastSessionDate: number - SessionCounters: SessionCounters - OverallCounters: OverallCounters - SessionExperienceMult?: number - ExperienceBonusMult?: number - Aggressor?: Aggressor - DroppedItems?: IDroppedItem[] - FoundInRaidItems?: FoundInRaidItem[] - DamageHistory?: DamageHistory - DeathCause?: DeathCause - LastPlayerState?: LastPlayerState - TotalInGameTime: number - SurvivorClass?: string + CarriedQuestItems: string[]; + Victims: Victim[]; + TotalSessionExperience: number; + LastSessionDate: number; + SessionCounters: SessionCounters; + OverallCounters: OverallCounters; + SessionExperienceMult?: number; + ExperienceBonusMult?: number; + Aggressor?: Aggressor; + DroppedItems?: IDroppedItem[]; + FoundInRaidItems?: FoundInRaidItem[]; + DamageHistory?: DamageHistory; + DeathCause?: DeathCause; + LastPlayerState?: LastPlayerState; + TotalInGameTime: number; + SurvivorClass?: string; } export interface IDroppedItem { - QuestId: string - ItemId: string - ZoneId: string + QuestId: string; + ItemId: string; + ZoneId: string; } export interface FoundInRaidItem { - QuestId: string - ItemId: string + QuestId: string; + ItemId: string; } -export interface Victim +export interface Victim { - AccountId: string - ProfileId: string - Name: string - Side: string - BodyPart: string - Time: string - Distance: number - Level: number - Weapon: string - Role: string + AccountId: string; + ProfileId: string; + Name: string; + Side: string; + BodyPart: string; + Time: string; + Distance: number; + Level: number; + Weapon: string; + Role: string; } -export interface SessionCounters +export interface SessionCounters { - Items: CounterKeyValue[] + Items: CounterKeyValue[]; } -export interface OverallCounters +export interface OverallCounters { - Items: CounterKeyValue[] + Items: CounterKeyValue[]; } -export interface CounterKeyValue +export interface CounterKeyValue { - Key: string[] - Value: number + Key: string[]; + Value: number; } -export interface ConditionCounters +export interface ConditionCounters { - Counters: Counter[] + Counters: Counter[]; } -export interface Counter +export interface Counter { - id: string - value: number - qid: string + id: string; + value: number; + qid: string; } -export interface Aggressor +export interface Aggressor { - AccountId: string - ProfileId: string - MainProfileNickname: string - Name: string - Side: string - BodyPart: string - HeadSegment: string - WeaponName: string - Category: string + AccountId: string; + ProfileId: string; + MainProfileNickname: string; + Name: string; + Side: string; + BodyPart: string; + HeadSegment: string; + WeaponName: string; + Category: string; } -export interface DamageHistory +export interface DamageHistory { - LethalDamagePart: string - LethalDamage: LethalDamage - BodyParts: BodyPartsDamageHistory + LethalDamagePart: string; + LethalDamage: LethalDamage; + BodyParts: BodyPartsDamageHistory; } -export interface LethalDamage +export interface LethalDamage { - Amount: number - Type: string - SourceId: string - OverDamageFrom: string - Blunt: boolean - ImpactsCount: number + Amount: number; + Type: string; + SourceId: string; + OverDamageFrom: string; + Blunt: boolean; + ImpactsCount: number; } -export interface BodyPartsDamageHistory +export interface BodyPartsDamageHistory { - Head: DamageStats[] - Chest: DamageStats[] - Stomach: DamageStats[] - LeftArm: DamageStats[] - RightArm: DamageStats[] - LeftLeg: DamageStats[] - RightLeg: DamageStats[] - Common: DamageStats[] + Head: DamageStats[]; + Chest: DamageStats[]; + Stomach: DamageStats[]; + LeftArm: DamageStats[]; + RightArm: DamageStats[]; + LeftLeg: DamageStats[]; + RightLeg: DamageStats[]; + Common: DamageStats[]; } -export interface DamageStats +export interface DamageStats { - Amount: number - Type: string - SourceId: string - OverDamageFrom: string - Blunt: boolean - ImpactsCount: number + Amount: number; + Type: string; + SourceId: string; + OverDamageFrom: string; + Blunt: boolean; + ImpactsCount: number; } -export interface DeathCause +export interface DeathCause { - DamageType: string - Side: string - Role: string - WeaponId: string + DamageType: string; + Side: string; + Role: string; + WeaponId: string; } export interface LastPlayerState { - Info: LastPlayerStateInfo - Customization: Record - Equipment: any + Info: LastPlayerStateInfo; + Customization: Record; + Equipment: any; } export interface LastPlayerStateInfo { - Nickname: string - Side: string - Level: number - MemberCategory: MemberCategory + Nickname: string; + Side: string; + Level: number; + MemberCategory: MemberCategory; } -export interface BackendCounter +export interface BackendCounter { - id: string - qid?: string - value: number + id: string; + qid?: string; + value: number; } -export interface InsuredItem +export interface InsuredItem { /** Trader Id item was insured by */ - tid: string - itemId: string + tid: string; + itemId: string; } -export interface Hideout +export interface Hideout { - Production: Record - Areas: HideoutArea[] - Improvement: Record - Seed: number - sptUpdateLastRunTimestamp: number + Production: Record; + Areas: HideoutArea[]; + Improvement: Record; + Seed: number; + sptUpdateLastRunTimestamp: number; } export interface IHideoutImprovement { - completed: boolean - improveCompleteTimestamp: number + completed: boolean; + improveCompleteTimestamp: number; } export interface Productive { - Products: Product[] + Products: Product[]; /** Seconds passed of production */ - Progress?: number + Progress?: number; /** Is craft in some state of being worked on by client (crafting/ready to pick up) */ - inProgress?: boolean - StartTimestamp?: number - SkipTime?: number + inProgress?: boolean; + StartTimestamp?: number; + SkipTime?: number; /** Seconds needed to fully craft */ - ProductionTime?: number - GivenItemsInStart?: string[] - Interrupted?: boolean + ProductionTime?: number; + GivenItemsInStart?: string[]; + Interrupted?: boolean; /** Used in hideout production.json */ - needFuelForAllProductionTime?: boolean + needFuelForAllProductionTime?: boolean; /** Used when sending data to client */ - NeedFuelForAllProductionTime?: boolean - sptIsScavCase?: boolean + NeedFuelForAllProductionTime?: boolean; + sptIsScavCase?: boolean; } -export interface Production extends Productive +export interface Production extends Productive { - RecipeId: string - SkipTime: number - ProductionTime: number + RecipeId: string; + SkipTime: number; + ProductionTime: number; } -export interface ScavCase extends Productive +export interface ScavCase extends Productive { - RecipeId: string + RecipeId: string; } -export interface Product +export interface Product { - _id: string - _tpl: string - upd?: Upd + _id: string; + _tpl: string; + upd?: Upd; } -export interface HideoutArea +export interface HideoutArea { - type: HideoutAreas - level: number - active: boolean - passiveBonusesEnabled: boolean - completeTime: number - constructing: boolean - slots: HideoutSlot[] - lastRecipe: string + type: HideoutAreas; + level: number; + active: boolean; + passiveBonusesEnabled: boolean; + completeTime: number; + constructing: boolean; + slots: HideoutSlot[]; + lastRecipe: string; } -export interface HideoutSlot +export interface HideoutSlot { /** SPT specific value to keep track of what index this slot is (0,1,2,3 etc) */ - locationIndex: number - item?: HideoutItem[] + locationIndex: number; + item?: HideoutItem[]; } -export interface HideoutItem +export interface HideoutItem { - _id: string - _tpl: string - upd?: Upd + _id: string; + _tpl: string; + upd?: Upd; } export interface LastCompleted { - $oid: string + $oid: string; } -export interface Notes +export interface Notes { - Notes: Note[] + Notes: Note[]; } -export interface CarExtractCounts +export interface CarExtractCounts { - } export enum SurvivorClass - { +{ UNKNOWN = 0, NEUTRALIZER = 1, MARAUDER = 2, PARAMEDIC = 3, - SURVIVOR = 4 + SURVIVOR = 4, } -export interface IQuestStatus +export interface IQuestStatus { - qid: string - startTime: number - status: QuestStatus - statusTimers?: Record + qid: string; + startTime: number; + status: QuestStatus; + statusTimers?: Record; /** SPT specific property */ - completedConditions?: string[] - availableAfter?: number + completedConditions?: string[]; + availableAfter?: number; } -export interface TraderInfo +export interface TraderInfo { - loyaltyLevel: number - salesSum: number - standing: number - nextResupply: number - unlocked: boolean - disabled: boolean + loyaltyLevel: number; + salesSum: number; + standing: number; + nextResupply: number; + unlocked: boolean; + disabled: boolean; } /** This object is sent to the client as part of traderRelations */ export interface TraderData { - salesSum: number - standing: number - loyalty: number - unlocked: boolean - disabled: boolean + salesSum: number; + standing: number; + loyalty: number; + unlocked: boolean; + disabled: boolean; } -export interface RagfairInfo +export interface RagfairInfo { - rating: number - isRatingGrowing: boolean - offers: IRagfairOffer[] + rating: number; + isRatingGrowing: boolean; + offers: IRagfairOffer[]; } -export interface Bonus +export interface Bonus { - id?: string - type: string - templateId?: string - passive?: boolean - production?: boolean - visible?: boolean - value?: number - icon?: string - filter?: string[] - skillType?: string + id?: string; + type: string; + templateId?: string; + passive?: boolean; + production?: boolean; + visible?: boolean; + value?: number; + icon?: string; + filter?: string[]; + skillType?: string; } -export interface Note +export interface Note { - Time: number, - Text: string -} \ No newline at end of file + Time: number; + Text: string; +} diff --git a/project/src/models/eft/common/tables/IBotCore.ts b/project/src/models/eft/common/tables/IBotCore.ts index af14541a..8499e840 100644 --- a/project/src/models/eft/common/tables/IBotCore.ts +++ b/project/src/models/eft/common/tables/IBotCore.ts @@ -1,135 +1,135 @@ /* eslint-disable @typescript-eslint/naming-convention */ -export interface IBotCore +export interface IBotCore { - SAVAGE_KILL_DIST: number - SOUND_DOOR_BREACH_METERS: number - SOUND_DOOR_OPEN_METERS: number - STEP_NOISE_DELTA: number - JUMP_NOISE_DELTA: number - GUNSHOT_SPREAD: number - GUNSHOT_SPREAD_SILENCE: number - BASE_WALK_SPEREAD2: number - MOVE_SPEED_COEF_MAX: number - SPEED_SERV_SOUND_COEF_A: number - SPEED_SERV_SOUND_COEF_B: number - G: number - STAY_COEF: number - SIT_COEF: number - LAY_COEF: number - MAX_ITERATIONS: number - START_DIST_TO_COV: number - MAX_DIST_TO_COV: number - STAY_HEIGHT: number - CLOSE_POINTS: number - COUNT_TURNS: number - SIMPLE_POINT_LIFE_TIME_SEC: number - DANGER_POINT_LIFE_TIME_SEC: number - DANGER_POWER: number - COVER_DIST_CLOSE: number - GOOD_DIST_TO_POINT: number - COVER_TOOFAR_FROM_BOSS: number - COVER_TOOFAR_FROM_BOSS_SQRT: number - MAX_Y_DIFF_TO_PROTECT: number - FLARE_POWER: number - MOVE_COEF: number - PRONE_POSE: number - LOWER_POSE: number - MAX_POSE: number - FLARE_TIME: number - MAX_REQUESTS__PER_GROUP: number - UPDATE_GOAL_TIMER_SEC: number - DIST_NOT_TO_GROUP: number - DIST_NOT_TO_GROUP_SQR: number - LAST_SEEN_POS_LIFETIME: number - DELTA_GRENADE_START_TIME: number - DELTA_GRENADE_END_TIME: number - DELTA_GRENADE_RUN_DIST: number - DELTA_GRENADE_RUN_DIST_SQRT: number - PATROL_MIN_LIGHT_DIST: number - HOLD_MIN_LIGHT_DIST: number - STANDART_BOT_PAUSE_DOOR: number - ARMOR_CLASS_COEF: number - SHOTGUN_POWER: number - RIFLE_POWER: number - PISTOL_POWER: number - SMG_POWER: number - SNIPE_POWER: number - GESTUS_PERIOD_SEC: number - GESTUS_AIMING_DELAY: number - GESTUS_REQUEST_LIFETIME: number - GESTUS_FIRST_STAGE_MAX_TIME: number - GESTUS_SECOND_STAGE_MAX_TIME: number - GESTUS_MAX_ANSWERS: number - GESTUS_FUCK_TO_SHOOT: number - GESTUS_DIST_ANSWERS: number - GESTUS_DIST_ANSWERS_SQRT: number - GESTUS_ANYWAY_CHANCE: number - TALK_DELAY: number - CAN_SHOOT_TO_HEAD: boolean - CAN_TILT: boolean - TILT_CHANCE: number - MIN_BLOCK_DIST: number - MIN_BLOCK_TIME: number - COVER_SECONDS_AFTER_LOSE_VISION: number - MIN_ARG_COEF: number - MAX_ARG_COEF: number - DEAD_AGR_DIST: number - MAX_DANGER_CARE_DIST_SQRT: number - MAX_DANGER_CARE_DIST: number - MIN_MAX_PERSON_SEARCH: number - PERCENT_PERSON_SEARCH: number - LOOK_ANYSIDE_BY_WALL_SEC_OF_ENEMY: number - CLOSE_TO_WALL_ROTATE_BY_WALL_SQRT: number - SHOOT_TO_CHANGE_RND_PART_MIN: number - SHOOT_TO_CHANGE_RND_PART_MAX: number - SHOOT_TO_CHANGE_RND_PART_DELTA: number - FORMUL_COEF_DELTA_DIST: number - FORMUL_COEF_DELTA_SHOOT: number - FORMUL_COEF_DELTA_FRIEND_COVER: number - SUSPETION_POINT_DIST_CHECK: number - MAX_BASE_REQUESTS_PER_PLAYER: number - MAX_HOLD_REQUESTS_PER_PLAYER: number - MAX_GO_TO_REQUESTS_PER_PLAYER: number - MAX_COME_WITH_ME_REQUESTS_PER_PLAYER: number - CORE_POINT_MAX_VALUE: number - CORE_POINTS_MAX: number - CORE_POINTS_MIN: number - BORN_POISTS_FREE_ONLY_FAREST_BOT: boolean - BORN_POINSTS_FREE_ONLY_FAREST_PLAYER: boolean - SCAV_GROUPS_TOGETHER: boolean - LAY_DOWN_ANG_SHOOT: number - HOLD_REQUEST_TIME_SEC: number - TRIGGERS_DOWN_TO_RUN_WHEN_MOVE: number - MIN_DIST_TO_RUN_WHILE_ATTACK_MOVING: number - MIN_DIST_TO_RUN_WHILE_ATTACK_MOVING_OTHER_ENEMIS: number - MIN_DIST_TO_STOP_RUN: number - JUMP_SPREAD_DIST: number - LOOK_TIMES_TO_KILL: number - COME_INSIDE_TIMES: number - TOTAL_TIME_KILL: number - TOTAL_TIME_KILL_AFTER_WARN: number - MOVING_AIM_COEF: number - VERTICAL_DIST_TO_IGNORE_SOUND: number - DEFENCE_LEVEL_SHIFT: number - MIN_DIST_CLOSE_DEF: number - USE_ID_PRIOR_WHO_GO: boolean - SMOKE_GRENADE_RADIUS_COEF: number - GRENADE_PRECISION: number - MAX_WARNS_BEFORE_KILL: number - CARE_ENEMY_ONLY_TIME: number - MIDDLE_POINT_COEF: number - MAIN_TACTIC_ONLY_ATTACK: boolean - LAST_DAMAGE_ACTIVE: number - SHALL_DIE_IF_NOT_INITED: boolean - CHECK_BOT_INIT_TIME_SEC: number - WEAPON_ROOT_Y_OFFSET: number - DELTA_SUPRESS_DISTANCE_SQRT: number - DELTA_SUPRESS_DISTANCE: number - WAVE_COEF_LOW: number - WAVE_COEF_MID: number - WAVE_COEF_HIGH: number - WAVE_COEF_HORDE: number - WAVE_ONLY_AS_ONLINE: boolean - LOCAL_BOTS_COUNT: number - AXE_MAN_KILLS_END: number -} \ No newline at end of file + SAVAGE_KILL_DIST: number; + SOUND_DOOR_BREACH_METERS: number; + SOUND_DOOR_OPEN_METERS: number; + STEP_NOISE_DELTA: number; + JUMP_NOISE_DELTA: number; + GUNSHOT_SPREAD: number; + GUNSHOT_SPREAD_SILENCE: number; + BASE_WALK_SPEREAD2: number; + MOVE_SPEED_COEF_MAX: number; + SPEED_SERV_SOUND_COEF_A: number; + SPEED_SERV_SOUND_COEF_B: number; + G: number; + STAY_COEF: number; + SIT_COEF: number; + LAY_COEF: number; + MAX_ITERATIONS: number; + START_DIST_TO_COV: number; + MAX_DIST_TO_COV: number; + STAY_HEIGHT: number; + CLOSE_POINTS: number; + COUNT_TURNS: number; + SIMPLE_POINT_LIFE_TIME_SEC: number; + DANGER_POINT_LIFE_TIME_SEC: number; + DANGER_POWER: number; + COVER_DIST_CLOSE: number; + GOOD_DIST_TO_POINT: number; + COVER_TOOFAR_FROM_BOSS: number; + COVER_TOOFAR_FROM_BOSS_SQRT: number; + MAX_Y_DIFF_TO_PROTECT: number; + FLARE_POWER: number; + MOVE_COEF: number; + PRONE_POSE: number; + LOWER_POSE: number; + MAX_POSE: number; + FLARE_TIME: number; + MAX_REQUESTS__PER_GROUP: number; + UPDATE_GOAL_TIMER_SEC: number; + DIST_NOT_TO_GROUP: number; + DIST_NOT_TO_GROUP_SQR: number; + LAST_SEEN_POS_LIFETIME: number; + DELTA_GRENADE_START_TIME: number; + DELTA_GRENADE_END_TIME: number; + DELTA_GRENADE_RUN_DIST: number; + DELTA_GRENADE_RUN_DIST_SQRT: number; + PATROL_MIN_LIGHT_DIST: number; + HOLD_MIN_LIGHT_DIST: number; + STANDART_BOT_PAUSE_DOOR: number; + ARMOR_CLASS_COEF: number; + SHOTGUN_POWER: number; + RIFLE_POWER: number; + PISTOL_POWER: number; + SMG_POWER: number; + SNIPE_POWER: number; + GESTUS_PERIOD_SEC: number; + GESTUS_AIMING_DELAY: number; + GESTUS_REQUEST_LIFETIME: number; + GESTUS_FIRST_STAGE_MAX_TIME: number; + GESTUS_SECOND_STAGE_MAX_TIME: number; + GESTUS_MAX_ANSWERS: number; + GESTUS_FUCK_TO_SHOOT: number; + GESTUS_DIST_ANSWERS: number; + GESTUS_DIST_ANSWERS_SQRT: number; + GESTUS_ANYWAY_CHANCE: number; + TALK_DELAY: number; + CAN_SHOOT_TO_HEAD: boolean; + CAN_TILT: boolean; + TILT_CHANCE: number; + MIN_BLOCK_DIST: number; + MIN_BLOCK_TIME: number; + COVER_SECONDS_AFTER_LOSE_VISION: number; + MIN_ARG_COEF: number; + MAX_ARG_COEF: number; + DEAD_AGR_DIST: number; + MAX_DANGER_CARE_DIST_SQRT: number; + MAX_DANGER_CARE_DIST: number; + MIN_MAX_PERSON_SEARCH: number; + PERCENT_PERSON_SEARCH: number; + LOOK_ANYSIDE_BY_WALL_SEC_OF_ENEMY: number; + CLOSE_TO_WALL_ROTATE_BY_WALL_SQRT: number; + SHOOT_TO_CHANGE_RND_PART_MIN: number; + SHOOT_TO_CHANGE_RND_PART_MAX: number; + SHOOT_TO_CHANGE_RND_PART_DELTA: number; + FORMUL_COEF_DELTA_DIST: number; + FORMUL_COEF_DELTA_SHOOT: number; + FORMUL_COEF_DELTA_FRIEND_COVER: number; + SUSPETION_POINT_DIST_CHECK: number; + MAX_BASE_REQUESTS_PER_PLAYER: number; + MAX_HOLD_REQUESTS_PER_PLAYER: number; + MAX_GO_TO_REQUESTS_PER_PLAYER: number; + MAX_COME_WITH_ME_REQUESTS_PER_PLAYER: number; + CORE_POINT_MAX_VALUE: number; + CORE_POINTS_MAX: number; + CORE_POINTS_MIN: number; + BORN_POISTS_FREE_ONLY_FAREST_BOT: boolean; + BORN_POINSTS_FREE_ONLY_FAREST_PLAYER: boolean; + SCAV_GROUPS_TOGETHER: boolean; + LAY_DOWN_ANG_SHOOT: number; + HOLD_REQUEST_TIME_SEC: number; + TRIGGERS_DOWN_TO_RUN_WHEN_MOVE: number; + MIN_DIST_TO_RUN_WHILE_ATTACK_MOVING: number; + MIN_DIST_TO_RUN_WHILE_ATTACK_MOVING_OTHER_ENEMIS: number; + MIN_DIST_TO_STOP_RUN: number; + JUMP_SPREAD_DIST: number; + LOOK_TIMES_TO_KILL: number; + COME_INSIDE_TIMES: number; + TOTAL_TIME_KILL: number; + TOTAL_TIME_KILL_AFTER_WARN: number; + MOVING_AIM_COEF: number; + VERTICAL_DIST_TO_IGNORE_SOUND: number; + DEFENCE_LEVEL_SHIFT: number; + MIN_DIST_CLOSE_DEF: number; + USE_ID_PRIOR_WHO_GO: boolean; + SMOKE_GRENADE_RADIUS_COEF: number; + GRENADE_PRECISION: number; + MAX_WARNS_BEFORE_KILL: number; + CARE_ENEMY_ONLY_TIME: number; + MIDDLE_POINT_COEF: number; + MAIN_TACTIC_ONLY_ATTACK: boolean; + LAST_DAMAGE_ACTIVE: number; + SHALL_DIE_IF_NOT_INITED: boolean; + CHECK_BOT_INIT_TIME_SEC: number; + WEAPON_ROOT_Y_OFFSET: number; + DELTA_SUPRESS_DISTANCE_SQRT: number; + DELTA_SUPRESS_DISTANCE: number; + WAVE_COEF_LOW: number; + WAVE_COEF_MID: number; + WAVE_COEF_HIGH: number; + WAVE_COEF_HORDE: number; + WAVE_ONLY_AS_ONLINE: boolean; + LOCAL_BOTS_COUNT: number; + AXE_MAN_KILLS_END: number; +} diff --git a/project/src/models/eft/common/tables/IBotType.ts b/project/src/models/eft/common/tables/IBotType.ts index 1ab63357..0bb6b94c 100644 --- a/project/src/models/eft/common/tables/IBotType.ts +++ b/project/src/models/eft/common/tables/IBotType.ts @@ -1,202 +1,202 @@ import { MinMax } from "@spt-aki/models/common/MinMax"; import { Skills } from "@spt-aki/models/eft/common/tables/IBotBase"; -export interface IBotType +export interface IBotType { - appearance: Appearance - chances: Chances - difficulty: Difficulties - experience: Experience - firstName: string[] - generation: Generation - health: Health - inventory: Inventory - lastName: string[] - skills: Skills + appearance: Appearance; + chances: Chances; + difficulty: Difficulties; + experience: Experience; + firstName: string[]; + generation: Generation; + health: Health; + inventory: Inventory; + lastName: string[]; + skills: Skills; } -export interface Appearance +export interface Appearance { - body: Record - feet: Record - hands: string[] - head: string[] - voice: string[] + body: Record; + feet: Record; + hands: string[]; + head: string[]; + voice: string[]; } -export interface Chances +export interface Chances { - equipment: EquipmentChances - mods: ModsChances + equipment: EquipmentChances; + mods: ModsChances; } -export interface EquipmentChances +export interface EquipmentChances { - ArmBand: number - ArmorVest: number - Backpack: number - Earpiece: number - Eyewear: number - FaceCover: number - FirstPrimaryWeapon: number - Headwear: number - Holster: number - Pockets: number - Scabbard: number - SecondPrimaryWeapon: number - SecuredContainer: number - TacticalVest: number + ArmBand: number; + ArmorVest: number; + Backpack: number; + Earpiece: number; + Eyewear: number; + FaceCover: number; + FirstPrimaryWeapon: number; + Headwear: number; + Holster: number; + Pockets: number; + Scabbard: number; + SecondPrimaryWeapon: number; + SecuredContainer: number; + TacticalVest: number; } /* eslint-disable @typescript-eslint/naming-convention */ -export interface ModsChances +export interface ModsChances { - mod_charge: number - mod_equipment: number - mod_equipment_000: number - mod_equipment_001: number - mod_equipment_002: number - mod_flashlight: number - mod_foregrip: number - mod_launcher: number - mod_magazine: number - mod_mount: number - mod_mount_000: number - mod_mount_001: number - mod_muzzle: number - mod_nvg: number - mod_pistol_grip: number - mod_reciever: number - mod_scope: number - mod_scope_000: number - mod_scope_001: number - mod_scope_002: number - mod_scope_003: number - mod_sight_front: number - mod_sight_rear: number - mod_stock: number - mod_stock_000: number - mod_stock_akms: number - mod_tactical: number - mod_tactical_000: number - mod_tactical_001: number - mod_tactical_002: number - mod_tactical_003: number - mod_handguard: number + mod_charge: number; + mod_equipment: number; + mod_equipment_000: number; + mod_equipment_001: number; + mod_equipment_002: number; + mod_flashlight: number; + mod_foregrip: number; + mod_launcher: number; + mod_magazine: number; + mod_mount: number; + mod_mount_000: number; + mod_mount_001: number; + mod_muzzle: number; + mod_nvg: number; + mod_pistol_grip: number; + mod_reciever: number; + mod_scope: number; + mod_scope_000: number; + mod_scope_001: number; + mod_scope_002: number; + mod_scope_003: number; + mod_sight_front: number; + mod_sight_rear: number; + mod_stock: number; + mod_stock_000: number; + mod_stock_akms: number; + mod_tactical: number; + mod_tactical_000: number; + mod_tactical_001: number; + mod_tactical_002: number; + mod_tactical_003: number; + mod_handguard: number; } -export interface Difficulties +export interface Difficulties { - easy: Difficulty - normal: Difficulty - hard: Difficulty - impossible: Difficulty + easy: Difficulty; + normal: Difficulty; + hard: Difficulty; + impossible: Difficulty; } -export interface Difficulty +export interface Difficulty { - Aiming: Record - Boss: Record - Change: Record - Core: Record - Cover: Record - Grenade: Record - Hearing: Record - Lay: Record - Look: Record - Mind: Record - Move: Record - Patrol: Record - Scattering: Record - Shoot: Record + Aiming: Record; + Boss: Record; + Change: Record; + Core: Record; + Cover: Record; + Grenade: Record; + Hearing: Record; + Lay: Record; + Look: Record; + Mind: Record; + Move: Record; + Patrol: Record; + Scattering: Record; + Shoot: Record; } -export interface Experience +export interface Experience { - aggressorBonus: number - level: MinMax - reward: MinMax - standingForKill: number + aggressorBonus: number; + level: MinMax; + reward: MinMax; + standingForKill: number; } -export interface Generation +export interface Generation { - items: GenerationWeightingItems + items: GenerationWeightingItems; } -export interface GenerationWeightingItems +export interface GenerationWeightingItems { - grenades: GenerationData - healing: GenerationData - drugs: GenerationData - stims: GenerationData - backpackLoot: GenerationData - pocketLoot: GenerationData - vestLoot: GenerationData - magazines: GenerationData - specialItems: GenerationData + grenades: GenerationData; + healing: GenerationData; + drugs: GenerationData; + stims: GenerationData; + backpackLoot: GenerationData; + pocketLoot: GenerationData; + vestLoot: GenerationData; + magazines: GenerationData; + specialItems: GenerationData; } export interface GenerationData { /** key: number of items, value: weighting */ - weights: Record + weights: Record; /** Array of item tpls */ - whitelist: string[] + whitelist: string[]; } -export interface Health +export interface Health { - BodyParts: BodyPart[] - Energy: MinMax - Hydration: MinMax - Temperature: MinMax + BodyParts: BodyPart[]; + Energy: MinMax; + Hydration: MinMax; + Temperature: MinMax; } -export interface BodyPart +export interface BodyPart { - Chest: MinMax - Head: MinMax - LeftArm: MinMax - LeftLeg: MinMax - RightArm: MinMax - RightLeg: MinMax - Stomach: MinMax + Chest: MinMax; + Head: MinMax; + LeftArm: MinMax; + LeftLeg: MinMax; + RightArm: MinMax; + RightLeg: MinMax; + Stomach: MinMax; } -export interface Inventory +export interface Inventory { - equipment: Equipment - Ammo: Record> - items: Items - mods: Mods + equipment: Equipment; + Ammo: Record>; + items: Items; + mods: Mods; } -export interface Equipment +export interface Equipment { - ArmBand: Record - ArmorVest: Record - Backpack: Record - Earpiece: Record - Eyewear: Record - FaceCover: Record - FirstPrimaryWeapon: Record - Headwear: Record - Holster: Record - Pockets: Record - Scabbard: Record - SecondPrimaryWeapon: Record - SecuredContainer: Record - TacticalVest: Record + ArmBand: Record; + ArmorVest: Record; + Backpack: Record; + Earpiece: Record; + Eyewear: Record; + FaceCover: Record; + FirstPrimaryWeapon: Record; + Headwear: Record; + Holster: Record; + Pockets: Record; + Scabbard: Record; + SecondPrimaryWeapon: Record; + SecuredContainer: Record; + TacticalVest: Record; } -export interface Items +export interface Items { - Backpack: string[] - Pockets: string[] - SecuredContainer: string[] - SpecialLoot: string[] - TacticalVest: string[] + Backpack: string[]; + Pockets: string[]; + SecuredContainer: string[]; + SpecialLoot: string[]; + TacticalVest: string[]; } -export type Mods = Record> \ No newline at end of file +export type Mods = Record>; diff --git a/project/src/models/eft/common/tables/ICustomizationItem.ts b/project/src/models/eft/common/tables/ICustomizationItem.ts index 9a173862..07585857 100644 --- a/project/src/models/eft/common/tables/ICustomizationItem.ts +++ b/project/src/models/eft/common/tables/ICustomizationItem.ts @@ -1,35 +1,35 @@ import { Ixyz } from "@spt-aki/models/eft/common/Ixyz"; -export interface ICustomizationItem +export interface ICustomizationItem { - _id: string - _name: string - _parent: string - _type: string - _props: Props - _proto: string + _id: string; + _name: string; + _parent: string; + _type: string; + _props: Props; + _proto: string; } -export interface Props +export interface Props { - Name: string - ShortName: string - Description: string - Side: string[] - BodyPart: string - AvailableAsDefault?: boolean - Body: string - Hands: string - Feet: string - Prefab: Prefab - WatchPrefab: Prefab - IntegratedArmorVest: boolean - WatchPosition: Ixyz - WatchRotation: Ixyz + Name: string; + ShortName: string; + Description: string; + Side: string[]; + BodyPart: string; + AvailableAsDefault?: boolean; + Body: string; + Hands: string; + Feet: string; + Prefab: Prefab; + WatchPrefab: Prefab; + IntegratedArmorVest: boolean; + WatchPosition: Ixyz; + WatchRotation: Ixyz; } -export interface Prefab +export interface Prefab { - path: string - rcid: string -} \ No newline at end of file + path: string; + rcid: string; +} diff --git a/project/src/models/eft/common/tables/IHandbookBase.ts b/project/src/models/eft/common/tables/IHandbookBase.ts index d3664e6c..c079d753 100644 --- a/project/src/models/eft/common/tables/IHandbookBase.ts +++ b/project/src/models/eft/common/tables/IHandbookBase.ts @@ -1,21 +1,21 @@ export interface IHandbookBase { - Categories: Category[] - Items: HandbookItem[] + Categories: Category[]; + Items: HandbookItem[]; } -export interface Category +export interface Category { - Id: string - ParentId?: string - Icon: string - Color: string - Order: string + Id: string; + ParentId?: string; + Icon: string; + Color: string; + Order: string; } - -export interface HandbookItem + +export interface HandbookItem { - Id: string - ParentId: string - Price: number -} \ No newline at end of file + Id: string; + ParentId: string; + Price: number; +} diff --git a/project/src/models/eft/common/tables/IItem.ts b/project/src/models/eft/common/tables/IItem.ts index 7dbc0f68..f49011e2 100644 --- a/project/src/models/eft/common/tables/IItem.ts +++ b/project/src/models/eft/common/tables/IItem.ts @@ -1,165 +1,164 @@ -export interface Item +export interface Item { - - _id: string - _tpl: string - parentId?: string - slotId?: string - location?: Location | number - upd?: Upd + _id: string; + _tpl: string; + parentId?: string; + slotId?: string; + location?: Location | number; + upd?: Upd; } -export interface Upd +export interface Upd { - Buff?: Buff - OriginalStackObjectsCount?: number - Togglable?: Togglable - Map?: Map - Tag?: Tag + Buff?: Buff; + OriginalStackObjectsCount?: number; + Togglable?: Togglable; + Map?: Map; + Tag?: Tag; /** SPT specific property, not made by BSG */ - sptPresetId?: string - FaceShield?: FaceShield - StackObjectsCount?: number - UnlimitedCount?: boolean - Repairable?: Repairable - RecodableComponent?: RecodableComponent - FireMode?: FireMode - SpawnedInSession?: boolean - Light?: Light - Key?: Key - Resource?: Resource - Sight?: Sight - MedKit?: MedKit - FoodDrink?: FoodDrink - Dogtag?: Dogtag - BuyRestrictionMax?: number - BuyRestrictionCurrent?: number - Foldable?: Foldable - SideEffect?: SideEffect - RepairKit?: RepairKit + sptPresetId?: string; + FaceShield?: FaceShield; + StackObjectsCount?: number; + UnlimitedCount?: boolean; + Repairable?: Repairable; + RecodableComponent?: RecodableComponent; + FireMode?: FireMode; + SpawnedInSession?: boolean; + Light?: Light; + Key?: Key; + Resource?: Resource; + Sight?: Sight; + MedKit?: MedKit; + FoodDrink?: FoodDrink; + Dogtag?: Dogtag; + BuyRestrictionMax?: number; + BuyRestrictionCurrent?: number; + Foldable?: Foldable; + SideEffect?: SideEffect; + RepairKit?: RepairKit; } export interface Buff { - rarity: string - buffType: string - value: number - thresholdDurability?: number + rarity: string; + buffType: string; + value: number; + thresholdDurability?: number; } export interface Togglable { - On: boolean -} - -export interface Map -{ - Markers: MapMarker[] -} - -export interface MapMarker -{ - X: number - Y: number -} - -export interface Tag -{ - Color: number; - Name: string + On: boolean; } -export interface FaceShield +export interface Map +{ + Markers: MapMarker[]; +} + +export interface MapMarker +{ + X: number; + Y: number; +} + +export interface Tag +{ + Color: number; + Name: string; +} + +export interface FaceShield { Hits: number; } - -export interface Repairable + +export interface Repairable { - Durability: number - MaxDurability: number + Durability: number; + MaxDurability: number; } export interface RecodableComponent { - IsEncoded: boolean -} - -export interface MedKit -{ - HpResource: number -} - -export interface Sight -{ - ScopesCurrentCalibPointIndexes: number[] - ScopesSelectedModes: number[] - SelectedScope: number -} - -export interface Foldable -{ - Folded: boolean -} - -export interface FireMode -{ - FireMode: string -} - -export interface FoodDrink -{ - HpPercent: number -} - -export interface Key -{ - NumberOfUsages: number -} - -export interface Resource -{ - Value: number - UnitsConsumed: number -} - -export interface Light -{ - IsActive: boolean - SelectedMode: number -} - -export interface Dogtag -{ - AccountId: string - ProfileId: string - Nickname: string - Side: string - Level: number - Time: string - Status: string - KillerAccountId: string - KillerProfileId: string - KillerName: string - WeaponName: string + IsEncoded: boolean; } -export interface Location +export interface MedKit { - x: number - y: number - r: string | number - isSearched?: boolean + HpResource: number; +} + +export interface Sight +{ + ScopesCurrentCalibPointIndexes: number[]; + ScopesSelectedModes: number[]; + SelectedScope: number; +} + +export interface Foldable +{ + Folded: boolean; +} + +export interface FireMode +{ + FireMode: string; +} + +export interface FoodDrink +{ + HpPercent: number; +} + +export interface Key +{ + NumberOfUsages: number; +} + +export interface Resource +{ + Value: number; + UnitsConsumed: number; +} + +export interface Light +{ + IsActive: boolean; + SelectedMode: number; +} + +export interface Dogtag +{ + AccountId: string; + ProfileId: string; + Nickname: string; + Side: string; + Level: number; + Time: string; + Status: string; + KillerAccountId: string; + KillerProfileId: string; + KillerName: string; + WeaponName: string; +} + +export interface Location +{ + x: number; + y: number; + r: string | number; + isSearched?: boolean; /** SPT property? */ - rotation?: string | boolean + rotation?: string | boolean; } -export interface SideEffect +export interface SideEffect { - Value: number + Value: number; } export interface RepairKit { - Resource: number -} \ No newline at end of file + Resource: number; +} diff --git a/project/src/models/eft/common/tables/ILocationsBase.ts b/project/src/models/eft/common/tables/ILocationsBase.ts index fdb6327b..28eac6b8 100644 --- a/project/src/models/eft/common/tables/ILocationsBase.ts +++ b/project/src/models/eft/common/tables/ILocationsBase.ts @@ -1,14 +1,14 @@ -export interface ILocationsBase +export interface ILocationsBase { - locations: Locations - paths: Path[] + locations: Locations; + paths: Path[]; } -export interface Locations -{ } +export interface Locations +{} -export interface Path +export interface Path { - Source: string - Destination: string -} \ No newline at end of file + Source: string; + Destination: string; +} diff --git a/project/src/models/eft/common/tables/ILootBase.ts b/project/src/models/eft/common/tables/ILootBase.ts index 12169055..9d8f0493 100644 --- a/project/src/models/eft/common/tables/ILootBase.ts +++ b/project/src/models/eft/common/tables/ILootBase.ts @@ -1,83 +1,83 @@ import { Ixyz } from "@spt-aki/models/eft/common/Ixyz"; import { Item } from "@spt-aki/models/eft/common/tables/IItem"; -export interface ILootBase +export interface ILootBase { - staticAmmo: Record - staticContainers: Record - staticLoot: Record + staticAmmo: Record; + staticContainers: Record; + staticLoot: Record; } -export interface IStaticAmmoDetails +export interface IStaticAmmoDetails { - tpl: string - relativeProbability: number + tpl: string; + relativeProbability: number; } -export interface IStaticContainerDetails +export interface IStaticContainerDetails { - staticWeapons: IStaticWeaponProps[] - staticContainers: IStaticContainerData[] - staticForced: IStaticForcedProps[] + staticWeapons: IStaticWeaponProps[]; + staticContainers: IStaticContainerData[]; + staticForced: IStaticForcedProps[]; } export interface IStaticContainerData { - probability: number - template: IStaticContainerProps + probability: number; + template: IStaticContainerProps; } export interface IStaticPropsBase { - Id: string - IsContainer: boolean - useGravity: boolean - randomRotation: boolean - Position: Ixyz - Rotation: Ixyz - IsGroupPosition: boolean - IsAlwaysSpawn: boolean - GroupPositions: any[] - Root: string - Items: any[] + Id: string; + IsContainer: boolean; + useGravity: boolean; + randomRotation: boolean; + Position: Ixyz; + Rotation: Ixyz; + IsGroupPosition: boolean; + IsAlwaysSpawn: boolean; + GroupPositions: any[]; + Root: string; + Items: any[]; } export interface IStaticWeaponProps extends IStaticPropsBase { - Items: Item[] + Items: Item[]; } export interface IStaticContainerProps extends IStaticPropsBase { - Items: StaticItem[] + Items: StaticItem[]; } -export interface StaticItem +export interface StaticItem { - _id: string - _tpl: string + _id: string; + _tpl: string; } -export interface IStaticForcedProps +export interface IStaticForcedProps { - containerId: string - itemTpl: string + containerId: string; + itemTpl: string; } -export interface IStaticLootDetails +export interface IStaticLootDetails { - itemcountDistribution: ItemCountDistribution[] - itemDistribution: ItemDistribution[] + itemcountDistribution: ItemCountDistribution[]; + itemDistribution: ItemDistribution[]; } -export interface ItemCountDistribution +export interface ItemCountDistribution { - count: number - relativeProbability: number + count: number; + relativeProbability: number; } -export interface ItemDistribution +export interface ItemDistribution { - tpl: string - relativeProbability: number -} \ No newline at end of file + tpl: string; + relativeProbability: number; +} diff --git a/project/src/models/eft/common/tables/IMatch.ts b/project/src/models/eft/common/tables/IMatch.ts index d4a60dca..59dafe72 100644 --- a/project/src/models/eft/common/tables/IMatch.ts +++ b/project/src/models/eft/common/tables/IMatch.ts @@ -1,14 +1,14 @@ export interface IMatch { - metrics: Metrics + metrics: Metrics; } export interface Metrics { - Keys: number[] - NetProcessingBins: number[] - RenderBins: number[] - GameUpdateBins: number[] - MemoryMeasureInterval: number - PauseReasons: number[] -} \ No newline at end of file + Keys: number[]; + NetProcessingBins: number[]; + RenderBins: number[]; + GameUpdateBins: number[]; + MemoryMeasureInterval: number; + PauseReasons: number[]; +} diff --git a/project/src/models/eft/common/tables/IProfileTemplate.ts b/project/src/models/eft/common/tables/IProfileTemplate.ts index 0f4ab7fc..ecefd75c 100644 --- a/project/src/models/eft/common/tables/IProfileTemplate.ts +++ b/project/src/models/eft/common/tables/IProfileTemplate.ts @@ -3,36 +3,36 @@ import { Dialogue, IUserBuilds } from "@spt-aki/models/eft/profile/IAkiProfile"; export interface IProfileTemplates { - Standard: IProfileSides + Standard: IProfileSides; // eslint-disable-next-line @typescript-eslint/naming-convention - "Left Behind": IProfileSides + "Left Behind": IProfileSides; // eslint-disable-next-line @typescript-eslint/naming-convention - "Prepare To Escape": IProfileSides + "Prepare To Escape": IProfileSides; // eslint-disable-next-line @typescript-eslint/naming-convention - "Edge Of Darkness": IProfileSides + "Edge Of Darkness": IProfileSides; } export interface IProfileSides { - usec: TemplateSide - bear: TemplateSide + usec: TemplateSide; + bear: TemplateSide; } export interface TemplateSide { - character: IPmcData - suits: string[] - dialogues: Record - userbuilds: IUserBuilds - trader: ProfileTraderTemplate + character: IPmcData; + suits: string[]; + dialogues: Record; + userbuilds: IUserBuilds; + trader: ProfileTraderTemplate; } export interface ProfileTraderTemplate { - initialLoyaltyLevel: number - setQuestsAvailableForStart?: boolean - setQuestsAvailableForFinish?: boolean - initialStanding: number - initialSalesSum: number - jaegerUnlocked: boolean -} \ No newline at end of file + initialLoyaltyLevel: number; + setQuestsAvailableForStart?: boolean; + setQuestsAvailableForFinish?: boolean; + initialStanding: number; + initialSalesSum: number; + jaegerUnlocked: boolean; +} diff --git a/project/src/models/eft/common/tables/IQuest.ts b/project/src/models/eft/common/tables/IQuest.ts index 89f90480..e0d2778a 100644 --- a/project/src/models/eft/common/tables/IQuest.ts +++ b/project/src/models/eft/common/tables/IQuest.ts @@ -3,146 +3,146 @@ import { QuestRewardType } from "@spt-aki/models/enums/QuestRewardType"; import { QuestStatus } from "@spt-aki/models/enums/QuestStatus"; import { QuestTypeEnum } from "@spt-aki/models/enums/QuestTypeEnum"; -export interface IQuest +export interface IQuest { /** SPT addition - human readable quest name */ - QuestName?: string - _id: string - canShowNotificationsInGame: boolean - conditions: Conditions - description: string - failMessageText: string - name: string - note: string - traderId: string - location: string - image: string - type: QuestTypeEnum - isKey: boolean + QuestName?: string; + _id: string; + canShowNotificationsInGame: boolean; + conditions: Conditions; + description: string; + failMessageText: string; + name: string; + note: string; + traderId: string; + location: string; + image: string; + type: QuestTypeEnum; + isKey: boolean; /** @deprecated - Likely not used, use 'status' instead */ - questStatus: QuestStatus - restartable: boolean - instantComplete: boolean - secretQuest: boolean - startedMessageText: string - successMessageText: string - templateId: string - rewards: Rewards + questStatus: QuestStatus; + restartable: boolean; + instantComplete: boolean; + secretQuest: boolean; + startedMessageText: string; + successMessageText: string; + templateId: string; + rewards: Rewards; /** Becomes 'AppearStatus' inside client */ - status: string | number - KeyQuest: boolean - changeQuestMessageText: string + status: string | number; + KeyQuest: boolean; + changeQuestMessageText: string; /** "Pmc" or "Scav" */ - side: string + side: string; /** Status of quest to player */ - sptStatus?: QuestStatus + sptStatus?: QuestStatus; } -export interface Conditions +export interface Conditions { - Started: AvailableForConditions[] - AvailableForFinish: AvailableForConditions[] - AvailableForStart: AvailableForConditions[] - Success: AvailableForConditions[] - Fail: AvailableForConditions[] + Started: AvailableForConditions[]; + AvailableForFinish: AvailableForConditions[]; + AvailableForStart: AvailableForConditions[]; + Success: AvailableForConditions[]; + Fail: AvailableForConditions[]; } - -export interface AvailableForConditions + +export interface AvailableForConditions { - _parent: string - _props: AvailableForProps - dynamicLocale?: boolean + _parent: string; + _props: AvailableForProps; + dynamicLocale?: boolean; } - -export interface AvailableForProps + +export interface AvailableForProps { - id: string - index: number - parentId: string - isEncoded: boolean - dynamicLocale: boolean - value?: string | number - compareMethod?: string - visibilityConditions?: VisibilityCondition[] - target?: string | string[] // TODO: split each availableForX object into each type: FindItem, HandoverItem, Level, Quest, TraderLoyalty etc - status?: QuestStatus[] - availableAfter?: number - dispersion?: number - onlyFoundInRaid?: boolean - oneSessionOnly?: boolean - doNotResetIfCounterCompleted?: boolean - dogtagLevel?: number - maxDurability?: number - minDurability?: number - counter?: AvailableForCounter - plantTime?: number - zoneId?: string - type?: boolean - countInRaid?: boolean - globalQuestCounterId?: any + id: string; + index: number; + parentId: string; + isEncoded: boolean; + dynamicLocale: boolean; + value?: string | number; + compareMethod?: string; + visibilityConditions?: VisibilityCondition[]; + target?: string | string[]; // TODO: split each availableForX object into each type: FindItem, HandoverItem, Level, Quest, TraderLoyalty etc + status?: QuestStatus[]; + availableAfter?: number; + dispersion?: number; + onlyFoundInRaid?: boolean; + oneSessionOnly?: boolean; + doNotResetIfCounterCompleted?: boolean; + dogtagLevel?: number; + maxDurability?: number; + minDurability?: number; + counter?: AvailableForCounter; + plantTime?: number; + zoneId?: string; + type?: boolean; + countInRaid?: boolean; + globalQuestCounterId?: any; } export interface AvailableForCounter { - id: string - conditions: CounterCondition[] + id: string; + conditions: CounterCondition[]; } export interface CounterCondition { - _parent: string - _props: CounterProps + _parent: string; + _props: CounterProps; } export interface CounterProps { - id: string - target: string[] | string // TODO: some objects have an array and some are just strings, thanks bsg very cool - compareMethod?: string - value?: string - weapon?: string[] - equipmentInclusive?: string[][] - weaponModsInclusive?: string[][] - status?: string[] - bodyPart?: string[] - daytime?: DaytimeCounter + id: string; + target: string[] | string; // TODO: some objects have an array and some are just strings, thanks bsg very cool + compareMethod?: string; + value?: string; + weapon?: string[]; + equipmentInclusive?: string[][]; + weaponModsInclusive?: string[][]; + status?: string[]; + bodyPart?: string[]; + daytime?: DaytimeCounter; } export interface DaytimeCounter { - from: number - to: number + from: number; + to: number; } export interface VisibilityCondition { - id: string - value: number - dynamicLocale: boolean - oneSessionOnly: boolean + id: string; + value: number; + dynamicLocale: boolean; + oneSessionOnly: boolean; } - -export interface Rewards + +export interface Rewards { - AvailableForStart: Reward[] - AvailableForFinish: Reward[] - Started: Reward[] - Success: Reward[] - Fail: Reward[] - FailRestartable: Reward[] - Expired: Reward[] + AvailableForStart: Reward[]; + AvailableForFinish: Reward[]; + Started: Reward[]; + Success: Reward[]; + Fail: Reward[]; + FailRestartable: Reward[]; + Expired: Reward[]; } - + export interface Reward extends Item { - value?: string | number - id: string - type: QuestRewardType - index: number - target?: string - items?: Item[] - loyaltyLevel?: number - traderId?: string - unknown?: boolean - findInRaid?: boolean + value?: string | number; + id: string; + type: QuestRewardType; + index: number; + target?: string; + items?: Item[]; + loyaltyLevel?: number; + traderId?: string; + unknown?: boolean; + findInRaid?: boolean; } diff --git a/project/src/models/eft/common/tables/IRepeatableQuests.ts b/project/src/models/eft/common/tables/IRepeatableQuests.ts index 3d717604..21836a5c 100644 --- a/project/src/models/eft/common/tables/IRepeatableQuests.ts +++ b/project/src/models/eft/common/tables/IRepeatableQuests.ts @@ -1,364 +1,360 @@ import { Item } from "@spt-aki/models/eft/common/tables/IItem"; -export interface IReward +export interface IReward { - index: number - type: string - value: number - target?: string - items?: Item[] + index: number; + type: string; + value: number; + target?: string; + items?: Item[]; } -export interface IRepeatableQuestDatabase +export interface IRepeatableQuestDatabase { - templates: ITemplates - rewards: IRewardOptions - data: IOptions - samples: ISampleQuests[] -} - -export interface ITemplates -{ - Elimination: IRepeatableQuest - Completion: IRepeatableQuest - Exploration: IRepeatableQuest + templates: ITemplates; + rewards: IRewardOptions; + data: IOptions; + samples: ISampleQuests[]; } -export interface IPmcDataRepeatableQuest +export interface ITemplates { - id?: string - name: string - activeQuests: IRepeatableQuest[] - inactiveQuests: IRepeatableQuest[] - endTime: number - changeRequirement: TChangeRequirementRecord // what it costs to reset redundant to change requirements within the IRepeatableQuest + Elimination: IRepeatableQuest; + Completion: IRepeatableQuest; + Exploration: IRepeatableQuest; } -export type TChangeRequirementRecord = Record +export interface IPmcDataRepeatableQuest +{ + id?: string; + name: string; + activeQuests: IRepeatableQuest[]; + inactiveQuests: IRepeatableQuest[]; + endTime: number; + changeRequirement: TChangeRequirementRecord; // what it costs to reset redundant to change requirements within the IRepeatableQuest +} + +export type TChangeRequirementRecord = Record; export interface IChangeRequirement { - changeCost: IChangeCost[] - changeStandingCost: number -} - -export interface IChangeCost -{ - templateId: string // what item it will take to reset daily - count: number // amount of item needed to reset + changeCost: IChangeCost[]; + changeStandingCost: number; } -export interface IRepeatableQuest +export interface IChangeCost { - _id: string - traderId: string - location: string - image: string - type: string - isKey: boolean - restartable: boolean - instantComplete: boolean - secretQuest: boolean - canShowNotificationsInGame: boolean - rewards: IRewards - conditions: IConditions - side: string - questStatus: any - name: string - note: string - description: string - successMessageText: string - failMessageText: string - startedMessageText: string - changeQuestMessageText: string - acceptPlayerMessage: string - declinePlayerMessage: string - completePlayerMessage: string - templateId: string - changeCost: IChangeCost[] - changeStandingCost: number + templateId: string; // what item it will take to reset daily + count: number; // amount of item needed to reset +} + +export interface IRepeatableQuest +{ + _id: string; + traderId: string; + location: string; + image: string; + type: string; + isKey: boolean; + restartable: boolean; + instantComplete: boolean; + secretQuest: boolean; + canShowNotificationsInGame: boolean; + rewards: IRewards; + conditions: IConditions; + side: string; + questStatus: any; + name: string; + note: string; + description: string; + successMessageText: string; + failMessageText: string; + startedMessageText: string; + changeQuestMessageText: string; + acceptPlayerMessage: string; + declinePlayerMessage: string; + completePlayerMessage: string; + templateId: string; + changeCost: IChangeCost[]; + changeStandingCost: number; sptRepatableGroupName?: string; } -export interface IRewards +export interface IRewards { - Started: IReward[] - Success: IReward[] - Fail: IReward[] + Started: IReward[]; + Success: IReward[]; + Fail: IReward[]; } -export interface IConditions +export interface IConditions { - AvailableForStart: any[] - AvailableForFinish: IAvailableFor[] - Fail: any[] + AvailableForStart: any[]; + AvailableForFinish: IAvailableFor[]; + Fail: any[]; } -export interface IAvailableFor +export interface IAvailableFor { - _props: IAvailableForProps - _parent: string - dynamicLocale: boolean + _props: IAvailableForProps; + _parent: string; + dynamicLocale: boolean; } -export interface IAvailableForProps +export interface IAvailableForProps { - id: string - parentId: string - dynamicLocale: boolean - index: number - visibilityConditions: IVisibilityCondition[] - value: number + id: string; + parentId: string; + dynamicLocale: boolean; + index: number; + visibilityConditions: IVisibilityCondition[]; + value: number; } -export interface IVisibilityCondition +export interface IVisibilityCondition { - id: string - oneSessionOnly: boolean - value: number - index: number - dynamicLocale: boolean + id: string; + oneSessionOnly: boolean; + value: number; + index: number; + dynamicLocale: boolean; } -export interface IAvailableForPropsCounter extends IAvailableForProps +export interface IAvailableForPropsCounter extends IAvailableForProps { - type: string - oneSessionOnly: boolean - doNotResetIfCounterCompleted: boolean - counter?: ICounter + type: string; + oneSessionOnly: boolean; + doNotResetIfCounterCompleted: boolean; + counter?: ICounter; } -export interface ICounter +export interface ICounter { - id: string, - conditions: ICondition[] + id: string; + conditions: ICondition[]; } -export interface ICondition +export interface ICondition { - _props: IConditionProps, - _parent: string + _props: IConditionProps; + _parent: string; } -export interface IConditionProps +export interface IConditionProps { - id: string, - dynamicLocale: boolean, + id: string; + dynamicLocale: boolean; } - // Elimination -export interface IElimination extends IRepeatableQuest +export interface IElimination extends IRepeatableQuest { - conditions: IEliminationConditions + conditions: IEliminationConditions; } -export interface IEliminationConditions extends IConditions +export interface IEliminationConditions extends IConditions { - AvailableForFinish: IEliminationAvailableFor[] + AvailableForFinish: IEliminationAvailableFor[]; } -export interface IEliminationAvailableFor extends IAvailableFor +export interface IEliminationAvailableFor extends IAvailableFor { - _props: IEliminationAvailableForProps + _props: IEliminationAvailableForProps; } - -export interface IEliminationAvailableForProps extends IAvailableForPropsCounter +export interface IEliminationAvailableForProps extends IAvailableForPropsCounter { - counter: IEliminationCounter + counter: IEliminationCounter; } -export interface IEliminationCounter extends ICounter +export interface IEliminationCounter extends ICounter { - conditions: IEliminationCondition[] + conditions: IEliminationCondition[]; } -export interface IEliminationCondition extends ICondition +export interface IEliminationCondition extends ICondition { - _props: ILocationConditionProps | IKillConditionProps + _props: ILocationConditionProps | IKillConditionProps; } - + // Exploration -export interface IExploration extends IRepeatableQuest +export interface IExploration extends IRepeatableQuest { - conditions: IExplorationConditions + conditions: IExplorationConditions; } -export interface IExplorationConditions extends IConditions +export interface IExplorationConditions extends IConditions { - AvailableForFinish: IExplorationAvailableFor[] + AvailableForFinish: IExplorationAvailableFor[]; } -export interface IExplorationAvailableFor extends IAvailableFor +export interface IExplorationAvailableFor extends IAvailableFor { - _props: IExplorationAvailableForProps + _props: IExplorationAvailableForProps; } -export interface IExplorationAvailableForProps extends IAvailableForPropsCounter +export interface IExplorationAvailableForProps extends IAvailableForPropsCounter { - counter: IExplorationCounter + counter: IExplorationCounter; } -export interface IExplorationCounter extends ICounter +export interface IExplorationCounter extends ICounter { - conditions: IExplorationCondition[] + conditions: IExplorationCondition[]; } -export interface IExplorationCondition extends ICondition +export interface IExplorationCondition extends ICondition { - _props: ILocationConditionProps | IExitStatusConditionProps | IExitNameConditionProps + _props: ILocationConditionProps | IExitStatusConditionProps | IExitNameConditionProps; } // Pickup -export interface IPickup extends IRepeatableQuest +export interface IPickup extends IRepeatableQuest { - conditions: IPickupConditions + conditions: IPickupConditions; } -export interface IPickupConditions extends IConditions +export interface IPickupConditions extends IConditions { - AvailableForFinish: IPickupAvailableFor[] + AvailableForFinish: IPickupAvailableFor[]; } -export interface IPickupAvailableFor extends IAvailableFor +export interface IPickupAvailableFor extends IAvailableFor { - _props: IPickupAvailableForProps + _props: IPickupAvailableForProps; } -export interface IPickupAvailableForProps extends IAvailableForPropsCounter +export interface IPickupAvailableForProps extends IAvailableForPropsCounter { - target: string[] - counter?: IPickupCounter + target: string[]; + counter?: IPickupCounter; } -export interface IPickupCounter extends ICounter +export interface IPickupCounter extends ICounter { - conditions: IPickupCondition[] + conditions: IPickupCondition[]; } -export interface IPickupCondition extends ICondition +export interface IPickupCondition extends ICondition { - _props: IEquipmentConditionProps | ILocationConditionProps | IExitStatusConditionProps + _props: IEquipmentConditionProps | ILocationConditionProps | IExitStatusConditionProps; } // Completion -export interface ICompletion extends IRepeatableQuest +export interface ICompletion extends IRepeatableQuest { - conditions: ICompletionConditions + conditions: ICompletionConditions; } -export interface ICompletionConditions extends IConditions +export interface ICompletionConditions extends IConditions { - AvailableForFinish: ICompletionAvailableFor[] + AvailableForFinish: ICompletionAvailableFor[]; } -export interface ICompletionAvailableFor extends IAvailableFor +export interface ICompletionAvailableFor extends IAvailableFor { - _props: ICompletionAvailableForProps + _props: ICompletionAvailableForProps; } -export interface ICompletionAvailableForProps extends IAvailableForProps +export interface ICompletionAvailableForProps extends IAvailableForProps { - target: string[] - minDurability: number - maxDurability: number - dogtagLevel: number - onlyFoundInRaid: boolean + target: string[]; + minDurability: number; + maxDurability: number; + dogtagLevel: number; + onlyFoundInRaid: boolean; } - // Quest Conditions -export interface ILocationConditionProps extends IConditionProps +export interface ILocationConditionProps extends IConditionProps { - target: string[], - weapon?: string[] - weaponCategories?: string[] + target: string[]; + weapon?: string[]; + weaponCategories?: string[]; } export interface IEquipmentConditionProps extends IConditionProps { - equipmentInclusive: [string[]] - IncludeNotEquippedItems: boolean + equipmentInclusive: [string[]]; + IncludeNotEquippedItems: boolean; } -export interface IKillConditionProps extends IConditionProps +export interface IKillConditionProps extends IConditionProps { - target: string - value: number - savageRole?: string[] - bodyPart?: string[] - distance?: IDistanceCheck - weapon?: string[] - weaponCategories? : string[] + target: string; + value: number; + savageRole?: string[]; + bodyPart?: string[]; + distance?: IDistanceCheck; + weapon?: string[]; + weaponCategories?: string[]; } -export interface IDistanceCheck +export interface IDistanceCheck { - compareMethod: string - value: number -} - -export interface IExitStatusConditionProps extends IConditionProps -{ - status: string[], + compareMethod: string; + value: number; } -export interface IExitNameConditionProps extends IConditionProps +export interface IExitStatusConditionProps extends IConditionProps { - exitName: string, + status: string[]; } +export interface IExitNameConditionProps extends IConditionProps +{ + exitName: string; +} // Config Options - -export interface IRewardOptions + +export interface IRewardOptions { - itemsBlacklist: string[] + itemsBlacklist: string[]; } - -export interface IOptions + +export interface IOptions { - Completion: ICompletionFilter + Completion: ICompletionFilter; } - -export interface ICompletionFilter + +export interface ICompletionFilter { - itemsBlacklist: ItemsBlacklist[] - itemsWhitelist: ItemsWhitelist[] + itemsBlacklist: ItemsBlacklist[]; + itemsWhitelist: ItemsWhitelist[]; } - -export interface ItemsBlacklist + +export interface ItemsBlacklist { - minPlayerLevel: number - itemIds: string[] + minPlayerLevel: number; + itemIds: string[]; } - -export interface ItemsWhitelist + +export interface ItemsWhitelist { - minPlayerLevel: number - itemIds: string[] + minPlayerLevel: number; + itemIds: string[]; } - -export interface ISampleQuests + +export interface ISampleQuests { - _id: string - traderId: string - location: string - image: string - type: string - isKey: boolean - restartable: boolean - instantComplete: boolean - secretQuest: boolean - canShowNotificationsInGame: boolean - rewards: IRewards - conditions: IConditions - name: string - note: string - description: string - successMessageText: string - failMessageText: string - startedMessageText: string - templateId: string -} \ No newline at end of file + _id: string; + traderId: string; + location: string; + image: string; + type: string; + isKey: boolean; + restartable: boolean; + instantComplete: boolean; + secretQuest: boolean; + canShowNotificationsInGame: boolean; + rewards: IRewards; + conditions: IConditions; + name: string; + note: string; + description: string; + successMessageText: string; + failMessageText: string; + startedMessageText: string; + templateId: string; +} diff --git a/project/src/models/eft/common/tables/ITemplateItem.ts b/project/src/models/eft/common/tables/ITemplateItem.ts index c7b45aae..15e99135 100644 --- a/project/src/models/eft/common/tables/ITemplateItem.ts +++ b/project/src/models/eft/common/tables/ITemplateItem.ts @@ -1,534 +1,534 @@ import { Ixyz } from "@spt-aki/models/eft/common/Ixyz"; -export interface ITemplateItem +export interface ITemplateItem { - _id: string - _name: string - _parent: string - _type: string - _props: Props - _proto: string + _id: string; + _name: string; + _parent: string; + _type: string; + _props: Props; + _proto: string; } -export interface Props +export interface Props { - AllowSpawnOnLocations?: any[] - BeltMagazineRefreshCount?: number - ChangePriceCoef?: number - FixedPrice?: boolean - SendToClient?: boolean - Name?: string - ShortName?: string - Description?: string - Weight?: number - BackgroundColor?: string - Width?: number - Height?: number - StackMaxSize?: number - Rarity?: string - SpawnChance?: number - CreditsPrice?: number - ItemSound?: string - Prefab?: Prefab - UsePrefab?: Prefab - StackObjectsCount?: number - NotShownInSlot?: boolean - ExaminedByDefault?: boolean - ExamineTime?: number - IsUndiscardable?: boolean - IsUnsaleable?: boolean - IsUnbuyable?: boolean - IsUngivable?: boolean - IsUnremovable?: boolean - IsLockedafterEquip?: boolean - IsSpecialSlotOnly?: boolean - IsStationaryWeapon?: boolean - QuestItem?: boolean - QuestStashMaxCount?: number - LootExperience?: number - ExamineExperience?: number - HideEntrails?: boolean - InsuranceDisabled?: boolean - RepairCost?: number - RepairSpeed?: number - ExtraSizeLeft?: number - ExtraSizeRight?: number - ExtraSizeUp?: number - ExtraSizeDown?: number - ExtraSizeForceAdd?: boolean - MergesWithChildren?: boolean - CanSellOnRagfair?: boolean - CanRequireOnRagfair?: boolean - ConflictingItems?: string[] - Unlootable?: boolean - UnlootableFromSlot?: string - UnlootableFromSide?: string[] - AnimationVariantsNumber?: number - DiscardingBlock?: boolean - DropSoundType?: string - RagFairCommissionModifier?: number - IsAlwaysAvailableForInsurance?: boolean - DiscardLimit?: number - MaxResource?: number - Resource?: number - DogTagQualities?: boolean - Grids?: Grid[] - Slots?: Slot[] - CanPutIntoDuringTheRaid?: boolean - CantRemoveFromSlotsDuringRaid?: string[] - KeyIds?: string[] - TagColor?: number - TagName?: string - Durability?: number - Accuracy?: number - Recoil?: number - Loudness?: number - EffectiveDistance?: number - Ergonomics?: number - Velocity?: number - RaidModdable?: boolean - ToolModdable?: boolean - UniqueAnimationModID?: number - BlocksFolding?: boolean - BlocksCollapsible?: boolean - IsAnimated?: boolean - HasShoulderContact?: boolean - SightingRange?: number - DoubleActionAccuracyPenaltyMult?: number - ModesCount?: any - DurabilityBurnModificator?: number - HeatFactor?: number - CoolFactor?: number - muzzleModType?: string - CustomAimPlane?: string - sightModType?: string - aimingSensitivity?: number - SightModesCount?: number - OpticCalibrationDistances?: number[] - ScopesCount?: number - AimSensitivity?: number|number[][] - Zooms?: number[][] - CalibrationDistances?: number[][] - Intensity?: number - Mask?: string - MaskSize?: number - IsMagazineForStationaryWeapon?: boolean - NoiseIntensity?: number - NoiseScale?: number - Color?: IColor - DiffuseIntensity?: number - MagazineWithBelt?: boolean - HasHinge?: boolean - RampPalette?: string - DepthFade?: number - RoughnessCoef?: number - SpecularCoef?: number - MainTexColorCoef?: number - MinimumTemperatureValue?: number - RampShift?: number - HeatMin?: number - ColdMax?: number - IsNoisy?: boolean - IsFpsStuck?: boolean - IsGlitch?: boolean - IsMotionBlurred?: boolean - IsPixelated?: boolean - PixelationBlockCount?: number - ShiftsAimCamera?: number - magAnimationIndex?: number - Cartridges?: Slot[] - CanFast?: boolean - CanHit?: boolean - CanAdmin?: boolean - LoadUnloadModifier?: number - CheckTimeModifier?: number - CheckOverride?: number - ReloadMagType?: string - VisibleAmmoRangesString?: string - MalfunctionChance?: number - IsShoulderContact?: boolean - Foldable?: boolean - Retractable?: boolean - SizeReduceRight?: number - CenterOfImpact?: number - ShotgunDispersion?: number - IsSilencer?: boolean - DeviationCurve?: number - DeviationMax?: number - SearchSound?: string - BlocksArmorVest?: boolean - speedPenaltyPercent?: number - GridLayoutName?: string - SpawnFilter?: any[] - containType?: any[] - sizeWidth?: number - sizeHeight?: number - isSecured?: boolean - spawnTypes?: string - lootFilter?: any[] - spawnRarity?: string - minCountSpawn?: number - maxCountSpawn?: number - openedByKeyID?: any[] - RigLayoutName?: string - MaxDurability?: number - armorZone?: string[] - armorClass?: string | number - mousePenalty?: number - weaponErgonomicPenalty?: number - BluntThroughput?: number - ArmorMaterial?: string - ArmorType?: string - weapClass?: string - weapUseType?: string - ammoCaliber?: string - OperatingResource?: number - RepairComplexity?: number - durabSpawnMin?: number - durabSpawnMax?: number - isFastReload?: boolean - RecoilForceUp?: number - RecoilForceBack?: number - Convergence?: number - RecoilAngle?: number - weapFireType?: string[] - RecolDispersion?: number - SingleFireRate?: number - CanQueueSecondShot?: boolean - bFirerate?: number - bEffDist?: number - bHearDist?: number - isChamberLoad?: boolean - chamberAmmoCount?: number - isBoltCatch?: boolean - defMagType?: string - defAmmo?: string - AdjustCollimatorsToTrajectory?: boolean - shotgunDispersion?: number - Chambers?: Slot[] - CameraRecoil?: number - CameraSnap?: number - ReloadMode?: string - AimPlane?: number - TacticalReloadStiffnes?: Ixyz - TacticalReloadFixation?: number - RecoilCenter?: Ixyz - RotationCenter?: Ixyz - RotationCenterNoStock?: Ixyz - FoldedSlot?: string - CompactHandling?: boolean - MinRepairDegradation?: number - MaxRepairDegradation?: number - IronSightRange?: number - IsBeltMachineGun?: boolean - IsFlareGun?: boolean - IsGrenadeLauncher?: boolean - IsOneoff?: boolean - MustBoltBeOpennedForExternalReload?: boolean - MustBoltBeOpennedForInternalReload?: boolean - NoFiremodeOnBoltcatch?: boolean - BoltAction?: boolean - HipAccuracyRestorationDelay?: number - HipAccuracyRestorationSpeed?: number - HipInnaccuracyGain?: number - ManualBoltCatch?: boolean - BurstShotsCount?: number - BaseMalfunctionChance?: number - AllowJam?: boolean - AllowFeed?: boolean - AllowMisfire?: boolean - AllowSlide?: boolean - DurabilityBurnRatio?: number - HeatFactorGun?: number - CoolFactorGun?: number - CoolFactorGunMods?: number - HeatFactorByShot?: number - AllowOverheat?: boolean - DoubleActionAccuracyPenalty?: number - RecoilPosZMult?: number - MinRepairKitDegradation?: number - MaxRepairKitDegradation?: number - BlocksEarpiece?: boolean - BlocksEyewear?: boolean - BlocksHeadwear?: boolean - BlocksFaceCover?: boolean - Indestructibility?: number - headSegments?: string[] - FaceShieldComponent?: boolean - FaceShieldMask?: string - MaterialType?: string - RicochetParams?: Ixyz - DeafStrength?: string - BlindnessProtection?: number - Distortion?: number - CompressorTreshold?: number - CompressorAttack?: number - CompressorRelease?: number - CompressorGain?: number - CutoffFreq?: number - Resonance?: number - RolloffMultiplier?: number - ReverbVolume?: number - CompressorVolume?: number - AmbientVolume?: number - DryVolume?: number - HighFrequenciesGain?: number - foodUseTime?: number - foodEffectType?: string - StimulatorBuffs?: string + AllowSpawnOnLocations?: any[]; + BeltMagazineRefreshCount?: number; + ChangePriceCoef?: number; + FixedPrice?: boolean; + SendToClient?: boolean; + Name?: string; + ShortName?: string; + Description?: string; + Weight?: number; + BackgroundColor?: string; + Width?: number; + Height?: number; + StackMaxSize?: number; + Rarity?: string; + SpawnChance?: number; + CreditsPrice?: number; + ItemSound?: string; + Prefab?: Prefab; + UsePrefab?: Prefab; + StackObjectsCount?: number; + NotShownInSlot?: boolean; + ExaminedByDefault?: boolean; + ExamineTime?: number; + IsUndiscardable?: boolean; + IsUnsaleable?: boolean; + IsUnbuyable?: boolean; + IsUngivable?: boolean; + IsUnremovable?: boolean; + IsLockedafterEquip?: boolean; + IsSpecialSlotOnly?: boolean; + IsStationaryWeapon?: boolean; + QuestItem?: boolean; + QuestStashMaxCount?: number; + LootExperience?: number; + ExamineExperience?: number; + HideEntrails?: boolean; + InsuranceDisabled?: boolean; + RepairCost?: number; + RepairSpeed?: number; + ExtraSizeLeft?: number; + ExtraSizeRight?: number; + ExtraSizeUp?: number; + ExtraSizeDown?: number; + ExtraSizeForceAdd?: boolean; + MergesWithChildren?: boolean; + CanSellOnRagfair?: boolean; + CanRequireOnRagfair?: boolean; + ConflictingItems?: string[]; + Unlootable?: boolean; + UnlootableFromSlot?: string; + UnlootableFromSide?: string[]; + AnimationVariantsNumber?: number; + DiscardingBlock?: boolean; + DropSoundType?: string; + RagFairCommissionModifier?: number; + IsAlwaysAvailableForInsurance?: boolean; + DiscardLimit?: number; + MaxResource?: number; + Resource?: number; + DogTagQualities?: boolean; + Grids?: Grid[]; + Slots?: Slot[]; + CanPutIntoDuringTheRaid?: boolean; + CantRemoveFromSlotsDuringRaid?: string[]; + KeyIds?: string[]; + TagColor?: number; + TagName?: string; + Durability?: number; + Accuracy?: number; + Recoil?: number; + Loudness?: number; + EffectiveDistance?: number; + Ergonomics?: number; + Velocity?: number; + RaidModdable?: boolean; + ToolModdable?: boolean; + UniqueAnimationModID?: number; + BlocksFolding?: boolean; + BlocksCollapsible?: boolean; + IsAnimated?: boolean; + HasShoulderContact?: boolean; + SightingRange?: number; + DoubleActionAccuracyPenaltyMult?: number; + ModesCount?: any; + DurabilityBurnModificator?: number; + HeatFactor?: number; + CoolFactor?: number; + muzzleModType?: string; + CustomAimPlane?: string; + sightModType?: string; + aimingSensitivity?: number; + SightModesCount?: number; + OpticCalibrationDistances?: number[]; + ScopesCount?: number; + AimSensitivity?: number | number[][]; + Zooms?: number[][]; + CalibrationDistances?: number[][]; + Intensity?: number; + Mask?: string; + MaskSize?: number; + IsMagazineForStationaryWeapon?: boolean; + NoiseIntensity?: number; + NoiseScale?: number; + Color?: IColor; + DiffuseIntensity?: number; + MagazineWithBelt?: boolean; + HasHinge?: boolean; + RampPalette?: string; + DepthFade?: number; + RoughnessCoef?: number; + SpecularCoef?: number; + MainTexColorCoef?: number; + MinimumTemperatureValue?: number; + RampShift?: number; + HeatMin?: number; + ColdMax?: number; + IsNoisy?: boolean; + IsFpsStuck?: boolean; + IsGlitch?: boolean; + IsMotionBlurred?: boolean; + IsPixelated?: boolean; + PixelationBlockCount?: number; + ShiftsAimCamera?: number; + magAnimationIndex?: number; + Cartridges?: Slot[]; + CanFast?: boolean; + CanHit?: boolean; + CanAdmin?: boolean; + LoadUnloadModifier?: number; + CheckTimeModifier?: number; + CheckOverride?: number; + ReloadMagType?: string; + VisibleAmmoRangesString?: string; + MalfunctionChance?: number; + IsShoulderContact?: boolean; + Foldable?: boolean; + Retractable?: boolean; + SizeReduceRight?: number; + CenterOfImpact?: number; + ShotgunDispersion?: number; + IsSilencer?: boolean; + DeviationCurve?: number; + DeviationMax?: number; + SearchSound?: string; + BlocksArmorVest?: boolean; + speedPenaltyPercent?: number; + GridLayoutName?: string; + SpawnFilter?: any[]; + containType?: any[]; + sizeWidth?: number; + sizeHeight?: number; + isSecured?: boolean; + spawnTypes?: string; + lootFilter?: any[]; + spawnRarity?: string; + minCountSpawn?: number; + maxCountSpawn?: number; + openedByKeyID?: any[]; + RigLayoutName?: string; + MaxDurability?: number; + armorZone?: string[]; + armorClass?: string | number; + mousePenalty?: number; + weaponErgonomicPenalty?: number; + BluntThroughput?: number; + ArmorMaterial?: string; + ArmorType?: string; + weapClass?: string; + weapUseType?: string; + ammoCaliber?: string; + OperatingResource?: number; + RepairComplexity?: number; + durabSpawnMin?: number; + durabSpawnMax?: number; + isFastReload?: boolean; + RecoilForceUp?: number; + RecoilForceBack?: number; + Convergence?: number; + RecoilAngle?: number; + weapFireType?: string[]; + RecolDispersion?: number; + SingleFireRate?: number; + CanQueueSecondShot?: boolean; + bFirerate?: number; + bEffDist?: number; + bHearDist?: number; + isChamberLoad?: boolean; + chamberAmmoCount?: number; + isBoltCatch?: boolean; + defMagType?: string; + defAmmo?: string; + AdjustCollimatorsToTrajectory?: boolean; + shotgunDispersion?: number; + Chambers?: Slot[]; + CameraRecoil?: number; + CameraSnap?: number; + ReloadMode?: string; + AimPlane?: number; + TacticalReloadStiffnes?: Ixyz; + TacticalReloadFixation?: number; + RecoilCenter?: Ixyz; + RotationCenter?: Ixyz; + RotationCenterNoStock?: Ixyz; + FoldedSlot?: string; + CompactHandling?: boolean; + MinRepairDegradation?: number; + MaxRepairDegradation?: number; + IronSightRange?: number; + IsBeltMachineGun?: boolean; + IsFlareGun?: boolean; + IsGrenadeLauncher?: boolean; + IsOneoff?: boolean; + MustBoltBeOpennedForExternalReload?: boolean; + MustBoltBeOpennedForInternalReload?: boolean; + NoFiremodeOnBoltcatch?: boolean; + BoltAction?: boolean; + HipAccuracyRestorationDelay?: number; + HipAccuracyRestorationSpeed?: number; + HipInnaccuracyGain?: number; + ManualBoltCatch?: boolean; + BurstShotsCount?: number; + BaseMalfunctionChance?: number; + AllowJam?: boolean; + AllowFeed?: boolean; + AllowMisfire?: boolean; + AllowSlide?: boolean; + DurabilityBurnRatio?: number; + HeatFactorGun?: number; + CoolFactorGun?: number; + CoolFactorGunMods?: number; + HeatFactorByShot?: number; + AllowOverheat?: boolean; + DoubleActionAccuracyPenalty?: number; + RecoilPosZMult?: number; + MinRepairKitDegradation?: number; + MaxRepairKitDegradation?: number; + BlocksEarpiece?: boolean; + BlocksEyewear?: boolean; + BlocksHeadwear?: boolean; + BlocksFaceCover?: boolean; + Indestructibility?: number; + headSegments?: string[]; + FaceShieldComponent?: boolean; + FaceShieldMask?: string; + MaterialType?: string; + RicochetParams?: Ixyz; + DeafStrength?: string; + BlindnessProtection?: number; + Distortion?: number; + CompressorTreshold?: number; + CompressorAttack?: number; + CompressorRelease?: number; + CompressorGain?: number; + CutoffFreq?: number; + Resonance?: number; + RolloffMultiplier?: number; + ReverbVolume?: number; + CompressorVolume?: number; + AmbientVolume?: number; + DryVolume?: number; + HighFrequenciesGain?: number; + foodUseTime?: number; + foodEffectType?: string; + StimulatorBuffs?: string; // eslint-disable-next-line @typescript-eslint/naming-convention - effects_health?: IHealthEffect[] | Record> + effects_health?: IHealthEffect[] | Record>; // eslint-disable-next-line @typescript-eslint/naming-convention - effects_damage?: Record - MaximumNumberOfUsage?: number - knifeHitDelay?: number - knifeHitSlashRate?: number - knifeHitStabRate?: number - knifeHitRadius?: number - knifeHitSlashDam?: number - knifeHitStabDam?: number - knifeDurab?: number - PrimaryDistance?: number - SecondryDistance?: number - SlashPenetration?: number - StabPenetration?: number - PrimaryConsumption?: number - SecondryConsumption?: number - DeflectionConsumption?: number - AppliedTrunkRotation?: Ixyz - AppliedHeadRotation?: Ixyz - DisplayOnModel?: boolean - AdditionalAnimationLayer?: number - StaminaBurnRate?: number - ColliderScaleMultiplier?: Ixyz - ConfigPathStr?: string - MaxMarkersCount?: number - scaleMin?: number - scaleMax?: number - medUseTime?: number - medEffectType?: string - MaxHpResource?: number - hpResourceRate?: number - apResource?: number - krResource?: number - MaxOpticZoom?: number - MaxRepairResource?: number - TargetItemFilter?: string[] - RepairQuality?: number - RepairType?: string - StackMinRandom?: number - StackMaxRandom?: number - ammoType?: string - InitialSpeed?: number - BallisticCoeficient?: number - BulletMassGram?: number - BulletDiameterMilimeters?: number - Damage?: number - ammoAccr?: number - ammoRec?: number - ammoDist?: number - buckshotBullets?: number - PenetrationPower?: number - PenetrationPowerDiviation?: number - ammoHear?: number - ammoSfx?: string - MisfireChance?: number - MinFragmentsCount?: number - MaxFragmentsCount?: number - ammoShiftChance?: number - casingName?: string - casingEjectPower?: number - casingMass?: number - casingSounds?: string - ProjectileCount?: number - PenetrationChance?: number - RicochetChance?: number - FragmentationChance?: number - Deterioration?: number - SpeedRetardation?: number - Tracer?: boolean - TracerColor?: string - TracerDistance?: number - ArmorDamage?: number - Caliber?: string - StaminaBurnPerDamage?: number - HeavyBleedingDelta?: number - LightBleedingDelta?: number - ShowBullet?: boolean - HasGrenaderComponent?: boolean - FuzeArmTimeSec?: number - ExplosionStrength?: number - MinExplosionDistance?: number - MaxExplosionDistance?: number - FragmentsCount?: number - FragmentType?: string - ShowHitEffectOnExplode?: boolean - ExplosionType?: string - AmmoLifeTimeSec?: number - Contusion?: Ixyz - ArmorDistanceDistanceDamage?: Ixyz - Blindness?: Ixyz - IsLightAndSoundShot?: boolean - LightAndSoundShotAngle?: number - LightAndSoundShotSelfContusionTime?: number - LightAndSoundShotSelfContusionStrength?: number - MalfMisfireChance?: number - MalfFeedChance?: number - StackSlots?: StackSlot[] - type?: string - eqMin?: number - eqMax?: number - rate?: number - ThrowType?: string - ExplDelay?: number - Strength?: number - ContusionDistance?: number - throwDamMax?: number - explDelay?: number - EmitTime?: number - CanBeHiddenDuringThrow?: boolean - MinTimeToContactExplode?: number - ExplosionEffectType?: string - LinkedWeapon?: string - UseAmmoWithoutShell?: boolean - RandomLootSettings?: IRandomLootSettings + effects_damage?: Record; + MaximumNumberOfUsage?: number; + knifeHitDelay?: number; + knifeHitSlashRate?: number; + knifeHitStabRate?: number; + knifeHitRadius?: number; + knifeHitSlashDam?: number; + knifeHitStabDam?: number; + knifeDurab?: number; + PrimaryDistance?: number; + SecondryDistance?: number; + SlashPenetration?: number; + StabPenetration?: number; + PrimaryConsumption?: number; + SecondryConsumption?: number; + DeflectionConsumption?: number; + AppliedTrunkRotation?: Ixyz; + AppliedHeadRotation?: Ixyz; + DisplayOnModel?: boolean; + AdditionalAnimationLayer?: number; + StaminaBurnRate?: number; + ColliderScaleMultiplier?: Ixyz; + ConfigPathStr?: string; + MaxMarkersCount?: number; + scaleMin?: number; + scaleMax?: number; + medUseTime?: number; + medEffectType?: string; + MaxHpResource?: number; + hpResourceRate?: number; + apResource?: number; + krResource?: number; + MaxOpticZoom?: number; + MaxRepairResource?: number; + TargetItemFilter?: string[]; + RepairQuality?: number; + RepairType?: string; + StackMinRandom?: number; + StackMaxRandom?: number; + ammoType?: string; + InitialSpeed?: number; + BallisticCoeficient?: number; + BulletMassGram?: number; + BulletDiameterMilimeters?: number; + Damage?: number; + ammoAccr?: number; + ammoRec?: number; + ammoDist?: number; + buckshotBullets?: number; + PenetrationPower?: number; + PenetrationPowerDiviation?: number; + ammoHear?: number; + ammoSfx?: string; + MisfireChance?: number; + MinFragmentsCount?: number; + MaxFragmentsCount?: number; + ammoShiftChance?: number; + casingName?: string; + casingEjectPower?: number; + casingMass?: number; + casingSounds?: string; + ProjectileCount?: number; + PenetrationChance?: number; + RicochetChance?: number; + FragmentationChance?: number; + Deterioration?: number; + SpeedRetardation?: number; + Tracer?: boolean; + TracerColor?: string; + TracerDistance?: number; + ArmorDamage?: number; + Caliber?: string; + StaminaBurnPerDamage?: number; + HeavyBleedingDelta?: number; + LightBleedingDelta?: number; + ShowBullet?: boolean; + HasGrenaderComponent?: boolean; + FuzeArmTimeSec?: number; + ExplosionStrength?: number; + MinExplosionDistance?: number; + MaxExplosionDistance?: number; + FragmentsCount?: number; + FragmentType?: string; + ShowHitEffectOnExplode?: boolean; + ExplosionType?: string; + AmmoLifeTimeSec?: number; + Contusion?: Ixyz; + ArmorDistanceDistanceDamage?: Ixyz; + Blindness?: Ixyz; + IsLightAndSoundShot?: boolean; + LightAndSoundShotAngle?: number; + LightAndSoundShotSelfContusionTime?: number; + LightAndSoundShotSelfContusionStrength?: number; + MalfMisfireChance?: number; + MalfFeedChance?: number; + StackSlots?: StackSlot[]; + type?: string; + eqMin?: number; + eqMax?: number; + rate?: number; + ThrowType?: string; + ExplDelay?: number; + Strength?: number; + ContusionDistance?: number; + throwDamMax?: number; + explDelay?: number; + EmitTime?: number; + CanBeHiddenDuringThrow?: boolean; + MinTimeToContactExplode?: number; + ExplosionEffectType?: string; + LinkedWeapon?: string; + UseAmmoWithoutShell?: boolean; + RandomLootSettings?: IRandomLootSettings; } export interface IHealthEffect { - type: string - value: number + type: string; + value: number; } -export interface Prefab +export interface Prefab { - path: string - rcid: string + path: string; + rcid: string; } -export interface Grid +export interface Grid { - _name: string - _id: string - _parent: string - _props: GridProps - _proto: string + _name: string; + _id: string; + _parent: string; + _props: GridProps; + _proto: string; } -export interface GridProps +export interface GridProps { - filters: GridFilter[] - cellsH: number - cellsV: number - minCount: number - maxCount: number - maxWeight: number - isSortingTable: boolean + filters: GridFilter[]; + cellsH: number; + cellsV: number; + minCount: number; + maxCount: number; + maxWeight: number; + isSortingTable: boolean; } -export interface GridFilter +export interface GridFilter { - Filter: string[] - ExcludedFilter: string[] + Filter: string[]; + ExcludedFilter: string[]; } -export interface Slot +export interface Slot { - _name: string - _id: string - _parent: string - _props: SlotProps + _name: string; + _id: string; + _parent: string; + _props: SlotProps; // eslint-disable-next-line @typescript-eslint/naming-convention - _max_count?: number - _required?: boolean - _mergeSlotWithChildren?: boolean - _proto: string + _max_count?: number; + _required?: boolean; + _mergeSlotWithChildren?: boolean; + _proto: string; } -export interface SlotProps +export interface SlotProps { - filters: SlotFilter[] + filters: SlotFilter[]; } -export interface SlotFilter +export interface SlotFilter { - Shift?: number - Filter: string[] - AnimationIndex?: number + Shift?: number; + Filter: string[]; + AnimationIndex?: number; } export interface StackSlot { - _name?: string - _id: string - _parent: string + _name?: string; + _id: string; + _parent: string; // eslint-disable-next-line @typescript-eslint/naming-convention - _max_count: number - _props: StackSlotProps - _proto: string - upd: any + _max_count: number; + _props: StackSlotProps; + _proto: string; + upd: any; } -export interface StackSlotProps +export interface StackSlotProps { - filters: SlotFilter[] + filters: SlotFilter[]; } export interface IRandomLootSettings { - allowToSpawnIdenticalItems: boolean - allowToSpawnQuestItems: boolean - countByRarity: any[] - excluded: IRandomLootExcluded - filters: any[] - findInRaid: boolean - maxCount: number - minCount: number + allowToSpawnIdenticalItems: boolean; + allowToSpawnQuestItems: boolean; + countByRarity: any[]; + excluded: IRandomLootExcluded; + filters: any[]; + findInRaid: boolean; + maxCount: number; + minCount: number; } export interface IRandomLootExcluded { - categoryTemplates: any[] - rarity: string[] - templates: any[] + categoryTemplates: any[]; + rarity: string[]; + templates: any[]; } -export interface EffectsHealth +export interface EffectsHealth { - Energy: EffectsHealthProps - Hydration: EffectsHealthProps + Energy: EffectsHealthProps; + Hydration: EffectsHealthProps; } -export interface EffectsHealthProps +export interface EffectsHealthProps { - value: number + value: number; } -export interface EffectsDamage +export interface EffectsDamage { - Pain: IEffectDamageProps - LightBleeding: IEffectDamageProps - HeavyBleeding: IEffectDamageProps - Contusion: IEffectDamageProps - RadExposure: IEffectDamageProps - Fracture: IEffectDamageProps - DestroyedPart: IEffectDamageProps + Pain: IEffectDamageProps; + LightBleeding: IEffectDamageProps; + HeavyBleeding: IEffectDamageProps; + Contusion: IEffectDamageProps; + RadExposure: IEffectDamageProps; + Fracture: IEffectDamageProps; + DestroyedPart: IEffectDamageProps; } -export interface IEffectDamageProps +export interface IEffectDamageProps { - delay: number - duration: number - fadeOut: number - cost?: number - healthPenaltyMin?: number - healthPenaltyMax?: number + delay: number; + duration: number; + fadeOut: number; + cost?: number; + healthPenaltyMin?: number; + healthPenaltyMax?: number; } -export interface IColor +export interface IColor { - r: number - g: number - b: number - a: number -} \ No newline at end of file + r: number; + g: number; + b: number; + a: number; +} diff --git a/project/src/models/eft/common/tables/ITrader.ts b/project/src/models/eft/common/tables/ITrader.ts index 3487a9de..ffe8ada7 100644 --- a/project/src/models/eft/common/tables/ITrader.ts +++ b/project/src/models/eft/common/tables/ITrader.ts @@ -1,122 +1,122 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { Item } from "@spt-aki/models/eft/common/tables/IItem"; -export interface ITrader +export interface ITrader { - assort: ITraderAssort - base: ITraderBase - dialogue?: Record - questassort: Record> - suits?: ISuit[] + assort: ITraderAssort; + base: ITraderBase; + dialogue?: Record; + questassort: Record>; + suits?: ISuit[]; } -export interface ITraderBase +export interface ITraderBase { - refreshTraderRagfairOffers: boolean - _id: string - availableInRaid: boolean - avatar: string - balance_dol: number - balance_eur: number - balance_rub: number - buyer_up: boolean - currency: string - customization_seller: boolean - discount: number - discount_end: number - gridHeight: number - insurance: Insurance - items_buy: IItemBuyData - items_buy_prohibited: IItemBuyData - location: string - loyaltyLevels: LoyaltyLevel[] - medic: boolean - name: string - nextResupply: number - nickname: string - repair: Repair - sell_category: string[] - surname: string - unlockedByDefault: boolean + refreshTraderRagfairOffers: boolean; + _id: string; + availableInRaid: boolean; + avatar: string; + balance_dol: number; + balance_eur: number; + balance_rub: number; + buyer_up: boolean; + currency: string; + customization_seller: boolean; + discount: number; + discount_end: number; + gridHeight: number; + insurance: Insurance; + items_buy: IItemBuyData; + items_buy_prohibited: IItemBuyData; + location: string; + loyaltyLevels: LoyaltyLevel[]; + medic: boolean; + name: string; + nextResupply: number; + nickname: string; + repair: Repair; + sell_category: string[]; + surname: string; + unlockedByDefault: boolean; } export interface IItemBuyData { - category: string[] - id_list: string[] + category: string[]; + id_list: string[]; } -export interface Insurance +export interface Insurance { - availability: boolean - excluded_category: string[] - max_return_hour: number - max_storage_time: number - min_payment: number - min_return_hour: number + availability: boolean; + excluded_category: string[]; + max_return_hour: number; + max_storage_time: number; + min_payment: number; + min_return_hour: number; } -export interface LoyaltyLevel +export interface LoyaltyLevel { - buy_price_coef: number - exchange_price_coef: number - heal_price_coef: number - insurance_price_coef: number - minLevel: number - minSalesSum: number - minStanding: number - repair_price_coef: number + buy_price_coef: number; + exchange_price_coef: number; + heal_price_coef: number; + insurance_price_coef: number; + minLevel: number; + minSalesSum: number; + minStanding: number; + repair_price_coef: number; } -export interface Repair +export interface Repair { - availability: boolean - currency: string - currency_coefficient: number - excluded_category: string[] + availability: boolean; + currency: string; + currency_coefficient: number; + excluded_category: string[]; /** Doesn't exist in client object */ - excluded_id_list: any[] - quality: number + excluded_id_list: any[]; + quality: number; } -export interface ITraderAssort +export interface ITraderAssort { - nextResupply: number - items: Item[] - barter_scheme: Record - loyal_level_items: Record + nextResupply: number; + items: Item[]; + barter_scheme: Record; + loyal_level_items: Record; } -export interface IBarterScheme +export interface IBarterScheme { - count: number - _tpl: string - onlyFunctional?: boolean - sptQuestLocked?: boolean + count: number; + _tpl: string; + onlyFunctional?: boolean; + sptQuestLocked?: boolean; } -export interface ISuit +export interface ISuit { - _id: string - tid: string - suiteId: string - isActive: boolean - requirements: ISuitRequirements + _id: string; + tid: string; + suiteId: string; + isActive: boolean; + requirements: ISuitRequirements; } -export interface ISuitRequirements +export interface ISuitRequirements { - loyaltyLevel: number - profileLevel: number - standing: number - skillRequirements: string[] - questRequirements: string[] - itemRequirements: ItemRequirement[] + loyaltyLevel: number; + profileLevel: number; + standing: number; + skillRequirements: string[]; + questRequirements: string[]; + itemRequirements: ItemRequirement[]; } -export interface ItemRequirement +export interface ItemRequirement { - count: number - _tpl: string - onlyFunctional: boolean + count: number; + _tpl: string; + onlyFunctional: boolean; } diff --git a/project/src/models/eft/customization/IBuyClothingRequestData.ts b/project/src/models/eft/customization/IBuyClothingRequestData.ts index cbdf758b..c5e461e4 100644 --- a/project/src/models/eft/customization/IBuyClothingRequestData.ts +++ b/project/src/models/eft/customization/IBuyClothingRequestData.ts @@ -1,13 +1,13 @@ -export interface IBuyClothingRequestData +export interface IBuyClothingRequestData { - Action: "CustomizationBuy" - offer: string - items: ClothingItem[] + Action: "CustomizationBuy"; + offer: string; + items: ClothingItem[]; } -export interface ClothingItem +export interface ClothingItem { - del: boolean - id: string - count: number + del: boolean; + id: string; + count: number; } diff --git a/project/src/models/eft/customization/IGetSuitsResponse.ts b/project/src/models/eft/customization/IGetSuitsResponse.ts index 0598acdd..d0635c44 100644 --- a/project/src/models/eft/customization/IGetSuitsResponse.ts +++ b/project/src/models/eft/customization/IGetSuitsResponse.ts @@ -1,5 +1,5 @@ export interface IGetSuitsResponse { - _id: string - suites: string[] -} \ No newline at end of file + _id: string; + suites: string[]; +} diff --git a/project/src/models/eft/customization/IWearClothingRequestData.ts b/project/src/models/eft/customization/IWearClothingRequestData.ts index a68b48eb..b4660f94 100644 --- a/project/src/models/eft/customization/IWearClothingRequestData.ts +++ b/project/src/models/eft/customization/IWearClothingRequestData.ts @@ -1,5 +1,5 @@ -export interface IWearClothingRequestData +export interface IWearClothingRequestData { - Action: "CustomizationWear" - suites: string[] -} \ No newline at end of file + Action: "CustomizationWear"; + suites: string[]; +} diff --git a/project/src/models/eft/dialog/IAcceptFriendRequestData.ts b/project/src/models/eft/dialog/IAcceptFriendRequestData.ts index 0434369b..263e76f6 100644 --- a/project/src/models/eft/dialog/IAcceptFriendRequestData.ts +++ b/project/src/models/eft/dialog/IAcceptFriendRequestData.ts @@ -1,15 +1,13 @@ export interface IAcceptFriendRequestData extends IBaseFriendRequest { - } export interface ICancelFriendRequestData extends IBaseFriendRequest { - } export interface IBaseFriendRequest { // eslint-disable-next-line @typescript-eslint/naming-convention - request_id: string + request_id: string; } diff --git a/project/src/models/eft/dialog/IChatServer.ts b/project/src/models/eft/dialog/IChatServer.ts index a5cc9c98..fc44abcb 100644 --- a/project/src/models/eft/dialog/IChatServer.ts +++ b/project/src/models/eft/dialog/IChatServer.ts @@ -1,19 +1,19 @@ export interface IChatServer { - _id: string - RegistrationId: number - VersionId: string - Ip: string - Port: number - DateTime: number - Chats: IChat[] - Regions: string[] + _id: string; + RegistrationId: number; + VersionId: string; + Ip: string; + Port: number; + DateTime: number; + Chats: IChat[]; + Regions: string[]; /** Possibly removed */ - IsDeveloper?: boolean + IsDeveloper?: boolean; } export interface IChat { - _id: string - Members: number -} \ No newline at end of file + _id: string; + Members: number; +} diff --git a/project/src/models/eft/dialog/IClearMailMessageRequest.ts b/project/src/models/eft/dialog/IClearMailMessageRequest.ts index 8aae110a..00c5e33b 100644 --- a/project/src/models/eft/dialog/IClearMailMessageRequest.ts +++ b/project/src/models/eft/dialog/IClearMailMessageRequest.ts @@ -1,4 +1,4 @@ export interface IClearMailMessageRequest { - dialogId: string -} \ No newline at end of file + dialogId: string; +} diff --git a/project/src/models/eft/dialog/IDeleteFriendRequest.ts b/project/src/models/eft/dialog/IDeleteFriendRequest.ts index f0cd8260..8f2c5fcb 100644 --- a/project/src/models/eft/dialog/IDeleteFriendRequest.ts +++ b/project/src/models/eft/dialog/IDeleteFriendRequest.ts @@ -1,5 +1,5 @@ export interface IDeleteFriendRequest { // eslint-disable-next-line @typescript-eslint/naming-convention - friend_id: string -} \ No newline at end of file + friend_id: string; +} diff --git a/project/src/models/eft/dialog/IFriendRequestData.ts b/project/src/models/eft/dialog/IFriendRequestData.ts index 005536f3..63194e7b 100644 --- a/project/src/models/eft/dialog/IFriendRequestData.ts +++ b/project/src/models/eft/dialog/IFriendRequestData.ts @@ -1,4 +1,4 @@ -export interface IFriendRequestData +export interface IFriendRequestData { - to: string -} \ No newline at end of file + to: string; +} diff --git a/project/src/models/eft/dialog/IFriendRequestSendResponse.ts b/project/src/models/eft/dialog/IFriendRequestSendResponse.ts index 3f7fb066..d83579bb 100644 --- a/project/src/models/eft/dialog/IFriendRequestSendResponse.ts +++ b/project/src/models/eft/dialog/IFriendRequestSendResponse.ts @@ -1,6 +1,6 @@ export interface IFriendRequestSendResponse { - status: number - requestid: string - retryAfter: number -} \ No newline at end of file + status: number; + requestid: string; + retryAfter: number; +} diff --git a/project/src/models/eft/dialog/IGetAllAttachmentsRequestData.ts b/project/src/models/eft/dialog/IGetAllAttachmentsRequestData.ts index bb683b6f..5c74c142 100644 --- a/project/src/models/eft/dialog/IGetAllAttachmentsRequestData.ts +++ b/project/src/models/eft/dialog/IGetAllAttachmentsRequestData.ts @@ -1,4 +1,4 @@ -export interface IGetAllAttachmentsRequestData +export interface IGetAllAttachmentsRequestData { - dialogId: string -} \ No newline at end of file + dialogId: string; +} diff --git a/project/src/models/eft/dialog/IGetAllAttachmentsResponse.ts b/project/src/models/eft/dialog/IGetAllAttachmentsResponse.ts index 61cf21da..5ad1c2ef 100644 --- a/project/src/models/eft/dialog/IGetAllAttachmentsResponse.ts +++ b/project/src/models/eft/dialog/IGetAllAttachmentsResponse.ts @@ -2,7 +2,7 @@ import { Message } from "@spt-aki/models/eft/profile/IAkiProfile"; export interface IGetAllAttachmentsResponse { - messages: Message[] - profiles: any[] - hasMessagesWithRewards: boolean -} \ No newline at end of file + messages: Message[]; + profiles: any[]; + hasMessagesWithRewards: boolean; +} diff --git a/project/src/models/eft/dialog/IGetChatServerListRequestData.ts b/project/src/models/eft/dialog/IGetChatServerListRequestData.ts index e16a671d..34fece80 100644 --- a/project/src/models/eft/dialog/IGetChatServerListRequestData.ts +++ b/project/src/models/eft/dialog/IGetChatServerListRequestData.ts @@ -1,4 +1,4 @@ export interface IGetChatServerListRequestData { - VersionId: string -} \ No newline at end of file + VersionId: string; +} diff --git a/project/src/models/eft/dialog/IGetFriendListDataResponse.ts b/project/src/models/eft/dialog/IGetFriendListDataResponse.ts index 454dfd4e..4733ee11 100644 --- a/project/src/models/eft/dialog/IGetFriendListDataResponse.ts +++ b/project/src/models/eft/dialog/IGetFriendListDataResponse.ts @@ -2,7 +2,7 @@ import { IUserDialogInfo } from "@spt-aki/models/eft/profile/IAkiProfile"; export interface IGetFriendListDataResponse { - Friends: IUserDialogInfo[] - Ignore: string[] - InIgnoreList: string[] -} \ No newline at end of file + Friends: IUserDialogInfo[]; + Ignore: string[]; + InIgnoreList: string[]; +} diff --git a/project/src/models/eft/dialog/IGetMailDialogInfoRequestData.ts b/project/src/models/eft/dialog/IGetMailDialogInfoRequestData.ts index c48cddc9..d138cbb7 100644 --- a/project/src/models/eft/dialog/IGetMailDialogInfoRequestData.ts +++ b/project/src/models/eft/dialog/IGetMailDialogInfoRequestData.ts @@ -1,5 +1,4 @@ export interface IGetMailDialogInfoRequestData { dialogId: string; - -} \ No newline at end of file +} diff --git a/project/src/models/eft/dialog/IGetMailDialogListRequestData.ts b/project/src/models/eft/dialog/IGetMailDialogListRequestData.ts index 1a2dbd31..c4605996 100644 --- a/project/src/models/eft/dialog/IGetMailDialogListRequestData.ts +++ b/project/src/models/eft/dialog/IGetMailDialogListRequestData.ts @@ -1,5 +1,5 @@ -export interface IGetMailDialogListRequestData +export interface IGetMailDialogListRequestData { - limit: number - offset: number -} \ No newline at end of file + limit: number; + offset: number; +} diff --git a/project/src/models/eft/dialog/IGetMailDialogViewRequestData.ts b/project/src/models/eft/dialog/IGetMailDialogViewRequestData.ts index 6e07a2fe..3b8f443f 100644 --- a/project/src/models/eft/dialog/IGetMailDialogViewRequestData.ts +++ b/project/src/models/eft/dialog/IGetMailDialogViewRequestData.ts @@ -1,9 +1,9 @@ import { MessageType } from "@spt-aki/models/enums/MessageType"; -export interface IGetMailDialogViewRequestData +export interface IGetMailDialogViewRequestData { - type: MessageType - dialogId: string - limit: number - time: number // decimal -} \ No newline at end of file + type: MessageType; + dialogId: string; + limit: number; + time: number; // decimal +} diff --git a/project/src/models/eft/dialog/IGetMailDialogViewResponseData.ts b/project/src/models/eft/dialog/IGetMailDialogViewResponseData.ts index ef3e5af6..763737d7 100644 --- a/project/src/models/eft/dialog/IGetMailDialogViewResponseData.ts +++ b/project/src/models/eft/dialog/IGetMailDialogViewResponseData.ts @@ -1,8 +1,8 @@ import { IUserDialogInfo, Message } from "@spt-aki/models/eft/profile/IAkiProfile"; -export interface IGetMailDialogViewResponseData +export interface IGetMailDialogViewResponseData { - messages: Message[] - profiles: IUserDialogInfo[] - hasMessagesWithRewards: boolean -} \ No newline at end of file + messages: Message[]; + profiles: IUserDialogInfo[]; + hasMessagesWithRewards: boolean; +} diff --git a/project/src/models/eft/dialog/IPinDialogRequestData.ts b/project/src/models/eft/dialog/IPinDialogRequestData.ts index 68c9793e..6dc1222a 100644 --- a/project/src/models/eft/dialog/IPinDialogRequestData.ts +++ b/project/src/models/eft/dialog/IPinDialogRequestData.ts @@ -1,4 +1,4 @@ -export interface IPinDialogRequestData +export interface IPinDialogRequestData { - dialogId: string -} \ No newline at end of file + dialogId: string; +} diff --git a/project/src/models/eft/dialog/IRemoveDialogRequestData.ts b/project/src/models/eft/dialog/IRemoveDialogRequestData.ts index c2fc47ff..591145f4 100644 --- a/project/src/models/eft/dialog/IRemoveDialogRequestData.ts +++ b/project/src/models/eft/dialog/IRemoveDialogRequestData.ts @@ -1,5 +1,4 @@ -export interface IRemoveDialogRequestData +export interface IRemoveDialogRequestData { dialogId: string; - -} \ No newline at end of file +} diff --git a/project/src/models/eft/dialog/IRemoveMailMessageRequest.ts b/project/src/models/eft/dialog/IRemoveMailMessageRequest.ts index a8ccd80a..1594a15f 100644 --- a/project/src/models/eft/dialog/IRemoveMailMessageRequest.ts +++ b/project/src/models/eft/dialog/IRemoveMailMessageRequest.ts @@ -1,4 +1,4 @@ export interface IRemoveMailMessageRequest { - dialogId: string -} \ No newline at end of file + dialogId: string; +} diff --git a/project/src/models/eft/dialog/ISendMessageRequest.ts b/project/src/models/eft/dialog/ISendMessageRequest.ts index dfbee57a..b09a7e93 100644 --- a/project/src/models/eft/dialog/ISendMessageRequest.ts +++ b/project/src/models/eft/dialog/ISendMessageRequest.ts @@ -2,8 +2,8 @@ import { MessageType } from "@spt-aki/models/enums/MessageType"; export interface ISendMessageRequest { - dialogId: string - type: MessageType - text: string - replyTo: string -} \ No newline at end of file + dialogId: string; + type: MessageType; + text: string; + replyTo: string; +} diff --git a/project/src/models/eft/dialog/ISetDialogReadRequestData.ts b/project/src/models/eft/dialog/ISetDialogReadRequestData.ts index 2fc21721..244d34a8 100644 --- a/project/src/models/eft/dialog/ISetDialogReadRequestData.ts +++ b/project/src/models/eft/dialog/ISetDialogReadRequestData.ts @@ -1,4 +1,4 @@ -export interface ISetDialogReadRequestData +export interface ISetDialogReadRequestData { dialogs: string[]; -} \ No newline at end of file +} diff --git a/project/src/models/eft/game/ICheckVersionResponse.ts b/project/src/models/eft/game/ICheckVersionResponse.ts index 1ce55616..f1cda7bc 100644 --- a/project/src/models/eft/game/ICheckVersionResponse.ts +++ b/project/src/models/eft/game/ICheckVersionResponse.ts @@ -1,5 +1,5 @@ export interface ICheckVersionResponse { - isvalid: boolean, - latestVersion: string -} \ No newline at end of file + isvalid: boolean; + latestVersion: string; +} diff --git a/project/src/models/eft/game/ICurrentGroupResponse.ts b/project/src/models/eft/game/ICurrentGroupResponse.ts index f664d9a3..3b39739e 100644 --- a/project/src/models/eft/game/ICurrentGroupResponse.ts +++ b/project/src/models/eft/game/ICurrentGroupResponse.ts @@ -2,22 +2,22 @@ import { MemberCategory } from "@spt-aki/models/enums/MemberCategory"; export interface ICurrentGroupResponse { - squad: any[] + squad: any[]; } export interface ICurrentGroupSquadMember { - _id: string - aid: string - info: ICurrentGroupMemberInfo - isLeader: boolean - isReady: boolean + _id: string; + aid: string; + info: ICurrentGroupMemberInfo; + isLeader: boolean; + isReady: boolean; } export interface ICurrentGroupMemberInfo { - Nickname: string - Side: string - Level: string - MemberCategory: MemberCategory -} \ No newline at end of file + Nickname: string; + Side: string; + Level: string; + MemberCategory: MemberCategory; +} diff --git a/project/src/models/eft/game/IGameConfigResponse.ts b/project/src/models/eft/game/IGameConfigResponse.ts index 247db660..23672eba 100644 --- a/project/src/models/eft/game/IGameConfigResponse.ts +++ b/project/src/models/eft/game/IGameConfigResponse.ts @@ -1,26 +1,26 @@ export interface IGameConfigResponse { - aid: number - lang: string - languages: Record - ndaFree: boolean - taxonomy: number - activeProfileId: string - backend: Backend - useProtobuf: boolean + aid: number; + lang: string; + languages: Record; + ndaFree: boolean; + taxonomy: number; + activeProfileId: string; + backend: Backend; + useProtobuf: boolean; // eslint-disable-next-line @typescript-eslint/naming-convention - utc_time: number + utc_time: number; /** Total in game time */ - totalInGame: number - reportAvailable: boolean - twitchEventMember: boolean + totalInGame: number; + reportAvailable: boolean; + twitchEventMember: boolean; } - + export interface Backend { - Lobby: string - Trading: string - Messaging: string - Main: string - RagFair: string -} \ No newline at end of file + Lobby: string; + Trading: string; + Messaging: string; + Main: string; + RagFair: string; +} diff --git a/project/src/models/eft/game/IGameEmptyCrcRequestData.ts b/project/src/models/eft/game/IGameEmptyCrcRequestData.ts index 0b19da50..8518f9a7 100644 --- a/project/src/models/eft/game/IGameEmptyCrcRequestData.ts +++ b/project/src/models/eft/game/IGameEmptyCrcRequestData.ts @@ -1,4 +1,4 @@ -export interface IGameEmptyCrcRequestData +export interface IGameEmptyCrcRequestData { - crc: number -} \ No newline at end of file + crc: number; +} diff --git a/project/src/models/eft/game/IGameKeepAliveResponse.ts b/project/src/models/eft/game/IGameKeepAliveResponse.ts index 6ad9b738..48d631f8 100644 --- a/project/src/models/eft/game/IGameKeepAliveResponse.ts +++ b/project/src/models/eft/game/IGameKeepAliveResponse.ts @@ -1,6 +1,6 @@ export interface IGameKeepAliveResponse { - msg: string + msg: string; // eslint-disable-next-line @typescript-eslint/naming-convention - utc_time: number -} \ No newline at end of file + utc_time: number; +} diff --git a/project/src/models/eft/game/IGameLogoutResponseData.ts b/project/src/models/eft/game/IGameLogoutResponseData.ts index 81b9679b..f3374559 100644 --- a/project/src/models/eft/game/IGameLogoutResponseData.ts +++ b/project/src/models/eft/game/IGameLogoutResponseData.ts @@ -1,4 +1,4 @@ export interface IGameLogoutResponseData { - status: string -} \ No newline at end of file + status: string; +} diff --git a/project/src/models/eft/game/IGameStartResponse.ts b/project/src/models/eft/game/IGameStartResponse.ts index 0f176899..7172081f 100644 --- a/project/src/models/eft/game/IGameStartResponse.ts +++ b/project/src/models/eft/game/IGameStartResponse.ts @@ -1,5 +1,5 @@ export interface IGameStartResponse { // eslint-disable-next-line @typescript-eslint/naming-convention - utc_time: number -} \ No newline at end of file + utc_time: number; +} diff --git a/project/src/models/eft/game/IGetItemPricesResponse.ts b/project/src/models/eft/game/IGetItemPricesResponse.ts index 1878f9c3..ab2bc2db 100644 --- a/project/src/models/eft/game/IGetItemPricesResponse.ts +++ b/project/src/models/eft/game/IGetItemPricesResponse.ts @@ -1,6 +1,6 @@ export interface IGetItemPricesResponse { - supplyNextTime: number - prices: Record - currencyCourses: Record -} \ No newline at end of file + supplyNextTime: number; + prices: Record; + currencyCourses: Record; +} diff --git a/project/src/models/eft/game/IReportNicknameRequestData.ts b/project/src/models/eft/game/IReportNicknameRequestData.ts index cc94e79a..bbce9814 100644 --- a/project/src/models/eft/game/IReportNicknameRequestData.ts +++ b/project/src/models/eft/game/IReportNicknameRequestData.ts @@ -1,4 +1,4 @@ export interface IReportNicknameRequestData { - uid: string -} \ No newline at end of file + uid: string; +} diff --git a/project/src/models/eft/game/IServerDetails.ts b/project/src/models/eft/game/IServerDetails.ts index f534d678..7d082d3e 100644 --- a/project/src/models/eft/game/IServerDetails.ts +++ b/project/src/models/eft/game/IServerDetails.ts @@ -1,5 +1,5 @@ export interface IServerDetails { - ip: string - port: number -} \ No newline at end of file + ip: string; + port: number; +} diff --git a/project/src/models/eft/game/IVersionValidateRequestData.ts b/project/src/models/eft/game/IVersionValidateRequestData.ts index ef9770ab..35730eba 100644 --- a/project/src/models/eft/game/IVersionValidateRequestData.ts +++ b/project/src/models/eft/game/IVersionValidateRequestData.ts @@ -1,14 +1,14 @@ -export interface IVersionValidateRequestData +export interface IVersionValidateRequestData { - version: Version - develop: boolean + version: Version; + develop: boolean; } -export interface Version +export interface Version { - major: string - minor: string - game: string - backend: string - taxonomy: string -} \ No newline at end of file + major: string; + minor: string; + game: string; + backend: string; + taxonomy: string; +} diff --git a/project/src/models/eft/health/Effect.ts b/project/src/models/eft/health/Effect.ts index ed9ac7ec..b27f856a 100644 --- a/project/src/models/eft/health/Effect.ts +++ b/project/src/models/eft/health/Effect.ts @@ -1,8 +1,8 @@ export enum Effect - { +{ FRACTURE = "Fracture", LIGHT_BLEEDING = "LightBleeding", HEAVY_BLEEDING = "HeavyBleeding", MILD_MUSCLE_PAIN = "MildMusclePain", - SEVERE_MUSCLE_PAIN = "SevereMusclePain" -} \ No newline at end of file + SEVERE_MUSCLE_PAIN = "SevereMusclePain", +} diff --git a/project/src/models/eft/health/IHealthTreatmentRequestData.ts b/project/src/models/eft/health/IHealthTreatmentRequestData.ts index ddfb1182..ec5859d7 100644 --- a/project/src/models/eft/health/IHealthTreatmentRequestData.ts +++ b/project/src/models/eft/health/IHealthTreatmentRequestData.ts @@ -1,41 +1,41 @@ -export interface IHealthTreatmentRequestData +export interface IHealthTreatmentRequestData { - Action: "RestoreHealth" - trader: string - items: Cost[] - difference: Difference - timestamp: number + Action: "RestoreHealth"; + trader: string; + items: Cost[]; + difference: Difference; + timestamp: number; } -export interface Cost +export interface Cost { /** Id of stack to take money from */ - id: string + id: string; /** Amount of money to take off player for treatment */ - count: number + count: number; } -export interface Difference +export interface Difference { - BodyParts: BodyParts - Energy: number - Hydration: number + BodyParts: BodyParts; + Energy: number; + Hydration: number; } -export interface BodyParts +export interface BodyParts { - Head: BodyPart - Chest: BodyPart - Stomach: BodyPart - LeftArm: BodyPart - RightArm: BodyPart - LeftLeg: BodyPart - RightLeg: BodyPart + Head: BodyPart; + Chest: BodyPart; + Stomach: BodyPart; + LeftArm: BodyPart; + RightArm: BodyPart; + LeftLeg: BodyPart; + RightLeg: BodyPart; } -export interface BodyPart +export interface BodyPart { - Health: number + Health: number; /** Effects in array are to be removed */ - Effects: string[] -} \ No newline at end of file + Effects: string[]; +} diff --git a/project/src/models/eft/health/IOffraidEatRequestData.ts b/project/src/models/eft/health/IOffraidEatRequestData.ts index 11b6d41d..a327bea0 100644 --- a/project/src/models/eft/health/IOffraidEatRequestData.ts +++ b/project/src/models/eft/health/IOffraidEatRequestData.ts @@ -1,9 +1,9 @@ import { IBaseInteractionRequestData } from "@spt-aki/models/eft/common/request/IBaseInteractionRequestData"; -export interface IOffraidEatRequestData extends IBaseInteractionRequestData +export interface IOffraidEatRequestData extends IBaseInteractionRequestData { - Action: "Eat" - item: string - count: number - time: number -} \ No newline at end of file + Action: "Eat"; + item: string; + count: number; + time: number; +} diff --git a/project/src/models/eft/health/IOffraidHealRequestData.ts b/project/src/models/eft/health/IOffraidHealRequestData.ts index dd922b4d..db7570e9 100644 --- a/project/src/models/eft/health/IOffraidHealRequestData.ts +++ b/project/src/models/eft/health/IOffraidHealRequestData.ts @@ -1,16 +1,16 @@ import { IBaseInteractionRequestData } from "@spt-aki/models/eft/common/request/IBaseInteractionRequestData"; -export interface IOffraidHealRequestData extends IBaseInteractionRequestData +export interface IOffraidHealRequestData extends IBaseInteractionRequestData { - Action: "Heal" - item: string - part: BodyPart - count: number - time: number + Action: "Heal"; + item: string; + part: BodyPart; + count: number; + time: number; } -export enum BodyPart - { +export enum BodyPart +{ HEAD = "Head", CHEST = "Chest", STOMACH = "Stomach", @@ -18,5 +18,5 @@ export enum BodyPart RIGHT_ARM = "RightArm", LEFT_LEG = "LeftLeg", RIGHT_LEG = "RightLeg", - COMMON = "Common" -} \ No newline at end of file + COMMON = "Common", +} diff --git a/project/src/models/eft/health/ISyncHealthRequestData.ts b/project/src/models/eft/health/ISyncHealthRequestData.ts index 8d9ddd73..5b59155a 100644 --- a/project/src/models/eft/health/ISyncHealthRequestData.ts +++ b/project/src/models/eft/health/ISyncHealthRequestData.ts @@ -1,26 +1,26 @@ -export interface ISyncHealthRequestData +export interface ISyncHealthRequestData { - Health: Health - IsAlive: boolean - Hydration?: number - Energy?: number - Temperature?: number + Health: Health; + IsAlive: boolean; + Hydration?: number; + Energy?: number; + Temperature?: number; } -export interface Health +export interface Health { - Head?: BodyPartHealth - Chest?: BodyPartHealth - Stomach?: BodyPartHealth - LeftArm?: BodyPartHealth - RightArm?: BodyPartHealth - LeftLeg?: BodyPartHealth - RightLeg?: BodyPartHealth + Head?: BodyPartHealth; + Chest?: BodyPartHealth; + Stomach?: BodyPartHealth; + LeftArm?: BodyPartHealth; + RightArm?: BodyPartHealth; + LeftLeg?: BodyPartHealth; + RightLeg?: BodyPartHealth; } -export interface BodyPartHealth +export interface BodyPartHealth { - Maximum: number - Current: number - Effects: Record + Maximum: number; + Current: number; + Effects: Record; } diff --git a/project/src/models/eft/health/IWorkoutData.ts b/project/src/models/eft/health/IWorkoutData.ts index cea5b5e0..36080734 100644 --- a/project/src/models/eft/health/IWorkoutData.ts +++ b/project/src/models/eft/health/IWorkoutData.ts @@ -1,7 +1,7 @@ // TODO: Type this properly. -export interface IWorkoutData extends Record +export interface IWorkoutData extends Record { - skills: any - effects: any -} \ No newline at end of file + skills: any; + effects: any; +} diff --git a/project/src/models/eft/hideout/HideoutUpgradeCompleteRequestData.ts b/project/src/models/eft/hideout/HideoutUpgradeCompleteRequestData.ts index 6a5ec4bd..5c8035c2 100644 --- a/project/src/models/eft/hideout/HideoutUpgradeCompleteRequestData.ts +++ b/project/src/models/eft/hideout/HideoutUpgradeCompleteRequestData.ts @@ -1,6 +1,6 @@ -export interface HideoutUpgradeCompleteRequestData +export interface HideoutUpgradeCompleteRequestData { - Action: string - areaType: number - timestamp: number -} \ No newline at end of file + Action: string; + areaType: number; + timestamp: number; +} diff --git a/project/src/models/eft/hideout/IHandleQTEEventRequestData.ts b/project/src/models/eft/hideout/IHandleQTEEventRequestData.ts index aac182c4..b2692536 100644 --- a/project/src/models/eft/hideout/IHandleQTEEventRequestData.ts +++ b/project/src/models/eft/hideout/IHandleQTEEventRequestData.ts @@ -1,9 +1,9 @@ export interface IHandleQTEEventRequestData { - Action: string + Action: string; /** true if QTE was successful, otherwise false */ - results: boolean[] + results: boolean[]; /** Id of the QTE object used from db/hideout/qte.json */ - id: string - timestamp: number -} \ No newline at end of file + id: string; + timestamp: number; +} diff --git a/project/src/models/eft/hideout/IHideoutArea.ts b/project/src/models/eft/hideout/IHideoutArea.ts index 88d2eb37..b134eb72 100644 --- a/project/src/models/eft/hideout/IHideoutArea.ts +++ b/project/src/models/eft/hideout/IHideoutArea.ts @@ -1,91 +1,91 @@ -export interface IHideoutArea +export interface IHideoutArea { - _id: string - type: number - enabled: boolean - needsFuel: boolean - requirements: IAreaRequirement[] - takeFromSlotLocked: boolean - craftGivesExp: boolean - displayLevel: boolean - enableAreaRequirements: boolean - parentArea?: string - stages: Record + _id: string; + type: number; + enabled: boolean; + needsFuel: boolean; + requirements: IAreaRequirement[]; + takeFromSlotLocked: boolean; + craftGivesExp: boolean; + displayLevel: boolean; + enableAreaRequirements: boolean; + parentArea?: string; + stages: Record; } export interface IAreaRequirement { - areaType: number - requiredlevel: number - type: string + areaType: number; + requiredlevel: number; + type: string; } export interface Stage { - autoUpgrade: boolean - bonuses: StageBonus[] - constructionTime: number + autoUpgrade: boolean; + bonuses: StageBonus[]; + constructionTime: number; /** Containers inventory tpl */ - container?: string - description: string - displayInterface: boolean - improvements: IStageImprovement[] - requirements: IStageRequirement[] - slots: number + container?: string; + description: string; + displayInterface: boolean; + improvements: IStageImprovement[]; + requirements: IStageRequirement[]; + slots: number; } export interface IStageImprovement { - id: string - bonuses: IStageImprovementBonus[] - improvementTime: number - requirements: IStageImprovementRequirement[] + id: string; + bonuses: IStageImprovementBonus[]; + improvementTime: number; + requirements: IStageImprovementRequirement[]; } export interface IStageImprovementBonus { - passive: boolean, - production: boolean, - type: string - value: number, - visible: boolean + passive: boolean; + production: boolean; + type: string; + value: number; + visible: boolean; } export interface IStageImprovementRequirement { - count: number - isEncoded: boolean - isFunctional: boolean - templateId: string - type: string + count: number; + isEncoded: boolean; + isFunctional: boolean; + templateId: string; + type: string; } -export interface IStageRequirement +export interface IStageRequirement { - areaType?: number - requiredLevel?: number - type: string - templateId?: string - count?: number - isEncoded: false - isFunctional?: boolean - traderId?: string - loyaltyLevel?: number - skillName?: string - skillLevel?: number + areaType?: number; + requiredLevel?: number; + type: string; + templateId?: string; + count?: number; + isEncoded: false; + isFunctional?: boolean; + traderId?: string; + loyaltyLevel?: number; + skillName?: string; + skillLevel?: number; } -export interface StageBonus +export interface StageBonus { - value: number - passive: boolean - production: boolean - visible: boolean - skillType?: string - type: string - filter?: string[] - icon?: string + value: number; + passive: boolean; + production: boolean; + visible: boolean; + skillType?: string; + type: string; + filter?: string[]; + icon?: string; /** CHANGES PER DUMP */ - id?: string - templateId?: string -} \ No newline at end of file + id?: string; + templateId?: string; +} diff --git a/project/src/models/eft/hideout/IHideoutCancelProductionRequestData.ts b/project/src/models/eft/hideout/IHideoutCancelProductionRequestData.ts index e076acd7..c9986ac8 100644 --- a/project/src/models/eft/hideout/IHideoutCancelProductionRequestData.ts +++ b/project/src/models/eft/hideout/IHideoutCancelProductionRequestData.ts @@ -1,6 +1,6 @@ -export interface IHideoutCancelProductionRequestData +export interface IHideoutCancelProductionRequestData { - Action: "HideoutCancelProductionCommand" - recipeId: string - timestamp: number + Action: "HideoutCancelProductionCommand"; + recipeId: string; + timestamp: number; } diff --git a/project/src/models/eft/hideout/IHideoutContinuousProductionStartRequestData.ts b/project/src/models/eft/hideout/IHideoutContinuousProductionStartRequestData.ts index 34d63171..8598c7a2 100644 --- a/project/src/models/eft/hideout/IHideoutContinuousProductionStartRequestData.ts +++ b/project/src/models/eft/hideout/IHideoutContinuousProductionStartRequestData.ts @@ -1,6 +1,6 @@ -export interface IHideoutContinuousProductionStartRequestData +export interface IHideoutContinuousProductionStartRequestData { - Action: "HideoutContinuousProductionStart" - recipeId: string - timestamp: number -} \ No newline at end of file + Action: "HideoutContinuousProductionStart"; + recipeId: string; + timestamp: number; +} diff --git a/project/src/models/eft/hideout/IHideoutImproveAreaRequestData.ts b/project/src/models/eft/hideout/IHideoutImproveAreaRequestData.ts index cdb45648..5c033735 100644 --- a/project/src/models/eft/hideout/IHideoutImproveAreaRequestData.ts +++ b/project/src/models/eft/hideout/IHideoutImproveAreaRequestData.ts @@ -1,16 +1,16 @@ export interface IHideoutImproveAreaRequestData { - Action: "HideoutImproveArea" + Action: "HideoutImproveArea"; /** Hideout area id from areas.json */ - id: string - areaType: number - items: HideoutItem[] - timestamp: number + id: string; + areaType: number; + items: HideoutItem[]; + timestamp: number; } export interface HideoutItem { /** Hideout inventory id that was used by improvement action */ - id: string - count: number -} \ No newline at end of file + id: string; + count: number; +} diff --git a/project/src/models/eft/hideout/IHideoutProduction.ts b/project/src/models/eft/hideout/IHideoutProduction.ts index 0e103bc5..d1e474b1 100644 --- a/project/src/models/eft/hideout/IHideoutProduction.ts +++ b/project/src/models/eft/hideout/IHideoutProduction.ts @@ -1,27 +1,27 @@ -export interface IHideoutProduction +export interface IHideoutProduction { - _id: string - areaType: number - requirements: Requirement[] - productionTime: number - endProduct: string - isEncoded: boolean - locked: boolean - needFuelForAllProductionTime: boolean - continuous: boolean - count: number - productionLimitCount: number + _id: string; + areaType: number; + requirements: Requirement[]; + productionTime: number; + endProduct: string; + isEncoded: boolean; + locked: boolean; + needFuelForAllProductionTime: boolean; + continuous: boolean; + count: number; + productionLimitCount: number; } -export interface Requirement +export interface Requirement { - templateId?: string - count?: number - isEncoded?: boolean - isFunctional?: boolean - type: string - areaType?: number - requiredLevel?: number - resource?: number - questId?: string -} \ No newline at end of file + templateId?: string; + count?: number; + isEncoded?: boolean; + isFunctional?: boolean; + type: string; + areaType?: number; + requiredLevel?: number; + resource?: number; + questId?: string; +} diff --git a/project/src/models/eft/hideout/IHideoutPutItemInRequestData.ts b/project/src/models/eft/hideout/IHideoutPutItemInRequestData.ts index eaf6a754..6f31cea3 100644 --- a/project/src/models/eft/hideout/IHideoutPutItemInRequestData.ts +++ b/project/src/models/eft/hideout/IHideoutPutItemInRequestData.ts @@ -1,13 +1,13 @@ export interface IHideoutPutItemInRequestData { - Action: "HideoutPutItemsInAreaSlots" - areaType: number - items: Record - timestamp: number + Action: "HideoutPutItemsInAreaSlots"; + areaType: number; + items: Record; + timestamp: number; } - -export interface ItemDetails + +export interface ItemDetails { - count: number - id: string -} \ No newline at end of file + count: number; + id: string; +} diff --git a/project/src/models/eft/hideout/IHideoutScavCase.ts b/project/src/models/eft/hideout/IHideoutScavCase.ts index f3e939e4..55dc1abd 100644 --- a/project/src/models/eft/hideout/IHideoutScavCase.ts +++ b/project/src/models/eft/hideout/IHideoutScavCase.ts @@ -1,23 +1,23 @@ import { MinMax } from "@spt-aki/models/common/MinMax"; -export interface IHideoutScavCase +export interface IHideoutScavCase { - _id: string - ProductionTime: number - Requirements: Requirement[] - EndProducts: EndProducts + _id: string; + ProductionTime: number; + Requirements: Requirement[]; + EndProducts: EndProducts; } -export interface Requirement +export interface Requirement { - templateId: string - count: number - isFunctional: boolean - type: string + templateId: string; + count: number; + isFunctional: boolean; + type: string; } - -export interface EndProducts + +export interface EndProducts { - Common: MinMax - Rare: MinMax - Superrare: MinMax + Common: MinMax; + Rare: MinMax; + Superrare: MinMax; } diff --git a/project/src/models/eft/hideout/IHideoutScavCaseStartRequestData.ts b/project/src/models/eft/hideout/IHideoutScavCaseStartRequestData.ts index 399efa0f..a97a5655 100644 --- a/project/src/models/eft/hideout/IHideoutScavCaseStartRequestData.ts +++ b/project/src/models/eft/hideout/IHideoutScavCaseStartRequestData.ts @@ -1,20 +1,20 @@ -export interface IHideoutScavCaseStartRequestData +export interface IHideoutScavCaseStartRequestData { - Action: "HideoutScavCaseProductionStart" - recipeId: string - items: HideoutItem[] - tools: Tool[] - timestamp: number + Action: "HideoutScavCaseProductionStart"; + recipeId: string; + items: HideoutItem[]; + tools: Tool[]; + timestamp: number; } -export interface HideoutItem +export interface HideoutItem { - id: string - count: number + id: string; + count: number; } export interface Tool { - id: string - count: number -} \ No newline at end of file + id: string; + count: number; +} diff --git a/project/src/models/eft/hideout/IHideoutSettingsBase.ts b/project/src/models/eft/hideout/IHideoutSettingsBase.ts index f7a57ac8..8432cd43 100644 --- a/project/src/models/eft/hideout/IHideoutSettingsBase.ts +++ b/project/src/models/eft/hideout/IHideoutSettingsBase.ts @@ -1,7 +1,7 @@ -export interface IHideoutSettingsBase +export interface IHideoutSettingsBase { - generatorSpeedWithoutFuel: number - generatorFuelFlowRate: number - airFilterUnitFlowRate: number - gpuBoostRate: number -} \ No newline at end of file + generatorSpeedWithoutFuel: number; + generatorFuelFlowRate: number; + airFilterUnitFlowRate: number; + gpuBoostRate: number; +} diff --git a/project/src/models/eft/hideout/IHideoutSingleProductionStartRequestData.ts b/project/src/models/eft/hideout/IHideoutSingleProductionStartRequestData.ts index 11f86cad..b63bd356 100644 --- a/project/src/models/eft/hideout/IHideoutSingleProductionStartRequestData.ts +++ b/project/src/models/eft/hideout/IHideoutSingleProductionStartRequestData.ts @@ -1,13 +1,13 @@ -export interface IHideoutSingleProductionStartRequestData +export interface IHideoutSingleProductionStartRequestData { - Action: "HideoutSingleProductionStart" - recipeId: string - items: Item[] - timestamp: number + Action: "HideoutSingleProductionStart"; + recipeId: string; + items: Item[]; + timestamp: number; } -export interface Item +export interface Item { - id: string - count: number -} \ No newline at end of file + id: string; + count: number; +} diff --git a/project/src/models/eft/hideout/IHideoutTakeItemOutRequestData.ts b/project/src/models/eft/hideout/IHideoutTakeItemOutRequestData.ts index d96e34c7..28577924 100644 --- a/project/src/models/eft/hideout/IHideoutTakeItemOutRequestData.ts +++ b/project/src/models/eft/hideout/IHideoutTakeItemOutRequestData.ts @@ -1,7 +1,7 @@ -export interface IHideoutTakeItemOutRequestData +export interface IHideoutTakeItemOutRequestData { - Action: "HideoutTakeItemsFromAreaSlots" - areaType: number - slots: number[] - timestamp: number -} \ No newline at end of file + Action: "HideoutTakeItemsFromAreaSlots"; + areaType: number; + slots: number[]; + timestamp: number; +} diff --git a/project/src/models/eft/hideout/IHideoutTakeProductionRequestData.ts b/project/src/models/eft/hideout/IHideoutTakeProductionRequestData.ts index 19861322..33b94f78 100644 --- a/project/src/models/eft/hideout/IHideoutTakeProductionRequestData.ts +++ b/project/src/models/eft/hideout/IHideoutTakeProductionRequestData.ts @@ -1,6 +1,6 @@ -export interface IHideoutTakeProductionRequestData +export interface IHideoutTakeProductionRequestData { - Action: "HideoutTakeProduction" - recipeId: string - timestamp: number -} \ No newline at end of file + Action: "HideoutTakeProduction"; + recipeId: string; + timestamp: number; +} diff --git a/project/src/models/eft/hideout/IHideoutToggleAreaRequestData.ts b/project/src/models/eft/hideout/IHideoutToggleAreaRequestData.ts index 9a9eb906..036c53b5 100644 --- a/project/src/models/eft/hideout/IHideoutToggleAreaRequestData.ts +++ b/project/src/models/eft/hideout/IHideoutToggleAreaRequestData.ts @@ -1,7 +1,7 @@ -export interface IHideoutToggleAreaRequestData +export interface IHideoutToggleAreaRequestData { - Action: "HideoutToggleArea" - areaType: number - enabled: boolean - timestamp: number -} \ No newline at end of file + Action: "HideoutToggleArea"; + areaType: number; + enabled: boolean; + timestamp: number; +} diff --git a/project/src/models/eft/hideout/IHideoutUpgradeCompleteRequestData.ts b/project/src/models/eft/hideout/IHideoutUpgradeCompleteRequestData.ts index feef6bf1..5b12263d 100644 --- a/project/src/models/eft/hideout/IHideoutUpgradeCompleteRequestData.ts +++ b/project/src/models/eft/hideout/IHideoutUpgradeCompleteRequestData.ts @@ -1,6 +1,6 @@ -export interface IHideoutUpgradeCompleteRequestData +export interface IHideoutUpgradeCompleteRequestData { - Action: "HideoutUpgradeComplete" - areaType: number - timestamp: number -} \ No newline at end of file + Action: "HideoutUpgradeComplete"; + areaType: number; + timestamp: number; +} diff --git a/project/src/models/eft/hideout/IHideoutUpgradeRequestData.ts b/project/src/models/eft/hideout/IHideoutUpgradeRequestData.ts index f5661eaf..4e6c03a2 100644 --- a/project/src/models/eft/hideout/IHideoutUpgradeRequestData.ts +++ b/project/src/models/eft/hideout/IHideoutUpgradeRequestData.ts @@ -1,13 +1,13 @@ -export interface IHideoutUpgradeRequestData +export interface IHideoutUpgradeRequestData { - Action: "HideoutUpgrade" - areaType: number - items: HideoutItem[] - timestamp: number + Action: "HideoutUpgrade"; + areaType: number; + items: HideoutItem[]; + timestamp: number; } -export interface HideoutItem +export interface HideoutItem { - count: number - id: string -} \ No newline at end of file + count: number; + id: string; +} diff --git a/project/src/models/eft/hideout/IQteData.ts b/project/src/models/eft/hideout/IQteData.ts index 3523d1ea..6f1f9e37 100644 --- a/project/src/models/eft/hideout/IQteData.ts +++ b/project/src/models/eft/hideout/IQteData.ts @@ -1,48 +1,48 @@ export interface IQteData { - Id: string - Type: string - Area: string - AreaLevel: number - QuickTimeEvents: IQuickTimeEvent[] - Requirements: IQteRequirement[] - Results: Record + Id: string; + Type: string; + Area: string; + AreaLevel: number; + QuickTimeEvents: IQuickTimeEvent[]; + Requirements: IQteRequirement[]; + Results: Record; } export interface IQuickTimeEvent { - Type: string - Position: number - StartDelay: number - EndDelay: number - Speed: number - SuccessRange: string - Key: string + Type: string; + Position: number; + StartDelay: number; + EndDelay: number; + Speed: number; + SuccessRange: string; + Key: string; } export interface IQteRequirement { - type: string + type: string; } export interface IQteResult { - Energy: number - Hydration: number - RewardsRange: IQteEffect[] + Energy: number; + Hydration: number; + RewardsRange: IQteEffect[]; } export interface IQteEffect { - Type: string - SkillId: string - levelMultipliers: ISkillLevelMultiplier[] - Time: number - Weight: number - Result: string + Type: string; + SkillId: string; + levelMultipliers: ISkillLevelMultiplier[]; + Time: number; + Weight: number; + Result: string; } export interface ISkillLevelMultiplier { - level: number - multiplier: number -} \ No newline at end of file + level: number; + multiplier: number; +} diff --git a/project/src/models/eft/hideout/IRecordShootingRangePoints.ts b/project/src/models/eft/hideout/IRecordShootingRangePoints.ts index 6367b02d..9a872848 100644 --- a/project/src/models/eft/hideout/IRecordShootingRangePoints.ts +++ b/project/src/models/eft/hideout/IRecordShootingRangePoints.ts @@ -1,5 +1,5 @@ export interface IRecordShootingRangePoints { - Action: "RecordShootingRangePoints" - points: number -} \ No newline at end of file + Action: "RecordShootingRangePoints"; + points: number; +} diff --git a/project/src/models/eft/httpResponse/IGetBodyResponseData.ts b/project/src/models/eft/httpResponse/IGetBodyResponseData.ts index 6a2e0f34..feff4081 100644 --- a/project/src/models/eft/httpResponse/IGetBodyResponseData.ts +++ b/project/src/models/eft/httpResponse/IGetBodyResponseData.ts @@ -1,6 +1,6 @@ -export interface IGetBodyResponseData +export interface IGetBodyResponseData { - err: number - errmsg: any - (data: Type): Type -} \ No newline at end of file + err: number; + errmsg: any; + (data: Type): Type; +} diff --git a/project/src/models/eft/httpResponse/INullResponseData.ts b/project/src/models/eft/httpResponse/INullResponseData.ts index 938c1f3d..72038291 100644 --- a/project/src/models/eft/httpResponse/INullResponseData.ts +++ b/project/src/models/eft/httpResponse/INullResponseData.ts @@ -1,6 +1,6 @@ -export interface INullResponseData +export interface INullResponseData { - err: number - errmsg: any - data: null -} \ No newline at end of file + err: number; + errmsg: any; + data: null; +} diff --git a/project/src/models/eft/inRaid/IInsuredItemsData.ts b/project/src/models/eft/inRaid/IInsuredItemsData.ts index 55367fd0..037c3308 100644 --- a/project/src/models/eft/inRaid/IInsuredItemsData.ts +++ b/project/src/models/eft/inRaid/IInsuredItemsData.ts @@ -1,7 +1,7 @@ -export interface IInsuredItemsData +export interface IInsuredItemsData { - id: string - durability?: number - maxDurability?: number - hits?: number -} \ No newline at end of file + id: string; + durability?: number; + maxDurability?: number; + hits?: number; +} diff --git a/project/src/models/eft/inRaid/IRegisterPlayerRequestData.ts b/project/src/models/eft/inRaid/IRegisterPlayerRequestData.ts index 24fb8a8b..bec81afa 100644 --- a/project/src/models/eft/inRaid/IRegisterPlayerRequestData.ts +++ b/project/src/models/eft/inRaid/IRegisterPlayerRequestData.ts @@ -1,6 +1,6 @@ -export interface IRegisterPlayerRequestData +export interface IRegisterPlayerRequestData { - crc: number - locationId: string - variantId: number -} \ No newline at end of file + crc: number; + locationId: string; + variantId: number; +} diff --git a/project/src/models/eft/inRaid/ISaveProgressRequestData.ts b/project/src/models/eft/inRaid/ISaveProgressRequestData.ts index 4defa3d9..cf9a8964 100644 --- a/project/src/models/eft/inRaid/ISaveProgressRequestData.ts +++ b/project/src/models/eft/inRaid/ISaveProgressRequestData.ts @@ -3,11 +3,11 @@ import { ISyncHealthRequestData } from "@spt-aki/models/eft/health/ISyncHealthRe import { IInsuredItemsData } from "@spt-aki/models/eft/inRaid/IInsuredItemsData"; import { PlayerRaidEndState } from "@spt-aki/models/enums/PlayerRaidEndState"; -export interface ISaveProgressRequestData +export interface ISaveProgressRequestData { - exit: PlayerRaidEndState // survived" | "killed" | "left" | "runner" | "missinginaction - profile: IPostRaidPmcData - isPlayerScav: boolean - health: ISyncHealthRequestData - insurance: IInsuredItemsData[] -} \ No newline at end of file + exit: PlayerRaidEndState; // survived" | "killed" | "left" | "runner" | "missinginaction + profile: IPostRaidPmcData; + isPlayerScav: boolean; + health: ISyncHealthRequestData; + insurance: IInsuredItemsData[]; +} diff --git a/project/src/models/eft/insurance/IGetInsuranceCostRequestData.ts b/project/src/models/eft/insurance/IGetInsuranceCostRequestData.ts index db4c7642..99ee41a6 100644 --- a/project/src/models/eft/insurance/IGetInsuranceCostRequestData.ts +++ b/project/src/models/eft/insurance/IGetInsuranceCostRequestData.ts @@ -1,5 +1,5 @@ -export interface IGetInsuranceCostRequestData +export interface IGetInsuranceCostRequestData { - traders: string[] - items: string[] -} \ No newline at end of file + traders: string[]; + items: string[]; +} diff --git a/project/src/models/eft/insurance/IGetInsuranceCostResponseData.ts b/project/src/models/eft/insurance/IGetInsuranceCostResponseData.ts index 5d29b2d0..4579fdbe 100644 --- a/project/src/models/eft/insurance/IGetInsuranceCostResponseData.ts +++ b/project/src/models/eft/insurance/IGetInsuranceCostResponseData.ts @@ -1 +1 @@ -export type IGetInsuranceCostResponseData = Record> \ No newline at end of file +export type IGetInsuranceCostResponseData = Record>; diff --git a/project/src/models/eft/insurance/IInsureRequestData.ts b/project/src/models/eft/insurance/IInsureRequestData.ts index 34bbd0d2..04b309bd 100644 --- a/project/src/models/eft/insurance/IInsureRequestData.ts +++ b/project/src/models/eft/insurance/IInsureRequestData.ts @@ -1,8 +1,8 @@ import { IBaseInteractionRequestData } from "@spt-aki/models/eft/common/request/IBaseInteractionRequestData"; -export interface IInsureRequestData extends IBaseInteractionRequestData +export interface IInsureRequestData extends IBaseInteractionRequestData { - Action: "Insure" - tid: string - items: string[] -} \ No newline at end of file + Action: "Insure"; + tid: string; + items: string[]; +} diff --git a/project/src/models/eft/inventory/IAddItemRequestData.ts b/project/src/models/eft/inventory/IAddItemRequestData.ts index f3bbd14a..8c615082 100644 --- a/project/src/models/eft/inventory/IAddItemRequestData.ts +++ b/project/src/models/eft/inventory/IAddItemRequestData.ts @@ -11,4 +11,4 @@ export interface AddItem isPreset?: boolean; // eslint-disable-next-line @typescript-eslint/naming-convention item_id: string; -} \ No newline at end of file +} diff --git a/project/src/models/eft/inventory/IAddItemTempObject.ts b/project/src/models/eft/inventory/IAddItemTempObject.ts index 3e910e28..762ca648 100644 --- a/project/src/models/eft/inventory/IAddItemTempObject.ts +++ b/project/src/models/eft/inventory/IAddItemTempObject.ts @@ -2,10 +2,10 @@ import { Item, Location } from "@spt-aki/models/eft/common/tables/IItem"; export interface IAddItemTempObject { - itemRef: Item - count: number - isPreset: boolean - location?: Location + itemRef: Item; + count: number; + isPreset: boolean; + location?: Location; // Container item will be placed in - stash or sorting table - containerId?: string -} \ No newline at end of file + containerId?: string; +} diff --git a/project/src/models/eft/inventory/IInventoryAddRequestData.ts b/project/src/models/eft/inventory/IInventoryAddRequestData.ts index 8d272f66..9ca991a4 100644 --- a/project/src/models/eft/inventory/IInventoryAddRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryAddRequestData.ts @@ -1,8 +1,11 @@ -import { Container, IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; +import { + Container, + IInventoryBaseActionRequestData, +} from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryAddRequestData extends IInventoryBaseActionRequestData +export interface IInventoryAddRequestData extends IInventoryBaseActionRequestData { - Action: "Add" - item: string - container: Container -} \ No newline at end of file + Action: "Add"; + item: string; + container: Container; +} diff --git a/project/src/models/eft/inventory/IInventoryBaseActionRequestData.ts b/project/src/models/eft/inventory/IInventoryBaseActionRequestData.ts index 658999be..08882a63 100644 --- a/project/src/models/eft/inventory/IInventoryBaseActionRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryBaseActionRequestData.ts @@ -1,39 +1,38 @@ import { IBaseInteractionRequestData } from "@spt-aki/models/eft/common/request/IBaseInteractionRequestData"; -export interface IInventoryBaseActionRequestData extends IBaseInteractionRequestData +export interface IInventoryBaseActionRequestData extends IBaseInteractionRequestData { - } -export interface To +export interface To { - id: string - container: string - location?: ToLocation | number // Hack - isSearched?: boolean + id: string; + container: string; + location?: ToLocation | number; // Hack + isSearched?: boolean; } -export interface ToLocation +export interface ToLocation { - x: number - y: number - r: string - rotation?: string - isSearched: boolean + x: number; + y: number; + r: string; + rotation?: string; + isSearched: boolean; } -export interface Container +export interface Container { - id: string - container: string - location?: Location | number // Hack - BSG data object shows it as Location only + id: string; + container: string; + location?: Location | number; // Hack - BSG data object shows it as Location only } - -export interface Location + +export interface Location { - x: number - y: number - r: string - rotation?: string - isSearched: boolean -} \ No newline at end of file + x: number; + y: number; + r: string; + rotation?: string; + isSearched: boolean; +} diff --git a/project/src/models/eft/inventory/IInventoryBindRequestData.ts b/project/src/models/eft/inventory/IInventoryBindRequestData.ts index 4fbd2756..84beaaaf 100644 --- a/project/src/models/eft/inventory/IInventoryBindRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryBindRequestData.ts @@ -1,8 +1,8 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryBindRequestData extends IInventoryBaseActionRequestData +export interface IInventoryBindRequestData extends IInventoryBaseActionRequestData { - Action: "Bind" - item: string - index: number -} \ No newline at end of file + Action: "Bind"; + item: string; + index: number; +} diff --git a/project/src/models/eft/inventory/IInventoryCreateMarkerRequestData.ts b/project/src/models/eft/inventory/IInventoryCreateMarkerRequestData.ts index 842d653d..aa72e56b 100644 --- a/project/src/models/eft/inventory/IInventoryCreateMarkerRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryCreateMarkerRequestData.ts @@ -1,16 +1,16 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryCreateMarkerRequestData extends IInventoryBaseActionRequestData +export interface IInventoryCreateMarkerRequestData extends IInventoryBaseActionRequestData { - Action: "CreateMapMarker" - item: string - mapMarker: MapMarker + Action: "CreateMapMarker"; + item: string; + mapMarker: MapMarker; } -export interface MapMarker +export interface MapMarker { - Type: string - X: number - Y: number - Note: string -} \ No newline at end of file + Type: string; + X: number; + Y: number; + Note: string; +} diff --git a/project/src/models/eft/inventory/IInventoryDeleteMarkerRequestData.ts b/project/src/models/eft/inventory/IInventoryDeleteMarkerRequestData.ts index a606fa6b..676f0b53 100644 --- a/project/src/models/eft/inventory/IInventoryDeleteMarkerRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryDeleteMarkerRequestData.ts @@ -1,9 +1,9 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryDeleteMarkerRequestData extends IInventoryBaseActionRequestData +export interface IInventoryDeleteMarkerRequestData extends IInventoryBaseActionRequestData { - Action: "DeleteMapMarker" - item: string - X: number - Y: number -} \ No newline at end of file + Action: "DeleteMapMarker"; + item: string; + X: number; + Y: number; +} diff --git a/project/src/models/eft/inventory/IInventoryEditMarkerRequestData.ts b/project/src/models/eft/inventory/IInventoryEditMarkerRequestData.ts index 8344c5a9..033cc88a 100644 --- a/project/src/models/eft/inventory/IInventoryEditMarkerRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryEditMarkerRequestData.ts @@ -1,18 +1,18 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryEditMarkerRequestData extends IInventoryBaseActionRequestData +export interface IInventoryEditMarkerRequestData extends IInventoryBaseActionRequestData { - Action: "EditMapMarker" - item: string - X: number - Y: number - mapMarker: MapMarker + Action: "EditMapMarker"; + item: string; + X: number; + Y: number; + mapMarker: MapMarker; } -export interface MapMarker +export interface MapMarker { - Type: string - X: number - Y: number - Note: string -} \ No newline at end of file + Type: string; + X: number; + Y: number; + Note: string; +} diff --git a/project/src/models/eft/inventory/IInventoryExamineRequestData.ts b/project/src/models/eft/inventory/IInventoryExamineRequestData.ts index 722f48fd..aac6e4bd 100644 --- a/project/src/models/eft/inventory/IInventoryExamineRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryExamineRequestData.ts @@ -1,9 +1,9 @@ import { OwnerInfo } from "@spt-aki/models/eft/common/request/IBaseInteractionRequestData"; import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryExamineRequestData extends IInventoryBaseActionRequestData +export interface IInventoryExamineRequestData extends IInventoryBaseActionRequestData { - Action: "Examine" - item: string - fromOwner: OwnerInfo -} \ No newline at end of file + Action: "Examine"; + item: string; + fromOwner: OwnerInfo; +} diff --git a/project/src/models/eft/inventory/IInventoryFoldRequestData.ts b/project/src/models/eft/inventory/IInventoryFoldRequestData.ts index 6005d864..971f630b 100644 --- a/project/src/models/eft/inventory/IInventoryFoldRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryFoldRequestData.ts @@ -1,8 +1,8 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryFoldRequestData extends IInventoryBaseActionRequestData +export interface IInventoryFoldRequestData extends IInventoryBaseActionRequestData { - Action: "Fold" - item: string - value: boolean -} \ No newline at end of file + Action: "Fold"; + item: string; + value: boolean; +} diff --git a/project/src/models/eft/inventory/IInventoryMergeRequestData.ts b/project/src/models/eft/inventory/IInventoryMergeRequestData.ts index 543606fd..68626ceb 100644 --- a/project/src/models/eft/inventory/IInventoryMergeRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryMergeRequestData.ts @@ -1,8 +1,8 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryMergeRequestData extends IInventoryBaseActionRequestData +export interface IInventoryMergeRequestData extends IInventoryBaseActionRequestData { - Action: "Merge" - item: string - with: string -} \ No newline at end of file + Action: "Merge"; + item: string; + with: string; +} diff --git a/project/src/models/eft/inventory/IInventoryMoveRequestData.ts b/project/src/models/eft/inventory/IInventoryMoveRequestData.ts index 45f3512b..cbf83d68 100644 --- a/project/src/models/eft/inventory/IInventoryMoveRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryMoveRequestData.ts @@ -1,8 +1,8 @@ import { IInventoryBaseActionRequestData, To } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryMoveRequestData extends IInventoryBaseActionRequestData +export interface IInventoryMoveRequestData extends IInventoryBaseActionRequestData { - Action: "Move" - item: string - to: To -} \ No newline at end of file + Action: "Move"; + item: string; + to: To; +} diff --git a/project/src/models/eft/inventory/IInventoryReadEncyclopediaRequestData.ts b/project/src/models/eft/inventory/IInventoryReadEncyclopediaRequestData.ts index c0171450..eac2a581 100644 --- a/project/src/models/eft/inventory/IInventoryReadEncyclopediaRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryReadEncyclopediaRequestData.ts @@ -1,7 +1,7 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryReadEncyclopediaRequestData extends IInventoryBaseActionRequestData +export interface IInventoryReadEncyclopediaRequestData extends IInventoryBaseActionRequestData { - Action: "ReadEncyclopedia" - ids: string[] -} \ No newline at end of file + Action: "ReadEncyclopedia"; + ids: string[]; +} diff --git a/project/src/models/eft/inventory/IInventoryRemoveRequestData.ts b/project/src/models/eft/inventory/IInventoryRemoveRequestData.ts index 97440f51..633734c8 100644 --- a/project/src/models/eft/inventory/IInventoryRemoveRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryRemoveRequestData.ts @@ -1,7 +1,7 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryRemoveRequestData extends IInventoryBaseActionRequestData +export interface IInventoryRemoveRequestData extends IInventoryBaseActionRequestData { - Action: "Remove" - item: string -} \ No newline at end of file + Action: "Remove"; + item: string; +} diff --git a/project/src/models/eft/inventory/IInventorySortRequestData.ts b/project/src/models/eft/inventory/IInventorySortRequestData.ts index cf98346e..e72d6439 100644 --- a/project/src/models/eft/inventory/IInventorySortRequestData.ts +++ b/project/src/models/eft/inventory/IInventorySortRequestData.ts @@ -1,26 +1,26 @@ import { Upd } from "@spt-aki/models/eft/common/tables/IItem"; import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventorySortRequestData extends IInventoryBaseActionRequestData +export interface IInventorySortRequestData extends IInventoryBaseActionRequestData { - Action: "ApplyInventoryChanges" - changedItems: ChangedItem[] + Action: "ApplyInventoryChanges"; + changedItems: ChangedItem[]; } -export interface ChangedItem +export interface ChangedItem { - _id: string - _tpl: string - parentId: string - slotId: string - location: Location - upd: Upd + _id: string; + _tpl: string; + parentId: string; + slotId: string; + location: Location; + upd: Upd; } -export interface Location +export interface Location { - x: number - y: number - r: string - isSearched: boolean -} \ No newline at end of file + x: number; + y: number; + r: string; + isSearched: boolean; +} diff --git a/project/src/models/eft/inventory/IInventorySplitRequestData.ts b/project/src/models/eft/inventory/IInventorySplitRequestData.ts index f087c3c9..abb447f3 100644 --- a/project/src/models/eft/inventory/IInventorySplitRequestData.ts +++ b/project/src/models/eft/inventory/IInventorySplitRequestData.ts @@ -1,14 +1,16 @@ -import { Container, IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; +import { + Container, + IInventoryBaseActionRequestData, +} from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventorySplitRequestData extends IInventoryBaseActionRequestData +export interface IInventorySplitRequestData extends IInventoryBaseActionRequestData { - Action: "Split" + Action: "Split"; /** Id of item to split */ - splitItem: string + splitItem: string; /** Id of new item stack */ - newItem: string + newItem: string; /** Destination new item will be placed in */ - container: Container - count: number + container: Container; + count: number; } - \ No newline at end of file diff --git a/project/src/models/eft/inventory/IInventorySwapRequestData.ts b/project/src/models/eft/inventory/IInventorySwapRequestData.ts index a78598c9..5d65f4d9 100644 --- a/project/src/models/eft/inventory/IInventorySwapRequestData.ts +++ b/project/src/models/eft/inventory/IInventorySwapRequestData.ts @@ -1,13 +1,13 @@ import { OwnerInfo } from "@spt-aki/models/eft/common/request/IBaseInteractionRequestData"; import { IInventoryBaseActionRequestData, To } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventorySwapRequestData extends IInventoryBaseActionRequestData +export interface IInventorySwapRequestData extends IInventoryBaseActionRequestData { - Action: "Swap" - item: string - to: To - item2: string - to2: To - fromOwner2: OwnerInfo - toOwner2: OwnerInfo -} \ No newline at end of file + Action: "Swap"; + item: string; + to: To; + item2: string; + to2: To; + fromOwner2: OwnerInfo; + toOwner2: OwnerInfo; +} diff --git a/project/src/models/eft/inventory/IInventoryTagRequestData.ts b/project/src/models/eft/inventory/IInventoryTagRequestData.ts index 97f008f0..4843764e 100644 --- a/project/src/models/eft/inventory/IInventoryTagRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryTagRequestData.ts @@ -1,9 +1,9 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryTagRequestData extends IInventoryBaseActionRequestData +export interface IInventoryTagRequestData extends IInventoryBaseActionRequestData { - Action: "Tag" - item: string - TagName: string - TagColor: number -} \ No newline at end of file + Action: "Tag"; + item: string; + TagName: string; + TagColor: number; +} diff --git a/project/src/models/eft/inventory/IInventoryToggleRequestData.ts b/project/src/models/eft/inventory/IInventoryToggleRequestData.ts index 2d5c3151..02e6c3c5 100644 --- a/project/src/models/eft/inventory/IInventoryToggleRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryToggleRequestData.ts @@ -1,8 +1,8 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryToggleRequestData extends IInventoryBaseActionRequestData +export interface IInventoryToggleRequestData extends IInventoryBaseActionRequestData { - Action: "Toggle" - item: string - value: boolean -} \ No newline at end of file + Action: "Toggle"; + item: string; + value: boolean; +} diff --git a/project/src/models/eft/inventory/IInventoryTransferRequestData.ts b/project/src/models/eft/inventory/IInventoryTransferRequestData.ts index 18bdc9be..0a286e67 100644 --- a/project/src/models/eft/inventory/IInventoryTransferRequestData.ts +++ b/project/src/models/eft/inventory/IInventoryTransferRequestData.ts @@ -1,9 +1,9 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IInventoryTransferRequestData extends IInventoryBaseActionRequestData +export interface IInventoryTransferRequestData extends IInventoryBaseActionRequestData { - Action: "Transfer" - item: string - with: string - count: number -} \ No newline at end of file + Action: "Transfer"; + item: string; + with: string; + count: number; +} diff --git a/project/src/models/eft/inventory/IOpenRandomLootContainerRequestData.ts b/project/src/models/eft/inventory/IOpenRandomLootContainerRequestData.ts index c292202f..589ff034 100644 --- a/project/src/models/eft/inventory/IOpenRandomLootContainerRequestData.ts +++ b/project/src/models/eft/inventory/IOpenRandomLootContainerRequestData.ts @@ -1,15 +1,15 @@ import { IInventoryBaseActionRequestData } from "@spt-aki/models/eft/inventory/IInventoryBaseActionRequestData"; -export interface IOpenRandomLootContainerRequestData extends IInventoryBaseActionRequestData +export interface IOpenRandomLootContainerRequestData extends IInventoryBaseActionRequestData { - Action: "OpenRandomLootContainer" + Action: "OpenRandomLootContainer"; /** Container item opened */ - item: string - to: To[] + item: string; + to: To[]; } export interface To { /** Player character (pmc/scav) id items will be sent to */ - id: string -} \ No newline at end of file + id: string; +} diff --git a/project/src/models/eft/itemEvent/IItemEventRouterBase.ts b/project/src/models/eft/itemEvent/IItemEventRouterBase.ts index 1256bfd4..d3ceeea1 100644 --- a/project/src/models/eft/itemEvent/IItemEventRouterBase.ts +++ b/project/src/models/eft/itemEvent/IItemEventRouterBase.ts @@ -7,93 +7,93 @@ import { EquipmentBuildType } from "@spt-aki/models/enums/EquipmentBuildType"; export interface IItemEventRouterBase { - warnings: Warning[] - profileChanges: TProfileChanges | "" + warnings: Warning[]; + profileChanges: TProfileChanges | ""; } -export type TProfileChanges = Record +export type TProfileChanges = Record; export interface Warning { - index: number - errmsg: string - code?: string - data?: any + index: number; + errmsg: string; + code?: string; + data?: any; } export interface ProfileChange { - _id: string - experience: number - quests: IQuest[] - ragFairOffers: IRagfairOffer[] - weaponBuilds: IWeaponBuildChange[] - equipmentBuilds: IEquipmentBuildChange[] - items: ItemChanges - production: Record + _id: string; + experience: number; + quests: IQuest[]; + ragFairOffers: IRagfairOffer[]; + weaponBuilds: IWeaponBuildChange[]; + equipmentBuilds: IEquipmentBuildChange[]; + items: ItemChanges; + production: Record; /** Hideout area improvement id */ - improvements: Record - skills: Skills - health: Health - traderRelations: Record - repeatableQuests?: IPmcDataRepeatableQuest[] - recipeUnlocked: Record - changedHideoutStashes?: Record - questsStatus: IQuestStatus[] + improvements: Record; + skills: Skills; + health: Health; + traderRelations: Record; + repeatableQuests?: IPmcDataRepeatableQuest[]; + recipeUnlocked: Record; + changedHideoutStashes?: Record; + questsStatus: IQuestStatus[]; } export interface IHideoutStashItem { - Id: string - Tpl: string + Id: string; + Tpl: string; } export interface IWeaponBuildChange { - id: string - name: string - root: string - items: Item[] + id: string; + name: string; + root: string; + items: Item[]; } export interface IEquipmentBuildChange { - id: string - name: string - root: string - items: Item[] - type: string - fastpanel: any[] - buildType: EquipmentBuildType + id: string; + name: string; + root: string; + items: Item[]; + type: string; + fastpanel: any[]; + buildType: EquipmentBuildType; } -export interface ItemChanges +export interface ItemChanges { - new: Product[] - change: Product[] - del: Product[] + new: Product[]; + change: Product[]; + del: Product[]; } export interface Improvement { - completed: boolean, - improveCompleteTimestamp: number + completed: boolean; + improveCompleteTimestamp: number; } export interface Product { - _id: string - _tpl?: string - parentId?: string - slotId?: string - location?: ItemChangeLocation - upd?: Upd + _id: string; + _tpl?: string; + parentId?: string; + slotId?: string; + location?: ItemChangeLocation; + upd?: Upd; } export interface ItemChangeLocation { - x: number, - y: number, - r: number, - isSearched?: boolean -} \ No newline at end of file + x: number; + y: number; + r: number; + isSearched?: boolean; +} diff --git a/project/src/models/eft/itemEvent/IItemEventRouterRequest.ts b/project/src/models/eft/itemEvent/IItemEventRouterRequest.ts index e685f9bf..4fd8eb7b 100644 --- a/project/src/models/eft/itemEvent/IItemEventRouterRequest.ts +++ b/project/src/models/eft/itemEvent/IItemEventRouterRequest.ts @@ -1,29 +1,28 @@ export interface IItemEventRouterRequest { - data: Daum[] - tm: number - reload: number + data: Daum[]; + tm: number; + reload: number; } - -export interface Daum + +export interface Daum { - Action: string - item: string - to: To + Action: string; + item: string; + to: To; } - -export interface To + +export interface To { - id: string - container: string - location?: Location + id: string; + container: string; + location?: Location; } - -export interface Location + +export interface Location { - x: number - y: number - r: string - isSearched: boolean + x: number; + y: number; + r: string; + isSearched: boolean; } - \ No newline at end of file diff --git a/project/src/models/eft/itemEvent/IItemEventRouterResponse.ts b/project/src/models/eft/itemEvent/IItemEventRouterResponse.ts index 8af4406b..459ddca1 100644 --- a/project/src/models/eft/itemEvent/IItemEventRouterResponse.ts +++ b/project/src/models/eft/itemEvent/IItemEventRouterResponse.ts @@ -1,4 +1,4 @@ import { IItemEventRouterBase } from "@spt-aki/models/eft/itemEvent/IItemEventRouterBase"; export interface IItemEventRouterResponse extends IItemEventRouterBase -{} \ No newline at end of file +{} diff --git a/project/src/models/eft/launcher/IChangeRequestData.ts b/project/src/models/eft/launcher/IChangeRequestData.ts index 71b306df..6257e992 100644 --- a/project/src/models/eft/launcher/IChangeRequestData.ts +++ b/project/src/models/eft/launcher/IChangeRequestData.ts @@ -2,5 +2,5 @@ import { ILoginRequestData } from "@spt-aki/models/eft/launcher/ILoginRequestDat export interface IChangeRequestData extends ILoginRequestData { - change: string, -} \ No newline at end of file + change: string; +} diff --git a/project/src/models/eft/launcher/IGetMiniProfileRequestData.ts b/project/src/models/eft/launcher/IGetMiniProfileRequestData.ts index 2aaefcb0..152ae360 100644 --- a/project/src/models/eft/launcher/IGetMiniProfileRequestData.ts +++ b/project/src/models/eft/launcher/IGetMiniProfileRequestData.ts @@ -1,5 +1,5 @@ -export interface IGetMiniProfileRequestData +export interface IGetMiniProfileRequestData { - username: string - password: string -} \ No newline at end of file + username: string; + password: string; +} diff --git a/project/src/models/eft/launcher/ILoginRequestData.ts b/project/src/models/eft/launcher/ILoginRequestData.ts index 79470936..c124b8ae 100644 --- a/project/src/models/eft/launcher/ILoginRequestData.ts +++ b/project/src/models/eft/launcher/ILoginRequestData.ts @@ -1,5 +1,5 @@ export interface ILoginRequestData { - username: string, - password: string -} \ No newline at end of file + username: string; + password: string; +} diff --git a/project/src/models/eft/launcher/IMiniProfile.ts b/project/src/models/eft/launcher/IMiniProfile.ts index af0acb45..41205298 100644 --- a/project/src/models/eft/launcher/IMiniProfile.ts +++ b/project/src/models/eft/launcher/IMiniProfile.ts @@ -1,17 +1,17 @@ -export interface IMiniProfile +export interface IMiniProfile { - username: string - nickname: string - side: string - currlvl: number - currexp: number - prevexp: number - nextlvl: number - maxlvl: number - akiData: AkiData + username: string; + nickname: string; + side: string; + currlvl: number; + currexp: number; + prevexp: number; + nextlvl: number; + maxlvl: number; + akiData: AkiData; } -export interface AkiData +export interface AkiData { - version: string -} \ No newline at end of file + version: string; +} diff --git a/project/src/models/eft/launcher/IRegisterData.ts b/project/src/models/eft/launcher/IRegisterData.ts index 55727493..c66e87f0 100644 --- a/project/src/models/eft/launcher/IRegisterData.ts +++ b/project/src/models/eft/launcher/IRegisterData.ts @@ -2,5 +2,5 @@ import { ILoginRequestData } from "@spt-aki/models/eft/launcher/ILoginRequestDat export interface IRegisterData extends ILoginRequestData { - edition: string -} \ No newline at end of file + edition: string; +} diff --git a/project/src/models/eft/launcher/IRemoveProfileData.ts b/project/src/models/eft/launcher/IRemoveProfileData.ts index b88f5b7e..f8a12f7b 100644 --- a/project/src/models/eft/launcher/IRemoveProfileData.ts +++ b/project/src/models/eft/launcher/IRemoveProfileData.ts @@ -1,3 +1,3 @@ import { ILoginRequestData } from "@spt-aki/models/eft/launcher/ILoginRequestData"; -export type IRemoveProfileData = ILoginRequestData \ No newline at end of file +export type IRemoveProfileData = ILoginRequestData; diff --git a/project/src/models/eft/location/IAirdropLootResult.ts b/project/src/models/eft/location/IAirdropLootResult.ts index 7e68e9ac..78d03c7b 100644 --- a/project/src/models/eft/location/IAirdropLootResult.ts +++ b/project/src/models/eft/location/IAirdropLootResult.ts @@ -2,6 +2,6 @@ import { LootItem } from "@spt-aki/models/spt/services/LootItem"; export interface IAirdropLootResult { - dropType: string - loot: LootItem[] -} \ No newline at end of file + dropType: string; + loot: LootItem[]; +} diff --git a/project/src/models/eft/location/IGetLocationRequestData.ts b/project/src/models/eft/location/IGetLocationRequestData.ts index 30ea52b0..c56dea96 100644 --- a/project/src/models/eft/location/IGetLocationRequestData.ts +++ b/project/src/models/eft/location/IGetLocationRequestData.ts @@ -1,6 +1,6 @@ -export interface IGetLocationRequestData +export interface IGetLocationRequestData { - crc: number - locationId: string - variantId: number -} \ No newline at end of file + crc: number; + locationId: string; + variantId: number; +} diff --git a/project/src/models/eft/match/IAcceptGroupInviteRequest.ts b/project/src/models/eft/match/IAcceptGroupInviteRequest.ts index d13f1691..eb670d39 100644 --- a/project/src/models/eft/match/IAcceptGroupInviteRequest.ts +++ b/project/src/models/eft/match/IAcceptGroupInviteRequest.ts @@ -1,4 +1,4 @@ export interface IAcceptGroupInviteRequest { - requestId: string -} \ No newline at end of file + requestId: string; +} diff --git a/project/src/models/eft/match/IAcceptGroupInviteResponse.ts b/project/src/models/eft/match/IAcceptGroupInviteResponse.ts index 8eaa0dbf..d525c761 100644 --- a/project/src/models/eft/match/IAcceptGroupInviteResponse.ts +++ b/project/src/models/eft/match/IAcceptGroupInviteResponse.ts @@ -1,19 +1,19 @@ export interface IAcceptGroupInviteResponse { - _id: string - aid: number - Info: PlayerInviteInfo - isLeader: boolean - isReady: boolean + _id: string; + aid: number; + Info: PlayerInviteInfo; + isLeader: boolean; + isReady: boolean; } export interface PlayerInviteInfo { - Nickname: string - Side: string - Level: number - MemberCategory: number - GameVersion: string - SavageLockTime: number - SavageNickname: string -} \ No newline at end of file + Nickname: string; + Side: string; + Level: number; + MemberCategory: number; + GameVersion: string; + SavageLockTime: number; + SavageNickname: string; +} diff --git a/project/src/models/eft/match/ICancelGroupInviteRequest.ts b/project/src/models/eft/match/ICancelGroupInviteRequest.ts index 6e6246c4..d2adf46d 100644 --- a/project/src/models/eft/match/ICancelGroupInviteRequest.ts +++ b/project/src/models/eft/match/ICancelGroupInviteRequest.ts @@ -1,4 +1,4 @@ export interface ICancelGroupInviteRequest { - requestId: string -} \ No newline at end of file + requestId: string; +} diff --git a/project/src/models/eft/match/ICreateGroupRequestData.ts b/project/src/models/eft/match/ICreateGroupRequestData.ts index 2cb7350a..dd99d1aa 100644 --- a/project/src/models/eft/match/ICreateGroupRequestData.ts +++ b/project/src/models/eft/match/ICreateGroupRequestData.ts @@ -2,7 +2,7 @@ import { RaidMode } from "@spt-aki/models/enums/RaidMode"; export interface ICreateGroupRequestData { - location: string - raidMode: RaidMode - startInGroup: boolean -} \ No newline at end of file + location: string; + raidMode: RaidMode; + startInGroup: boolean; +} diff --git a/project/src/models/eft/match/IEndOfflineRaidRequestData.ts b/project/src/models/eft/match/IEndOfflineRaidRequestData.ts index 18903b93..49e0a710 100644 --- a/project/src/models/eft/match/IEndOfflineRaidRequestData.ts +++ b/project/src/models/eft/match/IEndOfflineRaidRequestData.ts @@ -1,7 +1,7 @@ -export interface IEndOfflineRaidRequestData +export interface IEndOfflineRaidRequestData { - crc: number - exitStatus: string - exitName: string - raidSeconds: number + crc: number; + exitStatus: string; + exitName: string; + raidSeconds: number; } diff --git a/project/src/models/eft/match/IGetGroupStatusRequestData.ts b/project/src/models/eft/match/IGetGroupStatusRequestData.ts index b25fb8bf..b657a426 100644 --- a/project/src/models/eft/match/IGetGroupStatusRequestData.ts +++ b/project/src/models/eft/match/IGetGroupStatusRequestData.ts @@ -2,10 +2,10 @@ import { RaidMode } from "@spt-aki/models/enums/RaidMode"; export interface IGetGroupStatusRequestData { - location: string - savage: boolean - dt: string - keyId: string - raidMode: RaidMode - spawnPlace: string -} \ No newline at end of file + location: string; + savage: boolean; + dt: string; + keyId: string; + raidMode: RaidMode; + spawnPlace: string; +} diff --git a/project/src/models/eft/match/IGetProfileRequestData.ts b/project/src/models/eft/match/IGetProfileRequestData.ts index c2ec0a50..cb530bca 100644 --- a/project/src/models/eft/match/IGetProfileRequestData.ts +++ b/project/src/models/eft/match/IGetProfileRequestData.ts @@ -1,4 +1,4 @@ export interface IGetProfileRequestData { profileId: string; -} \ No newline at end of file +} diff --git a/project/src/models/eft/match/IGetRaidConfigurationRequestData.ts b/project/src/models/eft/match/IGetRaidConfigurationRequestData.ts index 87bc3791..6633df3d 100644 --- a/project/src/models/eft/match/IGetRaidConfigurationRequestData.ts +++ b/project/src/models/eft/match/IGetRaidConfigurationRequestData.ts @@ -1,15 +1,15 @@ export interface IGetRaidConfigurationRequestData { - keyId: string - side: string - location: string - timeVariant: string - raidMode: string - metabolismDisabled: boolean - playersSpawnPlace: string - timeAndWeatherSettings: TimeAndWeatherSettings - botSettings: BotSettings - wavesSettings: WavesSettings + keyId: string; + side: string; + location: string; + timeVariant: string; + raidMode: string; + metabolismDisabled: boolean; + playersSpawnPlace: string; + timeAndWeatherSettings: TimeAndWeatherSettings; + botSettings: BotSettings; + wavesSettings: WavesSettings; } // { @@ -41,31 +41,29 @@ export interface IGetRaidConfigurationRequestData // isTaggedAndCursed: false // } // } - export interface TimeAndWeatherSettings { - isRandomTime: boolean - isRandomWeather: boolean - cloudinessType: string - rainType: string - windType: string - fogType: string - timeFlowType: string - hourOfDay: number + isRandomTime: boolean; + isRandomWeather: boolean; + cloudinessType: string; + rainType: string; + windType: string; + fogType: string; + timeFlowType: string; + hourOfDay: number; } - + export interface BotSettings { - isScavWars: boolean - botAmount: string + isScavWars: boolean; + botAmount: string; } - + export interface WavesSettings { - botAmount: string - botDifficulty: string - isBosses: boolean - isTaggedAndCursed: boolean + botAmount: string; + botDifficulty: string; + isBosses: boolean; + isTaggedAndCursed: boolean; } - \ No newline at end of file diff --git a/project/src/models/eft/match/IJoinMatchRequestData.ts b/project/src/models/eft/match/IJoinMatchRequestData.ts index a937e870..4ec07d3f 100644 --- a/project/src/models/eft/match/IJoinMatchRequestData.ts +++ b/project/src/models/eft/match/IJoinMatchRequestData.ts @@ -1,12 +1,12 @@ export interface IJoinMatchRequestData { - groupid: string - servers: Server[] + groupid: string; + servers: Server[]; } export interface Server { - ping: number - ip: string - port: string -} \ No newline at end of file + ping: number; + ip: string; + port: string; +} diff --git a/project/src/models/eft/match/IJoinMatchResult.ts b/project/src/models/eft/match/IJoinMatchResult.ts index 916c9822..873bb0ee 100644 --- a/project/src/models/eft/match/IJoinMatchResult.ts +++ b/project/src/models/eft/match/IJoinMatchResult.ts @@ -1,22 +1,22 @@ export interface IJoinMatchResult { - maxPveCountExceeded: boolean - profiles: IJoinMatchPlayerProfile[] + maxPveCountExceeded: boolean; + profiles: IJoinMatchPlayerProfile[]; } export interface IJoinMatchPlayerProfile { - profileid: string - profileToken: string - status: string - sid: string - ip: string - port: number - version: string - location: string - raidMode: string - mode: string - shortid: string + profileid: string; + profileToken: string; + status: string; + sid: string; + ip: string; + port: number; + version: string; + location: string; + raidMode: string; + mode: string; + shortid: string; // eslint-disable-next-line @typescript-eslint/naming-convention - additional_info: any[] -} \ No newline at end of file + additional_info: any[]; +} diff --git a/project/src/models/eft/match/IPutMetricsRequestData.ts b/project/src/models/eft/match/IPutMetricsRequestData.ts index 5739e3c3..0fb57f0d 100644 --- a/project/src/models/eft/match/IPutMetricsRequestData.ts +++ b/project/src/models/eft/match/IPutMetricsRequestData.ts @@ -1,11 +1,11 @@ export interface IPutMetricsRequestData { - sid: string - settings: any - SharedSettings: any - HardwareDescription: any - Location: string - Metrics: any - ClientEvents: any - SpikeSamples: any[] -} \ No newline at end of file + sid: string; + settings: any; + SharedSettings: any; + HardwareDescription: any; + Location: string; + Metrics: any; + ClientEvents: any; + SpikeSamples: any[]; +} diff --git a/project/src/models/eft/match/IRemovePlayerFromGroupRequest.ts b/project/src/models/eft/match/IRemovePlayerFromGroupRequest.ts index d4a9d63e..6dcb7103 100644 --- a/project/src/models/eft/match/IRemovePlayerFromGroupRequest.ts +++ b/project/src/models/eft/match/IRemovePlayerFromGroupRequest.ts @@ -1,4 +1,4 @@ export interface IRemovePlayerFromGroupRequest { - aidToKick: string -} \ No newline at end of file + aidToKick: string; +} diff --git a/project/src/models/eft/match/ISendGroupInviteRequest.ts b/project/src/models/eft/match/ISendGroupInviteRequest.ts index a35d13bf..50e016ab 100644 --- a/project/src/models/eft/match/ISendGroupInviteRequest.ts +++ b/project/src/models/eft/match/ISendGroupInviteRequest.ts @@ -1,5 +1,5 @@ export interface ISendGroupInviteRequest { - to: string - inLobby: boolean -} \ No newline at end of file + to: string; + inLobby: boolean; +} diff --git a/project/src/models/eft/match/ITransferGroupRequest.ts b/project/src/models/eft/match/ITransferGroupRequest.ts index ed80a208..ad725553 100644 --- a/project/src/models/eft/match/ITransferGroupRequest.ts +++ b/project/src/models/eft/match/ITransferGroupRequest.ts @@ -1,4 +1,4 @@ export interface ITransferGroupRequest { - aidToChange: string -} \ No newline at end of file + aidToChange: string; +} diff --git a/project/src/models/eft/match/IUpdatePingRequestData.ts b/project/src/models/eft/match/IUpdatePingRequestData.ts index ff5ec41a..22ce549e 100644 --- a/project/src/models/eft/match/IUpdatePingRequestData.ts +++ b/project/src/models/eft/match/IUpdatePingRequestData.ts @@ -1,4 +1,4 @@ export interface IUpdatePingRequestData { - servers: any[] -} \ No newline at end of file + servers: any[]; +} diff --git a/project/src/models/eft/notes/INoteActionData.ts b/project/src/models/eft/notes/INoteActionData.ts index a36d405a..d2e71b0b 100644 --- a/project/src/models/eft/notes/INoteActionData.ts +++ b/project/src/models/eft/notes/INoteActionData.ts @@ -1,14 +1,14 @@ import { IBaseInteractionRequestData } from "@spt-aki/models/eft/common/request/IBaseInteractionRequestData"; -export interface INoteActionData extends IBaseInteractionRequestData +export interface INoteActionData extends IBaseInteractionRequestData { Action: string; index: number; note: INote; } -export interface INote +export interface INote { - Time: number - Text: string -} \ No newline at end of file + Time: number; + Text: string; +} diff --git a/project/src/models/eft/notifier/INotifier.ts b/project/src/models/eft/notifier/INotifier.ts index bd1b9c94..0031ed76 100644 --- a/project/src/models/eft/notifier/INotifier.ts +++ b/project/src/models/eft/notifier/INotifier.ts @@ -2,25 +2,24 @@ import { Message } from "@spt-aki/models/eft/profile/IAkiProfile"; export interface INotifierChannel { - server: string + server: string; // eslint-disable-next-line @typescript-eslint/naming-convention - channel_id: string, - url: string - notifierServer: string - ws: string + channel_id: string; + url: string; + notifierServer: string; + ws: string; } - export interface INotification { type: NotificationType; - eventId: string - dialogId?: string - message?: Message + eventId: string; + dialogId?: string; + message?: Message; } export enum NotificationType - { +{ RAGFAIR_OFFER_SOLD = "RagfairOfferSold", RAGFAIR_RATING_CHANGE = "RagfairRatingChange", /** ChatMessageReceived */ @@ -28,5 +27,5 @@ export enum NotificationType PING = "ping", TRADER_SUPPLY = "TraderSupply", TRADER_STANDING = "TraderStanding", - UNLOCK_TRADER = "UnlockTrader" -} \ No newline at end of file + UNLOCK_TRADER = "UnlockTrader", +} diff --git a/project/src/models/eft/notifier/ISelectProfileRequestData.ts b/project/src/models/eft/notifier/ISelectProfileRequestData.ts index 305f28a5..d5d8b98b 100644 --- a/project/src/models/eft/notifier/ISelectProfileRequestData.ts +++ b/project/src/models/eft/notifier/ISelectProfileRequestData.ts @@ -1,4 +1,4 @@ -export interface ISelectProfileRequestData +export interface ISelectProfileRequestData { - uid: string -} \ No newline at end of file + uid: string; +} diff --git a/project/src/models/eft/notifier/ISelectProfileResponse.ts b/project/src/models/eft/notifier/ISelectProfileResponse.ts index 64c56955..ae14c2c8 100644 --- a/project/src/models/eft/notifier/ISelectProfileResponse.ts +++ b/project/src/models/eft/notifier/ISelectProfileResponse.ts @@ -1,4 +1,4 @@ export interface ISelectProfileResponse { - status: string -} \ No newline at end of file + status: string; +} diff --git a/project/src/models/eft/player/IPlayerIncrementSkillLevelRequestData.ts b/project/src/models/eft/player/IPlayerIncrementSkillLevelRequestData.ts index ab1b2016..90b8dd56 100644 --- a/project/src/models/eft/player/IPlayerIncrementSkillLevelRequestData.ts +++ b/project/src/models/eft/player/IPlayerIncrementSkillLevelRequestData.ts @@ -1,27 +1,27 @@ import { Skills } from "@spt-aki/models/eft/common/tables/IBotBase"; -export interface IPlayerIncrementSkillLevelRequestData +export interface IPlayerIncrementSkillLevelRequestData { - _id: string - experience: number - quests: any[] - ragFairOffers: any[] - builds: any[] - items: Items - production: Production - skills: Skills - traderRelations: TraderRelations + _id: string; + experience: number; + quests: any[]; + ragFairOffers: any[]; + builds: any[]; + items: Items; + production: Production; + skills: Skills; + traderRelations: TraderRelations; } -export interface Items +export interface Items { - new: any[] - change: any[] - del: any[] + new: any[]; + change: any[]; + del: any[]; } -export interface Production -{ } +export interface Production +{} -export interface TraderRelations -{ } \ No newline at end of file +export interface TraderRelations +{} diff --git a/project/src/models/eft/presetBuild/IPresetBuildActionRequestData.ts b/project/src/models/eft/presetBuild/IPresetBuildActionRequestData.ts index eb623026..d7f2e765 100644 --- a/project/src/models/eft/presetBuild/IPresetBuildActionRequestData.ts +++ b/project/src/models/eft/presetBuild/IPresetBuildActionRequestData.ts @@ -1,10 +1,10 @@ import { Item } from "@spt-aki/models/eft/common/tables/IItem"; -export interface IPresetBuildActionRequestData +export interface IPresetBuildActionRequestData { - Action: string - id: string - name: string - root: string - items: Item[] -} \ No newline at end of file + Action: string; + id: string; + name: string; + root: string; + items: Item[]; +} diff --git a/project/src/models/eft/presetBuild/IRemoveBuildRequestData.ts b/project/src/models/eft/presetBuild/IRemoveBuildRequestData.ts index d4fc8ff4..fdfa7768 100644 --- a/project/src/models/eft/presetBuild/IRemoveBuildRequestData.ts +++ b/project/src/models/eft/presetBuild/IRemoveBuildRequestData.ts @@ -1,5 +1,5 @@ export interface IRemoveBuildRequestData { - Action: "RemoveBuild" - id: string -} \ No newline at end of file + Action: "RemoveBuild"; + id: string; +} diff --git a/project/src/models/eft/profile/GetProfileStatusResponseData.ts b/project/src/models/eft/profile/GetProfileStatusResponseData.ts index 1b93cebe..8b6f6698 100644 --- a/project/src/models/eft/profile/GetProfileStatusResponseData.ts +++ b/project/src/models/eft/profile/GetProfileStatusResponseData.ts @@ -1,22 +1,22 @@ export interface GetProfileStatusResponseData { - maxPveCountExceeded: false, - profiles: ProfileData[] + maxPveCountExceeded: false; + profiles: ProfileData[]; } export interface ProfileData { - profileid: string - profileToken: string - status: string - ip: string - port: number - sid: string - version?: string - location?: string - raidMode?: string - mode?: string - shortId?: string + profileid: string; + profileToken: string; + status: string; + ip: string; + port: number; + sid: string; + version?: string; + location?: string; + raidMode?: string; + mode?: string; + shortId?: string; // eslint-disable-next-line @typescript-eslint/naming-convention - additional_info?: any[] -} \ No newline at end of file + additional_info?: any[]; +} diff --git a/project/src/models/eft/profile/IAkiProfile.ts b/project/src/models/eft/profile/IAkiProfile.ts index 0c41f890..a2b7e5be 100644 --- a/project/src/models/eft/profile/IAkiProfile.ts +++ b/project/src/models/eft/profile/IAkiProfile.ts @@ -6,18 +6,18 @@ import { MessageType } from "@spt-aki/models/enums/MessageType"; export interface IAkiProfile { - info: Info - characters: Characters + info: Info; + characters: Characters; /** Clothing purchases */ - suits: string[] - userbuilds: IUserBuilds - dialogues: Record - aki: Aki - vitality: Vitality - inraid: Inraid - insurance: Insurance[] + suits: string[]; + userbuilds: IUserBuilds; + dialogues: Record; + aki: Aki; + vitality: Vitality; + inraid: Inraid; + insurance: Insurance[]; /** Assort purchases made by player since last trader refresh */ - traderPurchases?: Record> + traderPurchases?: Record>; } export class TraderPurchaseData @@ -28,252 +28,252 @@ export class TraderPurchaseData export interface Info { - id: string - aid: number - username: string - password: string - wipe: boolean - edition: string + id: string; + aid: number; + username: string; + password: string; + wipe: boolean; + edition: string; } export interface Characters { - pmc: IPmcData - scav: IPmcData + pmc: IPmcData; + scav: IPmcData; } export interface IUserBuilds { - weaponBuilds: IWeaponBuild[], - equipmentBuilds: IEquipmentBuild[] + weaponBuilds: IWeaponBuild[]; + equipmentBuilds: IEquipmentBuild[]; } -export interface IWeaponBuild -{ - id: string - name: string - root: string - items: Item[] - type: string +export interface IWeaponBuild +{ + id: string; + name: string; + root: string; + items: Item[]; + type: string; } export interface IEquipmentBuild { - id: string, - name: string, - root: string, - items: Item[], // same as PMC inventory items - type: string, - fastPanel: Record - buildType: EquipmentBuildType + id: string; + name: string; + root: string; + items: Item[]; // same as PMC inventory items + type: string; + fastPanel: Record; + buildType: EquipmentBuildType; } export interface Dialogue { - attachmentsNew: number - type: MessageType - new: number - _id: string - Users?: IUserDialogInfo[] - pinned: boolean - messages: Message[] + attachmentsNew: number; + type: MessageType; + new: number; + _id: string; + Users?: IUserDialogInfo[]; + pinned: boolean; + messages: Message[]; } export interface IUserDialogInfo { - _id: string - info: IUserDialogDetails + _id: string; + info: IUserDialogDetails; } export interface IUserDialogDetails { - Nickname: string - Side: string - Level: number - MemberCategory: MemberCategory + Nickname: string; + Side: string; + Level: number; + MemberCategory: MemberCategory; } // @Cleanup: Maybe the same as Dialogue? export interface DialogueInfo { - attachmentsNew: number - new: number - _id: string - type: MessageType - pinned: boolean - Users?: IUserDialogInfo[] - message: MessagePreview + attachmentsNew: number; + new: number; + _id: string; + type: MessageType; + pinned: boolean; + Users?: IUserDialogInfo[]; + message: MessagePreview; } export interface Message { - _id: string - uid: string - type: MessageType - dt: number - UtcDateTime?: number - Member?: IUpdatableChatMember - templateId?: string - text?: string - hasRewards?: boolean - rewardCollected: boolean - items?: MessageItems - maxStorageTime?: number - systemData?: ISystemData - profileChangeEvents?: any[] + _id: string; + uid: string; + type: MessageType; + dt: number; + UtcDateTime?: number; + Member?: IUpdatableChatMember; + templateId?: string; + text?: string; + hasRewards?: boolean; + rewardCollected: boolean; + items?: MessageItems; + maxStorageTime?: number; + systemData?: ISystemData; + profileChangeEvents?: any[]; } export interface MessagePreview { - uid: string - type: MessageType - dt: number - templateId: string - text?: string - systemData?: ISystemData + uid: string; + type: MessageType; + dt: number; + templateId: string; + text?: string; + systemData?: ISystemData; } export interface MessageItems { - stash?: string - data?: Item[] + stash?: string; + data?: Item[]; } export interface ISystemData { - date?: string - time?: string - location?: string - buyerNickname?: string - soldItem?: string - itemCount?: number + date?: string; + time?: string; + location?: string; + buyerNickname?: string; + soldItem?: string; + itemCount?: number; } export interface IUpdatableChatMember { - Nickname: string - Side: string - Level: number - MemberCategory: MemberCategory - Ignored: boolean - Banned: boolean + Nickname: string; + Side: string; + Level: number; + MemberCategory: MemberCategory; + Ignored: boolean; + Banned: boolean; } export interface DateTime { - date: string - time: string + date: string; + time: string; } export interface Aki { - version: string - mods?: ModDetails[] - receivedGifts: ReceivedGift[] + version: string; + mods?: ModDetails[]; + receivedGifts: ReceivedGift[]; } export interface ModDetails { - name: string - version: string - author: string - dateAdded: number + name: string; + version: string; + author: string; + dateAdded: number; } export interface ReceivedGift { - giftId: string - timestampAccepted: number + giftId: string; + timestampAccepted: number; } export interface Vitality { - health: Health - effects: Effects + health: Health; + effects: Effects; } export interface Health { - Hydration: number - Energy: number - Temperature: number - Head: number - Chest: number - Stomach: number - LeftArm: number - RightArm: number - LeftLeg: number - RightLeg: number + Hydration: number; + Energy: number; + Temperature: number; + Head: number; + Chest: number; + Stomach: number; + LeftArm: number; + RightArm: number; + LeftLeg: number; + RightLeg: number; } export interface Effects { - Head: Head - Chest: Chest - Stomach: Stomach - LeftArm: LeftArm - RightArm: RightArm - LeftLeg: LeftLeg - RightLeg: RightLeg + Head: Head; + Chest: Chest; + Stomach: Stomach; + LeftArm: LeftArm; + RightArm: RightArm; + LeftLeg: LeftLeg; + RightLeg: RightLeg; } -export interface Head -{ } +export interface Head +{} -export interface Chest -{ } +export interface Chest +{} -export interface Stomach -{ } +export interface Stomach +{} -export interface LeftArm +export interface LeftArm { - Fracture?: number + Fracture?: number; } -export interface RightArm +export interface RightArm { - Fracture?: number + Fracture?: number; } -export interface LeftLeg +export interface LeftLeg { - Fracture?: number + Fracture?: number; } -export interface RightLeg +export interface RightLeg { - Fracture?: number + Fracture?: number; } export interface Inraid { - location: string - character: string + location: string; + character: string; } export interface Insurance { - scheduledTime: number - traderId: string - messageContent: MessageContent - items: Item[] + scheduledTime: number; + traderId: string; + messageContent: MessageContent; + items: Item[]; } export interface MessageContent { - ragfair?: MessageContentRagfair - text?: string - templateId: string - type: MessageType - maxStorageTime?: number - profileChangeEvents?: any[] - systemData?: ISystemData + ragfair?: MessageContentRagfair; + text?: string; + templateId: string; + type: MessageType; + maxStorageTime?: number; + profileChangeEvents?: any[]; + systemData?: ISystemData; } -export interface MessageContentRagfair +export interface MessageContentRagfair { - offerId: string - count: number - handbookId: string -} \ No newline at end of file + offerId: string; + count: number; + handbookId: string; +} diff --git a/project/src/models/eft/profile/IConnectResponse.ts b/project/src/models/eft/profile/IConnectResponse.ts index e1ead5d4..54a561ac 100644 --- a/project/src/models/eft/profile/IConnectResponse.ts +++ b/project/src/models/eft/profile/IConnectResponse.ts @@ -1,7 +1,7 @@ export interface IConnectResponse { - backendUrl: string, - name: string, - editions: string[], - profileDescriptions: Record -} \ No newline at end of file + backendUrl: string; + name: string; + editions: string[]; + profileDescriptions: Record; +} diff --git a/project/src/models/eft/profile/IGetProfileSettingsRequest.ts b/project/src/models/eft/profile/IGetProfileSettingsRequest.ts index fa8e385d..0743d19b 100644 --- a/project/src/models/eft/profile/IGetProfileSettingsRequest.ts +++ b/project/src/models/eft/profile/IGetProfileSettingsRequest.ts @@ -1,4 +1,4 @@ export interface IGetProfileSettingsRequest { - squadInviteRestriction: boolean -} \ No newline at end of file + squadInviteRestriction: boolean; +} diff --git a/project/src/models/eft/profile/IProfileChangeNicknameRequestData.ts b/project/src/models/eft/profile/IProfileChangeNicknameRequestData.ts index 6bea622d..4538e42f 100644 --- a/project/src/models/eft/profile/IProfileChangeNicknameRequestData.ts +++ b/project/src/models/eft/profile/IProfileChangeNicknameRequestData.ts @@ -1,4 +1,4 @@ -export interface IProfileChangeNicknameRequestData +export interface IProfileChangeNicknameRequestData { - nickname: string -} \ No newline at end of file + nickname: string; +} diff --git a/project/src/models/eft/profile/IProfileChangeVoiceRequestData.ts b/project/src/models/eft/profile/IProfileChangeVoiceRequestData.ts index bd238354..b3654893 100644 --- a/project/src/models/eft/profile/IProfileChangeVoiceRequestData.ts +++ b/project/src/models/eft/profile/IProfileChangeVoiceRequestData.ts @@ -1,4 +1,4 @@ -export interface IProfileChangeVoiceRequestData +export interface IProfileChangeVoiceRequestData { - voice: string -} \ No newline at end of file + voice: string; +} diff --git a/project/src/models/eft/profile/IProfileCreateRequestData.ts b/project/src/models/eft/profile/IProfileCreateRequestData.ts index 21308a81..1c9a266b 100644 --- a/project/src/models/eft/profile/IProfileCreateRequestData.ts +++ b/project/src/models/eft/profile/IProfileCreateRequestData.ts @@ -1,7 +1,7 @@ -export interface IProfileCreateRequestData +export interface IProfileCreateRequestData { - side: string - nickname: string - headId: string - voiceId: string -} \ No newline at end of file + side: string; + nickname: string; + headId: string; + voiceId: string; +} diff --git a/project/src/models/eft/profile/ISearchFriendRequestData.ts b/project/src/models/eft/profile/ISearchFriendRequestData.ts index abbd540b..95e12c4b 100644 --- a/project/src/models/eft/profile/ISearchFriendRequestData.ts +++ b/project/src/models/eft/profile/ISearchFriendRequestData.ts @@ -1,4 +1,4 @@ export interface ISearchFriendRequestData { - nickname: string -} \ No newline at end of file + nickname: string; +} diff --git a/project/src/models/eft/profile/ISearchFriendResponse.ts b/project/src/models/eft/profile/ISearchFriendResponse.ts index 999bb178..dfb1676a 100644 --- a/project/src/models/eft/profile/ISearchFriendResponse.ts +++ b/project/src/models/eft/profile/ISearchFriendResponse.ts @@ -1,13 +1,12 @@ export interface ISearchFriendResponse { - _id: string - Info: Info + _id: string; + Info: Info; } - + export interface Info { - Nickname: string - Side: string - Level: number + Nickname: string; + Side: string; + Level: number; } - \ No newline at end of file diff --git a/project/src/models/eft/profile/IValidateNicknameRequestData.ts b/project/src/models/eft/profile/IValidateNicknameRequestData.ts index a93d4754..9807d254 100644 --- a/project/src/models/eft/profile/IValidateNicknameRequestData.ts +++ b/project/src/models/eft/profile/IValidateNicknameRequestData.ts @@ -1,4 +1,4 @@ -export interface IValidateNicknameRequestData +export interface IValidateNicknameRequestData { - nickname: string -} \ No newline at end of file + nickname: string; +} diff --git a/project/src/models/eft/quests/IAcceptQuestRequestData.ts b/project/src/models/eft/quests/IAcceptQuestRequestData.ts index 5abaa204..327c52ca 100644 --- a/project/src/models/eft/quests/IAcceptQuestRequestData.ts +++ b/project/src/models/eft/quests/IAcceptQuestRequestData.ts @@ -1,6 +1,6 @@ -export interface IAcceptQuestRequestData +export interface IAcceptQuestRequestData { - Action: "QuestAccept" - qid: string - type: string -} \ No newline at end of file + Action: "QuestAccept"; + qid: string; + type: string; +} diff --git a/project/src/models/eft/quests/ICompleteQuestRequestData.ts b/project/src/models/eft/quests/ICompleteQuestRequestData.ts index 5ab37aca..9886c81e 100644 --- a/project/src/models/eft/quests/ICompleteQuestRequestData.ts +++ b/project/src/models/eft/quests/ICompleteQuestRequestData.ts @@ -1,8 +1,8 @@ -export interface ICompleteQuestRequestData +export interface ICompleteQuestRequestData { - Action: string + Action: string; /** Quest Id */ - qid: string - removeExcessItems: boolean -} \ No newline at end of file + qid: string; + removeExcessItems: boolean; +} diff --git a/project/src/models/eft/quests/IFailQuestRequestData.ts b/project/src/models/eft/quests/IFailQuestRequestData.ts index 86d379a9..9beb44f5 100644 --- a/project/src/models/eft/quests/IFailQuestRequestData.ts +++ b/project/src/models/eft/quests/IFailQuestRequestData.ts @@ -1,6 +1,6 @@ -export interface IFailQuestRequestData +export interface IFailQuestRequestData { - Action: "QuestComplete" - qid: string - removeExcessItems: boolean -} \ No newline at end of file + Action: "QuestComplete"; + qid: string; + removeExcessItems: boolean; +} diff --git a/project/src/models/eft/quests/IHandoverQuestRequestData.ts b/project/src/models/eft/quests/IHandoverQuestRequestData.ts index df0e0f07..4543cd37 100644 --- a/project/src/models/eft/quests/IHandoverQuestRequestData.ts +++ b/project/src/models/eft/quests/IHandoverQuestRequestData.ts @@ -1,13 +1,13 @@ -export interface IHandoverQuestRequestData +export interface IHandoverQuestRequestData { - Action: "QuestHandover" - qid: string - conditionId: string - items: Item[] + Action: "QuestHandover"; + qid: string; + conditionId: string; + items: Item[]; } -export interface Item +export interface Item { - id: string - count: number -} \ No newline at end of file + id: string; + count: number; +} diff --git a/project/src/models/eft/quests/IListQuestsRequestData.ts b/project/src/models/eft/quests/IListQuestsRequestData.ts index 1ed88298..0598751e 100644 --- a/project/src/models/eft/quests/IListQuestsRequestData.ts +++ b/project/src/models/eft/quests/IListQuestsRequestData.ts @@ -1,4 +1,4 @@ -export interface IListQuestsRequestData +export interface IListQuestsRequestData { - completed: boolean -} \ No newline at end of file + completed: boolean; +} diff --git a/project/src/models/eft/quests/IRepeatableQuestChangeRequest.ts b/project/src/models/eft/quests/IRepeatableQuestChangeRequest.ts index ab08bdb0..58dc2140 100644 --- a/project/src/models/eft/quests/IRepeatableQuestChangeRequest.ts +++ b/project/src/models/eft/quests/IRepeatableQuestChangeRequest.ts @@ -1,5 +1,5 @@ export interface IRepeatableQuestChangeRequest { - Action: "RepeatableQuestChange" - qid: string -} \ No newline at end of file + Action: "RepeatableQuestChange"; + qid: string; +} diff --git a/project/src/models/eft/ragfair/IAddOfferRequestData.ts b/project/src/models/eft/ragfair/IAddOfferRequestData.ts index e08e64c5..18376a3a 100644 --- a/project/src/models/eft/ragfair/IAddOfferRequestData.ts +++ b/project/src/models/eft/ragfair/IAddOfferRequestData.ts @@ -1,16 +1,16 @@ -export interface IAddOfferRequestData +export interface IAddOfferRequestData { - Action: string - sellInOnePiece: boolean - items: string[] - requirements: Requirement[] + Action: string; + sellInOnePiece: boolean; + items: string[]; + requirements: Requirement[]; } -export interface Requirement +export interface Requirement { - _tpl: string - count: number - level: number - side: number - onlyFunctional: boolean -} \ No newline at end of file + _tpl: string; + count: number; + level: number; + side: number; + onlyFunctional: boolean; +} diff --git a/project/src/models/eft/ragfair/IExtendOfferRequestData.ts b/project/src/models/eft/ragfair/IExtendOfferRequestData.ts index 2359aa68..116ddebc 100644 --- a/project/src/models/eft/ragfair/IExtendOfferRequestData.ts +++ b/project/src/models/eft/ragfair/IExtendOfferRequestData.ts @@ -1,5 +1,5 @@ -export interface IExtendOfferRequestData +export interface IExtendOfferRequestData { - offerId: string - renewalTime: number -} \ No newline at end of file + offerId: string; + renewalTime: number; +} diff --git a/project/src/models/eft/ragfair/IGetItemPriceResult.ts b/project/src/models/eft/ragfair/IGetItemPriceResult.ts index 7e33d73e..0bb80f2b 100644 --- a/project/src/models/eft/ragfair/IGetItemPriceResult.ts +++ b/project/src/models/eft/ragfair/IGetItemPriceResult.ts @@ -2,5 +2,5 @@ import { MinMax } from "@spt-aki/models/common/MinMax"; export interface IGetItemPriceResult extends MinMax { - avg: number -} \ No newline at end of file + avg: number; +} diff --git a/project/src/models/eft/ragfair/IGetMarketPriceRequestData.ts b/project/src/models/eft/ragfair/IGetMarketPriceRequestData.ts index ca64aa0c..17b20561 100644 --- a/project/src/models/eft/ragfair/IGetMarketPriceRequestData.ts +++ b/project/src/models/eft/ragfair/IGetMarketPriceRequestData.ts @@ -1,4 +1,4 @@ export interface IGetMarketPriceRequestData { - templateId: string -} \ No newline at end of file + templateId: string; +} diff --git a/project/src/models/eft/ragfair/IGetOffersResult.ts b/project/src/models/eft/ragfair/IGetOffersResult.ts index e5a3d968..983680dd 100644 --- a/project/src/models/eft/ragfair/IGetOffersResult.ts +++ b/project/src/models/eft/ragfair/IGetOffersResult.ts @@ -1,9 +1,9 @@ import { IRagfairOffer } from "@spt-aki/models/eft/ragfair/IRagfairOffer"; -export interface IGetOffersResult +export interface IGetOffersResult { - categories?: Record - offers: IRagfairOffer[] - offersCount: number - selectedCategory: string -} \ No newline at end of file + categories?: Record; + offers: IRagfairOffer[]; + offersCount: number; + selectedCategory: string; +} diff --git a/project/src/models/eft/ragfair/IRagfairOffer.ts b/project/src/models/eft/ragfair/IRagfairOffer.ts index 100602c8..3ef94492 100644 --- a/project/src/models/eft/ragfair/IRagfairOffer.ts +++ b/project/src/models/eft/ragfair/IRagfairOffer.ts @@ -1,54 +1,54 @@ import { Item } from "@spt-aki/models/eft/common/tables/IItem"; import { MemberCategory } from "@spt-aki/models/enums/MemberCategory"; -export interface IRagfairOffer +export interface IRagfairOffer { - sellResult?: SellResult[] - _id: string - items: Item[] - requirements: OfferRequirement[] - root: string - intId: number + sellResult?: SellResult[]; + _id: string; + items: Item[]; + requirements: OfferRequirement[]; + root: string; + intId: number; /** Handbook price */ - itemsCost: number + itemsCost: number; /** Rouble price */ - requirementsCost: number - startTime: number - endTime: number - sellInOnePiece: boolean - loyaltyLevel: number - buyRestrictionMax?: number - buyRestrictionCurrent?: number - locked: boolean - unlimitedCount: boolean + requirementsCost: number; + startTime: number; + endTime: number; + sellInOnePiece: boolean; + loyaltyLevel: number; + buyRestrictionMax?: number; + buyRestrictionCurrent?: number; + locked: boolean; + unlimitedCount: boolean; /** Rouble price */ - summaryCost: number - user: IRagfairOfferUser - notAvailable: boolean + summaryCost: number; + user: IRagfairOfferUser; + notAvailable: boolean; /** TODO - implement this value - not currently used */ - CurrentItemCount: number - priority: boolean + CurrentItemCount: number; + priority: boolean; } -export interface OfferRequirement +export interface OfferRequirement { - _tpl: string - count: number - onlyFunctional: boolean + _tpl: string; + count: number; + onlyFunctional: boolean; } -export interface IRagfairOfferUser +export interface IRagfairOfferUser { - id: string - nickname?: string - rating?: number - memberType: MemberCategory - avatar?: string - isRatingGrowing?: boolean + id: string; + nickname?: string; + rating?: number; + memberType: MemberCategory; + avatar?: string; + isRatingGrowing?: boolean; } export interface SellResult { - sellTime: number - amount: number -} \ No newline at end of file + sellTime: number; + amount: number; +} diff --git a/project/src/models/eft/ragfair/IRemoveOfferRequestData.ts b/project/src/models/eft/ragfair/IRemoveOfferRequestData.ts index 576bd991..6bb8d2d3 100644 --- a/project/src/models/eft/ragfair/IRemoveOfferRequestData.ts +++ b/project/src/models/eft/ragfair/IRemoveOfferRequestData.ts @@ -1,5 +1,5 @@ -export interface IRemoveOfferRequestData +export interface IRemoveOfferRequestData { - Action: string - offerId: string -} \ No newline at end of file + Action: string; + offerId: string; +} diff --git a/project/src/models/eft/ragfair/ISearchRequestData.ts b/project/src/models/eft/ragfair/ISearchRequestData.ts index 155e4a54..8f11fe9f 100644 --- a/project/src/models/eft/ragfair/ISearchRequestData.ts +++ b/project/src/models/eft/ragfair/ISearchRequestData.ts @@ -2,37 +2,37 @@ import { RagfairSort } from "@spt-aki/models/enums/RagfairSort"; export interface ISearchRequestData { - page: number - limit: number - sortType: RagfairSort - sortDirection: number - currency: number - priceFrom: number - priceTo: number - quantityFrom: number - quantityTo: number - conditionFrom: number - conditionTo: number - oneHourExpiration: boolean - removeBartering: boolean - offerOwnerType: OfferOwnerType - onlyFunctional: boolean - updateOfferCount: boolean - handbookId: string - linkedSearchId: string - neededSearchId: string - buildItems: BuildItems - buildCount: number - tm: number - reload: number + page: number; + limit: number; + sortType: RagfairSort; + sortDirection: number; + currency: number; + priceFrom: number; + priceTo: number; + quantityFrom: number; + quantityTo: number; + conditionFrom: number; + conditionTo: number; + oneHourExpiration: boolean; + removeBartering: boolean; + offerOwnerType: OfferOwnerType; + onlyFunctional: boolean; + updateOfferCount: boolean; + handbookId: string; + linkedSearchId: string; + neededSearchId: string; + buildItems: BuildItems; + buildCount: number; + tm: number; + reload: number; } export enum OfferOwnerType - { +{ ANYOWNERTYPE = 0, TRADEROWNERTYPE = 1, - PLAYEROWNERTYPE = 2 + PLAYEROWNERTYPE = 2, } - -export interface BuildItems -{} \ No newline at end of file + +export interface BuildItems +{} diff --git a/project/src/models/eft/ragfair/ISendRagfairReportRequestData.ts b/project/src/models/eft/ragfair/ISendRagfairReportRequestData.ts index 09e17e72..f9deffa9 100644 --- a/project/src/models/eft/ragfair/ISendRagfairReportRequestData.ts +++ b/project/src/models/eft/ragfair/ISendRagfairReportRequestData.ts @@ -1,4 +1,4 @@ export interface ISendRagfairReportRequestData { - offerId: number -} \ No newline at end of file + offerId: number; +} diff --git a/project/src/models/eft/ragfair/IStorePlayerOfferTaxAmountRequestData.ts b/project/src/models/eft/ragfair/IStorePlayerOfferTaxAmountRequestData.ts index 89b22194..67aed9a5 100644 --- a/project/src/models/eft/ragfair/IStorePlayerOfferTaxAmountRequestData.ts +++ b/project/src/models/eft/ragfair/IStorePlayerOfferTaxAmountRequestData.ts @@ -1,7 +1,7 @@ export interface IStorePlayerOfferTaxAmountRequestData { - id: string - tpl: string - count: number - fee: number -} \ No newline at end of file + id: string; + tpl: string; + count: number; + fee: number; +} diff --git a/project/src/models/eft/repair/IBaseRepairActionDataRequest.ts b/project/src/models/eft/repair/IBaseRepairActionDataRequest.ts index e01e536b..67fe317f 100644 --- a/project/src/models/eft/repair/IBaseRepairActionDataRequest.ts +++ b/project/src/models/eft/repair/IBaseRepairActionDataRequest.ts @@ -1,4 +1,4 @@ export interface IBaseRepairActionDataRequest { - Action: string -} \ No newline at end of file + Action: string; +} diff --git a/project/src/models/eft/repair/IRepairActionDataRequest.ts b/project/src/models/eft/repair/IRepairActionDataRequest.ts index ad56e1f4..f22750a3 100644 --- a/project/src/models/eft/repair/IRepairActionDataRequest.ts +++ b/project/src/models/eft/repair/IRepairActionDataRequest.ts @@ -2,13 +2,13 @@ import { IBaseRepairActionDataRequest } from "@spt-aki/models/eft/repair/IBaseRe export interface IRepairActionDataRequest extends IBaseRepairActionDataRequest { - Action: "Repair" - repairKitsInfo: RepairKitsInfo[] - target: string // item to repair + Action: "Repair"; + repairKitsInfo: RepairKitsInfo[]; + target: string; // item to repair } export interface RepairKitsInfo { - _id: string // id of repair kit to use - count: number // amout of units to reduce kit by -} \ No newline at end of file + _id: string; // id of repair kit to use + count: number; // amout of units to reduce kit by +} diff --git a/project/src/models/eft/repair/ITraderRepairActionDataRequest.ts b/project/src/models/eft/repair/ITraderRepairActionDataRequest.ts index 586b177f..6aa6f5b5 100644 --- a/project/src/models/eft/repair/ITraderRepairActionDataRequest.ts +++ b/project/src/models/eft/repair/ITraderRepairActionDataRequest.ts @@ -2,13 +2,13 @@ import { IBaseRepairActionDataRequest } from "@spt-aki/models/eft/repair/IBaseRe export interface ITraderRepairActionDataRequest extends IBaseRepairActionDataRequest { - Action: "TraderRepair" - tid: string - repairItems: RepairItem[] + Action: "TraderRepair"; + tid: string; + repairItems: RepairItem[]; } - + export interface RepairItem { - _id: string - count: number -} \ No newline at end of file + _id: string; + count: number; +} diff --git a/project/src/models/eft/trade/IProcessBaseTradeRequestData.ts b/project/src/models/eft/trade/IProcessBaseTradeRequestData.ts index 5a93a75f..2d59e790 100644 --- a/project/src/models/eft/trade/IProcessBaseTradeRequestData.ts +++ b/project/src/models/eft/trade/IProcessBaseTradeRequestData.ts @@ -1,6 +1,6 @@ -export interface IProcessBaseTradeRequestData +export interface IProcessBaseTradeRequestData { - Action: string - type: string - tid: string -} \ No newline at end of file + Action: string; + type: string; + tid: string; +} diff --git a/project/src/models/eft/trade/IProcessBuyTradeRequestData.ts b/project/src/models/eft/trade/IProcessBuyTradeRequestData.ts index 5fc93bbb..84299f3d 100644 --- a/project/src/models/eft/trade/IProcessBuyTradeRequestData.ts +++ b/project/src/models/eft/trade/IProcessBuyTradeRequestData.ts @@ -1,20 +1,19 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { IProcessBaseTradeRequestData } from "@spt-aki/models/eft/trade/IProcessBaseTradeRequestData"; -export interface IProcessBuyTradeRequestData extends IProcessBaseTradeRequestData +export interface IProcessBuyTradeRequestData extends IProcessBaseTradeRequestData { - Action: "buy_from_trader" | "TradingConfirm" | "RestoreHealth" | "" - type: string - tid: string - item_id: string - count: number - scheme_id: number - scheme_items: SchemeItem[] + Action: "buy_from_trader" | "TradingConfirm" | "RestoreHealth" | ""; + type: string; + tid: string; + item_id: string; + count: number; + scheme_id: number; + scheme_items: SchemeItem[]; } - -export interface SchemeItem + +export interface SchemeItem { - id: string - count: number + id: string; + count: number; } - \ No newline at end of file diff --git a/project/src/models/eft/trade/IProcessRagfairTradeRequestData.ts b/project/src/models/eft/trade/IProcessRagfairTradeRequestData.ts index c258b75f..9b6567dc 100644 --- a/project/src/models/eft/trade/IProcessRagfairTradeRequestData.ts +++ b/project/src/models/eft/trade/IProcessRagfairTradeRequestData.ts @@ -1,18 +1,18 @@ -export interface IProcessRagfairTradeRequestData +export interface IProcessRagfairTradeRequestData { - Action: string - offers: Offer[] + Action: string; + offers: Offer[]; } -export interface Offer +export interface Offer { - id: string - count: number - items: Item[] + id: string; + count: number; + items: Item[]; } -export interface Item +export interface Item { - id: string - count: number -} \ No newline at end of file + id: string; + count: number; +} diff --git a/project/src/models/eft/trade/IProcessSellTradeRequestData.ts b/project/src/models/eft/trade/IProcessSellTradeRequestData.ts index 6790be15..6070c32b 100644 --- a/project/src/models/eft/trade/IProcessSellTradeRequestData.ts +++ b/project/src/models/eft/trade/IProcessSellTradeRequestData.ts @@ -1,18 +1,18 @@ import { IProcessBaseTradeRequestData } from "@spt-aki/models/eft/trade/IProcessBaseTradeRequestData"; -export interface IProcessSellTradeRequestData extends IProcessBaseTradeRequestData +export interface IProcessSellTradeRequestData extends IProcessBaseTradeRequestData { - Action: "sell_to_trader" - type: string - tid: string - price: number - items: Item[] + Action: "sell_to_trader"; + type: string; + tid: string; + price: number; + items: Item[]; } -export interface Item +export interface Item { - id: string - count: number + id: string; + count: number; // eslint-disable-next-line @typescript-eslint/naming-convention - scheme_id: number -} \ No newline at end of file + scheme_id: number; +} diff --git a/project/src/models/eft/trade/ISellScavItemsToFenceRequestData.ts b/project/src/models/eft/trade/ISellScavItemsToFenceRequestData.ts index 8137685c..bb40b787 100644 --- a/project/src/models/eft/trade/ISellScavItemsToFenceRequestData.ts +++ b/project/src/models/eft/trade/ISellScavItemsToFenceRequestData.ts @@ -2,7 +2,7 @@ import { OwnerInfo } from "@spt-aki/models/eft/common/request/IBaseInteractionRe export interface ISellScavItemsToFenceRequestData { - Action: "SellAllFromSavage", - fromOwner: OwnerInfo - toOwner: OwnerInfo -} \ No newline at end of file + Action: "SellAllFromSavage"; + fromOwner: OwnerInfo; + toOwner: OwnerInfo; +} diff --git a/project/src/models/eft/weather/IWeatherData.ts b/project/src/models/eft/weather/IWeatherData.ts index a15d7e1a..37174465 100644 --- a/project/src/models/eft/weather/IWeatherData.ts +++ b/project/src/models/eft/weather/IWeatherData.ts @@ -5,10 +5,10 @@ export interface IWeatherData acceleration: number; time: string; date: string; - weather?: IWeather + weather?: IWeather; } -export interface IWeather +export interface IWeather { pressure: number; temp: number; @@ -26,4 +26,4 @@ export interface IWeather time: string; date: string; timestamp: number; -} \ No newline at end of file +} diff --git a/project/src/models/eft/wishlist/IWishlistActionData.ts b/project/src/models/eft/wishlist/IWishlistActionData.ts index a15007c2..0f54fcfa 100644 --- a/project/src/models/eft/wishlist/IWishlistActionData.ts +++ b/project/src/models/eft/wishlist/IWishlistActionData.ts @@ -1,6 +1,5 @@ -export interface IWishlistActionData +export interface IWishlistActionData { - Action: string - templateId: string + Action: string; + templateId: string; } - \ No newline at end of file diff --git a/project/src/models/enums/AccountTypes.ts b/project/src/models/enums/AccountTypes.ts index da0df455..991d0f8c 100644 --- a/project/src/models/enums/AccountTypes.ts +++ b/project/src/models/enums/AccountTypes.ts @@ -1,4 +1,4 @@ export enum AccountTypes - { - SPT_DEVELOPER = "spt developer" -} \ No newline at end of file +{ + SPT_DEVELOPER = "spt developer", +} diff --git a/project/src/models/enums/AirdropType.ts b/project/src/models/enums/AirdropType.ts index ba55ab40..e1a54b67 100644 --- a/project/src/models/enums/AirdropType.ts +++ b/project/src/models/enums/AirdropType.ts @@ -1,7 +1,7 @@ export enum AirdropTypeEnum - { +{ MIXED = "mixed", WEAPONARMOR = "weaponarmor", FOODMEDICAL = "foodmedical", - BARTER = "barter" -} \ No newline at end of file + BARTER = "barter", +} diff --git a/project/src/models/enums/AmmoTypes.ts b/project/src/models/enums/AmmoTypes.ts index 6d486ec0..5da5c574 100644 --- a/project/src/models/enums/AmmoTypes.ts +++ b/project/src/models/enums/AmmoTypes.ts @@ -1,74 +1,74 @@ -export enum Grenade - { +export enum Grenade +{ M386_HE_GRENADE = "5ede475b549eed7c6d5c18fb", M576_MP_APERS_GRENADE = "5ede475339ee016e8c534742", M433_HEDP_GRENADE = "5f0c892565703e5c461894e9", M406_HE_GRENADE = "5ede4739e0350d05467f73e8", M381_HE_GRENADE = "5ede474b0c226a66f5402622", - M441_HE_GRENADE = "5ede47405b097655935d7d16" + M441_HE_GRENADE = "5ede47405b097655935d7d16", } export enum Ammo762x51 - { +{ M62_TRACER = "5a608bf24f39f98ffc77720e", M80 = "58dd3ad986f77403051cba8f", M61 = "5a6086ea4f39f99cd479502f", BCP_FMJ = "5e023e53d4353e3302577c4c", ULTRA_NOSLER = "5e023e88277cce2b522ff2b1", TCW_SP = "5e023e6e34d52a55c3304f71", - M993 = "5efb0c1bd79ff02a1f5e68d9" + M993 = "5efb0c1bd79ff02a1f5e68d9", } export enum Ammo762x54 - { +{ SNB_GZH = "560d61e84bdc2da74d8b4571", LPS_GZH = "5887431f2459777e1612938f", PS_GZH = "59e77a2386f7742ee578960a", T46M_GZH = "5e023cf8186a883be655e54f", BT_GZH = "5e023d34e8a400319a28ed44", - BS_GZH = "5e023d48186a883be655e551" + BS_GZH = "5e023d48186a883be655e551", } export enum Ammo86x70 - { +{ TAC_X = "5fc382b6d6fa9c00c571bbc3", UCW = "5fc382c1016cce60e8341b20", AP = "5fc382a9d724d907e2077dab", - FMJ = "5fc275cf85fd526b824a571a" + FMJ = "5fc275cf85fd526b824a571a", } export enum Ammo46x30 - { +{ AP_SX = "5ba26835d4351e0035628ff5", ACTION_SX = "5ba26812d4351e003201fef1", FMJ_SX = "5ba2678ad4351e44f824b344", - SUBSONIC_SX = "5ba26844d4351e00334c9475" + SUBSONIC_SX = "5ba26844d4351e00334c9475", } export enum Ammo57x28 - { +{ SS198LF = "5cc80f79e4a949033c7343b2", R37_F = "5cc86832d7f00c000d3a6e6c", SS190 = "5cc80f38e4a949001152b560", R37_X = "5cc86840d7f00c002412c56c", L191 = "5cc80f53e4a949000e1ea4f8", SS197SR = "5cc80f8fe4a949033b0224a2", - SB193 = "5cc80f67e4a949035e43bbba" + SB193 = "5cc80f67e4a949035e43bbba", } export enum Ammo762x25 - { +{ FMJ43 = "5735ff5c245977640e39ba7e", LRN = "573601b42459776410737435", P_GL = "5736026a245977644601dc61", PST_GZH = "573603562459776430731618", LRNPC = "573602322459776445391df1", AKBS = "5735fdcd2459776445391d61", - PT_GZH = "573603c924597764442bd9cb" + PT_GZH = "573603c924597764442bd9cb", } export enum Ammo9x18 - { +{ PM_SP8_GZH = "5737218f245977612125ba51", P_GZH = "573719762459775a626ccbc1", PSTM_GZH = "57371aab2459775a77142f22", @@ -82,11 +82,11 @@ export enum Ammo9x18 PS_GS_PPO = "57371f2b24597761224311f1", PRS_GS = "57371eb62459776125652ac1", PPT_GZH = "57371e4124597760ff7b25f1", - PPE_GZH = "57371b192459775a9f58a5e0" + PPE_GZH = "57371b192459775a9f58a5e0", } export enum Ammo9x19 - { +{ PSO_GZH = "58864a4f2459770fcc257101", PST_GZH = "56d59d3ad2720bdb418b4577", GREEN_TRACER = "5c3df7d588a4501f290594e5", @@ -94,36 +94,36 @@ export enum Ammo9x19 AP_63 = "5c925fa22e221601da359b7b", LUGER_CCI = "5a3c16fe86f77452b62de32a", PBP_GZH = "5efb0da7a29a85116f6ea05f", - QUAKEMAKER = "5efb0e16aeb21837e749c7ff" + QUAKEMAKER = "5efb0e16aeb21837e749c7ff", } export enum Ammo9x21 - { +{ P_GZH = "5a26abfac4a28232980eabff", PS_GZH = "5a269f97c4a282000b151807", PE_GZH = "5a26ac06c4a282000c5a90a8", - BT_GZH = "5a26ac0ec4a28200741e1e18" + BT_GZH = "5a26ac0ec4a28200741e1e18", } export enum Ammo9x33R - { +{ FMJ = "62330b3ed4dc74626d570b95", HOLLOW_POINT = "62330bfadc5883093563729b", SOFT_POINT = "62330c40bdd19b369e1e53d1", - JACKET_HP = "62330c18744e5e31df12f516" + JACKET_HP = "62330c18744e5e31df12f516", } export enum Ammo1143x23ACP - { +{ MATCH_FMJ = "5e81f423763d9f754677bf2e", HYDRA_SHOK = "5efb0fc6aeb21837e749c801", LASERMATCH_FMJ = "5efb0d4f4bc50b58e81710f3", AP = "5efb0cabfb3e451d70735af5", - RIP = "5ea2a8e200685063ec28c05a" + RIP = "5ea2a8e200685063ec28c05a", } export enum Ammo545x39 - { +{ PS_GS = "56dff3afd2720bba668b4567", SP = "56dff421d2720b5f5a8b4567", PPBS_GS_IGOLNIK = "5c0d5e4486f77478390952fe", @@ -136,11 +136,11 @@ export enum Ammo545x39 BS_GS = "56dff026d2720bb8668b4567", T_GS = "56dff4a2d2720bbd668b456a", PP_GS = "56dff2ced2720bb4668b4567", - FMJ = "56dff0bed2720bb0668b4567" + FMJ = "56dff0bed2720bb0668b4567", } export enum Ammo556x45 - { +{ M856 = "59e68f6f86f7746c9f75e846", MK255_MOD_0_RRLP = "59e6918f86f7746c9f75e849", M995 = "59e690b686f7746c9f75e848", @@ -151,54 +151,54 @@ export enum Ammo556x45 FMJ = "59e6920f86f77411d82aa167", WARMAGEDDON = "5c0d5ae286f7741e46554302", MK_318_MOD_0_SOST = "60194943740c5d77f6705eea", - SSA_AP = "601949593ae8f707c4608daa" + SSA_AP = "601949593ae8f707c4608daa", } export enum Ammo762x35 - { +{ M62_TRACER = "619636be6db0f2477964e710", BCP_FMJ = "5fbe3ffdf8b6a877a729ea82", AP = "5fd20ff893a8961fc660a954", V_MAX = "6196364158ef8c428c287d9f", - WHISPER = "6196365d58ef8c428c287da1" + WHISPER = "6196365d58ef8c428c287da1", } export enum Ammo762x39 - { +{ PS_GZH = "5656d7c34bdc2d9d198b4587", HP = "59e4d3d286f774176a36250a", US_GZH = "59e4d24686f7741776641ac7", T45M1_GZH = "59e4cf5286f7741778269d8a", BP_GZH = "59e0d99486f7744a32234762", - MAI_AP = "601aa3d2b2bcb34913271e6d" + MAI_AP = "601aa3d2b2bcb34913271e6d", } export enum Ammo9x39 - { +{ SP5_GS = "57a0dfb82459774d3078b56c", BP_GS = "5c0d688c86f77413ae3407b2", SP6_GS = "57a0e5022459774d1673f889", SPP_GS = "5c0d668f86f7747ccb7f13b2", - PAB9_GS = "61962d879bb3d20b0946d385" + PAB9_GS = "61962d879bb3d20b0946d385", } export enum Ammo366TKM - { +{ FMJ = "59e6542b86f77411dc52a77a", GEKSA = "59e6658b86f77411d949b250", EKO = "59e655cb86f77411dc52a77b", - APM = "5f0596629e22f464da6bbdd9" + APM = "5f0596629e22f464da6bbdd9", } export enum Ammo127x55 - { +{ PS12 = "5cadf6ddae9215051e1c23b2", PS12B = "5cadf6eeae921500134b2799", - PS12A = "5cadf6e5ae921500113bb973" + PS12A = "5cadf6e5ae921500113bb973", } export enum Ammo12Gauge - { +{ BUCKSHOT_7MM = "560d5e524bdc2d25448b4571", MAGNUM_85MM = "5d6e6806a4b936088465b17e", RIP = "5c0d591486f7744c505b416f", @@ -214,11 +214,11 @@ export enum Ammo12Gauge GRIZZLY_40_SLUG = "5d6e6869a4b9361c140bcfde", SUPERFORMANCE_HP_SLUG = "5d6e68d1a4b93622fe60e845", COPPER_SABOT_PREMIER_HP_SLUG = "5d6e68b3a4b9361bca7e50b5", - LEAD_SLUG = "58820d1224597753c90aeb13" + LEAD_SLUG = "58820d1224597753c90aeb13", } export enum Ammo20Gauge - { +{ BUCKSHOT_75MM = "5a38ebd9c4a282000d722a5b", STAR_SLUG = "5d6e6a05a4b93618084f58d0", BUCKSHOT_73MM = "5d6e69c7a4b9360b6c0d54e4", @@ -226,32 +226,32 @@ export enum Ammo20Gauge BUCKSHOT_56MM = "5d6e695fa4b936359b35d852", POLEVA_6U_SLUG = "5d6e6a42a4b9364f07165f52", POLEVA_3_SLUG = "5d6e6a53a4b9361bd473feec", - BUCKSHOT_62MM = "5d6e69b9a4b9361bc8618958" + BUCKSHOT_62MM = "5d6e69b9a4b9361bc8618958", } export enum Ammo23x75 - { +{ SHRAPNEL10_BUCKSHOT = "5e85a9a6eacf8c039e4e2ac1", SHRAPNEL25_BUCKSHOT = "5f647f31b6238e5dd066e196", ZVEZDA_FLASHBANG = "5e85a9f4add9fe03027d9bf1", - BARRIKADA_SLUG = "5e85aa1a988a8701445df1f5" + BARRIKADA_SLUG = "5e85aa1a988a8701445df1f5", } export enum Ammo30x29 - { - VOG_30 = "5d70e500a4b9364de70d38ce" +{ + VOG_30 = "5d70e500a4b9364de70d38ce", } export enum Ammo127x108 - { +{ B32 = "5cde8864d7f00c0010373be1", - BZT_44M = "5d2f2ab648f03550091993ca" + BZT_44M = "5d2f2ab648f03550091993ca", } export enum Ammo26x75 - { +{ GREEN_FLARE = "62389aaba63f32501b1b444f", RED_FLARE = "62389ba9a63f32501b1b4451", WHITE_FLARE = "62389bc9423ed1685422dc57", - YELLOW_FLARE = "62389be94d5d474bf712e709" -} \ No newline at end of file + YELLOW_FLARE = "62389be94d5d474bf712e709", +} diff --git a/project/src/models/enums/BackendErrorCodes.ts b/project/src/models/enums/BackendErrorCodes.ts index 299deee9..81f00650 100644 --- a/project/src/models/enums/BackendErrorCodes.ts +++ b/project/src/models/enums/BackendErrorCodes.ts @@ -1,5 +1,5 @@ export enum BackendErrorCodes - { +{ NONE = 0, UNKNOWN_ERROR = 200, NOT_AUTHORIZED = 201, @@ -78,9 +78,9 @@ export enum BackendErrorCodes PLAYERFORBIDDENGROUPINVITES = 502011, LEADERALREADYREADY = 502012, GROUPSENDINVITEERROR = 502013, - PLAYERISOFFLINE = 502014, + PLAYERISOFFLINE = 502014, PLAYERISNOTSEARCHINGFORGROUP = 502018, PLAYERALREADYLOOKINGFORGAME = 503001, PLAYERINRAID = 503002, - LIMITFORPRESETSREACHED = 504001 -} \ No newline at end of file + LIMITFORPRESETSREACHED = 504001, +} diff --git a/project/src/models/enums/BaseClasses.ts b/project/src/models/enums/BaseClasses.ts index 117e9441..b8411ce2 100644 --- a/project/src/models/enums/BaseClasses.ts +++ b/project/src/models/enums/BaseClasses.ts @@ -1,5 +1,5 @@ export enum BaseClasses - { +{ WEAPON = "5422acb9af1c889c16000029", UBGL = "55818b014bdc2ddc698b456b", ARMOR = "5448e54d4bdc2dcc718b4568", @@ -19,13 +19,13 @@ export enum BaseClasses INFO = "5448ecbe4bdc2d60728b4568", MEDKIT = "5448f39d4bdc2d0a728b4568", DRUGS = "5448f3a14bdc2d27728b4569", - STIMULATOR= "5448f3a64bdc2d60728b456a", + STIMULATOR = "5448f3a64bdc2d60728b456a", MEDICAL = "5448f3ac4bdc2dce718b4569", - MEDICAL_SUPPLIES= "57864c8c245977548867e7f1", + MEDICAL_SUPPLIES = "57864c8c245977548867e7f1", MOD = "5448fe124bdc2da5018b4567", FUNCTIONAL_MOD = "550aa4154bdc2dd8348b456b", FUEL = "5d650c3e815116009f6201d2", - GEAR_MOD= "55802f3e4bdc2de7118b4584", + GEAR_MOD = "55802f3e4bdc2de7118b4584", STOCK = "55818a594bdc2db9688b456a", FOREGRIP = "55818af64bdc2d5b648b4570", MASTER_MOD = "55802f4a4bdc2ddb688b4569", @@ -51,7 +51,7 @@ export enum BaseClasses SHOTGUN = "5447b6094bdc2dc3278b4567", MARKSMAN_RIFLE = "5447b6194bdc2d67278b4567", SNIPER_RIFLE = "5447b6254bdc2dc3278b4568", - MACHINE_GUN ="5447bed64bdc2d97278b4568", + MACHINE_GUN = "5447bed64bdc2d97278b4568", GRENADE_LAUNCHER = "5447bedf4bdc2d87278b4568", SPECIAL_WEAPON = "5447bee84bdc2dc3278b4569", SPEC_ITEM = "5447e0e74bdc2d3c308b4567", @@ -73,31 +73,31 @@ export enum BaseClasses DOG_TAG_BEAR = "59f32bb586f774757e1e8442", JEWELRY = "57864a3d24597754843f8721", ELECTRONICS = "57864a66245977548f04a81f", - BUILDING_MATERIAL= "57864ada245977548638de91", - TOOL= "57864bb7245977548b3b66c2", + BUILDING_MATERIAL = "57864ada245977548638de91", + TOOL = "57864bb7245977548b3b66c2", HOUSEHOLD_GOODS = "57864c322459775490116fbf", LUBRICANT = "57864e4c24597754843f8723", - BATTERY= "57864ee62459775490116fc1", + BATTERY = "57864ee62459775490116fc1", ASSAULT_SCOPE = "55818add4bdc2d5b648b456f", TACTICAL_COMBO = "55818b164bdc2ddc698b456c", FLASHLIGHT = "55818b084bdc2d5b648b4571", - MAGAZINE= "5448bc234bdc2d3c308b4569", - LIGHT_LASER_DESIGNATOR= "55818b0e4bdc2dde698b456e", - FLASH_HIDER= "550aa4bf4bdc2dd6348b456b", - COLLIMATOR= "55818ad54bdc2ddc698b4569", - IRON_SIGHT= "55818ac54bdc2d5b648b456e", - COMPACT_COLLIMATOR= "55818acf4bdc2dde698b456b", - COMPENSATOR= "550aa4af4bdc2dd4348b456e", - OPTIC_SCOPE= "55818ae44bdc2dde698b456c", - SPECIAL_SCOPE= "55818aeb4bdc2ddc698b456a", - OTHER= "590c745b86f7743cc433c5f2", - SILENCER= "550aa4cd4bdc2dd8348b456c", - PORTABLE_RANGE_FINDER= "61605ddea09d851a0a0c1bbc", - ITEM= "54009119af1c881c07000029", - CYLINDER_MAGAZINE= "610720f290b75a49ff2e5e25", + MAGAZINE = "5448bc234bdc2d3c308b4569", + LIGHT_LASER_DESIGNATOR = "55818b0e4bdc2dde698b456e", + FLASH_HIDER = "550aa4bf4bdc2dd6348b456b", + COLLIMATOR = "55818ad54bdc2ddc698b4569", + IRON_SIGHT = "55818ac54bdc2d5b648b456e", + COMPACT_COLLIMATOR = "55818acf4bdc2dde698b456b", + COMPENSATOR = "550aa4af4bdc2dd4348b456e", + OPTIC_SCOPE = "55818ae44bdc2dde698b456c", + SPECIAL_SCOPE = "55818aeb4bdc2ddc698b456a", + OTHER = "590c745b86f7743cc433c5f2", + SILENCER = "550aa4cd4bdc2dd8348b456c", + PORTABLE_RANGE_FINDER = "61605ddea09d851a0a0c1bbc", + ITEM = "54009119af1c881c07000029", + CYLINDER_MAGAZINE = "610720f290b75a49ff2e5e25", AUXILARY_MOD = "5a74651486f7744e73386dd1", BIPOD = "55818afb4bdc2dde698b456d", HEADPHONES = "5645bcb74bdc2ded0b8b4578", RANDOM_LOOT_CONTAINER = "62f109593b54472778797866", - STACKABLE_ITEM = "5661632d4bdc2d903d8b456b" -} \ No newline at end of file + STACKABLE_ITEM = "5661632d4bdc2d903d8b456b", +} diff --git a/project/src/models/enums/BotAmount.ts b/project/src/models/enums/BotAmount.ts index 9948d222..80ad9233 100644 --- a/project/src/models/enums/BotAmount.ts +++ b/project/src/models/enums/BotAmount.ts @@ -1,8 +1,8 @@ export enum BotAmount - { +{ AS_ONLINE = "AsOnline", LOW = "Low", MEDIUM = "Medium", HIGH = "High", - HORDE = "Horde" -} \ No newline at end of file + HORDE = "Horde", +} diff --git a/project/src/models/enums/BotDifficulty.ts b/project/src/models/enums/BotDifficulty.ts index 3e72c9cc..fd21a78b 100644 --- a/project/src/models/enums/BotDifficulty.ts +++ b/project/src/models/enums/BotDifficulty.ts @@ -1,9 +1,9 @@ export enum BotDifficulty - { +{ AS_ONLINE = "AsOnline", EASY = "Easy", MEDIUM = "Medium", HARD = "Hard", IMPOSSIBLE = "Impossible", - RANDOM = "Random" -} \ No newline at end of file + RANDOM = "Random", +} diff --git a/project/src/models/enums/ConfigTypes.ts b/project/src/models/enums/ConfigTypes.ts index 118fbf12..3cc2aed3 100644 --- a/project/src/models/enums/ConfigTypes.ts +++ b/project/src/models/enums/ConfigTypes.ts @@ -1,5 +1,5 @@ export enum ConfigTypes - { +{ AIRDROP = "aki-airdrop", BOT = "aki-bot", PMC = "aki-pmc", @@ -25,5 +25,5 @@ export enum ConfigTypes WEATHER = "aki-weather", SEASONAL_EVENT = "aki-seasonalevents", LOST_ON_DEATH = "aki-lostondeath", - GIFTS = "aki-gifts" -} \ No newline at end of file + GIFTS = "aki-gifts", +} diff --git a/project/src/models/enums/ContainerTypes.ts b/project/src/models/enums/ContainerTypes.ts index 114395ec..8f4de42b 100644 --- a/project/src/models/enums/ContainerTypes.ts +++ b/project/src/models/enums/ContainerTypes.ts @@ -1,5 +1,5 @@ -export enum CommonContainers - { +export enum CommonContainers +{ AMMO_CASE = "5aafbde786f774389d0cbc0f", DOCUMENTS_CASE = "590c60fc86f77412b13fddcf", DOGTAG_CASE = "5c093e3486f77430cb02e593", @@ -19,14 +19,14 @@ export enum CommonContainers THICC_ITEM_CASE = "5c0a840b86f7742ffa4f2482", THICC_WEAPON_CASE = "5b6d9ce188a4501afc1b2b25", WEAPON_CASE = "59fb023c86f7746d0d4b423c", - WZ_WALLET = "60b0f6c058e0b0481a09ad11" + WZ_WALLET = "60b0f6c058e0b0481a09ad11", } export enum SecuredContainers - { +{ ALPHA = "544a11ac4bdc2d470e8b456a", BETA = "5857a8b324597729ab0a0e7d", EPSILON = "59db794186f77448bc595262", GAMMA = "5857a8bc2459772bad15db29", - KAPPA = "5c093ca986f7740a1867ab12" -} \ No newline at end of file + KAPPA = "5c093ca986f7740a1867ab12", +} diff --git a/project/src/models/enums/ELocationName.ts b/project/src/models/enums/ELocationName.ts index c92b4153..9469f4c9 100644 --- a/project/src/models/enums/ELocationName.ts +++ b/project/src/models/enums/ELocationName.ts @@ -1,5 +1,5 @@ -export enum ELocationName - { +export enum ELocationName +{ FACTORY_DAY = "factory4_day", FACTORY_NIGHT = "factory4_night", BIGMAP = "bigmap", @@ -10,5 +10,5 @@ export enum ELocationName LABORATORY = "laboratory", RESERVE = "RezervBase", STREETS = "TarkovStreets", - ANY = "any" -} \ No newline at end of file + ANY = "any", +} diff --git a/project/src/models/enums/EquipmentBuildType.ts b/project/src/models/enums/EquipmentBuildType.ts index 9d7bb9e8..f309a9ea 100644 --- a/project/src/models/enums/EquipmentBuildType.ts +++ b/project/src/models/enums/EquipmentBuildType.ts @@ -1,5 +1,5 @@ export enum EquipmentBuildType - { +{ CUSTOM = 0, - STANDARD = 1 -} \ No newline at end of file + STANDARD = 1, +} diff --git a/project/src/models/enums/EquipmentSlots.ts b/project/src/models/enums/EquipmentSlots.ts index 24f332d9..510e97be 100644 --- a/project/src/models/enums/EquipmentSlots.ts +++ b/project/src/models/enums/EquipmentSlots.ts @@ -1,5 +1,5 @@ export enum EquipmentSlots - { +{ HEADWEAR = "Headwear", EARPIECE = "Earpiece", FACE_COVER = "FaceCover", @@ -13,5 +13,5 @@ export enum EquipmentSlots FIRST_PRIMARY_WEAPON = "FirstPrimaryWeapon", SECOND_PRIMARY_WEAPON = "SecondPrimaryWeapon", HOLSTER = "Holster", - SCABBARD = "Scabbard" -} \ No newline at end of file + SCABBARD = "Scabbard", +} diff --git a/project/src/models/enums/ExitStatis.ts b/project/src/models/enums/ExitStatis.ts index 4333e2cf..547afa60 100644 --- a/project/src/models/enums/ExitStatis.ts +++ b/project/src/models/enums/ExitStatis.ts @@ -1,8 +1,8 @@ export enum ExitStatus - { +{ SURVIVED = 0, KILLED = 1, LEFT = 2, RUNNER = 3, - MISSINGINACTION = 4 -} \ No newline at end of file + MISSINGINACTION = 4, +} diff --git a/project/src/models/enums/GiftSenderType.ts b/project/src/models/enums/GiftSenderType.ts index 793d0bd3..9bf3f3a2 100644 --- a/project/src/models/enums/GiftSenderType.ts +++ b/project/src/models/enums/GiftSenderType.ts @@ -1,6 +1,6 @@ export enum GiftSenderType - { +{ SYSTEM = "System", TRADER = "Trader", - USER = "User" -} \ No newline at end of file + USER = "User", +} diff --git a/project/src/models/enums/GiftSentResult.ts b/project/src/models/enums/GiftSentResult.ts index 7c1295dd..3e68390c 100644 --- a/project/src/models/enums/GiftSentResult.ts +++ b/project/src/models/enums/GiftSentResult.ts @@ -1,7 +1,7 @@ export enum GiftSentResult - { +{ FAILED_UNKNOWN = 1, FAILED_GIFT_ALREADY_RECEIVED = 2, FAILED_GIFT_DOESNT_EXIST = 3, - SUCCESS = 4 -} \ No newline at end of file + SUCCESS = 4, +} diff --git a/project/src/models/enums/HideoutAreas.ts b/project/src/models/enums/HideoutAreas.ts index 7e86ef7b..ba46a3cf 100644 --- a/project/src/models/enums/HideoutAreas.ts +++ b/project/src/models/enums/HideoutAreas.ts @@ -1,5 +1,5 @@ -export enum HideoutAreas - { +export enum HideoutAreas +{ NOTSET = -1, VENTS = 0, SECURITY = 1, @@ -26,5 +26,5 @@ export enum HideoutAreas EMERGENCY_WALL = 22, GYM = 23, WEAPON_STAND = 24, - WEAPON_STAND_SECONDARY = 25 -} \ No newline at end of file + WEAPON_STAND_SECONDARY = 25, +} diff --git a/project/src/models/enums/HideoutEventActions.ts b/project/src/models/enums/HideoutEventActions.ts index fc0424e8..4037bdf0 100644 --- a/project/src/models/enums/HideoutEventActions.ts +++ b/project/src/models/enums/HideoutEventActions.ts @@ -1,5 +1,5 @@ export enum HideoutEventActions - { +{ HIDEOUT_UPGRADE = "HideoutUpgrade", HIDEOUT_UPGRADE_COMPLETE = "HideoutUpgradeComplete", HIDEOUT_PUT_ITEMS_IN_AREA_SLOTS = "HideoutPutItemsInAreaSlots", @@ -11,5 +11,5 @@ export enum HideoutEventActions HIDEOUT_TAKE_PRODUCTION = "HideoutTakeProduction", HIDEOUT_RECORD_SHOOTING_RANGE_POINTS = "RecordShootingRangePoints", HIDEOUT_IMPROVE_AREA = "HideoutImproveArea", - HIDEOUT_CANCEL_PRODUCTION_COMMAND = "HideoutCancelProductionCommand" -} \ No newline at end of file + HIDEOUT_CANCEL_PRODUCTION_COMMAND = "HideoutCancelProductionCommand", +} diff --git a/project/src/models/enums/ItemAddedResult.ts b/project/src/models/enums/ItemAddedResult.ts index 2dca874a..72ad247d 100644 --- a/project/src/models/enums/ItemAddedResult.ts +++ b/project/src/models/enums/ItemAddedResult.ts @@ -1,5 +1,5 @@ export enum ItemAddedResult - { +{ SUCCESS = 1, - NO_SPACE = 2 -} \ No newline at end of file + NO_SPACE = 2, +} diff --git a/project/src/models/enums/ItemEventActions.ts b/project/src/models/enums/ItemEventActions.ts index 83e1f45b..6f2f0d60 100644 --- a/project/src/models/enums/ItemEventActions.ts +++ b/project/src/models/enums/ItemEventActions.ts @@ -1,5 +1,5 @@ export enum ItemEventActions - { +{ MOVE = "Move", REMOVE = "Remove", SPLIT = "Split", @@ -22,5 +22,5 @@ export enum ItemEventActions REMOVE_WEAPON_BUILD = "RemoveWeaponBuild", REMOVE_BUILD = "RemoveBuild", SAVE_EQUIPMENT_BUILD = "SaveEquipmentBuild", - REMOVE_EQUIPMENT_BUILD = "RemoveEquipmentBuild" -} \ No newline at end of file + REMOVE_EQUIPMENT_BUILD = "RemoveEquipmentBuild", +} diff --git a/project/src/models/enums/MemberCategory.ts b/project/src/models/enums/MemberCategory.ts index 267363f8..fc97de1f 100644 --- a/project/src/models/enums/MemberCategory.ts +++ b/project/src/models/enums/MemberCategory.ts @@ -1,6 +1,5 @@ - export enum MemberCategory // player type - { +{ DEFAULT = 0, DEVELOPER = 1, UNIQUE_ID = 2, @@ -11,5 +10,5 @@ export enum MemberCategory // player type CHAT_MODERATOR_WITH_PERMANENT_BAN = 64, UNIT_TEST = 128, SHERPA = 256, - EMISSARY = 512 + EMISSARY = 512, } diff --git a/project/src/models/enums/MessageType.ts b/project/src/models/enums/MessageType.ts index f61b9d21..55d08945 100644 --- a/project/src/models/enums/MessageType.ts +++ b/project/src/models/enums/MessageType.ts @@ -1,6 +1,5 @@ - export enum MessageType - { +{ // if this variables are supposed to be strings for the type // then the equals value should be the name that should be // required by the client instead of an int @@ -18,5 +17,5 @@ export enum MessageType QUEST_FAIL = 11, QUEST_SUCCESS = 12, MESSAGE_WITH_ITEMS = 13, - INITIAL_SUPPORT = 14 -} \ No newline at end of file + INITIAL_SUPPORT = 14, +} diff --git a/project/src/models/enums/Money.ts b/project/src/models/enums/Money.ts index 72d61744..9fde164c 100644 --- a/project/src/models/enums/Money.ts +++ b/project/src/models/enums/Money.ts @@ -1,6 +1,6 @@ export enum Money - { +{ ROUBLES = "5449016a4bdc2d6f028b456f", EUROS = "569668774bdc2da2298b4568", - DOLLARS = "5696686a4bdc2da3298b456a" -} \ No newline at end of file + DOLLARS = "5696686a4bdc2da3298b456a", +} diff --git a/project/src/models/enums/PlayerRaidEndState.ts b/project/src/models/enums/PlayerRaidEndState.ts index f06f2090..bb170ca2 100644 --- a/project/src/models/enums/PlayerRaidEndState.ts +++ b/project/src/models/enums/PlayerRaidEndState.ts @@ -1,8 +1,8 @@ export enum PlayerRaidEndState - { +{ SURVIVED = "survived", LEFT = "left", RUNNER = "runner", MISSING_IN_ACTION = "missinginaction", - KILLED = "killed" -} \ No newline at end of file + KILLED = "killed", +} diff --git a/project/src/models/enums/QuestRewardType.ts b/project/src/models/enums/QuestRewardType.ts index 72cba3bc..b4e74188 100644 --- a/project/src/models/enums/QuestRewardType.ts +++ b/project/src/models/enums/QuestRewardType.ts @@ -1,5 +1,5 @@ export enum QuestRewardType - { +{ SKILL = "Skill", EXPERIENCE = "Experience", TRADER_STANDING = "TraderStanding", @@ -9,5 +9,5 @@ export enum QuestRewardType PRODUCTIONS_SCHEME = "ProductionScheme", TRADER_STANDING_RESET = "TraderStandingReset", TRADER_STANDING_RESTORE = "TraderStandingRestore", - STASH_ROWS = "StashRows" -} \ No newline at end of file + STASH_ROWS = "StashRows", +} diff --git a/project/src/models/enums/QuestStatus.ts b/project/src/models/enums/QuestStatus.ts index 0545c28b..bb837224 100644 --- a/project/src/models/enums/QuestStatus.ts +++ b/project/src/models/enums/QuestStatus.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/naming-convention */ export enum QuestStatus - { +{ Locked = 0, AvailableForStart = 1, Started = 2, @@ -10,5 +10,5 @@ export enum QuestStatus FailRestartable = 6, MarkedAsFailed = 7, Expired = 8, - AvailableAfter = 9 -} \ No newline at end of file + AvailableAfter = 9, +} diff --git a/project/src/models/enums/QuestTypeEnum.ts b/project/src/models/enums/QuestTypeEnum.ts index 38b0fcdd..c26eae7a 100644 --- a/project/src/models/enums/QuestTypeEnum.ts +++ b/project/src/models/enums/QuestTypeEnum.ts @@ -1,6 +1,5 @@ - -export enum QuestTypeEnum - { +export enum QuestTypeEnum +{ PICKUP = "PickUp", ELIMINATION = "Elimination", DISCOVER = "Discover", @@ -13,5 +12,5 @@ export enum QuestTypeEnum MERCHANT = "Merchant", SKILL = "Skill", MULTI = "Multi", - WEAPON_ASSEMBLY = "WeaponAssembly" + WEAPON_ASSEMBLY = "WeaponAssembly", } diff --git a/project/src/models/enums/RagfairSort.ts b/project/src/models/enums/RagfairSort.ts index 35b4482a..49c768f6 100644 --- a/project/src/models/enums/RagfairSort.ts +++ b/project/src/models/enums/RagfairSort.ts @@ -1,8 +1,8 @@ export enum RagfairSort - { +{ ID = 0, RATING = 3, OFFER_TITLE = 4, PRICE = 5, - EXPIRY = 6 -} \ No newline at end of file + EXPIRY = 6, +} diff --git a/project/src/models/enums/RaidMode.ts b/project/src/models/enums/RaidMode.ts index a0c96ef0..2d9ac5aa 100644 --- a/project/src/models/enums/RaidMode.ts +++ b/project/src/models/enums/RaidMode.ts @@ -1,6 +1,6 @@ export enum RaidMode - { +{ ONLINE = "Online", LOCAL = "Local", - COOP = "Coop" -} \ No newline at end of file + COOP = "Coop", +} diff --git a/project/src/models/enums/SeasonalEventType.ts b/project/src/models/enums/SeasonalEventType.ts index 158b4df8..ebc93a94 100644 --- a/project/src/models/enums/SeasonalEventType.ts +++ b/project/src/models/enums/SeasonalEventType.ts @@ -1,8 +1,8 @@ export enum SeasonalEventType - { +{ NONE = "None", CHRISTMAS = "Christmas", HALLOWEEN = "Halloween", NEW_YEARS = "NewYears", - PROMO = "Promo" -} \ No newline at end of file + PROMO = "Promo", +} diff --git a/project/src/models/enums/SkillTypes.ts b/project/src/models/enums/SkillTypes.ts index 6ff377ba..ea94c754 100644 --- a/project/src/models/enums/SkillTypes.ts +++ b/project/src/models/enums/SkillTypes.ts @@ -1,5 +1,5 @@ export enum SkillTypes - { +{ BOT_RELOAD = "BotReload", BOT_SOUND = "BotSound", HIDEOUT_MANAGEMENT = "HideoutManagement", @@ -53,5 +53,5 @@ export enum SkillTypes USEC_DEEP_WEAPON_MOD = "UsecDeepweaponmodding_Settings", USEC_LONG_RANGE_OPTICS = "UsecLongrangeoptics_Settings", USEC_NEGOTIATIONS = "UsecNegotiations", - USEC_TACTICS = "UsecTactics" -} \ No newline at end of file + USEC_TACTICS = "UsecTactics", +} diff --git a/project/src/models/enums/Traders.ts b/project/src/models/enums/Traders.ts index 172fcfaa..2a668cfd 100644 --- a/project/src/models/enums/Traders.ts +++ b/project/src/models/enums/Traders.ts @@ -1,6 +1,6 @@ export enum Traders - { - PRAPOR = "54cb50c76803fa8b248b4571", +{ + PRAPOR = "54cb50c76803fa8b248b4571", THERAPIST = "54cb57776803fa99248b456e", FENCE = "579dc571d53a0658a154fbec", SKIER = "58330581ace78e27b8b10cee", @@ -8,5 +8,5 @@ export enum Traders MECHANIC = "5a7c2eca46aef81a7ca2145d", RAGMAN = "5ac3b934156ae10c4430e83c", JAEGER = "5c0647fdd443bc2504c2d371", - LIGHTHOUSEKEEPER = "638f541a29ffd1183d187f57" -} \ No newline at end of file + LIGHTHOUSEKEEPER = "638f541a29ffd1183d187f57", +} diff --git a/project/src/models/enums/WeaponSkillTypes.ts b/project/src/models/enums/WeaponSkillTypes.ts index 6458865a..e2b5fe06 100644 --- a/project/src/models/enums/WeaponSkillTypes.ts +++ b/project/src/models/enums/WeaponSkillTypes.ts @@ -1,5 +1,5 @@ export enum WeaponSkillTypes - { +{ PISTOL = "Pistol", REVOLVER = "Revolver", SMG = "SMG", @@ -11,5 +11,5 @@ export enum WeaponSkillTypes DMR = "DMR", LAUNCHER = "Launcher", ATTACHED_LAUNCHER = "AttachedLauncher", - MELEE = "Melee" -} \ No newline at end of file + MELEE = "Melee", +} diff --git a/project/src/models/enums/WeaponTypes.ts b/project/src/models/enums/WeaponTypes.ts index 660ee688..873c26e9 100644 --- a/project/src/models/enums/WeaponTypes.ts +++ b/project/src/models/enums/WeaponTypes.ts @@ -1,31 +1,31 @@ export enum Weapons127x55 - { - ASH_12 = "5cadfbf7ae92152ac412eeef" +{ + ASH_12 = "5cadfbf7ae92152ac412eeef", } export enum Weapons86x70 - { +{ MK_18 = "5fc22d7c187fea44d52eda44", - AXMC = "627e14b21713922ded6f2c15" + AXMC = "627e14b21713922ded6f2c15", } export enum Weapons9x39 - { +{ AS_VAL = "57c44b372459772d2b39b8ce", - VSS_VINTOREZ = "57838ad32459774a17445cd2" + VSS_VINTOREZ = "57838ad32459774a17445cd2", } export enum Weapons762x54R - { +{ SVDS = "5c46fbd72e2216398b5a8c9c", MP_18 = "61f7c9e189e6fb1a5e3ea78d", MOSIN_INFANTRY = "5bfd297f0db834001a669119", MOSIN_SNIPER = "5ae08f0a5acfc408fb1398a1", - SV_98 = "55801eed4bdc2d89578b4588" + SV_98 = "55801eed4bdc2d89578b4588", } export enum Weapons762x51 - { +{ VPO_101 = "5c501a4d2e221602b412b540", DT_MDR_762 = "5dcbd56fdbd3d91b3e5468d5", SA_58 = "5b0bbe4e5acfc40dc528a72d", @@ -38,17 +38,17 @@ export enum Weapons762x51 SR_25 = "5df8ce05b11454561e39243b", DVL_10 = "588892092459774ac91d4b11", M700 = "5bfea6e90db834001b7347f3", - T5000M = "5df24cf80dee1b22f862e9bc" + T5000M = "5df24cf80dee1b22f862e9bc", } export enum Weapons366TKM - { +{ VPO_209 = "59e6687d86f77411d949b251", - VPO_215 = "5de652c31b7e3716273428be" + VPO_215 = "5de652c31b7e3716273428be", } export enum Weapons762x39 - { +{ OP_SKS = "587e02ff24597743df3deaeb", SKS = "574d967124597745970e7c94", AK_103 = "5ac66d2e5acfc43b321d4b53", @@ -59,16 +59,16 @@ export enum Weapons762x39 AKMSN = "5abcbc27d8ce8700182eceeb", MK47_MUTANT = "606587252535c57a13424cfd", RD_704 = "628a60ae6b1d481ff772e9c8", - VPO_136 = "59e6152586f77473dc057aa1" + VPO_136 = "59e6152586f77473dc057aa1", } export enum Weapons762x35 - { - MCX = "5fbcc1d9016cce60e8341ab3" +{ + MCX = "5fbcc1d9016cce60e8341ab3", } export enum Weapons556x45 - { +{ ADAR_2_15 = "5c07c60e0db834002330051f", AK_101 = "5ac66cb05acfc40198510a10", AK_102 = "5ac66d015acfc400180ae6e4", @@ -78,11 +78,11 @@ export enum Weapons556x45 M4A1 = "5447a9cd4bdc2dbd208b4567", SCARL_BLACK = "6184055050224f204c1da540", SCARL_FDE = "618428466ef05c2ce828f218", - TX15_DML = "5d43021ca4b9362eab4b5e25" + TX15_DML = "5d43021ca4b9362eab4b5e25", } export enum Weapons545x39 - { +{ AK_105 = "5ac66d9b5acfc4001633997a", AK_74 = "5bf3e03b0db834001d2c4a9c", AK_74M = "5ac4cd105acfc40016339859", @@ -94,43 +94,43 @@ export enum Weapons545x39 AKS_74UN = "583990e32459771419544dd2", SAG_AK = "628b5638ad252a16da6dd245", SAG_AK_SHORT = "628b9c37a733087d0d7fe84b", - RPK_16 = "5beed0f50db834001c062b12" + RPK_16 = "5beed0f50db834001c062b12", } export enum Weapons57x28FN - { +{ FN_57_BLACK = "5d3eb3b0a4b93615055e84d2", FN_57_FDE = "5d67abc1a4b93614ec50137f", - FN_P90 = "5cc82d76e24e8d00134b4b83" + FN_P90 = "5cc82d76e24e8d00134b4b83", } export enum Weapons46x30HK - { +{ MP7A1 = "5ba26383d4351e00334c93d9", - MP7A2 = "5bd70322209c4d00d7167b8f" + MP7A2 = "5bd70322209c4d00d7167b8f", } export enum Weapons1143x23 - { +{ M1911A1 = "5e81c3cbac2bb513793cdc75", M45A1 = "5f36a0e5fbf956000b716b65", USP45 = "6193a720f8ee7e52e42109ed", UMP45 = "5fc3e272f8b6a877a729eac5", - VECTOR45 = "5fb64bc92b1b027b1f50bcf2" + VECTOR45 = "5fb64bc92b1b027b1f50bcf2", } export enum Weapons9x33R - { - CR_50DS = "61a4c8884f95bc3b2c5dc96f" +{ + CR_50DS = "61a4c8884f95bc3b2c5dc96f", } export enum Weapons9x21 - { - SR_1MP = "59f98b4986f7746f546d2cef" +{ + SR_1MP = "59f98b4986f7746f546d2cef", } export enum Weapons9x19 - { +{ GLOCK_17 = "5a7ae0c351dfba0017554310", GLOCK_18C = "5b1fa9b25acfc40018633c01", M9A3 = "5cadc190ae921500103bb3b6", @@ -146,30 +146,30 @@ export enum Weapons9x19 PP_19_01 = "59984ab886f7743e98271174", SAIGA_9 = "59f9cabd86f7743a10721f46", STM_9 = "60339954d62c9b14ed777c06", - VECTOR_9MM = "5fc3f2d5900b1d5091531e57" + VECTOR_9MM = "5fc3f2d5900b1d5091531e57", } export enum Weapons9x18 - { +{ APB = "5abccb7dd8ce87001773e277", - APS = "5a17f98cfcdbcb0980087290", + APS = "5a17f98cfcdbcb0980087290", PB_SILENCED = "56e0598dd2720bb5668b45a6", PM = "5448bd6b4bdc2dfc2f8b4569", PM_T = "579204f224597773d619e051", PP9_KLIN = "57f4c844245977379d5c14d1", PP91_KEDR = "57d14d2524597714373db789", - PP91_KEDRB = "57f3c6bd24597738e730fa2f" + PP91_KEDRB = "57f3c6bd24597738e730fa2f", } export enum Weapons762x25 - { +{ TT = "571a12c42459771f627b58a0", TT_GOLD = "5b3b713c5acfc4330140bd8d", - PPSH_41 = "5ea03f7400685063ec28bfa8" + PPSH_41 = "5ea03f7400685063ec28bfa8", } export enum Weapons12Gauge - { +{ M3_SUPER90 = "6259b864ebedf17603599e88", M590A1 = "5e870397991fd70db46995c8", M870 = "5a7828548dc32e5a9c28b516", @@ -178,15 +178,15 @@ export enum Weapons12Gauge MP_155 = "606dae0ab0e443224b421bb7", MP_43_1C = "5580223e4bdc2d1c128b457f", MTS_255_12 = "60db29ce99594040e04c4a27", - SAIGA_12GA = "576165642459773c7a400233" + SAIGA_12GA = "576165642459773c7a400233", } export enum Weapons20Gauge - { - TOZ_106 = "5a38e6bac4a2826c6e06d79b" +{ + TOZ_106 = "5a38e6bac4a2826c6e06d79b", } export enum Weapons23x75 - { - KS_23M = "5e848cc2988a8701445df1e8" +{ + KS_23M = "5e848cc2988a8701445df1e8", } diff --git a/project/src/models/enums/WeatherType.ts b/project/src/models/enums/WeatherType.ts index 0ca55ebe..e5627a8f 100644 --- a/project/src/models/enums/WeatherType.ts +++ b/project/src/models/enums/WeatherType.ts @@ -1,5 +1,5 @@ export enum WeatherType - { +{ CLEAR_DAY = 0, CLEAR_WIND = 1, CLEAR_NIGHT = 2, @@ -16,5 +16,5 @@ export enum WeatherType CLOUD_WIND_RAIN = 13, FULL_CLOUD = 14, THUNDER_CLOUD = 15, - NONE = 16 -} \ No newline at end of file + NONE = 16, +} diff --git a/project/src/models/enums/WildSpawnTypeNumber.ts b/project/src/models/enums/WildSpawnTypeNumber.ts index ae415b82..7be37544 100644 --- a/project/src/models/enums/WildSpawnTypeNumber.ts +++ b/project/src/models/enums/WildSpawnTypeNumber.ts @@ -1,5 +1,5 @@ export enum WildSpawnTypeNumber - { +{ MARKSMAN = 0, ASSAULT = 1, BOSSTEST = 2, @@ -41,5 +41,5 @@ export enum WildSpawnTypeNumber SECTACTPRIESTEVENT = 39, RAVANGEZRYACHIYEVENT = 40, SPTUSEC = 41, - SPTBEAR = 42 -} \ No newline at end of file + SPTBEAR = 42, +} diff --git a/project/src/models/enums/WindDirection.ts b/project/src/models/enums/WindDirection.ts index 9480a0a0..1e03f9b8 100644 --- a/project/src/models/enums/WindDirection.ts +++ b/project/src/models/enums/WindDirection.ts @@ -1,5 +1,5 @@ export enum WindDirection - { +{ EAST = 1, NORTH = 2, WEST = 3, @@ -7,5 +7,5 @@ export enum WindDirection SE = 5, SW = 6, NW = 7, - NE = 8 -} \ No newline at end of file + NE = 8, +} diff --git a/project/src/models/external/HttpFramework.ts b/project/src/models/external/HttpFramework.ts index 42a4c3d1..36b69531 100644 --- a/project/src/models/external/HttpFramework.ts +++ b/project/src/models/external/HttpFramework.ts @@ -13,7 +13,7 @@ export type HandleFn = (_: string, req: IncomingMessage, resp: ServerResponse) = */ export const Listen = (basePath: string) => { - return (Base: T): T => + return (Base: T): T => { // Used for the base class to be able to use DI injectable()(Base); @@ -29,16 +29,25 @@ export const Listen = (basePath: string) => // Retrieve all handlers const handlersArray = Base.prototype["handlers"]; - if (!handlersArray) return; + if (!handlersArray) + { + return; + } // Add each flagged handler to the Record - for (const { handlerName, path, httpMethod } of handlersArray) + for (const {handlerName, path, httpMethod} of handlersArray) { - if (!this.handlers[httpMethod]) this.handlers[httpMethod] = {}; + if (!this.handlers[httpMethod]) + { + this.handlers[httpMethod] = {}; + } if (this[handlerName] !== undefined && typeof this[handlerName] === "function") { - if (!path || path === "") this.handlers[httpMethod][`/${basePath}`] = this[handlerName]; + if (!path || path === "") + { + this.handlers[httpMethod][`/${basePath}`] = this[handlerName]; + } this.handlers[httpMethod][`/${basePath}/${path}`] = this[handlerName]; } } @@ -53,14 +62,17 @@ export const Listen = (basePath: string) => { const routesHandles = this.handlers[req.method]; - return Object.keys(this.handlers).some(meth => meth === req.method) && - Object.keys(routesHandles).some(route => (new RegExp(route)).test(req.url)); + return Object.keys(this.handlers).some((meth) => meth === req.method) && + Object.keys(routesHandles).some((route) => (new RegExp(route)).test(req.url)); }; // The actual handle method dispatches the request to the registered handlers handle = (sessionID: string, req: IncomingMessage, resp: ServerResponse): void => { - if (Object.keys(this.handlers).length === 0) return; + if (Object.keys(this.handlers).length === 0) + { + return; + } // Get all routes for the HTTP method and sort them so that // The more precise is selected (eg. "/test/A" is selected over "/test") @@ -70,8 +82,11 @@ export const Listen = (basePath: string) => routes.sort((routeA, routeB) => routeB.length - routeA.length); // Filter to select valid routes but only use the first element since it's the most precise - const validRoutes = routes.filter(handlerKey => (new RegExp(handlerKey)).test(route)); - if (validRoutes.length > 0) routesHandles[validRoutes[0]](sessionID, req, resp); + const validRoutes = routes.filter((handlerKey) => (new RegExp(handlerKey)).test(route)); + if (validRoutes.length > 0) + { + routesHandles[validRoutes[0]](sessionID, req, resp); + } }; }; }; @@ -90,13 +105,16 @@ const createHttpDecorator = (httpMethod: HttpMethods) => return (target: any, propertyKey: string) => { // If the handlers array has not been initialized yet - if (!target["handlers"]) target["handlers"] = []; + if (!target["handlers"]) + { + target["handlers"] = []; + } // Flag the method as a HTTP handler target["handlers"].push({ handlerName: propertyKey, path, - httpMethod + httpMethod, }); }; }; @@ -130,4 +148,4 @@ export const Post = createHttpDecorator(HttpMethods.POST); /** * HTTP PUT decorator */ -export const Put = createHttpDecorator(HttpMethods.PUT); \ No newline at end of file +export const Put = createHttpDecorator(HttpMethods.PUT); diff --git a/project/src/models/external/IPostAkiLoadMod.ts b/project/src/models/external/IPostAkiLoadMod.ts index 4748a1da..d88e8e3d 100644 --- a/project/src/models/external/IPostAkiLoadMod.ts +++ b/project/src/models/external/IPostAkiLoadMod.ts @@ -3,4 +3,4 @@ import type { DependencyContainer } from "tsyringe"; export interface IPostAkiLoadMod { postAkiLoad(container: DependencyContainer): void; -} \ No newline at end of file +} diff --git a/project/src/models/external/IPostAkiLoadModAsync.ts b/project/src/models/external/IPostAkiLoadModAsync.ts index 62c16073..3bfb37e7 100644 --- a/project/src/models/external/IPostAkiLoadModAsync.ts +++ b/project/src/models/external/IPostAkiLoadModAsync.ts @@ -3,4 +3,4 @@ import type { DependencyContainer } from "tsyringe"; export interface IPostAkiLoadModAsync { postAkiLoadAsync(container: DependencyContainer): Promise; -} \ No newline at end of file +} diff --git a/project/src/models/external/IPostDBLoadMod.ts b/project/src/models/external/IPostDBLoadMod.ts index 3d5231ef..d5af8f9a 100644 --- a/project/src/models/external/IPostDBLoadMod.ts +++ b/project/src/models/external/IPostDBLoadMod.ts @@ -3,4 +3,4 @@ import type { DependencyContainer } from "tsyringe"; export interface IPostDBLoadMod { postDBLoad(container: DependencyContainer): void; -} \ No newline at end of file +} diff --git a/project/src/models/external/IPostDBLoadModAsync.ts b/project/src/models/external/IPostDBLoadModAsync.ts index ab336308..14297c3e 100644 --- a/project/src/models/external/IPostDBLoadModAsync.ts +++ b/project/src/models/external/IPostDBLoadModAsync.ts @@ -3,4 +3,4 @@ import type { DependencyContainer } from "tsyringe"; export interface IPostDBLoadModAsync { postDBLoadAsync(container: DependencyContainer): Promise; -} \ No newline at end of file +} diff --git a/project/src/models/external/IPreAkiLoadMod.ts b/project/src/models/external/IPreAkiLoadMod.ts index af37de75..9d5532a1 100644 --- a/project/src/models/external/IPreAkiLoadMod.ts +++ b/project/src/models/external/IPreAkiLoadMod.ts @@ -3,4 +3,4 @@ import type { DependencyContainer } from "tsyringe"; export interface IPreAkiLoadMod { preAkiLoad(container: DependencyContainer): void; -} \ No newline at end of file +} diff --git a/project/src/models/external/IPreAkiLoadModAsync.ts b/project/src/models/external/IPreAkiLoadModAsync.ts index f3aa6e5b..2b15db36 100644 --- a/project/src/models/external/IPreAkiLoadModAsync.ts +++ b/project/src/models/external/IPreAkiLoadModAsync.ts @@ -3,4 +3,4 @@ import type { DependencyContainer } from "tsyringe"; export interface IPreAkiLoadModAsync { preAkiLoadAsync(container: DependencyContainer): Promise; -} \ No newline at end of file +} diff --git a/project/src/models/spt/bindings/Route.ts b/project/src/models/spt/bindings/Route.ts index 14224b74..be18924e 100644 --- a/project/src/models/spt/bindings/Route.ts +++ b/project/src/models/spt/bindings/Route.ts @@ -1,4 +1,4 @@ export interface IRoute { - aki: any -} \ No newline at end of file + aki: any; +} diff --git a/project/src/models/spt/bots/BotGenerationDetails.ts b/project/src/models/spt/bots/BotGenerationDetails.ts index 970ba422..90596346 100644 --- a/project/src/models/spt/bots/BotGenerationDetails.ts +++ b/project/src/models/spt/bots/BotGenerationDetails.ts @@ -1,20 +1,20 @@ export interface BotGenerationDetails { /** Should the bot be generated as a PMC */ - isPmc: boolean + isPmc: boolean; /** assault/pmcBot etc */ - role: string + role: string; /** Side of bot */ - side: string + side: string; /** Active players current level */ - playerLevel: number + playerLevel: number; /** Delta of highest level of bot */ - botRelativeLevelDeltaMax: number + botRelativeLevelDeltaMax: number; /** How many to create and store */ - botCountToGenerate: number + botCountToGenerate: number; /** Desired difficulty of the bot */ - botDifficulty: string + botDifficulty: string; /** Will the generated bot be a player scav */ - isPlayerScav: boolean - eventRole?: string -} \ No newline at end of file + isPlayerScav: boolean; + eventRole?: string; +} diff --git a/project/src/models/spt/bots/GenerateWeaponResult.ts b/project/src/models/spt/bots/GenerateWeaponResult.ts index a53f26e4..c720383e 100644 --- a/project/src/models/spt/bots/GenerateWeaponResult.ts +++ b/project/src/models/spt/bots/GenerateWeaponResult.ts @@ -9,4 +9,4 @@ export class GenerateWeaponResult chosenUbglAmmoTpl: string; weaponMods: Mods; weaponTemplate: ITemplateItem; -} \ No newline at end of file +} diff --git a/project/src/models/spt/bots/IBotLootCache.ts b/project/src/models/spt/bots/IBotLootCache.ts index 9460a094..83735fca 100644 --- a/project/src/models/spt/bots/IBotLootCache.ts +++ b/project/src/models/spt/bots/IBotLootCache.ts @@ -2,20 +2,20 @@ import { ITemplateItem } from "@spt-aki/models/eft/common/tables/ITemplateItem"; export interface IBotLootCache { - backpackLoot: ITemplateItem[] - pocketLoot: ITemplateItem[] - vestLoot: ITemplateItem[] - combinedPoolLoot: ITemplateItem[] + backpackLoot: ITemplateItem[]; + pocketLoot: ITemplateItem[]; + vestLoot: ITemplateItem[]; + combinedPoolLoot: ITemplateItem[]; - specialItems: ITemplateItem[] - healingItems: ITemplateItem[] - drugItems: ITemplateItem[] - stimItems: ITemplateItem[] - grenadeItems: ITemplateItem[] + specialItems: ITemplateItem[]; + healingItems: ITemplateItem[]; + drugItems: ITemplateItem[]; + stimItems: ITemplateItem[]; + grenadeItems: ITemplateItem[]; } export enum LootCacheType - { +{ SPECIAL = "Special", BACKPACK = "Backpack", POCKET = "Pocket", @@ -24,6 +24,5 @@ export enum LootCacheType HEALING_ITEMS = "HealingItems", DRUG_ITEMS = "DrugItems", STIM_ITEMS = "StimItems", - GRENADE_ITEMS = "GrenadeItems" - -} \ No newline at end of file + GRENADE_ITEMS = "GrenadeItems", +} diff --git a/project/src/models/spt/callbacks/IBundleCallbacks.ts b/project/src/models/spt/callbacks/IBundleCallbacks.ts index a99cadfa..1f0354df 100644 --- a/project/src/models/spt/callbacks/IBundleCallbacks.ts +++ b/project/src/models/spt/callbacks/IBundleCallbacks.ts @@ -1,6 +1,6 @@ export interface IBundleCallbacks { - sendBundle(sessionID: string, req: any, resp: any, body: any): any - getBundles(url: string, info: any, sessionID: string): string - getBundle(url: string, info: any, sessionID: string): string + sendBundle(sessionID: string, req: any, resp: any, body: any): any; + getBundles(url: string, info: any, sessionID: string): string; + getBundle(url: string, info: any, sessionID: string): string; } diff --git a/project/src/models/spt/callbacks/ICustomizationCallbacks.ts b/project/src/models/spt/callbacks/ICustomizationCallbacks.ts index bbb0303e..0398f5af 100644 --- a/project/src/models/spt/callbacks/ICustomizationCallbacks.ts +++ b/project/src/models/spt/callbacks/ICustomizationCallbacks.ts @@ -11,4 +11,4 @@ export interface ICustomizationCallbacks getTraderSuits(url: string, info: any, sessionID: string): IGetBodyResponseData; wearClothing(pmcData: IPmcData, body: IWearClothingRequestData, sessionID: string): IItemEventRouterResponse; buyClothing(pmcData: IPmcData, body: IBuyClothingRequestData, sessionID: string): IItemEventRouterResponse; -} \ No newline at end of file +} diff --git a/project/src/models/spt/callbacks/IDataCallbacks.ts b/project/src/models/spt/callbacks/IDataCallbacks.ts index a4d08185..6f970b76 100644 --- a/project/src/models/spt/callbacks/IDataCallbacks.ts +++ b/project/src/models/spt/callbacks/IDataCallbacks.ts @@ -15,11 +15,27 @@ export interface IDataCallbacks getTemplateHandbook(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; getTemplateSuits(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; getTemplateCharacter(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; - getHideoutSettings(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; + getHideoutSettings( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData; getHideoutAreas(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; - gethideoutProduction(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; - getHideoutScavcase(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; - getLocalesLanguages(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData>; + gethideoutProduction( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData; + getHideoutScavcase( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData; + getLocalesLanguages( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData>; getLocalesMenu(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; getLocalesGlobal(url: string, info: IEmptyRequestData, sessionID: string): string; } diff --git a/project/src/models/spt/callbacks/IDialogueCallbacks.ts b/project/src/models/spt/callbacks/IDialogueCallbacks.ts index 818c5db2..66f83179 100644 --- a/project/src/models/spt/callbacks/IDialogueCallbacks.ts +++ b/project/src/models/spt/callbacks/IDialogueCallbacks.ts @@ -18,16 +18,32 @@ import { DialogueInfo } from "@spt-aki/models/eft/profile/IAkiProfile"; export interface IDialogueCallbacks { - getFriendList(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; + getFriendList( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData; getChatServerList(url: string, info: IGetChatServerListRequestData, sessionID: string): IGetBodyResponseData; - getMailDialogList(url: string, info: IGetMailDialogListRequestData, sessionID: string): IGetBodyResponseData; - getMailDialogView(url: string, info: IGetMailDialogViewRequestData, sessionID: string): IGetBodyResponseData; + getMailDialogList( + url: string, + info: IGetMailDialogListRequestData, + sessionID: string, + ): IGetBodyResponseData; + getMailDialogView( + url: string, + info: IGetMailDialogViewRequestData, + sessionID: string, + ): IGetBodyResponseData; getMailDialogInfo(url: string, info: IGetMailDialogInfoRequestData, sessionID: string): IGetBodyResponseData; removeDialog(url: string, info: IRemoveDialogRequestData, sessionID: string): IGetBodyResponseData; pinDialog(url: string, info: IPinDialogRequestData, sessionID: string): IGetBodyResponseData; unpinDialog(url: string, info: IPinDialogRequestData, sessionID: string): IGetBodyResponseData; setRead(url: string, info: ISetDialogReadRequestData, sessionID: string): IGetBodyResponseData; - getAllAttachments(url: string, info: IGetAllAttachmentsRequestData, sessionID: string): IGetBodyResponseData; + getAllAttachments( + url: string, + info: IGetAllAttachmentsRequestData, + sessionID: string, + ): IGetBodyResponseData; listOutbox(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; listInbox(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; sendFriendRequest(url: string, request: IFriendRequestData, sessionID: string): INullResponseData; diff --git a/project/src/models/spt/callbacks/IGameCallbacks.ts b/project/src/models/spt/callbacks/IGameCallbacks.ts index 15d07c67..bb08f360 100644 --- a/project/src/models/spt/callbacks/IGameCallbacks.ts +++ b/project/src/models/spt/callbacks/IGameCallbacks.ts @@ -10,7 +10,11 @@ export interface IGameCallbacks versionValidate(url: string, info: IVersionValidateRequestData, sessionID: string): INullResponseData; gameStart(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; gameLogout(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; - getGameConfig(url: string, info: IGameEmptyCrcRequestData, sessionID: string): IGetBodyResponseData; + getGameConfig( + url: string, + info: IGameEmptyCrcRequestData, + sessionID: string, + ): IGetBodyResponseData; getServer(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; validateGameVersion(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; gameKeepalive(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; diff --git a/project/src/models/spt/callbacks/IHideoutCallbacks.ts b/project/src/models/spt/callbacks/IHideoutCallbacks.ts index 2ef57ab0..3746d364 100644 --- a/project/src/models/spt/callbacks/IHideoutCallbacks.ts +++ b/project/src/models/spt/callbacks/IHideoutCallbacks.ts @@ -13,13 +13,41 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve export interface IHideoutCallbacks { upgrade(pmcData: IPmcData, body: IHideoutUpgradeRequestData, sessionID: string): IItemEventRouterResponse; - upgradeComplete(pmcData: IPmcData, body: IHideoutUpgradeCompleteRequestData, sessionID: string): IItemEventRouterResponse; - putItemsInAreaSlots(pmcData: IPmcData, body: IHideoutPutItemInRequestData, sessionID: string): IItemEventRouterResponse; - takeItemsFromAreaSlots(pmcData: IPmcData, body: IHideoutTakeItemOutRequestData, sessionID: string): IItemEventRouterResponse; + upgradeComplete( + pmcData: IPmcData, + body: IHideoutUpgradeCompleteRequestData, + sessionID: string, + ): IItemEventRouterResponse; + putItemsInAreaSlots( + pmcData: IPmcData, + body: IHideoutPutItemInRequestData, + sessionID: string, + ): IItemEventRouterResponse; + takeItemsFromAreaSlots( + pmcData: IPmcData, + body: IHideoutTakeItemOutRequestData, + sessionID: string, + ): IItemEventRouterResponse; toggleArea(pmcData: IPmcData, body: IHideoutToggleAreaRequestData, sessionID: string): IItemEventRouterResponse; - singleProductionStart(pmcData: IPmcData, body: IHideoutSingleProductionStartRequestData, sessionID: string): IItemEventRouterResponse; - scavCaseProductionStart(pmcData: IPmcData, body: IHideoutScavCaseStartRequestData, sessionID: string): IItemEventRouterResponse; - continuousProductionStart(pmcData: IPmcData, body: IHideoutContinuousProductionStartRequestData, sessionID: string): IItemEventRouterResponse; - takeProduction(pmcData: IPmcData, body: IHideoutTakeProductionRequestData, sessionID: string): IItemEventRouterResponse; + singleProductionStart( + pmcData: IPmcData, + body: IHideoutSingleProductionStartRequestData, + sessionID: string, + ): IItemEventRouterResponse; + scavCaseProductionStart( + pmcData: IPmcData, + body: IHideoutScavCaseStartRequestData, + sessionID: string, + ): IItemEventRouterResponse; + continuousProductionStart( + pmcData: IPmcData, + body: IHideoutContinuousProductionStartRequestData, + sessionID: string, + ): IItemEventRouterResponse; + takeProduction( + pmcData: IPmcData, + body: IHideoutTakeProductionRequestData, + sessionID: string, + ): IItemEventRouterResponse; update(timeSinceLastRun: number): boolean; -} \ No newline at end of file +} diff --git a/project/src/models/spt/callbacks/IInventoryCallbacks.ts b/project/src/models/spt/callbacks/IInventoryCallbacks.ts index e7aa62be..92640338 100644 --- a/project/src/models/spt/callbacks/IInventoryCallbacks.ts +++ b/project/src/models/spt/callbacks/IInventoryCallbacks.ts @@ -30,9 +30,25 @@ export interface IInventoryCallbacks tagItem(pmcData: IPmcData, body: IInventoryTagRequestData, sessionID: string): IItemEventRouterResponse; bindItem(pmcData: IPmcData, body: IInventoryBindRequestData, sessionID: string): IItemEventRouterResponse; examineItem(pmcData: IPmcData, body: IInventoryExamineRequestData, sessionID: string): IItemEventRouterResponse; - readEncyclopedia(pmcData: IPmcData, body: IInventoryReadEncyclopediaRequestData, sessionID: string): IItemEventRouterResponse; + readEncyclopedia( + pmcData: IPmcData, + body: IInventoryReadEncyclopediaRequestData, + sessionID: string, + ): IItemEventRouterResponse; sortInventory(pmcData: IPmcData, body: IInventorySortRequestData, sessionID: string): IItemEventRouterResponse; - createMapMarker(pmcData: IPmcData, body: IInventoryCreateMarkerRequestData, sessionID: string): IItemEventRouterResponse; - deleteMapMarker(pmcData: IPmcData, body: IInventoryDeleteMarkerRequestData, sessionID: string): IItemEventRouterResponse; - editMapMarker(pmcData: IPmcData, body: IInventoryEditMarkerRequestData, sessionID: string): IItemEventRouterResponse; + createMapMarker( + pmcData: IPmcData, + body: IInventoryCreateMarkerRequestData, + sessionID: string, + ): IItemEventRouterResponse; + deleteMapMarker( + pmcData: IPmcData, + body: IInventoryDeleteMarkerRequestData, + sessionID: string, + ): IItemEventRouterResponse; + editMapMarker( + pmcData: IPmcData, + body: IInventoryEditMarkerRequestData, + sessionID: string, + ): IItemEventRouterResponse; } diff --git a/project/src/models/spt/callbacks/IItemEventCallbacks.ts b/project/src/models/spt/callbacks/IItemEventCallbacks.ts index ccfabaea..5b02f663 100644 --- a/project/src/models/spt/callbacks/IItemEventCallbacks.ts +++ b/project/src/models/spt/callbacks/IItemEventCallbacks.ts @@ -4,5 +4,9 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve export interface IItemEventCallbacks { - handleEvents(url: string, info: IItemEventRouterRequest, sessionID: string): IGetBodyResponseData; + handleEvents( + url: string, + info: IItemEventRouterRequest, + sessionID: string, + ): IGetBodyResponseData; } diff --git a/project/src/models/spt/callbacks/INotifierCallbacks.ts b/project/src/models/spt/callbacks/INotifierCallbacks.ts index 45148f28..1dd6a6c0 100644 --- a/project/src/models/spt/callbacks/INotifierCallbacks.ts +++ b/project/src/models/spt/callbacks/INotifierCallbacks.ts @@ -13,7 +13,11 @@ export interface INotifierCallbacks */ sendNotification(sessionID: string, req: any, resp: any, data: any): void; getNotifier(url: string, info: any, sessionID: string): IGetBodyResponseData; - createNotifierChannel(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; + createNotifierChannel( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData; selectProfile(url: string, info: ISelectProfileRequestData, sessionID: string): IGetBodyResponseData; notify(url: string, info: any, sessionID: string): string; -} \ No newline at end of file +} diff --git a/project/src/models/spt/callbacks/IPresetBuildCallbacks.ts b/project/src/models/spt/callbacks/IPresetBuildCallbacks.ts index 33bc01b6..fc1cdc48 100644 --- a/project/src/models/spt/callbacks/IPresetBuildCallbacks.ts +++ b/project/src/models/spt/callbacks/IPresetBuildCallbacks.ts @@ -7,8 +7,24 @@ import { IWeaponBuild } from "@spt-aki/models/eft/profile/IAkiProfile"; export interface IPresetBuildCallbacks { getHandbookUserlist(url: string, info: any, sessionID: string): IGetBodyResponseData; - saveWeaponBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string): IItemEventRouterResponse; - removeWeaponBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string): IItemEventRouterResponse; - saveEquipmentBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string): IItemEventRouterResponse; - removeEquipmentBuild(pmcData: IPmcData, body: IPresetBuildActionRequestData, sessionID: string): IItemEventRouterResponse; + saveWeaponBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + ): IItemEventRouterResponse; + removeWeaponBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + ): IItemEventRouterResponse; + saveEquipmentBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + ): IItemEventRouterResponse; + removeEquipmentBuild( + pmcData: IPmcData, + body: IPresetBuildActionRequestData, + sessionID: string, + ): IItemEventRouterResponse; } diff --git a/project/src/models/spt/callbacks/IProfileCallbacks.ts b/project/src/models/spt/callbacks/IProfileCallbacks.ts index ff687972..41ffecbe 100644 --- a/project/src/models/spt/callbacks/IProfileCallbacks.ts +++ b/project/src/models/spt/callbacks/IProfileCallbacks.ts @@ -19,5 +19,9 @@ export interface IProfileCallbacks validateNickname(url: string, info: IValidateNicknameRequestData, sessionID: string): IGetBodyResponseData; getReservedNickname(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; getProfileStatus(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; - searchFriend(url: string, info: ISearchFriendRequestData, sessionID: string): IGetBodyResponseData; + searchFriend( + url: string, + info: ISearchFriendRequestData, + sessionID: string, + ): IGetBodyResponseData; } diff --git a/project/src/models/spt/callbacks/IQuestCallbacks.ts b/project/src/models/spt/callbacks/IQuestCallbacks.ts index e3a7c782..f68105f6 100644 --- a/project/src/models/spt/callbacks/IQuestCallbacks.ts +++ b/project/src/models/spt/callbacks/IQuestCallbacks.ts @@ -12,10 +12,18 @@ import { IRepeatableQuestChangeRequest } from "@spt-aki/models/eft/quests/IRepea export interface IQuestCallbacks { - changeRepeatableQuest(pmcData: IPmcData, body: IRepeatableQuestChangeRequest, sessionID: string): IItemEventRouterResponse; + changeRepeatableQuest( + pmcData: IPmcData, + body: IRepeatableQuestChangeRequest, + sessionID: string, + ): IItemEventRouterResponse; acceptQuest(pmcData: IPmcData, body: IAcceptQuestRequestData, sessionID: string): IItemEventRouterResponse; completeQuest(pmcData: IPmcData, body: ICompleteQuestRequestData, sessionID: string): IItemEventRouterResponse; handoverQuest(pmcData: IPmcData, body: IHandoverQuestRequestData, sessionID: string): IItemEventRouterResponse; listQuests(url: string, info: IListQuestsRequestData, sessionID: string): IGetBodyResponseData; - activityPeriods(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; + activityPeriods( + url: string, + info: IEmptyRequestData, + sessionID: string, + ): IGetBodyResponseData; } diff --git a/project/src/models/spt/callbacks/IRagfairCallbacks.ts b/project/src/models/spt/callbacks/IRagfairCallbacks.ts index 4b0a8269..5550e6b5 100644 --- a/project/src/models/spt/callbacks/IRagfairCallbacks.ts +++ b/project/src/models/spt/callbacks/IRagfairCallbacks.ts @@ -9,11 +9,15 @@ import { IGetMarketPriceRequestData } from "@spt-aki/models/eft/ragfair/IGetMark import { IRemoveOfferRequestData } from "@spt-aki/models/eft/ragfair/IRemoveOfferRequestData"; import { ISearchRequestData } from "@spt-aki/models/eft/ragfair/ISearchRequestData"; -export interface IRagfairCallbacks +export interface IRagfairCallbacks { load(): void; search(url: string, info: ISearchRequestData, sessionID: string): IGetBodyResponseData; - getMarketPrice(url: string, info: IGetMarketPriceRequestData, sessionID: string): IGetBodyResponseData; + getMarketPrice( + url: string, + info: IGetMarketPriceRequestData, + sessionID: string, + ): IGetBodyResponseData; getItemPrices(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; addOffer(pmcData: IPmcData, info: IAddOfferRequestData, sessionID: string): IItemEventRouterResponse; removeOffer(pmcData: IPmcData, info: IRemoveOfferRequestData, sessionID: string): IItemEventRouterResponse; diff --git a/project/src/models/spt/callbacks/ITradeCallbacks.ts b/project/src/models/spt/callbacks/ITradeCallbacks.ts index 95882807..d4ef386c 100644 --- a/project/src/models/spt/callbacks/ITradeCallbacks.ts +++ b/project/src/models/spt/callbacks/ITradeCallbacks.ts @@ -6,5 +6,9 @@ import { IProcessRagfairTradeRequestData } from "@spt-aki/models/eft/trade/IProc export interface ITradeCallbacks { processTrade(pmcData: IPmcData, body: IProcessBaseTradeRequestData, sessionID: string): IItemEventRouterResponse; - processRagfairTrade(pmcData: IPmcData, body: IProcessRagfairTradeRequestData, sessionID: string): IItemEventRouterResponse; + processRagfairTrade( + pmcData: IPmcData, + body: IProcessRagfairTradeRequestData, + sessionID: string, + ): IItemEventRouterResponse; } diff --git a/project/src/models/spt/callbacks/ITraderCallbacks.ts b/project/src/models/spt/callbacks/ITraderCallbacks.ts index 2ca11af9..33a854e3 100644 --- a/project/src/models/spt/callbacks/ITraderCallbacks.ts +++ b/project/src/models/spt/callbacks/ITraderCallbacks.ts @@ -1,17 +1,16 @@ /* * File generated by Interface generator (dotup.dotup-vscode-interface-generator) - * Date: 2022-04-28 14:22:44 -*/ + * Date: 2022-04-28 14:22:44 + */ import { IEmptyRequestData } from "@spt-aki/models/eft/common/IEmptyRequestData"; import { ITraderAssort, ITraderBase } from "@spt-aki/models/eft/common/tables/ITrader"; import { IGetBodyResponseData } from "@spt-aki/models/eft/httpResponse/IGetBodyResponseData"; export interface ITraderCallbacks { - load(): void - getTraderSettings(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData - getTrader(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData - getAssort(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData - update(): boolean - + load(): void; + getTraderSettings(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; + getTrader(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; + getAssort(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData; + update(): boolean; } diff --git a/project/src/models/spt/config/IAirdropConfig.ts b/project/src/models/spt/config/IAirdropConfig.ts index e09fe1e1..dc385675 100644 --- a/project/src/models/spt/config/IAirdropConfig.ts +++ b/project/src/models/spt/config/IAirdropConfig.ts @@ -4,61 +4,60 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IAirdropConfig extends IBaseConfig { - kind: "aki-airdrop" - airdropChancePercent: AirdropChancePercent - airdropTypeWeightings: Record + kind: "aki-airdrop"; + airdropChancePercent: AirdropChancePercent; + airdropTypeWeightings: Record; /** Lowest point plane will fly at */ - planeMinFlyHeight: number + planeMinFlyHeight: number; /** Highest point plane will fly at */ - planeMaxFlyHeight: number + planeMaxFlyHeight: number; /** Loudness of plane engine */ - planeVolume: number + planeVolume: number; /** Speed plane flies overhead */ - planeSpeed: number + planeSpeed: number; /** Speed loot crate falls after being dropped */ - crateFallSpeed: number + crateFallSpeed: number; /** Container tpls to use when spawning crate - affects container size, keyed by drop type e.g. mixed/weaponArmor/foodMedical/barter */ - containerIds: Record + containerIds: Record; /** Earliest time aircraft will spawn in raid */ - airdropMinStartTimeSeconds: number + airdropMinStartTimeSeconds: number; /** Latest time aircraft will spawn in raid */ - airdropMaxStartTimeSeconds: number + airdropMaxStartTimeSeconds: number; /** What rewards will the loot crate contain, keyed by drop type e.g. mixed/weaponArmor/foodMedical/barter */ - loot: Record + loot: Record; } /** Chance map will have an airdrop occur out of 100 - locations not included count as 0% */ export interface AirdropChancePercent { - bigmap: number - woods: number - lighthouse: number - shoreline: number - interchange: number - reserve: number - tarkovStreets: number + bigmap: number; + woods: number; + lighthouse: number; + shoreline: number; + interchange: number; + reserve: number; + tarkovStreets: number; } /** Loot inside crate */ export interface AirdropLoot { /** Min/max of weapons inside crate */ - presetCount?: MinMax + presetCount?: MinMax; /** Min/max of items inside crate */ - itemCount: MinMax + itemCount: MinMax; /** Min/max of sealed weapon boxes inside crate */ - weaponCrateCount: MinMax + weaponCrateCount: MinMax; /** Items to never allow - tpls */ - itemBlacklist: string[] + itemBlacklist: string[]; /** Item type (parentId) to allow inside crate */ - itemTypeWhitelist: string[] + itemTypeWhitelist: string[]; /** Item type/ item tpls to limit count of inside crate - key: item base type: value: max count */ - itemLimits: Record + itemLimits: Record; /** Items to limit stack size of key: item tpl value: min/max stack size */ - itemStackLimits: Record + itemStackLimits: Record; /** Armor levels to allow inside crate e.g. [4,5,6] */ - armorLevelWhitelist?: number[] + armorLevelWhitelist?: number[]; /** Should boss items be added to airdrop crate */ allowBossItems: boolean; } - \ No newline at end of file diff --git a/project/src/models/spt/config/IBaseConfig.ts b/project/src/models/spt/config/IBaseConfig.ts index d1f15405..c35b6fa6 100644 --- a/project/src/models/spt/config/IBaseConfig.ts +++ b/project/src/models/spt/config/IBaseConfig.ts @@ -1,4 +1,4 @@ export interface IBaseConfig { - kind: string -} \ No newline at end of file + kind: string; +} diff --git a/project/src/models/spt/config/IBotConfig.ts b/project/src/models/spt/config/IBotConfig.ts index 544bdf7a..d1c1a3e4 100644 --- a/project/src/models/spt/config/IBotConfig.ts +++ b/project/src/models/spt/config/IBotConfig.ts @@ -5,91 +5,91 @@ import { IBotDurability } from "@spt-aki/models/spt/config/IBotDurability"; export interface IBotConfig extends IBaseConfig { - kind: "aki-bot" + kind: "aki-bot"; /** How many variants of each bot should be generated on raid start */ - presetBatch: PresetBatch + presetBatch: PresetBatch; /** Bot roles that should not have PMC types (sptBear/sptUsec) added as enemies to */ - botsToNotAddPMCsAsEnemiesTo: string[] + botsToNotAddPMCsAsEnemiesTo: string[]; /** What bot types should be classified as bosses */ - bosses: string[] + bosses: string[]; /** Control weapon/armor durability min/max values for each bot type */ - durability: IBotDurability + durability: IBotDurability; /** Controls the percentage values of randomization item resources */ - lootItemResourceRandomization: Record + lootItemResourceRandomization: Record; /** Control the weighting of how expensive an average loot item is on a PMC or Scav */ - lootNValue: LootNvalue + lootNValue: LootNvalue; /** Control what bots are added to a bots revenge list key: bottype, value: bottypes to revenge on seeing their death */ - revenge: Record + revenge: Record; /** Control how many items are allowed to spawn on a bot * key: bottype, value: */ - itemSpawnLimits: Record> + itemSpawnLimits: Record>; /** Blacklist/whitelist items on a bot */ - equipment: Record + equipment: Record; /** Show a bots botType value after their name */ - showTypeInNickname: boolean + showTypeInNickname: boolean; /** What ai brain should a normal scav use per map */ - assaultBrainType: Record> + assaultBrainType: Record>; /** Max number of bots that can be spawned in a raid at any one time */ - maxBotCap: Record + maxBotCap: Record; /** Chance scav has fake pscav name e.g. Scav name (player name) */ chanceAssaultScavHasPlayerScavName: number; /** How many stacks of secret ammo should a bot have in its bot secure container */ - secureContainerAmmoStackCount: number + secureContainerAmmoStackCount: number; } /** Number of bots to generate and store in cache on raid start per bot type */ -export interface PresetBatch +export interface PresetBatch { - assault: number - bossBully: number - bossGluhar: number - bossKilla: number - bossKojaniy: number - bossSanitar: number - bossTagilla: number - bossKnight: number - bossTest: number - cursedAssault: number - followerBully: number - followerGluharAssault: number - followerGluharScout: number - followerGluharSecurity: number - followerGluharSnipe: number - followerKojaniy: number - followerSanitar: number - followerTagilla: number - followerBirdEye: number - followerBigPipe: number - followerTest: number, - followerBoar: number - marksman: number - pmcBot: number - sectantPriest: number - sectantWarrior: number - gifter: number - test: number - exUsec: number, - arenaFighterEvent: number, - arenaFighter: number, - crazyAssaultEvent: number, - bossBoar: number, - bossBoarSniper: number, - sptUsec: number, - sptBear: number + assault: number; + bossBully: number; + bossGluhar: number; + bossKilla: number; + bossKojaniy: number; + bossSanitar: number; + bossTagilla: number; + bossKnight: number; + bossTest: number; + cursedAssault: number; + followerBully: number; + followerGluharAssault: number; + followerGluharScout: number; + followerGluharSecurity: number; + followerGluharSnipe: number; + followerKojaniy: number; + followerSanitar: number; + followerTagilla: number; + followerBirdEye: number; + followerBigPipe: number; + followerTest: number; + followerBoar: number; + marksman: number; + pmcBot: number; + sectantPriest: number; + sectantWarrior: number; + gifter: number; + test: number; + exUsec: number; + arenaFighterEvent: number; + arenaFighter: number; + crazyAssaultEvent: number; + bossBoar: number; + bossBoarSniper: number; + sptUsec: number; + sptBear: number; } -export interface LootNvalue +export interface LootNvalue { - scav: number - pmc: number + scav: number; + pmc: number; } export interface EquipmentFilters { /** Limits for mod types per weapon .e.g. scopes */ - weaponModLimits: ModLimits + weaponModLimits: ModLimits; /** Whitelist for weapon sight types allowed per gun */ - weaponSightWhitelist: Record + weaponSightWhitelist: Record; /** Chance face shield is down/active */ faceShieldIsActiveChancePercent?: number; /** Chance gun flashlight is active during the day */ @@ -103,79 +103,79 @@ export interface EquipmentFilters /** Chance NODS are down/active during the night */ nvgIsActiveChanceNightPercent?: number; /** Adjust weighting/chances of items on bot by level of bot */ - randomisation: RandomisationDetails[] + randomisation: RandomisationDetails[]; /** Blacklist equipment by level of bot */ - blacklist: EquipmentFilterDetails[] + blacklist: EquipmentFilterDetails[]; /** Whitelist equipment by level of bot */ - whitelist: EquipmentFilterDetails[] + whitelist: EquipmentFilterDetails[]; /** Adjust equipment/ammo */ - weightingAdjustmentsByBotLevel: WeightingAdjustmentDetails[] + weightingAdjustmentsByBotLevel: WeightingAdjustmentDetails[]; /** Same as weightingAdjustments but based on player level instead of bot level */ - weightingAdjustmentsByPlayerLevel?: WeightingAdjustmentDetails[] + weightingAdjustmentsByPlayerLevel?: WeightingAdjustmentDetails[]; /** Should the stock mod be forced to spawn on bot */ - forceStock: boolean + forceStock: boolean; } export interface ModLimits { /** How many scopes are allowed on a weapon - hard coded to work with OPTIC_SCOPE, ASSAULT_SCOPE, COLLIMATOR, COMPACT_COLLIMATOR */ - scopeLimit?: number + scopeLimit?: number; /** How many lasers or lights are allowed on a weapon - hard coded to work with TACTICAL_COMBO, and FLASHLIGHT */ - lightLaserLimit?: number + lightLaserLimit?: number; } export interface RandomisationDetails { /** Between what levels do these randomisation setting apply to */ - levelRange: MinMax - generation?: Record + levelRange: MinMax; + generation?: Record; /** Mod slots that should be fully randomisate -ignores mods from bottype.json */ - randomisedWeaponModSlots?: string[] + randomisedWeaponModSlots?: string[]; /** Armor slots that should be randomised e.g. 'Headwear, Armband' */ - randomisedArmorSlots?: string[] + randomisedArmorSlots?: string[]; /** Equipment chances */ - equipment?: Record + equipment?: Record; /** Mod chances */ - mods?: Record + mods?: Record; } export interface EquipmentFilterDetails { /** Between what levels do these equipment filter setting apply to */ - levelRange: MinMax + levelRange: MinMax; /** Key: mod slot name e.g. mod_magazine, value: item tpls */ - equipment: Record + equipment: Record; /** Key: cartridge type e.g. Caliber23x75, value: item tpls */ - cartridge: Record + cartridge: Record; } export interface WeightingAdjustmentDetails { /** Between what levels do these weight settings apply to */ - levelRange: MinMax + levelRange: MinMax; /** Key: ammo type e.g. Caliber556x45NATO, value: item tpl + weight */ - ammo?: AdjustmentDetails + ammo?: AdjustmentDetails; /** Key: equipment slot e.g. TacticalVest, value: item tpl + weight */ - equipment?: AdjustmentDetails + equipment?: AdjustmentDetails; /** Key: clothing slot e.g. feet, value: item tpl + weight */ - clothing?: AdjustmentDetails + clothing?: AdjustmentDetails; } export interface AdjustmentDetails { - add: Record> - edit: Record> + add: Record>; + edit: Record>; } export interface IRandomisedResourceDetails { - food: IRandomisedResourceValues - meds: IRandomisedResourceValues + food: IRandomisedResourceValues; + meds: IRandomisedResourceValues; } export interface IRandomisedResourceValues { /** Minimum percent of item to randomized between min and max resource*/ - resourcePercent: number + resourcePercent: number; /** Chance for randomization to not occur */ - chanceMaxResourcePercent: number + chanceMaxResourcePercent: number; } diff --git a/project/src/models/spt/config/IBotDurability.ts b/project/src/models/spt/config/IBotDurability.ts index b340a95f..fab49064 100644 --- a/project/src/models/spt/config/IBotDurability.ts +++ b/project/src/models/spt/config/IBotDurability.ts @@ -1,61 +1,61 @@ -export interface IBotDurability +export interface IBotDurability { - default: DefaultDurability - pmc: PmcDurability - boss: BotDurability - follower: BotDurability - assault: BotDurability - cursedassault: BotDurability - marksman: BotDurability - pmcbot: BotDurability - arenafighterevent: BotDurability - arenafighter: BotDurability - crazyassaultevent: BotDurability - exusec: BotDurability - gifter: BotDurability - sectantpriest: BotDurability - sectantwarrior: BotDurability + default: DefaultDurability; + pmc: PmcDurability; + boss: BotDurability; + follower: BotDurability; + assault: BotDurability; + cursedassault: BotDurability; + marksman: BotDurability; + pmcbot: BotDurability; + arenafighterevent: BotDurability; + arenafighter: BotDurability; + crazyassaultevent: BotDurability; + exusec: BotDurability; + gifter: BotDurability; + sectantpriest: BotDurability; + sectantwarrior: BotDurability; } /** Durability values to be used when a more specific bot type cant be found */ -export interface DefaultDurability +export interface DefaultDurability { - armor: ArmorDurability - weapon: WeaponDurability + armor: ArmorDurability; + weapon: WeaponDurability; } -export interface PmcDurability +export interface PmcDurability { - armor: PmcDurabilityArmor - weapon: WeaponDurability + armor: PmcDurabilityArmor; + weapon: WeaponDurability; } -export interface PmcDurabilityArmor +export interface PmcDurabilityArmor { - lowestMaxPercent: number - highestMaxPercent: number - maxDelta: number - minDelta: number + lowestMaxPercent: number; + highestMaxPercent: number; + maxDelta: number; + minDelta: number; } -export interface BotDurability +export interface BotDurability { - armor: ArmorDurability - weapon: WeaponDurability + armor: ArmorDurability; + weapon: WeaponDurability; } -export interface ArmorDurability +export interface ArmorDurability { - maxDelta: number - minDelta: number - minLimitPercent: number + maxDelta: number; + minDelta: number; + minLimitPercent: number; } -export interface WeaponDurability +export interface WeaponDurability { - lowestMax: number - highestMax: number - maxDelta: number - minDelta: number - minLimitPercent: number -} \ No newline at end of file + lowestMax: number; + highestMax: number; + maxDelta: number; + minDelta: number; + minLimitPercent: number; +} diff --git a/project/src/models/spt/config/ICoreConfig.ts b/project/src/models/spt/config/ICoreConfig.ts index 20d6be99..9c20726b 100644 --- a/project/src/models/spt/config/ICoreConfig.ts +++ b/project/src/models/spt/config/ICoreConfig.ts @@ -25,8 +25,8 @@ export interface IGameFixes removeModItemsFromProfile: boolean; } -export interface IServerFeatures +export interface IServerFeatures { /* Controls whether or not the server attempts to download mod dependencies not included in the server's executable */ autoInstallModDependencies: boolean; -} \ No newline at end of file +} diff --git a/project/src/models/spt/config/IGiftsConfig.ts b/project/src/models/spt/config/IGiftsConfig.ts index 95887014..f772f91b 100644 --- a/project/src/models/spt/config/IGiftsConfig.ts +++ b/project/src/models/spt/config/IGiftsConfig.ts @@ -7,26 +7,26 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IGiftsConfig extends IBaseConfig { - kind: "aki-gifts" - gifts: Record + kind: "aki-gifts"; + gifts: Record; } export interface Gift { /** Items to send to player */ - items: Item[] + items: Item[]; /** Who is sending the gift to player */ - sender: GiftSenderType + sender: GiftSenderType; /** Optinal - supply a users id to send from, not necessary when sending from SYSTEM or TRADER */ - senderId?: string - senderDetails: IUserDialogInfo, + senderId?: string; + senderDetails: IUserDialogInfo; /** Optional - supply a trader type to send from, not necessary when sending from SYSTEM or USER */ - trader?: Traders - messageText: string + trader?: Traders; + messageText: string; /** Optional - if sending text from the client locale file */ - localeTextId?: string + localeTextId?: string; /** Optional - Used by Seasonal events to send on specific day */ - timestampToSend?: number - associatedEvent: SeasonalEventType - collectionTimeHours: number -} \ No newline at end of file + timestampToSend?: number; + associatedEvent: SeasonalEventType; + collectionTimeHours: number; +} diff --git a/project/src/models/spt/config/IHealthConfig.ts b/project/src/models/spt/config/IHealthConfig.ts index e31de433..33a62d96 100644 --- a/project/src/models/spt/config/IHealthConfig.ts +++ b/project/src/models/spt/config/IHealthConfig.ts @@ -2,19 +2,19 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IHealthConfig extends IBaseConfig { - kind: "aki-health" - healthMultipliers: HealthMultipliers - save: Save + kind: "aki-health"; + healthMultipliers: HealthMultipliers; + save: Save; } -export interface HealthMultipliers +export interface HealthMultipliers { - death: number - blacked: number + death: number; + blacked: number; } -export interface Save +export interface Save { - health: boolean - effects: boolean -} \ No newline at end of file + health: boolean; + effects: boolean; +} diff --git a/project/src/models/spt/config/IHideoutConfig.ts b/project/src/models/spt/config/IHideoutConfig.ts index 05eea7fc..06b199b0 100644 --- a/project/src/models/spt/config/IHideoutConfig.ts +++ b/project/src/models/spt/config/IHideoutConfig.ts @@ -2,8 +2,8 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IHideoutConfig extends IBaseConfig { - kind: "aki-hideout" - runIntervalSeconds: number - hoursForSkillCrafting: number + kind: "aki-hideout"; + runIntervalSeconds: number; + hoursForSkillCrafting: number; expCraftAmount: number; -} \ No newline at end of file +} diff --git a/project/src/models/spt/config/IHttpConfig.ts b/project/src/models/spt/config/IHttpConfig.ts index 7a78105d..e1ddb9d5 100644 --- a/project/src/models/spt/config/IHttpConfig.ts +++ b/project/src/models/spt/config/IHttpConfig.ts @@ -2,11 +2,11 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IHttpConfig extends IBaseConfig { - webSocketPingDelayMs: number - kind: "aki-http" - ip: string - port: number - logRequests: boolean + webSocketPingDelayMs: number; + kind: "aki-http"; + ip: string; + port: number; + logRequests: boolean; /** e.g. "Aki_Data/Server/images/traders/579dc571d53a0658a154fbec.png": "Aki_Data/Server/images/traders/NewTraderImage.png" */ - serverImagePathOverride: Record -} \ No newline at end of file + serverImagePathOverride: Record; +} diff --git a/project/src/models/spt/config/IInRaidConfig.ts b/project/src/models/spt/config/IInRaidConfig.ts index a0248170..4a320868 100644 --- a/project/src/models/spt/config/IInRaidConfig.ts +++ b/project/src/models/spt/config/IInRaidConfig.ts @@ -2,37 +2,37 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IInRaidConfig extends IBaseConfig { - kind: "aki-inraid" - MIAOnRaidEnd: boolean + kind: "aki-inraid"; + MIAOnRaidEnd: boolean; /** Overrides to apply to the pre-raid settings screen */ - raidMenuSettings: RaidMenuSettings + raidMenuSettings: RaidMenuSettings; /** What effects should be saved post-raid */ - save: Save + save: Save; /** Names of car extracts */ - carExtracts: string[] + carExtracts: string[]; /** Names of coop extracts */ - coopExtracts: string[] + coopExtracts: string[]; /** Fene rep gain from a single car extract */ - carExtractBaseStandingGain: number + carExtractBaseStandingGain: number; /** Fence rep gain when successfully extracting as pscav */ - scavExtractGain: number + scavExtractGain: number; /** On death should items in your secure keep their Find in raid status regardless of how you finished the raid */ - keepFiRSecureContainerOnDeath: boolean + keepFiRSecureContainerOnDeath: boolean; } -export interface RaidMenuSettings +export interface RaidMenuSettings { - aiAmount: string - aiDifficulty: string - bossEnabled: boolean - scavWars: boolean - taggedAndCursed: boolean - enablePve: boolean + aiAmount: string; + aiDifficulty: string; + bossEnabled: boolean; + scavWars: boolean; + taggedAndCursed: boolean; + enablePve: boolean; } -export interface Save +export interface Save { /** Should loot gained from raid be saved */ - loot: boolean - durability: boolean -} \ No newline at end of file + loot: boolean; + durability: boolean; +} diff --git a/project/src/models/spt/config/IInsuranceConfig.ts b/project/src/models/spt/config/IInsuranceConfig.ts index 42174269..50014421 100644 --- a/project/src/models/spt/config/IInsuranceConfig.ts +++ b/project/src/models/spt/config/IInsuranceConfig.ts @@ -2,15 +2,15 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IInsuranceConfig extends IBaseConfig { - kind: "aki-insurance" + kind: "aki-insurance"; /** Insurance price multiplier */ - insuranceMultiplier: Record + insuranceMultiplier: Record; /** Chance item is returned as insurance, keyed by trader id */ - returnChancePercent: Record + returnChancePercent: Record; /** Item slots that should never be returned as insurance */ - blacklistedEquipment: string[] + blacklistedEquipment: string[]; /** Override to control how quickly insurance is processed/returned in second */ - returnTimeOverrideSeconds: number + returnTimeOverrideSeconds: number; /** How often server should process insurance in seconds */ - runIntervalSeconds: number + runIntervalSeconds: number; } diff --git a/project/src/models/spt/config/IInventoryConfig.ts b/project/src/models/spt/config/IInventoryConfig.ts index 1a187a34..7d3580c9 100644 --- a/project/src/models/spt/config/IInventoryConfig.ts +++ b/project/src/models/spt/config/IInventoryConfig.ts @@ -3,31 +3,31 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IInventoryConfig extends IBaseConfig { - kind: "aki-inventory" + kind: "aki-inventory"; /** Should new items purchased by flagged as found in raid */ - newItemsMarkedFound: boolean - randomLootContainers: Record - sealedAirdropContainer: ISealedAirdropContainerSettings + newItemsMarkedFound: boolean; + randomLootContainers: Record; + sealedAirdropContainer: ISealedAirdropContainerSettings; /** Contains item tpls that the server should consider money and treat the same as roubles/euros/dollars */ - customMoneyTpls: string[] + customMoneyTpls: string[]; } export interface RewardDetails { - rewardCount: number - foundInRaid: boolean - rewardTplPool?: Record - rewardTypePool?: Record + rewardCount: number; + foundInRaid: boolean; + rewardTplPool?: Record; + rewardTypePool?: Record; } export interface ISealedAirdropContainerSettings { - weaponRewardWeight: Record - defaultPresetsOnly: boolean + weaponRewardWeight: Record; + defaultPresetsOnly: boolean; /** Should contents be flagged as found in raid when opened */ foundInRaid: boolean; - weaponModRewardLimits: Record - rewardTypeLimits: Record - ammoBoxWhitelist: string[] - allowBossItems: boolean -} \ No newline at end of file + weaponModRewardLimits: Record; + rewardTypeLimits: Record; + ammoBoxWhitelist: string[]; + allowBossItems: boolean; +} diff --git a/project/src/models/spt/config/IItemConfig.ts b/project/src/models/spt/config/IItemConfig.ts index 55518842..610cd8ee 100644 --- a/project/src/models/spt/config/IItemConfig.ts +++ b/project/src/models/spt/config/IItemConfig.ts @@ -2,9 +2,9 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IItemConfig extends IBaseConfig { - kind: "aki-item" + kind: "aki-item"; /** Items that should be globally blacklisted */ - blacklist: string[], + blacklist: string[]; /** Items that can only be found on bosses */ - bossItems: string[] -} \ No newline at end of file + bossItems: string[]; +} diff --git a/project/src/models/spt/config/ILocaleConfig.ts b/project/src/models/spt/config/ILocaleConfig.ts index a3c6307e..b1dc7aef 100644 --- a/project/src/models/spt/config/ILocaleConfig.ts +++ b/project/src/models/spt/config/ILocaleConfig.ts @@ -2,11 +2,11 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface ILocaleConfig extends IBaseConfig { - kind: "aki-locale" + kind: "aki-locale"; /** e.g. ru/en/cn/fr etc, or 'system', will take computer locale setting */ - gameLocale: string + gameLocale: string; /** e.g. ru/en/cn/fr etc, or 'system', will take computer locale setting */ - serverLocale: string + serverLocale: string; /** Languages server can be translated into */ - serverSupportedLocales: string[] + serverSupportedLocales: string[]; } diff --git a/project/src/models/spt/config/ILocationConfig.ts b/project/src/models/spt/config/ILocationConfig.ts index c1f8c985..91803ad2 100644 --- a/project/src/models/spt/config/ILocationConfig.ts +++ b/project/src/models/spt/config/ILocationConfig.ts @@ -4,103 +4,103 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface ILocationConfig extends IBaseConfig { - kind: "aki-location" + kind: "aki-location"; /** Waves with a min/max of the same value don't spawn any bots, bsg only spawn the difference between min and max */ fixEmptyBotWavesSettings: IFixEmptyBotWavesSettings; /** Rogues are classified as bosses and spawn immediatly, this can result in no scavs spawning, delay rogues spawning to allow scavs to spawn first */ - rogueLighthouseSpawnTimeSettings: IRogueLighthouseSpawnTimeSettings + rogueLighthouseSpawnTimeSettings: IRogueLighthouseSpawnTimeSettings; /** When a map has hit max alive bots, any wave that should spawn will be reduced to 1 bot in size and placed in a spawn queue, this splits waves into smaller sizes to reduce the impact of this behaviour */ - splitWaveIntoSingleSpawnsSettings: ISplitWaveSettings - looseLootMultiplier: LootMultiplier - staticLootMultiplier: LootMultiplier + splitWaveIntoSingleSpawnsSettings: ISplitWaveSettings; + looseLootMultiplier: LootMultiplier; + staticLootMultiplier: LootMultiplier; /** Custom bot waves to add to a locations base json on game start if addCustomBotWavesToMaps is true */ - customWaves: CustomWaves + customWaves: CustomWaves; /** Open zones to add to map */ - openZones: Record + openZones: Record; /** Key = map id, value = item tpls that should only have one forced loot spawn position */ - forcedLootSingleSpawnById: Record + forcedLootSingleSpawnById: Record; /** How many attempts should be taken to fit an item into a container before giving up */ fitLootIntoContainerAttempts: number; /** Add all possible zones to each maps `OpenZones` property */ - addOpenZonesToAllMaps: boolean + addOpenZonesToAllMaps: boolean; /** Allow addition of custom bot waves designed by SPT to be added to maps - defined in configs/location.json.customWaves*/ - addCustomBotWavesToMaps: boolean + addCustomBotWavesToMaps: boolean; /** Should the limits defined inside botTypeLimits to appled to locations on game start */ - enableBotTypeLimits: boolean + enableBotTypeLimits: boolean; /** Add limits to a locations base.MinMaxBots array if enableBotTypeLimits is true*/ - botTypeLimits: Record + botTypeLimits: Record; /** container randomisation settings */ containerRandomisationSettings: IContainerRandomistionSettings; /** How full must a random loose magazine be %*/ - minFillLooseMagazinePercent: number + minFillLooseMagazinePercent: number; /** How full must a random static magazine be %*/ - minFillStaticMagazinePercent: number - allowDuplicateItemsInStaticContainers: boolean + minFillStaticMagazinePercent: number; + allowDuplicateItemsInStaticContainers: boolean; /** Key: map, value: loose loot ids to ignore */ - looseLootBlacklist: Record + looseLootBlacklist: Record; } export interface IContainerRandomistionSettings { - enabled: boolean + enabled: boolean; /** What maps can use the container randomisation feature */ - maps: Record + maps: Record; /** Some container types don't work when randomised */ - containerTypesToNotRandomise: string[] - containerGroupMinSizeMultiplier: number - containerGroupMaxSizeMultiplier: number + containerTypesToNotRandomise: string[]; + containerGroupMinSizeMultiplier: number; + containerGroupMaxSizeMultiplier: number; } export interface IFixEmptyBotWavesSettings { - enabled: boolean, + enabled: boolean; ignoreMaps: string[]; } export interface IRogueLighthouseSpawnTimeSettings { - enabled: boolean - waitTimeSeconds: number + enabled: boolean; + waitTimeSeconds: number; } export interface ISplitWaveSettings { - enabled: boolean + enabled: boolean; ignoreMaps: string[]; - waveSizeThreshold: number + waveSizeThreshold: number; } export interface CustomWaves { /** Bosses spawn on raid start */ - boss: Record - normal: Record + boss: Record; + normal: Record; } export interface IBotTypeLimit extends MinMax { - type: string + type: string; } /** Multiplier to apply to the loot count for a given map */ -export interface LootMultiplier +export interface LootMultiplier { - bigmap: number - develop: number + bigmap: number; + develop: number; // eslint-disable-next-line @typescript-eslint/naming-convention - factory4_day: number + factory4_day: number; // eslint-disable-next-line @typescript-eslint/naming-convention - factory4_night: number - interchange: number - laboratory: number - rezervbase: number - shoreline: number - woods: number - hideout: number - lighthouse: number - privatearea: number - suburbs: number - tarkovstreets: number - terminal: number - town: number + factory4_night: number; + interchange: number; + laboratory: number; + rezervbase: number; + shoreline: number; + woods: number; + hideout: number; + lighthouse: number; + privatearea: number; + suburbs: number; + tarkovstreets: number; + terminal: number; + town: number; } diff --git a/project/src/models/spt/config/ILootConfig.ts b/project/src/models/spt/config/ILootConfig.ts index aaf6ba1b..d8ac9cab 100644 --- a/project/src/models/spt/config/ILootConfig.ts +++ b/project/src/models/spt/config/ILootConfig.ts @@ -3,9 +3,9 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface ILootConfig extends IBaseConfig { - kind: "aki-loot" + kind: "aki-loot"; /** Spawn positions to add into a map, key=mapid */ - looseLoot: Record + looseLoot: Record; /** Loose loot probability adjustments to apply on game start */ looseLootSpawnPointAdjustments: Record>; -} \ No newline at end of file +} diff --git a/project/src/models/spt/config/ILostOnDeathConfig.ts b/project/src/models/spt/config/ILostOnDeathConfig.ts index 8ebff4c1..db5eb4c3 100644 --- a/project/src/models/spt/config/ILostOnDeathConfig.ts +++ b/project/src/models/spt/config/ILostOnDeathConfig.ts @@ -2,27 +2,27 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface ILostOnDeathConfig extends IBaseConfig { - kind: "aki-lostondeath" + kind: "aki-lostondeath"; /** What equipment in each slot should be lost on death */ - equipment: Equipment + equipment: Equipment; /** Should special slot items be removed from quest inventory on death e.g. wifi camera/markers */ specialSlotItems: boolean; /** Should quest items be removed from quest inventory on death */ - questItems: boolean + questItems: boolean; } export interface Equipment { - ArmBand: boolean - Headwear: boolean - Earpiece: boolean - FaceCover: boolean - ArmorVest: boolean - Eyewear: boolean - TacticalVest: boolean - Backpack: boolean - Holster: boolean - FirstPrimaryWeapon: boolean - SecondPrimaryWeapon: boolean - Scabbard: boolean -} \ No newline at end of file + ArmBand: boolean; + Headwear: boolean; + Earpiece: boolean; + FaceCover: boolean; + ArmorVest: boolean; + Eyewear: boolean; + TacticalVest: boolean; + Backpack: boolean; + Holster: boolean; + FirstPrimaryWeapon: boolean; + SecondPrimaryWeapon: boolean; + Scabbard: boolean; +} diff --git a/project/src/models/spt/config/IMatchConfig.ts b/project/src/models/spt/config/IMatchConfig.ts index 7034b308..6b42237a 100644 --- a/project/src/models/spt/config/IMatchConfig.ts +++ b/project/src/models/spt/config/IMatchConfig.ts @@ -2,6 +2,6 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IMatchConfig extends IBaseConfig { - kind: "aki-match" - enabled: boolean -} \ No newline at end of file + kind: "aki-match"; + enabled: boolean; +} diff --git a/project/src/models/spt/config/IPlayerScavConfig.ts b/project/src/models/spt/config/IPlayerScavConfig.ts index fa981245..f21a436a 100644 --- a/project/src/models/spt/config/IPlayerScavConfig.ts +++ b/project/src/models/spt/config/IPlayerScavConfig.ts @@ -3,31 +3,31 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IPlayerScavConfig extends IBaseConfig { - kind: "aki-playerscav" - karmaLevel: Record + kind: "aki-playerscav"; + karmaLevel: Record; } export interface KarmaLevel { - botTypeForLoot: string - modifiers: Modifiers - itemLimits: ItemLimits - equipmentBlacklist: Record - labsAccessCardChancePercent: number + botTypeForLoot: string; + modifiers: Modifiers; + itemLimits: ItemLimits; + equipmentBlacklist: Record; + labsAccessCardChancePercent: number; } export interface Modifiers { - equipment: Record - mod: Record + equipment: Record; + mod: Record; } export interface ItemLimits { - healing: GenerationData - drugs: GenerationData - stims: GenerationData - looseLoot: GenerationData - magazines: GenerationData - grenades: GenerationData + healing: GenerationData; + drugs: GenerationData; + stims: GenerationData; + looseLoot: GenerationData; + magazines: GenerationData; + grenades: GenerationData; } diff --git a/project/src/models/spt/config/IPmChatResponse.ts b/project/src/models/spt/config/IPmChatResponse.ts index ef40efe9..5aebb6cd 100644 --- a/project/src/models/spt/config/IPmChatResponse.ts +++ b/project/src/models/spt/config/IPmChatResponse.ts @@ -2,16 +2,16 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IPmcChatResponse extends IBaseConfig { - kind: "aki-pmcchatresponse" - victim: IResponseSettings - killer: IResponseSettings + kind: "aki-pmcchatresponse"; + victim: IResponseSettings; + killer: IResponseSettings; } export interface IResponseSettings { - responseChancePercent: number - responseTypeWeights: Record - stripCapitalisationChancePercent: number + responseChancePercent: number; + responseTypeWeights: Record; + stripCapitalisationChancePercent: number; allCapsChancePercent: number; appendBroToMessageEndChancePercent: number; -} \ No newline at end of file +} diff --git a/project/src/models/spt/config/IPmcConfig.ts b/project/src/models/spt/config/IPmcConfig.ts index 2fc551e5..fff537e1 100644 --- a/project/src/models/spt/config/IPmcConfig.ts +++ b/project/src/models/spt/config/IPmcConfig.ts @@ -4,66 +4,66 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IPmcConfig extends IBaseConfig { - kind: "aki-pmc" + kind: "aki-pmc"; /** What game version should the PMC have */ - gameVersionWeight: Record + gameVersionWeight: Record; /** What account type should the PMC have */ - accountTypeWeight: Record + accountTypeWeight: Record; /** Global whitelist/blacklist of vest loot for PMCs */ - vestLoot: SlotLootSettings + vestLoot: SlotLootSettings; /** Global whitelist/blacklist of pocket loot for PMCs */ - pocketLoot: SlotLootSettings + pocketLoot: SlotLootSettings; /** Global whitelist/blacklist of backpack loot for PMCs */ - backpackLoot: SlotLootSettings - dynamicLoot: DynamicLoot + backpackLoot: SlotLootSettings; + dynamicLoot: DynamicLoot; /** Use difficulty defined in config/bot.json/difficulty instead of chosen difficulty dropdown value */ - useDifficultyOverride: boolean + useDifficultyOverride: boolean; /** Difficulty override e.g. "AsOnline/Hard" */ - difficulty: string + difficulty: string; /** Chance out of 100 to have a complete gun in backpack */ - looseWeaponInBackpackChancePercent: number + looseWeaponInBackpackChancePercent: number; /** Chance out of 100 to have an enhancement applied to PMC weapon */ - weaponHasEnhancementChancePercent: number + weaponHasEnhancementChancePercent: number; /** MinMax count of weapons to have in backpack */ - looseWeaponInBackpackLootMinMax: MinMax + looseWeaponInBackpackLootMinMax: MinMax; /** Percentage chance PMC will be USEC */ - isUsec: number + isUsec: number; /** WildSpawnType enum value USEC PMCs use */ - usecType: string + usecType: string; /** WildSpawnType enum value BEAR PMCs use */ - bearType: string - chanceSameSideIsHostilePercent: number + bearType: string; + chanceSameSideIsHostilePercent: number; /** What 'brain' does a PMC use, keyed by map and side (USEC/BEAR) key: map location, value: type for usec/bear */ - pmcType: Record>> - maxBackpackLootTotalRub: number - maxPocketLootTotalRub: number - maxVestLootTotalRub: number + pmcType: Record>>; + maxBackpackLootTotalRub: number; + maxPocketLootTotalRub: number; + maxVestLootTotalRub: number; /** Percentage chance a bot from a wave is converted into a PMC, key = bot wildspawn tpye (assault/exusec), value: min+max chance to be converted */ - convertIntoPmcChance: Record + convertIntoPmcChance: Record; /** WildSpawnType bots PMCs should see as hostile */ - enemyTypes: string[] + enemyTypes: string[]; /** How many levels above player level can a PMC be */ - botRelativeLevelDeltaMax: number + botRelativeLevelDeltaMax: number; /** Force a number of healing items into PMCs secure container to ensure they can heal */ - forceHealingItemsIntoSecure: boolean - addPrefixToSameNamePMCAsPlayerChance: number - allPMCsHavePlayerNameWithRandomPrefixChance: number + forceHealingItemsIntoSecure: boolean; + addPrefixToSameNamePMCAsPlayerChance: number; + allPMCsHavePlayerNameWithRandomPrefixChance: number; } export interface PmcTypes { - usec: string - bear: string + usec: string; + bear: string; } -export interface SlotLootSettings +export interface SlotLootSettings { - whitelist: string[] - blacklist: string[] - moneyStackLimits: Record + whitelist: string[]; + blacklist: string[]; + moneyStackLimits: Record; } -export interface DynamicLoot +export interface DynamicLoot { - moneyStackLimits: Record -} \ No newline at end of file + moneyStackLimits: Record; +} diff --git a/project/src/models/spt/config/IQuestConfig.ts b/project/src/models/spt/config/IQuestConfig.ts index 34753847..583ea608 100644 --- a/project/src/models/spt/config/IQuestConfig.ts +++ b/project/src/models/spt/config/IQuestConfig.ts @@ -5,173 +5,173 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IQuestConfig extends IBaseConfig { - kind: "aki-quest" + kind: "aki-quest"; // Hours to get/redeem items from quest mail - redeemTime: number - questTemplateIds: IPlayerTypeQuestIds + redeemTime: number; + questTemplateIds: IPlayerTypeQuestIds; /** Show non-seasonal quests be shown to player */ - showNonSeasonalEventQuests: boolean - eventQuests: Record - repeatableQuests: IRepeatableQuestConfig[] - locationIdMap: Record - bearOnlyQuests: string[] - usecOnlyQuests: string[] + showNonSeasonalEventQuests: boolean; + eventQuests: Record; + repeatableQuests: IRepeatableQuestConfig[]; + locationIdMap: Record; + bearOnlyQuests: string[]; + usecOnlyQuests: string[]; } export interface IPlayerTypeQuestIds { - pmc: IQuestTypeIds - scav: IQuestTypeIds + pmc: IQuestTypeIds; + scav: IQuestTypeIds; } export interface IQuestTypeIds { - Elimination: string - Completion: string - Exploration: string + Elimination: string; + Completion: string; + Exploration: string; } export interface IEventQuestData { - name: string - season: SeasonalEventType - startTimestamp: number - endTimestamp: number - yearly: boolean + name: string; + season: SeasonalEventType; + startTimestamp: number; + endTimestamp: number; + yearly: boolean; } - -export interface IRepeatableQuestConfig + +export interface IRepeatableQuestConfig { id: string; - name: string - side: string - types: string[] - resetTime: number - numQuests: number - minPlayerLevel: number - rewardScaling: IRewardScaling - locations: Record - traderWhitelist: ITraderWhitelist[] - questConfig: IRepeatableQuestTypesConfig + name: string; + side: string; + types: string[]; + resetTime: number; + numQuests: number; + minPlayerLevel: number; + rewardScaling: IRewardScaling; + locations: Record; + traderWhitelist: ITraderWhitelist[]; + questConfig: IRepeatableQuestTypesConfig; /** Item base types to block when generating rewards */ - rewardBaseTypeBlacklist: string[] + rewardBaseTypeBlacklist: string[]; /** Item tplIds to ignore when generating rewards */ - rewardBlacklist: string[] + rewardBlacklist: string[]; rewardAmmoStackMinSize: number; } - -export interface IRewardScaling + +export interface IRewardScaling { - levels: number[] - experience: number[] - roubles: number[] - items: number[] - reputation: number[] - rewardSpread: number - skillRewardChance: number[] - skillPointReward: number[] + levels: number[]; + experience: number[]; + roubles: number[]; + items: number[]; + reputation: number[]; + rewardSpread: number; + skillRewardChance: number[]; + skillPointReward: number[]; } - -export interface ITraderWhitelist + +export interface ITraderWhitelist { - traderId: string - questTypes: string[] + traderId: string; + questTypes: string[]; } - -export interface IRepeatableQuestTypesConfig + +export interface IRepeatableQuestTypesConfig { - Exploration: IExploration - Completion: ICompletion + Exploration: IExploration; + Completion: ICompletion; Pickup: IPickup; - Elimination: IEliminationConfig[] + Elimination: IEliminationConfig[]; } - + export interface IExploration extends IBaseQuestConfig { - maxExtracts: number - specificExits: ISpecificExits + maxExtracts: number; + specificExits: ISpecificExits; } - -export interface ISpecificExits + +export interface ISpecificExits { - probability: number - passageRequirementWhitelist: string[] + probability: number; + passageRequirementWhitelist: string[]; } - + export interface ICompletion extends IBaseQuestConfig { - minRequestedAmount: number - maxRequestedAmount: number - minRequestedBulletAmount: number - maxRequestedBulletAmount: number - useWhitelist: boolean - useBlacklist: boolean + minRequestedAmount: number; + maxRequestedAmount: number; + minRequestedBulletAmount: number; + maxRequestedBulletAmount: number; + useWhitelist: boolean; + useBlacklist: boolean; } export interface IPickup extends IBaseQuestConfig { - ItemTypeToFetchWithMaxCount: IPickupTypeWithMaxCount[] + ItemTypeToFetchWithMaxCount: IPickupTypeWithMaxCount[]; } export interface IPickupTypeWithMaxCount { - itemType: string - maxPickupCount: number - minPickupCount: number + itemType: string; + maxPickupCount: number; + minPickupCount: number; } - + export interface IEliminationConfig extends IBaseQuestConfig { - levelRange: MinMax - targets: ITarget[] - bodyPartProb: number - bodyParts: IBodyPart[] - specificLocationProb: number - distLocationBlacklist: string[] - distProb: number - maxDist: number - minDist: number - maxKills: number - minKills: number - minBossKills: number - maxBossKills: number - minPmcKills: number - maxPmcKills: number - weaponCategoryRequirementProb: number - weaponCategoryRequirements: IWeaponRequirement[] - weaponRequirementProb: number - weaponRequirements: IWeaponRequirement[] + levelRange: MinMax; + targets: ITarget[]; + bodyPartProb: number; + bodyParts: IBodyPart[]; + specificLocationProb: number; + distLocationBlacklist: string[]; + distProb: number; + maxDist: number; + minDist: number; + maxKills: number; + minKills: number; + minBossKills: number; + maxBossKills: number; + minPmcKills: number; + maxPmcKills: number; + weaponCategoryRequirementProb: number; + weaponCategoryRequirements: IWeaponRequirement[]; + weaponRequirementProb: number; + weaponRequirements: IWeaponRequirement[]; } export interface IBaseQuestConfig { - possibleSkillRewards: string[] + possibleSkillRewards: string[]; } export interface ITarget extends IProbabilityObject { - data: IBossInfo + data: IBossInfo; } -export interface IBossInfo +export interface IBossInfo { - isBoss: boolean - isPmc: boolean + isBoss: boolean; + isPmc: boolean; } -export interface IBodyPart extends IProbabilityObject +export interface IBodyPart extends IProbabilityObject { - data: string[] + data: string[]; } -export interface IWeaponRequirement extends IProbabilityObject +export interface IWeaponRequirement extends IProbabilityObject { - data: string[] + data: string[]; } -export interface IProbabilityObject +export interface IProbabilityObject { - key: string - relativeProbability: number - data?: any -} \ No newline at end of file + key: string; + relativeProbability: number; + data?: any; +} diff --git a/project/src/models/spt/config/IRagfairConfig.ts b/project/src/models/spt/config/IRagfairConfig.ts index 1755dcb3..dcffc7c8 100644 --- a/project/src/models/spt/config/IRagfairConfig.ts +++ b/project/src/models/spt/config/IRagfairConfig.ts @@ -3,128 +3,127 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IRagfairConfig extends IBaseConfig { - kind: "aki-ragfair" + kind: "aki-ragfair"; /** How many seconds should pass before expired offers and procesed + player offers checked if sold */ - runIntervalSeconds: number + runIntervalSeconds: number; /** Player listing settings */ - sell: Sell + sell: Sell; /** Trader ids + should their assorts be listed on flea*/ - traders: Record - dynamic: Dynamic + traders: Record; + dynamic: Dynamic; } - -export interface Sell + +export interface Sell { /** Should a fee be deducted from player when liting an item for sale */ - fees: boolean + fees: boolean; /** Settings to control chances of offer being sold */ - chance: Chance + chance: Chance; /** Settings to control how long it takes for a player offer to sell */ - time: Time + time: Time; /** Player offer reputation gain/loss settings */ - reputation: Reputation + reputation: Reputation; /** How many hours are simulated to figure out if player offer was sold */ - simulatedSellHours: number + simulatedSellHours: number; /**Seconds from clicking remove to remove offer from market */ - expireSeconds: number + expireSeconds: number; } - -export interface Chance + +export interface Chance { - base: number - overpriced: number - underpriced: number + base: number; + overpriced: number; + underpriced: number; } - + export interface Time extends MinMax { - base: number + base: number; } - -export interface Reputation + +export interface Reputation { - gain: number - loss: number + gain: number; + loss: number; } - -export interface Dynamic +export interface Dynamic { // Should a purchased dynamic offers items be flagged as found in raid - purchasesAreFoundInRaid: boolean + purchasesAreFoundInRaid: boolean; /** Use the highest trader price for an offer if its greater than the price in templates/prices.json */ useTraderPriceForOffersIfHigher: boolean; /** Barter offer specific settings */ - barter: IBarterDetails - pack: IPackDetails + barter: IBarterDetails; + pack: IPackDetails; /** Dynamic offer price below handbook adjustment values */ - offerAdjustment: OfferAdjustment + offerAdjustment: OfferAdjustment; /** How many offers should expire before an offer regeneration occurs */ - expiredOfferThreshold: number + expiredOfferThreshold: number; /** How many offers should be listed */ - offerItemCount: MinMax + offerItemCount: MinMax; /** How much should the price of an offer vary by (percent 0.8 = 80%, 1.2 = 120%) */ - priceRanges: IPriceRanges + priceRanges: IPriceRanges; /** Should default presets to listed only or should non-standard presets found in globals.json be listed too */ - showDefaultPresetsOnly: boolean - endTimeSeconds: MinMax + showDefaultPresetsOnly: boolean; + endTimeSeconds: MinMax; /** Settings to control the durability range of item items listed on flea */ - condition: Condition + condition: Condition; /** Size stackable items should be listed for in percent of max stack size */ - stackablePercent: MinMax + stackablePercent: MinMax; /** Items that cannot be stacked can have multiples sold in one offer, what range of values can be listed */ - nonStackableCount: MinMax + nonStackableCount: MinMax; /** Range of rating offers for items being listed */ - rating: MinMax + rating: MinMax; /** Percentages to sell offers in each currency */ - currencies: Record + currencies: Record; /** Item tpls that should be forced to sell as a single item */ - showAsSingleStack: string[] + showAsSingleStack: string[]; /** Should christmas/halloween items be removed from flea when not within the seasonal bounds */ - removeSeasonalItemsWhenNotInEvent: boolean + removeSeasonalItemsWhenNotInEvent: boolean; /** Flea blacklist settings */ - blacklist: Blacklist + blacklist: Blacklist; /** Dict of price limits keyed by item type */ - unreasonableModPrices: Record + unreasonableModPrices: Record; } export interface IPriceRanges { - default: MinMax - preset: MinMax - pack: MinMax + default: MinMax; + preset: MinMax; + pack: MinMax; } export interface IBarterDetails { /** Should barter offers be generated */ - enable: boolean + enable: boolean; /** Percentage change an offer is listed as a barter */ - chancePercent: number + chancePercent: number; /** Min number of required items for a barter requirement */ - itemCountMin: number + itemCountMin: number; /** Max number of required items for a barter requirement */ - itemCountMax: number + itemCountMax: number; /** How much can the total price of requested items vary from the item offered */ - priceRangeVariancePercent: number + priceRangeVariancePercent: number; /** Min rouble price for an offer to be considered for turning into a barter */ - minRoubleCostToBecomeBarter: number + minRoubleCostToBecomeBarter: number; /** Item Tpls to never be turned into a barter */ - itemTypeBlacklist: string[] + itemTypeBlacklist: string[]; } export interface IPackDetails { /** Should pack offers be generated */ - enable: boolean + enable: boolean; /** Percentage change an offer is listed as a pack */ - chancePercent: number + chancePercent: number; /** Min number of required items for a pack */ - itemCountMin: number + itemCountMin: number; /** Max number of required items for a pack */ - itemCountMax: number + itemCountMax: number; /** item types to allow being a pack */ - itemTypeWhitelist: string[] + itemTypeWhitelist: string[]; } export interface OfferAdjustment @@ -132,37 +131,36 @@ export interface OfferAdjustment /** Shuld offer price be adjusted when below handbook price */ adjustPriceWhenBelowHandbookPrice: boolean; /** How big a percentage difference does price need to vary from handbook to be considered for adjustment */ - maxPriceDifferenceBelowHandbookPercent: number + maxPriceDifferenceBelowHandbookPercent: number; /** How much to multiply the handbook price to get the new price */ - handbookPriceMultipier: number + handbookPriceMultipier: number; /** What is the minimum rouble price to consider adjusting price of item */ - priceThreshholdRub: number + priceThreshholdRub: number; } - + export interface Condition extends MinMax { /** Percentage change durability is altered */ - conditionChance: number + conditionChance: number; } - -export interface Blacklist + +export interface Blacklist { /** Damaged ammo packs */ - damagedAmmoPacks: boolean + damagedAmmoPacks: boolean; /** Custom blacklist for item Tpls */ - custom: string[] + custom: string[]; /** BSG blacklist a large number of items from flea, true = use blacklist */ - enableBsgList: boolean + enableBsgList: boolean; /** Should quest items be blacklisted from flea */ - enableQuestList: boolean + enableQuestList: boolean; /** Should trader items that are blacklisted by bsg */ - traderItems: boolean + traderItems: boolean; } export interface IUnreasonableModPrices { - enabled: boolean - handbookPriceOverMultiplier: number - newPriceHandbookMultiplier: number + enabled: boolean; + handbookPriceOverMultiplier: number; + newPriceHandbookMultiplier: number; } - \ No newline at end of file diff --git a/project/src/models/spt/config/IRepairConfig.ts b/project/src/models/spt/config/IRepairConfig.ts index 0b65b465..d004147f 100644 --- a/project/src/models/spt/config/IRepairConfig.ts +++ b/project/src/models/spt/config/IRepairConfig.ts @@ -3,60 +3,60 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IRepairConfig extends IBaseConfig { - kind: "aki-repair" - priceMultiplier: number - applyRandomizeDurabilityLoss: boolean - weaponSkillRepairGain: number - armorKitSkillPointGainPerRepairPointMultiplier: number + kind: "aki-repair"; + priceMultiplier: number; + applyRandomizeDurabilityLoss: boolean; + weaponSkillRepairGain: number; + armorKitSkillPointGainPerRepairPointMultiplier: number; /** INT gain multiplier per repaired item type */ - repairKitIntellectGainMultiplier: IIntellectGainValues - //** How much INT can be given to player per repair action */ + repairKitIntellectGainMultiplier: IIntellectGainValues; + // ** How much INT can be given to player per repair action */ maxIntellectGainPerRepair: IMaxIntellectGainValues; weaponTreatment: IWeaponTreatmentRepairValues; - repairKit: RepairKit + repairKit: RepairKit; } export interface IIntellectGainValues { - weapon: number - armor: number + weapon: number; + armor: number; } export interface IMaxIntellectGainValues { - kit: number - trader: number + kit: number; + trader: number; } export interface IWeaponTreatmentRepairValues { /** The chance to gain more weapon maintenance skill */ - critSuccessChance: number - critSuccessAmount: number + critSuccessChance: number; + critSuccessAmount: number; /** The chance to gain less weapon maintenance skill */ - critFailureChance: number - critFailureAmount: number + critFailureChance: number; + critFailureAmount: number; /** The multiplier used for calculating weapon maintenance XP */ - pointGainMultiplier: number + pointGainMultiplier: number; } export interface RepairKit { - armor: BonusSettings - weapon: BonusSettings + armor: BonusSettings; + weapon: BonusSettings; } export interface BonusSettings { - rarityWeight: Record - bonusTypeWeight: Record - common: Record - rare: Record + rarityWeight: Record; + bonusTypeWeight: Record; + common: Record; + rare: Record; } export interface BonusValues { - valuesMinMax: MinMax + valuesMinMax: MinMax; /** What dura is buff active between (min max of current max) */ - activeDurabilityPercentMinMax: MinMax -} \ No newline at end of file + activeDurabilityPercentMinMax: MinMax; +} diff --git a/project/src/models/spt/config/IScavCaseConfig.ts b/project/src/models/spt/config/IScavCaseConfig.ts index 6ceaeb6e..0d3c8265 100644 --- a/project/src/models/spt/config/IScavCaseConfig.ts +++ b/project/src/models/spt/config/IScavCaseConfig.ts @@ -3,36 +3,36 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IScavCaseConfig extends IBaseConfig { - kind: "aki-scavcase" - rewardItemValueRangeRub: Record - moneyRewards: MoneyRewards - ammoRewards: AmmoRewards - rewardItemParentBlacklist: string[] - rewardItemBlacklist: string[] - allowMultipleMoneyRewardsPerRarity: boolean - allowMultipleAmmoRewardsPerRarity: boolean - allowBossItemsAsRewards: boolean + kind: "aki-scavcase"; + rewardItemValueRangeRub: Record; + moneyRewards: MoneyRewards; + ammoRewards: AmmoRewards; + rewardItemParentBlacklist: string[]; + rewardItemBlacklist: string[]; + allowMultipleMoneyRewardsPerRarity: boolean; + allowMultipleAmmoRewardsPerRarity: boolean; + allowBossItemsAsRewards: boolean; } -export interface MoneyRewards +export interface MoneyRewards { - moneyRewardChancePercent: number - rubCount: MoneyLevels - usdCount: MoneyLevels - eurCount: MoneyLevels + moneyRewardChancePercent: number; + rubCount: MoneyLevels; + usdCount: MoneyLevels; + eurCount: MoneyLevels; } export interface MoneyLevels { - common: MinMax - rare: MinMax - superrare: MinMax + common: MinMax; + rare: MinMax; + superrare: MinMax; } -export interface AmmoRewards +export interface AmmoRewards { - ammoRewardChancePercent: number - ammoRewardBlacklist: Record - ammoRewardValueRangeRub: Record - minStackSize: number -} \ No newline at end of file + ammoRewardChancePercent: number; + ammoRewardBlacklist: Record; + ammoRewardValueRangeRub: Record; + minStackSize: number; +} diff --git a/project/src/models/spt/config/ISeasonalEventConfig.ts b/project/src/models/spt/config/ISeasonalEventConfig.ts index 4d11606b..925a8b8a 100644 --- a/project/src/models/spt/config/ISeasonalEventConfig.ts +++ b/project/src/models/spt/config/ISeasonalEventConfig.ts @@ -4,29 +4,29 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface ISeasonalEventConfig extends IBaseConfig { - kind: "aki-seasonalevents" - enableSeasonalEventDetection: boolean + kind: "aki-seasonalevents"; + enableSeasonalEventDetection: boolean; /** event / botType / equipSlot / itemid */ - eventGear: Record>>> - events: ISeasonalEvent[] + eventGear: Record>>>; + events: ISeasonalEvent[]; eventBotMapping: Record; - eventBossSpawns: Record> - gifterSettings: GifterSetting[] + eventBossSpawns: Record>; + gifterSettings: GifterSetting[]; } export interface ISeasonalEvent { - name: string - type: SeasonalEventType - startDay: number - startMonth: number - endDay: number - endMonth: number + name: string; + type: SeasonalEventType; + startDay: number; + startMonth: number; + endDay: number; + endMonth: number; } export interface GifterSetting { - map: string - zones: string - spawnChance: number -} \ No newline at end of file + map: string; + zones: string; + spawnChance: number; +} diff --git a/project/src/models/spt/config/ITraderConfig.ts b/project/src/models/spt/config/ITraderConfig.ts index 93b4329b..be48cf3b 100644 --- a/project/src/models/spt/config/ITraderConfig.ts +++ b/project/src/models/spt/config/ITraderConfig.ts @@ -4,57 +4,57 @@ import { LootRequest } from "@spt-aki/models/spt/services/LootRequest"; export interface ITraderConfig extends IBaseConfig { - kind: "aki-trader" - updateTime: UpdateTime[] + kind: "aki-trader"; + updateTime: UpdateTime[]; purchasesAreFoundInRaid: boolean; - updateTimeDefault: number - traderPriceMultipler: number + updateTimeDefault: number; + traderPriceMultipler: number; /** Keep track of purchased trader-limited items beyond server restarts to prevent server-restart item scumming */ - persistPurchaseDataInProfile: boolean - fence: FenceConfig + persistPurchaseDataInProfile: boolean; + fence: FenceConfig; } -export interface UpdateTime +export interface UpdateTime { - traderId: string - seconds: number + traderId: string; + seconds: number; } export interface FenceConfig { - discountOptions: DiscountOptions - partialRefreshTimeSeconds: number - partialRefreshChangePercent: number - assortSize: number - maxPresetsPercent: number - itemPriceMult: number - presetPriceMult: number - armorMaxDurabilityPercentMinMax: MinMax - presetMaxDurabilityPercentMinMax: MinMax + discountOptions: DiscountOptions; + partialRefreshTimeSeconds: number; + partialRefreshChangePercent: number; + assortSize: number; + maxPresetsPercent: number; + itemPriceMult: number; + presetPriceMult: number; + armorMaxDurabilityPercentMinMax: MinMax; + presetMaxDurabilityPercentMinMax: MinMax; /** Key: item tpl */ - itemStackSizeOverrideMinMax: Record - itemTypeLimits: Record - regenerateAssortsOnRefresh: boolean + itemStackSizeOverrideMinMax: Record; + itemTypeLimits: Record; + regenerateAssortsOnRefresh: boolean; /** Max rouble price before item is not listed on flea */ - itemCategoryRoublePriceLimit: Record + itemCategoryRoublePriceLimit: Record; /** Each slotid with % to be removed prior to listing on fence */ - presetSlotsToRemoveChancePercent: Record + presetSlotsToRemoveChancePercent: Record; /** Block seasonal items from appearing when season is inactive */ blacklistSeasonalItems: boolean; - blacklist: string[], - coopExtractGift: CoopExtractReward + blacklist: string[]; + coopExtractGift: CoopExtractReward; } export interface CoopExtractReward extends LootRequest { - sendGift: boolean - messageLocaleIds: string[] - giftExpiryHours: number + sendGift: boolean; + messageLocaleIds: string[]; + giftExpiryHours: number; } export interface DiscountOptions { - assortSize: number - itemPriceMult: number - presetPriceMult: number -} \ No newline at end of file + assortSize: number; + itemPriceMult: number; + presetPriceMult: number; +} diff --git a/project/src/models/spt/config/IWeatherConfig.ts b/project/src/models/spt/config/IWeatherConfig.ts index 9fac2f88..08c738b2 100644 --- a/project/src/models/spt/config/IWeatherConfig.ts +++ b/project/src/models/spt/config/IWeatherConfig.ts @@ -4,26 +4,26 @@ import { IBaseConfig } from "@spt-aki/models/spt/config/IBaseConfig"; export interface IWeatherConfig extends IBaseConfig { - kind: "aki-weather" - acceleration: number - weather: Weather + kind: "aki-weather"; + acceleration: number; + weather: Weather; } - -export interface Weather + +export interface Weather { - clouds: WeatherSettings - windSpeed: WeatherSettings - windDirection: WeatherSettings - windGustiness: MinMax - rain: WeatherSettings - rainIntensity: MinMax - fog: WeatherSettings - temp: MinMax - pressure: MinMax + clouds: WeatherSettings; + windSpeed: WeatherSettings; + windDirection: WeatherSettings; + windGustiness: MinMax; + rain: WeatherSettings; + rainIntensity: MinMax; + fog: WeatherSettings; + temp: MinMax; + pressure: MinMax; } export interface WeatherSettings { - values: T[] - weights: number[] + values: T[]; + weights: number[]; } diff --git a/project/src/models/spt/controllers/IBotController.ts b/project/src/models/spt/controllers/IBotController.ts index 20c9b6ec..0d8dc3e3 100644 --- a/project/src/models/spt/controllers/IBotController.ts +++ b/project/src/models/spt/controllers/IBotController.ts @@ -3,7 +3,7 @@ import { IBotBase } from "@spt-aki/models/eft/common/tables/IBotBase"; import { IBotCore } from "@spt-aki/models/eft/common/tables/IBotCore"; import { Difficulty } from "@spt-aki/models/eft/common/tables/IBotType"; -export interface IBotController +export interface IBotController { getBotLimit(type: string): number; getBotDifficulty(type: string, difficulty: string): IBotCore | Difficulty; diff --git a/project/src/models/spt/dialog/ISendMessageDetails.ts b/project/src/models/spt/dialog/ISendMessageDetails.ts index c574f2e0..1365dfbc 100644 --- a/project/src/models/spt/dialog/ISendMessageDetails.ts +++ b/project/src/models/spt/dialog/ISendMessageDetails.ts @@ -3,30 +3,30 @@ import { ISystemData, IUserDialogInfo, MessageContentRagfair } from "@spt-aki/mo import { MessageType } from "@spt-aki/models/enums/MessageType"; import { Traders } from "@spt-aki/models/enums/Traders"; -export interface ISendMessageDetails +export interface ISendMessageDetails { /** Player id */ - recipientId: string + recipientId: string; /** Who is sending this message */ - sender: MessageType + sender: MessageType; /** Optional - leave blank to use sender value */ - dialogType?: MessageType + dialogType?: MessageType; /** Optional - if sender is USER these details are used */ - senderDetails?: IUserDialogInfo + senderDetails?: IUserDialogInfo; /** Optional - the trader sending the message */ - trader?: Traders + trader?: Traders; /** Optional - used in player/system messages, otherwise templateId is used */ - messageText?: string + messageText?: string; /** Optinal - Items to send to player */ items?: Item[]; /** Optional - How long items will be stored in mail before expiry */ - itemsMaxStorageLifetimeSeconds?: number + itemsMaxStorageLifetimeSeconds?: number; /** Optional - Used when sending messages from traders who send text from locale json */ - templateId?: string + templateId?: string; /** Optional - ragfair related */ - systemData?: ISystemData + systemData?: ISystemData; /** Optional - Used by ragfair messages */ - ragfairDetails?: MessageContentRagfair + ragfairDetails?: MessageContentRagfair; /** Optional - Usage not known, unsure of purpose, even dumps dont have it */ - profileChangeEvents?: any[] + profileChangeEvents?: any[]; } diff --git a/project/src/models/spt/generators/IBotGenerator.ts b/project/src/models/spt/generators/IBotGenerator.ts index a15fb52a..0fa0f3a4 100644 --- a/project/src/models/spt/generators/IBotGenerator.ts +++ b/project/src/models/spt/generators/IBotGenerator.ts @@ -3,7 +3,13 @@ import { Chances, Generation, Inventory } from "@spt-aki/models/eft/common/table export interface IBotGenerator { - generateInventory(templateInventory: Inventory, equipmentChances: Chances, generation: Generation, botRole: string, isPmc: boolean): PmcInventory; + generateInventory( + templateInventory: Inventory, + equipmentChances: Chances, + generation: Generation, + botRole: string, + isPmc: boolean, + ): PmcInventory; } export interface IExhaustableArray diff --git a/project/src/models/spt/generators/ILocationGenerator.ts b/project/src/models/spt/generators/ILocationGenerator.ts index 195a8a8b..9ddcb24f 100644 --- a/project/src/models/spt/generators/ILocationGenerator.ts +++ b/project/src/models/spt/generators/ILocationGenerator.ts @@ -1,8 +1,23 @@ import { ILooseLoot, SpawnpointTemplate } from "@spt-aki/models/eft/common/ILooseLoot"; -import { IStaticAmmoDetails, IStaticContainerProps, IStaticForcedProps, IStaticLootDetails } from "@spt-aki/models/eft/common/tables/ILootBase"; +import { + IStaticAmmoDetails, + IStaticContainerProps, + IStaticForcedProps, + IStaticLootDetails, +} from "@spt-aki/models/eft/common/tables/ILootBase"; export interface ILocationGenerator { - generateContainerLoot(containerIn: IStaticContainerProps, staticForced: IStaticForcedProps[], staticLootDist: Record, staticAmmoDist: Record, locationName: string): IStaticContainerProps; - generateDynamicLoot(dynamicLootDist: ILooseLoot, staticAmmoDist: Record, locationName: string): SpawnpointTemplate[]; + generateContainerLoot( + containerIn: IStaticContainerProps, + staticForced: IStaticForcedProps[], + staticLootDist: Record, + staticAmmoDist: Record, + locationName: string, + ): IStaticContainerProps; + generateDynamicLoot( + dynamicLootDist: ILooseLoot, + staticAmmoDist: Record, + locationName: string, + ): SpawnpointTemplate[]; } diff --git a/project/src/models/spt/generators/IRagfairOfferGenerator.ts b/project/src/models/spt/generators/IRagfairOfferGenerator.ts index 0ab65f07..a6aa2906 100644 --- a/project/src/models/spt/generators/IRagfairOfferGenerator.ts +++ b/project/src/models/spt/generators/IRagfairOfferGenerator.ts @@ -4,5 +4,13 @@ import { IRagfairOffer } from "@spt-aki/models/eft/ragfair/IRagfairOffer"; export interface IRagfairOfferGenerator { - createOffer(userID: string, time: number, items: Item[], barterScheme: IBarterScheme[], loyalLevel: number, price: number, sellInOnePiece: boolean): IRagfairOffer; + createOffer( + userID: string, + time: number, + items: Item[], + barterScheme: IBarterScheme[], + loyalLevel: number, + price: number, + sellInOnePiece: boolean, + ): IRagfairOffer; } diff --git a/project/src/models/spt/hideout/ScavCaseRewardCountsAndPrices.ts b/project/src/models/spt/hideout/ScavCaseRewardCountsAndPrices.ts index bf9d1794..8a25efa0 100644 --- a/project/src/models/spt/hideout/ScavCaseRewardCountsAndPrices.ts +++ b/project/src/models/spt/hideout/ScavCaseRewardCountsAndPrices.ts @@ -1,14 +1,14 @@ export interface ScavCaseRewardCountsAndPrices { - Common: RewardCountAndPriceDetails, - Rare: RewardCountAndPriceDetails, - Superrare: RewardCountAndPriceDetails + Common: RewardCountAndPriceDetails; + Rare: RewardCountAndPriceDetails; + Superrare: RewardCountAndPriceDetails; } export interface RewardCountAndPriceDetails { - minCount: number, - maxCount: number, - minPriceRub: number, - maxPriceRub: number -} \ No newline at end of file + minCount: number; + maxCount: number; + minPriceRub: number; + maxPriceRub: number; +} diff --git a/project/src/models/spt/logging/IClientLogRequest.ts b/project/src/models/spt/logging/IClientLogRequest.ts index fab6e8d7..7fe31dc1 100644 --- a/project/src/models/spt/logging/IClientLogRequest.ts +++ b/project/src/models/spt/logging/IClientLogRequest.ts @@ -1,10 +1,10 @@ import { LogLevel } from "@spt-aki/models/spt/logging/LogLevel"; -export interface IClientLogRequest +export interface IClientLogRequest { - Source: string - Level: LogLevel | string - Message: string - Color?: string - BackgroundColor?: string -} \ No newline at end of file + Source: string; + Level: LogLevel | string; + Message: string; + Color?: string; + BackgroundColor?: string; +} diff --git a/project/src/models/spt/logging/LogBackgroundColor.ts b/project/src/models/spt/logging/LogBackgroundColor.ts index 880656a8..56dd102a 100644 --- a/project/src/models/spt/logging/LogBackgroundColor.ts +++ b/project/src/models/spt/logging/LogBackgroundColor.ts @@ -1,5 +1,5 @@ export enum LogBackgroundColor - { +{ DEFAULT = "", BLACK = "blackBG", RED = "redBG", @@ -8,5 +8,5 @@ export enum LogBackgroundColor BLUE = "blueBG", MAGENTA = "magentaBG", CYAN = "cyanBG", - WHITE = "whiteBG" -} \ No newline at end of file + WHITE = "whiteBG", +} diff --git a/project/src/models/spt/logging/LogLevel.ts b/project/src/models/spt/logging/LogLevel.ts index a7517d9b..0723f167 100644 --- a/project/src/models/spt/logging/LogLevel.ts +++ b/project/src/models/spt/logging/LogLevel.ts @@ -1,9 +1,9 @@ -export enum LogLevel - { +export enum LogLevel +{ ERROR = 0, WARN = 1, SUCCESS = 2, INFO = 3, CUSTOM = 4, - DEBUG = 5 -} \ No newline at end of file + DEBUG = 5, +} diff --git a/project/src/models/spt/logging/LogTextColor.ts b/project/src/models/spt/logging/LogTextColor.ts index a5dfbf43..a99a4a1b 100644 --- a/project/src/models/spt/logging/LogTextColor.ts +++ b/project/src/models/spt/logging/LogTextColor.ts @@ -1,5 +1,5 @@ export enum LogTextColor - { +{ BLACK = "black", RED = "red", GREEN = "green", @@ -8,5 +8,5 @@ export enum LogTextColor MAGENTA = "magenta", CYAN = "cyan", WHITE = "white", - GRAY = "" -} \ No newline at end of file + GRAY = "", +} diff --git a/project/src/models/spt/logging/SptLogger.ts b/project/src/models/spt/logging/SptLogger.ts index e41338a9..34bf845b 100644 --- a/project/src/models/spt/logging/SptLogger.ts +++ b/project/src/models/spt/logging/SptLogger.ts @@ -1,8 +1,8 @@ export interface SptLogger { - error: (msg: string | Record) => void - warn: (msg: string | Record) => void - succ?: (msg: string | Record) => void - info: (msg: string | Record) => void - debug: (msg: string | Record) => void -} \ No newline at end of file + error: (msg: string | Record) => void; + warn: (msg: string | Record) => void; + succ?: (msg: string | Record) => void; + info: (msg: string | Record) => void; + debug: (msg: string | Record) => void; +} diff --git a/project/src/models/spt/mod/IModLoader.ts b/project/src/models/spt/mod/IModLoader.ts index c9c41adb..786bdd2e 100644 --- a/project/src/models/spt/mod/IModLoader.ts +++ b/project/src/models/spt/mod/IModLoader.ts @@ -5,4 +5,4 @@ export interface IModLoader load(container: DependencyContainer): void; getModPath(mod: string): string; -} \ No newline at end of file +} diff --git a/project/src/models/spt/mod/NewItemDetails.ts b/project/src/models/spt/mod/NewItemDetails.ts index 4e911d8f..3b9c60c5 100644 --- a/project/src/models/spt/mod/NewItemDetails.ts +++ b/project/src/models/spt/mod/NewItemDetails.ts @@ -9,7 +9,7 @@ export abstract class NewItemDetailsBase handbookPriceRoubles: number; /** Handbook ParentId for the new item */ - handbookParentId : string; + handbookParentId: string; /** * A dictionary for locale settings, key = langauge (e.g. en,cn,es-mx,jp,fr) @@ -29,7 +29,7 @@ export class NewItemFromCloneDetails extends NewItemDetailsBase /** ParentId for the new item (item type) */ parentId: string; - /** + /** * the id the new item should have, leave blank to have one generated for you * This is often known as the TplId, or TemplateId */ @@ -58,4 +58,4 @@ export class CreateItemResult success: boolean; itemId: string; errors: string[]; -} \ No newline at end of file +} diff --git a/project/src/models/spt/ragfair/IRagfairServerPrices.ts b/project/src/models/spt/ragfair/IRagfairServerPrices.ts index 64f50674..aa385dc3 100644 --- a/project/src/models/spt/ragfair/IRagfairServerPrices.ts +++ b/project/src/models/spt/ragfair/IRagfairServerPrices.ts @@ -1,5 +1,5 @@ -export interface IRagfairServerPrices +export interface IRagfairServerPrices { - static: Record - dynamic: Record -} \ No newline at end of file + static: Record; + dynamic: Record; +} diff --git a/project/src/models/spt/repeatable/IQuestTypePool.ts b/project/src/models/spt/repeatable/IQuestTypePool.ts index d724536e..185fbcd9 100644 --- a/project/src/models/spt/repeatable/IQuestTypePool.ts +++ b/project/src/models/spt/repeatable/IQuestTypePool.ts @@ -2,43 +2,43 @@ import { ELocationName } from "@spt-aki/models/enums/ELocationName"; export interface IQuestTypePool { - types: string[], - pool: IQuestPool + types: string[]; + pool: IQuestPool; } export interface IQuestPool { - Exploration: IExplorationPool - Elimination: IEliminationPool - Pickup: IExplorationPool + Exploration: IExplorationPool; + Elimination: IEliminationPool; + Pickup: IExplorationPool; } export interface IExplorationPool { - locations: Partial> + locations: Partial>; } export interface IEliminationPool { - targets: IEliminationTargetPool + targets: IEliminationTargetPool; } export interface IEliminationTargetPool { - Savage?: ITargetLocation - AnyPmc?: ITargetLocation - bossBully?: ITargetLocation - bossGluhar?: ITargetLocation - bossKilla?: ITargetLocation - bossSanitar?: ITargetLocation - bossTagilla?: ITargetLocation - bossKnight?: ITargetLocation - bossZryachiy?: ITargetLocation - bossBoar?: ITargetLocation - bossBoarSniper?: ITargetLocation + Savage?: ITargetLocation; + AnyPmc?: ITargetLocation; + bossBully?: ITargetLocation; + bossGluhar?: ITargetLocation; + bossKilla?: ITargetLocation; + bossSanitar?: ITargetLocation; + bossTagilla?: ITargetLocation; + bossKnight?: ITargetLocation; + bossZryachiy?: ITargetLocation; + bossBoar?: ITargetLocation; + bossBoarSniper?: ITargetLocation; } export interface ITargetLocation { - locations: string[] -} \ No newline at end of file + locations: string[]; +} diff --git a/project/src/models/spt/server/IDatabaseTables.ts b/project/src/models/spt/server/IDatabaseTables.ts index d80ba637..140bd1d6 100644 --- a/project/src/models/spt/server/IDatabaseTables.ts +++ b/project/src/models/spt/server/IDatabaseTables.ts @@ -22,44 +22,44 @@ import { ILocations } from "@spt-aki/models/spt/server/ILocations"; import { IServerBase } from "@spt-aki/models/spt/server/IServerBase"; import { ISettingsBase } from "@spt-aki/models/spt/server/ISettingsBase"; -export interface IDatabaseTables +export interface IDatabaseTables { bots?: { - types: Record - base: IBotBase - core: IBotCore - } + types: Record; + base: IBotBase; + core: IBotCore; + }; hideout?: { - areas: IHideoutArea[] - production: IHideoutProduction[] - scavcase: IHideoutScavCase[] - settings: IHideoutSettingsBase - qte: IQteData[] - } - locales?: ILocaleBase - locations?: ILocations - loot?: ILootBase - match?: IMatch + areas: IHideoutArea[]; + production: IHideoutProduction[]; + scavcase: IHideoutScavCase[]; + settings: IHideoutSettingsBase; + qte: IQteData[]; + }; + locales?: ILocaleBase; + locations?: ILocations; + loot?: ILootBase; + match?: IMatch; templates?: { - character: string[] - items: Record - quests: Record - repeatableQuests: IRepeatableQuestDatabase - handbook: IHandbookBase - customization: Record + character: string[]; + items: Record; + quests: Record; + repeatableQuests: IRepeatableQuestDatabase; + handbook: IHandbookBase; + customization: Record; /** The profile templates listed in the launcher on profile creation, split by account type (e.g. Standard) then side (e.g. bear/usec) */ - profiles: IProfileTemplates + profiles: IProfileTemplates; /** Flea prices of items - gathered from online flea market dump */ - prices: Record + prices: Record; /** Default equipment loadouts that show on main inventory screen */ - defaultEquipmentPresets: IEquipmentBuild[] - } - traders?: Record + defaultEquipmentPresets: IEquipmentBuild[]; + }; + traders?: Record; - globals?: IGlobals - server?: IServerBase - settings?: ISettingsBase -} \ No newline at end of file + globals?: IGlobals; + server?: IServerBase; + settings?: ISettingsBase; +} diff --git a/project/src/models/spt/server/ILocaleBase.ts b/project/src/models/spt/server/ILocaleBase.ts index 611d99b5..46498aec 100644 --- a/project/src/models/spt/server/ILocaleBase.ts +++ b/project/src/models/spt/server/ILocaleBase.ts @@ -1,7 +1,7 @@ -export interface ILocaleBase +export interface ILocaleBase { - global: Record> - menu: Record - languages: Record - server: Record> -} \ No newline at end of file + global: Record>; + menu: Record; + languages: Record; + server: Record>; +} diff --git a/project/src/models/spt/server/ILocations.ts b/project/src/models/spt/server/ILocations.ts index b663341b..c8798863 100644 --- a/project/src/models/spt/server/ILocations.ts +++ b/project/src/models/spt/server/ILocations.ts @@ -2,31 +2,31 @@ import { ILocationBase } from "@spt-aki/models/eft/common/ILocationBase"; import { ILooseLoot } from "@spt-aki/models/eft/common/ILooseLoot"; import { ILocationsBase } from "@spt-aki/models/eft/common/tables/ILocationsBase"; -export interface ILocations +export interface ILocations { - bigmap?: ILocationData - develop?: ILocationData + bigmap?: ILocationData; + develop?: ILocationData; // eslint-disable-next-line @typescript-eslint/naming-convention - factory4_day?: ILocationData + factory4_day?: ILocationData; // eslint-disable-next-line @typescript-eslint/naming-convention - factory4_night?: ILocationData - hideout?: ILocationData - interchange?: ILocationData - laboratory?: ILocationData - lighthouse?: ILocationData - privatearea?: ILocationData - rezervbase?: ILocationData - shoreline?: ILocationData - suburbs?: ILocationData - tarkovstreets?: ILocationData - terminal?: ILocationData - town?: ILocationData - woods?: ILocationData - base?: ILocationsBase + factory4_night?: ILocationData; + hideout?: ILocationData; + interchange?: ILocationData; + laboratory?: ILocationData; + lighthouse?: ILocationData; + privatearea?: ILocationData; + rezervbase?: ILocationData; + shoreline?: ILocationData; + suburbs?: ILocationData; + tarkovstreets?: ILocationData; + terminal?: ILocationData; + town?: ILocationData; + woods?: ILocationData; + base?: ILocationsBase; } export interface ILocationData { - base: ILocationBase - looseLoot?: ILooseLoot -} \ No newline at end of file + base: ILocationBase; + looseLoot?: ILooseLoot; +} diff --git a/project/src/models/spt/server/IServerBase.ts b/project/src/models/spt/server/IServerBase.ts index a5d1b98c..ebaf84ad 100644 --- a/project/src/models/spt/server/IServerBase.ts +++ b/project/src/models/spt/server/IServerBase.ts @@ -1,5 +1,5 @@ -export interface IServerBase +export interface IServerBase { - ip: string - port: number -} \ No newline at end of file + ip: string; + port: number; +} diff --git a/project/src/models/spt/server/ISettingsBase.ts b/project/src/models/spt/server/ISettingsBase.ts index acaef969..0fd27a0d 100644 --- a/project/src/models/spt/server/ISettingsBase.ts +++ b/project/src/models/spt/server/ISettingsBase.ts @@ -1,64 +1,64 @@ export interface ISettingsBase { - config: Config + config: Config; } export interface Config { - AFKTimeoutSeconds: number - AdditionalRandomDelaySeconds: number - ClientSendRateLimit: number - CriticalRetriesCount: number - DefaultRetriesCount: number - FirstCycleDelaySeconds: number - FramerateLimit: FramerateLimit - GroupStatusInterval: number - GroupStatusButtonInterval: number - KeepAliveInterval: number - LobbyKeepAliveInterval: number - Mark502and504AsNonImportant: boolean - MemoryManagementSettings: MemoryManagementSettings - NVidiaHighlights: boolean - NextCycleDelaySeconds: number - PingServerResultSendInterval: number - PingServersInterval: number - ReleaseProfiler: ReleaseProfiler - RequestConfirmationTimeouts: number[] - RequestsMadeThroughLobby: string[] - SecondCycleDelaySeconds: number - ShouldEstablishLobbyConnection: boolean - TurnOffLogging: boolean - WeaponOverlapDistanceCulling: number - WebDiagnosticsEnabled: boolean - NetworkStateView: INetworkStateView + AFKTimeoutSeconds: number; + AdditionalRandomDelaySeconds: number; + ClientSendRateLimit: number; + CriticalRetriesCount: number; + DefaultRetriesCount: number; + FirstCycleDelaySeconds: number; + FramerateLimit: FramerateLimit; + GroupStatusInterval: number; + GroupStatusButtonInterval: number; + KeepAliveInterval: number; + LobbyKeepAliveInterval: number; + Mark502and504AsNonImportant: boolean; + MemoryManagementSettings: MemoryManagementSettings; + NVidiaHighlights: boolean; + NextCycleDelaySeconds: number; + PingServerResultSendInterval: number; + PingServersInterval: number; + ReleaseProfiler: ReleaseProfiler; + RequestConfirmationTimeouts: number[]; + RequestsMadeThroughLobby: string[]; + SecondCycleDelaySeconds: number; + ShouldEstablishLobbyConnection: boolean; + TurnOffLogging: boolean; + WeaponOverlapDistanceCulling: number; + WebDiagnosticsEnabled: boolean; + NetworkStateView: INetworkStateView; } export interface FramerateLimit { - MaxFramerateGameLimit: number - MaxFramerateLobbyLimit: number - MinFramerateLimit: number + MaxFramerateGameLimit: number; + MaxFramerateLobbyLimit: number; + MinFramerateLimit: number; } export interface MemoryManagementSettings { - AggressiveGC: boolean - GigabytesRequiredToDisableGCDuringRaid: number - HeapPreAllocationEnabled: boolean - HeapPreAllocationMB: number - OverrideRamCleanerSettings: boolean - RamCleanerEnabled: boolean + AggressiveGC: boolean; + GigabytesRequiredToDisableGCDuringRaid: number; + HeapPreAllocationEnabled: boolean; + HeapPreAllocationMB: number; + OverrideRamCleanerSettings: boolean; + RamCleanerEnabled: boolean; } export interface ReleaseProfiler { - Enabled: boolean - MaxRecords: number - RecordTriggerValue: number + Enabled: boolean; + MaxRecords: number; + RecordTriggerValue: number; } export interface INetworkStateView { - LossThreshold: number - RttThreshold: number -} \ No newline at end of file + LossThreshold: number; + RttThreshold: number; +} diff --git a/project/src/models/spt/services/CustomPreset.ts b/project/src/models/spt/services/CustomPreset.ts index e4d865b2..b385f928 100644 --- a/project/src/models/spt/services/CustomPreset.ts +++ b/project/src/models/spt/services/CustomPreset.ts @@ -2,6 +2,6 @@ import { IPreset } from "@spt-aki/models/eft/common/IGlobals"; export interface CustomPreset { - key: string, - preset: IPreset -} \ No newline at end of file + key: string; + preset: IPreset; +} diff --git a/project/src/models/spt/services/CustomTraderAssortData.ts b/project/src/models/spt/services/CustomTraderAssortData.ts index 18058d78..19ecc32c 100644 --- a/project/src/models/spt/services/CustomTraderAssortData.ts +++ b/project/src/models/spt/services/CustomTraderAssortData.ts @@ -3,6 +3,6 @@ import { Traders } from "@spt-aki/models/enums/Traders"; export interface CustomTraderAssortData { - traderId: Traders, - assorts: ITraderAssort -} \ No newline at end of file + traderId: Traders; + assorts: ITraderAssort; +} diff --git a/project/src/models/spt/services/LootItem.ts b/project/src/models/spt/services/LootItem.ts index 0bd736dd..e75dd0d8 100644 --- a/project/src/models/spt/services/LootItem.ts +++ b/project/src/models/spt/services/LootItem.ts @@ -4,4 +4,4 @@ export class LootItem tpl: string; isPreset: boolean; stackCount: number; -} \ No newline at end of file +} diff --git a/project/src/models/spt/services/LootRequest.ts b/project/src/models/spt/services/LootRequest.ts index 6420d794..442b9659 100644 --- a/project/src/models/spt/services/LootRequest.ts +++ b/project/src/models/spt/services/LootRequest.ts @@ -2,14 +2,14 @@ import { MinMax } from "@spt-aki/models/common/MinMax"; export interface LootRequest { - presetCount: MinMax - itemCount: MinMax - weaponCrateCount: MinMax - itemBlacklist: string[] - itemTypeWhitelist: string[] + presetCount: MinMax; + itemCount: MinMax; + weaponCrateCount: MinMax; + itemBlacklist: string[]; + itemTypeWhitelist: string[]; /** key: item base type: value: max count */ - itemLimits: Record - itemStackLimits: Record - armorLevelWhitelist: number[] - allowBossItems: boolean -} \ No newline at end of file + itemLimits: Record; + itemStackLimits: Record; + armorLevelWhitelist: number[]; + allowBossItems: boolean; +} diff --git a/project/src/models/spt/utils/IAsyncQueue.ts b/project/src/models/spt/utils/IAsyncQueue.ts index d511b050..c962f3cf 100644 --- a/project/src/models/spt/utils/IAsyncQueue.ts +++ b/project/src/models/spt/utils/IAsyncQueue.ts @@ -1,6 +1,6 @@ import { ICommand } from "@spt-aki/models/spt/utils/ICommand"; -export interface IAsyncQueue +export interface IAsyncQueue { - waitFor(command: ICommand): Promise -} \ No newline at end of file + waitFor(command: ICommand): Promise; +} diff --git a/project/src/models/spt/utils/ICommand.ts b/project/src/models/spt/utils/ICommand.ts index 9d13fd67..87c7692f 100644 --- a/project/src/models/spt/utils/ICommand.ts +++ b/project/src/models/spt/utils/ICommand.ts @@ -1,5 +1,5 @@ -export interface ICommand +export interface ICommand { - uuid: string - cmd: () => Promise -} \ No newline at end of file + uuid: string; + cmd: () => Promise; +} diff --git a/project/src/models/spt/utils/ILogger.ts b/project/src/models/spt/utils/ILogger.ts index a1e42404..f41acb17 100644 --- a/project/src/models/spt/utils/ILogger.ts +++ b/project/src/models/spt/utils/ILogger.ts @@ -2,11 +2,15 @@ import { Daum } from "@spt-aki/models/eft/itemEvent/IItemEventRouterRequest"; import { LogBackgroundColor } from "@spt-aki/models/spt/logging/LogBackgroundColor"; import { LogTextColor } from "@spt-aki/models/spt/logging/LogTextColor"; -export interface ILogger +export interface ILogger { writeToLogFile(data: string | Daum): void; log(data: string | Record | Error, color: string, backgroundColor?: string): void; - logWithColor(data: string | Record, textColor: LogTextColor, backgroundColor?: LogBackgroundColor): void; + logWithColor( + data: string | Record, + textColor: LogTextColor, + backgroundColor?: LogBackgroundColor, + ): void; error(data: string): void; @@ -14,5 +18,5 @@ export interface ILogger success(data: string): void; info(data: string): void; - debug(data: string| Record, onlyShowInConsole?: boolean): void; + debug(data: string | Record, onlyShowInConsole?: boolean): void; } From b90fb8c8b99ca892c191e74ba554b988b2fd68cf Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:12:17 -0500 Subject: [PATCH 30/41] Formatting for routers. --- project/src/routers/EventOutputHolder.ts | 28 ++-- project/src/routers/HttpRouter.ts | 19 ++- project/src/routers/ImageRouter.ts | 7 +- project/src/routers/ItemEventRouter.ts | 17 +-- .../src/routers/dynamic/BotDynamicRouter.ts | 24 ++- .../routers/dynamic/BundleDynamicRouter.ts | 15 +- .../dynamic/CustomizationDynamicRouter.ts | 16 +- .../src/routers/dynamic/DataDynamicRouter.ts | 24 ++- .../src/routers/dynamic/HttpDynamicRouter.ts | 22 ++- .../routers/dynamic/InraidDynamicRouter.ts | 17 +-- .../routers/dynamic/LocationDynamicRouter.ts | 17 +-- .../routers/dynamic/NotifierDynamicRouter.ts | 25 ++- .../routers/dynamic/TraderDynamicRouter.ts | 18 +-- .../CustomizationItemEventRouter.ts | 19 ++- .../item_events/HealthItemEventRouter.ts | 19 ++- .../item_events/HideoutItemEventRouter.ts | 19 ++- .../item_events/InsuranceItemEventRouter.ts | 20 ++- .../item_events/InventoryItemEventRouter.ts | 20 ++- .../item_events/NoteItemEventRouter.ts | 23 +-- .../item_events/PresetBuildItemEventRouter.ts | 19 ++- .../item_events/QuestItemEventRouter.ts | 25 +-- .../item_events/RagfairItemEventRouter.ts | 19 ++- .../item_events/RepairItemEventRouter.ts | 19 ++- .../item_events/TradeItemEventRouter.ts | 19 ++- .../item_events/WishlistItemEventRouter.ts | 19 ++- .../routers/save_load/HealthSaveLoadRouter.ts | 20 +-- .../routers/save_load/InraidSaveLoadRouter.ts | 12 +- .../save_load/InsuranceSaveLoadRouter.ts | 10 +- .../save_load/ProfileSaveLoadRouter.ts | 12 +- .../routers/serializers/BundleSerializer.ts | 6 +- .../routers/serializers/ImageSerializer.ts | 8 +- .../routers/serializers/NotifySerializer.ts | 8 +- project/src/routers/static/BotStaticRouter.ts | 17 +-- .../src/routers/static/BundleStaticRouter.ts | 17 +-- .../routers/static/ClientLogStaticRouter.ts | 11 +- .../static/CustomizationStaticRouter.ts | 17 +-- .../src/routers/static/DataStaticRouter.ts | 72 ++++----- .../src/routers/static/DialogStaticRouter.ts | 117 ++++++--------- .../src/routers/static/GameStaticRouter.ts | 62 ++++---- .../src/routers/static/HealthStaticRouter.ts | 22 ++- .../src/routers/static/InraidStaticRouter.ts | 37 ++--- .../routers/static/InsuranceStaticRouter.ts | 17 +-- .../routers/static/ItemEventStaticRouter.ts | 17 +-- .../routers/static/LauncherStaticRouter.ts | 79 ++++------ .../routers/static/LocationStaticRouter.ts | 20 ++- .../src/routers/static/MatchStaticRouter.ts | 142 ++++++++---------- .../routers/static/NotifierStaticRouter.ts | 26 ++-- .../src/routers/static/PresetStaticRouter.ts | 19 ++- .../src/routers/static/ProfileStaticRouter.ts | 96 ++++++------ .../src/routers/static/QuestStaticRouter.ts | 26 ++-- .../src/routers/static/RagfairStaticRouter.ts | 59 ++++---- .../src/routers/static/TraderStaticRouter.ts | 19 ++- .../src/routers/static/WeatherStaticRouter.ts | 18 +-- 53 files changed, 708 insertions(+), 767 deletions(-) diff --git a/project/src/routers/EventOutputHolder.ts b/project/src/routers/EventOutputHolder.ts index 2e9ddf49..b020371d 100644 --- a/project/src/routers/EventOutputHolder.ts +++ b/project/src/routers/EventOutputHolder.ts @@ -12,19 +12,19 @@ import { TimeUtil } from "@spt-aki/utils/TimeUtil"; export class EventOutputHolder { /** What has client been informed of this game session */ - protected clientActiveSessionStorage: Record = {}; + protected clientActiveSessionStorage: Record = {}; constructor( @inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("ProfileHelper") protected profileHelper: ProfileHelper, - @inject("TimeUtil") protected timeUtil: TimeUtil + @inject("TimeUtil") protected timeUtil: TimeUtil, ) {} // TODO REMEMBER TO CHANGE OUTPUT protected output: IItemEventRouterResponse = { warnings: [], - profileChanges: {} + profileChanges: {}, }; public getOutput(sessionID: string): IItemEventRouterResponse @@ -57,20 +57,20 @@ export class EventOutputHolder items: { new: [], change: [], - del: [] + del: [], }, production: {}, improvements: {}, skills: { Common: [], Mastering: [], - Points: 0 + Points: 0, }, health: this.jsonUtil.clone(pmcData.Health), traderRelations: {}, - //changedHideoutStashes: {}, + // changedHideoutStashes: {}, recipeUnlocked: {}, - questsStatus: [] + questsStatus: [], }; } @@ -89,7 +89,9 @@ export class EventOutputHolder profileChanges.skills.Mastering = this.jsonUtil.clone(pmcData.Skills.Mastering); // Clone productions to ensure we preseve the profile jsons data - profileChanges.production = this.getProductionsFromProfileAndFlagComplete(this.jsonUtil.clone(pmcData.Hideout.Production)); + profileChanges.production = this.getProductionsFromProfileAndFlagComplete( + this.jsonUtil.clone(pmcData.Hideout.Production), + ); profileChanges.improvements = this.jsonUtil.clone(this.getImprovementsFromProfileAndFlagComplete(pmcData)); profileChanges.traderRelations = this.constructTraderRelations(pmcData.TradersInfo); } @@ -111,13 +113,13 @@ export class EventOutputHolder disabled: baseData.disabled, loyalty: baseData.loyaltyLevel, standing: baseData.standing, - unlocked: baseData.unlocked + unlocked: baseData.unlocked, }; } return result; } - + /** * Return all hideout Improvements from player profile, adjust completed Improvements' completed property to be true * @param pmcData Player profile @@ -149,7 +151,9 @@ export class EventOutputHolder * @param pmcData Player profile * @returns dictionary of hideout productions */ - protected getProductionsFromProfileAndFlagComplete(productions: Record): Record + protected getProductionsFromProfileAndFlagComplete( + productions: Record, + ): Record { for (const productionKey in productions) { @@ -177,7 +181,7 @@ export class EventOutputHolder // Flag started craft as having been seen by client if (production.Progress > 0 && !this.clientActiveSessionStorage[productionKey]?.clientInformed) { - this.clientActiveSessionStorage[productionKey] = { clientInformed: true }; + this.clientActiveSessionStorage[productionKey] = {clientInformed: true}; } } diff --git a/project/src/routers/HttpRouter.ts b/project/src/routers/HttpRouter.ts index 9267b590..3e2f41f2 100644 --- a/project/src/routers/HttpRouter.ts +++ b/project/src/routers/HttpRouter.ts @@ -8,11 +8,11 @@ export class HttpRouter { constructor( @injectAll("StaticRoutes") protected staticRouters: StaticRouter[], - @injectAll("DynamicRoutes") protected dynamicRoutes: DynamicRouter[] + @injectAll("DynamicRoutes") protected dynamicRoutes: DynamicRouter[], ) - { } + {} - protected groupBy(list: T[], keyGetter: (t:T) => string): Map + protected groupBy(list: T[], keyGetter: (t: T) => string): Map { const map: Map = new Map(); for (const item of list) @@ -56,7 +56,14 @@ export class HttpRouter return wrapper.output; } - protected handleRoute(url: string, info: any, sessionID: string, wrapper: ResponseWrapper, routers: Router[], dynamic: boolean): boolean + protected handleRoute( + url: string, + info: any, + sessionID: string, + wrapper: ResponseWrapper, + routers: Router[], + dynamic: boolean, + ): boolean { let matched = false; for (const route of routers) @@ -81,7 +88,7 @@ export class HttpRouter class ResponseWrapper { constructor( - public output: string + public output: string, ) {} -} \ No newline at end of file +} diff --git a/project/src/routers/ImageRouter.ts b/project/src/routers/ImageRouter.ts index 4fc8fe38..b6814c15 100644 --- a/project/src/routers/ImageRouter.ts +++ b/project/src/routers/ImageRouter.ts @@ -11,16 +11,15 @@ export class ImageRouter constructor( @inject("VFS") protected vfs: VFS, @inject("ImageRouteService") protected imageRouteService: ImageRouteService, - @inject("HttpFileUtil") protected httpFileUtil: HttpFileUtil + @inject("HttpFileUtil") protected httpFileUtil: HttpFileUtil, ) - { } + {} public addRoute(key: string, valueToAdd: string): void { this.imageRouteService.addRoute(key, valueToAdd); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public sendImage(sessionID: string, req: IncomingMessage, resp: ServerResponse, body: any): void { // remove file extension @@ -37,4 +36,4 @@ export class ImageRouter { return "IMAGE"; } -} \ No newline at end of file +} diff --git a/project/src/routers/ItemEventRouter.ts b/project/src/routers/ItemEventRouter.ts index 84fa77d5..bd1fd158 100644 --- a/project/src/routers/ItemEventRouter.ts +++ b/project/src/routers/ItemEventRouter.ts @@ -9,24 +9,23 @@ import { EventOutputHolder } from "@spt-aki/routers/EventOutputHolder"; import { LocalisationService } from "@spt-aki/services/LocalisationService"; @injectable() -export class ItemEventRouter +export class ItemEventRouter { constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("ProfileHelper") protected profileHelper: ProfileHelper, @injectAll("IERouters") protected itemEventRouters: ItemEventRouterDefinition[], @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder - ) - { } + @inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder, + ) + {} /** - * * @param info Event request * @param sessionID Session id * @returns Item response */ - public handleEvents(info: IItemEventRouterRequest, sessionID: string): IItemEventRouterResponse + public handleEvents(info: IItemEventRouterRequest, sessionID: string): IItemEventRouterResponse { this.eventOutputHolder.resetOutput(sessionID); @@ -36,13 +35,13 @@ export class ItemEventRouter { const pmcData = this.profileHelper.getPmcProfile(sessionID); - const eventRouter = this.itemEventRouters.find(r => r.canHandle(body.Action)); - if (eventRouter) + const eventRouter = this.itemEventRouters.find((r) => r.canHandle(body.Action)); + if (eventRouter) { this.logger.debug(`event: ${body.Action}`); result = eventRouter.handleItemEvent(body.Action, pmcData, body, sessionID); } - else + else { this.logger.error(this.localisationService.getText("event-unhandled_event", body.Action)); this.logger.writeToLogFile(body); diff --git a/project/src/routers/dynamic/BotDynamicRouter.ts b/project/src/routers/dynamic/BotDynamicRouter.ts index 50e110f3..6f374792 100644 --- a/project/src/routers/dynamic/BotDynamicRouter.ts +++ b/project/src/routers/dynamic/BotDynamicRouter.ts @@ -4,47 +4,43 @@ import { BotCallbacks } from "@spt-aki/callbacks/BotCallbacks"; import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() -export class BotDynamicRouter extends DynamicRouter +export class BotDynamicRouter extends DynamicRouter { constructor( - @inject("BotCallbacks") protected botCallbacks: BotCallbacks - ) + @inject("BotCallbacks") protected botCallbacks: BotCallbacks, + ) { super( [ new RouteAction( "/singleplayer/settings/bot/limit/", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.botCallbacks.getBotLimit(url, info, sessionID); - } + }, ), new RouteAction( "/singleplayer/settings/bot/difficulty/", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.botCallbacks.getBotDifficulty(url, info, sessionID); - } + }, ), new RouteAction( "/singleplayer/settings/bot/maxCap", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.botCallbacks.getBotCap(); - } + }, ), new RouteAction( "/singleplayer/settings/bot/getBotBehaviours/", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.botCallbacks.getBotBehaviours(); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/dynamic/BundleDynamicRouter.ts b/project/src/routers/dynamic/BundleDynamicRouter.ts index 1d8f3a06..c365c98d 100644 --- a/project/src/routers/dynamic/BundleDynamicRouter.ts +++ b/project/src/routers/dynamic/BundleDynamicRouter.ts @@ -4,23 +4,22 @@ import { BundleCallbacks } from "@spt-aki/callbacks/BundleCallbacks"; import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() -export class BundleDynamicRouter extends DynamicRouter +export class BundleDynamicRouter extends DynamicRouter { constructor( - @inject("BundleCallbacks") protected bundleCallbacks: BundleCallbacks - ) + @inject("BundleCallbacks") protected bundleCallbacks: BundleCallbacks, + ) { super( [ new RouteAction( ".bundle", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.bundleCallbacks.getBundle(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/dynamic/CustomizationDynamicRouter.ts b/project/src/routers/dynamic/CustomizationDynamicRouter.ts index 0110d63e..75e8d516 100644 --- a/project/src/routers/dynamic/CustomizationDynamicRouter.ts +++ b/project/src/routers/dynamic/CustomizationDynamicRouter.ts @@ -4,24 +4,22 @@ import { CustomizationCallbacks } from "@spt-aki/callbacks/CustomizationCallback import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() -export class CustomizationDynamicRouter extends DynamicRouter +export class CustomizationDynamicRouter extends DynamicRouter { constructor( - @inject("CustomizationCallbacks") protected customizationCallbacks: CustomizationCallbacks - ) + @inject("CustomizationCallbacks") protected customizationCallbacks: CustomizationCallbacks, + ) { super( [ new RouteAction( "/client/trading/customization/", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.customizationCallbacks.getTraderSuits(url, info, sessionID); - } - ) - - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/dynamic/DataDynamicRouter.ts b/project/src/routers/dynamic/DataDynamicRouter.ts index cf71b6bc..9f364c17 100644 --- a/project/src/routers/dynamic/DataDynamicRouter.ts +++ b/project/src/routers/dynamic/DataDynamicRouter.ts @@ -4,38 +4,36 @@ import { DataCallbacks } from "@spt-aki/callbacks/DataCallbacks"; import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() -export class DataDynamicRouter extends DynamicRouter +export class DataDynamicRouter extends DynamicRouter { constructor( - @inject("DataCallbacks") protected dataCallbacks: DataCallbacks - ) + @inject("DataCallbacks") protected dataCallbacks: DataCallbacks, + ) { super( [ new RouteAction( "/client/menu/locale/", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getLocalesMenu(url, info, sessionID); - } + }, ), new RouteAction( "/client/locale/", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getLocalesGlobal(url, info, sessionID); - } + }, ), new RouteAction( - "/client/items/prices/", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/items/prices/", + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getItemPrices(url, info, sessionID); - }) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/dynamic/HttpDynamicRouter.ts b/project/src/routers/dynamic/HttpDynamicRouter.ts index f46a4252..4fd9357e 100644 --- a/project/src/routers/dynamic/HttpDynamicRouter.ts +++ b/project/src/routers/dynamic/HttpDynamicRouter.ts @@ -4,40 +4,36 @@ import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; import { ImageRouter } from "@spt-aki/routers/ImageRouter"; @injectable() -export class HttpDynamicRouter extends DynamicRouter +export class HttpDynamicRouter extends DynamicRouter { constructor( - @inject("ImageRouter") protected imageRouter: ImageRouter - ) + @inject("ImageRouter") protected imageRouter: ImageRouter, + ) { super( [ new RouteAction( ".jpg", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.imageRouter.getImage(); - } + }, ), new RouteAction( ".png", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.imageRouter.getImage(); - } + }, ), new RouteAction( ".ico", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.imageRouter.getImage(); - } - ) - - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/dynamic/InraidDynamicRouter.ts b/project/src/routers/dynamic/InraidDynamicRouter.ts index e8e9eac0..f8e1a9c2 100644 --- a/project/src/routers/dynamic/InraidDynamicRouter.ts +++ b/project/src/routers/dynamic/InraidDynamicRouter.ts @@ -4,28 +4,27 @@ import { InraidCallbacks } from "@spt-aki/callbacks/InraidCallbacks"; import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() -export class InraidDynamicRouter extends DynamicRouter +export class InraidDynamicRouter extends DynamicRouter { constructor( - @inject("InraidCallbacks") protected inraidCallbacks: InraidCallbacks - ) + @inject("InraidCallbacks") protected inraidCallbacks: InraidCallbacks, + ) { super( [ new RouteAction( "/client/location/getLocalloot", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.inraidCallbacks.registerPlayer(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } - public override getTopLevelRoute(): string + public override getTopLevelRoute(): string { return "aki-name"; } -} \ No newline at end of file +} diff --git a/project/src/routers/dynamic/LocationDynamicRouter.ts b/project/src/routers/dynamic/LocationDynamicRouter.ts index 06e41c30..798ece9d 100644 --- a/project/src/routers/dynamic/LocationDynamicRouter.ts +++ b/project/src/routers/dynamic/LocationDynamicRouter.ts @@ -4,28 +4,27 @@ import { LocationCallbacks } from "@spt-aki/callbacks/LocationCallbacks"; import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() -export class LocationDynamicRouter extends DynamicRouter +export class LocationDynamicRouter extends DynamicRouter { constructor( - @inject("LocationCallbacks") protected locationCallbacks: LocationCallbacks - ) + @inject("LocationCallbacks") protected locationCallbacks: LocationCallbacks, + ) { super( [ new RouteAction( "/client/location/getLocalloot", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, _output: string): any => { return this.locationCallbacks.getLocation(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } - public override getTopLevelRoute(): string + public override getTopLevelRoute(): string { return "aki-loot"; } -} \ No newline at end of file +} diff --git a/project/src/routers/dynamic/NotifierDynamicRouter.ts b/project/src/routers/dynamic/NotifierDynamicRouter.ts index f7a4e0d3..261c2a20 100644 --- a/project/src/routers/dynamic/NotifierDynamicRouter.ts +++ b/project/src/routers/dynamic/NotifierDynamicRouter.ts @@ -4,48 +4,43 @@ import { NotifierCallbacks } from "@spt-aki/callbacks/NotifierCallbacks"; import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() -export class NotifierDynamicRouter extends DynamicRouter +export class NotifierDynamicRouter extends DynamicRouter { constructor( - @inject("NotifierCallbacks") protected notifierCallbacks: NotifierCallbacks - ) + @inject("NotifierCallbacks") protected notifierCallbacks: NotifierCallbacks, + ) { super( [ new RouteAction( "/?last_id", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.notifierCallbacks.notify(url, info, sessionID); - } + }, ), new RouteAction( "/notifierServer", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.notifierCallbacks.notify(url, info, sessionID); - } + }, ), new RouteAction( "/push/notifier/get/", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.notifierCallbacks.getNotifier(url, info, sessionID); - } + }, ), new RouteAction( "/push/notifier/getwebsocket/", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.notifierCallbacks.getNotifier(url, info, sessionID); - } - ) - ] + }, + ), + ], ); - } -} \ No newline at end of file +} diff --git a/project/src/routers/dynamic/TraderDynamicRouter.ts b/project/src/routers/dynamic/TraderDynamicRouter.ts index c1bc2118..f8f821a4 100644 --- a/project/src/routers/dynamic/TraderDynamicRouter.ts +++ b/project/src/routers/dynamic/TraderDynamicRouter.ts @@ -4,31 +4,29 @@ import { TraderCallbacks } from "@spt-aki/callbacks/TraderCallbacks"; import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() -export class TraderDynamicRouter extends DynamicRouter +export class TraderDynamicRouter extends DynamicRouter { constructor( - @inject("TraderCallbacks") protected traderCallbacks: TraderCallbacks - ) + @inject("TraderCallbacks") protected traderCallbacks: TraderCallbacks, + ) { super( [ new RouteAction( "/client/trading/api/getTrader/", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.traderCallbacks.getTrader(url, info, sessionID); - } + }, ), new RouteAction( "/client/trading/api/getTraderAssort/", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.traderCallbacks.getAssort(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/CustomizationItemEventRouter.ts b/project/src/routers/item_events/CustomizationItemEventRouter.ts index 5f56ffa6..b6a6dc1e 100644 --- a/project/src/routers/item_events/CustomizationItemEventRouter.ts +++ b/project/src/routers/item_events/CustomizationItemEventRouter.ts @@ -6,24 +6,29 @@ import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; @injectable() -export class CustomizationItemEventRouter extends ItemEventRouterDefinition +export class CustomizationItemEventRouter extends ItemEventRouterDefinition { constructor( - @inject("CustomizationCallbacks") protected customizationCallbacks: CustomizationCallbacks // TODO: delay required - ) + @inject("CustomizationCallbacks") protected customizationCallbacks: CustomizationCallbacks, // TODO: delay required + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ new HandledRoute("CustomizationWear", false), - new HandledRoute("CustomizationBuy", false) + new HandledRoute("CustomizationBuy", false), ]; } - public override handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + url: string, + pmcData: IPmcData, + body: any, + sessionID: string, + ): IItemEventRouterResponse { switch (url) { @@ -33,4 +38,4 @@ export class CustomizationItemEventRouter extends ItemEventRouterDefinition return this.customizationCallbacks.buyClothing(pmcData, body, sessionID); } } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/HealthItemEventRouter.ts b/project/src/routers/item_events/HealthItemEventRouter.ts index b287ac1d..807e9877 100644 --- a/project/src/routers/item_events/HealthItemEventRouter.ts +++ b/project/src/routers/item_events/HealthItemEventRouter.ts @@ -6,25 +6,30 @@ import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; @injectable() -export class HealthItemEventRouter extends ItemEventRouterDefinition +export class HealthItemEventRouter extends ItemEventRouterDefinition { constructor( - @inject("HealthCallbacks") protected healthCallbacks: HealthCallbacks // TODO: delay required - ) + @inject("HealthCallbacks") protected healthCallbacks: HealthCallbacks, // TODO: delay required + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ new HandledRoute("Eat", false), new HandledRoute("Heal", false), - new HandledRoute("RestoreHealth", false) + new HandledRoute("RestoreHealth", false), ]; } - public override handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + url: string, + pmcData: IPmcData, + body: any, + sessionID: string, + ): IItemEventRouterResponse { switch (url) { @@ -36,4 +41,4 @@ export class HealthItemEventRouter extends ItemEventRouterDefinition return this.healthCallbacks.healthTreatment(pmcData, body, sessionID); } } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/HideoutItemEventRouter.ts b/project/src/routers/item_events/HideoutItemEventRouter.ts index 0dd12165..b4a6d3f2 100644 --- a/project/src/routers/item_events/HideoutItemEventRouter.ts +++ b/project/src/routers/item_events/HideoutItemEventRouter.ts @@ -7,16 +7,16 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve import { HideoutEventActions } from "@spt-aki/models/enums/HideoutEventActions"; @injectable() -export class HideoutItemEventRouter extends ItemEventRouterDefinition +export class HideoutItemEventRouter extends ItemEventRouterDefinition { constructor( - @inject("HideoutCallbacks") protected hideoutCallbacks: HideoutCallbacks - ) + @inject("HideoutCallbacks") protected hideoutCallbacks: HideoutCallbacks, + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ new HandledRoute(HideoutEventActions.HIDEOUT_UPGRADE, false), @@ -30,11 +30,16 @@ export class HideoutItemEventRouter extends ItemEventRouterDefinition new HandledRoute(HideoutEventActions.HIDEOUT_TAKE_PRODUCTION, false), new HandledRoute(HideoutEventActions.HIDEOUT_RECORD_SHOOTING_RANGE_POINTS, false), new HandledRoute(HideoutEventActions.HIDEOUT_IMPROVE_AREA, false), - new HandledRoute(HideoutEventActions.HIDEOUT_CANCEL_PRODUCTION_COMMAND, false) + new HandledRoute(HideoutEventActions.HIDEOUT_CANCEL_PRODUCTION_COMMAND, false), ]; } - public override handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + url: string, + pmcData: IPmcData, + body: any, + sessionID: string, + ): IItemEventRouterResponse { switch (url) { @@ -64,4 +69,4 @@ export class HideoutItemEventRouter extends ItemEventRouterDefinition return this.hideoutCallbacks.cancelProduction(pmcData, body, sessionID); } } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/InsuranceItemEventRouter.ts b/project/src/routers/item_events/InsuranceItemEventRouter.ts index bce4aaba..b2849336 100644 --- a/project/src/routers/item_events/InsuranceItemEventRouter.ts +++ b/project/src/routers/item_events/InsuranceItemEventRouter.ts @@ -6,29 +6,33 @@ import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; @injectable() -export class InsuranceItemEventRouter extends ItemEventRouterDefinition +export class InsuranceItemEventRouter extends ItemEventRouterDefinition { constructor( - @inject("InsuranceCallbacks") protected insuranceCallbacks: InsuranceCallbacks // TODO: delay required - ) + @inject("InsuranceCallbacks") protected insuranceCallbacks: InsuranceCallbacks, // TODO: delay required + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ - new HandledRoute("Insure", false) + new HandledRoute("Insure", false), ]; } - public override handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + url: string, + pmcData: IPmcData, + body: any, + sessionID: string, + ): IItemEventRouterResponse { switch (url) { case "Insure": return this.insuranceCallbacks.insure(pmcData, body, sessionID); - } } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/InventoryItemEventRouter.ts b/project/src/routers/item_events/InventoryItemEventRouter.ts index 90267a03..dc016997 100644 --- a/project/src/routers/item_events/InventoryItemEventRouter.ts +++ b/project/src/routers/item_events/InventoryItemEventRouter.ts @@ -8,18 +8,17 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve import { ItemEventActions } from "@spt-aki/models/enums/ItemEventActions"; @injectable() -export class InventoryItemEventRouter extends ItemEventRouterDefinition +export class InventoryItemEventRouter extends ItemEventRouterDefinition { constructor( @inject("InventoryCallbacks") protected inventoryCallbacks: InventoryCallbacks, - @inject("HideoutCallbacks") protected hideoutCallbacks: HideoutCallbacks - - ) + @inject("HideoutCallbacks") protected hideoutCallbacks: HideoutCallbacks, + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ new HandledRoute(ItemEventActions.MOVE, false), @@ -39,11 +38,16 @@ export class InventoryItemEventRouter extends ItemEventRouterDefinition new HandledRoute(ItemEventActions.DELETE_MAP_MARKER, false), new HandledRoute(ItemEventActions.EDIT_MAP_MARKER, false), new HandledRoute(ItemEventActions.OPEN_RANDOM_LOOT_CONTAINER, false), - new HandledRoute(ItemEventActions.HIDEOUT_QTE_EVENT, false) + new HandledRoute(ItemEventActions.HIDEOUT_QTE_EVENT, false), ]; } - public override handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + url: string, + pmcData: IPmcData, + body: any, + sessionID: string, + ): IItemEventRouterResponse { switch (url) { @@ -87,4 +91,4 @@ export class InventoryItemEventRouter extends ItemEventRouterDefinition throw new Error(`Unhandled event ${url}`); } } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/NoteItemEventRouter.ts b/project/src/routers/item_events/NoteItemEventRouter.ts index 179ed61b..ce0b79de 100644 --- a/project/src/routers/item_events/NoteItemEventRouter.ts +++ b/project/src/routers/item_events/NoteItemEventRouter.ts @@ -7,34 +7,39 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve import { INoteActionData } from "@spt-aki/models/eft/notes/INoteActionData"; @injectable() -export class NoteItemEventRouter extends ItemEventRouterDefinition +export class NoteItemEventRouter extends ItemEventRouterDefinition { constructor( - @inject("NoteCallbacks") protected noteCallbacks: NoteCallbacks // TODO: delay required - ) + @inject("NoteCallbacks") protected noteCallbacks: NoteCallbacks, // TODO: delay required + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ new HandledRoute("AddNote", false), new HandledRoute("EditNote", false), - new HandledRoute("DeleteNote", false) + new HandledRoute("DeleteNote", false), ]; } - public override handleItemEvent(url: string, pmcData: IPmcData, body: INoteActionData, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + url: string, + pmcData: IPmcData, + body: INoteActionData, + sessionID: string, + ): IItemEventRouterResponse { switch (url) { case "AddNote": return this.noteCallbacks.addNote(pmcData, body, sessionID); case "EditNote": - return this.noteCallbacks.editNote(pmcData, body, sessionID); + return this.noteCallbacks.editNote(pmcData, body, sessionID); case "DeleteNote": - return this.noteCallbacks.deleteNote(pmcData, body, sessionID); + return this.noteCallbacks.deleteNote(pmcData, body, sessionID); } } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/PresetBuildItemEventRouter.ts b/project/src/routers/item_events/PresetBuildItemEventRouter.ts index 4fa1b4e4..07e8ee2f 100644 --- a/project/src/routers/item_events/PresetBuildItemEventRouter.ts +++ b/project/src/routers/item_events/PresetBuildItemEventRouter.ts @@ -7,27 +7,32 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve import { ItemEventActions } from "@spt-aki/models/enums/ItemEventActions"; @injectable() -export class PresetBuildItemEventRouter extends ItemEventRouterDefinition +export class PresetBuildItemEventRouter extends ItemEventRouterDefinition { constructor( - @inject("PresetBuildCallbacks") protected presetBuildCallbacks: PresetBuildCallbacks - ) + @inject("PresetBuildCallbacks") protected presetBuildCallbacks: PresetBuildCallbacks, + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ new HandledRoute(ItemEventActions.SAVE_WEAPON_BUILD, false), new HandledRoute(ItemEventActions.REMOVE_WEAPON_BUILD, false), new HandledRoute(ItemEventActions.SAVE_EQUIPMENT_BUILD, false), new HandledRoute(ItemEventActions.REMOVE_EQUIPMENT_BUILD, false), - new HandledRoute(ItemEventActions.REMOVE_BUILD, false) + new HandledRoute(ItemEventActions.REMOVE_BUILD, false), ]; } - public override handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + url: string, + pmcData: IPmcData, + body: any, + sessionID: string, + ): IItemEventRouterResponse { switch (url) { @@ -43,4 +48,4 @@ export class PresetBuildItemEventRouter extends ItemEventRouterDefinition return this.presetBuildCallbacks.removeEquipmentBuild(pmcData, body, sessionID); } } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/QuestItemEventRouter.ts b/project/src/routers/item_events/QuestItemEventRouter.ts index 1e881404..7138e81b 100644 --- a/project/src/routers/item_events/QuestItemEventRouter.ts +++ b/project/src/routers/item_events/QuestItemEventRouter.ts @@ -7,27 +7,32 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; @injectable() -export class QuestItemEventRouter extends ItemEventRouterDefinition +export class QuestItemEventRouter extends ItemEventRouterDefinition { constructor( @inject("WinstonLogger") protected logger: ILogger, - @inject("QuestCallbacks") protected questCallbacks: QuestCallbacks - ) + @inject("QuestCallbacks") protected questCallbacks: QuestCallbacks, + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ new HandledRoute("QuestAccept", false), new HandledRoute("QuestComplete", false), new HandledRoute("QuestHandover", false), - new HandledRoute("RepeatableQuestChange", false) + new HandledRoute("RepeatableQuestChange", false), ]; } - public override handleItemEvent(eventAction: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + eventAction: string, + pmcData: IPmcData, + body: any, + sessionID: string, + ): IItemEventRouterResponse { this.logger.debug(`${eventAction} ${body.qid}`); switch (eventAction) @@ -35,11 +40,11 @@ export class QuestItemEventRouter extends ItemEventRouterDefinition case "QuestAccept": return this.questCallbacks.acceptQuest(pmcData, body, sessionID); case "QuestComplete": - return this.questCallbacks.completeQuest(pmcData, body, sessionID); + return this.questCallbacks.completeQuest(pmcData, body, sessionID); case "QuestHandover": - return this.questCallbacks.handoverQuest(pmcData, body, sessionID); + return this.questCallbacks.handoverQuest(pmcData, body, sessionID); case "RepeatableQuestChange": - return this.questCallbacks.changeRepeatableQuest(pmcData, body, sessionID); + return this.questCallbacks.changeRepeatableQuest(pmcData, body, sessionID); } } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/RagfairItemEventRouter.ts b/project/src/routers/item_events/RagfairItemEventRouter.ts index 7c62eae1..fb0d0fb8 100644 --- a/project/src/routers/item_events/RagfairItemEventRouter.ts +++ b/project/src/routers/item_events/RagfairItemEventRouter.ts @@ -6,25 +6,30 @@ import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; @injectable() -export class RagfairItemEventRouter extends ItemEventRouterDefinition +export class RagfairItemEventRouter extends ItemEventRouterDefinition { constructor( - @inject("RagfairCallbacks") protected ragfairCallbacks: RagfairCallbacks - ) + @inject("RagfairCallbacks") protected ragfairCallbacks: RagfairCallbacks, + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ new HandledRoute("RagFairAddOffer", false), new HandledRoute("RagFairRemoveOffer", false), - new HandledRoute("RagFairRenewOffer", false) + new HandledRoute("RagFairRenewOffer", false), ]; } - public override handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + url: string, + pmcData: IPmcData, + body: any, + sessionID: string, + ): IItemEventRouterResponse { switch (url) { @@ -36,4 +41,4 @@ export class RagfairItemEventRouter extends ItemEventRouterDefinition return this.ragfairCallbacks.extendOffer(pmcData, body, sessionID); } } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/RepairItemEventRouter.ts b/project/src/routers/item_events/RepairItemEventRouter.ts index 1333ea2c..608760f7 100644 --- a/project/src/routers/item_events/RepairItemEventRouter.ts +++ b/project/src/routers/item_events/RepairItemEventRouter.ts @@ -6,24 +6,29 @@ import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; @injectable() -export class RepairItemEventRouter extends ItemEventRouterDefinition +export class RepairItemEventRouter extends ItemEventRouterDefinition { constructor( - @inject("RepairCallbacks") protected repairCallbacks: RepairCallbacks - ) + @inject("RepairCallbacks") protected repairCallbacks: RepairCallbacks, + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ new HandledRoute("Repair", false), - new HandledRoute("TraderRepair", false) + new HandledRoute("TraderRepair", false), ]; } - public override handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + url: string, + pmcData: IPmcData, + body: any, + sessionID: string, + ): IItemEventRouterResponse { switch (url) { @@ -33,4 +38,4 @@ export class RepairItemEventRouter extends ItemEventRouterDefinition return this.repairCallbacks.traderRepair(pmcData, body, sessionID); } } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/TradeItemEventRouter.ts b/project/src/routers/item_events/TradeItemEventRouter.ts index 36a737fd..b4db5dc0 100644 --- a/project/src/routers/item_events/TradeItemEventRouter.ts +++ b/project/src/routers/item_events/TradeItemEventRouter.ts @@ -6,25 +6,30 @@ import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; @injectable() -export class TradeItemEventRouter extends ItemEventRouterDefinition +export class TradeItemEventRouter extends ItemEventRouterDefinition { constructor( - @inject("TradeCallbacks") protected tradeCallbacks: TradeCallbacks - ) + @inject("TradeCallbacks") protected tradeCallbacks: TradeCallbacks, + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ new HandledRoute("TradingConfirm", false), new HandledRoute("RagFairBuyOffer", false), - new HandledRoute("SellAllFromSavage", false) + new HandledRoute("SellAllFromSavage", false), ]; } - public override handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + url: string, + pmcData: IPmcData, + body: any, + sessionID: string, + ): IItemEventRouterResponse { switch (url) { @@ -36,4 +41,4 @@ export class TradeItemEventRouter extends ItemEventRouterDefinition return this.tradeCallbacks.sellAllFromSavage(pmcData, body, sessionID); } } -} \ No newline at end of file +} diff --git a/project/src/routers/item_events/WishlistItemEventRouter.ts b/project/src/routers/item_events/WishlistItemEventRouter.ts index e18c1ebc..b1132edb 100644 --- a/project/src/routers/item_events/WishlistItemEventRouter.ts +++ b/project/src/routers/item_events/WishlistItemEventRouter.ts @@ -6,24 +6,29 @@ import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; @injectable() -export class WishlistItemEventRouter extends ItemEventRouterDefinition +export class WishlistItemEventRouter extends ItemEventRouterDefinition { constructor( - @inject("WishlistCallbacks") protected wishlistCallbacks: WishlistCallbacks - ) + @inject("WishlistCallbacks") protected wishlistCallbacks: WishlistCallbacks, + ) { super(); } - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ new HandledRoute("AddToWishList", false), - new HandledRoute("RemoveFromWishList", false) + new HandledRoute("RemoveFromWishList", false), ]; } - public override handleItemEvent(url: string, pmcData: IPmcData, body: any, sessionID: string): IItemEventRouterResponse + public override handleItemEvent( + url: string, + pmcData: IPmcData, + body: any, + sessionID: string, + ): IItemEventRouterResponse { switch (url) { @@ -33,4 +38,4 @@ export class WishlistItemEventRouter extends ItemEventRouterDefinition return this.wishlistCallbacks.removeFromWishlist(pmcData, body, sessionID); } } -} \ No newline at end of file +} diff --git a/project/src/routers/save_load/HealthSaveLoadRouter.ts b/project/src/routers/save_load/HealthSaveLoadRouter.ts index 9de28d57..b41bb39e 100644 --- a/project/src/routers/save_load/HealthSaveLoadRouter.ts +++ b/project/src/routers/save_load/HealthSaveLoadRouter.ts @@ -4,22 +4,22 @@ import { HandledRoute, SaveLoadRouter } from "@spt-aki/di/Router"; import { IAkiProfile } from "@spt-aki/models/eft/profile/IAkiProfile"; @injectable() -export class HealthSaveLoadRouter extends SaveLoadRouter +export class HealthSaveLoadRouter extends SaveLoadRouter { - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ - new HandledRoute("aki-health", false) + new HandledRoute("aki-health", false), ]; } - public override handleLoad(profile: IAkiProfile): IAkiProfile + public override handleLoad(profile: IAkiProfile): IAkiProfile { - if (!profile.vitality) // Occurs on newly created profiles - { + if (!profile.vitality) + { // Occurs on newly created profiles profile.vitality = { health: null, - effects: null + effects: null, }; } profile.vitality.health = { @@ -32,7 +32,7 @@ export class HealthSaveLoadRouter extends SaveLoadRouter LeftArm: 0, RightArm: 0, LeftLeg: 0, - RightLeg: 0 + RightLeg: 0, }; profile.vitality.effects = { @@ -42,9 +42,9 @@ export class HealthSaveLoadRouter extends SaveLoadRouter LeftArm: {}, RightArm: {}, LeftLeg: {}, - RightLeg: {} + RightLeg: {}, }; return profile; } -} \ No newline at end of file +} diff --git a/project/src/routers/save_load/InraidSaveLoadRouter.ts b/project/src/routers/save_load/InraidSaveLoadRouter.ts index 46d84a59..3f9b6ab7 100644 --- a/project/src/routers/save_load/InraidSaveLoadRouter.ts +++ b/project/src/routers/save_load/InraidSaveLoadRouter.ts @@ -4,25 +4,25 @@ import { HandledRoute, SaveLoadRouter } from "@spt-aki/di/Router"; import { IAkiProfile } from "@spt-aki/models/eft/profile/IAkiProfile"; @injectable() -export class InraidSaveLoadRouter extends SaveLoadRouter +export class InraidSaveLoadRouter extends SaveLoadRouter { - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ - new HandledRoute("aki-inraid", false) + new HandledRoute("aki-inraid", false), ]; } - public override handleLoad(profile: IAkiProfile): IAkiProfile + public override handleLoad(profile: IAkiProfile): IAkiProfile { if (profile.inraid === undefined) { profile.inraid = { location: "none", - character: "none" + character: "none", }; } return profile; } -} \ No newline at end of file +} diff --git a/project/src/routers/save_load/InsuranceSaveLoadRouter.ts b/project/src/routers/save_load/InsuranceSaveLoadRouter.ts index 4137b8e1..82264828 100644 --- a/project/src/routers/save_load/InsuranceSaveLoadRouter.ts +++ b/project/src/routers/save_load/InsuranceSaveLoadRouter.ts @@ -4,16 +4,16 @@ import { HandledRoute, SaveLoadRouter } from "@spt-aki/di/Router"; import { IAkiProfile } from "@spt-aki/models/eft/profile/IAkiProfile"; @injectable() -export class InsuranceSaveLoadRouter extends SaveLoadRouter +export class InsuranceSaveLoadRouter extends SaveLoadRouter { - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ - new HandledRoute("aki-insurance", false) + new HandledRoute("aki-insurance", false), ]; } - public override handleLoad(profile: IAkiProfile): IAkiProfile + public override handleLoad(profile: IAkiProfile): IAkiProfile { if (profile.insurance === undefined) { @@ -21,4 +21,4 @@ export class InsuranceSaveLoadRouter extends SaveLoadRouter } return profile; } -} \ No newline at end of file +} diff --git a/project/src/routers/save_load/ProfileSaveLoadRouter.ts b/project/src/routers/save_load/ProfileSaveLoadRouter.ts index 75ae8d91..87348102 100644 --- a/project/src/routers/save_load/ProfileSaveLoadRouter.ts +++ b/project/src/routers/save_load/ProfileSaveLoadRouter.ts @@ -5,24 +5,24 @@ import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IAkiProfile } from "@spt-aki/models/eft/profile/IAkiProfile"; @injectable() -export class ProfileSaveLoadRouter extends SaveLoadRouter +export class ProfileSaveLoadRouter extends SaveLoadRouter { - public override getHandledRoutes(): HandledRoute[] + public override getHandledRoutes(): HandledRoute[] { return [ - new HandledRoute("aki-profile", false) + new HandledRoute("aki-profile", false), ]; } - public override handleLoad(profile: IAkiProfile): IAkiProfile + public override handleLoad(profile: IAkiProfile): IAkiProfile { if (profile.characters === null) { profile.characters = { pmc: {} as IPmcData, - scav: {} as IPmcData + scav: {} as IPmcData, }; } return profile; } -} \ No newline at end of file +} diff --git a/project/src/routers/serializers/BundleSerializer.ts b/project/src/routers/serializers/BundleSerializer.ts index 326733f0..691f7dee 100644 --- a/project/src/routers/serializers/BundleSerializer.ts +++ b/project/src/routers/serializers/BundleSerializer.ts @@ -9,17 +9,15 @@ import { HttpFileUtil } from "@spt-aki/utils/HttpFileUtil"; @injectable() export class BundleSerializer extends Serializer { - constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("BundleLoader") protected bundleLoader: BundleLoader, - @inject("HttpFileUtil") protected httpFileUtil: HttpFileUtil + @inject("HttpFileUtil") protected httpFileUtil: HttpFileUtil, ) { super(); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars public override serialize(sessionID: string, req: IncomingMessage, resp: ServerResponse, body: any): void { this.logger.info(`[BUNDLE]: ${req.url}`); @@ -35,4 +33,4 @@ export class BundleSerializer extends Serializer { return route === "BUNDLE"; } -} \ No newline at end of file +} diff --git a/project/src/routers/serializers/ImageSerializer.ts b/project/src/routers/serializers/ImageSerializer.ts index be3d7d7a..af220c0a 100644 --- a/project/src/routers/serializers/ImageSerializer.ts +++ b/project/src/routers/serializers/ImageSerializer.ts @@ -5,16 +5,16 @@ import { Serializer } from "@spt-aki/di/Serializer"; import { ImageRouter } from "@spt-aki/routers/ImageRouter"; @injectable() -export class ImageSerializer extends Serializer +export class ImageSerializer extends Serializer { constructor( - @inject("ImageRouter") protected imageRouter: ImageRouter + @inject("ImageRouter") protected imageRouter: ImageRouter, ) { super(); } - public override serialize(sessionID: string, req: IncomingMessage, resp: ServerResponse, body: any): void + public override serialize(sessionID: string, req: IncomingMessage, resp: ServerResponse, body: any): void { this.imageRouter.sendImage(sessionID, req, resp, body); } @@ -23,4 +23,4 @@ export class ImageSerializer extends Serializer { return route === "IMAGE"; } -} \ No newline at end of file +} diff --git a/project/src/routers/serializers/NotifySerializer.ts b/project/src/routers/serializers/NotifySerializer.ts index b0960af1..2cc1975d 100644 --- a/project/src/routers/serializers/NotifySerializer.ts +++ b/project/src/routers/serializers/NotifySerializer.ts @@ -9,17 +9,15 @@ import { JsonUtil } from "@spt-aki/utils/JsonUtil"; @injectable() export class NotifySerializer extends Serializer { - constructor( @inject("NotifierController") protected notifierController: NotifierController, @inject("JsonUtil") protected jsonUtil: JsonUtil, - @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper + @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper, ) { super(); } - - // eslint-disable-next-line @typescript-eslint/no-unused-vars + public override serialize(_sessionID: string, req: IncomingMessage, resp: ServerResponse, _: any): void { const splittedUrl = req.url.split("/"); @@ -38,4 +36,4 @@ export class NotifySerializer extends Serializer { return route.toUpperCase() === "NOTIFY"; } -} \ No newline at end of file +} diff --git a/project/src/routers/static/BotStaticRouter.ts b/project/src/routers/static/BotStaticRouter.ts index dde4ba98..c4efff6c 100644 --- a/project/src/routers/static/BotStaticRouter.ts +++ b/project/src/routers/static/BotStaticRouter.ts @@ -4,23 +4,22 @@ import { BotCallbacks } from "@spt-aki/callbacks/BotCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class BotStaticRouter extends StaticRouter +export class BotStaticRouter extends StaticRouter { constructor( - @inject("BotCallbacks") protected botCallbacks: BotCallbacks - ) + @inject("BotCallbacks") protected botCallbacks: BotCallbacks, + ) { super( [ new RouteAction( "/client/game/bot/generate", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.botCallbacks.generateBots(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/BundleStaticRouter.ts b/project/src/routers/static/BundleStaticRouter.ts index b608362c..b269a36e 100644 --- a/project/src/routers/static/BundleStaticRouter.ts +++ b/project/src/routers/static/BundleStaticRouter.ts @@ -4,23 +4,22 @@ import { BundleCallbacks } from "@spt-aki/callbacks/BundleCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class BundleStaticRouter extends StaticRouter +export class BundleStaticRouter extends StaticRouter { constructor( - @inject("BundleCallbacks") protected bundleCallbacks: BundleCallbacks - ) + @inject("BundleCallbacks") protected bundleCallbacks: BundleCallbacks, + ) { super( [ new RouteAction( "/singleplayer/bundles", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.bundleCallbacks.getBundles(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/ClientLogStaticRouter.ts b/project/src/routers/static/ClientLogStaticRouter.ts index 3df61bd5..3844d2f0 100644 --- a/project/src/routers/static/ClientLogStaticRouter.ts +++ b/project/src/routers/static/ClientLogStaticRouter.ts @@ -7,20 +7,19 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; export class ClientLogStaticRouter extends StaticRouter { constructor( - @inject("ClientLogCallbacks") protected clientLogCallbacks: ClientLogCallbacks + @inject("ClientLogCallbacks") protected clientLogCallbacks: ClientLogCallbacks, ) { super( [ new RouteAction( "/singleplayer/log", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, output: string): any => { return this.clientLogCallbacks.clientLog(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/CustomizationStaticRouter.ts b/project/src/routers/static/CustomizationStaticRouter.ts index 56d6c94f..94392ab9 100644 --- a/project/src/routers/static/CustomizationStaticRouter.ts +++ b/project/src/routers/static/CustomizationStaticRouter.ts @@ -4,23 +4,22 @@ import { CustomizationCallbacks } from "@spt-aki/callbacks/CustomizationCallback import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class CustomizationStaticRouter extends StaticRouter +export class CustomizationStaticRouter extends StaticRouter { constructor( - @inject("CustomizationCallbacks") protected customizationCallbacks: CustomizationCallbacks - ) + @inject("CustomizationCallbacks") protected customizationCallbacks: CustomizationCallbacks, + ) { super( [ new RouteAction( "/client/trading/customization/storage", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.customizationCallbacks.getSuits(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/DataStaticRouter.ts b/project/src/routers/static/DataStaticRouter.ts index c4ab65f1..22360c59 100644 --- a/project/src/routers/static/DataStaticRouter.ts +++ b/project/src/routers/static/DataStaticRouter.ts @@ -4,111 +4,99 @@ import { DataCallbacks } from "@spt-aki/callbacks/DataCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class DataStaticRouter extends StaticRouter +export class DataStaticRouter extends StaticRouter { constructor( - @inject("DataCallbacks") protected dataCallbacks: DataCallbacks - ) + @inject("DataCallbacks") protected dataCallbacks: DataCallbacks, + ) { super( [ new RouteAction( "/client/settings", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getSettings(url, info, sessionID); - } + }, ), new RouteAction( "/client/globals", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getGlobals(url, info, sessionID); - } + }, ), new RouteAction( "/client/items", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getTemplateItems(url, info, sessionID); - } + }, ), new RouteAction( "/client/handbook/templates", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getTemplateHandbook(url, info, sessionID); - } + }, ), new RouteAction( "/client/customization", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getTemplateSuits(url, info, sessionID); - } + }, ), new RouteAction( "/client/account/customization", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getTemplateCharacter(url, info, sessionID); - } + }, ), new RouteAction( "/client/hideout/production/recipes", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.gethideoutProduction(url, info, sessionID); - } + }, ), new RouteAction( "/client/hideout/settings", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getHideoutSettings(url, info, sessionID); - } + }, ), new RouteAction( "/client/hideout/areas", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getHideoutAreas(url, info, sessionID); - } + }, ), new RouteAction( "/client/hideout/production/scavcase/recipes", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getHideoutScavcase(url, info, sessionID); - } + }, ), new RouteAction( "/client/languages", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getLocalesLanguages(url, info, sessionID); - } + }, ), new RouteAction( "/client/hideout/qte/list", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dataCallbacks.getQteList(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/DialogStaticRouter.ts b/project/src/routers/static/DialogStaticRouter.ts index 0bd64f73..2bee28c2 100644 --- a/project/src/routers/static/DialogStaticRouter.ts +++ b/project/src/routers/static/DialogStaticRouter.ts @@ -4,183 +4,162 @@ import { DialogueCallbacks } from "@spt-aki/callbacks/DialogueCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class DialogStaticRouter extends StaticRouter +export class DialogStaticRouter extends StaticRouter { constructor( - @inject("DialogueCallbacks") protected dialogueCallbacks: DialogueCallbacks - ) + @inject("DialogueCallbacks") protected dialogueCallbacks: DialogueCallbacks, + ) { super( [ new RouteAction( "/client/chatServer/list", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.getChatServerList(url, info, sessionID); - } + }, ), new RouteAction( "/client/mail/dialog/list", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.getMailDialogList(url, info, sessionID); - } + }, ), new RouteAction( "/client/mail/dialog/view", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.getMailDialogView(url, info, sessionID); - } + }, ), new RouteAction( "/client/mail/dialog/info", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.getMailDialogInfo(url, info, sessionID); - } + }, ), new RouteAction( "/client/mail/dialog/remove", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.removeDialog(url, info, sessionID); - } + }, ), new RouteAction( "/client/mail/dialog/pin", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.pinDialog(url, info, sessionID); - } + }, ), new RouteAction( "/client/mail/dialog/unpin", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.unpinDialog(url, info, sessionID); - } + }, ), new RouteAction( "/client/mail/dialog/read", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.setRead(url, info, sessionID); - } + }, ), new RouteAction( "/client/mail/dialog/remove", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.removeMail(url, info, sessionID); - } + }, ), new RouteAction( "/client/mail/dialog/getAllAttachments", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.getAllAttachments(url, info, sessionID); - } + }, ), new RouteAction( "/client/mail/msg/send", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.sendMessage(url, info, sessionID); - } + }, ), new RouteAction( "/client/mail/dialog/clear", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.clearMail(url, info, sessionID); - } + }, ), new RouteAction( "/client/friend/list", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.getFriendList(url, info, sessionID); - } + }, ), new RouteAction( "/client/friend/request/list/outbox", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.listOutbox(url, info, sessionID); - } + }, ), new RouteAction( "/client/friend/request/list/inbox", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.listInbox(url, info, sessionID); - } + }, ), new RouteAction( "/client/friend/request/send", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.sendFriendRequest(url, info, sessionID); - } + }, ), new RouteAction( "/client/friend/request/accept", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.acceptFriendRequest(url, info, sessionID); - } + }, ), new RouteAction( "/client/friend/request/cancel", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.cancelFriendRequest(url, info, sessionID); - } + }, ), new RouteAction( "/client/friend/delete", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.deleteFriend(url, info, sessionID); - } + }, ), new RouteAction( "/client/friend/ignore/set", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.ignoreFriend(url, info, sessionID); - } + }, ), new RouteAction( "/client/friend/ignore/remove", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.dialogueCallbacks.unIgnoreFriend(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/GameStaticRouter.ts b/project/src/routers/static/GameStaticRouter.ts index e9d9d788..34d5fe4e 100644 --- a/project/src/routers/static/GameStaticRouter.ts +++ b/project/src/routers/static/GameStaticRouter.ts @@ -4,95 +4,85 @@ import { GameCallbacks } from "@spt-aki/callbacks/GameCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class GameStaticRouter extends StaticRouter +export class GameStaticRouter extends StaticRouter { constructor( - @inject("GameCallbacks") protected gameCallbacks: GameCallbacks - ) + @inject("GameCallbacks") protected gameCallbacks: GameCallbacks, + ) { super( [ new RouteAction( "/client/game/config", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.gameCallbacks.getGameConfig(url, info, sessionID); - } + }, ), new RouteAction( "/client/server/list", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.gameCallbacks.getServer(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/current", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.gameCallbacks.getCurrentGroup(url, info, sessionID); - } + }, ), new RouteAction( "/client/game/version/validate", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.gameCallbacks.versionValidate(url, info, sessionID); - } + }, ), new RouteAction( "/client/game/start", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.gameCallbacks.gameStart(url, info, sessionID); - } + }, ), new RouteAction( "/client/game/logout", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.gameCallbacks.gameLogout(url, info, sessionID); - } + }, ), new RouteAction( "/client/checkVersion", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.gameCallbacks.validateGameVersion(url, info, sessionID); - } + }, ), new RouteAction( "/client/game/keepalive", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.gameCallbacks.gameKeepalive(url, info, sessionID); - } + }, ), new RouteAction( "/singleplayer/settings/version", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.gameCallbacks.getVersion(url, info, sessionID); - } + }, ), new RouteAction( "/client/reports/lobby/send", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.gameCallbacks.reportNickname(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/HealthStaticRouter.ts b/project/src/routers/static/HealthStaticRouter.ts index 2f4471ed..9f4aa243 100644 --- a/project/src/routers/static/HealthStaticRouter.ts +++ b/project/src/routers/static/HealthStaticRouter.ts @@ -4,31 +4,29 @@ import { HealthCallbacks } from "@spt-aki/callbacks/HealthCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class HealthStaticRouter extends StaticRouter +export class HealthStaticRouter extends StaticRouter { constructor( - @inject("HealthCallbacks") protected healthCallbacks: HealthCallbacks - ) + @inject("HealthCallbacks") protected healthCallbacks: HealthCallbacks, + ) { super( [ new RouteAction( "/player/health/sync", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.healthCallbacks.syncHealth(url, info, sessionID); - } + }, ), new RouteAction( "/client/hideout/workout", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.healthCallbacks.handleWorkoutEffects(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/InraidStaticRouter.ts b/project/src/routers/static/InraidStaticRouter.ts index 4bcf2b67..a3e958ae 100644 --- a/project/src/routers/static/InraidStaticRouter.ts +++ b/project/src/routers/static/InraidStaticRouter.ts @@ -4,55 +4,50 @@ import { InraidCallbacks } from "@spt-aki/callbacks/InraidCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class InraidStaticRouter extends StaticRouter +export class InraidStaticRouter extends StaticRouter { constructor( - @inject("InraidCallbacks") protected inraidCallbacks: InraidCallbacks - ) + @inject("InraidCallbacks") protected inraidCallbacks: InraidCallbacks, + ) { super( [ new RouteAction( "/raid/profile/save", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.inraidCallbacks.saveProgress(url, info, sessionID); - } + }, ), new RouteAction( "/singleplayer/settings/raid/endstate", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.inraidCallbacks.getRaidEndState(); - } + }, ), new RouteAction( "/singleplayer/settings/weapon/durability", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.inraidCallbacks.getWeaponDurability(); - } + }, ), new RouteAction( "/singleplayer/settings/raid/menu", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.inraidCallbacks.getRaidMenuSettings(); - } + }, ), new RouteAction( "/singleplayer/airdrop/config", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.inraidCallbacks.getAirdropConfig(); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/InsuranceStaticRouter.ts b/project/src/routers/static/InsuranceStaticRouter.ts index d9c5bc00..08d879ed 100644 --- a/project/src/routers/static/InsuranceStaticRouter.ts +++ b/project/src/routers/static/InsuranceStaticRouter.ts @@ -4,23 +4,22 @@ import { InsuranceCallbacks } from "@spt-aki/callbacks/InsuranceCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class InsuranceStaticRouter extends StaticRouter +export class InsuranceStaticRouter extends StaticRouter { constructor( - @inject("InsuranceCallbacks") protected insuranceCallbacks: InsuranceCallbacks - ) + @inject("InsuranceCallbacks") protected insuranceCallbacks: InsuranceCallbacks, + ) { super( [ new RouteAction( "/client/insurance/items/list/cost", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.insuranceCallbacks.getInsuranceCost(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/ItemEventStaticRouter.ts b/project/src/routers/static/ItemEventStaticRouter.ts index 9dc0e46f..793494da 100644 --- a/project/src/routers/static/ItemEventStaticRouter.ts +++ b/project/src/routers/static/ItemEventStaticRouter.ts @@ -4,23 +4,22 @@ import { ItemEventCallbacks } from "@spt-aki/callbacks/ItemEventCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class ItemEventStaticRouter extends StaticRouter +export class ItemEventStaticRouter extends StaticRouter { constructor( - @inject("ItemEventCallbacks") protected itemEventCallbacks: ItemEventCallbacks - ) + @inject("ItemEventCallbacks") protected itemEventCallbacks: ItemEventCallbacks, + ) { super( [ new RouteAction( "/client/game/profile/items/moving", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.itemEventCallbacks.handleEvents(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/LauncherStaticRouter.ts b/project/src/routers/static/LauncherStaticRouter.ts index b471723e..7ecd65dd 100644 --- a/project/src/routers/static/LauncherStaticRouter.ts +++ b/project/src/routers/static/LauncherStaticRouter.ts @@ -4,119 +4,106 @@ import { LauncherCallbacks } from "@spt-aki/callbacks/LauncherCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class LauncherStaticRouter extends StaticRouter +export class LauncherStaticRouter extends StaticRouter { constructor( - @inject("LauncherCallbacks") protected launcherCallbacks: LauncherCallbacks - ) + @inject("LauncherCallbacks") protected launcherCallbacks: LauncherCallbacks, + ) { super( [ new RouteAction( "/launcher/ping", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.ping(url, info, sessionID); - } + }, ), new RouteAction( "/launcher/server/connect", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.connect(); - } + }, ), new RouteAction( "/launcher/profile/login", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { - return this.launcherCallbacks.login(url, info,sessionID); - } + return this.launcherCallbacks.login(url, info, sessionID); + }, ), new RouteAction( "/launcher/profile/register", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.register(url, info, sessionID); - } + }, ), new RouteAction( "/launcher/profile/get", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.get(url, info, sessionID); - } + }, ), new RouteAction( "/launcher/profile/change/username", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.changeUsername(url, info, sessionID); - } + }, ), new RouteAction( "/launcher/profile/change/password", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.changePassword(url, info, sessionID); - } + }, ), new RouteAction( "/launcher/profile/change/wipe", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.wipe(url, info, sessionID); - } + }, ), new RouteAction( "/launcher/profile/remove", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.removeProfile(url, info, sessionID); - } + }, ), new RouteAction( "/launcher/profile/compatibleTarkovVersion", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.getCompatibleTarkovVersion(); - } + }, ), new RouteAction( "/launcher/server/version", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.getServerVersion(); - } + }, ), new RouteAction( "/launcher/server/loadedServerMods", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.getLoadedServerMods(); - } + }, ), new RouteAction( "/launcher/server/serverModsUsedByProfile", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.launcherCallbacks.getServerModsProfileUsed(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/LocationStaticRouter.ts b/project/src/routers/static/LocationStaticRouter.ts index 73295bec..ccfb93a0 100644 --- a/project/src/routers/static/LocationStaticRouter.ts +++ b/project/src/routers/static/LocationStaticRouter.ts @@ -4,31 +4,29 @@ import { LocationCallbacks } from "@spt-aki/callbacks/LocationCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class LocationStaticRouter extends StaticRouter +export class LocationStaticRouter extends StaticRouter { constructor( - @inject("LocationCallbacks") protected locationCallbacks: LocationCallbacks - ) + @inject("LocationCallbacks") protected locationCallbacks: LocationCallbacks, + ) { super( [ new RouteAction( "/client/locations", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.locationCallbacks.getLocationData(url, info, sessionID); - } + }, ), new RouteAction( "/client/location/getAirdropLoot", - // eslint-disable-next-line @typescript-eslint/no-unused-vars (url: string, info: any, sessionID: string, _output: string): any => { return this.locationCallbacks.getAirdropLoot(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/MatchStaticRouter.ts b/project/src/routers/static/MatchStaticRouter.ts index 1731fc49..74c81455 100644 --- a/project/src/routers/static/MatchStaticRouter.ts +++ b/project/src/routers/static/MatchStaticRouter.ts @@ -4,200 +4,176 @@ import { MatchCallbacks } from "@spt-aki/callbacks/MatchCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class MatchStaticRouter extends StaticRouter +export class MatchStaticRouter extends StaticRouter { constructor( - @inject("MatchCallbacks") protected matchCallbacks: MatchCallbacks - ) + @inject("MatchCallbacks") protected matchCallbacks: MatchCallbacks, + ) { super( [ new RouteAction( - "/raid/profile/list", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/raid/profile/list", + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.getProfile(url, info, sessionID); - } + }, ), new RouteAction( - "/client/match/available", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/match/available", + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.serverAvailable(url, info, sessionID); - } + }, ), new RouteAction( - "/client/match/updatePing", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/match/updatePing", + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.updatePing(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/join", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.joinMatch(url, info, sessionID); - } + }, ), new RouteAction( - "/client/match/exit", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/match/exit", + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.exitMatch(url, info, sessionID); - } + }, ), new RouteAction( - "/client/match/group/create", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/match/group/create", + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.createGroup(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/delete", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { - return this. matchCallbacks.deleteGroup(url, info, sessionID); - } + return this.matchCallbacks.deleteGroup(url, info, sessionID); + }, ), new RouteAction( "/client/match/group/leave", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { - return this. matchCallbacks.leaveGroup(url, info, sessionID); - } + return this.matchCallbacks.leaveGroup(url, info, sessionID); + }, ), new RouteAction( "/client/match/group/status", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.getGroupStatus(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/start_game", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.joinMatch(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/exit_from_menu", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.exitToMenu(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/looking/start", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.startGroupSearch(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/looking/stop", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.stopGroupSearch(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/invite/send", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.sendGroupInvite(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/invite/accept", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.acceptGroupInvite(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/invite/cancel", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.cancelGroupInvite(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/invite/cancel-all", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.cancelAllGroupInvite(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/transfer", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.transferGroup(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/offline/end", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.endOfflineRaid(url, info, sessionID); - - } + }, ), new RouteAction( "/client/putMetrics", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.putMetrics(url, info, sessionID); - } + }, ), new RouteAction( "/client/getMetricsConfig", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.getMetrics(url, info, sessionID); - } + }, ), new RouteAction( "/client/raid/configuration", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.getRaidConfiguration(url, info, sessionID); - } + }, ), new RouteAction( "/client/match/group/player/remove", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.matchCallbacks.removePlayerFromGroup(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/NotifierStaticRouter.ts b/project/src/routers/static/NotifierStaticRouter.ts index c065ffeb..56b34ce2 100644 --- a/project/src/routers/static/NotifierStaticRouter.ts +++ b/project/src/routers/static/NotifierStaticRouter.ts @@ -4,31 +4,29 @@ import { NotifierCallbacks } from "@spt-aki/callbacks/NotifierCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class NotifierStaticRouter extends StaticRouter +export class NotifierStaticRouter extends StaticRouter { constructor( - @inject("NotifierCallbacks") protected notifierCallbacks: NotifierCallbacks - ) + @inject("NotifierCallbacks") protected notifierCallbacks: NotifierCallbacks, + ) { super( [ new RouteAction( - "/client/notifier/channel/create", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/notifier/channel/create", + (url: string, info: any, sessionID: string, output: string): any => { return this.notifierCallbacks.createNotifierChannel(url, info, sessionID); - } + }, ), new RouteAction( - "/client/game/profile/select", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/game/profile/select", + (url: string, info: any, sessionID: string, output: string): any => { return this.notifierCallbacks.selectProfile(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/PresetStaticRouter.ts b/project/src/routers/static/PresetStaticRouter.ts index 860695cc..c08482ff 100644 --- a/project/src/routers/static/PresetStaticRouter.ts +++ b/project/src/routers/static/PresetStaticRouter.ts @@ -4,23 +4,22 @@ import { PresetBuildCallbacks } from "@spt-aki/callbacks/PresetBuildCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class PresetStaticRouter extends StaticRouter +export class PresetStaticRouter extends StaticRouter { constructor( - @inject("PresetBuildCallbacks") protected presetCallbacks: PresetBuildCallbacks - ) + @inject("PresetBuildCallbacks") protected presetCallbacks: PresetBuildCallbacks, + ) { super( [ new RouteAction( - "/client/handbook/builds/my/list", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/handbook/builds/my/list", + (url: string, info: any, sessionID: string, output: string): any => { return this.presetCallbacks.getHandbookUserlist(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/ProfileStaticRouter.ts b/project/src/routers/static/ProfileStaticRouter.ts index a2cd71b0..147a066e 100644 --- a/project/src/routers/static/ProfileStaticRouter.ts +++ b/project/src/routers/static/ProfileStaticRouter.ts @@ -4,99 +4,99 @@ import { ProfileCallbacks } from "@spt-aki/callbacks/ProfileCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class ProfileStaticRouter extends StaticRouter +export class ProfileStaticRouter extends StaticRouter { constructor( - @inject("ProfileCallbacks") protected profileCallbacks: ProfileCallbacks - ) + @inject("ProfileCallbacks") protected profileCallbacks: ProfileCallbacks, + ) { super( [ new RouteAction( - "/client/game/profile/create", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/game/profile/create", + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.createProfile(url, info, sessionID); - }), + }, + ), new RouteAction( "/client/game/profile/list", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.getProfileData(url, info, sessionID); - }), + }, + ), new RouteAction( - "/client/game/profile/savage/regenerate", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/game/profile/savage/regenerate", + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.regenerateScav(url, info, sessionID); - }), + }, + ), new RouteAction( "/client/game/profile/voice/change", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.changeVoice(url, info, sessionID); - }), + }, + ), new RouteAction( "/client/game/profile/nickname/change", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.changeNickname(url, info, sessionID); - }), + }, + ), new RouteAction( - "/client/game/profile/nickname/validate", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/game/profile/nickname/validate", + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.validateNickname(url, info, sessionID); - }), + }, + ), new RouteAction( "/client/game/profile/nickname/reserved", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.getReservedNickname(url, info, sessionID); - }), + }, + ), new RouteAction( - "/client/profile/status", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/profile/status", + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.getProfileStatus(url, info, sessionID); - }), + }, + ), new RouteAction( - "/client/profile/settings", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/profile/settings", + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.getProfileSettings(url, info, sessionID); - }), + }, + ), new RouteAction( - "/client/game/profile/search", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/game/profile/search", + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.searchFriend(url, info, sessionID); - }), + }, + ), new RouteAction( - "/launcher/profile/info", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/launcher/profile/info", + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.getMiniProfile(url, info, sessionID); - }), + }, + ), new RouteAction( "/launcher/profiles", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + (url: string, info: any, sessionID: string, output: string): any => { return this.profileCallbacks.getAllMiniProfiles(url, info, sessionID); - }) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/QuestStaticRouter.ts b/project/src/routers/static/QuestStaticRouter.ts index 8d4caa42..d0ac6f12 100644 --- a/project/src/routers/static/QuestStaticRouter.ts +++ b/project/src/routers/static/QuestStaticRouter.ts @@ -4,29 +4,29 @@ import { QuestCallbacks } from "@spt-aki/callbacks/QuestCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class QuestStaticRouter extends StaticRouter +export class QuestStaticRouter extends StaticRouter { constructor( - @inject("QuestCallbacks") protected questCallbacks: QuestCallbacks - ) + @inject("QuestCallbacks") protected questCallbacks: QuestCallbacks, + ) { super( [ new RouteAction( - "/client/quest/list", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/quest/list", + (url: string, info: any, sessionID: string, output: string): any => { return this.questCallbacks.listQuests(url, info, sessionID); - }), + }, + ), new RouteAction( - "/client/repeatalbeQuests/activityPeriods", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/repeatalbeQuests/activityPeriods", + (url: string, info: any, sessionID: string, output: string): any => { return this.questCallbacks.activityPeriods(url, info, sessionID); - }) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/RagfairStaticRouter.ts b/project/src/routers/static/RagfairStaticRouter.ts index 4da872f0..06461d4f 100644 --- a/project/src/routers/static/RagfairStaticRouter.ts +++ b/project/src/routers/static/RagfairStaticRouter.ts @@ -4,58 +4,57 @@ import { RagfairCallbacks } from "@spt-aki/callbacks/RagfairCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class RagfairStaticRouter extends StaticRouter +export class RagfairStaticRouter extends StaticRouter { constructor( - @inject("RagfairCallbacks") protected ragfairCallbacks: RagfairCallbacks - ) + @inject("RagfairCallbacks") protected ragfairCallbacks: RagfairCallbacks, + ) { super( [ new RouteAction( - "/client/ragfair/search", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/ragfair/search", + (url: string, info: any, sessionID: string, output: string): any => { return this.ragfairCallbacks.search(url, info, sessionID); - }), + }, + ), new RouteAction( - "/client/ragfair/find", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/ragfair/find", + (url: string, info: any, sessionID: string, output: string): any => { return this.ragfairCallbacks.search(url, info, sessionID); - }), + }, + ), new RouteAction( - "/client/ragfair/itemMarketPrice", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/ragfair/itemMarketPrice", + (url: string, info: any, sessionID: string, output: string): any => { return this.ragfairCallbacks.getMarketPrice(url, info, sessionID); - }), + }, + ), new RouteAction( - "/client/ragfair/offerfees", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/ragfair/offerfees", + (url: string, info: any, sessionID: string, output: string): any => { return this.ragfairCallbacks.storePlayerOfferTaxAmount(url, info, sessionID); - }), + }, + ), new RouteAction( - "/client/reports/ragfair/send", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/reports/ragfair/send", + (url: string, info: any, sessionID: string, output: string): any => { return this.ragfairCallbacks.sendReport(url, info, sessionID); - }), + }, + ), new RouteAction( - "/client/items/prices", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/items/prices", + (url: string, info: any, sessionID: string, output: string): any => { return this.ragfairCallbacks.getFleaPrices(url, info, sessionID); - }) - ] + }, + ), + ], ); } - -} \ No newline at end of file +} diff --git a/project/src/routers/static/TraderStaticRouter.ts b/project/src/routers/static/TraderStaticRouter.ts index 40c7b3fc..12ac0359 100644 --- a/project/src/routers/static/TraderStaticRouter.ts +++ b/project/src/routers/static/TraderStaticRouter.ts @@ -4,23 +4,22 @@ import { TraderCallbacks } from "@spt-aki/callbacks/TraderCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class TraderStaticRouter extends StaticRouter +export class TraderStaticRouter extends StaticRouter { constructor( - @inject("TraderCallbacks") protected traderCallbacks: TraderCallbacks - ) + @inject("TraderCallbacks") protected traderCallbacks: TraderCallbacks, + ) { super( [ new RouteAction( - "/client/trading/api/traderSettings", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/trading/api/traderSettings", + (url: string, info: any, sessionID: string, output: string): any => { return this.traderCallbacks.getTraderSettings(url, info, sessionID); - } - ) - ] + }, + ), + ], ); } -} \ No newline at end of file +} diff --git a/project/src/routers/static/WeatherStaticRouter.ts b/project/src/routers/static/WeatherStaticRouter.ts index 2ec39e40..df013520 100644 --- a/project/src/routers/static/WeatherStaticRouter.ts +++ b/project/src/routers/static/WeatherStaticRouter.ts @@ -4,22 +4,22 @@ import { WeatherCallbacks } from "@spt-aki/callbacks/WeatherCallbacks"; import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() -export class WeatherStaticRouter extends StaticRouter +export class WeatherStaticRouter extends StaticRouter { constructor( - @inject("WeatherCallbacks") protected weatherCallbacks: WeatherCallbacks - ) + @inject("WeatherCallbacks") protected weatherCallbacks: WeatherCallbacks, + ) { super( [ new RouteAction( - "/client/weather", - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (url: string, info: any, sessionID: string, output: string): any => + "/client/weather", + (url: string, info: any, sessionID: string, output: string): any => { return this.weatherCallbacks.getWeather(url, info, sessionID); - }) - ] + }, + ), + ], ); } -} \ No newline at end of file +} From ca9ab9bcc8083a75d5f0df89c4b1042dee72023f Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:12:51 -0500 Subject: [PATCH 31/41] Formatting for servers. --- project/src/servers/ConfigServer.ts | 17 ++++--- project/src/servers/DatabaseServer.ts | 2 +- project/src/servers/HttpServer.ts | 16 ++++--- project/src/servers/RagfairServer.ts | 8 ++-- project/src/servers/SaveServer.ts | 14 +++--- project/src/servers/WebSocketServer.ts | 49 +++++++++++---------- project/src/servers/http/AkiHttpListener.ts | 42 ++++++++++-------- project/src/servers/http/HttpMethods.ts | 8 ++-- project/src/servers/http/IHttpListener.ts | 6 +-- 9 files changed, 87 insertions(+), 75 deletions(-) diff --git a/project/src/servers/ConfigServer.ts b/project/src/servers/ConfigServer.ts index 2fb9ead1..5fec377a 100644 --- a/project/src/servers/ConfigServer.ts +++ b/project/src/servers/ConfigServer.ts @@ -7,7 +7,7 @@ import { JsonUtil } from "@spt-aki/utils/JsonUtil"; import { VFS } from "@spt-aki/utils/VFS"; @injectable() -export class ConfigServer +export class ConfigServer { protected configs: Record = {}; protected readonly acceptableFileExtensions: string[] = ["json", "jsonc"]; @@ -15,7 +15,7 @@ export class ConfigServer constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("VFS") protected vfs: VFS, - @inject("JsonUtil") protected jsonUtil: JsonUtil + @inject("JsonUtil") protected jsonUtil: JsonUtil, ) { this.initialize(); @@ -36,9 +36,9 @@ export class ConfigServer this.logger.debug("Importing configs..."); // Get all filepaths - const filepath = (globalThis.G_RELEASE_CONFIGURATION) - ? "Aki_Data/Server/configs/" - : "./assets/configs/"; + const filepath = (globalThis.G_RELEASE_CONFIGURATION) ? + "Aki_Data/Server/configs/" : + "./assets/configs/"; const files = this.vfs.getFiles(filepath); // Add file content to result @@ -48,10 +48,13 @@ export class ConfigServer { const fileName = this.vfs.stripExtension(file); const filePathAndName = `${filepath}${file}`; - this.configs[`aki-${fileName}`] = this.jsonUtil.deserializeJsonC(this.vfs.readFile(filePathAndName), filePathAndName); + this.configs[`aki-${fileName}`] = this.jsonUtil.deserializeJsonC( + this.vfs.readFile(filePathAndName), + filePathAndName, + ); } } - + this.logger.info(`Commit hash: ${(this.configs[ConfigTypes.CORE] as ICoreConfig).commit || "DEBUG"}`); this.logger.info(`Build date: ${(this.configs[ConfigTypes.CORE] as ICoreConfig).buildTime || "DEBUG"}`); } diff --git a/project/src/servers/DatabaseServer.ts b/project/src/servers/DatabaseServer.ts index 49c34fa4..e6c48dfa 100644 --- a/project/src/servers/DatabaseServer.ts +++ b/project/src/servers/DatabaseServer.ts @@ -16,7 +16,7 @@ export class DatabaseServer traders: undefined, globals: undefined, server: undefined, - settings: undefined + settings: undefined, }; public getTables(): IDatabaseTables diff --git a/project/src/servers/HttpServer.ts b/project/src/servers/HttpServer.ts index 556322c7..c8f59b5d 100644 --- a/project/src/servers/HttpServer.ts +++ b/project/src/servers/HttpServer.ts @@ -1,5 +1,5 @@ import http, { IncomingMessage, ServerResponse } from "node:http"; -import { inject, injectAll, injectable } from "tsyringe"; +import { inject, injectable, injectAll } from "tsyringe"; import { ApplicationContext } from "@spt-aki/context/ApplicationContext"; import { ContextVariableType } from "@spt-aki/context/ContextVariableType"; @@ -9,8 +9,8 @@ import { IHttpConfig } from "@spt-aki/models/spt/config/IHttpConfig"; import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; import { ConfigServer } from "@spt-aki/servers/ConfigServer"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; -import { WebSocketServer } from "@spt-aki/servers/WebSocketServer"; import { IHttpListener } from "@spt-aki/servers/http/IHttpListener"; +import { WebSocketServer } from "@spt-aki/servers/WebSocketServer"; import { LocalisationService } from "@spt-aki/services/LocalisationService"; @injectable() @@ -26,7 +26,7 @@ export class HttpServer @injectAll("HttpListener") protected httpListeners: IHttpListener[], @inject("ConfigServer") protected configServer: ConfigServer, @inject("ApplicationContext") protected applicationContext: ApplicationContext, - @inject("WebSocketServer") protected webSocketServer: WebSocketServer + @inject("WebSocketServer") protected webSocketServer: WebSocketServer, ) { this.httpConfig = this.configServer.getConfig(ConfigTypes.HTTP); @@ -49,7 +49,9 @@ export class HttpServer /* Config server to listen on a port */ httpServer.listen(this.httpConfig.port, this.httpConfig.ip, () => { - this.logger.success(this.localisationService.getText("started_webserver_success", this.httpServerHelper.getBackendUrl())); + this.logger.success( + this.localisationService.getText("started_webserver_success", this.httpServerHelper.getBackendUrl()), + ); }); httpServer.on("error", (e: any) => @@ -76,11 +78,11 @@ export class HttpServer this.applicationContext.addValue(ContextVariableType.SESSION_ID, sessionId); // http.json logRequests boolean option to allow the user/server to choose to not log requests - if (this.httpConfig.logRequests) + if (this.httpConfig.logRequests) { this.logger.info(this.localisationService.getText("client_request", req.url)); } - + for (const listener of this.httpListeners) { if (listener.canHandle(sessionId, req)) @@ -108,4 +110,4 @@ export class HttpServer return found; } -} \ No newline at end of file +} diff --git a/project/src/servers/RagfairServer.ts b/project/src/servers/RagfairServer.ts index 22fb4b84..87ad6de3 100644 --- a/project/src/servers/RagfairServer.ts +++ b/project/src/servers/RagfairServer.ts @@ -28,7 +28,7 @@ export class RagfairServer @inject("LocalisationService") protected localisationService: LocalisationService, @inject("TraderHelper") protected traderHelper: TraderHelper, @inject("TraderAssortHelper") protected traderAssortHelper: TraderAssortHelper, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); @@ -79,7 +79,7 @@ export class RagfairServer */ protected getUpdateableTraders(): string[] { - return Object.keys(this.ragfairConfig.traders).filter(x => this.ragfairConfig.traders[x]); + return Object.keys(this.ragfairConfig.traders).filter((x) => this.ragfairConfig.traders[x]); } public getAllCategories(): Record @@ -99,7 +99,7 @@ export class RagfairServer public hideOffer(offerId: string): void { const offers = this.ragfairOfferService.getOffers(); - const offer = offers.find(x => x._id === offerId); + const offer = offers.find((x) => x._id === offerId); if (!offer) { @@ -135,4 +135,4 @@ export class RagfairServer { this.ragfairOfferService.addPlayerOffers(); } -} \ No newline at end of file +} diff --git a/project/src/servers/SaveServer.ts b/project/src/servers/SaveServer.ts index 998eb85f..d5edf855 100644 --- a/project/src/servers/SaveServer.ts +++ b/project/src/servers/SaveServer.ts @@ -23,9 +23,9 @@ export class SaveServer @inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("HashUtil") protected hashUtil: HashUtil, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("WinstonLogger") protected logger: ILogger + @inject("WinstonLogger") protected logger: ILogger, ) - { } + {} /** * Add callback to occur prior to saving profile changes @@ -144,7 +144,7 @@ export class SaveServer this.profiles[profileInfo.id] = { info: profileInfo, - characters: { pmc: {}, scav: {}} + characters: {pmc: {}, scav: {}}, }; } @@ -180,14 +180,14 @@ export class SaveServer } /** - * Save changes from in-memory profile to user/profiles json + * Save changes from in-memory profile to user/profiles json * Execute onBeforeSaveCallbacks callbacks prior to being saved to json * @param sessionID profile id (user/profiles/id.json) */ public saveProfile(sessionID: string): void { const filePath = `${this.profileFilepath}${sessionID}.json`; - + // run callbacks for (const callback in this.onBeforeSaveCallbacks) { @@ -198,14 +198,14 @@ export class SaveServer } catch (error) { - this.logger.error(this.localisationService.getText("profile_save_callback_error", { callback, error })); + this.logger.error(this.localisationService.getText("profile_save_callback_error", {callback, error})); this.profiles[sessionID] = previous; } } const jsonProfile = this.jsonUtil.serialize(this.profiles[sessionID], true); const fmd5 = this.hashUtil.generateMd5ForData(jsonProfile); - if (typeof(this.saveMd5[sessionID]) !== "string" || this.saveMd5[sessionID] !== fmd5) + if (typeof (this.saveMd5[sessionID]) !== "string" || this.saveMd5[sessionID] !== fmd5) { this.saveMd5[sessionID] = String(fmd5); // save profile to disk diff --git a/project/src/servers/WebSocketServer.ts b/project/src/servers/WebSocketServer.ts index 678c093d..3b804a85 100644 --- a/project/src/servers/WebSocketServer.ts +++ b/project/src/servers/WebSocketServer.ts @@ -13,17 +13,16 @@ import { JsonUtil } from "@spt-aki/utils/JsonUtil"; import { RandomUtil } from "@spt-aki/utils/RandomUtil"; @injectable() -export class WebSocketServer +export class WebSocketServer { - constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("RandomUtil") protected randomUtil: RandomUtil, @inject("ConfigServer") protected configServer: ConfigServer, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("JsonUtil") protected jsonUtil: JsonUtil, - @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper - ) + @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper, + ) { this.httpConfig = this.configServer.getConfig(ConfigTypes.HTTP); } @@ -31,22 +30,26 @@ export class WebSocketServer protected httpConfig: IHttpConfig; protected defaultNotification: INotification = { type: NotificationType.PING, - eventId: "ping" + eventId: "ping", }; protected webSockets: Record = {}; protected websocketPingHandler = null; - public setupWebSocket(httpServer: http.Server): void + public setupWebSocket(httpServer: http.Server): void { const webSocketServer = new WebSocket.Server({ - server: httpServer + server: httpServer, }); - webSocketServer.addListener("listening", () => + webSocketServer.addListener("listening", () => { - this.logger.success(this.localisationService.getText("websocket-started", this.httpServerHelper.getWebsocketUrl())); - this.logger.success(`${this.localisationService.getText("server_running")}, ${this.getRandomisedMessage()}!`); + this.logger.success( + this.localisationService.getText("websocket-started", this.httpServerHelper.getWebsocketUrl()), + ); + this.logger.success( + `${this.localisationService.getText("server_running")}, ${this.getRandomisedMessage()}!`, + ); }); webSocketServer.addListener("connection", this.wsOnConnection.bind(this)); @@ -72,24 +75,24 @@ export class WebSocketServer } } - protected getRandomisedMessage(): string + protected getRandomisedMessage(): string { - if (this.randomUtil.getInt(1, 1000) > 999) + if (this.randomUtil.getInt(1, 1000) > 999) { return this.localisationService.getRandomTextThatMatchesPartialKey("server_start_meme_"); } - return (globalThis.G_RELEASE_CONFIGURATION) - ? `${this.localisationService.getText("server_start_success")}!` - : this.localisationService.getText("server_start_success"); + return (globalThis.G_RELEASE_CONFIGURATION) ? + `${this.localisationService.getText("server_start_success")}!` : + this.localisationService.getText("server_start_success"); } - public isConnectionWebSocket(sessionID: string): boolean + public isConnectionWebSocket(sessionID: string): boolean { return this.webSockets[sessionID] !== undefined && this.webSockets[sessionID].readyState === WebSocket.OPEN; } - protected wsOnConnection(ws: WebSocket.WebSocket, req: IncomingMessage): void + protected wsOnConnection(ws: WebSocket.WebSocket, req: IncomingMessage): void { // Strip request and break it into sections const splitUrl = req.url.substring(0, req.url.indexOf("?")).split("/"); @@ -99,27 +102,27 @@ export class WebSocketServer const logger = this.logger; const msgToLog = this.localisationService.getText("websocket-received_message", sessionID); - ws.on("message", function message(msg) + ws.on("message", function message(msg) { logger.info(`${msgToLog} ${msg}`); }); this.webSockets[sessionID] = ws; - if (this.websocketPingHandler) + if (this.websocketPingHandler) { clearInterval(this.websocketPingHandler); } - this.websocketPingHandler = setInterval(() => + this.websocketPingHandler = setInterval(() => { this.logger.debug(this.localisationService.getText("websocket-pinging_player", sessionID)); - if (ws.readyState === WebSocket.OPEN) + if (ws.readyState === WebSocket.OPEN) { ws.send(this.jsonUtil.serialize(this.defaultNotification)); } - else + else { this.logger.debug(this.localisationService.getText("websocket-socket_lost_deleting_handle")); clearInterval(this.websocketPingHandler); @@ -127,4 +130,4 @@ export class WebSocketServer } }, this.httpConfig.webSocketPingDelayMs); } -} \ No newline at end of file +} diff --git a/project/src/servers/http/AkiHttpListener.ts b/project/src/servers/http/AkiHttpListener.ts index 08e29f1b..6cc436bc 100644 --- a/project/src/servers/http/AkiHttpListener.ts +++ b/project/src/servers/http/AkiHttpListener.ts @@ -1,6 +1,6 @@ import { IncomingHttpHeaders, IncomingMessage, ServerResponse } from "node:http"; import zlib from "node:zlib"; -import { inject, injectAll, injectable } from "tsyringe"; +import { inject, injectable, injectAll } from "tsyringe"; import { Serializer } from "@spt-aki/di/Serializer"; import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; @@ -13,7 +13,6 @@ import { JsonUtil } from "@spt-aki/utils/JsonUtil"; @injectable() export class AkiHttpListener implements IHttpListener { - constructor( @inject("HttpRouter") protected httpRouter: HttpRouter, // TODO: delay required @injectAll("Serializer") protected serializers: Serializer[], @@ -21,7 +20,7 @@ export class AkiHttpListener implements IHttpListener @inject("RequestsLogger") protected requestsLogger: ILogger, @inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, - @inject("LocalisationService") protected localisationService: LocalisationService + @inject("LocalisationService") protected localisationService: LocalisationService, ) { } @@ -53,7 +52,7 @@ export class AkiHttpListener implements IHttpListener const buffer = Buffer.alloc(requestLength); let written = 0; - req.on("data", (data: any) => + req.on("data", (data: any) => { data.copy(buffer, written, 0); written += data.length; @@ -96,7 +95,13 @@ export class AkiHttpListener implements IHttpListener * @param body Buffer * @param output Server generated response data */ - public sendResponse(sessionID: string, req: IncomingMessage, resp: ServerResponse, body: Buffer, output: string): void + public sendResponse( + sessionID: string, + req: IncomingMessage, + resp: ServerResponse, + body: Buffer, + output: string, + ): void { const info = this.getBodyInfo(body); let handled = false; @@ -136,9 +141,9 @@ export class AkiHttpListener implements IHttpListener if (globalThis.G_LOG_REQUESTS) { // Parse quest info into object - const data = (typeof info === "object") - ? info - : this.jsonUtil.deserialize(info); + const data = (typeof info === "object") ? + info : + this.jsonUtil.deserialize(info); const log = new Request(req.method, new RequestData(req.url, req.headers, data)); this.requestsLogger.info(`REQUEST=${this.jsonUtil.serialize(log)}`); @@ -150,32 +155,31 @@ export class AkiHttpListener implements IHttpListener { this.logger.error(this.localisationService.getText("unhandled_response", req.url)); this.logger.info(info); - output = this.httpResponse.getBody(null, 404, `UNHANDLED RESPONSE: ${req.url}`); + output = this.httpResponse.getBody(null, 404, `UNHANDLED RESPONSE: ${req.url}`); } return output; } - protected getBodyInfo(body: Buffer, requestUrl = null): any + protected getBodyInfo(body: Buffer, requestUrl = null): any { - const text = (body) ? body.toString() : "{}"; - const info = (text) ? this.jsonUtil.deserialize(text, requestUrl) : {}; + const text = body ? body.toString() : "{}"; + const info = text ? this.jsonUtil.deserialize(text, requestUrl) : {}; return info; } public sendJson(resp: ServerResponse, output: string, sessionID: string): void { // eslint-disable-next-line @typescript-eslint/naming-convention - resp.writeHead(200, "OK", { "Content-Type": "application/json", "Set-Cookie": `PHPSESSID=${sessionID}` }); + resp.writeHead(200, "OK", {"Content-Type": "application/json", "Set-Cookie": `PHPSESSID=${sessionID}`}); resp.end(output); } public sendZlibJson(resp: ServerResponse, output: string, sessionID: string): void { // eslint-disable-next-line @typescript-eslint/naming-convention - resp.writeHead(200, "OK", { "Content-Type": "application/json", "Set-Cookie": `PHPSESSID=${sessionID}` }); + resp.writeHead(200, "OK", {"Content-Type": "application/json", "Set-Cookie": `PHPSESSID=${sessionID}`}); zlib.deflate(output, (_, buf) => resp.end(buf)); } - } class RequestData @@ -183,7 +187,7 @@ class RequestData constructor( public url: string, public headers: IncomingHttpHeaders, - public data?: any + public data?: any, ) {} } @@ -192,7 +196,7 @@ class Request { constructor( public type: string, - public req: RequestData + public req: RequestData, ) {} } @@ -201,7 +205,7 @@ class Response { constructor( public type: string, - public response: any + public response: any, ) {} -} \ No newline at end of file +} diff --git a/project/src/servers/http/HttpMethods.ts b/project/src/servers/http/HttpMethods.ts index a5be4da3..031ca7c1 100644 --- a/project/src/servers/http/HttpMethods.ts +++ b/project/src/servers/http/HttpMethods.ts @@ -1,9 +1,9 @@ -export enum HttpMethods - { +export enum HttpMethods +{ OPTIONS = "OPTIONS", GET = "GET", POST = "POST", PUT = "PUT", PATCH = "PATCH", - DELETE = "DELETE" -} \ No newline at end of file + DELETE = "DELETE", +} diff --git a/project/src/servers/http/IHttpListener.ts b/project/src/servers/http/IHttpListener.ts index 22b8bbd8..9d746768 100644 --- a/project/src/servers/http/IHttpListener.ts +++ b/project/src/servers/http/IHttpListener.ts @@ -2,6 +2,6 @@ import { IncomingMessage, ServerResponse } from "node:http"; export interface IHttpListener { - canHandle(sessionId: string, req: IncomingMessage): boolean - handle(sessionId: string, req: IncomingMessage, resp: ServerResponse): void -} \ No newline at end of file + canHandle(sessionId: string, req: IncomingMessage): boolean; + handle(sessionId: string, req: IncomingMessage, resp: ServerResponse): void; +} From 857692940428b53c80f7e155c90c035b714e1976 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:13:25 -0500 Subject: [PATCH 32/41] Formatting for services. --- .../src/services/BotEquipmentFilterService.ts | 113 +++++-- .../services/BotEquipmentModPoolService.ts | 27 +- .../src/services/BotGenerationCacheService.ts | 16 +- project/src/services/BotLootCacheService.ts | 145 +++++---- .../src/services/BotWeaponModLimitService.ts | 73 +++-- .../src/services/CustomLocationWaveService.ts | 12 +- project/src/services/FenceService.ts | 166 ++++++---- project/src/services/GiftService.ts | 32 +- project/src/services/HashCacheService.ts | 12 +- project/src/services/InsuranceService.ts | 82 +++-- project/src/services/ItemBaseClassService.ts | 8 +- project/src/services/ItemFilterService.ts | 8 +- project/src/services/LocaleService.ts | 12 +- project/src/services/LocalisationService.ts | 19 +- project/src/services/MailSendService.ts | 127 ++++++-- .../services/MatchBotDetailsCacheService.ts | 5 +- project/src/services/MatchLocationService.ts | 12 +- project/src/services/ModCompilerService.ts | 66 ++-- project/src/services/NotificationService.ts | 2 +- project/src/services/OpenZoneService.ts | 6 +- project/src/services/PaymentService.ts | 99 ++++-- project/src/services/PlayerService.ts | 7 +- .../src/services/PmcChatResponseService.ts | 90 ++++-- project/src/services/ProfileFixerService.ts | 301 ++++++++++++------ .../src/services/ProfileSnapshotService.ts | 6 +- .../src/services/RagfairCategoriesService.ts | 24 +- .../src/services/RagfairLinkedItemService.ts | 21 +- project/src/services/RagfairOfferService.ts | 19 +- project/src/services/RagfairPriceService.ts | 73 +++-- .../services/RagfairRequiredItemsService.ts | 7 +- project/src/services/RagfairTaxService.ts | 55 +++- project/src/services/RepairService.ts | 172 ++++++---- project/src/services/SeasonalEventService.ts | 93 ++++-- project/src/services/TraderAssortService.ts | 4 +- .../TraderPurchasePersisterService.ts | 19 +- project/src/services/mod/CustomItemService.ts | 23 +- .../mod/dynamicRouter/DynamicRouterMod.ts | 8 +- .../dynamicRouter/DynamicRouterModService.ts | 10 +- .../mod/httpListener/HttpListenerMod.ts | 10 +- .../httpListener/HttpListenerModService.ts | 16 +- .../services/mod/image/ImageRouteService.ts | 2 +- project/src/services/mod/onLoad/OnLoadMod.ts | 10 +- .../services/mod/onLoad/OnLoadModService.ts | 12 +- .../src/services/mod/onUpdate/OnUpdateMod.ts | 10 +- .../mod/onUpdate/OnUpdateModService.ts | 12 +- .../mod/staticRouter/StaticRouterMod.ts | 8 +- .../staticRouter/StaticRouterModService.ts | 10 +- 47 files changed, 1325 insertions(+), 739 deletions(-) diff --git a/project/src/services/BotEquipmentFilterService.ts b/project/src/services/BotEquipmentFilterService.ts index 597a1dd2..2abb7aa0 100644 --- a/project/src/services/BotEquipmentFilterService.ts +++ b/project/src/services/BotEquipmentFilterService.ts @@ -3,16 +3,20 @@ import { inject, injectable } from "tsyringe"; import { BotHelper } from "@spt-aki/helpers/BotHelper"; import { ProfileHelper } from "@spt-aki/helpers/ProfileHelper"; import { - EquipmentChances, Generation, + EquipmentChances, + Generation, GenerationData, IBotType, - ModsChances + ModsChances, } from "@spt-aki/models/eft/common/tables/IBotType"; import { ConfigTypes } from "@spt-aki/models/enums/ConfigTypes"; import { BotGenerationDetails } from "@spt-aki/models/spt/bots/BotGenerationDetails"; import { - AdjustmentDetails, EquipmentFilterDetails, EquipmentFilters, IBotConfig, - WeightingAdjustmentDetails + AdjustmentDetails, + EquipmentFilterDetails, + EquipmentFilters, + IBotConfig, + WeightingAdjustmentDetails, } from "@spt-aki/models/spt/config/IBotConfig"; import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; import { ConfigServer } from "@spt-aki/servers/ConfigServer"; @@ -27,7 +31,7 @@ export class BotEquipmentFilterService @inject("WinstonLogger") protected logger: ILogger, @inject("BotHelper") protected botHelper: BotHelper, @inject("ProfileHelper") protected profileHelper: ProfileHelper, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); @@ -41,27 +45,35 @@ export class BotEquipmentFilterService * @param botLevel Level of the bot * @param botGenerationDetails details on how to generate a bot */ - public filterBotEquipment(sessionId: string, baseBotNode: IBotType, botLevel: number, botGenerationDetails: BotGenerationDetails): void + public filterBotEquipment( + sessionId: string, + baseBotNode: IBotType, + botLevel: number, + botGenerationDetails: BotGenerationDetails, + ): void { const pmcProfile = this.profileHelper.getPmcProfile(sessionId); - const botRole = (botGenerationDetails.isPmc) - ? "pmc" - : botGenerationDetails.role; + const botRole = (botGenerationDetails.isPmc) ? + "pmc" : + botGenerationDetails.role; const botEquipmentBlacklist = this.getBotEquipmentBlacklist(botRole, botLevel); const botEquipmentWhitelist = this.getBotEquipmentWhitelist(botRole, botLevel); const botWeightingAdjustments = this.getBotWeightingAdjustments(botRole, botLevel); - const botWeightingAdjustmentsByPlayerLevel = this.getBotWeightingAdjustmentsByPlayerLevel(botRole, pmcProfile.Info.Level); + const botWeightingAdjustmentsByPlayerLevel = this.getBotWeightingAdjustmentsByPlayerLevel( + botRole, + pmcProfile.Info.Level, + ); const botEquipConfig = this.botConfig.equipment[botRole]; const randomisationDetails = this.botHelper.getBotRandomizationDetails(botLevel, botEquipConfig); - + if (botEquipmentBlacklist || botEquipmentWhitelist) { this.filterEquipment(baseBotNode, botEquipmentBlacklist, botEquipmentWhitelist); this.filterCartridges(baseBotNode, botEquipmentBlacklist, botEquipmentWhitelist); } - + if (botWeightingAdjustments) { this.adjustWeighting(botWeightingAdjustments?.equipment, baseBotNode.inventory.equipment); @@ -107,7 +119,10 @@ export class BotEquipmentFilterService * @param generationChanges Changes to apply * @param baseBotGeneration dictionary to update */ - protected adjustGenerationChances(generationChanges: Record, baseBotGeneration: Generation): void + protected adjustGenerationChances( + generationChanges: Record, + baseBotGeneration: Generation, + ): void { if (!generationChanges) { @@ -159,12 +174,17 @@ export class BotEquipmentFilterService const blacklistDetailsForBot = this.botEquipmentConfig[botRole]; // No equipment blacklist found, skip - if (!blacklistDetailsForBot || Object.keys(blacklistDetailsForBot).length === 0 || !blacklistDetailsForBot.blacklist) + if ( + !blacklistDetailsForBot || Object.keys(blacklistDetailsForBot).length === 0 || + !blacklistDetailsForBot.blacklist + ) { return null; } - return blacklistDetailsForBot.blacklist.find(x => playerLevel >= x.levelRange.min && playerLevel <= x.levelRange.max); + return blacklistDetailsForBot.blacklist.find((x) => + playerLevel >= x.levelRange.min && playerLevel <= x.levelRange.max + ); } /** @@ -183,7 +203,9 @@ export class BotEquipmentFilterService return null; } - return botEquipmentConfig.whitelist.find(x => playerLevel >= x.levelRange.min && playerLevel <= x.levelRange.max); + return botEquipmentConfig.whitelist.find((x) => + playerLevel >= x.levelRange.min && playerLevel <= x.levelRange.max + ); } /** @@ -197,12 +219,17 @@ export class BotEquipmentFilterService const botEquipmentConfig = this.botEquipmentConfig[botRole]; // No config found, skip - if (!botEquipmentConfig || Object.keys(botEquipmentConfig).length === 0 || !botEquipmentConfig.weightingAdjustmentsByBotLevel) + if ( + !botEquipmentConfig || Object.keys(botEquipmentConfig).length === 0 || + !botEquipmentConfig.weightingAdjustmentsByBotLevel + ) { return null; } - return botEquipmentConfig.weightingAdjustmentsByBotLevel.find(x => botLevel >= x.levelRange.min && botLevel <= x.levelRange.max); + return botEquipmentConfig.weightingAdjustmentsByBotLevel.find((x) => + botLevel >= x.levelRange.min && botLevel <= x.levelRange.max + ); } /** @@ -216,12 +243,17 @@ export class BotEquipmentFilterService const botEquipmentConfig = this.botEquipmentConfig[botRole]; // No config found, skip - if (!botEquipmentConfig || Object.keys(botEquipmentConfig).length === 0 || !botEquipmentConfig.weightingAdjustmentsByPlayerLevel) + if ( + !botEquipmentConfig || Object.keys(botEquipmentConfig).length === 0 || + !botEquipmentConfig.weightingAdjustmentsByPlayerLevel + ) { return null; } - return botEquipmentConfig.weightingAdjustmentsByPlayerLevel.find(x => playerlevel >= x.levelRange.min && playerlevel <= x.levelRange.max); + return botEquipmentConfig.weightingAdjustmentsByPlayerLevel.find((x) => + playerlevel >= x.levelRange.min && playerlevel <= x.levelRange.max + ); } /** @@ -231,7 +263,11 @@ export class BotEquipmentFilterService * @param blacklist equipment blacklist * @returns Filtered bot file */ - protected filterEquipment(baseBotNode: IBotType, blacklist: EquipmentFilterDetails, whitelist: EquipmentFilterDetails): void + protected filterEquipment( + baseBotNode: IBotType, + blacklist: EquipmentFilterDetails, + whitelist: EquipmentFilterDetails, + ): void { if (whitelist) { @@ -247,7 +283,9 @@ export class BotEquipmentFilterService } // Filter equipment slot items to just items in whitelist - baseBotNode.inventory.equipment[equipmentSlotKey] = Object.keys(botEquipment).filter((tpl) => whitelistEquipmentForSlot.includes(tpl)).reduce( (res, key) => (res[key] = botEquipment[key], res), {} ); + baseBotNode.inventory.equipment[equipmentSlotKey] = Object.keys(botEquipment).filter((tpl) => + whitelistEquipmentForSlot.includes(tpl) + ).reduce((res, key) => (res[key] = botEquipment[key], res), {}); } return; @@ -267,7 +305,9 @@ export class BotEquipmentFilterService } // Filter equipment slot items to just items not in blacklist - baseBotNode.inventory.equipment[equipmentSlotKey] = Object.keys(botEquipment).filter((tpl) => !equipmentSlotBlacklist.includes(tpl)).reduce( (res, key) => (res[key] = botEquipment[key], res), {} ); + baseBotNode.inventory.equipment[equipmentSlotKey] = Object.keys(botEquipment).filter((tpl) => + !equipmentSlotBlacklist.includes(tpl) + ).reduce((res, key) => (res[key] = botEquipment[key], res), {}); } } } @@ -280,7 +320,11 @@ export class BotEquipmentFilterService * @param whitelist equipment on this list should be used exclusively * @returns Filtered bot file */ - protected filterCartridges(baseBotNode: IBotType, blacklist: EquipmentFilterDetails, whitelist: EquipmentFilterDetails): void + protected filterCartridges( + baseBotNode: IBotType, + blacklist: EquipmentFilterDetails, + whitelist: EquipmentFilterDetails, + ): void { if (whitelist) { @@ -296,7 +340,9 @@ export class BotEquipmentFilterService } // Filter caliber slot items to just items in whitelist - baseBotNode.inventory.Ammo[ammoCaliberKey] = Object.keys(botAmmo).filter((tpl) => whitelist.cartridge[ammoCaliberKey].includes(tpl)).reduce( (res, key) => (res[key] = botAmmo[key], res), {} ); + baseBotNode.inventory.Ammo[ammoCaliberKey] = Object.keys(botAmmo).filter((tpl) => + whitelist.cartridge[ammoCaliberKey].includes(tpl) + ).reduce((res, key) => (res[key] = botAmmo[key], res), {}); } return; @@ -316,7 +362,9 @@ export class BotEquipmentFilterService } // Filter cartridge slot items to just items not in blacklist - baseBotNode.inventory.Ammo[ammoCaliberKey] = Object.keys(botAmmo).filter((tpl) => !cartridgeCaliberBlacklist.includes(tpl)).reduce( (res, key) => (res[key] = botAmmo[key], res), {} ); + baseBotNode.inventory.Ammo[ammoCaliberKey] = Object.keys(botAmmo).filter((tpl) => + !cartridgeCaliberBlacklist.includes(tpl) + ).reduce((res, key) => (res[key] = botAmmo[key], res), {}); } } } @@ -326,7 +374,11 @@ export class BotEquipmentFilterService * @param weightingAdjustments Weighting change to apply to bot * @param botItemPool Bot item dictionary to adjust */ - protected adjustWeighting(weightingAdjustments: AdjustmentDetails, botItemPool: Record, showEditWarnings = true): void + protected adjustWeighting( + weightingAdjustments: AdjustmentDetails, + botItemPool: Record, + showEditWarnings = true, + ): void { if (!weightingAdjustments) { @@ -361,12 +413,13 @@ export class BotEquipmentFilterService { if (showEditWarnings) { - this.logger.warning(`Tried to edit a non-existent item for slot: ${poolAdjustmentKey} ${itemToEditKey}`); + this.logger.warning( + `Tried to edit a non-existent item for slot: ${poolAdjustmentKey} ${itemToEditKey}`, + ); } } } } } } - -} \ No newline at end of file +} diff --git a/project/src/services/BotEquipmentModPoolService.ts b/project/src/services/BotEquipmentModPoolService.ts index df906d1e..a6b944a6 100644 --- a/project/src/services/BotEquipmentModPoolService.ts +++ b/project/src/services/BotEquipmentModPoolService.ts @@ -28,7 +28,7 @@ export class BotEquipmentModPoolService @inject("ItemHelper") protected itemHelper: ItemHelper, @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); @@ -48,12 +48,17 @@ export class BotEquipmentModPoolService } // Get weapon or gear pool - const pool = (poolType === "weapon" ? this.weaponModPool : this.gearModPool); + const pool = poolType === "weapon" ? this.weaponModPool : this.gearModPool; for (const item of items) { if (!item._props) { - this.logger.error(this.localisationService.getText("bot-item_missing_props_property", {itemTpl: item._id, name: item._name})); + this.logger.error( + this.localisationService.getText("bot-item_missing_props_property", { + itemTpl: item._id, + name: item._name, + }), + ); continue; } @@ -85,9 +90,9 @@ export class BotEquipmentModPoolService { pool[item._id][slot._name] = []; } - + // only add item to pool if it doesnt already exist - if (!pool[item._id][slot._name].some(x => x === itemToAdd)) + if (!pool[item._id][slot._name].some((x) => x === itemToAdd)) { pool[item._id][slot._name].push(itemToAdd); @@ -99,7 +104,7 @@ export class BotEquipmentModPoolService // Recursive call this.generatePool([subItemDetails], poolType); } - } + } } } } @@ -181,7 +186,9 @@ export class BotEquipmentModPoolService */ protected generateWeaponPool(): void { - const weapons = Object.values(this.databaseServer.getTables().templates.items).filter(x => x._type === "Item" && this.itemHelper.isOfBaseclass(x._id, BaseClasses.WEAPON)); + const weapons = Object.values(this.databaseServer.getTables().templates.items).filter((x) => + x._type === "Item" && this.itemHelper.isOfBaseclass(x._id, BaseClasses.WEAPON) + ); this.generatePool(weapons, "weapon"); // Flag pool as being complete @@ -193,10 +200,12 @@ export class BotEquipmentModPoolService */ protected generateGearPool(): void { - const gear = Object.values(this.databaseServer.getTables().templates.items).filter(x => x._type === "Item" && this.itemHelper.isOfBaseclass(x._id, BaseClasses.ARMOREDEQUIPMENT)); + const gear = Object.values(this.databaseServer.getTables().templates.items).filter((x) => + x._type === "Item" && this.itemHelper.isOfBaseclass(x._id, BaseClasses.ARMOREDEQUIPMENT) + ); this.generatePool(gear, "gear"); // Flag pool as being complete this.armorPoolGenerated = true; } -} \ No newline at end of file +} diff --git a/project/src/services/BotGenerationCacheService.ts b/project/src/services/BotGenerationCacheService.ts index f77e64be..4445c1c4 100644 --- a/project/src/services/BotGenerationCacheService.ts +++ b/project/src/services/BotGenerationCacheService.ts @@ -11,22 +11,22 @@ import { RandomUtil } from "@spt-aki/utils/RandomUtil"; export class BotGenerationCacheService { protected storedBots: Map = new Map(); - + constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("RandomUtil") protected randomUtil: RandomUtil, @inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("BotHelper") protected botHelper: BotHelper + @inject("BotHelper") protected botHelper: BotHelper, ) - { } - + {} + /** * Store array of bots in cache, shuffle results before storage * @param botsToStore Bots we want to store in the cache */ public storeBots(key: string, botsToStore: IBotBase[]): void - { + { for (const bot of botsToStore) { if (this.storedBots.has(key)) @@ -63,7 +63,7 @@ export class BotGenerationCacheService return undefined; } - + /** * Remove all cached bot profiles from memory */ @@ -71,7 +71,7 @@ export class BotGenerationCacheService { this.storedBots = new Map(); } - + /** * Does cache have a bot with requested key * @returns false if empty @@ -80,4 +80,4 @@ export class BotGenerationCacheService { return this.storedBots.has(key) && this.storedBots.get(key).length > 0; } -} \ No newline at end of file +} diff --git a/project/src/services/BotLootCacheService.ts b/project/src/services/BotLootCacheService.ts index 3e736c7c..bb7f3895 100644 --- a/project/src/services/BotLootCacheService.ts +++ b/project/src/services/BotLootCacheService.ts @@ -24,7 +24,7 @@ export class BotLootCacheService @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("PMCLootGenerator") protected pmcLootGenerator: PMCLootGenerator, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("RagfairPriceService") protected ragfairPriceService: RagfairPriceService + @inject("RagfairPriceService") protected ragfairPriceService: RagfairPriceService, ) { this.clearCache(); @@ -46,7 +46,12 @@ export class BotLootCacheService * @param botJsonTemplate Base json db file for the bot having its loot generated * @returns ITemplateItem array */ - public getLootFromCache(botRole: string, isPmc: boolean, lootType: LootCacheType, botJsonTemplate: IBotType): ITemplateItem[] + public getLootFromCache( + botRole: string, + isPmc: boolean, + lootType: LootCacheType, + botJsonTemplate: IBotType, + ): ITemplateItem[] { if (!this.botRoleExistsInCache(botRole)) { @@ -75,7 +80,13 @@ export class BotLootCacheService case LootCacheType.STIM_ITEMS: return this.lootCache[botRole].stimItems; default: - this.logger.error(this.localisationService.getText("bot-loot_type_not_found", {lootType: lootType, botRole: botRole, isPmc: isPmc})); + this.logger.error( + this.localisationService.getText("bot-loot_type_not_found", { + lootType: lootType, + botRole: botRole, + isPmc: isPmc, + }), + ); break; } } @@ -138,7 +149,7 @@ export class BotLootCacheService itemsToAdd = pool.map((lootTpl: string) => items[lootTpl]); this.addUniqueItemsToPool(backpackLootTemplates, itemsToAdd); } - + // Add items to combined pool if any exist if (Object.keys(itemsToAdd).length > 0) { @@ -154,61 +165,67 @@ export class BotLootCacheService this.sortPoolByRagfairPrice(combinedPoolTemplates); // use whitelist if array has values, otherwise process above sorted pools - const specialLootItems = (botJsonTemplate.generation.items.specialItems.whitelist?.length > 0) - ? botJsonTemplate.generation.items.specialItems.whitelist.map(x => this.itemHelper.getItem(x)[1]) - : specialLootTemplates.filter(template => - !(this.isBulletOrGrenade(template._props) - || this.isMagazine(template._props))); + const specialLootItems = (botJsonTemplate.generation.items.specialItems.whitelist?.length > 0) ? + botJsonTemplate.generation.items.specialItems.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : + specialLootTemplates.filter((template) => + !(this.isBulletOrGrenade(template._props) || + this.isMagazine(template._props)) + ); - const healingItems = (botJsonTemplate.generation.items.healing.whitelist?.length > 0) - ? botJsonTemplate.generation.items.healing.whitelist.map(x => this.itemHelper.getItem(x)[1]) - : combinedPoolTemplates.filter(template => - this.isMedicalItem(template._props) - && template._parent !== BaseClasses.STIMULATOR - && template._parent !== BaseClasses.DRUGS); + const healingItems = (botJsonTemplate.generation.items.healing.whitelist?.length > 0) ? + botJsonTemplate.generation.items.healing.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : + combinedPoolTemplates.filter((template) => + this.isMedicalItem(template._props) && + template._parent !== BaseClasses.STIMULATOR && + template._parent !== BaseClasses.DRUGS + ); - const drugItems = (botJsonTemplate.generation.items.drugs.whitelist?.length > 0) - ? botJsonTemplate.generation.items.drugs.whitelist.map(x => this.itemHelper.getItem(x)[1]) - : combinedPoolTemplates.filter(template => - this.isMedicalItem(template._props) - && template._parent === BaseClasses.DRUGS); + const drugItems = (botJsonTemplate.generation.items.drugs.whitelist?.length > 0) ? + botJsonTemplate.generation.items.drugs.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : + combinedPoolTemplates.filter((template) => + this.isMedicalItem(template._props) && + template._parent === BaseClasses.DRUGS + ); - const stimItems = (botJsonTemplate.generation.items.stims.whitelist?.length > 0) - ? botJsonTemplate.generation.items.stims.whitelist.map(x => this.itemHelper.getItem(x)[1]) - : combinedPoolTemplates.filter(template => - this.isMedicalItem(template._props) - && template._parent === BaseClasses.STIMULATOR); + const stimItems = (botJsonTemplate.generation.items.stims.whitelist?.length > 0) ? + botJsonTemplate.generation.items.stims.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : + combinedPoolTemplates.filter((template) => + this.isMedicalItem(template._props) && + template._parent === BaseClasses.STIMULATOR + ); - const grenadeItems = (botJsonTemplate.generation.items.grenades.whitelist?.length > 0) - ? botJsonTemplate.generation.items.grenades.whitelist.map(x => this.itemHelper.getItem(x)[1]) - : combinedPoolTemplates.filter(template => - this.isGrenade(template._props)); + const grenadeItems = (botJsonTemplate.generation.items.grenades.whitelist?.length > 0) ? + botJsonTemplate.generation.items.grenades.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : + combinedPoolTemplates.filter((template) => this.isGrenade(template._props)); // Get loot items (excluding magazines, bullets, grenades and healing items) - const backpackLootItems = backpackLootTemplates.filter(template => + const backpackLootItems = backpackLootTemplates.filter((template) => // biome-ignore lint/complexity/useSimplifiedLogicExpression: - !this.isBulletOrGrenade(template._props) - && !this.isMagazine(template._props) - //&& !this.isMedicalItem(template._props) // Disabled for now as followSanitar has a lot of med items as loot - && !this.isGrenade(template._props)); + !this.isBulletOrGrenade(template._props) && + !this.isMagazine(template._props) && + // && !this.isMedicalItem(template._props) // Disabled for now as followSanitar has a lot of med items as loot + !this.isGrenade(template._props) + ); // Get pocket loot - const pocketLootItems = pocketLootTemplates.filter(template => + const pocketLootItems = pocketLootTemplates.filter((template) => // biome-ignore lint/complexity/useSimplifiedLogicExpression: - !this.isBulletOrGrenade(template._props) - && !this.isMagazine(template._props) - && !this.isMedicalItem(template._props) - && !this.isGrenade(template._props) - && ("Height" in template._props) - && ("Width" in template._props)); + !this.isBulletOrGrenade(template._props) && + !this.isMagazine(template._props) && + !this.isMedicalItem(template._props) && + !this.isGrenade(template._props) && + ("Height" in template._props) && + ("Width" in template._props) + ); // Get vest loot items - const vestLootItems = vestLootTemplates.filter(template => + const vestLootItems = vestLootTemplates.filter((template) => // biome-ignore lint/complexity/useSimplifiedLogicExpression: - !this.isBulletOrGrenade(template._props) - && !this.isMagazine(template._props) - && !this.isMedicalItem(template._props) - && !this.isGrenade(template._props)); + !this.isBulletOrGrenade(template._props) && + !this.isMagazine(template._props) && + !this.isMedicalItem(template._props) && + !this.isGrenade(template._props) + ); this.lootCache[botRole].healingItems = healingItems; this.lootCache[botRole].drugItems = drugItems; @@ -227,7 +244,12 @@ export class BotLootCacheService */ protected sortPoolByRagfairPrice(poolToSort: ITemplateItem[]): void { - poolToSort.sort((a, b) => this.compareByValue(this.ragfairPriceService.getFleaPriceForItem(a._id), this.ragfairPriceService.getFleaPriceForItem(b._id))); + poolToSort.sort((a, b) => + this.compareByValue( + this.ragfairPriceService.getFleaPriceForItem(a._id), + this.ragfairPriceService.getFleaPriceForItem(b._id), + ) + ); } /** @@ -246,15 +268,15 @@ export class BotLootCacheService const mergedItemPools = [...combinedItemPool, ...itemsToAdd]; // Save only unique array values - const uniqueResults = [... new Set([].concat(...mergedItemPools))]; + const uniqueResults = [...new Set([].concat(...mergedItemPools))]; combinedItemPool.splice(0, combinedItemPool.length); combinedItemPool.push(...uniqueResults); } /** * Ammo/grenades have this property - * @param props - * @returns + * @param props + * @returns */ protected isBulletOrGrenade(props: Props): boolean { @@ -263,8 +285,8 @@ export class BotLootCacheService /** * Internal and external magazine have this property - * @param props - * @returns + * @param props + * @returns */ protected isMagazine(props: Props): boolean { @@ -273,8 +295,8 @@ export class BotLootCacheService /** * Medical use items (e.g. morphine/lip balm/grizzly) - * @param props - * @returns + * @param props + * @returns */ protected isMedicalItem(props: Props): boolean { @@ -283,8 +305,8 @@ export class BotLootCacheService /** * Grenades have this property (e.g. smoke/frag/flash grenades) - * @param props - * @returns + * @param props + * @returns */ protected isGrenade(props: Props): boolean { @@ -317,7 +339,7 @@ export class BotLootCacheService grenadeItems: [], drugItems: [], healingItems: [], - stimItems: [] + stimItems: [], }; } @@ -326,9 +348,9 @@ export class BotLootCacheService * -1 when a < b * 0 when a === b * 1 when a > b - * @param itemAPrice - * @param itemBPrice - * @returns + * @param itemAPrice + * @param itemBPrice + * @returns */ protected compareByValue(itemAPrice: number, itemBPrice: number): number { @@ -355,5 +377,4 @@ export class BotLootCacheService return 0; } - -} \ No newline at end of file +} diff --git a/project/src/services/BotWeaponModLimitService.ts b/project/src/services/BotWeaponModLimitService.ts index 89bee596..052756a7 100644 --- a/project/src/services/BotWeaponModLimitService.ts +++ b/project/src/services/BotWeaponModLimitService.ts @@ -32,7 +32,7 @@ export class BotWeaponModLimitService constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("ConfigServer") protected configServer: ConfigServer, - @inject("ItemHelper") protected itemHelper: ItemHelper + @inject("ItemHelper") protected itemHelper: ItemHelper, ) { this.botConfig = this.configServer.getConfig(ConfigTypes.BOT); @@ -48,10 +48,20 @@ export class BotWeaponModLimitService return { scope: {count: 0}, scopeMax: this.botConfig.equipment[botRole]?.weaponModLimits?.scopeLimit, - scopeBaseTypes: [BaseClasses.OPTIC_SCOPE, BaseClasses.ASSAULT_SCOPE, BaseClasses.COLLIMATOR, BaseClasses.COMPACT_COLLIMATOR, BaseClasses.SPECIAL_SCOPE], + scopeBaseTypes: [ + BaseClasses.OPTIC_SCOPE, + BaseClasses.ASSAULT_SCOPE, + BaseClasses.COLLIMATOR, + BaseClasses.COMPACT_COLLIMATOR, + BaseClasses.SPECIAL_SCOPE, + ], flashlightLaser: {count: 0}, flashlightLaserMax: this.botConfig.equipment[botRole]?.weaponModLimits?.lightLaserLimit, - flashlgihtLaserBaseTypes: [BaseClasses.TACTICAL_COMBO, BaseClasses.FLASHLIGHT, BaseClasses.PORTABLE_RANGE_FINDER] + flashlgihtLaserBaseTypes: [ + BaseClasses.TACTICAL_COMBO, + BaseClasses.FLASHLIGHT, + BaseClasses.PORTABLE_RANGE_FINDER, + ], }; } @@ -67,14 +77,28 @@ export class BotWeaponModLimitService * @param modsParent The parent of the mod to be checked * @returns true if over item limit */ - public weaponModHasReachedLimit(botRole: string, modTemplate: ITemplateItem, modLimits: BotModLimits, modsParent: ITemplateItem, weapon: Item[]): boolean + public weaponModHasReachedLimit( + botRole: string, + modTemplate: ITemplateItem, + modLimits: BotModLimits, + modsParent: ITemplateItem, + weapon: Item[], + ): boolean { // If mod or mods parent is the NcSTAR MPR45 Backup mount, allow it as it looks cool const ncSTARTpl = "5649a2464bdc2d91118b45a8"; if (modsParent._id === ncSTARTpl || modTemplate._id === ncSTARTpl) { // If weapon already has a longer ranged scope on it, allow ncstar to be spawned - if (weapon.some(x => this.itemHelper.isOfBaseclasses(x._tpl, [BaseClasses.ASSAULT_SCOPE, BaseClasses.OPTIC_SCOPE, BaseClasses.SPECIAL_SCOPE]))) + if ( + weapon.some((x) => + this.itemHelper.isOfBaseclasses(x._tpl, [ + BaseClasses.ASSAULT_SCOPE, + BaseClasses.OPTIC_SCOPE, + BaseClasses.SPECIAL_SCOPE, + ]) + ) + ) { return false; } @@ -96,10 +120,12 @@ export class BotWeaponModLimitService } // Mod is a mount that can hold only scopes and limit is reached (dont want to add empty mounts if limit is reached) - if (this.itemHelper.isOfBaseclass(modTemplate._id, BaseClasses.MOUNT) - && modTemplate._props.Slots.some(x => x._name === "mod_scope") - && modTemplate._props.Slots.length === 1 - && modLimits.scope.count >= modLimits.scopeMax) + if ( + this.itemHelper.isOfBaseclass(modTemplate._id, BaseClasses.MOUNT) && + modTemplate._props.Slots.some((x) => x._name === "mod_scope") && + modTemplate._props.Slots.length === 1 && + modLimits.scope.count >= modLimits.scopeMax + ) { return true; } @@ -108,14 +134,21 @@ export class BotWeaponModLimitService const modIsLightOrLaser = this.itemHelper.isOfBaseclasses(modTemplate._id, modLimits.flashlgihtLaserBaseTypes); if (modIsLightOrLaser) { - return this.weaponModLimitReached(modTemplate._id, modLimits.flashlightLaser, modLimits.flashlightLaserMax, botRole); + return this.weaponModLimitReached( + modTemplate._id, + modLimits.flashlightLaser, + modLimits.flashlightLaserMax, + botRole, + ); } // Mod is a mount that can hold only flashlights ad limit is reached (dont want to add empty mounts if limit is reached) - if (this.itemHelper.isOfBaseclass(modTemplate._id, BaseClasses.MOUNT) - && modTemplate._props.Slots.some(x => x._name === "mod_flashlight") - && modTemplate._props.Slots.length === 1 - && modLimits.scope.count >= modLimits.scopeMax) + if ( + this.itemHelper.isOfBaseclass(modTemplate._id, BaseClasses.MOUNT) && + modTemplate._props.Slots.some((x) => x._name === "mod_flashlight") && + modTemplate._props.Slots.length === 1 && + modLimits.scope.count >= modLimits.scopeMax + ) { return true; } @@ -131,8 +164,12 @@ export class BotWeaponModLimitService * @param botRole role of bot we're checking weapon of * @returns true if limit reached */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - protected weaponModLimitReached(modTpl: string, currentCount: { count: number; }, maxLimit: number, botRole: string): boolean + protected weaponModLimitReached( + modTpl: string, + currentCount: {count: number;}, + maxLimit: number, + botRole: string, + ): boolean { // No value or 0 if (!maxLimit) @@ -143,7 +180,7 @@ export class BotWeaponModLimitService // Has mod limit for bot type been reached if (currentCount.count >= maxLimit) { - //this.logger.debug(`[${botRole}] scope limit reached! tried to add ${modTpl} but scope count is ${currentCount.count}`); + // this.logger.debug(`[${botRole}] scope limit reached! tried to add ${modTpl} but scope count is ${currentCount.count}`); return true; } @@ -152,4 +189,4 @@ export class BotWeaponModLimitService return false; } -} \ No newline at end of file +} diff --git a/project/src/services/CustomLocationWaveService.ts b/project/src/services/CustomLocationWaveService.ts index 732827be..28d77df8 100644 --- a/project/src/services/CustomLocationWaveService.ts +++ b/project/src/services/CustomLocationWaveService.ts @@ -19,7 +19,7 @@ export class CustomLocationWaveService @inject("RandomUtil") protected randomUtil: RandomUtil, @inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("DatabaseServer") protected databaseServer: DatabaseServer, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.locationConfig = this.configServer.getConfig(ConfigTypes.LOCATION); @@ -76,13 +76,15 @@ export class CustomLocationWaveService const location: ILocationBase = this.databaseServer.getTables().locations[mapKey].base; for (const bossWave of bossWavesToApply[mapKey]) { - if (location.BossLocationSpawn.find(x => x.sptId === bossWave.sptId)) + if (location.BossLocationSpawn.find((x) => x.sptId === bossWave.sptId)) { // Already exists, skip continue; } location.BossLocationSpawn.push(bossWave); - this.logger.debug(`Added custom boss wave to ${mapKey} of type ${bossWave.BossName}, time: ${bossWave.Time}, chance: ${bossWave.BossChance}, zone: ${bossWave.BossZone}`); + this.logger.debug( + `Added custom boss wave to ${mapKey} of type ${bossWave.BossName}, time: ${bossWave.Time}, chance: ${bossWave.BossChance}, zone: ${bossWave.BossZone}`, + ); } } @@ -91,7 +93,7 @@ export class CustomLocationWaveService const location: ILocationBase = this.databaseServer.getTables().locations[mapKey].base; for (const normalWave of normalWavesToApply[mapKey]) { - if (location.waves.find(x => x.sptId === normalWave.sptId)) + if (location.waves.find((x) => x.sptId === normalWave.sptId)) { // Already exists, skip continue; @@ -102,4 +104,4 @@ export class CustomLocationWaveService } } } -} \ No newline at end of file +} diff --git a/project/src/services/FenceService.ts b/project/src/services/FenceService.ts index 33ee7f7c..77aa47c0 100644 --- a/project/src/services/FenceService.ts +++ b/project/src/services/FenceService.ts @@ -49,7 +49,7 @@ export class FenceService @inject("PresetHelper") protected presetHelper: PresetHelper, @inject("ItemFilterService") protected itemFilterService: ItemFilterService, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.traderConfig = this.configServer.getConfig(ConfigTypes.TRADER); @@ -88,13 +88,21 @@ export class FenceService // Clone assorts so we can adjust prices before sending to client const assort = this.jsonUtil.clone(this.fenceAssort); - this.adjustAssortItemPrices(assort, this.getFenceInfo(pmcProfile).PriceModifier, this.traderConfig.fence.presetPriceMult); + this.adjustAssortItemPrices( + assort, + this.getFenceInfo(pmcProfile).PriceModifier, + this.traderConfig.fence.presetPriceMult, + ); // merge normal fence assorts + discount assorts if player standing is large enough if (pmcProfile.TradersInfo[Traders.FENCE].standing >= 6) { const discountAssort = this.jsonUtil.clone(this.fenceDiscountAssort); - this.adjustAssortItemPrices(discountAssort, this.traderConfig.fence.discountOptions.itemPriceMult, this.traderConfig.fence.discountOptions.presetPriceMult); + this.adjustAssortItemPrices( + discountAssort, + this.traderConfig.fence.discountOptions.itemPriceMult, + this.traderConfig.fence.discountOptions.presetPriceMult, + ); const mergedAssorts = this.mergeAssorts(assort, discountAssort); return mergedAssorts; @@ -129,7 +137,7 @@ export class FenceService * @param secondAssort assort #2 * @returns merged assort */ - protected mergeAssorts(firstAssort: ITraderAssort,secondAssort: ITraderAssort): ITraderAssort + protected mergeAssorts(firstAssort: ITraderAssort, secondAssort: ITraderAssort): ITraderAssort { for (const itemId in secondAssort.barter_scheme) { @@ -156,14 +164,19 @@ export class FenceService * @param modifier value to multiply item price by * @param presetModifier value to multiply preset price by */ - protected adjustItemPriceByModifier(item: Item, assort: ITraderAssort, modifier: number, presetModifier: number): void + protected adjustItemPriceByModifier( + item: Item, + assort: ITraderAssort, + modifier: number, + presetModifier: number, + ): void { // Is preset if (item.upd.sptPresetId) { if (assort.barter_scheme[item._id]) { - assort.barter_scheme[item._id][0][0].count *= (modifier + presetModifier); + assort.barter_scheme[item._id][0][0].count *= modifier + presetModifier; } } else if (assort.barter_scheme[item._id]) @@ -200,7 +213,9 @@ export class FenceService public performPartialRefresh(): void { let itemCountToReplace = this.getCountOfItemsToReplace(this.traderConfig.fence.assortSize); - const discountItemCountToReplace = this.getCountOfItemsToReplace(this.traderConfig.fence.discountOptions.assortSize); + const discountItemCountToReplace = this.getCountOfItemsToReplace( + this.traderConfig.fence.discountOptions.assortSize, + ); // Iterate x times to remove items (only remove if assort has items) if (this.fenceAssort?.items?.length > 0) @@ -220,7 +235,6 @@ export class FenceService } } - itemCountToReplace = this.getCountOfItemsToGenerate(itemCountToReplace); const newItems = this.createBaseTraderAssortItem(); @@ -253,7 +267,8 @@ export class FenceService // Add loyalty items to fence discount assorts loyalty object for (const loyaltyItemKey in newDiscountItems.loyal_level_items) { - this.fenceDiscountAssort.loyal_level_items[loyaltyItemKey] = newDiscountItems.loyal_level_items[loyaltyItemKey]; + this.fenceDiscountAssort.loyal_level_items[loyaltyItemKey] = + newDiscountItems.loyal_level_items[loyaltyItemKey]; } this.incrementPartialRefreshTime(); @@ -264,7 +279,8 @@ export class FenceService */ protected incrementPartialRefreshTime(): void { - this.nextMiniRefreshTimestamp = this.timeUtil.getTimestamp() + this.traderConfig.fence.partialRefreshTimeSeconds; + this.nextMiniRefreshTimestamp = this.timeUtil.getTimestamp() + + this.traderConfig.fence.partialRefreshTimeSeconds; } /** @@ -278,14 +294,14 @@ export class FenceService const desiredTotalCount = this.traderConfig.fence.assortSize; const actualTotalCount = this.fenceAssort.items.reduce((count, item) => { - return item.slotId === "hideout" - ? count + 1 - : count; + return item.slotId === "hideout" ? + count + 1 : + count; }, 0); - return actualTotalCount < desiredTotalCount - ? (desiredTotalCount - actualTotalCount) + existingItemCountToReplace - : existingItemCountToReplace; + return actualTotalCount < desiredTotalCount ? + (desiredTotalCount - actualTotalCount) + existingItemCountToReplace : + existingItemCountToReplace; } /** @@ -295,9 +311,11 @@ export class FenceService protected removeRandomItemFromAssorts(assort: ITraderAssort): void { // Only remove if assort has items - if (!assort.items.some(x => x.slotId === "hideout")) + if (!assort.items.some((x) => x.slotId === "hideout")) { - this.logger.warning("Unable to remove random assort from trader as they have no assorts with a slotid of `hideout`"); + this.logger.warning( + "Unable to remove random assort from trader as they have no assorts with a slotid of `hideout`", + ); return; } @@ -308,12 +326,12 @@ export class FenceService itemToRemove = this.randomUtil.getArrayValue(assort.items); } - const indexOfItemToRemove = assort.items.findIndex(x => x._id === itemToRemove._id); + const indexOfItemToRemove = assort.items.findIndex((x) => x._id === itemToRemove._id); assort.items.splice(indexOfItemToRemove, 1); // Clean up any mods if item removed was a weapon // TODO: also check for mods attached down the item chain - assort.items = assort.items.filter(x => x.parentId !== itemToRemove._id); + assort.items = assort.items.filter((x) => x.parentId !== itemToRemove._id); delete assort.barter_scheme[itemToRemove._id]; delete assort.loyal_level_items[itemToRemove._id]; @@ -376,7 +394,7 @@ export class FenceService barter_scheme: {}, // eslint-disable-next-line @typescript-eslint/naming-convention loyal_level_items: {}, - nextResupply: this.getNextFenceUpdateTimestamp() + nextResupply: this.getNextFenceUpdateTimestamp(), }; } @@ -400,7 +418,14 @@ export class FenceService this.addPresets(randomisedPresetCount, defaultWeaponPresets, assorts, loyaltyLevel); } - protected addItemAssorts(assortCount: number, fenceAssortIds: string[], assorts: ITraderAssort, fenceAssort: ITraderAssort, itemTypeCounts: Record, loyaltyLevel: number): void + protected addItemAssorts( + assortCount: number, + fenceAssortIds: string[], + assorts: ITraderAssort, + fenceAssort: ITraderAssort, + itemTypeCounts: Record, + loyaltyLevel: number, + ): void { const priceLimits = this.traderConfig.fence.itemCategoryRoublePriceLimit; for (let i = 0; i < assortCount; i++) @@ -420,7 +445,7 @@ export class FenceService // It's a normal non-preset item if (!itemIsPreset) { - const desiredAssort = fenceAssort.items[fenceAssort.items.findIndex(i => i._id === itemTpl)]; + const desiredAssort = fenceAssort.items[fenceAssort.items.findIndex((i) => i._id === itemTpl)]; if (!desiredAssort) { this.logger.error(this.localisationService.getText("fence-unable_to_find_assort_by_id", itemTpl)); @@ -481,11 +506,11 @@ export class FenceService if (this.itemHelper.isOfBaseclass(itemDbDetails._id, BaseClasses.AMMO)) { // No override, use stack max size from item db - return itemDbDetails._props.StackMaxSize === 1 - ? 1 - : this.randomUtil.getInt(itemDbDetails._props.StackMinRandom, itemDbDetails._props.StackMaxRandom); + return itemDbDetails._props.StackMaxSize === 1 ? + 1 : + this.randomUtil.getInt(itemDbDetails._props.StackMinRandom, itemDbDetails._props.StackMaxRandom); } - + return 1; } @@ -496,7 +521,12 @@ export class FenceService * @param assorts object to add presets to * @param loyaltyLevel loyalty level to requre item at */ - protected addPresets(desiredPresetCount: number, defaultWeaponPresets: Record, assorts: ITraderAssort, loyaltyLevel: number): void + protected addPresets( + desiredPresetCount: number, + defaultWeaponPresets: Record, + assorts: ITraderAssort, + loyaltyLevel: number, + ): void { let presetCount = 0; const presetKeys = Object.keys(defaultWeaponPresets); @@ -512,19 +542,22 @@ export class FenceService } // Skip presets we've already added - if (assorts.items.some(i => i.upd && i.upd.sptPresetId === preset._id)) + if (assorts.items.some((i) => i.upd && i.upd.sptPresetId === preset._id)) { continue; } - + // Construct weapon + mods - const weaponAndMods: Item[] = this.itemHelper.replaceIDs(null, this.jsonUtil.clone(defaultWeaponPresets[preset._id]._items)); + const weaponAndMods: Item[] = this.itemHelper.replaceIDs( + null, + this.jsonUtil.clone(defaultWeaponPresets[preset._id]._items), + ); this.removeRandomPartsOfWeapon(weaponAndMods); for (let i = 0; i < weaponAndMods.length; i++) { const mod = weaponAndMods[i]; - //build root Item info + // build root Item info if (!("parentId" in mod)) { mod._id = weaponAndMods[0]._id; @@ -534,7 +567,7 @@ export class FenceService UnlimitedCount: false, StackObjectsCount: 1, BuyRestrictionCurrent: 0, - sptPresetId: preset._id // Store preset id here so we can check it later to prevent preset dupes + sptPresetId: preset._id, // Store preset id here so we can check it later to prevent preset dupes }; } } @@ -556,7 +589,7 @@ export class FenceService assorts.barter_scheme[weaponAndMods[0]._id] = [[]]; assorts.barter_scheme[weaponAndMods[0]._id][0][0] = { _tpl: Money.ROUBLES, - count: Math.round(rub) + count: Math.round(rub), }; assorts.loyal_level_items[weaponAndMods[0]._id] = loyaltyLevel; @@ -624,9 +657,9 @@ export class FenceService // Roll from 0 to 9999, then divide it by 100: 9999 = 99.99% const randomChance = this.randomUtil.getInt(0, 9999) / 100; - - return randomChance > removalChance - && !itemsBeingDeleted.includes(weaponMod._id); + + return randomChance > removalChance && + !itemsBeingDeleted.includes(weaponMod._id); } /** @@ -638,7 +671,9 @@ export class FenceService { if (!itemDetails._props) { - this.logger.error(`Item ${itemDetails._name} lacks a _props field, unable to randomise item: ${itemToAdjust._id}`); + this.logger.error( + `Item ${itemDetails._name} lacks a _props field, unable to randomise item: ${itemToAdjust._id}`, + ); return; } @@ -647,28 +682,30 @@ export class FenceService if ("MaxHpResource" in itemDetails._props && itemDetails._props.MaxHpResource > 0) { itemToAdjust.upd.MedKit = { - HpResource: this.randomUtil.getInt(1, itemDetails._props.MaxHpResource) + HpResource: this.randomUtil.getInt(1, itemDetails._props.MaxHpResource), }; } // Randomise armor durability - if ((itemDetails._parent === BaseClasses.ARMOR - || itemDetails._parent === BaseClasses.HEADWEAR - || itemDetails._parent === BaseClasses.VEST - || itemDetails._parent === BaseClasses.ARMOREDEQUIPMENT - || itemDetails._parent === BaseClasses.FACECOVER) - && itemDetails._props.MaxDurability > 0) + if ( + (itemDetails._parent === BaseClasses.ARMOR || + itemDetails._parent === BaseClasses.HEADWEAR || + itemDetails._parent === BaseClasses.VEST || + itemDetails._parent === BaseClasses.ARMOREDEQUIPMENT || + itemDetails._parent === BaseClasses.FACECOVER) && + itemDetails._props.MaxDurability > 0 + ) { const armorMaxDurabilityLimits = this.traderConfig.fence.armorMaxDurabilityPercentMinMax; - const duraMin = (armorMaxDurabilityLimits.min / 100 * itemDetails._props.MaxDurability); - const duraMax = (armorMaxDurabilityLimits.max / 100 * itemDetails._props.MaxDurability); + const duraMin = armorMaxDurabilityLimits.min / 100 * itemDetails._props.MaxDurability; + const duraMax = armorMaxDurabilityLimits.max / 100 * itemDetails._props.MaxDurability; const maxDurability = this.randomUtil.getInt(duraMin, duraMax); const durability = this.randomUtil.getInt(1, maxDurability); itemToAdjust.upd.Repairable = { Durability: durability, - MaxDurability: maxDurability + MaxDurability: maxDurability, }; return; @@ -678,15 +715,15 @@ export class FenceService if (this.itemHelper.isOfBaseclass(itemDetails._id, BaseClasses.WEAPON)) { const presetMaxDurabilityLimits = this.traderConfig.fence.presetMaxDurabilityPercentMinMax; - const duraMin = (presetMaxDurabilityLimits.min / 100 * itemDetails._props.MaxDurability); - const duraMax = (presetMaxDurabilityLimits.max / 100 * itemDetails._props.MaxDurability); + const duraMin = presetMaxDurabilityLimits.min / 100 * itemDetails._props.MaxDurability; + const duraMax = presetMaxDurabilityLimits.max / 100 * itemDetails._props.MaxDurability; const maxDurability = this.randomUtil.getInt(duraMin, duraMax); const durability = this.randomUtil.getInt(1, maxDurability); itemToAdjust.upd.Repairable = { Durability: durability, - MaxDurability: maxDurability + MaxDurability: maxDurability, }; return; @@ -695,17 +732,20 @@ export class FenceService if (this.itemHelper.isOfBaseclass(itemDetails._id, BaseClasses.REPAIR_KITS)) { itemToAdjust.upd.RepairKit = { - Resource: this.randomUtil.getInt(1, itemDetails._props.MaxRepairResource) + Resource: this.randomUtil.getInt(1, itemDetails._props.MaxRepairResource), }; return; } // Mechanical key + has limited uses - if (this.itemHelper.isOfBaseclass(itemDetails._id, BaseClasses.KEY_MECHANICAL) && itemDetails._props.MaximumNumberOfUsage > 1) + if ( + this.itemHelper.isOfBaseclass(itemDetails._id, BaseClasses.KEY_MECHANICAL) && + itemDetails._props.MaximumNumberOfUsage > 1 + ) { itemToAdjust.upd.Key = { - NumberOfUsages: this.randomUtil.getInt(0, itemDetails._props.MaximumNumberOfUsage - 1) + NumberOfUsages: this.randomUtil.getInt(0, itemDetails._props.MaximumNumberOfUsage - 1), }; return; @@ -718,8 +758,8 @@ export class FenceService const resourceCurrent = this.randomUtil.getInt(1, itemDetails._props.MaxResource); itemToAdjust.upd.Resource = { - Value : resourceMax - resourceCurrent, - UnitsConsumed: resourceCurrent + Value: resourceMax - resourceCurrent, + UnitsConsumed: resourceCurrent, }; } } @@ -729,15 +769,15 @@ export class FenceService * @param limits limits as defined in config * @returns record, key: item tplId, value: current/max item count allowed */ - protected initItemLimitCounter(limits: Record): Record + protected initItemLimitCounter(limits: Record): Record { - const itemTypeCounts: Record = {}; + const itemTypeCounts: Record = {}; for (const x in limits) { itemTypeCounts[x] = { current: 0, - max: limits[x] + max: limits[x], }; } @@ -760,7 +800,7 @@ export class FenceService */ protected getFenceRefreshTime(): number { - return this.traderConfig.updateTime.find(x => x.traderId === Traders.FENCE).seconds; + return this.traderConfig.updateTime.find((x) => x.traderId === Traders.FENCE).seconds; } /** @@ -802,12 +842,12 @@ export class FenceService */ public removeFenceOffer(assortIdToRemove: string): void { - let relatedAssortIndex = this.fenceAssort.items.findIndex(i => i._id === assortIdToRemove); + let relatedAssortIndex = this.fenceAssort.items.findIndex((i) => i._id === assortIdToRemove); // No offer found in main assort, check discount items if (relatedAssortIndex === -1) { - relatedAssortIndex = this.fenceDiscountAssort.items.findIndex(i => i._id === assortIdToRemove); + relatedAssortIndex = this.fenceDiscountAssort.items.findIndex((i) => i._id === assortIdToRemove); this.fenceDiscountAssort.items.splice(relatedAssortIndex, 1); return; @@ -816,4 +856,4 @@ export class FenceService // Remove offer from assort this.fenceAssort.items.splice(relatedAssortIndex, 1); } -} \ No newline at end of file +} diff --git a/project/src/services/GiftService.ts b/project/src/services/GiftService.ts index 2d7e6a6f..1a82e920 100644 --- a/project/src/services/GiftService.ts +++ b/project/src/services/GiftService.ts @@ -25,7 +25,7 @@ export class GiftService @inject("HashUtil") protected hashUtil: HashUtil, @inject("TimeUtil") protected timeUtil: TimeUtil, @inject("ProfileHelper") protected profileHelper: ProfileHelper, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.giftConfig = this.configServer.getConfig(ConfigTypes.GIFTS); @@ -77,7 +77,8 @@ export class GiftService playerId, giftData.localeTextId, giftData.items, - this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours)); + this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours), + ); } else { @@ -85,10 +86,9 @@ export class GiftService playerId, giftData.messageText, giftData.items, - this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours)); + this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours), + ); } - - } // Handle user messages else if (giftData.sender === GiftSenderType.USER) @@ -98,7 +98,8 @@ export class GiftService giftData.senderDetails, giftData.messageText, giftData.items, - this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours)); + this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours), + ); } else if (giftData.sender === GiftSenderType.TRADER) { @@ -110,7 +111,8 @@ export class GiftService MessageType.MESSAGE_WITH_ITEMS, giftData.localeTextId, giftData.items, - this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours)); + this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours), + ); } else { @@ -120,8 +122,9 @@ export class GiftService MessageType.MESSAGE_WITH_ITEMS, giftData.messageText, giftData.items, - this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours)); - } + this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours), + ); + } } else { @@ -130,10 +133,10 @@ export class GiftService const details: ISendMessageDetails = { recipientId: playerId, sender: this.getMessageType(giftData), - senderDetails: { _id: this.getSenderId(giftData), info: null}, + senderDetails: {_id: this.getSenderId(giftData), info: null}, messageText: giftData.messageText, items: giftData.items, - itemsMaxStorageLifetimeSeconds: this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours) + itemsMaxStorageLifetimeSeconds: this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours), }; if (giftData.trader) @@ -142,7 +145,7 @@ export class GiftService } this.mailSendService.sendMessageToPlayer(details); - } + } this.profileHelper.addGiftReceivedFlagToProfile(playerId, giftId); @@ -195,7 +198,7 @@ export class GiftService */ public sendPraporStartingGift(sessionId: string, day: number): void { - switch (day) + switch (day) { case 1: if (this.profileHelper.playerHasRecievedGift(sessionId, "PraporGiftDay1")) @@ -210,6 +213,5 @@ export class GiftService } break; } - } -} \ No newline at end of file +} diff --git a/project/src/services/HashCacheService.ts b/project/src/services/HashCacheService.ts index 101088da..a2c629d0 100644 --- a/project/src/services/HashCacheService.ts +++ b/project/src/services/HashCacheService.ts @@ -16,17 +16,17 @@ export class HashCacheService @inject("VFS") protected vfs: VFS, @inject("HashUtil") protected hashUtil: HashUtil, @inject("JsonUtil") protected jsonUtil: JsonUtil, - @inject("WinstonLogger") protected logger: ILogger + @inject("WinstonLogger") protected logger: ILogger, ) - { + { if (!this.vfs.exists(this.modCachePath)) { this.vfs.writeFile(this.modCachePath, "{}"); } // get mod hash file - if (!this.modHashes) // empty - { + if (!this.modHashes) + { // empty this.modHashes = this.jsonUtil.deserialize(this.vfs.readFile(`${this.modCachePath}`)); } } @@ -44,7 +44,7 @@ export class HashCacheService /** * Does the generated hash match the stored hash * @param modName name of mod - * @param modContent + * @param modContent * @returns True if they match */ public modContentMatchesStoredHash(modName: string, modContent: string): boolean @@ -77,4 +77,4 @@ export class HashCacheService this.logger.debug(`Mod ${modName} hash stored in ${this.modCachePath}`); } -} \ No newline at end of file +} diff --git a/project/src/services/InsuranceService.ts b/project/src/services/InsuranceService.ts index a52e3de7..02cc0ea4 100644 --- a/project/src/services/InsuranceService.ts +++ b/project/src/services/InsuranceService.ts @@ -46,7 +46,7 @@ export class InsuranceService @inject("LocalisationService") protected localisationService: LocalisationService, @inject("LocaleService") protected localeService: LocaleService, @inject("MailSendService") protected mailSendService: MailSendService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.insuranceConfig = this.configServer.getConfig(ConfigTypes.INSURANCE); @@ -103,13 +103,17 @@ export class InsuranceService const dialogueTemplates = this.databaseServer.getTables().traders[traderId].dialogue; // Construct "i will go look for your stuff" message - const messageContent = this.dialogueHelper.createMessageContext(this.randomUtil.getArrayValue(dialogueTemplates.insuranceStart), MessageType.NPC_TRADER, traderBase.insurance.max_storage_time); + const messageContent = this.dialogueHelper.createMessageContext( + this.randomUtil.getArrayValue(dialogueTemplates.insuranceStart), + MessageType.NPC_TRADER, + traderBase.insurance.max_storage_time, + ); messageContent.text = ""; // Live insurance returns have an empty string for the text property messageContent.profileChangeEvents = []; messageContent.systemData = { date: this.timeUtil.getDateMailFormat(), time: this.timeUtil.getTimeMailFormat(), - location: mapId + location: mapId, }; // MUST occur after systemData is hydrated @@ -128,7 +132,7 @@ export class InsuranceService scheduledTime: insuranceReturnTimestamp, traderId: traderId, messageContent: messageContent, - items: this.getInsurance(sessionID)[traderId] + items: this.getInsurance(sessionID)[traderId], }); } @@ -143,9 +147,9 @@ export class InsuranceService public sendLostInsuranceMessage(sessionId: string, locationName = ""): void { const dialogueTemplates = this.databaseServer.getTables().traders[Traders.PRAPOR].dialogue; // todo: get trader id instead of hard coded prapor - const randomResponseId = locationName?.toLowerCase() === "laboratory" - ? this.randomUtil.getArrayValue(dialogueTemplates["insuranceFailedLabs"]) - : this.randomUtil.getArrayValue(dialogueTemplates["insuranceFailed"]); + const randomResponseId = locationName?.toLowerCase() === "laboratory" ? + this.randomUtil.getArrayValue(dialogueTemplates["insuranceFailedLabs"]) : + this.randomUtil.getArrayValue(dialogueTemplates["insuranceFailed"]); this.mailSendService.sendLocalisedNpcMessageToPlayer( sessionId, @@ -154,7 +158,8 @@ export class InsuranceService randomResponseId, [], null, - {location: locationName}); + {location: locationName}, + ); } /** @@ -168,7 +173,7 @@ export class InsuranceService for (const insuredItem of this.getInsurance(sessionId)[traderId]) { // Find insured items parent - const insuredItemsParent = insuredItems.find(x => x._id === insuredItem.parentId); + const insuredItemsParent = insuredItems.find((x) => x._id === insuredItem.parentId); if (!insuredItemsParent) { // Remove location + set slotId of insured items parent @@ -190,14 +195,16 @@ export class InsuranceService // If override inconfig is non-zero, use that instead of trader values if (this.insuranceConfig.returnTimeOverrideSeconds > 0) { - this.logger.debug(`Insurance override used: returning in ${this.insuranceConfig.returnTimeOverrideSeconds} seconds`); + this.logger.debug( + `Insurance override used: returning in ${this.insuranceConfig.returnTimeOverrideSeconds} seconds`, + ); return this.timeUtil.getTimestamp() + this.insuranceConfig.returnTimeOverrideSeconds; } - const insuranceReturnTimeBonus = pmcData.Bonuses.find(b => b.type === "InsuranceReturnTime"); - const insuranceReturnTimeBonusPercent = 1.0 - (insuranceReturnTimeBonus - ? Math.abs(insuranceReturnTimeBonus.value) - : 0) / 100; + const insuranceReturnTimeBonus = pmcData.Bonuses.find((b) => b.type === "InsuranceReturnTime"); + const insuranceReturnTimeBonusPercent = 1.0 - (insuranceReturnTimeBonus ? + Math.abs(insuranceReturnTimeBonus.value) : + 0) / 100; const traderMinReturnAsSeconds = trader.insurance.min_return_hour * TimeUtil.oneHourAsSeconds; const traderMaxReturnAsSeconds = trader.insurance.max_return_hour * TimeUtil.oneHourAsSeconds; @@ -215,7 +222,13 @@ export class InsuranceService * @param sessionID Session id * @param playerDied did the player die in raid */ - public storeLostGear(pmcData: IPmcData, offraidData: ISaveProgressRequestData, preRaidGear: Item[], sessionID: string, playerDied: boolean): void + public storeLostGear( + pmcData: IPmcData, + offraidData: ISaveProgressRequestData, + preRaidGear: Item[], + sessionID: string, + playerDied: boolean, + ): void { const preRaidGearHash = this.createItemHashTable(preRaidGear); const offRaidGearHash = this.createItemHashTable(offraidData.profile.Inventory.items); @@ -242,9 +255,13 @@ export class InsuranceService { equipmentToSendToPlayer.push({ pmcData: pmcData, - itemToReturnToPlayer: this.getInsuredItemDetails(pmcData, preRaidItem, offraidData.insurance?.find(x => x.id === insuredItem.itemId)), + itemToReturnToPlayer: this.getInsuredItemDetails( + pmcData, + preRaidItem, + offraidData.insurance?.find((x) => x.id === insuredItem.itemId), + ), traderId: insuredItem.tid, - sessionID: sessionID + sessionID: sessionID, }); } } @@ -264,7 +281,11 @@ export class InsuranceService * @param insuredItemFromClient Item data when player left raid (durability values) * @returns Item object */ - protected getInsuredItemDetails(pmcData: IPmcData, preRaidItem: Item, insuredItemFromClient: IInsuredItemsData): Item + protected getInsuredItemDetails( + pmcData: IPmcData, + preRaidItem: Item, + insuredItemFromClient: IInsuredItemsData, + ): Item { // Get baseline item to return, clone pre raid item const itemToReturn: Item = this.jsonUtil.clone(preRaidItem); @@ -298,7 +319,7 @@ export class InsuranceService { itemToReturn.upd.Repairable = { Durability: insuredItemFromClient.durability, - MaxDurability: insuredItemFromClient.maxDurability + MaxDurability: insuredItemFromClient.maxDurability, }; } else @@ -306,7 +327,6 @@ export class InsuranceService itemToReturn.upd.Repairable.Durability = insuredItemFromClient.durability; itemToReturn.upd.Repairable.MaxDurability = insuredItemFromClient.maxDurability; } - } // Client item has FaceShield values, Ensure values persist into server data @@ -316,14 +336,13 @@ export class InsuranceService if (!itemToReturn.upd.FaceShield) { itemToReturn.upd.FaceShield = { - Hits: insuredItemFromClient.hits + Hits: insuredItemFromClient.hits, }; } else { itemToReturn.upd.FaceShield.Hits = insuredItemFromClient.hits; } - } return itemToReturn; @@ -340,17 +359,17 @@ export class InsuranceService "pocket1", "pocket2", "pocket3", - "pocket4" + "pocket4", ]; // Some pockets can lose items with player death, some don't - if (!("slotId" in itemToReturn) || pocketSlots.includes(itemToReturn.slotId)) + if (!("slotId" in itemToReturn) || pocketSlots.includes(itemToReturn.slotId)) { itemToReturn.slotId = "hideout"; } // Mark root-level items for later processing - if (itemToReturn.parentId === playerBaseInventoryEquipmentId) + if (itemToReturn.parentId === playerBaseInventoryEquipmentId) { itemToReturn.slotId = "hideout"; } @@ -379,7 +398,9 @@ export class InsuranceService * @param itemToReturnToPlayer item to store * @param traderId Id of trader item was insured with */ - protected addGearToSend(gear: { sessionID: string; pmcData: IPmcData; itemToReturnToPlayer: Item; traderId: string}): void + protected addGearToSend( + gear: {sessionID: string; pmcData: IPmcData; itemToReturnToPlayer: Item; traderId: string;}, + ): void { const sessionId = gear.sessionID; const pmcData = gear.pmcData; @@ -436,7 +457,6 @@ export class InsuranceService */ public addInsuranceItemToArray(sessionId: string, traderId: string, itemToAdd: Item): void { - this.insured[sessionId][traderId].push(itemToAdd); } @@ -453,7 +473,9 @@ export class InsuranceService if (!insuranceMultiplier) { insuranceMultiplier = 0.3; - this.logger.warning(this.localisationService.getText("insurance-missing_insurance_price_multiplier", traderId)); + this.logger.warning( + this.localisationService.getText("insurance-missing_insurance_price_multiplier", traderId), + ); } // Multiply item handbook price by multiplier in config to get the new insurance price @@ -462,9 +484,9 @@ export class InsuranceService if (coef > 0) { - pricePremium *= (1 - this.traderHelper.getLoyaltyLevel(traderId, pmcData).insurance_price_coef / 100); + pricePremium *= 1 - this.traderHelper.getLoyaltyLevel(traderId, pmcData).insurance_price_coef / 100; } return Math.round(pricePremium); } -} \ No newline at end of file +} diff --git a/project/src/services/ItemBaseClassService.ts b/project/src/services/ItemBaseClassService.ts index 114bf39e..7f0b2a0a 100644 --- a/project/src/services/ItemBaseClassService.ts +++ b/project/src/services/ItemBaseClassService.ts @@ -18,7 +18,7 @@ export class ItemBaseClassService constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("DatabaseServer") protected databaseServer: DatabaseServer + @inject("DatabaseServer") protected databaseServer: DatabaseServer, ) {} @@ -39,7 +39,7 @@ export class ItemBaseClassService return; } - const filteredDbItems = Object.values(allDbItems).filter(x => x._type === "Item"); + const filteredDbItems = Object.values(allDbItems).filter((x) => x._type === "Item"); for (const item of filteredDbItems) { const itemIdToUpdate = item._id; @@ -111,7 +111,7 @@ export class ItemBaseClassService } } - return this.itemBaseClassesCache[itemTpl].some(x => baseClasses.includes(x)); + return this.itemBaseClassesCache[itemTpl].some((x) => baseClasses.includes(x)); } /** @@ -133,4 +133,4 @@ export class ItemBaseClassService return this.itemBaseClassesCache[itemTpl]; } -} \ No newline at end of file +} diff --git a/project/src/services/ItemFilterService.ts b/project/src/services/ItemFilterService.ts index 91d8fcd9..52bd472f 100644 --- a/project/src/services/ItemFilterService.ts +++ b/project/src/services/ItemFilterService.ts @@ -6,16 +6,16 @@ import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; import { ConfigServer } from "@spt-aki/servers/ConfigServer"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; -/** Centralise the handling of blacklisting items, uses blacklist found in config/item.json, stores items that should not be used by players / broken items */ +/** Centralise the handling of blacklisting items, uses blacklist found in config/item.json, stores items that should not be used by players / broken items */ @injectable() export class ItemFilterService { - protected itemConfig: IItemConfig ; + protected itemConfig: IItemConfig; constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("DatabaseServer") protected databaseServer: DatabaseServer, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.itemConfig = this.configServer.getConfig(ConfigTypes.ITEM); @@ -58,4 +58,4 @@ export class ItemFilterService { return this.itemConfig.bossItems; } -} \ No newline at end of file +} diff --git a/project/src/services/LocaleService.ts b/project/src/services/LocaleService.ts index 5747df1e..25bf76d7 100644 --- a/project/src/services/LocaleService.ts +++ b/project/src/services/LocaleService.ts @@ -17,7 +17,7 @@ export class LocaleService constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("DatabaseServer") protected databaseServer: DatabaseServer, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.localeConfig = this.configServer.getConfig(ConfigTypes.LOCALE); @@ -35,7 +35,9 @@ export class LocaleService return desiredLocale; } - this.logger.warning(`Unable to find desired locale file using locale ${this.getDesiredGameLocale()} from config/locale.json, falling back to 'en'`); + this.logger.warning( + `Unable to find desired locale file using locale ${this.getDesiredGameLocale()} from config/locale.json, falling back to 'en'`, + ); return this.databaseServer.getTables().locales.global["en"]; } @@ -95,10 +97,12 @@ export class LocaleService if (!this.localeConfig.serverSupportedLocales.includes(platformLocale.language)) { - this.logger.warning(`Unsupported system langauge found ${platformLocale.baseName}, falling back to english`); + this.logger.warning( + `Unsupported system langauge found ${platformLocale.baseName}, falling back to english`, + ); return "en"; } return platformLocale.language; } -} \ No newline at end of file +} diff --git a/project/src/services/LocalisationService.ts b/project/src/services/LocalisationService.ts index 0477aa86..d946dfab 100644 --- a/project/src/services/LocalisationService.ts +++ b/project/src/services/LocalisationService.ts @@ -21,17 +21,22 @@ export class LocalisationService @inject("WinstonLogger") protected logger: ILogger, @inject("RandomUtil") protected randomUtil: RandomUtil, @inject("DatabaseServer") protected databaseServer: DatabaseServer, - @inject("LocaleService") protected localeService: LocaleService + @inject("LocaleService") protected localeService: LocaleService, ) { - const localeFileDirectory = path.join(process.cwd(), globalThis.G_RELEASE_CONFIGURATION ? "Aki_Data/Server/database/locales/server" : "./assets/database/locales/server"); + const localeFileDirectory = path.join( + process.cwd(), + globalThis.G_RELEASE_CONFIGURATION ? + "Aki_Data/Server/database/locales/server" : + "./assets/database/locales/server", + ); this.i18n = new I18n( { locales: this.localeService.getServerSupportedLocales(), defaultLocale: "en", directory: localeFileDirectory, - retryInDefaultLocale: true - } + retryInDefaultLocale: true, + }, ); this.i18n.setLocale(this.localeService.getDesiredServerLocale()); @@ -64,9 +69,11 @@ export class LocalisationService */ public getRandomTextThatMatchesPartialKey(partialKey: string): string { - const filteredKeys = Object.keys(this.databaseServer.getTables().locales.server["en"]).filter(x => x.startsWith(partialKey)); + const filteredKeys = Object.keys(this.databaseServer.getTables().locales.server["en"]).filter((x) => + x.startsWith(partialKey) + ); const chosenKey = this.randomUtil.getArrayValue(filteredKeys); return this.getText(chosenKey); } -} \ No newline at end of file +} diff --git a/project/src/services/MailSendService.ts b/project/src/services/MailSendService.ts index 88c853a0..42e9b45a 100644 --- a/project/src/services/MailSendService.ts +++ b/project/src/services/MailSendService.ts @@ -33,9 +33,9 @@ export class MailSendService @inject("NotificationSendHelper") protected notificationSendHelper: NotificationSendHelper, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("ItemHelper") protected itemHelper: ItemHelper, - @inject("TraderHelper") protected traderHelper: TraderHelper + @inject("TraderHelper") protected traderHelper: TraderHelper, ) - { } + {} /** * Send a message from an NPC (e.g. prapor) to the player with or without items using direct message text, do not look up any locale @@ -46,11 +46,25 @@ export class MailSendService * @param items Optional items to send to player * @param maxStorageTimeSeconds Optional time to collect items before they expire */ - public sendDirectNpcMessageToPlayer(sessionId: string, trader: Traders, messageType: MessageType, message: string, items: Item[] = [], maxStorageTimeSeconds = null, systemData = null, ragfair = null): void + public sendDirectNpcMessageToPlayer( + sessionId: string, + trader: Traders, + messageType: MessageType, + message: string, + items: Item[] = [], + maxStorageTimeSeconds = null, + systemData = null, + ragfair = null, + ): void { if (!trader) { - this.logger.error(this.localisationService.getText("mailsend-missing_trader", {messageType: messageType, sessionId: sessionId})); + this.logger.error( + this.localisationService.getText("mailsend-missing_trader", { + messageType: messageType, + sessionId: sessionId, + }), + ); return; } @@ -60,7 +74,7 @@ export class MailSendService sender: messageType, dialogType: MessageType.NPC_TRADER, trader: trader, - messageText: message + messageText: message, }; // Add items to message @@ -92,11 +106,25 @@ export class MailSendService * @param items Optional items to send to player * @param maxStorageTimeSeconds Optional time to collect items before they expire */ - public sendLocalisedNpcMessageToPlayer(sessionId: string, trader: Traders, messageType: MessageType, messageLocaleId: string, items: Item[] = [], maxStorageTimeSeconds = null, systemData = null, ragfair = null): void + public sendLocalisedNpcMessageToPlayer( + sessionId: string, + trader: Traders, + messageType: MessageType, + messageLocaleId: string, + items: Item[] = [], + maxStorageTimeSeconds = null, + systemData = null, + ragfair = null, + ): void { if (!trader) { - this.logger.error(this.localisationService.getText("mailsend-missing_trader", {messageType: messageType, sessionId: sessionId})); + this.logger.error( + this.localisationService.getText("mailsend-missing_trader", { + messageType: messageType, + sessionId: sessionId, + }), + ); return; } @@ -106,7 +134,7 @@ export class MailSendService sender: messageType, dialogType: MessageType.NPC_TRADER, trader: trader, - templateId: messageLocaleId + templateId: messageLocaleId, }; // Add items to message @@ -136,12 +164,17 @@ export class MailSendService * @param items Optional items to send to player * @param maxStorageTimeSeconds Optional time to collect items before they expire */ - public sendSystemMessageToPlayer(sessionId: string, message: string, items: Item[] = [], maxStorageTimeSeconds = null): void + public sendSystemMessageToPlayer( + sessionId: string, + message: string, + items: Item[] = [], + maxStorageTimeSeconds = null, + ): void { const details: ISendMessageDetails = { recipientId: sessionId, sender: MessageType.SYSTEM_MESSAGE, - messageText: message + messageText: message, }; // Add items to message @@ -161,12 +194,17 @@ export class MailSendService * @param items Optional items to send to player * @param maxStorageTimeSeconds Optional time to collect items before they expire */ - public sendLocalisedSystemMessageToPlayer(sessionId: string, messageLocaleId: string, items: Item[] = [], maxStorageTimeSeconds = null): void + public sendLocalisedSystemMessageToPlayer( + sessionId: string, + messageLocaleId: string, + items: Item[] = [], + maxStorageTimeSeconds = null, + ): void { const details: ISendMessageDetails = { recipientId: sessionId, sender: MessageType.SYSTEM_MESSAGE, - templateId: messageLocaleId + templateId: messageLocaleId, }; // Add items to message @@ -187,13 +225,19 @@ export class MailSendService * @param items Optional items to send to player * @param maxStorageTimeSeconds Optional time to collect items before they expire */ - public sendUserMessageToPlayer(sessionId: string, senderDetails: IUserDialogInfo, message: string, items: Item[] = [], maxStorageTimeSeconds = null): void + public sendUserMessageToPlayer( + sessionId: string, + senderDetails: IUserDialogInfo, + message: string, + items: Item[] = [], + maxStorageTimeSeconds = null, + ): void { const details: ISendMessageDetails = { recipientId: sessionId, sender: MessageType.USER_MESSAGE, senderDetails: senderDetails, - messageText: message + messageText: message, }; // Add items to message @@ -222,7 +266,7 @@ export class MailSendService // Craft message const message = this.createDialogMessage(senderDialog._id, messageDetails); - // Create items array + // Create items array // Generate item stash if we have rewards. const itemsToSendToPlayer = this.processItemsBeforeAddingToMail(senderDialog.type, messageDetails); @@ -240,9 +284,15 @@ export class MailSendService // TODO: clean up old code here // Offer Sold notifications are now separate from the main notification - if ([MessageType.NPC_TRADER, MessageType.FLEAMARKET_MESSAGE].includes(senderDialog.type) && messageDetails.ragfairDetails) + if ( + [MessageType.NPC_TRADER, MessageType.FLEAMARKET_MESSAGE].includes(senderDialog.type) && + messageDetails.ragfairDetails + ) { - const offerSoldMessage = this.notifierHelper.createRagfairOfferSoldNotification(message, messageDetails.ragfairDetails); + const offerSoldMessage = this.notifierHelper.createRagfairOfferSoldNotification( + message, + messageDetails.ragfairDetails, + ); this.notificationSendHelper.sendMessage(messageDetails.recipientId, offerSoldMessage); message.type = MessageType.MESSAGE_WITH_ITEMS; // Should prevent getting the same notification popup twice } @@ -276,7 +326,7 @@ export class MailSendService uid: playerProfile.characters.pmc._id, type: MessageType.USER_MESSAGE, rewardCollected: false, - text: message + text: message, }); } @@ -298,7 +348,9 @@ export class MailSendService hasRewards: false, // The default dialog message has no rewards, can be added later via addRewardItemsToMessage() rewardCollected: false, // The default dialog message has no rewards, can be added later via addRewardItemsToMessage() systemData: messageDetails.systemData ? messageDetails.systemData : undefined, // Used by ragfair / localised messages that need "location" or "time" - profileChangeEvents: (messageDetails.profileChangeEvents?.length === 0) ? messageDetails.profileChangeEvents : undefined // no one knows, its never been used in any dumps + profileChangeEvents: (messageDetails.profileChangeEvents?.length === 0) ? + messageDetails.profileChangeEvents : + undefined, // no one knows, its never been used in any dumps }; // Clean up empty system data @@ -322,7 +374,11 @@ export class MailSendService * @param itemsToSendToPlayer Items to add to message * @param maxStorageTimeSeconds total time items are stored in mail before being deleted */ - protected addRewardItemsToMessage(message: Message, itemsToSendToPlayer: MessageItems, maxStorageTimeSeconds: number): void + protected addRewardItemsToMessage( + message: Message, + itemsToSendToPlayer: MessageItems, + maxStorageTimeSeconds: number, + ): void { if (itemsToSendToPlayer?.data?.length > 0) { @@ -335,8 +391,8 @@ export class MailSendService /** * perform various sanitising actions on the items before they're considered ready for insertion into message - * @param dialogType The type of the dialog that will hold the reward items being processed - * @param messageDetails + * @param dialogType The type of the dialog that will hold the reward items being processed + * @param messageDetails * @returns Sanitised items */ protected processItemsBeforeAddingToMail(dialogType: MessageType, messageDetails: ISendMessageDetails): MessageItems @@ -350,7 +406,10 @@ export class MailSendService const parentItem = this.getBaseItemFromRewards(messageDetails.items); if (!parentItem) { - this.localisationService.getText("mailsend-missing_parent", {traderId: messageDetails.trader, sender: messageDetails.sender}); + this.localisationService.getText("mailsend-missing_parent", { + traderId: messageDetails.trader, + sender: messageDetails.sender, + }); return itemsToSendToPlayer; } @@ -363,9 +422,9 @@ export class MailSendService itemsToSendToPlayer = { stash: parentItem.parentId, - data: [] + data: [], }; - + // Ensure Ids are unique and cont collide with items in player inventory later messageDetails.items = this.itemHelper.replaceIDs(null, messageDetails.items); @@ -376,7 +435,12 @@ export class MailSendService if (!itemTemplate) { // Can happen when modded items are insured + mod is removed - this.logger.error(this.localisationService.getText("dialog-missing_item_template", {tpl: reward._tpl, type: dialogType})); + this.logger.error( + this.localisationService.getText("dialog-missing_item_template", { + tpl: reward._tpl, + type: dialogType, + }), + ); continue; } @@ -427,7 +491,7 @@ export class MailSendService } // Find first item with slotId that indicates its a 'base' item - let item = items.find(x => ["hideout", "main"].includes(x.slotId)); + let item = items.find((x) => ["hideout", "main"].includes(x.slotId)); if (item) { return item; @@ -435,7 +499,7 @@ export class MailSendService // Not a singlular item + no items have a hideout/main slotid // Look for first item without parent id - item = items.find(x => !x.parentId); + item = items.find((x) => !x.parentId); if (item) { return item; @@ -467,7 +531,7 @@ export class MailSendService messages: [], pinned: false, new: 0, - attachmentsNew: 0 + attachmentsNew: 0, }; senderDialog = dialogsInProfile[senderId]; @@ -478,7 +542,7 @@ export class MailSendService /** * Get the appropriate sender id by the sender enum type - * @param messageDetails + * @param messageDetails * @returns gets an id of the individual sending it */ protected getMessageSenderIdByType(messageDetails: ISendMessageDetails): string @@ -510,5 +574,4 @@ export class MailSendService this.logger.warning(`Unable to handle message of type: ${messageDetails.sender}`); } - -} \ No newline at end of file +} diff --git a/project/src/services/MatchBotDetailsCacheService.ts b/project/src/services/MatchBotDetailsCacheService.ts index 2e1dc2e5..826f731b 100644 --- a/project/src/services/MatchBotDetailsCacheService.ts +++ b/project/src/services/MatchBotDetailsCacheService.ts @@ -12,7 +12,7 @@ export class MatchBotDetailsCacheService constructor( @inject("WinstonLogger") protected logger: ILogger, - @inject("LocalisationService") protected localisationService: LocalisationService + @inject("LocalisationService") protected localisationService: LocalisationService, ) {} @@ -48,5 +48,4 @@ export class MatchBotDetailsCacheService return botInCache; } - -} \ No newline at end of file +} diff --git a/project/src/services/MatchLocationService.ts b/project/src/services/MatchLocationService.ts index cba086c6..1b3e40bd 100644 --- a/project/src/services/MatchLocationService.ts +++ b/project/src/services/MatchLocationService.ts @@ -9,9 +9,9 @@ export class MatchLocationService protected locations = {}; constructor( - @inject("TimeUtil") protected timeUtil: TimeUtil + @inject("TimeUtil") protected timeUtil: TimeUtil, ) - { } + {} public createGroup(sessionID: string, info: ICreateGroupRequestData): any { @@ -33,10 +33,10 @@ export class MatchLocationService region: "EUR", ip: "127.0.0.1", savageId: `scav${sessionID}`, - accessKeyId: "" - } + accessKeyId: "", + }, ], - customDataCenter: [] + customDataCenter: [], }; return this.locations[info.location].groups[groupID]; @@ -56,4 +56,4 @@ export class MatchLocationService } } } -} \ No newline at end of file +} diff --git a/project/src/services/ModCompilerService.ts b/project/src/services/ModCompilerService.ts index c69f50b4..d02e72fb 100644 --- a/project/src/services/ModCompilerService.ts +++ b/project/src/services/ModCompilerService.ts @@ -16,7 +16,7 @@ export class ModCompilerService constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("HashCacheService") protected hashCacheService: HashCacheService, - @inject("VFS") protected vfs: VFS + @inject("VFS") protected vfs: VFS, ) { const packageJsonPath: string = path.join(__dirname, "../../package.json"); @@ -27,8 +27,8 @@ export class ModCompilerService * Convert a mods TS into JS * @param modName Name of mod * @param modPath Dir path to mod - * @param modTypeScriptFiles - * @returns + * @param modTypeScriptFiles + * @returns */ public async compileMod(modName: string, modPath: string, modTypeScriptFiles: string[]): Promise { @@ -38,7 +38,7 @@ export class ModCompilerService for (const file of modTypeScriptFiles) { const fileContent = this.vfs.readFile(file); - tsFileContents+= fileContent; + tsFileContents += fileContent; // Does equivalent .js file exist if (!this.vfs.exists(file.replace(".ts", ".js"))) @@ -61,22 +61,21 @@ export class ModCompilerService this.hashCacheService.storeModContent(modName, tsFileContents); } - return this.compile(modTypeScriptFiles, - { - noEmitOnError: true, - noImplicitAny: false, - target: ts.ScriptTarget.ES2022, - module: ts.ModuleKind.CommonJS, - moduleResolution: ts.ModuleResolutionKind.Node10, - sourceMap: true, - resolveJsonModule: true, - allowJs: true, - esModuleInterop: true, - downlevelIteration: true, - experimentalDecorators: true, - emitDecoratorMetadata: true, - rootDir: modPath - }); + return this.compile(modTypeScriptFiles, { + noEmitOnError: true, + noImplicitAny: false, + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.CommonJS, + moduleResolution: ts.ModuleResolutionKind.Node10, + sourceMap: true, + resolveJsonModule: true, + allowJs: true, + esModuleInterop: true, + downlevelIteration: true, + experimentalDecorators: true, + emitDecoratorMetadata: true, + rootDir: modPath, + }); } /** @@ -87,7 +86,7 @@ export class ModCompilerService protected async compile(fileNames: string[], options: ts.CompilerOptions): Promise { // C:/snapshot/project || /snapshot/project - const baseDir: string = __dirname.replace(/\\/g,"/").split("/").slice(0, 3).join("/"); + const baseDir: string = __dirname.replace(/\\/g, "/").split("/").slice(0, 3).join("/"); for (const filePath of fileNames) { @@ -100,25 +99,28 @@ export class ModCompilerService if (globalThis.G_RELEASE_CONFIGURATION) { replacedText = text.replace(/(@spt-aki)/g, `${baseDir}/obj`); - for (const dependency of this.serverDependencies) + for (const dependency of this.serverDependencies) { replacedText = replacedText.replace(`"${dependency}"`, `"${baseDir}/node_modules/${dependency}"`); } } else { - replacedText = text.replace(/(@spt-aki)/g, path.join(__dirname, "..").replace(/\\/g,"/")); + replacedText = text.replace(/(@spt-aki)/g, path.join(__dirname, "..").replace(/\\/g, "/")); } - const output = ts.transpileModule(replacedText, { compilerOptions: options }); + const output = ts.transpileModule(replacedText, {compilerOptions: options}); if (output.sourceMapText) { - output.outputText = output.outputText.replace("//# sourceMappingURL=module.js.map", `//# sourceMappingURL=${parsedDestPath.base}.map`); + output.outputText = output.outputText.replace( + "//# sourceMappingURL=module.js.map", + `//# sourceMappingURL=${parsedDestPath.base}.map`, + ); const sourceMap = JSON.parse(output.sourceMapText); sourceMap.file = parsedDestPath.base; - sourceMap.sources = [ parsedPath.base ]; + sourceMap.sources = [parsedPath.base]; fs.writeFileSync(`${destPath}.map`, JSON.stringify(sourceMap)); } @@ -133,21 +135,21 @@ export class ModCompilerService /** * Do the files at the provided paths exist - * @param fileNames - * @returns + * @param fileNames + * @returns */ protected areFilesReady(fileNames: string[]): boolean { - return fileNames.filter(x => !this.vfs.exists(x.replace(".ts", ".js"))).length === 0; + return fileNames.filter((x) => !this.vfs.exists(x.replace(".ts", ".js"))).length === 0; } /** * Wait the provided number of milliseconds * @param ms Milliseconds - * @returns + * @returns */ protected delay(ms: number): Promise { - return new Promise( resolve => setTimeout(resolve, ms) ); + return new Promise((resolve) => setTimeout(resolve, ms)); } -} \ No newline at end of file +} diff --git a/project/src/services/NotificationService.ts b/project/src/services/NotificationService.ts index e0356e7f..2439eba8 100644 --- a/project/src/services/NotificationService.ts +++ b/project/src/services/NotificationService.ts @@ -61,4 +61,4 @@ export class NotificationService return this.messageQueue[sessionID]; } -} \ No newline at end of file +} diff --git a/project/src/services/OpenZoneService.ts b/project/src/services/OpenZoneService.ts index c5bb5410..303d4f92 100644 --- a/project/src/services/OpenZoneService.ts +++ b/project/src/services/OpenZoneService.ts @@ -22,7 +22,7 @@ export class OpenZoneService @inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.locationConfig = this.configServer.getConfig(ConfigTypes.LOCATION); @@ -54,7 +54,7 @@ export class OpenZoneService { const dbLocations = this.databaseServer.getTables().locations; for (const mapKey in this.locationConfig.openZones) - { + { if (!dbLocations[mapKey]) { this.logger.error(this.localisationService.getText("openzone-unable_to_find_map", mapKey)); @@ -76,4 +76,4 @@ export class OpenZoneService } } } -} \ No newline at end of file +} diff --git a/project/src/services/PaymentService.ts b/project/src/services/PaymentService.ts index 09e022c6..63ad9d1e 100644 --- a/project/src/services/PaymentService.ts +++ b/project/src/services/PaymentService.ts @@ -28,9 +28,9 @@ export class PaymentService @inject("ItemHelper") protected itemHelper: ItemHelper, @inject("InventoryHelper") protected inventoryHelper: InventoryHelper, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("PaymentHelper") protected paymentHelper: PaymentHelper + @inject("PaymentHelper") protected paymentHelper: PaymentHelper, ) - { } + {} /** * Take money and insert items into return to server request @@ -39,12 +39,17 @@ export class PaymentService * @param {string} sessionID * @returns IItemEventRouterResponse */ - public payMoney(pmcData: IPmcData, request: IProcessBuyTradeRequestData, sessionID: string, output: IItemEventRouterResponse): IItemEventRouterResponse + public payMoney( + pmcData: IPmcData, + request: IProcessBuyTradeRequestData, + sessionID: string, + output: IItemEventRouterResponse, + ): IItemEventRouterResponse { const trader = this.traderHelper.getTrader(request.tid, sessionID); // Track the amounts of each type of currency involved in the trade. - const currencyAmounts: { [key: string]: number } = {}; + const currencyAmounts: {[key: string]: number;} = {}; // Delete barter items and track currencies if the action is "TradingConfirm". if (request.Action === "TradingConfirm") @@ -52,7 +57,7 @@ export class PaymentService for (const index in request.scheme_items) { // Find the corresponding item in the player's inventory. - const item = pmcData.Inventory.items.find(i => i._id === request.scheme_items[index].id); + const item = pmcData.Inventory.items.find((i) => i._id === request.scheme_items[index].id); if (item !== undefined) { if (!this.paymentHelper.isMoneyTpl(item._tpl)) @@ -64,7 +69,8 @@ export class PaymentService else { // If the item is money, add its count to the currencyAmounts object. - currencyAmounts[item._tpl] = (currencyAmounts[item._tpl] || 0) + request.scheme_items[index].count; + currencyAmounts[item._tpl] = (currencyAmounts[item._tpl] || 0) + + request.scheme_items[index].count; } } } @@ -90,7 +96,10 @@ export class PaymentService } // Convert the amount to the trader's currency and update the sales sum. - const costOfPurchaseInCurrency = this.handbookHelper.fromRUB(this.handbookHelper.inRUB(currencyAmount, currencyTpl), this.paymentHelper.getCurrency(trader.currency)); + const costOfPurchaseInCurrency = this.handbookHelper.fromRUB( + this.handbookHelper.inRUB(currencyAmount, currencyTpl), + this.paymentHelper.getCurrency(trader.currency), + ); pmcData.TradersInfo[request.tid].salesSum += costOfPurchaseInCurrency; } } @@ -101,7 +110,10 @@ export class PaymentService this.logger.debug(this.localisationService.getText("payment-zero_price_no_payment")); // Convert the handbook price to the trader's currency and update the sales sum. - const costOfPurchaseInCurrency = this.handbookHelper.fromRUB(this.getTraderItemHandbookPriceRouble(request.item_id, request.tid), this.paymentHelper.getCurrency(trader.currency)); + const costOfPurchaseInCurrency = this.handbookHelper.fromRUB( + this.getTraderItemHandbookPriceRouble(request.item_id, request.tid), + this.paymentHelper.getCurrency(trader.currency), + ); pmcData.TradersInfo[request.tid].salesSum += costOfPurchaseInCurrency; } @@ -128,8 +140,10 @@ export class PaymentService const assortItemPriceRouble = this.handbookHelper.getTemplatePrice(purchasedAssortItem._tpl); if (!assortItemPriceRouble) { - this.logger.debug(`No item price found for ${purchasedAssortItem._tpl} on trader: ${traderId} in assort: ${traderAssortId}`); - + this.logger.debug( + `No item price found for ${purchasedAssortItem._tpl} on trader: ${traderId} in assort: ${traderAssortId}`, + ); + return 1; } @@ -145,7 +159,13 @@ export class PaymentService * @param {string} sessionID * @returns IItemEventRouterResponse */ - public getMoney(pmcData: IPmcData, amount: number, body: IProcessSellTradeRequestData, output: IItemEventRouterResponse, sessionID: string): IItemEventRouterResponse + public getMoney( + pmcData: IPmcData, + amount: number, + body: IProcessSellTradeRequestData, + output: IItemEventRouterResponse, + sessionID: string, + ): IItemEventRouterResponse { const trader = this.traderHelper.getTrader(body.tid, sessionID); const currency = this.paymentHelper.getCurrency(trader.currency); @@ -169,7 +189,6 @@ export class PaymentService if (item.upd.StackObjectsCount < maxStackSize) { - if (item.upd.StackObjectsCount + calcAmount > maxStackSize) { // calculate difference @@ -197,9 +216,9 @@ export class PaymentService items: [{ // eslint-disable-next-line @typescript-eslint/naming-convention item_id: currency, - count: calcAmount + count: calcAmount, }], - tid: body.tid + tid: body.tid, }; output = this.inventoryHelper.addItem(pmcData, request, output, sessionID, null, false, null, true); @@ -215,22 +234,22 @@ export class PaymentService } /** - * Recursively checks if the given item is - * inside the stash, that is it has the stash as - * ancestor with slotId=hideout - */ + * Recursively checks if the given item is + * inside the stash, that is it has the stash as + * ancestor with slotId=hideout + */ protected isItemInStash(pmcData: IPmcData, item: Item): boolean { let container = item; - + while ("parentId" in container) { if (container.parentId === pmcData.Inventory.stash && container.slotId === "hideout") { return true; } - - container = pmcData.Inventory.items.find(i => i._id === container.parentId); + + container = pmcData.Inventory.items.find((i) => i._id === container.parentId); if (!container) { break; @@ -248,16 +267,38 @@ export class PaymentService * @param output output object to send to client * @returns IItemEventRouterResponse */ - public addPaymentToOutput(pmcData: IPmcData, currencyTpl: string, amountToPay: number, sessionID: string, output: IItemEventRouterResponse): IItemEventRouterResponse + public addPaymentToOutput( + pmcData: IPmcData, + currencyTpl: string, + amountToPay: number, + sessionID: string, + output: IItemEventRouterResponse, + ): IItemEventRouterResponse { - const moneyItemsInInventory = this.getSortedMoneyItemsInInventory(pmcData, currencyTpl, pmcData.Inventory.stash); - const amountAvailable = moneyItemsInInventory.reduce((accumulator, item) => accumulator + item.upd.StackObjectsCount, 0); + const moneyItemsInInventory = this.getSortedMoneyItemsInInventory( + pmcData, + currencyTpl, + pmcData.Inventory.stash, + ); + const amountAvailable = moneyItemsInInventory.reduce( + (accumulator, item) => accumulator + item.upd.StackObjectsCount, + 0, + ); // If no money in inventory or amount is not enough we return false if (moneyItemsInInventory.length <= 0 || amountAvailable < amountToPay) { - this.logger.error(this.localisationService.getText("payment-not_enough_money_to_complete_transation", {amountToPay: amountToPay, amountAvailable: amountAvailable})); - output = this.httpResponse.appendErrorToOutput(output, this.localisationService.getText("payment-not_enough_money_to_complete_transation_short"), BackendErrorCodes.UNKNOWN_TRADING_ERROR); + this.logger.error( + this.localisationService.getText("payment-not_enough_money_to_complete_transation", { + amountToPay: amountToPay, + amountAvailable: amountAvailable, + }), + ); + output = this.httpResponse.appendErrorToOutput( + output, + this.localisationService.getText("payment-not_enough_money_to_complete_transation_short"), + BackendErrorCodes.UNKNOWN_TRADING_ERROR, + ); return output; } @@ -289,8 +330,8 @@ export class PaymentService /** * Get all money stacks in inventory and prioritse items in stash - * @param pmcData - * @param currencyTpl + * @param pmcData + * @param currencyTpl * @param playerStashId Players stash id * @returns Sorting money items */ @@ -360,7 +401,7 @@ export class PaymentService */ protected isInStash(itemId: string, inventoryItems: Item[], playerStashId: string): boolean { - const itemParent = inventoryItems.find(x => x._id === itemId); + const itemParent = inventoryItems.find((x) => x._id === itemId); if (itemParent) { diff --git a/project/src/services/PlayerService.ts b/project/src/services/PlayerService.ts index 8ef07062..ee66ee84 100644 --- a/project/src/services/PlayerService.ts +++ b/project/src/services/PlayerService.ts @@ -9,14 +9,13 @@ import { TimeUtil } from "@spt-aki/utils/TimeUtil"; @injectable() export class PlayerService { - constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("TimeUtil") protected timeUtil: TimeUtil, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("DatabaseServer") protected databaseServer: DatabaseServer + @inject("DatabaseServer") protected databaseServer: DatabaseServer, ) - { } + {} /** * Get level of player @@ -27,7 +26,7 @@ export class PlayerService { let accExp = 0; - for (const [level, { exp }] of this.databaseServer.getTables().globals.config.exp.level.exp_table.entries()) + for (const [level, {exp}] of this.databaseServer.getTables().globals.config.exp.level.exp_table.entries()) { accExp += exp; diff --git a/project/src/services/PmcChatResponseService.ts b/project/src/services/PmcChatResponseService.ts index 933861eb..3c91543e 100644 --- a/project/src/services/PmcChatResponseService.ts +++ b/project/src/services/PmcChatResponseService.ts @@ -27,7 +27,7 @@ export class PmcChatResponseService @inject("MatchBotDetailsCacheService") protected matchBotDetailsCacheService: MatchBotDetailsCacheService, @inject("LocalisationService") protected localisationService: LocalisationService, @inject("WeightedRandomHelper") protected weightedRandomHelper: WeightedRandomHelper, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.pmcResponsesConfig = this.configServer.getConfig(ConfigTypes.PMC_CHAT_RESPONSE); @@ -50,18 +50,21 @@ export class PmcChatResponseService const victimDetails = this.getVictimDetails(victim); const message = this.chooseMessage(true, pmcData); - this.notificationSendHelper.sendMessageToPlayer(sessionId, victimDetails, message, MessageType.USER_MESSAGE); - } + this.notificationSendHelper.sendMessageToPlayer( + sessionId, + victimDetails, + message, + MessageType.USER_MESSAGE, + ); + } } - /** * Not fully implemented yet, needs method of acquiring killers details after raid * @param sessionId Session id * @param pmcData Players profile * @param killer The bot who killed the player */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars public sendKillerResponse(sessionId: string, pmcData: IPmcData, killer: Aggressor): void { if (!killer) @@ -75,7 +78,10 @@ export class PmcChatResponseService } // find bot by name in cache - const killerDetailsInCache = this.matchBotDetailsCacheService.getBotByNameAndSide(killer.Name.trim(), killer.Side); + const killerDetailsInCache = this.matchBotDetailsCacheService.getBotByNameAndSide( + killer.Name.trim(), + killer.Side, + ); if (!killerDetailsInCache) { return; @@ -93,8 +99,8 @@ export class PmcChatResponseService Nickname: killerDetailsInCache.Info.Nickname, Side: killerDetailsInCache.Info.Side, Level: killerDetailsInCache.Info.Level, - MemberCategory: killerDetailsInCache.Info.MemberCategory - } + MemberCategory: killerDetailsInCache.Info.MemberCategory, + }, }; const message = this.chooseMessage(false, pmcData); @@ -127,14 +133,20 @@ export class PmcChatResponseService } // Choose random response from above list and request it from localisation service - let responseText = this.localisationService.getText(this.randomUtil.getArrayValue(possibleResponseLocaleKeys), {playerName: pmcData.Info.Nickname, playerLevel: pmcData.Info.Level, playerSide: pmcData.Info.Side}); + let responseText = this.localisationService.getText(this.randomUtil.getArrayValue(possibleResponseLocaleKeys), { + playerName: pmcData.Info.Nickname, + playerLevel: pmcData.Info.Level, + playerSide: pmcData.Info.Side, + }); if (this.appendSuffixToMessageEnd(isVictim)) { - const suffixText = this.localisationService.getText(this.randomUtil.getArrayValue(this.getResponseSuffixLocaleKeys())); + const suffixText = this.localisationService.getText( + this.randomUtil.getArrayValue(this.getResponseSuffixLocaleKeys()), + ); responseText += ` ${suffixText}`; } - + if (this.stripCapitalistion(isVictim)) { responseText = responseText.toLowerCase(); @@ -155,9 +167,9 @@ export class PmcChatResponseService */ protected stripCapitalistion(isVictim: boolean): boolean { - const chance = isVictim - ? this.pmcResponsesConfig.victim.stripCapitalisationChancePercent - : this.pmcResponsesConfig.killer.stripCapitalisationChancePercent; + const chance = isVictim ? + this.pmcResponsesConfig.victim.stripCapitalisationChancePercent : + this.pmcResponsesConfig.killer.stripCapitalisationChancePercent; return this.randomUtil.getChance100(chance); } @@ -169,9 +181,9 @@ export class PmcChatResponseService */ protected allCaps(isVictim: boolean): boolean { - const chance = isVictim - ? this.pmcResponsesConfig.victim.allCapsChancePercent - : this.pmcResponsesConfig.killer.allCapsChancePercent; + const chance = isVictim ? + this.pmcResponsesConfig.victim.allCapsChancePercent : + this.pmcResponsesConfig.killer.allCapsChancePercent; return this.randomUtil.getChance100(chance); } @@ -183,13 +195,13 @@ export class PmcChatResponseService */ appendSuffixToMessageEnd(isVictim: boolean): boolean { - const chance = isVictim - ? this.pmcResponsesConfig.victim.appendBroToMessageEndChancePercent - : this.pmcResponsesConfig.killer.appendBroToMessageEndChancePercent; + const chance = isVictim ? + this.pmcResponsesConfig.victim.appendBroToMessageEndChancePercent : + this.pmcResponsesConfig.killer.appendBroToMessageEndChancePercent; return this.randomUtil.getChance100(chance); } - + /** * Choose a type of response based on the weightings in pmc response config * @param isVictim Was responder killed by player @@ -197,9 +209,9 @@ export class PmcChatResponseService */ protected chooseResponseType(isVictim = true): string { - const responseWeights = isVictim - ? this.pmcResponsesConfig.victim.responseTypeWeights - : this.pmcResponsesConfig.killer.responseTypeWeights; + const responseWeights = isVictim ? + this.pmcResponsesConfig.victim.responseTypeWeights : + this.pmcResponsesConfig.killer.responseTypeWeights; return this.weightedRandomHelper.getWeightedValue(responseWeights); } @@ -208,14 +220,14 @@ export class PmcChatResponseService * Get locale keys related to the type of response to send (victim/killer) * @param keyType Positive/negative * @param isVictim Was responder killed by player - * @returns + * @returns */ protected getResponseLocaleKeys(keyType: string, isVictim = true): string[] { const keyBase = isVictim ? "pmcresponse-victim_" : "pmcresponse-killer_"; const keys = this.localisationService.getKeys(); - return keys.filter(x => x.startsWith(`${keyBase}${keyType}`)); + return keys.filter((x) => x.startsWith(`${keyBase}${keyType}`)); } /** @@ -226,7 +238,7 @@ export class PmcChatResponseService { const keys = this.localisationService.getKeys(); - return keys.filter(x => x.startsWith("pmcresponse-suffix")); + return keys.filter((x) => x.startsWith("pmcresponse-suffix")); } /** @@ -248,7 +260,25 @@ export class PmcChatResponseService */ protected getVictimDetails(pmcVictim: Victim): IUserDialogInfo { - const categories = [MemberCategory.UNIQUE_ID, MemberCategory.DEFAULT, MemberCategory.DEFAULT, MemberCategory.DEFAULT, MemberCategory.DEFAULT, MemberCategory.DEFAULT, MemberCategory.DEFAULT, MemberCategory.SHERPA, MemberCategory.DEVELOPER]; - return {_id: pmcVictim.Name, info:{Nickname: pmcVictim.Name, Level: pmcVictim.Level, Side: pmcVictim.Side, MemberCategory: this.randomUtil.getArrayValue(categories)}}; + const categories = [ + MemberCategory.UNIQUE_ID, + MemberCategory.DEFAULT, + MemberCategory.DEFAULT, + MemberCategory.DEFAULT, + MemberCategory.DEFAULT, + MemberCategory.DEFAULT, + MemberCategory.DEFAULT, + MemberCategory.SHERPA, + MemberCategory.DEVELOPER, + ]; + return { + _id: pmcVictim.Name, + info: { + Nickname: pmcVictim.Name, + Level: pmcVictim.Level, + Side: pmcVictim.Side, + MemberCategory: this.randomUtil.getArrayValue(categories), + }, + }; } -} \ No newline at end of file +} diff --git a/project/src/services/ProfileFixerService.ts b/project/src/services/ProfileFixerService.ts index 24cf3994..690c4b46 100644 --- a/project/src/services/ProfileFixerService.ts +++ b/project/src/services/ProfileFixerService.ts @@ -44,7 +44,7 @@ export class ProfileFixerService @inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("HashUtil") protected hashUtil: HashUtil, @inject("DatabaseServer") protected databaseServer: DatabaseServer, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.coreConfig = this.configServer.getConfig(ConfigTypes.CORE); @@ -81,30 +81,74 @@ export class ProfileFixerService this.reorderHideoutAreasWithResouceInputs(pmcProfile); - if (pmcProfile.Hideout.Areas[HideoutAreas.GENERATOR].slots.length < - (6 + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots.Generator.Slots)) + if ( + pmcProfile.Hideout.Areas[HideoutAreas.GENERATOR].slots.length < + (6 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + .Generator.Slots) + ) { this.logger.debug("Updating generator area slots to a size of 6 + hideout management skill"); - this.addEmptyObjectsToHideoutAreaSlots(HideoutAreas.GENERATOR, (6 + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots.Generator.Slots), pmcProfile); + this.addEmptyObjectsToHideoutAreaSlots( + HideoutAreas.GENERATOR, + 6 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + .Generator + .Slots, + pmcProfile, + ); } - if (pmcProfile.Hideout.Areas[HideoutAreas.WATER_COLLECTOR].slots.length < (1 + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots.WaterCollector.Slots)) + if ( + pmcProfile.Hideout.Areas[HideoutAreas.WATER_COLLECTOR].slots.length < + (1 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + .WaterCollector.Slots) + ) { this.logger.debug("Updating water collector area slots to a size of 1 + hideout management skill"); - this.addEmptyObjectsToHideoutAreaSlots(HideoutAreas.WATER_COLLECTOR, (1 + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots.WaterCollector.Slots), pmcProfile); + this.addEmptyObjectsToHideoutAreaSlots( + HideoutAreas.WATER_COLLECTOR, + 1 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + .WaterCollector.Slots, + pmcProfile, + ); } - if (pmcProfile.Hideout.Areas[HideoutAreas.AIR_FILTERING].slots.length < (3 + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots.AirFilteringUnit.Slots)) + if ( + pmcProfile.Hideout.Areas[HideoutAreas.AIR_FILTERING].slots.length < + (3 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + .AirFilteringUnit.Slots) + ) { this.logger.debug("Updating air filter area slots to a size of 3 + hideout management skill"); - this.addEmptyObjectsToHideoutAreaSlots(HideoutAreas.AIR_FILTERING, (3 + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots.AirFilteringUnit.Slots), pmcProfile); + this.addEmptyObjectsToHideoutAreaSlots( + HideoutAreas.AIR_FILTERING, + 3 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + .AirFilteringUnit.Slots, + pmcProfile, + ); } // BTC Farm doesnt have extra slots for hideout management, but we still check for modded stuff!! - if (pmcProfile.Hideout.Areas[HideoutAreas.BITCOIN_FARM].slots.length < (50 + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots.BitcoinFarm.Slots)) + if ( + pmcProfile.Hideout.Areas[HideoutAreas.BITCOIN_FARM].slots.length < + (50 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + .BitcoinFarm.Slots) + ) { this.logger.debug("Updating bitcoin farm area slots to a size of 50 + hideout management skill"); - this.addEmptyObjectsToHideoutAreaSlots(HideoutAreas.BITCOIN_FARM, (50 + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots.BitcoinFarm.Slots), pmcProfile); + this.addEmptyObjectsToHideoutAreaSlots( + HideoutAreas.BITCOIN_FARM, + 50 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + .BitcoinFarm.Slots, + pmcProfile, + ); } } @@ -120,7 +164,7 @@ export class ProfileFixerService protected addMissingGunStandContainerImprovements(pmcProfile: IPmcData): void { - const weaponStandArea = pmcProfile.Hideout.Areas.find(x => x.type === HideoutAreas.WEAPON_STAND); + const weaponStandArea = pmcProfile.Hideout.Areas.find((x) => x.type === HideoutAreas.WEAPON_STAND); if (!weaponStandArea || weaponStandArea.level === 0) { // No stand in profile or its level 0, skip @@ -128,8 +172,8 @@ export class ProfileFixerService } const db = this.databaseServer.getTables(); - const hideoutStandAreaDb = db.hideout.areas.find(x => x.type === HideoutAreas.WEAPON_STAND); - const hideoutStandSecondaryAreaDb = db.hideout.areas.find(x => x.parentArea === hideoutStandAreaDb._id); + const hideoutStandAreaDb = db.hideout.areas.find((x) => x.type === HideoutAreas.WEAPON_STAND); + const hideoutStandSecondaryAreaDb = db.hideout.areas.find((x) => x.parentArea === hideoutStandAreaDb._id); const stageCurrentAt = hideoutStandAreaDb.stages[weaponStandArea.level]; const hideoutStandStashId = pmcProfile.Inventory.hideoutAreaStashes[HideoutAreas.WEAPON_STAND]; const hideoutSecondaryStashId = pmcProfile.Inventory.hideoutAreaStashes[HideoutAreas.WEAPON_STAND_SECONDARY]; @@ -139,51 +183,66 @@ export class ProfileFixerService { // Value is missing, add it pmcProfile.Inventory.hideoutAreaStashes[HideoutAreas.WEAPON_STAND] = hideoutStandAreaDb._id; - pmcProfile.Inventory.hideoutAreaStashes[HideoutAreas.WEAPON_STAND_SECONDARY] = hideoutStandSecondaryAreaDb._id; + pmcProfile.Inventory.hideoutAreaStashes[HideoutAreas.WEAPON_STAND_SECONDARY] = + hideoutStandSecondaryAreaDb._id; // Add stash item to profile - const gunStandStashItem = pmcProfile.Inventory.items.find(x => x._id === hideoutStandAreaDb._id); + const gunStandStashItem = pmcProfile.Inventory.items.find((x) => x._id === hideoutStandAreaDb._id); if (gunStandStashItem) { gunStandStashItem._tpl = stageCurrentAt.container; - this.logger.debug(`Updated existing gun stand inventory stash: ${gunStandStashItem._id} tpl to ${stageCurrentAt.container}`); + this.logger.debug( + `Updated existing gun stand inventory stash: ${gunStandStashItem._id} tpl to ${stageCurrentAt.container}`, + ); } else { - pmcProfile.Inventory.items.push({ _id: hideoutStandAreaDb._id, _tpl: stageCurrentAt.container }); - this.logger.debug(`Added missing gun stand inventory stash: ${hideoutStandAreaDb._id} tpl to ${stageCurrentAt.container}`); + pmcProfile.Inventory.items.push({_id: hideoutStandAreaDb._id, _tpl: stageCurrentAt.container}); + this.logger.debug( + `Added missing gun stand inventory stash: ${hideoutStandAreaDb._id} tpl to ${stageCurrentAt.container}`, + ); } // Add secondary stash item to profile - const gunStandStashSecondaryItem = pmcProfile.Inventory.items.find(x => x._id === hideoutStandSecondaryAreaDb._id); + const gunStandStashSecondaryItem = pmcProfile.Inventory.items.find((x) => + x._id === hideoutStandSecondaryAreaDb._id + ); if (gunStandStashItem) { gunStandStashSecondaryItem._tpl = stageCurrentAt.container; - this.logger.debug(`Updated gun stand existing inventory secondary stash: ${gunStandStashSecondaryItem._id} tpl to ${stageCurrentAt.container}`); + this.logger.debug( + `Updated gun stand existing inventory secondary stash: ${gunStandStashSecondaryItem._id} tpl to ${stageCurrentAt.container}`, + ); } else { - pmcProfile.Inventory.items.push({ _id: hideoutStandSecondaryAreaDb._id, _tpl: stageCurrentAt.container }); - this.logger.debug(`Added missing gun stand inventory secondary stash: ${hideoutStandSecondaryAreaDb._id} tpl to ${stageCurrentAt.container}`); + pmcProfile.Inventory.items.push({_id: hideoutStandSecondaryAreaDb._id, _tpl: stageCurrentAt.container}); + this.logger.debug( + `Added missing gun stand inventory secondary stash: ${hideoutStandSecondaryAreaDb._id} tpl to ${stageCurrentAt.container}`, + ); } return; } - const stashItem = pmcProfile.Inventory.items?.find(x => x._id === hideoutStandAreaDb._id); + const stashItem = pmcProfile.Inventory.items?.find((x) => x._id === hideoutStandAreaDb._id); // `hideoutAreaStashes` has value related stash inventory items tpl doesnt match what's expected if (hideoutStandStashId && stashItem?._tpl !== stageCurrentAt.container) { - this.logger.debug(`primary Stash tpl was: ${stashItem._tpl}, but should be ${stageCurrentAt.container}, updating`); + this.logger.debug( + `primary Stash tpl was: ${stashItem._tpl}, but should be ${stageCurrentAt.container}, updating`, + ); // The id inside the profile does not match what the hideout db value is, out of sync, adjust stashItem._tpl = stageCurrentAt.container; } - const stashSecondaryItem = pmcProfile.Inventory.items?.find(x => x._id === hideoutStandSecondaryAreaDb._id); + const stashSecondaryItem = pmcProfile.Inventory.items?.find((x) => x._id === hideoutStandSecondaryAreaDb._id); // `hideoutAreaStashes` has value related stash inventory items tpl doesnt match what's expected if (hideoutSecondaryStashId && stashSecondaryItem?._tpl !== stageCurrentAt.container) { - this.logger.debug(`Secondary stash tpl was: ${stashSecondaryItem._tpl}, but should be ${stageCurrentAt.container}, updating`); + this.logger.debug( + `Secondary stash tpl was: ${stashSecondaryItem._tpl}, but should be ${stageCurrentAt.container}, updating`, + ); // The id inside the profile does not match what the hideout db value is, out of sync, adjust stashSecondaryItem._tpl = stageCurrentAt.container; } @@ -192,10 +251,10 @@ export class ProfileFixerService protected ensureGunStandLevelsMatch(pmcProfile: IPmcData): void { // only proceed if stand is level 1 or above - const gunStandParent = pmcProfile.Hideout.Areas.find(x => x.type === HideoutAreas.WEAPON_STAND); + const gunStandParent = pmcProfile.Hideout.Areas.find((x) => x.type === HideoutAreas.WEAPON_STAND); if (gunStandParent && gunStandParent.level > 0) { - const gunStandChild = pmcProfile.Hideout.Areas.find(x => x.type === HideoutAreas.WEAPON_STAND_SECONDARY); + const gunStandChild = pmcProfile.Hideout.Areas.find((x) => x.type === HideoutAreas.WEAPON_STAND_SECONDARY); if (gunStandChild && gunStandParent.level !== gunStandChild.level) { this.logger.success("Upgraded gun stand levels to match"); @@ -203,7 +262,7 @@ export class ProfileFixerService } } } - + protected addHideoutAreaStashes(pmcProfile: IPmcData): void { if (!pmcProfile?.Inventory?.hideoutAreaStashes) @@ -215,7 +274,7 @@ export class ProfileFixerService protected addMissingHideoutWallAreas(pmcProfile: IPmcData): void { - if (!pmcProfile.Hideout.Areas.find(x => x.type === HideoutAreas.WEAPON_STAND)) + if (!pmcProfile.Hideout.Areas.find((x) => x.type === HideoutAreas.WEAPON_STAND)) { pmcProfile.Hideout.Areas.push( { @@ -226,12 +285,12 @@ export class ProfileFixerService completeTime: 0, constructing: false, slots: [], - lastRecipe: "" - } + lastRecipe: "", + }, ); } - if (!pmcProfile.Hideout.Areas.find(x => x.type === HideoutAreas.WEAPON_STAND_SECONDARY)) + if (!pmcProfile.Hideout.Areas.find((x) => x.type === HideoutAreas.WEAPON_STAND_SECONDARY)) { pmcProfile.Hideout.Areas.push( { @@ -242,8 +301,8 @@ export class ProfileFixerService completeTime: 0, constructing: false, slots: [], - lastRecipe: "" - } + lastRecipe: "", + }, ); } } @@ -269,7 +328,7 @@ export class ProfileFixerService continue; } - const itemHandbookPrice = handbookPrices.find(x => x.Id === itemTpl); + const itemHandbookPrice = handbookPrices.find((x) => x.Id === itemTpl); if (!itemHandbookPrice) { continue; @@ -279,7 +338,7 @@ export class ProfileFixerService { if (fleaPrices[itemTpl] <= 1) { - continue; + continue; } // Price is over limit, adjust @@ -291,7 +350,7 @@ export class ProfileFixerService /** * Add tag to profile to indicate when it was made - * @param fullProfile + * @param fullProfile */ public addMissingAkiVersionTagToProfile(fullProfile: IAkiProfile): void { @@ -300,7 +359,7 @@ export class ProfileFixerService this.logger.debug("Adding aki object to profile"); fullProfile.aki = { version: this.watermark.getVersionTag(), - receivedGifts: [] + receivedGifts: [], }; } } @@ -314,7 +373,7 @@ export class ProfileFixerService { if (pmcProfile.ConditionCounters) { - pmcProfile.ConditionCounters.Counters = pmcProfile.ConditionCounters.Counters.filter(c => c.qid !== null); + pmcProfile.ConditionCounters.Counters = pmcProfile.ConditionCounters.Counters.filter((c) => c.qid !== null); } } @@ -325,7 +384,7 @@ export class ProfileFixerService return; } - // only add if other traders exist, means this is pre-patch 13 profile + // only add if other traders exist, means this is pre-patch 13 profile if (!pmcProfile.TradersInfo[Traders.LIGHTHOUSEKEEPER] && Object.keys(pmcProfile.TradersInfo).length > 0) { this.logger.warning("Added missing Lighthouse keeper trader to pmc profile"); @@ -335,7 +394,7 @@ export class ProfileFixerService salesSum: 0, standing: 0.2, loyaltyLevel: 1, - nextResupply: this.timeUtil.getTimestamp() + 3600 // now + 1 hour + nextResupply: this.timeUtil.getTimestamp() + 3600, // now + 1 hour }; } } @@ -346,7 +405,7 @@ export class ProfileFixerService { this.logger.debug("Adding UnlockedInfo object to profile"); pmcProfile.UnlockedInfo = { - unlockedProductionRecipe: [] + unlockedProductionRecipe: [], }; } } @@ -361,9 +420,9 @@ export class ProfileFixerService { if (pmcProfile.RepeatableQuests && activeQuests.length > 0) { - const existsInActiveRepeatableQuests = activeQuests.some(x => x._id === backendCounter.qid); - const existsInQuests = pmcProfile.Quests.some(q => q.qid === backendCounter.qid); - + const existsInActiveRepeatableQuests = activeQuests.some((x) => x._id === backendCounter.qid); + const existsInQuests = pmcProfile.Quests.some((q) => q.qid === backendCounter.qid); + // if BackendCounter's quest is neither in activeQuests nor Quests it's stale if (!existsInActiveRepeatableQuests && !existsInQuests) { @@ -375,7 +434,7 @@ export class ProfileFixerService for (const counterKeyToRemove of counterKeysToRemove) { this.logger.debug(`Removed ${counterKeyToRemove} backend count object`); - delete pmcProfile.BackendCounters[counterKeyToRemove]; + delete pmcProfile.BackendCounters[counterKeyToRemove]; } } } @@ -400,7 +459,7 @@ export class ProfileFixerService for (const traderId in pmcProfile.TradersInfo) { const trader = pmcProfile.TradersInfo[traderId]; - if (trader && trader.salesSum === null) + if (trader && trader.salesSum === null) { this.logger.warning(`trader ${traderId} has a null salesSum value, resetting to 0`); trader.salesSum = 0; @@ -430,7 +489,7 @@ export class ProfileFixerService return; } - const fixes = new Map(); + const fixes = new Map(); const questsToDelete: IQuestStatus[] = []; const fullProfile = this.profileHelper.getFullProfile(pmcProfile.sessionId); const isDevProfile = fullProfile?.info.edition.toLowerCase() === "spt developer"; @@ -448,9 +507,13 @@ export class ProfileFixerService if (quest.status && !Number(quest.status)) { if (fixes.has(quest.status)) + { fixes.set(quest.status, fixes.get(quest.status) + 1); + } else + { fixes.set(quest.status, 1); + } const newQuestStatus = QuestStatus[quest.status]; quest.status = newQuestStatus; @@ -461,7 +524,7 @@ export class ProfileFixerService { const newKey = QuestStatus[statusTimer]; quest.statusTimers[newKey] = quest.statusTimers[statusTimer]; - delete quest.statusTimers[statusTimer]; + delete quest.statusTimers[statusTimer]; } } } @@ -473,7 +536,13 @@ export class ProfileFixerService } if (fixes.size > 0) - this.logger.debug(`Updated quests values: ${Array.from(fixes.entries()).map(([k, v]) => `(${k}: ${v} times)`).join(", ")}`); + { + this.logger.debug( + `Updated quests values: ${ + Array.from(fixes.entries()).map(([k, v]) => `(${k}: ${v} times)`).join(", ") + }`, + ); + } } protected addMissingRepeatableQuestsProperty(pmcProfile: IPmcData): void @@ -485,7 +554,9 @@ export class ProfileFixerService { if ( !(currentRepeatable.changeRequirement && - currentRepeatable.activeQuests.every(x => (typeof x.changeCost !== "undefined" && typeof x.changeStandingCost !== "undefined"))) + currentRepeatable.activeQuests.every( + (x) => (typeof x.changeCost !== "undefined" && typeof x.changeStandingCost !== "undefined"), + )) ) { repeatablesCompatible = false; @@ -507,7 +578,9 @@ export class ProfileFixerService protected addMissingWallImprovements(pmcProfile: IPmcData): void { const profileWallArea = pmcProfile.Hideout.Areas[HideoutAreas.EMERGENCY_WALL]; - const wallDb = this.databaseServer.getTables().hideout.areas.find(x => x.type === HideoutAreas.EMERGENCY_WALL); + const wallDb = this.databaseServer.getTables().hideout.areas.find((x) => + x.type === HideoutAreas.EMERGENCY_WALL + ); if (profileWallArea.level > 0) { @@ -531,7 +604,7 @@ export class ProfileFixerService pmcProfile.Hideout.Improvement[improvement.id] = { completed: true, - improveCompleteTimestamp: this.timeUtil.getTimestamp() + i // add some variability + improveCompleteTimestamp: this.timeUtil.getTimestamp() + i, // add some variability }; this.logger.debug(`Added wall improvement ${improvement.id} to profile`); @@ -555,13 +628,13 @@ export class ProfileFixerService } // Only slots with location index - area.slots = area.slots.filter(x => "locationIndex" in x); + area.slots = area.slots.filter((x) => "locationIndex" in x); // Only slots that: // Have an item property and it has at least one item in it // Or // Have no item property - area.slots = area.slots.filter(x => "item" in x && x.item?.length > 0 || !("item" in x)); + area.slots = area.slots.filter((x) => "item" in x && x.item?.length > 0 || !("item" in x)); } } @@ -571,7 +644,12 @@ export class ProfileFixerService */ protected reorderHideoutAreasWithResouceInputs(pmcProfile: IPmcData): void { - const areasToCheck = [HideoutAreas.AIR_FILTERING, HideoutAreas.GENERATOR, HideoutAreas.BITCOIN_FARM, HideoutAreas.WATER_COLLECTOR]; + const areasToCheck = [ + HideoutAreas.AIR_FILTERING, + HideoutAreas.GENERATOR, + HideoutAreas.BITCOIN_FARM, + HideoutAreas.WATER_COLLECTOR, + ]; for (const areaId of areasToCheck) { @@ -583,13 +661,13 @@ export class ProfileFixerService continue; } - if (!area.slots || area.slots.length === 0) + if (!area.slots || area.slots.length === 0) { this.logger.debug(`unable to sort ${areaId} slots, no slots found`); continue; } - area.slots = area.slots.sort( (a, b) => + area.slots = area.slots.sort((a, b) => { return a.locationIndex > b.locationIndex ? 1 : -1; }); @@ -601,10 +679,13 @@ export class ProfileFixerService * @param areaType area to check * @param pmcProfile profile to update */ - protected addEmptyObjectsToHideoutAreaSlots(areaType: HideoutAreas, emptyItemCount: number, pmcProfile: IPmcData): void + protected addEmptyObjectsToHideoutAreaSlots( + areaType: HideoutAreas, + emptyItemCount: number, + pmcProfile: IPmcData, + ): void { - - const area = pmcProfile.Hideout.Areas.find(x => x.type === areaType); + const area = pmcProfile.Hideout.Areas.find((x) => x.type === areaType); area.slots = this.addObjectsToArray(emptyItemCount, area.slots); } @@ -612,23 +693,22 @@ export class ProfileFixerService { for (let i = 0; i < count; i++) { - if (!slots.find(x => x.locationIndex === i)) + if (!slots.find((x) => x.locationIndex === i)) { slots.push({locationIndex: i}); } } return slots; - } /** * In 18876 bsg changed the pockets tplid to be one that has 3 additional special slots - * @param pmcProfile + * @param pmcProfile */ protected updateProfilePocketsToNewId(pmcProfile: IPmcData): void { - const pocketItem = pmcProfile.Inventory?.items?.find(x => x.slotId === "Pockets"); + const pocketItem = pmcProfile.Inventory?.items?.find((x) => x.slotId === "Pockets"); if (pocketItem) { if (pocketItem._tpl === "557ffd194bdc2d28148b457f") @@ -668,7 +748,7 @@ export class ProfileFixerService } // Iterate over area levels, check for bonuses, add if needed - const dbArea = dbHideoutAreas.find(x => x.type === areaType); + const dbArea = dbHideoutAreas.find((x) => x.type === areaType); if (!dbArea) { continue; @@ -691,16 +771,19 @@ export class ProfileFixerService if (!profileBonus) { // no bonus, add to profile - this.logger.debug(`Profile has level ${level} area ${HideoutAreas[area.type]} but no bonus found, adding ${bonus.type}`); + this.logger.debug( + `Profile has level ${level} area ${ + HideoutAreas[area.type] + } but no bonus found, adding ${bonus.type}`, + ); this.hideoutHelper.applyPlayerUpgradesBonuses(pmcProfile, bonus); } - } + } } } } /** - * * @param profileBonuses bonuses from profile * @param bonus bonus to find * @returns matching bonus @@ -710,27 +793,33 @@ export class ProfileFixerService // match by id first, used by "TextBonus" bonuses if (bonus.id) { - return profileBonuses.find(x => x.id === bonus.id); + return profileBonuses.find((x) => x.id === bonus.id); } if (bonus.type.toLowerCase() === "stashsize") { return profileBonuses.find( - x => x.type === bonus.type - && x.templateId === bonus.templateId); + (x) => + x.type === bonus.type && + x.templateId === bonus.templateId, + ); } if (bonus.type.toLowerCase() === "additionalslots") { return profileBonuses.find( - x => x.type === bonus.type - && x.value === bonus.value - && x.visible === bonus.visible); + (x) => + x.type === bonus.type && + x.value === bonus.value && + x.visible === bonus.visible, + ); } return profileBonuses.find( - x => x.type === bonus.type - && x.value === bonus.value); + (x) => + x.type === bonus.type && + x.value === bonus.value, + ); } /** @@ -745,7 +834,7 @@ export class ProfileFixerService // Get items placed in root of stash // TODO: extend to other areas / sub items - const inventoryItemsToCheck = pmcProfile.Inventory.items.filter(x => ["hideout", "main"].includes(x.slotId)); + const inventoryItemsToCheck = pmcProfile.Inventory.items.filter((x) => ["hideout", "main"].includes(x.slotId)); if (!inventoryItemsToCheck) { return; @@ -760,7 +849,9 @@ export class ProfileFixerService if (this.coreConfig.fixes.removeModItemsFromProfile) { - this.logger.success(`Deleting item from inventory and insurance with id: ${item._id} tpl: ${item._tpl}`); + this.logger.success( + `Deleting item from inventory and insurance with id: ${item._id} tpl: ${item._tpl}`, + ); // Also deletes from insured array this.inventoryHelper.removeItem(pmcProfile, item._id, sessionId); @@ -781,7 +872,9 @@ export class ProfileFixerService if (this.coreConfig.fixes.removeModItemsFromProfile) { delete fullProfile.userbuilds.weaponBuilds[buildId]; - this.logger.warning(`Item: ${item._tpl} has resulted in the deletion of weapon build: ${buildId}`); + this.logger.warning( + `Item: ${item._tpl} has resulted in the deletion of weapon build: ${buildId}`, + ); } break; @@ -824,8 +917,10 @@ export class ProfileFixerService if (this.coreConfig.fixes.removeModItemsFromProfile) { - dialog.messages.splice(dialog.messages.findIndex(x => x._id === message._id), 1); - this.logger.warning(`Item: ${item._tpl} has resulted in the deletion of message: ${message._id} from dialog ${dialogId}`); + dialog.messages.splice(dialog.messages.findIndex((x) => x._id === message._id), 1); + this.logger.warning( + `Item: ${item._tpl} has resulted in the deletion of message: ${message._id} from dialog ${dialogId}`, + ); } break; @@ -857,8 +952,13 @@ export class ProfileFixerService this.logger.error(this.localisationService.getText("fixer-mod_item_found", activeQuest.traderId)); if (this.coreConfig.fixes.removeModItemsFromProfile) { - this.logger.warning(`Non-default quest: ${activeQuest._id} from trader: ${activeQuest.traderId} removed from RepeatableQuests list in profile`); - repeatable.activeQuests.splice(repeatable.activeQuests.findIndex(x => x._id === activeQuest._id), 1); + this.logger.warning( + `Non-default quest: ${activeQuest._id} from trader: ${activeQuest.traderId} removed from RepeatableQuests list in profile`, + ); + repeatable.activeQuests.splice( + repeatable.activeQuests.findIndex((x) => x._id === activeQuest._id), + 1, + ); } continue; @@ -872,11 +972,18 @@ export class ProfileFixerService { if (!itemsDb[rewardItem._tpl]) { - this.logger.error(this.localisationService.getText("fixer-mod_item_found", rewardItem._tpl)); + this.logger.error( + this.localisationService.getText("fixer-mod_item_found", rewardItem._tpl), + ); if (this.coreConfig.fixes.removeModItemsFromProfile) { - this.logger.warning(`Non-default quest: ${activeQuest._id} from trader: ${activeQuest.traderId} removed from RepeatableQuests list in profile`); - repeatable.activeQuests.splice(repeatable.activeQuests.findIndex(x => x._id === activeQuest._id), 1); + this.logger.warning( + `Non-default quest: ${activeQuest._id} from trader: ${activeQuest.traderId} removed from RepeatableQuests list in profile`, + ); + repeatable.activeQuests.splice( + repeatable.activeQuests.findIndex((x) => x._id === activeQuest._id), + 1, + ); } } } @@ -898,7 +1005,7 @@ export class ProfileFixerService } } } - + /** * Add `Improvements` object to hideout if missing - added in eft 13.0.21469 * @param pmcProfile profile to update @@ -939,7 +1046,7 @@ export class ProfileFixerService // Get all areas from templates/profiles.json for (const area of profileTemplate.character.Hideout.Areas) { - if (!pmcProfile.Hideout.Areas.find(x => x.type === area.type)) + if (!pmcProfile.Hideout.Areas.find((x) => x.type === area.type)) { pmcProfile.Hideout.Areas.push(area); this.logger.debug(`Added missing hideout area ${area.type} to profile`); @@ -957,7 +1064,7 @@ export class ProfileFixerService { if (prodKey.startsWith("ScavCase")) { - delete pmcProfile.Hideout.Production[prodKey]; + delete pmcProfile.Hideout.Production[prodKey]; } } } @@ -980,7 +1087,9 @@ export class ProfileFixerService fullProfile.info.aid = fullProfile.characters.pmc.aid; - this.logger.debug(`Migrated AccountId from: ${fullProfile.characters.pmc.sessionId} to: ${fullProfile.characters.pmc.aid}`); + this.logger.debug( + `Migrated AccountId from: ${fullProfile.characters.pmc.sessionId} to: ${fullProfile.characters.pmc.aid}`, + ); } } @@ -1020,12 +1129,14 @@ export class ProfileFixerService // Bonus lacks id, find matching hideout area / stage / bonus for (const area of this.databaseServer.getTables().hideout.areas) - { + { // TODO: skip if no stages for (const stageIndex in area.stages) { const stageInfo = area.stages[stageIndex]; - const matchingBonus = stageInfo.bonuses.find(x => x.templateId === bonus.templateId && x.type === bonus.type); + const matchingBonus = stageInfo.bonuses.find((x) => + x.templateId === bonus.templateId && x.type === bonus.type + ); if (matchingBonus) { // Add id to bonus, flag bonus as found and exit stage loop @@ -1060,4 +1171,4 @@ export class ProfileFixerService this.logger.success("Successfully migrated hideout Improvements data to new location, deleted old data"); } } -} \ No newline at end of file +} diff --git a/project/src/services/ProfileSnapshotService.ts b/project/src/services/ProfileSnapshotService.ts index b8dfc36d..2007ea5c 100644 --- a/project/src/services/ProfileSnapshotService.ts +++ b/project/src/services/ProfileSnapshotService.ts @@ -9,10 +9,10 @@ export class ProfileSnapshotService protected storedProfileSnapshots: Record = {}; constructor( - @inject("JsonUtil") protected jsonUtil: JsonUtil + @inject("JsonUtil") protected jsonUtil: JsonUtil, ) {} - + /** * Store a profile into an in-memory object * @param sessionID session id - acts as the key @@ -61,4 +61,4 @@ export class ProfileSnapshotService { delete this.storedProfileSnapshots[sessionID]; } -} \ No newline at end of file +} diff --git a/project/src/services/RagfairCategoriesService.ts b/project/src/services/RagfairCategoriesService.ts index 1ee6cb64..a0624b1b 100644 --- a/project/src/services/RagfairCategoriesService.ts +++ b/project/src/services/RagfairCategoriesService.ts @@ -9,15 +9,15 @@ export class RagfairCategoriesService protected categories: Record = {}; constructor( - @inject("WinstonLogger") protected logger: ILogger + @inject("WinstonLogger") protected logger: ILogger, ) - { } + {} /** * Get all flea categories and their count of offers * @returns item categories and count */ - public getAllCategories(): Record + public getAllCategories(): Record { return this.categories; } @@ -26,7 +26,7 @@ export class RagfairCategoriesService * With the supplied items, get custom categories * @returns a custom list of categories */ - public getBespokeCategories(offers: IRagfairOffer[]): Record + public getBespokeCategories(offers: IRagfairOffer[]): Record { return this.processOffersIntoCategories(offers); } @@ -36,7 +36,7 @@ export class RagfairCategoriesService * @param offers ragfair offers * @returns categories and count */ - protected processOffersIntoCategories(offers: IRagfairOffer[]): Record + protected processOffersIntoCategories(offers: IRagfairOffer[]): Record { const result = {}; for (const offer of offers) @@ -53,14 +53,14 @@ export class RagfairCategoriesService * @param categories Categories to update * @param increment (Optional) Should item be incremented or decremented */ - protected addOrIncrementCategory(offer: IRagfairOffer, categories: Record, increment = true ): void + protected addOrIncrementCategory(offer: IRagfairOffer, categories: Record, increment = true): void { const itemId = offer.items[0]._tpl; if (increment) { - categories[itemId] = categories[itemId] - ? categories[itemId] + 1 - : 1; + categories[itemId] = categories[itemId] ? + categories[itemId] + 1 : + 1; } else { @@ -80,7 +80,7 @@ export class RagfairCategoriesService /** * Increase category count by 1 - * @param offer + * @param offer */ public incrementCategory(offer: IRagfairOffer): void { @@ -90,11 +90,11 @@ export class RagfairCategoriesService /** * Reduce category count by 1 - * @param offer + * @param offer */ public decrementCategory(offer: IRagfairOffer): void { this.addOrIncrementCategory(offer, this.categories, false); this.categories[offer.items[0]._tpl]--; } -} \ No newline at end of file +} diff --git a/project/src/services/RagfairLinkedItemService.ts b/project/src/services/RagfairLinkedItemService.ts index de08ac68..b881cdc0 100644 --- a/project/src/services/RagfairLinkedItemService.ts +++ b/project/src/services/RagfairLinkedItemService.ts @@ -12,9 +12,9 @@ export class RagfairLinkedItemService constructor( @inject("DatabaseServer") protected databaseServer: DatabaseServer, - @inject("ItemHelper") protected itemHelper: ItemHelper + @inject("ItemHelper") protected itemHelper: ItemHelper, ) - { } + {} public getLinkedItems(linkedSearchId: string): Set { @@ -34,7 +34,7 @@ export class RagfairLinkedItemService public getLinkedDbItems(itemTpl: string): ITemplateItem[] { const linkedItemsToWeaponTpls = this.getLinkedItems(itemTpl); - return [...linkedItemsToWeaponTpls].map(x => + return [...linkedItemsToWeaponTpls].map((x) => { const itemDetails = this.itemHelper.getItem(x); return itemDetails[1]; @@ -88,11 +88,14 @@ export class RagfairLinkedItemService /** * Add ammo to revolvers linked item dictionary * @param cylinder Revolvers cylinder - * @param applyLinkedItems + * @param applyLinkedItems */ - protected addRevolverCylinderAmmoToLinkedItems(cylinder: ITemplateItem, applyLinkedItems: (items: string[]) => void): void + protected addRevolverCylinderAmmoToLinkedItems( + cylinder: ITemplateItem, + applyLinkedItems: (items: string[]) => void, + ): void { - const cylinderMod = cylinder._props.Slots.find(x => x._name === "mod_magazine"); + const cylinderMod = cylinder._props.Slots.find((x) => x._name === "mod_magazine"); if (cylinderMod) { // Get the first cylinder filter tpl @@ -108,8 +111,8 @@ export class RagfairLinkedItemService /** * Scans a given slot type for filters and returns them as a Set - * @param item - * @param slot + * @param item + * @param slot * @returns array of ids */ protected getFilters(item: ITemplateItem, slot: string): string[] @@ -140,4 +143,4 @@ export class RagfairLinkedItemService return filters; } -} \ No newline at end of file +} diff --git a/project/src/services/RagfairOfferService.ts b/project/src/services/RagfairOfferService.ts index e67b659f..c38e2973 100644 --- a/project/src/services/RagfairOfferService.ts +++ b/project/src/services/RagfairOfferService.ts @@ -38,7 +38,7 @@ export class RagfairOfferService @inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder, @inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); @@ -113,12 +113,14 @@ export class RagfairOfferService * Remove an offer from ragfair by offer id * @param offerId Offer id to remove */ - public removeOfferById(offerId: string): void + public removeOfferById(offerId: string): void { const offer = this.ragfairOfferHandler.getOfferById(offerId); if (!offer) { - this.logger.warning(this.localisationService.getText("ragfair-unable_to_remove_offer_doesnt_exist", offerId)); + this.logger.warning( + this.localisationService.getText("ragfair-unable_to_remove_offer_doesnt_exist", offerId), + ); return; } @@ -171,13 +173,13 @@ export class RagfairOfferService for (const sessionID in this.saveServer.getProfiles()) { const pmcData = this.saveServer.getProfile(sessionID).characters.pmc; - + if (pmcData.RagfairInfo === undefined || pmcData.RagfairInfo.offers === undefined) { // Profile is wiped continue; } - + this.ragfairOfferHandler.addOffers(pmcData.RagfairInfo.offers); } this.playerOffersLoaded = true; @@ -235,7 +237,7 @@ export class RagfairOfferService const pmcID = String(offer.user.id); const profile = this.profileHelper.getProfileByPmcId(pmcID); const sessionID = profile.sessionId; - const offerIndex = profile.RagfairInfo.offers.findIndex(o => o._id === offer._id); + const offerIndex = profile.RagfairInfo.offers.findIndex((o) => o._id === offer._id); profile.RagfairInfo.rating -= this.ragfairConfig.sell.reputation.loss; profile.RagfairInfo.isRatingGrowing = false; @@ -243,7 +245,10 @@ export class RagfairOfferService if (offerIndex === -1) { this.logger.warning(this.localisationService.getText("ragfair-unable_to_find_offer_to_remove", offer._id)); - return this.httpResponse.appendErrorToOutput(this.eventOutputHolder.getOutput(sessionID), this.localisationService.getText("ragfair-offer_not_found_in_profile_short")); + return this.httpResponse.appendErrorToOutput( + this.eventOutputHolder.getOutput(sessionID), + this.localisationService.getText("ragfair-offer_not_found_in_profile_short"), + ); } if (offer.items[0].upd.StackObjectsCount > offer.items[0].upd.OriginalStackObjectsCount) diff --git a/project/src/services/RagfairPriceService.ts b/project/src/services/RagfairPriceService.ts index 54a236d4..435dd0cd 100644 --- a/project/src/services/RagfairPriceService.ts +++ b/project/src/services/RagfairPriceService.ts @@ -31,7 +31,7 @@ export class RagfairPriceService implements OnLoad protected prices: IRagfairServerPrices = { static: {}, - dynamic: {} + dynamic: {}, }; constructor( @@ -43,7 +43,7 @@ export class RagfairPriceService implements OnLoad @inject("TraderHelper") protected traderHelper: TraderHelper, @inject("RandomUtil") protected randomUtil: RandomUtil, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.ragfairConfig = this.configServer.getConfig(ConfigTypes.RAGFAIR); @@ -52,7 +52,7 @@ export class RagfairPriceService implements OnLoad /** * Generate static (handbook) and dynamic (prices.json) flea prices, store inside class as dictionaries */ - public async onLoad(): Promise + public async onLoad(): Promise { if (!this.generatedStaticPrices) { @@ -67,7 +67,7 @@ export class RagfairPriceService implements OnLoad } } - public getRoute(): string + public getRoute(): string { return "RagfairPriceService"; } @@ -77,7 +77,11 @@ export class RagfairPriceService implements OnLoad */ public generateStaticPrices(): void { - for (const item of Object.values(this.databaseServer.getTables().templates.items).filter(x => x._type === "Item")) + for ( + const item of Object.values(this.databaseServer.getTables().templates.items).filter((x) => + x._type === "Item" + ) + ) { this.prices.static[item._id] = Math.round(this.handbookHelper.getTemplatePrice(item._id)); } @@ -103,7 +107,9 @@ export class RagfairPriceService implements OnLoad let itemPrice = this.getDynamicPriceForItem(tplId) || this.getStaticPriceForItem(tplId); if (!itemPrice) { - this.logger.warning(this.localisationService.getText("ragfair-unable_to_find_item_price_for_item_in_flea_handbook", tplId)); + this.logger.warning( + this.localisationService.getText("ragfair-unable_to_find_item_price_for_item_in_flea_handbook", tplId), + ); } // If no price in dynamic/static, set to 1 @@ -150,7 +156,7 @@ export class RagfairPriceService implements OnLoad public getAllFleaPrices(): Record { // assign static values first, then overwrite them with dynamic, any values not stored in dynamic data will be covered by static data - return { ...this.prices.static, ...this.prices.dynamic }; + return {...this.prices.static, ...this.prices.dynamic}; } public getAllStaticPrices(): Record @@ -171,7 +177,7 @@ export class RagfairPriceService implements OnLoad /** * Get the rouble price for an assorts barter scheme - * @param barterScheme + * @param barterScheme * @returns Rouble price */ public getBarterPrice(barterScheme: IBarterScheme[]): number @@ -180,7 +186,7 @@ export class RagfairPriceService implements OnLoad for (const item of barterScheme) { - price += (this.prices.static[item._tpl] * item.count); + price += this.prices.static[item._tpl] * item.count; } return Math.round(price); @@ -219,7 +225,7 @@ export class RagfairPriceService implements OnLoad itemPrice = traderPrice; } } - + // Check if item type is weapon preset, handle differently const itemDetails = this.itemHelper.getItem(item._tpl); if (this.presetHelper.isPreset(item._id) && itemDetails[1]._props.weapFireType) @@ -248,7 +254,7 @@ export class RagfairPriceService implements OnLoad const rangeValues = this.getOfferTypeRangeValues(isPreset, isPackOffer); price = this.randomiseOfferPrice(price, rangeValues); - + if (price < 1) { price = 1; @@ -291,12 +297,17 @@ export class RagfairPriceService implements OnLoad const priceDifferencePercent = this.getPriceDifference(itemHandbookPrice, itemPrice); // Only adjust price if difference is > a percent AND item price passes threshhold set in config - if (priceDifferencePercent > this.ragfairConfig.dynamic.offerAdjustment.maxPriceDifferenceBelowHandbookPercent - && itemPrice >= this.ragfairConfig.dynamic.offerAdjustment.priceThreshholdRub) + if ( + priceDifferencePercent > + this.ragfairConfig.dynamic.offerAdjustment.maxPriceDifferenceBelowHandbookPercent && + itemPrice >= this.ragfairConfig.dynamic.offerAdjustment.priceThreshholdRub + ) { - //const itemDetails = this.itemHelper.getItem(itemTpl); - //this.logger.debug(`item below handbook price ${itemDetails[1]._name} handbook: ${itemHandbookPrice} flea: ${itemPrice} ${priceDifferencePercent}%`); - itemPrice = Math.round(itemHandbookPrice * this.ragfairConfig.dynamic.offerAdjustment.handbookPriceMultipier); + // const itemDetails = this.itemHelper.getItem(itemTpl); + // this.logger.debug(`item below handbook price ${itemDetails[1]._name} handbook: ${itemHandbookPrice} flea: ${itemPrice} ${priceDifferencePercent}%`); + itemPrice = Math.round( + itemHandbookPrice * this.ragfairConfig.dynamic.offerAdjustment.handbookPriceMultipier, + ); } return itemPrice; @@ -344,7 +355,9 @@ export class RagfairPriceService implements OnLoad } // Get mods on current gun not in default preset - const newOrReplacedModsInPresetVsDefault = items.filter(x => !presetResult.preset._items.some(y => y._tpl === x._tpl)); + const newOrReplacedModsInPresetVsDefault = items.filter((x) => + !presetResult.preset._items.some((y) => y._tpl === x._tpl) + ); // Add up extra mods price let extraModsPrice = 0; @@ -358,7 +371,9 @@ export class RagfairPriceService implements OnLoad if (newOrReplacedModsInPresetVsDefault.length >= 1) { // Add up cost of mods replaced - const modsReplacedByNewMods = newOrReplacedModsInPresetVsDefault.filter(x => presetResult.preset._items.some(y => y.slotId === x.slotId)); + const modsReplacedByNewMods = newOrReplacedModsInPresetVsDefault.filter((x) => + presetResult.preset._items.some((y) => y.slotId === x.slotId) + ); // Add up replaced mods price let replacedModsPrice = 0; @@ -398,29 +413,37 @@ export class RagfairPriceService implements OnLoad * @param presets weapon presets to choose from * @returns Default preset object */ - protected getWeaponPreset(presets: IPreset[], weapon: Item): {isDefault: boolean, preset: IPreset} + protected getWeaponPreset(presets: IPreset[], weapon: Item): {isDefault: boolean; preset: IPreset;} { - const defaultPreset = presets.find(x => x._encyclopedia); + const defaultPreset = presets.find((x) => x._encyclopedia); if (defaultPreset) { return { isDefault: true, - preset: defaultPreset + preset: defaultPreset, }; } if (presets.length === 1) { - this.logger.debug(`Item Id: ${weapon._tpl} has no default encyclopedia entry but only one preset (${presets[0]._name}), choosing preset (${presets[0]._name})`); + this.logger.debug( + `Item Id: ${weapon._tpl} has no default encyclopedia entry but only one preset (${ + presets[0]._name + }), choosing preset (${presets[0]._name})`, + ); } else { - this.logger.debug(`Item Id: ${weapon._tpl} has no default encyclopedia entry, choosing first preset (${presets[0]._name}) of ${presets.length}`); + this.logger.debug( + `Item Id: ${weapon._tpl} has no default encyclopedia entry, choosing first preset (${ + presets[0]._name + }) of ${presets.length}`, + ); } return { isDefault: false, - preset: presets[0] + preset: presets[0], }; } -} \ No newline at end of file +} diff --git a/project/src/services/RagfairRequiredItemsService.ts b/project/src/services/RagfairRequiredItemsService.ts index 8adc0efd..23e90891 100644 --- a/project/src/services/RagfairRequiredItemsService.ts +++ b/project/src/services/RagfairRequiredItemsService.ts @@ -12,9 +12,9 @@ export class RagfairRequiredItemsService constructor( @inject("WinstonLogger") protected logger: ILogger, @inject("PaymentHelper") protected paymentHelper: PaymentHelper, - @inject("RagfairOfferService") protected ragfairOfferService: RagfairOfferService + @inject("RagfairOfferService") protected ragfairOfferService: RagfairOfferService, ) - { } + {} public getRequiredItemsById(searchId: string): any { @@ -50,5 +50,4 @@ export class RagfairRequiredItemsService this.requiredItemsCache = requiredItems; } - -} \ No newline at end of file +} diff --git a/project/src/services/RagfairTaxService.ts b/project/src/services/RagfairTaxService.ts index e29ba5f9..edfa3a3e 100644 --- a/project/src/services/RagfairTaxService.ts +++ b/project/src/services/RagfairTaxService.ts @@ -18,9 +18,9 @@ export class RagfairTaxService @inject("WinstonLogger") protected logger: ILogger, @inject("DatabaseServer") protected databaseServer: DatabaseServer, @inject("RagfairPriceService") protected ragfairPriceService: RagfairPriceService, - @inject("ItemHelper") protected itemHelper: ItemHelper + @inject("ItemHelper") protected itemHelper: ItemHelper, ) - { } + {} public storeClientOfferTaxValue(sessionId: string, offer: IStorePlayerOfferTaxAmountRequestData): void { @@ -39,7 +39,13 @@ export class RagfairTaxService // This method, along with calculateItemWorth, is trying to mirror the client-side code found in the method "CalculateTaxPrice". // It's structured to resemble the client-side code as closely as possible - avoid making any big structure changes if it's not necessary. - public calculateTax(item: Item, pmcData: IPmcData, requirementsValue: number, offerItemCount: number, sellInOnePiece: boolean): number + public calculateTax( + item: Item, + pmcData: IPmcData, + requirementsValue: number, + offerItemCount: number, + sellInOnePiece: boolean, + ): number { if (!requirementsValue) { @@ -56,7 +62,8 @@ export class RagfairTaxService const requirementsPrice = requirementsValue * (sellInOnePiece ? 1 : offerItemCount); const itemTaxMult = this.databaseServer.getTables().globals.config.RagFair.communityItemTax / 100.0; - const requirementTaxMult = this.databaseServer.getTables().globals.config.RagFair.communityRequirementTax / 100.0; + const requirementTaxMult = this.databaseServer.getTables().globals.config.RagFair.communityRequirementTax / + 100.0; let itemPriceMult = Math.log10(itemWorth / requirementsPrice); let requirementPriceMult = Math.log10(requirementsPrice / itemWorth); @@ -73,12 +80,15 @@ export class RagfairTaxService itemPriceMult = 4 ** itemPriceMult; requirementPriceMult = 4 ** requirementPriceMult; - const hideoutFleaTaxDiscountBonus = pmcData.Bonuses.find(b => b.type === "RagfairCommission"); + const hideoutFleaTaxDiscountBonus = pmcData.Bonuses.find((b) => b.type === "RagfairCommission"); const taxDiscountPercent = hideoutFleaTaxDiscountBonus ? Math.abs(hideoutFleaTaxDiscountBonus.value) : 0; - const tax = itemWorth * itemTaxMult * itemPriceMult + requirementsPrice * requirementTaxMult * requirementPriceMult; + const tax = itemWorth * itemTaxMult * itemPriceMult + + requirementsPrice * requirementTaxMult * requirementPriceMult; const discountedTax = tax * (1.0 - taxDiscountPercent / 100.0); - const itemComissionMult = itemTemplate._props.RagFairCommissionModifier ? itemTemplate._props.RagFairCommissionModifier : 1; + const itemComissionMult = itemTemplate._props.RagFairCommissionModifier ? + itemTemplate._props.RagFairCommissionModifier : + 1; if (item.upd.Buff) { @@ -93,13 +103,19 @@ export class RagfairTaxService // This method is trying to replicate the item worth calculation method found in the client code. // Any inefficiencies or style issues are intentional and should not be fixed, to preserve the client-side code mirroring. - protected calculateItemWorth(item: Item, itemTemplate: ITemplateItem, itemCount: number, pmcData: IPmcData, isRootItem = true): number + protected calculateItemWorth( + item: Item, + itemTemplate: ITemplateItem, + itemCount: number, + pmcData: IPmcData, + isRootItem = true, + ): number { let worth = this.ragfairPriceService.getFleaPriceForItem(item._tpl); // In client, all item slots are traversed and any items contained within have their values added - if (isRootItem) // Since we get a flat list of all child items, we only want to recurse from parent item - { + if (isRootItem) + { // Since we get a flat list of all child items, we only want to recurse from parent item const itemChildren = this.itemHelper.findAndReturnChildrenAsItems(pmcData.Inventory.items, item._id); if (itemChildren.length > 1) { @@ -110,7 +126,13 @@ export class RagfairTaxService continue; } - worth += this.calculateItemWorth(child, this.itemHelper.getItem(child._tpl)[1], child.upd.StackObjectsCount, pmcData, false); + worth += this.calculateItemWorth( + child, + this.itemHelper.getItem(child._tpl)[1], + child.upd.StackObjectsCount, + pmcData, + false, + ); } } } @@ -122,7 +144,8 @@ export class RagfairTaxService if ("Key" in item.upd && itemTemplate._props.MaximumNumberOfUsage > 0) { - worth = worth / itemTemplate._props.MaximumNumberOfUsage * (itemTemplate._props.MaximumNumberOfUsage - item.upd.Key.NumberOfUsages); + worth = worth / itemTemplate._props.MaximumNumberOfUsage * + (itemTemplate._props.MaximumNumberOfUsage - item.upd.Key.NumberOfUsages); } if ("Resource" in item.upd && itemTemplate._props.MaxResource > 0) @@ -148,9 +171,13 @@ export class RagfairTaxService if ("Repairable" in item.upd && itemTemplate._props.armorClass > 0) { const num2 = 0.01 * (0.0 ** item.upd.Repairable.MaxDurability); - worth = worth * ((item.upd.Repairable.MaxDurability / itemTemplate._props.Durability) - num2) - Math.floor(itemTemplate._props.RepairCost * (item.upd.Repairable.MaxDurability - item.upd.Repairable.Durability)); + worth = worth * ((item.upd.Repairable.MaxDurability / itemTemplate._props.Durability) - num2) - + Math.floor( + itemTemplate._props.RepairCost * + (item.upd.Repairable.MaxDurability - item.upd.Repairable.Durability), + ); } return worth * itemCount; } -} \ No newline at end of file +} diff --git a/project/src/services/RepairService.ts b/project/src/services/RepairService.ts index 918503ea..a2cdaa91 100644 --- a/project/src/services/RepairService.ts +++ b/project/src/services/RepairService.ts @@ -39,7 +39,7 @@ export class RepairService @inject("PaymentService") protected paymentService: PaymentService, @inject("RepairHelper") protected repairHelper: RepairHelper, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.repairConfig = this.configServer.getConfig(ConfigTypes.REPAIR); @@ -53,9 +53,14 @@ export class RepairService * @param traderId Trader being used to repair item * @returns RepairDetails object */ - public repairItemByTrader(sessionID: string, pmcData: IPmcData, repairItemDetails: RepairItem, traderId: string): RepairDetails + public repairItemByTrader( + sessionID: string, + pmcData: IPmcData, + repairItemDetails: RepairItem, + traderId: string, + ): RepairDetails { - const itemToRepair = pmcData.Inventory.items.find(x => x._id === repairItemDetails._id); + const itemToRepair = pmcData.Inventory.items.find((x) => x._id === repairItemDetails._id); if (itemToRepair === undefined) { throw new Error(`Item ${repairItemDetails._id} not found in profile inventory, unable to repair`); @@ -64,12 +69,12 @@ export class RepairService const priceCoef = this.traderHelper.getLoyaltyLevel(traderId, pmcData).repair_price_coef; const traderRepairDetails = this.traderHelper.getTrader(traderId, sessionID).repair; const repairQualityMultiplier = traderRepairDetails.quality; - const repairRate = (priceCoef <= 0) - ? 1 - : (priceCoef / 100 + 1); + const repairRate = (priceCoef <= 0) ? + 1 : + (priceCoef / 100 + 1); const itemToRepairDetails = this.databaseServer.getTables().templates.items[itemToRepair._tpl]; - const repairItemIsArmor = (!!itemToRepairDetails._props.ArmorMaterial); + const repairItemIsArmor = !!itemToRepairDetails._props.ArmorMaterial; this.repairHelper.updateItemDurability( itemToRepair, @@ -78,12 +83,14 @@ export class RepairService repairItemDetails.count, false, repairQualityMultiplier, - repairQualityMultiplier !== 0 && this.repairConfig.applyRandomizeDurabilityLoss + repairQualityMultiplier !== 0 && this.repairConfig.applyRandomizeDurabilityLoss, ); // get repair price const itemRepairCost = this.databaseServer.getTables().templates.items[itemToRepair._tpl]._props.RepairCost; - const repairCost = Math.round((itemRepairCost * repairItemDetails.count * repairRate) * this.repairConfig.priceMultiplier); + const repairCost = Math.round( + (itemRepairCost * repairItemDetails.count * repairRate) * this.repairConfig.priceMultiplier, + ); this.logger.debug(`item base repair cost: ${itemRepairCost}`, true); this.logger.debug(`price multipler: ${this.repairConfig.priceMultiplier}`, true); @@ -94,18 +101,17 @@ export class RepairService repairedItem: itemToRepair, repairedItemIsArmor: repairItemIsArmor, repairAmount: repairItemDetails.count, - repairedByKit: false + repairedByKit: false, }; } /** - * * @param sessionID Session id * @param pmcData profile to take money from * @param repairedItemId Repaired item id * @param repairCost Cost to repair item in roubles * @param traderId Id of the trader who repaired the item / who is paid - * @param output + * @param output */ public payForRepair( sessionID: string, @@ -113,15 +119,16 @@ export class RepairService repairedItemId: string, repairCost: number, traderId: string, - output: IItemEventRouterResponse): void + output: IItemEventRouterResponse, + ): void { const options: IProcessBuyTradeRequestData = { // eslint-disable-next-line @typescript-eslint/naming-convention scheme_items: [ { id: repairedItemId, - count: Math.round(repairCost) - } + count: Math.round(repairCost), + }, ], tid: traderId, Action: "", @@ -130,7 +137,7 @@ export class RepairService item_id: "", count: 0, // eslint-disable-next-line @typescript-eslint/naming-convention - scheme_id: 0 + scheme_id: 0, }; this.paymentService.payMoney(pmcData, options, sessionID, output); @@ -145,9 +152,13 @@ export class RepairService public addRepairSkillPoints( sessionId: string, repairDetails: RepairDetails, - pmcData: IPmcData): void + pmcData: IPmcData, + ): void { - if (repairDetails.repairedByKit && this.itemHelper.isOfBaseclass(repairDetails.repairedItem._tpl, BaseClasses.WEAPON)) + if ( + repairDetails.repairedByKit && + this.itemHelper.isOfBaseclass(repairDetails.repairedItem._tpl, BaseClasses.WEAPON) + ) { const skillPoints = this.getWeaponRepairSkillPoints(repairDetails); @@ -155,22 +166,31 @@ export class RepairService } // Handle kit repairs of armor - if (repairDetails.repairedByKit && this.itemHelper.isOfBaseclasses(repairDetails.repairedItem._tpl, [BaseClasses.ARMOR, BaseClasses.VEST])) + if ( + repairDetails.repairedByKit && + this.itemHelper.isOfBaseclasses(repairDetails.repairedItem._tpl, [BaseClasses.ARMOR, BaseClasses.VEST]) + ) { const itemDetails = this.itemHelper.getItem(repairDetails.repairedItem._tpl); if (!itemDetails[0]) { // No item found - this.logger.error(this.localisationService.getText("repair-unable_to_find_item_in_db", repairDetails.repairedItem._tpl)); + this.logger.error( + this.localisationService.getText( + "repair-unable_to_find_item_in_db", + repairDetails.repairedItem._tpl, + ), + ); return; } const isHeavyArmor = itemDetails[1]._props.ArmorType === "Heavy"; - const vestSkillToLevel = (isHeavyArmor) - ? SkillTypes.HEAVY_VESTS - : SkillTypes.LIGHT_VESTS; - const pointsToAddToVestSkill = repairDetails.repairPoints * this.repairConfig.armorKitSkillPointGainPerRepairPointMultiplier; + const vestSkillToLevel = isHeavyArmor ? + SkillTypes.HEAVY_VESTS : + SkillTypes.LIGHT_VESTS; + const pointsToAddToVestSkill = repairDetails.repairPoints * + this.repairConfig.armorKitSkillPointGainPerRepairPointMultiplier; this.profileHelper.addSkillPointsToPlayer(pmcData, vestSkillToLevel, pointsToAddToVestSkill); } @@ -179,17 +199,24 @@ export class RepairService let intellectGainedFromRepair: number; if (repairDetails.repairedByKit) { - const intRepairMultiplier = (this.itemHelper.isOfBaseclass(repairDetails.repairedItem._tpl, BaseClasses.WEAPON)) - ? this.repairConfig.repairKitIntellectGainMultiplier.weapon - : this.repairConfig.repairKitIntellectGainMultiplier.armor; + const intRepairMultiplier = + (this.itemHelper.isOfBaseclass(repairDetails.repairedItem._tpl, BaseClasses.WEAPON)) ? + this.repairConfig.repairKitIntellectGainMultiplier.weapon : + this.repairConfig.repairKitIntellectGainMultiplier.armor; // limit gain to a max value defined in config.maxIntellectGainPerRepair - intellectGainedFromRepair = Math.min(repairDetails.repairPoints * intRepairMultiplier, this.repairConfig.maxIntellectGainPerRepair.kit); + intellectGainedFromRepair = Math.min( + repairDetails.repairPoints * intRepairMultiplier, + this.repairConfig.maxIntellectGainPerRepair.kit, + ); } else { // Trader repair - Not as accurate as kit, needs data from live - intellectGainedFromRepair = Math.min(repairDetails.repairAmount / 10, this.repairConfig.maxIntellectGainPerRepair.trader); + intellectGainedFromRepair = Math.min( + repairDetails.repairAmount / 10, + this.repairConfig.maxIntellectGainPerRepair.trader, + ); } this.profileHelper.addSkillPointsToPlayer(pmcData, SkillTypes.INTELLECT, intellectGainedFromRepair); @@ -201,7 +228,8 @@ export class RepairService * @returns the number of skill points to reward the user */ protected getWeaponRepairSkillPoints( - repairDetails: RepairDetails): number + repairDetails: RepairDetails, + ): number { // This formula and associated configs is calculated based on 30 repairs done on live // The points always came out 2-aligned, which is why there's a divide/multiply by 2 with ceil calls @@ -228,12 +256,11 @@ export class RepairService { skillPoints += this.repairConfig.weaponTreatment.critSuccessAmount; } - + return skillPoints; } - + /** - * * @param sessionId Session id * @param pmcData Profile to update repaired item in * @param repairKits Array of Repair kits to use @@ -246,10 +273,11 @@ export class RepairService pmcData: IPmcData, repairKits: RepairKitsInfo[], itemToRepairId: string, - output: IItemEventRouterResponse): RepairDetails + output: IItemEventRouterResponse, + ): RepairDetails { // Find item to repair in inventory - const itemToRepair = pmcData.Inventory.items.find((x: { _id: string; }) => x._id === itemToRepairId); + const itemToRepair = pmcData.Inventory.items.find((x: {_id: string;}) => x._id === itemToRepairId); if (itemToRepair === undefined) { throw new Error(`Item ${itemToRepairId} not found, unable to repair`); @@ -257,9 +285,12 @@ export class RepairService const itemsDb = this.databaseServer.getTables().templates.items; const itemToRepairDetails = itemsDb[itemToRepair._tpl]; - const repairItemIsArmor = (!!itemToRepairDetails._props.ArmorMaterial); + const repairItemIsArmor = !!itemToRepairDetails._props.ArmorMaterial; const repairAmount = repairKits[0].count / this.getKitDivisor(itemToRepairDetails, repairItemIsArmor, pmcData); - const shouldApplyDurabilityLoss = this.shouldRepairKitApplyDurabilityLoss(pmcData, this.repairConfig.applyRandomizeDurabilityLoss); + const shouldApplyDurabilityLoss = this.shouldRepairKitApplyDurabilityLoss( + pmcData, + this.repairConfig.applyRandomizeDurabilityLoss, + ); this.repairHelper.updateItemDurability( itemToRepair, @@ -268,12 +299,13 @@ export class RepairService repairAmount, true, 1, - shouldApplyDurabilityLoss); + shouldApplyDurabilityLoss, + ); // Find and use repair kit defined in body for (const repairKit of repairKits) { - const repairKitInInventory = pmcData.Inventory.items.find(x => x._id === repairKit._id); + const repairKitInInventory = pmcData.Inventory.items.find((x) => x._id === repairKit._id); const repairKitDetails = itemsDb[repairKitInInventory._tpl]; const repairKitReductionAmount = repairKit.count; @@ -290,7 +322,7 @@ export class RepairService repairedItem: itemToRepair, repairedItemIsArmor: repairItemIsArmor, repairAmount: repairAmount, - repairedByKit: true + repairedByKit: true, }; } @@ -301,33 +333,34 @@ export class RepairService * @param pmcData Player profile * @returns Number to divide kit points by */ - protected getKitDivisor(itemToRepairDetails: ITemplateItem, isArmor: boolean, pmcData: IPmcData): number + protected getKitDivisor(itemToRepairDetails: ITemplateItem, isArmor: boolean, pmcData: IPmcData): number { const globals = this.databaseServer.getTables().globals; const globalRepairSettings = globals.config.RepairSettings; const intellectRepairPointsPerLevel = globals.config.SkillsSettings.Intellect.RepairPointsCostReduction; - const profileIntellectLevel = this.profileHelper.getSkillFromProfile(pmcData, SkillTypes.INTELLECT)?.Progress ?? 0; + const profileIntellectLevel = this.profileHelper.getSkillFromProfile(pmcData, SkillTypes.INTELLECT)?.Progress ?? + 0; const intellectPointReduction = intellectRepairPointsPerLevel * Math.trunc(profileIntellectLevel / 100); if (isArmor) { const durabilityPointCostArmor = globalRepairSettings.durabilityPointCostArmor; const repairArmorBonus = this.getBonusMultiplierValue("RepairArmorBonus", pmcData); - const armorBonus = (1.0 - (repairArmorBonus - 1.0) - intellectPointReduction); + const armorBonus = 1.0 - (repairArmorBonus - 1.0) - intellectPointReduction; const materialType = itemToRepairDetails._props.ArmorMaterial ?? ""; const armorMaterial = globals.config.ArmorMaterials[materialType] as IArmorType; - const destructability = (1 + armorMaterial.Destructibility); + const destructability = 1 + armorMaterial.Destructibility; const armorClass = parseInt(`${itemToRepairDetails._props.armorClass}`); const armorClassDivisor = globals.config.RepairSettings.armorClassDivisor; - const armorClassMultiplier = (1.0 + armorClass / armorClassDivisor); + const armorClassMultiplier = 1.0 + armorClass / armorClassDivisor; return durabilityPointCostArmor * armorBonus * destructability * armorClassMultiplier; } - else + else { const repairWeaponBonus = this.getBonusMultiplierValue("RepairWeaponBonus", pmcData) - 1; - const repairPointMultiplier = (1.0 - repairWeaponBonus - intellectPointReduction); + const repairPointMultiplier = 1.0 - repairWeaponBonus - intellectPointReduction; const durabilityPointCostGuns = globals.config.RepairSettings.durabilityPointCostGuns; return durabilityPointCostGuns * repairPointMultiplier; @@ -342,11 +375,11 @@ export class RepairService */ protected getBonusMultiplierValue(skillBonusName: string, pmcData: IPmcData): number { - const bonusesMatched = pmcData?.Bonuses?.filter(b => b.type === skillBonusName); + const bonusesMatched = pmcData?.Bonuses?.filter((b) => b.type === skillBonusName); let value = 1; if (bonusesMatched != null) { - const sumedPercentage = bonusesMatched.map(b => b.value).reduce((v1,v2) => v1 + v2, 0); + const sumedPercentage = bonusesMatched.map((b) => b.value).reduce((v1, v2) => v1 + v2, 0); value = 1 + sumedPercentage / 100; } @@ -389,14 +422,14 @@ export class RepairService this.logger.debug(`Repair kit: ${repairKitInInventory._id} in inventory lacks upd object, adding`); repairKitInInventory.upd = { RepairKit: { - Resource: maxRepairAmount - } + Resource: maxRepairAmount, + }, }; } if (!repairKitInInventory.upd.RepairKit?.Resource) { repairKitInInventory.upd.RepairKit = { - Resource: maxRepairAmount + Resource: maxRepairAmount, }; } } @@ -432,7 +465,7 @@ export class RepairService /** * Add random buff to item - * @param itemConfig weapon/armor config + * @param itemConfig weapon/armor config * @param repairDetails Details for item to repair */ public addBuff(itemConfig: BonusSettings, item: Item): void @@ -450,7 +483,10 @@ export class RepairService rarity: bonusRarity, buffType: bonusType, value: bonusValue, - thresholdDurability: this.randomUtil.getPercentOfValue(bonusThresholdPercent, item.upd.Repairable.Durability) + thresholdDurability: this.randomUtil.getPercentOfValue( + bonusThresholdPercent, + item.upd.Repairable.Durability, + ), }; } @@ -467,7 +503,9 @@ export class RepairService const hasTemplate = this.itemHelper.getItem(repairDetails.repairedItem._tpl); if (!hasTemplate[0]) + { return false; + } const template = hasTemplate[1]; const itemSkillType = this.getItemSkillType(template); @@ -476,14 +514,22 @@ export class RepairService return false; } - const commonBuffMinChanceValue = globals.config.SkillsSettings[itemSkillType as string].BuffSettings.CommonBuffMinChanceValue; - const commonBuffChanceLevelBonus = globals.config.SkillsSettings[itemSkillType as string].BuffSettings.CommonBuffChanceLevelBonus; - const receivedDurabilityMaxPercent = globals.config.SkillsSettings[itemSkillType as string].BuffSettings.ReceivedDurabilityMaxPercent; + const commonBuffMinChanceValue = + globals.config.SkillsSettings[itemSkillType as string].BuffSettings.CommonBuffMinChanceValue; + const commonBuffChanceLevelBonus = + globals.config.SkillsSettings[itemSkillType as string].BuffSettings.CommonBuffChanceLevelBonus; + const receivedDurabilityMaxPercent = + globals.config.SkillsSettings[itemSkillType as string].BuffSettings.ReceivedDurabilityMaxPercent; - const skillLevel = Math.trunc((this.profileHelper.getSkillFromProfile(pmcData, itemSkillType)?.Progress ?? 0) / 100); + const skillLevel = Math.trunc( + (this.profileHelper.getSkillFromProfile(pmcData, itemSkillType)?.Progress ?? 0) / 100, + ); const durabilityToRestorePercent = repairDetails.repairPoints / template._props.MaxDurability; - const durabilityMultiplier = this.getDurabilityMultiplier(receivedDurabilityMaxPercent, durabilityToRestorePercent); + const durabilityMultiplier = this.getDurabilityMultiplier( + receivedDurabilityMaxPercent, + durabilityToRestorePercent, + ); const doBuff = commonBuffMinChanceValue + commonBuffChanceLevelBonus * skillLevel * durabilityMultiplier; @@ -494,13 +540,13 @@ export class RepairService return false; } - + /** * Based on item, what underlying skill does this item use for buff settings * @param itemTemplate Item to check for skill * @returns Skill name */ - protected getItemSkillType(itemTemplate: ITemplateItem): SkillTypes + protected getItemSkillType(itemTemplate: ITemplateItem): SkillTypes { if (this.itemHelper.isOfBaseclass(itemTemplate._id, BaseClasses.ARMOR)) { @@ -533,7 +579,7 @@ export class RepairService */ protected getDurabilityMultiplier(receiveDurabilityMaxPercent: number, receiveDurabilityPercent: number): number { - receiveDurabilityMaxPercent = ((receiveDurabilityMaxPercent > 0) ? receiveDurabilityMaxPercent : 0.01); + receiveDurabilityMaxPercent = (receiveDurabilityMaxPercent > 0) ? receiveDurabilityMaxPercent : 0.01; const num = receiveDurabilityPercent / receiveDurabilityMaxPercent; if (num > 1) { @@ -556,4 +602,4 @@ export class RepairDetails repairedItemIsArmor: boolean; repairAmount: number; repairedByKit: boolean; -} \ No newline at end of file +} diff --git a/project/src/services/SeasonalEventService.ts b/project/src/services/SeasonalEventService.ts index 1f8387e2..51d2a73d 100644 --- a/project/src/services/SeasonalEventService.ts +++ b/project/src/services/SeasonalEventService.ts @@ -36,7 +36,7 @@ export class SeasonalEventService @inject("LocalisationService") protected localisationService: LocalisationService, @inject("BotHelper") protected botHelper: BotHelper, @inject("ProfileHelper") protected profileHelper: ProfileHelper, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.seasonalEventConfig = this.configServer.getConfig(ConfigTypes.SEASONAL_EVENT); @@ -54,7 +54,7 @@ export class SeasonalEventService "5df8a77486f77412672a1e3f", // Violet bauble "5df8a72c86f77412640e2e83", // Silver bauble "5a43943586f77416ad2f06e2", // Ded moroz hat - "5a43957686f7742a2c2f11b0" // Santa hat + "5a43957686f7742a2c2f11b0", // Santa hat ]; } @@ -71,7 +71,7 @@ export class SeasonalEventService "6176a40f0b8c0312ac75a3d3", // Ghoul mask "62a5c2c98ec41a51b34739c0", // Hockey player mask "Captain" "62a5c333ec21e50cad3b5dc6", // Hockey player mask "Brawler" - "62a5c41e8ec41a51b34739c3" // Hockey player mask "Quiet" + "62a5c41e8ec41a51b34739c3", // Hockey player mask "Quiet" ]; } @@ -106,7 +106,7 @@ export class SeasonalEventService /** * Check if item id exists in christmas or halloween event arrays * @param itemTpl item tpl to check for - * @returns + * @returns */ public itemIsSeasonalRelated(itemTpl: string): boolean { @@ -236,11 +236,13 @@ export class SeasonalEventService const eventEndDate = new Date(currentDate.getFullYear(), event.endMonth - 1, event.endDay); // Current date is between start/end dates - if (currentDate >= eventStartDate - && currentDate <= eventEndDate) + if ( + currentDate >= eventStartDate && + currentDate <= eventEndDate + ) { - this.christmasEventActive = (SeasonalEventType[event.type] === SeasonalEventType.CHRISTMAS); - this.halloweenEventActive = (SeasonalEventType[event.type] === SeasonalEventType.HALLOWEEN); + this.christmasEventActive = SeasonalEventType[event.type] === SeasonalEventType.CHRISTMAS; + this.halloweenEventActive = SeasonalEventType[event.type] === SeasonalEventType.HALLOWEEN; } } } @@ -261,12 +263,18 @@ export class SeasonalEventService { if (!botInventory.equipment[equipmentSlotKey]) { - this.logger.warning(this.localisationService.getText("seasonal-missing_equipment_slot_on_bot", {equipmentSlot: equipmentSlotKey, botRole: botRole})); + this.logger.warning( + this.localisationService.getText("seasonal-missing_equipment_slot_on_bot", { + equipmentSlot: equipmentSlotKey, + botRole: botRole, + }), + ); } const equipment: Record = botInventory.equipment[equipmentSlotKey]; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - botInventory.equipment[equipmentSlotKey] = Object.fromEntries(Object.entries(equipment).filter(([index]) => !christmasItems.includes(index))); + botInventory.equipment[equipmentSlotKey] = Object.fromEntries( + Object.entries(equipment).filter(([index]) => !christmasItems.includes(index)), + ); } // Remove christmas related loot from loot containers @@ -274,10 +282,17 @@ export class SeasonalEventService { if (!botInventory.items[lootContainerKey]) { - this.logger.warning(this.localisationService.getText("seasonal-missing_loot_container_slot_on_bot", {lootContainer: lootContainerKey, botRole: botRole})); + this.logger.warning( + this.localisationService.getText("seasonal-missing_loot_container_slot_on_bot", { + lootContainer: lootContainerKey, + botRole: botRole, + }), + ); } - botInventory.items[lootContainerKey] = botInventory.items[lootContainerKey].filter((x: string) => !christmasItems.includes(x)); + botInventory.items[lootContainerKey] = botInventory.items[lootContainerKey].filter((x: string) => + !christmasItems.includes(x) + ); } } @@ -292,7 +307,7 @@ export class SeasonalEventService switch (eventType.toLowerCase()) { case SeasonalEventType.HALLOWEEN.toLowerCase(): - globalConfig.EventType = globalConfig.EventType.filter(x => x !== "None"); + globalConfig.EventType = globalConfig.EventType.filter((x) => x !== "None"); globalConfig.EventType.push("Halloween"); globalConfig.EventType.push("HalloweenIllumination"); globalConfig.Health.ProfileHealthSettings.DefaultStimulatorBuff = "Buffs_Halloween"; @@ -304,7 +319,7 @@ export class SeasonalEventService this.adjustTraderIcons(eventType); break; case SeasonalEventType.CHRISTMAS.toLowerCase(): - globalConfig.EventType = globalConfig.EventType.filter(x => x !== "None"); + globalConfig.EventType = globalConfig.EventType.filter((x) => x !== "None"); globalConfig.EventType.push("Christmas"); this.addEventGearToBots(eventType); this.addGifterBotToMaps(); @@ -352,10 +367,10 @@ export class SeasonalEventService } for (const boss of bossesToAdd) { - const mapBosses: BossLocationSpawn[] = this.databaseServer.getTables().locations[mapKey].base.BossLocationSpawn; - if (!mapBosses.find(x => x.BossName === boss.BossName)) + const mapBosses: BossLocationSpawn[] = + this.databaseServer.getTables().locations[mapKey].base.BossLocationSpawn; + if (!mapBosses.find((x) => x.BossName === boss.BossName)) { - this.databaseServer.getTables().locations[mapKey].base.BossLocationSpawn.push(...bossesToAdd); } } @@ -371,21 +386,31 @@ export class SeasonalEventService switch (eventType.toLowerCase()) { case SeasonalEventType.HALLOWEEN.toLowerCase(): - this.httpConfig.serverImagePathOverride["./assets/images/traders/5a7c2ebb86f7746e324a06ab.png"] = "./assets/images/traders/halloween/5a7c2ebb86f7746e324a06ab.png"; - this.httpConfig.serverImagePathOverride["./assets/images/traders/5ac3b86a86f77461491d1ad8.png"] = "./assets/images/traders/halloween/5ac3b86a86f77461491d1ad8.png"; - this.httpConfig.serverImagePathOverride["./assets/images/traders/5c06531a86f7746319710e1b.png"] = "./assets/images/traders/halloween/5c06531a86f7746319710e1b.png"; - this.httpConfig.serverImagePathOverride["./assets/images/traders/59b91ca086f77469a81232e4.png"] = "./assets/images/traders/halloween/59b91ca086f77469a81232e4.png"; - this.httpConfig.serverImagePathOverride["./assets/images/traders/59b91cab86f77469aa5343ca.png"] = "./assets/images/traders/halloween/59b91cab86f77469aa5343ca.png"; - this.httpConfig.serverImagePathOverride["./assets/images/traders/59b91cb486f77469a81232e5.png"] = "./assets/images/traders/halloween/59b91cb486f77469a81232e5.png"; - this.httpConfig.serverImagePathOverride["./assets/images/traders/59b91cbd86f77469aa5343cb.png"] = "./assets/images/traders/halloween/59b91cbd86f77469aa5343cb.png"; - this.httpConfig.serverImagePathOverride["./assets/images/traders/579dc571d53a0658a154fbec.png"] = "./assets/images/traders/halloween/579dc571d53a0658a154fbec.png"; - break; + this.httpConfig.serverImagePathOverride["./assets/images/traders/5a7c2ebb86f7746e324a06ab.png"] = + "./assets/images/traders/halloween/5a7c2ebb86f7746e324a06ab.png"; + this.httpConfig.serverImagePathOverride["./assets/images/traders/5ac3b86a86f77461491d1ad8.png"] = + "./assets/images/traders/halloween/5ac3b86a86f77461491d1ad8.png"; + this.httpConfig.serverImagePathOverride["./assets/images/traders/5c06531a86f7746319710e1b.png"] = + "./assets/images/traders/halloween/5c06531a86f7746319710e1b.png"; + this.httpConfig.serverImagePathOverride["./assets/images/traders/59b91ca086f77469a81232e4.png"] = + "./assets/images/traders/halloween/59b91ca086f77469a81232e4.png"; + this.httpConfig.serverImagePathOverride["./assets/images/traders/59b91cab86f77469aa5343ca.png"] = + "./assets/images/traders/halloween/59b91cab86f77469aa5343ca.png"; + this.httpConfig.serverImagePathOverride["./assets/images/traders/59b91cb486f77469a81232e5.png"] = + "./assets/images/traders/halloween/59b91cb486f77469a81232e5.png"; + this.httpConfig.serverImagePathOverride["./assets/images/traders/59b91cbd86f77469aa5343cb.png"] = + "./assets/images/traders/halloween/59b91cbd86f77469aa5343cb.png"; + this.httpConfig.serverImagePathOverride["./assets/images/traders/579dc571d53a0658a154fbec.png"] = + "./assets/images/traders/halloween/579dc571d53a0658a154fbec.png"; + break; case SeasonalEventType.CHRISTMAS.toLowerCase(): // TODO: find christmas trader icons break; } - this.databaseImporter.loadImages(`${this.databaseImporter.getSptDataPath()}images/`, ["traders"], ["/files/trader/avatar/"]); + this.databaseImporter.loadImages(`${this.databaseImporter.getSptDataPath()}images/`, ["traders"], [ + "/files/trader/avatar/", + ]); } /** @@ -413,7 +438,7 @@ export class SeasonalEventService return; } - + // Iterate over bots with changes to apply for (const bot in botGearChanges) { @@ -429,7 +454,10 @@ export class SeasonalEventService for (const equipmentSlot in gearAmendments) { // Adjust slots spawn chance to be at least 75% - botToUpdate.chances.equipment[equipmentSlot] = Math.max(botToUpdate.chances.equipment[equipmentSlot], 75); + botToUpdate.chances.equipment[equipmentSlot] = Math.max( + botToUpdate.chances.equipment[equipmentSlot], + 75, + ); // Grab gear to add and loop over it const itemsToAdd = gearAmendments[equipmentSlot]; @@ -496,7 +524,7 @@ export class SeasonalEventService TriggerId: "", TriggerName: "", Delay: 0, - RandomTimeSpawn: false + RandomTimeSpawn: false, }); } } @@ -512,7 +540,6 @@ export class SeasonalEventService { this.giftService.sendGiftToPlayer(playerId, giftkey); } - } /** @@ -524,4 +551,4 @@ export class SeasonalEventService { return this.seasonalEventConfig.eventBotMapping[eventBotRole]; } -} \ No newline at end of file +} diff --git a/project/src/services/TraderAssortService.ts b/project/src/services/TraderAssortService.ts index 5a826c12..77e6cd0b 100644 --- a/project/src/services/TraderAssortService.ts +++ b/project/src/services/TraderAssortService.ts @@ -1,6 +1,6 @@ import { ITraderAssort } from "@spt-aki/models/eft/common/tables/ITrader"; -export class TraderAssortService +export class TraderAssortService { protected pristineTraderAssorts: Record = {}; @@ -18,4 +18,4 @@ export class TraderAssortService { this.pristineTraderAssorts[traderId] = assort; } -} \ No newline at end of file +} diff --git a/project/src/services/TraderPurchasePersisterService.ts b/project/src/services/TraderPurchasePersisterService.ts index b050ce51..ff0deee9 100644 --- a/project/src/services/TraderPurchasePersisterService.ts +++ b/project/src/services/TraderPurchasePersisterService.ts @@ -22,7 +22,7 @@ export class TraderPurchasePersisterService @inject("TimeUtil") protected timeUtil: TimeUtil, @inject("ProfileHelper") protected profileHelper: ProfileHelper, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.traderConfig = this.configServer.getConfig(ConfigTypes.TRADER); @@ -95,23 +95,30 @@ export class TraderPurchasePersisterService for (const purchaseKey in profile.traderPurchases[traderId]) { - const traderUpdateDetails = this.traderConfig.updateTime.find(x => x.traderId === traderId); + const traderUpdateDetails = this.traderConfig.updateTime.find((x) => x.traderId === traderId); if (!traderUpdateDetails) { - this.logger.error(this.localisationService.getText("trader-unable_to_delete_stale_purchases", {profileId: profile.info.id, traderId: traderId})); + this.logger.error( + this.localisationService.getText("trader-unable_to_delete_stale_purchases", { + profileId: profile.info.id, + traderId: traderId, + }), + ); continue; } const purchaseDetails = profile.traderPurchases[traderId][purchaseKey]; const resetTimeForItem = purchaseDetails.purchaseTimestamp + traderUpdateDetails.seconds; - if ((resetTimeForItem) < this.timeUtil.getTimestamp()) + if (resetTimeForItem < this.timeUtil.getTimestamp()) { // Item was purchased far enough in past a trader refresh would have occured, remove purchase record from profile - this.logger.debug(`Removed trader: ${traderId} purchase: ${purchaseKey} from profile: ${profile.info.id}`); + this.logger.debug( + `Removed trader: ${traderId} purchase: ${purchaseKey} from profile: ${profile.info.id}`, + ); delete profile.traderPurchases[traderId][purchaseKey]; } } } } -} \ No newline at end of file +} diff --git a/project/src/services/mod/CustomItemService.ts b/project/src/services/mod/CustomItemService.ts index ae25d6a1..80b3b8ff 100644 --- a/project/src/services/mod/CustomItemService.ts +++ b/project/src/services/mod/CustomItemService.ts @@ -1,7 +1,12 @@ import { inject, injectable } from "tsyringe"; import { ITemplateItem, Props } from "@spt-aki/models/eft/common/tables/ITemplateItem"; -import { CreateItemResult, LocaleDetails, NewItemDetails, NewItemFromCloneDetails } from "@spt-aki/models/spt/mod/NewItemDetails"; +import { + CreateItemResult, + LocaleDetails, + NewItemDetails, + NewItemFromCloneDetails, +} from "@spt-aki/models/spt/mod/NewItemDetails"; import { IDatabaseTables } from "@spt-aki/models/spt/server/IDatabaseTables"; import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; @@ -17,7 +22,7 @@ export class CustomItemService @inject("WinstonLogger") protected logger: ILogger, @inject("HashUtil") protected hashUtil: HashUtil, @inject("JsonUtil") protected jsonUtil: JsonUtil, - @inject("DatabaseServer") protected databaseServer: DatabaseServer + @inject("DatabaseServer") protected databaseServer: DatabaseServer, ) { this.tables = this.databaseServer.getTables(); @@ -115,9 +120,9 @@ export class CustomItemService */ protected getOrGenerateIdForItem(newId: string): string { - return (newId === "") - ? this.hashUtil.generate() - : newId; + return (newId === "") ? + this.hashUtil.generate() : + newId; } /** @@ -156,8 +161,8 @@ export class CustomItemService { Id: newItemId, ParentId: parentId, - Price: priceRoubles - } + Price: priceRoubles, + }, ); } @@ -167,7 +172,7 @@ export class CustomItemService * e.g. * en[0] * fr[1] - * + * * No jp provided, so english will be used as a substitute * @param localeDetails key is language, value are the new locale details * @param newItemId id of the item being created @@ -200,4 +205,4 @@ export class CustomItemService { this.tables.templates.prices[newItemId] = fleaPriceRoubles; } -} \ No newline at end of file +} diff --git a/project/src/services/mod/dynamicRouter/DynamicRouterMod.ts b/project/src/services/mod/dynamicRouter/DynamicRouterMod.ts index 075a19db..f2b1054c 100644 --- a/project/src/services/mod/dynamicRouter/DynamicRouterMod.ts +++ b/project/src/services/mod/dynamicRouter/DynamicRouterMod.ts @@ -4,14 +4,14 @@ export class DynamicRouterMod extends DynamicRouter { public constructor( routes: RouteAction[], - private topLevelRoute: string - ) + private topLevelRoute: string, + ) { super(routes); } - public override getTopLevelRoute(): string + public override getTopLevelRoute(): string { return this.topLevelRoute; } -} \ No newline at end of file +} diff --git a/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts b/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts index 92dc69ec..3992f0c1 100644 --- a/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts +++ b/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts @@ -4,17 +4,17 @@ import { RouteAction } from "@spt-aki/di/Router"; import { DynamicRouterMod } from "@spt-aki/services/mod/dynamicRouter/DynamicRouterMod"; @injectable() -export class DynamicRouterModService +export class DynamicRouterModService { - constructor(private container: DependencyContainer) + constructor(private container: DependencyContainer) {} public registerDynamicRouter( name: string, routes: RouteAction[], - topLevelRoute: string - ): void + topLevelRoute: string, + ): void { this.container.register(name, {useValue: new DynamicRouterMod(routes, topLevelRoute)}); this.container.registerType("DynamicRoutes", name); } -} \ No newline at end of file +} diff --git a/project/src/services/mod/httpListener/HttpListenerMod.ts b/project/src/services/mod/httpListener/HttpListenerMod.ts index d0fcf049..760cc14a 100644 --- a/project/src/services/mod/httpListener/HttpListenerMod.ts +++ b/project/src/services/mod/httpListener/HttpListenerMod.ts @@ -6,18 +6,18 @@ export class HttpListenerMod implements IHttpListener { public constructor( private canHandleOverride: (sessionId: string, req: IncomingMessage) => boolean, - private handleOverride: (sessionId: string, req: IncomingMessage, resp: ServerResponse) => void - ) + private handleOverride: (sessionId: string, req: IncomingMessage, resp: ServerResponse) => void, + ) { } - public canHandle(sessionId: string, req: IncomingMessage): boolean + public canHandle(sessionId: string, req: IncomingMessage): boolean { return this.canHandleOverride(sessionId, req); } - public handle(sessionId: string, req: IncomingMessage, resp: ServerResponse): void + public handle(sessionId: string, req: IncomingMessage, resp: ServerResponse): void { this.handleOverride(sessionId, req, resp); } -} \ No newline at end of file +} diff --git a/project/src/services/mod/httpListener/HttpListenerModService.ts b/project/src/services/mod/httpListener/HttpListenerModService.ts index e862ff5b..40fbcd49 100644 --- a/project/src/services/mod/httpListener/HttpListenerModService.ts +++ b/project/src/services/mod/httpListener/HttpListenerModService.ts @@ -5,18 +5,20 @@ import { IHttpListener } from "@spt-aki/servers/http/IHttpListener"; import { HttpListenerMod } from "@spt-aki/services/mod/httpListener/HttpListenerMod"; @injectable() -export class HttpListenerModService +export class HttpListenerModService { - constructor(protected container: DependencyContainer) + constructor(protected container: DependencyContainer) {} - + public registerHttpListener( name: string, canHandleOverride: (sessionId: string, req: IncomingMessage) => boolean, - handleOverride: (sessionId: string, req: IncomingMessage, resp: ServerResponse) => void - ): void + handleOverride: (sessionId: string, req: IncomingMessage, resp: ServerResponse) => void, + ): void { - this.container.register(name, {useValue: new HttpListenerMod(canHandleOverride, handleOverride)}); + this.container.register(name, { + useValue: new HttpListenerMod(canHandleOverride, handleOverride), + }); this.container.registerType("HttpListener", name); } -} \ No newline at end of file +} diff --git a/project/src/services/mod/image/ImageRouteService.ts b/project/src/services/mod/image/ImageRouteService.ts index d676f5c7..de1ea20b 100644 --- a/project/src/services/mod/image/ImageRouteService.ts +++ b/project/src/services/mod/image/ImageRouteService.ts @@ -16,4 +16,4 @@ export class ImageRouteService { return (this.routes[urlKey] !== undefined); } -} \ No newline at end of file +} diff --git a/project/src/services/mod/onLoad/OnLoadMod.ts b/project/src/services/mod/onLoad/OnLoadMod.ts index 24f253cc..b70b4644 100644 --- a/project/src/services/mod/onLoad/OnLoadMod.ts +++ b/project/src/services/mod/onLoad/OnLoadMod.ts @@ -4,10 +4,10 @@ export class OnLoadMod implements OnLoad { public constructor( private onLoadOverride: () => void, - private getRouteOverride: () => string - ) + private getRouteOverride: () => string, + ) { - //super(); + // super(); } public async onLoad(): Promise @@ -15,8 +15,8 @@ export class OnLoadMod implements OnLoad return this.onLoadOverride(); } - public getRoute(): string + public getRoute(): string { return this.getRouteOverride(); } -} \ No newline at end of file +} diff --git a/project/src/services/mod/onLoad/OnLoadModService.ts b/project/src/services/mod/onLoad/OnLoadModService.ts index 4ffb03bf..7ada64c6 100644 --- a/project/src/services/mod/onLoad/OnLoadModService.ts +++ b/project/src/services/mod/onLoad/OnLoadModService.ts @@ -3,18 +3,18 @@ import { DependencyContainer, injectable } from "tsyringe"; import { OnLoadMod } from "@spt-aki/services/mod/onLoad/OnLoadMod"; @injectable() -export class OnLoadModService +export class OnLoadModService { - constructor(protected container: DependencyContainer) + constructor(protected container: DependencyContainer) {} - + public registerOnLoad( name: string, onLoad: () => void, - getRoute: () => string - ): void + getRoute: () => string, + ): void { this.container.register(name, {useValue: new OnLoadMod(onLoad, getRoute)}); this.container.registerType("OnLoad", name); } -} \ No newline at end of file +} diff --git a/project/src/services/mod/onUpdate/OnUpdateMod.ts b/project/src/services/mod/onUpdate/OnUpdateMod.ts index 88def5a4..8474f5dc 100644 --- a/project/src/services/mod/onUpdate/OnUpdateMod.ts +++ b/project/src/services/mod/onUpdate/OnUpdateMod.ts @@ -3,9 +3,9 @@ import { OnUpdate } from "@spt-aki/di/OnUpdate"; export class OnUpdateMod implements OnUpdate { public constructor( - private onUpdateOverride: ( timeSinceLastRun: number ) => boolean, - private getRouteOverride: () => string - ) + private onUpdateOverride: (timeSinceLastRun: number) => boolean, + private getRouteOverride: () => string, + ) { } @@ -14,8 +14,8 @@ export class OnUpdateMod implements OnUpdate return this.onUpdateOverride(timeSinceLastRun); } - public getRoute(): string + public getRoute(): string { return this.getRouteOverride(); } -} \ No newline at end of file +} diff --git a/project/src/services/mod/onUpdate/OnUpdateModService.ts b/project/src/services/mod/onUpdate/OnUpdateModService.ts index 711a5c12..b8885d2d 100644 --- a/project/src/services/mod/onUpdate/OnUpdateModService.ts +++ b/project/src/services/mod/onUpdate/OnUpdateModService.ts @@ -3,18 +3,18 @@ import { DependencyContainer, injectable } from "tsyringe"; import { OnUpdateMod } from "@spt-aki/services/mod/onUpdate/OnUpdateMod"; @injectable() -export class OnUpdateModService +export class OnUpdateModService { - constructor(protected container: DependencyContainer) + constructor(protected container: DependencyContainer) {} - + public registerOnUpdate( name: string, onUpdate: (timeSinceLastRun: number) => boolean, - getRoute: () => string - ): void + getRoute: () => string, + ): void { this.container.register(name, {useValue: new OnUpdateMod(onUpdate, getRoute)}); this.container.registerType("OnUpdate", name); } -} \ No newline at end of file +} diff --git a/project/src/services/mod/staticRouter/StaticRouterMod.ts b/project/src/services/mod/staticRouter/StaticRouterMod.ts index b6065286..01977a6f 100644 --- a/project/src/services/mod/staticRouter/StaticRouterMod.ts +++ b/project/src/services/mod/staticRouter/StaticRouterMod.ts @@ -4,14 +4,14 @@ export class StaticRouterMod extends StaticRouter { public constructor( routes: RouteAction[], - private topLevelRoute: string - ) + private topLevelRoute: string, + ) { super(routes); } - public override getTopLevelRoute(): string + public override getTopLevelRoute(): string { return this.topLevelRoute; } -} \ No newline at end of file +} diff --git a/project/src/services/mod/staticRouter/StaticRouterModService.ts b/project/src/services/mod/staticRouter/StaticRouterModService.ts index 957efcbc..70502e87 100644 --- a/project/src/services/mod/staticRouter/StaticRouterModService.ts +++ b/project/src/services/mod/staticRouter/StaticRouterModService.ts @@ -4,17 +4,17 @@ import { RouteAction } from "@spt-aki/di/Router"; import { StaticRouterMod } from "@spt-aki/services/mod/staticRouter/StaticRouterMod"; @injectable() -export class StaticRouterModService +export class StaticRouterModService { - constructor(protected container: DependencyContainer) + constructor(protected container: DependencyContainer) {} public registerStaticRouter( name: string, routes: RouteAction[], - topLevelRoute: string - ): void + topLevelRoute: string, + ): void { this.container.register(name, {useValue: new StaticRouterMod(routes, topLevelRoute)}); this.container.registerType("StaticRoutes", name); } -} \ No newline at end of file +} From 4479f683885c2f190717ca465682b0f0e95cdd12 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:14:58 -0500 Subject: [PATCH 33/41] Formatting for utils. --- project/src/utils/App.ts | 14 +- project/src/utils/AsyncQueue.ts | 10 +- project/src/utils/DatabaseImporter.ts | 45 ++++--- project/src/utils/EncodingUtil.ts | 8 +- project/src/utils/HashUtil.ts | 4 +- project/src/utils/HttpFileUtil.ts | 9 +- project/src/utils/HttpResponseUtil.ts | 19 +-- project/src/utils/ImporterUtil.ts | 66 +++++---- project/src/utils/JsonUtil.ts | 54 +++++--- project/src/utils/MathUtil.ts | 30 ++--- project/src/utils/ObjectId.ts | 6 +- project/src/utils/RagfairOfferHolder.ts | 6 +- project/src/utils/RandomUtil.ts | 127 ++++++++++-------- project/src/utils/TimeUtil.ts | 2 +- project/src/utils/VFS.ts | 43 +++--- project/src/utils/Watermark.ts | 22 +-- .../src/utils/collections/lists/LinkedList.ts | 72 +++++----- project/src/utils/collections/queue/Queue.ts | 17 ++- .../utils/logging/AbstractWinstonLogger.ts | 80 ++++++----- .../src/utils/logging/WinstonMainLogger.ts | 2 +- .../src/utils/logging/WinstonRequestLogger.ts | 2 +- 21 files changed, 354 insertions(+), 284 deletions(-) diff --git a/project/src/utils/App.ts b/project/src/utils/App.ts index 20ad2c45..15985000 100644 --- a/project/src/utils/App.ts +++ b/project/src/utils/App.ts @@ -19,9 +19,9 @@ export class App @inject("LocalisationService") protected localisationService: LocalisationService, @inject("EncodingUtil") protected encodingUtil: EncodingUtil, @injectAll("OnLoad") protected onLoadComponents: OnLoad[], - @injectAll("OnUpdate") protected onUpdateComponents: OnUpdate[] + @injectAll("OnUpdate") protected onUpdateComponents: OnUpdate[], ) - { } + {} public async load(): Promise { @@ -73,7 +73,9 @@ export class App if (success === void 0 && !(secondsSinceLastRun % warnTime)) { - this.logger.debug(this.localisationService.getText("route_onupdate_no_response", updateable.getRoute())); + this.logger.debug( + this.localisationService.getText("route_onupdate_no_response", updateable.getRoute()), + ); } } } @@ -82,13 +84,13 @@ export class App protected logUpdateException(err: any, updateable: OnUpdate): void { this.logger.error(this.localisationService.getText("scheduled_event_failed_to_run", updateable.getRoute())); - if (err.message) + if (err.message) { this.logger.error(err.message); } - if (err.stack) + if (err.stack) { this.logger.error(err.stack); } } -} \ No newline at end of file +} diff --git a/project/src/utils/AsyncQueue.ts b/project/src/utils/AsyncQueue.ts index 2e2398c3..86ef0701 100644 --- a/project/src/utils/AsyncQueue.ts +++ b/project/src/utils/AsyncQueue.ts @@ -12,21 +12,21 @@ export class AsyncQueue implements IAsyncQueue // Wait for the right command to execute // This ensures that the commands execute in the right order, thus no data corruption - public async waitFor(command: ICommand): Promise + public async waitFor(command: ICommand): Promise { // Add to the queue this.commandsQueue.push(command); // eslint-disable-next-line no-constant-condition - while (this.commandsQueue[0].uuid !== command.uuid) + while (this.commandsQueue[0].uuid !== command.uuid) { - await new Promise(resolve => + await new Promise((resolve) => { - setTimeout(resolve, 100); + setTimeout(resolve, 100); }); } // When the command is ready, execute it return this.commandsQueue.shift().cmd(); } -} \ No newline at end of file +} diff --git a/project/src/utils/DatabaseImporter.ts b/project/src/utils/DatabaseImporter.ts index 8a88ec4d..802d041a 100644 --- a/project/src/utils/DatabaseImporter.ts +++ b/project/src/utils/DatabaseImporter.ts @@ -33,7 +33,7 @@ export class DatabaseImporter implements OnLoad @inject("EncodingUtil") protected encodingUtil: EncodingUtil, @inject("HashUtil") protected hashUtil: HashUtil, @inject("ImporterUtil") protected importerUtil: ImporterUtil, - @inject("ConfigServer") protected configServer: ConfigServer + @inject("ConfigServer") protected configServer: ConfigServer, ) { this.httpConfig = this.configServer.getConfig(ConfigTypes.HTTP); @@ -45,25 +45,28 @@ export class DatabaseImporter implements OnLoad */ public getSptDataPath(): string { - return (globalThis.G_RELEASE_CONFIGURATION) - ? "Aki_Data/Server/" - : "./assets/"; + return (globalThis.G_RELEASE_CONFIGURATION) ? + "Aki_Data/Server/" : + "./assets/"; } - + public async onLoad(): Promise { this.filepath = this.getSptDataPath(); - + if (globalThis.G_RELEASE_CONFIGURATION) { - try + try { // Reading the dynamic SHA1 file const file = "checks.dat"; const fileWithPath = `${this.filepath}${file}`; if (this.vfs.exists(fileWithPath)) { - this.hashedFile = this.jsonUtil.deserialize(this.encodingUtil.fromBase64(this.vfs.readFile(fileWithPath)), file); + this.hashedFile = this.jsonUtil.deserialize( + this.encodingUtil.fromBase64(this.vfs.readFile(fileWithPath)), + file, + ); } else { @@ -88,7 +91,7 @@ export class DatabaseImporter implements OnLoad "/files/Hideout/", "/files/launcher/", "/files/quest/icon/", - "/files/trader/avatar/" + "/files/trader/avatar/", ]); } @@ -99,42 +102,50 @@ export class DatabaseImporter implements OnLoad protected async hydrateDatabase(filepath: string): Promise { this.logger.info(this.localisationService.getText("importing_database")); - + const dataToImport = await this.importerUtil.loadAsync( `${filepath}database/`, this.filepath, - (fileWithPath: string, data: string) => this.onReadValidate(fileWithPath, data) + (fileWithPath: string, data: string) => this.onReadValidate(fileWithPath, data), ); - const validation = (this.valid === VaildationResult.FAILED || this.valid === VaildationResult.NOT_FOUND) ? "." : ""; + const validation = (this.valid === VaildationResult.FAILED || this.valid === VaildationResult.NOT_FOUND) ? + "." : + ""; this.logger.info(`${this.localisationService.getText("importing_database_finish")}${validation}`); this.databaseServer.setTables(dataToImport); } - + protected onReadValidate(fileWithPath: string, data: string): void { // Validate files if (globalThis.G_RELEASE_CONFIGURATION && this.hashedFile && !this.validateFile(fileWithPath, data)) + { this.valid = VaildationResult.FAILED; + } } public getRoute(): string { return "aki-database"; } - + protected validateFile(filePathAndName: string, fileData: any): boolean { - try + try { const finalPath = filePathAndName.replace(this.filepath, "").replace(".json", ""); let tempObject; for (const prop of finalPath.split("/")) { if (!tempObject) + { tempObject = this.hashedFile[prop]; + } else + { tempObject = tempObject[prop]; + } } if (tempObject !== this.hashUtil.generateSha1ForData(fileData)) @@ -196,9 +207,9 @@ export class DatabaseImporter implements OnLoad } enum VaildationResult - { +{ SUCCESS = 0, FAILED = 1, NOT_FOUND = 2, - UNDEFINED = 3 + UNDEFINED = 3, } diff --git a/project/src/utils/EncodingUtil.ts b/project/src/utils/EncodingUtil.ts index 3468b12e..6ab124ef 100644 --- a/project/src/utils/EncodingUtil.ts +++ b/project/src/utils/EncodingUtil.ts @@ -3,7 +3,6 @@ import { injectable } from "tsyringe"; @injectable() export class EncodingUtil { - public encode(value: string, encode: EncodeType): string { return Buffer.from(value).toString(encode); @@ -33,14 +32,13 @@ export class EncodingUtil { return this.encode(value, EncodeType.HEX); } - } export enum EncodeType - { +{ BASE64 = "base64", HEX = "hex", ASCII = "ascii", BINARY = "binary", - UTF8 = "utf8" -} \ No newline at end of file + UTF8 = "utf8", +} diff --git a/project/src/utils/HashUtil.ts b/project/src/utils/HashUtil.ts index 7832f427..043f3cbc 100644 --- a/project/src/utils/HashUtil.ts +++ b/project/src/utils/HashUtil.ts @@ -7,9 +7,9 @@ import { TimeUtil } from "@spt-aki/utils/TimeUtil"; export class HashUtil { constructor( - @inject("TimeUtil") protected timeUtil: TimeUtil + @inject("TimeUtil") protected timeUtil: TimeUtil, ) - { } + {} /** * Create a 24 character id using the sha256 algorithm + current timestamp diff --git a/project/src/utils/HttpFileUtil.ts b/project/src/utils/HttpFileUtil.ts index 7dc79adc..faa4cd29 100644 --- a/project/src/utils/HttpFileUtil.ts +++ b/project/src/utils/HttpFileUtil.ts @@ -8,7 +8,7 @@ import { HttpServerHelper } from "@spt-aki/helpers/HttpServerHelper"; export class HttpFileUtil { constructor( - @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper + @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper, ) { } @@ -16,13 +16,14 @@ export class HttpFileUtil public sendFile(resp: ServerResponse, file: any): void { const pathSlic = file.split("/"); - const type = this.httpServerHelper.getMimeText(pathSlic[pathSlic.length - 1].split(".").at(-1)) || this.httpServerHelper.getMimeText("txt"); + const type = this.httpServerHelper.getMimeText(pathSlic[pathSlic.length - 1].split(".").at(-1)) || + this.httpServerHelper.getMimeText("txt"); const fileStream = fs.createReadStream(file); - fileStream.on("open", function () + fileStream.on("open", function() { resp.setHeader("Content-Type", type); fileStream.pipe(resp); }); } -} \ No newline at end of file +} diff --git a/project/src/utils/HttpResponseUtil.ts b/project/src/utils/HttpResponseUtil.ts index dbd93496..f10fdaba 100644 --- a/project/src/utils/HttpResponseUtil.ts +++ b/project/src/utils/HttpResponseUtil.ts @@ -10,12 +10,11 @@ import { JsonUtil } from "@spt-aki/utils/JsonUtil"; @injectable() export class HttpResponseUtil { - constructor( @inject("JsonUtil") protected jsonUtil: JsonUtil, - @inject("LocalisationService") protected localisationService: LocalisationService + @inject("LocalisationService") protected localisationService: LocalisationService, ) - { } + {} protected clearString(s: string): any { @@ -29,8 +28,8 @@ export class HttpResponseUtil /** * Return passed in data as JSON string - * @param data - * @returns + * @param data + * @returns */ public noBody(data: any): any { @@ -47,7 +46,7 @@ export class HttpResponseUtil return this.jsonUtil.serialize({ err: err, errmsg: errmsg, - data: data + data: data, }); } @@ -66,12 +65,16 @@ export class HttpResponseUtil return this.getBody([]); } - public appendErrorToOutput(output: IItemEventRouterResponse, message = this.localisationService.getText("http-unknown_error"), errorCode = BackendErrorCodes.NONE): IItemEventRouterResponse + public appendErrorToOutput( + output: IItemEventRouterResponse, + message = this.localisationService.getText("http-unknown_error"), + errorCode = BackendErrorCodes.NONE, + ): IItemEventRouterResponse { output.warnings = [{ index: 0, errmsg: message, - code: errorCode.toString() + code: errorCode.toString(), }]; return output; diff --git a/project/src/utils/ImporterUtil.ts b/project/src/utils/ImporterUtil.ts index 9c5e25a2..7bdb87c1 100644 --- a/project/src/utils/ImporterUtil.ts +++ b/project/src/utils/ImporterUtil.ts @@ -11,7 +11,7 @@ export class ImporterUtil { constructor( @inject("VFS") protected vfs: VFS, - @inject("JsonUtil") protected jsonUtil: JsonUtil + @inject("JsonUtil") protected jsonUtil: JsonUtil, ) {} @@ -22,8 +22,10 @@ export class ImporterUtil */ public async loadRecursiveAsync( filepath: string, - onReadCallback: (fileWithPath: string, data: string) => void = () => {}, - onObjectDeserialized: (fileWithPath: string, object: any) => void = () => {} + onReadCallback: (fileWithPath: string, data: string) => void = () => + {}, + onObjectDeserialized: (fileWithPath: string, object: any) => void = () => + {}, ): Promise { const result = {} as T; @@ -39,7 +41,7 @@ export class ImporterUtil { const filename = this.vfs.stripExtension(file); const filePathAndName = `${filepath}${file}`; - await this.vfs.readFileAsync(filePathAndName).then(fileData => + await this.vfs.readFileAsync(filePathAndName).then((fileData) => { onReadCallback(filePathAndName, fileData); const fileDeserialized = this.jsonUtil.deserializeWithCacheCheck(fileData, filePathAndName); @@ -57,7 +59,7 @@ export class ImporterUtil // set all loadRecursive to be executed asynchronously const resEntries = Object.entries(result); - const resResolved = await Promise.all(resEntries.map(ent => ent[1])); + const resResolved = await Promise.all(resEntries.map((ent) => ent[1])); for (let resIdx = 0; resIdx < resResolved.length; resIdx++) { resEntries[resIdx][1] = resResolved[resIdx]; @@ -67,16 +69,17 @@ export class ImporterUtil return Object.fromEntries(resEntries) as T; } - /** * Load files into js objects recursively (synchronous) * @param filepath Path to folder with files - * @returns + * @returns */ public loadRecursive( filepath: string, - onReadCallback: (fileWithPath: string, data: string) => void = () => {}, - onObjectDeserialized: (fileWithPath: string, object: any) => void = () => {} + onReadCallback: (fileWithPath: string, data: string) => void = () => + {}, + onObjectDeserialized: (fileWithPath: string, object: any) => void = () => + {}, ): T { const result = {} as T; @@ -112,8 +115,10 @@ export class ImporterUtil public async loadAsync( filepath: string, strippablePath = "", - onReadCallback: (fileWithPath: string, data: string) => void = () => {}, - onObjectDeserialized: (fileWithPath: string, object: any) => void = () => {} + onReadCallback: (fileWithPath: string, data: string) => void = () => + {}, + onObjectDeserialized: (fileWithPath: string, object: any) => void = () => + {}, ): Promise { const directoriesToRead = new Queue(); @@ -125,15 +130,15 @@ export class ImporterUtil const files = this.vfs.getFiles(filepath); const directories = this.vfs.getDirs(filepath); - - directoriesToRead.enqueueAll(directories.map(d => `${filepath}${d}`)); - filesToProcess.enqueueAll(files.map(f => new VisitNode(filepath, f))); + + directoriesToRead.enqueueAll(directories.map((d) => `${filepath}${d}`)); + filesToProcess.enqueueAll(files.map((f) => new VisitNode(filepath, f))); while (!directoriesToRead.isEmpty()) { const directory = directoriesToRead.dequeue(); - filesToProcess.enqueueAll(this.vfs.getFiles(directory).map(f => new VisitNode(`${directory}/`, f))); - directoriesToRead.enqueueAll(this.vfs.getDirs(directory).map(d => `${directory}/${d}`)); + filesToProcess.enqueueAll(this.vfs.getFiles(directory).map((f) => new VisitNode(`${directory}/`, f))); + directoriesToRead.enqueueAll(this.vfs.getDirs(directory).map((d) => `${directory}/${d}`)); } while (!filesToProcess.isEmpty()) @@ -144,25 +149,28 @@ export class ImporterUtil const filePathAndName = `${fileNode.filePath}${fileNode.fileName}`; promises.push( this.vfs.readFileAsync(filePathAndName) - .then(async fileData => { + .then(async (fileData) => + { onReadCallback(filePathAndName, fileData); return this.jsonUtil.deserializeWithCacheCheckAsync(fileData, filePathAndName); }) - .then(async fileDeserialized => { + .then(async (fileDeserialized) => + { onObjectDeserialized(filePathAndName, fileDeserialized); const strippedFilePath = this.vfs.stripExtension(filePathAndName).replace(filepath, ""); this.placeObject(fileDeserialized, strippedFilePath, result, strippablePath); - }) + }), ); } } - - await Promise.all(promises).catch(e => console.error(e)); - + + await Promise.all(promises).catch((e) => console.error(e)); + return result; } - - protected placeObject(fileDeserialized: any, strippedFilePath: string, result: T, strippablePath: string):void { + + protected placeObject(fileDeserialized: any, strippedFilePath: string, result: T, strippablePath: string): void + { const strippedFinalPath = strippedFilePath.replace(strippablePath, ""); let temp = result; const propertiesToVisit = strippedFinalPath.split("/"); @@ -177,7 +185,9 @@ export class ImporterUtil else { if (!temp[property]) + { temp[property] = {}; + } temp = temp[property]; } } @@ -188,7 +198,7 @@ class VisitNode { constructor( public filePath: string, - public fileName: string - ){} - -} \ No newline at end of file + public fileName: string, + ) + {} +} diff --git a/project/src/utils/JsonUtil.ts b/project/src/utils/JsonUtil.ts index a5b5877f..73a7666c 100644 --- a/project/src/utils/JsonUtil.ts +++ b/project/src/utils/JsonUtil.ts @@ -18,9 +18,9 @@ export class JsonUtil constructor( @inject("VFS") protected vfs: VFS, @inject("HashUtil") protected hashUtil: HashUtil, - @inject("WinstonLogger") protected logger: ILogger + @inject("WinstonLogger") protected logger: ILogger, ) - { } + {} /** * From object to string @@ -47,23 +47,27 @@ export class JsonUtil * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. * @returns string */ - public serializeAdvanced(data: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string + public serializeAdvanced( + data: any, + replacer?: (this: any, key: string, value: any) => any, + space?: string | number, + ): string { - return JSON.stringify(data, replacer, space); } /** * From object to string * @param data object to turn into JSON - * @param filename Name of file being serialized - * @param options Stringify options or a replacer. - * @returns The string converted from the JavaScript value + * @param filename Name of file being serialized + * @param options Stringify options or a replacer. + * @returns The string converted from the JavaScript value */ public serializeJsonC( data: any, filename?: string | null, - options?: IStringifyOptions | Reviver): string + options?: IStringifyOptions | Reviver, + ): string { try { @@ -71,14 +75,17 @@ export class JsonUtil } catch (error) { - this.logger.error(`unable to stringify jsonC file: ${filename} message: ${error.message}, stack: ${error.stack}`); + this.logger.error( + `unable to stringify jsonC file: ${filename} message: ${error.message}, stack: ${error.stack}`, + ); } } public serializeJson5( data: any, filename?: string | null, - prettify = false): string + prettify = false, + ): string { try { @@ -93,7 +100,9 @@ export class JsonUtil } catch (error) { - this.logger.error(`unable to stringify json5 file: ${filename} message: ${error.message}, stack: ${error.stack}`); + this.logger.error( + `unable to stringify json5 file: ${filename} message: ${error.message}, stack: ${error.stack}`, + ); } } @@ -111,7 +120,9 @@ export class JsonUtil } catch (error) { - this.logger.error(`unable to parse json file: ${filename} message: ${error.message}, stack: ${error.stack}`); + this.logger.error( + `unable to parse json file: ${filename} message: ${error.message}, stack: ${error.stack}`, + ); } } @@ -130,7 +141,9 @@ export class JsonUtil } catch (error) { - this.logger.error(`unable to parse jsonC file: ${filename} message: ${error.message}, stack: ${error.stack}`); + this.logger.error( + `unable to parse jsonC file: ${filename} message: ${error.message}, stack: ${error.stack}`, + ); } } @@ -142,13 +155,15 @@ export class JsonUtil } catch (error) { - this.logger.error(`unable to parse json file: ${filename} message: ${error.message}, stack: ${error.stack}`); + this.logger.error( + `unable to parse json file: ${filename} message: ${error.message}, stack: ${error.stack}`, + ); } } public async deserializeWithCacheCheckAsync(jsonString: string, filePath: string): Promise { - return new Promise((resolve) => + return new Promise((resolve) => { resolve(this.deserializeWithCacheCheck(jsonString, filePath)); }); @@ -174,9 +189,9 @@ export class JsonUtil { try { - const { data, changed } = fixJson(jsonString); - if (changed) // data invalid, return it - { + const {data, changed} = fixJson(jsonString); + if (changed) + { // data invalid, return it this.logger.error(`${filePath} - Detected faulty json, please fix your json file using VSCodium`); } else @@ -206,7 +221,6 @@ export class JsonUtil return this.deserialize(jsonString); } - /** * Create file if nothing found * @param jsonCachePath path to cache @@ -228,7 +242,7 @@ export class JsonUtil * Read contents of json cache and add to class field * @param jsonCachePath Path to cache */ - protected hydrateJsonCache(jsonCachePath: string) : void + protected hydrateJsonCache(jsonCachePath: string): void { // Get all file hashes if (!this.fileHashes) diff --git a/project/src/utils/MathUtil.ts b/project/src/utils/MathUtil.ts index ab72896f..ec23703d 100644 --- a/project/src/utils/MathUtil.ts +++ b/project/src/utils/MathUtil.ts @@ -5,9 +5,9 @@ export class MathUtil { /** * Helper to create the sum of all array elements - * @param {array} values The array with numbers of which to calculate the sum - * @return {number} sum(values) - */ + * @param {array} values The array with numbers of which to calculate the sum + * @return {number} sum(values) + */ public arraySum(values: number[]): number { // sum with initial value being 0 @@ -24,7 +24,7 @@ export class MathUtil { // curried function for cumulative sum: (cum, x) => cum += x // and 0 being the initial value for the map - return values.map((cum => x => cum += x)(0)); + return values.map(((cum) => (x) => cum += x)(0)); } /** @@ -34,7 +34,7 @@ export class MathUtil */ public arrayProd(values: number[], factor: number): number[] { - return values.map(x => x * factor); + return values.map((x) => x * factor); } /** @@ -44,7 +44,7 @@ export class MathUtil */ public arrayAdd(values: number[], summand: number): number[] { - return values.map(x => x + summand); + return values.map((x) => x + summand); } /** @@ -72,14 +72,14 @@ export class MathUtil } /** - * Linear interpolation - * e.g. used to do a continuous integration for quest rewards which are defined for specific support centers of pmcLevel - * - * @param {string} xp the point of x at which to interpolate - * @param {array} x support points in x (of same length as y) - * @param {array} y support points in y (of same length as x) - * @return {number} y(xp) - */ + * Linear interpolation + * e.g. used to do a continuous integration for quest rewards which are defined for specific support centers of pmcLevel + * + * @param {string} xp the point of x at which to interpolate + * @param {array} x support points in x (of same length as y) + * @param {array} y support points in y (of same length as x) + * @return {number} y(xp) + */ public interp1(xp: number, x: number[], y: number[]): number { if (xp > x[x.length - 1]) @@ -101,4 +101,4 @@ export class MathUtil } } } -} \ No newline at end of file +} diff --git a/project/src/utils/ObjectId.ts b/project/src/utils/ObjectId.ts index 40183e9b..6656bb97 100644 --- a/project/src/utils/ObjectId.ts +++ b/project/src/utils/ObjectId.ts @@ -7,9 +7,9 @@ import { TimeUtil } from "@spt-aki/utils/TimeUtil"; export class ObjectId { constructor( - @inject("TimeUtil") protected timeUtil: TimeUtil + @inject("TimeUtil") protected timeUtil: TimeUtil, ) - { } + {} protected randomBytes = crypto.randomBytes(5); protected constglobalCounter = 0; @@ -58,4 +58,4 @@ export class ObjectId return this.toHexString(objectIdBinary); } -} \ No newline at end of file +} diff --git a/project/src/utils/RagfairOfferHolder.ts b/project/src/utils/RagfairOfferHolder.ts index 75491e5f..fc772c8e 100644 --- a/project/src/utils/RagfairOfferHolder.ts +++ b/project/src/utils/RagfairOfferHolder.ts @@ -84,7 +84,7 @@ export class RagfairOfferHolder this.removeOffer(offer); } } - + public removeOfferByTrader(traderId: string): void { if (this.offersByTrader.has(traderId)) @@ -99,7 +99,7 @@ export class RagfairOfferHolder */ public getStaleOffers(time: number): Array { - return this.getOffers().filter(o => this.isStale(o, time)); + return this.getOffers().filter((o) => this.isStale(o, time)); } protected addOfferByTemplates(template: string, offer: IRagfairOffer): void @@ -134,4 +134,4 @@ export class RagfairOfferHolder { return offer.endTime < time || offer.items[0].upd.StackObjectsCount < 1; } -} \ No newline at end of file +} diff --git a/project/src/utils/RandomUtil.ts b/project/src/utils/RandomUtil.ts index e0cf76b1..4e0ed9c3 100644 --- a/project/src/utils/RandomUtil.ts +++ b/project/src/utils/RandomUtil.ts @@ -5,32 +5,35 @@ import { JsonUtil } from "@spt-aki/utils/JsonUtil"; import { MathUtil } from "@spt-aki/utils/MathUtil"; /** - * Array of ProbabilityObjectArray which allow to randomly draw of the contained objects - * based on the relative probability of each of its elements. - * The probabilities of the contained element is not required to be normalized. - * - * Example: - * po = new ProbabilityObjectArray( - * new ProbabilityObject("a", 5), - * new ProbabilityObject("b", 1), - * new ProbabilityObject("c", 1) - * ); - * res = po.draw(10000); - * // count the elements which should be distributed according to the relative probabilities - * res.filter(x => x==="b").reduce((sum, x) => sum + 1 , 0) - */ -export class ProbabilityObjectArray extends Array> + * Array of ProbabilityObjectArray which allow to randomly draw of the contained objects + * based on the relative probability of each of its elements. + * The probabilities of the contained element is not required to be normalized. + * + * Example: + * po = new ProbabilityObjectArray( + * new ProbabilityObject("a", 5), + * new ProbabilityObject("b", 1), + * new ProbabilityObject("c", 1) + * ); + * res = po.draw(10000); + * // count the elements which should be distributed according to the relative probabilities + * res.filter(x => x==="b").reduce((sum, x) => sum + 1 , 0) + */ +export class ProbabilityObjectArray extends Array> { constructor( private mathUtil: MathUtil, private jsonUtil: JsonUtil, - ...items: ProbabilityObject[]) + ...items: ProbabilityObject[] + ) { super(); this.push(...items); } - filter(callbackfn: (value: ProbabilityObject, index: number, array: ProbabilityObject[]) => any): ProbabilityObjectArray + filter( + callbackfn: (value: ProbabilityObject, index: number, array: ProbabilityObject[]) => any, + ): ProbabilityObjectArray { return new ProbabilityObjectArray(this.mathUtil, this.jsonUtil, ...super.filter(callbackfn)); } @@ -56,7 +59,7 @@ export class ProbabilityObjectArray extends Array(this.mathUtil, this.jsonUtil); - for (const ci of clone) + for (const ci of clone) { probabliltyObjects.push(new ProbabilityObject(ci.key, ci.relativeProbability, ci.data)); } @@ -71,7 +74,7 @@ export class ProbabilityObjectArray extends Array { - return this.filter(r => r.key !== key); + return this.filter((r) => r.key !== key); } /** @@ -81,7 +84,7 @@ export class ProbabilityObjectArray extends Array r.key === key)[0]?.data; + return this.filter((r) => r.key === key)[0]?.data; } /** @@ -96,7 +99,7 @@ export class ProbabilityObjectArray extends Array r.key === key)[0].relativeProbability; + return this.filter((r) => r.key === key)[0].relativeProbability; } /** @@ -110,7 +113,7 @@ export class ProbabilityObjectArray extends Array x.relativeProbability)); + return Math.max(...this.map((x) => x.relativeProbability)); } /** @@ -124,7 +127,7 @@ export class ProbabilityObjectArray extends Array x.relativeProbability)); + return Math.min(...this.map((x) => x.relativeProbability)); } /** @@ -146,17 +149,17 @@ export class ProbabilityObjectArray extends Array x > rand); + const randomIndex = probCumsum.findIndex((x) => x > rand); // We cannot put Math.random() directly in the findIndex because then it draws anew for each of its iteration - if (replacement || locklist.includes(keyArray[randomIndex])) + if (replacement || locklist.includes(keyArray[randomIndex])) { // Add random item from possible value into return array drawnKeys.push(keyArray[randomIndex]); } - else + else { // We draw without replacement -> remove the key and its probability from array const key = keyArray.splice(randomIndex, 1)[0]; @@ -164,7 +167,7 @@ export class ProbabilityObjectArray extends Array extends Array + * A ProbabilityObject which is use as an element to the ProbabilityObjectArray array + * It contains a key, the relative probability as well as optional data. + */ +export class ProbabilityObject { key: K; relativeProbability: number; data: V; /** - * Constructor for the ProbabilityObject - * @param {string} key The key of the element - * @param {number} relativeProbability The relative probability of this element - * @param {any} data Optional data attached to the element - */ + * Constructor for the ProbabilityObject + * @param {string} key The key of the element + * @param {number} relativeProbability The relative probability of this element + * @param {any} data Optional data attached to the element + */ constructor(key: K, relativeProbability: number, data: V = null) { this.key = key; @@ -201,9 +204,9 @@ export class ProbabilityObject @injectable() export class RandomUtil { - constructor ( + constructor( @inject("JsonUtil") protected jsonUtil: JsonUtil, - @inject("WinstonLogger") protected logger: ILogger + @inject("WinstonLogger") protected logger: ILogger, ) { } @@ -261,7 +264,7 @@ export class RandomUtil return this.getArrayValue(Object.keys(node)); } - public getKeyValue(node: { [x: string]: any; }): any + public getKeyValue(node: {[x: string]: any;}): any { return node[this.getKey(node)]; } @@ -276,8 +279,14 @@ export class RandomUtil { let u = 0; let v = 0; - while (u === 0) u = Math.random(); //Converting [0,1) to (0,1) - while (v === 0) v = Math.random(); + while (u === 0) + { + u = Math.random(); // Converting [0,1) to (0,1) + } + while (v === 0) + { + v = Math.random(); + } const w = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v); return mu + w * sigma; } @@ -291,11 +300,11 @@ export class RandomUtil */ public randInt(low: number, high?: number): number { - if (high) + if (high) { return low + Math.floor(Math.random() * (high - low)); } - else + else { return Math.floor(Math.random() * low); } @@ -311,20 +320,20 @@ export class RandomUtil */ public drawRandomFromList(list: Array, count = 1, replacement = true): Array { - if (!replacement) + if (!replacement) { list = this.jsonUtil.clone(list); } const results = []; - for (let i = 0; i < count; i++) + for (let i = 0; i < count; i++) { const randomIndex = this.randInt(list.length); - if (replacement) + if (replacement) { results.push(list[randomIndex]); } - else + else { results.push(list.splice(randomIndex, 1)[0]); } @@ -366,7 +375,7 @@ export class RandomUtil { throw { name: "Invalid arguments", - message: `Bounded random number generation max is smaller than min (${max} < ${min})` + message: `Bounded random number generation max is smaller than min (${max} < ${min})`, }; } @@ -374,7 +383,7 @@ export class RandomUtil { throw { name: "Invalid argument", - message: `'n' must be 1 or greater (received ${n})` + message: `'n' must be 1 or greater (received ${n})`, }; } @@ -390,7 +399,9 @@ export class RandomUtil * A shift that is equal to the available range only has a 50% chance of rolling correctly, theoretically halving performance. * Shifting even further drops the success chance very rapidly - so we want to warn against that */ - this.logger.warning("Bias shift for random number generation is greater than the range of available numbers.\nThis can have a very severe performance impact!"); + this.logger.warning( + "Bias shift for random number generation is greater than the range of available numbers.\nThis can have a very severe performance impact!", + ); this.logger.info(`min -> ${min}; max -> ${max}; shift -> ${shift}`); } @@ -433,19 +444,21 @@ export class RandomUtil { let currentIndex = array.length; let randomIndex: number; - + // While there remain elements to shuffle. - while (currentIndex !== 0) + while (currentIndex !== 0) { // Pick a remaining element. randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; - + // And swap it with the current element. [array[currentIndex], array[randomIndex]] = [ - array[randomIndex], array[currentIndex]]; + array[randomIndex], + array[currentIndex], + ]; } - + return array; } -} \ No newline at end of file +} diff --git a/project/src/utils/TimeUtil.ts b/project/src/utils/TimeUtil.ts index 12b9f7ce..a74cc943 100644 --- a/project/src/utils/TimeUtil.ts +++ b/project/src/utils/TimeUtil.ts @@ -1,5 +1,5 @@ -import { injectable } from "tsyringe"; import { formatInTimeZone } from "date-fns-tz"; +import { injectable } from "tsyringe"; /** * Utility class to handle time related operations. diff --git a/project/src/utils/VFS.ts b/project/src/utils/VFS.ts index bf0f49ca..0d357769 100644 --- a/project/src/utils/VFS.ts +++ b/project/src/utils/VFS.ts @@ -1,30 +1,33 @@ import "reflect-metadata"; import { inject, injectable } from "tsyringe"; -import fs from "node:fs"; -import crypto from "node:crypto"; -import { promisify } from "node:util"; -import path, { resolve } from "node:path"; -import { writeFileSync } from "atomically"; -import lockfile from "proper-lockfile"; import { IAsyncQueue } from "@spt-aki/models/spt/utils/IAsyncQueue"; +import { writeFileSync } from "atomically"; +import crypto from "node:crypto"; +import fs from "node:fs"; +import path, { resolve } from "node:path"; +import { promisify } from "node:util"; +import lockfile from "proper-lockfile"; @injectable() export class VFS { accessFilePromisify: (path: fs.PathLike, mode?: number) => Promise; copyFilePromisify: (src: fs.PathLike, dst: fs.PathLike, flags?: number) => Promise; - mkdirPromisify: (path: fs.PathLike, options: fs.MakeDirectoryOptions & { recursive: true; }) => Promise; + mkdirPromisify: (path: fs.PathLike, options: fs.MakeDirectoryOptions & {recursive: true;}) => Promise; readFilePromisify: (path: fs.PathLike) => Promise; writeFilePromisify: (path: fs.PathLike, data: string, options?: any) => Promise; - readdirPromisify: (path: fs.PathLike, options?: BufferEncoding | { encoding: BufferEncoding; withFileTypes?: false; }) => Promise; - statPromisify: (path: fs.PathLike, options?: fs.StatOptions & { bigint?: false; }) => Promise; + readdirPromisify: ( + path: fs.PathLike, + options?: BufferEncoding | {encoding: BufferEncoding; withFileTypes?: false;}, + ) => Promise; + statPromisify: (path: fs.PathLike, options?: fs.StatOptions & {bigint?: false;}) => Promise; unlinkPromisify: (path: fs.PathLike) => Promise; rmdirPromisify: (path: fs.PathLike) => Promise; renamePromisify: (oldPath: fs.PathLike, newPath: fs.PathLike) => Promise; constructor( - @inject("AsyncQueue") protected asyncQueue: IAsyncQueue + @inject("AsyncQueue") protected asyncQueue: IAsyncQueue, ) { this.accessFilePromisify = promisify(fs.access); @@ -51,7 +54,7 @@ export class VFS // Create the command to add to the queue const command = { uuid: crypto.randomUUID(), - cmd: async () => await this.accessFilePromisify(filepath) + cmd: async () => await this.accessFilePromisify(filepath), }; // Wait for the command completion await this.asyncQueue.waitFor(command); @@ -75,21 +78,22 @@ export class VFS { const command = { uuid: crypto.randomUUID(), - cmd: async () => await this.copyFilePromisify(filepath, target) + cmd: async () => await this.copyFilePromisify(filepath, target), }; await this.asyncQueue.waitFor(command); } public createDir(filepath: string): void { - fs.mkdirSync(filepath.substr(0, filepath.lastIndexOf("/")), { recursive: true }); + fs.mkdirSync(filepath.substr(0, filepath.lastIndexOf("/")), {recursive: true}); } public async createDirAsync(filepath: string): Promise { const command = { uuid: crypto.randomUUID(), - cmd: async () => await this.mkdirPromisify(filepath.substr(0, filepath.lastIndexOf("/")), { recursive: true }) + cmd: async () => + await this.mkdirPromisify(filepath.substr(0, filepath.lastIndexOf("/")), {recursive: true}), }; await this.asyncQueue.waitFor(command); } @@ -148,7 +152,9 @@ export class VFS { const read = fs.readFileSync(...args); if (this.isBuffer(read)) + { return read.toString(); + } return read; } @@ -156,7 +162,9 @@ export class VFS { const read = await this.readFilePromisify(path); if (this.isBuffer(read)) + { return read.toString(); + } return read; } @@ -167,7 +175,7 @@ export class VFS public writeFile(filepath: any, data = "", append = false, atomic = true): void { - const options = append ? { flag: "a" } : { flag: "w" }; + const options = append ? {flag: "a"} : {flag: "w"}; if (!this.exists(filepath)) { @@ -194,7 +202,7 @@ export class VFS public async writeFileAsync(filepath: any, data = "", append = false, atomic = true): Promise { - const options = append ? { flag: "a" } : { flag: "w" }; + const options = append ? {flag: "a"} : {flag: "w"}; if (!await this.exists(filepath)) { @@ -230,7 +238,6 @@ export class VFS }); } - public getDirs(filepath: string): string[] { return fs.readdirSync(filepath).filter((item) => @@ -377,7 +384,7 @@ export class VFS return files; } - const dirents = fs.readdirSync(directory, { encoding: "utf-8", withFileTypes: true }); + const dirents = fs.readdirSync(directory, {encoding: "utf-8", withFileTypes: true}); for (const dirent of dirents) { const res = resolve(directory, dirent.name); diff --git a/project/src/utils/Watermark.ts b/project/src/utils/Watermark.ts index fb7fb068..72d72659 100644 --- a/project/src/utils/Watermark.ts +++ b/project/src/utils/Watermark.ts @@ -15,7 +15,7 @@ export class WatermarkLocale protected modding: string[]; constructor( - @inject("LocalisationService") protected localisationService: LocalisationService + @inject("LocalisationService") protected localisationService: LocalisationService, ) { this.description = [ @@ -23,7 +23,7 @@ export class WatermarkLocale "", this.localisationService.getText("watermark-free_of_charge"), this.localisationService.getText("watermark-paid_scammed"), - this.localisationService.getText("watermark-commercial_use_prohibited") + this.localisationService.getText("watermark-commercial_use_prohibited"), ]; this.warning = [ "", @@ -33,14 +33,14 @@ export class WatermarkLocale `${this.localisationService.getText("watermark-report_issues_to")}:`, this.localisationService.getText("watermark-issue_tracker_url"), "", - this.localisationService.getText("watermark-use_at_own_risk") + this.localisationService.getText("watermark-use_at_own_risk"), ]; this.modding = [ "", this.localisationService.getText("watermark-modding_disabled"), "", this.localisationService.getText("watermark-not_an_issue"), - this.localisationService.getText("watermark-do_not_report") + this.localisationService.getText("watermark-do_not_report"), ]; } @@ -71,7 +71,7 @@ export class Watermark @inject("WinstonLogger") protected logger: ILogger, @inject("ConfigServer") protected configServer: ConfigServer, @inject("LocalisationService") protected localisationService: LocalisationService, - @inject("WatermarkLocale") protected watermarkLocale?: WatermarkLocale + @inject("WatermarkLocale") protected watermarkLocale?: WatermarkLocale, ) { this.akiConfig = this.configServer.getConfig(ConfigTypes.CORE); @@ -110,9 +110,9 @@ export class Watermark */ public getVersionTag(withEftVersion = false): string { - const versionTag = (globalThis.G_DEBUG_CONFIGURATION) - ? `${this.akiConfig.akiVersion} - ${this.localisationService.getText("bleeding_edge_build")}` - : this.akiConfig.akiVersion; + const versionTag = (globalThis.G_DEBUG_CONFIGURATION) ? + `${this.akiConfig.akiVersion} - ${this.localisationService.getText("bleeding_edge_build")}` : + this.akiConfig.akiVersion; if (withEftVersion) { @@ -130,9 +130,9 @@ export class Watermark */ public getInGameVersionLabel(): string { - const versionTag = (globalThis.G_DEBUG_CONFIGURATION) - ? `${this.akiConfig.akiVersion} - BLEEDINGEDGE` - : this.akiConfig.akiVersion; + const versionTag = (globalThis.G_DEBUG_CONFIGURATION) ? + `${this.akiConfig.akiVersion} - BLEEDINGEDGE` : + this.akiConfig.akiVersion; return `${this.akiConfig.projectName} ${versionTag}`; } diff --git a/project/src/utils/collections/lists/LinkedList.ts b/project/src/utils/collections/lists/LinkedList.ts index 2aa51fa3..3a60d5ca 100644 --- a/project/src/utils/collections/lists/LinkedList.ts +++ b/project/src/utils/collections/lists/LinkedList.ts @@ -3,19 +3,19 @@ export class LinkedList private head: LinkedListNode; private tail: LinkedListNode; - public add(t: T): void + public add(t: T): void { - if (!this.head) + if (!this.head) { const node = new LinkedListNode(t); this.head = node; this.tail = node; } - else + else { let ref = this.head; let next = this.head.getNextNode(); - while (next) + while (next) { ref = next; next = ref.getNextNode(); @@ -26,34 +26,34 @@ export class LinkedList } } - public addRange(list: T[]): void + public addRange(list: T[]): void { - for (const item of list) + for (const item of list) { this.add(item); } } - public getHead(): LinkedListNode + public getHead(): LinkedListNode { return this.head; } - public getTail(): LinkedListNode + public getTail(): LinkedListNode { return this.tail; } - public isEmpty(): boolean + public isEmpty(): boolean { return this.head === undefined || this.head === null; } - public getSize(): number + public getSize(): number { let size = 0; let next = this.head; - while (next) + while (next) { size++; next = next.getNextNode(); @@ -61,41 +61,47 @@ export class LinkedList return size; } - public removeFirst(): LinkedListNode + public removeFirst(): LinkedListNode { - if (!this.head) return undefined; + if (!this.head) + { + return undefined; + } const node = this.head; - if (this.head.getNextNode()) + if (this.head.getNextNode()) { this.head = this.head.getNextNode(); this.head.setPreviousNode(undefined); } - else + else { this.head = undefined; } return node; } - public removeLast(): LinkedListNode + public removeLast(): LinkedListNode { - if (!this.tail) return undefined; - + if (!this.tail) + { + return undefined; + } + const node = this.tail; - if (this.tail.getPreviousNode()) + if (this.tail.getPreviousNode()) { this.tail = this.tail.getPreviousNode(); this.tail.setNextNode(undefined); } - else + else { this.tail = undefined; } return node; } - public indexOf(func: (t:T) => boolean): number + public indexOf(func: (t: T) => boolean): number { const node = this.head; let index = 0; @@ -110,7 +116,7 @@ export class LinkedList return undefined; } - public contains(func: (t:T) => boolean): boolean + public contains(func: (t: T) => boolean): boolean { let node = this.head; while (node) @@ -124,7 +130,7 @@ export class LinkedList return false; } - public forEachNode(func: (t:LinkedListNode) => void): void + public forEachNode(func: (t: LinkedListNode) => void): void { let node = this.head; while (node) @@ -134,7 +140,7 @@ export class LinkedList } } - public forEachValue(func: (t:T) => void): void + public forEachValue(func: (t: T) => void): void { let node = this.head; while (node) @@ -144,7 +150,7 @@ export class LinkedList } } - public findFirstNode(func: (t:LinkedListNode) => boolean): LinkedListNode + public findFirstNode(func: (t: LinkedListNode) => boolean): LinkedListNode { let node = this.head; while (node) @@ -158,7 +164,7 @@ export class LinkedList return undefined; } - public findFirstValue(func: (t:T) => boolean): T + public findFirstValue(func: (t: T) => boolean): T { let node = this.head; while (node) @@ -191,35 +197,35 @@ export class LinkedListNode private value: T; private next: LinkedListNode; - constructor(value: T, previous: LinkedListNode = undefined, next: LinkedListNode = undefined) + constructor(value: T, previous: LinkedListNode = undefined, next: LinkedListNode = undefined) { this.value = value; this.previous = previous; this.next = next; } - public getValue(): T + public getValue(): T { return this.value; } - public getNextNode(): LinkedListNode + public getNextNode(): LinkedListNode { return this.next; } - public setNextNode(node: LinkedListNode): void + public setNextNode(node: LinkedListNode): void { this.next = node; } - public getPreviousNode(): LinkedListNode + public getPreviousNode(): LinkedListNode { return this.previous; } - public setPreviousNode(node: LinkedListNode): void + public setPreviousNode(node: LinkedListNode): void { this.previous = node; } -} \ No newline at end of file +} diff --git a/project/src/utils/collections/queue/Queue.ts b/project/src/utils/collections/queue/Queue.ts index 4d632372..5bce00e4 100644 --- a/project/src/utils/collections/queue/Queue.ts +++ b/project/src/utils/collections/queue/Queue.ts @@ -3,21 +3,20 @@ export class Queue private elements: Record; private head: number; private tail: number; - constructor() - + constructor() { this.elements = {}; this.head = 0; this.tail = 0; } - - public enqueue(element: T): void + + public enqueue(element: T): void { this.elements[this.tail] = element; this.tail++; } - public enqueueAll(elements: T[]): void + public enqueueAll(elements: T[]): void { for (const element of elements) { @@ -25,7 +24,7 @@ export class Queue } } - public dequeue(): T + public dequeue(): T { const item = this.elements[this.head]; delete this.elements[this.head]; @@ -33,11 +32,11 @@ export class Queue return item; } - public peek():T + public peek(): T { return this.elements[this.head]; } - public getLength(): number + public getLength(): number { return this.tail - this.head; } @@ -46,4 +45,4 @@ export class Queue { return this.getLength() === 0; } -} \ No newline at end of file +} diff --git a/project/src/utils/logging/AbstractWinstonLogger.ts b/project/src/utils/logging/AbstractWinstonLogger.ts index 8eeec508..95761eba 100644 --- a/project/src/utils/logging/AbstractWinstonLogger.ts +++ b/project/src/utils/logging/AbstractWinstonLogger.ts @@ -1,5 +1,5 @@ -import fs from "node:fs"; import crypto from "node:crypto"; +import fs from "node:fs"; import { promisify } from "node:util"; import winston, { createLogger, format, transports } from "winston"; import DailyRotateFile from "winston-daily-rotate-file"; @@ -23,7 +23,7 @@ export abstract class AbstractWinstonLogger implements ILogger succ: 2, info: 3, custom: 4, - debug: 5 + debug: 5, }, colors: { error: "red", @@ -31,7 +31,7 @@ export abstract class AbstractWinstonLogger implements ILogger succ: "green", info: "white", custom: "black", - debug: "gray" + debug: "gray", }, bgColors: { default: "", @@ -42,14 +42,14 @@ export abstract class AbstractWinstonLogger implements ILogger blueBG: "blueBG", magentaBG: "magentaBG", cyanBG: "cyanBG", - whiteBG: "whiteBG" - } + whiteBG: "whiteBG", + }, }; protected logger: winston.Logger & SptLogger; protected writeFilePromisify: (path: fs.PathLike, data: string, options?: any) => Promise; constructor( - protected asyncQueue: IAsyncQueue + protected asyncQueue: IAsyncQueue, ) { this.filePath = `${this.getFilePath()}${this.getFileName()}`; @@ -57,7 +57,7 @@ export abstract class AbstractWinstonLogger implements ILogger this.showDebugInConsole = globalThis.G_DEBUG_CONFIGURATION; if (!fs.existsSync(this.getFilePath())) { - fs.mkdirSync(this.getFilePath(), { recursive: true }); + fs.mkdirSync(this.getFilePath(), {recursive: true}); } const transportsList: winston.transport[] = []; @@ -68,13 +68,13 @@ export abstract class AbstractWinstonLogger implements ILogger new transports.Console({ level: this.showDebugInConsole ? "debug" : "custom", format: format.combine( - format.colorize({ all: true, colors: this.logLevels.colors }), - format.printf(({ message }) => + format.colorize({all: true, colors: this.logLevels.colors}), + format.printf(({message}) => { return `${message}`; - }) - ) - }) + }), + ), + }), ); } if (this.isLogToFile()) @@ -91,19 +91,19 @@ export abstract class AbstractWinstonLogger implements ILogger format.timestamp(), format.align(), format.json(), - format.printf(({ timestamp, level, message }) => + format.printf(({timestamp, level, message}) => { return `[${timestamp}] ${level}: ${message}`; - }) - ) - }) + }), + ), + }), ); } winston.addColors(this.logLevels.colors); this.logger = createLogger({ levels: this.logLevels.levels, - transports: [...transportsList] + transports: [...transportsList], }); if (this.isLogExceptions()) @@ -140,39 +140,41 @@ export abstract class AbstractWinstonLogger implements ILogger { const command: ICommand = { uuid: crypto.randomUUID(), - cmd: async () => await this.writeFilePromisify(this.filePath, `${data}\n`, true) + cmd: async () => await this.writeFilePromisify(this.filePath, `${data}\n`, true), }; await this.asyncQueue.waitFor(command); } - public async log(data: string | Error | Record, color: string, backgroundColor = "" ): Promise + public async log(data: string | Error | Record, color: string, backgroundColor = ""): Promise { const textColor = `${color} ${backgroundColor}`.trimEnd(); const tmpLogger = createLogger({ - levels: { custom: 0 }, + levels: {custom: 0}, level: "custom", - transports: [new transports.Console({ - format: format.combine( - format.colorize({ all: true, colors: { custom: textColor } }), - format.printf(({ message }) => message) - ) - })] + transports: [ + new transports.Console({ + format: format.combine( + format.colorize({all: true, colors: {custom: textColor}}), + format.printf(({message}) => message), + ), + }), + ], }); let command: ICommand; - if (typeof (data) === "string") + if (typeof data === "string") { command = { uuid: crypto.randomUUID(), - cmd: async () => await tmpLogger.log("custom", data) + cmd: async () => await tmpLogger.log("custom", data), }; } else { command = { uuid: crypto.randomUUID(), - cmd: async () => await tmpLogger.log("custom", JSON.stringify(data, null, 4)) + cmd: async () => await tmpLogger.log("custom", JSON.stringify(data, null, 4)), }; } @@ -183,7 +185,7 @@ export abstract class AbstractWinstonLogger implements ILogger { const command: ICommand = { uuid: crypto.randomUUID(), - cmd: async () => await this.logger.error(data) + cmd: async () => await this.logger.error(data), }; await this.asyncQueue.waitFor(command); } @@ -192,7 +194,7 @@ export abstract class AbstractWinstonLogger implements ILogger { const command: ICommand = { uuid: crypto.randomUUID(), - cmd: async () => await this.logger.warn(data) + cmd: async () => await this.logger.warn(data), }; await this.asyncQueue.waitFor(command); } @@ -201,7 +203,7 @@ export abstract class AbstractWinstonLogger implements ILogger { const command: ICommand = { uuid: crypto.randomUUID(), - cmd: async () => await this.logger.succ(data) + cmd: async () => await this.logger.succ(data), }; await this.asyncQueue.waitFor(command); } @@ -210,7 +212,7 @@ export abstract class AbstractWinstonLogger implements ILogger { const command: ICommand = { uuid: crypto.randomUUID(), - cmd: async () => await this.logger.info(data) + cmd: async () => await this.logger.info(data), }; await this.asyncQueue.waitFor(command); } @@ -221,11 +223,15 @@ export abstract class AbstractWinstonLogger implements ILogger * @param textColor color of text * @param backgroundColor color of background */ - public async logWithColor(data: string | Record, textColor: LogTextColor, backgroundColor = LogBackgroundColor.DEFAULT): Promise + public async logWithColor( + data: string | Record, + textColor: LogTextColor, + backgroundColor = LogBackgroundColor.DEFAULT, + ): Promise { const command: ICommand = { uuid: crypto.randomUUID(), - cmd: async () => await this.log(data, textColor.toString(), backgroundColor.toString()) + cmd: async () => await this.log(data, textColor.toString(), backgroundColor.toString()), }; await this.asyncQueue.waitFor(command); @@ -239,14 +245,14 @@ export abstract class AbstractWinstonLogger implements ILogger { command = { uuid: crypto.randomUUID(), - cmd: async () => await this.log(data, this.logLevels.colors.debug) + cmd: async () => await this.log(data, this.logLevels.colors.debug), }; } else { command = { uuid: crypto.randomUUID(), - cmd: async () => await this.logger.debug(data) + cmd: async () => await this.logger.debug(data), }; } diff --git a/project/src/utils/logging/WinstonMainLogger.ts b/project/src/utils/logging/WinstonMainLogger.ts index 145d1059..ff02f482 100644 --- a/project/src/utils/logging/WinstonMainLogger.ts +++ b/project/src/utils/logging/WinstonMainLogger.ts @@ -7,7 +7,7 @@ import { AbstractWinstonLogger } from "@spt-aki/utils/logging/AbstractWinstonLog export class WinstonMainLogger extends AbstractWinstonLogger { constructor( - @inject("AsyncQueue") protected asyncQueue: IAsyncQueue + @inject("AsyncQueue") protected asyncQueue: IAsyncQueue, ) { super(asyncQueue); diff --git a/project/src/utils/logging/WinstonRequestLogger.ts b/project/src/utils/logging/WinstonRequestLogger.ts index 4883f310..9206d48e 100644 --- a/project/src/utils/logging/WinstonRequestLogger.ts +++ b/project/src/utils/logging/WinstonRequestLogger.ts @@ -7,7 +7,7 @@ import { AbstractWinstonLogger } from "@spt-aki/utils/logging/AbstractWinstonLog export class WinstonRequestLogger extends AbstractWinstonLogger { constructor( - @inject("AsyncQueue") protected asyncQueue: IAsyncQueue + @inject("AsyncQueue") protected asyncQueue: IAsyncQueue, ) { super(asyncQueue); From 33c3dd48e494d122b48cac14a007a7fe52053116 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:37:49 -0500 Subject: [PATCH 34/41] Disables dprint import/export sorting & adds a fix option for the linting errors. --- project/dprint.json | 4 ++++ project/package.json | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/project/dprint.json b/project/dprint.json index 287af9de..9b3e865d 100644 --- a/project/dprint.json +++ b/project/dprint.json @@ -32,6 +32,10 @@ "constructorType.spaceAfterNewKeyword": false, "constructSignature.spaceAfterNewKeyword": false, "doWhileStatement.spaceAfterWhileKeyword": true, + "module.sortImportDeclarations": "maintain", + "module.sortExportDeclarations": "maintain", + "exportDeclaration.sortNamedExports": "maintain", + "importDeclaration.sortNamedImports": "maintain", "exportDeclaration.spaceSurroundingNamedExports": false, "forInStatement.spaceAfterForKeyword": true, "forOfStatement.spaceAfterForKeyword": true, diff --git a/project/package.json b/project/package.json index 1893e3d4..9f313feb 100644 --- a/project/package.json +++ b/project/package.json @@ -13,7 +13,7 @@ "scripts": { "check:circular": "madge --circular --ts-config tsconfig.json --extensions ts ./src/", "lint": "biome ci src --formatter-enabled=false --max-diagnostics=200", - "lint:fix": "eslint --fix --ext .ts src/**", + "lint:fix": "biome check --apply-unsafe --max-diagnostics=200 . && dprint fmt --incremental=false", "style": "dprint check --incremental=false", "style:fix": "dprint fmt --incremental=false", "test": "vitest run", From e709b6c1110faa1bc49942d72d71829132ee6350 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:43:37 -0500 Subject: [PATCH 35/41] Reformatted imports with (only) Biome. --- project/gulpfile.mjs | 6 ++-- project/src/Program.ts | 2 +- .../src/controllers/InsuranceController.ts | 2 +- project/src/di/Container.ts | 32 +++++++++---------- project/src/generators/BotWeaponGenerator.ts | 2 +- project/src/generators/LocationGenerator.ts | 2 +- project/src/routers/HttpRouter.ts | 2 +- project/src/routers/ItemEventRouter.ts | 2 +- project/src/servers/HttpServer.ts | 4 +-- project/src/servers/SaveServer.ts | 2 +- project/src/servers/http/AkiHttpListener.ts | 2 +- project/src/services/LocalisationService.ts | 2 +- project/src/utils/App.ts | 2 +- project/src/utils/ImporterUtil.ts | 2 +- project/src/utils/VFS.ts | 4 +-- project/tests/CustomEnvironment.ts | 4 +-- project/tests/generators/BotGenerator.test.ts | 6 ++-- .../services/ItemBaseClassService.test.ts | 4 +-- 18 files changed, 41 insertions(+), 41 deletions(-) diff --git a/project/gulpfile.mjs b/project/gulpfile.mjs index 26ba5a31..613e916c 100644 --- a/project/gulpfile.mjs +++ b/project/gulpfile.mjs @@ -1,10 +1,10 @@ -import gulp from "gulp"; -import { exec } from "gulp-execa"; -import rename from "gulp-rename"; import crypto from "node:crypto"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; +import gulp from "gulp"; +import { exec } from "gulp-execa"; +import rename from "gulp-rename"; import pkg from "pkg"; import pkgfetch from "pkg-fetch"; import * as ResEdit from "resedit"; diff --git a/project/src/Program.ts b/project/src/Program.ts index 7ea38751..476e69e0 100644 --- a/project/src/Program.ts +++ b/project/src/Program.ts @@ -1,7 +1,7 @@ import { container } from "tsyringe"; -import { Container } from "@spt-aki/di/Container"; import { ErrorHandler } from "@spt-aki/ErrorHandler"; +import { Container } from "@spt-aki/di/Container"; import type { PreAkiModLoader } from "@spt-aki/loaders/PreAkiModLoader"; import { App } from "@spt-aki/utils/App"; import { Watermark } from "@spt-aki/utils/Watermark"; diff --git a/project/src/controllers/InsuranceController.ts b/project/src/controllers/InsuranceController.ts index 271ad0bd..f27fc583 100644 --- a/project/src/controllers/InsuranceController.ts +++ b/project/src/controllers/InsuranceController.ts @@ -10,7 +10,7 @@ import { IGetInsuranceCostRequestData } from "@spt-aki/models/eft/insurance/IGet import { IGetInsuranceCostResponseData } from "@spt-aki/models/eft/insurance/IGetInsuranceCostResponseData"; import { IInsureRequestData } from "@spt-aki/models/eft/insurance/IInsureRequestData"; import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse"; -import { Insurance, ISystemData } from "@spt-aki/models/eft/profile/IAkiProfile"; +import { ISystemData, Insurance } from "@spt-aki/models/eft/profile/IAkiProfile"; import { IProcessBuyTradeRequestData } from "@spt-aki/models/eft/trade/IProcessBuyTradeRequestData"; import { ConfigTypes } from "@spt-aki/models/enums/ConfigTypes"; import { MessageType } from "@spt-aki/models/enums/MessageType"; diff --git a/project/src/di/Container.ts b/project/src/di/Container.ts index 9e13eb14..e80d5579 100644 --- a/project/src/di/Container.ts +++ b/project/src/di/Container.ts @@ -69,17 +69,17 @@ import { BotWeaponGenerator } from "@spt-aki/generators/BotWeaponGenerator"; import { FenceBaseAssortGenerator } from "@spt-aki/generators/FenceBaseAssortGenerator"; import { LocationGenerator } from "@spt-aki/generators/LocationGenerator"; import { LootGenerator } from "@spt-aki/generators/LootGenerator"; -import { PlayerScavGenerator } from "@spt-aki/generators/PlayerScavGenerator"; import { PMCLootGenerator } from "@spt-aki/generators/PMCLootGenerator"; +import { PlayerScavGenerator } from "@spt-aki/generators/PlayerScavGenerator"; import { RagfairAssortGenerator } from "@spt-aki/generators/RagfairAssortGenerator"; import { RagfairOfferGenerator } from "@spt-aki/generators/RagfairOfferGenerator"; import { RepeatableQuestGenerator } from "@spt-aki/generators/RepeatableQuestGenerator"; import { ScavCaseRewardGenerator } from "@spt-aki/generators/ScavCaseRewardGenerator"; +import { WeatherGenerator } from "@spt-aki/generators/WeatherGenerator"; import { BarrelInventoryMagGen } from "@spt-aki/generators/weapongen/implementations/BarrelInventoryMagGen"; import { ExternalInventoryMagGen } from "@spt-aki/generators/weapongen/implementations/ExternalInventoryMagGen"; import { InternalMagazineInventoryMagGen } from "@spt-aki/generators/weapongen/implementations/InternalMagazineInventoryMagGen"; import { UbglExternalMagGen } from "@spt-aki/generators/weapongen/implementations/UbglExternalMagGen"; -import { WeatherGenerator } from "@spt-aki/generators/WeatherGenerator"; import { AssortHelper } from "@spt-aki/helpers/AssortHelper"; import { BotDifficultyHelper } from "@spt-aki/helpers/BotDifficultyHelper"; import { BotGeneratorHelper } from "@spt-aki/helpers/BotGeneratorHelper"; @@ -124,6 +124,10 @@ import { PostAkiModLoader } from "@spt-aki/loaders/PostAkiModLoader"; import { PostDBModLoader } from "@spt-aki/loaders/PostDBModLoader"; import { PreAkiModLoader } from "@spt-aki/loaders/PreAkiModLoader"; import { IAsyncQueue } from "@spt-aki/models/spt/utils/IAsyncQueue"; +import { EventOutputHolder } from "@spt-aki/routers/EventOutputHolder"; +import { HttpRouter } from "@spt-aki/routers/HttpRouter"; +import { ImageRouter } from "@spt-aki/routers/ImageRouter"; +import { ItemEventRouter } from "@spt-aki/routers/ItemEventRouter"; import { BotDynamicRouter } from "@spt-aki/routers/dynamic/BotDynamicRouter"; import { BundleDynamicRouter } from "@spt-aki/routers/dynamic/BundleDynamicRouter"; import { CustomizationDynamicRouter } from "@spt-aki/routers/dynamic/CustomizationDynamicRouter"; @@ -133,9 +137,6 @@ import { InraidDynamicRouter } from "@spt-aki/routers/dynamic/InraidDynamicRoute import { LocationDynamicRouter } from "@spt-aki/routers/dynamic/LocationDynamicRouter"; import { NotifierDynamicRouter } from "@spt-aki/routers/dynamic/NotifierDynamicRouter"; import { TraderDynamicRouter } from "@spt-aki/routers/dynamic/TraderDynamicRouter"; -import { EventOutputHolder } from "@spt-aki/routers/EventOutputHolder"; -import { HttpRouter } from "@spt-aki/routers/HttpRouter"; -import { ImageRouter } from "@spt-aki/routers/ImageRouter"; import { CustomizationItemEventRouter } from "@spt-aki/routers/item_events/CustomizationItemEventRouter"; import { HealthItemEventRouter } from "@spt-aki/routers/item_events/HealthItemEventRouter"; import { HideoutItemEventRouter } from "@spt-aki/routers/item_events/HideoutItemEventRouter"; @@ -148,7 +149,6 @@ import { RagfairItemEventRouter } from "@spt-aki/routers/item_events/RagfairItem import { RepairItemEventRouter } from "@spt-aki/routers/item_events/RepairItemEventRouter"; import { TradeItemEventRouter } from "@spt-aki/routers/item_events/TradeItemEventRouter"; import { WishlistItemEventRouter } from "@spt-aki/routers/item_events/WishlistItemEventRouter"; -import { ItemEventRouter } from "@spt-aki/routers/ItemEventRouter"; import { HealthSaveLoadRouter } from "@spt-aki/routers/save_load/HealthSaveLoadRouter"; import { InraidSaveLoadRouter } from "@spt-aki/routers/save_load/InraidSaveLoadRouter"; import { InsuranceSaveLoadRouter } from "@spt-aki/routers/save_load/InsuranceSaveLoadRouter"; @@ -179,11 +179,11 @@ import { TraderStaticRouter } from "@spt-aki/routers/static/TraderStaticRouter"; import { WeatherStaticRouter } from "@spt-aki/routers/static/WeatherStaticRouter"; import { ConfigServer } from "@spt-aki/servers/ConfigServer"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; -import { AkiHttpListener } from "@spt-aki/servers/http/AkiHttpListener"; import { HttpServer } from "@spt-aki/servers/HttpServer"; import { RagfairServer } from "@spt-aki/servers/RagfairServer"; import { SaveServer } from "@spt-aki/servers/SaveServer"; import { WebSocketServer } from "@spt-aki/servers/WebSocketServer"; +import { AkiHttpListener } from "@spt-aki/servers/http/AkiHttpListener"; import { BotEquipmentFilterService } from "@spt-aki/services/BotEquipmentFilterService"; import { BotEquipmentModPoolService } from "@spt-aki/services/BotEquipmentModPoolService"; import { BotGenerationCacheService } from "@spt-aki/services/BotGenerationCacheService"; @@ -201,13 +201,6 @@ import { LocalisationService } from "@spt-aki/services/LocalisationService"; import { MailSendService } from "@spt-aki/services/MailSendService"; import { MatchBotDetailsCacheService } from "@spt-aki/services/MatchBotDetailsCacheService"; import { MatchLocationService } from "@spt-aki/services/MatchLocationService"; -import { CustomItemService } from "@spt-aki/services/mod/CustomItemService"; -import { DynamicRouterModService } from "@spt-aki/services/mod/dynamicRouter/DynamicRouterModService"; -import { HttpListenerModService } from "@spt-aki/services/mod/httpListener/HttpListenerModService"; -import { ImageRouteService } from "@spt-aki/services/mod/image/ImageRouteService"; -import { OnLoadModService } from "@spt-aki/services/mod/onLoad/OnLoadModService"; -import { OnUpdateModService } from "@spt-aki/services/mod/onUpdate/OnUpdateModService"; -import { StaticRouterModService } from "@spt-aki/services/mod/staticRouter/StaticRouterModService"; import { ModCompilerService } from "@spt-aki/services/ModCompilerService"; import { NotificationService } from "@spt-aki/services/NotificationService"; import { OpenZoneService } from "@spt-aki/services/OpenZoneService"; @@ -226,6 +219,13 @@ import { RepairService } from "@spt-aki/services/RepairService"; import { SeasonalEventService } from "@spt-aki/services/SeasonalEventService"; import { TraderAssortService } from "@spt-aki/services/TraderAssortService"; import { TraderPurchasePersisterService } from "@spt-aki/services/TraderPurchasePersisterService"; +import { CustomItemService } from "@spt-aki/services/mod/CustomItemService"; +import { DynamicRouterModService } from "@spt-aki/services/mod/dynamicRouter/DynamicRouterModService"; +import { HttpListenerModService } from "@spt-aki/services/mod/httpListener/HttpListenerModService"; +import { ImageRouteService } from "@spt-aki/services/mod/image/ImageRouteService"; +import { OnLoadModService } from "@spt-aki/services/mod/onLoad/OnLoadModService"; +import { OnUpdateModService } from "@spt-aki/services/mod/onUpdate/OnUpdateModService"; +import { StaticRouterModService } from "@spt-aki/services/mod/staticRouter/StaticRouterModService"; import { App } from "@spt-aki/utils/App"; import { AsyncQueue } from "@spt-aki/utils/AsyncQueue"; import { DatabaseImporter } from "@spt-aki/utils/DatabaseImporter"; @@ -235,14 +235,14 @@ import { HttpFileUtil } from "@spt-aki/utils/HttpFileUtil"; import { HttpResponseUtil } from "@spt-aki/utils/HttpResponseUtil"; import { ImporterUtil } from "@spt-aki/utils/ImporterUtil"; import { JsonUtil } from "@spt-aki/utils/JsonUtil"; -import { WinstonMainLogger } from "@spt-aki/utils/logging/WinstonMainLogger"; -import { WinstonRequestLogger } from "@spt-aki/utils/logging/WinstonRequestLogger"; import { MathUtil } from "@spt-aki/utils/MathUtil"; import { ObjectId } from "@spt-aki/utils/ObjectId"; import { RandomUtil } from "@spt-aki/utils/RandomUtil"; import { TimeUtil } from "@spt-aki/utils/TimeUtil"; import { VFS } from "@spt-aki/utils/VFS"; import { Watermark, WatermarkLocale } from "@spt-aki/utils/Watermark"; +import { WinstonMainLogger } from "@spt-aki/utils/logging/WinstonMainLogger"; +import { WinstonRequestLogger } from "@spt-aki/utils/logging/WinstonRequestLogger"; /** * Handle the registration of classes to be used by the Dependency Injection code diff --git a/project/src/generators/BotWeaponGenerator.ts b/project/src/generators/BotWeaponGenerator.ts index db97c19f..ad7fc5ef 100644 --- a/project/src/generators/BotWeaponGenerator.ts +++ b/project/src/generators/BotWeaponGenerator.ts @@ -1,4 +1,4 @@ -import { inject, injectable, injectAll } from "tsyringe"; +import { inject, injectAll, injectable } from "tsyringe"; import { BotEquipmentModGenerator } from "@spt-aki/generators/BotEquipmentModGenerator"; import { IInventoryMagGen } from "@spt-aki/generators/weapongen/IInventoryMagGen"; diff --git a/project/src/generators/LocationGenerator.ts b/project/src/generators/LocationGenerator.ts index a43d738f..bdb1bd8e 100644 --- a/project/src/generators/LocationGenerator.ts +++ b/project/src/generators/LocationGenerator.ts @@ -6,7 +6,7 @@ import { PresetHelper } from "@spt-aki/helpers/PresetHelper"; import { RagfairServerHelper } from "@spt-aki/helpers/RagfairServerHelper"; import { IContainerMinMax, IStaticContainer } from "@spt-aki/models/eft/common/ILocation"; import { ILocationBase } from "@spt-aki/models/eft/common/ILocationBase"; -import { ILooseLoot, Spawnpoint, SpawnpointsForced, SpawnpointTemplate } from "@spt-aki/models/eft/common/ILooseLoot"; +import { ILooseLoot, Spawnpoint, SpawnpointTemplate, SpawnpointsForced } from "@spt-aki/models/eft/common/ILooseLoot"; import { Item } from "@spt-aki/models/eft/common/tables/IItem"; import { IStaticAmmoDetails, diff --git a/project/src/routers/HttpRouter.ts b/project/src/routers/HttpRouter.ts index 3e2f41f2..620c53d3 100644 --- a/project/src/routers/HttpRouter.ts +++ b/project/src/routers/HttpRouter.ts @@ -1,5 +1,5 @@ import { IncomingMessage } from "node:http"; -import { injectable, injectAll } from "tsyringe"; +import { injectAll, injectable } from "tsyringe"; import { DynamicRouter, Router, StaticRouter } from "@spt-aki/di/Router"; diff --git a/project/src/routers/ItemEventRouter.ts b/project/src/routers/ItemEventRouter.ts index bd1fd158..a1bf45fb 100644 --- a/project/src/routers/ItemEventRouter.ts +++ b/project/src/routers/ItemEventRouter.ts @@ -1,4 +1,4 @@ -import { inject, injectable, injectAll } from "tsyringe"; +import { inject, injectAll, injectable } from "tsyringe"; import { ItemEventRouterDefinition } from "@spt-aki/di/Router"; import { ProfileHelper } from "@spt-aki/helpers/ProfileHelper"; diff --git a/project/src/servers/HttpServer.ts b/project/src/servers/HttpServer.ts index c8f59b5d..ae163092 100644 --- a/project/src/servers/HttpServer.ts +++ b/project/src/servers/HttpServer.ts @@ -1,5 +1,5 @@ import http, { IncomingMessage, ServerResponse } from "node:http"; -import { inject, injectable, injectAll } from "tsyringe"; +import { inject, injectAll, injectable } from "tsyringe"; import { ApplicationContext } from "@spt-aki/context/ApplicationContext"; import { ContextVariableType } from "@spt-aki/context/ContextVariableType"; @@ -9,8 +9,8 @@ import { IHttpConfig } from "@spt-aki/models/spt/config/IHttpConfig"; import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; import { ConfigServer } from "@spt-aki/servers/ConfigServer"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; -import { IHttpListener } from "@spt-aki/servers/http/IHttpListener"; import { WebSocketServer } from "@spt-aki/servers/WebSocketServer"; +import { IHttpListener } from "@spt-aki/servers/http/IHttpListener"; import { LocalisationService } from "@spt-aki/services/LocalisationService"; @injectable() diff --git a/project/src/servers/SaveServer.ts b/project/src/servers/SaveServer.ts index d5edf855..8105ab79 100644 --- a/project/src/servers/SaveServer.ts +++ b/project/src/servers/SaveServer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, injectAll } from "tsyringe"; +import { inject, injectAll, injectable } from "tsyringe"; import { SaveLoadRouter } from "@spt-aki/di/Router"; import { IAkiProfile, Info } from "@spt-aki/models/eft/profile/IAkiProfile"; diff --git a/project/src/servers/http/AkiHttpListener.ts b/project/src/servers/http/AkiHttpListener.ts index 6cc436bc..ef795e91 100644 --- a/project/src/servers/http/AkiHttpListener.ts +++ b/project/src/servers/http/AkiHttpListener.ts @@ -1,6 +1,6 @@ import { IncomingHttpHeaders, IncomingMessage, ServerResponse } from "node:http"; import zlib from "node:zlib"; -import { inject, injectable, injectAll } from "tsyringe"; +import { inject, injectAll, injectable } from "tsyringe"; import { Serializer } from "@spt-aki/di/Serializer"; import { ILogger } from "@spt-aki/models/spt/utils/ILogger"; diff --git a/project/src/services/LocalisationService.ts b/project/src/services/LocalisationService.ts index d946dfab..6a75cb7f 100644 --- a/project/src/services/LocalisationService.ts +++ b/project/src/services/LocalisationService.ts @@ -1,5 +1,5 @@ -import { I18n } from "i18n"; import path from "node:path"; +import { I18n } from "i18n"; import { inject, injectable } from "tsyringe"; import { ILocaleConfig } from "@spt-aki/models/spt/config/ILocaleConfig"; diff --git a/project/src/utils/App.ts b/project/src/utils/App.ts index 15985000..eac8989d 100644 --- a/project/src/utils/App.ts +++ b/project/src/utils/App.ts @@ -1,5 +1,5 @@ import os from "node:os"; -import { inject, injectable, injectAll } from "tsyringe"; +import { inject, injectAll, injectable } from "tsyringe"; import { OnLoad } from "@spt-aki/di/OnLoad"; import { OnUpdate } from "@spt-aki/di/OnUpdate"; diff --git a/project/src/utils/ImporterUtil.ts b/project/src/utils/ImporterUtil.ts index 7bdb87c1..ee92c21e 100644 --- a/project/src/utils/ImporterUtil.ts +++ b/project/src/utils/ImporterUtil.ts @@ -1,8 +1,8 @@ import { inject, injectable } from "tsyringe"; -import { Queue } from "@spt-aki/utils/collections/queue/Queue"; import { JsonUtil } from "@spt-aki/utils/JsonUtil"; import { VFS } from "@spt-aki/utils/VFS"; +import { Queue } from "@spt-aki/utils/collections/queue/Queue"; /* eslint-disable @typescript-eslint/no-empty-function */ /* eslint-disable @typescript-eslint/brace-style */ diff --git a/project/src/utils/VFS.ts b/project/src/utils/VFS.ts index 0d357769..05198a83 100644 --- a/project/src/utils/VFS.ts +++ b/project/src/utils/VFS.ts @@ -1,12 +1,12 @@ import "reflect-metadata"; import { inject, injectable } from "tsyringe"; -import { IAsyncQueue } from "@spt-aki/models/spt/utils/IAsyncQueue"; -import { writeFileSync } from "atomically"; import crypto from "node:crypto"; import fs from "node:fs"; import path, { resolve } from "node:path"; import { promisify } from "node:util"; +import { IAsyncQueue } from "@spt-aki/models/spt/utils/IAsyncQueue"; +import { writeFileSync } from "atomically"; import lockfile from "proper-lockfile"; @injectable() diff --git a/project/tests/CustomEnvironment.ts b/project/tests/CustomEnvironment.ts index 0307444e..4dd917dd 100644 --- a/project/tests/CustomEnvironment.ts +++ b/project/tests/CustomEnvironment.ts @@ -1,11 +1,11 @@ import "reflect-metadata"; -import { container, DependencyContainer, Lifecycle } from "tsyringe"; +import { DependencyContainer, Lifecycle, container } from "tsyringe"; +import path from "node:path"; import { Container } from "@spt-aki/di/Container"; import { IDatabaseTables } from "@spt-aki/models/spt/server/IDatabaseTables"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; import { ImporterUtil } from "@spt-aki/utils/ImporterUtil"; -import path from "node:path"; import type { Environment } from "vitest"; // Manually mock the logger. diff --git a/project/tests/generators/BotGenerator.test.ts b/project/tests/generators/BotGenerator.test.ts index 7545a69d..a6e781de 100644 --- a/project/tests/generators/BotGenerator.test.ts +++ b/project/tests/generators/BotGenerator.test.ts @@ -1,10 +1,10 @@ -/* eslint-disable @typescript-eslint/naming-convention */ import "reflect-metadata"; -import { BotGenerator } from "@spt-aki/generators/BotGenerator"; -import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { container } from "tsyringe"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { BotGenerator } from "@spt-aki/generators/BotGenerator"; +import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; + describe("BotGenerator", () => { let botGenerator: any; diff --git a/project/tests/services/ItemBaseClassService.test.ts b/project/tests/services/ItemBaseClassService.test.ts index d2dbe193..eee0d619 100644 --- a/project/tests/services/ItemBaseClassService.test.ts +++ b/project/tests/services/ItemBaseClassService.test.ts @@ -1,9 +1,9 @@ -/* eslint-disable @typescript-eslint/naming-convention */ import "reflect-metadata"; -import { ItemBaseClassService } from "@spt-aki/services/ItemBaseClassService"; import { container } from "tsyringe"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ItemBaseClassService } from "@spt-aki/services/ItemBaseClassService"; + describe("ItemBaseClassService", () => { let itemBaseClassService: any; From ce45862e75f340f80065010a1c55d7a6b83ed845 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:51:02 -0500 Subject: [PATCH 36/41] Favours dot object notation whenever possible. --- project/src/controllers/GameController.ts | 20 +++++++++---------- project/src/controllers/HideoutController.ts | 4 ++-- project/src/controllers/QuestController.ts | 2 +- .../controllers/RepeatableQuestController.ts | 2 +- project/src/generators/BotGenerator.ts | 4 ++-- project/src/generators/BotLootGenerator.ts | 6 +++--- project/src/helpers/BotHelper.ts | 8 ++++---- project/src/helpers/DurabilityLimitsHelper.ts | 4 ++-- project/src/helpers/HttpServerHelper.ts | 2 +- project/src/helpers/InventoryHelper.ts | 4 ++-- project/src/models/external/HttpFramework.ts | 10 +++++----- project/src/servers/HttpServer.ts | 2 +- project/src/servers/http/AkiHttpListener.ts | 6 +++--- project/src/services/InsuranceService.ts | 4 ++-- project/src/services/LocaleService.ts | 2 +- project/src/services/LocalisationService.ts | 4 ++-- project/src/services/ProfileFixerService.ts | 12 +++++------ project/src/services/SeasonalEventService.ts | 6 +++--- project/tests/generators/BotGenerator.test.ts | 4 ++-- project/tests/helpers/ItemHelper.test.ts | 6 +++--- 20 files changed, 56 insertions(+), 56 deletions(-) diff --git a/project/src/controllers/GameController.ts b/project/src/controllers/GameController.ts index cef02021..d2684f94 100644 --- a/project/src/controllers/GameController.ts +++ b/project/src/controllers/GameController.ts @@ -651,7 +651,7 @@ export class GameController */ protected fixRoguesSpawningInstantlyOnLighthouse(): void { - const lighthouse = this.databaseServer.getTables().locations["lighthouse"].base; + const lighthouse = this.databaseServer.getTables().locations.lighthouse.base; for (const wave of lighthouse.BossLocationSpawn) { // Find Rogues that spawn instantly @@ -815,9 +815,9 @@ export class GameController // Merge started/success/fail quest assorts into one dictionary const mergedQuestAssorts = { - ...traderData.questassort["started"], - ...traderData.questassort["success"], - ...traderData.questassort["fail"], + ...traderData.questassort.started, + ...traderData.questassort.success, + ...traderData.questassort.fail, }; // Loop over all assorts for trader @@ -850,14 +850,14 @@ export class GameController { const bots = this.databaseServer.getTables().bots.types; - if (bots["bear"]) + if (bots.bear) { - bots["bear"].firstName.push(playerName); + bots.bear.firstName.push(playerName); } - if (bots["usec"]) + if (bots.usec) { - bots["usec"].firstName.push(playerName); + bots.usec.firstName.push(playerName); } } } @@ -868,10 +868,10 @@ export class GameController */ protected checkForAndRemoveUndefinedDialogs(fullProfile: IAkiProfile): void { - const undefinedDialog = fullProfile.dialogues["undefined"]; + const undefinedDialog = fullProfile.dialogues.undefined; if (undefinedDialog) { - delete fullProfile.dialogues["undefined"]; + delete fullProfile.dialogues.undefined; } } diff --git a/project/src/controllers/HideoutController.ts b/project/src/controllers/HideoutController.ts index af7c6b62..9cbe4536 100644 --- a/project/src/controllers/HideoutController.ts +++ b/project/src/controllers/HideoutController.ts @@ -374,7 +374,7 @@ export class HideoutController const itemsToAdd = Object.entries(addItemToHideoutRequest.items).map((kvp) => { - const item = pmcData.Inventory.items.find((invItem) => invItem._id === kvp[1]["id"]); + const item = pmcData.Inventory.items.find((invItem) => invItem._id === kvp[1].id); return { inventoryItem: item, requestedItem: kvp[1], @@ -400,7 +400,7 @@ export class HideoutController { this.logger.error( this.localisationService.getText("hideout-unable_to_find_item_in_inventory", { - itemId: item.requestedItem["id"], + itemId: item.requestedItem.id, area: hideoutArea.type, }), ); diff --git a/project/src/controllers/QuestController.ts b/project/src/controllers/QuestController.ts index 3ce39b96..93de5e56 100644 --- a/project/src/controllers/QuestController.ts +++ b/project/src/controllers/QuestController.ts @@ -410,7 +410,7 @@ export class QuestController ); // For some reason non-en locales don't have repeatable quest ids, fall back to en and grab it if possible - const enLocale = this.databaseServer.getTables().locales.global["en"]; + const enLocale = this.databaseServer.getTables().locales.global.en; questStartedMessageText = enLocale[repeatableQuestProfile.startedMessageText]; if (!questStartedMessageText) diff --git a/project/src/controllers/RepeatableQuestController.ts b/project/src/controllers/RepeatableQuestController.ts index 531fae50..ec9e30bb 100644 --- a/project/src/controllers/RepeatableQuestController.ts +++ b/project/src/controllers/RepeatableQuestController.ts @@ -305,7 +305,7 @@ export class RepeatableQuestController } // Add "any" to pickup quest pool - questPool.pool.Pickup.locations["any"] = ["any"]; + questPool.pool.Pickup.locations.any = ["any"]; const eliminationConfig = this.repeatableQuestHelper.getEliminationConfigByPmcLevel(pmcLevel, repeatableConfig); const targetsConfig = this.repeatableQuestHelper.probabilityObjectArray(eliminationConfig.targets); diff --git a/project/src/generators/BotGenerator.ts b/project/src/generators/BotGenerator.ts index f43bf0b3..c0b19da8 100644 --- a/project/src/generators/BotGenerator.ts +++ b/project/src/generators/BotGenerator.ts @@ -282,8 +282,8 @@ export class BotGenerator } const pmcNames = [ - ...this.databaseServer.getTables().bots.types["usec"].firstName, - ...this.databaseServer.getTables().bots.types["bear"].firstName, + ...this.databaseServer.getTables().bots.types.usec.firstName, + ...this.databaseServer.getTables().bots.types.bear.firstName, ]; return `${name} (${this.randomUtil.getArrayValue(pmcNames)})`; diff --git a/project/src/generators/BotLootGenerator.ts b/project/src/generators/BotLootGenerator.ts index 4125fd5c..1c7af16d 100644 --- a/project/src/generators/BotLootGenerator.ts +++ b/project/src/generators/BotLootGenerator.ts @@ -502,7 +502,7 @@ export class BotLootGenerator { this.logger.warning(this.localisationService.getText("bot-unable_to_find_loot_n_value_for_bot", botRole)); - return this.botConfig.lootNValue["scav"]; + return this.botConfig.lootNValue.scav; } return result; @@ -642,7 +642,7 @@ export class BotLootGenerator { if (isPmc) { - return this.botConfig.itemSpawnLimits["pmc"]; + return this.botConfig.itemSpawnLimits.pmc; } if (this.botConfig.itemSpawnLimits[botRole.toLowerCase()]) @@ -654,7 +654,7 @@ export class BotLootGenerator this.localisationService.getText("bot-unable_to_find_spawn_limits_fallback_to_defaults", botRole), ); - return this.botConfig.itemSpawnLimits["default"]; + return this.botConfig.itemSpawnLimits.default; } /** diff --git a/project/src/helpers/BotHelper.ts b/project/src/helpers/BotHelper.ts index 71f718b7..aaae6ebf 100644 --- a/project/src/helpers/BotHelper.ts +++ b/project/src/helpers/BotHelper.ts @@ -50,10 +50,10 @@ export class BotHelper { if (this.randomUtil.getChance100(this.pmcConfig.chanceSameSideIsHostilePercent)) { - difficultySettings.Mind["CAN_RECEIVE_PLAYER_REQUESTS_BEAR"] = false; - difficultySettings.Mind["CAN_RECEIVE_PLAYER_REQUESTS_USEC"] = false; - difficultySettings.Mind["DEFAULT_USEC_BEHAVIOUR"] = "Attack"; - difficultySettings.Mind["DEFAULT_BEAR_BEHAVIOUR"] = "Attack"; + difficultySettings.Mind.CAN_RECEIVE_PLAYER_REQUESTS_BEAR = false; + difficultySettings.Mind.CAN_RECEIVE_PLAYER_REQUESTS_USEC = false; + difficultySettings.Mind.DEFAULT_USEC_BEHAVIOUR = "Attack"; + difficultySettings.Mind.DEFAULT_BEAR_BEHAVIOUR = "Attack"; } } diff --git a/project/src/helpers/DurabilityLimitsHelper.ts b/project/src/helpers/DurabilityLimitsHelper.ts index f888d30c..84e53e73 100644 --- a/project/src/helpers/DurabilityLimitsHelper.ts +++ b/project/src/helpers/DurabilityLimitsHelper.ts @@ -139,8 +139,8 @@ export class DurabilityLimitsHelper protected generateMaxPmcArmorDurability(itemMaxDurability: number): number { - const lowestMaxPercent = this.botConfig.durability["pmc"].armor.lowestMaxPercent; - const highestMaxPercent = this.botConfig.durability["pmc"].armor.highestMaxPercent; + const lowestMaxPercent = this.botConfig.durability.pmc.armor.lowestMaxPercent; + const highestMaxPercent = this.botConfig.durability.pmc.armor.highestMaxPercent; const multiplier = this.randomUtil.getInt(lowestMaxPercent, highestMaxPercent); return itemMaxDurability * (multiplier / 100); diff --git a/project/src/helpers/HttpServerHelper.ts b/project/src/helpers/HttpServerHelper.ts index e6db7dee..65b38bcc 100644 --- a/project/src/helpers/HttpServerHelper.ts +++ b/project/src/helpers/HttpServerHelper.ts @@ -60,7 +60,7 @@ export class HttpServerHelper public sendTextJson(resp: any, output: any): void { // eslint-disable-next-line @typescript-eslint/naming-convention - resp.writeHead(200, "OK", {"Content-Type": this.mime["json"]}); + resp.writeHead(200, "OK", {"Content-Type": this.mime.json}); resp.end(output); } } diff --git a/project/src/helpers/InventoryHelper.ts b/project/src/helpers/InventoryHelper.ts index 793a80b1..724e65fb 100644 --- a/project/src/helpers/InventoryHelper.ts +++ b/project/src/helpers/InventoryHelper.ts @@ -325,9 +325,9 @@ export class InventoryHelper const itemLocation = {}; // Item already has location property, use it - if (itemLib[tmpKey]["location"] !== undefined) + if (itemLib[tmpKey].location !== undefined) { - itemLocation["location"] = itemLib[tmpKey]["location"]; + itemLocation.location = itemLib[tmpKey].location; } output.profileChanges[sessionID].items.new.push({ diff --git a/project/src/models/external/HttpFramework.ts b/project/src/models/external/HttpFramework.ts index 36b69531..fa5fc86a 100644 --- a/project/src/models/external/HttpFramework.ts +++ b/project/src/models/external/HttpFramework.ts @@ -28,7 +28,7 @@ export const Listen = (basePath: string) => this.handlers = {}; // Retrieve all handlers - const handlersArray = Base.prototype["handlers"]; + const handlersArray = Base.prototype.handlers; if (!handlersArray) { return; @@ -53,7 +53,7 @@ export const Listen = (basePath: string) => } // Cleanup the handlers list - Base.prototype["handlers"] = []; + Base.prototype.handlers = []; } // The canHandle method is used to check if the Listener handles a request @@ -105,13 +105,13 @@ const createHttpDecorator = (httpMethod: HttpMethods) => return (target: any, propertyKey: string) => { // If the handlers array has not been initialized yet - if (!target["handlers"]) + if (!target.handlers) { - target["handlers"] = []; + target.handlers = []; } // Flag the method as a HTTP handler - target["handlers"].push({ + target.handlers.push({ handlerName: propertyKey, path, httpMethod, diff --git a/project/src/servers/HttpServer.ts b/project/src/servers/HttpServer.ts index ae163092..9aabff8c 100644 --- a/project/src/servers/HttpServer.ts +++ b/project/src/servers/HttpServer.ts @@ -74,7 +74,7 @@ export class HttpServer protected handleRequest(req: IncomingMessage, resp: ServerResponse): void { // Pull sessionId out of cookies and store inside app context - const sessionId = this.getCookies(req)["PHPSESSID"]; + const sessionId = this.getCookies(req).PHPSESSID; this.applicationContext.addValue(ContextVariableType.SESSION_ID, sessionId); // http.json logRequests boolean option to allow the user/server to choose to not log requests diff --git a/project/src/servers/http/AkiHttpListener.ts b/project/src/servers/http/AkiHttpListener.ts index ef795e91..cd481fb6 100644 --- a/project/src/servers/http/AkiHttpListener.ts +++ b/project/src/servers/http/AkiHttpListener.ts @@ -64,10 +64,10 @@ export class AkiHttpListener implements IHttpListener // determine if the payload is compressed. All PUT requests are, and POST requests without // debug = 1 are as well. This should be fixed. // let compressed = req.headers["content-encoding"] === "deflate"; - const compressed = req.method === "PUT" || req.headers["debug"] !== "1"; + const compressed = req.method === "PUT" || req.headers.debug !== "1"; const value = compressed ? zlib.inflateSync(buffer) : buffer; - if (req.headers["debug"] === "1") + if (req.headers.debug === "1") { this.logger.debug(value.toString(), true); } @@ -107,7 +107,7 @@ export class AkiHttpListener implements IHttpListener let handled = false; // Check if this is a debug request, if so just send the raw response without transformation - if (req.headers["debug"] === "1") + if (req.headers.debug === "1") { this.sendJson(resp, output, sessionID); } diff --git a/project/src/services/InsuranceService.ts b/project/src/services/InsuranceService.ts index 02cc0ea4..5f0f1724 100644 --- a/project/src/services/InsuranceService.ts +++ b/project/src/services/InsuranceService.ts @@ -148,8 +148,8 @@ export class InsuranceService { const dialogueTemplates = this.databaseServer.getTables().traders[Traders.PRAPOR].dialogue; // todo: get trader id instead of hard coded prapor const randomResponseId = locationName?.toLowerCase() === "laboratory" ? - this.randomUtil.getArrayValue(dialogueTemplates["insuranceFailedLabs"]) : - this.randomUtil.getArrayValue(dialogueTemplates["insuranceFailed"]); + this.randomUtil.getArrayValue(dialogueTemplates.insuranceFailedLabs) : + this.randomUtil.getArrayValue(dialogueTemplates.insuranceFailed); this.mailSendService.sendLocalisedNpcMessageToPlayer( sessionId, diff --git a/project/src/services/LocaleService.ts b/project/src/services/LocaleService.ts index 25bf76d7..c9bc8263 100644 --- a/project/src/services/LocaleService.ts +++ b/project/src/services/LocaleService.ts @@ -39,7 +39,7 @@ export class LocaleService `Unable to find desired locale file using locale ${this.getDesiredGameLocale()} from config/locale.json, falling back to 'en'`, ); - return this.databaseServer.getTables().locales.global["en"]; + return this.databaseServer.getTables().locales.global.en; } /** diff --git a/project/src/services/LocalisationService.ts b/project/src/services/LocalisationService.ts index 6a75cb7f..df610e64 100644 --- a/project/src/services/LocalisationService.ts +++ b/project/src/services/LocalisationService.ts @@ -59,7 +59,7 @@ export class LocalisationService */ public getKeys(): string[] { - return Object.keys(this.databaseServer.getTables().locales.server["en"]); + return Object.keys(this.databaseServer.getTables().locales.server.en); } /** @@ -69,7 +69,7 @@ export class LocalisationService */ public getRandomTextThatMatchesPartialKey(partialKey: string): string { - const filteredKeys = Object.keys(this.databaseServer.getTables().locales.server["en"]).filter((x) => + const filteredKeys = Object.keys(this.databaseServer.getTables().locales.server.en).filter((x) => x.startsWith(partialKey) ); const chosenKey = this.randomUtil.getArrayValue(filteredKeys); diff --git a/project/src/services/ProfileFixerService.ts b/project/src/services/ProfileFixerService.ts index 690c4b46..9d672128 100644 --- a/project/src/services/ProfileFixerService.ts +++ b/project/src/services/ProfileFixerService.ts @@ -469,9 +469,9 @@ export class ProfileFixerService protected addMissingBonusesProperty(pmcProfile: IPmcData): void { - if (typeof pmcProfile["Bonuses"] === "undefined") + if (typeof pmcProfile.Bonuses === "undefined") { - pmcProfile["Bonuses"] = []; + pmcProfile.Bonuses = []; this.logger.debug("Missing Bonuses property added to profile"); } } @@ -1024,7 +1024,7 @@ export class ProfileFixerService */ public addMissingHideoutAreasToProfile(fullProfile: IAkiProfile): void { - const pmcProfile = fullProfile.characters["pmc"]; + const pmcProfile = fullProfile.characters.pmc; // No profile, probably new account being created if (!pmcProfile?.Hideout) { @@ -1163,11 +1163,11 @@ export class ProfileFixerService */ protected migrateImprovements(pmcProfile: IPmcData): void { - if (pmcProfile.Hideout["Improvements"]) + if (pmcProfile.Hideout.Improvements) { // Correct name is `Improvement` - pmcProfile.Hideout.Improvement = this.jsonUtil.clone(pmcProfile.Hideout["Improvements"]); - delete pmcProfile.Hideout["Improvements"]; + pmcProfile.Hideout.Improvement = this.jsonUtil.clone(pmcProfile.Hideout.Improvements); + delete pmcProfile.Hideout.Improvements; this.logger.success("Successfully migrated hideout Improvements data to new location, deleted old data"); } } diff --git a/project/src/services/SeasonalEventService.ts b/project/src/services/SeasonalEventService.ts index 51d2a73d..6e97737d 100644 --- a/project/src/services/SeasonalEventService.ts +++ b/project/src/services/SeasonalEventService.ts @@ -418,10 +418,10 @@ export class SeasonalEventService */ protected addLootItemsToGifterDropItemsList(): void { - const gifterBot = this.databaseServer.getTables().bots.types["gifter"]; + const gifterBot = this.databaseServer.getTables().bots.types.gifter; for (const difficulty in gifterBot.difficulty) { - gifterBot.difficulty[difficulty].Patrol["ITEMS_TO_DROP"] = gifterBot.inventory.items.Backpack.join(", "); + gifterBot.difficulty[difficulty].Patrol.ITEMS_TO_DROP = gifterBot.inventory.items.Backpack.join(", "); } } @@ -471,7 +471,7 @@ export class SeasonalEventService protected addPumpkinsToScavBackpacks(): void { - const assaultBackpack = this.databaseServer.getTables().bots.types["assault"].inventory.items.Backpack; + const assaultBackpack = this.databaseServer.getTables().bots.types.assault.inventory.items.Backpack; assaultBackpack.push("634959225289190e5e773b3b"); assaultBackpack.push("634959225289190e5e773b3b"); assaultBackpack.push("634959225289190e5e773b3b"); diff --git a/project/tests/generators/BotGenerator.test.ts b/project/tests/generators/BotGenerator.test.ts index a6e781de..2072430e 100644 --- a/project/tests/generators/BotGenerator.test.ts +++ b/project/tests/generators/BotGenerator.test.ts @@ -161,8 +161,8 @@ describe("BotGenerator", () => it("should return name `test (usec)` for player scav bot", () => { botGenerator.botConfig.chanceAssaultScavHasPlayerScavName = 100; - botGenerator.databaseServer.getTables().bots.types["usec"].firstName = ["usec"]; - botGenerator.databaseServer.getTables().bots.types["bear"].firstName = []; + botGenerator.databaseServer.getTables().bots.types.usec.firstName = ["usec"]; + botGenerator.databaseServer.getTables().bots.types.bear.firstName = []; const mockPlayerProfile = { Info: { diff --git a/project/tests/helpers/ItemHelper.test.ts b/project/tests/helpers/ItemHelper.test.ts index e86ae492..ba98a991 100644 --- a/project/tests/helpers/ItemHelper.test.ts +++ b/project/tests/helpers/ItemHelper.test.ts @@ -256,7 +256,7 @@ describe("ItemHelper", () => const fixedItem = itemHelper.fixItemStackCount(initialItem); expect(fixedItem.upd).toBeDefined(); - expect(fixedItem.upd!.StackObjectsCount).toBe(1); + expect(fixedItem.upd?.StackObjectsCount).toBe(1); }); it("should set upd.StackObjectsCount to 1 if upd.StackObjectsCount is undefined", () => @@ -269,7 +269,7 @@ describe("ItemHelper", () => const fixedItem = itemHelper.fixItemStackCount(initialItem); expect(fixedItem.upd).toBeDefined(); - expect(fixedItem.upd!.StackObjectsCount).toBe(1); + expect(fixedItem.upd?.StackObjectsCount).toBe(1); }); it("should not change upd.StackObjectsCount if it is already defined", () => @@ -284,7 +284,7 @@ describe("ItemHelper", () => const fixedItem = itemHelper.fixItemStackCount(initialItem); expect(fixedItem.upd).toBeDefined(); - expect(fixedItem.upd!.StackObjectsCount).toBe(5); + expect(fixedItem.upd?.StackObjectsCount).toBe(5); }); }); From 11b5c76512917dbab3b6e6e2563f14a3d83f68cb Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 11:51:52 -0500 Subject: [PATCH 37/41] Favours single line variable declarations. --- .../tests/controllers/InsuranceController.test.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/project/tests/controllers/InsuranceController.test.ts b/project/tests/controllers/InsuranceController.test.ts index 70326f3e..2c064266 100644 --- a/project/tests/controllers/InsuranceController.test.ts +++ b/project/tests/controllers/InsuranceController.test.ts @@ -1438,13 +1438,13 @@ describe("InsuranceController", () => describe("insure", () => { - let pmcData: any, - body: any, - sessionId: string, - insuranceController: any, - mockGetPremium: any, - mockPayMoney: any, - mockGetOutput: any; + let pmcData: any; + let body: any; + let sessionId: string; + let insuranceController: any; + let mockGetPremium: any; + let mockPayMoney: any; + let mockGetOutput: any; beforeEach(() => { From 2b826f8b1e5fc3c19a8f0d3831fb0fbab322baf7 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 12:00:49 -0500 Subject: [PATCH 38/41] Conditional Code Adjustments Re:Biome When multiple falsey conditions are being checked Biome recommends to check for all the truthy conditions negated. Logic remains untouched, while only using one negation. Apparently easier to comprehend. --- project/src/generators/BotEquipmentModGenerator.ts | 6 ++---- project/src/generators/LocationGenerator.ts | 4 ++-- project/src/generators/LootGenerator.ts | 2 +- project/src/services/ProfileFixerService.ts | 2 +- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/project/src/generators/BotEquipmentModGenerator.ts b/project/src/generators/BotEquipmentModGenerator.ts index d572694c..c5a1740a 100644 --- a/project/src/generators/BotEquipmentModGenerator.ts +++ b/project/src/generators/BotEquipmentModGenerator.ts @@ -199,11 +199,9 @@ export class BotEquipmentModGenerator const compatibleModsPool = modPool[parentTemplate._id]; // Null guard against bad input weapon - // biome-ignore lint/complexity/useSimplifiedLogicExpression: if ( - !parentTemplate._props.Slots.length && - !parentTemplate._props.Cartridges?.length && - !parentTemplate._props.Chambers?.length + !((parentTemplate._props.Slots.length || parentTemplate._props.Cartridges?.length) || + parentTemplate._props.Chambers?.length) ) { this.logger.error( diff --git a/project/src/generators/LocationGenerator.ts b/project/src/generators/LocationGenerator.ts index bdb1bd8e..93e9554a 100644 --- a/project/src/generators/LocationGenerator.ts +++ b/project/src/generators/LocationGenerator.ts @@ -133,8 +133,8 @@ export class LocationGenerator // randomisation is turned off globally or just turned off for this map if ( - !this.locationConfig.containerRandomisationSettings.enabled || - !this.locationConfig.containerRandomisationSettings.maps[locationId] + !(this.locationConfig.containerRandomisationSettings.enabled && + this.locationConfig.containerRandomisationSettings.maps[locationId]) ) { this.logger.debug( diff --git a/project/src/generators/LootGenerator.ts b/project/src/generators/LootGenerator.ts index 7658f480..3f5babb6 100644 --- a/project/src/generators/LootGenerator.ts +++ b/project/src/generators/LootGenerator.ts @@ -410,7 +410,7 @@ export class LootGenerator x._parent === rewardTypeId && x._type.toLowerCase() === "item" && !this.itemFilterService.isItemBlacklisted(x._id) && - (!containerSettings.allowBossItems && !this.itemFilterService.isBossItem(x._id)) && + (!(containerSettings.allowBossItems || this.itemFilterService.isBossItem(x._id))) && !x._props.QuestItem ); diff --git a/project/src/services/ProfileFixerService.ts b/project/src/services/ProfileFixerService.ts index 9d672128..3fdb0212 100644 --- a/project/src/services/ProfileFixerService.ts +++ b/project/src/services/ProfileFixerService.ts @@ -424,7 +424,7 @@ export class ProfileFixerService const existsInQuests = pmcProfile.Quests.some((q) => q.qid === backendCounter.qid); // if BackendCounter's quest is neither in activeQuests nor Quests it's stale - if (!existsInActiveRepeatableQuests && !existsInQuests) + if (!(existsInActiveRepeatableQuests || existsInQuests)) { counterKeysToRemove.push(key); } From 7533d33358b987fe26a61e57112986b9310ec061 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 12:29:16 -0500 Subject: [PATCH 39/41] Formatting Change - Operator positions are now at the start of the next line (for multi-line statements). --- project/dprint.json | 2 +- project/src/callbacks/ItemEventCallbacks.ts | 7 +- project/src/controllers/BotController.ts | 12 +-- project/src/controllers/GameController.ts | 10 +-- project/src/controllers/HideoutController.ts | 30 ++++---- project/src/controllers/InraidController.ts | 4 +- .../src/controllers/InsuranceController.ts | 6 +- .../src/controllers/InventoryController.ts | 12 +-- project/src/controllers/QuestController.ts | 36 ++++----- project/src/controllers/RagfairController.ts | 45 ++++++----- .../controllers/RepeatableQuestController.ts | 21 +++--- project/src/controllers/TradeController.ts | 8 +- .../generators/BotEquipmentModGenerator.ts | 37 ++++----- project/src/generators/BotGenerator.ts | 12 +-- .../src/generators/BotInventoryGenerator.ts | 27 ++++--- project/src/generators/BotLootGenerator.ts | 12 +-- project/src/generators/BotWeaponGenerator.ts | 10 +-- .../generators/FenceBaseAssortGenerator.ts | 4 +- project/src/generators/LocationGenerator.ts | 44 +++++------ project/src/generators/LootGenerator.ts | 28 +++---- project/src/generators/PMCLootGenerator.ts | 30 ++++---- project/src/generators/PlayerScavGenerator.ts | 6 +- .../src/generators/RagfairAssortGenerator.ts | 10 +-- .../src/generators/RagfairOfferGenerator.ts | 56 +++++++------- .../generators/RepeatableQuestGenerator.ts | 52 ++++++------- .../src/generators/ScavCaseRewardGenerator.ts | 14 ++-- project/src/generators/WeatherGenerator.ts | 6 +- .../ExternalInventoryMagGen.ts | 6 +- project/src/helpers/BotDifficultyHelper.ts | 18 ++--- project/src/helpers/BotGeneratorHelper.ts | 24 +++--- project/src/helpers/BotHelper.ts | 16 ++-- project/src/helpers/DialogueHelper.ts | 6 +- project/src/helpers/DurabilityLimitsHelper.ts | 12 +-- project/src/helpers/HealthHelper.ts | 8 +- project/src/helpers/HideoutHelper.ts | 75 +++++++++---------- project/src/helpers/InRaidHelper.ts | 8 +- project/src/helpers/InventoryHelper.ts | 58 +++++++------- project/src/helpers/ItemHelper.ts | 60 +++++++-------- project/src/helpers/NotificationSendHelper.ts | 6 +- project/src/helpers/ProfileHelper.ts | 4 +- project/src/helpers/QuestHelper.ts | 44 +++++------ project/src/helpers/RagfairHelper.ts | 6 +- project/src/helpers/RagfairOfferHelper.ts | 8 +- project/src/helpers/RagfairSellHelper.ts | 16 ++-- project/src/helpers/RagfairServerHelper.ts | 8 +- project/src/helpers/RagfairSortHelper.ts | 10 +-- project/src/helpers/RepairHelper.ts | 32 ++++---- project/src/helpers/TraderHelper.ts | 26 +++---- project/src/loaders/ModTypeCheck.ts | 12 +-- project/src/loaders/PreAkiModLoader.ts | 4 +- project/src/models/external/HttpFramework.ts | 4 +- project/src/servers/ConfigServer.ts | 6 +- project/src/servers/WebSocketServer.ts | 6 +- project/src/servers/http/AkiHttpListener.ts | 6 +- .../src/services/BotEquipmentFilterService.ts | 18 ++--- project/src/services/BotLootCacheService.ts | 74 +++++++++--------- .../src/services/BotWeaponModLimitService.ts | 16 ++-- project/src/services/FenceService.ts | 42 +++++------ project/src/services/InsuranceService.ts | 12 +-- project/src/services/LocalisationService.ts | 6 +- project/src/services/MailSendService.ts | 10 +-- project/src/services/PaymentService.ts | 4 +- .../src/services/PmcChatResponseService.ts | 24 +++--- project/src/services/ProfileFixerService.ts | 58 +++++++------- .../src/services/RagfairCategoriesService.ts | 6 +- project/src/services/RagfairPriceService.ts | 6 +- project/src/services/RagfairTaxService.ts | 26 +++---- project/src/services/RepairService.ts | 34 ++++----- project/src/services/SeasonalEventService.ts | 4 +- project/src/services/mod/CustomItemService.ts | 6 +- project/src/utils/DatabaseImporter.ts | 12 +-- project/src/utils/HttpFileUtil.ts | 4 +- project/src/utils/Watermark.ts | 12 +-- 73 files changed, 704 insertions(+), 700 deletions(-) diff --git a/project/dprint.json b/project/dprint.json index 9b3e865d..60c34ce2 100644 --- a/project/dprint.json +++ b/project/dprint.json @@ -13,7 +13,7 @@ "singleBodyPosition": "maintain", "nextControlFlowPosition": "nextLine", "trailingCommas": "onlyMultiLine", - "operatorPosition": "sameLine", + "operatorPosition": "nextLine", "preferHanging": false, "preferSingleLine": false, "arrowFunction.useParentheses": "force", diff --git a/project/src/callbacks/ItemEventCallbacks.ts b/project/src/callbacks/ItemEventCallbacks.ts index 41b16424..ad396ff9 100644 --- a/project/src/callbacks/ItemEventCallbacks.ts +++ b/project/src/callbacks/ItemEventCallbacks.ts @@ -24,14 +24,13 @@ export class ItemEventCallbacks ): IGetBodyResponseData { const eventResponse = this.itemEventRouter.handleEvents(info, sessionID); - const result = (eventResponse.warnings.length > 0) ? - this.httpResponse.getBody( + const result = (eventResponse.warnings.length > 0) + ? this.httpResponse.getBody( eventResponse, this.getErrorCode(eventResponse.warnings), eventResponse.warnings[0].errmsg, ) // TODO: map 228 to its enum value - : - this.httpResponse.getBody(eventResponse); + : this.httpResponse.getBody(eventResponse); return result; } diff --git a/project/src/controllers/BotController.ts b/project/src/controllers/BotController.ts index c10640b4..98753c00 100644 --- a/project/src/controllers/BotController.ts +++ b/project/src/controllers/BotController.ts @@ -58,9 +58,9 @@ export class BotController public getBotPresetGenerationLimit(type: string): number { const value = this.botConfig.presetBatch[ - (type === "assaultGroup") ? - "assault" : - type + (type === "assaultGroup") + ? "assault" + : type ]; if (!value) @@ -275,9 +275,9 @@ export class BotController this.logger.warning(this.localisationService.getText("bot-missing_saved_match_info")); } - const mapName = raidConfig ? - raidConfig.location : - defaultMapCapId; + const mapName = raidConfig + ? raidConfig.location + : defaultMapCapId; let botCap = this.botConfig.maxBotCap[mapName.toLowerCase()]; if (!botCap) diff --git a/project/src/controllers/GameController.ts b/project/src/controllers/GameController.ts index d2684f94..ddf296ff 100644 --- a/project/src/controllers/GameController.ts +++ b/project/src/controllers/GameController.ts @@ -704,8 +704,8 @@ export class GameController { // Wave has size that makes it candidate for splitting if ( - wave.slots_max - wave.slots_min >= - this.locationConfig.splitWaveIntoSingleSpawnsSettings.waveSizeThreshold + wave.slots_max - wave.slots_min + >= this.locationConfig.splitWaveIntoSingleSpawnsSettings.waveSizeThreshold ) { // Get count of bots to be spawned in wave @@ -777,9 +777,9 @@ export class GameController const modDetails = activeMods[modKey]; if ( fullProfile.aki.mods.some((x) => - x.author === modDetails.author && - x.name === modDetails.name && - x.version === modDetails.version + x.author === modDetails.author + && x.name === modDetails.name + && x.version === modDetails.version ) ) { diff --git a/project/src/controllers/HideoutController.ts b/project/src/controllers/HideoutController.ts index 9cbe4536..449b1865 100644 --- a/project/src/controllers/HideoutController.ts +++ b/project/src/controllers/HideoutController.ts @@ -111,10 +111,10 @@ export class HideoutController } if ( - this.paymentHelper.isMoneyTpl(item.inventoryItem._tpl) && - item.inventoryItem.upd && - item.inventoryItem.upd.StackObjectsCount && - item.inventoryItem.upd.StackObjectsCount > item.requestedItem.count + this.paymentHelper.isMoneyTpl(item.inventoryItem._tpl) + && item.inventoryItem.upd + && item.inventoryItem.upd.StackObjectsCount + && item.inventoryItem.upd.StackObjectsCount > item.requestedItem.count ) { item.inventoryItem.upd.StackObjectsCount -= item.requestedItem.count; @@ -220,8 +220,8 @@ export class HideoutController // Upgrading water collector / med station if ( - profileHideoutArea.type === HideoutAreas.WATER_COLLECTOR || - profileHideoutArea.type === HideoutAreas.MEDSTATION + profileHideoutArea.type === HideoutAreas.WATER_COLLECTOR + || profileHideoutArea.type === HideoutAreas.MEDSTATION ) { this.checkAndUpgradeWall(pmcData); @@ -632,8 +632,8 @@ export class HideoutController } if ( - inventoryItem.upd?.StackObjectsCount && - inventoryItem.upd.StackObjectsCount > requestedItem.count + inventoryItem.upd?.StackObjectsCount + && inventoryItem.upd.StackObjectsCount > requestedItem.count ) { inventoryItem.upd.StackObjectsCount -= requestedItem.count; @@ -957,9 +957,9 @@ export class HideoutController { id = this.presetHelper.getDefaultPreset(id)._id; } - const numOfItems = !x.upd?.StackObjectsCount ? - 1 : - x.upd.StackObjectsCount; + const numOfItems = !x.upd?.StackObjectsCount + ? 1 + : x.upd.StackObjectsCount; return {item_id: id, count: numOfItems}; }, @@ -1112,10 +1112,10 @@ export class HideoutController } if ( - this.paymentHelper.isMoneyTpl(item.inventoryItem._tpl) && - item.inventoryItem.upd && - item.inventoryItem.upd.StackObjectsCount && - item.inventoryItem.upd.StackObjectsCount > item.requestedItem.count + this.paymentHelper.isMoneyTpl(item.inventoryItem._tpl) + && item.inventoryItem.upd + && item.inventoryItem.upd.StackObjectsCount + && item.inventoryItem.upd.StackObjectsCount > item.requestedItem.count ) { item.inventoryItem.upd.StackObjectsCount -= item.requestedItem.count; diff --git a/project/src/controllers/InraidController.ts b/project/src/controllers/InraidController.ts index 682134e3..35da378e 100644 --- a/project/src/controllers/InraidController.ts +++ b/project/src/controllers/InraidController.ts @@ -332,8 +332,8 @@ export class InraidController // Post-raid status is enum word e.g. `Started` but pmc quest status is number e.g. 2 // Status values mismatch or statusTimers counts mismatch if ( - quest.status !== QuestStatus[pmcQuest.status] || - quest.statusTimers.length !== pmcQuest.statusTimers.length + quest.status !== QuestStatus[pmcQuest.status] + || quest.statusTimers.length !== pmcQuest.statusTimers.length ) { this.logger.warning( diff --git a/project/src/controllers/InsuranceController.ts b/project/src/controllers/InsuranceController.ts index f27fc583..b2d2720c 100644 --- a/project/src/controllers/InsuranceController.ts +++ b/project/src/controllers/InsuranceController.ts @@ -164,9 +164,9 @@ export class InsuranceController { const profile = this.saveServer.getProfile(sessionID); profile.insurance = profile.insurance.filter((insurance) => - insurance.messageContent.systemData.date !== packageInfo.date || - insurance.messageContent.systemData.time !== packageInfo.time || - insurance.messageContent.systemData.location !== packageInfo.location + insurance.messageContent.systemData.date !== packageInfo.date + || insurance.messageContent.systemData.time !== packageInfo.time + || insurance.messageContent.systemData.location !== packageInfo.location ); this.logger.debug( diff --git a/project/src/controllers/InventoryController.ts b/project/src/controllers/InventoryController.ts index 084787b1..e921f893 100644 --- a/project/src/controllers/InventoryController.ts +++ b/project/src/controllers/InventoryController.ts @@ -168,9 +168,9 @@ export class InventoryController ); } - const profileToRemoveItemFrom = (!body.fromOwner || body.fromOwner.id === pmcData._id) ? - pmcData : - this.profileHelper.getFullProfile(sessionID).characters.scav; + const profileToRemoveItemFrom = (!body.fromOwner || body.fromOwner.id === pmcData._id) + ? pmcData + : this.profileHelper.getFullProfile(sessionID).characters.scav; return this.inventoryHelper.removeItem( profileToRemoveItemFrom, @@ -459,9 +459,9 @@ export class InventoryController { // Fix for folding weapons while on they're in the Scav inventory if ( - body.fromOwner && - body.fromOwner.type === "Profile" && - body.fromOwner.id !== pmcData._id + body.fromOwner + && body.fromOwner.type === "Profile" + && body.fromOwner.id !== pmcData._id ) { pmcData = this.profileHelper.getScavProfile(sessionID); diff --git a/project/src/controllers/QuestController.ts b/project/src/controllers/QuestController.ts index 93de5e56..bf57a1d8 100644 --- a/project/src/controllers/QuestController.ts +++ b/project/src/controllers/QuestController.ts @@ -230,8 +230,8 @@ export class QuestController // Not christmas + quest is for christmas if ( - !isChristmasEventActive && - this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.CHRISTMAS) + !isChristmasEventActive + && this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.CHRISTMAS) ) { return false; @@ -239,8 +239,8 @@ export class QuestController // Not halloween + quest is for halloween if ( - !isHalloweenEventActive && - this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.HALLOWEEN) + !isHalloweenEventActive + && this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.HALLOWEEN) ) { return false; @@ -248,8 +248,8 @@ export class QuestController // Should non-season event quests be shown to player if ( - !this.questConfig.showNonSeasonalEventQuests && - this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.NONE) + !this.questConfig.showNonSeasonalEventQuests + && this.seasonalEventService.isQuestRelatedToEvent(questId, SeasonalEventType.NONE) ) { return false; @@ -381,8 +381,8 @@ export class QuestController // Some scav quests need to be added to scav profile for them to show up in-raid if ( - repeatableQuestProfile.side === "Scav" && - ["PickUp", "Exploration", "Elimination"].includes(repeatableQuestProfile.type) + repeatableQuestProfile.side === "Scav" + && ["PickUp", "Exploration", "Elimination"].includes(repeatableQuestProfile.type) ) { const fullProfile = this.profileHelper.getFullProfile(sessionID); @@ -448,8 +448,10 @@ export class QuestController const change = {}; change[repeatableQuestProfile._id] = repeatableSettings.changeRequirement[repeatableQuestProfile._id]; const responseData: IPmcDataRepeatableQuest = { - id: repeatableSettings.id ?? - this.questConfig.repeatableQuests.find((x) => x.name === repeatableQuestProfile.sptRepatableGroupName) + id: repeatableSettings.id + ?? this.questConfig.repeatableQuests.find((x) => + x.name === repeatableQuestProfile.sptRepatableGroupName + ) .id, name: repeatableSettings.name, endTime: repeatableSettings.endTime, @@ -666,8 +668,8 @@ export class QuestController if (nextQuestWaitCondition) { // Now + wait time - const availableAfterTimestamp = this.timeUtil.getTimestamp() + - nextQuestWaitCondition._props.availableAfter; + const availableAfterTimestamp = this.timeUtil.getTimestamp() + + nextQuestWaitCondition._props.availableAfter; // Update quest in profile with status of AvailableAfter const existingQuestInProfile = pmcData.Quests.find((x) => x.qid === quest._id); @@ -787,17 +789,17 @@ export class QuestController for (const condition of quest.conditions.AvailableForFinish) { if ( - condition._props.id === handoverQuestRequest.conditionId && - handoverQuestTypes.includes(condition._parent) + condition._props.id === handoverQuestRequest.conditionId + && handoverQuestTypes.includes(condition._parent) ) { handedInCount = Number.parseInt(condition._props.value); isItemHandoverQuest = condition._parent === handoverQuestTypes[0]; handoverRequirements = condition; - const profileCounter = (handoverQuestRequest.conditionId in pmcData.BackendCounters) ? - pmcData.BackendCounters[handoverQuestRequest.conditionId].value : - 0; + const profileCounter = (handoverQuestRequest.conditionId in pmcData.BackendCounters) + ? pmcData.BackendCounters[handoverQuestRequest.conditionId].value + : 0; handedInCount -= profileCounter; if (handedInCount <= 0) diff --git a/project/src/controllers/RagfairController.ts b/project/src/controllers/RagfairController.ts index 313c30bb..74188ccc 100644 --- a/project/src/controllers/RagfairController.ts +++ b/project/src/controllers/RagfairController.ts @@ -256,9 +256,9 @@ export class RagfairController const assortData = traderAssorts.find((x) => x._id === assortId); // Use value stored in profile, otherwise use value directly from in-memory trader assort data - offer.buyRestrictionCurrent = profile.traderPurchases[offer.user.id][assortId] ? - profile.traderPurchases[offer.user.id][assortId].count : - assortData.upd.BuyRestrictionCurrent; + offer.buyRestrictionCurrent = profile.traderPurchases[offer.user.id][assortId] + ? profile.traderPurchases[offer.user.id][assortId].count + : assortData.upd.BuyRestrictionCurrent; offer.buyRestrictionMax = assortData.upd.BuyRestrictionMax; } @@ -397,22 +397,21 @@ export class RagfairController ); const rootItem = offer.items[0]; const qualityMultiplier = this.itemHelper.getItemQualityModifier(rootItem); - const averageOfferPrice = this.ragfairPriceService.getFleaPriceForItem(rootItem._tpl) * - rootItem.upd.StackObjectsCount * qualityMultiplier; - const itemStackCount = (offerRequest.sellInOnePiece) ? - 1 : - rootItem.upd.StackObjectsCount; + const averageOfferPrice = this.ragfairPriceService.getFleaPriceForItem(rootItem._tpl) + * rootItem.upd.StackObjectsCount * qualityMultiplier; + const itemStackCount = (offerRequest.sellInOnePiece) + ? 1 + : rootItem.upd.StackObjectsCount; // Get averaged price of a single item being listed - const averageSingleItemPrice = (offerRequest.sellInOnePiece) ? - averageOfferPrice / rootItem.upd.StackObjectsCount // Packs are a single offer made of many items - : - averageOfferPrice / itemStackCount; + const averageSingleItemPrice = (offerRequest.sellInOnePiece) + ? averageOfferPrice / rootItem.upd.StackObjectsCount // Packs are a single offer made of many items + : averageOfferPrice / itemStackCount; // Get averaged price of listing - const averagePlayerListedPriceInRub = (offerRequest.sellInOnePiece) ? - playerListedPriceInRub / rootItem.upd.StackObjectsCount : - playerListedPriceInRub; + const averagePlayerListedPriceInRub = (offerRequest.sellInOnePiece) + ? playerListedPriceInRub / rootItem.upd.StackObjectsCount + : playerListedPriceInRub; // Packs are reduced to the average price of a single item in the pack vs the averaged single price of an item const sellChancePercent = this.ragfairSellHelper.calculateSellChance( @@ -475,9 +474,9 @@ export class RagfairController { // Get tax from cache hydrated earlier by client, if that's missing fall back to server calculation (inaccurate) const storedClientTaxValue = this.ragfairTaxService.getStoredClientOfferTaxValueById(offerRequest.items[0]); - const tax = storedClientTaxValue ? - storedClientTaxValue.fee : - this.ragfairTaxService.calculateTax( + const tax = storedClientTaxValue + ? storedClientTaxValue.fee + : this.ragfairTaxService.calculateTax( rootItem, pmcData, requirementsPriceInRub, @@ -549,8 +548,8 @@ export class RagfairController } else { - requirementsPriceInRub += this.ragfairPriceService.getDynamicPriceForItem(requestedItemTpl) * - item.count; + requirementsPriceInRub += this.ragfairPriceService.getDynamicPriceForItem(requestedItemTpl) + * item.count; } } @@ -719,9 +718,9 @@ export class RagfairController // MOD: Pay flea market fee if (this.ragfairConfig.sell.fees) { - const count = offers[index].sellInOnePiece ? - 1 : - offers[index].items.reduce((sum, item) => sum += item.upd.StackObjectsCount, 0); + const count = offers[index].sellInOnePiece + ? 1 + : offers[index].items.reduce((sum, item) => sum += item.upd.StackObjectsCount, 0); const tax = this.ragfairTaxService.calculateTax( offers[index].items[0], this.profileHelper.getPmcProfile(sessionID), diff --git a/project/src/controllers/RepeatableQuestController.ts b/project/src/controllers/RepeatableQuestController.ts index ec9e30bb..d40b81ad 100644 --- a/project/src/controllers/RepeatableQuestController.ts +++ b/project/src/controllers/RepeatableQuestController.ts @@ -99,9 +99,9 @@ export class RepeatableQuestController const currentRepeatableQuestType = this.getRepeatableQuestSubTypeFromProfile(repeatableConfig, pmcData); if ( - repeatableConfig.side === "Pmc" && - pmcData.Info.Level >= repeatableConfig.minPlayerLevel || - repeatableConfig.side === "Scav" && scavQuestUnlocked + repeatableConfig.side === "Pmc" + && pmcData.Info.Level >= repeatableConfig.minPlayerLevel + || repeatableConfig.side === "Scav" && scavQuestUnlocked ) { if (time > currentRepeatableQuestType.endTime - 1) @@ -209,13 +209,14 @@ export class RepeatableQuestController protected getQuestCount(repeatableConfig: IRepeatableQuestConfig, pmcData: IPmcData): number { if ( - repeatableConfig.name.toLowerCase() === "daily" && - this.profileHelper.hasEliteSkillLevel(SkillTypes.CHARISMA, pmcData) + repeatableConfig.name.toLowerCase() === "daily" + && this.profileHelper.hasEliteSkillLevel(SkillTypes.CHARISMA, pmcData) ) { // Elite charisma skill gives extra daily quest(s) - return repeatableConfig.numQuests + - this.databaseServer.getTables().globals.config.SkillsSettings.Charisma.BonusSettings.EliteBonusSettings + return repeatableConfig.numQuests + + this.databaseServer.getTables().globals.config.SkillsSettings.Charisma.BonusSettings + .EliteBonusSettings .RepeatableQuestExtraCount; } @@ -321,9 +322,9 @@ export class RepeatableQuestController const possibleLocations = Object.keys(repeatableConfig.locations); // Set possible locations for elimination task, if target is savage, exclude labs from locations - questPool.pool.Elimination.targets[probabilityObject.key] = (probabilityObject.key === "Savage") ? - {locations: possibleLocations.filter((x) => x !== "laboratory")} : - {locations: possibleLocations}; + questPool.pool.Elimination.targets[probabilityObject.key] = (probabilityObject.key === "Savage") + ? {locations: possibleLocations.filter((x) => x !== "laboratory")} + : {locations: possibleLocations}; } } diff --git a/project/src/controllers/TradeController.ts b/project/src/controllers/TradeController.ts index db399e4b..53d11b83 100644 --- a/project/src/controllers/TradeController.ts +++ b/project/src/controllers/TradeController.ts @@ -95,8 +95,8 @@ export class TradeController // Skip buying items when player doesn't have necessary loyalty if ( - fleaOffer.user.memberType === MemberCategory.TRADER && - fleaOffer.loyaltyLevel > pmcData.TradersInfo[fleaOffer.user.id].loyaltyLevel + fleaOffer.user.memberType === MemberCategory.TRADER + && fleaOffer.loyaltyLevel > pmcData.TradersInfo[fleaOffer.user.id].loyaltyLevel ) { this.logger.debug( @@ -231,8 +231,8 @@ export class TradeController { const itemDetails = this.itemHelper.getItem(itemToSell._tpl); if ( - !(itemDetails[0] && - this.itemHelper.isOfBaseclasses(itemDetails[1]._id, traderDetails.items_buy.category)) + !(itemDetails[0] + && this.itemHelper.isOfBaseclasses(itemDetails[1]._id, traderDetails.items_buy.category)) ) { // Skip if tpl isn't item OR item doesn't fulfill match traders buy categories diff --git a/project/src/generators/BotEquipmentModGenerator.ts b/project/src/generators/BotEquipmentModGenerator.ts index c5a1740a..06f49c89 100644 --- a/project/src/generators/BotEquipmentModGenerator.ts +++ b/project/src/generators/BotEquipmentModGenerator.ts @@ -97,9 +97,9 @@ export class BotEquipmentModGenerator } // Ensure submods for nvgs all spawn together - forceSpawn = (modSlot === "mod_nvg") ? - true : - false; + forceSpawn = (modSlot === "mod_nvg") + ? true + : false; let modTpl: string; let found = false; @@ -200,8 +200,8 @@ export class BotEquipmentModGenerator // Null guard against bad input weapon if ( - !((parentTemplate._props.Slots.length || parentTemplate._props.Cartridges?.length) || - parentTemplate._props.Chambers?.length) + !((parentTemplate._props.Slots.length || parentTemplate._props.Cartridges?.length) + || parentTemplate._props.Chambers?.length) ) { this.logger.error( @@ -329,8 +329,8 @@ export class BotEquipmentModGenerator // Handguard mod can take a sub handguard mod + weapon has no UBGL (takes same slot) // Force spawn chance to be 100% to ensure it gets added if ( - modSlot === "mod_handguard" && modToAddTemplate._props.Slots.find((x) => x._name === "mod_handguard") && - !weapon.find((x) => x.slotId === "mod_launcher") + modSlot === "mod_handguard" && modToAddTemplate._props.Slots.find((x) => x._name === "mod_handguard") + && !weapon.find((x) => x.slotId === "mod_launcher") ) { // Needed for handguards with lower @@ -340,8 +340,10 @@ export class BotEquipmentModGenerator // If stock mod can take a sub stock mod, force spawn chance to be 100% to ensure sub-stock gets added // Or if mod_stock is configured to be forced on if ( - modSlot === "mod_stock" && - (modToAddTemplate._props.Slots.find((x) => x._name.includes("mod_stock") || botEquipConfig.forceStock)) + modSlot === "mod_stock" + && (modToAddTemplate._props.Slots.find((x) => + x._name.includes("mod_stock") || botEquipConfig.forceStock + )) ) { // Stock mod can take additional stocks, could be a locking device, force 100% chance @@ -433,8 +435,8 @@ export class BotEquipmentModGenerator "mod_scope_001", "mod_scope_002", "mod_scope_003", - ].includes(modSlot.toLowerCase()) && - modsParentId === BaseClasses.MOUNT; + ].includes(modSlot.toLowerCase()) + && modsParentId === BaseClasses.MOUNT; } /** @@ -579,9 +581,8 @@ export class BotEquipmentModGenerator protected shouldModBeSpawned(itemSlot: Slot, modSlot: string, modSpawnChances: ModsChances): boolean { const modSpawnChance = itemSlot._required || this.getAmmoContainers().includes(modSlot) // Required OR it is ammo - ? - 100 : - modSpawnChances[modSlot]; + ? 100 + : modSpawnChances[modSlot]; if (modSpawnChance === 100) { @@ -824,8 +825,8 @@ export class BotEquipmentModGenerator // If mod id doesn't exist in slots filter list and mod id doesn't have any of the slots filters as a base class, mod isn't valid for the slot if ( - !(itemSlot._props.filters[0].Filter.includes(modToAdd[1]._id) || - this.itemHelper.isOfBaseclasses(modToAdd[1]._id, itemSlot._props.filters[0].Filter)) + !(itemSlot._props.filters[0].Filter.includes(modToAdd[1]._id) + || this.itemHelper.isOfBaseclasses(modToAdd[1]._id, itemSlot._props.filters[0].Filter)) ) { this.logger.warning( @@ -1114,8 +1115,8 @@ export class BotEquipmentModGenerator if ( scopeSlot?.every((x) => x._props.filters[0].Filter.every((x) => - this.itemHelper.isOfBaseclasses(x, whitelistedSightTypes) || - this.itemHelper.isOfBaseclass(x, BaseClasses.MOUNT) + this.itemHelper.isOfBaseclasses(x, whitelistedSightTypes) + || this.itemHelper.isOfBaseclass(x, BaseClasses.MOUNT) ) ) ) diff --git a/project/src/generators/BotGenerator.ts b/project/src/generators/BotGenerator.ts index c0b19da8..22d6aa52 100644 --- a/project/src/generators/BotGenerator.ts +++ b/project/src/generators/BotGenerator.ts @@ -115,9 +115,9 @@ export class BotGenerator // Get raw json data for bot (Cloned) const botJsonTemplate = this.jsonUtil.clone(this.botHelper.getBotTemplate( - (botGenerationDetails.isPmc) ? - bot.Info.Side : - botGenerationDetails.role, + (botGenerationDetails.isPmc) + ? bot.Info.Side + : botGenerationDetails.role, )); bot = this.generateBot(sessionId, bot, botJsonTemplate, botGenerationDetails); @@ -328,9 +328,9 @@ export class BotGenerator */ protected generateHealth(healthObj: Health, playerScav = false): PmcHealth { - const bodyParts = playerScav ? - healthObj.BodyParts[0] : - this.randomUtil.getArrayValue(healthObj.BodyParts); + const bodyParts = playerScav + ? healthObj.BodyParts[0] + : this.randomUtil.getArrayValue(healthObj.BodyParts); const newHealth: PmcHealth = { Hydration: { diff --git a/project/src/generators/BotInventoryGenerator.ts b/project/src/generators/BotInventoryGenerator.ts index e6f49862..a6c81361 100644 --- a/project/src/generators/BotInventoryGenerator.ts +++ b/project/src/generators/BotInventoryGenerator.ts @@ -262,9 +262,9 @@ export class BotInventoryGenerator ): void { const spawnChance = - ([EquipmentSlots.POCKETS, EquipmentSlots.SECURED_CONTAINER] as string[]).includes(equipmentSlot) ? - 100 : - spawnChances.equipment[equipmentSlot]; + ([EquipmentSlots.POCKETS, EquipmentSlots.SECURED_CONTAINER] as string[]).includes(equipmentSlot) + ? 100 + : spawnChances.equipment[equipmentSlot]; if (typeof spawnChance === "undefined") { this.logger.warning( @@ -312,8 +312,8 @@ export class BotInventoryGenerator // use dynamic mod pool if enabled in config const botEquipmentRole = this.botGeneratorHelper.getBotEquipmentRole(botRole); if ( - this.botConfig.equipment[botEquipmentRole] && - randomisationDetails?.randomisedArmorSlots?.includes(equipmentSlot) + this.botConfig.equipment[botEquipmentRole] + && randomisationDetails?.randomisedArmorSlots?.includes(equipmentSlot) ) { modPool[equipmentItemTpl] = this.getFilteredDynamicModsForItem( @@ -323,8 +323,8 @@ export class BotInventoryGenerator } if ( - typeof (modPool[equipmentItemTpl]) !== "undefined" || - Object.keys(modPool[equipmentItemTpl] || {}).length > 0 + typeof (modPool[equipmentItemTpl]) !== "undefined" + || Object.keys(modPool[equipmentItemTpl] || {}).length > 0 ) { const items = this.botEquipmentModGenerator.generateModsForEquipment( @@ -428,16 +428,15 @@ export class BotInventoryGenerator }, { slot: EquipmentSlots.SECOND_PRIMARY_WEAPON, - shouldSpawn: shouldSpawnPrimary ? - this.randomUtil.getChance100(equipmentChances.equipment.SecondPrimaryWeapon) : - false, + shouldSpawn: shouldSpawnPrimary + ? this.randomUtil.getChance100(equipmentChances.equipment.SecondPrimaryWeapon) + : false, }, { slot: EquipmentSlots.HOLSTER, - shouldSpawn: shouldSpawnPrimary ? - this.randomUtil.getChance100(equipmentChances.equipment.Holster) // Primary weapon = roll for chance at pistol - : - true, // No primary = force pistol + shouldSpawn: shouldSpawnPrimary + ? this.randomUtil.getChance100(equipmentChances.equipment.Holster) // Primary weapon = roll for chance at pistol + : true, // No primary = force pistol }, ]; } diff --git a/project/src/generators/BotLootGenerator.ts b/project/src/generators/BotLootGenerator.ts index 1c7af16d..54f6a28b 100644 --- a/project/src/generators/BotLootGenerator.ts +++ b/project/src/generators/BotLootGenerator.ts @@ -598,9 +598,9 @@ export class BotLootGenerator { // PMCs have a different stack max size const minStackSize = itemTemplate._props.StackMinRandom; - const maxStackSize = isPmc ? - this.pmcConfig.dynamicLoot.moneyStackLimits[itemTemplate._id] : - itemTemplate._props.StackMaxRandom; + const maxStackSize = isPmc + ? this.pmcConfig.dynamicLoot.moneyStackLimits[itemTemplate._id] + : itemTemplate._props.StackMaxRandom; const randomSize = this.randomUtil.getInt(minStackSize, maxStackSize); if (!moneyItem.upd) @@ -619,9 +619,9 @@ export class BotLootGenerator */ protected randomiseAmmoStackSize(isPmc: boolean, itemTemplate: ITemplateItem, ammoItem: Item): void { - const randomSize = itemTemplate._props.StackMaxSize === 1 ? - 1 : - this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); + const randomSize = itemTemplate._props.StackMaxSize === 1 + ? 1 + : this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); if (!ammoItem.upd) { diff --git a/project/src/generators/BotWeaponGenerator.ts b/project/src/generators/BotWeaponGenerator.ts index ad7fc5ef..7f5e946a 100644 --- a/project/src/generators/BotWeaponGenerator.ts +++ b/project/src/generators/BotWeaponGenerator.ts @@ -207,9 +207,9 @@ export class BotWeaponGenerator // Add cartridge to gun chamber if weapon has slot for it if ( - weaponItemTemplate._props.Chambers?.length === 1 && - weaponItemTemplate._props.Chambers[0]?._name === "patron_in_weapon" && - weaponItemTemplate._props.Chambers[0]?._props?.filters[0]?.Filter?.includes(ammoTpl) + weaponItemTemplate._props.Chambers?.length === 1 + && weaponItemTemplate._props.Chambers[0]?._name === "patron_in_weapon" + && weaponItemTemplate._props.Chambers[0]?._props?.filters[0]?.Filter?.includes(ammoTpl) ) { this.addCartridgeToChamber(weaponWithModsArray, ammoTpl, "patron_in_weapon"); @@ -615,8 +615,8 @@ export class BotWeaponGenerator const chosenAmmoTpl = this.weightedRandomHelper.getWeightedValue(compatibleCartridges); if ( - weaponTemplate._props.Chambers[0] && - !weaponTemplate._props.Chambers[0]._props.filters[0].Filter.includes(chosenAmmoTpl) + weaponTemplate._props.Chambers[0] + && !weaponTemplate._props.Chambers[0]._props.filters[0].Filter.includes(chosenAmmoTpl) ) { this.logger.debug( diff --git a/project/src/generators/FenceBaseAssortGenerator.ts b/project/src/generators/FenceBaseAssortGenerator.ts index 905c7fa9..f2418d1b 100644 --- a/project/src/generators/FenceBaseAssortGenerator.ts +++ b/project/src/generators/FenceBaseAssortGenerator.ts @@ -66,8 +66,8 @@ export class FenceBaseAssortGenerator if (this.traderConfig.fence.blacklist.length > 0) { if ( - this.traderConfig.fence.blacklist.includes(item._id) || - this.itemHelper.isOfBaseclasses(item._id, this.traderConfig.fence.blacklist) + this.traderConfig.fence.blacklist.includes(item._id) + || this.itemHelper.isOfBaseclasses(item._id, this.traderConfig.fence.blacklist) ) { continue; diff --git a/project/src/generators/LocationGenerator.ts b/project/src/generators/LocationGenerator.ts index 93e9554a..36d7c9a3 100644 --- a/project/src/generators/LocationGenerator.ts +++ b/project/src/generators/LocationGenerator.ts @@ -133,8 +133,8 @@ export class LocationGenerator // randomisation is turned off globally or just turned off for this map if ( - !(this.locationConfig.containerRandomisationSettings.enabled && - this.locationConfig.containerRandomisationSettings.maps[locationId]) + !(this.locationConfig.containerRandomisationSettings.enabled + && this.locationConfig.containerRandomisationSettings.maps[locationId]) ) { this.logger.debug( @@ -249,8 +249,8 @@ export class LocationGenerator { return staticContainers .filter((x) => - x.probability !== 1 && !x.template.IsAlwaysSpawn && - !this.locationConfig.containerRandomisationSettings.containerTypesToNotRandomise.includes( + x.probability !== 1 && !x.template.IsAlwaysSpawn + && !this.locationConfig.containerRandomisationSettings.containerTypesToNotRandomise.includes( x.template.Items[0]._tpl, ) ); @@ -264,8 +264,8 @@ export class LocationGenerator protected getGuaranteedContainers(staticContainersOnMap: IStaticContainerData[]): IStaticContainerData[] { return staticContainersOnMap.filter((x) => - x.probability === 1 || x.template.IsAlwaysSpawn || - this.locationConfig.containerRandomisationSettings.containerTypesToNotRandomise.includes( + x.probability === 1 || x.template.IsAlwaysSpawn + || this.locationConfig.containerRandomisationSettings.containerTypesToNotRandomise.includes( x.template.Items[0]._tpl, ) ); @@ -325,12 +325,12 @@ export class LocationGenerator containerIdsWithProbability: {}, chosenCount: this.randomUtil.getInt( Math.round( - groupData.minContainers * - this.locationConfig.containerRandomisationSettings.containerGroupMinSizeMultiplier, + groupData.minContainers + * this.locationConfig.containerRandomisationSettings.containerGroupMinSizeMultiplier, ), Math.round( - groupData.maxContainers * - this.locationConfig.containerRandomisationSettings.containerGroupMaxSizeMultiplier, + groupData.maxContainers + * this.locationConfig.containerRandomisationSettings.containerGroupMaxSizeMultiplier, ), ), }; @@ -570,8 +570,8 @@ export class LocationGenerator // Draw from random distribution const desiredSpawnpointCount = Math.round( - this.getLooseLootMultiplerForLocation(locationName) * - this.randomUtil.randn( + this.getLooseLootMultiplerForLocation(locationName) + * this.randomUtil.randn( dynamicLootDist.spawnpointCount.mean, dynamicLootDist.spawnpointCount.std, ), @@ -782,15 +782,15 @@ export class LocationGenerator // Money/Ammo - don't rely on items in spawnPoint.template.Items so we can randomise it ourselves if ( - this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.MONEY) || - this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.AMMO) + this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.MONEY) + || this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.AMMO) ) { const itemTemplate = this.itemHelper.getItem(chosenTpl)[1]; - const stackCount = itemTemplate._props.StackMaxSize === 1 ? - 1 : - this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); + const stackCount = itemTemplate._props.StackMaxSize === 1 + ? 1 + : this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); itemWithMods.push( { @@ -915,14 +915,14 @@ export class LocationGenerator } if ( - this.itemHelper.isOfBaseclass(tpl, BaseClasses.MONEY) || - this.itemHelper.isOfBaseclass(tpl, BaseClasses.AMMO) + this.itemHelper.isOfBaseclass(tpl, BaseClasses.MONEY) + || this.itemHelper.isOfBaseclass(tpl, BaseClasses.AMMO) ) { // Edge case - some ammos e.g. flares or M406 grenades shouldn't be stacked - const stackCount = itemTemplate._props.StackMaxSize === 1 ? - 1 : - this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); + const stackCount = itemTemplate._props.StackMaxSize === 1 + ? 1 + : this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); items[0].upd = {StackObjectsCount: stackCount}; } // No spawn point, use default template diff --git a/project/src/generators/LootGenerator.ts b/project/src/generators/LootGenerator.ts index 3f5babb6..56bb3032 100644 --- a/project/src/generators/LootGenerator.ts +++ b/project/src/generators/LootGenerator.ts @@ -93,10 +93,10 @@ export class LootGenerator // Get items from items.json that have a type of item + not in global blacklist + basetype is in whitelist const items = Object.entries(tables.templates.items).filter((x) => - !itemBlacklist.has(x[1]._id) && - x[1]._type.toLowerCase() === "item" && - !x[1]._props.QuestItem && - options.itemTypeWhitelist.includes(x[1]._parent) + !itemBlacklist.has(x[1]._id) + && x[1]._type.toLowerCase() === "item" + && !x[1]._props.QuestItem + && options.itemTypeWhitelist.includes(x[1]._parent) ); const randomisedItemCount = this.randomUtil.getInt(options.itemCount.min, options.itemCount.max); @@ -175,8 +175,8 @@ export class LootGenerator // Check if armor has level in allowed whitelist if ( - randomItem._parent === BaseClasses.ARMOR || - randomItem._parent === BaseClasses.VEST + randomItem._parent === BaseClasses.ARMOR + || randomItem._parent === BaseClasses.VEST ) { if (!options.armorLevelWhitelist.includes(Number(randomItem._props.armorClass))) @@ -319,9 +319,9 @@ export class LootGenerator } // Get weapon preset - default or choose a random one from all possible - let chosenWeaponPreset = containerSettings.defaultPresetsOnly ? - this.presetHelper.getDefaultPreset(chosenWeaponTpl) : - this.randomUtil.getArrayValue(this.presetHelper.getPresets(chosenWeaponTpl)); + let chosenWeaponPreset = containerSettings.defaultPresetsOnly + ? this.presetHelper.getDefaultPreset(chosenWeaponTpl) + : this.randomUtil.getArrayValue(this.presetHelper.getPresets(chosenWeaponTpl)); if (!chosenWeaponPreset) { @@ -407,11 +407,11 @@ export class LootGenerator // Get all items of the desired type + not quest items + not globally blacklisted const rewardItemPool = Object.values(this.databaseServer.getTables().templates.items) .filter((x) => - x._parent === rewardTypeId && - x._type.toLowerCase() === "item" && - !this.itemFilterService.isItemBlacklisted(x._id) && - (!(containerSettings.allowBossItems || this.itemFilterService.isBossItem(x._id))) && - !x._props.QuestItem + x._parent === rewardTypeId + && x._type.toLowerCase() === "item" + && !this.itemFilterService.isItemBlacklisted(x._id) + && (!(containerSettings.allowBossItems || this.itemFilterService.isBossItem(x._id))) + && !x._props.QuestItem ); if (rewardItemPool.length === 0) diff --git a/project/src/generators/PMCLootGenerator.ts b/project/src/generators/PMCLootGenerator.ts index 2b6c11a8..b7f6e6be 100644 --- a/project/src/generators/PMCLootGenerator.ts +++ b/project/src/generators/PMCLootGenerator.ts @@ -56,12 +56,12 @@ export class PMCLootGenerator } const itemsToAdd = Object.values(items).filter((item) => - allowedItemTypes.includes(item._parent) && - this.itemHelper.isValidItem(item._id) && - !pmcItemBlacklist.includes(item._id) && - !itemBlacklist.includes(item._id) && - item._props.Width === 1 && - item._props.Height === 1 + allowedItemTypes.includes(item._parent) + && this.itemHelper.isValidItem(item._id) + && !pmcItemBlacklist.includes(item._id) + && !itemBlacklist.includes(item._id) + && item._props.Width === 1 + && item._props.Height === 1 ); this.pocketLootPool = itemsToAdd.map((x) => x._id); @@ -94,11 +94,11 @@ export class PMCLootGenerator } const itemsToAdd = Object.values(items).filter((item) => - allowedItemTypes.includes(item._parent) && - this.itemHelper.isValidItem(item._id) && - !pmcItemBlacklist.includes(item._id) && - !itemBlacklist.includes(item._id) && - this.itemFitsInto2By2Slot(item) + allowedItemTypes.includes(item._parent) + && this.itemHelper.isValidItem(item._id) + && !pmcItemBlacklist.includes(item._id) + && !itemBlacklist.includes(item._id) + && this.itemFitsInto2By2Slot(item) ); this.vestLootPool = itemsToAdd.map((x) => x._id); @@ -141,10 +141,10 @@ export class PMCLootGenerator } const itemsToAdd = Object.values(items).filter((item) => - allowedItemTypes.includes(item._parent) && - this.itemHelper.isValidItem(item._id) && - !pmcItemBlacklist.includes(item._id) && - !itemBlacklist.includes(item._id) + allowedItemTypes.includes(item._parent) + && this.itemHelper.isValidItem(item._id) + && !pmcItemBlacklist.includes(item._id) + && !itemBlacklist.includes(item._id) ); this.backpackLootPool = itemsToAdd.map((x) => x._id); diff --git a/project/src/generators/PlayerScavGenerator.ts b/project/src/generators/PlayerScavGenerator.ts index 69f1b849..f612c208 100644 --- a/project/src/generators/PlayerScavGenerator.ts +++ b/project/src/generators/PlayerScavGenerator.ts @@ -66,9 +66,9 @@ export class PlayerScavGenerator const existingScavData = this.jsonUtil.clone(profile.characters.scav); // scav profile can be empty on first profile creation - const scavKarmaLevel = (Object.keys(existingScavData).length === 0) ? - 0 : - this.getScavKarmaLevel(pmcData); + const scavKarmaLevel = (Object.keys(existingScavData).length === 0) + ? 0 + : this.getScavKarmaLevel(pmcData); // use karma level to get correct karmaSettings const playerScavKarmaSettings = this.playerScavConfig.karmaLevel[scavKarmaLevel]; diff --git a/project/src/generators/RagfairAssortGenerator.ts b/project/src/generators/RagfairAssortGenerator.ts index 65e301f0..ceccce7d 100644 --- a/project/src/generators/RagfairAssortGenerator.ts +++ b/project/src/generators/RagfairAssortGenerator.ts @@ -62,9 +62,9 @@ export class RagfairAssortGenerator const results: Item[] = []; const items = this.itemHelper.getItems(); - const weaponPresets = (this.ragfairConfig.dynamic.showDefaultPresetsOnly) ? - this.getDefaultPresets() : - this.getPresets(); + const weaponPresets = (this.ragfairConfig.dynamic.showDefaultPresetsOnly) + ? this.getDefaultPresets() + : this.getPresets(); const ragfairItemInvalidBaseTypes: string[] = [ BaseClasses.LOOT_CONTAINER, // safe, barrel cache etc @@ -85,8 +85,8 @@ export class RagfairAssortGenerator } if ( - this.ragfairConfig.dynamic.removeSeasonalItemsWhenNotInEvent && !seasonalEventActive && - seasonalItemTplBlacklist.includes(item._id) + this.ragfairConfig.dynamic.removeSeasonalItemsWhenNotInEvent && !seasonalEventActive + && seasonalItemTplBlacklist.includes(item._id) ) { continue; diff --git a/project/src/generators/RagfairOfferGenerator.ts b/project/src/generators/RagfairOfferGenerator.ts index 5f08253e..2a716526 100644 --- a/project/src/generators/RagfairOfferGenerator.ts +++ b/project/src/generators/RagfairOfferGenerator.ts @@ -126,9 +126,9 @@ export class RagfairOfferGenerator intId: 0, user: { id: this.getTraderId(userID), - memberType: (userID === "ragfair") ? - MemberCategory.DEFAULT : - this.ragfairServerHelper.getMemberType(userID), + memberType: (userID === "ragfair") + ? MemberCategory.DEFAULT + : this.ragfairServerHelper.getMemberType(userID), nickname: this.ragfairServerHelper.getNickname(userID), rating: this.getRating(userID), isRatingGrowing: this.getRatingGrowing(userID), @@ -164,9 +164,9 @@ export class RagfairOfferGenerator let roublePrice = 0; for (const requirement of offerRequirements) { - roublePrice += this.paymentHelper.isMoneyTpl(requirement._tpl) ? - Math.round(this.calculateRoublePrice(requirement.count, requirement._tpl)) : - this.ragfairPriceService.getFleaPriceForItem(requirement._tpl) * requirement.count; // get flea price for barter offer items + roublePrice += this.paymentHelper.isMoneyTpl(requirement._tpl) + ? Math.round(this.calculateRoublePrice(requirement.count, requirement._tpl)) + : this.ragfairPriceService.getFleaPriceForItem(requirement._tpl) * requirement.count; // get flea price for barter offer items } return roublePrice; @@ -290,8 +290,8 @@ export class RagfairOfferGenerator // Generated fake-player offer return Math.round( - time + - this.randomUtil.getInt( + time + + this.randomUtil.getInt( this.ragfairConfig.dynamic.endTimeSeconds.min, this.ragfairConfig.dynamic.endTimeSeconds.max, ), @@ -307,9 +307,9 @@ export class RagfairOfferGenerator const config = this.ragfairConfig.dynamic; // get assort items from param if they exist, otherwise grab freshly generated assorts - const assortItemsToProcess: Item[] = expiredOffers ? - expiredOffers : - this.ragfairAssortGenerator.getAssortItems(); + const assortItemsToProcess: Item[] = expiredOffers + ? expiredOffers + : this.ragfairAssortGenerator.getAssortItems(); // Store all functions to create an offer for every item and pass into Promise.all to run async const assorOffersForItemsProcesses = []; @@ -348,9 +348,9 @@ export class RagfairOfferGenerator } // Get item + sub-items if preset, otherwise just get item - const items: Item[] = isPreset ? - this.ragfairServerHelper.getPresetItems(assortItem) : - [ + const items: Item[] = isPreset + ? this.ragfairServerHelper.getPresetItems(assortItem) + : [ ...[assortItem], ...this.itemHelper.findAndReturnChildrenByAssort( assortItem._id, @@ -360,9 +360,9 @@ export class RagfairOfferGenerator // Get number of offers to create // Limit to 1 offer when processing expired - const offerCount = expiredOffers ? - 1 : - Math.round(this.randomUtil.getInt(config.offerItemCount.min, config.offerItemCount.max)); + const offerCount = expiredOffers + ? 1 + : Math.round(this.randomUtil.getInt(config.offerItemCount.min, config.offerItemCount.max)); // Store all functions to create offers for this item and pass into Promise.all to run async const assortSingleOfferProcesses = []; @@ -391,10 +391,10 @@ export class RagfairOfferGenerator items[0].upd.StackObjectsCount = this.ragfairServerHelper.calculateDynamicStackCount(items[0]._tpl, isPreset); const isBarterOffer = this.randomUtil.getChance100(this.ragfairConfig.dynamic.barter.chancePercent); - const isPackOffer = this.randomUtil.getChance100(this.ragfairConfig.dynamic.pack.chancePercent) && - !isBarterOffer && - items.length === 1 && - this.itemHelper.isOfBaseclasses(items[0]._tpl, this.ragfairConfig.dynamic.pack.itemTypeWhitelist); + const isPackOffer = this.randomUtil.getChance100(this.ragfairConfig.dynamic.pack.chancePercent) + && !isBarterOffer + && items.length === 1 + && this.itemHelper.isOfBaseclasses(items[0]._tpl, this.ragfairConfig.dynamic.pack.itemTypeWhitelist); const randomUserId = this.hashUtil.generate(); let barterScheme: IBarterScheme[]; @@ -488,9 +488,9 @@ export class RagfairOfferGenerator } const isPreset = this.presetHelper.isPreset(item._id); - const items: Item[] = isPreset ? - this.ragfairServerHelper.getPresetItems(item) : - [...[item], ...this.itemHelper.findAndReturnChildrenByAssort(item._id, assorts.items)]; + const items: Item[] = isPreset + ? this.ragfairServerHelper.getPresetItems(item) + : [...[item], ...this.itemHelper.findAndReturnChildrenByAssort(item._id, assorts.items)]; const barterScheme = assorts.barter_scheme[item._id]; if (!barterScheme) @@ -762,8 +762,8 @@ export class RagfairOfferGenerator // Filter possible barters to items that match the price range + not itself const filtered = fleaPrices.filter((x) => - x.price >= desiredItemCost - offerCostVariance && x.price <= desiredItemCost + offerCostVariance && - x.tpl !== offerItems[0]._tpl + x.price >= desiredItemCost - offerCostVariance && x.price <= desiredItemCost + offerCostVariance + && x.tpl !== offerItems[0]._tpl ); // No items on flea have a matching price, fall back to currency @@ -816,8 +816,8 @@ export class RagfairOfferGenerator protected createCurrencyBarterScheme(offerItems: Item[], isPackOffer: boolean, multipler = 1): IBarterScheme[] { const currency = this.ragfairServerHelper.getDynamicOfferCurrency(); - const price = this.ragfairPriceService.getDynamicOfferPriceForOffer(offerItems, currency, isPackOffer) * - multipler; + const price = this.ragfairPriceService.getDynamicOfferPriceForOffer(offerItems, currency, isPackOffer) + * multipler; return [ { diff --git a/project/src/generators/RepeatableQuestGenerator.ts b/project/src/generators/RepeatableQuestGenerator.ts index 40f608c2..e8d24768 100644 --- a/project/src/generators/RepeatableQuestGenerator.ts +++ b/project/src/generators/RepeatableQuestGenerator.ts @@ -212,8 +212,8 @@ export class RepeatableQuestGenerator // we use any also if the random condition is not met in case only "any" was in the pool let locationKey = "any"; if ( - locations.includes("any") && - (eliminationConfig.specificLocationProb < Math.random() || locations.length <= 1) + locations.includes("any") + && (eliminationConfig.specificLocationProb < Math.random() || locations.length <= 1) ) { locationKey = "any"; @@ -290,8 +290,8 @@ export class RepeatableQuestGenerator { // random distance with lower values more likely; simple distribution for starters... distance = Math.floor( - Math.abs(Math.random() - Math.random()) * (1 + eliminationConfig.maxDist - eliminationConfig.minDist) + - eliminationConfig.minDist, + Math.abs(Math.random() - Math.random()) * (1 + eliminationConfig.maxDist - eliminationConfig.minDist) + + eliminationConfig.minDist, ); distance = Math.ceil(distance / 5) * 5; distanceDifficulty = maxDistDifficulty * distance / eliminationConfig.maxDist; @@ -542,8 +542,8 @@ export class RepeatableQuestGenerator itemSelection = itemSelection.filter((x) => { // Whitelist can contain item tpls and item base type ids - return (itemIdsWhitelisted.some((v) => this.itemHelper.isOfBaseclass(x[0], v)) || - itemIdsWhitelisted.includes(x[0])); + return (itemIdsWhitelisted.some((v) => this.itemHelper.isOfBaseclass(x[0], v)) + || itemIdsWhitelisted.includes(x[0])); }); // check if items are missing // const flatList = itemSelection.reduce((a, il) => a.concat(il[0]), []); @@ -561,8 +561,8 @@ export class RepeatableQuestGenerator ); itemSelection = itemSelection.filter((x) => { - return itemIdsBlacklisted.every((v) => !this.itemHelper.isOfBaseclass(x[0], v)) || - !itemIdsBlacklisted.includes(x[0]); + return itemIdsBlacklisted.every((v) => !this.itemHelper.isOfBaseclass(x[0], v)) + || !itemIdsBlacklisted.includes(x[0]); }); } @@ -637,16 +637,16 @@ export class RepeatableQuestGenerator let minDurability = 0; let onlyFoundInRaid = true; if ( - this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.WEAPON) || - this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.ARMOR) + this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.WEAPON) + || this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.ARMOR) ) { minDurability = 80; } if ( - this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.DOG_TAG_USEC) || - this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.DOG_TAG_BEAR) + this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.DOG_TAG_USEC) + || this.itemHelper.isOfBaseclass(targetItemId, BaseClasses.DOG_TAG_BEAR) ) { onlyFoundInRaid = false; @@ -744,11 +744,11 @@ export class RepeatableQuestGenerator (this.databaseServer.getTables().locations[locationKey.toLowerCase()].base as ILocationBase).exits; const possibleExists = mapExits.filter( (x) => - (!("PassageRequirement" in x) || - repeatableConfig.questConfig.Exploration.specificExits.passageRequirementWhitelist.includes( + (!("PassageRequirement" in x) + || repeatableConfig.questConfig.Exploration.specificExits.passageRequirementWhitelist.includes( x.PassageRequirement, - )) && - x.Chance > 0, + )) + && x.Chance > 0, ); const exit = this.randomUtil.drawRandomFromList(possibleExists, 1)[0]; const exitCondition = this.generateExplorationExitCondition(exit); @@ -879,20 +879,20 @@ export class RepeatableQuestGenerator // rewards are generated based on pmcLevel, difficulty and a random spread const rewardXP = Math.floor( - difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, xpConfig) * - this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig), + difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, xpConfig) + * this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig), ); const rewardRoubles = Math.floor( - difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, roublesConfig) * - this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig), + difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, roublesConfig) + * this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig), ); const rewardNumItems = this.randomUtil.randInt( 1, Math.round(this.mathUtil.interp1(pmcLevel, levelsConfig, itemsConfig)) + 1, ); const rewardReputation = Math.round( - 100 * difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, reputationConfig) * - this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig), + 100 * difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, reputationConfig) + * this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig), ) / 100; const skillRewardChance = this.mathUtil.interp1(pmcLevel, levelsConfig, skillRewardChanceConfig); const skillPointReward = this.mathUtil.interp1(pmcLevel, levelsConfig, skillPointRewardConfig); @@ -1124,8 +1124,8 @@ export class RepeatableQuestGenerator // Item is on repeatable or global blacklist if ( - repeatableQuestConfig.rewardBlacklist.includes(tpl) || - this.itemFilterService.isItemBlacklisted(tpl) + repeatableQuestConfig.rewardBlacklist.includes(tpl) + || this.itemFilterService.isItemBlacklisted(tpl) ) { return false; @@ -1152,8 +1152,8 @@ export class RepeatableQuestGenerator // Skip globally blacklisted items + boss items // biome-ignore lint/complexity/useSimplifiedLogicExpression: - valid = !this.itemFilterService.isItemBlacklisted(tpl) && - !this.itemFilterService.isBossItem(tpl); + valid = !this.itemFilterService.isItemBlacklisted(tpl) + && !this.itemFilterService.isBossItem(tpl); return valid; } diff --git a/project/src/generators/ScavCaseRewardGenerator.ts b/project/src/generators/ScavCaseRewardGenerator.ts index bb130a30..2cb56bc3 100644 --- a/project/src/generators/ScavCaseRewardGenerator.ts +++ b/project/src/generators/ScavCaseRewardGenerator.ts @@ -107,9 +107,9 @@ export class ScavCaseRewardGenerator // Skip item if item id is on blacklist if ( - (item._type !== "Item") || - this.scavCaseConfig.rewardItemBlacklist.includes(item._id) || - this.itemFilterService.isItemBlacklisted(item._id) + (item._type !== "Item") + || this.scavCaseConfig.rewardItemBlacklist.includes(item._id) + || this.itemFilterService.isItemBlacklisted(item._id) ) { return false; @@ -249,8 +249,8 @@ export class ScavCaseRewardGenerator // Is ammo handbook price between desired range const handbookPrice = this.ragfairPriceService.getStaticPriceForItem(ammo._id); if ( - handbookPrice >= this.scavCaseConfig.ammoRewards.ammoRewardValueRangeRub[rarity].min && - handbookPrice <= this.scavCaseConfig.ammoRewards.ammoRewardValueRangeRub[rarity].max + handbookPrice >= this.scavCaseConfig.ammoRewards.ammoRewardValueRangeRub[rarity].min + && handbookPrice <= this.scavCaseConfig.ammoRewards.ammoRewardValueRangeRub[rarity].max ) { return true; @@ -332,8 +332,8 @@ export class ScavCaseRewardGenerator { const handbookPrice = this.ragfairPriceService.getStaticPriceForItem(item._id); if ( - handbookPrice >= itemFilters.minPriceRub && - handbookPrice <= itemFilters.maxPriceRub + handbookPrice >= itemFilters.minPriceRub + && handbookPrice <= itemFilters.maxPriceRub ) { return true; diff --git a/project/src/generators/WeatherGenerator.ts b/project/src/generators/WeatherGenerator.ts index 80288400..224e9d88 100644 --- a/project/src/generators/WeatherGenerator.ts +++ b/project/src/generators/WeatherGenerator.ts @@ -106,9 +106,9 @@ export class WeatherGenerator wind_gustiness: this.getRandomFloat("windGustiness"), rain: rain, // eslint-disable-next-line @typescript-eslint/naming-convention - rain_intensity: (rain > 1) ? - this.getRandomFloat("rainIntensity") : - 0, + rain_intensity: (rain > 1) + ? this.getRandomFloat("rainIntensity") + : 0, fog: this.getWeightedFog(), temp: this.getRandomFloat("temp"), pressure: this.getRandomFloat("pressure"), diff --git a/project/src/generators/weapongen/implementations/ExternalInventoryMagGen.ts b/project/src/generators/weapongen/implementations/ExternalInventoryMagGen.ts index 11f06b55..c3df2544 100644 --- a/project/src/generators/weapongen/implementations/ExternalInventoryMagGen.ts +++ b/project/src/generators/weapongen/implementations/ExternalInventoryMagGen.ts @@ -59,8 +59,10 @@ export class ExternalInventoryMagGen implements IInventoryMagGen // and try again. Temporary workaround to Killa spawning with no extras if he spawns with a drum mag. // TODO: Fix this properly if ( - magazineTpl === - this.botWeaponGeneratorHelper.getWeaponsDefaultMagazineTpl(inventoryMagGen.getWeaponTemplate()) + magazineTpl + === this.botWeaponGeneratorHelper.getWeaponsDefaultMagazineTpl( + inventoryMagGen.getWeaponTemplate(), + ) ) { // We were already on default - stop here to prevent infinite looping diff --git a/project/src/helpers/BotDifficultyHelper.ts b/project/src/helpers/BotDifficultyHelper.ts index 59c4a9bb..3b6298f5 100644 --- a/project/src/helpers/BotDifficultyHelper.ts +++ b/project/src/helpers/BotDifficultyHelper.ts @@ -38,12 +38,12 @@ export class BotDifficultyHelper { const difficultySettings = this.getDifficultySettings(pmcType, difficulty); - const friendlyType = pmcType === "bear" ? - bearType : - usecType; - const enemyType = pmcType === "bear" ? - usecType : - bearType; + const friendlyType = pmcType === "bear" + ? bearType + : usecType; + const enemyType = pmcType === "bear" + ? usecType + : bearType; this.botHelper.addBotToEnemyList(difficultySettings, this.pmcConfig.enemyTypes, friendlyType); // Add generic bot types to enemy list this.botHelper.addBotToEnemyList(difficultySettings, [enemyType, friendlyType], ""); // add same/opposite side to enemy list @@ -96,9 +96,9 @@ export class BotDifficultyHelper */ protected getDifficultySettings(type: string, difficulty: string): Difficulty { - let difficultySetting = this.pmcConfig.difficulty.toLowerCase() === "asonline" ? - difficulty : - this.pmcConfig.difficulty.toLowerCase(); + let difficultySetting = this.pmcConfig.difficulty.toLowerCase() === "asonline" + ? difficulty + : this.pmcConfig.difficulty.toLowerCase(); difficultySetting = this.convertBotDifficultyDropdownToBotDifficulty(difficultySetting); diff --git a/project/src/helpers/BotGeneratorHelper.ts b/project/src/helpers/BotGeneratorHelper.ts index eab60729..e1849094 100644 --- a/project/src/helpers/BotGeneratorHelper.ts +++ b/project/src/helpers/BotGeneratorHelper.ts @@ -113,9 +113,9 @@ export class BotGeneratorHelper if (itemTemplate._parent === BaseClasses.FLASHLIGHT) { // Get chance from botconfig for bot type - const lightLaserActiveChance = raidIsNight ? - this.getBotEquipmentSettingFromConfig(botRole, "lightIsActiveNightChancePercent", 50) : - this.getBotEquipmentSettingFromConfig(botRole, "lightIsActiveDayChancePercent", 25); + const lightLaserActiveChance = raidIsNight + ? this.getBotEquipmentSettingFromConfig(botRole, "lightIsActiveNightChancePercent", 50) + : this.getBotEquipmentSettingFromConfig(botRole, "lightIsActiveDayChancePercent", 25); itemProperties.Light = {IsActive: (this.randomUtil.getChance100(lightLaserActiveChance)), SelectedMode: 0}; } else if (itemTemplate._parent === BaseClasses.TACTICAL_COMBO) @@ -132,9 +132,9 @@ export class BotGeneratorHelper if (itemTemplate._parent === BaseClasses.NIGHTVISION) { // Get chance from botconfig for bot type - const nvgActiveChance = raidIsNight ? - this.getBotEquipmentSettingFromConfig(botRole, "nvgIsActiveChanceNightPercent", 90) : - this.getBotEquipmentSettingFromConfig(botRole, "nvgIsActiveChanceDayPercent", 15); + const nvgActiveChance = raidIsNight + ? this.getBotEquipmentSettingFromConfig(botRole, "nvgIsActiveChanceNightPercent", 90) + : this.getBotEquipmentSettingFromConfig(botRole, "nvgIsActiveChanceDayPercent", 15); itemProperties.Togglable = {On: (this.randomUtil.getChance100(nvgActiveChance))}; } @@ -150,9 +150,9 @@ export class BotGeneratorHelper itemProperties.Togglable = {On: (this.randomUtil.getChance100(faceShieldActiveChance))}; } - return Object.keys(itemProperties).length ? - {upd: itemProperties} : - {}; + return Object.keys(itemProperties).length + ? {upd: itemProperties} + : {}; } /** @@ -370,9 +370,9 @@ export class BotGeneratorHelper { return ([this.pmcConfig.usecType.toLowerCase(), this.pmcConfig.bearType.toLowerCase()].includes( botRole.toLowerCase(), - )) ? - "pmc" : - botRole; + )) + ? "pmc" + : botRole; } } diff --git a/project/src/helpers/BotHelper.ts b/project/src/helpers/BotHelper.ts index aaae6ebf..9801ecb7 100644 --- a/project/src/helpers/BotHelper.ts +++ b/project/src/helpers/BotHelper.ts @@ -185,8 +185,8 @@ export class BotHelper public rollChanceToBePmc(role: string, botConvertMinMax: MinMax): boolean { - return role.toLowerCase() in this.pmcConfig.convertIntoPmcChance && - this.randomUtil.getChance100(this.randomUtil.getInt(botConvertMinMax.min, botConvertMinMax.max)); + return role.toLowerCase() in this.pmcConfig.convertIntoPmcChance + && this.randomUtil.getChance100(this.randomUtil.getInt(botConvertMinMax.min, botConvertMinMax.max)); } public botRoleIsPmc(botRole: string): boolean @@ -219,9 +219,9 @@ export class BotHelper */ public getRandomizedPmcRole(): string { - return (this.randomUtil.getChance100(this.pmcConfig.isUsec)) ? - this.pmcConfig.usecType : - this.pmcConfig.bearType; + return (this.randomUtil.getChance100(this.pmcConfig.isUsec)) + ? this.pmcConfig.usecType + : this.pmcConfig.bearType; } /** @@ -248,8 +248,8 @@ export class BotHelper */ protected getRandomizedPmcSide(): string { - return (this.randomUtil.getChance100(this.pmcConfig.isUsec)) ? - "Usec" : - "Bear"; + return (this.randomUtil.getChance100(this.pmcConfig.isUsec)) + ? "Usec" + : "Bear"; } } diff --git a/project/src/helpers/DialogueHelper.ts b/project/src/helpers/DialogueHelper.ts index 49ac0d91..86e2ecdf 100644 --- a/project/src/helpers/DialogueHelper.ts +++ b/project/src/helpers/DialogueHelper.ts @@ -149,9 +149,9 @@ export class DialogueHelper items: items, maxStorageTime: messageContent.maxStorageTime, systemData: messageContent.systemData ? messageContent.systemData : undefined, - profileChangeEvents: (messageContent.profileChangeEvents?.length === 0) ? - messageContent.profileChangeEvents : - undefined, + profileChangeEvents: (messageContent.profileChangeEvents?.length === 0) + ? messageContent.profileChangeEvents + : undefined, }; if (!message.templateId) diff --git a/project/src/helpers/DurabilityLimitsHelper.ts b/project/src/helpers/DurabilityLimitsHelper.ts index 84e53e73..8840976e 100644 --- a/project/src/helpers/DurabilityLimitsHelper.ts +++ b/project/src/helpers/DurabilityLimitsHelper.ts @@ -177,9 +177,9 @@ export class DurabilityLimitsHelper ); // Dont let weapon dura go below the percent defined in config - return (result >= durabilityValueMinLimit) ? - result : - durabilityValueMinLimit; + return (result >= durabilityValueMinLimit) + ? result + : durabilityValueMinLimit; } protected generateArmorDurability(botRole: string, maxDurability: number): number @@ -193,9 +193,9 @@ export class DurabilityLimitsHelper ); // Dont let armor dura go below the percent defined in config - return (result >= durabilityValueMinLimit) ? - result : - durabilityValueMinLimit; + return (result >= durabilityValueMinLimit) + ? result + : durabilityValueMinLimit; } protected getMinWeaponDeltaFromConfig(botRole: string): number diff --git a/project/src/helpers/HealthHelper.ts b/project/src/helpers/HealthHelper.ts index 7a67f1f2..aa934564 100644 --- a/project/src/helpers/HealthHelper.ts +++ b/project/src/helpers/HealthHelper.ts @@ -108,8 +108,8 @@ export class HealthHelper } else { - profileHealth[bodyPart] = pmcData.Health.BodyParts[bodyPart].Health.Maximum * - this.healthConfig.healthMultipliers.death; + profileHealth[bodyPart] = pmcData.Health.BodyParts[bodyPart].Health.Maximum + * this.healthConfig.healthMultipliers.death; } } @@ -172,8 +172,8 @@ export class HealthHelper { // Blacked body part target = Math.round( - pmcData.Health.BodyParts[healthModifier].Health.Maximum * - this.healthConfig.healthMultipliers.blacked, + pmcData.Health.BodyParts[healthModifier].Health.Maximum + * this.healthConfig.healthMultipliers.blacked, ); } diff --git a/project/src/helpers/HideoutHelper.ts b/project/src/helpers/HideoutHelper.ts index cf88cb96..55e83f88 100644 --- a/project/src/helpers/HideoutHelper.ts +++ b/project/src/helpers/HideoutHelper.ts @@ -75,8 +75,8 @@ export class HideoutHelper return this.httpResponse.appendErrorToOutput(this.eventOutputHolder.getOutput(sessionID)); } - const modifiedProductionTime = recipe.productionTime - - this.getCraftingSkillProductionTimeReduction(pmcData, recipe.productionTime); + const modifiedProductionTime = recipe.productionTime + - this.getCraftingSkillProductionTimeReduction(pmcData, recipe.productionTime); // @Important: Here we need to be very exact: // - normal recipe: Production time value is stored in attribute "productionType" with small "p" @@ -353,8 +353,8 @@ export class HideoutHelper */ protected updateScavCaseProductionTimer(pmcData: IPmcData, productionId: string): void { - const timeElapsed = (this.timeUtil.getTimestamp() - pmcData.Hideout.Production[productionId].StartTimestamp) - - pmcData.Hideout.Production[productionId].Progress; + const timeElapsed = (this.timeUtil.getTimestamp() - pmcData.Hideout.Production[productionId].StartTimestamp) + - pmcData.Hideout.Production[productionId].Progress; pmcData.Hideout.Production[productionId].Progress += timeElapsed; } @@ -398,8 +398,8 @@ export class HideoutHelper { // 1 resource last 14 min 27 sec, 1/14.45/60 = 0.00115 // 10-10-2021 From wiki, 1 resource last 12 minutes 38 seconds, 1/12.63333/60 = 0.00131 - let fuelDrainRate = this.databaseServer.getTables().hideout.settings.generatorFuelFlowRate * - this.hideoutConfig.runIntervalSeconds; + let fuelDrainRate = this.databaseServer.getTables().hideout.settings.generatorFuelFlowRate + * this.hideoutConfig.runIntervalSeconds; // implemented moddable bonus for fuel consumption bonus instead of using solar power variable as before const fuelBonus = pmcData.Bonuses.find((b) => b.type === "FuelConsumption"); const fuelBonusPercent = 1.0 - (fuelBonus ? Math.abs(fuelBonus.value) : 0) / 100; @@ -414,9 +414,9 @@ export class HideoutHelper { if (generatorArea.slots[i].item) { - let resourceValue = (generatorArea.slots[i].item[0].upd?.Resource) ? - generatorArea.slots[i].item[0].upd.Resource.Value : - null; + let resourceValue = (generatorArea.slots[i].item[0].upd?.Resource) + ? generatorArea.slots[i].item[0].upd.Resource.Value + : null; if (resourceValue === 0) { continue; @@ -424,9 +424,9 @@ export class HideoutHelper else if (!resourceValue) { const fuelItem = HideoutHelper.expeditionaryFuelTank; - resourceValue = generatorArea.slots[i].item[0]._tpl === fuelItem ? - 60 - fuelDrainRate : - 100 - fuelDrainRate; + resourceValue = generatorArea.slots[i].item[0]._tpl === fuelItem + ? 60 - fuelDrainRate + : 100 - fuelDrainRate; pointsConsumed = fuelDrainRate; } else @@ -542,9 +542,9 @@ export class HideoutHelper if (waterFilterArea.slots[i].item) { // How many units of filter are left - let resourceValue = (waterFilterArea.slots[i].item[0].upd?.Resource) ? - waterFilterArea.slots[i].item[0].upd.Resource.Value : - null; + let resourceValue = (waterFilterArea.slots[i].item[0].upd?.Resource) + ? waterFilterArea.slots[i].item[0].upd.Resource.Value + : null; if (!resourceValue) { // None left @@ -553,8 +553,8 @@ export class HideoutHelper } else { - pointsConsumed = (waterFilterArea.slots[i].item[0].upd.Resource.UnitsConsumed || 0) + - filterDrainRate; + pointsConsumed = (waterFilterArea.slots[i].item[0].upd.Resource.UnitsConsumed || 0) + + filterDrainRate; resourceValue -= filterDrainRate; } @@ -606,10 +606,9 @@ export class HideoutHelper baseFilterDrainRate: number, ): number { - const drainRateMultiplier = secondsSinceServerTick > totalProductionTime ? - (totalProductionTime - productionProgress) // more time passed than prod time, get total minus the current progress - : - secondsSinceServerTick; + const drainRateMultiplier = secondsSinceServerTick > totalProductionTime + ? (totalProductionTime - productionProgress) // more time passed than prod time, get total minus the current progress + : secondsSinceServerTick; // Multiply drain rate by calculated multiplier baseFilterDrainRate *= drainRateMultiplier; @@ -668,8 +667,8 @@ export class HideoutHelper Lasts for 17 hours 38 minutes and 49 seconds (23 hours 31 minutes and 45 seconds with elite hideout management skill), 300/17.64694/60/60 = 0.004722 */ - let filterDrainRate = this.databaseServer.getTables().hideout.settings.airFilterUnitFlowRate * - this.hideoutConfig.runIntervalSeconds; + let filterDrainRate = this.databaseServer.getTables().hideout.settings.airFilterUnitFlowRate + * this.hideoutConfig.runIntervalSeconds; // Hideout management resource consumption bonus: const hideoutManagementConsumptionBonus = 1.0 - this.getHideoutManagementConsumptionBonus(pmcData); filterDrainRate *= hideoutManagementConsumptionBonus; @@ -679,9 +678,9 @@ export class HideoutHelper { if (airFilterArea.slots[i].item) { - let resourceValue = (airFilterArea.slots[i].item[0].upd?.Resource) ? - airFilterArea.slots[i].item[0].upd.Resource.Value : - null; + let resourceValue = (airFilterArea.slots[i].item[0].upd?.Resource) + ? airFilterArea.slots[i].item[0].upd.Resource.Value + : null; if (!resourceValue) { resourceValue = 300 - filterDrainRate; @@ -781,8 +780,8 @@ export class HideoutHelper } */ // BSG finally fixed their settings, they now get loaded from the settings and used in the client - const coinCraftTimeSeconds = bitcoinProdData.productionTime / - (1 + (btcFarmCGs - 1) * this.databaseServer.getTables().hideout.settings.gpuBoostRate); + const coinCraftTimeSeconds = bitcoinProdData.productionTime + / (1 + (btcFarmCGs - 1) * this.databaseServer.getTables().hideout.settings.gpuBoostRate); while (btcProd.Progress > coinCraftTimeSeconds) { if (btcProd.Products.length < coinSlotCount) @@ -897,12 +896,12 @@ export class HideoutHelper // at level 1 you already get 0.5%, so it goes up until level 50. For some reason the wiki // says that it caps at level 51 with 25% but as per dump data that is incorrect apparently let roundedLevel = Math.floor(hideoutManagementSkill.Progress / 100); - roundedLevel = (roundedLevel === 51) ? - roundedLevel - 1 : - roundedLevel; + roundedLevel = (roundedLevel === 51) + ? roundedLevel - 1 + : roundedLevel; - return (roundedLevel * - this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement + return (roundedLevel + * this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement .ConsumptionReductionPerLevel) / 100; } @@ -1024,9 +1023,9 @@ export class HideoutHelper */ protected hideoutImprovementIsComplete(improvement: IHideoutImprovement): boolean { - return improvement?.completed ? - true : - false; + return improvement?.completed + ? true + : false; } /** @@ -1039,8 +1038,8 @@ export class HideoutHelper { const improvementDetails = pmcProfile.Hideout.Improvement[improvementId]; if ( - improvementDetails.completed === false && - improvementDetails.improveCompleteTimestamp < this.timeUtil.getTimestamp() + improvementDetails.completed === false + && improvementDetails.improveCompleteTimestamp < this.timeUtil.getTimestamp() ) { improvementDetails.completed = true; diff --git a/project/src/helpers/InRaidHelper.ts b/project/src/helpers/InRaidHelper.ts index bc4d02c5..952a134a 100644 --- a/project/src/helpers/InRaidHelper.ts +++ b/project/src/helpers/InRaidHelper.ts @@ -379,10 +379,10 @@ export class InRaidHelper const itemsToRemovePropertyFrom = postRaidProfile.Inventory.items.filter((x) => { // Has upd object + upd.SpawnedInSession property + not a quest item - return "upd" in x && "SpawnedInSession" in x.upd && - !dbItems[x._tpl]._props.QuestItem && - !(this.inRaidConfig.keepFiRSecureContainerOnDeath && - this.itemHelper.itemIsInsideContainer(x, "SecuredContainer", postRaidProfile.Inventory.items)); + return "upd" in x && "SpawnedInSession" in x.upd + && !dbItems[x._tpl]._props.QuestItem + && !(this.inRaidConfig.keepFiRSecureContainerOnDeath + && this.itemHelper.itemIsInsideContainer(x, "SecuredContainer", postRaidProfile.Inventory.items)); }); for (const item of itemsToRemovePropertyFrom) diff --git a/project/src/helpers/InventoryHelper.ts b/project/src/helpers/InventoryHelper.ts index 724e65fb..9bf19682 100644 --- a/project/src/helpers/InventoryHelper.ts +++ b/project/src/helpers/InventoryHelper.ts @@ -175,9 +175,9 @@ export class InventoryHelper catch (err) { // Callback failed - const message = typeof err === "string" ? - err : - this.localisationService.getText("http-unknown_error"); + const message = typeof err === "string" + ? err + : this.localisationService.getText("http-unknown_error"); return this.httpResponse.appendErrorToOutput(output, message); } @@ -405,9 +405,9 @@ export class InventoryHelper } catch (err) { - const errorText = typeof err === "string" ? - ` -> ${err}` : - ""; + const errorText = typeof err === "string" + ? ` -> ${err}` + : ""; this.logger.error(this.localisationService.getText("inventory-fill_container_failed", errorText)); return this.httpResponse.appendErrorToOutput( @@ -563,13 +563,13 @@ export class InventoryHelper if (requestItem.count > itemDetails._props.StackMaxSize) { let remainingCountOfItemToAdd = requestItem.count; - const calc = requestItem.count - - (Math.floor(requestItem.count / itemDetails._props.StackMaxSize) * - itemDetails._props.StackMaxSize); + const calc = requestItem.count + - (Math.floor(requestItem.count / itemDetails._props.StackMaxSize) + * itemDetails._props.StackMaxSize); - maxStackCount = (calc > 0) ? - maxStackCount + Math.floor(remainingCountOfItemToAdd / itemDetails._props.StackMaxSize) : - Math.floor(remainingCountOfItemToAdd / itemDetails._props.StackMaxSize); + maxStackCount = (calc > 0) + ? maxStackCount + Math.floor(remainingCountOfItemToAdd / itemDetails._props.StackMaxSize) + : Math.floor(remainingCountOfItemToAdd / itemDetails._props.StackMaxSize); // Iterate until totalCountOfPurchasedItem is 0 for (let i = 0; i < maxStackCount; i++) @@ -942,14 +942,14 @@ export class InventoryHelper const tmpSize = this.getSizeByInventoryItemHash(item._tpl, item._id, inventoryItemHash); const iW = tmpSize[0]; // x const iH = tmpSize[1]; // y - const fH = ((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" || - (item.location as Location).rotation === "Vertical") ? - iW : - iH; - const fW = ((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" || - (item.location as Location).rotation === "Vertical") ? - iH : - iW; + const fH = ((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" + || (item.location as Location).rotation === "Vertical") + ? iW + : iH; + const fW = ((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" + || (item.location as Location).rotation === "Vertical") + ? iH + : iW; const fillTo = (item.location as Location).x + fW; for (let y = 0; y < fH; y++) @@ -1002,9 +1002,9 @@ export class InventoryHelper else if (request.fromOwner.type.toLocaleLowerCase() === "mail") { // Split requests dont use 'use' but 'splitItem' property - const item = "splitItem" in request ? - request.splitItem : - request.item; + const item = "splitItem" in request + ? request.splitItem + : request.item; fromInventoryItems = this.dialogueHelper.getMessageItemContents(request.fromOwner.id, sessionId, item); fromType = "mail"; } @@ -1077,12 +1077,12 @@ export class InventoryHelper this.logger.error(this.localisationService.getText("inventory-stash_not_found", stashTPL)); } - const stashX = stashItemDetails[1]._props.Grids[0]._props.cellsH !== 0 ? - stashItemDetails[1]._props.Grids[0]._props.cellsH : - 10; - const stashY = stashItemDetails[1]._props.Grids[0]._props.cellsV !== 0 ? - stashItemDetails[1]._props.Grids[0]._props.cellsV : - 66; + const stashX = stashItemDetails[1]._props.Grids[0]._props.cellsH !== 0 + ? stashItemDetails[1]._props.Grids[0]._props.cellsH + : 10; + const stashY = stashItemDetails[1]._props.Grids[0]._props.cellsV !== 0 + ? stashItemDetails[1]._props.Grids[0]._props.cellsV + : 66; return [stashX, stashY]; } diff --git a/project/src/helpers/ItemHelper.ts b/project/src/helpers/ItemHelper.ts index f0451687..1c47c474 100644 --- a/project/src/helpers/ItemHelper.ts +++ b/project/src/helpers/ItemHelper.ts @@ -68,11 +68,11 @@ class ItemHelper } // Is item valid - return !itemDetails[1]._props.QuestItem && - itemDetails[1]._type === "Item" && - invalidBaseTypes.every((x) => !this.isOfBaseclass(tpl, x)) && - this.getItemPrice(tpl) > 0 && - !this.itemFilterService.isItemBlacklisted(tpl); + return !itemDetails[1]._props.QuestItem + && itemDetails[1]._type === "Item" + && invalidBaseTypes.every((x) => !this.isOfBaseclass(tpl, x)) + && this.getItemPrice(tpl) > 0 + && !this.itemFilterService.isItemBlacklisted(tpl); } /** @@ -378,9 +378,9 @@ class ItemHelper // Weapon // Get max dura from props, if it isnt there use repairable max dura value - const maxDurability = (itemDetails._props.MaxDurability) ? - itemDetails._props.MaxDurability : - repairable.MaxDurability; + const maxDurability = (itemDetails._props.MaxDurability) + ? itemDetails._props.MaxDurability + : repairable.MaxDurability; const durability = repairable.Durability / maxDurability; if (!durability) @@ -474,8 +474,8 @@ class ItemHelper public hasBuyRestrictions(itemToCheck: Item): boolean { if ( - itemToCheck.upd?.BuyRestrictionCurrent !== undefined && - itemToCheck.upd?.BuyRestrictionMax !== undefined + itemToCheck.upd?.BuyRestrictionCurrent !== undefined + && itemToCheck.upd?.BuyRestrictionMax !== undefined ) { return true; @@ -574,18 +574,18 @@ class ItemHelper public findBarterItems(by: "tpl" | "id", items: Item[], barterItemId: string): Item[] { // find required items to take after buying (handles multiple items) - const barterIDs = typeof barterItemId === "string" ? - [barterItemId] : - barterItemId; + const barterIDs = typeof barterItemId === "string" + ? [barterItemId] + : barterItemId; let barterItems: Item[] = []; for (const barterID of barterIDs) { const filterResult = items.filter((item) => { - return by === "tpl" ? - (item._tpl === barterID) : - (item._id === barterID); + return by === "tpl" + ? (item._tpl === barterID) + : (item._id === barterID); }); barterItems = Object.assign(barterItems, filterResult); @@ -625,11 +625,11 @@ class ItemHelper // Do not replace important ID's if ( - item._id === pmcData.Inventory.equipment || - item._id === pmcData.Inventory.questRaidItems || - item._id === pmcData.Inventory.questStashItems || - item._id === pmcData.Inventory.sortingTable || - item._id === pmcData.Inventory.stash + item._id === pmcData.Inventory.equipment + || item._id === pmcData.Inventory.questRaidItems + || item._id === pmcData.Inventory.questStashItems + || item._id === pmcData.Inventory.sortingTable + || item._id === pmcData.Inventory.stash ) { continue; @@ -904,9 +904,9 @@ class ItemHelper sizeUp = sizeUp < itemTemplate._props.ExtraSizeUp ? itemTemplate._props.ExtraSizeUp : sizeUp; sizeDown = sizeDown < itemTemplate._props.ExtraSizeDown ? itemTemplate._props.ExtraSizeDown : sizeDown; sizeLeft = sizeLeft < itemTemplate._props.ExtraSizeLeft ? itemTemplate._props.ExtraSizeLeft : sizeLeft; - sizeRight = sizeRight < itemTemplate._props.ExtraSizeRight ? - itemTemplate._props.ExtraSizeRight : - sizeRight; + sizeRight = sizeRight < itemTemplate._props.ExtraSizeRight + ? itemTemplate._props.ExtraSizeRight + : sizeRight; } } @@ -954,9 +954,9 @@ class ItemHelper while (currentStoredCartridgeCount < ammoBoxMaxCartridgeCount) { const remainingSpace = ammoBoxMaxCartridgeCount - currentStoredCartridgeCount; - const cartridgeCountToAdd = (remainingSpace < maxPerStack) ? - remainingSpace : - maxPerStack; + const cartridgeCountToAdd = (remainingSpace < maxPerStack) + ? remainingSpace + : maxPerStack; // Add cartridge item into items array ammoBox.push(this.createCartridges(ammoBox[0]._id, cartridgeTpl, cartridgeCountToAdd, location)); @@ -1057,9 +1057,9 @@ class ItemHelper while (currentStoredCartridgeCount < desiredStackCount) { // Get stack size of cartridges - let cartridgeCountToAdd = (desiredStackCount <= cartridgeMaxStackSize) ? - desiredStackCount : - cartridgeMaxStackSize; + let cartridgeCountToAdd = (desiredStackCount <= cartridgeMaxStackSize) + ? desiredStackCount + : cartridgeMaxStackSize; // Ensure we don't go over the max stackcount size const remainingSpace = desiredStackCount - currentStoredCartridgeCount; diff --git a/project/src/helpers/NotificationSendHelper.ts b/project/src/helpers/NotificationSendHelper.ts index f70a6290..788d0dbd 100644 --- a/project/src/helpers/NotificationSendHelper.ts +++ b/project/src/helpers/NotificationSendHelper.ts @@ -85,9 +85,9 @@ export class NotificationSendHelper protected getDialog(sessionId: string, messageType: MessageType, senderDetails: IUserDialogInfo): Dialogue { // Use trader id if sender is trader, otherwise use nickname - const key = (senderDetails.info.MemberCategory === MemberCategory.TRADER) ? - senderDetails._id : - senderDetails.info.Nickname; + const key = (senderDetails.info.MemberCategory === MemberCategory.TRADER) + ? senderDetails._id + : senderDetails.info.Nickname; const dialogueData = this.saveServer.getProfile(sessionId).dialogues; const isNewDialogue = !(key in dialogueData); let dialogue: Dialogue = dialogueData[key]; diff --git a/project/src/helpers/ProfileHelper.ts b/project/src/helpers/ProfileHelper.ts index f852b50c..95ebea98 100644 --- a/project/src/helpers/ProfileHelper.ts +++ b/project/src/helpers/ProfileHelper.ts @@ -139,8 +139,8 @@ export class ProfileHelper } if ( - !this.sessionIdMatchesProfileId(profile.info.id, sessionID) && - this.nicknameMatches(profile.characters.pmc.Info.LowerNickname, nicknameRequest.nickname) + !this.sessionIdMatchesProfileId(profile.info.id, sessionID) + && this.nicknameMatches(profile.characters.pmc.Info.LowerNickname, nicknameRequest.nickname) ) { return true; diff --git a/project/src/helpers/QuestHelper.ts b/project/src/helpers/QuestHelper.ts index 18893d95..4af49a8f 100644 --- a/project/src/helpers/QuestHelper.ts +++ b/project/src/helpers/QuestHelper.ts @@ -69,9 +69,9 @@ export class QuestHelper { const quest = pmcData.Quests?.find((q) => q.qid === questId); - return quest ? - quest.status : - QuestStatus.Locked; + return quest + ? quest.status + : QuestStatus.Locked; } /** @@ -279,9 +279,9 @@ export class QuestHelper if (item._id === reward.target) { if ( - (item.parentId !== undefined) && (item.parentId === "hideout") && - (item.upd !== undefined) && (item.upd.StackObjectsCount !== undefined) && - (item.upd.StackObjectsCount > 1) + (item.parentId !== undefined) && (item.parentId === "hideout") + && (item.upd !== undefined) && (item.upd.StackObjectsCount !== undefined) + && (item.upd.StackObjectsCount > 1) ) { item.upd.StackObjectsCount = 1; @@ -330,9 +330,9 @@ export class QuestHelper // Iterate over all rewards with the desired status, flatten out items that have a type of Item const questRewards = quest.rewards[QuestStatus[status]] .flatMap((reward: Reward) => - reward.type === "Item" ? - this.processReward(reward) : - [] + reward.type === "Item" + ? this.processReward(reward) + : [] ); return questRewards; @@ -413,9 +413,9 @@ export class QuestHelper // e.g. Quest A passed in, quest B is looped over and has requirement of A to be started, include it const acceptedQuestCondition = quest.conditions.AvailableForStart.find((x) => { - return x._parent === "Quest" && - x._props.target === startedQuestId && - x._props.status[0] === QuestStatus.Started; + return x._parent === "Quest" + && x._props.target === startedQuestId + && x._props.status[0] === QuestStatus.Started; }); // Not found, skip quest @@ -447,8 +447,8 @@ export class QuestHelper } // Include if quest found in profile and is started or ready to hand in - return startedQuestInProfile && - ([QuestStatus.Started, QuestStatus.AvailableForFinish].includes(startedQuestInProfile.status)); + return startedQuestInProfile + && ([QuestStatus.Started, QuestStatus.AvailableForFinish].includes(startedQuestInProfile.status)); }); return this.getQuestsWithOnlyLevelRequirementStartCondition(eligibleQuests); @@ -470,9 +470,9 @@ export class QuestHelper const acceptedQuestCondition = q.conditions.AvailableForStart.find( (c) => { - return c._parent === "Quest" && - c._props.target === failedQuestId && - c._props.status[0] === QuestStatus.Fail; + return c._parent === "Quest" + && c._props.target === failedQuestId + && c._props.status[0] === QuestStatus.Fail; }, ); @@ -704,8 +704,8 @@ export class QuestHelper // blank or is a guid, use description instead const startedMessageText = this.getQuestLocaleIdFromDb(startedMessageTextId); if ( - !startedMessageText || startedMessageText.trim() === "" || startedMessageText.toLowerCase() === "test" || - startedMessageText.length === 24 + !startedMessageText || startedMessageText.trim() === "" || startedMessageText.toLowerCase() === "test" + || startedMessageText.length === 24 ) { return questDescriptionId; @@ -850,9 +850,9 @@ export class QuestHelper // Get hideout crafts and find those that match by areatype/required level/end product tpl - hope for just one match const hideoutProductions = this.databaseServer.getTables().hideout.production; const matchingProductions = hideoutProductions.filter((x) => - x.areaType === Number.parseInt(craftUnlockReward.traderId) && - x.requirements.some((x) => x.requiredLevel === craftUnlockReward.loyaltyLevel) && - x.endProduct === craftUnlockReward.items[0]._tpl + x.areaType === Number.parseInt(craftUnlockReward.traderId) + && x.requirements.some((x) => x.requiredLevel === craftUnlockReward.loyaltyLevel) + && x.endProduct === craftUnlockReward.items[0]._tpl ); // More/less than 1 match, above filtering wasn't strict enough diff --git a/project/src/helpers/RagfairHelper.ts b/project/src/helpers/RagfairHelper.ts index e8790996..3f8f9d39 100644 --- a/project/src/helpers/RagfairHelper.ts +++ b/project/src/helpers/RagfairHelper.ts @@ -73,9 +73,9 @@ export class RagfairHelper if (info.linkedSearchId) { const data = this.ragfairLinkedItemService.getLinkedItems(info.linkedSearchId); - result = !data ? - [] : - [...data]; + result = !data + ? [] + : [...data]; } // Case: category diff --git a/project/src/helpers/RagfairOfferHelper.ts b/project/src/helpers/RagfairOfferHelper.ts index 9de15133..0a53a8bc 100644 --- a/project/src/helpers/RagfairOfferHelper.ts +++ b/project/src/helpers/RagfairOfferHelper.ts @@ -534,8 +534,8 @@ export class RagfairOfferHelper const isDefaultUserOffer = offer.user.memberType === MemberCategory.DEFAULT; if ( - pmcProfile.Info.Level < this.databaseServer.getTables().globals.config.RagFair.minUserLevel && - isDefaultUserOffer + pmcProfile.Info.Level < this.databaseServer.getTables().globals.config.RagFair.minUserLevel + && isDefaultUserOffer ) { // Skip item if player is < global unlock level (default is 15) and item is from a dynamically generated source @@ -597,8 +597,8 @@ export class RagfairOfferHelper } if ( - (item.upd.MedKit || item.upd.Repairable) && - !this.itemQualityInRange(item, searchRequest.conditionFrom, searchRequest.conditionTo) + (item.upd.MedKit || item.upd.Repairable) + && !this.itemQualityInRange(item, searchRequest.conditionFrom, searchRequest.conditionTo) ) { return false; diff --git a/project/src/helpers/RagfairSellHelper.ts b/project/src/helpers/RagfairSellHelper.ts index bbe9777c..5804df65 100644 --- a/project/src/helpers/RagfairSellHelper.ts +++ b/project/src/helpers/RagfairSellHelper.ts @@ -40,10 +40,12 @@ export class RagfairSellHelper const listedPriceAboveAverage = playerListedPriceRub > averageOfferPriceRub; // Get sell chance multiplier - const multiplier = listedPriceAboveAverage ? - this.ragfairConfig.sell.chance.overpriced // Player price is over average listing price - : - this.getSellMultiplierWhenPlayerPriceIsBelowAverageListingPrice(averageOfferPriceRub, playerListedPriceRub); + const multiplier = listedPriceAboveAverage + ? this.ragfairConfig.sell.chance.overpriced // Player price is over average listing price + : this.getSellMultiplierWhenPlayerPriceIsBelowAverageListingPrice( + averageOfferPriceRub, + playerListedPriceRub, + ); return Math.round(baseSellChancePercent * (averageOfferPriceRub / playerListedPriceRub * multiplier)); } @@ -59,9 +61,9 @@ export class RagfairSellHelper playerListedPriceRub: number, ): number { - return (playerListedPriceRub < averageOfferPriceRub) ? - this.ragfairConfig.sell.chance.underpriced : - 1; + return (playerListedPriceRub < averageOfferPriceRub) + ? this.ragfairConfig.sell.chance.underpriced + : 1; } /** diff --git a/project/src/helpers/RagfairServerHelper.ts b/project/src/helpers/RagfairServerHelper.ts index 06fc2646..5f12bb48 100644 --- a/project/src/helpers/RagfairServerHelper.ts +++ b/project/src/helpers/RagfairServerHelper.ts @@ -96,8 +96,8 @@ export class RagfairServerHelper // Don't include damaged ammo packs if ( - this.ragfairConfig.dynamic.blacklist.damagedAmmoPacks && itemDetails[1]._parent === BaseClasses.AMMO_BOX && - itemDetails[1]._name.includes("_damaged") + this.ragfairConfig.dynamic.blacklist.damagedAmmoPacks && itemDetails[1]._parent === BaseClasses.AMMO_BOX + && itemDetails[1]._name.includes("_damaged") ) { return false; @@ -175,8 +175,8 @@ export class RagfairServerHelper // Item Types to return one of if ( - isWeaponPreset || - this.itemHelper.isOfBaseclasses(itemDetails[1]._id, this.ragfairConfig.dynamic.showAsSingleStack) + isWeaponPreset + || this.itemHelper.isOfBaseclasses(itemDetails[1]._id, this.ragfairConfig.dynamic.showAsSingleStack) ) { return 1; diff --git a/project/src/helpers/RagfairSortHelper.ts b/project/src/helpers/RagfairSortHelper.ts index 22450fe8..afbfcc5b 100644 --- a/project/src/helpers/RagfairSortHelper.ts +++ b/project/src/helpers/RagfairSortHelper.ts @@ -75,11 +75,11 @@ export class RagfairSortHelper const nameA = locale[`${tplA} Name`] || tplA; const nameB = locale[`${tplB} Name`] || tplB; - return (nameA < nameB) ? - -1 : - (nameA > nameB) ? - 1 : - 0; + return (nameA < nameB) + ? -1 + : (nameA > nameB) + ? 1 + : 0; } /** diff --git a/project/src/helpers/RepairHelper.ts b/project/src/helpers/RepairHelper.ts index 84b9fe5d..6aa88118 100644 --- a/project/src/helpers/RepairHelper.ts +++ b/project/src/helpers/RepairHelper.ts @@ -77,14 +77,14 @@ export class RepairHelper // the code below generates a random degradation on the weapon durability if (applyMaxDurabilityDegradation) { - const randomisedWearAmount = isArmor ? - this.getRandomisedArmorRepairDegradationValue( + const randomisedWearAmount = isArmor + ? this.getRandomisedArmorRepairDegradationValue( itemToRepairDetails._props.ArmorMaterial, useRepairKit, itemCurrentMaxDurability, traderQualityMultipler, - ) : - this.getRandomisedWeaponRepairDegradationValue( + ) + : this.getRandomisedWeaponRepairDegradationValue( itemToRepairDetails._props, useRepairKit, itemCurrentMaxDurability, @@ -117,13 +117,13 @@ export class RepairHelper { const armorMaterialSettings = this.databaseServer.getTables().globals.config.ArmorMaterials[armorMaterial]; - const minMultiplier = isRepairKit ? - armorMaterialSettings.MinRepairKitDegradation : - armorMaterialSettings.MinRepairDegradation; + const minMultiplier = isRepairKit + ? armorMaterialSettings.MinRepairKitDegradation + : armorMaterialSettings.MinRepairDegradation; - const maxMultiplier = isRepairKit ? - armorMaterialSettings.MaxRepairKitDegradation : - armorMaterialSettings.MaxRepairDegradation; + const maxMultiplier = isRepairKit + ? armorMaterialSettings.MaxRepairKitDegradation + : armorMaterialSettings.MaxRepairDegradation; const duraLossPercent = this.randomUtil.getFloat(minMultiplier, maxMultiplier); const duraLossMultipliedByTraderMultiplier = (duraLossPercent * armorMax) * traderQualityMultipler; @@ -138,12 +138,12 @@ export class RepairHelper traderQualityMultipler: number, ): number { - const minRepairDeg = isRepairKit ? - itemProps.MinRepairKitDegradation : - itemProps.MinRepairDegradation; - let maxRepairDeg = isRepairKit ? - itemProps.MaxRepairKitDegradation : - itemProps.MaxRepairDegradation; + const minRepairDeg = isRepairKit + ? itemProps.MinRepairKitDegradation + : itemProps.MinRepairDegradation; + let maxRepairDeg = isRepairKit + ? itemProps.MaxRepairKitDegradation + : itemProps.MaxRepairDegradation; // WORKAROUND: Some items are always 0 when repairkit is true if (maxRepairDeg === 0) diff --git a/project/src/helpers/TraderHelper.ts b/project/src/helpers/TraderHelper.ts index 19056e3c..7f0af7d8 100644 --- a/project/src/helpers/TraderHelper.ts +++ b/project/src/helpers/TraderHelper.ts @@ -87,9 +87,9 @@ export class TraderHelper */ public getTraderAssortsByTraderId(traderId: string): ITraderAssort { - return traderId === Traders.FENCE ? - this.fenceService.getRawFenceAssorts() : - this.databaseServer.getTables().traders[traderId].assort; + return traderId === Traders.FENCE + ? this.fenceService.getRawFenceAssorts() + : this.databaseServer.getTables().traders[traderId].assort; } /** @@ -199,9 +199,9 @@ export class TraderHelper { const newStanding = currentStanding + standingToAdd; - return newStanding < 0 ? - 0 : - newStanding; + return newStanding < 0 + ? 0 + : newStanding; } /** @@ -227,10 +227,10 @@ export class TraderHelper const loyalty = loyaltyLevels[level]; if ( - (loyalty.minLevel <= pmcData.Info.Level && - loyalty.minSalesSum <= pmcData.TradersInfo[traderID].salesSum && - loyalty.minStanding <= pmcData.TradersInfo[traderID].standing) && - targetLevel < 4 + (loyalty.minLevel <= pmcData.Info.Level + && loyalty.minSalesSum <= pmcData.TradersInfo[traderID].salesSum + && loyalty.minStanding <= pmcData.TradersInfo[traderID].standing) + && targetLevel < 4 ) { // level reached @@ -386,9 +386,9 @@ export class TraderHelper const barterScheme = traderAssorts.barter_scheme[item._id][0][0]; // Convert into roubles - const roubleAmount = barterScheme._tpl === Money.ROUBLES ? - barterScheme.count : - this.handbookHelper.inRUB(barterScheme.count, barterScheme._tpl); + const roubleAmount = barterScheme._tpl === Money.ROUBLES + ? barterScheme.count + : this.handbookHelper.inRUB(barterScheme.count, barterScheme._tpl); // Existing price smaller in dict than current iteration, overwrite if (this.highestTraderPriceItems[item._tpl] ?? 0 < roubleAmount) diff --git a/project/src/loaders/ModTypeCheck.ts b/project/src/loaders/ModTypeCheck.ts index 12f302b5..56b0cd29 100644 --- a/project/src/loaders/ModTypeCheck.ts +++ b/project/src/loaders/ModTypeCheck.ts @@ -70,11 +70,11 @@ export class ModTypeCheck */ public isPostV3Compatible(mod: any): boolean { - return this.isPreAkiLoad(mod) || - this.isPostAkiLoad(mod) || - this.isPostDBAkiLoad(mod) || - this.isPreAkiLoadAsync(mod) || - this.isPostAkiLoadAsync(mod) || - this.isPostDBAkiLoadAsync(mod); + return this.isPreAkiLoad(mod) + || this.isPostAkiLoad(mod) + || this.isPostDBAkiLoad(mod) + || this.isPreAkiLoadAsync(mod) + || this.isPostAkiLoadAsync(mod) + || this.isPostDBAkiLoadAsync(mod); } } diff --git a/project/src/loaders/PreAkiModLoader.ts b/project/src/loaders/PreAkiModLoader.ts index 3568eb83..17f98067 100644 --- a/project/src/loaders/PreAkiModLoader.ts +++ b/project/src/loaders/PreAkiModLoader.ts @@ -176,8 +176,8 @@ export class PreAkiModLoader implements IModLoader // if the mod has library dependencies check if these dependencies are bundled in the server, if not install them if ( - modToValidate.dependencies && Object.keys(modToValidate.dependencies).length > 0 && - !this.vfs.exists(`${this.basepath}${modFolderName}/node_modules`) + modToValidate.dependencies && Object.keys(modToValidate.dependencies).length > 0 + && !this.vfs.exists(`${this.basepath}${modFolderName}/node_modules`) ) { this.autoInstallDependencies(`${this.basepath}${modFolderName}`, modToValidate); diff --git a/project/src/models/external/HttpFramework.ts b/project/src/models/external/HttpFramework.ts index fa5fc86a..8c3d0326 100644 --- a/project/src/models/external/HttpFramework.ts +++ b/project/src/models/external/HttpFramework.ts @@ -62,8 +62,8 @@ export const Listen = (basePath: string) => { const routesHandles = this.handlers[req.method]; - return Object.keys(this.handlers).some((meth) => meth === req.method) && - Object.keys(routesHandles).some((route) => (new RegExp(route)).test(req.url)); + return Object.keys(this.handlers).some((meth) => meth === req.method) + && Object.keys(routesHandles).some((route) => (new RegExp(route)).test(req.url)); }; // The actual handle method dispatches the request to the registered handlers diff --git a/project/src/servers/ConfigServer.ts b/project/src/servers/ConfigServer.ts index 5fec377a..d6128e37 100644 --- a/project/src/servers/ConfigServer.ts +++ b/project/src/servers/ConfigServer.ts @@ -36,9 +36,9 @@ export class ConfigServer this.logger.debug("Importing configs..."); // Get all filepaths - const filepath = (globalThis.G_RELEASE_CONFIGURATION) ? - "Aki_Data/Server/configs/" : - "./assets/configs/"; + const filepath = (globalThis.G_RELEASE_CONFIGURATION) + ? "Aki_Data/Server/configs/" + : "./assets/configs/"; const files = this.vfs.getFiles(filepath); // Add file content to result diff --git a/project/src/servers/WebSocketServer.ts b/project/src/servers/WebSocketServer.ts index 3b804a85..aece4db8 100644 --- a/project/src/servers/WebSocketServer.ts +++ b/project/src/servers/WebSocketServer.ts @@ -82,9 +82,9 @@ export class WebSocketServer return this.localisationService.getRandomTextThatMatchesPartialKey("server_start_meme_"); } - return (globalThis.G_RELEASE_CONFIGURATION) ? - `${this.localisationService.getText("server_start_success")}!` : - this.localisationService.getText("server_start_success"); + return (globalThis.G_RELEASE_CONFIGURATION) + ? `${this.localisationService.getText("server_start_success")}!` + : this.localisationService.getText("server_start_success"); } public isConnectionWebSocket(sessionID: string): boolean diff --git a/project/src/servers/http/AkiHttpListener.ts b/project/src/servers/http/AkiHttpListener.ts index cd481fb6..77f48918 100644 --- a/project/src/servers/http/AkiHttpListener.ts +++ b/project/src/servers/http/AkiHttpListener.ts @@ -141,9 +141,9 @@ export class AkiHttpListener implements IHttpListener if (globalThis.G_LOG_REQUESTS) { // Parse quest info into object - const data = (typeof info === "object") ? - info : - this.jsonUtil.deserialize(info); + const data = (typeof info === "object") + ? info + : this.jsonUtil.deserialize(info); const log = new Request(req.method, new RequestData(req.url, req.headers, data)); this.requestsLogger.info(`REQUEST=${this.jsonUtil.serialize(log)}`); diff --git a/project/src/services/BotEquipmentFilterService.ts b/project/src/services/BotEquipmentFilterService.ts index 2abb7aa0..c9d99111 100644 --- a/project/src/services/BotEquipmentFilterService.ts +++ b/project/src/services/BotEquipmentFilterService.ts @@ -54,9 +54,9 @@ export class BotEquipmentFilterService { const pmcProfile = this.profileHelper.getPmcProfile(sessionId); - const botRole = (botGenerationDetails.isPmc) ? - "pmc" : - botGenerationDetails.role; + const botRole = (botGenerationDetails.isPmc) + ? "pmc" + : botGenerationDetails.role; const botEquipmentBlacklist = this.getBotEquipmentBlacklist(botRole, botLevel); const botEquipmentWhitelist = this.getBotEquipmentWhitelist(botRole, botLevel); const botWeightingAdjustments = this.getBotWeightingAdjustments(botRole, botLevel); @@ -175,8 +175,8 @@ export class BotEquipmentFilterService // No equipment blacklist found, skip if ( - !blacklistDetailsForBot || Object.keys(blacklistDetailsForBot).length === 0 || - !blacklistDetailsForBot.blacklist + !blacklistDetailsForBot || Object.keys(blacklistDetailsForBot).length === 0 + || !blacklistDetailsForBot.blacklist ) { return null; @@ -220,8 +220,8 @@ export class BotEquipmentFilterService // No config found, skip if ( - !botEquipmentConfig || Object.keys(botEquipmentConfig).length === 0 || - !botEquipmentConfig.weightingAdjustmentsByBotLevel + !botEquipmentConfig || Object.keys(botEquipmentConfig).length === 0 + || !botEquipmentConfig.weightingAdjustmentsByBotLevel ) { return null; @@ -244,8 +244,8 @@ export class BotEquipmentFilterService // No config found, skip if ( - !botEquipmentConfig || Object.keys(botEquipmentConfig).length === 0 || - !botEquipmentConfig.weightingAdjustmentsByPlayerLevel + !botEquipmentConfig || Object.keys(botEquipmentConfig).length === 0 + || !botEquipmentConfig.weightingAdjustmentsByPlayerLevel ) { return null; diff --git a/project/src/services/BotLootCacheService.ts b/project/src/services/BotLootCacheService.ts index bb7f3895..76828d14 100644 --- a/project/src/services/BotLootCacheService.ts +++ b/project/src/services/BotLootCacheService.ts @@ -165,66 +165,66 @@ export class BotLootCacheService this.sortPoolByRagfairPrice(combinedPoolTemplates); // use whitelist if array has values, otherwise process above sorted pools - const specialLootItems = (botJsonTemplate.generation.items.specialItems.whitelist?.length > 0) ? - botJsonTemplate.generation.items.specialItems.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : - specialLootTemplates.filter((template) => - !(this.isBulletOrGrenade(template._props) || - this.isMagazine(template._props)) + const specialLootItems = (botJsonTemplate.generation.items.specialItems.whitelist?.length > 0) + ? botJsonTemplate.generation.items.specialItems.whitelist.map((x) => this.itemHelper.getItem(x)[1]) + : specialLootTemplates.filter((template) => + !(this.isBulletOrGrenade(template._props) + || this.isMagazine(template._props)) ); - const healingItems = (botJsonTemplate.generation.items.healing.whitelist?.length > 0) ? - botJsonTemplate.generation.items.healing.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : - combinedPoolTemplates.filter((template) => - this.isMedicalItem(template._props) && - template._parent !== BaseClasses.STIMULATOR && - template._parent !== BaseClasses.DRUGS + const healingItems = (botJsonTemplate.generation.items.healing.whitelist?.length > 0) + ? botJsonTemplate.generation.items.healing.whitelist.map((x) => this.itemHelper.getItem(x)[1]) + : combinedPoolTemplates.filter((template) => + this.isMedicalItem(template._props) + && template._parent !== BaseClasses.STIMULATOR + && template._parent !== BaseClasses.DRUGS ); - const drugItems = (botJsonTemplate.generation.items.drugs.whitelist?.length > 0) ? - botJsonTemplate.generation.items.drugs.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : - combinedPoolTemplates.filter((template) => - this.isMedicalItem(template._props) && - template._parent === BaseClasses.DRUGS + const drugItems = (botJsonTemplate.generation.items.drugs.whitelist?.length > 0) + ? botJsonTemplate.generation.items.drugs.whitelist.map((x) => this.itemHelper.getItem(x)[1]) + : combinedPoolTemplates.filter((template) => + this.isMedicalItem(template._props) + && template._parent === BaseClasses.DRUGS ); - const stimItems = (botJsonTemplate.generation.items.stims.whitelist?.length > 0) ? - botJsonTemplate.generation.items.stims.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : - combinedPoolTemplates.filter((template) => - this.isMedicalItem(template._props) && - template._parent === BaseClasses.STIMULATOR + const stimItems = (botJsonTemplate.generation.items.stims.whitelist?.length > 0) + ? botJsonTemplate.generation.items.stims.whitelist.map((x) => this.itemHelper.getItem(x)[1]) + : combinedPoolTemplates.filter((template) => + this.isMedicalItem(template._props) + && template._parent === BaseClasses.STIMULATOR ); - const grenadeItems = (botJsonTemplate.generation.items.grenades.whitelist?.length > 0) ? - botJsonTemplate.generation.items.grenades.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : - combinedPoolTemplates.filter((template) => this.isGrenade(template._props)); + const grenadeItems = (botJsonTemplate.generation.items.grenades.whitelist?.length > 0) + ? botJsonTemplate.generation.items.grenades.whitelist.map((x) => this.itemHelper.getItem(x)[1]) + : combinedPoolTemplates.filter((template) => this.isGrenade(template._props)); // Get loot items (excluding magazines, bullets, grenades and healing items) const backpackLootItems = backpackLootTemplates.filter((template) => // biome-ignore lint/complexity/useSimplifiedLogicExpression: - !this.isBulletOrGrenade(template._props) && - !this.isMagazine(template._props) && + !this.isBulletOrGrenade(template._props) + && !this.isMagazine(template._props) // && !this.isMedicalItem(template._props) // Disabled for now as followSanitar has a lot of med items as loot - !this.isGrenade(template._props) + && !this.isGrenade(template._props) ); // Get pocket loot const pocketLootItems = pocketLootTemplates.filter((template) => // biome-ignore lint/complexity/useSimplifiedLogicExpression: - !this.isBulletOrGrenade(template._props) && - !this.isMagazine(template._props) && - !this.isMedicalItem(template._props) && - !this.isGrenade(template._props) && - ("Height" in template._props) && - ("Width" in template._props) + !this.isBulletOrGrenade(template._props) + && !this.isMagazine(template._props) + && !this.isMedicalItem(template._props) + && !this.isGrenade(template._props) + && ("Height" in template._props) + && ("Width" in template._props) ); // Get vest loot items const vestLootItems = vestLootTemplates.filter((template) => // biome-ignore lint/complexity/useSimplifiedLogicExpression: - !this.isBulletOrGrenade(template._props) && - !this.isMagazine(template._props) && - !this.isMedicalItem(template._props) && - !this.isGrenade(template._props) + !this.isBulletOrGrenade(template._props) + && !this.isMagazine(template._props) + && !this.isMedicalItem(template._props) + && !this.isGrenade(template._props) ); this.lootCache[botRole].healingItems = healingItems; diff --git a/project/src/services/BotWeaponModLimitService.ts b/project/src/services/BotWeaponModLimitService.ts index 052756a7..99020cd8 100644 --- a/project/src/services/BotWeaponModLimitService.ts +++ b/project/src/services/BotWeaponModLimitService.ts @@ -121,10 +121,10 @@ export class BotWeaponModLimitService // Mod is a mount that can hold only scopes and limit is reached (dont want to add empty mounts if limit is reached) if ( - this.itemHelper.isOfBaseclass(modTemplate._id, BaseClasses.MOUNT) && - modTemplate._props.Slots.some((x) => x._name === "mod_scope") && - modTemplate._props.Slots.length === 1 && - modLimits.scope.count >= modLimits.scopeMax + this.itemHelper.isOfBaseclass(modTemplate._id, BaseClasses.MOUNT) + && modTemplate._props.Slots.some((x) => x._name === "mod_scope") + && modTemplate._props.Slots.length === 1 + && modLimits.scope.count >= modLimits.scopeMax ) { return true; @@ -144,10 +144,10 @@ export class BotWeaponModLimitService // Mod is a mount that can hold only flashlights ad limit is reached (dont want to add empty mounts if limit is reached) if ( - this.itemHelper.isOfBaseclass(modTemplate._id, BaseClasses.MOUNT) && - modTemplate._props.Slots.some((x) => x._name === "mod_flashlight") && - modTemplate._props.Slots.length === 1 && - modLimits.scope.count >= modLimits.scopeMax + this.itemHelper.isOfBaseclass(modTemplate._id, BaseClasses.MOUNT) + && modTemplate._props.Slots.some((x) => x._name === "mod_flashlight") + && modTemplate._props.Slots.length === 1 + && modLimits.scope.count >= modLimits.scopeMax ) { return true; diff --git a/project/src/services/FenceService.ts b/project/src/services/FenceService.ts index 77aa47c0..f1e53b17 100644 --- a/project/src/services/FenceService.ts +++ b/project/src/services/FenceService.ts @@ -279,8 +279,8 @@ export class FenceService */ protected incrementPartialRefreshTime(): void { - this.nextMiniRefreshTimestamp = this.timeUtil.getTimestamp() + - this.traderConfig.fence.partialRefreshTimeSeconds; + this.nextMiniRefreshTimestamp = this.timeUtil.getTimestamp() + + this.traderConfig.fence.partialRefreshTimeSeconds; } /** @@ -294,14 +294,14 @@ export class FenceService const desiredTotalCount = this.traderConfig.fence.assortSize; const actualTotalCount = this.fenceAssort.items.reduce((count, item) => { - return item.slotId === "hideout" ? - count + 1 : - count; + return item.slotId === "hideout" + ? count + 1 + : count; }, 0); - return actualTotalCount < desiredTotalCount ? - (desiredTotalCount - actualTotalCount) + existingItemCountToReplace : - existingItemCountToReplace; + return actualTotalCount < desiredTotalCount + ? (desiredTotalCount - actualTotalCount) + existingItemCountToReplace + : existingItemCountToReplace; } /** @@ -506,9 +506,9 @@ export class FenceService if (this.itemHelper.isOfBaseclass(itemDbDetails._id, BaseClasses.AMMO)) { // No override, use stack max size from item db - return itemDbDetails._props.StackMaxSize === 1 ? - 1 : - this.randomUtil.getInt(itemDbDetails._props.StackMinRandom, itemDbDetails._props.StackMaxRandom); + return itemDbDetails._props.StackMaxSize === 1 + ? 1 + : this.randomUtil.getInt(itemDbDetails._props.StackMinRandom, itemDbDetails._props.StackMaxRandom); } return 1; @@ -658,8 +658,8 @@ export class FenceService // Roll from 0 to 9999, then divide it by 100: 9999 = 99.99% const randomChance = this.randomUtil.getInt(0, 9999) / 100; - return randomChance > removalChance && - !itemsBeingDeleted.includes(weaponMod._id); + return randomChance > removalChance + && !itemsBeingDeleted.includes(weaponMod._id); } /** @@ -688,12 +688,12 @@ export class FenceService // Randomise armor durability if ( - (itemDetails._parent === BaseClasses.ARMOR || - itemDetails._parent === BaseClasses.HEADWEAR || - itemDetails._parent === BaseClasses.VEST || - itemDetails._parent === BaseClasses.ARMOREDEQUIPMENT || - itemDetails._parent === BaseClasses.FACECOVER) && - itemDetails._props.MaxDurability > 0 + (itemDetails._parent === BaseClasses.ARMOR + || itemDetails._parent === BaseClasses.HEADWEAR + || itemDetails._parent === BaseClasses.VEST + || itemDetails._parent === BaseClasses.ARMOREDEQUIPMENT + || itemDetails._parent === BaseClasses.FACECOVER) + && itemDetails._props.MaxDurability > 0 ) { const armorMaxDurabilityLimits = this.traderConfig.fence.armorMaxDurabilityPercentMinMax; @@ -740,8 +740,8 @@ export class FenceService // Mechanical key + has limited uses if ( - this.itemHelper.isOfBaseclass(itemDetails._id, BaseClasses.KEY_MECHANICAL) && - itemDetails._props.MaximumNumberOfUsage > 1 + this.itemHelper.isOfBaseclass(itemDetails._id, BaseClasses.KEY_MECHANICAL) + && itemDetails._props.MaximumNumberOfUsage > 1 ) { itemToAdjust.upd.Key = { diff --git a/project/src/services/InsuranceService.ts b/project/src/services/InsuranceService.ts index 5f0f1724..86055e5e 100644 --- a/project/src/services/InsuranceService.ts +++ b/project/src/services/InsuranceService.ts @@ -147,9 +147,9 @@ export class InsuranceService public sendLostInsuranceMessage(sessionId: string, locationName = ""): void { const dialogueTemplates = this.databaseServer.getTables().traders[Traders.PRAPOR].dialogue; // todo: get trader id instead of hard coded prapor - const randomResponseId = locationName?.toLowerCase() === "laboratory" ? - this.randomUtil.getArrayValue(dialogueTemplates.insuranceFailedLabs) : - this.randomUtil.getArrayValue(dialogueTemplates.insuranceFailed); + const randomResponseId = locationName?.toLowerCase() === "laboratory" + ? this.randomUtil.getArrayValue(dialogueTemplates.insuranceFailedLabs) + : this.randomUtil.getArrayValue(dialogueTemplates.insuranceFailed); this.mailSendService.sendLocalisedNpcMessageToPlayer( sessionId, @@ -202,9 +202,9 @@ export class InsuranceService } const insuranceReturnTimeBonus = pmcData.Bonuses.find((b) => b.type === "InsuranceReturnTime"); - const insuranceReturnTimeBonusPercent = 1.0 - (insuranceReturnTimeBonus ? - Math.abs(insuranceReturnTimeBonus.value) : - 0) / 100; + const insuranceReturnTimeBonusPercent = 1.0 - (insuranceReturnTimeBonus + ? Math.abs(insuranceReturnTimeBonus.value) + : 0) / 100; const traderMinReturnAsSeconds = trader.insurance.min_return_hour * TimeUtil.oneHourAsSeconds; const traderMaxReturnAsSeconds = trader.insurance.max_return_hour * TimeUtil.oneHourAsSeconds; diff --git a/project/src/services/LocalisationService.ts b/project/src/services/LocalisationService.ts index df610e64..525e9e25 100644 --- a/project/src/services/LocalisationService.ts +++ b/project/src/services/LocalisationService.ts @@ -26,9 +26,9 @@ export class LocalisationService { const localeFileDirectory = path.join( process.cwd(), - globalThis.G_RELEASE_CONFIGURATION ? - "Aki_Data/Server/database/locales/server" : - "./assets/database/locales/server", + globalThis.G_RELEASE_CONFIGURATION + ? "Aki_Data/Server/database/locales/server" + : "./assets/database/locales/server", ); this.i18n = new I18n( { diff --git a/project/src/services/MailSendService.ts b/project/src/services/MailSendService.ts index 42e9b45a..41f9ec78 100644 --- a/project/src/services/MailSendService.ts +++ b/project/src/services/MailSendService.ts @@ -285,8 +285,8 @@ export class MailSendService // TODO: clean up old code here // Offer Sold notifications are now separate from the main notification if ( - [MessageType.NPC_TRADER, MessageType.FLEAMARKET_MESSAGE].includes(senderDialog.type) && - messageDetails.ragfairDetails + [MessageType.NPC_TRADER, MessageType.FLEAMARKET_MESSAGE].includes(senderDialog.type) + && messageDetails.ragfairDetails ) { const offerSoldMessage = this.notifierHelper.createRagfairOfferSoldNotification( @@ -348,9 +348,9 @@ export class MailSendService hasRewards: false, // The default dialog message has no rewards, can be added later via addRewardItemsToMessage() rewardCollected: false, // The default dialog message has no rewards, can be added later via addRewardItemsToMessage() systemData: messageDetails.systemData ? messageDetails.systemData : undefined, // Used by ragfair / localised messages that need "location" or "time" - profileChangeEvents: (messageDetails.profileChangeEvents?.length === 0) ? - messageDetails.profileChangeEvents : - undefined, // no one knows, its never been used in any dumps + profileChangeEvents: (messageDetails.profileChangeEvents?.length === 0) + ? messageDetails.profileChangeEvents + : undefined, // no one knows, its never been used in any dumps }; // Clean up empty system data diff --git a/project/src/services/PaymentService.ts b/project/src/services/PaymentService.ts index 63ad9d1e..ed6334c2 100644 --- a/project/src/services/PaymentService.ts +++ b/project/src/services/PaymentService.ts @@ -69,8 +69,8 @@ export class PaymentService else { // If the item is money, add its count to the currencyAmounts object. - currencyAmounts[item._tpl] = (currencyAmounts[item._tpl] || 0) + - request.scheme_items[index].count; + currencyAmounts[item._tpl] = (currencyAmounts[item._tpl] || 0) + + request.scheme_items[index].count; } } } diff --git a/project/src/services/PmcChatResponseService.ts b/project/src/services/PmcChatResponseService.ts index 3c91543e..597fc338 100644 --- a/project/src/services/PmcChatResponseService.ts +++ b/project/src/services/PmcChatResponseService.ts @@ -167,9 +167,9 @@ export class PmcChatResponseService */ protected stripCapitalistion(isVictim: boolean): boolean { - const chance = isVictim ? - this.pmcResponsesConfig.victim.stripCapitalisationChancePercent : - this.pmcResponsesConfig.killer.stripCapitalisationChancePercent; + const chance = isVictim + ? this.pmcResponsesConfig.victim.stripCapitalisationChancePercent + : this.pmcResponsesConfig.killer.stripCapitalisationChancePercent; return this.randomUtil.getChance100(chance); } @@ -181,9 +181,9 @@ export class PmcChatResponseService */ protected allCaps(isVictim: boolean): boolean { - const chance = isVictim ? - this.pmcResponsesConfig.victim.allCapsChancePercent : - this.pmcResponsesConfig.killer.allCapsChancePercent; + const chance = isVictim + ? this.pmcResponsesConfig.victim.allCapsChancePercent + : this.pmcResponsesConfig.killer.allCapsChancePercent; return this.randomUtil.getChance100(chance); } @@ -195,9 +195,9 @@ export class PmcChatResponseService */ appendSuffixToMessageEnd(isVictim: boolean): boolean { - const chance = isVictim ? - this.pmcResponsesConfig.victim.appendBroToMessageEndChancePercent : - this.pmcResponsesConfig.killer.appendBroToMessageEndChancePercent; + const chance = isVictim + ? this.pmcResponsesConfig.victim.appendBroToMessageEndChancePercent + : this.pmcResponsesConfig.killer.appendBroToMessageEndChancePercent; return this.randomUtil.getChance100(chance); } @@ -209,9 +209,9 @@ export class PmcChatResponseService */ protected chooseResponseType(isVictim = true): string { - const responseWeights = isVictim ? - this.pmcResponsesConfig.victim.responseTypeWeights : - this.pmcResponsesConfig.killer.responseTypeWeights; + const responseWeights = isVictim + ? this.pmcResponsesConfig.victim.responseTypeWeights + : this.pmcResponsesConfig.killer.responseTypeWeights; return this.weightedRandomHelper.getWeightedValue(responseWeights); } diff --git a/project/src/services/ProfileFixerService.ts b/project/src/services/ProfileFixerService.ts index 3fdb0212..7dfe1b39 100644 --- a/project/src/services/ProfileFixerService.ts +++ b/project/src/services/ProfileFixerService.ts @@ -82,17 +82,17 @@ export class ProfileFixerService this.reorderHideoutAreasWithResouceInputs(pmcProfile); if ( - pmcProfile.Hideout.Areas[HideoutAreas.GENERATOR].slots.length < - (6 + - this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + pmcProfile.Hideout.Areas[HideoutAreas.GENERATOR].slots.length + < (6 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots .Generator.Slots) ) { this.logger.debug("Updating generator area slots to a size of 6 + hideout management skill"); this.addEmptyObjectsToHideoutAreaSlots( HideoutAreas.GENERATOR, - 6 + - this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + 6 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots .Generator .Slots, pmcProfile, @@ -100,34 +100,34 @@ export class ProfileFixerService } if ( - pmcProfile.Hideout.Areas[HideoutAreas.WATER_COLLECTOR].slots.length < - (1 + - this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + pmcProfile.Hideout.Areas[HideoutAreas.WATER_COLLECTOR].slots.length + < (1 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots .WaterCollector.Slots) ) { this.logger.debug("Updating water collector area slots to a size of 1 + hideout management skill"); this.addEmptyObjectsToHideoutAreaSlots( HideoutAreas.WATER_COLLECTOR, - 1 + - this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + 1 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots .WaterCollector.Slots, pmcProfile, ); } if ( - pmcProfile.Hideout.Areas[HideoutAreas.AIR_FILTERING].slots.length < - (3 + - this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + pmcProfile.Hideout.Areas[HideoutAreas.AIR_FILTERING].slots.length + < (3 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots .AirFilteringUnit.Slots) ) { this.logger.debug("Updating air filter area slots to a size of 3 + hideout management skill"); this.addEmptyObjectsToHideoutAreaSlots( HideoutAreas.AIR_FILTERING, - 3 + - this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + 3 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots .AirFilteringUnit.Slots, pmcProfile, ); @@ -135,17 +135,17 @@ export class ProfileFixerService // BTC Farm doesnt have extra slots for hideout management, but we still check for modded stuff!! if ( - pmcProfile.Hideout.Areas[HideoutAreas.BITCOIN_FARM].slots.length < - (50 + - this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + pmcProfile.Hideout.Areas[HideoutAreas.BITCOIN_FARM].slots.length + < (50 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots .BitcoinFarm.Slots) ) { this.logger.debug("Updating bitcoin farm area slots to a size of 50 + hideout management skill"); this.addEmptyObjectsToHideoutAreaSlots( HideoutAreas.BITCOIN_FARM, - 50 + - this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots + 50 + + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots .BitcoinFarm.Slots, pmcProfile, ); @@ -553,8 +553,8 @@ export class ProfileFixerService for (const currentRepeatable of pmcProfile.RepeatableQuests) { if ( - !(currentRepeatable.changeRequirement && - currentRepeatable.activeQuests.every( + !(currentRepeatable.changeRequirement + && currentRepeatable.activeQuests.every( (x) => (typeof x.changeCost !== "undefined" && typeof x.changeStandingCost !== "undefined"), )) ) @@ -800,8 +800,8 @@ export class ProfileFixerService { return profileBonuses.find( (x) => - x.type === bonus.type && - x.templateId === bonus.templateId, + x.type === bonus.type + && x.templateId === bonus.templateId, ); } @@ -809,16 +809,16 @@ export class ProfileFixerService { return profileBonuses.find( (x) => - x.type === bonus.type && - x.value === bonus.value && - x.visible === bonus.visible, + x.type === bonus.type + && x.value === bonus.value + && x.visible === bonus.visible, ); } return profileBonuses.find( (x) => - x.type === bonus.type && - x.value === bonus.value, + x.type === bonus.type + && x.value === bonus.value, ); } diff --git a/project/src/services/RagfairCategoriesService.ts b/project/src/services/RagfairCategoriesService.ts index a0624b1b..a8039963 100644 --- a/project/src/services/RagfairCategoriesService.ts +++ b/project/src/services/RagfairCategoriesService.ts @@ -58,9 +58,9 @@ export class RagfairCategoriesService const itemId = offer.items[0]._tpl; if (increment) { - categories[itemId] = categories[itemId] ? - categories[itemId] + 1 : - 1; + categories[itemId] = categories[itemId] + ? categories[itemId] + 1 + : 1; } else { diff --git a/project/src/services/RagfairPriceService.ts b/project/src/services/RagfairPriceService.ts index 435dd0cd..3eba729a 100644 --- a/project/src/services/RagfairPriceService.ts +++ b/project/src/services/RagfairPriceService.ts @@ -298,9 +298,9 @@ export class RagfairPriceService implements OnLoad // Only adjust price if difference is > a percent AND item price passes threshhold set in config if ( - priceDifferencePercent > - this.ragfairConfig.dynamic.offerAdjustment.maxPriceDifferenceBelowHandbookPercent && - itemPrice >= this.ragfairConfig.dynamic.offerAdjustment.priceThreshholdRub + priceDifferencePercent + > this.ragfairConfig.dynamic.offerAdjustment.maxPriceDifferenceBelowHandbookPercent + && itemPrice >= this.ragfairConfig.dynamic.offerAdjustment.priceThreshholdRub ) { // const itemDetails = this.itemHelper.getItem(itemTpl); diff --git a/project/src/services/RagfairTaxService.ts b/project/src/services/RagfairTaxService.ts index edfa3a3e..084b5fe0 100644 --- a/project/src/services/RagfairTaxService.ts +++ b/project/src/services/RagfairTaxService.ts @@ -62,8 +62,8 @@ export class RagfairTaxService const requirementsPrice = requirementsValue * (sellInOnePiece ? 1 : offerItemCount); const itemTaxMult = this.databaseServer.getTables().globals.config.RagFair.communityItemTax / 100.0; - const requirementTaxMult = this.databaseServer.getTables().globals.config.RagFair.communityRequirementTax / - 100.0; + const requirementTaxMult = this.databaseServer.getTables().globals.config.RagFair.communityRequirementTax + / 100.0; let itemPriceMult = Math.log10(itemWorth / requirementsPrice); let requirementPriceMult = Math.log10(requirementsPrice / itemWorth); @@ -83,12 +83,12 @@ export class RagfairTaxService const hideoutFleaTaxDiscountBonus = pmcData.Bonuses.find((b) => b.type === "RagfairCommission"); const taxDiscountPercent = hideoutFleaTaxDiscountBonus ? Math.abs(hideoutFleaTaxDiscountBonus.value) : 0; - const tax = itemWorth * itemTaxMult * itemPriceMult + - requirementsPrice * requirementTaxMult * requirementPriceMult; + const tax = itemWorth * itemTaxMult * itemPriceMult + + requirementsPrice * requirementTaxMult * requirementPriceMult; const discountedTax = tax * (1.0 - taxDiscountPercent / 100.0); - const itemComissionMult = itemTemplate._props.RagFairCommissionModifier ? - itemTemplate._props.RagFairCommissionModifier : - 1; + const itemComissionMult = itemTemplate._props.RagFairCommissionModifier + ? itemTemplate._props.RagFairCommissionModifier + : 1; if (item.upd.Buff) { @@ -144,8 +144,8 @@ export class RagfairTaxService if ("Key" in item.upd && itemTemplate._props.MaximumNumberOfUsage > 0) { - worth = worth / itemTemplate._props.MaximumNumberOfUsage * - (itemTemplate._props.MaximumNumberOfUsage - item.upd.Key.NumberOfUsages); + worth = worth / itemTemplate._props.MaximumNumberOfUsage + * (itemTemplate._props.MaximumNumberOfUsage - item.upd.Key.NumberOfUsages); } if ("Resource" in item.upd && itemTemplate._props.MaxResource > 0) @@ -171,10 +171,10 @@ export class RagfairTaxService if ("Repairable" in item.upd && itemTemplate._props.armorClass > 0) { const num2 = 0.01 * (0.0 ** item.upd.Repairable.MaxDurability); - worth = worth * ((item.upd.Repairable.MaxDurability / itemTemplate._props.Durability) - num2) - - Math.floor( - itemTemplate._props.RepairCost * - (item.upd.Repairable.MaxDurability - item.upd.Repairable.Durability), + worth = worth * ((item.upd.Repairable.MaxDurability / itemTemplate._props.Durability) - num2) + - Math.floor( + itemTemplate._props.RepairCost + * (item.upd.Repairable.MaxDurability - item.upd.Repairable.Durability), ); } diff --git a/project/src/services/RepairService.ts b/project/src/services/RepairService.ts index a2cdaa91..9b1cd272 100644 --- a/project/src/services/RepairService.ts +++ b/project/src/services/RepairService.ts @@ -69,9 +69,9 @@ export class RepairService const priceCoef = this.traderHelper.getLoyaltyLevel(traderId, pmcData).repair_price_coef; const traderRepairDetails = this.traderHelper.getTrader(traderId, sessionID).repair; const repairQualityMultiplier = traderRepairDetails.quality; - const repairRate = (priceCoef <= 0) ? - 1 : - (priceCoef / 100 + 1); + const repairRate = (priceCoef <= 0) + ? 1 + : (priceCoef / 100 + 1); const itemToRepairDetails = this.databaseServer.getTables().templates.items[itemToRepair._tpl]; const repairItemIsArmor = !!itemToRepairDetails._props.ArmorMaterial; @@ -156,8 +156,8 @@ export class RepairService ): void { if ( - repairDetails.repairedByKit && - this.itemHelper.isOfBaseclass(repairDetails.repairedItem._tpl, BaseClasses.WEAPON) + repairDetails.repairedByKit + && this.itemHelper.isOfBaseclass(repairDetails.repairedItem._tpl, BaseClasses.WEAPON) ) { const skillPoints = this.getWeaponRepairSkillPoints(repairDetails); @@ -167,8 +167,8 @@ export class RepairService // Handle kit repairs of armor if ( - repairDetails.repairedByKit && - this.itemHelper.isOfBaseclasses(repairDetails.repairedItem._tpl, [BaseClasses.ARMOR, BaseClasses.VEST]) + repairDetails.repairedByKit + && this.itemHelper.isOfBaseclasses(repairDetails.repairedItem._tpl, [BaseClasses.ARMOR, BaseClasses.VEST]) ) { const itemDetails = this.itemHelper.getItem(repairDetails.repairedItem._tpl); @@ -186,11 +186,11 @@ export class RepairService } const isHeavyArmor = itemDetails[1]._props.ArmorType === "Heavy"; - const vestSkillToLevel = isHeavyArmor ? - SkillTypes.HEAVY_VESTS : - SkillTypes.LIGHT_VESTS; - const pointsToAddToVestSkill = repairDetails.repairPoints * - this.repairConfig.armorKitSkillPointGainPerRepairPointMultiplier; + const vestSkillToLevel = isHeavyArmor + ? SkillTypes.HEAVY_VESTS + : SkillTypes.LIGHT_VESTS; + const pointsToAddToVestSkill = repairDetails.repairPoints + * this.repairConfig.armorKitSkillPointGainPerRepairPointMultiplier; this.profileHelper.addSkillPointsToPlayer(pmcData, vestSkillToLevel, pointsToAddToVestSkill); } @@ -200,9 +200,9 @@ export class RepairService if (repairDetails.repairedByKit) { const intRepairMultiplier = - (this.itemHelper.isOfBaseclass(repairDetails.repairedItem._tpl, BaseClasses.WEAPON)) ? - this.repairConfig.repairKitIntellectGainMultiplier.weapon : - this.repairConfig.repairKitIntellectGainMultiplier.armor; + (this.itemHelper.isOfBaseclass(repairDetails.repairedItem._tpl, BaseClasses.WEAPON)) + ? this.repairConfig.repairKitIntellectGainMultiplier.weapon + : this.repairConfig.repairKitIntellectGainMultiplier.armor; // limit gain to a max value defined in config.maxIntellectGainPerRepair intellectGainedFromRepair = Math.min( @@ -339,8 +339,8 @@ export class RepairService const globalRepairSettings = globals.config.RepairSettings; const intellectRepairPointsPerLevel = globals.config.SkillsSettings.Intellect.RepairPointsCostReduction; - const profileIntellectLevel = this.profileHelper.getSkillFromProfile(pmcData, SkillTypes.INTELLECT)?.Progress ?? - 0; + const profileIntellectLevel = this.profileHelper.getSkillFromProfile(pmcData, SkillTypes.INTELLECT)?.Progress + ?? 0; const intellectPointReduction = intellectRepairPointsPerLevel * Math.trunc(profileIntellectLevel / 100); if (isArmor) diff --git a/project/src/services/SeasonalEventService.ts b/project/src/services/SeasonalEventService.ts index 6e97737d..b606d40e 100644 --- a/project/src/services/SeasonalEventService.ts +++ b/project/src/services/SeasonalEventService.ts @@ -237,8 +237,8 @@ export class SeasonalEventService // Current date is between start/end dates if ( - currentDate >= eventStartDate && - currentDate <= eventEndDate + currentDate >= eventStartDate + && currentDate <= eventEndDate ) { this.christmasEventActive = SeasonalEventType[event.type] === SeasonalEventType.CHRISTMAS; diff --git a/project/src/services/mod/CustomItemService.ts b/project/src/services/mod/CustomItemService.ts index 80b3b8ff..5ae95575 100644 --- a/project/src/services/mod/CustomItemService.ts +++ b/project/src/services/mod/CustomItemService.ts @@ -120,9 +120,9 @@ export class CustomItemService */ protected getOrGenerateIdForItem(newId: string): string { - return (newId === "") ? - this.hashUtil.generate() : - newId; + return (newId === "") + ? this.hashUtil.generate() + : newId; } /** diff --git a/project/src/utils/DatabaseImporter.ts b/project/src/utils/DatabaseImporter.ts index 802d041a..b22e83f4 100644 --- a/project/src/utils/DatabaseImporter.ts +++ b/project/src/utils/DatabaseImporter.ts @@ -45,9 +45,9 @@ export class DatabaseImporter implements OnLoad */ public getSptDataPath(): string { - return (globalThis.G_RELEASE_CONFIGURATION) ? - "Aki_Data/Server/" : - "./assets/"; + return (globalThis.G_RELEASE_CONFIGURATION) + ? "Aki_Data/Server/" + : "./assets/"; } public async onLoad(): Promise @@ -109,9 +109,9 @@ export class DatabaseImporter implements OnLoad (fileWithPath: string, data: string) => this.onReadValidate(fileWithPath, data), ); - const validation = (this.valid === VaildationResult.FAILED || this.valid === VaildationResult.NOT_FOUND) ? - "." : - ""; + const validation = (this.valid === VaildationResult.FAILED || this.valid === VaildationResult.NOT_FOUND) + ? "." + : ""; this.logger.info(`${this.localisationService.getText("importing_database_finish")}${validation}`); this.databaseServer.setTables(dataToImport); } diff --git a/project/src/utils/HttpFileUtil.ts b/project/src/utils/HttpFileUtil.ts index faa4cd29..358471cc 100644 --- a/project/src/utils/HttpFileUtil.ts +++ b/project/src/utils/HttpFileUtil.ts @@ -16,8 +16,8 @@ export class HttpFileUtil public sendFile(resp: ServerResponse, file: any): void { const pathSlic = file.split("/"); - const type = this.httpServerHelper.getMimeText(pathSlic[pathSlic.length - 1].split(".").at(-1)) || - this.httpServerHelper.getMimeText("txt"); + const type = this.httpServerHelper.getMimeText(pathSlic[pathSlic.length - 1].split(".").at(-1)) + || this.httpServerHelper.getMimeText("txt"); const fileStream = fs.createReadStream(file); fileStream.on("open", function() diff --git a/project/src/utils/Watermark.ts b/project/src/utils/Watermark.ts index 72d72659..226d649d 100644 --- a/project/src/utils/Watermark.ts +++ b/project/src/utils/Watermark.ts @@ -110,9 +110,9 @@ export class Watermark */ public getVersionTag(withEftVersion = false): string { - const versionTag = (globalThis.G_DEBUG_CONFIGURATION) ? - `${this.akiConfig.akiVersion} - ${this.localisationService.getText("bleeding_edge_build")}` : - this.akiConfig.akiVersion; + const versionTag = (globalThis.G_DEBUG_CONFIGURATION) + ? `${this.akiConfig.akiVersion} - ${this.localisationService.getText("bleeding_edge_build")}` + : this.akiConfig.akiVersion; if (withEftVersion) { @@ -130,9 +130,9 @@ export class Watermark */ public getInGameVersionLabel(): string { - const versionTag = (globalThis.G_DEBUG_CONFIGURATION) ? - `${this.akiConfig.akiVersion} - BLEEDINGEDGE` : - this.akiConfig.akiVersion; + const versionTag = (globalThis.G_DEBUG_CONFIGURATION) + ? `${this.akiConfig.akiVersion} - BLEEDINGEDGE` + : this.akiConfig.akiVersion; return `${this.akiConfig.projectName} ${versionTag}`; } From 32b47bdc186c88f53a7c136453b35c6eba84bcc9 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 12:31:52 -0500 Subject: [PATCH 40/41] Formatting Change - When a statement can be moved into a single line and still be under the maximum line length, it is. --- project/dprint.json | 2 +- project/gulpfile.mjs | 15 +- project/src/ErrorHandler.ts | 5 +- .../src/callbacks/CustomizationCallbacks.ts | 5 +- project/src/callbacks/DialogueCallbacks.ts | 7 +- project/src/callbacks/GameCallbacks.ts | 12 +- project/src/callbacks/HandbookCallbacks.ts | 4 +- project/src/callbacks/HealthCallbacks.ts | 6 +- project/src/callbacks/HttpCallbacks.ts | 4 +- project/src/callbacks/InventoryCallbacks.ts | 4 +- project/src/callbacks/NoteCallbacks.ts | 4 +- project/src/callbacks/NotifierCallbacks.ts | 10 +- project/src/callbacks/PresetCallbacks.ts | 4 +- project/src/callbacks/ProfileCallbacks.ts | 41 +- project/src/callbacks/RepairCallbacks.ts | 4 +- project/src/callbacks/TradeCallbacks.ts | 4 +- project/src/callbacks/WishlistCallbacks.ts | 4 +- project/src/controllers/BotController.ts | 15 +- .../src/controllers/ClientLogController.ts | 4 +- project/src/controllers/DialogueController.ts | 6 +- project/src/controllers/GameController.ts | 23 +- project/src/controllers/HideoutController.ts | 51 +- .../src/controllers/InsuranceController.ts | 5 +- .../src/controllers/InventoryController.ts | 30 +- project/src/controllers/LocationController.ts | 5 +- project/src/controllers/MatchController.ts | 29 +- project/src/controllers/NoteController.ts | 9 +- .../src/controllers/PresetBuildController.ts | 13 +- project/src/controllers/ProfileController.ts | 14 +- project/src/controllers/QuestController.ts | 14 +- project/src/controllers/RagfairController.ts | 29 +- .../controllers/RepeatableQuestController.ts | 18 +- project/src/controllers/WeatherController.ts | 7 +- project/src/controllers/WishlistController.ts | 4 +- project/src/di/Container.ts | 4 +- project/src/di/Router.ts | 10 +- .../generators/BotEquipmentModGenerator.ts | 31 +- project/src/generators/BotGenerator.ts | 22 +- .../src/generators/BotInventoryGenerator.ts | 54 +- project/src/generators/BotLootGenerator.ts | 44 +- project/src/generators/BotWeaponGenerator.ts | 28 +- .../generators/FenceBaseAssortGenerator.ts | 5 +- project/src/generators/LocationGenerator.ts | 71 +- project/src/generators/LootGenerator.ts | 36 +- project/src/generators/PlayerScavGenerator.ts | 10 +- .../src/generators/RagfairAssortGenerator.ts | 5 +- .../src/generators/RagfairOfferGenerator.ts | 47 +- .../generators/RepeatableQuestGenerator.ts | 137 +- .../src/generators/ScavCaseRewardGenerator.ts | 15 +- project/src/generators/WeatherGenerator.ts | 4 +- .../InternalMagazineInventoryMagGen.ts | 4 +- .../implementations/UbglExternalMagGen.ts | 4 +- project/src/helpers/BotDifficultyHelper.ts | 8 +- project/src/helpers/BotGeneratorHelper.ts | 20 +- project/src/helpers/BotHelper.ts | 4 +- .../src/helpers/BotWeaponGeneratorHelper.ts | 15 +- project/src/helpers/DialogueHelper.ts | 19 +- project/src/helpers/DurabilityLimitsHelper.ts | 8 +- project/src/helpers/HandbookHelper.ts | 8 +- project/src/helpers/HealthHelper.ts | 5 +- project/src/helpers/HideoutHelper.ts | 25 +- project/src/helpers/HttpServerHelper.ts | 4 +- project/src/helpers/InRaidHelper.ts | 5 +- project/src/helpers/InventoryHelper.ts | 47 +- project/src/helpers/ItemHelper.ts | 35 +- project/src/helpers/NotifierHelper.ts | 9 +- project/src/helpers/PaymentHelper.ts | 4 +- project/src/helpers/PresetHelper.ts | 14 +- project/src/helpers/ProfileHelper.ts | 10 +- project/src/helpers/QuestHelper.ts | 31 +- project/src/helpers/RagfairHelper.ts | 4 +- project/src/helpers/RagfairSellHelper.ts | 9 +- project/src/helpers/RagfairSortHelper.ts | 6 +- project/src/helpers/RepairHelper.ts | 13 +- project/src/helpers/SecureContainerHelper.ts | 4 +- project/src/helpers/TradeHelper.ts | 12 +- project/src/helpers/TraderAssortHelper.ts | 6 +- project/src/helpers/TraderHelper.ts | 12 +- project/src/helpers/WeightedRandomHelper.ts | 5 +- project/src/models/external/HttpFramework.ts | 6 +- .../src/models/spt/server/IDatabaseTables.ts | 6 +- project/src/routers/EventOutputHolder.ts | 17 +- project/src/routers/HttpRouter.ts | 4 +- .../src/routers/dynamic/BotDynamicRouter.ts | 66 +- .../routers/dynamic/BundleDynamicRouter.ts | 21 +- .../dynamic/CustomizationDynamicRouter.ts | 24 +- .../src/routers/dynamic/DataDynamicRouter.ts | 43 +- .../src/routers/dynamic/HttpDynamicRouter.ts | 43 +- .../routers/dynamic/InraidDynamicRouter.ts | 24 +- .../routers/dynamic/LocationDynamicRouter.ts | 24 +- .../routers/dynamic/NotifierDynamicRouter.ts | 57 +- .../routers/dynamic/TraderDynamicRouter.ts | 38 +- .../CustomizationItemEventRouter.ts | 5 +- .../item_events/HideoutItemEventRouter.ts | 4 +- .../item_events/InsuranceItemEventRouter.ts | 4 +- .../item_events/PresetBuildItemEventRouter.ts | 4 +- .../item_events/RagfairItemEventRouter.ts | 4 +- .../item_events/RepairItemEventRouter.ts | 9 +- .../item_events/TradeItemEventRouter.ts | 4 +- .../item_events/WishlistItemEventRouter.ts | 9 +- .../routers/save_load/HealthSaveLoadRouter.ts | 9 +- .../routers/save_load/InraidSaveLoadRouter.ts | 9 +- .../save_load/InsuranceSaveLoadRouter.ts | 4 +- .../save_load/ProfileSaveLoadRouter.ts | 9 +- .../routers/serializers/ImageSerializer.ts | 4 +- .../routers/serializers/NotifySerializer.ts | 6 +- project/src/routers/static/BotStaticRouter.ts | 24 +- .../src/routers/static/BundleStaticRouter.ts | 21 +- .../routers/static/ClientLogStaticRouter.ts | 21 +- .../static/CustomizationStaticRouter.ts | 24 +- .../src/routers/static/DataStaticRouter.ts | 160 +- .../src/routers/static/DialogStaticRouter.ts | 295 ++- .../src/routers/static/GameStaticRouter.ts | 135 +- .../src/routers/static/HealthStaticRouter.ts | 35 +- .../src/routers/static/InraidStaticRouter.ts | 77 +- .../routers/static/InsuranceStaticRouter.ts | 24 +- .../routers/static/ItemEventStaticRouter.ts | 24 +- .../routers/static/LauncherStaticRouter.ts | 186 +- .../routers/static/LocationStaticRouter.ts | 35 +- .../src/routers/static/MatchStaticRouter.ts | 320 ++- .../routers/static/NotifierStaticRouter.ts | 38 +- .../src/routers/static/PresetStaticRouter.ts | 24 +- .../src/routers/static/ProfileStaticRouter.ts | 175 +- .../src/routers/static/QuestStaticRouter.ts | 35 +- .../src/routers/static/RagfairStaticRouter.ts | 88 +- .../src/routers/static/TraderStaticRouter.ts | 24 +- .../src/routers/static/WeatherStaticRouter.ts | 21 +- project/src/servers/ConfigServer.ts | 4 +- project/src/servers/SaveServer.ts | 5 +- project/src/servers/WebSocketServer.ts | 9 +- project/src/servers/http/AkiHttpListener.ts | 20 +- .../src/services/BotEquipmentFilterService.ts | 4 +- project/src/services/BotLootCacheService.ts | 13 +- project/src/services/FenceService.ts | 43 +- project/src/services/InsuranceService.ts | 16 +- project/src/services/LocalisationService.ts | 14 +- project/src/services/MailSendService.ts | 5 +- project/src/services/MatchLocationService.ts | 20 +- project/src/services/ProfileFixerService.ts | 81 +- .../src/services/ProfileSnapshotService.ts | 4 +- .../src/services/RagfairCategoriesService.ts | 8 +- project/src/services/RagfairPriceService.ts | 18 +- project/src/services/RepairService.ts | 35 +- project/src/services/SeasonalEventService.ts | 5 +- project/src/services/mod/CustomItemService.ts | 12 +- .../mod/dynamicRouter/DynamicRouterMod.ts | 5 +- .../dynamicRouter/DynamicRouterModService.ts | 6 +- project/src/services/mod/onLoad/OnLoadMod.ts | 5 +- .../services/mod/onLoad/OnLoadModService.ts | 6 +- .../mod/onUpdate/OnUpdateModService.ts | 6 +- .../mod/staticRouter/StaticRouterMod.ts | 5 +- .../staticRouter/StaticRouterModService.ts | 6 +- project/src/utils/DatabaseImporter.ts | 4 +- project/src/utils/HashUtil.ts | 4 +- project/src/utils/HttpFileUtil.ts | 4 +- project/src/utils/HttpResponseUtil.ts | 22 +- project/src/utils/ImporterUtil.ts | 42 +- project/src/utils/JsonUtil.ts | 12 +- project/src/utils/ObjectId.ts | 4 +- project/src/utils/RandomUtil.ts | 21 +- project/src/utils/VFS.ts | 14 +- project/src/utils/Watermark.ts | 4 +- .../utils/logging/AbstractWinstonLogger.ts | 62 +- .../src/utils/logging/WinstonMainLogger.ts | 4 +- .../src/utils/logging/WinstonRequestLogger.ts | 4 +- .../__fixture__/profileInsurance.fixture.ts | 2151 ++++++----------- .../controllers/InsuranceController.test.ts | 250 +- project/tests/generators/BotGenerator.test.ts | 60 +- .../generators/BotLevelGenerator.test.ts | 15 +- project/tests/helpers/InRaidHelper.test.ts | 51 +- project/tests/helpers/ItemHelper.test.ts | 149 +- project/tests/services/PaymentService.test.ts | 46 +- project/vitest.config.ts | 16 +- 173 files changed, 2320 insertions(+), 4501 deletions(-) diff --git a/project/dprint.json b/project/dprint.json index 60c34ce2..d264a421 100644 --- a/project/dprint.json +++ b/project/dprint.json @@ -15,7 +15,7 @@ "trailingCommas": "onlyMultiLine", "operatorPosition": "nextLine", "preferHanging": false, - "preferSingleLine": false, + "preferSingleLine": true, "arrowFunction.useParentheses": "force", "binaryExpression.linePerExpression": false, "memberExpression.linePerExpression": false, diff --git a/project/gulpfile.mjs b/project/gulpfile.mjs index 613e916c..c856b25f 100644 --- a/project/gulpfile.mjs +++ b/project/gulpfile.mjs @@ -74,15 +74,12 @@ const updateBuildProperties = async () => const vi = ResEdit.Resource.VersionInfo.fromEntries(res.entries)[0]; - vi.setStringValues( - {lang: 1033, codepage: 1200}, - { - ProductName: manifest.author, - FileDescription: manifest.description, - CompanyName: manifest.name, - LegalCopyright: manifest.license, - }, - ); + vi.setStringValues({lang: 1033, codepage: 1200}, { + ProductName: manifest.author, + FileDescription: manifest.description, + CompanyName: manifest.name, + LegalCopyright: manifest.license, + }); vi.removeStringValue({lang: 1033, codepage: 1200}, "OriginalFilename"); vi.removeStringValue({lang: 1033, codepage: 1200}, "InternalName"); vi.setFileVersion(...manifest.version.split(".").map(Number)); diff --git a/project/src/ErrorHandler.ts b/project/src/ErrorHandler.ts index 81c1576d..afb88de9 100644 --- a/project/src/ErrorHandler.ts +++ b/project/src/ErrorHandler.ts @@ -12,10 +12,7 @@ export class ErrorHandler constructor() { this.logger = new WinstonMainLogger(new AsyncQueue()); - this.readLine = readline.createInterface({ - input: process.stdin, - output: process.stdout, - }); + this.readLine = readline.createInterface({input: process.stdin, output: process.stdout}); } public handleCriticalError(err: Error): void diff --git a/project/src/callbacks/CustomizationCallbacks.ts b/project/src/callbacks/CustomizationCallbacks.ts index 35c85210..9d4cec90 100644 --- a/project/src/callbacks/CustomizationCallbacks.ts +++ b/project/src/callbacks/CustomizationCallbacks.ts @@ -28,10 +28,7 @@ export class CustomizationCallbacks */ public getSuits(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { - const result: IGetSuitsResponse = { - _id: `pmc${sessionID}`, - suites: this.saveServer.getProfile(sessionID).suits, - }; + const result: IGetSuitsResponse = {_id: `pmc${sessionID}`, suites: this.saveServer.getProfile(sessionID).suits}; return this.httpResponse.getBody(result); } diff --git a/project/src/callbacks/DialogueCallbacks.ts b/project/src/callbacks/DialogueCallbacks.ts index 881a1fb3..a1298527 100644 --- a/project/src/callbacks/DialogueCallbacks.ts +++ b/project/src/callbacks/DialogueCallbacks.ts @@ -75,12 +75,7 @@ export class DialogueCallbacks implements OnUpdate VersionId: "bgkidft87ddd", // TODO: Is this... correct? Ip: "", Port: 0, - Chats: [ - { - _id: "0", - Members: 0, - }, - ], + Chats: [{_id: "0", Members: 0}], }; return this.httpResponse.getBody([chatServer]); diff --git a/project/src/callbacks/GameCallbacks.ts b/project/src/callbacks/GameCallbacks.ts index 780c5aa7..0b712181 100644 --- a/project/src/callbacks/GameCallbacks.ts +++ b/project/src/callbacks/GameCallbacks.ts @@ -58,9 +58,7 @@ export class GameCallbacks implements OnLoad const today = new Date().toUTCString(); const startTimeStampMS = Date.parse(today); this.gameController.gameStart(url, info, sessionID, startTimeStampMS); - return this.httpResponse.getBody({ - utc_time: startTimeStampMS / 1000, - }); + return this.httpResponse.getBody({utc_time: startTimeStampMS / 1000}); } /** @@ -75,9 +73,7 @@ export class GameCallbacks implements OnLoad ): IGetBodyResponseData { this.saveServer.save(); - return this.httpResponse.getBody({ - status: "ok", - }); + return this.httpResponse.getBody({status: "ok"}); } /** @@ -144,9 +140,7 @@ export class GameCallbacks implements OnLoad */ public getVersion(url: string, info: IEmptyRequestData, sessionID: string): string { - return this.httpResponse.noBody({ - Version: this.watermark.getInGameVersionLabel(), - }); + return this.httpResponse.noBody({Version: this.watermark.getInGameVersionLabel()}); } public reportNickname(url: string, info: IReportNicknameRequestData, sessionID: string): INullResponseData diff --git a/project/src/callbacks/HandbookCallbacks.ts b/project/src/callbacks/HandbookCallbacks.ts index 7f60703c..588fb04a 100644 --- a/project/src/callbacks/HandbookCallbacks.ts +++ b/project/src/callbacks/HandbookCallbacks.ts @@ -6,9 +6,7 @@ import { OnLoad } from "@spt-aki/di/OnLoad"; @injectable() export class HandbookCallbacks implements OnLoad { - constructor( - @inject("HandbookController") protected handbookController: HandbookController, - ) + constructor(@inject("HandbookController") protected handbookController: HandbookController) {} public async onLoad(): Promise diff --git a/project/src/callbacks/HealthCallbacks.ts b/project/src/callbacks/HealthCallbacks.ts index 9fb41cb6..1cbaaf49 100644 --- a/project/src/callbacks/HealthCallbacks.ts +++ b/project/src/callbacks/HealthCallbacks.ts @@ -44,11 +44,7 @@ export class HealthCallbacks */ public handleWorkoutEffects(url: string, info: IWorkoutData, sessionID: string): IGetBodyResponseData { - this.healthController.applyWorkoutChanges( - this.profileHelper.getPmcProfile(sessionID), - info, - sessionID, - ); + this.healthController.applyWorkoutChanges(this.profileHelper.getPmcProfile(sessionID), info, sessionID); return this.httpResponse.emptyResponse(); } diff --git a/project/src/callbacks/HttpCallbacks.ts b/project/src/callbacks/HttpCallbacks.ts index 0012f67c..ef34a6ea 100644 --- a/project/src/callbacks/HttpCallbacks.ts +++ b/project/src/callbacks/HttpCallbacks.ts @@ -6,9 +6,7 @@ import { HttpServer } from "@spt-aki/servers/HttpServer"; @injectable() export class HttpCallbacks implements OnLoad { - constructor( - @inject("HttpServer") protected httpServer: HttpServer, - ) + constructor(@inject("HttpServer") protected httpServer: HttpServer) {} public async onLoad(): Promise diff --git a/project/src/callbacks/InventoryCallbacks.ts b/project/src/callbacks/InventoryCallbacks.ts index 876a20a1..262001ea 100644 --- a/project/src/callbacks/InventoryCallbacks.ts +++ b/project/src/callbacks/InventoryCallbacks.ts @@ -24,9 +24,7 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve @injectable() export class InventoryCallbacks { - constructor( - @inject("InventoryController") protected inventoryController: InventoryController, - ) + constructor(@inject("InventoryController") protected inventoryController: InventoryController) {} /** Handle Move event */ diff --git a/project/src/callbacks/NoteCallbacks.ts b/project/src/callbacks/NoteCallbacks.ts index 0e3499ce..95e450ec 100644 --- a/project/src/callbacks/NoteCallbacks.ts +++ b/project/src/callbacks/NoteCallbacks.ts @@ -8,9 +8,7 @@ import { INoteActionData } from "@spt-aki/models/eft/notes/INoteActionData"; @injectable() export class NoteCallbacks { - constructor( - @inject("NoteController") protected noteController: NoteController, - ) + constructor(@inject("NoteController") protected noteController: NoteController) {} /** Handle AddNote event */ diff --git a/project/src/callbacks/NotifierCallbacks.ts b/project/src/callbacks/NotifierCallbacks.ts index 244846c8..61df5e1a 100644 --- a/project/src/callbacks/NotifierCallbacks.ts +++ b/project/src/callbacks/NotifierCallbacks.ts @@ -36,9 +36,9 @@ export class NotifierCallbacks * Take our array of JSON message objects and cast them to JSON strings, so that they can then * be sent to client as NEWLINE separated strings... yup. */ - this.notifierController.notifyAsync(tmpSessionID) - .then((messages: any) => messages.map((message: any) => this.jsonUtil.serialize(message)).join("\n")) - .then((text) => this.httpServerHelper.sendTextJson(resp, text)); + this.notifierController.notifyAsync(tmpSessionID).then((messages: any) => + messages.map((message: any) => this.jsonUtil.serialize(message)).join("\n") + ).then((text) => this.httpServerHelper.sendTextJson(resp, text)); } /** Handle push/notifier/get */ @@ -68,9 +68,7 @@ export class NotifierCallbacks sessionID: string, ): IGetBodyResponseData { - return this.httpResponse.getBody({ - status: "ok", - }); + return this.httpResponse.getBody({status: "ok"}); } public notify(url: string, info: any, sessionID: string): string diff --git a/project/src/callbacks/PresetCallbacks.ts b/project/src/callbacks/PresetCallbacks.ts index 3ded09d4..23b11de8 100644 --- a/project/src/callbacks/PresetCallbacks.ts +++ b/project/src/callbacks/PresetCallbacks.ts @@ -6,9 +6,7 @@ import { OnLoad } from "@spt-aki/di/OnLoad"; @injectable() export class PresetCallbacks implements OnLoad { - constructor( - @inject("PresetController") protected presetController: PresetController, - ) + constructor(@inject("PresetController") protected presetController: PresetController) {} public async onLoad(): Promise diff --git a/project/src/callbacks/ProfileCallbacks.ts b/project/src/callbacks/ProfileCallbacks.ts index 591f4e35..7ba9eac8 100644 --- a/project/src/callbacks/ProfileCallbacks.ts +++ b/project/src/callbacks/ProfileCallbacks.ts @@ -91,10 +91,7 @@ export class ProfileCallbacks return this.httpResponse.getBody(null, 1, "The nickname is too short"); } - return this.httpResponse.getBody({ - status: 0, - nicknamechangedate: this.timeUtil.getTimestamp(), - }); + return this.httpResponse.getBody({status: 0, nicknamechangedate: this.timeUtil.getTimestamp()}); } /** @@ -141,29 +138,19 @@ export class ProfileCallbacks { const response: GetProfileStatusResponseData = { maxPveCountExceeded: false, - profiles: [ - { - profileid: `scav${sessionID}`, - profileToken: null, - status: "Free", - sid: "", - ip: "", - port: 0, - version: "live", - location: "bigmap", - raidMode: "Online", - mode: "deathmatch", - shortId: "xxx1x1", - }, - { - profileid: `pmc${sessionID}`, - profileToken: null, - status: "Free", - sid: "", - ip: "", - port: 0, - }, - ], + profiles: [{ + profileid: `scav${sessionID}`, + profileToken: null, + status: "Free", + sid: "", + ip: "", + port: 0, + version: "live", + location: "bigmap", + raidMode: "Online", + mode: "deathmatch", + shortId: "xxx1x1", + }, {profileid: `pmc${sessionID}`, profileToken: null, status: "Free", sid: "", ip: "", port: 0}], }; return this.httpResponse.getBody(response); diff --git a/project/src/callbacks/RepairCallbacks.ts b/project/src/callbacks/RepairCallbacks.ts index 034f1d2f..d5514850 100644 --- a/project/src/callbacks/RepairCallbacks.ts +++ b/project/src/callbacks/RepairCallbacks.ts @@ -9,9 +9,7 @@ import { ITraderRepairActionDataRequest } from "@spt-aki/models/eft/repair/ITrad @injectable() export class RepairCallbacks { - constructor( - @inject("RepairController") protected repairController: RepairController, - ) + constructor(@inject("RepairController") protected repairController: RepairController) {} /** diff --git a/project/src/callbacks/TradeCallbacks.ts b/project/src/callbacks/TradeCallbacks.ts index 9b9b8ce8..3fad61eb 100644 --- a/project/src/callbacks/TradeCallbacks.ts +++ b/project/src/callbacks/TradeCallbacks.ts @@ -10,9 +10,7 @@ import { ISellScavItemsToFenceRequestData } from "@spt-aki/models/eft/trade/ISel @injectable() export class TradeCallbacks { - constructor( - @inject("TradeController") protected tradeController: TradeController, - ) + constructor(@inject("TradeController") protected tradeController: TradeController) {} /** diff --git a/project/src/callbacks/WishlistCallbacks.ts b/project/src/callbacks/WishlistCallbacks.ts index c4b659d7..550e59d5 100644 --- a/project/src/callbacks/WishlistCallbacks.ts +++ b/project/src/callbacks/WishlistCallbacks.ts @@ -8,9 +8,7 @@ import { IWishlistActionData } from "@spt-aki/models/eft/wishlist/IWishlistActio @injectable() export class WishlistCallbacks { - constructor( - @inject("WishlistController") protected wishlistController: WishlistController, - ) + constructor(@inject("WishlistController") protected wishlistController: WishlistController) {} /** Handle AddToWishList event */ diff --git a/project/src/controllers/BotController.ts b/project/src/controllers/BotController.ts index 98753c00..5de94655 100644 --- a/project/src/controllers/BotController.ts +++ b/project/src/controllers/BotController.ts @@ -57,11 +57,7 @@ export class BotController */ public getBotPresetGenerationLimit(type: string): number { - const value = this.botConfig.presetBatch[ - (type === "assaultGroup") - ? "assault" - : type - ]; + const value = this.botConfig.presetBatch[(type === "assaultGroup") ? "assault" : type]; if (!value) { @@ -275,9 +271,7 @@ export class BotController this.logger.warning(this.localisationService.getText("bot-missing_saved_match_info")); } - const mapName = raidConfig - ? raidConfig.location - : defaultMapCapId; + const mapName = raidConfig ? raidConfig.location : defaultMapCapId; let botCap = this.botConfig.maxBotCap[mapName.toLowerCase()]; if (!botCap) @@ -296,9 +290,6 @@ export class BotController public getAiBotBrainTypes(): any { - return { - pmc: this.pmcConfig.pmcType, - assault: this.botConfig.assaultBrainType, - }; + return {pmc: this.pmcConfig.pmcType, assault: this.botConfig.assaultBrainType}; } } diff --git a/project/src/controllers/ClientLogController.ts b/project/src/controllers/ClientLogController.ts index 0db5d170..988f6442 100644 --- a/project/src/controllers/ClientLogController.ts +++ b/project/src/controllers/ClientLogController.ts @@ -8,9 +8,7 @@ import { inject, injectable } from "tsyringe"; @injectable() export class ClientLogController { - constructor( - @inject("WinstonLogger") protected logger: ILogger, - ) + constructor(@inject("WinstonLogger") protected logger: ILogger) {} /** diff --git a/project/src/controllers/DialogueController.ts b/project/src/controllers/DialogueController.ts index 76bc8c09..6e085fe5 100644 --- a/project/src/controllers/DialogueController.ts +++ b/project/src/controllers/DialogueController.ts @@ -60,11 +60,7 @@ export class DialogueController public getFriendList(sessionID: string): IGetFriendListDataResponse { // Force a fake friend called SPT into friend list - return { - Friends: [this.getSptFriendData()], - Ignore: [], - InIgnoreList: [], - }; + return {Friends: [this.getSptFriendData()], Ignore: [], InIgnoreList: []}; } /** diff --git a/project/src/controllers/GameController.ts b/project/src/controllers/GameController.ts index ddf296ff..22146dcf 100644 --- a/project/src/controllers/GameController.ts +++ b/project/src/controllers/GameController.ts @@ -435,10 +435,7 @@ export class GameController */ public getServer(sessionId: string): IServerDetails[] { - return [{ - ip: this.httpConfig.ip, - port: this.httpConfig.port, - }]; + return [{ip: this.httpConfig.ip, port: this.httpConfig.port}]; } /** @@ -446,9 +443,7 @@ export class GameController */ public getCurrentGroup(sessionId: string): ICurrentGroupResponse { - return { - squad: [], - }; + return {squad: []}; } /** @@ -456,10 +451,7 @@ export class GameController */ public getValidGameVersion(sessionId: string): ICheckVersionResponse { - return { - isvalid: true, - latestVersion: this.coreConfig.compatibleTarkovVersion, - }; + return {isvalid: true, latestVersion: this.coreConfig.compatibleTarkovVersion}; } /** @@ -467,10 +459,7 @@ export class GameController */ public getKeepAlive(sessionId: string): IGameKeepAliveResponse { - return { - msg: "OK", - utc_time: new Date().getTime() / 1000, - }; + return {msg: "OK", utc_time: new Date().getTime() / 1000}; } /** @@ -777,9 +766,7 @@ export class GameController const modDetails = activeMods[modKey]; if ( fullProfile.aki.mods.some((x) => - x.author === modDetails.author - && x.name === modDetails.name - && x.version === modDetails.version + x.author === modDetails.author && x.name === modDetails.name && x.version === modDetails.version ) ) { diff --git a/project/src/controllers/HideoutController.ts b/project/src/controllers/HideoutController.ts index 449b1865..d31021bf 100644 --- a/project/src/controllers/HideoutController.ts +++ b/project/src/controllers/HideoutController.ts @@ -93,10 +93,7 @@ export class HideoutController const items = request.items.map((reqItem) => { const item = pmcData.Inventory.items.find((invItem) => invItem._id === reqItem.id); - return { - inventoryItem: item, - requestedItem: reqItem, - }; + return {inventoryItem: item, requestedItem: reqItem}; }); // If it's not money, its construction / barter items @@ -375,11 +372,7 @@ export class HideoutController const itemsToAdd = Object.entries(addItemToHideoutRequest.items).map((kvp) => { const item = pmcData.Inventory.items.find((invItem) => invItem._id === kvp[1].id); - return { - inventoryItem: item, - requestedItem: kvp[1], - slot: kvp[0], - }; + return {inventoryItem: item, requestedItem: kvp[1], slot: kvp[0]}; }); const hideoutArea = pmcData.Hideout.Areas.find((area) => area.type === addItemToHideoutRequest.areaType); @@ -631,10 +624,7 @@ export class HideoutController return this.httpResponse.appendErrorToOutput(output); } - if ( - inventoryItem.upd?.StackObjectsCount - && inventoryItem.upd.StackObjectsCount > requestedItem.count - ) + if (inventoryItem.upd?.StackObjectsCount && inventoryItem.upd.StackObjectsCount > requestedItem.count) { inventoryItem.upd.StackObjectsCount -= requestedItem.count; } @@ -693,9 +683,7 @@ export class HideoutController */ protected addScavCaseRewardsToProfile(pmcData: IPmcData, rewards: Product[], recipeId: string): void { - pmcData.Hideout.Production[`ScavCase${recipeId}`] = { - Products: rewards, - }; + pmcData.Hideout.Production[`ScavCase${recipeId}`] = {Products: rewards}; } /** @@ -799,13 +787,7 @@ export class HideoutController id = this.presetHelper.getDefaultPreset(id)._id; } - const newReq = { - items: [{ - item_id: id, - count: recipe.count, - }], - tid: "ragfair", - }; + const newReq = {items: [{item_id: id, count: recipe.count}], tid: "ragfair"}; const entries = Object.entries(pmcData.Hideout.Production); let prodId: string; @@ -889,9 +871,7 @@ export class HideoutController // Handle the isEncoded flag from recipe if (recipe.isEncoded) { - const upd: Upd = { - RecodableComponent: {IsEncoded: true}, - }; + const upd: Upd = {RecodableComponent: {IsEncoded: true}}; return this.inventoryHelper.addItem(pmcData, newReq, output, sessionID, callback, true, upd); } @@ -957,18 +937,13 @@ export class HideoutController { id = this.presetHelper.getDefaultPreset(id)._id; } - const numOfItems = !x.upd?.StackObjectsCount - ? 1 - : x.upd.StackObjectsCount; + const numOfItems = !x.upd?.StackObjectsCount ? 1 : x.upd.StackObjectsCount; return {item_id: id, count: numOfItems}; }, ); - const newReq = { - items: itemsToAdd, - tid: "ragfair", - }; + const newReq = {items: itemsToAdd, tid: "ragfair"}; const callback = () => { @@ -1060,10 +1035,7 @@ export class HideoutController // Check if counter exists, add placeholder if it doesn't if (!pmcData.Stats.Eft.OverallCounters.Items.find((x) => x.Key.includes("ShootingRangePoints"))) { - pmcData.Stats.Eft.OverallCounters.Items.push({ - Key: ["ShootingRangePoints"], - Value: 0, - }); + pmcData.Stats.Eft.OverallCounters.Items.push({Key: ["ShootingRangePoints"], Value: 0}); } // Find counter by key and update value @@ -1094,10 +1066,7 @@ export class HideoutController const items = request.items.map((reqItem) => { const item = pmcData.Inventory.items.find((invItem) => invItem._id === reqItem.id); - return { - inventoryItem: item, - requestedItem: reqItem, - }; + return {inventoryItem: item, requestedItem: reqItem}; }); // If it's not money, its construction / barter items diff --git a/project/src/controllers/InsuranceController.ts b/project/src/controllers/InsuranceController.ts index b2d2720c..5552fd36 100644 --- a/project/src/controllers/InsuranceController.ts +++ b/project/src/controllers/InsuranceController.ts @@ -625,10 +625,7 @@ export class InsuranceController // add items to InsuredItems list once money has been paid for (const key of body.items) { - pmcData.InsuredItems.push({ - tid: body.tid, - itemId: inventoryItemsHash[key]._id, - }); + pmcData.InsuredItems.push({tid: body.tid, itemId: inventoryItemsHash[key]._id}); } this.profileHelper.addSkillPointsToPlayer(pmcData, SkillTypes.CHARISMA, itemsToInsureCount * 0.01); diff --git a/project/src/controllers/InventoryController.ts b/project/src/controllers/InventoryController.ts index e921f893..7885b1e1 100644 --- a/project/src/controllers/InventoryController.ts +++ b/project/src/controllers/InventoryController.ts @@ -287,9 +287,7 @@ export class InventoryController if (!sourceItem.upd) { - sourceItem.upd = { - StackObjectsCount: 1, - }; + sourceItem.upd = {StackObjectsCount: 1}; } else if (!sourceItem.upd.StackObjectsCount) { @@ -458,11 +456,7 @@ export class InventoryController public foldItem(pmcData: IPmcData, body: IInventoryFoldRequestData, sessionID: string): IItemEventRouterResponse { // Fix for folding weapons while on they're in the Scav inventory - if ( - body.fromOwner - && body.fromOwner.type === "Profile" - && body.fromOwner.id !== pmcData._id - ) + if (body.fromOwner && body.fromOwner.type === "Profile" && body.fromOwner.id !== pmcData._id) { pmcData = this.profileHelper.getScavProfile(sessionID); } @@ -476,10 +470,7 @@ export class InventoryController } } - return { - warnings: [], - profileChanges: {}, - }; + return {warnings: [], profileChanges: {}}; } /** @@ -519,10 +510,7 @@ export class InventoryController ); } - return { - warnings: [], - profileChanges: {}, - }; + return {warnings: [], profileChanges: {}}; } /** @@ -551,10 +539,7 @@ export class InventoryController } } - return { - warnings: [], - profileChanges: {}, - }; + return {warnings: [], profileChanges: {}}; } /** @@ -872,10 +857,7 @@ export class InventoryController const containerDetails = this.itemHelper.getItem(openedItem._tpl); const isSealedWeaponBox = containerDetails[1]._name.includes("event_container_airdrop"); - const newItemRequest: IAddItemRequestData = { - tid: "RandomLootContainer", - items: [], - }; + const newItemRequest: IAddItemRequestData = {tid: "RandomLootContainer", items: []}; let foundInRaid = false; if (isSealedWeaponBox) diff --git a/project/src/controllers/LocationController.ts b/project/src/controllers/LocationController.ts index df0c5671..00fd78f7 100644 --- a/project/src/controllers/LocationController.ts +++ b/project/src/controllers/LocationController.ts @@ -135,10 +135,7 @@ export class LocationController locations[mapBase._Id] = mapBase; } - return { - locations: locations, - paths: locationsFromDb.base.paths, - }; + return {locations: locations, paths: locationsFromDb.base.paths}; } /** diff --git a/project/src/controllers/MatchController.ts b/project/src/controllers/MatchController.ts index 0baefa00..436f7082 100644 --- a/project/src/controllers/MatchController.ts +++ b/project/src/controllers/MatchController.ts @@ -101,10 +101,7 @@ export class MatchController /** Handle match/group/start_game */ public joinMatch(info: IJoinMatchRequestData, sessionId: string): IJoinMatchResult { - const output: IJoinMatchResult = { - maxPveCountExceeded: false, - profiles: [], - }; + const output: IJoinMatchResult = {maxPveCountExceeded: false, profiles: []}; // get list of players joining into the match output.profiles.push({ @@ -128,10 +125,7 @@ export class MatchController /** Handle client/match/group/status */ public getGroupStatus(info: IGetGroupStatusRequestData): any { - return { - players: [], - maxPveCountExceeded: false, - }; + return {players: [], maxPveCountExceeded: false}; } /** @@ -226,18 +220,13 @@ export class MatchController const parentId = this.hashUtil.generate(); for (const item of loot) { - mailableLoot.push( - { - _id: item.id, - _tpl: item.tpl, - slotId: "main", - parentId: parentId, - upd: { - StackObjectsCount: item.stackCount, - SpawnedInSession: true, - }, - }, - ); + mailableLoot.push({ + _id: item.id, + _tpl: item.tpl, + slotId: "main", + parentId: parentId, + upd: {StackObjectsCount: item.stackCount, SpawnedInSession: true}, + }); } // Send message from fence giving player reward generated above diff --git a/project/src/controllers/NoteController.ts b/project/src/controllers/NoteController.ts index 4f6fcc16..bc56a5a0 100644 --- a/project/src/controllers/NoteController.ts +++ b/project/src/controllers/NoteController.ts @@ -9,17 +9,12 @@ import { EventOutputHolder } from "@spt-aki/routers/EventOutputHolder"; @injectable() export class NoteController { - constructor( - @inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder, - ) + constructor(@inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder) {} public addNote(pmcData: IPmcData, body: INoteActionData, sessionID: string): IItemEventRouterResponse { - const newNote: Note = { - Time: body.note.Time, - Text: body.note.Text, - }; + const newNote: Note = {Time: body.note.Time, Text: body.note.Text}; pmcData.Notes.Notes.push(newNote); return this.eventOutputHolder.getOutput(sessionID); diff --git a/project/src/controllers/PresetBuildController.ts b/project/src/controllers/PresetBuildController.ts index 9a42b95f..7e44a0b0 100644 --- a/project/src/controllers/PresetBuildController.ts +++ b/project/src/controllers/PresetBuildController.ts @@ -33,10 +33,7 @@ export class PresetBuildController const profile = this.saveServer.getProfile(sessionID); if (!profile.userbuilds) { - profile.userbuilds = { - equipmentBuilds: [], - weaponBuilds: [], - }; + profile.userbuilds = {equipmentBuilds: [], weaponBuilds: []}; } // Ensure the secure container in the default presets match what the player has equipped @@ -87,13 +84,7 @@ export class PresetBuildController // Create new object ready to save into profile userbuilds.weaponBuilds const newId = this.hashUtil.generate(); // Id is empty, generate it - const newBuild: IWeaponBuild = { - id: newId, - name: body.name, - root: body.root, - items: body.items, - type: "weapon", - }; + const newBuild: IWeaponBuild = {id: newId, name: body.name, root: body.root, items: body.items, type: "weapon"}; const savedWeaponBuilds = this.saveServer.getProfile(sessionId).userbuilds.weaponBuilds; const existingBuild = savedWeaponBuilds.find((x) => x.id === body.id); diff --git a/project/src/controllers/ProfileController.ts b/project/src/controllers/ProfileController.ts index 521e5f0c..ec391eaf 100644 --- a/project/src/controllers/ProfileController.ts +++ b/project/src/controllers/ProfileController.ts @@ -164,10 +164,7 @@ export class ProfileController // Create profile const profileDetails: IAkiProfile = { info: account, - characters: { - pmc: pmcData, - scav: {} as IPmcData, - }, + characters: {pmc: pmcData, scav: {} as IPmcData}, suits: profile.suits, userbuilds: profile.userbuilds, dialogues: profile.dialogues, @@ -351,13 +348,6 @@ export class ProfileController */ public getFriends(info: ISearchFriendRequestData, sessionID: string): ISearchFriendResponse[] { - return [{ - _id: this.hashUtil.generate(), - Info: { - Level: 1, - Side: "Bear", - Nickname: info.nickname, - }, - }]; + return [{_id: this.hashUtil.generate(), Info: {Level: 1, Side: "Bear", Nickname: info.nickname}}]; } } diff --git a/project/src/controllers/QuestController.ts b/project/src/controllers/QuestController.ts index bf57a1d8..ce96a841 100644 --- a/project/src/controllers/QuestController.ts +++ b/project/src/controllers/QuestController.ts @@ -448,11 +448,9 @@ export class QuestController const change = {}; change[repeatableQuestProfile._id] = repeatableSettings.changeRequirement[repeatableQuestProfile._id]; const responseData: IPmcDataRepeatableQuest = { - id: repeatableSettings.id - ?? this.questConfig.repeatableQuests.find((x) => - x.name === repeatableQuestProfile.sptRepatableGroupName - ) - .id, + id: repeatableSettings.id ?? this.questConfig.repeatableQuests.find((x) => + x.name === repeatableQuestProfile.sptRepatableGroupName + ).id, name: repeatableSettings.name, endTime: repeatableSettings.endTime, changeRequirement: change, @@ -957,10 +955,6 @@ export class QuestController return; } - pmcData.BackendCounters[conditionId] = { - id: conditionId, - qid: questId, - value: counterValue, - }; + pmcData.BackendCounters[conditionId] = {id: conditionId, qid: questId, value: counterValue}; } } diff --git a/project/src/controllers/RagfairController.ts b/project/src/controllers/RagfairController.ts index 74188ccc..bf4a4902 100644 --- a/project/src/controllers/RagfairController.ts +++ b/project/src/controllers/RagfairController.ts @@ -326,11 +326,7 @@ export class RagfairController const min = offers[0].requirementsCost; // Get first item from array as its pre-sorted const max = offers.at(-1).requirementsCost; // Get last item from array as its pre-sorted - return { - avg: (min + max) / 2, - min: min, - max: max, - }; + return {avg: (min + max) / 2, min: min, max: max}; } // No offers listed, get price from live ragfair price list prices.json else @@ -344,11 +340,7 @@ export class RagfairController tplPrice = this.handbookHelper.getTemplatePrice(getPriceRequest.templateId); } - return { - avg: tplPrice, - min: tplPrice, - max: tplPrice, - }; + return {avg: tplPrice, min: tplPrice, max: tplPrice}; } } @@ -399,9 +391,7 @@ export class RagfairController const qualityMultiplier = this.itemHelper.getItemQualityModifier(rootItem); const averageOfferPrice = this.ragfairPriceService.getFleaPriceForItem(rootItem._tpl) * rootItem.upd.StackObjectsCount * qualityMultiplier; - const itemStackCount = (offerRequest.sellInOnePiece) - ? 1 - : rootItem.upd.StackObjectsCount; + const itemStackCount = (offerRequest.sellInOnePiece) ? 1 : rootItem.upd.StackObjectsCount; // Get averaged price of a single item being listed const averageSingleItemPrice = (offerRequest.sellInOnePiece) @@ -623,11 +613,7 @@ export class RagfairController const formattedRequirements: IBarterScheme[] = requirements.map((item) => { - return { - _tpl: item._tpl, - count: item.count, - onlyFunctional: item.onlyFunctional, - }; + return {_tpl: item._tpl, count: item.count, onlyFunctional: item.onlyFunctional}; }); return this.ragfairOfferGenerator.createFleaOffer( @@ -756,12 +742,7 @@ export class RagfairController return { tid: "ragfair", Action: "TradingConfirm", - scheme_items: [ - { - id: this.paymentHelper.getCurrency(currency), - count: Math.round(value), - }, - ], + scheme_items: [{id: this.paymentHelper.getCurrency(currency), count: Math.round(value)}], type: "", item_id: "", count: 0, diff --git a/project/src/controllers/RepeatableQuestController.ts b/project/src/controllers/RepeatableQuestController.ts index d40b81ad..94fd56b8 100644 --- a/project/src/controllers/RepeatableQuestController.ts +++ b/project/src/controllers/RepeatableQuestController.ts @@ -99,8 +99,7 @@ export class RepeatableQuestController const currentRepeatableQuestType = this.getRepeatableQuestSubTypeFromProfile(repeatableConfig, pmcData); if ( - repeatableConfig.side === "Pmc" - && pmcData.Info.Level >= repeatableConfig.minPlayerLevel + repeatableConfig.side === "Pmc" && pmcData.Info.Level >= repeatableConfig.minPlayerLevel || repeatableConfig.side === "Scav" && scavQuestUnlocked ) { @@ -216,8 +215,7 @@ export class RepeatableQuestController // Elite charisma skill gives extra daily quest(s) return repeatableConfig.numQuests + this.databaseServer.getTables().globals.config.SkillsSettings.Charisma.BonusSettings - .EliteBonusSettings - .RepeatableQuestExtraCount; + .EliteBonusSettings.RepeatableQuestExtraCount; } return repeatableConfig.numQuests; @@ -335,17 +333,7 @@ export class RepeatableQuestController { return { types: repeatableConfig.types.slice(), - pool: { - Exploration: { - locations: {}, - }, - Elimination: { - targets: {}, - }, - Pickup: { - locations: {}, - }, - }, + pool: {Exploration: {locations: {}}, Elimination: {targets: {}}, Pickup: {locations: {}}}, }; } diff --git a/project/src/controllers/WeatherController.ts b/project/src/controllers/WeatherController.ts index eca193db..90350ea9 100644 --- a/project/src/controllers/WeatherController.ts +++ b/project/src/controllers/WeatherController.ts @@ -24,12 +24,7 @@ export class WeatherController /** Handle client/weather */ public generate(): IWeatherData { - let result: IWeatherData = { - acceleration: 0, - time: "", - date: "", - weather: null, - }; + let result: IWeatherData = {acceleration: 0, time: "", date: "", weather: null}; result = this.weatherGenerator.calculateGameTime(result); result.weather = this.weatherGenerator.generateWeather(); diff --git a/project/src/controllers/WishlistController.ts b/project/src/controllers/WishlistController.ts index aae3f9e5..eefa8c9b 100644 --- a/project/src/controllers/WishlistController.ts +++ b/project/src/controllers/WishlistController.ts @@ -8,9 +8,7 @@ import { EventOutputHolder } from "@spt-aki/routers/EventOutputHolder"; @injectable() export class WishlistController { - constructor( - @inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder, - ) + constructor(@inject("EventOutputHolder") protected eventOutputHolder: EventOutputHolder) {} /** Handle AddToWishList */ diff --git a/project/src/di/Container.ts b/project/src/di/Container.ts index e80d5579..a6d45798 100644 --- a/project/src/di/Container.ts +++ b/project/src/di/Container.ts @@ -608,9 +608,7 @@ export class Container con.register("BotGenerationCacheService", BotGenerationCacheService, { lifecycle: Lifecycle.Singleton, }); - con.register("LocalisationService", LocalisationService, { - lifecycle: Lifecycle.Singleton, - }); + con.register("LocalisationService", LocalisationService, {lifecycle: Lifecycle.Singleton}); con.register("CustomLocationWaveService", CustomLocationWaveService, { lifecycle: Lifecycle.Singleton, }); diff --git a/project/src/di/Router.ts b/project/src/di/Router.ts index ae36542e..c575500f 100644 --- a/project/src/di/Router.ts +++ b/project/src/di/Router.ts @@ -94,18 +94,12 @@ export class SaveLoadRouter extends Router export class HandledRoute { - constructor( - public route: string, - public dynamic: boolean, - ) + constructor(public route: string, public dynamic: boolean) {} } export class RouteAction { - constructor( - public url: string, - public action: (url: string, info: any, sessionID: string, output: string) => any, - ) + constructor(public url: string, public action: (url: string, info: any, sessionID: string, output: string) => any) {} } diff --git a/project/src/generators/BotEquipmentModGenerator.ts b/project/src/generators/BotEquipmentModGenerator.ts index 06f49c89..658938b4 100644 --- a/project/src/generators/BotEquipmentModGenerator.ts +++ b/project/src/generators/BotEquipmentModGenerator.ts @@ -97,9 +97,7 @@ export class BotEquipmentModGenerator } // Ensure submods for nvgs all spawn together - forceSpawn = (modSlot === "mod_nvg") - ? true - : false; + forceSpawn = (modSlot === "mod_nvg") ? true : false; let modTpl: string; let found = false; @@ -290,13 +288,7 @@ export class BotEquipmentModGenerator if (this.modSlotCanHoldScope(modSlot, modToAddTemplate._parent)) { // mod_mount was picked to be added to weapon, force scope chance to ensure its filled - const scopeSlots = [ - "mod_scope", - "mod_scope_000", - "mod_scope_001", - "mod_scope_002", - "mod_scope_003", - ]; + const scopeSlots = ["mod_scope", "mod_scope_000", "mod_scope_001", "mod_scope_002", "mod_scope_003"]; this.adjustSlotSpawnChances(modSpawnChances, scopeSlots, 100); // Hydrate pool of mods that fit into mount as its a randomisable slot @@ -310,11 +302,7 @@ export class BotEquipmentModGenerator // If picked item is muzzle adapter that can hold a child, adjust spawn chance if (this.modSlotCanHoldMuzzleDevices(modSlot, modToAddTemplate._parent)) { - const muzzleSlots = [ - "mod_muzzle", - "mod_muzzle_000", - "mod_muzzle_001", - ]; + const muzzleSlots = ["mod_muzzle", "mod_muzzle_000", "mod_muzzle_001"]; // Make chance of muzzle devices 95%, nearly certain but not guaranteed this.adjustSlotSpawnChances(modSpawnChances, muzzleSlots, 95); } @@ -340,8 +328,7 @@ export class BotEquipmentModGenerator // If stock mod can take a sub stock mod, force spawn chance to be 100% to ensure sub-stock gets added // Or if mod_stock is configured to be forced on if ( - modSlot === "mod_stock" - && (modToAddTemplate._props.Slots.find((x) => + modSlot === "mod_stock" && (modToAddTemplate._props.Slots.find((x) => x._name.includes("mod_stock") || botEquipConfig.forceStock )) ) @@ -435,8 +422,7 @@ export class BotEquipmentModGenerator "mod_scope_001", "mod_scope_002", "mod_scope_003", - ].includes(modSlot.toLowerCase()) - && modsParentId === BaseClasses.MOUNT; + ].includes(modSlot.toLowerCase()) && modsParentId === BaseClasses.MOUNT; } /** @@ -1025,12 +1011,7 @@ export class BotEquipmentModGenerator { const modSlotId = slot._name; const modId = this.hashUtil.generate(); - items.push({ - _id: modId, - _tpl: modTpl, - parentId: parentId, - slotId: modSlotId, - }); + items.push({_id: modId, _tpl: modTpl, parentId: parentId, slotId: modSlotId}); } } diff --git a/project/src/generators/BotGenerator.ts b/project/src/generators/BotGenerator.ts index 22d6aa52..a8c3f794 100644 --- a/project/src/generators/BotGenerator.ts +++ b/project/src/generators/BotGenerator.ts @@ -99,10 +99,7 @@ export class BotGenerator * @param botGenerationDetails details on how to generate bots * @returns array of bots */ - public prepareAndGenerateBots( - sessionId: string, - botGenerationDetails: BotGenerationDetails, - ): IBotBase[] + public prepareAndGenerateBots(sessionId: string, botGenerationDetails: BotGenerationDetails): IBotBase[] { const output: IBotBase[] = []; for (let i = 0; i < botGenerationDetails.botCountToGenerate; i++) @@ -114,11 +111,9 @@ export class BotGenerator bot.Info.Settings.BotDifficulty = botGenerationDetails.botDifficulty; // Get raw json data for bot (Cloned) - const botJsonTemplate = this.jsonUtil.clone(this.botHelper.getBotTemplate( - (botGenerationDetails.isPmc) - ? bot.Info.Side - : botGenerationDetails.role, - )); + const botJsonTemplate = this.jsonUtil.clone( + this.botHelper.getBotTemplate((botGenerationDetails.isPmc) ? bot.Info.Side : botGenerationDetails.role), + ); bot = this.generateBot(sessionId, bot, botJsonTemplate, botGenerationDetails); @@ -328,9 +323,7 @@ export class BotGenerator */ protected generateHealth(healthObj: Health, playerScav = false): PmcHealth { - const bodyParts = playerScav - ? healthObj.BodyParts[0] - : this.randomUtil.getArrayValue(healthObj.BodyParts); + const bodyParts = playerScav ? healthObj.BodyParts[0] : this.randomUtil.getArrayValue(healthObj.BodyParts); const newHealth: PmcHealth = { Hydration: { @@ -437,10 +430,7 @@ export class BotGenerator } // All skills have id and progress props - const skillToAdd: IBaseSkill = { - Id: skillKey, - Progress: this.randomUtil.getInt(skill.min, skill.max), - }; + const skillToAdd: IBaseSkill = {Id: skillKey, Progress: this.randomUtil.getInt(skill.min, skill.max)}; // Common skills have additional props if (isCommonSkills) diff --git a/project/src/generators/BotInventoryGenerator.ts b/project/src/generators/BotInventoryGenerator.ts index a6c81361..6128e349 100644 --- a/project/src/generators/BotInventoryGenerator.ts +++ b/project/src/generators/BotInventoryGenerator.ts @@ -112,26 +112,11 @@ export class BotInventoryGenerator return { items: [ - { - _id: equipmentId, - _tpl: equipmentTpl, - }, - { - _id: stashId, - _tpl: stashTpl, - }, - { - _id: questRaidItemsId, - _tpl: questRaidItemsTpl, - }, - { - _id: questStashItemsId, - _tpl: questStashItemsTpl, - }, - { - _id: sortingTableId, - _tpl: sortingTableTpl, - }, + {_id: equipmentId, _tpl: equipmentTpl}, + {_id: stashId, _tpl: stashTpl}, + {_id: questRaidItemsId, _tpl: questRaidItemsTpl}, + {_id: questStashItemsId, _tpl: questStashItemsTpl}, + {_id: sortingTableId, _tpl: sortingTableTpl}, ], equipment: equipmentId, stash: stashId, @@ -421,24 +406,17 @@ export class BotInventoryGenerator protected getDesiredWeaponsForBot(equipmentChances: Chances): {slot: EquipmentSlots; shouldSpawn: boolean;}[] { const shouldSpawnPrimary = this.randomUtil.getChance100(equipmentChances.equipment.FirstPrimaryWeapon); - return [ - { - slot: EquipmentSlots.FIRST_PRIMARY_WEAPON, - shouldSpawn: shouldSpawnPrimary, - }, - { - slot: EquipmentSlots.SECOND_PRIMARY_WEAPON, - shouldSpawn: shouldSpawnPrimary - ? this.randomUtil.getChance100(equipmentChances.equipment.SecondPrimaryWeapon) - : false, - }, - { - slot: EquipmentSlots.HOLSTER, - shouldSpawn: shouldSpawnPrimary - ? this.randomUtil.getChance100(equipmentChances.equipment.Holster) // Primary weapon = roll for chance at pistol - : true, // No primary = force pistol - }, - ]; + return [{slot: EquipmentSlots.FIRST_PRIMARY_WEAPON, shouldSpawn: shouldSpawnPrimary}, { + slot: EquipmentSlots.SECOND_PRIMARY_WEAPON, + shouldSpawn: shouldSpawnPrimary + ? this.randomUtil.getChance100(equipmentChances.equipment.SecondPrimaryWeapon) + : false, + }, { + slot: EquipmentSlots.HOLSTER, + shouldSpawn: shouldSpawnPrimary + ? this.randomUtil.getChance100(equipmentChances.equipment.Holster) // Primary weapon = roll for chance at pistol + : true, // No primary = force pistol + }]; } /** diff --git a/project/src/generators/BotLootGenerator.ts b/project/src/generators/BotLootGenerator.ts index 54f6a28b..8bd4d68f 100644 --- a/project/src/generators/BotLootGenerator.ts +++ b/project/src/generators/BotLootGenerator.ts @@ -237,52 +237,16 @@ export class BotLootGenerator protected addForcedMedicalItemsToPmcSecure(botInventory: PmcInventory, botRole: string): void { const grizzly = this.itemHelper.getItem("590c657e86f77412b013051d")[1]; - this.addLootFromPool( - [grizzly], - [EquipmentSlots.SECURED_CONTAINER], - 2, - botInventory, - botRole, - false, - 0, - true, - ); + this.addLootFromPool([grizzly], [EquipmentSlots.SECURED_CONTAINER], 2, botInventory, botRole, false, 0, true); const surv12 = this.itemHelper.getItem("5d02797c86f774203f38e30a")[1]; - this.addLootFromPool( - [surv12], - [EquipmentSlots.SECURED_CONTAINER], - 1, - botInventory, - botRole, - false, - 0, - true, - ); + this.addLootFromPool([surv12], [EquipmentSlots.SECURED_CONTAINER], 1, botInventory, botRole, false, 0, true); const morphine = this.itemHelper.getItem("544fb3f34bdc2d03748b456a")[1]; - this.addLootFromPool( - [morphine], - [EquipmentSlots.SECURED_CONTAINER], - 3, - botInventory, - botRole, - false, - 0, - true, - ); + this.addLootFromPool([morphine], [EquipmentSlots.SECURED_CONTAINER], 3, botInventory, botRole, false, 0, true); const afak = this.itemHelper.getItem("60098ad7c2240c0fe85c570a")[1]; - this.addLootFromPool( - [afak], - [EquipmentSlots.SECURED_CONTAINER], - 2, - botInventory, - botRole, - false, - 0, - true, - ); + this.addLootFromPool([afak], [EquipmentSlots.SECURED_CONTAINER], 2, botInventory, botRole, false, 0, true); } /** diff --git a/project/src/generators/BotWeaponGenerator.ts b/project/src/generators/BotWeaponGenerator.ts index 7f5e946a..854399f7 100644 --- a/project/src/generators/BotWeaponGenerator.ts +++ b/project/src/generators/BotWeaponGenerator.ts @@ -258,9 +258,7 @@ export class BotWeaponGenerator else { // Already exists, update values - existingItemWithSlot.upd = { - StackObjectsCount: 1, - }; + existingItemWithSlot.upd = {StackObjectsCount: 1}; existingItemWithSlot._tpl = ammoTpl; } } @@ -532,11 +530,7 @@ export class BotWeaponGenerator [EquipmentSlots.SECURED_CONTAINER], id, ammoTpl, - [{ - _id: id, - _tpl: ammoTpl, - upd: {StackObjectsCount: stackSize}, - }], + [{_id: id, _tpl: ammoTpl, upd: {StackObjectsCount: stackSize}}], inventory, ); } @@ -705,17 +699,13 @@ export class BotWeaponGenerator */ protected fillUbgl(weaponMods: Item[], ubglMod: Item, ubglAmmoTpl: string): void { - weaponMods.push( - { - _id: this.hashUtil.generate(), - _tpl: ubglAmmoTpl, - parentId: ubglMod._id, - slotId: "patron_in_weapon", - upd: { - StackObjectsCount: 1, - }, - }, - ); + weaponMods.push({ + _id: this.hashUtil.generate(), + _tpl: ubglAmmoTpl, + parentId: ubglMod._id, + slotId: "patron_in_weapon", + upd: {StackObjectsCount: 1}, + }); } /** diff --git a/project/src/generators/FenceBaseAssortGenerator.ts b/project/src/generators/FenceBaseAssortGenerator.ts index f2418d1b..30c50dce 100644 --- a/project/src/generators/FenceBaseAssortGenerator.ts +++ b/project/src/generators/FenceBaseAssortGenerator.ts @@ -97,10 +97,7 @@ export class FenceBaseAssortGenerator _tpl: item._id, parentId: "hideout", slotId: "hideout", - upd: { - StackObjectsCount: 9999999, - UnlimitedCount: true, - }, + upd: {StackObjectsCount: 9999999, UnlimitedCount: true}, }; // Add item to base diff --git a/project/src/generators/LocationGenerator.ts b/project/src/generators/LocationGenerator.ts index 36d7c9a3..6f5f5316 100644 --- a/project/src/generators/LocationGenerator.ts +++ b/project/src/generators/LocationGenerator.ts @@ -247,13 +247,12 @@ export class LocationGenerator */ protected getRandomisableContainersOnMap(staticContainers: IStaticContainerData[]): IStaticContainerData[] { - return staticContainers - .filter((x) => - x.probability !== 1 && !x.template.IsAlwaysSpawn - && !this.locationConfig.containerRandomisationSettings.containerTypesToNotRandomise.includes( - x.template.Items[0]._tpl, - ) - ); + return staticContainers.filter((x) => + x.probability !== 1 && !x.template.IsAlwaysSpawn + && !this.locationConfig.containerRandomisationSettings.containerTypesToNotRandomise.includes( + x.template.Items[0]._tpl, + ) + ); } /** @@ -530,9 +529,7 @@ export class LocationGenerator continue; } - itemDistribution.push( - new ProbabilityObject(icd.tpl, icd.relativeProbability), - ); + itemDistribution.push(new ProbabilityObject(icd.tpl, icd.relativeProbability)); } return itemDistribution; @@ -571,10 +568,7 @@ export class LocationGenerator // Draw from random distribution const desiredSpawnpointCount = Math.round( this.getLooseLootMultiplerForLocation(locationName) - * this.randomUtil.randn( - dynamicLootDist.spawnpointCount.mean, - dynamicLootDist.spawnpointCount.std, - ), + * this.randomUtil.randn(dynamicLootDist.spawnpointCount.mean, dynamicLootDist.spawnpointCount.std), ); // Positions not in forced but have 100% chance to spawn @@ -598,9 +592,7 @@ export class LocationGenerator continue; } - spawnpointArray.push( - new ProbabilityObject(spawnpoint.template.Id, spawnpoint.probability, spawnpoint), - ); + spawnpointArray.push(new ProbabilityObject(spawnpoint.template.Id, spawnpoint.probability, spawnpoint)); } // Select a number of spawn points to add loot to @@ -665,9 +657,7 @@ export class LocationGenerator continue; } - itemArray.push( - new ProbabilityObject(itemDist.composedKey.key, itemDist.relativeProbability), - ); + itemArray.push(new ProbabilityObject(itemDist.composedKey.key, itemDist.relativeProbability)); } // Draw a random item from spawn points possible items @@ -720,9 +710,7 @@ export class LocationGenerator for (const si of items) { // use locationId as template.Id is the same across all items - spawnpointArray.push( - new ProbabilityObject(si.locationId, si.probability, si), - ); + spawnpointArray.push(new ProbabilityObject(si.locationId, si.probability, si)); } // Choose 1 out of all found spawn positions for spawn id and add to loot array @@ -792,22 +780,13 @@ export class LocationGenerator ? 1 : this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); - itemWithMods.push( - { - _id: this.objectId.generate(), - _tpl: chosenTpl, - upd: {StackObjectsCount: stackCount}, - }, - ); + itemWithMods.push({_id: this.objectId.generate(), _tpl: chosenTpl, upd: {StackObjectsCount: stackCount}}); } else if (this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.AMMO_BOX)) { // Fill with cartrdiges const ammoBoxTemplate = this.itemHelper.getItem(chosenTpl)[1]; - const ammoBoxItem: Item[] = [{ - _id: this.objectId.generate(), - _tpl: chosenTpl, - }]; + const ammoBoxItem: Item[] = [{_id: this.objectId.generate(), _tpl: chosenTpl}]; this.itemHelper.addCartridgesToAmmoBox(ammoBoxItem, ammoBoxTemplate); itemWithMods.push(...ammoBoxItem); } @@ -815,10 +794,7 @@ export class LocationGenerator { // Create array with just magazine + randomised amount of cartridges const magazineTemplate = this.itemHelper.getItem(chosenTpl)[1]; - const magazineItem: Item[] = [{ - _id: this.objectId.generate(), - _tpl: chosenTpl, - }]; + const magazineItem: Item[] = [{_id: this.objectId.generate(), _tpl: chosenTpl}]; this.itemHelper.fillMagazineWithRandomCartridge( magazineItem, magazineTemplate, @@ -845,11 +821,7 @@ export class LocationGenerator // Get inventory size of item const size = this.itemHelper.getItemSize(itemWithMods, itemWithMods[0]._id); - return { - items: itemWithMods, - width: size.width, - height: size.height, - }; + return {items: itemWithMods, width: size.width, height: size.height}; } /** @@ -901,12 +873,7 @@ export class LocationGenerator const itemTemplate = this.itemHelper.getItem(tpl)[1]; let width = itemTemplate._props.Width; let height = itemTemplate._props.Height; - let items: Item[] = [ - { - _id: this.objectId.generate(), - _tpl: tpl, - }, - ]; + let items: Item[] = [{_id: this.objectId.generate(), _tpl: tpl}]; // Use passed in parentId as override for new item if (parentId) @@ -1037,10 +1004,6 @@ export class LocationGenerator items.splice(items.indexOf(items[0]), 1, ...magazineWithCartridges); } - return { - items: items, - width: width, - height: height, - }; + return {items: items, width: width, height: height}; } } diff --git a/project/src/generators/LootGenerator.ts b/project/src/generators/LootGenerator.ts index 56bb3032..2dce664f 100644 --- a/project/src/generators/LootGenerator.ts +++ b/project/src/generators/LootGenerator.ts @@ -19,10 +19,7 @@ import { RagfairLinkedItemService } from "@spt-aki/services/RagfairLinkedItemSer import { HashUtil } from "@spt-aki/utils/HashUtil"; import { RandomUtil } from "@spt-aki/utils/RandomUtil"; -type ItemLimit = { - current: number; - max: number; -}; +type ItemLimit = {current: number; max: number;}; @injectable() export class LootGenerator @@ -134,10 +131,7 @@ export class LootGenerator const itemTypeCounts: Record = {}; for (const itemTypeId in limits) { - itemTypeCounts[itemTypeId] = { - current: 0, - max: limits[itemTypeId], - }; + itemTypeCounts[itemTypeId] = {current: 0, max: limits[itemTypeId]}; } return itemTypeCounts; @@ -174,10 +168,7 @@ export class LootGenerator }; // Check if armor has level in allowed whitelist - if ( - randomItem._parent === BaseClasses.ARMOR - || randomItem._parent === BaseClasses.VEST - ) + if (randomItem._parent === BaseClasses.ARMOR || randomItem._parent === BaseClasses.VEST) { if (!options.armorLevelWhitelist.includes(Number(randomItem._props.armorClass))) { @@ -277,11 +268,7 @@ export class LootGenerator return false; } - const newLootItem: LootItem = { - tpl: randomPreset._items[0]._tpl, - isPreset: true, - stackCount: 1, - }; + const newLootItem: LootItem = {tpl: randomPreset._items[0]._tpl, isPreset: true, stackCount: 1}; result.push(newLootItem); @@ -405,14 +392,13 @@ export class LootGenerator } // Get all items of the desired type + not quest items + not globally blacklisted - const rewardItemPool = Object.values(this.databaseServer.getTables().templates.items) - .filter((x) => - x._parent === rewardTypeId - && x._type.toLowerCase() === "item" - && !this.itemFilterService.isItemBlacklisted(x._id) - && (!(containerSettings.allowBossItems || this.itemFilterService.isBossItem(x._id))) - && !x._props.QuestItem - ); + const rewardItemPool = Object.values(this.databaseServer.getTables().templates.items).filter((x) => + x._parent === rewardTypeId + && x._type.toLowerCase() === "item" + && !this.itemFilterService.isItemBlacklisted(x._id) + && (!(containerSettings.allowBossItems || this.itemFilterService.isBossItem(x._id))) + && !x._props.QuestItem + ); if (rewardItemPool.length === 0) { diff --git a/project/src/generators/PlayerScavGenerator.ts b/project/src/generators/PlayerScavGenerator.ts index f612c208..14fe59fc 100644 --- a/project/src/generators/PlayerScavGenerator.ts +++ b/project/src/generators/PlayerScavGenerator.ts @@ -66,9 +66,7 @@ export class PlayerScavGenerator const existingScavData = this.jsonUtil.clone(profile.characters.scav); // scav profile can be empty on first profile creation - const scavKarmaLevel = (Object.keys(existingScavData).length === 0) - ? 0 - : this.getScavKarmaLevel(pmcData); + const scavKarmaLevel = (Object.keys(existingScavData).length === 0) ? 0 : this.getScavKarmaLevel(pmcData); // use karma level to get correct karmaSettings const playerScavKarmaSettings = this.playerScavConfig.karmaLevel[scavKarmaLevel]; @@ -258,11 +256,7 @@ export class PlayerScavGenerator protected getDefaultScavSkills(): Skills { - return { - Common: [], - Mastering: [], - Points: 0, - }; + return {Common: [], Mastering: [], Points: 0}; } protected getScavStats(scavProfile: IPmcData): Stats diff --git a/project/src/generators/RagfairAssortGenerator.ts b/project/src/generators/RagfairAssortGenerator.ts index ceccce7d..4e343613 100644 --- a/project/src/generators/RagfairAssortGenerator.ts +++ b/project/src/generators/RagfairAssortGenerator.ts @@ -135,10 +135,7 @@ export class RagfairAssortGenerator _tpl: tplId, parentId: "hideout", slotId: "hideout", - upd: { - StackObjectsCount: 99999999, - UnlimitedCount: true, - }, + upd: {StackObjectsCount: 99999999, UnlimitedCount: true}, }; } } diff --git a/project/src/generators/RagfairOfferGenerator.ts b/project/src/generators/RagfairOfferGenerator.ts index 2a716526..68071f03 100644 --- a/project/src/generators/RagfairOfferGenerator.ts +++ b/project/src/generators/RagfairOfferGenerator.ts @@ -636,10 +636,7 @@ export class RagfairOfferGenerator { const totalCapacity = itemDetails._props.MaxResource; const remainingFuel = Math.round(totalCapacity * multiplier); - item.upd.Resource = { - UnitsConsumed: totalCapacity - remainingFuel, - Value: remainingFuel, - }; + item.upd.Resource = {UnitsConsumed: totalCapacity - remainingFuel, Value: remainingFuel}; } } @@ -653,9 +650,10 @@ export class RagfairOfferGenerator item.upd.Repairable.Durability = Math.round(item.upd.Repairable.Durability * multiplier) || 1; // randomize max durability, store to a temporary value so we can still compare the max durability - let tempMaxDurability = Math.round( - this.randomUtil.getFloat(item.upd.Repairable.Durability - 5, item.upd.Repairable.MaxDurability + 5), - ) || item.upd.Repairable.Durability; + let tempMaxDurability = + Math.round( + this.randomUtil.getFloat(item.upd.Repairable.Durability - 5, item.upd.Repairable.MaxDurability + 5), + ) || item.upd.Repairable.Durability; // clamp values to max/current if (tempMaxDurability >= item.upd.Repairable.MaxDurability) @@ -689,38 +687,27 @@ export class RagfairOfferGenerator if (isRepairable && props.Durability > 0) { - item.upd.Repairable = { - Durability: props.Durability, - MaxDurability: props.Durability, - }; + item.upd.Repairable = {Durability: props.Durability, MaxDurability: props.Durability}; } if (isMedkit && props.MaxHpResource > 0) { - item.upd.MedKit = { - HpResource: props.MaxHpResource, - }; + item.upd.MedKit = {HpResource: props.MaxHpResource}; } if (isKey) { - item.upd.Key = { - NumberOfUsages: 0, - }; + item.upd.Key = {NumberOfUsages: 0}; } if (isConsumable) { - item.upd.FoodDrink = { - HpPercent: props.MaxResource, - }; + item.upd.FoodDrink = {HpPercent: props.MaxResource}; } if (isRepairKit) { - item.upd.RepairKit = { - Resource: props.MaxRepairResource, - }; + item.upd.RepairKit = {Resource: props.MaxRepairResource}; } return item; @@ -775,12 +762,7 @@ export class RagfairOfferGenerator // Choose random item from price-filtered flea items const randomItem = this.randomUtil.getArrayValue(filtered); - return [ - { - count: barterItemCount, - _tpl: randomItem.tpl, - }, - ]; + return [{count: barterItemCount, _tpl: randomItem.tpl}]; } /** @@ -819,11 +801,6 @@ export class RagfairOfferGenerator const price = this.ragfairPriceService.getDynamicOfferPriceForOffer(offerItems, currency, isPackOffer) * multipler; - return [ - { - count: price, - _tpl: currency, - }, - ]; + return [{count: price, _tpl: currency}]; } } diff --git a/project/src/generators/RepeatableQuestGenerator.ts b/project/src/generators/RepeatableQuestGenerator.ts index e8d24768..c2c219a8 100644 --- a/project/src/generators/RepeatableQuestGenerator.ts +++ b/project/src/generators/RepeatableQuestGenerator.ts @@ -273,13 +273,12 @@ export class RepeatableQuestGenerator // get all boss spawn information const bossSpawns = Object.values(this.databaseServer.getTables().locations).filter((x) => "base" in x && "Id" in x.base - ).map( - (x) => ({Id: x.base.Id, BossSpawn: x.base.BossLocationSpawn}), - ); + ).map((x) => ({Id: x.base.Id, BossSpawn: x.base.BossLocationSpawn})); // filter for the current boss to spawn on map - const thisBossSpawns = bossSpawns.map( - (x) => ({Id: x.Id, BossSpawn: x.BossSpawn.filter((e) => e.BossName === targetKey)}), - ).filter((x) => x.BossSpawn.length > 0); + const thisBossSpawns = bossSpawns.map((x) => ({ + Id: x.Id, + BossSpawn: x.BossSpawn.filter((e) => e.BossName === targetKey), + })).filter((x) => x.BossSpawn.length > 0); // remove blacklisted locations const allowedSpawns = thisBossSpawns.filter((x) => !eliminationConfig.distLocationBlacklist.includes(x.Id)); // if the boss spawns on nom-blacklisted locations and the current location is allowed we can generate a distance kill requirement @@ -416,11 +415,7 @@ export class RepeatableQuestGenerator protected generateEliminationLocation(location: string[]): IEliminationCondition { const propsObject: IEliminationCondition = { - _props: { - target: location, - id: this.objectId.generate(), - dynamicLocale: true, - }, + _props: {target: location, id: this.objectId.generate(), dynamicLocale: true}, _parent: "Location", }; @@ -466,10 +461,7 @@ export class RepeatableQuestGenerator // Dont allow distance + melee requirement if (distance && allowedWeaponCategory !== "5b5f7a0886f77409407a7f96") { - killConditionProps.distance = { - compareMethod: ">=", - value: distance, - }; + killConditionProps.distance = {compareMethod: ">=", value: distance}; } // Has specific weapon requirement @@ -484,10 +476,7 @@ export class RepeatableQuestGenerator killConditionProps.weaponCategories = [allowedWeaponCategory]; } - return { - _props: killConditionProps, - _parent: "Kills", - }; + return {_props: killConditionProps, _parent: "Kills"}; } /** @@ -710,28 +699,15 @@ export class RepeatableQuestGenerator const exitStatusCondition: IExplorationCondition = { _parent: "ExitStatus", - _props: { - id: this.objectId.generate(), - dynamicLocale: true, - status: [ - "Survived", - ], - }, + _props: {id: this.objectId.generate(), dynamicLocale: true, status: ["Survived"]}, }; const locationCondition: IExplorationCondition = { _parent: "Location", - _props: { - id: this.objectId.generate(), - dynamicLocale: true, - target: locationTarget, - }, + _props: {id: this.objectId.generate(), dynamicLocale: true, target: locationTarget}, }; quest.conditions.AvailableForFinish[0]._props.counter.id = this.objectId.generate(); - quest.conditions.AvailableForFinish[0]._props.counter.conditions = [ - exitStatusCondition, - locationCondition, - ]; + quest.conditions.AvailableForFinish[0]._props.counter.conditions = [exitStatusCondition, locationCondition]; quest.conditions.AvailableForFinish[0]._props.value = numExtracts; quest.conditions.AvailableForFinish[0]._props.id = this.objectId.generate(); quest.location = this.getQuestLocationByMapId(locationKey); @@ -742,13 +718,11 @@ export class RepeatableQuestGenerator // Scav exits are not listed at all in locations.base currently. If that changes at some point, additional filtering will be required const mapExits = (this.databaseServer.getTables().locations[locationKey.toLowerCase()].base as ILocationBase).exits; - const possibleExists = mapExits.filter( - (x) => - (!("PassageRequirement" in x) - || repeatableConfig.questConfig.Exploration.specificExits.passageRequirementWhitelist.includes( - x.PassageRequirement, - )) - && x.Chance > 0, + const possibleExists = mapExits.filter((x) => + (!("PassageRequirement" in x) + || repeatableConfig.questConfig.Exploration.specificExits.passageRequirementWhitelist.includes( + x.PassageRequirement, + )) && x.Chance > 0 ); const exit = this.randomUtil.drawRandomFromList(possibleExists, 1)[0]; const exitCondition = this.generateExplorationExitCondition(exit); @@ -823,14 +797,7 @@ export class RepeatableQuestGenerator */ protected generateExplorationExitCondition(exit: Exit): IExplorationCondition { - return { - _parent: "ExitName", - _props: { - exitName: exit.Name, - id: this.objectId.generate(), - dynamicLocale: true, - }, - }; + return {_parent: "ExitName", _props: {exitName: exit.Name, id: this.objectId.generate(), dynamicLocale: true}}; } /** @@ -890,10 +857,11 @@ export class RepeatableQuestGenerator 1, Math.round(this.mathUtil.interp1(pmcLevel, levelsConfig, itemsConfig)) + 1, ); - const rewardReputation = Math.round( - 100 * difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, reputationConfig) - * this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig), - ) / 100; + const rewardReputation = + Math.round( + 100 * difficulty * this.mathUtil.interp1(pmcLevel, levelsConfig, reputationConfig) + * this.randomUtil.getFloat(1 - rewardSpreadConfig, 1 + rewardSpreadConfig), + ) / 100; const skillRewardChance = this.mathUtil.interp1(pmcLevel, levelsConfig, skillRewardChanceConfig); const skillPointReward = this.mathUtil.interp1(pmcLevel, levelsConfig, skillPointRewardConfig); @@ -901,17 +869,7 @@ export class RepeatableQuestGenerator let roublesBudget = rewardRoubles; let chosenRewardItems = this.chooseRewardItemsWithinBudget(repeatableConfig, roublesBudget); - const rewards: IRewards = { - Started: [], - Success: [ - { - value: rewardXP, - type: "Experience", - index: 0, - }, - ], - Fail: [], - }; + const rewards: IRewards = {Started: [], Success: [{value: rewardXP, type: "Experience", index: 0}], Fail: []}; if (traderId === Traders.PEACEKEEPER) { @@ -988,12 +946,7 @@ export class RepeatableQuestGenerator // Add rep reward to rewards array if (rewardReputation > 0) { - const reward: IReward = { - target: traderId, - value: rewardReputation, - type: "TraderStanding", - index: index, - }; + const reward: IReward = {target: traderId, value: rewardReputation, type: "TraderStanding", index: index}; rewards.Success.push(reward); } @@ -1057,21 +1010,9 @@ export class RepeatableQuestGenerator protected generateRewardItem(tpl: string, value: number, index: number, preset = null): IReward { const id = this.objectId.generate(); - const rewardItem: IReward = { - target: id, - value: value, - type: "Item", - index: index, - }; + const rewardItem: IReward = {target: id, value: value, type: "Item", index: index}; - const rootItem = { - _id: id, - _tpl: tpl, - upd: { - StackObjectsCount: value, - SpawnedInSession: true, - }, - }; + const rootItem = {_id: id, _tpl: tpl, upd: {StackObjectsCount: value, SpawnedInSession: true}}; if (preset) { @@ -1094,18 +1035,16 @@ export class RepeatableQuestGenerator // check for specific baseclasses which don't make sense as reward item // also check if the price is greater than 0; there are some items whose price can not be found // those are not in the game yet (e.g. AGS grenade launcher) - return Object.entries(this.databaseServer.getTables().templates.items).filter( - ([tpl, itemTemplate]) => + return Object.entries(this.databaseServer.getTables().templates.items).filter(([tpl, itemTemplate]) => + { + // Base "Item" item has no parent, ignore it + if (itemTemplate._parent === "") { - // Base "Item" item has no parent, ignore it - if (itemTemplate._parent === "") - { - return false; - } + return false; + } - return this.isValidRewardItem(tpl, repeatableQuestConfig); - }, - ); + return this.isValidRewardItem(tpl, repeatableQuestConfig); + }); } /** @@ -1123,10 +1062,7 @@ export class RepeatableQuestGenerator } // Item is on repeatable or global blacklist - if ( - repeatableQuestConfig.rewardBlacklist.includes(tpl) - || this.itemFilterService.isItemBlacklisted(tpl) - ) + if (repeatableQuestConfig.rewardBlacklist.includes(tpl) || this.itemFilterService.isItemBlacklisted(tpl)) { return false; } @@ -1152,8 +1088,7 @@ export class RepeatableQuestGenerator // Skip globally blacklisted items + boss items // biome-ignore lint/complexity/useSimplifiedLogicExpression: - valid = !this.itemFilterService.isItemBlacklisted(tpl) - && !this.itemFilterService.isBossItem(tpl); + valid = !this.itemFilterService.isItemBlacklisted(tpl) && !this.itemFilterService.isBossItem(tpl); return valid; } diff --git a/project/src/generators/ScavCaseRewardGenerator.ts b/project/src/generators/ScavCaseRewardGenerator.ts index 2cb56bc3..21ca83a9 100644 --- a/project/src/generators/ScavCaseRewardGenerator.ts +++ b/project/src/generators/ScavCaseRewardGenerator.ts @@ -279,11 +279,7 @@ export class ScavCaseRewardGenerator const result: Product[] = []; for (const item of rewardItems) { - const resultItem = { - _id: this.hashUtil.generate(), - _tpl: item._id, - upd: undefined, - }; + const resultItem = {_id: this.hashUtil.generate(), _tpl: item._id, upd: undefined}; this.addStackCountToAmmoAndMoney(item, resultItem, rarity); @@ -312,9 +308,7 @@ export class ScavCaseRewardGenerator { if (item._parent === BaseClasses.AMMO || item._parent === BaseClasses.MONEY) { - resultItem.upd = { - StackObjectsCount: this.getRandomAmountRewardForScavCase(item, rarity), - }; + resultItem.upd = {StackObjectsCount: this.getRandomAmountRewardForScavCase(item, rarity)}; } } @@ -331,10 +325,7 @@ export class ScavCaseRewardGenerator return dbItems.filter((item) => { const handbookPrice = this.ragfairPriceService.getStaticPriceForItem(item._id); - if ( - handbookPrice >= itemFilters.minPriceRub - && handbookPrice <= itemFilters.maxPriceRub - ) + if (handbookPrice >= itemFilters.minPriceRub && handbookPrice <= itemFilters.maxPriceRub) { return true; } diff --git a/project/src/generators/WeatherGenerator.ts b/project/src/generators/WeatherGenerator.ts index 224e9d88..7f2efb42 100644 --- a/project/src/generators/WeatherGenerator.ts +++ b/project/src/generators/WeatherGenerator.ts @@ -106,9 +106,7 @@ export class WeatherGenerator wind_gustiness: this.getRandomFloat("windGustiness"), rain: rain, // eslint-disable-next-line @typescript-eslint/naming-convention - rain_intensity: (rain > 1) - ? this.getRandomFloat("rainIntensity") - : 0, + rain_intensity: (rain > 1) ? this.getRandomFloat("rainIntensity") : 0, fog: this.getWeightedFog(), temp: this.getRandomFloat("temp"), pressure: this.getRandomFloat("pressure"), diff --git a/project/src/generators/weapongen/implementations/InternalMagazineInventoryMagGen.ts b/project/src/generators/weapongen/implementations/InternalMagazineInventoryMagGen.ts index 800013bd..2d865fee 100644 --- a/project/src/generators/weapongen/implementations/InternalMagazineInventoryMagGen.ts +++ b/project/src/generators/weapongen/implementations/InternalMagazineInventoryMagGen.ts @@ -7,9 +7,7 @@ import { BotWeaponGeneratorHelper } from "@spt-aki/helpers/BotWeaponGeneratorHel @injectable() export class InternalMagazineInventoryMagGen implements IInventoryMagGen { - constructor( - @inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper, - ) + constructor(@inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper) {} public getPriority(): number diff --git a/project/src/generators/weapongen/implementations/UbglExternalMagGen.ts b/project/src/generators/weapongen/implementations/UbglExternalMagGen.ts index 1821eafc..03abcb02 100644 --- a/project/src/generators/weapongen/implementations/UbglExternalMagGen.ts +++ b/project/src/generators/weapongen/implementations/UbglExternalMagGen.ts @@ -9,9 +9,7 @@ import { EquipmentSlots } from "@spt-aki/models/enums/EquipmentSlots"; @injectable() export class UbglExternalMagGen implements IInventoryMagGen { - constructor( - @inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper, - ) + constructor(@inject("BotWeaponGeneratorHelper") protected botWeaponGeneratorHelper: BotWeaponGeneratorHelper) {} public getPriority(): number diff --git a/project/src/helpers/BotDifficultyHelper.ts b/project/src/helpers/BotDifficultyHelper.ts index 3b6298f5..9fd469d6 100644 --- a/project/src/helpers/BotDifficultyHelper.ts +++ b/project/src/helpers/BotDifficultyHelper.ts @@ -38,12 +38,8 @@ export class BotDifficultyHelper { const difficultySettings = this.getDifficultySettings(pmcType, difficulty); - const friendlyType = pmcType === "bear" - ? bearType - : usecType; - const enemyType = pmcType === "bear" - ? usecType - : bearType; + const friendlyType = pmcType === "bear" ? bearType : usecType; + const enemyType = pmcType === "bear" ? usecType : bearType; this.botHelper.addBotToEnemyList(difficultySettings, this.pmcConfig.enemyTypes, friendlyType); // Add generic bot types to enemy list this.botHelper.addBotToEnemyList(difficultySettings, [enemyType, friendlyType], ""); // add same/opposite side to enemy list diff --git a/project/src/helpers/BotGeneratorHelper.ts b/project/src/helpers/BotGeneratorHelper.ts index e1849094..97ac6b87 100644 --- a/project/src/helpers/BotGeneratorHelper.ts +++ b/project/src/helpers/BotGeneratorHelper.ts @@ -150,9 +150,7 @@ export class BotGeneratorHelper itemProperties.Togglable = {On: (this.randomUtil.getChance100(faceShieldActiveChance))}; } - return Object.keys(itemProperties).length - ? {upd: itemProperties} - : {}; + return Object.keys(itemProperties).length ? {upd: itemProperties} : {}; } /** @@ -240,10 +238,7 @@ export class BotGeneratorHelper maxDurability, ); - return { - Durability: currentDurability, - MaxDurability: maxDurability, - }; + return {Durability: currentDurability, MaxDurability: maxDurability}; } /** @@ -271,10 +266,7 @@ export class BotGeneratorHelper ); } - return { - Durability: currentDurability, - MaxDurability: maxDurability, - }; + return {Durability: currentDurability, MaxDurability: maxDurability}; } /** @@ -381,11 +373,7 @@ export class ExhaustableArray { private pool: T[]; - constructor( - private itemPool: T[], - private randomUtil: RandomUtil, - private jsonUtil: JsonUtil, - ) + constructor(private itemPool: T[], private randomUtil: RandomUtil, private jsonUtil: JsonUtil) { this.pool = this.jsonUtil.clone(itemPool); } diff --git a/project/src/helpers/BotHelper.ts b/project/src/helpers/BotHelper.ts index 9801ecb7..d7c1991d 100644 --- a/project/src/helpers/BotHelper.ts +++ b/project/src/helpers/BotHelper.ts @@ -248,8 +248,6 @@ export class BotHelper */ protected getRandomizedPmcSide(): string { - return (this.randomUtil.getChance100(this.pmcConfig.isUsec)) - ? "Usec" - : "Bear"; + return (this.randomUtil.getChance100(this.pmcConfig.isUsec)) ? "Usec" : "Bear"; } } diff --git a/project/src/helpers/BotWeaponGeneratorHelper.ts b/project/src/helpers/BotWeaponGeneratorHelper.ts index 3a0631e1..8be17470 100644 --- a/project/src/helpers/BotWeaponGeneratorHelper.ts +++ b/project/src/helpers/BotWeaponGeneratorHelper.ts @@ -96,10 +96,7 @@ export class BotWeaponGeneratorHelper */ public createMagazineWithAmmo(magazineTpl: string, ammoTpl: string, magTemplate: ITemplateItem): Item[] { - const magazine: Item[] = [{ - _id: this.hashUtil.generate(), - _tpl: magazineTpl, - }]; + const magazine: Item[] = [{_id: this.hashUtil.generate(), _tpl: magazineTpl}]; this.itemHelper.fillMagazineWithCartridge(magazine, magTemplate, ammoTpl, 1); @@ -128,13 +125,9 @@ export class BotWeaponGeneratorHelper for (const ammoItem of ammoItems) { - const result = this.addItemWithChildrenToEquipmentSlot( - equipmentSlotsToAddTo, - ammoItem._id, - ammoItem._tpl, - [ammoItem], - inventory, - ); + const result = this.addItemWithChildrenToEquipmentSlot(equipmentSlotsToAddTo, ammoItem._id, ammoItem._tpl, [ + ammoItem, + ], inventory); if (result === ItemAddedResult.NO_SPACE) { diff --git a/project/src/helpers/DialogueHelper.ts b/project/src/helpers/DialogueHelper.ts index 86e2ecdf..47c4a799 100644 --- a/project/src/helpers/DialogueHelper.ts +++ b/project/src/helpers/DialogueHelper.ts @@ -39,10 +39,7 @@ export class DialogueHelper */ public createMessageContext(templateId: string, messageType: MessageType, maxStoreTime = null): MessageContent { - const result: MessageContent = { - templateId: templateId, - type: messageType, - }; + const result: MessageContent = {templateId: templateId, type: messageType}; if (maxStoreTime) { @@ -69,14 +66,7 @@ export class DialogueHelper if (isNewDialogue) { - dialogue = { - _id: dialogueID, - type: messageType, - messages: [], - pinned: false, - new: 0, - attachmentsNew: 0, - }; + dialogue = {_id: dialogueID, type: messageType, messages: [], pinned: false, new: 0, attachmentsNew: 0}; dialogueData[dialogueID] = dialogue; } @@ -89,10 +79,7 @@ export class DialogueHelper if (rewards.length > 0) { const stashId = this.hashUtil.generate(); - items = { - stash: stashId, - data: [], - }; + items = {stash: stashId, data: []}; rewards = this.itemHelper.replaceIDs(null, rewards); for (const reward of rewards) diff --git a/project/src/helpers/DurabilityLimitsHelper.ts b/project/src/helpers/DurabilityLimitsHelper.ts index 8840976e..45d2abcb 100644 --- a/project/src/helpers/DurabilityLimitsHelper.ts +++ b/project/src/helpers/DurabilityLimitsHelper.ts @@ -177,9 +177,7 @@ export class DurabilityLimitsHelper ); // Dont let weapon dura go below the percent defined in config - return (result >= durabilityValueMinLimit) - ? result - : durabilityValueMinLimit; + return (result >= durabilityValueMinLimit) ? result : durabilityValueMinLimit; } protected generateArmorDurability(botRole: string, maxDurability: number): number @@ -193,9 +191,7 @@ export class DurabilityLimitsHelper ); // Dont let armor dura go below the percent defined in config - return (result >= durabilityValueMinLimit) - ? result - : durabilityValueMinLimit; + return (result >= durabilityValueMinLimit) ? result : durabilityValueMinLimit; } protected getMinWeaponDeltaFromConfig(botRole: string): number diff --git a/project/src/helpers/HandbookHelper.ts b/project/src/helpers/HandbookHelper.ts index bc93a88d..a5662eb5 100644 --- a/project/src/helpers/HandbookHelper.ts +++ b/project/src/helpers/HandbookHelper.ts @@ -49,9 +49,7 @@ export class HandbookHelper { this.handbookPriceCache.items.byParent.set(handbookItem.ParentId, []); } - this.handbookPriceCache.items.byParent - .get(handbookItem.ParentId) - .push(handbookItem.Id); + this.handbookPriceCache.items.byParent.get(handbookItem.ParentId).push(handbookItem.Id); } for (const handbookCategory of handbookDb.Categories) @@ -63,9 +61,7 @@ export class HandbookHelper { this.handbookPriceCache.categories.byParent.set(handbookCategory.ParentId, []); } - this.handbookPriceCache.categories.byParent - .get(handbookCategory.ParentId) - .push(handbookCategory.Id); + this.handbookPriceCache.categories.byParent.get(handbookCategory.ParentId).push(handbookCategory.Id); } } } diff --git a/project/src/helpers/HealthHelper.ts b/project/src/helpers/HealthHelper.ts index aa934564..f9247e8a 100644 --- a/project/src/helpers/HealthHelper.ts +++ b/project/src/helpers/HealthHelper.ts @@ -38,10 +38,7 @@ export class HealthHelper if (!profile.vitality) { // Occurs on newly created profiles - profile.vitality = { - health: null, - effects: null, - }; + profile.vitality = {health: null, effects: null}; } profile.vitality.health = { Hydration: 0, diff --git a/project/src/helpers/HideoutHelper.ts b/project/src/helpers/HideoutHelper.ts index 55e83f88..b6449457 100644 --- a/project/src/helpers/HideoutHelper.ts +++ b/project/src/helpers/HideoutHelper.ts @@ -651,13 +651,7 @@ export class HideoutHelper */ protected getAreaUpdObject(stackCount: number, resourceValue: number, resourceUnitsConsumed: number): Upd { - return { - StackObjectsCount: stackCount, - Resource: { - Value: resourceValue, - UnitsConsumed: resourceUnitsConsumed, - }, - }; + return {StackObjectsCount: stackCount, Resource: {Value: resourceValue, UnitsConsumed: resourceUnitsConsumed}}; } protected updateAirFilters(airFilterArea: HideoutArea, pmcData: IPmcData): void @@ -705,10 +699,7 @@ export class HideoutHelper { airFilterArea.slots[i].item[0].upd = { StackObjectsCount: 1, - Resource: { - Value: resourceValue, - UnitsConsumed: pointsConsumed, - }, + Resource: {Value: resourceValue, UnitsConsumed: pointsConsumed}, }; this.logger.debug(`Air filter: ${resourceValue} filter left on slot ${i + 1}`); break; // Break here to avoid updating all filters @@ -815,9 +806,7 @@ export class HideoutHelper btcProd.Products.push({ _id: this.hashUtil.generate(), _tpl: "59faff1d86f7746c51718c9c", - upd: { - StackObjectsCount: 1, - }, + upd: {StackObjectsCount: 1}, }); btcProd.Progress -= coinCraftTimeSeconds; @@ -896,9 +885,7 @@ export class HideoutHelper // at level 1 you already get 0.5%, so it goes up until level 50. For some reason the wiki // says that it caps at level 51 with 25% but as per dump data that is incorrect apparently let roundedLevel = Math.floor(hideoutManagementSkill.Progress / 100); - roundedLevel = (roundedLevel === 51) - ? roundedLevel - 1 - : roundedLevel; + roundedLevel = (roundedLevel === 51) ? roundedLevel - 1 : roundedLevel; return (roundedLevel * this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement @@ -1023,9 +1010,7 @@ export class HideoutHelper */ protected hideoutImprovementIsComplete(improvement: IHideoutImprovement): boolean { - return improvement?.completed - ? true - : false; + return improvement?.completed ? true : false; } /** diff --git a/project/src/helpers/HttpServerHelper.ts b/project/src/helpers/HttpServerHelper.ts index 65b38bcc..d8f0c1e6 100644 --- a/project/src/helpers/HttpServerHelper.ts +++ b/project/src/helpers/HttpServerHelper.ts @@ -21,9 +21,7 @@ export class HttpServerHelper txt: "text/plain", }; - constructor( - @inject("ConfigServer") protected configServer: ConfigServer, - ) + constructor(@inject("ConfigServer") protected configServer: ConfigServer) { this.httpConfig = this.configServer.getConfig(ConfigTypes.HTTP); } diff --git a/project/src/helpers/InRaidHelper.ts b/project/src/helpers/InRaidHelper.ts index 952a134a..c5c35953 100644 --- a/project/src/helpers/InRaidHelper.ts +++ b/project/src/helpers/InRaidHelper.ts @@ -593,10 +593,7 @@ export class InRaidHelper } // Add these new found items to our list of inventory items - inventoryItems = [ - ...inventoryItems, - ...foundItems, - ]; + inventoryItems = [...inventoryItems, ...foundItems]; // Now find the children of these items newItems = foundItems; diff --git a/project/src/helpers/InventoryHelper.ts b/project/src/helpers/InventoryHelper.ts index 9bf19682..e94f4ba9 100644 --- a/project/src/helpers/InventoryHelper.ts +++ b/project/src/helpers/InventoryHelper.ts @@ -175,9 +175,7 @@ export class InventoryHelper catch (err) { // Callback failed - const message = typeof err === "string" - ? err - : this.localisationService.getText("http-unknown_error"); + const message = typeof err === "string" ? err : this.localisationService.getText("http-unknown_error"); return this.httpResponse.appendErrorToOutput(output, message); } @@ -299,11 +297,7 @@ export class InventoryHelper _tpl: itemLib[tmpKey]._tpl, parentId: toDo[0][1], slotId: slotID, - location: { - x: itemToAdd.location.x, - y: itemToAdd.location.y, - r: "Horizontal", - }, + location: {x: itemToAdd.location.x, y: itemToAdd.location.y, r: "Horizontal"}, upd: this.jsonUtil.clone(upd), }); @@ -312,11 +306,7 @@ export class InventoryHelper _tpl: itemLib[tmpKey]._tpl, parentId: toDo[0][1], slotId: itemLib[tmpKey].slotId, - location: { - x: itemToAdd.location.x, - y: itemToAdd.location.y, - r: "Horizontal", - }, + location: {x: itemToAdd.location.x, y: itemToAdd.location.y, r: "Horizontal"}, upd: this.jsonUtil.clone(upd), }); } @@ -405,9 +395,7 @@ export class InventoryHelper } catch (err) { - const errorText = typeof err === "string" - ? ` -> ${err}` - : ""; + const errorText = typeof err === "string" ? ` -> ${err}` : ""; this.logger.error(this.localisationService.getText("inventory-fill_container_failed", errorText)); return this.httpResponse.appendErrorToOutput( @@ -897,10 +885,7 @@ export class InventoryHelper protected getInventoryItemHash(inventoryItem: Item[]): InventoryHelper.InventoryItemHash { - const inventoryItemHash: InventoryHelper.InventoryItemHash = { - byItemId: {}, - byParentId: {}, - }; + const inventoryItemHash: InventoryHelper.InventoryItemHash = {byItemId: {}, byParentId: {}}; for (const item of inventoryItem) { @@ -942,14 +927,16 @@ export class InventoryHelper const tmpSize = this.getSizeByInventoryItemHash(item._tpl, item._id, inventoryItemHash); const iW = tmpSize[0]; // x const iH = tmpSize[1]; // y - const fH = ((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" - || (item.location as Location).rotation === "Vertical") - ? iW - : iH; - const fW = ((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" - || (item.location as Location).rotation === "Vertical") - ? iH - : iW; + const fH = + ((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" + || (item.location as Location).rotation === "Vertical") + ? iW + : iH; + const fW = + ((item.location as Location).r === 1 || (item.location as Location).r === "Vertical" + || (item.location as Location).rotation === "Vertical") + ? iH + : iW; const fillTo = (item.location as Location).x + fW; for (let y = 0; y < fH; y++) @@ -1002,9 +989,7 @@ export class InventoryHelper else if (request.fromOwner.type.toLocaleLowerCase() === "mail") { // Split requests dont use 'use' but 'splitItem' property - const item = "splitItem" in request - ? request.splitItem - : request.item; + const item = "splitItem" in request ? request.splitItem : request.item; fromInventoryItems = this.dialogueHelper.getMessageItemContents(request.fromOwner.id, sessionId, item); fromType = "mail"; } diff --git a/project/src/helpers/ItemHelper.ts b/project/src/helpers/ItemHelper.ts index 1c47c474..cc9731ca 100644 --- a/project/src/helpers/ItemHelper.ts +++ b/project/src/helpers/ItemHelper.ts @@ -176,9 +176,7 @@ class ItemHelper { if (item.upd === undefined) { - item.upd = { - StackObjectsCount: 1, - }; + item.upd = {StackObjectsCount: 1}; } if (item.upd.StackObjectsCount === undefined) @@ -243,9 +241,7 @@ class ItemHelper parentId: parentId, slotId: slotId, location: 0, - upd: { - StackObjectsCount: count, - }, + upd: {StackObjectsCount: count}, }; stackSlotItems.push(stackSlotItem); } @@ -473,10 +469,7 @@ class ItemHelper */ public hasBuyRestrictions(itemToCheck: Item): boolean { - if ( - itemToCheck.upd?.BuyRestrictionCurrent !== undefined - && itemToCheck.upd?.BuyRestrictionMax !== undefined - ) + if (itemToCheck.upd?.BuyRestrictionCurrent !== undefined && itemToCheck.upd?.BuyRestrictionMax !== undefined) { return true; } @@ -574,18 +567,14 @@ class ItemHelper public findBarterItems(by: "tpl" | "id", items: Item[], barterItemId: string): Item[] { // find required items to take after buying (handles multiple items) - const barterIDs = typeof barterItemId === "string" - ? [barterItemId] - : barterItemId; + const barterIDs = typeof barterItemId === "string" ? [barterItemId] : barterItemId; let barterItems: Item[] = []; for (const barterID of barterIDs) { const filterResult = items.filter((item) => { - return by === "tpl" - ? (item._tpl === barterID) - : (item._id === barterID); + return by === "tpl" ? (item._tpl === barterID) : (item._id === barterID); }); barterItems = Object.assign(barterItems, filterResult); @@ -954,9 +943,7 @@ class ItemHelper while (currentStoredCartridgeCount < ammoBoxMaxCartridgeCount) { const remainingSpace = ammoBoxMaxCartridgeCount - currentStoredCartridgeCount; - const cartridgeCountToAdd = (remainingSpace < maxPerStack) - ? remainingSpace - : maxPerStack; + const cartridgeCountToAdd = (remainingSpace < maxPerStack) ? remainingSpace : maxPerStack; // Add cartridge item into items array ammoBox.push(this.createCartridges(ammoBox[0]._id, cartridgeTpl, cartridgeCountToAdd, location)); @@ -1086,10 +1073,8 @@ class ItemHelper const ammoTpls = magTemplate._props.Cartridges[0]._props.filters[0].Filter; const calibers = [ ...new Set( - ammoTpls.filter( - (x: string) => this.getItem(x)[0], - ).map( - (x: string) => this.getItem(x)[1]._props.Caliber, + ammoTpls.filter((x: string) => this.getItem(x)[0]).map((x: string) => + this.getItem(x)[1]._props.Caliber ), ), ]; @@ -1107,9 +1092,7 @@ class ItemHelper const ammoArray = new ProbabilityObjectArray(this.mathUtil, this.jsonUtil); for (const icd of staticAmmoDist[caliber]) { - ammoArray.push( - new ProbabilityObject(icd.tpl, icd.relativeProbability), - ); + ammoArray.push(new ProbabilityObject(icd.tpl, icd.relativeProbability)); } return ammoArray.draw(1)[0]; } diff --git a/project/src/helpers/NotifierHelper.ts b/project/src/helpers/NotifierHelper.ts index 4f340086..fb170a45 100644 --- a/project/src/helpers/NotifierHelper.ts +++ b/project/src/helpers/NotifierHelper.ts @@ -10,14 +10,9 @@ export class NotifierHelper /** * The default notification sent when waiting times out. */ - protected defaultNotification: INotification = { - type: NotificationType.PING, - eventId: "ping", - }; + protected defaultNotification: INotification = {type: NotificationType.PING, eventId: "ping"}; - constructor( - @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper, - ) + constructor(@inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper) {} public getDefaultNotification(): INotification diff --git a/project/src/helpers/PaymentHelper.ts b/project/src/helpers/PaymentHelper.ts index a835ab31..909dceb9 100644 --- a/project/src/helpers/PaymentHelper.ts +++ b/project/src/helpers/PaymentHelper.ts @@ -10,9 +10,7 @@ export class PaymentHelper { protected inventoryConfig: IInventoryConfig; - constructor( - @inject("ConfigServer") protected configServer: ConfigServer, - ) + constructor(@inject("ConfigServer") protected configServer: ConfigServer) { this.inventoryConfig = this.configServer.getConfig(ConfigTypes.INVENTORY); } diff --git a/project/src/helpers/PresetHelper.ts b/project/src/helpers/PresetHelper.ts index c973fd98..cfefb0bd 100644 --- a/project/src/helpers/PresetHelper.ts +++ b/project/src/helpers/PresetHelper.ts @@ -25,13 +25,13 @@ export class PresetHelper { if (!this.defaultPresets) { - this.defaultPresets = Object.values(this.databaseServer.getTables().globals.ItemPresets) - .filter((x) => x._encyclopedia !== undefined) - .reduce((acc, cur) => - { - acc[cur._id] = cur; - return acc; - }, {}); + this.defaultPresets = Object.values(this.databaseServer.getTables().globals.ItemPresets).filter((x) => + x._encyclopedia !== undefined + ).reduce((acc, cur) => + { + acc[cur._id] = cur; + return acc; + }, {}); } return this.defaultPresets; diff --git a/project/src/helpers/ProfileHelper.ts b/project/src/helpers/ProfileHelper.ts index 95ebea98..120b65d9 100644 --- a/project/src/helpers/ProfileHelper.ts +++ b/project/src/helpers/ProfileHelper.ts @@ -217,9 +217,7 @@ export class ProfileHelper public getDefaultAkiDataObject(): any { - return { - version: this.getServerVersion(), - }; + return {version: this.getServerVersion()}; } public getFullProfile(sessionID: string): IAkiProfile @@ -257,11 +255,7 @@ export class ProfileHelper return { Eft: { CarriedQuestItems: [], - DamageHistory: { - LethalDamagePart: "Head", - LethalDamage: undefined, - BodyParts: [], - }, + DamageHistory: {LethalDamagePart: "Head", LethalDamage: undefined, BodyParts: []}, DroppedItems: [], ExperienceBonusMult: 0, FoundInRaidItems: [], diff --git a/project/src/helpers/QuestHelper.ts b/project/src/helpers/QuestHelper.ts index 4af49a8f..30d9ebfa 100644 --- a/project/src/helpers/QuestHelper.ts +++ b/project/src/helpers/QuestHelper.ts @@ -69,9 +69,7 @@ export class QuestHelper { const quest = pmcData.Quests?.find((q) => q.qid === questId); - return quest - ? quest.status - : QuestStatus.Locked; + return quest ? quest.status : QuestStatus.Locked; } /** @@ -328,12 +326,9 @@ export class QuestHelper public getQuestRewardItems(quest: IQuest, status: QuestStatus): Reward[] { // Iterate over all rewards with the desired status, flatten out items that have a type of Item - const questRewards = quest.rewards[QuestStatus[status]] - .flatMap((reward: Reward) => - reward.type === "Item" - ? this.processReward(reward) - : [] - ); + const questRewards = quest.rewards[QuestStatus[status]].flatMap((reward: Reward) => + reward.type === "Item" ? this.processReward(reward) : [] + ); return questRewards; } @@ -467,14 +462,12 @@ export class QuestHelper const quests = this.getQuestsFromDb().filter((q) => { - const acceptedQuestCondition = q.conditions.AvailableForStart.find( - (c) => - { - return c._parent === "Quest" - && c._props.target === failedQuestId - && c._props.status[0] === QuestStatus.Fail; - }, - ); + const acceptedQuestCondition = q.conditions.AvailableForStart.find((c) => + { + return c._parent === "Quest" + && c._props.target === failedQuestId + && c._props.status[0] === QuestStatus.Fail; + }); if (!acceptedQuestCondition) { @@ -581,9 +574,7 @@ export class QuestHelper parentId: item.parentId, slotId: item.slotId, location: item.location, - upd: { - StackObjectsCount: item.upd.StackObjectsCount, - }, + upd: {StackObjectsCount: item.upd.StackObjectsCount}, }); } diff --git a/project/src/helpers/RagfairHelper.ts b/project/src/helpers/RagfairHelper.ts index 3f8f9d39..105cecfb 100644 --- a/project/src/helpers/RagfairHelper.ts +++ b/project/src/helpers/RagfairHelper.ts @@ -73,9 +73,7 @@ export class RagfairHelper if (info.linkedSearchId) { const data = this.ragfairLinkedItemService.getLinkedItems(info.linkedSearchId); - result = !data - ? [] - : [...data]; + result = !data ? [] : [...data]; } // Case: category diff --git a/project/src/helpers/RagfairSellHelper.ts b/project/src/helpers/RagfairSellHelper.ts index 5804df65..5f5d174f 100644 --- a/project/src/helpers/RagfairSellHelper.ts +++ b/project/src/helpers/RagfairSellHelper.ts @@ -61,9 +61,7 @@ export class RagfairSellHelper playerListedPriceRub: number, ): number { - return (playerListedPriceRub < averageOfferPriceRub) - ? this.ragfairConfig.sell.chance.underpriced - : 1; + return (playerListedPriceRub < averageOfferPriceRub) ? this.ragfairConfig.sell.chance.underpriced : 1; } /** @@ -114,10 +112,7 @@ export class RagfairSellHelper this.ragfairConfig.sell.time.min * 60, ); - result.push({ - sellTime: sellTime, - amount: boughtAmount, - }); + result.push({sellTime: sellTime, amount: boughtAmount}); this.logger.debug(`Offer will sell at: ${new Date(sellTime * 1000).toLocaleTimeString("en-US")}`); } diff --git a/project/src/helpers/RagfairSortHelper.ts b/project/src/helpers/RagfairSortHelper.ts index afbfcc5b..edb06fa4 100644 --- a/project/src/helpers/RagfairSortHelper.ts +++ b/project/src/helpers/RagfairSortHelper.ts @@ -75,11 +75,7 @@ export class RagfairSortHelper const nameA = locale[`${tplA} Name`] || tplA; const nameB = locale[`${tplB} Name`] || tplB; - return (nameA < nameB) - ? -1 - : (nameA > nameB) - ? 1 - : 0; + return (nameA < nameB) ? -1 : (nameA > nameB) ? 1 : 0; } /** diff --git a/project/src/helpers/RepairHelper.ts b/project/src/helpers/RepairHelper.ts index 6aa88118..2b0e48f9 100644 --- a/project/src/helpers/RepairHelper.ts +++ b/project/src/helpers/RepairHelper.ts @@ -68,10 +68,7 @@ export class RepairHelper } // Construct object to return - itemToRepair.upd.Repairable = { - Durability: newCurrentDurability, - MaxDurability: newCurrentMaxDurability, - }; + itemToRepair.upd.Repairable = {Durability: newCurrentDurability, MaxDurability: newCurrentMaxDurability}; // when modders set the repair coefficient to 0 it means that they dont want to lose durability on items // the code below generates a random degradation on the weapon durability @@ -138,12 +135,8 @@ export class RepairHelper traderQualityMultipler: number, ): number { - const minRepairDeg = isRepairKit - ? itemProps.MinRepairKitDegradation - : itemProps.MinRepairDegradation; - let maxRepairDeg = isRepairKit - ? itemProps.MaxRepairKitDegradation - : itemProps.MaxRepairDegradation; + const minRepairDeg = isRepairKit ? itemProps.MinRepairKitDegradation : itemProps.MinRepairDegradation; + let maxRepairDeg = isRepairKit ? itemProps.MaxRepairKitDegradation : itemProps.MaxRepairDegradation; // WORKAROUND: Some items are always 0 when repairkit is true if (maxRepairDeg === 0) diff --git a/project/src/helpers/SecureContainerHelper.ts b/project/src/helpers/SecureContainerHelper.ts index a62f51b1..a8dd36af 100644 --- a/project/src/helpers/SecureContainerHelper.ts +++ b/project/src/helpers/SecureContainerHelper.ts @@ -14,9 +14,7 @@ export interface OwnerInventoryItems @injectable() export class SecureContainerHelper { - constructor( - @inject("ItemHelper") protected itemHelper: ItemHelper, - ) + constructor(@inject("ItemHelper") protected itemHelper: ItemHelper) {} public getSecureContainerItems(items: Item[]): string[] diff --git a/project/src/helpers/TradeHelper.ts b/project/src/helpers/TradeHelper.ts index c4b0d3c1..11750a18 100644 --- a/project/src/helpers/TradeHelper.ts +++ b/project/src/helpers/TradeHelper.ts @@ -60,13 +60,11 @@ export class TradeHelper let output = this.eventOutputHolder.getOutput(sessionID); const newReq = { - items: [ - { - // eslint-disable-next-line @typescript-eslint/naming-convention - item_id: buyRequestData.item_id, - count: buyRequestData.count, - }, - ], + items: [{ + // eslint-disable-next-line @typescript-eslint/naming-convention + item_id: buyRequestData.item_id, + count: buyRequestData.count, + }], tid: buyRequestData.tid, }; diff --git a/project/src/helpers/TraderAssortHelper.ts b/project/src/helpers/TraderAssortHelper.ts index 535d48e6..3ee329fc 100644 --- a/project/src/helpers/TraderAssortHelper.ts +++ b/project/src/helpers/TraderAssortHelper.ts @@ -26,11 +26,7 @@ import { TimeUtil } from "@spt-aki/utils/TimeUtil"; export class TraderAssortHelper { protected traderConfig: ITraderConfig; - protected mergedQuestAssorts: Record> = { - started: {}, - success: {}, - fail: {}, - }; + protected mergedQuestAssorts: Record> = {started: {}, success: {}, fail: {}}; protected createdMergedQuestAssorts = false; constructor( diff --git a/project/src/helpers/TraderHelper.ts b/project/src/helpers/TraderHelper.ts index 7f0af7d8..aaae8ecd 100644 --- a/project/src/helpers/TraderHelper.ts +++ b/project/src/helpers/TraderHelper.ts @@ -199,9 +199,7 @@ export class TraderHelper { const newStanding = currentStanding + standingToAdd; - return newStanding < 0 - ? 0 - : newStanding; + return newStanding < 0 ? 0 : newStanding; } /** @@ -229,8 +227,7 @@ export class TraderHelper if ( (loyalty.minLevel <= pmcData.Info.Level && loyalty.minSalesSum <= pmcData.TradersInfo[traderID].salesSum - && loyalty.minStanding <= pmcData.TradersInfo[traderID].standing) - && targetLevel < 4 + && loyalty.minStanding <= pmcData.TradersInfo[traderID].standing) && targetLevel < 4 ) { // level reached @@ -271,10 +268,7 @@ export class TraderHelper }), ); this.traderConfig.updateTime.push( // create temporary entry to prevent logger spam - { - traderId: traderId, - seconds: this.traderConfig.updateTimeDefault, - }, + {traderId: traderId, seconds: this.traderConfig.updateTimeDefault}, ); } else diff --git a/project/src/helpers/WeightedRandomHelper.ts b/project/src/helpers/WeightedRandomHelper.ts index 5b6178a4..7e66a3e0 100644 --- a/project/src/helpers/WeightedRandomHelper.ts +++ b/project/src/helpers/WeightedRandomHelper.ts @@ -77,10 +77,7 @@ export class WeightedRandomHelper { if (cumulativeWeights[itemIndex] >= randomNumber) { - return { - item: items[itemIndex], - index: itemIndex, - }; + return {item: items[itemIndex], index: itemIndex}; } } } diff --git a/project/src/models/external/HttpFramework.ts b/project/src/models/external/HttpFramework.ts index 8c3d0326..ffc28468 100644 --- a/project/src/models/external/HttpFramework.ts +++ b/project/src/models/external/HttpFramework.ts @@ -111,11 +111,7 @@ const createHttpDecorator = (httpMethod: HttpMethods) => } // Flag the method as a HTTP handler - target.handlers.push({ - handlerName: propertyKey, - path, - httpMethod, - }); + target.handlers.push({handlerName: propertyKey, path, httpMethod}); }; }; }; diff --git a/project/src/models/spt/server/IDatabaseTables.ts b/project/src/models/spt/server/IDatabaseTables.ts index 140bd1d6..73ce43ed 100644 --- a/project/src/models/spt/server/IDatabaseTables.ts +++ b/project/src/models/spt/server/IDatabaseTables.ts @@ -24,11 +24,7 @@ import { ISettingsBase } from "@spt-aki/models/spt/server/ISettingsBase"; export interface IDatabaseTables { - bots?: { - types: Record; - base: IBotBase; - core: IBotCore; - }; + bots?: {types: Record; base: IBotBase; core: IBotCore;}; hideout?: { areas: IHideoutArea[]; production: IHideoutProduction[]; diff --git a/project/src/routers/EventOutputHolder.ts b/project/src/routers/EventOutputHolder.ts index b020371d..dca76e78 100644 --- a/project/src/routers/EventOutputHolder.ts +++ b/project/src/routers/EventOutputHolder.ts @@ -22,10 +22,7 @@ export class EventOutputHolder {} // TODO REMEMBER TO CHANGE OUTPUT - protected output: IItemEventRouterResponse = { - warnings: [], - profileChanges: {}, - }; + protected output: IItemEventRouterResponse = {warnings: [], profileChanges: {}}; public getOutput(sessionID: string): IItemEventRouterResponse { @@ -54,18 +51,10 @@ export class EventOutputHolder ragFairOffers: [], weaponBuilds: [], equipmentBuilds: [], - items: { - new: [], - change: [], - del: [], - }, + items: {new: [], change: [], del: []}, production: {}, improvements: {}, - skills: { - Common: [], - Mastering: [], - Points: 0, - }, + skills: {Common: [], Mastering: [], Points: 0}, health: this.jsonUtil.clone(pmcData.Health), traderRelations: {}, // changedHideoutStashes: {}, diff --git a/project/src/routers/HttpRouter.ts b/project/src/routers/HttpRouter.ts index 620c53d3..a507f3c8 100644 --- a/project/src/routers/HttpRouter.ts +++ b/project/src/routers/HttpRouter.ts @@ -87,8 +87,6 @@ export class HttpRouter class ResponseWrapper { - constructor( - public output: string, - ) + constructor(public output: string) {} } diff --git a/project/src/routers/dynamic/BotDynamicRouter.ts b/project/src/routers/dynamic/BotDynamicRouter.ts index 6f374792..df65c79b 100644 --- a/project/src/routers/dynamic/BotDynamicRouter.ts +++ b/project/src/routers/dynamic/BotDynamicRouter.ts @@ -6,41 +6,37 @@ import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() export class BotDynamicRouter extends DynamicRouter { - constructor( - @inject("BotCallbacks") protected botCallbacks: BotCallbacks, - ) + constructor(@inject("BotCallbacks") protected botCallbacks: BotCallbacks) { - super( - [ - new RouteAction( - "/singleplayer/settings/bot/limit/", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.botCallbacks.getBotLimit(url, info, sessionID); - }, - ), - new RouteAction( - "/singleplayer/settings/bot/difficulty/", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.botCallbacks.getBotDifficulty(url, info, sessionID); - }, - ), - new RouteAction( - "/singleplayer/settings/bot/maxCap", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.botCallbacks.getBotCap(); - }, - ), - new RouteAction( - "/singleplayer/settings/bot/getBotBehaviours/", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.botCallbacks.getBotBehaviours(); - }, - ), - ], - ); + super([ + new RouteAction( + "/singleplayer/settings/bot/limit/", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.botCallbacks.getBotLimit(url, info, sessionID); + }, + ), + new RouteAction( + "/singleplayer/settings/bot/difficulty/", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.botCallbacks.getBotDifficulty(url, info, sessionID); + }, + ), + new RouteAction( + "/singleplayer/settings/bot/maxCap", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.botCallbacks.getBotCap(); + }, + ), + new RouteAction( + "/singleplayer/settings/bot/getBotBehaviours/", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.botCallbacks.getBotBehaviours(); + }, + ), + ]); } } diff --git a/project/src/routers/dynamic/BundleDynamicRouter.ts b/project/src/routers/dynamic/BundleDynamicRouter.ts index c365c98d..929eba50 100644 --- a/project/src/routers/dynamic/BundleDynamicRouter.ts +++ b/project/src/routers/dynamic/BundleDynamicRouter.ts @@ -6,20 +6,13 @@ import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() export class BundleDynamicRouter extends DynamicRouter { - constructor( - @inject("BundleCallbacks") protected bundleCallbacks: BundleCallbacks, - ) + constructor(@inject("BundleCallbacks") protected bundleCallbacks: BundleCallbacks) { - super( - [ - new RouteAction( - ".bundle", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.bundleCallbacks.getBundle(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction(".bundle", (url: string, info: any, sessionID: string, output: string): any => + { + return this.bundleCallbacks.getBundle(url, info, sessionID); + }), + ]); } } diff --git a/project/src/routers/dynamic/CustomizationDynamicRouter.ts b/project/src/routers/dynamic/CustomizationDynamicRouter.ts index 75e8d516..1a146349 100644 --- a/project/src/routers/dynamic/CustomizationDynamicRouter.ts +++ b/project/src/routers/dynamic/CustomizationDynamicRouter.ts @@ -6,20 +6,16 @@ import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() export class CustomizationDynamicRouter extends DynamicRouter { - constructor( - @inject("CustomizationCallbacks") protected customizationCallbacks: CustomizationCallbacks, - ) + constructor(@inject("CustomizationCallbacks") protected customizationCallbacks: CustomizationCallbacks) { - super( - [ - new RouteAction( - "/client/trading/customization/", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.customizationCallbacks.getTraderSuits(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/trading/customization/", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.customizationCallbacks.getTraderSuits(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/dynamic/DataDynamicRouter.ts b/project/src/routers/dynamic/DataDynamicRouter.ts index 9f364c17..82ab4860 100644 --- a/project/src/routers/dynamic/DataDynamicRouter.ts +++ b/project/src/routers/dynamic/DataDynamicRouter.ts @@ -6,34 +6,21 @@ import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() export class DataDynamicRouter extends DynamicRouter { - constructor( - @inject("DataCallbacks") protected dataCallbacks: DataCallbacks, - ) + constructor(@inject("DataCallbacks") protected dataCallbacks: DataCallbacks) { - super( - [ - new RouteAction( - "/client/menu/locale/", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getLocalesMenu(url, info, sessionID); - }, - ), - new RouteAction( - "/client/locale/", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getLocalesGlobal(url, info, sessionID); - }, - ), - new RouteAction( - "/client/items/prices/", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getItemPrices(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/client/menu/locale/", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getLocalesMenu(url, info, sessionID); + }), + new RouteAction("/client/locale/", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getLocalesGlobal(url, info, sessionID); + }), + new RouteAction("/client/items/prices/", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getItemPrices(url, info, sessionID); + }), + ]); } } diff --git a/project/src/routers/dynamic/HttpDynamicRouter.ts b/project/src/routers/dynamic/HttpDynamicRouter.ts index 4fd9357e..c7e677ec 100644 --- a/project/src/routers/dynamic/HttpDynamicRouter.ts +++ b/project/src/routers/dynamic/HttpDynamicRouter.ts @@ -6,34 +6,21 @@ import { ImageRouter } from "@spt-aki/routers/ImageRouter"; @injectable() export class HttpDynamicRouter extends DynamicRouter { - constructor( - @inject("ImageRouter") protected imageRouter: ImageRouter, - ) + constructor(@inject("ImageRouter") protected imageRouter: ImageRouter) { - super( - [ - new RouteAction( - ".jpg", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.imageRouter.getImage(); - }, - ), - new RouteAction( - ".png", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.imageRouter.getImage(); - }, - ), - new RouteAction( - ".ico", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.imageRouter.getImage(); - }, - ), - ], - ); + super([ + new RouteAction(".jpg", (url: string, info: any, sessionID: string, output: string): any => + { + return this.imageRouter.getImage(); + }), + new RouteAction(".png", (url: string, info: any, sessionID: string, output: string): any => + { + return this.imageRouter.getImage(); + }), + new RouteAction(".ico", (url: string, info: any, sessionID: string, output: string): any => + { + return this.imageRouter.getImage(); + }), + ]); } } diff --git a/project/src/routers/dynamic/InraidDynamicRouter.ts b/project/src/routers/dynamic/InraidDynamicRouter.ts index f8e1a9c2..72ccea1d 100644 --- a/project/src/routers/dynamic/InraidDynamicRouter.ts +++ b/project/src/routers/dynamic/InraidDynamicRouter.ts @@ -6,21 +6,17 @@ import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() export class InraidDynamicRouter extends DynamicRouter { - constructor( - @inject("InraidCallbacks") protected inraidCallbacks: InraidCallbacks, - ) + constructor(@inject("InraidCallbacks") protected inraidCallbacks: InraidCallbacks) { - super( - [ - new RouteAction( - "/client/location/getLocalloot", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.inraidCallbacks.registerPlayer(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/location/getLocalloot", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.inraidCallbacks.registerPlayer(url, info, sessionID); + }, + ), + ]); } public override getTopLevelRoute(): string diff --git a/project/src/routers/dynamic/LocationDynamicRouter.ts b/project/src/routers/dynamic/LocationDynamicRouter.ts index 798ece9d..76eaa6ba 100644 --- a/project/src/routers/dynamic/LocationDynamicRouter.ts +++ b/project/src/routers/dynamic/LocationDynamicRouter.ts @@ -6,21 +6,17 @@ import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() export class LocationDynamicRouter extends DynamicRouter { - constructor( - @inject("LocationCallbacks") protected locationCallbacks: LocationCallbacks, - ) + constructor(@inject("LocationCallbacks") protected locationCallbacks: LocationCallbacks) { - super( - [ - new RouteAction( - "/client/location/getLocalloot", - (url: string, info: any, sessionID: string, _output: string): any => - { - return this.locationCallbacks.getLocation(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/location/getLocalloot", + (url: string, info: any, sessionID: string, _output: string): any => + { + return this.locationCallbacks.getLocation(url, info, sessionID); + }, + ), + ]); } public override getTopLevelRoute(): string diff --git a/project/src/routers/dynamic/NotifierDynamicRouter.ts b/project/src/routers/dynamic/NotifierDynamicRouter.ts index 261c2a20..cf8c86b8 100644 --- a/project/src/routers/dynamic/NotifierDynamicRouter.ts +++ b/project/src/routers/dynamic/NotifierDynamicRouter.ts @@ -6,41 +6,28 @@ import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() export class NotifierDynamicRouter extends DynamicRouter { - constructor( - @inject("NotifierCallbacks") protected notifierCallbacks: NotifierCallbacks, - ) + constructor(@inject("NotifierCallbacks") protected notifierCallbacks: NotifierCallbacks) { - super( - [ - new RouteAction( - "/?last_id", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.notifierCallbacks.notify(url, info, sessionID); - }, - ), - new RouteAction( - "/notifierServer", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.notifierCallbacks.notify(url, info, sessionID); - }, - ), - new RouteAction( - "/push/notifier/get/", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.notifierCallbacks.getNotifier(url, info, sessionID); - }, - ), - new RouteAction( - "/push/notifier/getwebsocket/", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.notifierCallbacks.getNotifier(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/?last_id", (url: string, info: any, sessionID: string, output: string): any => + { + return this.notifierCallbacks.notify(url, info, sessionID); + }), + new RouteAction("/notifierServer", (url: string, info: any, sessionID: string, output: string): any => + { + return this.notifierCallbacks.notify(url, info, sessionID); + }), + new RouteAction("/push/notifier/get/", (url: string, info: any, sessionID: string, output: string): any => + { + return this.notifierCallbacks.getNotifier(url, info, sessionID); + }), + new RouteAction( + "/push/notifier/getwebsocket/", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.notifierCallbacks.getNotifier(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/dynamic/TraderDynamicRouter.ts b/project/src/routers/dynamic/TraderDynamicRouter.ts index f8f821a4..b5c92eed 100644 --- a/project/src/routers/dynamic/TraderDynamicRouter.ts +++ b/project/src/routers/dynamic/TraderDynamicRouter.ts @@ -6,27 +6,23 @@ import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; @injectable() export class TraderDynamicRouter extends DynamicRouter { - constructor( - @inject("TraderCallbacks") protected traderCallbacks: TraderCallbacks, - ) + constructor(@inject("TraderCallbacks") protected traderCallbacks: TraderCallbacks) { - super( - [ - new RouteAction( - "/client/trading/api/getTrader/", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.traderCallbacks.getTrader(url, info, sessionID); - }, - ), - new RouteAction( - "/client/trading/api/getTraderAssort/", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.traderCallbacks.getAssort(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/trading/api/getTrader/", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.traderCallbacks.getTrader(url, info, sessionID); + }, + ), + new RouteAction( + "/client/trading/api/getTraderAssort/", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.traderCallbacks.getAssort(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/item_events/CustomizationItemEventRouter.ts b/project/src/routers/item_events/CustomizationItemEventRouter.ts index b6a6dc1e..f944fed4 100644 --- a/project/src/routers/item_events/CustomizationItemEventRouter.ts +++ b/project/src/routers/item_events/CustomizationItemEventRouter.ts @@ -17,10 +17,7 @@ export class CustomizationItemEventRouter extends ItemEventRouterDefinition public override getHandledRoutes(): HandledRoute[] { - return [ - new HandledRoute("CustomizationWear", false), - new HandledRoute("CustomizationBuy", false), - ]; + return [new HandledRoute("CustomizationWear", false), new HandledRoute("CustomizationBuy", false)]; } public override handleItemEvent( diff --git a/project/src/routers/item_events/HideoutItemEventRouter.ts b/project/src/routers/item_events/HideoutItemEventRouter.ts index b4a6d3f2..4fba95f4 100644 --- a/project/src/routers/item_events/HideoutItemEventRouter.ts +++ b/project/src/routers/item_events/HideoutItemEventRouter.ts @@ -9,9 +9,7 @@ import { HideoutEventActions } from "@spt-aki/models/enums/HideoutEventActions"; @injectable() export class HideoutItemEventRouter extends ItemEventRouterDefinition { - constructor( - @inject("HideoutCallbacks") protected hideoutCallbacks: HideoutCallbacks, - ) + constructor(@inject("HideoutCallbacks") protected hideoutCallbacks: HideoutCallbacks) { super(); } diff --git a/project/src/routers/item_events/InsuranceItemEventRouter.ts b/project/src/routers/item_events/InsuranceItemEventRouter.ts index b2849336..087d8145 100644 --- a/project/src/routers/item_events/InsuranceItemEventRouter.ts +++ b/project/src/routers/item_events/InsuranceItemEventRouter.ts @@ -17,9 +17,7 @@ export class InsuranceItemEventRouter extends ItemEventRouterDefinition public override getHandledRoutes(): HandledRoute[] { - return [ - new HandledRoute("Insure", false), - ]; + return [new HandledRoute("Insure", false)]; } public override handleItemEvent( diff --git a/project/src/routers/item_events/PresetBuildItemEventRouter.ts b/project/src/routers/item_events/PresetBuildItemEventRouter.ts index 07e8ee2f..577464e0 100644 --- a/project/src/routers/item_events/PresetBuildItemEventRouter.ts +++ b/project/src/routers/item_events/PresetBuildItemEventRouter.ts @@ -9,9 +9,7 @@ import { ItemEventActions } from "@spt-aki/models/enums/ItemEventActions"; @injectable() export class PresetBuildItemEventRouter extends ItemEventRouterDefinition { - constructor( - @inject("PresetBuildCallbacks") protected presetBuildCallbacks: PresetBuildCallbacks, - ) + constructor(@inject("PresetBuildCallbacks") protected presetBuildCallbacks: PresetBuildCallbacks) { super(); } diff --git a/project/src/routers/item_events/RagfairItemEventRouter.ts b/project/src/routers/item_events/RagfairItemEventRouter.ts index fb0d0fb8..ae65e463 100644 --- a/project/src/routers/item_events/RagfairItemEventRouter.ts +++ b/project/src/routers/item_events/RagfairItemEventRouter.ts @@ -8,9 +8,7 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve @injectable() export class RagfairItemEventRouter extends ItemEventRouterDefinition { - constructor( - @inject("RagfairCallbacks") protected ragfairCallbacks: RagfairCallbacks, - ) + constructor(@inject("RagfairCallbacks") protected ragfairCallbacks: RagfairCallbacks) { super(); } diff --git a/project/src/routers/item_events/RepairItemEventRouter.ts b/project/src/routers/item_events/RepairItemEventRouter.ts index 608760f7..af906ef2 100644 --- a/project/src/routers/item_events/RepairItemEventRouter.ts +++ b/project/src/routers/item_events/RepairItemEventRouter.ts @@ -8,19 +8,14 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve @injectable() export class RepairItemEventRouter extends ItemEventRouterDefinition { - constructor( - @inject("RepairCallbacks") protected repairCallbacks: RepairCallbacks, - ) + constructor(@inject("RepairCallbacks") protected repairCallbacks: RepairCallbacks) { super(); } public override getHandledRoutes(): HandledRoute[] { - return [ - new HandledRoute("Repair", false), - new HandledRoute("TraderRepair", false), - ]; + return [new HandledRoute("Repair", false), new HandledRoute("TraderRepair", false)]; } public override handleItemEvent( diff --git a/project/src/routers/item_events/TradeItemEventRouter.ts b/project/src/routers/item_events/TradeItemEventRouter.ts index b4db5dc0..c36ba60f 100644 --- a/project/src/routers/item_events/TradeItemEventRouter.ts +++ b/project/src/routers/item_events/TradeItemEventRouter.ts @@ -8,9 +8,7 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve @injectable() export class TradeItemEventRouter extends ItemEventRouterDefinition { - constructor( - @inject("TradeCallbacks") protected tradeCallbacks: TradeCallbacks, - ) + constructor(@inject("TradeCallbacks") protected tradeCallbacks: TradeCallbacks) { super(); } diff --git a/project/src/routers/item_events/WishlistItemEventRouter.ts b/project/src/routers/item_events/WishlistItemEventRouter.ts index b1132edb..dd15eae4 100644 --- a/project/src/routers/item_events/WishlistItemEventRouter.ts +++ b/project/src/routers/item_events/WishlistItemEventRouter.ts @@ -8,19 +8,14 @@ import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEve @injectable() export class WishlistItemEventRouter extends ItemEventRouterDefinition { - constructor( - @inject("WishlistCallbacks") protected wishlistCallbacks: WishlistCallbacks, - ) + constructor(@inject("WishlistCallbacks") protected wishlistCallbacks: WishlistCallbacks) { super(); } public override getHandledRoutes(): HandledRoute[] { - return [ - new HandledRoute("AddToWishList", false), - new HandledRoute("RemoveFromWishList", false), - ]; + return [new HandledRoute("AddToWishList", false), new HandledRoute("RemoveFromWishList", false)]; } public override handleItemEvent( diff --git a/project/src/routers/save_load/HealthSaveLoadRouter.ts b/project/src/routers/save_load/HealthSaveLoadRouter.ts index b41bb39e..343490d2 100644 --- a/project/src/routers/save_load/HealthSaveLoadRouter.ts +++ b/project/src/routers/save_load/HealthSaveLoadRouter.ts @@ -8,19 +8,14 @@ export class HealthSaveLoadRouter extends SaveLoadRouter { public override getHandledRoutes(): HandledRoute[] { - return [ - new HandledRoute("aki-health", false), - ]; + return [new HandledRoute("aki-health", false)]; } public override handleLoad(profile: IAkiProfile): IAkiProfile { if (!profile.vitality) { // Occurs on newly created profiles - profile.vitality = { - health: null, - effects: null, - }; + profile.vitality = {health: null, effects: null}; } profile.vitality.health = { Hydration: 0, diff --git a/project/src/routers/save_load/InraidSaveLoadRouter.ts b/project/src/routers/save_load/InraidSaveLoadRouter.ts index 3f9b6ab7..bea4532f 100644 --- a/project/src/routers/save_load/InraidSaveLoadRouter.ts +++ b/project/src/routers/save_load/InraidSaveLoadRouter.ts @@ -8,19 +8,14 @@ export class InraidSaveLoadRouter extends SaveLoadRouter { public override getHandledRoutes(): HandledRoute[] { - return [ - new HandledRoute("aki-inraid", false), - ]; + return [new HandledRoute("aki-inraid", false)]; } public override handleLoad(profile: IAkiProfile): IAkiProfile { if (profile.inraid === undefined) { - profile.inraid = { - location: "none", - character: "none", - }; + profile.inraid = {location: "none", character: "none"}; } return profile; diff --git a/project/src/routers/save_load/InsuranceSaveLoadRouter.ts b/project/src/routers/save_load/InsuranceSaveLoadRouter.ts index 82264828..433b8a49 100644 --- a/project/src/routers/save_load/InsuranceSaveLoadRouter.ts +++ b/project/src/routers/save_load/InsuranceSaveLoadRouter.ts @@ -8,9 +8,7 @@ export class InsuranceSaveLoadRouter extends SaveLoadRouter { public override getHandledRoutes(): HandledRoute[] { - return [ - new HandledRoute("aki-insurance", false), - ]; + return [new HandledRoute("aki-insurance", false)]; } public override handleLoad(profile: IAkiProfile): IAkiProfile diff --git a/project/src/routers/save_load/ProfileSaveLoadRouter.ts b/project/src/routers/save_load/ProfileSaveLoadRouter.ts index 87348102..bab47117 100644 --- a/project/src/routers/save_load/ProfileSaveLoadRouter.ts +++ b/project/src/routers/save_load/ProfileSaveLoadRouter.ts @@ -9,19 +9,14 @@ export class ProfileSaveLoadRouter extends SaveLoadRouter { public override getHandledRoutes(): HandledRoute[] { - return [ - new HandledRoute("aki-profile", false), - ]; + return [new HandledRoute("aki-profile", false)]; } public override handleLoad(profile: IAkiProfile): IAkiProfile { if (profile.characters === null) { - profile.characters = { - pmc: {} as IPmcData, - scav: {} as IPmcData, - }; + profile.characters = {pmc: {} as IPmcData, scav: {} as IPmcData}; } return profile; } diff --git a/project/src/routers/serializers/ImageSerializer.ts b/project/src/routers/serializers/ImageSerializer.ts index af220c0a..90a0ccec 100644 --- a/project/src/routers/serializers/ImageSerializer.ts +++ b/project/src/routers/serializers/ImageSerializer.ts @@ -7,9 +7,7 @@ import { ImageRouter } from "@spt-aki/routers/ImageRouter"; @injectable() export class ImageSerializer extends Serializer { - constructor( - @inject("ImageRouter") protected imageRouter: ImageRouter, - ) + constructor(@inject("ImageRouter") protected imageRouter: ImageRouter) { super(); } diff --git a/project/src/routers/serializers/NotifySerializer.ts b/project/src/routers/serializers/NotifySerializer.ts index 2cc1975d..5ff48468 100644 --- a/project/src/routers/serializers/NotifySerializer.ts +++ b/project/src/routers/serializers/NotifySerializer.ts @@ -27,9 +27,9 @@ export class NotifySerializer extends Serializer * Take our array of JSON message objects and cast them to JSON strings, so that they can then * be sent to client as NEWLINE separated strings... yup. */ - this.notifierController.notifyAsync(tmpSessionID) - .then((messages: any) => messages.map((message: any) => this.jsonUtil.serialize(message)).join("\n")) - .then((text) => this.httpServerHelper.sendTextJson(resp, text)); + this.notifierController.notifyAsync(tmpSessionID).then((messages: any) => + messages.map((message: any) => this.jsonUtil.serialize(message)).join("\n") + ).then((text) => this.httpServerHelper.sendTextJson(resp, text)); } public override canHandle(route: string): boolean diff --git a/project/src/routers/static/BotStaticRouter.ts b/project/src/routers/static/BotStaticRouter.ts index c4efff6c..4a1968e5 100644 --- a/project/src/routers/static/BotStaticRouter.ts +++ b/project/src/routers/static/BotStaticRouter.ts @@ -6,20 +6,16 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class BotStaticRouter extends StaticRouter { - constructor( - @inject("BotCallbacks") protected botCallbacks: BotCallbacks, - ) + constructor(@inject("BotCallbacks") protected botCallbacks: BotCallbacks) { - super( - [ - new RouteAction( - "/client/game/bot/generate", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.botCallbacks.generateBots(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/game/bot/generate", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.botCallbacks.generateBots(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/BundleStaticRouter.ts b/project/src/routers/static/BundleStaticRouter.ts index b269a36e..a982835c 100644 --- a/project/src/routers/static/BundleStaticRouter.ts +++ b/project/src/routers/static/BundleStaticRouter.ts @@ -6,20 +6,13 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class BundleStaticRouter extends StaticRouter { - constructor( - @inject("BundleCallbacks") protected bundleCallbacks: BundleCallbacks, - ) + constructor(@inject("BundleCallbacks") protected bundleCallbacks: BundleCallbacks) { - super( - [ - new RouteAction( - "/singleplayer/bundles", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.bundleCallbacks.getBundles(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/singleplayer/bundles", (url: string, info: any, sessionID: string, output: string): any => + { + return this.bundleCallbacks.getBundles(url, info, sessionID); + }), + ]); } } diff --git a/project/src/routers/static/ClientLogStaticRouter.ts b/project/src/routers/static/ClientLogStaticRouter.ts index 3844d2f0..4c183531 100644 --- a/project/src/routers/static/ClientLogStaticRouter.ts +++ b/project/src/routers/static/ClientLogStaticRouter.ts @@ -6,20 +6,13 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class ClientLogStaticRouter extends StaticRouter { - constructor( - @inject("ClientLogCallbacks") protected clientLogCallbacks: ClientLogCallbacks, - ) + constructor(@inject("ClientLogCallbacks") protected clientLogCallbacks: ClientLogCallbacks) { - super( - [ - new RouteAction( - "/singleplayer/log", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.clientLogCallbacks.clientLog(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/singleplayer/log", (url: string, info: any, sessionID: string, output: string): any => + { + return this.clientLogCallbacks.clientLog(url, info, sessionID); + }), + ]); } } diff --git a/project/src/routers/static/CustomizationStaticRouter.ts b/project/src/routers/static/CustomizationStaticRouter.ts index 94392ab9..c2fe4b29 100644 --- a/project/src/routers/static/CustomizationStaticRouter.ts +++ b/project/src/routers/static/CustomizationStaticRouter.ts @@ -6,20 +6,16 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class CustomizationStaticRouter extends StaticRouter { - constructor( - @inject("CustomizationCallbacks") protected customizationCallbacks: CustomizationCallbacks, - ) + constructor(@inject("CustomizationCallbacks") protected customizationCallbacks: CustomizationCallbacks) { - super( - [ - new RouteAction( - "/client/trading/customization/storage", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.customizationCallbacks.getSuits(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/trading/customization/storage", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.customizationCallbacks.getSuits(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/DataStaticRouter.ts b/project/src/routers/static/DataStaticRouter.ts index 22360c59..cbb7e7a0 100644 --- a/project/src/routers/static/DataStaticRouter.ts +++ b/project/src/routers/static/DataStaticRouter.ts @@ -6,97 +6,75 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class DataStaticRouter extends StaticRouter { - constructor( - @inject("DataCallbacks") protected dataCallbacks: DataCallbacks, - ) + constructor(@inject("DataCallbacks") protected dataCallbacks: DataCallbacks) { - super( - [ - new RouteAction( - "/client/settings", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getSettings(url, info, sessionID); - }, - ), - new RouteAction( - "/client/globals", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getGlobals(url, info, sessionID); - }, - ), - new RouteAction( - "/client/items", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getTemplateItems(url, info, sessionID); - }, - ), - new RouteAction( - "/client/handbook/templates", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getTemplateHandbook(url, info, sessionID); - }, - ), - new RouteAction( - "/client/customization", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getTemplateSuits(url, info, sessionID); - }, - ), - new RouteAction( - "/client/account/customization", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getTemplateCharacter(url, info, sessionID); - }, - ), - new RouteAction( - "/client/hideout/production/recipes", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.gethideoutProduction(url, info, sessionID); - }, - ), - new RouteAction( - "/client/hideout/settings", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getHideoutSettings(url, info, sessionID); - }, - ), - new RouteAction( - "/client/hideout/areas", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getHideoutAreas(url, info, sessionID); - }, - ), - new RouteAction( - "/client/hideout/production/scavcase/recipes", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getHideoutScavcase(url, info, sessionID); - }, - ), - new RouteAction( - "/client/languages", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getLocalesLanguages(url, info, sessionID); - }, - ), - new RouteAction( - "/client/hideout/qte/list", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dataCallbacks.getQteList(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/client/settings", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getSettings(url, info, sessionID); + }), + new RouteAction("/client/globals", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getGlobals(url, info, sessionID); + }), + new RouteAction("/client/items", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getTemplateItems(url, info, sessionID); + }), + new RouteAction( + "/client/handbook/templates", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getTemplateHandbook(url, info, sessionID); + }, + ), + new RouteAction("/client/customization", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getTemplateSuits(url, info, sessionID); + }), + new RouteAction( + "/client/account/customization", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getTemplateCharacter(url, info, sessionID); + }, + ), + new RouteAction( + "/client/hideout/production/recipes", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.gethideoutProduction(url, info, sessionID); + }, + ), + new RouteAction( + "/client/hideout/settings", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getHideoutSettings(url, info, sessionID); + }, + ), + new RouteAction("/client/hideout/areas", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getHideoutAreas(url, info, sessionID); + }), + new RouteAction( + "/client/hideout/production/scavcase/recipes", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getHideoutScavcase(url, info, sessionID); + }, + ), + new RouteAction("/client/languages", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getLocalesLanguages(url, info, sessionID); + }), + new RouteAction( + "/client/hideout/qte/list", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dataCallbacks.getQteList(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/DialogStaticRouter.ts b/project/src/routers/static/DialogStaticRouter.ts index 2bee28c2..a22acc6d 100644 --- a/project/src/routers/static/DialogStaticRouter.ts +++ b/project/src/routers/static/DialogStaticRouter.ts @@ -6,160 +6,147 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class DialogStaticRouter extends StaticRouter { - constructor( - @inject("DialogueCallbacks") protected dialogueCallbacks: DialogueCallbacks, - ) + constructor(@inject("DialogueCallbacks") protected dialogueCallbacks: DialogueCallbacks) { - super( - [ - new RouteAction( - "/client/chatServer/list", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.getChatServerList(url, info, sessionID); - }, - ), - new RouteAction( - "/client/mail/dialog/list", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.getMailDialogList(url, info, sessionID); - }, - ), - new RouteAction( - "/client/mail/dialog/view", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.getMailDialogView(url, info, sessionID); - }, - ), - new RouteAction( - "/client/mail/dialog/info", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.getMailDialogInfo(url, info, sessionID); - }, - ), - new RouteAction( - "/client/mail/dialog/remove", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.removeDialog(url, info, sessionID); - }, - ), - new RouteAction( - "/client/mail/dialog/pin", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.pinDialog(url, info, sessionID); - }, - ), - new RouteAction( - "/client/mail/dialog/unpin", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.unpinDialog(url, info, sessionID); - }, - ), - new RouteAction( - "/client/mail/dialog/read", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.setRead(url, info, sessionID); - }, - ), - new RouteAction( - "/client/mail/dialog/remove", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.removeMail(url, info, sessionID); - }, - ), - new RouteAction( - "/client/mail/dialog/getAllAttachments", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.getAllAttachments(url, info, sessionID); - }, - ), - new RouteAction( - "/client/mail/msg/send", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.sendMessage(url, info, sessionID); - }, - ), - new RouteAction( - "/client/mail/dialog/clear", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.clearMail(url, info, sessionID); - }, - ), - new RouteAction( - "/client/friend/list", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.getFriendList(url, info, sessionID); - }, - ), - new RouteAction( - "/client/friend/request/list/outbox", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.listOutbox(url, info, sessionID); - }, - ), - new RouteAction( - "/client/friend/request/list/inbox", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.listInbox(url, info, sessionID); - }, - ), - new RouteAction( - "/client/friend/request/send", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.sendFriendRequest(url, info, sessionID); - }, - ), - new RouteAction( - "/client/friend/request/accept", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.acceptFriendRequest(url, info, sessionID); - }, - ), - new RouteAction( - "/client/friend/request/cancel", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.cancelFriendRequest(url, info, sessionID); - }, - ), - new RouteAction( - "/client/friend/delete", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.deleteFriend(url, info, sessionID); - }, - ), - new RouteAction( - "/client/friend/ignore/set", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.ignoreFriend(url, info, sessionID); - }, - ), - new RouteAction( - "/client/friend/ignore/remove", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.dialogueCallbacks.unIgnoreFriend(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/chatServer/list", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.getChatServerList(url, info, sessionID); + }, + ), + new RouteAction( + "/client/mail/dialog/list", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.getMailDialogList(url, info, sessionID); + }, + ), + new RouteAction( + "/client/mail/dialog/view", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.getMailDialogView(url, info, sessionID); + }, + ), + new RouteAction( + "/client/mail/dialog/info", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.getMailDialogInfo(url, info, sessionID); + }, + ), + new RouteAction( + "/client/mail/dialog/remove", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.removeDialog(url, info, sessionID); + }, + ), + new RouteAction( + "/client/mail/dialog/pin", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.pinDialog(url, info, sessionID); + }, + ), + new RouteAction( + "/client/mail/dialog/unpin", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.unpinDialog(url, info, sessionID); + }, + ), + new RouteAction( + "/client/mail/dialog/read", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.setRead(url, info, sessionID); + }, + ), + new RouteAction( + "/client/mail/dialog/remove", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.removeMail(url, info, sessionID); + }, + ), + new RouteAction( + "/client/mail/dialog/getAllAttachments", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.getAllAttachments(url, info, sessionID); + }, + ), + new RouteAction("/client/mail/msg/send", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.sendMessage(url, info, sessionID); + }), + new RouteAction( + "/client/mail/dialog/clear", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.clearMail(url, info, sessionID); + }, + ), + new RouteAction("/client/friend/list", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.getFriendList(url, info, sessionID); + }), + new RouteAction( + "/client/friend/request/list/outbox", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.listOutbox(url, info, sessionID); + }, + ), + new RouteAction( + "/client/friend/request/list/inbox", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.listInbox(url, info, sessionID); + }, + ), + new RouteAction( + "/client/friend/request/send", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.sendFriendRequest(url, info, sessionID); + }, + ), + new RouteAction( + "/client/friend/request/accept", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.acceptFriendRequest(url, info, sessionID); + }, + ), + new RouteAction( + "/client/friend/request/cancel", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.cancelFriendRequest(url, info, sessionID); + }, + ), + new RouteAction("/client/friend/delete", (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.deleteFriend(url, info, sessionID); + }), + new RouteAction( + "/client/friend/ignore/set", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.ignoreFriend(url, info, sessionID); + }, + ), + new RouteAction( + "/client/friend/ignore/remove", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.dialogueCallbacks.unIgnoreFriend(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/GameStaticRouter.ts b/project/src/routers/static/GameStaticRouter.ts index 34d5fe4e..04c89a6c 100644 --- a/project/src/routers/static/GameStaticRouter.ts +++ b/project/src/routers/static/GameStaticRouter.ts @@ -6,83 +6,64 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class GameStaticRouter extends StaticRouter { - constructor( - @inject("GameCallbacks") protected gameCallbacks: GameCallbacks, - ) + constructor(@inject("GameCallbacks") protected gameCallbacks: GameCallbacks) { - super( - [ - new RouteAction( - "/client/game/config", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.gameCallbacks.getGameConfig(url, info, sessionID); - }, - ), - new RouteAction( - "/client/server/list", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.gameCallbacks.getServer(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/current", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.gameCallbacks.getCurrentGroup(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/version/validate", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.gameCallbacks.versionValidate(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/start", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.gameCallbacks.gameStart(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/logout", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.gameCallbacks.gameLogout(url, info, sessionID); - }, - ), - new RouteAction( - "/client/checkVersion", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.gameCallbacks.validateGameVersion(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/keepalive", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.gameCallbacks.gameKeepalive(url, info, sessionID); - }, - ), - new RouteAction( - "/singleplayer/settings/version", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.gameCallbacks.getVersion(url, info, sessionID); - }, - ), - new RouteAction( - "/client/reports/lobby/send", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.gameCallbacks.reportNickname(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/client/game/config", (url: string, info: any, sessionID: string, output: string): any => + { + return this.gameCallbacks.getGameConfig(url, info, sessionID); + }), + new RouteAction("/client/server/list", (url: string, info: any, sessionID: string, output: string): any => + { + return this.gameCallbacks.getServer(url, info, sessionID); + }), + new RouteAction( + "/client/match/group/current", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.gameCallbacks.getCurrentGroup(url, info, sessionID); + }, + ), + new RouteAction( + "/client/game/version/validate", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.gameCallbacks.versionValidate(url, info, sessionID); + }, + ), + new RouteAction("/client/game/start", (url: string, info: any, sessionID: string, output: string): any => + { + return this.gameCallbacks.gameStart(url, info, sessionID); + }), + new RouteAction("/client/game/logout", (url: string, info: any, sessionID: string, output: string): any => + { + return this.gameCallbacks.gameLogout(url, info, sessionID); + }), + new RouteAction("/client/checkVersion", (url: string, info: any, sessionID: string, output: string): any => + { + return this.gameCallbacks.validateGameVersion(url, info, sessionID); + }), + new RouteAction( + "/client/game/keepalive", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.gameCallbacks.gameKeepalive(url, info, sessionID); + }, + ), + new RouteAction( + "/singleplayer/settings/version", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.gameCallbacks.getVersion(url, info, sessionID); + }, + ), + new RouteAction( + "/client/reports/lobby/send", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.gameCallbacks.reportNickname(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/HealthStaticRouter.ts b/project/src/routers/static/HealthStaticRouter.ts index 9f4aa243..f20da993 100644 --- a/project/src/routers/static/HealthStaticRouter.ts +++ b/project/src/routers/static/HealthStaticRouter.ts @@ -6,27 +6,20 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class HealthStaticRouter extends StaticRouter { - constructor( - @inject("HealthCallbacks") protected healthCallbacks: HealthCallbacks, - ) + constructor(@inject("HealthCallbacks") protected healthCallbacks: HealthCallbacks) { - super( - [ - new RouteAction( - "/player/health/sync", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.healthCallbacks.syncHealth(url, info, sessionID); - }, - ), - new RouteAction( - "/client/hideout/workout", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.healthCallbacks.handleWorkoutEffects(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/player/health/sync", (url: string, info: any, sessionID: string, output: string): any => + { + return this.healthCallbacks.syncHealth(url, info, sessionID); + }), + new RouteAction( + "/client/hideout/workout", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.healthCallbacks.handleWorkoutEffects(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/InraidStaticRouter.ts b/project/src/routers/static/InraidStaticRouter.ts index a3e958ae..3d3eda8d 100644 --- a/project/src/routers/static/InraidStaticRouter.ts +++ b/project/src/routers/static/InraidStaticRouter.ts @@ -6,48 +6,41 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class InraidStaticRouter extends StaticRouter { - constructor( - @inject("InraidCallbacks") protected inraidCallbacks: InraidCallbacks, - ) + constructor(@inject("InraidCallbacks") protected inraidCallbacks: InraidCallbacks) { - super( - [ - new RouteAction( - "/raid/profile/save", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.inraidCallbacks.saveProgress(url, info, sessionID); - }, - ), - new RouteAction( - "/singleplayer/settings/raid/endstate", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.inraidCallbacks.getRaidEndState(); - }, - ), - new RouteAction( - "/singleplayer/settings/weapon/durability", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.inraidCallbacks.getWeaponDurability(); - }, - ), - new RouteAction( - "/singleplayer/settings/raid/menu", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.inraidCallbacks.getRaidMenuSettings(); - }, - ), - new RouteAction( - "/singleplayer/airdrop/config", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.inraidCallbacks.getAirdropConfig(); - }, - ), - ], - ); + super([ + new RouteAction("/raid/profile/save", (url: string, info: any, sessionID: string, output: string): any => + { + return this.inraidCallbacks.saveProgress(url, info, sessionID); + }), + new RouteAction( + "/singleplayer/settings/raid/endstate", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.inraidCallbacks.getRaidEndState(); + }, + ), + new RouteAction( + "/singleplayer/settings/weapon/durability", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.inraidCallbacks.getWeaponDurability(); + }, + ), + new RouteAction( + "/singleplayer/settings/raid/menu", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.inraidCallbacks.getRaidMenuSettings(); + }, + ), + new RouteAction( + "/singleplayer/airdrop/config", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.inraidCallbacks.getAirdropConfig(); + }, + ), + ]); } } diff --git a/project/src/routers/static/InsuranceStaticRouter.ts b/project/src/routers/static/InsuranceStaticRouter.ts index 08d879ed..dcb333ea 100644 --- a/project/src/routers/static/InsuranceStaticRouter.ts +++ b/project/src/routers/static/InsuranceStaticRouter.ts @@ -6,20 +6,16 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class InsuranceStaticRouter extends StaticRouter { - constructor( - @inject("InsuranceCallbacks") protected insuranceCallbacks: InsuranceCallbacks, - ) + constructor(@inject("InsuranceCallbacks") protected insuranceCallbacks: InsuranceCallbacks) { - super( - [ - new RouteAction( - "/client/insurance/items/list/cost", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.insuranceCallbacks.getInsuranceCost(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/insurance/items/list/cost", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.insuranceCallbacks.getInsuranceCost(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/ItemEventStaticRouter.ts b/project/src/routers/static/ItemEventStaticRouter.ts index 793494da..54d668f2 100644 --- a/project/src/routers/static/ItemEventStaticRouter.ts +++ b/project/src/routers/static/ItemEventStaticRouter.ts @@ -6,20 +6,16 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class ItemEventStaticRouter extends StaticRouter { - constructor( - @inject("ItemEventCallbacks") protected itemEventCallbacks: ItemEventCallbacks, - ) + constructor(@inject("ItemEventCallbacks") protected itemEventCallbacks: ItemEventCallbacks) { - super( - [ - new RouteAction( - "/client/game/profile/items/moving", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.itemEventCallbacks.handleEvents(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/game/profile/items/moving", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.itemEventCallbacks.handleEvents(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/LauncherStaticRouter.ts b/project/src/routers/static/LauncherStaticRouter.ts index 7ecd65dd..0cdae88c 100644 --- a/project/src/routers/static/LauncherStaticRouter.ts +++ b/project/src/routers/static/LauncherStaticRouter.ts @@ -6,104 +6,94 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class LauncherStaticRouter extends StaticRouter { - constructor( - @inject("LauncherCallbacks") protected launcherCallbacks: LauncherCallbacks, - ) + constructor(@inject("LauncherCallbacks") protected launcherCallbacks: LauncherCallbacks) { - super( - [ - new RouteAction( - "/launcher/ping", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.ping(url, info, sessionID); - }, - ), - new RouteAction( - "/launcher/server/connect", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.connect(); - }, - ), - new RouteAction( - "/launcher/profile/login", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.login(url, info, sessionID); - }, - ), - new RouteAction( - "/launcher/profile/register", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.register(url, info, sessionID); - }, - ), - new RouteAction( - "/launcher/profile/get", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.get(url, info, sessionID); - }, - ), - new RouteAction( - "/launcher/profile/change/username", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.changeUsername(url, info, sessionID); - }, - ), - new RouteAction( - "/launcher/profile/change/password", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.changePassword(url, info, sessionID); - }, - ), - new RouteAction( - "/launcher/profile/change/wipe", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.wipe(url, info, sessionID); - }, - ), - new RouteAction( - "/launcher/profile/remove", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.removeProfile(url, info, sessionID); - }, - ), - new RouteAction( - "/launcher/profile/compatibleTarkovVersion", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.getCompatibleTarkovVersion(); - }, - ), - new RouteAction( - "/launcher/server/version", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.getServerVersion(); - }, - ), - new RouteAction( - "/launcher/server/loadedServerMods", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.getLoadedServerMods(); - }, - ), - new RouteAction( - "/launcher/server/serverModsUsedByProfile", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.launcherCallbacks.getServerModsProfileUsed(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/launcher/ping", (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.ping(url, info, sessionID); + }), + new RouteAction( + "/launcher/server/connect", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.connect(); + }, + ), + new RouteAction( + "/launcher/profile/login", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.login(url, info, sessionID); + }, + ), + new RouteAction( + "/launcher/profile/register", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.register(url, info, sessionID); + }, + ), + new RouteAction("/launcher/profile/get", (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.get(url, info, sessionID); + }), + new RouteAction( + "/launcher/profile/change/username", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.changeUsername(url, info, sessionID); + }, + ), + new RouteAction( + "/launcher/profile/change/password", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.changePassword(url, info, sessionID); + }, + ), + new RouteAction( + "/launcher/profile/change/wipe", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.wipe(url, info, sessionID); + }, + ), + new RouteAction( + "/launcher/profile/remove", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.removeProfile(url, info, sessionID); + }, + ), + new RouteAction( + "/launcher/profile/compatibleTarkovVersion", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.getCompatibleTarkovVersion(); + }, + ), + new RouteAction( + "/launcher/server/version", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.getServerVersion(); + }, + ), + new RouteAction( + "/launcher/server/loadedServerMods", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.getLoadedServerMods(); + }, + ), + new RouteAction( + "/launcher/server/serverModsUsedByProfile", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.launcherCallbacks.getServerModsProfileUsed(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/LocationStaticRouter.ts b/project/src/routers/static/LocationStaticRouter.ts index ccfb93a0..a2bff938 100644 --- a/project/src/routers/static/LocationStaticRouter.ts +++ b/project/src/routers/static/LocationStaticRouter.ts @@ -6,27 +6,20 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class LocationStaticRouter extends StaticRouter { - constructor( - @inject("LocationCallbacks") protected locationCallbacks: LocationCallbacks, - ) + constructor(@inject("LocationCallbacks") protected locationCallbacks: LocationCallbacks) { - super( - [ - new RouteAction( - "/client/locations", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.locationCallbacks.getLocationData(url, info, sessionID); - }, - ), - new RouteAction( - "/client/location/getAirdropLoot", - (url: string, info: any, sessionID: string, _output: string): any => - { - return this.locationCallbacks.getAirdropLoot(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/client/locations", (url: string, info: any, sessionID: string, output: string): any => + { + return this.locationCallbacks.getLocationData(url, info, sessionID); + }), + new RouteAction( + "/client/location/getAirdropLoot", + (url: string, info: any, sessionID: string, _output: string): any => + { + return this.locationCallbacks.getAirdropLoot(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/MatchStaticRouter.ts b/project/src/routers/static/MatchStaticRouter.ts index 74c81455..22ce8bb3 100644 --- a/project/src/routers/static/MatchStaticRouter.ts +++ b/project/src/routers/static/MatchStaticRouter.ts @@ -6,174 +6,158 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class MatchStaticRouter extends StaticRouter { - constructor( - @inject("MatchCallbacks") protected matchCallbacks: MatchCallbacks, - ) + constructor(@inject("MatchCallbacks") protected matchCallbacks: MatchCallbacks) { - super( - [ - new RouteAction( - "/raid/profile/list", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.getProfile(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/available", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.serverAvailable(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/updatePing", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.updatePing(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/join", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.joinMatch(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/exit", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.exitMatch(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/create", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.createGroup(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/delete", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.deleteGroup(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/leave", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.leaveGroup(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/status", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.getGroupStatus(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/start_game", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.joinMatch(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/exit_from_menu", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.exitToMenu(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/looking/start", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.startGroupSearch(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/looking/stop", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.stopGroupSearch(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/invite/send", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.sendGroupInvite(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/invite/accept", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.acceptGroupInvite(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/invite/cancel", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.cancelGroupInvite(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/invite/cancel-all", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.cancelAllGroupInvite(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/transfer", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.transferGroup(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/offline/end", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.endOfflineRaid(url, info, sessionID); - }, - ), - new RouteAction( - "/client/putMetrics", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.putMetrics(url, info, sessionID); - }, - ), - new RouteAction( - "/client/getMetricsConfig", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.getMetrics(url, info, sessionID); - }, - ), - new RouteAction( - "/client/raid/configuration", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.getRaidConfiguration(url, info, sessionID); - }, - ), - new RouteAction( - "/client/match/group/player/remove", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.matchCallbacks.removePlayerFromGroup(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/raid/profile/list", (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.getProfile(url, info, sessionID); + }), + new RouteAction( + "/client/match/available", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.serverAvailable(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/updatePing", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.updatePing(url, info, sessionID); + }, + ), + new RouteAction("/client/match/join", (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.joinMatch(url, info, sessionID); + }), + new RouteAction("/client/match/exit", (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.exitMatch(url, info, sessionID); + }), + new RouteAction( + "/client/match/group/create", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.createGroup(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/delete", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.deleteGroup(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/leave", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.leaveGroup(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/status", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.getGroupStatus(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/start_game", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.joinMatch(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/exit_from_menu", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.exitToMenu(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/looking/start", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.startGroupSearch(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/looking/stop", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.stopGroupSearch(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/invite/send", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.sendGroupInvite(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/invite/accept", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.acceptGroupInvite(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/invite/cancel", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.cancelGroupInvite(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/invite/cancel-all", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.cancelAllGroupInvite(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/transfer", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.transferGroup(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/offline/end", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.endOfflineRaid(url, info, sessionID); + }, + ), + new RouteAction("/client/putMetrics", (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.putMetrics(url, info, sessionID); + }), + new RouteAction( + "/client/getMetricsConfig", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.getMetrics(url, info, sessionID); + }, + ), + new RouteAction( + "/client/raid/configuration", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.getRaidConfiguration(url, info, sessionID); + }, + ), + new RouteAction( + "/client/match/group/player/remove", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.matchCallbacks.removePlayerFromGroup(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/NotifierStaticRouter.ts b/project/src/routers/static/NotifierStaticRouter.ts index 56b34ce2..19cfbd08 100644 --- a/project/src/routers/static/NotifierStaticRouter.ts +++ b/project/src/routers/static/NotifierStaticRouter.ts @@ -6,27 +6,23 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class NotifierStaticRouter extends StaticRouter { - constructor( - @inject("NotifierCallbacks") protected notifierCallbacks: NotifierCallbacks, - ) + constructor(@inject("NotifierCallbacks") protected notifierCallbacks: NotifierCallbacks) { - super( - [ - new RouteAction( - "/client/notifier/channel/create", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.notifierCallbacks.createNotifierChannel(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/profile/select", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.notifierCallbacks.selectProfile(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/notifier/channel/create", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.notifierCallbacks.createNotifierChannel(url, info, sessionID); + }, + ), + new RouteAction( + "/client/game/profile/select", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.notifierCallbacks.selectProfile(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/PresetStaticRouter.ts b/project/src/routers/static/PresetStaticRouter.ts index c08482ff..08d84521 100644 --- a/project/src/routers/static/PresetStaticRouter.ts +++ b/project/src/routers/static/PresetStaticRouter.ts @@ -6,20 +6,16 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class PresetStaticRouter extends StaticRouter { - constructor( - @inject("PresetBuildCallbacks") protected presetCallbacks: PresetBuildCallbacks, - ) + constructor(@inject("PresetBuildCallbacks") protected presetCallbacks: PresetBuildCallbacks) { - super( - [ - new RouteAction( - "/client/handbook/builds/my/list", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.presetCallbacks.getHandbookUserlist(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/handbook/builds/my/list", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.presetCallbacks.getHandbookUserlist(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/ProfileStaticRouter.ts b/project/src/routers/static/ProfileStaticRouter.ts index 147a066e..4ab84e5f 100644 --- a/project/src/routers/static/ProfileStaticRouter.ts +++ b/project/src/routers/static/ProfileStaticRouter.ts @@ -6,97 +6,90 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class ProfileStaticRouter extends StaticRouter { - constructor( - @inject("ProfileCallbacks") protected profileCallbacks: ProfileCallbacks, - ) + constructor(@inject("ProfileCallbacks") protected profileCallbacks: ProfileCallbacks) { - super( - [ - new RouteAction( - "/client/game/profile/create", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.createProfile(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/profile/list", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.getProfileData(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/profile/savage/regenerate", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.regenerateScav(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/profile/voice/change", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.changeVoice(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/profile/nickname/change", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.changeNickname(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/profile/nickname/validate", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.validateNickname(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/profile/nickname/reserved", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.getReservedNickname(url, info, sessionID); - }, - ), - new RouteAction( - "/client/profile/status", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.getProfileStatus(url, info, sessionID); - }, - ), - new RouteAction( - "/client/profile/settings", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.getProfileSettings(url, info, sessionID); - }, - ), - new RouteAction( - "/client/game/profile/search", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.searchFriend(url, info, sessionID); - }, - ), - new RouteAction( - "/launcher/profile/info", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.getMiniProfile(url, info, sessionID); - }, - ), - new RouteAction( - "/launcher/profiles", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.profileCallbacks.getAllMiniProfiles(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/game/profile/create", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.createProfile(url, info, sessionID); + }, + ), + new RouteAction( + "/client/game/profile/list", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.getProfileData(url, info, sessionID); + }, + ), + new RouteAction( + "/client/game/profile/savage/regenerate", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.regenerateScav(url, info, sessionID); + }, + ), + new RouteAction( + "/client/game/profile/voice/change", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.changeVoice(url, info, sessionID); + }, + ), + new RouteAction( + "/client/game/profile/nickname/change", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.changeNickname(url, info, sessionID); + }, + ), + new RouteAction( + "/client/game/profile/nickname/validate", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.validateNickname(url, info, sessionID); + }, + ), + new RouteAction( + "/client/game/profile/nickname/reserved", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.getReservedNickname(url, info, sessionID); + }, + ), + new RouteAction( + "/client/profile/status", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.getProfileStatus(url, info, sessionID); + }, + ), + new RouteAction( + "/client/profile/settings", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.getProfileSettings(url, info, sessionID); + }, + ), + new RouteAction( + "/client/game/profile/search", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.searchFriend(url, info, sessionID); + }, + ), + new RouteAction( + "/launcher/profile/info", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.getMiniProfile(url, info, sessionID); + }, + ), + new RouteAction("/launcher/profiles", (url: string, info: any, sessionID: string, output: string): any => + { + return this.profileCallbacks.getAllMiniProfiles(url, info, sessionID); + }), + ]); } } diff --git a/project/src/routers/static/QuestStaticRouter.ts b/project/src/routers/static/QuestStaticRouter.ts index d0ac6f12..e56f51ac 100644 --- a/project/src/routers/static/QuestStaticRouter.ts +++ b/project/src/routers/static/QuestStaticRouter.ts @@ -6,27 +6,20 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class QuestStaticRouter extends StaticRouter { - constructor( - @inject("QuestCallbacks") protected questCallbacks: QuestCallbacks, - ) + constructor(@inject("QuestCallbacks") protected questCallbacks: QuestCallbacks) { - super( - [ - new RouteAction( - "/client/quest/list", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.questCallbacks.listQuests(url, info, sessionID); - }, - ), - new RouteAction( - "/client/repeatalbeQuests/activityPeriods", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.questCallbacks.activityPeriods(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/client/quest/list", (url: string, info: any, sessionID: string, output: string): any => + { + return this.questCallbacks.listQuests(url, info, sessionID); + }), + new RouteAction( + "/client/repeatalbeQuests/activityPeriods", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.questCallbacks.activityPeriods(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/RagfairStaticRouter.ts b/project/src/routers/static/RagfairStaticRouter.ts index 06461d4f..376b8c6d 100644 --- a/project/src/routers/static/RagfairStaticRouter.ts +++ b/project/src/routers/static/RagfairStaticRouter.ts @@ -6,55 +6,45 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class RagfairStaticRouter extends StaticRouter { - constructor( - @inject("RagfairCallbacks") protected ragfairCallbacks: RagfairCallbacks, - ) + constructor(@inject("RagfairCallbacks") protected ragfairCallbacks: RagfairCallbacks) { - super( - [ - new RouteAction( - "/client/ragfair/search", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.ragfairCallbacks.search(url, info, sessionID); - }, - ), - new RouteAction( - "/client/ragfair/find", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.ragfairCallbacks.search(url, info, sessionID); - }, - ), - new RouteAction( - "/client/ragfair/itemMarketPrice", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.ragfairCallbacks.getMarketPrice(url, info, sessionID); - }, - ), - new RouteAction( - "/client/ragfair/offerfees", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.ragfairCallbacks.storePlayerOfferTaxAmount(url, info, sessionID); - }, - ), - new RouteAction( - "/client/reports/ragfair/send", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.ragfairCallbacks.sendReport(url, info, sessionID); - }, - ), - new RouteAction( - "/client/items/prices", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.ragfairCallbacks.getFleaPrices(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/ragfair/search", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.ragfairCallbacks.search(url, info, sessionID); + }, + ), + new RouteAction("/client/ragfair/find", (url: string, info: any, sessionID: string, output: string): any => + { + return this.ragfairCallbacks.search(url, info, sessionID); + }), + new RouteAction( + "/client/ragfair/itemMarketPrice", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.ragfairCallbacks.getMarketPrice(url, info, sessionID); + }, + ), + new RouteAction( + "/client/ragfair/offerfees", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.ragfairCallbacks.storePlayerOfferTaxAmount(url, info, sessionID); + }, + ), + new RouteAction( + "/client/reports/ragfair/send", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.ragfairCallbacks.sendReport(url, info, sessionID); + }, + ), + new RouteAction("/client/items/prices", (url: string, info: any, sessionID: string, output: string): any => + { + return this.ragfairCallbacks.getFleaPrices(url, info, sessionID); + }), + ]); } } diff --git a/project/src/routers/static/TraderStaticRouter.ts b/project/src/routers/static/TraderStaticRouter.ts index 12ac0359..2903f9be 100644 --- a/project/src/routers/static/TraderStaticRouter.ts +++ b/project/src/routers/static/TraderStaticRouter.ts @@ -6,20 +6,16 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class TraderStaticRouter extends StaticRouter { - constructor( - @inject("TraderCallbacks") protected traderCallbacks: TraderCallbacks, - ) + constructor(@inject("TraderCallbacks") protected traderCallbacks: TraderCallbacks) { - super( - [ - new RouteAction( - "/client/trading/api/traderSettings", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.traderCallbacks.getTraderSettings(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction( + "/client/trading/api/traderSettings", + (url: string, info: any, sessionID: string, output: string): any => + { + return this.traderCallbacks.getTraderSettings(url, info, sessionID); + }, + ), + ]); } } diff --git a/project/src/routers/static/WeatherStaticRouter.ts b/project/src/routers/static/WeatherStaticRouter.ts index df013520..28504cc1 100644 --- a/project/src/routers/static/WeatherStaticRouter.ts +++ b/project/src/routers/static/WeatherStaticRouter.ts @@ -6,20 +6,13 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; @injectable() export class WeatherStaticRouter extends StaticRouter { - constructor( - @inject("WeatherCallbacks") protected weatherCallbacks: WeatherCallbacks, - ) + constructor(@inject("WeatherCallbacks") protected weatherCallbacks: WeatherCallbacks) { - super( - [ - new RouteAction( - "/client/weather", - (url: string, info: any, sessionID: string, output: string): any => - { - return this.weatherCallbacks.getWeather(url, info, sessionID); - }, - ), - ], - ); + super([ + new RouteAction("/client/weather", (url: string, info: any, sessionID: string, output: string): any => + { + return this.weatherCallbacks.getWeather(url, info, sessionID); + }), + ]); } } diff --git a/project/src/servers/ConfigServer.ts b/project/src/servers/ConfigServer.ts index d6128e37..85c4cb6f 100644 --- a/project/src/servers/ConfigServer.ts +++ b/project/src/servers/ConfigServer.ts @@ -36,9 +36,7 @@ export class ConfigServer this.logger.debug("Importing configs..."); // Get all filepaths - const filepath = (globalThis.G_RELEASE_CONFIGURATION) - ? "Aki_Data/Server/configs/" - : "./assets/configs/"; + const filepath = (globalThis.G_RELEASE_CONFIGURATION) ? "Aki_Data/Server/configs/" : "./assets/configs/"; const files = this.vfs.getFiles(filepath); // Add file content to result diff --git a/project/src/servers/SaveServer.ts b/project/src/servers/SaveServer.ts index 8105ab79..5599b361 100644 --- a/project/src/servers/SaveServer.ts +++ b/project/src/servers/SaveServer.ts @@ -142,10 +142,7 @@ export class SaveServer throw new Error(`profile already exists for sessionId: ${profileInfo.id}`); } - this.profiles[profileInfo.id] = { - info: profileInfo, - characters: {pmc: {}, scav: {}}, - }; + this.profiles[profileInfo.id] = {info: profileInfo, characters: {pmc: {}, scav: {}}}; } /** diff --git a/project/src/servers/WebSocketServer.ts b/project/src/servers/WebSocketServer.ts index aece4db8..fcf3ea16 100644 --- a/project/src/servers/WebSocketServer.ts +++ b/project/src/servers/WebSocketServer.ts @@ -28,19 +28,14 @@ export class WebSocketServer } protected httpConfig: IHttpConfig; - protected defaultNotification: INotification = { - type: NotificationType.PING, - eventId: "ping", - }; + protected defaultNotification: INotification = {type: NotificationType.PING, eventId: "ping"}; protected webSockets: Record = {}; protected websocketPingHandler = null; public setupWebSocket(httpServer: http.Server): void { - const webSocketServer = new WebSocket.Server({ - server: httpServer, - }); + const webSocketServer = new WebSocket.Server({server: httpServer}); webSocketServer.addListener("listening", () => { diff --git a/project/src/servers/http/AkiHttpListener.ts b/project/src/servers/http/AkiHttpListener.ts index 77f48918..bc74db94 100644 --- a/project/src/servers/http/AkiHttpListener.ts +++ b/project/src/servers/http/AkiHttpListener.ts @@ -141,9 +141,7 @@ export class AkiHttpListener implements IHttpListener if (globalThis.G_LOG_REQUESTS) { // Parse quest info into object - const data = (typeof info === "object") - ? info - : this.jsonUtil.deserialize(info); + const data = (typeof info === "object") ? info : this.jsonUtil.deserialize(info); const log = new Request(req.method, new RequestData(req.url, req.headers, data)); this.requestsLogger.info(`REQUEST=${this.jsonUtil.serialize(log)}`); @@ -184,28 +182,18 @@ export class AkiHttpListener implements IHttpListener class RequestData { - constructor( - public url: string, - public headers: IncomingHttpHeaders, - public data?: any, - ) + constructor(public url: string, public headers: IncomingHttpHeaders, public data?: any) {} } class Request { - constructor( - public type: string, - public req: RequestData, - ) + constructor(public type: string, public req: RequestData) {} } class Response { - constructor( - public type: string, - public response: any, - ) + constructor(public type: string, public response: any) {} } diff --git a/project/src/services/BotEquipmentFilterService.ts b/project/src/services/BotEquipmentFilterService.ts index c9d99111..5c67c0d8 100644 --- a/project/src/services/BotEquipmentFilterService.ts +++ b/project/src/services/BotEquipmentFilterService.ts @@ -54,9 +54,7 @@ export class BotEquipmentFilterService { const pmcProfile = this.profileHelper.getPmcProfile(sessionId); - const botRole = (botGenerationDetails.isPmc) - ? "pmc" - : botGenerationDetails.role; + const botRole = (botGenerationDetails.isPmc) ? "pmc" : botGenerationDetails.role; const botEquipmentBlacklist = this.getBotEquipmentBlacklist(botRole, botLevel); const botEquipmentWhitelist = this.getBotEquipmentWhitelist(botRole, botLevel); const botWeightingAdjustments = this.getBotWeightingAdjustments(botRole, botLevel); diff --git a/project/src/services/BotLootCacheService.ts b/project/src/services/BotLootCacheService.ts index 76828d14..f24ba9ff 100644 --- a/project/src/services/BotLootCacheService.ts +++ b/project/src/services/BotLootCacheService.ts @@ -168,8 +168,7 @@ export class BotLootCacheService const specialLootItems = (botJsonTemplate.generation.items.specialItems.whitelist?.length > 0) ? botJsonTemplate.generation.items.specialItems.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : specialLootTemplates.filter((template) => - !(this.isBulletOrGrenade(template._props) - || this.isMagazine(template._props)) + !(this.isBulletOrGrenade(template._props) || this.isMagazine(template._props)) ); const healingItems = (botJsonTemplate.generation.items.healing.whitelist?.length > 0) @@ -183,15 +182,13 @@ export class BotLootCacheService const drugItems = (botJsonTemplate.generation.items.drugs.whitelist?.length > 0) ? botJsonTemplate.generation.items.drugs.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : combinedPoolTemplates.filter((template) => - this.isMedicalItem(template._props) - && template._parent === BaseClasses.DRUGS + this.isMedicalItem(template._props) && template._parent === BaseClasses.DRUGS ); const stimItems = (botJsonTemplate.generation.items.stims.whitelist?.length > 0) ? botJsonTemplate.generation.items.stims.whitelist.map((x) => this.itemHelper.getItem(x)[1]) : combinedPoolTemplates.filter((template) => - this.isMedicalItem(template._props) - && template._parent === BaseClasses.STIMULATOR + this.isMedicalItem(template._props) && template._parent === BaseClasses.STIMULATOR ); const grenadeItems = (botJsonTemplate.generation.items.grenades.whitelist?.length > 0) @@ -201,9 +198,7 @@ export class BotLootCacheService // Get loot items (excluding magazines, bullets, grenades and healing items) const backpackLootItems = backpackLootTemplates.filter((template) => // biome-ignore lint/complexity/useSimplifiedLogicExpression: - !this.isBulletOrGrenade(template._props) - && !this.isMagazine(template._props) - // && !this.isMedicalItem(template._props) // Disabled for now as followSanitar has a lot of med items as loot + !this.isBulletOrGrenade(template._props) && !this.isMagazine(template._props) // && !this.isMedicalItem(template._props) // Disabled for now as followSanitar has a lot of med items as loot && !this.isGrenade(template._props) ); diff --git a/project/src/services/FenceService.ts b/project/src/services/FenceService.ts index f1e53b17..9eb4afed 100644 --- a/project/src/services/FenceService.ts +++ b/project/src/services/FenceService.ts @@ -294,9 +294,7 @@ export class FenceService const desiredTotalCount = this.traderConfig.fence.assortSize; const actualTotalCount = this.fenceAssort.items.reduce((count, item) => { - return item.slotId === "hideout" - ? count + 1 - : count; + return item.slotId === "hideout" ? count + 1 : count; }, 0); return actualTotalCount < desiredTotalCount @@ -587,10 +585,7 @@ export class FenceService // Multiply weapon+mods rouble price by multipler in config assorts.barter_scheme[weaponAndMods[0]._id] = [[]]; - assorts.barter_scheme[weaponAndMods[0]._id][0][0] = { - _tpl: Money.ROUBLES, - count: Math.round(rub), - }; + assorts.barter_scheme[weaponAndMods[0]._id][0][0] = {_tpl: Money.ROUBLES, count: Math.round(rub)}; assorts.loyal_level_items[weaponAndMods[0]._id] = loyaltyLevel; @@ -658,8 +653,7 @@ export class FenceService // Roll from 0 to 9999, then divide it by 100: 9999 = 99.99% const randomChance = this.randomUtil.getInt(0, 9999) / 100; - return randomChance > removalChance - && !itemsBeingDeleted.includes(weaponMod._id); + return randomChance > removalChance && !itemsBeingDeleted.includes(weaponMod._id); } /** @@ -681,9 +675,7 @@ export class FenceService // Randomise hp resource of med items if ("MaxHpResource" in itemDetails._props && itemDetails._props.MaxHpResource > 0) { - itemToAdjust.upd.MedKit = { - HpResource: this.randomUtil.getInt(1, itemDetails._props.MaxHpResource), - }; + itemToAdjust.upd.MedKit = {HpResource: this.randomUtil.getInt(1, itemDetails._props.MaxHpResource)}; } // Randomise armor durability @@ -692,8 +684,7 @@ export class FenceService || itemDetails._parent === BaseClasses.HEADWEAR || itemDetails._parent === BaseClasses.VEST || itemDetails._parent === BaseClasses.ARMOREDEQUIPMENT - || itemDetails._parent === BaseClasses.FACECOVER) - && itemDetails._props.MaxDurability > 0 + || itemDetails._parent === BaseClasses.FACECOVER) && itemDetails._props.MaxDurability > 0 ) { const armorMaxDurabilityLimits = this.traderConfig.fence.armorMaxDurabilityPercentMinMax; @@ -703,10 +694,7 @@ export class FenceService const maxDurability = this.randomUtil.getInt(duraMin, duraMax); const durability = this.randomUtil.getInt(1, maxDurability); - itemToAdjust.upd.Repairable = { - Durability: durability, - MaxDurability: maxDurability, - }; + itemToAdjust.upd.Repairable = {Durability: durability, MaxDurability: maxDurability}; return; } @@ -721,19 +709,14 @@ export class FenceService const maxDurability = this.randomUtil.getInt(duraMin, duraMax); const durability = this.randomUtil.getInt(1, maxDurability); - itemToAdjust.upd.Repairable = { - Durability: durability, - MaxDurability: maxDurability, - }; + itemToAdjust.upd.Repairable = {Durability: durability, MaxDurability: maxDurability}; return; } if (this.itemHelper.isOfBaseclass(itemDetails._id, BaseClasses.REPAIR_KITS)) { - itemToAdjust.upd.RepairKit = { - Resource: this.randomUtil.getInt(1, itemDetails._props.MaxRepairResource), - }; + itemToAdjust.upd.RepairKit = {Resource: this.randomUtil.getInt(1, itemDetails._props.MaxRepairResource)}; return; } @@ -757,10 +740,7 @@ export class FenceService const resourceMax = itemDetails._props.MaxResource; const resourceCurrent = this.randomUtil.getInt(1, itemDetails._props.MaxResource); - itemToAdjust.upd.Resource = { - Value: resourceMax - resourceCurrent, - UnitsConsumed: resourceCurrent, - }; + itemToAdjust.upd.Resource = {Value: resourceMax - resourceCurrent, UnitsConsumed: resourceCurrent}; } } @@ -775,10 +755,7 @@ export class FenceService for (const x in limits) { - itemTypeCounts[x] = { - current: 0, - max: limits[x], - }; + itemTypeCounts[x] = {current: 0, max: limits[x]}; } return itemTypeCounts; diff --git a/project/src/services/InsuranceService.ts b/project/src/services/InsuranceService.ts index 86055e5e..b32d9bbd 100644 --- a/project/src/services/InsuranceService.ts +++ b/project/src/services/InsuranceService.ts @@ -202,9 +202,8 @@ export class InsuranceService } const insuranceReturnTimeBonus = pmcData.Bonuses.find((b) => b.type === "InsuranceReturnTime"); - const insuranceReturnTimeBonusPercent = 1.0 - (insuranceReturnTimeBonus - ? Math.abs(insuranceReturnTimeBonus.value) - : 0) / 100; + const insuranceReturnTimeBonusPercent = 1.0 + - (insuranceReturnTimeBonus ? Math.abs(insuranceReturnTimeBonus.value) : 0) / 100; const traderMinReturnAsSeconds = trader.insurance.min_return_hour * TimeUtil.oneHourAsSeconds; const traderMaxReturnAsSeconds = trader.insurance.max_return_hour * TimeUtil.oneHourAsSeconds; @@ -335,9 +334,7 @@ export class InsuranceService // Item didnt have faceshield object pre-raid, add it if (!itemToReturn.upd.FaceShield) { - itemToReturn.upd.FaceShield = { - Hits: insuredItemFromClient.hits, - }; + itemToReturn.upd.FaceShield = {Hits: insuredItemFromClient.hits}; } else { @@ -355,12 +352,7 @@ export class InsuranceService */ protected updateSlotIdValue(playerBaseInventoryEquipmentId: string, itemToReturn: Item): void { - const pocketSlots = [ - "pocket1", - "pocket2", - "pocket3", - "pocket4", - ]; + const pocketSlots = ["pocket1", "pocket2", "pocket3", "pocket4"]; // Some pockets can lose items with player death, some don't if (!("slotId" in itemToReturn) || pocketSlots.includes(itemToReturn.slotId)) diff --git a/project/src/services/LocalisationService.ts b/project/src/services/LocalisationService.ts index 525e9e25..73859227 100644 --- a/project/src/services/LocalisationService.ts +++ b/project/src/services/LocalisationService.ts @@ -30,14 +30,12 @@ export class LocalisationService ? "Aki_Data/Server/database/locales/server" : "./assets/database/locales/server", ); - this.i18n = new I18n( - { - locales: this.localeService.getServerSupportedLocales(), - defaultLocale: "en", - directory: localeFileDirectory, - retryInDefaultLocale: true, - }, - ); + this.i18n = new I18n({ + locales: this.localeService.getServerSupportedLocales(), + defaultLocale: "en", + directory: localeFileDirectory, + retryInDefaultLocale: true, + }); this.i18n.setLocale(this.localeService.getDesiredServerLocale()); } diff --git a/project/src/services/MailSendService.ts b/project/src/services/MailSendService.ts index 41f9ec78..d5accb8a 100644 --- a/project/src/services/MailSendService.ts +++ b/project/src/services/MailSendService.ts @@ -420,10 +420,7 @@ export class MailSendService parentItem.parentId = this.hashUtil.generate(); } - itemsToSendToPlayer = { - stash: parentItem.parentId, - data: [], - }; + itemsToSendToPlayer = {stash: parentItem.parentId, data: []}; // Ensure Ids are unique and cont collide with items in player inventory later messageDetails.items = this.itemHelper.replaceIDs(null, messageDetails.items); diff --git a/project/src/services/MatchLocationService.ts b/project/src/services/MatchLocationService.ts index 1b3e40bd..d81b1817 100644 --- a/project/src/services/MatchLocationService.ts +++ b/project/src/services/MatchLocationService.ts @@ -8,9 +8,7 @@ export class MatchLocationService { protected locations = {}; - constructor( - @inject("TimeUtil") protected timeUtil: TimeUtil, - ) + constructor(@inject("TimeUtil") protected timeUtil: TimeUtil) {} public createGroup(sessionID: string, info: ICreateGroupRequestData): any @@ -27,15 +25,13 @@ export class MatchLocationService isSavage: false, timeShift: "CURR", dt: this.timeUtil.getTimestamp(), - players: [ - { - _id: `pmc${sessionID}`, - region: "EUR", - ip: "127.0.0.1", - savageId: `scav${sessionID}`, - accessKeyId: "", - }, - ], + players: [{ + _id: `pmc${sessionID}`, + region: "EUR", + ip: "127.0.0.1", + savageId: `scav${sessionID}`, + accessKeyId: "", + }], customDataCenter: [], }; diff --git a/project/src/services/ProfileFixerService.ts b/project/src/services/ProfileFixerService.ts index 7dfe1b39..2dcb1547 100644 --- a/project/src/services/ProfileFixerService.ts +++ b/project/src/services/ProfileFixerService.ts @@ -93,8 +93,7 @@ export class ProfileFixerService HideoutAreas.GENERATOR, 6 + this.databaseServer.getTables().globals.config.SkillsSettings.HideoutManagement.EliteSlots - .Generator - .Slots, + .Generator.Slots, pmcProfile, ); } @@ -276,34 +275,30 @@ export class ProfileFixerService { if (!pmcProfile.Hideout.Areas.find((x) => x.type === HideoutAreas.WEAPON_STAND)) { - pmcProfile.Hideout.Areas.push( - { - type: 24, - level: 0, - active: true, - passiveBonusesEnabled: true, - completeTime: 0, - constructing: false, - slots: [], - lastRecipe: "", - }, - ); + pmcProfile.Hideout.Areas.push({ + type: 24, + level: 0, + active: true, + passiveBonusesEnabled: true, + completeTime: 0, + constructing: false, + slots: [], + lastRecipe: "", + }); } if (!pmcProfile.Hideout.Areas.find((x) => x.type === HideoutAreas.WEAPON_STAND_SECONDARY)) { - pmcProfile.Hideout.Areas.push( - { - type: 25, - level: 0, - active: true, - passiveBonusesEnabled: true, - completeTime: 0, - constructing: false, - slots: [], - lastRecipe: "", - }, - ); + pmcProfile.Hideout.Areas.push({ + type: 25, + level: 0, + active: true, + passiveBonusesEnabled: true, + completeTime: 0, + constructing: false, + slots: [], + lastRecipe: "", + }); } } @@ -357,10 +352,7 @@ export class ProfileFixerService if (!fullProfile.aki) { this.logger.debug("Adding aki object to profile"); - fullProfile.aki = { - version: this.watermark.getVersionTag(), - receivedGifts: [], - }; + fullProfile.aki = {version: this.watermark.getVersionTag(), receivedGifts: []}; } } @@ -404,9 +396,7 @@ export class ProfileFixerService if (!pmcProfile.UnlockedInfo) { this.logger.debug("Adding UnlockedInfo object to profile"); - pmcProfile.UnlockedInfo = { - unlockedProductionRecipe: [], - }; + pmcProfile.UnlockedInfo = {unlockedProductionRecipe: []}; } } @@ -554,9 +544,9 @@ export class ProfileFixerService { if ( !(currentRepeatable.changeRequirement - && currentRepeatable.activeQuests.every( - (x) => (typeof x.changeCost !== "undefined" && typeof x.changeStandingCost !== "undefined"), - )) + && currentRepeatable.activeQuests.every(( + x, + ) => (typeof x.changeCost !== "undefined" && typeof x.changeStandingCost !== "undefined"))) ) { repeatablesCompatible = false; @@ -798,28 +788,17 @@ export class ProfileFixerService if (bonus.type.toLowerCase() === "stashsize") { - return profileBonuses.find( - (x) => - x.type === bonus.type - && x.templateId === bonus.templateId, - ); + return profileBonuses.find((x) => x.type === bonus.type && x.templateId === bonus.templateId); } if (bonus.type.toLowerCase() === "additionalslots") { - return profileBonuses.find( - (x) => - x.type === bonus.type - && x.value === bonus.value - && x.visible === bonus.visible, + return profileBonuses.find((x) => + x.type === bonus.type && x.value === bonus.value && x.visible === bonus.visible ); } - return profileBonuses.find( - (x) => - x.type === bonus.type - && x.value === bonus.value, - ); + return profileBonuses.find((x) => x.type === bonus.type && x.value === bonus.value); } /** diff --git a/project/src/services/ProfileSnapshotService.ts b/project/src/services/ProfileSnapshotService.ts index 2007ea5c..f1ffe7c5 100644 --- a/project/src/services/ProfileSnapshotService.ts +++ b/project/src/services/ProfileSnapshotService.ts @@ -8,9 +8,7 @@ export class ProfileSnapshotService { protected storedProfileSnapshots: Record = {}; - constructor( - @inject("JsonUtil") protected jsonUtil: JsonUtil, - ) + constructor(@inject("JsonUtil") protected jsonUtil: JsonUtil) {} /** diff --git a/project/src/services/RagfairCategoriesService.ts b/project/src/services/RagfairCategoriesService.ts index a8039963..5a1196bd 100644 --- a/project/src/services/RagfairCategoriesService.ts +++ b/project/src/services/RagfairCategoriesService.ts @@ -8,9 +8,7 @@ export class RagfairCategoriesService { protected categories: Record = {}; - constructor( - @inject("WinstonLogger") protected logger: ILogger, - ) + constructor(@inject("WinstonLogger") protected logger: ILogger) {} /** @@ -58,9 +56,7 @@ export class RagfairCategoriesService const itemId = offer.items[0]._tpl; if (increment) { - categories[itemId] = categories[itemId] - ? categories[itemId] + 1 - : 1; + categories[itemId] = categories[itemId] ? categories[itemId] + 1 : 1; } else { diff --git a/project/src/services/RagfairPriceService.ts b/project/src/services/RagfairPriceService.ts index 3eba729a..22b57672 100644 --- a/project/src/services/RagfairPriceService.ts +++ b/project/src/services/RagfairPriceService.ts @@ -29,10 +29,7 @@ export class RagfairPriceService implements OnLoad protected generatedDynamicPrices: boolean; protected generatedStaticPrices: boolean; - protected prices: IRagfairServerPrices = { - static: {}, - dynamic: {}, - }; + protected prices: IRagfairServerPrices = {static: {}, dynamic: {}}; constructor( @inject("HandbookHelper") protected handbookHelper: HandbookHelper, @@ -298,8 +295,7 @@ export class RagfairPriceService implements OnLoad // Only adjust price if difference is > a percent AND item price passes threshhold set in config if ( - priceDifferencePercent - > this.ragfairConfig.dynamic.offerAdjustment.maxPriceDifferenceBelowHandbookPercent + priceDifferencePercent > this.ragfairConfig.dynamic.offerAdjustment.maxPriceDifferenceBelowHandbookPercent && itemPrice >= this.ragfairConfig.dynamic.offerAdjustment.priceThreshholdRub ) { @@ -418,10 +414,7 @@ export class RagfairPriceService implements OnLoad const defaultPreset = presets.find((x) => x._encyclopedia); if (defaultPreset) { - return { - isDefault: true, - preset: defaultPreset, - }; + return {isDefault: true, preset: defaultPreset}; } if (presets.length === 1) @@ -441,9 +434,6 @@ export class RagfairPriceService implements OnLoad ); } - return { - isDefault: false, - preset: presets[0], - }; + return {isDefault: false, preset: presets[0]}; } } diff --git a/project/src/services/RepairService.ts b/project/src/services/RepairService.ts index 9b1cd272..4064fd87 100644 --- a/project/src/services/RepairService.ts +++ b/project/src/services/RepairService.ts @@ -69,9 +69,7 @@ export class RepairService const priceCoef = this.traderHelper.getLoyaltyLevel(traderId, pmcData).repair_price_coef; const traderRepairDetails = this.traderHelper.getTrader(traderId, sessionID).repair; const repairQualityMultiplier = traderRepairDetails.quality; - const repairRate = (priceCoef <= 0) - ? 1 - : (priceCoef / 100 + 1); + const repairRate = (priceCoef <= 0) ? 1 : (priceCoef / 100 + 1); const itemToRepairDetails = this.databaseServer.getTables().templates.items[itemToRepair._tpl]; const repairItemIsArmor = !!itemToRepairDetails._props.ArmorMaterial; @@ -124,12 +122,7 @@ export class RepairService { const options: IProcessBuyTradeRequestData = { // eslint-disable-next-line @typescript-eslint/naming-convention - scheme_items: [ - { - id: repairedItemId, - count: Math.round(repairCost), - }, - ], + scheme_items: [{id: repairedItemId, count: Math.round(repairCost)}], tid: traderId, Action: "", type: "", @@ -149,11 +142,7 @@ export class RepairService * @param repairDetails details of item repaired, cost/item * @param pmcData Profile to add points to */ - public addRepairSkillPoints( - sessionId: string, - repairDetails: RepairDetails, - pmcData: IPmcData, - ): void + public addRepairSkillPoints(sessionId: string, repairDetails: RepairDetails, pmcData: IPmcData): void { if ( repairDetails.repairedByKit @@ -186,9 +175,7 @@ export class RepairService } const isHeavyArmor = itemDetails[1]._props.ArmorType === "Heavy"; - const vestSkillToLevel = isHeavyArmor - ? SkillTypes.HEAVY_VESTS - : SkillTypes.LIGHT_VESTS; + const vestSkillToLevel = isHeavyArmor ? SkillTypes.HEAVY_VESTS : SkillTypes.LIGHT_VESTS; const pointsToAddToVestSkill = repairDetails.repairPoints * this.repairConfig.armorKitSkillPointGainPerRepairPointMultiplier; @@ -227,9 +214,7 @@ export class RepairService * @param repairDetails the repair details to calculate skill points for * @returns the number of skill points to reward the user */ - protected getWeaponRepairSkillPoints( - repairDetails: RepairDetails, - ): number + protected getWeaponRepairSkillPoints(repairDetails: RepairDetails): number { // This formula and associated configs is calculated based on 30 repairs done on live // The points always came out 2-aligned, which is why there's a divide/multiply by 2 with ceil calls @@ -420,17 +405,11 @@ export class RepairService if (!repairKitInInventory.upd) { this.logger.debug(`Repair kit: ${repairKitInInventory._id} in inventory lacks upd object, adding`); - repairKitInInventory.upd = { - RepairKit: { - Resource: maxRepairAmount, - }, - }; + repairKitInInventory.upd = {RepairKit: {Resource: maxRepairAmount}}; } if (!repairKitInInventory.upd.RepairKit?.Resource) { - repairKitInInventory.upd.RepairKit = { - Resource: maxRepairAmount, - }; + repairKitInInventory.upd.RepairKit = {Resource: maxRepairAmount}; } } diff --git a/project/src/services/SeasonalEventService.ts b/project/src/services/SeasonalEventService.ts index b606d40e..2601fb90 100644 --- a/project/src/services/SeasonalEventService.ts +++ b/project/src/services/SeasonalEventService.ts @@ -236,10 +236,7 @@ export class SeasonalEventService const eventEndDate = new Date(currentDate.getFullYear(), event.endMonth - 1, event.endDay); // Current date is between start/end dates - if ( - currentDate >= eventStartDate - && currentDate <= eventEndDate - ) + if (currentDate >= eventStartDate && currentDate <= eventEndDate) { this.christmasEventActive = SeasonalEventType[event.type] === SeasonalEventType.CHRISTMAS; this.halloweenEventActive = SeasonalEventType[event.type] === SeasonalEventType.HALLOWEEN; diff --git a/project/src/services/mod/CustomItemService.ts b/project/src/services/mod/CustomItemService.ts index 5ae95575..45835d5a 100644 --- a/project/src/services/mod/CustomItemService.ts +++ b/project/src/services/mod/CustomItemService.ts @@ -120,9 +120,7 @@ export class CustomItemService */ protected getOrGenerateIdForItem(newId: string): string { - return (newId === "") - ? this.hashUtil.generate() - : newId; + return (newId === "") ? this.hashUtil.generate() : newId; } /** @@ -157,13 +155,7 @@ export class CustomItemService */ protected addToHandbookDb(newItemId: string, parentId: string, priceRoubles: number): void { - this.tables.templates.handbook.Items.push( - { - Id: newItemId, - ParentId: parentId, - Price: priceRoubles, - }, - ); + this.tables.templates.handbook.Items.push({Id: newItemId, ParentId: parentId, Price: priceRoubles}); } /** diff --git a/project/src/services/mod/dynamicRouter/DynamicRouterMod.ts b/project/src/services/mod/dynamicRouter/DynamicRouterMod.ts index f2b1054c..fc93971a 100644 --- a/project/src/services/mod/dynamicRouter/DynamicRouterMod.ts +++ b/project/src/services/mod/dynamicRouter/DynamicRouterMod.ts @@ -2,10 +2,7 @@ import { DynamicRouter, RouteAction } from "@spt-aki/di/Router"; export class DynamicRouterMod extends DynamicRouter { - public constructor( - routes: RouteAction[], - private topLevelRoute: string, - ) + public constructor(routes: RouteAction[], private topLevelRoute: string) { super(routes); } diff --git a/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts b/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts index 3992f0c1..a980bc5b 100644 --- a/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts +++ b/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts @@ -8,11 +8,7 @@ export class DynamicRouterModService { constructor(private container: DependencyContainer) {} - public registerDynamicRouter( - name: string, - routes: RouteAction[], - topLevelRoute: string, - ): void + public registerDynamicRouter(name: string, routes: RouteAction[], topLevelRoute: string): void { this.container.register(name, {useValue: new DynamicRouterMod(routes, topLevelRoute)}); this.container.registerType("DynamicRoutes", name); diff --git a/project/src/services/mod/onLoad/OnLoadMod.ts b/project/src/services/mod/onLoad/OnLoadMod.ts index b70b4644..2f1b4458 100644 --- a/project/src/services/mod/onLoad/OnLoadMod.ts +++ b/project/src/services/mod/onLoad/OnLoadMod.ts @@ -2,10 +2,7 @@ import { OnLoad } from "@spt-aki/di/OnLoad"; export class OnLoadMod implements OnLoad { - public constructor( - private onLoadOverride: () => void, - private getRouteOverride: () => string, - ) + public constructor(private onLoadOverride: () => void, private getRouteOverride: () => string) { // super(); } diff --git a/project/src/services/mod/onLoad/OnLoadModService.ts b/project/src/services/mod/onLoad/OnLoadModService.ts index 7ada64c6..8145d480 100644 --- a/project/src/services/mod/onLoad/OnLoadModService.ts +++ b/project/src/services/mod/onLoad/OnLoadModService.ts @@ -8,11 +8,7 @@ export class OnLoadModService constructor(protected container: DependencyContainer) {} - public registerOnLoad( - name: string, - onLoad: () => void, - getRoute: () => string, - ): void + public registerOnLoad(name: string, onLoad: () => void, getRoute: () => string): void { this.container.register(name, {useValue: new OnLoadMod(onLoad, getRoute)}); this.container.registerType("OnLoad", name); diff --git a/project/src/services/mod/onUpdate/OnUpdateModService.ts b/project/src/services/mod/onUpdate/OnUpdateModService.ts index b8885d2d..5c55e677 100644 --- a/project/src/services/mod/onUpdate/OnUpdateModService.ts +++ b/project/src/services/mod/onUpdate/OnUpdateModService.ts @@ -8,11 +8,7 @@ export class OnUpdateModService constructor(protected container: DependencyContainer) {} - public registerOnUpdate( - name: string, - onUpdate: (timeSinceLastRun: number) => boolean, - getRoute: () => string, - ): void + public registerOnUpdate(name: string, onUpdate: (timeSinceLastRun: number) => boolean, getRoute: () => string): void { this.container.register(name, {useValue: new OnUpdateMod(onUpdate, getRoute)}); this.container.registerType("OnUpdate", name); diff --git a/project/src/services/mod/staticRouter/StaticRouterMod.ts b/project/src/services/mod/staticRouter/StaticRouterMod.ts index 01977a6f..04e07227 100644 --- a/project/src/services/mod/staticRouter/StaticRouterMod.ts +++ b/project/src/services/mod/staticRouter/StaticRouterMod.ts @@ -2,10 +2,7 @@ import { RouteAction, StaticRouter } from "@spt-aki/di/Router"; export class StaticRouterMod extends StaticRouter { - public constructor( - routes: RouteAction[], - private topLevelRoute: string, - ) + public constructor(routes: RouteAction[], private topLevelRoute: string) { super(routes); } diff --git a/project/src/services/mod/staticRouter/StaticRouterModService.ts b/project/src/services/mod/staticRouter/StaticRouterModService.ts index 70502e87..14047c09 100644 --- a/project/src/services/mod/staticRouter/StaticRouterModService.ts +++ b/project/src/services/mod/staticRouter/StaticRouterModService.ts @@ -8,11 +8,7 @@ export class StaticRouterModService { constructor(protected container: DependencyContainer) {} - public registerStaticRouter( - name: string, - routes: RouteAction[], - topLevelRoute: string, - ): void + public registerStaticRouter(name: string, routes: RouteAction[], topLevelRoute: string): void { this.container.register(name, {useValue: new StaticRouterMod(routes, topLevelRoute)}); this.container.registerType("StaticRoutes", name); diff --git a/project/src/utils/DatabaseImporter.ts b/project/src/utils/DatabaseImporter.ts index b22e83f4..c348e6d5 100644 --- a/project/src/utils/DatabaseImporter.ts +++ b/project/src/utils/DatabaseImporter.ts @@ -45,9 +45,7 @@ export class DatabaseImporter implements OnLoad */ public getSptDataPath(): string { - return (globalThis.G_RELEASE_CONFIGURATION) - ? "Aki_Data/Server/" - : "./assets/"; + return (globalThis.G_RELEASE_CONFIGURATION) ? "Aki_Data/Server/" : "./assets/"; } public async onLoad(): Promise diff --git a/project/src/utils/HashUtil.ts b/project/src/utils/HashUtil.ts index 043f3cbc..6b9d0d2e 100644 --- a/project/src/utils/HashUtil.ts +++ b/project/src/utils/HashUtil.ts @@ -6,9 +6,7 @@ import { TimeUtil } from "@spt-aki/utils/TimeUtil"; @injectable() export class HashUtil { - constructor( - @inject("TimeUtil") protected timeUtil: TimeUtil, - ) + constructor(@inject("TimeUtil") protected timeUtil: TimeUtil) {} /** diff --git a/project/src/utils/HttpFileUtil.ts b/project/src/utils/HttpFileUtil.ts index 358471cc..baca8734 100644 --- a/project/src/utils/HttpFileUtil.ts +++ b/project/src/utils/HttpFileUtil.ts @@ -7,9 +7,7 @@ import { HttpServerHelper } from "@spt-aki/helpers/HttpServerHelper"; @injectable() export class HttpFileUtil { - constructor( - @inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper, - ) + constructor(@inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper) { } diff --git a/project/src/utils/HttpResponseUtil.ts b/project/src/utils/HttpResponseUtil.ts index f10fdaba..5549dfa0 100644 --- a/project/src/utils/HttpResponseUtil.ts +++ b/project/src/utils/HttpResponseUtil.ts @@ -18,12 +18,10 @@ export class HttpResponseUtil protected clearString(s: string): any { - return s.replace(/[\b]/g, "") - .replace(/[\f]/g, "") - .replace(/[\n]/g, "") - .replace(/[\r]/g, "") - .replace(/[\t]/g, "") - .replace(/[\\]/g, ""); + return s.replace(/[\b]/g, "").replace(/[\f]/g, "").replace(/[\n]/g, "").replace(/[\r]/g, "").replace( + /[\t]/g, + "", + ).replace(/[\\]/g, ""); } /** @@ -43,11 +41,7 @@ export class HttpResponseUtil public getUnclearedBody(data: any, err = 0, errmsg = null): string { - return this.jsonUtil.serialize({ - err: err, - errmsg: errmsg, - data: data, - }); + return this.jsonUtil.serialize({err: err, errmsg: errmsg, data: data}); } public emptyResponse(): IGetBodyResponseData @@ -71,11 +65,7 @@ export class HttpResponseUtil errorCode = BackendErrorCodes.NONE, ): IItemEventRouterResponse { - output.warnings = [{ - index: 0, - errmsg: message, - code: errorCode.toString(), - }]; + output.warnings = [{index: 0, errmsg: message, code: errorCode.toString()}]; return output; } diff --git a/project/src/utils/ImporterUtil.ts b/project/src/utils/ImporterUtil.ts index ee92c21e..51173cec 100644 --- a/project/src/utils/ImporterUtil.ts +++ b/project/src/utils/ImporterUtil.ts @@ -9,10 +9,7 @@ import { Queue } from "@spt-aki/utils/collections/queue/Queue"; @injectable() export class ImporterUtil { - constructor( - @inject("VFS") protected vfs: VFS, - @inject("JsonUtil") protected jsonUtil: JsonUtil, - ) + constructor(@inject("VFS") protected vfs: VFS, @inject("JsonUtil") protected jsonUtil: JsonUtil) {} /** @@ -74,13 +71,9 @@ export class ImporterUtil * @param filepath Path to folder with files * @returns */ - public loadRecursive( - filepath: string, - onReadCallback: (fileWithPath: string, data: string) => void = () => - {}, - onObjectDeserialized: (fileWithPath: string, object: any) => void = () => - {}, - ): T + public loadRecursive(filepath: string, onReadCallback: (fileWithPath: string, data: string) => void = () => + {}, onObjectDeserialized: (fileWithPath: string, object: any) => void = () => + {}): T { const result = {} as T; @@ -148,18 +141,16 @@ export class ImporterUtil { const filePathAndName = `${fileNode.filePath}${fileNode.fileName}`; promises.push( - this.vfs.readFileAsync(filePathAndName) - .then(async (fileData) => - { - onReadCallback(filePathAndName, fileData); - return this.jsonUtil.deserializeWithCacheCheckAsync(fileData, filePathAndName); - }) - .then(async (fileDeserialized) => - { - onObjectDeserialized(filePathAndName, fileDeserialized); - const strippedFilePath = this.vfs.stripExtension(filePathAndName).replace(filepath, ""); - this.placeObject(fileDeserialized, strippedFilePath, result, strippablePath); - }), + this.vfs.readFileAsync(filePathAndName).then(async (fileData) => + { + onReadCallback(filePathAndName, fileData); + return this.jsonUtil.deserializeWithCacheCheckAsync(fileData, filePathAndName); + }).then(async (fileDeserialized) => + { + onObjectDeserialized(filePathAndName, fileDeserialized); + const strippedFilePath = this.vfs.stripExtension(filePathAndName).replace(filepath, ""); + this.placeObject(fileDeserialized, strippedFilePath, result, strippablePath); + }), ); } } @@ -196,9 +187,6 @@ export class ImporterUtil class VisitNode { - constructor( - public filePath: string, - public fileName: string, - ) + constructor(public filePath: string, public fileName: string) {} } diff --git a/project/src/utils/JsonUtil.ts b/project/src/utils/JsonUtil.ts index 73a7666c..a4cbe075 100644 --- a/project/src/utils/JsonUtil.ts +++ b/project/src/utils/JsonUtil.ts @@ -63,11 +63,7 @@ export class JsonUtil * @param options Stringify options or a replacer. * @returns The string converted from the JavaScript value */ - public serializeJsonC( - data: any, - filename?: string | null, - options?: IStringifyOptions | Reviver, - ): string + public serializeJsonC(data: any, filename?: string | null, options?: IStringifyOptions | Reviver): string { try { @@ -81,11 +77,7 @@ export class JsonUtil } } - public serializeJson5( - data: any, - filename?: string | null, - prettify = false, - ): string + public serializeJson5(data: any, filename?: string | null, prettify = false): string { try { diff --git a/project/src/utils/ObjectId.ts b/project/src/utils/ObjectId.ts index 6656bb97..4438e5e2 100644 --- a/project/src/utils/ObjectId.ts +++ b/project/src/utils/ObjectId.ts @@ -6,9 +6,7 @@ import { TimeUtil } from "@spt-aki/utils/TimeUtil"; @injectable() export class ObjectId { - constructor( - @inject("TimeUtil") protected timeUtil: TimeUtil, - ) + constructor(@inject("TimeUtil") protected timeUtil: TimeUtil) {} protected randomBytes = crypto.randomBytes(5); diff --git a/project/src/utils/RandomUtil.ts b/project/src/utils/RandomUtil.ts index 4e0ed9c3..5b45bf82 100644 --- a/project/src/utils/RandomUtil.ts +++ b/project/src/utils/RandomUtil.ts @@ -21,11 +21,7 @@ import { MathUtil } from "@spt-aki/utils/MathUtil"; */ export class ProbabilityObjectArray extends Array> { - constructor( - private mathUtil: MathUtil, - private jsonUtil: JsonUtil, - ...items: ProbabilityObject[] - ) + constructor(private mathUtil: MathUtil, private jsonUtil: JsonUtil, ...items: ProbabilityObject[]) { super(); this.push(...items); @@ -204,10 +200,7 @@ export class ProbabilityObject @injectable() export class RandomUtil { - constructor( - @inject("JsonUtil") protected jsonUtil: JsonUtil, - @inject("WinstonLogger") protected logger: ILogger, - ) + constructor(@inject("JsonUtil") protected jsonUtil: JsonUtil, @inject("WinstonLogger") protected logger: ILogger) { } @@ -381,10 +374,7 @@ export class RandomUtil if (n < 1) { - throw { - name: "Invalid argument", - message: `'n' must be 1 or greater (received ${n})`, - }; + throw {name: "Invalid argument", message: `'n' must be 1 or greater (received ${n})`}; } if (min === max) @@ -453,10 +443,7 @@ export class RandomUtil currentIndex--; // And swap it with the current element. - [array[currentIndex], array[randomIndex]] = [ - array[randomIndex], - array[currentIndex], - ]; + [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]]; } return array; diff --git a/project/src/utils/VFS.ts b/project/src/utils/VFS.ts index 05198a83..fd835750 100644 --- a/project/src/utils/VFS.ts +++ b/project/src/utils/VFS.ts @@ -26,9 +26,7 @@ export class VFS rmdirPromisify: (path: fs.PathLike) => Promise; renamePromisify: (oldPath: fs.PathLike, newPath: fs.PathLike) => Promise; - constructor( - @inject("AsyncQueue") protected asyncQueue: IAsyncQueue, - ) + constructor(@inject("AsyncQueue") protected asyncQueue: IAsyncQueue) { this.accessFilePromisify = promisify(fs.access); this.copyFilePromisify = promisify(fs.copyFile); @@ -52,10 +50,7 @@ export class VFS try { // Create the command to add to the queue - const command = { - uuid: crypto.randomUUID(), - cmd: async () => await this.accessFilePromisify(filepath), - }; + const command = {uuid: crypto.randomUUID(), cmd: async () => await this.accessFilePromisify(filepath)}; // Wait for the command completion await this.asyncQueue.waitFor(command); @@ -76,10 +71,7 @@ export class VFS public async copyAsync(filepath: fs.PathLike, target: fs.PathLike): Promise { - const command = { - uuid: crypto.randomUUID(), - cmd: async () => await this.copyFilePromisify(filepath, target), - }; + const command = {uuid: crypto.randomUUID(), cmd: async () => await this.copyFilePromisify(filepath, target)}; await this.asyncQueue.waitFor(command); } diff --git a/project/src/utils/Watermark.ts b/project/src/utils/Watermark.ts index 226d649d..33dce3fe 100644 --- a/project/src/utils/Watermark.ts +++ b/project/src/utils/Watermark.ts @@ -14,9 +14,7 @@ export class WatermarkLocale protected warning: string[]; protected modding: string[]; - constructor( - @inject("LocalisationService") protected localisationService: LocalisationService, - ) + constructor(@inject("LocalisationService") protected localisationService: LocalisationService) { this.description = [ this.localisationService.getText("watermark-discord_url"), diff --git a/project/src/utils/logging/AbstractWinstonLogger.ts b/project/src/utils/logging/AbstractWinstonLogger.ts index 95761eba..1facf66a 100644 --- a/project/src/utils/logging/AbstractWinstonLogger.ts +++ b/project/src/utils/logging/AbstractWinstonLogger.ts @@ -17,22 +17,8 @@ export abstract class AbstractWinstonLogger implements ILogger protected showDebugInConsole = false; protected filePath: string; protected logLevels = { - levels: { - error: 0, - warn: 1, - succ: 2, - info: 3, - custom: 4, - debug: 5, - }, - colors: { - error: "red", - warn: "yellow", - succ: "green", - info: "white", - custom: "black", - debug: "gray", - }, + levels: {error: 0, warn: 1, succ: 2, info: 3, custom: 4, debug: 5}, + colors: {error: "red", warn: "yellow", succ: "green", info: "white", custom: "black", debug: "gray"}, bgColors: { default: "", blackBG: "blackBG", @@ -48,9 +34,7 @@ export abstract class AbstractWinstonLogger implements ILogger protected logger: winston.Logger & SptLogger; protected writeFilePromisify: (path: fs.PathLike, data: string, options?: any) => Promise; - constructor( - protected asyncQueue: IAsyncQueue, - ) + constructor(protected asyncQueue: IAsyncQueue) { this.filePath = `${this.getFilePath()}${this.getFileName()}`; this.writeFilePromisify = promisify(fs.writeFile); @@ -101,10 +85,7 @@ export abstract class AbstractWinstonLogger implements ILogger } winston.addColors(this.logLevels.colors); - this.logger = createLogger({ - levels: this.logLevels.levels, - transports: [...transportsList], - }); + this.logger = createLogger({levels: this.logLevels.levels, transports: [...transportsList]}); if (this.isLogExceptions()) { @@ -165,10 +146,7 @@ export abstract class AbstractWinstonLogger implements ILogger if (typeof data === "string") { - command = { - uuid: crypto.randomUUID(), - cmd: async () => await tmpLogger.log("custom", data), - }; + command = {uuid: crypto.randomUUID(), cmd: async () => await tmpLogger.log("custom", data)}; } else { @@ -183,37 +161,25 @@ export abstract class AbstractWinstonLogger implements ILogger public async error(data: string | Record): Promise { - const command: ICommand = { - uuid: crypto.randomUUID(), - cmd: async () => await this.logger.error(data), - }; + const command: ICommand = {uuid: crypto.randomUUID(), cmd: async () => await this.logger.error(data)}; await this.asyncQueue.waitFor(command); } public async warning(data: string | Record): Promise { - const command: ICommand = { - uuid: crypto.randomUUID(), - cmd: async () => await this.logger.warn(data), - }; + const command: ICommand = {uuid: crypto.randomUUID(), cmd: async () => await this.logger.warn(data)}; await this.asyncQueue.waitFor(command); } public async success(data: string | Record): Promise { - const command: ICommand = { - uuid: crypto.randomUUID(), - cmd: async () => await this.logger.succ(data), - }; + const command: ICommand = {uuid: crypto.randomUUID(), cmd: async () => await this.logger.succ(data)}; await this.asyncQueue.waitFor(command); } public async info(data: string | Record): Promise { - const command: ICommand = { - uuid: crypto.randomUUID(), - cmd: async () => await this.logger.info(data), - }; + const command: ICommand = {uuid: crypto.randomUUID(), cmd: async () => await this.logger.info(data)}; await this.asyncQueue.waitFor(command); } @@ -243,17 +209,11 @@ export abstract class AbstractWinstonLogger implements ILogger if (onlyShowInConsole) { - command = { - uuid: crypto.randomUUID(), - cmd: async () => await this.log(data, this.logLevels.colors.debug), - }; + command = {uuid: crypto.randomUUID(), cmd: async () => await this.log(data, this.logLevels.colors.debug)}; } else { - command = { - uuid: crypto.randomUUID(), - cmd: async () => await this.logger.debug(data), - }; + command = {uuid: crypto.randomUUID(), cmd: async () => await this.logger.debug(data)}; } await this.asyncQueue.waitFor(command); diff --git a/project/src/utils/logging/WinstonMainLogger.ts b/project/src/utils/logging/WinstonMainLogger.ts index ff02f482..9b7ad449 100644 --- a/project/src/utils/logging/WinstonMainLogger.ts +++ b/project/src/utils/logging/WinstonMainLogger.ts @@ -6,9 +6,7 @@ import { AbstractWinstonLogger } from "@spt-aki/utils/logging/AbstractWinstonLog @injectable() export class WinstonMainLogger extends AbstractWinstonLogger { - constructor( - @inject("AsyncQueue") protected asyncQueue: IAsyncQueue, - ) + constructor(@inject("AsyncQueue") protected asyncQueue: IAsyncQueue) { super(asyncQueue); } diff --git a/project/src/utils/logging/WinstonRequestLogger.ts b/project/src/utils/logging/WinstonRequestLogger.ts index 9206d48e..b6812c2c 100644 --- a/project/src/utils/logging/WinstonRequestLogger.ts +++ b/project/src/utils/logging/WinstonRequestLogger.ts @@ -6,9 +6,7 @@ import { AbstractWinstonLogger } from "@spt-aki/utils/logging/AbstractWinstonLog @injectable() export class WinstonRequestLogger extends AbstractWinstonLogger { - constructor( - @inject("AsyncQueue") protected asyncQueue: IAsyncQueue, - ) + constructor(@inject("AsyncQueue") protected asyncQueue: IAsyncQueue) { super(asyncQueue); } diff --git a/project/tests/__fixture__/profileInsurance.fixture.ts b/project/tests/__fixture__/profileInsurance.fixture.ts index de0b4f19..1e9008d2 100644 --- a/project/tests/__fixture__/profileInsurance.fixture.ts +++ b/project/tests/__fixture__/profileInsurance.fixture.ts @@ -1,1412 +1,747 @@ import { Insurance } from "@spt-aki/models/eft/profile/IAkiProfile"; -export const profileInsuranceFixture: Insurance[] = [ - { - scheduledTime: 1698945140, - traderId: "54cb50c76803fa8b248b4571", // Prapor - messageContent: { - templateId: "58fe0e4586f774728248ca13 4", - type: 8, - maxStorageTime: 345600, - text: "", - profileChangeEvents: [], - systemData: { - date: "01.11.2023", - time: "10:51", - location: "factory4_day", - }, - }, - items: [ - { - _id: "3679078e05f5b14466d6a730", - _tpl: "5d6d3716a4b9361bc8618872", - parentId: "5fe49444ae6628187a2e77b8", - slotId: "hideout", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 55, - MaxDurability: 55, - }, - }, - }, - { - _id: "911a0f04d5d9c7e239807ae0", - _tpl: "5644bd2b4bdc2d3b4c8b4572", - parentId: "5fe49444ae6628187a2e77b8", - slotId: "hideout", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 97.7862549, - MaxDurability: 100, - }, - }, - }, - { - _id: "695b13896108f765e8985698", - _tpl: "5648a69d4bdc2ded0b8b457b", - parentId: "5fe49444ae6628187a2e77b8", - slotId: "hideout", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "bb49d6ceb3e87d8563a06455", - _tpl: "5df8a4d786f77412672a1e3b", - parentId: "5fe49444ae6628187a2e77b8", - slotId: "hideout", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "631f8492de748dec852f7ddf", - _tpl: "64abd93857958b4249003418", - parentId: "5fe49444ae6628187a2e77b8", - slotId: "hideout", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 49.2865, - MaxDurability: 60, - }, - }, - }, - { - _id: "a2b0c716162c5e31ec28c55a", - _tpl: "5a16b8a9fcdbcb00165aa6ca", - parentId: "3679078e05f5b14466d6a730", - slotId: "mod_nvg", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "dc565f750342cb2d19eeda06", - _tpl: "5d6d3be5a4b9361bc73bc763", - parentId: "3679078e05f5b14466d6a730", - slotId: "mod_equipment_001", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 29.33, - MaxDurability: 29.33, - }, - }, - }, - { - _id: "e9ff62601669d9e2ea9c2fbb", - _tpl: "5d6d3943a4b9360dbc46d0cc", - parentId: "3679078e05f5b14466d6a730", - slotId: "mod_equipment_002", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "ac134d7cf6c9d8e25edd0015", - _tpl: "5c11046cd174af02a012e42b", - parentId: "a2b0c716162c5e31ec28c55a", - slotId: "mod_nvg", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "22274b895ecc80d51c3cba1c", - _tpl: "5c110624d174af029e69734c", - parentId: "ac134d7cf6c9d8e25edd0015", - slotId: "mod_nvg", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - Togglable: { - On: true, - }, - }, - }, - { - _id: "c9278dd8251e99578bf7a274", - _tpl: "59c6633186f7740cf0493bb9", - parentId: "911a0f04d5d9c7e239807ae0", - slotId: "mod_gas_block", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "677c209ebb45445ebb42c405", - _tpl: "5649ab884bdc2ded0b8b457f", - parentId: "911a0f04d5d9c7e239807ae0", - slotId: "mod_muzzle", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "8ada5c9cc26585281577c6eb", - _tpl: "5649ae4a4bdc2d1b2b8b4588", - parentId: "911a0f04d5d9c7e239807ae0", - slotId: "mod_pistol_grip", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "4bd10f89836fd9f86aedcac1", - _tpl: "5649af094bdc2df8348b4586", - parentId: "911a0f04d5d9c7e239807ae0", - slotId: "mod_reciever", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "8b1327270791b142ac341b03", - _tpl: "5649d9a14bdc2d79388b4580", - parentId: "911a0f04d5d9c7e239807ae0", - slotId: "mod_sight_rear", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "566335b3df586f34b47f5e35", - _tpl: "5649b2314bdc2d79388b4576", - parentId: "911a0f04d5d9c7e239807ae0", - slotId: "mod_stock", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "da8cde1b3024c336f6e06152", - _tpl: "55d482194bdc2d1d4e8b456b", - parentId: "911a0f04d5d9c7e239807ae0", - slotId: "mod_magazine", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "1e0b177df108c0c117028812", - _tpl: "57cffddc24597763133760c6", - parentId: "c9278dd8251e99578bf7a274", - slotId: "mod_handguard", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "bc041c0011d76f714b898400", - _tpl: "57cffcd624597763133760c5", - parentId: "1e0b177df108c0c117028812", - slotId: "mod_mount_003", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "9f8d7880a6e0a47a211ec5d3", - _tpl: "58491f3324597764bc48fa02", - parentId: "8b1327270791b142ac341b03", - slotId: "mod_scope", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "402b4086535a50ef7d9cef88", - _tpl: "5649be884bdc2d79388b4577", - parentId: "566335b3df586f34b47f5e35", - slotId: "mod_stock", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "db2ef9442178910eba985b51", - _tpl: "58d2946386f774496974c37e", - parentId: "402b4086535a50ef7d9cef88", - slotId: "mod_stock_000", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "3c32b7d47ad80e83749fa906", - _tpl: "58d2912286f7744e27117493", - parentId: "db2ef9442178910eba985b51", - slotId: "mod_stock", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "574a9b5535585255cde19570", - _tpl: "55d482194bdc2d1d4e8b456b", - parentId: "695b13896108f765e8985698", - slotId: "1", - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "696835b2badfb96623ea887c", - _tpl: "55d482194bdc2d1d4e8b456b", - parentId: "695b13896108f765e8985698", - slotId: "2", - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "c2d5e23c7886e8ff02010731", - _tpl: "55d482194bdc2d1d4e8b456b", - parentId: "695b13896108f765e8985698", - slotId: "3", - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "306de2f475a559610a4f6f1d", - _tpl: "55d482194bdc2d1d4e8b456b", - parentId: "695b13896108f765e8985698", - slotId: "4", - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "eb0445b49a97e84e27d47f3c", - _tpl: "5aa2ba71e5b5b000137b758f", - parentId: "695b13896108f765e8985698", - slotId: "5", - upd: { - StackObjectsCount: 1, - }, - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - }, - { - _id: "fad89a5bdfd23e3248123346", - _tpl: "5fc5396e900b1d5091531e72", - parentId: "695b13896108f765e8985698", - slotId: "6", - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "b16c2a938954cd69c687c51a", - _tpl: "5b4736b986f77405cb415c10", - parentId: "695b13896108f765e8985698", - slotId: "7", - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "a2b3019ac8d340eeb068d429", - _tpl: "5ea18c84ecf1982c7712d9a2", - parentId: "695b13896108f765e8985698", - slotId: "10", - location: { - x: 0, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 29, - MaxDurability: 33, - }, - }, - }, - { - _id: "0b3c5d183e8b506d655f85c4", - _tpl: "644a3df63b0b6f03e101e065", - parentId: "fad89a5bdfd23e3248123346", - slotId: "mod_tactical", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "757211a0b648fe27b0475ded", - _tpl: "59f8a37386f7747af3328f06", - parentId: "b16c2a938954cd69c687c51a", - slotId: "mod_foregrip", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "870a887c63ca30fb15736b3d", - _tpl: "62a1b7fbc30cfa1d366af586", - parentId: "bb49d6ceb3e87d8563a06455", - slotId: "main", - upd: { - StackObjectsCount: 1, - }, - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - }, - { - _id: "f3de631a1bb2b74bd0160d9a", - _tpl: "5d6d3be5a4b9361bc73bc763", - parentId: "bb49d6ceb3e87d8563a06455", - slotId: "main", - location: { - x: 5, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 22.41, - MaxDurability: 22.41, - }, - }, - }, - { - _id: "351180f3248d45c71cb2ebdc", - _tpl: "57c44b372459772d2b39b8ce", - parentId: "870a887c63ca30fb15736b3d", - slotId: "main", - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "7237f722106866f2df8dc8d1", - _tpl: "56e33680d2720be2748b4576", - parentId: "870a887c63ca30fb15736b3d", - slotId: "main", - location: { - x: 0, - y: 3, - r: "Horizontal", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "d0cf00aff56ea520cdd94330", - _tpl: "57c44dd02459772d2e0ae249", - parentId: "351180f3248d45c71cb2ebdc", - slotId: "mod_muzzle", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "5119653b2c66d57ee219e26f", - _tpl: "57c44f4f2459772d2c627113", - parentId: "351180f3248d45c71cb2ebdc", - slotId: "mod_reciever", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "ed1ac0183a8af587110aa74e", - _tpl: "5a9e81fba2750c00164f6b11", - parentId: "351180f3248d45c71cb2ebdc", - slotId: "mod_magazine", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "310a7d1bb07ae0e522f3f8e3", - _tpl: "5a69a2ed8dc32e000d46d1f1", - parentId: "351180f3248d45c71cb2ebdc", - slotId: "mod_pistol_grip", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "8a7e3489197b3b98126447fd", - _tpl: "6130ca3fd92c473c77020dbd", - parentId: "351180f3248d45c71cb2ebdc", - slotId: "mod_charge", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "e818616e11ae07aa05388759", - _tpl: "5dff8db859400025ea5150d4", - parentId: "351180f3248d45c71cb2ebdc", - slotId: "mod_mount_000", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "768812984debf2756bece089", - _tpl: "57c44e7b2459772d28133248", - parentId: "d0cf00aff56ea520cdd94330", - slotId: "mod_sight_rear", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "67c610585ed668baf4604931", - _tpl: "59eb7ebe86f7740b373438ce", - parentId: "d0cf00aff56ea520cdd94330", - slotId: "mod_mount_000", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "80e9dffa49bfe263ab0128c7", - _tpl: "6267c6396b642f77f56f5c1c", - parentId: "67c610585ed668baf4604931", - slotId: "mod_tactical_000", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "dee323443ce23ba8c54b9f1c", - _tpl: "5cc9c20cd7f00c001336c65d", - parentId: "67c610585ed668baf4604931", - slotId: "mod_tactical_001", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "3008088022dd55f1c99e5a32", - _tpl: "5c1cd46f2e22164bef5cfedb", - parentId: "67c610585ed668baf4604931", - slotId: "mod_foregrip", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "71e9f8d005c72940d857fe64", - _tpl: "59d790f486f77403cb06aec6", - parentId: "80e9dffa49bfe263ab0128c7", - slotId: "mod_flashlight", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "8c610c6cc67115a5fc1662ff", - _tpl: "56eabf3bd2720b75698b4569", - parentId: "310a7d1bb07ae0e522f3f8e3", - slotId: "mod_stock_000", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "9bf01177f0c1e346b2d65373", - _tpl: "58d2912286f7744e27117493", - parentId: "8c610c6cc67115a5fc1662ff", - slotId: "mod_stock", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "7dd43ffa6e03c2da6cddc56e", - _tpl: "6171407e50224f204c1da3c5", - parentId: "e818616e11ae07aa05388759", - slotId: "mod_scope", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "fa9da4ccf3630cb173c293f9", - _tpl: "5b3b99475acfc432ff4dcbee", - parentId: "7dd43ffa6e03c2da6cddc56e", - slotId: "mod_scope_000", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "6e2727806fb12e12123e9a57", - _tpl: "616554fe50224f204c1da2aa", - parentId: "7dd43ffa6e03c2da6cddc56e", - slotId: "mod_scope_001", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "2c868d4676adc934f897e9a7", - _tpl: "61605d88ffa6e502ac5e7eeb", - parentId: "7dd43ffa6e03c2da6cddc56e", - slotId: "mod_scope_002", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "1b159fdc14c350f8a4a7e19e", - _tpl: "58d39b0386f77443380bf13c", - parentId: "6e2727806fb12e12123e9a57", - slotId: "mod_scope", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "7691790ffc5290da292cab99", - _tpl: "61657230d92c473c770213d7", - parentId: "1b159fdc14c350f8a4a7e19e", - slotId: "mod_scope", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "012a11e7dcb1280a1ab9d2f6", - _tpl: "618168b350224f204c1da4d8", - parentId: "7237f722106866f2df8dc8d1", - slotId: "main", - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "38ca7415a458c4d22ba2f3c3", - _tpl: "6130c43c67085e45ef1405a1", - parentId: "012a11e7dcb1280a1ab9d2f6", - slotId: "mod_muzzle", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "c5a0621ebf856ce1b0945efc", - _tpl: "61816fcad92c473c770215cc", - parentId: "012a11e7dcb1280a1ab9d2f6", - slotId: "mod_sight_front", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "a74677b17c1c49edc002df9b", - _tpl: "5dfa3d2b0dee1b22f862eade", - parentId: "38ca7415a458c4d22ba2f3c3", - slotId: "mod_muzzle", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - ], +export const profileInsuranceFixture: Insurance[] = [{ + scheduledTime: 1698945140, + traderId: "54cb50c76803fa8b248b4571", // Prapor + messageContent: { + templateId: "58fe0e4586f774728248ca13 4", + type: 8, + maxStorageTime: 345600, + text: "", + profileChangeEvents: [], + systemData: {date: "01.11.2023", time: "10:51", location: "factory4_day"}, }, - { - scheduledTime: 1698945140, - traderId: "54cb57776803fa99248b456e", // Therapist - messageContent: { - templateId: "58fe0e3486f77471f772c3f2 2", - type: 8, - maxStorageTime: 518400, - text: "", - profileChangeEvents: [], - systemData: { - date: "01.11.2023", - time: "11:18", - location: "factory4_day", - }, - }, - items: [ - { - _id: "5ae1c2b99a0a339adc620148", - _tpl: "5cebec38d7f00c00110a652a", - parentId: "ad018df9da0cbf2726394ef1", - slotId: "mod_mount_000", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "30f4bcb87bcc4604e27c02c1", - _tpl: "5cc70146e4a949000d73bf6b", - parentId: "ad018df9da0cbf2726394ef1", - slotId: "mod_mount_001", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "ad018df9da0cbf2726394ef1", - _tpl: "5cc70102e4a949035e43ba74", - parentId: "3bc4ff5bd99f165dc75cbd25", - slotId: "main", - upd: { - StackObjectsCount: 1, - }, - location: { - x: 3, - y: 0, - r: "Horizontal", - isSearched: true, - }, - }, - { - _id: "12c243bd6b3e486e61325f81", - _tpl: "5cc82d76e24e8d00134b4b83", - parentId: "5fe49444ae6628187a2e77b8", - slotId: "hideout", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 99.93771, - MaxDurability: 100, - }, - }, - }, - { - _id: "760652d86ee78eed513e0ad7", - _tpl: "5ab8f39486f7745cd93a1cca", - parentId: "5fe49444ae6628187a2e77b8", - slotId: "hideout", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "61ab4afefac354dfc64c7874", - _tpl: "5b432d215acfc4771e1c6624", - parentId: "5fe49444ae6628187a2e77b8", - slotId: "hideout", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 30, - MaxDurability: 30, - }, - }, - }, - { - _id: "285e9d9ae196ae4e336cd04f", - _tpl: "5d5d87f786f77427997cfaef", - parentId: "5fe49444ae6628187a2e77b8", - slotId: "hideout", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 75, - MaxDurability: 80, - }, - }, - }, - { - _id: "3bc4ff5bd99f165dc75cbd25", - _tpl: "5f5e467b0bc58666c37e7821", - parentId: "5fe49444ae6628187a2e77b8", - slotId: "hideout", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "6bf5d8ee81a3c9aec21bbbad", - _tpl: "5d5fca1ea4b93635fd598c07", - parentId: "5fe49444ae6628187a2e77b8", - slotId: "hideout", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "2371438cf809b5e483bf5d85", - _tpl: "5cc70093e4a949033c734312", - parentId: "12c243bd6b3e486e61325f81", - slotId: "mod_magazine", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "7f890346ea5b2cbc68c3170f", - _tpl: "5cc700b9e4a949000f0f0f25", - parentId: "12c243bd6b3e486e61325f81", - slotId: "mod_stock", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "12fb79a9c4929009ff8d89e1", - _tpl: "5cc700ede4a949033c734315", - parentId: "12c243bd6b3e486e61325f81", - slotId: "mod_reciever", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "d4c5274082ed716e19447f46", - _tpl: "5cc701d7e4a94900100ac4e7", - parentId: "12c243bd6b3e486e61325f81", - slotId: "mod_barrel", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "d819dd4d2b13de10e9d6d805", - _tpl: "5cc6ea85e4a949000e1ea3c3", - parentId: "12c243bd6b3e486e61325f81", - slotId: "mod_charge", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "fc9a664cacc477c4e725a81a", - _tpl: "5cc700d4e4a949000f0f0f28", - parentId: "7f890346ea5b2cbc68c3170f", - slotId: "mod_stock_000", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "372891c593cf14e176b93ce2", - _tpl: "5cc7012ae4a949001252b43e", - parentId: "12fb79a9c4929009ff8d89e1", - slotId: "mod_mount_000", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "bd196435a57bdc433df1e49d", - _tpl: "5cc7012ae4a949001252b43e", - parentId: "12fb79a9c4929009ff8d89e1", - slotId: "mod_mount_001", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "ea3349d29797354d835c2192", - _tpl: "58491f3324597764bc48fa02", - parentId: "12fb79a9c4929009ff8d89e1", - slotId: "mod_scope", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "4ccf7c74ca7d2167deb0ae5c", - _tpl: "626becf9582c3e319310b837", - parentId: "372891c593cf14e176b93ce2", - slotId: "mod_tactical", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "adfd3640fc93daf21c721ca6", - _tpl: "5cc9c20cd7f00c001336c65d", - parentId: "bd196435a57bdc433df1e49d", - slotId: "mod_tactical", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "deeb36b1812790b0145d2532", - _tpl: "5a16badafcdbcb001865f72d", - parentId: "61ab4afefac354dfc64c7874", - slotId: "mod_equipment_000", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 12, - MaxDurability: 25, - }, - }, - }, - { - _id: "4c0e0548df904c384569190c", - _tpl: "5ea058e01dbce517f324b3e2", - parentId: "61ab4afefac354dfc64c7874", - slotId: "mod_nvg", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 3, - MaxDurability: 39, - }, - }, - }, - { - _id: "da82c293cabc705b30fef93a", - _tpl: "5a398ab9c4a282000c5a9842", - parentId: "61ab4afefac354dfc64c7874", - slotId: "mod_mount", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "b8fc94611def6e9ba534a8b3", - _tpl: "5a16b8a9fcdbcb00165aa6ca", - parentId: "4c0e0548df904c384569190c", - slotId: "mod_nvg", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "20d6193c1f399e6326ebbc10", - _tpl: "5a16b93dfcdbcbcae6687261", - parentId: "b8fc94611def6e9ba534a8b3", - slotId: "mod_nvg", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "065c4f13b2bd8be266e1e809", - _tpl: "57235b6f24597759bf5a30f1", - parentId: "20d6193c1f399e6326ebbc10", - slotId: "mod_nvg", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - Togglable: { - On: true, - }, - }, - }, - { - _id: "1883b955ab202fa099809278", - _tpl: "57d17c5e2459775a5c57d17d", - parentId: "da82c293cabc705b30fef93a", - slotId: "mod_flashlight", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "e3c9e50ce31900c950b4ff6f", - _tpl: "5cc70093e4a949033c734312", - parentId: "285e9d9ae196ae4e336cd04f", - slotId: "1", - location: { - x: 0, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "193259b5eb848af4d036bee5", - _tpl: "5cc70093e4a949033c734312", - parentId: "285e9d9ae196ae4e336cd04f", - slotId: "2", - location: { - x: 0, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "f97ce69443f63bbe8f8097a7", - _tpl: "5cc70093e4a949033c734312", - parentId: "285e9d9ae196ae4e336cd04f", - slotId: "3", - location: { - x: 0, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "5d1c154a8abcfa934e477ac4", - _tpl: "5cc70093e4a949033c734312", - parentId: "285e9d9ae196ae4e336cd04f", - slotId: "4", - location: { - x: 0, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "289f7af841690c5388095477", - _tpl: "5cc70093e4a949033c734312", - parentId: "285e9d9ae196ae4e336cd04f", - slotId: "5", - location: { - x: 0, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "3e6d578165b61aef9865f677", - _tpl: "5cc70093e4a949033c734312", - parentId: "285e9d9ae196ae4e336cd04f", - slotId: "6", - location: { - x: 0, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "338682523f8504f97f84f3ab", - _tpl: "5cc70093e4a949033c734312", - parentId: "285e9d9ae196ae4e336cd04f", - slotId: "7", - location: { - x: 0, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "6d18ac01aa04b16e4f0d5d2f", - _tpl: "5cc70093e4a949033c734312", - parentId: "285e9d9ae196ae4e336cd04f", - slotId: "8", - location: { - x: 0, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "ac4ed54d61daa0c5219f8522", - _tpl: "5cc70093e4a949033c734312", - parentId: "285e9d9ae196ae4e336cd04f", - slotId: "9", - location: { - x: 0, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "2460460ef3d3df5c1ce07edb", - _tpl: "5cc70093e4a949033c734312", - parentId: "285e9d9ae196ae4e336cd04f", - slotId: "10", - location: { - x: 0, - y: 0, - r: "Vertical", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "3aeb18aac0b532f34255f162", - _tpl: "5cc70146e4a949000d73bf6b", - parentId: "285e9d9ae196ae4e336cd04f", - slotId: "11", - upd: { - StackObjectsCount: 1, - }, - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - }, - { - _id: "bdb46107abbf1d92edaaf14e", - _tpl: "6272379924e29f06af4d5ecb", - parentId: "3aeb18aac0b532f34255f162", - slotId: "mod_tactical", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "0caadd8507a36d9ea871e88e", - _tpl: "5ab8f04f86f774585f4237d8", - parentId: "3bc4ff5bd99f165dc75cbd25", - slotId: "main", - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "240046eebc9040c1d7e58611", - _tpl: "5ac66d015acfc400180ae6e4", - parentId: "0caadd8507a36d9ea871e88e", - slotId: "main", - location: { - x: 0, - y: 0, - r: "Horizontal", - isSearched: true, - }, - upd: { - StackObjectsCount: 1, - sptPresetId: "5acf7dfc86f774401e19c390", - Repairable: { - Durability: 32, - MaxDurability: 59, - }, - Foldable: { - Folded: true, - }, - }, - }, - { - _id: "70b23c628fa17699d9a71e94", - _tpl: "59c6633186f7740cf0493bb9", - parentId: "240046eebc9040c1d7e58611", - slotId: "mod_gas_block", - upd: { - StackObjectsCount: 1, - sptPresetId: "5acf7dfc86f774401e19c390", - Repairable: { - Durability: 32, - MaxDurability: 59, - }, - }, - }, - { - _id: "7cc2e24dc6bc0716bdddc472", - _tpl: "5943ee5a86f77413872d25ec", - parentId: "240046eebc9040c1d7e58611", - slotId: "mod_muzzle", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "7a51ebbad703082660d59d27", - _tpl: "5649ade84bdc2d1b2b8b4587", - parentId: "240046eebc9040c1d7e58611", - slotId: "mod_pistol_grip", - upd: { - StackObjectsCount: 1, - sptPresetId: "5acf7dfc86f774401e19c390", - Repairable: { - Durability: 32, - MaxDurability: 59, - }, - }, - }, - { - _id: "b481bc57436ed9a0c3abe7f3", - _tpl: "5d2c76ed48f03532f2136169", - parentId: "240046eebc9040c1d7e58611", - slotId: "mod_reciever", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "5774ef80597c7f91bff40dbb", - _tpl: "5ac50c185acfc400163398d4", - parentId: "240046eebc9040c1d7e58611", - slotId: "mod_stock", - upd: { - StackObjectsCount: 1, - sptPresetId: "5acf7dfc86f774401e19c390", - Repairable: { - Durability: 32, - MaxDurability: 59, - }, - }, - }, - { - _id: "8b7c8e6ba172ac390c99a2ae", - _tpl: "5ac66c5d5acfc4001718d314", - parentId: "240046eebc9040c1d7e58611", - slotId: "mod_magazine", - upd: { - StackObjectsCount: 1, - }, - }, - { - _id: "1ed3a416b1fc7adbed1160df", - _tpl: "6130ca3fd92c473c77020dbd", - parentId: "240046eebc9040c1d7e58611", - slotId: "mod_charge", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "bbe087661947c0d9c1cde146", - _tpl: "5648b1504bdc2d9d488b4584", - parentId: "70b23c628fa17699d9a71e94", - slotId: "mod_handguard", - upd: { - StackObjectsCount: 1, - sptPresetId: "5acf7dfc86f774401e19c390", - Repairable: { - Durability: 32, - MaxDurability: 59, - }, - }, - }, - { - _id: "724388f8110434efccd79b3a", - _tpl: "544a3a774bdc2d3a388b4567", - parentId: "b481bc57436ed9a0c3abe7f3", - slotId: "mod_scope", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - { - _id: "8581038b0f795618a3d26c94", - _tpl: "58d268fc86f774111273f8c2", - parentId: "724388f8110434efccd79b3a", - slotId: "mod_scope", - upd: { - StackObjectsCount: 1, - Repairable: { - Durability: 100, - MaxDurability: 100, - }, - }, - }, - ], + items: [{ + _id: "3679078e05f5b14466d6a730", + _tpl: "5d6d3716a4b9361bc8618872", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: {StackObjectsCount: 1, Repairable: {Durability: 55, MaxDurability: 55}}, + }, { + _id: "911a0f04d5d9c7e239807ae0", + _tpl: "5644bd2b4bdc2d3b4c8b4572", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: {StackObjectsCount: 1, Repairable: {Durability: 97.7862549, MaxDurability: 100}}, + }, { + _id: "695b13896108f765e8985698", + _tpl: "5648a69d4bdc2ded0b8b457b", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: {StackObjectsCount: 1}, + }, { + _id: "bb49d6ceb3e87d8563a06455", + _tpl: "5df8a4d786f77412672a1e3b", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: {StackObjectsCount: 1}, + }, { + _id: "631f8492de748dec852f7ddf", + _tpl: "64abd93857958b4249003418", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: {StackObjectsCount: 1, Repairable: {Durability: 49.2865, MaxDurability: 60}}, + }, { + _id: "a2b0c716162c5e31ec28c55a", + _tpl: "5a16b8a9fcdbcb00165aa6ca", + parentId: "3679078e05f5b14466d6a730", + slotId: "mod_nvg", + upd: {StackObjectsCount: 1}, + }, { + _id: "dc565f750342cb2d19eeda06", + _tpl: "5d6d3be5a4b9361bc73bc763", + parentId: "3679078e05f5b14466d6a730", + slotId: "mod_equipment_001", + upd: {StackObjectsCount: 1, Repairable: {Durability: 29.33, MaxDurability: 29.33}}, + }, { + _id: "e9ff62601669d9e2ea9c2fbb", + _tpl: "5d6d3943a4b9360dbc46d0cc", + parentId: "3679078e05f5b14466d6a730", + slotId: "mod_equipment_002", + upd: {StackObjectsCount: 1}, + }, { + _id: "ac134d7cf6c9d8e25edd0015", + _tpl: "5c11046cd174af02a012e42b", + parentId: "a2b0c716162c5e31ec28c55a", + slotId: "mod_nvg", + upd: {StackObjectsCount: 1}, + }, { + _id: "22274b895ecc80d51c3cba1c", + _tpl: "5c110624d174af029e69734c", + parentId: "ac134d7cf6c9d8e25edd0015", + slotId: "mod_nvg", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}, Togglable: {On: true}}, + }, { + _id: "c9278dd8251e99578bf7a274", + _tpl: "59c6633186f7740cf0493bb9", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_gas_block", + upd: {StackObjectsCount: 1}, + }, { + _id: "677c209ebb45445ebb42c405", + _tpl: "5649ab884bdc2ded0b8b457f", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_muzzle", + upd: {StackObjectsCount: 1}, + }, { + _id: "8ada5c9cc26585281577c6eb", + _tpl: "5649ae4a4bdc2d1b2b8b4588", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_pistol_grip", + upd: {StackObjectsCount: 1}, + }, { + _id: "4bd10f89836fd9f86aedcac1", + _tpl: "5649af094bdc2df8348b4586", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_reciever", + upd: {StackObjectsCount: 1}, + }, { + _id: "8b1327270791b142ac341b03", + _tpl: "5649d9a14bdc2d79388b4580", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_sight_rear", + upd: {StackObjectsCount: 1}, + }, { + _id: "566335b3df586f34b47f5e35", + _tpl: "5649b2314bdc2d79388b4576", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_stock", + upd: {StackObjectsCount: 1}, + }, { + _id: "da8cde1b3024c336f6e06152", + _tpl: "55d482194bdc2d1d4e8b456b", + parentId: "911a0f04d5d9c7e239807ae0", + slotId: "mod_magazine", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "1e0b177df108c0c117028812", + _tpl: "57cffddc24597763133760c6", + parentId: "c9278dd8251e99578bf7a274", + slotId: "mod_handguard", + upd: {StackObjectsCount: 1}, + }, { + _id: "bc041c0011d76f714b898400", + _tpl: "57cffcd624597763133760c5", + parentId: "1e0b177df108c0c117028812", + slotId: "mod_mount_003", + upd: {StackObjectsCount: 1}, + }, { + _id: "9f8d7880a6e0a47a211ec5d3", + _tpl: "58491f3324597764bc48fa02", + parentId: "8b1327270791b142ac341b03", + slotId: "mod_scope", + upd: {StackObjectsCount: 1}, + }, { + _id: "402b4086535a50ef7d9cef88", + _tpl: "5649be884bdc2d79388b4577", + parentId: "566335b3df586f34b47f5e35", + slotId: "mod_stock", + upd: {StackObjectsCount: 1}, + }, { + _id: "db2ef9442178910eba985b51", + _tpl: "58d2946386f774496974c37e", + parentId: "402b4086535a50ef7d9cef88", + slotId: "mod_stock_000", + upd: {StackObjectsCount: 1}, + }, { + _id: "3c32b7d47ad80e83749fa906", + _tpl: "58d2912286f7744e27117493", + parentId: "db2ef9442178910eba985b51", + slotId: "mod_stock", + upd: {StackObjectsCount: 1}, + }, { + _id: "574a9b5535585255cde19570", + _tpl: "55d482194bdc2d1d4e8b456b", + parentId: "695b13896108f765e8985698", + slotId: "1", + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "696835b2badfb96623ea887c", + _tpl: "55d482194bdc2d1d4e8b456b", + parentId: "695b13896108f765e8985698", + slotId: "2", + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "c2d5e23c7886e8ff02010731", + _tpl: "55d482194bdc2d1d4e8b456b", + parentId: "695b13896108f765e8985698", + slotId: "3", + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "306de2f475a559610a4f6f1d", + _tpl: "55d482194bdc2d1d4e8b456b", + parentId: "695b13896108f765e8985698", + slotId: "4", + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "eb0445b49a97e84e27d47f3c", + _tpl: "5aa2ba71e5b5b000137b758f", + parentId: "695b13896108f765e8985698", + slotId: "5", + upd: {StackObjectsCount: 1}, + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + }, { + _id: "fad89a5bdfd23e3248123346", + _tpl: "5fc5396e900b1d5091531e72", + parentId: "695b13896108f765e8985698", + slotId: "6", + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "b16c2a938954cd69c687c51a", + _tpl: "5b4736b986f77405cb415c10", + parentId: "695b13896108f765e8985698", + slotId: "7", + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "a2b3019ac8d340eeb068d429", + _tpl: "5ea18c84ecf1982c7712d9a2", + parentId: "695b13896108f765e8985698", + slotId: "10", + location: {x: 0, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1, Repairable: {Durability: 29, MaxDurability: 33}}, + }, { + _id: "0b3c5d183e8b506d655f85c4", + _tpl: "644a3df63b0b6f03e101e065", + parentId: "fad89a5bdfd23e3248123346", + slotId: "mod_tactical", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "757211a0b648fe27b0475ded", + _tpl: "59f8a37386f7747af3328f06", + parentId: "b16c2a938954cd69c687c51a", + slotId: "mod_foregrip", + upd: {StackObjectsCount: 1}, + }, { + _id: "870a887c63ca30fb15736b3d", + _tpl: "62a1b7fbc30cfa1d366af586", + parentId: "bb49d6ceb3e87d8563a06455", + slotId: "main", + upd: {StackObjectsCount: 1}, + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + }, { + _id: "f3de631a1bb2b74bd0160d9a", + _tpl: "5d6d3be5a4b9361bc73bc763", + parentId: "bb49d6ceb3e87d8563a06455", + slotId: "main", + location: {x: 5, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1, Repairable: {Durability: 22.41, MaxDurability: 22.41}}, + }, { + _id: "351180f3248d45c71cb2ebdc", + _tpl: "57c44b372459772d2b39b8ce", + parentId: "870a887c63ca30fb15736b3d", + slotId: "main", + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "7237f722106866f2df8dc8d1", + _tpl: "56e33680d2720be2748b4576", + parentId: "870a887c63ca30fb15736b3d", + slotId: "main", + location: {x: 0, y: 3, r: "Horizontal", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "d0cf00aff56ea520cdd94330", + _tpl: "57c44dd02459772d2e0ae249", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_muzzle", + upd: {StackObjectsCount: 1}, + }, { + _id: "5119653b2c66d57ee219e26f", + _tpl: "57c44f4f2459772d2c627113", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_reciever", + upd: {StackObjectsCount: 1}, + }, { + _id: "ed1ac0183a8af587110aa74e", + _tpl: "5a9e81fba2750c00164f6b11", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_magazine", + upd: {StackObjectsCount: 1}, + }, { + _id: "310a7d1bb07ae0e522f3f8e3", + _tpl: "5a69a2ed8dc32e000d46d1f1", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_pistol_grip", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "8a7e3489197b3b98126447fd", + _tpl: "6130ca3fd92c473c77020dbd", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_charge", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "e818616e11ae07aa05388759", + _tpl: "5dff8db859400025ea5150d4", + parentId: "351180f3248d45c71cb2ebdc", + slotId: "mod_mount_000", + upd: {StackObjectsCount: 1}, + }, { + _id: "768812984debf2756bece089", + _tpl: "57c44e7b2459772d28133248", + parentId: "d0cf00aff56ea520cdd94330", + slotId: "mod_sight_rear", + upd: {StackObjectsCount: 1}, + }, { + _id: "67c610585ed668baf4604931", + _tpl: "59eb7ebe86f7740b373438ce", + parentId: "d0cf00aff56ea520cdd94330", + slotId: "mod_mount_000", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "80e9dffa49bfe263ab0128c7", + _tpl: "6267c6396b642f77f56f5c1c", + parentId: "67c610585ed668baf4604931", + slotId: "mod_tactical_000", + upd: {StackObjectsCount: 1}, + }, { + _id: "dee323443ce23ba8c54b9f1c", + _tpl: "5cc9c20cd7f00c001336c65d", + parentId: "67c610585ed668baf4604931", + slotId: "mod_tactical_001", + upd: {StackObjectsCount: 1}, + }, { + _id: "3008088022dd55f1c99e5a32", + _tpl: "5c1cd46f2e22164bef5cfedb", + parentId: "67c610585ed668baf4604931", + slotId: "mod_foregrip", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "71e9f8d005c72940d857fe64", + _tpl: "59d790f486f77403cb06aec6", + parentId: "80e9dffa49bfe263ab0128c7", + slotId: "mod_flashlight", + upd: {StackObjectsCount: 1}, + }, { + _id: "8c610c6cc67115a5fc1662ff", + _tpl: "56eabf3bd2720b75698b4569", + parentId: "310a7d1bb07ae0e522f3f8e3", + slotId: "mod_stock_000", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "9bf01177f0c1e346b2d65373", + _tpl: "58d2912286f7744e27117493", + parentId: "8c610c6cc67115a5fc1662ff", + slotId: "mod_stock", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "7dd43ffa6e03c2da6cddc56e", + _tpl: "6171407e50224f204c1da3c5", + parentId: "e818616e11ae07aa05388759", + slotId: "mod_scope", + upd: {StackObjectsCount: 1}, + }, { + _id: "fa9da4ccf3630cb173c293f9", + _tpl: "5b3b99475acfc432ff4dcbee", + parentId: "7dd43ffa6e03c2da6cddc56e", + slotId: "mod_scope_000", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "6e2727806fb12e12123e9a57", + _tpl: "616554fe50224f204c1da2aa", + parentId: "7dd43ffa6e03c2da6cddc56e", + slotId: "mod_scope_001", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "2c868d4676adc934f897e9a7", + _tpl: "61605d88ffa6e502ac5e7eeb", + parentId: "7dd43ffa6e03c2da6cddc56e", + slotId: "mod_scope_002", + upd: {StackObjectsCount: 1}, + }, { + _id: "1b159fdc14c350f8a4a7e19e", + _tpl: "58d39b0386f77443380bf13c", + parentId: "6e2727806fb12e12123e9a57", + slotId: "mod_scope", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "7691790ffc5290da292cab99", + _tpl: "61657230d92c473c770213d7", + parentId: "1b159fdc14c350f8a4a7e19e", + slotId: "mod_scope", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "012a11e7dcb1280a1ab9d2f6", + _tpl: "618168b350224f204c1da4d8", + parentId: "7237f722106866f2df8dc8d1", + slotId: "main", + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "38ca7415a458c4d22ba2f3c3", + _tpl: "6130c43c67085e45ef1405a1", + parentId: "012a11e7dcb1280a1ab9d2f6", + slotId: "mod_muzzle", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "c5a0621ebf856ce1b0945efc", + _tpl: "61816fcad92c473c770215cc", + parentId: "012a11e7dcb1280a1ab9d2f6", + slotId: "mod_sight_front", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "a74677b17c1c49edc002df9b", + _tpl: "5dfa3d2b0dee1b22f862eade", + parentId: "38ca7415a458c4d22ba2f3c3", + slotId: "mod_muzzle", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }], +}, { + scheduledTime: 1698945140, + traderId: "54cb57776803fa99248b456e", // Therapist + messageContent: { + templateId: "58fe0e3486f77471f772c3f2 2", + type: 8, + maxStorageTime: 518400, + text: "", + profileChangeEvents: [], + systemData: {date: "01.11.2023", time: "11:18", location: "factory4_day"}, }, -]; + items: [{ + _id: "5ae1c2b99a0a339adc620148", + _tpl: "5cebec38d7f00c00110a652a", + parentId: "ad018df9da0cbf2726394ef1", + slotId: "mod_mount_000", + upd: {StackObjectsCount: 1}, + }, { + _id: "30f4bcb87bcc4604e27c02c1", + _tpl: "5cc70146e4a949000d73bf6b", + parentId: "ad018df9da0cbf2726394ef1", + slotId: "mod_mount_001", + upd: {StackObjectsCount: 1}, + }, { + _id: "ad018df9da0cbf2726394ef1", + _tpl: "5cc70102e4a949035e43ba74", + parentId: "3bc4ff5bd99f165dc75cbd25", + slotId: "main", + upd: {StackObjectsCount: 1}, + location: {x: 3, y: 0, r: "Horizontal", isSearched: true}, + }, { + _id: "12c243bd6b3e486e61325f81", + _tpl: "5cc82d76e24e8d00134b4b83", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: {StackObjectsCount: 1, Repairable: {Durability: 99.93771, MaxDurability: 100}}, + }, { + _id: "760652d86ee78eed513e0ad7", + _tpl: "5ab8f39486f7745cd93a1cca", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: {StackObjectsCount: 1}, + }, { + _id: "61ab4afefac354dfc64c7874", + _tpl: "5b432d215acfc4771e1c6624", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: {StackObjectsCount: 1, Repairable: {Durability: 30, MaxDurability: 30}}, + }, { + _id: "285e9d9ae196ae4e336cd04f", + _tpl: "5d5d87f786f77427997cfaef", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: {StackObjectsCount: 1, Repairable: {Durability: 75, MaxDurability: 80}}, + }, { + _id: "3bc4ff5bd99f165dc75cbd25", + _tpl: "5f5e467b0bc58666c37e7821", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: {StackObjectsCount: 1}, + }, { + _id: "6bf5d8ee81a3c9aec21bbbad", + _tpl: "5d5fca1ea4b93635fd598c07", + parentId: "5fe49444ae6628187a2e77b8", + slotId: "hideout", + upd: {StackObjectsCount: 1}, + }, { + _id: "2371438cf809b5e483bf5d85", + _tpl: "5cc70093e4a949033c734312", + parentId: "12c243bd6b3e486e61325f81", + slotId: "mod_magazine", + upd: {StackObjectsCount: 1}, + }, { + _id: "7f890346ea5b2cbc68c3170f", + _tpl: "5cc700b9e4a949000f0f0f25", + parentId: "12c243bd6b3e486e61325f81", + slotId: "mod_stock", + upd: {StackObjectsCount: 1}, + }, { + _id: "12fb79a9c4929009ff8d89e1", + _tpl: "5cc700ede4a949033c734315", + parentId: "12c243bd6b3e486e61325f81", + slotId: "mod_reciever", + upd: {StackObjectsCount: 1}, + }, { + _id: "d4c5274082ed716e19447f46", + _tpl: "5cc701d7e4a94900100ac4e7", + parentId: "12c243bd6b3e486e61325f81", + slotId: "mod_barrel", + upd: {StackObjectsCount: 1}, + }, { + _id: "d819dd4d2b13de10e9d6d805", + _tpl: "5cc6ea85e4a949000e1ea3c3", + parentId: "12c243bd6b3e486e61325f81", + slotId: "mod_charge", + upd: {StackObjectsCount: 1}, + }, { + _id: "fc9a664cacc477c4e725a81a", + _tpl: "5cc700d4e4a949000f0f0f28", + parentId: "7f890346ea5b2cbc68c3170f", + slotId: "mod_stock_000", + upd: {StackObjectsCount: 1}, + }, { + _id: "372891c593cf14e176b93ce2", + _tpl: "5cc7012ae4a949001252b43e", + parentId: "12fb79a9c4929009ff8d89e1", + slotId: "mod_mount_000", + upd: {StackObjectsCount: 1}, + }, { + _id: "bd196435a57bdc433df1e49d", + _tpl: "5cc7012ae4a949001252b43e", + parentId: "12fb79a9c4929009ff8d89e1", + slotId: "mod_mount_001", + upd: {StackObjectsCount: 1}, + }, { + _id: "ea3349d29797354d835c2192", + _tpl: "58491f3324597764bc48fa02", + parentId: "12fb79a9c4929009ff8d89e1", + slotId: "mod_scope", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "4ccf7c74ca7d2167deb0ae5c", + _tpl: "626becf9582c3e319310b837", + parentId: "372891c593cf14e176b93ce2", + slotId: "mod_tactical", + upd: {StackObjectsCount: 1}, + }, { + _id: "adfd3640fc93daf21c721ca6", + _tpl: "5cc9c20cd7f00c001336c65d", + parentId: "bd196435a57bdc433df1e49d", + slotId: "mod_tactical", + upd: {StackObjectsCount: 1}, + }, { + _id: "deeb36b1812790b0145d2532", + _tpl: "5a16badafcdbcb001865f72d", + parentId: "61ab4afefac354dfc64c7874", + slotId: "mod_equipment_000", + upd: {StackObjectsCount: 1, Repairable: {Durability: 12, MaxDurability: 25}}, + }, { + _id: "4c0e0548df904c384569190c", + _tpl: "5ea058e01dbce517f324b3e2", + parentId: "61ab4afefac354dfc64c7874", + slotId: "mod_nvg", + upd: {StackObjectsCount: 1, Repairable: {Durability: 3, MaxDurability: 39}}, + }, { + _id: "da82c293cabc705b30fef93a", + _tpl: "5a398ab9c4a282000c5a9842", + parentId: "61ab4afefac354dfc64c7874", + slotId: "mod_mount", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "b8fc94611def6e9ba534a8b3", + _tpl: "5a16b8a9fcdbcb00165aa6ca", + parentId: "4c0e0548df904c384569190c", + slotId: "mod_nvg", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "20d6193c1f399e6326ebbc10", + _tpl: "5a16b93dfcdbcbcae6687261", + parentId: "b8fc94611def6e9ba534a8b3", + slotId: "mod_nvg", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "065c4f13b2bd8be266e1e809", + _tpl: "57235b6f24597759bf5a30f1", + parentId: "20d6193c1f399e6326ebbc10", + slotId: "mod_nvg", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}, Togglable: {On: true}}, + }, { + _id: "1883b955ab202fa099809278", + _tpl: "57d17c5e2459775a5c57d17d", + parentId: "da82c293cabc705b30fef93a", + slotId: "mod_flashlight", + upd: {StackObjectsCount: 1}, + }, { + _id: "e3c9e50ce31900c950b4ff6f", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "1", + location: {x: 0, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "193259b5eb848af4d036bee5", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "2", + location: {x: 0, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "f97ce69443f63bbe8f8097a7", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "3", + location: {x: 0, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "5d1c154a8abcfa934e477ac4", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "4", + location: {x: 0, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "289f7af841690c5388095477", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "5", + location: {x: 0, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "3e6d578165b61aef9865f677", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "6", + location: {x: 0, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "338682523f8504f97f84f3ab", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "7", + location: {x: 0, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "6d18ac01aa04b16e4f0d5d2f", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "8", + location: {x: 0, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "ac4ed54d61daa0c5219f8522", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "9", + location: {x: 0, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "2460460ef3d3df5c1ce07edb", + _tpl: "5cc70093e4a949033c734312", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "10", + location: {x: 0, y: 0, r: "Vertical", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "3aeb18aac0b532f34255f162", + _tpl: "5cc70146e4a949000d73bf6b", + parentId: "285e9d9ae196ae4e336cd04f", + slotId: "11", + upd: {StackObjectsCount: 1}, + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + }, { + _id: "bdb46107abbf1d92edaaf14e", + _tpl: "6272379924e29f06af4d5ecb", + parentId: "3aeb18aac0b532f34255f162", + slotId: "mod_tactical", + upd: {StackObjectsCount: 1}, + }, { + _id: "0caadd8507a36d9ea871e88e", + _tpl: "5ab8f04f86f774585f4237d8", + parentId: "3bc4ff5bd99f165dc75cbd25", + slotId: "main", + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: {StackObjectsCount: 1}, + }, { + _id: "240046eebc9040c1d7e58611", + _tpl: "5ac66d015acfc400180ae6e4", + parentId: "0caadd8507a36d9ea871e88e", + slotId: "main", + location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: { + StackObjectsCount: 1, + sptPresetId: "5acf7dfc86f774401e19c390", + Repairable: {Durability: 32, MaxDurability: 59}, + Foldable: {Folded: true}, + }, + }, { + _id: "70b23c628fa17699d9a71e94", + _tpl: "59c6633186f7740cf0493bb9", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_gas_block", + upd: { + StackObjectsCount: 1, + sptPresetId: "5acf7dfc86f774401e19c390", + Repairable: {Durability: 32, MaxDurability: 59}, + }, + }, { + _id: "7cc2e24dc6bc0716bdddc472", + _tpl: "5943ee5a86f77413872d25ec", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_muzzle", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "7a51ebbad703082660d59d27", + _tpl: "5649ade84bdc2d1b2b8b4587", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_pistol_grip", + upd: { + StackObjectsCount: 1, + sptPresetId: "5acf7dfc86f774401e19c390", + Repairable: {Durability: 32, MaxDurability: 59}, + }, + }, { + _id: "b481bc57436ed9a0c3abe7f3", + _tpl: "5d2c76ed48f03532f2136169", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_reciever", + upd: {StackObjectsCount: 1}, + }, { + _id: "5774ef80597c7f91bff40dbb", + _tpl: "5ac50c185acfc400163398d4", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_stock", + upd: { + StackObjectsCount: 1, + sptPresetId: "5acf7dfc86f774401e19c390", + Repairable: {Durability: 32, MaxDurability: 59}, + }, + }, { + _id: "8b7c8e6ba172ac390c99a2ae", + _tpl: "5ac66c5d5acfc4001718d314", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_magazine", + upd: {StackObjectsCount: 1}, + }, { + _id: "1ed3a416b1fc7adbed1160df", + _tpl: "6130ca3fd92c473c77020dbd", + parentId: "240046eebc9040c1d7e58611", + slotId: "mod_charge", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "bbe087661947c0d9c1cde146", + _tpl: "5648b1504bdc2d9d488b4584", + parentId: "70b23c628fa17699d9a71e94", + slotId: "mod_handguard", + upd: { + StackObjectsCount: 1, + sptPresetId: "5acf7dfc86f774401e19c390", + Repairable: {Durability: 32, MaxDurability: 59}, + }, + }, { + _id: "724388f8110434efccd79b3a", + _tpl: "544a3a774bdc2d3a388b4567", + parentId: "b481bc57436ed9a0c3abe7f3", + slotId: "mod_scope", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }, { + _id: "8581038b0f795618a3d26c94", + _tpl: "58d268fc86f774111273f8c2", + parentId: "724388f8110434efccd79b3a", + slotId: "mod_scope", + upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + }], +}]; diff --git a/project/tests/controllers/InsuranceController.test.ts b/project/tests/controllers/InsuranceController.test.ts index 2c064266..af6f94a9 100644 --- a/project/tests/controllers/InsuranceController.test.ts +++ b/project/tests/controllers/InsuranceController.test.ts @@ -34,10 +34,7 @@ describe("InsuranceController", () => { const session1 = "session1"; const session2 = "session2"; - const profiles = { - [session1]: {}, - [session2]: {}, - }; + const profiles = {[session1]: {}, [session2]: {}}; const getProfilesSpy = vi.spyOn(insuranceController.saveServer, "getProfiles").mockReturnValue(profiles); const processReturnByProfileSpy = vi.spyOn(insuranceController, "processReturnByProfile").mockReturnValue( vi.fn(), @@ -75,10 +72,12 @@ describe("InsuranceController", () => const sessionId = "session-id"; // Mock internal methods. - const mockFilterInsuredItems = vi.spyOn(insuranceController, "filterInsuredItems") - .mockReturnValue(insuranceFixture); - const mockProcessInsuredItems = vi.spyOn(insuranceController, "processInsuredItems") - .mockImplementation(vi.fn()); + const mockFilterInsuredItems = vi.spyOn(insuranceController, "filterInsuredItems").mockReturnValue( + insuranceFixture, + ); + const mockProcessInsuredItems = vi.spyOn(insuranceController, "processInsuredItems").mockImplementation( + vi.fn(), + ); insuranceController.processReturnByProfile(sessionId); @@ -92,10 +91,10 @@ describe("InsuranceController", () => const sessionId = "session-id"; // Mock internal methods. - const mockFilterInsuredItems = vi.spyOn(insuranceController, "filterInsuredItems") - .mockReturnValue([]); // Return an empty array. - const mockProcessInsuredItems = vi.spyOn(insuranceController, "processInsuredItems") - .mockImplementation(vi.fn()); + const mockFilterInsuredItems = vi.spyOn(insuranceController, "filterInsuredItems").mockReturnValue([]); // Return an empty array. + const mockProcessInsuredItems = vi.spyOn(insuranceController, "processInsuredItems").mockImplementation( + vi.fn(), + ); insuranceController.processReturnByProfile(sessionId); @@ -113,8 +112,9 @@ describe("InsuranceController", () => const insured = JSON.parse(JSON.stringify(insuranceFixture)); // Mock getProfile to return the fixture. - const mockGetProfile = vi.spyOn(insuranceController.saveServer, "getProfile") - .mockReturnValue({insurance: insured}); + const mockGetProfile = vi.spyOn(insuranceController.saveServer, "getProfile").mockReturnValue({ + insurance: insured, + }); const mockLoggerDebug = vi.spyOn(insuranceController.logger, "debug"); // Execute the method. @@ -137,8 +137,9 @@ describe("InsuranceController", () => insured[0].scheduledTime = Math.floor((Date.now() / 1000) + (2 * 60 * 60)); // Mock getProfile to return the fixture. - const mockGetProfile = vi.spyOn(insuranceController.saveServer, "getProfile") - .mockReturnValue({insurance: insured}); + const mockGetProfile = vi.spyOn(insuranceController.saveServer, "getProfile").mockReturnValue({ + insurance: insured, + }); const mockLoggerDebug = vi.spyOn(insuranceController.logger, "debug"); // Execute the method. @@ -158,8 +159,9 @@ describe("InsuranceController", () => const insured = JSON.parse(JSON.stringify(insuranceFixture)); // Mock getProfile to return the fixture. - const mockGetProfile = vi.spyOn(insuranceController.saveServer, "getProfile") - .mockReturnValue({insurance: insured}); + const mockGetProfile = vi.spyOn(insuranceController.saveServer, "getProfile").mockReturnValue({ + insurance: insured, + }); const mockLoggerDebug = vi.spyOn(insuranceController.logger, "debug"); // Execute the method, passing in a time that's two hours in the past. The function should use this past @@ -241,25 +243,19 @@ describe("InsuranceController", () => { it("should return the total number of items in all insurance packages", () => { - const insurance = [ - { - _id: "1", - upd: 1234567890, - items: [ - {_id: "1", parentId: "1", slotId: "1"}, - {_id: "2", parentId: "1", slotId: "2"}, - ], - }, - { - _id: "2", - upd: 1234567890, - items: [ - {_id: "3", parentId: "2", slotId: "1"}, - {_id: "4", parentId: "2", slotId: "2"}, - {_id: "5", parentId: "2", slotId: "3"}, - ], - }, - ]; + const insurance = [{ + _id: "1", + upd: 1234567890, + items: [{_id: "1", parentId: "1", slotId: "1"}, {_id: "2", parentId: "1", slotId: "2"}], + }, { + _id: "2", + upd: 1234567890, + items: [{_id: "3", parentId: "2", slotId: "1"}, {_id: "4", parentId: "2", slotId: "2"}, { + _id: "5", + parentId: "2", + slotId: "3", + }], + }]; const expectedCount = 5; // 2 items in the first package + 3 items in the second package. // Execute the method. @@ -283,18 +279,7 @@ describe("InsuranceController", () => it("should return 0 if there are no items in any of the insurance packages", () => { - const insurance = [ - { - _id: "1", - upd: 1234567890, - items: [], - }, - { - _id: "2", - upd: 1234567890, - items: [], - }, - ]; + const insurance = [{_id: "1", upd: 1234567890, items: []}, {_id: "2", upd: 1234567890, items: []}]; const expectedCount = 0; // Execute the method. @@ -310,32 +295,13 @@ describe("InsuranceController", () => it("should remove the specified insurance package from the profile", () => { const sessionID = "session-id"; - const packageToRemove = { - date: "01.11.2023", - time: "10:51", - location: "factory4_day", - }; + const packageToRemove = {date: "01.11.2023", time: "10:51", location: "factory4_day"}; const profile = { - insurance: [ - { - messageContent: { - systemData: { - date: "01.11.2023", - time: "11:18", - location: "factory4_day", - }, - }, - }, - { // This one should be removed - messageContent: { - systemData: { - date: "01.11.2023", - time: "10:51", - location: "factory4_day", - }, - }, - }, - ], + insurance: [{ + messageContent: {systemData: {date: "01.11.2023", time: "11:18", location: "factory4_day"}}, + }, { // This one should be removed + messageContent: {systemData: {date: "01.11.2023", time: "10:51", location: "factory4_day"}}, + }], }; // Mock the getProfile method to return the above profile. @@ -356,23 +322,11 @@ describe("InsuranceController", () => it("should log a message indicating that the package was removed", () => { const sessionID = "session-id"; - const packageToRemove = { - date: "01.11.2023", - time: "10:51", - location: "factory4_day", - }; + const packageToRemove = {date: "01.11.2023", time: "10:51", location: "factory4_day"}; const profile = { - insurance: [ - { - messageContent: { - systemData: { - date: "01.11.2023", - time: "10:51", - location: "factory4_day", - }, - }, - }, - ], + insurance: [{ + messageContent: {systemData: {date: "01.11.2023", time: "10:51", location: "factory4_day"}}, + }], }; // Mock the getProfile method to return the above profile. @@ -393,23 +347,11 @@ describe("InsuranceController", () => it("should not remove any packages if the specified package is not found", () => { const sessionID = "session-id"; - const packageToRemove = { - date: "01.11.2023", - time: "10:51", - location: "factory4_day", - }; + const packageToRemove = {date: "01.11.2023", time: "10:51", location: "factory4_day"}; const profile = { - insurance: [ - { - messageContent: { - systemData: { - date: "02.11.2023", - time: "10:50", - location: "factory4_night", - }, - }, - }, - ], + insurance: [{ + messageContent: {systemData: {date: "02.11.2023", time: "10:50", location: "factory4_night"}}, + }], }; // Mock the getProfile method to return the above profile. @@ -975,10 +917,11 @@ describe("InsuranceController", () => { it("should log details for each attachment", () => { - const attachments = [ - {_id: "item1", name: "Item 1", maxPrice: 100}, - {_id: "item2", name: "Item 2", maxPrice: 200}, - ]; + const attachments = [{_id: "item1", name: "Item 1", maxPrice: 100}, { + _id: "item2", + name: "Item 2", + maxPrice: 200, + }]; // Mock the logger.debug function. const loggerDebugSpy = vi.spyOn(insuranceController.logger, "debug"); @@ -1018,8 +961,7 @@ describe("InsuranceController", () => // Mock rollForDelete to return true for the first two attachments. const mockRollForDelete = vi.spyOn(insuranceController, "rollForDelete").mockReturnValue(false) - .mockReturnValueOnce(true) - .mockReturnValueOnce(true); + .mockReturnValueOnce(true).mockReturnValueOnce(true); // Execute the method. const result = insuranceController.countSuccessfulRolls(attachments, insured.traderId); @@ -1298,8 +1240,9 @@ describe("InsuranceController", () => const insuranceFailedTpl = "failed-message-template"; // Mock the randomUtil to return a static failed template string. - const mockGetArrayValue = vi.spyOn(insuranceController.randomUtil, "getArrayValue") - .mockReturnValue(insuranceFailedTpl); + const mockGetArrayValue = vi.spyOn(insuranceController.randomUtil, "getArrayValue").mockReturnValue( + insuranceFailedTpl, + ); // Don't actually send the message. const sendMessageSpy = vi.spyOn(insuranceController.mailSendService, "sendLocalisedNpcMessageToPlayer") @@ -1332,8 +1275,9 @@ describe("InsuranceController", () => const insuranceFailedTpl = "failed-message-template"; // Mock the randomUtil to return a static failed template string. - const mockGetArrayValue = vi.spyOn(insuranceController.randomUtil, "getArrayValue") - .mockReturnValue(insuranceFailedTpl); + const mockGetArrayValue = vi.spyOn(insuranceController.randomUtil, "getArrayValue").mockReturnValue( + insuranceFailedTpl, + ); // Don't actually send the message. const sendMessageSpy = vi.spyOn(insuranceController.mailSendService, "sendLocalisedNpcMessageToPlayer") @@ -1452,18 +1396,10 @@ describe("InsuranceController", () => // Setup shared test data. pmcData = { - Inventory: { - items: [ - {_id: "item1", otherProps: "value1"}, - {_id: "item2", otherProps: "value2"}, - ], - }, + Inventory: {items: [{_id: "item1", otherProps: "value1"}, {_id: "item2", otherProps: "value2"}]}, InsuredItems: [], }; - body = { - items: ["item1", "item2"], - tid: "someTraderId", - }; + body = {items: ["item1", "item2"], tid: "someTraderId"}; sessionId = "session-id"; // Setup shared mocks. @@ -1488,10 +1424,7 @@ describe("InsuranceController", () => expect(mockPayMoney).toHaveBeenCalledWith( pmcData, { - scheme_items: [ - {id: "item1", count: 100}, - {id: "item2", count: 100}, - ], + scheme_items: [{id: "item1", count: 100}, {id: "item2", count: 100}], tid: "someTraderId", Action: "", type: "", @@ -1500,10 +1433,7 @@ describe("InsuranceController", () => scheme_id: 0, }, sessionId, - { - warnings: [], - otherProperty: "property-value", - }, + {warnings: [], otherProperty: "property-value"}, ); }); @@ -1529,10 +1459,7 @@ describe("InsuranceController", () => // Define the expected payment options structure based on the setup data. const expectedPaymentOptions = { - scheme_items: [ - {id: "item1", count: 100}, - {id: "item2", count: 100}, - ], + scheme_items: [{id: "item1", count: 100}, {id: "item2", count: 100}], tid: body.tid, Action: "", type: "", @@ -1571,11 +1498,7 @@ describe("InsuranceController", () => { // Override the payMoney mock to simulate a payment failure with a warning. const expectedPayMoneyReturn = { - warnings: [{ - index: 0, - errmsg: "Not enough money to complete transaction", - code: 500, - }], + warnings: [{index: 0, errmsg: "Not enough money to complete transaction", code: 500}], otherProperty: "property-value", }; mockPayMoney.mockReturnValue(expectedPayMoneyReturn); @@ -1594,11 +1517,7 @@ describe("InsuranceController", () => { // Override the payMoney mock to simulate a payment failure with a warning. const expectedPayMoneyReturn = { - warnings: [{ - index: 0, - errmsg: "Not enough money to complete transaction", - code: 500, - }], + warnings: [{index: 0, errmsg: "Not enough money to complete transaction", code: 500}], otherProperty: "property-value", }; mockPayMoney.mockReturnValue(expectedPayMoneyReturn); @@ -1623,11 +1542,11 @@ describe("InsuranceController", () => vi.spyOn(insuranceController.profileHelper, "getPmcProfile").mockReturnValue({ Inventory: { - items: [ - {_id: "itemId1", _tpl: "itemTpl1", otherProperty: "property-value1"}, - {_id: "itemId2", _tpl: "itemTpl2", otherProperty: "property-value2"}, - {_id: "itemId3", _tpl: "itemTpl3", otherProperty: "property-value3"}, - ], + items: [{_id: "itemId1", _tpl: "itemTpl1", otherProperty: "property-value1"}, { + _id: "itemId2", + _tpl: "itemTpl2", + otherProperty: "property-value2", + }, {_id: "itemId3", _tpl: "itemTpl3", otherProperty: "property-value3"}], }, }); }); @@ -1664,23 +1583,16 @@ describe("InsuranceController", () => it("should return the expected cost for each item and trader", () => { - const request = { - traders: ["prapor", "therapist"], - items: ["itemId1", "itemId2", "itemId3"], - }; + const request = {traders: ["prapor", "therapist"], items: ["itemId1", "itemId2", "itemId3"]}; const expected = { prapor: {itemTpl1: 100, itemTpl2: 200, itemTpl3: 300}, therapist: {itemTpl1: 150, itemTpl2: 250, itemTpl3: 350}, }; // Mock the InsuranceService.getPremium method to return the expected values. - vi.spyOn(insuranceController.insuranceService, "getPremium") - .mockReturnValueOnce(100) - .mockReturnValueOnce(200) - .mockReturnValueOnce(300) - .mockReturnValueOnce(150) - .mockReturnValueOnce(250) - .mockReturnValueOnce(350); + vi.spyOn(insuranceController.insuranceService, "getPremium").mockReturnValueOnce(100).mockReturnValueOnce( + 200, + ).mockReturnValueOnce(300).mockReturnValueOnce(150).mockReturnValueOnce(250).mockReturnValueOnce(350); const result = insuranceController.cost(request, sessionId); @@ -1697,14 +1609,12 @@ describe("InsuranceController", () => "itemId4", // Doesn't exist in the player's inventory. ], }; - const expected = { - prapor: {itemTpl1: 100, itemTpl2: 200}, - }; + const expected = {prapor: {itemTpl1: 100, itemTpl2: 200}}; // Mock the InsuranceService.getPremium method to return the expected values. - vi.spyOn(insuranceController.insuranceService, "getPremium") - .mockReturnValueOnce(100) - .mockReturnValueOnce(200); + vi.spyOn(insuranceController.insuranceService, "getPremium").mockReturnValueOnce(100).mockReturnValueOnce( + 200, + ); const result = insuranceController.cost(request, sessionId); diff --git a/project/tests/generators/BotGenerator.test.ts b/project/tests/generators/BotGenerator.test.ts index 2072430e..c8f72397 100644 --- a/project/tests/generators/BotGenerator.test.ts +++ b/project/tests/generators/BotGenerator.test.ts @@ -59,19 +59,11 @@ describe("BotGenerator", () => { botGenerator.botConfig.chanceAssaultScavHasPlayerScavName = 0; - const mockPlayerProfile = { - Info: { - Nickname: "Player Nickname", - Level: 1, - }, - }; + const mockPlayerProfile = {Info: {Nickname: "Player Nickname", Level: 1}}; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); - const botJsonTemplate = { - firstName: ["test"], - lastName: [], - }; + const botJsonTemplate = {firstName: ["test"], lastName: []}; const sessionId = "sessionId"; const isPlayerScav = false; @@ -85,18 +77,10 @@ describe("BotGenerator", () => { botGenerator.botConfig.showTypeInNickname = true; - const mockPlayerProfile = { - Info: { - Nickname: "Player Nickname", - Level: 1, - }, - }; + const mockPlayerProfile = {Info: {Nickname: "Player Nickname", Level: 1}}; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); - const botJsonTemplate = { - firstName: ["test"], - lastName: [], - }; + const botJsonTemplate = {firstName: ["test"], lastName: []}; const sessionId = "sessionId"; const isPlayerScav = false; @@ -111,19 +95,11 @@ describe("BotGenerator", () => botGenerator.botConfig.showTypeInNickname = false; botGenerator.pmcConfig.addPrefixToSameNamePMCAsPlayerChance = 100; - const mockPlayerProfile = { - Info: { - Nickname: "Player", - Level: 1, - }, - }; + const mockPlayerProfile = {Info: {Nickname: "Player", Level: 1}}; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); vi.spyOn(botGenerator.localisationService, "getRandomTextThatMatchesPartialKey").mockReturnValue("test"); - const botJsonTemplate = { - firstName: ["Player"], - lastName: [], - }; + const botJsonTemplate = {firstName: ["Player"], lastName: []}; const sessionId = "sessionId"; const isPlayerScav = false; @@ -137,18 +113,10 @@ describe("BotGenerator", () => { botGenerator.botConfig.chanceAssaultScavHasPlayerScavName = 100; - const mockPlayerProfile = { - Info: { - Nickname: "Player", - Level: 1, - }, - }; + const mockPlayerProfile = {Info: {Nickname: "Player", Level: 1}}; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); - const botJsonTemplate = { - firstName: ["test"], - lastName: [], - }; + const botJsonTemplate = {firstName: ["test"], lastName: []}; const sessionId = "sessionId"; const isPlayerScav = true; @@ -164,18 +132,10 @@ describe("BotGenerator", () => botGenerator.databaseServer.getTables().bots.types.usec.firstName = ["usec"]; botGenerator.databaseServer.getTables().bots.types.bear.firstName = []; - const mockPlayerProfile = { - Info: { - Nickname: "Player", - Level: 1, - }, - }; + const mockPlayerProfile = {Info: {Nickname: "Player", Level: 1}}; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); - const botJsonTemplate = { - firstName: ["test"], - lastName: [], - }; + const botJsonTemplate = {firstName: ["test"], lastName: []}; const sessionId = "sessionId"; const isPlayerScav = false; diff --git a/project/tests/generators/BotLevelGenerator.test.ts b/project/tests/generators/BotLevelGenerator.test.ts index dc04eef4..762cb99f 100644 --- a/project/tests/generators/BotLevelGenerator.test.ts +++ b/project/tests/generators/BotLevelGenerator.test.ts @@ -27,10 +27,7 @@ describe("BotLevelGenerator", () => { it("should return value between 5 and 10 when player is level 5 and max is 10", () => { - const levelDetails: MinMax = { - min: 5, - max: 10, - }; + const levelDetails: MinMax = {min: 5, max: 10}; const botGenerationDetails: BotGenerationDetails = { isPmc: false, @@ -53,10 +50,7 @@ describe("BotLevelGenerator", () => { it("should return 10 when player level is 5 and delta is 5", () => { - const levelDetails: MinMax = { - min: 5, - max: 10, - }; + const levelDetails: MinMax = {min: 5, max: 10}; const expTable = databaseServer.getTables().globals.config.exp.level.exp_table; @@ -67,10 +61,7 @@ describe("BotLevelGenerator", () => it("should return 79 when player level is above possible max (100), desired max is 100 and delta is 5", () => { - const levelDetails: MinMax = { - min: 100, - max: 100, - }; + const levelDetails: MinMax = {min: 100, max: 100}; const expTable = databaseServer.getTables().globals.config.exp.level.exp_table; const playerLevel = 100; diff --git a/project/tests/helpers/InRaidHelper.test.ts b/project/tests/helpers/InRaidHelper.test.ts index a6c65bd0..965ea126 100644 --- a/project/tests/helpers/InRaidHelper.test.ts +++ b/project/tests/helpers/InRaidHelper.test.ts @@ -24,16 +24,7 @@ describe("InRaidHelper", () => it("should return negative value when player kills 2 scavs as scav", () => { const fenceStanding = 0; - const postRaidPlayerVictims = [ - { - Side: "Savage", - Role: "assault", - }, - { - Side: "Savage", - Role: "assault", - }, - ]; // Kills + const postRaidPlayerVictims = [{Side: "Savage", Role: "assault"}, {Side: "Savage", Role: "assault"}]; // Kills const databaseServer = container.resolve("DatabaseServer"); const scavStandingChangeOnKill = databaseServer.getTables().bots.types.assault.experience.standingForKill; @@ -46,16 +37,7 @@ describe("InRaidHelper", () => it("should return positive value when player kills 2 PMCs of different sides as scav", () => { const fenceStanding = 0; - const postRaidPlayerVictims = [ - { - Side: "Usec", - Role: "sptUsec", - }, - { - Side: "Bear", - Role: "sptBear", - }, - ]; // Kills + const postRaidPlayerVictims = [{Side: "Usec", Role: "sptUsec"}, {Side: "Bear", Role: "sptBear"}]; // Kills const databaseServer = container.resolve("DatabaseServer"); const bearStandingChangeOnKill = databaseServer.getTables().bots.types.bear.experience.standingForKill; @@ -69,24 +51,10 @@ describe("InRaidHelper", () => it("should return negative value when player kills 1 PMC, 1 boss and 2 scavs as scav", () => { const fenceStanding = 0; - const postRaidPlayerVictims = [ - { - Side: "Usec", - Role: "sptUsec", - }, - { - Side: "savage", - Role: "assault", - }, - { - Side: "savage", - Role: "bossBoar", - }, - { - Side: "savage", - Role: "assault", - }, - ]; // Kills + const postRaidPlayerVictims = [{Side: "Usec", Role: "sptUsec"}, {Side: "savage", Role: "assault"}, { + Side: "savage", + Role: "bossBoar", + }, {Side: "savage", Role: "assault"}]; // Kills const databaseServer = container.resolve("DatabaseServer"); const usecStandingChangeOnKill = databaseServer.getTables().bots.types.bear.experience.standingForKill; @@ -104,12 +72,7 @@ describe("InRaidHelper", () => it("should return 0 when player kills bot with undefined standing as scav", () => { const fenceStanding = 0; - const postRaidPlayerVictims = [ - { - Side: "savage", - Role: "testRole", - }, - ]; // Kills + const postRaidPlayerVictims = [{Side: "savage", Role: "testRole"}]; // Kills // Fake getFenceStandingChangeForKillAsScav() returning null vi.spyOn(inraidHelper, "getFenceStandingChangeForKillAsScav").mockReturnValueOnce(null).mockReturnValueOnce( diff --git a/project/tests/helpers/ItemHelper.test.ts b/project/tests/helpers/ItemHelper.test.ts index ba98a991..b00addb7 100644 --- a/project/tests/helpers/ItemHelper.test.ts +++ b/project/tests/helpers/ItemHelper.test.ts @@ -249,10 +249,7 @@ describe("ItemHelper", () => { it("should set upd.StackObjectsCount to 1 if upd is undefined", () => { - const initialItem: Item = { - _id: "", - _tpl: "", - }; + const initialItem: Item = {_id: "", _tpl: ""}; const fixedItem = itemHelper.fixItemStackCount(initialItem); expect(fixedItem.upd).toBeDefined(); @@ -261,11 +258,7 @@ describe("ItemHelper", () => it("should set upd.StackObjectsCount to 1 if upd.StackObjectsCount is undefined", () => { - const initialItem: Item = { - _id: "", - _tpl: "", - upd: {}, - }; + const initialItem: Item = {_id: "", _tpl: "", upd: {}}; const fixedItem = itemHelper.fixItemStackCount(initialItem); expect(fixedItem.upd).toBeDefined(); @@ -274,13 +267,7 @@ describe("ItemHelper", () => it("should not change upd.StackObjectsCount if it is already defined", () => { - const initialItem: Item = { - _id: "", - _tpl: "", - upd: { - StackObjectsCount: 5, - }, - }; + const initialItem: Item = {_id: "", _tpl: "", upd: {StackObjectsCount: 5}}; const fixedItem = itemHelper.fixItemStackCount(initialItem); expect(fixedItem.upd).toBeDefined(); @@ -465,12 +452,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "5b40e1525acfc4771e1c6611", // "HighCom Striker ULACH IIIA helmet (Black)" - upd: { - Repairable: { - Durability: 19, - MaxDurability: 38, - }, - }, + upd: {Repairable: {Durability: 19, MaxDurability: 38}}, }; const result = itemHelper.getItemQualityModifier(item); @@ -484,12 +466,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "5a38e6bac4a2826c6e06d79b", // "TOZ-106 20ga bolt-action shotgun" - upd: { - Repairable: { - Durability: 20, - MaxDurability: 100, - }, - }, + upd: {Repairable: {Durability: 20, MaxDurability: 100}}, }; const result = itemHelper.getItemQualityModifier(item); @@ -521,11 +498,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "5780cf7f2459777de4559322", // "Dorm room 314 marked key" - upd: { - Key: { - NumberOfUsages: 5, - }, - }, + upd: {Key: {NumberOfUsages: 5}}, }; const result = itemHelper.getItemQualityModifier(item); @@ -558,11 +531,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" - upd: { - RepairKit: { - Resource: 600, - }, - }, + upd: {RepairKit: {Resource: 600}}, }; const result = itemHelper.getItemQualityModifier(item); @@ -576,11 +545,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" - upd: { - RepairKit: { - Resource: 0, - }, - }, + upd: {RepairKit: {Resource: 0}}, }; const result = itemHelper.getItemQualityModifier(item); @@ -594,10 +559,7 @@ describe("ItemHelper", () => it("should return the correct quality value for armor items", () => { const armor = itemHelper.getItem("5648a7494bdc2d9d488b4583")[1]; // "PACA Soft Armor" - const repairable: Repairable = { - Durability: 25, - MaxDurability: 50, - }; + const repairable: Repairable = {Durability: 25, MaxDurability: 50}; const item: Item = { // Not used for armor, but required for the method. _id: "", _tpl: "", @@ -630,14 +592,8 @@ describe("ItemHelper", () => it("should return the correct quality value for weapon items", () => { const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" - const repairable: Repairable = { - Durability: 50, - MaxDurability: 100, - }; - const item: Item = { - _id: "", - _tpl: "", - }; + const repairable: Repairable = {Durability: 50, MaxDurability: 100}; + const item: Item = {_id: "", _tpl: ""}; // Cast the method to any to allow access to private/protected method. const result = (itemHelper as any).getRepairableItemQualityValue(weapon, repairable, item); @@ -653,10 +609,7 @@ describe("ItemHelper", () => Durability: 50, MaxDurability: 200, // This should be used now. }; - const item: Item = { - _id: "", - _tpl: "", - }; + const item: Item = {_id: "", _tpl: ""}; // Cast the method to any to allow access to private/protected method. const result = (itemHelper as any).getRepairableItemQualityValue(weapon, repairable, item); @@ -672,10 +625,7 @@ describe("ItemHelper", () => Durability: 50, MaxDurability: undefined, // Remove the MaxDurability property value... Technically an invalid Type. }; - const item: Item = { - _id: "", - _tpl: "", - }; + const item: Item = {_id: "", _tpl: ""}; // Mock the logger's error method to prevent it from being actually called. const loggerErrorSpy = vi.spyOn((itemHelper as any).logger, "error").mockImplementation(() => @@ -696,10 +646,7 @@ describe("ItemHelper", () => Durability: 50, MaxDurability: 0, // This is a problem. }; - const item: Item = { - _id: "", - _tpl: "", - }; + const item: Item = {_id: "", _tpl: ""}; // Cast the method to any to allow access to private/protected method. const result = (itemHelper as any).getRepairableItemQualityValue(weapon, repairable, item); @@ -715,10 +662,7 @@ describe("ItemHelper", () => Durability: 50, MaxDurability: undefined, // Remove the MaxDurability property value... Technically an invalid Type. }; - const item: Item = { - _id: "", - _tpl: "", - }; + const item: Item = {_id: "", _tpl: ""}; const loggerErrorSpy = vi.spyOn((itemHelper as any).logger, "error"); @@ -733,44 +677,40 @@ describe("ItemHelper", () => { it("should return an array containing only the parent ID when no children are found", () => { - const items: Item[] = [ - {_id: "1", _tpl: "", parentId: null}, - {_id: "2", _tpl: "", parentId: null}, - {_id: "3", _tpl: "", parentId: "2"}, - ]; + const items: Item[] = [{_id: "1", _tpl: "", parentId: null}, {_id: "2", _tpl: "", parentId: null}, { + _id: "3", + _tpl: "", + parentId: "2", + }]; const result = itemHelper.findAndReturnChildrenByItems(items, "1"); expect(result).toEqual(["1"]); }); it("should return array of child IDs when single-level children are found", () => { - const items: Item[] = [ - {_id: "1", _tpl: "", parentId: null}, - {_id: "2", _tpl: "", parentId: "1"}, - {_id: "3", _tpl: "", parentId: "1"}, - ]; + const items: Item[] = [{_id: "1", _tpl: "", parentId: null}, {_id: "2", _tpl: "", parentId: "1"}, { + _id: "3", + _tpl: "", + parentId: "1", + }]; const result = itemHelper.findAndReturnChildrenByItems(items, "1"); expect(result).toEqual(["2", "3", "1"]); }); it("should return array of child IDs when multi-level children are found", () => { - const items: Item[] = [ - {_id: "1", _tpl: "", parentId: null}, - {_id: "2", _tpl: "", parentId: "1"}, - {_id: "3", _tpl: "", parentId: "2"}, - {_id: "4", _tpl: "", parentId: "3"}, - ]; + const items: Item[] = [{_id: "1", _tpl: "", parentId: null}, {_id: "2", _tpl: "", parentId: "1"}, { + _id: "3", + _tpl: "", + parentId: "2", + }, {_id: "4", _tpl: "", parentId: "3"}]; const result = itemHelper.findAndReturnChildrenByItems(items, "1"); expect(result).toEqual(["4", "3", "2", "1"]); }); it("should return an array containing only the parent ID when parent ID does not exist in items", () => { - const items: Item[] = [ - {_id: "1", _tpl: "", parentId: null}, - {_id: "2", _tpl: "", parentId: "1"}, - ]; + const items: Item[] = [{_id: "1", _tpl: "", parentId: null}, {_id: "2", _tpl: "", parentId: "1"}]; const result = itemHelper.findAndReturnChildrenByItems(items, "3"); expect(result).toEqual(["3"]); }); @@ -807,9 +747,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" - upd: { - StackObjectsCount: 5, - }, + upd: {StackObjectsCount: 5}, }; const result = itemHelper.getItemStackSize(item); expect(result).toBe(5); @@ -824,10 +762,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" - upd: { - BuyRestrictionCurrent: 0, - BuyRestrictionMax: 1, - }, + upd: {BuyRestrictionCurrent: 0, BuyRestrictionMax: 1}, }; const result = itemHelper.hasBuyRestrictions(item); expect(result).toBe(true); @@ -1089,15 +1024,7 @@ describe("ItemHelper", () => const mockTemplateItem = { _id: "571a29dc2459771fb2755a6a", _name: "mag_tt_toz_std_762x25tt_8", - _props: { - Cartridges: [{ - _props: { - filters: [{ - Filter: validAmmoItems, - }], - }, - }], - }, + _props: {Cartridges: [{_props: {filters: [{Filter: validAmmoItems}]}}]}, }; vi.spyOn((itemHelper as any).randomUtil, "getArrayValue").mockReturnValue(validAmmoItems[0]); @@ -1109,13 +1036,7 @@ describe("ItemHelper", () => it("should return null when passed template has empty cartridge property", () => { - const fakeTemplateItem = { - _props: { - Cartridges: [ - {}, - ], - }, - }; + const fakeTemplateItem = {_props: {Cartridges: [{}]}}; const result = itemHelper.getRandomCompatibleCaliberTemplateId(fakeTemplateItem as ITemplateItem); expect(result).toBe(null); diff --git a/project/tests/services/PaymentService.test.ts b/project/tests/services/PaymentService.test.ts index 33275d68..9e78fa02 100644 --- a/project/tests/services/PaymentService.test.ts +++ b/project/tests/services/PaymentService.test.ts @@ -50,16 +50,8 @@ describe("PaymentService", () => // Object representing the player's PMC inventory. const pmcData = { - TradersInfo: { - [traderId]: { - salesSum: 0, - unlocked: true, - disabled: false, - }, - }, - Inventory: { - items: [moneyItem], - }, + TradersInfo: {[traderId]: {salesSum: 0, unlocked: true, disabled: false}}, + Inventory: {items: [moneyItem]}, } as unknown as IPmcData; // Buy a factory map from Therapist... although it doesn't really matter what the item is as there's no @@ -71,12 +63,7 @@ describe("PaymentService", () => item_id: purchaseItemId, count: purchaseQuantity, scheme_id: 0, - scheme_items: [ - { - id: costItemId, - count: costAmount, - }, - ], + scheme_items: [{id: costItemId, count: costAmount}], } as IProcessBuyTradeRequestData; // Inconsequential profile ID @@ -84,16 +71,7 @@ describe("PaymentService", () => const itemEventRouterResponse = { warnings: [], - profileChanges: { - sessionID: { - _id: sessionID, - items: { - new: [], - change: [], - del: [], - }, - }, - }, + profileChanges: {sessionID: {_id: sessionID, items: {new: [], change: [], del: []}}}, } as unknown as IItemEventRouterResponse; // Mock the logger debug method to return void. @@ -102,25 +80,13 @@ describe("PaymentService", () => // Mock the trader helper to return a trader with the currency of Roubles. const traderHelperGetTraderSpy = vi.spyOn((paymentService as any).traderHelper, "getTrader") - .mockReturnValue({ - tid: traderId, - currency: "RUB", - } as unknown as ITraderBase); + .mockReturnValue({tid: traderId, currency: "RUB"} as unknown as ITraderBase); // Mock the addPaymentToOutput method to subtract the item cost from the money stack. const addPaymentToOutputSpy = vi.spyOn(paymentService as any, "addPaymentToOutput").mockImplementation(() => { moneyItem.upd.StackObjectsCount -= costAmount; - return { - warnings: [], - profileChanges: { - [sessionID]: { - items: { - change: [moneyItem], - }, - }, - }, - }; + return {warnings: [], profileChanges: {[sessionID]: {items: {change: [moneyItem]}}}}; }); // Mock the traderHelper lvlUp method to return void. diff --git a/project/vitest.config.ts b/project/vitest.config.ts index 44ba8b7f..166961b4 100644 --- a/project/vitest.config.ts +++ b/project/vitest.config.ts @@ -7,9 +7,7 @@ export default defineConfig({ reporters: ["default"], root: "./", include: ["**/*.{test,spec}.?(c|m)[jt]s?(x)"], - cache: { - dir: "./tests/__cache__", - }, + cache: {dir: "./tests/__cache__"}, environment: "./tests/CustomEnvironment.ts", globals: true, coverage: { @@ -22,15 +20,7 @@ export default defineConfig({ exclude: ["src/models/**", "tests/**"], }, pool: "threads", - poolOptions: { - threads: { - singleThread: true, - isolate: false, - }, - }, - alias: { - "@spt-aki": path.resolve(__dirname, "src"), - "@tests": path.resolve(__dirname, "tests"), - }, + poolOptions: {threads: {singleThread: true, isolate: false}}, + alias: {"@spt-aki": path.resolve(__dirname, "src"), "@tests": path.resolve(__dirname, "tests")}, }, }); From 0793df60c23ca132ac4eaecd8245c283561a2b11 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 13 Nov 2023 12:38:16 -0500 Subject: [PATCH 41/41] Formatting Change - Space is now given around object properties. --- project/dprint.json | 8 +- project/gulpfile.mjs | 25 +- project/src/ErrorHandler.ts | 2 +- .../src/callbacks/CustomizationCallbacks.ts | 5 +- project/src/callbacks/DialogueCallbacks.ts | 8 +- project/src/callbacks/GameCallbacks.ts | 6 +- project/src/callbacks/NotifierCallbacks.ts | 2 +- project/src/callbacks/ProfileCallbacks.ts | 8 +- project/src/controllers/BotController.ts | 2 +- .../controllers/CustomizationController.ts | 2 +- project/src/controllers/DialogueController.ts | 2 +- project/src/controllers/GameController.ts | 8 +- project/src/controllers/HealthController.ts | 4 +- project/src/controllers/HideoutController.ts | 22 +- .../src/controllers/InsuranceController.ts | 10 +- .../src/controllers/InventoryController.ts | 28 +- project/src/controllers/LocationController.ts | 4 +- project/src/controllers/MatchController.ts | 6 +- project/src/controllers/NoteController.ts | 2 +- .../src/controllers/PresetBuildController.ts | 10 +- project/src/controllers/ProfileController.ts | 6 +- project/src/controllers/QuestController.ts | 4 +- project/src/controllers/RagfairController.ts | 12 +- .../controllers/RepeatableQuestController.ts | 8 +- project/src/controllers/TradeController.ts | 6 +- project/src/controllers/WeatherController.ts | 2 +- project/src/di/Container.ts | 418 +++++++++--------- .../generators/BotEquipmentModGenerator.ts | 7 +- project/src/generators/BotGenerator.ts | 2 +- .../src/generators/BotInventoryGenerator.ts | 16 +- project/src/generators/BotLevelGenerator.ts | 2 +- project/src/generators/BotWeaponGenerator.ts | 12 +- .../generators/FenceBaseAssortGenerator.ts | 2 +- project/src/generators/LocationGenerator.ts | 24 +- project/src/generators/LootGenerator.ts | 12 +- project/src/generators/PlayerScavGenerator.ts | 6 +- .../src/generators/RagfairAssortGenerator.ts | 2 +- .../src/generators/RagfairOfferGenerator.ts | 22 +- .../generators/RepeatableQuestGenerator.ts | 29 +- .../src/generators/ScavCaseRewardGenerator.ts | 6 +- project/src/helpers/AssortHelper.ts | 6 +- project/src/helpers/BotGeneratorHelper.ts | 36 +- .../src/helpers/BotWeaponGeneratorHelper.ts | 4 +- project/src/helpers/DialogueHelper.ts | 6 +- project/src/helpers/HealthHelper.ts | 6 +- project/src/helpers/HideoutHelper.ts | 19 +- project/src/helpers/HttpServerHelper.ts | 2 +- project/src/helpers/InRaidHelper.ts | 2 +- project/src/helpers/InventoryHelper.ts | 32 +- project/src/helpers/ItemHelper.ts | 6 +- project/src/helpers/NotifierHelper.ts | 2 +- project/src/helpers/ProfileHelper.ts | 10 +- project/src/helpers/QuestHelper.ts | 4 +- project/src/helpers/RagfairOfferHelper.ts | 2 +- project/src/helpers/RagfairSellHelper.ts | 2 +- project/src/helpers/RepairHelper.ts | 2 +- project/src/helpers/TraderAssortHelper.ts | 2 +- project/src/helpers/TraderHelper.ts | 4 +- project/src/helpers/WeightedRandomHelper.ts | 8 +- project/src/loaders/PreAkiModLoader.ts | 10 +- project/src/models/external/HttpFramework.ts | 6 +- .../src/models/spt/server/IDatabaseTables.ts | 2 +- project/src/routers/EventOutputHolder.ts | 10 +- .../routers/save_load/HealthSaveLoadRouter.ts | 2 +- .../routers/save_load/InraidSaveLoadRouter.ts | 2 +- .../save_load/ProfileSaveLoadRouter.ts | 2 +- project/src/servers/SaveServer.ts | 4 +- project/src/servers/WebSocketServer.ts | 4 +- project/src/servers/http/AkiHttpListener.ts | 4 +- .../src/services/BotWeaponModLimitService.ts | 6 +- project/src/services/FenceService.ts | 20 +- project/src/services/GiftService.ts | 2 +- project/src/services/InsuranceService.ts | 6 +- project/src/services/MailSendService.ts | 2 +- project/src/services/ModCompilerService.ts | 2 +- project/src/services/PaymentService.ts | 2 +- project/src/services/PlayerService.ts | 2 +- project/src/services/ProfileFixerService.ts | 15 +- project/src/services/RagfairPriceService.ts | 12 +- project/src/services/RepairService.ts | 8 +- project/src/services/mod/CustomItemService.ts | 2 +- .../dynamicRouter/DynamicRouterModService.ts | 2 +- .../services/mod/onLoad/OnLoadModService.ts | 2 +- .../mod/onUpdate/OnUpdateModService.ts | 2 +- .../staticRouter/StaticRouterModService.ts | 2 +- project/src/utils/HttpResponseUtil.ts | 4 +- project/src/utils/JsonUtil.ts | 2 +- project/src/utils/RandomUtil.ts | 8 +- project/src/utils/VFS.ts | 20 +- .../utils/logging/AbstractWinstonLogger.ts | 34 +- project/tests/CustomEnvironment.ts | 2 +- .../__factories__/ProfileInsurance.factory.ts | 2 +- .../__fixture__/profileInsurance.fixture.ts | 284 ++++++------ .../controllers/InsuranceController.test.ts | 60 +-- project/tests/generators/BotGenerator.test.ts | 20 +- .../generators/BotLevelGenerator.test.ts | 6 +- project/tests/helpers/InRaidHelper.test.ts | 10 +- project/tests/helpers/ItemHelper.test.ts | 48 +- project/tests/services/PaymentService.test.ts | 12 +- project/vitest.config.ts | 6 +- 100 files changed, 813 insertions(+), 755 deletions(-) diff --git a/project/dprint.json b/project/dprint.json index d264a421..96405138 100644 --- a/project/dprint.json +++ b/project/dprint.json @@ -22,10 +22,10 @@ "typeLiteral.separatorKind": "semiColon", "enumDeclaration.memberSpacing": "newLine", "spaceAround": false, - "spaceSurroundingProperties": false, - "objectExpression.spaceSurroundingProperties": false, - "objectPattern.spaceSurroundingProperties": false, - "typeLiteral.spaceSurroundingProperties": false, + "spaceSurroundingProperties": true, + "objectExpression.spaceSurroundingProperties": true, + "objectPattern.spaceSurroundingProperties": true, + "typeLiteral.spaceSurroundingProperties": true, "binaryExpression.spaceSurroundingBitwiseAndArithmeticOperator": true, "commentLine.forceSpaceAfterSlashes": true, "constructor.spaceBeforeParentheses": false, diff --git a/project/gulpfile.mjs b/project/gulpfile.mjs index c856b25f..476c1797 100644 --- a/project/gulpfile.mjs +++ b/project/gulpfile.mjs @@ -8,7 +8,7 @@ import rename from "gulp-rename"; import pkg from "pkg"; import pkgfetch from "pkg-fetch"; import * as ResEdit from "resedit"; -import manifest from "./package.json" assert {type: "json"}; +import manifest from "./package.json" assert { type: "json" }; const nodeVersion = "node18"; // As of pkg-fetch v3.5, it's v18.15.0 const stdio = "inherit"; @@ -27,7 +27,7 @@ const licenseFile = "../LICENSE.md"; /** * Transpile src files into Javascript with SWC */ -const compile = async () => await exec("swc src -d obj", {stdio}); +const compile = async () => await exec("swc src -d obj", { stdio }); // Packaging const fetchPackageImage = async () => @@ -74,14 +74,14 @@ const updateBuildProperties = async () => const vi = ResEdit.Resource.VersionInfo.fromEntries(res.entries)[0]; - vi.setStringValues({lang: 1033, codepage: 1200}, { + vi.setStringValues({ lang: 1033, codepage: 1200 }, { ProductName: manifest.author, FileDescription: manifest.description, CompanyName: manifest.name, LegalCopyright: manifest.license, }); - vi.removeStringValue({lang: 1033, codepage: 1200}, "OriginalFilename"); - vi.removeStringValue({lang: 1033, codepage: 1200}, "InternalName"); + vi.removeStringValue({ lang: 1033, codepage: 1200 }, "OriginalFilename"); + vi.removeStringValue({ lang: 1033, codepage: 1200 }, "InternalName"); vi.setFileVersion(...manifest.version.split(".").map(Number)); vi.setProductVersion(...manifest.version.split(".").map(Number)); vi.outputToResourceEntries(res.entries); @@ -120,7 +120,7 @@ const writeCommitHashToCoreJSON = async () => const parsed = JSON.parse(coreJSON); // Fetch the latest Git commit hash - const gitResult = await exec("git rev-parse HEAD", {stdout: "pipe"}); + const gitResult = await exec("git rev-parse HEAD", { stdout: "pipe" }); // Update the commit hash in the core.json object parsed.commit = gitResult.stdout.trim() || ""; @@ -154,12 +154,12 @@ const addAssets = gulp.series(copyAssets, copyExecutables, copyLicense, writeCom /** * Cleans the build directory. */ -const cleanBuild = async () => await fs.rm(buildDir, {recursive: true, force: true}); +const cleanBuild = async () => await fs.rm(buildDir, { recursive: true, force: true }); /** * Cleans the transpiled javascript directory. */ -const cleanCompiled = async () => await fs.rm("./obj", {recursive: true, force: true}); +const cleanCompiled = async () => await fs.rm("./obj", { recursive: true, force: true }); /** * Recursively builds an array of paths for json files. @@ -305,11 +305,14 @@ gulp.task("build:debug", build("debug")); gulp.task("build:release", build("release")); gulp.task("build:bleeding", build("bleeding")); -gulp.task("run:build", async () => await exec("Aki.Server.exe", {stdio, cwd: buildDir})); -gulp.task("run:debug", async () => await exec("ts-node-dev -r tsconfig-paths/register src/ide/TestEntry.ts", {stdio})); +gulp.task("run:build", async () => await exec("Aki.Server.exe", { stdio, cwd: buildDir })); +gulp.task( + "run:debug", + async () => await exec("ts-node-dev -r tsconfig-paths/register src/ide/TestEntry.ts", { stdio }), +); 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/ide/TestEntry.js", { stdio }); }); diff --git a/project/src/ErrorHandler.ts b/project/src/ErrorHandler.ts index afb88de9..b8b286ac 100644 --- a/project/src/ErrorHandler.ts +++ b/project/src/ErrorHandler.ts @@ -12,7 +12,7 @@ export class ErrorHandler constructor() { this.logger = new WinstonMainLogger(new AsyncQueue()); - this.readLine = readline.createInterface({input: process.stdin, output: process.stdout}); + this.readLine = readline.createInterface({ input: process.stdin, output: process.stdout }); } public handleCriticalError(err: Error): void diff --git a/project/src/callbacks/CustomizationCallbacks.ts b/project/src/callbacks/CustomizationCallbacks.ts index 9d4cec90..35c85210 100644 --- a/project/src/callbacks/CustomizationCallbacks.ts +++ b/project/src/callbacks/CustomizationCallbacks.ts @@ -28,7 +28,10 @@ export class CustomizationCallbacks */ public getSuits(url: string, info: IEmptyRequestData, sessionID: string): IGetBodyResponseData { - const result: IGetSuitsResponse = {_id: `pmc${sessionID}`, suites: this.saveServer.getProfile(sessionID).suits}; + const result: IGetSuitsResponse = { + _id: `pmc${sessionID}`, + suites: this.saveServer.getProfile(sessionID).suits, + }; return this.httpResponse.getBody(result); } diff --git a/project/src/callbacks/DialogueCallbacks.ts b/project/src/callbacks/DialogueCallbacks.ts index a1298527..23221dbe 100644 --- a/project/src/callbacks/DialogueCallbacks.ts +++ b/project/src/callbacks/DialogueCallbacks.ts @@ -75,7 +75,7 @@ export class DialogueCallbacks implements OnUpdate VersionId: "bgkidft87ddd", // TODO: Is this... correct? Ip: "", Port: 0, - Chats: [{_id: "0", Members: 0}], + Chats: [{ _id: "0", Members: 0 }], }; return this.httpResponse.getBody([chatServer]); @@ -181,7 +181,7 @@ export class DialogueCallbacks implements OnUpdate sessionID: string, ): IGetBodyResponseData { - return this.httpResponse.getBody({status: 0, requestid: "12345", retryAfter: 600}); + return this.httpResponse.getBody({ status: 0, requestid: "12345", retryAfter: 600 }); } /** @@ -215,13 +215,13 @@ export class DialogueCallbacks implements OnUpdate } /** Handle client/friend/ignore/set */ - public ignoreFriend(url: string, request: {uid: string;}, sessionID: string): any + public ignoreFriend(url: string, request: { uid: string; }, sessionID: string): any { return this.httpResponse.nullResponse(); } /** Handle client/friend/ignore/remove */ - public unIgnoreFriend(url: string, request: {uid: string;}, sessionID: string): any + public unIgnoreFriend(url: string, request: { uid: string; }, sessionID: string): any { return this.httpResponse.nullResponse(); } diff --git a/project/src/callbacks/GameCallbacks.ts b/project/src/callbacks/GameCallbacks.ts index 0b712181..20712f55 100644 --- a/project/src/callbacks/GameCallbacks.ts +++ b/project/src/callbacks/GameCallbacks.ts @@ -58,7 +58,7 @@ export class GameCallbacks implements OnLoad const today = new Date().toUTCString(); const startTimeStampMS = Date.parse(today); this.gameController.gameStart(url, info, sessionID, startTimeStampMS); - return this.httpResponse.getBody({utc_time: startTimeStampMS / 1000}); + return this.httpResponse.getBody({ utc_time: startTimeStampMS / 1000 }); } /** @@ -73,7 +73,7 @@ export class GameCallbacks implements OnLoad ): IGetBodyResponseData { this.saveServer.save(); - return this.httpResponse.getBody({status: "ok"}); + return this.httpResponse.getBody({ status: "ok" }); } /** @@ -140,7 +140,7 @@ export class GameCallbacks implements OnLoad */ public getVersion(url: string, info: IEmptyRequestData, sessionID: string): string { - return this.httpResponse.noBody({Version: this.watermark.getInGameVersionLabel()}); + return this.httpResponse.noBody({ Version: this.watermark.getInGameVersionLabel() }); } public reportNickname(url: string, info: IReportNicknameRequestData, sessionID: string): INullResponseData diff --git a/project/src/callbacks/NotifierCallbacks.ts b/project/src/callbacks/NotifierCallbacks.ts index 61df5e1a..b5509d2f 100644 --- a/project/src/callbacks/NotifierCallbacks.ts +++ b/project/src/callbacks/NotifierCallbacks.ts @@ -68,7 +68,7 @@ export class NotifierCallbacks sessionID: string, ): IGetBodyResponseData { - return this.httpResponse.getBody({status: "ok"}); + return this.httpResponse.getBody({ status: "ok" }); } public notify(url: string, info: any, sessionID: string): string diff --git a/project/src/callbacks/ProfileCallbacks.ts b/project/src/callbacks/ProfileCallbacks.ts index 7ba9eac8..55f89db2 100644 --- a/project/src/callbacks/ProfileCallbacks.ts +++ b/project/src/callbacks/ProfileCallbacks.ts @@ -34,7 +34,7 @@ export class ProfileCallbacks public createProfile(url: string, info: IProfileCreateRequestData, sessionID: string): IGetBodyResponseData { this.profileController.createProfile(info, sessionID); - return this.httpResponse.getBody({uid: `pmc${sessionID}`}); + return this.httpResponse.getBody({ uid: `pmc${sessionID}` }); } /** @@ -91,7 +91,7 @@ export class ProfileCallbacks return this.httpResponse.getBody(null, 1, "The nickname is too short"); } - return this.httpResponse.getBody({status: 0, nicknamechangedate: this.timeUtil.getTimestamp()}); + return this.httpResponse.getBody({ status: 0, nicknamechangedate: this.timeUtil.getTimestamp() }); } /** @@ -115,7 +115,7 @@ export class ProfileCallbacks return this.httpResponse.getBody(null, 256, "256 - "); } - return this.httpResponse.getBody({status: "ok"}); + return this.httpResponse.getBody({ status: "ok" }); } /** @@ -150,7 +150,7 @@ export class ProfileCallbacks raidMode: "Online", mode: "deathmatch", shortId: "xxx1x1", - }, {profileid: `pmc${sessionID}`, profileToken: null, status: "Free", sid: "", ip: "", port: 0}], + }, { profileid: `pmc${sessionID}`, profileToken: null, status: "Free", sid: "", ip: "", port: 0 }], }; return this.httpResponse.getBody(response); diff --git a/project/src/controllers/BotController.ts b/project/src/controllers/BotController.ts index 5de94655..1a8d0479 100644 --- a/project/src/controllers/BotController.ts +++ b/project/src/controllers/BotController.ts @@ -290,6 +290,6 @@ export class BotController public getAiBotBrainTypes(): any { - return {pmc: this.pmcConfig.pmcType, assault: this.botConfig.assaultBrainType}; + return { pmc: this.pmcConfig.pmcType, assault: this.botConfig.assaultBrainType }; } } diff --git a/project/src/controllers/CustomizationController.ts b/project/src/controllers/CustomizationController.ts index 62fafde6..d1aac172 100644 --- a/project/src/controllers/CustomizationController.ts +++ b/project/src/controllers/CustomizationController.ts @@ -209,7 +209,7 @@ export class CustomizationController parentId: relatedItem.parentId, slotId: relatedItem.slotId, location: relatedItem.location, - upd: {StackObjectsCount: relatedItem.upd.StackObjectsCount}, + upd: { StackObjectsCount: relatedItem.upd.StackObjectsCount }, }); } } diff --git a/project/src/controllers/DialogueController.ts b/project/src/controllers/DialogueController.ts index 6e085fe5..1c74a1c3 100644 --- a/project/src/controllers/DialogueController.ts +++ b/project/src/controllers/DialogueController.ts @@ -60,7 +60,7 @@ export class DialogueController public getFriendList(sessionID: string): IGetFriendListDataResponse { // Force a fake friend called SPT into friend list - return {Friends: [this.getSptFriendData()], Ignore: [], InIgnoreList: []}; + return { Friends: [this.getSptFriendData()], Ignore: [], InIgnoreList: [] }; } /** diff --git a/project/src/controllers/GameController.ts b/project/src/controllers/GameController.ts index 22146dcf..fefec388 100644 --- a/project/src/controllers/GameController.ts +++ b/project/src/controllers/GameController.ts @@ -435,7 +435,7 @@ export class GameController */ public getServer(sessionId: string): IServerDetails[] { - return [{ip: this.httpConfig.ip, port: this.httpConfig.port}]; + return [{ ip: this.httpConfig.ip, port: this.httpConfig.port }]; } /** @@ -443,7 +443,7 @@ export class GameController */ public getCurrentGroup(sessionId: string): ICurrentGroupResponse { - return {squad: []}; + return { squad: [] }; } /** @@ -451,7 +451,7 @@ export class GameController */ public getValidGameVersion(sessionId: string): ICheckVersionResponse { - return {isvalid: true, latestVersion: this.coreConfig.compatibleTarkovVersion}; + return { isvalid: true, latestVersion: this.coreConfig.compatibleTarkovVersion }; } /** @@ -459,7 +459,7 @@ export class GameController */ public getKeepAlive(sessionId: string): IGameKeepAliveResponse { - return {msg: "OK", utc_time: new Date().getTime() / 1000}; + return { msg: "OK", utc_time: new Date().getTime() / 1000 }; } /** diff --git a/project/src/controllers/HealthController.ts b/project/src/controllers/HealthController.ts index 5090b36f..afc3c39a 100644 --- a/project/src/controllers/HealthController.ts +++ b/project/src/controllers/HealthController.ts @@ -92,7 +92,7 @@ export class HealthController { // Get max healing from db const maxHp = this.itemHelper.getItem(healingItemToUse._tpl)[1]._props.MaxHpResource; - healingItemToUse.upd.MedKit = {HpResource: maxHp - request.count}; // Subtract amount used from max + healingItemToUse.upd.MedKit = { HpResource: maxHp - request.count }; // Subtract amount used from max } // Resource in medkit is spent, delete it @@ -132,7 +132,7 @@ export class HealthController { if (itemToConsume.upd.FoodDrink === undefined) { - itemToConsume.upd.FoodDrink = {HpPercent: consumedItemMaxResource - request.count}; + itemToConsume.upd.FoodDrink = { HpPercent: consumedItemMaxResource - request.count }; } else { diff --git a/project/src/controllers/HideoutController.ts b/project/src/controllers/HideoutController.ts index d31021bf..8cf9b2cc 100644 --- a/project/src/controllers/HideoutController.ts +++ b/project/src/controllers/HideoutController.ts @@ -93,7 +93,7 @@ export class HideoutController const items = request.items.map((reqItem) => { const item = pmcData.Inventory.items.find((invItem) => invItem._id === reqItem.id); - return {inventoryItem: item, requestedItem: reqItem}; + return { inventoryItem: item, requestedItem: reqItem }; }); // If it's not money, its construction / barter items @@ -324,7 +324,7 @@ export class HideoutController } // Add new item as none exists - pmcData.Inventory.items.push({_id: dbHideoutData._id, _tpl: hideoutStage.container}); + pmcData.Inventory.items.push({ _id: dbHideoutData._id, _tpl: hideoutStage.container }); } /** @@ -372,7 +372,7 @@ export class HideoutController const itemsToAdd = Object.entries(addItemToHideoutRequest.items).map((kvp) => { const item = pmcData.Inventory.items.find((invItem) => invItem._id === kvp[1].id); - return {inventoryItem: item, requestedItem: kvp[1], slot: kvp[0]}; + return { inventoryItem: item, requestedItem: kvp[1], slot: kvp[0] }; }); const hideoutArea = pmcData.Hideout.Areas.find((area) => area.type === addItemToHideoutRequest.areaType); @@ -683,7 +683,7 @@ export class HideoutController */ protected addScavCaseRewardsToProfile(pmcData: IPmcData, rewards: Product[], recipeId: string): void { - pmcData.Hideout.Production[`ScavCase${recipeId}`] = {Products: rewards}; + pmcData.Hideout.Production[`ScavCase${recipeId}`] = { Products: rewards }; } /** @@ -787,7 +787,7 @@ export class HideoutController id = this.presetHelper.getDefaultPreset(id)._id; } - const newReq = {items: [{item_id: id, count: recipe.count}], tid: "ragfair"}; + const newReq = { items: [{ item_id: id, count: recipe.count }], tid: "ragfair" }; const entries = Object.entries(pmcData.Hideout.Production); let prodId: string; @@ -871,7 +871,7 @@ export class HideoutController // Handle the isEncoded flag from recipe if (recipe.isEncoded) { - const upd: Upd = {RecodableComponent: {IsEncoded: true}}; + const upd: Upd = { RecodableComponent: { IsEncoded: true } }; return this.inventoryHelper.addItem(pmcData, newReq, output, sessionID, callback, true, upd); } @@ -930,7 +930,7 @@ export class HideoutController delete output.profileChanges[sessionID].production[request.recipeId]; const itemsToAdd = pmcData.Hideout.Production[prodId].Products.map( - (x: {_tpl: string; upd?: {StackObjectsCount?: number;};}) => + (x: { _tpl: string; upd?: { StackObjectsCount?: number; }; }) => { let id = x._tpl; if (this.presetHelper.hasPreset(id)) @@ -939,11 +939,11 @@ export class HideoutController } const numOfItems = !x.upd?.StackObjectsCount ? 1 : x.upd.StackObjectsCount; - return {item_id: id, count: numOfItems}; + return { item_id: id, count: numOfItems }; }, ); - const newReq = {items: itemsToAdd, tid: "ragfair"}; + const newReq = { items: itemsToAdd, tid: "ragfair" }; const callback = () => { @@ -1035,7 +1035,7 @@ export class HideoutController // Check if counter exists, add placeholder if it doesn't if (!pmcData.Stats.Eft.OverallCounters.Items.find((x) => x.Key.includes("ShootingRangePoints"))) { - pmcData.Stats.Eft.OverallCounters.Items.push({Key: ["ShootingRangePoints"], Value: 0}); + pmcData.Stats.Eft.OverallCounters.Items.push({ Key: ["ShootingRangePoints"], Value: 0 }); } // Find counter by key and update value @@ -1066,7 +1066,7 @@ export class HideoutController const items = request.items.map((reqItem) => { const item = pmcData.Inventory.items.find((invItem) => invItem._id === reqItem.id); - return {inventoryItem: item, requestedItem: reqItem}; + return { inventoryItem: item, requestedItem: reqItem }; }); // If it's not money, its construction / barter items diff --git a/project/src/controllers/InsuranceController.ts b/project/src/controllers/InsuranceController.ts index 5552fd36..9a08f430 100644 --- a/project/src/controllers/InsuranceController.ts +++ b/project/src/controllers/InsuranceController.ts @@ -423,7 +423,7 @@ export class InsuranceController */ protected countSuccessfulRolls(attachments: Item[], traderId: string): number { - const rolls = Array.from({length: attachments.length}, () => this.rollForDelete(traderId)); + const rolls = Array.from({ length: attachments.length }, () => this.rollForDelete(traderId)); return rolls.filter(Boolean).length; } @@ -440,14 +440,14 @@ export class InsuranceController toDelete: Set, ): void { - const valuableToDelete = attachments.slice(0, successfulRolls).map(({_id}) => _id); + const valuableToDelete = attachments.slice(0, successfulRolls).map(({ _id }) => _id); for (const attachmentsId of valuableToDelete) { - const valuableChild = attachments.find(({_id}) => _id === attachmentsId); + const valuableChild = attachments.find(({ _id }) => _id === attachmentsId); if (valuableChild) { - const {name, maxPrice} = valuableChild; + const { name, maxPrice } = valuableChild; this.logger.debug(`Marked for removal - Child Item: ${name}, Max Price: ${maxPrice}`); toDelete.add(attachmentsId); } @@ -625,7 +625,7 @@ export class InsuranceController // add items to InsuredItems list once money has been paid for (const key of body.items) { - pmcData.InsuredItems.push({tid: body.tid, itemId: inventoryItemsHash[key]._id}); + pmcData.InsuredItems.push({ tid: body.tid, itemId: inventoryItemsHash[key]._id }); } this.profileHelper.addSkillPointsToPlayer(pmcData, SkillTypes.CHARISMA, itemsToInsureCount * 0.01); diff --git a/project/src/controllers/InventoryController.ts b/project/src/controllers/InventoryController.ts index 7885b1e1..82d0344e 100644 --- a/project/src/controllers/InventoryController.ts +++ b/project/src/controllers/InventoryController.ts @@ -282,12 +282,12 @@ export class InventoryController if (!(destinationItem.upd?.StackObjectsCount)) { // No stack count on destination, add one - destinationItem.upd = {StackObjectsCount: 1}; + destinationItem.upd = { StackObjectsCount: 1 }; } if (!sourceItem.upd) { - sourceItem.upd = {StackObjectsCount: 1}; + sourceItem.upd = { StackObjectsCount: 1 }; } else if (!sourceItem.upd.StackObjectsCount) { @@ -296,7 +296,7 @@ export class InventoryController } destinationItem.upd.StackObjectsCount += sourceItem.upd.StackObjectsCount; // Add source stack count to destination - output.profileChanges[sessionID].items.del.push({_id: sourceItem._id}); // Inform client source item being deleted + output.profileChanges[sessionID].items.del.push({ _id: sourceItem._id }); // Inform client source item being deleted const indexOfItemToRemove = inventoryItems.from.findIndex((x) => x._id === sourceItem._id); if (indexOfItemToRemove === -1) @@ -370,7 +370,7 @@ export class InventoryController let sourceStackCount = 1; if (!sourceItem.upd) { - sourceItem.upd = {StackObjectsCount: 1}; + sourceItem.upd = { StackObjectsCount: 1 }; } sourceStackCount = sourceItem.upd.StackObjectsCount; @@ -392,7 +392,7 @@ export class InventoryController } else { - Object.assign(destinationItem, {upd: {StackObjectsCount: 1}}); + Object.assign(destinationItem, { upd: { StackObjectsCount: 1 } }); } destinationItem.upd.StackObjectsCount = destinationStackCount + body.count; @@ -465,12 +465,12 @@ export class InventoryController { if (item._id && item._id === body.item) { - item.upd.Foldable = {Folded: body.value}; + item.upd.Foldable = { Folded: body.value }; return this.eventOutputHolder.getOutput(sessionID); } } - return {warnings: [], profileChanges: {}}; + return { warnings: [], profileChanges: {} }; } /** @@ -499,7 +499,7 @@ export class InventoryController itemToToggle.upd = {}; } - itemToToggle.upd.Togglable = {On: body.value}; + itemToToggle.upd.Togglable = { On: body.value }; return this.eventOutputHolder.getOutput(sessionID); } @@ -510,7 +510,7 @@ export class InventoryController ); } - return {warnings: [], profileChanges: {}}; + return { warnings: [], profileChanges: {} }; } /** @@ -528,18 +528,18 @@ export class InventoryController { if ("upd" in item) { - item.upd.Tag = {Color: body.TagColor, Name: body.TagName}; + item.upd.Tag = { Color: body.TagColor, Name: body.TagName }; } else { - item.upd = {Tag: {Color: body.TagColor, Name: body.TagName}}; + item.upd = { Tag: { Color: body.TagColor, Name: body.TagName } }; } return this.eventOutputHolder.getOutput(sessionID); } } - return {warnings: [], profileChanges: {}}; + return { warnings: [], profileChanges: {} }; } /** @@ -761,7 +761,7 @@ export class InventoryController const mapItem = pmcData.Inventory.items.find((i) => i._id === request.item); // add marker - mapItem.upd.Map = mapItem.upd.Map || {Markers: []}; + mapItem.upd.Map = mapItem.upd.Map || { Markers: [] }; request.mapMarker.Note = this.sanitiseMapMarkerText(request.mapMarker.Note); mapItem.upd.Map.Markers.push(request.mapMarker); @@ -857,7 +857,7 @@ export class InventoryController const containerDetails = this.itemHelper.getItem(openedItem._tpl); const isSealedWeaponBox = containerDetails[1]._name.includes("event_container_airdrop"); - const newItemRequest: IAddItemRequestData = {tid: "RandomLootContainer", items: []}; + const newItemRequest: IAddItemRequestData = { tid: "RandomLootContainer", items: [] }; let foundInRaid = false; if (isSealedWeaponBox) diff --git a/project/src/controllers/LocationController.ts b/project/src/controllers/LocationController.ts index 00fd78f7..d69eef58 100644 --- a/project/src/controllers/LocationController.ts +++ b/project/src/controllers/LocationController.ts @@ -135,7 +135,7 @@ export class LocationController locations[mapBase._Id] = mapBase; } - return {locations: locations, paths: locationsFromDb.base.paths}; + return { locations: locations, paths: locationsFromDb.base.paths }; } /** @@ -152,7 +152,7 @@ export class LocationController const airdropConfig = this.getAirdropLootConfigByType(airdropType); - return {dropType: airdropType, loot: this.lootGenerator.createRandomLoot(airdropConfig)}; + return { dropType: airdropType, loot: this.lootGenerator.createRandomLoot(airdropConfig) }; } /** diff --git a/project/src/controllers/MatchController.ts b/project/src/controllers/MatchController.ts index 436f7082..fa906259 100644 --- a/project/src/controllers/MatchController.ts +++ b/project/src/controllers/MatchController.ts @@ -101,7 +101,7 @@ export class MatchController /** Handle match/group/start_game */ public joinMatch(info: IJoinMatchRequestData, sessionId: string): IJoinMatchResult { - const output: IJoinMatchResult = {maxPveCountExceeded: false, profiles: []}; + const output: IJoinMatchResult = { maxPveCountExceeded: false, profiles: [] }; // get list of players joining into the match output.profiles.push({ @@ -125,7 +125,7 @@ export class MatchController /** Handle client/match/group/status */ public getGroupStatus(info: IGetGroupStatusRequestData): any { - return {players: [], maxPveCountExceeded: false}; + return { players: [], maxPveCountExceeded: false }; } /** @@ -225,7 +225,7 @@ export class MatchController _tpl: item.tpl, slotId: "main", parentId: parentId, - upd: {StackObjectsCount: item.stackCount, SpawnedInSession: true}, + upd: { StackObjectsCount: item.stackCount, SpawnedInSession: true }, }); } diff --git a/project/src/controllers/NoteController.ts b/project/src/controllers/NoteController.ts index bc56a5a0..d6689621 100644 --- a/project/src/controllers/NoteController.ts +++ b/project/src/controllers/NoteController.ts @@ -14,7 +14,7 @@ export class NoteController public addNote(pmcData: IPmcData, body: INoteActionData, sessionID: string): IItemEventRouterResponse { - const newNote: Note = {Time: body.note.Time, Text: body.note.Text}; + const newNote: Note = { Time: body.note.Time, Text: body.note.Text }; pmcData.Notes.Notes.push(newNote); return this.eventOutputHolder.getOutput(sessionID); diff --git a/project/src/controllers/PresetBuildController.ts b/project/src/controllers/PresetBuildController.ts index 7e44a0b0..6c19797b 100644 --- a/project/src/controllers/PresetBuildController.ts +++ b/project/src/controllers/PresetBuildController.ts @@ -33,7 +33,7 @@ export class PresetBuildController const profile = this.saveServer.getProfile(sessionID); if (!profile.userbuilds) { - profile.userbuilds = {equipmentBuilds: [], weaponBuilds: []}; + profile.userbuilds = { equipmentBuilds: [], weaponBuilds: [] }; } // Ensure the secure container in the default presets match what the player has equipped @@ -84,7 +84,13 @@ export class PresetBuildController // Create new object ready to save into profile userbuilds.weaponBuilds const newId = this.hashUtil.generate(); // Id is empty, generate it - const newBuild: IWeaponBuild = {id: newId, name: body.name, root: body.root, items: body.items, type: "weapon"}; + const newBuild: IWeaponBuild = { + id: newId, + name: body.name, + root: body.root, + items: body.items, + type: "weapon", + }; const savedWeaponBuilds = this.saveServer.getProfile(sessionId).userbuilds.weaponBuilds; const existingBuild = savedWeaponBuilds.find((x) => x.id === body.id); diff --git a/project/src/controllers/ProfileController.ts b/project/src/controllers/ProfileController.ts index ec391eaf..fb2c2336 100644 --- a/project/src/controllers/ProfileController.ts +++ b/project/src/controllers/ProfileController.ts @@ -149,7 +149,7 @@ export class ProfileController if (!pmcData.UnlockedInfo) { - pmcData.UnlockedInfo = {unlockedProductionRecipe: []}; + pmcData.UnlockedInfo = { unlockedProductionRecipe: [] }; } // Change item id's to be unique @@ -164,7 +164,7 @@ export class ProfileController // Create profile const profileDetails: IAkiProfile = { info: account, - characters: {pmc: pmcData, scav: {} as IPmcData}, + characters: { pmc: pmcData, scav: {} as IPmcData }, suits: profile.suits, userbuilds: profile.userbuilds, dialogues: profile.dialogues, @@ -348,6 +348,6 @@ export class ProfileController */ public getFriends(info: ISearchFriendRequestData, sessionID: string): ISearchFriendResponse[] { - return [{_id: this.hashUtil.generate(), Info: {Level: 1, Side: "Bear", Nickname: info.nickname}}]; + return [{ _id: this.hashUtil.generate(), Info: { Level: 1, Side: "Bear", Nickname: info.nickname } }]; } } diff --git a/project/src/controllers/QuestController.ts b/project/src/controllers/QuestController.ts index ce96a841..7eb07df6 100644 --- a/project/src/controllers/QuestController.ts +++ b/project/src/controllers/QuestController.ts @@ -866,7 +866,7 @@ export class QuestController let index = pmcData.Inventory.items.length; // Important: don't tell the client to remove the attachments, it will handle it - output.profileChanges[sessionID].items.del.push({_id: itemHandover.id}); + output.profileChanges[sessionID].items.del.push({ _id: itemHandover.id }); // Important: loop backward when removing items from the array we're looping on while (index-- > 0) @@ -955,6 +955,6 @@ export class QuestController return; } - pmcData.BackendCounters[conditionId] = {id: conditionId, qid: questId, value: counterValue}; + pmcData.BackendCounters[conditionId] = { id: conditionId, qid: questId, value: counterValue }; } } diff --git a/project/src/controllers/RagfairController.ts b/project/src/controllers/RagfairController.ts index bf4a4902..b76d12e6 100644 --- a/project/src/controllers/RagfairController.ts +++ b/project/src/controllers/RagfairController.ts @@ -326,7 +326,7 @@ export class RagfairController const min = offers[0].requirementsCost; // Get first item from array as its pre-sorted const max = offers.at(-1).requirementsCost; // Get last item from array as its pre-sorted - return {avg: (min + max) / 2, min: min, max: max}; + return { avg: (min + max) / 2, min: min, max: max }; } // No offers listed, get price from live ragfair price list prices.json else @@ -340,7 +340,7 @@ export class RagfairController tplPrice = this.handbookHelper.getTemplatePrice(getPriceRequest.templateId); } - return {avg: tplPrice, min: tplPrice, max: tplPrice}; + return { avg: tplPrice, min: tplPrice, max: tplPrice }; } } @@ -613,7 +613,7 @@ export class RagfairController const formattedRequirements: IBarterScheme[] = requirements.map((item) => { - return {_tpl: item._tpl, count: item.count, onlyFunctional: item.onlyFunctional}; + return { _tpl: item._tpl, count: item.count, onlyFunctional: item.onlyFunctional }; }); return this.ragfairOfferGenerator.createFleaOffer( @@ -663,7 +663,7 @@ export class RagfairController if (index === -1) { this.logger.error( - this.localisationService.getText("ragfair-offer_not_found_in_profile", {offerId: offerId}), + this.localisationService.getText("ragfair-offer_not_found_in_profile", { offerId: offerId }), ); return this.httpResponse.appendErrorToOutput( this.eventOutputHolder.getOutput(sessionID), @@ -693,7 +693,7 @@ export class RagfairController if (index === -1) { this.logger.warning( - this.localisationService.getText("ragfair-offer_not_found_in_profile", {offerId: info.offerId}), + this.localisationService.getText("ragfair-offer_not_found_in_profile", { offerId: info.offerId }), ); return this.httpResponse.appendErrorToOutput( this.eventOutputHolder.getOutput(sessionID), @@ -742,7 +742,7 @@ export class RagfairController return { tid: "ragfair", Action: "TradingConfirm", - scheme_items: [{id: this.paymentHelper.getCurrency(currency), count: Math.round(value)}], + scheme_items: [{ id: this.paymentHelper.getCurrency(currency), count: Math.round(value) }], type: "", item_id: "", count: 0, diff --git a/project/src/controllers/RepeatableQuestController.ts b/project/src/controllers/RepeatableQuestController.ts index 94fd56b8..d7e2aa2c 100644 --- a/project/src/controllers/RepeatableQuestController.ts +++ b/project/src/controllers/RepeatableQuestController.ts @@ -313,7 +313,7 @@ export class RepeatableQuestController // Target is boss if (probabilityObject.data.isBoss) { - questPool.pool.Elimination.targets[probabilityObject.key] = {locations: ["any"]}; + questPool.pool.Elimination.targets[probabilityObject.key] = { locations: ["any"] }; } else { @@ -321,8 +321,8 @@ export class RepeatableQuestController // Set possible locations for elimination task, if target is savage, exclude labs from locations questPool.pool.Elimination.targets[probabilityObject.key] = (probabilityObject.key === "Savage") - ? {locations: possibleLocations.filter((x) => x !== "laboratory")} - : {locations: possibleLocations}; + ? { locations: possibleLocations.filter((x) => x !== "laboratory") } + : { locations: possibleLocations }; } } @@ -333,7 +333,7 @@ export class RepeatableQuestController { return { types: repeatableConfig.types.slice(), - pool: {Exploration: {locations: {}}, Elimination: {targets: {}}, Pickup: {locations: {}}}, + pool: { Exploration: { locations: {} }, Elimination: { targets: {} }, Pickup: { locations: {} } }, }; } diff --git a/project/src/controllers/TradeController.ts b/project/src/controllers/TradeController.ts index 53d11b83..364b6fb1 100644 --- a/project/src/controllers/TradeController.ts +++ b/project/src/controllers/TradeController.ts @@ -203,7 +203,11 @@ export class TradeController // Add item details to request // eslint-disable-next-line @typescript-eslint/naming-convention - sellRequest.items.push({id: itemToSell._id, count: itemToSell?.upd?.StackObjectsCount ?? 1, scheme_id: 0}); + sellRequest.items.push({ + id: itemToSell._id, + count: itemToSell?.upd?.StackObjectsCount ?? 1, + scheme_id: 0, + }); } this.logger.debug(`Selling scav items to fence for ${sellRequest.price} roubles`); return this.tradeHelper.sellItem(profileWithItemsToSell, profileThatGetsMoney, sellRequest, sessionId); diff --git a/project/src/controllers/WeatherController.ts b/project/src/controllers/WeatherController.ts index 90350ea9..7c695b91 100644 --- a/project/src/controllers/WeatherController.ts +++ b/project/src/controllers/WeatherController.ts @@ -24,7 +24,7 @@ export class WeatherController /** Handle client/weather */ public generate(): IWeatherData { - let result: IWeatherData = {acceleration: 0, time: "", date: "", weather: null}; + let result: IWeatherData = { acceleration: 0, time: "", date: "", weather: null }; result = this.weatherGenerator.calculateGameTime(result); result.weather = this.weatherGenerator.generateWeather(); diff --git a/project/src/di/Container.ts b/project/src/di/Container.ts index a6d45798..fd2c2a5f 100644 --- a/project/src/di/Container.ts +++ b/project/src/di/Container.ts @@ -251,13 +251,13 @@ export class Container { public static registerPostLoadTypes(container: DependencyContainer, childContainer: DependencyContainer): void { - container.register("AkiHttpListener", AkiHttpListener, {lifecycle: Lifecycle.Singleton}); + container.register("AkiHttpListener", AkiHttpListener, { lifecycle: Lifecycle.Singleton }); childContainer.registerType("HttpListener", "AkiHttpListener"); } public static registerTypes(con: DependencyContainer): void { - con.register("ApplicationContext", ApplicationContext, {lifecycle: Lifecycle.Singleton}); + con.register("ApplicationContext", ApplicationContext, { lifecycle: Lifecycle.Singleton }); Container.registerUtils(con); Container.registerRouters(con); Container.registerGenerators(con); @@ -271,11 +271,11 @@ export class Container public static registerListTypes(con: DependencyContainer): void { - con.register("OnLoadModService", {useValue: new OnLoadModService(con)}); - con.register("HttpListenerModService", {useValue: new HttpListenerModService(con)}); - con.register("OnUpdateModService", {useValue: new OnUpdateModService(con)}); - con.register("DynamicRouterModService", {useValue: new DynamicRouterModService(con)}); - con.register("StaticRouterModService", {useValue: new StaticRouterModService(con)}); + con.register("OnLoadModService", { useValue: new OnLoadModService(con) }); + con.register("HttpListenerModService", { useValue: new HttpListenerModService(con) }); + con.register("OnUpdateModService", { useValue: new OnUpdateModService(con) }); + con.register("DynamicRouterModService", { useValue: new DynamicRouterModService(con) }); + con.register("StaticRouterModService", { useValue: new StaticRouterModService(con) }); con.registerType("OnLoad", "DatabaseImporter"); con.registerType("OnLoad", "PostDBModLoader"); @@ -351,96 +351,100 @@ export class Container private static registerUtils(con: DependencyContainer): void { // Utils - con.register("App", App, {lifecycle: Lifecycle.Singleton}); - con.register("DatabaseImporter", DatabaseImporter, {lifecycle: Lifecycle.Singleton}); - con.register("HashUtil", HashUtil, {lifecycle: Lifecycle.Singleton}); - con.register("ImporterUtil", ImporterUtil, {lifecycle: Lifecycle.Singleton}); + con.register("App", App, { lifecycle: Lifecycle.Singleton }); + con.register("DatabaseImporter", DatabaseImporter, { lifecycle: Lifecycle.Singleton }); + con.register("HashUtil", HashUtil, { lifecycle: Lifecycle.Singleton }); + con.register("ImporterUtil", ImporterUtil, { lifecycle: Lifecycle.Singleton }); con.register("HttpResponseUtil", HttpResponseUtil); - con.register("EncodingUtil", EncodingUtil, {lifecycle: Lifecycle.Singleton}); + con.register("EncodingUtil", EncodingUtil, { lifecycle: Lifecycle.Singleton }); con.register("JsonUtil", JsonUtil); - con.register("WinstonLogger", WinstonMainLogger, {lifecycle: Lifecycle.Singleton}); - con.register("RequestsLogger", WinstonRequestLogger, {lifecycle: Lifecycle.Singleton}); - con.register("MathUtil", MathUtil, {lifecycle: Lifecycle.Singleton}); + con.register("WinstonLogger", WinstonMainLogger, { lifecycle: Lifecycle.Singleton }); + con.register("RequestsLogger", WinstonRequestLogger, { lifecycle: Lifecycle.Singleton }); + con.register("MathUtil", MathUtil, { lifecycle: Lifecycle.Singleton }); con.register("ObjectId", ObjectId); - con.register("RandomUtil", RandomUtil, {lifecycle: Lifecycle.Singleton}); - con.register("TimeUtil", TimeUtil, {lifecycle: Lifecycle.Singleton}); - con.register("VFS", VFS, {lifecycle: Lifecycle.Singleton}); - con.register("WatermarkLocale", WatermarkLocale, {lifecycle: Lifecycle.Singleton}); - con.register("Watermark", Watermark, {lifecycle: Lifecycle.Singleton}); - con.register("AsyncQueue", AsyncQueue, {lifecycle: Lifecycle.Singleton}); - con.register("HttpFileUtil", HttpFileUtil, {lifecycle: Lifecycle.Singleton}); - con.register("ModLoadOrder", ModLoadOrder, {lifecycle: Lifecycle.Singleton}); - con.register("ModTypeCheck", ModTypeCheck, {lifecycle: Lifecycle.Singleton}); + con.register("RandomUtil", RandomUtil, { lifecycle: Lifecycle.Singleton }); + con.register("TimeUtil", TimeUtil, { lifecycle: Lifecycle.Singleton }); + con.register("VFS", VFS, { lifecycle: Lifecycle.Singleton }); + con.register("WatermarkLocale", WatermarkLocale, { lifecycle: Lifecycle.Singleton }); + con.register("Watermark", Watermark, { lifecycle: Lifecycle.Singleton }); + con.register("AsyncQueue", AsyncQueue, { lifecycle: Lifecycle.Singleton }); + con.register("HttpFileUtil", HttpFileUtil, { lifecycle: Lifecycle.Singleton }); + con.register("ModLoadOrder", ModLoadOrder, { lifecycle: Lifecycle.Singleton }); + con.register("ModTypeCheck", ModTypeCheck, { lifecycle: Lifecycle.Singleton }); } private static registerRouters(con: DependencyContainer): void { // Routers - con.register("HttpRouter", HttpRouter, {lifecycle: Lifecycle.Singleton}); + con.register("HttpRouter", HttpRouter, { lifecycle: Lifecycle.Singleton }); con.register("ImageRouter", ImageRouter); - con.register("EventOutputHolder", EventOutputHolder, {lifecycle: Lifecycle.Singleton}); + con.register("EventOutputHolder", EventOutputHolder, { lifecycle: Lifecycle.Singleton }); con.register("ItemEventRouter", ItemEventRouter); // Dynamic routes - con.register("BotDynamicRouter", {useClass: BotDynamicRouter}); - con.register("BundleDynamicRouter", {useClass: BundleDynamicRouter}); - con.register("CustomizationDynamicRouter", {useClass: CustomizationDynamicRouter}); - con.register("DataDynamicRouter", {useClass: DataDynamicRouter}); - con.register("HttpDynamicRouter", {useClass: HttpDynamicRouter}); - con.register("InraidDynamicRouter", {useClass: InraidDynamicRouter}); - con.register("LocationDynamicRouter", {useClass: LocationDynamicRouter}); - con.register("NotifierDynamicRouter", {useClass: NotifierDynamicRouter}); - con.register("TraderDynamicRouter", {useClass: TraderDynamicRouter}); + con.register("BotDynamicRouter", { useClass: BotDynamicRouter }); + con.register("BundleDynamicRouter", { useClass: BundleDynamicRouter }); + con.register("CustomizationDynamicRouter", { + useClass: CustomizationDynamicRouter, + }); + con.register("DataDynamicRouter", { useClass: DataDynamicRouter }); + con.register("HttpDynamicRouter", { useClass: HttpDynamicRouter }); + con.register("InraidDynamicRouter", { useClass: InraidDynamicRouter }); + con.register("LocationDynamicRouter", { useClass: LocationDynamicRouter }); + con.register("NotifierDynamicRouter", { useClass: NotifierDynamicRouter }); + con.register("TraderDynamicRouter", { useClass: TraderDynamicRouter }); // Item event routes con.register("CustomizationItemEventRouter", { useClass: CustomizationItemEventRouter, }); - con.register("HealthItemEventRouter", {useClass: HealthItemEventRouter}); - con.register("HideoutItemEventRouter", {useClass: HideoutItemEventRouter}); - con.register("InsuranceItemEventRouter", {useClass: InsuranceItemEventRouter}); - con.register("InventoryItemEventRouter", {useClass: InventoryItemEventRouter}); - con.register("NoteItemEventRouter", {useClass: NoteItemEventRouter}); - con.register("PresetBuildItemEventRouter", {useClass: PresetBuildItemEventRouter}); - con.register("QuestItemEventRouter", {useClass: QuestItemEventRouter}); - con.register("RagfairItemEventRouter", {useClass: RagfairItemEventRouter}); - con.register("RepairItemEventRouter", {useClass: RepairItemEventRouter}); - con.register("TradeItemEventRouter", {useClass: TradeItemEventRouter}); - con.register("WishlistItemEventRouter", {useClass: WishlistItemEventRouter}); + con.register("HealthItemEventRouter", { useClass: HealthItemEventRouter }); + con.register("HideoutItemEventRouter", { useClass: HideoutItemEventRouter }); + con.register("InsuranceItemEventRouter", { useClass: InsuranceItemEventRouter }); + con.register("InventoryItemEventRouter", { useClass: InventoryItemEventRouter }); + con.register("NoteItemEventRouter", { useClass: NoteItemEventRouter }); + con.register("PresetBuildItemEventRouter", { + useClass: PresetBuildItemEventRouter, + }); + con.register("QuestItemEventRouter", { useClass: QuestItemEventRouter }); + con.register("RagfairItemEventRouter", { useClass: RagfairItemEventRouter }); + con.register("RepairItemEventRouter", { useClass: RepairItemEventRouter }); + con.register("TradeItemEventRouter", { useClass: TradeItemEventRouter }); + con.register("WishlistItemEventRouter", { useClass: WishlistItemEventRouter }); // save load routes - con.register("HealthSaveLoadRouter", {useClass: HealthSaveLoadRouter}); - con.register("InraidSaveLoadRouter", {useClass: InraidSaveLoadRouter}); - con.register("InsuranceSaveLoadRouter", {useClass: InsuranceSaveLoadRouter}); - con.register("ProfileSaveLoadRouter", {useClass: ProfileSaveLoadRouter}); + con.register("HealthSaveLoadRouter", { useClass: HealthSaveLoadRouter }); + con.register("InraidSaveLoadRouter", { useClass: InraidSaveLoadRouter }); + con.register("InsuranceSaveLoadRouter", { useClass: InsuranceSaveLoadRouter }); + con.register("ProfileSaveLoadRouter", { useClass: ProfileSaveLoadRouter }); // Route serializers - con.register("BundleSerializer", {useClass: BundleSerializer}); - con.register("ImageSerializer", {useClass: ImageSerializer}); - con.register("NotifySerializer", {useClass: NotifySerializer}); + con.register("BundleSerializer", { useClass: BundleSerializer }); + con.register("ImageSerializer", { useClass: ImageSerializer }); + con.register("NotifySerializer", { useClass: NotifySerializer }); // Static routes - con.register("BotStaticRouter", {useClass: BotStaticRouter}); - con.register("BundleStaticRouter", {useClass: BundleStaticRouter}); - con.register("ClientLogStaticRouter", {useClass: ClientLogStaticRouter}); - con.register("CustomizationStaticRouter", {useClass: CustomizationStaticRouter}); - con.register("DataStaticRouter", {useClass: DataStaticRouter}); - con.register("DialogStaticRouter", {useClass: DialogStaticRouter}); - con.register("GameStaticRouter", {useClass: GameStaticRouter}); - con.register("HealthStaticRouter", {useClass: HealthStaticRouter}); - con.register("InraidStaticRouter", {useClass: InraidStaticRouter}); - con.register("InsuranceStaticRouter", {useClass: InsuranceStaticRouter}); - con.register("ItemEventStaticRouter", {useClass: ItemEventStaticRouter}); - con.register("LauncherStaticRouter", {useClass: LauncherStaticRouter}); - con.register("LocationStaticRouter", {useClass: LocationStaticRouter}); - con.register("MatchStaticRouter", {useClass: MatchStaticRouter}); - con.register("NotifierStaticRouter", {useClass: NotifierStaticRouter}); - con.register("PresetStaticRouter", {useClass: PresetStaticRouter}); - con.register("ProfileStaticRouter", {useClass: ProfileStaticRouter}); - con.register("QuestStaticRouter", {useClass: QuestStaticRouter}); - con.register("RagfairStaticRouter", {useClass: RagfairStaticRouter}); - con.register("TraderStaticRouter", {useClass: TraderStaticRouter}); - con.register("WeatherStaticRouter", {useClass: WeatherStaticRouter}); + con.register("BotStaticRouter", { useClass: BotStaticRouter }); + con.register("BundleStaticRouter", { useClass: BundleStaticRouter }); + con.register("ClientLogStaticRouter", { useClass: ClientLogStaticRouter }); + con.register("CustomizationStaticRouter", { useClass: CustomizationStaticRouter }); + con.register("DataStaticRouter", { useClass: DataStaticRouter }); + con.register("DialogStaticRouter", { useClass: DialogStaticRouter }); + con.register("GameStaticRouter", { useClass: GameStaticRouter }); + con.register("HealthStaticRouter", { useClass: HealthStaticRouter }); + con.register("InraidStaticRouter", { useClass: InraidStaticRouter }); + con.register("InsuranceStaticRouter", { useClass: InsuranceStaticRouter }); + con.register("ItemEventStaticRouter", { useClass: ItemEventStaticRouter }); + con.register("LauncherStaticRouter", { useClass: LauncherStaticRouter }); + con.register("LocationStaticRouter", { useClass: LocationStaticRouter }); + con.register("MatchStaticRouter", { useClass: MatchStaticRouter }); + con.register("NotifierStaticRouter", { useClass: NotifierStaticRouter }); + con.register("PresetStaticRouter", { useClass: PresetStaticRouter }); + con.register("ProfileStaticRouter", { useClass: ProfileStaticRouter }); + con.register("QuestStaticRouter", { useClass: QuestStaticRouter }); + con.register("RagfairStaticRouter", { useClass: RagfairStaticRouter }); + con.register("TraderStaticRouter", { useClass: TraderStaticRouter }); + con.register("WeatherStaticRouter", { useClass: WeatherStaticRouter }); } private static registerGenerators(con: DependencyContainer): void @@ -450,27 +454,27 @@ export class Container con.register("BotWeaponGenerator", BotWeaponGenerator); con.register("BotLootGenerator", BotLootGenerator); con.register("BotInventoryGenerator", BotInventoryGenerator); - con.register("LocationGenerator", {useClass: LocationGenerator}); - con.register("PMCLootGenerator", PMCLootGenerator, {lifecycle: Lifecycle.Singleton}); + con.register("LocationGenerator", { useClass: LocationGenerator }); + con.register("PMCLootGenerator", PMCLootGenerator, { lifecycle: Lifecycle.Singleton }); con.register("ScavCaseRewardGenerator", ScavCaseRewardGenerator, { lifecycle: Lifecycle.Singleton, }); - con.register("RagfairAssortGenerator", {useClass: RagfairAssortGenerator}); - con.register("RagfairOfferGenerator", {useClass: RagfairOfferGenerator}); - con.register("WeatherGenerator", {useClass: WeatherGenerator}); - con.register("PlayerScavGenerator", {useClass: PlayerScavGenerator}); - con.register("LootGenerator", {useClass: LootGenerator}); - con.register("FenceBaseAssortGenerator", {useClass: FenceBaseAssortGenerator}); - con.register("BotLevelGenerator", {useClass: BotLevelGenerator}); - con.register("BotEquipmentModGenerator", {useClass: BotEquipmentModGenerator}); - con.register("RepeatableQuestGenerator", {useClass: RepeatableQuestGenerator}); + con.register("RagfairAssortGenerator", { useClass: RagfairAssortGenerator }); + con.register("RagfairOfferGenerator", { useClass: RagfairOfferGenerator }); + con.register("WeatherGenerator", { useClass: WeatherGenerator }); + con.register("PlayerScavGenerator", { useClass: PlayerScavGenerator }); + con.register("LootGenerator", { useClass: LootGenerator }); + con.register("FenceBaseAssortGenerator", { useClass: FenceBaseAssortGenerator }); + con.register("BotLevelGenerator", { useClass: BotLevelGenerator }); + con.register("BotEquipmentModGenerator", { useClass: BotEquipmentModGenerator }); + con.register("RepeatableQuestGenerator", { useClass: RepeatableQuestGenerator }); - con.register("BarrelInventoryMagGen", {useClass: BarrelInventoryMagGen}); - con.register("ExternalInventoryMagGen", {useClass: ExternalInventoryMagGen}); + con.register("BarrelInventoryMagGen", { useClass: BarrelInventoryMagGen }); + con.register("ExternalInventoryMagGen", { useClass: ExternalInventoryMagGen }); con.register("InternalMagazineInventoryMagGen", { useClass: InternalMagazineInventoryMagGen, }); - con.register("UbglExternalMagGen", {useClass: UbglExternalMagGen}); + con.register("UbglExternalMagGen", { useClass: UbglExternalMagGen }); con.registerType("InventoryMagGen", "BarrelInventoryMagGen"); con.registerType("InventoryMagGen", "ExternalInventoryMagGen"); @@ -481,107 +485,113 @@ export class Container private static registerHelpers(con: DependencyContainer): void { // Helpers - con.register("AssortHelper", {useClass: AssortHelper}); - con.register("BotHelper", {useClass: BotHelper}); - con.register("BotGeneratorHelper", {useClass: BotGeneratorHelper}); + con.register("AssortHelper", { useClass: AssortHelper }); + con.register("BotHelper", { useClass: BotHelper }); + con.register("BotGeneratorHelper", { useClass: BotGeneratorHelper }); con.register("ContainerHelper", ContainerHelper); - con.register("DialogueHelper", {useClass: DialogueHelper}); - con.register("DurabilityLimitsHelper", {useClass: DurabilityLimitsHelper}); + con.register("DialogueHelper", { useClass: DialogueHelper }); + con.register("DurabilityLimitsHelper", { useClass: DurabilityLimitsHelper }); con.register("GameEventHelper", GameEventHelper); - con.register("HandbookHelper", HandbookHelper, {lifecycle: Lifecycle.Singleton}); - con.register("HealthHelper", {useClass: HealthHelper}); - con.register("HideoutHelper", {useClass: HideoutHelper}); - con.register("InRaidHelper", {useClass: InRaidHelper}); - con.register("InventoryHelper", {useClass: InventoryHelper}); + con.register("HandbookHelper", HandbookHelper, { lifecycle: Lifecycle.Singleton }); + con.register("HealthHelper", { useClass: HealthHelper }); + con.register("HideoutHelper", { useClass: HideoutHelper }); + con.register("InRaidHelper", { useClass: InRaidHelper }); + con.register("InventoryHelper", { useClass: InventoryHelper }); con.register("PaymentHelper", PaymentHelper); - con.register("ItemHelper", {useClass: ItemHelper}); - con.register("PresetHelper", PresetHelper, {lifecycle: Lifecycle.Singleton}); - con.register("ProfileHelper", {useClass: ProfileHelper}); - con.register("QuestHelper", {useClass: QuestHelper}); + con.register("ItemHelper", { useClass: ItemHelper }); + con.register("PresetHelper", PresetHelper, { lifecycle: Lifecycle.Singleton }); + con.register("ProfileHelper", { useClass: ProfileHelper }); + con.register("QuestHelper", { useClass: QuestHelper }); con.register("QuestConditionHelper", QuestConditionHelper); - con.register("RagfairHelper", {useClass: RagfairHelper}); - con.register("RagfairSortHelper", {useClass: RagfairSortHelper}); - con.register("RagfairSellHelper", {useClass: RagfairSellHelper}); - con.register("RagfairOfferHelper", {useClass: RagfairOfferHelper}); - con.register("RagfairServerHelper", {useClass: RagfairServerHelper}); - con.register("RepairHelper", {useClass: RepairHelper}); + con.register("RagfairHelper", { useClass: RagfairHelper }); + con.register("RagfairSortHelper", { useClass: RagfairSortHelper }); + con.register("RagfairSellHelper", { useClass: RagfairSellHelper }); + con.register("RagfairOfferHelper", { useClass: RagfairOfferHelper }); + con.register("RagfairServerHelper", { useClass: RagfairServerHelper }); + con.register("RepairHelper", { useClass: RepairHelper }); con.register("TraderHelper", TraderHelper); - con.register("TraderAssortHelper", TraderAssortHelper, {lifecycle: Lifecycle.Singleton}); - con.register("TradeHelper", {useClass: TradeHelper}); - con.register("NotifierHelper", {useClass: NotifierHelper}); + con.register("TraderAssortHelper", TraderAssortHelper, { lifecycle: Lifecycle.Singleton }); + con.register("TradeHelper", { useClass: TradeHelper }); + con.register("NotifierHelper", { useClass: NotifierHelper }); con.register("UtilityHelper", UtilityHelper); - con.register("WeightedRandomHelper", {useClass: WeightedRandomHelper}); - con.register("HttpServerHelper", {useClass: HttpServerHelper}); - con.register("NotificationSendHelper", {useClass: NotificationSendHelper}); - con.register("SecureContainerHelper", {useClass: SecureContainerHelper}); - con.register("ProbabilityHelper", {useClass: ProbabilityHelper}); - con.register("BotWeaponGeneratorHelper", {useClass: BotWeaponGeneratorHelper}); - con.register("BotDifficultyHelper", {useClass: BotDifficultyHelper}); - con.register("RepeatableQuestHelper", {useClass: RepeatableQuestHelper}); + con.register("WeightedRandomHelper", { useClass: WeightedRandomHelper }); + con.register("HttpServerHelper", { useClass: HttpServerHelper }); + con.register("NotificationSendHelper", { useClass: NotificationSendHelper }); + con.register("SecureContainerHelper", { useClass: SecureContainerHelper }); + con.register("ProbabilityHelper", { useClass: ProbabilityHelper }); + con.register("BotWeaponGeneratorHelper", { useClass: BotWeaponGeneratorHelper }); + con.register("BotDifficultyHelper", { useClass: BotDifficultyHelper }); + con.register("RepeatableQuestHelper", { useClass: RepeatableQuestHelper }); } private static registerLoaders(con: DependencyContainer): void { // Loaders - con.register("BundleLoader", BundleLoader, {lifecycle: Lifecycle.Singleton}); - con.register("PreAkiModLoader", PreAkiModLoader, {lifecycle: Lifecycle.Singleton}); - con.register("PostAkiModLoader", PostAkiModLoader, {lifecycle: Lifecycle.Singleton}); + con.register("BundleLoader", BundleLoader, { lifecycle: Lifecycle.Singleton }); + con.register("PreAkiModLoader", PreAkiModLoader, { lifecycle: Lifecycle.Singleton }); + con.register("PostAkiModLoader", PostAkiModLoader, { lifecycle: Lifecycle.Singleton }); } private static registerCallbacks(con: DependencyContainer): void { // Callbacks - con.register("BotCallbacks", {useClass: BotCallbacks}); - con.register("BundleCallbacks", {useClass: BundleCallbacks}); - con.register("ClientLogCallbacks", {useClass: ClientLogCallbacks}); - con.register("CustomizationCallbacks", {useClass: CustomizationCallbacks}); - con.register("DataCallbacks", {useClass: DataCallbacks}); - con.register("DialogueCallbacks", {useClass: DialogueCallbacks}); - con.register("GameCallbacks", {useClass: GameCallbacks}); - con.register("HandbookCallbacks", {useClass: HandbookCallbacks}); - con.register("HealthCallbacks", {useClass: HealthCallbacks}); - con.register("HideoutCallbacks", {useClass: HideoutCallbacks}); - con.register("HttpCallbacks", {useClass: HttpCallbacks}); - con.register("InraidCallbacks", {useClass: InraidCallbacks}); - con.register("InsuranceCallbacks", {useClass: InsuranceCallbacks}); - con.register("InventoryCallbacks", {useClass: InventoryCallbacks}); - con.register("ItemEventCallbacks", {useClass: ItemEventCallbacks}); - con.register("LauncherCallbacks", {useClass: LauncherCallbacks}); - con.register("LocationCallbacks", {useClass: LocationCallbacks}); - con.register("MatchCallbacks", {useClass: MatchCallbacks}); - con.register("ModCallbacks", {useClass: ModCallbacks}); - con.register("PostDBModLoader", {useClass: PostDBModLoader}); - con.register("NoteCallbacks", {useClass: NoteCallbacks}); - con.register("NotifierCallbacks", {useClass: NotifierCallbacks}); - con.register("PresetBuildCallbacks", {useClass: PresetBuildCallbacks}); - con.register("PresetCallbacks", {useClass: PresetCallbacks}); - con.register("ProfileCallbacks", {useClass: ProfileCallbacks}); - con.register("QuestCallbacks", {useClass: QuestCallbacks}); - con.register("RagfairCallbacks", {useClass: RagfairCallbacks}); - con.register("RepairCallbacks", {useClass: RepairCallbacks}); - con.register("SaveCallbacks", {useClass: SaveCallbacks}); - con.register("TradeCallbacks", {useClass: TradeCallbacks}); - con.register("TraderCallbacks", {useClass: TraderCallbacks}); - con.register("WeatherCallbacks", {useClass: WeatherCallbacks}); - con.register("WishlistCallbacks", {useClass: WishlistCallbacks}); + con.register("BotCallbacks", { useClass: BotCallbacks }); + con.register("BundleCallbacks", { useClass: BundleCallbacks }); + con.register("ClientLogCallbacks", { useClass: ClientLogCallbacks }); + con.register("CustomizationCallbacks", { useClass: CustomizationCallbacks }); + con.register("DataCallbacks", { useClass: DataCallbacks }); + con.register("DialogueCallbacks", { useClass: DialogueCallbacks }); + con.register("GameCallbacks", { useClass: GameCallbacks }); + con.register("HandbookCallbacks", { useClass: HandbookCallbacks }); + con.register("HealthCallbacks", { useClass: HealthCallbacks }); + con.register("HideoutCallbacks", { useClass: HideoutCallbacks }); + con.register("HttpCallbacks", { useClass: HttpCallbacks }); + con.register("InraidCallbacks", { useClass: InraidCallbacks }); + con.register("InsuranceCallbacks", { useClass: InsuranceCallbacks }); + con.register("InventoryCallbacks", { useClass: InventoryCallbacks }); + con.register("ItemEventCallbacks", { useClass: ItemEventCallbacks }); + con.register("LauncherCallbacks", { useClass: LauncherCallbacks }); + con.register("LocationCallbacks", { useClass: LocationCallbacks }); + con.register("MatchCallbacks", { useClass: MatchCallbacks }); + con.register("ModCallbacks", { useClass: ModCallbacks }); + con.register("PostDBModLoader", { useClass: PostDBModLoader }); + con.register("NoteCallbacks", { useClass: NoteCallbacks }); + con.register("NotifierCallbacks", { useClass: NotifierCallbacks }); + con.register("PresetBuildCallbacks", { useClass: PresetBuildCallbacks }); + con.register("PresetCallbacks", { useClass: PresetCallbacks }); + con.register("ProfileCallbacks", { useClass: ProfileCallbacks }); + con.register("QuestCallbacks", { useClass: QuestCallbacks }); + con.register("RagfairCallbacks", { useClass: RagfairCallbacks }); + con.register("RepairCallbacks", { useClass: RepairCallbacks }); + con.register("SaveCallbacks", { useClass: SaveCallbacks }); + con.register("TradeCallbacks", { useClass: TradeCallbacks }); + con.register("TraderCallbacks", { useClass: TraderCallbacks }); + con.register("WeatherCallbacks", { useClass: WeatherCallbacks }); + con.register("WishlistCallbacks", { useClass: WishlistCallbacks }); } private static registerServices(con: DependencyContainer): void { // Services - con.register("ImageRouteService", ImageRouteService, {lifecycle: Lifecycle.Singleton}); + con.register("ImageRouteService", ImageRouteService, { lifecycle: Lifecycle.Singleton }); - con.register("FenceService", FenceService, {lifecycle: Lifecycle.Singleton}); - con.register("PlayerService", {useClass: PlayerService}); - con.register("PaymentService", {useClass: PaymentService}); - con.register("InsuranceService", InsuranceService, {lifecycle: Lifecycle.Singleton}); - con.register("TraderAssortService", TraderAssortService, {lifecycle: Lifecycle.Singleton}); + con.register("FenceService", FenceService, { lifecycle: Lifecycle.Singleton }); + con.register("PlayerService", { useClass: PlayerService }); + con.register("PaymentService", { useClass: PaymentService }); + con.register("InsuranceService", InsuranceService, { lifecycle: Lifecycle.Singleton }); + con.register("TraderAssortService", TraderAssortService, { + lifecycle: Lifecycle.Singleton, + }); - con.register("RagfairPriceService", RagfairPriceService, {lifecycle: Lifecycle.Singleton}); + con.register("RagfairPriceService", RagfairPriceService, { + lifecycle: Lifecycle.Singleton, + }); con.register("RagfairCategoriesService", RagfairCategoriesService, { lifecycle: Lifecycle.Singleton, }); - con.register("RagfairOfferService", RagfairOfferService, {lifecycle: Lifecycle.Singleton}); + con.register("RagfairOfferService", RagfairOfferService, { + lifecycle: Lifecycle.Singleton, + }); con.register("RagfairLinkedItemService", RagfairLinkedItemService, { lifecycle: Lifecycle.Singleton, }); @@ -589,30 +599,36 @@ export class Container lifecycle: Lifecycle.Singleton, }); - con.register("NotificationService", NotificationService, {lifecycle: Lifecycle.Singleton}); + con.register("NotificationService", NotificationService, { + lifecycle: Lifecycle.Singleton, + }); con.register("MatchLocationService", MatchLocationService, { lifecycle: Lifecycle.Singleton, }); con.register("ModCompilerService", ModCompilerService); - con.register("HashCacheService", HashCacheService, {lifecycle: Lifecycle.Singleton}); - con.register("LocaleService", LocaleService, {lifecycle: Lifecycle.Singleton}); + con.register("HashCacheService", HashCacheService, { lifecycle: Lifecycle.Singleton }); + con.register("LocaleService", LocaleService, { lifecycle: Lifecycle.Singleton }); con.register("ProfileFixerService", ProfileFixerService); con.register("RepairService", RepairService); - con.register("BotLootCacheService", BotLootCacheService, {lifecycle: Lifecycle.Singleton}); + con.register("BotLootCacheService", BotLootCacheService, { + lifecycle: Lifecycle.Singleton, + }); con.register("CustomItemService", CustomItemService); con.register("BotEquipmentFilterService", BotEquipmentFilterService); con.register("ProfileSnapshotService", ProfileSnapshotService, { lifecycle: Lifecycle.Singleton, }); - con.register("ItemFilterService", ItemFilterService, {lifecycle: Lifecycle.Singleton}); + con.register("ItemFilterService", ItemFilterService, { lifecycle: Lifecycle.Singleton }); con.register("BotGenerationCacheService", BotGenerationCacheService, { lifecycle: Lifecycle.Singleton, }); - con.register("LocalisationService", LocalisationService, {lifecycle: Lifecycle.Singleton}); + con.register("LocalisationService", LocalisationService, { + lifecycle: Lifecycle.Singleton, + }); con.register("CustomLocationWaveService", CustomLocationWaveService, { lifecycle: Lifecycle.Singleton, }); - con.register("OpenZoneService", OpenZoneService, {lifecycle: Lifecycle.Singleton}); + con.register("OpenZoneService", OpenZoneService, { lifecycle: Lifecycle.Singleton }); con.register("ItemBaseClassService", ItemBaseClassService, { lifecycle: Lifecycle.Singleton, }); @@ -628,7 +644,7 @@ export class Container con.register("MatchBotDetailsCacheService", MatchBotDetailsCacheService, { lifecycle: Lifecycle.Singleton, }); - con.register("RagfairTaxService", RagfairTaxService, {lifecycle: Lifecycle.Singleton}); + con.register("RagfairTaxService", RagfairTaxService, { lifecycle: Lifecycle.Singleton }); con.register("TraderPurchasePersisterService", TraderPurchasePersisterService); con.register("PmcChatResponseService", PmcChatResponseService); con.register("GiftService", GiftService); @@ -638,43 +654,43 @@ export class Container private static registerServers(con: DependencyContainer): void { // Servers - con.register("DatabaseServer", DatabaseServer, {lifecycle: Lifecycle.Singleton}); - con.register("HttpServer", HttpServer, {lifecycle: Lifecycle.Singleton}); - con.register("WebSocketServer", WebSocketServer, {lifecycle: Lifecycle.Singleton}); + con.register("DatabaseServer", DatabaseServer, { lifecycle: Lifecycle.Singleton }); + con.register("HttpServer", HttpServer, { lifecycle: Lifecycle.Singleton }); + con.register("WebSocketServer", WebSocketServer, { lifecycle: Lifecycle.Singleton }); con.register("RagfairServer", RagfairServer); - con.register("SaveServer", SaveServer, {lifecycle: Lifecycle.Singleton}); - con.register("ConfigServer", ConfigServer, {lifecycle: Lifecycle.Singleton}); + con.register("SaveServer", SaveServer, { lifecycle: Lifecycle.Singleton }); + con.register("ConfigServer", ConfigServer, { lifecycle: Lifecycle.Singleton }); } private static registerControllers(con: DependencyContainer): void { // Controllers - con.register("BotController", {useClass: BotController}); - con.register("ClientLogController", {useClass: ClientLogController}); - con.register("CustomizationController", {useClass: CustomizationController}); - con.register("DialogueController", {useClass: DialogueController}); - con.register("GameController", {useClass: GameController}); - con.register("HandbookController", {useClass: HandbookController}); - con.register("HealthController", {useClass: HealthController}); - con.register("HideoutController", {useClass: HideoutController}); - con.register("InraidController", {useClass: InraidController}); - con.register("InsuranceController", {useClass: InsuranceController}); - con.register("InventoryController", {useClass: InventoryController}); - con.register("LauncherController", {useClass: LauncherController}); - con.register("LocationController", {useClass: LocationController}); + con.register("BotController", { useClass: BotController }); + con.register("ClientLogController", { useClass: ClientLogController }); + con.register("CustomizationController", { useClass: CustomizationController }); + con.register("DialogueController", { useClass: DialogueController }); + con.register("GameController", { useClass: GameController }); + con.register("HandbookController", { useClass: HandbookController }); + con.register("HealthController", { useClass: HealthController }); + con.register("HideoutController", { useClass: HideoutController }); + con.register("InraidController", { useClass: InraidController }); + con.register("InsuranceController", { useClass: InsuranceController }); + con.register("InventoryController", { useClass: InventoryController }); + con.register("LauncherController", { useClass: LauncherController }); + con.register("LocationController", { useClass: LocationController }); con.register("MatchController", MatchController); - con.register("NoteController", {useClass: NoteController}); - con.register("NotifierController", {useClass: NotifierController}); - con.register("PresetBuildController", {useClass: PresetBuildController}); - con.register("PresetController", {useClass: PresetController}); - con.register("ProfileController", {useClass: ProfileController}); - con.register("QuestController", {useClass: QuestController}); - con.register("RagfairController", {useClass: RagfairController}); - con.register("RepairController", {useClass: RepairController}); - con.register("RepeatableQuestController", {useClass: RepeatableQuestController}); - con.register("TradeController", {useClass: TradeController}); - con.register("TraderController", {useClass: TraderController}); - con.register("WeatherController", {useClass: WeatherController}); + con.register("NoteController", { useClass: NoteController }); + con.register("NotifierController", { useClass: NotifierController }); + con.register("PresetBuildController", { useClass: PresetBuildController }); + con.register("PresetController", { useClass: PresetController }); + con.register("ProfileController", { useClass: ProfileController }); + con.register("QuestController", { useClass: QuestController }); + con.register("RagfairController", { useClass: RagfairController }); + con.register("RepairController", { useClass: RepairController }); + con.register("RepeatableQuestController", { useClass: RepeatableQuestController }); + con.register("TradeController", { useClass: TradeController }); + con.register("TraderController", { useClass: TraderController }); + con.register("WeatherController", { useClass: WeatherController }); con.register("WishlistController", WishlistController); } } diff --git a/project/src/generators/BotEquipmentModGenerator.ts b/project/src/generators/BotEquipmentModGenerator.ts index 658938b4..d105e602 100644 --- a/project/src/generators/BotEquipmentModGenerator.ts +++ b/project/src/generators/BotEquipmentModGenerator.ts @@ -642,7 +642,10 @@ export class BotEquipmentModGenerator // Pick random mod and check it's compatible const exhaustableModPool = new ExhaustableArray(itemModPool[modSlot], this.randomUtil, this.jsonUtil); - let modCompatibilityResult: {incompatible: boolean; reason: string;} = {incompatible: false, reason: ""}; + let modCompatibilityResult: { incompatible: boolean; reason: string; } = { + incompatible: false, + reason: "", + }; while (exhaustableModPool.hasValues()) { modTpl = exhaustableModPool.getRandomValue(); @@ -1011,7 +1014,7 @@ export class BotEquipmentModGenerator { const modSlotId = slot._name; const modId = this.hashUtil.generate(); - items.push({_id: modId, _tpl: modTpl, parentId: parentId, slotId: modSlotId}); + items.push({ _id: modId, _tpl: modTpl, parentId: parentId, slotId: modSlotId }); } } diff --git a/project/src/generators/BotGenerator.ts b/project/src/generators/BotGenerator.ts index a8c3f794..df914f37 100644 --- a/project/src/generators/BotGenerator.ts +++ b/project/src/generators/BotGenerator.ts @@ -430,7 +430,7 @@ export class BotGenerator } // All skills have id and progress props - const skillToAdd: IBaseSkill = {Id: skillKey, Progress: this.randomUtil.getInt(skill.min, skill.max)}; + const skillToAdd: IBaseSkill = { Id: skillKey, Progress: this.randomUtil.getInt(skill.min, skill.max) }; // Common skills have additional props if (isCommonSkills) diff --git a/project/src/generators/BotInventoryGenerator.ts b/project/src/generators/BotInventoryGenerator.ts index 6128e349..482c4497 100644 --- a/project/src/generators/BotInventoryGenerator.ts +++ b/project/src/generators/BotInventoryGenerator.ts @@ -112,11 +112,11 @@ export class BotInventoryGenerator return { items: [ - {_id: equipmentId, _tpl: equipmentTpl}, - {_id: stashId, _tpl: stashTpl}, - {_id: questRaidItemsId, _tpl: questRaidItemsTpl}, - {_id: questStashItemsId, _tpl: questStashItemsTpl}, - {_id: sortingTableId, _tpl: sortingTableTpl}, + { _id: equipmentId, _tpl: equipmentTpl }, + { _id: stashId, _tpl: stashTpl }, + { _id: questRaidItemsId, _tpl: questRaidItemsTpl }, + { _id: questStashItemsId, _tpl: questStashItemsTpl }, + { _id: sortingTableId, _tpl: sortingTableTpl }, ], equipment: equipmentId, stash: stashId, @@ -403,10 +403,10 @@ export class BotInventoryGenerator * @param equipmentChances Chances bot has certain equipment * @returns What slots bot should have weapons generated for */ - protected getDesiredWeaponsForBot(equipmentChances: Chances): {slot: EquipmentSlots; shouldSpawn: boolean;}[] + protected getDesiredWeaponsForBot(equipmentChances: Chances): { slot: EquipmentSlots; shouldSpawn: boolean; }[] { const shouldSpawnPrimary = this.randomUtil.getChance100(equipmentChances.equipment.FirstPrimaryWeapon); - return [{slot: EquipmentSlots.FIRST_PRIMARY_WEAPON, shouldSpawn: shouldSpawnPrimary}, { + return [{ slot: EquipmentSlots.FIRST_PRIMARY_WEAPON, shouldSpawn: shouldSpawnPrimary }, { slot: EquipmentSlots.SECOND_PRIMARY_WEAPON, shouldSpawn: shouldSpawnPrimary ? this.randomUtil.getChance100(equipmentChances.equipment.SecondPrimaryWeapon) @@ -432,7 +432,7 @@ export class BotInventoryGenerator */ protected addWeaponAndMagazinesToInventory( sessionId: string, - weaponSlot: {slot: EquipmentSlots; shouldSpawn: boolean;}, + weaponSlot: { slot: EquipmentSlots; shouldSpawn: boolean; }, templateInventory: Inventory, botInventory: PmcInventory, equipmentChances: Chances, diff --git a/project/src/generators/BotLevelGenerator.ts b/project/src/generators/BotLevelGenerator.ts index 8b2be669..38778504 100644 --- a/project/src/generators/BotLevelGenerator.ts +++ b/project/src/generators/BotLevelGenerator.ts @@ -55,7 +55,7 @@ export class BotLevelGenerator exp += this.randomUtil.getInt(0, expTable[level].exp - 1); } - return {level, exp}; + return { level, exp }; } /** diff --git a/project/src/generators/BotWeaponGenerator.ts b/project/src/generators/BotWeaponGenerator.ts index 854399f7..e0f2551a 100644 --- a/project/src/generators/BotWeaponGenerator.ts +++ b/project/src/generators/BotWeaponGenerator.ts @@ -252,13 +252,13 @@ export class BotWeaponGenerator _tpl: ammoTpl, parentId: weaponWithModsArray[0]._id, slotId: desiredSlotId, - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }); } else { // Already exists, update values - existingItemWithSlot.upd = {StackObjectsCount: 1}; + existingItemWithSlot.upd = { StackObjectsCount: 1 }; existingItemWithSlot._tpl = ammoTpl; } } @@ -486,7 +486,7 @@ export class BotWeaponGenerator // Define min/max of how many grenades bot will have const ubglMinMax: GenerationData = { // eslint-disable-next-line @typescript-eslint/naming-convention - weights: {"1": 1, "2": 1}, + weights: { "1": 1, "2": 1 }, whitelist: [], }; @@ -530,7 +530,7 @@ export class BotWeaponGenerator [EquipmentSlots.SECURED_CONTAINER], id, ammoTpl, - [{_id: id, _tpl: ammoTpl, upd: {StackObjectsCount: stackSize}}], + [{ _id: id, _tpl: ammoTpl, upd: { StackObjectsCount: stackSize } }], inventory, ); } @@ -704,7 +704,7 @@ export class BotWeaponGenerator _tpl: ubglAmmoTpl, parentId: ubglMod._id, slotId: "patron_in_weapon", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }); } @@ -763,7 +763,7 @@ export class BotWeaponGenerator } else { - camora.upd = {StackObjectsCount: 1}; + camora.upd = { StackObjectsCount: 1 }; } } } diff --git a/project/src/generators/FenceBaseAssortGenerator.ts b/project/src/generators/FenceBaseAssortGenerator.ts index 30c50dce..e7232944 100644 --- a/project/src/generators/FenceBaseAssortGenerator.ts +++ b/project/src/generators/FenceBaseAssortGenerator.ts @@ -97,7 +97,7 @@ export class FenceBaseAssortGenerator _tpl: item._id, parentId: "hideout", slotId: "hideout", - upd: {StackObjectsCount: 9999999, UnlimitedCount: true}, + upd: { StackObjectsCount: 9999999, UnlimitedCount: true }, }; // Add item to base diff --git a/project/src/generators/LocationGenerator.ts b/project/src/generators/LocationGenerator.ts index 6f5f5316..a05df10b 100644 --- a/project/src/generators/LocationGenerator.ts +++ b/project/src/generators/LocationGenerator.ts @@ -338,7 +338,7 @@ export class LocationGenerator // Add an empty group for containers without a group id but still have a < 100% chance to spawn // Likely bad BSG data, will be fixed...eventually, example of the groupids: `NEED_TO_BE_FIXED1`,`NEED_TO_BE_FIXED_SE02`, `NEED_TO_BE_FIXED_NW_01` - mapping[""] = {containerIdsWithProbability: {}, chosenCount: -1}; + mapping[""] = { containerIdsWithProbability: {}, chosenCount: -1 }; // Iterate over all containers and add to group keyed by groupId // Containers without a group go into a group with empty key "" @@ -449,7 +449,7 @@ export class LocationGenerator const rotation = result.rotation ? 1 : 0; items[0].slotId = "main"; - items[0].location = {x: result.x, y: result.y, r: rotation}; + items[0].location = { x: result.x, y: result.y, r: rotation }; // Add loot to container before returning for (const item of items) @@ -780,13 +780,17 @@ export class LocationGenerator ? 1 : this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); - itemWithMods.push({_id: this.objectId.generate(), _tpl: chosenTpl, upd: {StackObjectsCount: stackCount}}); + itemWithMods.push({ + _id: this.objectId.generate(), + _tpl: chosenTpl, + upd: { StackObjectsCount: stackCount }, + }); } else if (this.itemHelper.isOfBaseclass(chosenTpl, BaseClasses.AMMO_BOX)) { // Fill with cartrdiges const ammoBoxTemplate = this.itemHelper.getItem(chosenTpl)[1]; - const ammoBoxItem: Item[] = [{_id: this.objectId.generate(), _tpl: chosenTpl}]; + const ammoBoxItem: Item[] = [{ _id: this.objectId.generate(), _tpl: chosenTpl }]; this.itemHelper.addCartridgesToAmmoBox(ammoBoxItem, ammoBoxTemplate); itemWithMods.push(...ammoBoxItem); } @@ -794,7 +798,7 @@ export class LocationGenerator { // Create array with just magazine + randomised amount of cartridges const magazineTemplate = this.itemHelper.getItem(chosenTpl)[1]; - const magazineItem: Item[] = [{_id: this.objectId.generate(), _tpl: chosenTpl}]; + const magazineItem: Item[] = [{ _id: this.objectId.generate(), _tpl: chosenTpl }]; this.itemHelper.fillMagazineWithRandomCartridge( magazineItem, magazineTemplate, @@ -821,7 +825,7 @@ export class LocationGenerator // Get inventory size of item const size = this.itemHelper.getItemSize(itemWithMods, itemWithMods[0]._id); - return {items: itemWithMods, width: size.width, height: size.height}; + return { items: itemWithMods, width: size.width, height: size.height }; } /** @@ -873,7 +877,7 @@ export class LocationGenerator const itemTemplate = this.itemHelper.getItem(tpl)[1]; let width = itemTemplate._props.Width; let height = itemTemplate._props.Height; - let items: Item[] = [{_id: this.objectId.generate(), _tpl: tpl}]; + let items: Item[] = [{ _id: this.objectId.generate(), _tpl: tpl }]; // Use passed in parentId as override for new item if (parentId) @@ -890,7 +894,7 @@ export class LocationGenerator const stackCount = itemTemplate._props.StackMaxSize === 1 ? 1 : this.randomUtil.getInt(itemTemplate._props.StackMinRandom, itemTemplate._props.StackMaxRandom); - items[0].upd = {StackObjectsCount: stackCount}; + items[0].upd = { StackObjectsCount: stackCount }; } // No spawn point, use default template else if (this.itemHelper.isOfBaseclass(tpl, BaseClasses.WEAPON)) @@ -930,7 +934,7 @@ export class LocationGenerator if (!rootItem) { this.logger.error( - this.localisationService.getText("location-missing_root_item", {tpl: tpl, parentId: parentId}), + this.localisationService.getText("location-missing_root_item", { tpl: tpl, parentId: parentId }), ); throw new Error(this.localisationService.getText("location-critical_error_see_log")); @@ -1004,6 +1008,6 @@ export class LocationGenerator items.splice(items.indexOf(items[0]), 1, ...magazineWithCartridges); } - return {items: items, width: width, height: height}; + return { items: items, width: width, height: height }; } } diff --git a/project/src/generators/LootGenerator.ts b/project/src/generators/LootGenerator.ts index 2dce664f..cf5f57ce 100644 --- a/project/src/generators/LootGenerator.ts +++ b/project/src/generators/LootGenerator.ts @@ -19,7 +19,7 @@ import { RagfairLinkedItemService } from "@spt-aki/services/RagfairLinkedItemSer import { HashUtil } from "@spt-aki/utils/HashUtil"; import { RandomUtil } from "@spt-aki/utils/RandomUtil"; -type ItemLimit = {current: number; max: number;}; +type ItemLimit = { current: number; max: number; }; @injectable() export class LootGenerator @@ -131,7 +131,7 @@ export class LootGenerator const itemTypeCounts: Record = {}; for (const itemTypeId in limits) { - itemTypeCounts[itemTypeId] = {current: 0, max: limits[itemTypeId]}; + itemTypeCounts[itemTypeId] = { current: 0, max: limits[itemTypeId] }; } return itemTypeCounts; @@ -147,7 +147,7 @@ export class LootGenerator */ protected findAndAddRandomItemToLoot( items: [string, ITemplateItem][], - itemTypeCounts: Record, + itemTypeCounts: Record, options: LootRequest, result: LootItem[], ): boolean @@ -225,7 +225,7 @@ export class LootGenerator */ protected findAndAddRandomPresetToLoot( globalDefaultPresets: [string, IPreset][], - itemTypeCounts: Record, + itemTypeCounts: Record, itemBlacklist: string[], result: LootItem[], ): boolean @@ -268,7 +268,7 @@ export class LootGenerator return false; } - const newLootItem: LootItem = {tpl: randomPreset._items[0]._tpl, isPreset: true, stackCount: 1}; + const newLootItem: LootItem = { tpl: randomPreset._items[0]._tpl, isPreset: true, stackCount: 1 }; result.push(newLootItem); @@ -505,7 +505,7 @@ export class LootGenerator else { // eslint-disable-next-line @typescript-eslint/naming-convention - resultsArray.push({item_id: itemTplToAdd, count: 1, isPreset: false}); + resultsArray.push({ item_id: itemTplToAdd, count: 1, isPreset: false }); } } } diff --git a/project/src/generators/PlayerScavGenerator.ts b/project/src/generators/PlayerScavGenerator.ts index 14fe59fc..ce557c24 100644 --- a/project/src/generators/PlayerScavGenerator.ts +++ b/project/src/generators/PlayerScavGenerator.ts @@ -112,8 +112,8 @@ export class PlayerScavGenerator scavData.Info.Level = this.getScavLevel(existingScavData); scavData.Info.Experience = this.getScavExperience(existingScavData); scavData.Quests = existingScavData.Quests ?? []; - scavData.ConditionCounters = existingScavData.ConditionCounters ?? {Counters: []}; - scavData.Notes = existingScavData.Notes ?? {Notes: []}; + scavData.ConditionCounters = existingScavData.ConditionCounters ?? { Counters: [] }; + scavData.Notes = existingScavData.Notes ?? { Notes: [] }; scavData.WishList = existingScavData.WishList ?? []; // Add an extra labs card to pscav backpack based on config chance @@ -256,7 +256,7 @@ export class PlayerScavGenerator protected getDefaultScavSkills(): Skills { - return {Common: [], Mastering: [], Points: 0}; + return { Common: [], Mastering: [], Points: 0 }; } protected getScavStats(scavProfile: IPmcData): Stats diff --git a/project/src/generators/RagfairAssortGenerator.ts b/project/src/generators/RagfairAssortGenerator.ts index 4e343613..b88944ee 100644 --- a/project/src/generators/RagfairAssortGenerator.ts +++ b/project/src/generators/RagfairAssortGenerator.ts @@ -135,7 +135,7 @@ export class RagfairAssortGenerator _tpl: tplId, parentId: "hideout", slotId: "hideout", - upd: {StackObjectsCount: 99999999, UnlimitedCount: true}, + upd: { StackObjectsCount: 99999999, UnlimitedCount: true }, }; } } diff --git a/project/src/generators/RagfairOfferGenerator.ts b/project/src/generators/RagfairOfferGenerator.ts index 68071f03..3fba7154 100644 --- a/project/src/generators/RagfairOfferGenerator.ts +++ b/project/src/generators/RagfairOfferGenerator.ts @@ -33,7 +33,7 @@ import { TimeUtil } from "@spt-aki/utils/TimeUtil"; export class RagfairOfferGenerator { protected ragfairConfig: IRagfairConfig; - protected allowedFleaPriceItemsForBarter: {tpl: string; price: number;}[]; + protected allowedFleaPriceItemsForBarter: { tpl: string; price: number; }[]; constructor( @inject("WinstonLogger") protected logger: ILogger, @@ -636,7 +636,7 @@ export class RagfairOfferGenerator { const totalCapacity = itemDetails._props.MaxResource; const remainingFuel = Math.round(totalCapacity * multiplier); - item.upd.Resource = {UnitsConsumed: totalCapacity - remainingFuel, Value: remainingFuel}; + item.upd.Resource = { UnitsConsumed: totalCapacity - remainingFuel, Value: remainingFuel }; } } @@ -687,27 +687,27 @@ export class RagfairOfferGenerator if (isRepairable && props.Durability > 0) { - item.upd.Repairable = {Durability: props.Durability, MaxDurability: props.Durability}; + item.upd.Repairable = { Durability: props.Durability, MaxDurability: props.Durability }; } if (isMedkit && props.MaxHpResource > 0) { - item.upd.MedKit = {HpResource: props.MaxHpResource}; + item.upd.MedKit = { HpResource: props.MaxHpResource }; } if (isKey) { - item.upd.Key = {NumberOfUsages: 0}; + item.upd.Key = { NumberOfUsages: 0 }; } if (isConsumable) { - item.upd.FoodDrink = {HpPercent: props.MaxResource}; + item.upd.FoodDrink = { HpPercent: props.MaxResource }; } if (isRepairKit) { - item.upd.RepairKit = {Resource: props.MaxRepairResource}; + item.upd.RepairKit = { Resource: props.MaxRepairResource }; } return item; @@ -762,20 +762,20 @@ export class RagfairOfferGenerator // Choose random item from price-filtered flea items const randomItem = this.randomUtil.getArrayValue(filtered); - return [{count: barterItemCount, _tpl: randomItem.tpl}]; + return [{ count: barterItemCount, _tpl: randomItem.tpl }]; } /** * Get an array of flea prices + item tpl, cached in generator class inside `allowedFleaPriceItemsForBarter` * @returns array with tpl/price values */ - protected getFleaPricesAsArray(): {tpl: string; price: number;}[] + protected getFleaPricesAsArray(): { tpl: string; price: number; }[] { // Generate if needed if (!this.allowedFleaPriceItemsForBarter) { const fleaPrices = this.databaseServer.getTables().templates.prices; - const fleaArray = Object.entries(fleaPrices).map(([tpl, price]) => ({tpl: tpl, price: price})); + const fleaArray = Object.entries(fleaPrices).map(([tpl, price]) => ({ tpl: tpl, price: price })); // Only get item prices for items that also exist in items.json const filteredItems = fleaArray.filter((x) => this.itemHelper.getItem(x.tpl)[0]); @@ -801,6 +801,6 @@ export class RagfairOfferGenerator const price = this.ragfairPriceService.getDynamicOfferPriceForOffer(offerItems, currency, isPackOffer) * multipler; - return [{count: price, _tpl: currency}]; + return [{ count: price, _tpl: currency }]; } } diff --git a/project/src/generators/RepeatableQuestGenerator.ts b/project/src/generators/RepeatableQuestGenerator.ts index c2c219a8..aa65f9ff 100644 --- a/project/src/generators/RepeatableQuestGenerator.ts +++ b/project/src/generators/RepeatableQuestGenerator.ts @@ -273,7 +273,7 @@ export class RepeatableQuestGenerator // get all boss spawn information const bossSpawns = Object.values(this.databaseServer.getTables().locations).filter((x) => "base" in x && "Id" in x.base - ).map((x) => ({Id: x.base.Id, BossSpawn: x.base.BossLocationSpawn})); + ).map((x) => ({ Id: x.base.Id, BossSpawn: x.base.BossLocationSpawn })); // filter for the current boss to spawn on map const thisBossSpawns = bossSpawns.map((x) => ({ Id: x.Id, @@ -415,7 +415,7 @@ export class RepeatableQuestGenerator protected generateEliminationLocation(location: string[]): IEliminationCondition { const propsObject: IEliminationCondition = { - _props: {target: location, id: this.objectId.generate(), dynamicLocale: true}, + _props: { target: location, id: this.objectId.generate(), dynamicLocale: true }, _parent: "Location", }; @@ -461,7 +461,7 @@ export class RepeatableQuestGenerator // Dont allow distance + melee requirement if (distance && allowedWeaponCategory !== "5b5f7a0886f77409407a7f96") { - killConditionProps.distance = {compareMethod: ">=", value: distance}; + killConditionProps.distance = { compareMethod: ">=", value: distance }; } // Has specific weapon requirement @@ -476,7 +476,7 @@ export class RepeatableQuestGenerator killConditionProps.weaponCategories = [allowedWeaponCategory]; } - return {_props: killConditionProps, _parent: "Kills"}; + return { _props: killConditionProps, _parent: "Kills" }; } /** @@ -699,11 +699,11 @@ export class RepeatableQuestGenerator const exitStatusCondition: IExplorationCondition = { _parent: "ExitStatus", - _props: {id: this.objectId.generate(), dynamicLocale: true, status: ["Survived"]}, + _props: { id: this.objectId.generate(), dynamicLocale: true, status: ["Survived"] }, }; const locationCondition: IExplorationCondition = { _parent: "Location", - _props: {id: this.objectId.generate(), dynamicLocale: true, target: locationTarget}, + _props: { id: this.objectId.generate(), dynamicLocale: true, target: locationTarget }, }; quest.conditions.AvailableForFinish[0]._props.counter.id = this.objectId.generate(); @@ -797,7 +797,10 @@ export class RepeatableQuestGenerator */ protected generateExplorationExitCondition(exit: Exit): IExplorationCondition { - return {_parent: "ExitName", _props: {exitName: exit.Name, id: this.objectId.generate(), dynamicLocale: true}}; + return { + _parent: "ExitName", + _props: { exitName: exit.Name, id: this.objectId.generate(), dynamicLocale: true }, + }; } /** @@ -869,7 +872,11 @@ export class RepeatableQuestGenerator let roublesBudget = rewardRoubles; let chosenRewardItems = this.chooseRewardItemsWithinBudget(repeatableConfig, roublesBudget); - const rewards: IRewards = {Started: [], Success: [{value: rewardXP, type: "Experience", index: 0}], Fail: []}; + const rewards: IRewards = { + Started: [], + Success: [{ value: rewardXP, type: "Experience", index: 0 }], + Fail: [], + }; if (traderId === Traders.PEACEKEEPER) { @@ -946,7 +953,7 @@ export class RepeatableQuestGenerator // Add rep reward to rewards array if (rewardReputation > 0) { - const reward: IReward = {target: traderId, value: rewardReputation, type: "TraderStanding", index: index}; + const reward: IReward = { target: traderId, value: rewardReputation, type: "TraderStanding", index: index }; rewards.Success.push(reward); } @@ -1010,9 +1017,9 @@ export class RepeatableQuestGenerator protected generateRewardItem(tpl: string, value: number, index: number, preset = null): IReward { const id = this.objectId.generate(); - const rewardItem: IReward = {target: id, value: value, type: "Item", index: index}; + const rewardItem: IReward = { target: id, value: value, type: "Item", index: index }; - const rootItem = {_id: id, _tpl: tpl, upd: {StackObjectsCount: value, SpawnedInSession: true}}; + const rootItem = { _id: id, _tpl: tpl, upd: { StackObjectsCount: value, SpawnedInSession: true } }; if (preset) { diff --git a/project/src/generators/ScavCaseRewardGenerator.ts b/project/src/generators/ScavCaseRewardGenerator.ts index 21ca83a9..6ceddaa7 100644 --- a/project/src/generators/ScavCaseRewardGenerator.ts +++ b/project/src/generators/ScavCaseRewardGenerator.ts @@ -279,7 +279,7 @@ export class ScavCaseRewardGenerator const result: Product[] = []; for (const item of rewardItems) { - const resultItem = {_id: this.hashUtil.generate(), _tpl: item._id, upd: undefined}; + const resultItem = { _id: this.hashUtil.generate(), _tpl: item._id, upd: undefined }; this.addStackCountToAmmoAndMoney(item, resultItem, rarity); @@ -302,13 +302,13 @@ export class ScavCaseRewardGenerator */ protected addStackCountToAmmoAndMoney( item: ITemplateItem, - resultItem: {_id: string; _tpl: string; upd: Upd;}, + resultItem: { _id: string; _tpl: string; upd: Upd; }, rarity: string, ): void { if (item._parent === BaseClasses.AMMO || item._parent === BaseClasses.MONEY) { - resultItem.upd = {StackObjectsCount: this.getRandomAmountRewardForScavCase(item, rarity)}; + resultItem.upd = { StackObjectsCount: this.getRandomAmountRewardForScavCase(item, rarity) }; } } diff --git a/project/src/helpers/AssortHelper.ts b/project/src/helpers/AssortHelper.ts index 04148c2c..83fa16a3 100644 --- a/project/src/helpers/AssortHelper.ts +++ b/project/src/helpers/AssortHelper.ts @@ -75,7 +75,7 @@ export class AssortHelper protected getQuestIdAndStatusThatShowAssort( mergedQuestAssorts: Record>, assortId: string, - ): {questId: string; status: QuestStatus[];} + ): { questId: string; status: QuestStatus[]; } { if (assortId in mergedQuestAssorts.started) { @@ -87,11 +87,11 @@ export class AssortHelper } else if (assortId in mergedQuestAssorts.success) { - return {questId: mergedQuestAssorts.success[assortId], status: [QuestStatus.Success]}; + return { questId: mergedQuestAssorts.success[assortId], status: [QuestStatus.Success] }; } else if (assortId in mergedQuestAssorts.fail) { - return {questId: mergedQuestAssorts.fail[assortId], status: [QuestStatus.Fail]}; + return { questId: mergedQuestAssorts.fail[assortId], status: [QuestStatus.Fail] }; } return undefined; diff --git a/project/src/helpers/BotGeneratorHelper.ts b/project/src/helpers/BotGeneratorHelper.ts index 97ac6b87..2263d6bb 100644 --- a/project/src/helpers/BotGeneratorHelper.ts +++ b/project/src/helpers/BotGeneratorHelper.ts @@ -46,7 +46,7 @@ export class BotGeneratorHelper * @param botRole Used by weapons to randomize the durability values. Null for non-equipped items * @returns Item Upd object with extra properties */ - public generateExtraPropertiesForItem(itemTemplate: ITemplateItem, botRole?: string): {upd?: Upd;} + public generateExtraPropertiesForItem(itemTemplate: ITemplateItem, botRole?: string): { upd?: Upd; } { // Get raid settings, if no raid, default to day const raidSettings = this.applicationContext.getLatestValue(ContextVariableType.RAID_CONFIGURATION)?.getValue< @@ -70,23 +70,23 @@ export class BotGeneratorHelper if (itemTemplate._props.HasHinge) { - itemProperties.Togglable = {On: true}; + itemProperties.Togglable = { On: true }; } if (itemTemplate._props.Foldable) { - itemProperties.Foldable = {Folded: false}; + itemProperties.Foldable = { Folded: false }; } if (itemTemplate._props.weapFireType?.length) { if (itemTemplate._props.weapFireType.includes("fullauto")) { - itemProperties.FireMode = {FireMode: "fullauto"}; + itemProperties.FireMode = { FireMode: "fullauto" }; } else { - itemProperties.FireMode = {FireMode: this.randomUtil.getArrayValue(itemTemplate._props.weapFireType)}; + itemProperties.FireMode = { FireMode: this.randomUtil.getArrayValue(itemTemplate._props.weapFireType) }; } } @@ -116,7 +116,10 @@ export class BotGeneratorHelper const lightLaserActiveChance = raidIsNight ? this.getBotEquipmentSettingFromConfig(botRole, "lightIsActiveNightChancePercent", 50) : this.getBotEquipmentSettingFromConfig(botRole, "lightIsActiveDayChancePercent", 25); - itemProperties.Light = {IsActive: (this.randomUtil.getChance100(lightLaserActiveChance)), SelectedMode: 0}; + itemProperties.Light = { + IsActive: (this.randomUtil.getChance100(lightLaserActiveChance)), + SelectedMode: 0, + }; } else if (itemTemplate._parent === BaseClasses.TACTICAL_COMBO) { @@ -126,7 +129,10 @@ export class BotGeneratorHelper "laserIsActiveChancePercent", 50, ); - itemProperties.Light = {IsActive: (this.randomUtil.getChance100(lightLaserActiveChance)), SelectedMode: 0}; + itemProperties.Light = { + IsActive: (this.randomUtil.getChance100(lightLaserActiveChance)), + SelectedMode: 0, + }; } if (itemTemplate._parent === BaseClasses.NIGHTVISION) @@ -135,7 +141,7 @@ export class BotGeneratorHelper const nvgActiveChance = raidIsNight ? this.getBotEquipmentSettingFromConfig(botRole, "nvgIsActiveChanceNightPercent", 90) : this.getBotEquipmentSettingFromConfig(botRole, "nvgIsActiveChanceDayPercent", 15); - itemProperties.Togglable = {On: (this.randomUtil.getChance100(nvgActiveChance))}; + itemProperties.Togglable = { On: (this.randomUtil.getChance100(nvgActiveChance)) }; } // Togglable face shield @@ -147,10 +153,10 @@ export class BotGeneratorHelper "faceShieldIsActiveChancePercent", 75, ); - itemProperties.Togglable = {On: (this.randomUtil.getChance100(faceShieldActiveChance))}; + itemProperties.Togglable = { On: (this.randomUtil.getChance100(faceShieldActiveChance)) }; } - return Object.keys(itemProperties).length ? {upd: itemProperties} : {}; + return Object.keys(itemProperties).length ? { upd: itemProperties } : {}; } /** @@ -238,7 +244,7 @@ export class BotGeneratorHelper maxDurability, ); - return {Durability: currentDurability, MaxDurability: maxDurability}; + return { Durability: currentDurability, MaxDurability: maxDurability }; } /** @@ -266,7 +272,7 @@ export class BotGeneratorHelper ); } - return {Durability: currentDurability, MaxDurability: maxDurability}; + return { Durability: currentDurability, MaxDurability: maxDurability }; } /** @@ -280,12 +286,12 @@ export class BotGeneratorHelper items: Item[], tplToCheck: string, equipmentSlot: string, - ): {incompatible: boolean; reason: string;} + ): { incompatible: boolean; reason: string; } { // Skip slots that have no incompatibilities if (["Scabbard", "Backpack", "SecureContainer", "Holster", "ArmBand"].includes(equipmentSlot)) { - return {incompatible: false, reason: ""}; + return { incompatible: false, reason: "" }; } // TODO: Can probably be optimized to cache itemTemplates as items are added to inventory @@ -350,7 +356,7 @@ export class BotGeneratorHelper }; } - return {incompatible: false, reason: ""}; + return { incompatible: false, reason: "" }; } /** diff --git a/project/src/helpers/BotWeaponGeneratorHelper.ts b/project/src/helpers/BotWeaponGeneratorHelper.ts index 8be17470..fe9afb69 100644 --- a/project/src/helpers/BotWeaponGeneratorHelper.ts +++ b/project/src/helpers/BotWeaponGeneratorHelper.ts @@ -96,7 +96,7 @@ export class BotWeaponGeneratorHelper */ public createMagazineWithAmmo(magazineTpl: string, ammoTpl: string, magTemplate: ITemplateItem): Item[] { - const magazine: Item[] = [{_id: this.hashUtil.generate(), _tpl: magazineTpl}]; + const magazine: Item[] = [{ _id: this.hashUtil.generate(), _tpl: magazineTpl }]; this.itemHelper.fillMagazineWithCartridge(magazine, magTemplate, ammoTpl, 1); @@ -120,7 +120,7 @@ export class BotWeaponGeneratorHelper const ammoItems = this.itemHelper.splitStack({ _id: this.hashUtil.generate(), _tpl: ammoTpl, - upd: {StackObjectsCount: cartridgeCount}, + upd: { StackObjectsCount: cartridgeCount }, }); for (const ammoItem of ammoItems) diff --git a/project/src/helpers/DialogueHelper.ts b/project/src/helpers/DialogueHelper.ts index 47c4a799..90a69dfc 100644 --- a/project/src/helpers/DialogueHelper.ts +++ b/project/src/helpers/DialogueHelper.ts @@ -39,7 +39,7 @@ export class DialogueHelper */ public createMessageContext(templateId: string, messageType: MessageType, maxStoreTime = null): MessageContent { - const result: MessageContent = {templateId: templateId, type: messageType}; + const result: MessageContent = { templateId: templateId, type: messageType }; if (maxStoreTime) { @@ -66,7 +66,7 @@ export class DialogueHelper if (isNewDialogue) { - dialogue = {_id: dialogueID, type: messageType, messages: [], pinned: false, new: 0, attachmentsNew: 0}; + dialogue = { _id: dialogueID, type: messageType, messages: [], pinned: false, new: 0, attachmentsNew: 0 }; dialogueData[dialogueID] = dialogue; } @@ -79,7 +79,7 @@ export class DialogueHelper if (rewards.length > 0) { const stashId = this.hashUtil.generate(); - items = {stash: stashId, data: []}; + items = { stash: stashId, data: [] }; rewards = this.itemHelper.replaceIDs(null, rewards); for (const reward of rewards) diff --git a/project/src/helpers/HealthHelper.ts b/project/src/helpers/HealthHelper.ts index f9247e8a..d5b2d3a0 100644 --- a/project/src/helpers/HealthHelper.ts +++ b/project/src/helpers/HealthHelper.ts @@ -38,7 +38,7 @@ export class HealthHelper if (!profile.vitality) { // Occurs on newly created profiles - profile.vitality = {health: null, effects: null}; + profile.vitality = { health: null, effects: null }; } profile.vitality.health = { Hydration: 0, @@ -255,7 +255,7 @@ export class HealthHelper profileBodyPart.Effects = {}; } - profileBodyPart.Effects[effectType] = {Time: duration}; + profileBodyPart.Effects[effectType] = { Time: duration }; // Delete empty property to prevent client bugs if (this.isEmpty(profileBodyPart.Effects)) @@ -264,7 +264,7 @@ export class HealthHelper } } - protected isEmpty(map: Record): boolean + protected isEmpty(map: Record): boolean { for (const key in map) { diff --git a/project/src/helpers/HideoutHelper.ts b/project/src/helpers/HideoutHelper.ts index b6449457..9fff70fd 100644 --- a/project/src/helpers/HideoutHelper.ts +++ b/project/src/helpers/HideoutHelper.ts @@ -187,7 +187,7 @@ export class HideoutHelper */ protected getHideoutProperties( pmcData: IPmcData, - ): {btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean;} + ): { btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean; } { const bitcoinFarm = pmcData.Hideout.Areas.find((x) => x.type === HideoutAreas.BITCOIN_FARM); const bitcoinCount = bitcoinFarm?.slots.filter((slot) => slot.item).length ?? 0; // Get slots with an item property @@ -224,7 +224,7 @@ export class HideoutHelper protected updateWaterCollectorProductionTimer( pmcData: IPmcData, productionId: string, - hideoutProperties: {btcFarmCGs?: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean;}, + hideoutProperties: { btcFarmCGs?: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean; }, ): void { const timeElapsed = this.getTimeElapsedSinceLastServerTick(pmcData, hideoutProperties.isGeneratorOn); @@ -241,7 +241,7 @@ export class HideoutHelper */ protected updateProductionTimers( pmcData: IPmcData, - hideoutProperties: {btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean;}, + hideoutProperties: { btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean; }, ): void { const recipes = this.databaseServer.getTables().hideout.production; @@ -310,7 +310,7 @@ export class HideoutHelper pmcData: IPmcData, prodId: string, recipe: IHideoutProduction, - hideoutProperties: {btcFarmCGs?: number; isGeneratorOn: boolean; waterCollectorHasFilter?: boolean;}, + hideoutProperties: { btcFarmCGs?: number; isGeneratorOn: boolean; waterCollectorHasFilter?: boolean; }, ): void { // Production is complete, no need to do any calculations @@ -367,7 +367,7 @@ export class HideoutHelper protected updateAreasWithResources( sessionID: string, pmcData: IPmcData, - hideoutProperties: {btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean;}, + hideoutProperties: { btcFarmCGs: number; isGeneratorOn: boolean; waterCollectorHasFilter: boolean; }, ): void { for (const area of pmcData.Hideout.Areas) @@ -651,7 +651,10 @@ export class HideoutHelper */ protected getAreaUpdObject(stackCount: number, resourceValue: number, resourceUnitsConsumed: number): Upd { - return {StackObjectsCount: stackCount, Resource: {Value: resourceValue, UnitsConsumed: resourceUnitsConsumed}}; + return { + StackObjectsCount: stackCount, + Resource: { Value: resourceValue, UnitsConsumed: resourceUnitsConsumed }, + }; } protected updateAirFilters(airFilterArea: HideoutArea, pmcData: IPmcData): void @@ -699,7 +702,7 @@ export class HideoutHelper { airFilterArea.slots[i].item[0].upd = { StackObjectsCount: 1, - Resource: {Value: resourceValue, UnitsConsumed: pointsConsumed}, + Resource: { Value: resourceValue, UnitsConsumed: pointsConsumed }, }; this.logger.debug(`Air filter: ${resourceValue} filter left on slot ${i + 1}`); break; // Break here to avoid updating all filters @@ -806,7 +809,7 @@ export class HideoutHelper btcProd.Products.push({ _id: this.hashUtil.generate(), _tpl: "59faff1d86f7746c51718c9c", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }); btcProd.Progress -= coinCraftTimeSeconds; diff --git a/project/src/helpers/HttpServerHelper.ts b/project/src/helpers/HttpServerHelper.ts index d8f0c1e6..d647c047 100644 --- a/project/src/helpers/HttpServerHelper.ts +++ b/project/src/helpers/HttpServerHelper.ts @@ -58,7 +58,7 @@ export class HttpServerHelper public sendTextJson(resp: any, output: any): void { // eslint-disable-next-line @typescript-eslint/naming-convention - resp.writeHead(200, "OK", {"Content-Type": this.mime.json}); + resp.writeHead(200, "OK", { "Content-Type": this.mime.json }); resp.end(output); } } diff --git a/project/src/helpers/InRaidHelper.ts b/project/src/helpers/InRaidHelper.ts index c5c35953..891f4f74 100644 --- a/project/src/helpers/InRaidHelper.ts +++ b/project/src/helpers/InRaidHelper.ts @@ -294,7 +294,7 @@ export class InRaidHelper } // Add effect to server profile - profileBodyPartEffects[effect] = {Time: effectDetails.Time ?? -1}; + profileBodyPartEffects[effect] = { Time: effectDetails.Time ?? -1 }; } } } diff --git a/project/src/helpers/InventoryHelper.ts b/project/src/helpers/InventoryHelper.ts index e94f4ba9..66b98fa0 100644 --- a/project/src/helpers/InventoryHelper.ts +++ b/project/src/helpers/InventoryHelper.ts @@ -103,7 +103,7 @@ export class InventoryHelper } else if (this.paymentHelper.isMoneyTpl(requestItem.item_id)) { - itemLib.push({_id: requestItem.item_id, _tpl: requestItem.item_id}); + itemLib.push({ _id: requestItem.item_id, _tpl: requestItem.item_id }); } else if (request.tid === Traders.FENCE) { @@ -125,7 +125,7 @@ export class InventoryHelper } else if (request.tid === "RandomLootContainer") { - itemLib.push({_id: requestItem.item_id, _tpl: requestItem.item_id}); + itemLib.push({ _id: requestItem.item_id, _tpl: requestItem.item_id }); } else { @@ -185,7 +185,7 @@ export class InventoryHelper { let idForItemToAdd = this.hashUtil.generate(); const toDo: string[][] = [[itemToAdd.itemRef._id, idForItemToAdd]]; // WHAT IS THIS?! - let upd: Upd = {StackObjectsCount: itemToAdd.count}; + let upd: Upd = { StackObjectsCount: itemToAdd.count }; // If item being added is preset, load preset's upd data too. if (itemToAdd.isPreset) @@ -213,7 +213,7 @@ export class InventoryHelper // add ragfair upd properties if (addUpd) { - upd = {...addUpd, ...upd}; + upd = { ...addUpd, ...upd }; } // Hideout items need to be marked as found in raid @@ -244,7 +244,7 @@ export class InventoryHelper _tpl: itemToAdd.itemRef._tpl, parentId: itemToAdd.containerId, slotId: "hideout", - location: {x: itemToAdd.location.x, y: itemToAdd.location.y, r: itemToAdd.location.rotation ? 1 : 0}, + location: { x: itemToAdd.location.x, y: itemToAdd.location.y, r: itemToAdd.location.rotation ? 1 : 0 }, upd: this.jsonUtil.clone(upd), }); @@ -253,7 +253,7 @@ export class InventoryHelper _tpl: itemToAdd.itemRef._tpl, parentId: itemToAdd.containerId, slotId: "hideout", - location: {x: itemToAdd.location.x, y: itemToAdd.location.y, r: itemToAdd.location.rotation ? 1 : 0}, + location: { x: itemToAdd.location.x, y: itemToAdd.location.y, r: itemToAdd.location.rotation ? 1 : 0 }, upd: this.jsonUtil.clone(upd), // Clone upd to prevent multi-purchases of same item referencing same upd object in memory }); @@ -277,7 +277,7 @@ export class InventoryHelper // If its from ItemPreset, load preset's upd data too. if (itemToAdd.isPreset) { - upd = {StackObjectsCount: itemToAdd.count}; + upd = { StackObjectsCount: itemToAdd.count }; for (const updID in itemLib[tmpKey].upd) { @@ -297,7 +297,7 @@ export class InventoryHelper _tpl: itemLib[tmpKey]._tpl, parentId: toDo[0][1], slotId: slotID, - location: {x: itemToAdd.location.x, y: itemToAdd.location.y, r: "Horizontal"}, + location: { x: itemToAdd.location.x, y: itemToAdd.location.y, r: "Horizontal" }, upd: this.jsonUtil.clone(upd), }); @@ -306,7 +306,7 @@ export class InventoryHelper _tpl: itemLib[tmpKey]._tpl, parentId: toDo[0][1], slotId: itemLib[tmpKey].slotId, - location: {x: itemToAdd.location.x, y: itemToAdd.location.y, r: "Horizontal"}, + location: { x: itemToAdd.location.x, y: itemToAdd.location.y, r: "Horizontal" }, upd: this.jsonUtil.clone(upd), }); } @@ -506,7 +506,7 @@ export class InventoryHelper parentId: parentId, slotId: "cartridges", location: location, - upd: {StackObjectsCount: ammoStackSize}, + upd: { StackObjectsCount: ammoStackSize }, }; if (foundInRaid) @@ -622,7 +622,7 @@ export class InventoryHelper // We have output object, inform client of item deletion if (output) { - output.profileChanges[sessionID].items.del.push({_id: itemId}); + output.profileChanges[sessionID].items.del.push({ _id: itemId }); } for (const childId of itemToRemoveWithChildren) @@ -885,7 +885,7 @@ export class InventoryHelper protected getInventoryItemHash(inventoryItem: Item[]): InventoryHelper.InventoryItemHash { - const inventoryItemHash: InventoryHelper.InventoryItemHash = {byItemId: {}, byParentId: {}}; + const inventoryItemHash: InventoryHelper.InventoryItemHash = { byItemId: {}, byParentId: {} }; for (const item of inventoryItem) { @@ -1144,7 +1144,7 @@ export class InventoryHelper pmcData: IPmcData, inventoryItems: Item[], moveRequest: IInventoryMoveRequestData, - ): {success: boolean; errorMessage?: string;} + ): { success: boolean; errorMessage?: string; } { this.handleCartridges(inventoryItems, moveRequest); @@ -1155,7 +1155,7 @@ export class InventoryHelper const errorMesage = `Unable to move item: ${moveRequest.item}, cannot find in inventory`; this.logger.error(errorMesage); - return {success: false, errorMessage: errorMesage}; + return { success: false, errorMessage: errorMesage }; } this.logger.debug( @@ -1172,7 +1172,7 @@ export class InventoryHelper }), ); - return {success: true}; + return { success: true }; } // Edit items details to match its new location @@ -1193,7 +1193,7 @@ export class InventoryHelper } } - return {success: true}; + return { success: true }; } /** diff --git a/project/src/helpers/ItemHelper.ts b/project/src/helpers/ItemHelper.ts index cc9731ca..fa076340 100644 --- a/project/src/helpers/ItemHelper.ts +++ b/project/src/helpers/ItemHelper.ts @@ -176,7 +176,7 @@ class ItemHelper { if (item.upd === undefined) { - item.upd = {StackObjectsCount: 1}; + item.upd = { StackObjectsCount: 1 }; } if (item.upd.StackObjectsCount === undefined) @@ -241,7 +241,7 @@ class ItemHelper parentId: parentId, slotId: slotId, location: 0, - upd: {StackObjectsCount: count}, + upd: { StackObjectsCount: count }, }; stackSlotItems.push(stackSlotItem); } @@ -1113,7 +1113,7 @@ class ItemHelper parentId: parentId, slotId: "cartridges", location: location, - upd: {StackObjectsCount: stackCount}, + upd: { StackObjectsCount: stackCount }, }; } diff --git a/project/src/helpers/NotifierHelper.ts b/project/src/helpers/NotifierHelper.ts index fb170a45..a32e24f8 100644 --- a/project/src/helpers/NotifierHelper.ts +++ b/project/src/helpers/NotifierHelper.ts @@ -10,7 +10,7 @@ export class NotifierHelper /** * The default notification sent when waiting times out. */ - protected defaultNotification: INotification = {type: NotificationType.PING, eventId: "ping"}; + protected defaultNotification: INotification = { type: NotificationType.PING, eventId: "ping" }; constructor(@inject("HttpServerHelper") protected httpServerHelper: HttpServerHelper) {} diff --git a/project/src/helpers/ProfileHelper.ts b/project/src/helpers/ProfileHelper.ts index 120b65d9..5afba25e 100644 --- a/project/src/helpers/ProfileHelper.ts +++ b/project/src/helpers/ProfileHelper.ts @@ -217,7 +217,7 @@ export class ProfileHelper public getDefaultAkiDataObject(): any { - return {version: this.getServerVersion()}; + return { version: this.getServerVersion() }; } public getFullProfile(sessionID: string): IAkiProfile @@ -255,14 +255,14 @@ export class ProfileHelper return { Eft: { CarriedQuestItems: [], - DamageHistory: {LethalDamagePart: "Head", LethalDamage: undefined, BodyParts: []}, + DamageHistory: { LethalDamagePart: "Head", LethalDamage: undefined, BodyParts: [] }, DroppedItems: [], ExperienceBonusMult: 0, FoundInRaidItems: [], LastPlayerState: undefined, LastSessionDate: 0, - OverallCounters: {Items: []}, - SessionCounters: {Items: []}, + OverallCounters: { Items: [] }, + SessionCounters: { Items: [] }, SessionExperienceMult: 0, SurvivorClass: "Unknown", TotalInGameTime: 0, @@ -321,7 +321,7 @@ export class ProfileHelper profileToUpdate.aki.receivedGifts = []; } - profileToUpdate.aki.receivedGifts.push({giftId: giftId, timestampAccepted: this.timeUtil.getTimestamp()}); + profileToUpdate.aki.receivedGifts.push({ giftId: giftId, timestampAccepted: this.timeUtil.getTimestamp() }); } /** diff --git a/project/src/helpers/QuestHelper.ts b/project/src/helpers/QuestHelper.ts index 30d9ebfa..506350b3 100644 --- a/project/src/helpers/QuestHelper.ts +++ b/project/src/helpers/QuestHelper.ts @@ -551,7 +551,7 @@ export class QuestHelper { // this case is probably dead Code right now, since the only calling function // checks explicitly for Value > 0. - output.profileChanges[sessionID].items.del.push({_id: itemId}); + output.profileChanges[sessionID].items.del.push({ _id: itemId }); pmcData.Inventory.items.splice(inventoryItemIndex, 1); } } @@ -574,7 +574,7 @@ export class QuestHelper parentId: item.parentId, slotId: item.slotId, location: item.location, - upd: {StackObjectsCount: item.upd.StackObjectsCount}, + upd: { StackObjectsCount: item.upd.StackObjectsCount }, }); } diff --git a/project/src/helpers/RagfairOfferHelper.ts b/project/src/helpers/RagfairOfferHelper.ts index 0a53a8bc..1c09f087 100644 --- a/project/src/helpers/RagfairOfferHelper.ts +++ b/project/src/helpers/RagfairOfferHelper.ts @@ -432,7 +432,7 @@ export class RagfairOfferHelper const requestedItem: Item = { _id: this.hashUtil.generate(), _tpl: requirement._tpl, - upd: {StackObjectsCount: requirement.count * boughtAmount}, + upd: { StackObjectsCount: requirement.count * boughtAmount }, }; const stacks = this.itemHelper.splitStack(requestedItem); diff --git a/project/src/helpers/RagfairSellHelper.ts b/project/src/helpers/RagfairSellHelper.ts index 5f5d174f..8cbf6545 100644 --- a/project/src/helpers/RagfairSellHelper.ts +++ b/project/src/helpers/RagfairSellHelper.ts @@ -112,7 +112,7 @@ export class RagfairSellHelper this.ragfairConfig.sell.time.min * 60, ); - result.push({sellTime: sellTime, amount: boughtAmount}); + result.push({ sellTime: sellTime, amount: boughtAmount }); this.logger.debug(`Offer will sell at: ${new Date(sellTime * 1000).toLocaleTimeString("en-US")}`); } diff --git a/project/src/helpers/RepairHelper.ts b/project/src/helpers/RepairHelper.ts index 2b0e48f9..0e031ecd 100644 --- a/project/src/helpers/RepairHelper.ts +++ b/project/src/helpers/RepairHelper.ts @@ -68,7 +68,7 @@ export class RepairHelper } // Construct object to return - itemToRepair.upd.Repairable = {Durability: newCurrentDurability, MaxDurability: newCurrentMaxDurability}; + itemToRepair.upd.Repairable = { Durability: newCurrentDurability, MaxDurability: newCurrentMaxDurability }; // when modders set the repair coefficient to 0 it means that they dont want to lose durability on items // the code below generates a random degradation on the weapon durability diff --git a/project/src/helpers/TraderAssortHelper.ts b/project/src/helpers/TraderAssortHelper.ts index 3ee329fc..fb6a4431 100644 --- a/project/src/helpers/TraderAssortHelper.ts +++ b/project/src/helpers/TraderAssortHelper.ts @@ -26,7 +26,7 @@ import { TimeUtil } from "@spt-aki/utils/TimeUtil"; export class TraderAssortHelper { protected traderConfig: ITraderConfig; - protected mergedQuestAssorts: Record> = {started: {}, success: {}, fail: {}}; + protected mergedQuestAssorts: Record> = { started: {}, success: {}, fail: {} }; protected createdMergedQuestAssorts = false; constructor( diff --git a/project/src/helpers/TraderHelper.ts b/project/src/helpers/TraderHelper.ts index aaae8ecd..7730ff34 100644 --- a/project/src/helpers/TraderHelper.ts +++ b/project/src/helpers/TraderHelper.ts @@ -268,7 +268,7 @@ export class TraderHelper }), ); this.traderConfig.updateTime.push( // create temporary entry to prevent logger spam - {traderId: traderId, seconds: this.traderConfig.updateTimeDefault}, + { traderId: traderId, seconds: this.traderConfig.updateTimeDefault }, ); } else @@ -303,7 +303,7 @@ export class TraderHelper // eslint-disable-next-line @typescript-eslint/naming-convention public addTraderPurchasesToPlayerProfile( sessionID: string, - newPurchaseDetails: {items: {item_id: string; count: number;}[]; tid: string;}, + newPurchaseDetails: { items: { item_id: string; count: number; }[]; tid: string; }, ): void { const profile = this.profileHelper.getFullProfile(sessionID); diff --git a/project/src/helpers/WeightedRandomHelper.ts b/project/src/helpers/WeightedRandomHelper.ts index 7e66a3e0..7b5f8169 100644 --- a/project/src/helpers/WeightedRandomHelper.ts +++ b/project/src/helpers/WeightedRandomHelper.ts @@ -9,7 +9,7 @@ export class WeightedRandomHelper * @param {tplId: weighting[]} itemArray * @returns tplId */ - public getWeightedInventoryItem(itemArray: {[tplId: string]: unknown;} | ArrayLike): string + public getWeightedInventoryItem(itemArray: { [tplId: string]: unknown; } | ArrayLike): string { const itemKeys = Object.keys(itemArray); const weights = Object.values(itemArray); @@ -18,7 +18,7 @@ export class WeightedRandomHelper return chosenItem.item; } - public getWeightedValue(itemArray: {[key: string]: unknown;} | ArrayLike): T + public getWeightedValue(itemArray: { [key: string]: unknown; } | ArrayLike): T { const itemKeys = Object.keys(itemArray); const weights = Object.values(itemArray); @@ -41,7 +41,7 @@ export class WeightedRandomHelper * @param {number[]} weights * @returns {{item: any, index: number}} */ - public weightedRandom(items: string | any[], weights: string | any[]): {item: any; index: number;} + public weightedRandom(items: string | any[], weights: string | any[]): { item: any; index: number; } { if (items.length !== weights.length) { @@ -77,7 +77,7 @@ export class WeightedRandomHelper { if (cumulativeWeights[itemIndex] >= randomNumber) { - return {item: items[itemIndex], index: itemIndex}; + return { item: items[itemIndex], index: itemIndex }; } } } diff --git a/project/src/loaders/PreAkiModLoader.ts b/project/src/loaders/PreAkiModLoader.ts index 17f98067..297eca6b 100644 --- a/project/src/loaders/PreAkiModLoader.ts +++ b/project/src/loaders/PreAkiModLoader.ts @@ -139,11 +139,11 @@ export class PreAkiModLoader implements IModLoader this.logger.info(this.localisationService.getText("modloader-mod_order_missing")); // Write file with empty order array to disk - this.vfs.writeFile(this.modOrderPath, this.jsonUtil.serializeAdvanced({order: []}, null, 4)); + this.vfs.writeFile(this.modOrderPath, this.jsonUtil.serializeAdvanced({ order: [] }, null, 4)); } else { - const modOrder = this.vfs.readFile(this.modOrderPath, {encoding: "utf8"}); + const modOrder = this.vfs.readFile(this.modOrderPath, { encoding: "utf8" }); try { for (const [index, mod] of (this.jsonUtil.deserialize(modOrder).order as string[]).entries()) @@ -225,7 +225,7 @@ export class PreAkiModLoader implements IModLoader if (this.shouldSkipMod(pkg)) { - this.logger.warning(this.localisationService.getText("modloader-skipped_mod", {mod: mod})); + this.logger.warning(this.localisationService.getText("modloader-skipped_mod", { mod: mod })); continue; } @@ -473,7 +473,7 @@ export class PreAkiModLoader implements IModLoader pkg.scripts = {}; // Add mod to imported list - this.imported[mod] = {...pkg, dependencies: pkg.modDependencies}; + this.imported[mod] = { ...pkg, dependencies: pkg.modDependencies }; this.logger.info( this.localisationService.getText("modloader-loaded_mod", { name: pkg.name, @@ -557,7 +557,7 @@ export class PreAkiModLoader implements IModLoader ); let command = `${pnpmPath} install `; command += dependenciesToInstall.map(([depName, depVersion]) => `${depName}@${depVersion}`).join(" "); - execSync(command, {cwd: modPath}); + execSync(command, { cwd: modPath }); // Delete the new blank package.json then rename the backup back to the original name this.vfs.removeFile(`${modPath}/package.json`); diff --git a/project/src/models/external/HttpFramework.ts b/project/src/models/external/HttpFramework.ts index ffc28468..9ac9db8b 100644 --- a/project/src/models/external/HttpFramework.ts +++ b/project/src/models/external/HttpFramework.ts @@ -13,7 +13,7 @@ export type HandleFn = (_: string, req: IncomingMessage, resp: ServerResponse) = */ export const Listen = (basePath: string) => { - return (Base: T): T => + return (Base: T): T => { // Used for the base class to be able to use DI injectable()(Base); @@ -35,7 +35,7 @@ export const Listen = (basePath: string) => } // Add each flagged handler to the Record - for (const {handlerName, path, httpMethod} of handlersArray) + for (const { handlerName, path, httpMethod } of handlersArray) { if (!this.handlers[httpMethod]) { @@ -111,7 +111,7 @@ const createHttpDecorator = (httpMethod: HttpMethods) => } // Flag the method as a HTTP handler - target.handlers.push({handlerName: propertyKey, path, httpMethod}); + target.handlers.push({ handlerName: propertyKey, path, httpMethod }); }; }; }; diff --git a/project/src/models/spt/server/IDatabaseTables.ts b/project/src/models/spt/server/IDatabaseTables.ts index 73ce43ed..acd72d6e 100644 --- a/project/src/models/spt/server/IDatabaseTables.ts +++ b/project/src/models/spt/server/IDatabaseTables.ts @@ -24,7 +24,7 @@ import { ISettingsBase } from "@spt-aki/models/spt/server/ISettingsBase"; export interface IDatabaseTables { - bots?: {types: Record; base: IBotBase; core: IBotCore;}; + bots?: { types: Record; base: IBotBase; core: IBotCore; }; hideout?: { areas: IHideoutArea[]; production: IHideoutProduction[]; diff --git a/project/src/routers/EventOutputHolder.ts b/project/src/routers/EventOutputHolder.ts index dca76e78..abbc9da2 100644 --- a/project/src/routers/EventOutputHolder.ts +++ b/project/src/routers/EventOutputHolder.ts @@ -12,7 +12,7 @@ import { TimeUtil } from "@spt-aki/utils/TimeUtil"; export class EventOutputHolder { /** What has client been informed of this game session */ - protected clientActiveSessionStorage: Record = {}; + protected clientActiveSessionStorage: Record = {}; constructor( @inject("JsonUtil") protected jsonUtil: JsonUtil, @@ -22,7 +22,7 @@ export class EventOutputHolder {} // TODO REMEMBER TO CHANGE OUTPUT - protected output: IItemEventRouterResponse = {warnings: [], profileChanges: {}}; + protected output: IItemEventRouterResponse = { warnings: [], profileChanges: {} }; public getOutput(sessionID: string): IItemEventRouterResponse { @@ -51,10 +51,10 @@ export class EventOutputHolder ragFairOffers: [], weaponBuilds: [], equipmentBuilds: [], - items: {new: [], change: [], del: []}, + items: { new: [], change: [], del: [] }, production: {}, improvements: {}, - skills: {Common: [], Mastering: [], Points: 0}, + skills: { Common: [], Mastering: [], Points: 0 }, health: this.jsonUtil.clone(pmcData.Health), traderRelations: {}, // changedHideoutStashes: {}, @@ -170,7 +170,7 @@ export class EventOutputHolder // Flag started craft as having been seen by client if (production.Progress > 0 && !this.clientActiveSessionStorage[productionKey]?.clientInformed) { - this.clientActiveSessionStorage[productionKey] = {clientInformed: true}; + this.clientActiveSessionStorage[productionKey] = { clientInformed: true }; } } diff --git a/project/src/routers/save_load/HealthSaveLoadRouter.ts b/project/src/routers/save_load/HealthSaveLoadRouter.ts index 343490d2..b32f49ce 100644 --- a/project/src/routers/save_load/HealthSaveLoadRouter.ts +++ b/project/src/routers/save_load/HealthSaveLoadRouter.ts @@ -15,7 +15,7 @@ export class HealthSaveLoadRouter extends SaveLoadRouter { if (!profile.vitality) { // Occurs on newly created profiles - profile.vitality = {health: null, effects: null}; + profile.vitality = { health: null, effects: null }; } profile.vitality.health = { Hydration: 0, diff --git a/project/src/routers/save_load/InraidSaveLoadRouter.ts b/project/src/routers/save_load/InraidSaveLoadRouter.ts index bea4532f..241300dd 100644 --- a/project/src/routers/save_load/InraidSaveLoadRouter.ts +++ b/project/src/routers/save_load/InraidSaveLoadRouter.ts @@ -15,7 +15,7 @@ export class InraidSaveLoadRouter extends SaveLoadRouter { if (profile.inraid === undefined) { - profile.inraid = {location: "none", character: "none"}; + profile.inraid = { location: "none", character: "none" }; } return profile; diff --git a/project/src/routers/save_load/ProfileSaveLoadRouter.ts b/project/src/routers/save_load/ProfileSaveLoadRouter.ts index bab47117..97d1309f 100644 --- a/project/src/routers/save_load/ProfileSaveLoadRouter.ts +++ b/project/src/routers/save_load/ProfileSaveLoadRouter.ts @@ -16,7 +16,7 @@ export class ProfileSaveLoadRouter extends SaveLoadRouter { if (profile.characters === null) { - profile.characters = {pmc: {} as IPmcData, scav: {} as IPmcData}; + profile.characters = { pmc: {} as IPmcData, scav: {} as IPmcData }; } return profile; } diff --git a/project/src/servers/SaveServer.ts b/project/src/servers/SaveServer.ts index 5599b361..95152dee 100644 --- a/project/src/servers/SaveServer.ts +++ b/project/src/servers/SaveServer.ts @@ -142,7 +142,7 @@ export class SaveServer throw new Error(`profile already exists for sessionId: ${profileInfo.id}`); } - this.profiles[profileInfo.id] = {info: profileInfo, characters: {pmc: {}, scav: {}}}; + this.profiles[profileInfo.id] = { info: profileInfo, characters: { pmc: {}, scav: {} } }; } /** @@ -195,7 +195,7 @@ export class SaveServer } catch (error) { - this.logger.error(this.localisationService.getText("profile_save_callback_error", {callback, error})); + this.logger.error(this.localisationService.getText("profile_save_callback_error", { callback, error })); this.profiles[sessionID] = previous; } } diff --git a/project/src/servers/WebSocketServer.ts b/project/src/servers/WebSocketServer.ts index fcf3ea16..19fa82eb 100644 --- a/project/src/servers/WebSocketServer.ts +++ b/project/src/servers/WebSocketServer.ts @@ -28,14 +28,14 @@ export class WebSocketServer } protected httpConfig: IHttpConfig; - protected defaultNotification: INotification = {type: NotificationType.PING, eventId: "ping"}; + protected defaultNotification: INotification = { type: NotificationType.PING, eventId: "ping" }; protected webSockets: Record = {}; protected websocketPingHandler = null; public setupWebSocket(httpServer: http.Server): void { - const webSocketServer = new WebSocket.Server({server: httpServer}); + const webSocketServer = new WebSocket.Server({ server: httpServer }); webSocketServer.addListener("listening", () => { diff --git a/project/src/servers/http/AkiHttpListener.ts b/project/src/servers/http/AkiHttpListener.ts index bc74db94..cc48eb62 100644 --- a/project/src/servers/http/AkiHttpListener.ts +++ b/project/src/servers/http/AkiHttpListener.ts @@ -168,14 +168,14 @@ export class AkiHttpListener implements IHttpListener public sendJson(resp: ServerResponse, output: string, sessionID: string): void { // eslint-disable-next-line @typescript-eslint/naming-convention - resp.writeHead(200, "OK", {"Content-Type": "application/json", "Set-Cookie": `PHPSESSID=${sessionID}`}); + resp.writeHead(200, "OK", { "Content-Type": "application/json", "Set-Cookie": `PHPSESSID=${sessionID}` }); resp.end(output); } public sendZlibJson(resp: ServerResponse, output: string, sessionID: string): void { // eslint-disable-next-line @typescript-eslint/naming-convention - resp.writeHead(200, "OK", {"Content-Type": "application/json", "Set-Cookie": `PHPSESSID=${sessionID}`}); + resp.writeHead(200, "OK", { "Content-Type": "application/json", "Set-Cookie": `PHPSESSID=${sessionID}` }); zlib.deflate(output, (_, buf) => resp.end(buf)); } } diff --git a/project/src/services/BotWeaponModLimitService.ts b/project/src/services/BotWeaponModLimitService.ts index 99020cd8..6fbf9f35 100644 --- a/project/src/services/BotWeaponModLimitService.ts +++ b/project/src/services/BotWeaponModLimitService.ts @@ -46,7 +46,7 @@ export class BotWeaponModLimitService public getWeaponModLimits(botRole: string): BotModLimits { return { - scope: {count: 0}, + scope: { count: 0 }, scopeMax: this.botConfig.equipment[botRole]?.weaponModLimits?.scopeLimit, scopeBaseTypes: [ BaseClasses.OPTIC_SCOPE, @@ -55,7 +55,7 @@ export class BotWeaponModLimitService BaseClasses.COMPACT_COLLIMATOR, BaseClasses.SPECIAL_SCOPE, ], - flashlightLaser: {count: 0}, + flashlightLaser: { count: 0 }, flashlightLaserMax: this.botConfig.equipment[botRole]?.weaponModLimits?.lightLaserLimit, flashlgihtLaserBaseTypes: [ BaseClasses.TACTICAL_COMBO, @@ -166,7 +166,7 @@ export class BotWeaponModLimitService */ protected weaponModLimitReached( modTpl: string, - currentCount: {count: number;}, + currentCount: { count: number; }, maxLimit: number, botRole: string, ): boolean diff --git a/project/src/services/FenceService.ts b/project/src/services/FenceService.ts index 9eb4afed..eacc3908 100644 --- a/project/src/services/FenceService.ts +++ b/project/src/services/FenceService.ts @@ -421,7 +421,7 @@ export class FenceService fenceAssortIds: string[], assorts: ITraderAssort, fenceAssort: ITraderAssort, - itemTypeCounts: Record, + itemTypeCounts: Record, loyaltyLevel: number, ): void { @@ -585,7 +585,7 @@ export class FenceService // Multiply weapon+mods rouble price by multipler in config assorts.barter_scheme[weaponAndMods[0]._id] = [[]]; - assorts.barter_scheme[weaponAndMods[0]._id][0][0] = {_tpl: Money.ROUBLES, count: Math.round(rub)}; + assorts.barter_scheme[weaponAndMods[0]._id][0][0] = { _tpl: Money.ROUBLES, count: Math.round(rub) }; assorts.loyal_level_items[weaponAndMods[0]._id] = loyaltyLevel; @@ -675,7 +675,7 @@ export class FenceService // Randomise hp resource of med items if ("MaxHpResource" in itemDetails._props && itemDetails._props.MaxHpResource > 0) { - itemToAdjust.upd.MedKit = {HpResource: this.randomUtil.getInt(1, itemDetails._props.MaxHpResource)}; + itemToAdjust.upd.MedKit = { HpResource: this.randomUtil.getInt(1, itemDetails._props.MaxHpResource) }; } // Randomise armor durability @@ -694,7 +694,7 @@ export class FenceService const maxDurability = this.randomUtil.getInt(duraMin, duraMax); const durability = this.randomUtil.getInt(1, maxDurability); - itemToAdjust.upd.Repairable = {Durability: durability, MaxDurability: maxDurability}; + itemToAdjust.upd.Repairable = { Durability: durability, MaxDurability: maxDurability }; return; } @@ -709,14 +709,14 @@ export class FenceService const maxDurability = this.randomUtil.getInt(duraMin, duraMax); const durability = this.randomUtil.getInt(1, maxDurability); - itemToAdjust.upd.Repairable = {Durability: durability, MaxDurability: maxDurability}; + itemToAdjust.upd.Repairable = { Durability: durability, MaxDurability: maxDurability }; return; } if (this.itemHelper.isOfBaseclass(itemDetails._id, BaseClasses.REPAIR_KITS)) { - itemToAdjust.upd.RepairKit = {Resource: this.randomUtil.getInt(1, itemDetails._props.MaxRepairResource)}; + itemToAdjust.upd.RepairKit = { Resource: this.randomUtil.getInt(1, itemDetails._props.MaxRepairResource) }; return; } @@ -740,7 +740,7 @@ export class FenceService const resourceMax = itemDetails._props.MaxResource; const resourceCurrent = this.randomUtil.getInt(1, itemDetails._props.MaxResource); - itemToAdjust.upd.Resource = {Value: resourceMax - resourceCurrent, UnitsConsumed: resourceCurrent}; + itemToAdjust.upd.Resource = { Value: resourceMax - resourceCurrent, UnitsConsumed: resourceCurrent }; } } @@ -749,13 +749,13 @@ export class FenceService * @param limits limits as defined in config * @returns record, key: item tplId, value: current/max item count allowed */ - protected initItemLimitCounter(limits: Record): Record + protected initItemLimitCounter(limits: Record): Record { - const itemTypeCounts: Record = {}; + const itemTypeCounts: Record = {}; for (const x in limits) { - itemTypeCounts[x] = {current: 0, max: limits[x]}; + itemTypeCounts[x] = { current: 0, max: limits[x] }; } return itemTypeCounts; diff --git a/project/src/services/GiftService.ts b/project/src/services/GiftService.ts index 1a82e920..4193f2a5 100644 --- a/project/src/services/GiftService.ts +++ b/project/src/services/GiftService.ts @@ -133,7 +133,7 @@ export class GiftService const details: ISendMessageDetails = { recipientId: playerId, sender: this.getMessageType(giftData), - senderDetails: {_id: this.getSenderId(giftData), info: null}, + senderDetails: { _id: this.getSenderId(giftData), info: null }, messageText: giftData.messageText, items: giftData.items, itemsMaxStorageLifetimeSeconds: this.timeUtil.getHoursAsSeconds(giftData.collectionTimeHours), diff --git a/project/src/services/InsuranceService.ts b/project/src/services/InsuranceService.ts index b32d9bbd..c7ac6a21 100644 --- a/project/src/services/InsuranceService.ts +++ b/project/src/services/InsuranceService.ts @@ -158,7 +158,7 @@ export class InsuranceService randomResponseId, [], null, - {location: locationName}, + { location: locationName }, ); } @@ -334,7 +334,7 @@ export class InsuranceService // Item didnt have faceshield object pre-raid, add it if (!itemToReturn.upd.FaceShield) { - itemToReturn.upd.FaceShield = {Hits: insuredItemFromClient.hits}; + itemToReturn.upd.FaceShield = { Hits: insuredItemFromClient.hits }; } else { @@ -391,7 +391,7 @@ export class InsuranceService * @param traderId Id of trader item was insured with */ protected addGearToSend( - gear: {sessionID: string; pmcData: IPmcData; itemToReturnToPlayer: Item; traderId: string;}, + gear: { sessionID: string; pmcData: IPmcData; itemToReturnToPlayer: Item; traderId: string; }, ): void { const sessionId = gear.sessionID; diff --git a/project/src/services/MailSendService.ts b/project/src/services/MailSendService.ts index d5accb8a..242dd658 100644 --- a/project/src/services/MailSendService.ts +++ b/project/src/services/MailSendService.ts @@ -420,7 +420,7 @@ export class MailSendService parentItem.parentId = this.hashUtil.generate(); } - itemsToSendToPlayer = {stash: parentItem.parentId, data: []}; + itemsToSendToPlayer = { stash: parentItem.parentId, data: [] }; // Ensure Ids are unique and cont collide with items in player inventory later messageDetails.items = this.itemHelper.replaceIDs(null, messageDetails.items); diff --git a/project/src/services/ModCompilerService.ts b/project/src/services/ModCompilerService.ts index d02e72fb..833c22d7 100644 --- a/project/src/services/ModCompilerService.ts +++ b/project/src/services/ModCompilerService.ts @@ -109,7 +109,7 @@ export class ModCompilerService replacedText = text.replace(/(@spt-aki)/g, path.join(__dirname, "..").replace(/\\/g, "/")); } - const output = ts.transpileModule(replacedText, {compilerOptions: options}); + const output = ts.transpileModule(replacedText, { compilerOptions: options }); if (output.sourceMapText) { diff --git a/project/src/services/PaymentService.ts b/project/src/services/PaymentService.ts index ed6334c2..0b5c5ebd 100644 --- a/project/src/services/PaymentService.ts +++ b/project/src/services/PaymentService.ts @@ -49,7 +49,7 @@ export class PaymentService const trader = this.traderHelper.getTrader(request.tid, sessionID); // Track the amounts of each type of currency involved in the trade. - const currencyAmounts: {[key: string]: number;} = {}; + const currencyAmounts: { [key: string]: number; } = {}; // Delete barter items and track currencies if the action is "TradingConfirm". if (request.Action === "TradingConfirm") diff --git a/project/src/services/PlayerService.ts b/project/src/services/PlayerService.ts index ee66ee84..c416f7a8 100644 --- a/project/src/services/PlayerService.ts +++ b/project/src/services/PlayerService.ts @@ -26,7 +26,7 @@ export class PlayerService { let accExp = 0; - for (const [level, {exp}] of this.databaseServer.getTables().globals.config.exp.level.exp_table.entries()) + for (const [level, { exp }] of this.databaseServer.getTables().globals.config.exp.level.exp_table.entries()) { accExp += exp; diff --git a/project/src/services/ProfileFixerService.ts b/project/src/services/ProfileFixerService.ts index 2dcb1547..59731787 100644 --- a/project/src/services/ProfileFixerService.ts +++ b/project/src/services/ProfileFixerService.ts @@ -196,7 +196,7 @@ export class ProfileFixerService } else { - pmcProfile.Inventory.items.push({_id: hideoutStandAreaDb._id, _tpl: stageCurrentAt.container}); + pmcProfile.Inventory.items.push({ _id: hideoutStandAreaDb._id, _tpl: stageCurrentAt.container }); this.logger.debug( `Added missing gun stand inventory stash: ${hideoutStandAreaDb._id} tpl to ${stageCurrentAt.container}`, ); @@ -215,7 +215,10 @@ export class ProfileFixerService } else { - pmcProfile.Inventory.items.push({_id: hideoutStandSecondaryAreaDb._id, _tpl: stageCurrentAt.container}); + pmcProfile.Inventory.items.push({ + _id: hideoutStandSecondaryAreaDb._id, + _tpl: stageCurrentAt.container, + }); this.logger.debug( `Added missing gun stand inventory secondary stash: ${hideoutStandSecondaryAreaDb._id} tpl to ${stageCurrentAt.container}`, ); @@ -352,7 +355,7 @@ export class ProfileFixerService if (!fullProfile.aki) { this.logger.debug("Adding aki object to profile"); - fullProfile.aki = {version: this.watermark.getVersionTag(), receivedGifts: []}; + fullProfile.aki = { version: this.watermark.getVersionTag(), receivedGifts: [] }; } } @@ -396,7 +399,7 @@ export class ProfileFixerService if (!pmcProfile.UnlockedInfo) { this.logger.debug("Adding UnlockedInfo object to profile"); - pmcProfile.UnlockedInfo = {unlockedProductionRecipe: []}; + pmcProfile.UnlockedInfo = { unlockedProductionRecipe: [] }; } } @@ -685,7 +688,7 @@ export class ProfileFixerService { if (!slots.find((x) => x.locationIndex === i)) { - slots.push({locationIndex: i}); + slots.push({ locationIndex: i }); } } @@ -1085,7 +1088,7 @@ export class ProfileFixerService const statsCopy = this.jsonUtil.clone(fullProfile.characters.pmc.Stats); // Clear stats object - fullProfile.characters.pmc.Stats = {Eft: null}; + fullProfile.characters.pmc.Stats = { Eft: null }; fullProfile.characters.pmc.Stats.Eft = statsCopy; } diff --git a/project/src/services/RagfairPriceService.ts b/project/src/services/RagfairPriceService.ts index 22b57672..1bc169e5 100644 --- a/project/src/services/RagfairPriceService.ts +++ b/project/src/services/RagfairPriceService.ts @@ -29,7 +29,7 @@ export class RagfairPriceService implements OnLoad protected generatedDynamicPrices: boolean; protected generatedStaticPrices: boolean; - protected prices: IRagfairServerPrices = {static: {}, dynamic: {}}; + protected prices: IRagfairServerPrices = { static: {}, dynamic: {} }; constructor( @inject("HandbookHelper") protected handbookHelper: HandbookHelper, @@ -153,12 +153,12 @@ export class RagfairPriceService implements OnLoad public getAllFleaPrices(): Record { // assign static values first, then overwrite them with dynamic, any values not stored in dynamic data will be covered by static data - return {...this.prices.static, ...this.prices.dynamic}; + return { ...this.prices.static, ...this.prices.dynamic }; } public getAllStaticPrices(): Record { - return {...this.prices.static}; + return { ...this.prices.static }; } /** @@ -409,12 +409,12 @@ export class RagfairPriceService implements OnLoad * @param presets weapon presets to choose from * @returns Default preset object */ - protected getWeaponPreset(presets: IPreset[], weapon: Item): {isDefault: boolean; preset: IPreset;} + protected getWeaponPreset(presets: IPreset[], weapon: Item): { isDefault: boolean; preset: IPreset; } { const defaultPreset = presets.find((x) => x._encyclopedia); if (defaultPreset) { - return {isDefault: true, preset: defaultPreset}; + return { isDefault: true, preset: defaultPreset }; } if (presets.length === 1) @@ -434,6 +434,6 @@ export class RagfairPriceService implements OnLoad ); } - return {isDefault: false, preset: presets[0]}; + return { isDefault: false, preset: presets[0] }; } } diff --git a/project/src/services/RepairService.ts b/project/src/services/RepairService.ts index 4064fd87..de1f86f6 100644 --- a/project/src/services/RepairService.ts +++ b/project/src/services/RepairService.ts @@ -122,7 +122,7 @@ export class RepairService { const options: IProcessBuyTradeRequestData = { // eslint-disable-next-line @typescript-eslint/naming-convention - scheme_items: [{id: repairedItemId, count: Math.round(repairCost)}], + scheme_items: [{ id: repairedItemId, count: Math.round(repairCost) }], tid: traderId, Action: "", type: "", @@ -262,7 +262,7 @@ export class RepairService ): RepairDetails { // Find item to repair in inventory - const itemToRepair = pmcData.Inventory.items.find((x: {_id: string;}) => x._id === itemToRepairId); + const itemToRepair = pmcData.Inventory.items.find((x: { _id: string; }) => x._id === itemToRepairId); if (itemToRepair === undefined) { throw new Error(`Item ${itemToRepairId} not found, unable to repair`); @@ -405,11 +405,11 @@ export class RepairService if (!repairKitInInventory.upd) { this.logger.debug(`Repair kit: ${repairKitInInventory._id} in inventory lacks upd object, adding`); - repairKitInInventory.upd = {RepairKit: {Resource: maxRepairAmount}}; + repairKitInInventory.upd = { RepairKit: { Resource: maxRepairAmount } }; } if (!repairKitInInventory.upd.RepairKit?.Resource) { - repairKitInInventory.upd.RepairKit = {Resource: maxRepairAmount}; + repairKitInInventory.upd.RepairKit = { Resource: maxRepairAmount }; } } diff --git a/project/src/services/mod/CustomItemService.ts b/project/src/services/mod/CustomItemService.ts index 45835d5a..507fb962 100644 --- a/project/src/services/mod/CustomItemService.ts +++ b/project/src/services/mod/CustomItemService.ts @@ -155,7 +155,7 @@ export class CustomItemService */ protected addToHandbookDb(newItemId: string, parentId: string, priceRoubles: number): void { - this.tables.templates.handbook.Items.push({Id: newItemId, ParentId: parentId, Price: priceRoubles}); + this.tables.templates.handbook.Items.push({ Id: newItemId, ParentId: parentId, Price: priceRoubles }); } /** diff --git a/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts b/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts index a980bc5b..58675ee4 100644 --- a/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts +++ b/project/src/services/mod/dynamicRouter/DynamicRouterModService.ts @@ -10,7 +10,7 @@ export class DynamicRouterModService {} public registerDynamicRouter(name: string, routes: RouteAction[], topLevelRoute: string): void { - this.container.register(name, {useValue: new DynamicRouterMod(routes, topLevelRoute)}); + this.container.register(name, { useValue: new DynamicRouterMod(routes, topLevelRoute) }); this.container.registerType("DynamicRoutes", name); } } diff --git a/project/src/services/mod/onLoad/OnLoadModService.ts b/project/src/services/mod/onLoad/OnLoadModService.ts index 8145d480..f86887db 100644 --- a/project/src/services/mod/onLoad/OnLoadModService.ts +++ b/project/src/services/mod/onLoad/OnLoadModService.ts @@ -10,7 +10,7 @@ export class OnLoadModService public registerOnLoad(name: string, onLoad: () => void, getRoute: () => string): void { - this.container.register(name, {useValue: new OnLoadMod(onLoad, getRoute)}); + this.container.register(name, { useValue: new OnLoadMod(onLoad, getRoute) }); this.container.registerType("OnLoad", name); } } diff --git a/project/src/services/mod/onUpdate/OnUpdateModService.ts b/project/src/services/mod/onUpdate/OnUpdateModService.ts index 5c55e677..fdb384c5 100644 --- a/project/src/services/mod/onUpdate/OnUpdateModService.ts +++ b/project/src/services/mod/onUpdate/OnUpdateModService.ts @@ -10,7 +10,7 @@ export class OnUpdateModService public registerOnUpdate(name: string, onUpdate: (timeSinceLastRun: number) => boolean, getRoute: () => string): void { - this.container.register(name, {useValue: new OnUpdateMod(onUpdate, getRoute)}); + this.container.register(name, { useValue: new OnUpdateMod(onUpdate, getRoute) }); this.container.registerType("OnUpdate", name); } } diff --git a/project/src/services/mod/staticRouter/StaticRouterModService.ts b/project/src/services/mod/staticRouter/StaticRouterModService.ts index 14047c09..7b3d1e65 100644 --- a/project/src/services/mod/staticRouter/StaticRouterModService.ts +++ b/project/src/services/mod/staticRouter/StaticRouterModService.ts @@ -10,7 +10,7 @@ export class StaticRouterModService {} public registerStaticRouter(name: string, routes: RouteAction[], topLevelRoute: string): void { - this.container.register(name, {useValue: new StaticRouterMod(routes, topLevelRoute)}); + this.container.register(name, { useValue: new StaticRouterMod(routes, topLevelRoute) }); this.container.registerType("StaticRoutes", name); } } diff --git a/project/src/utils/HttpResponseUtil.ts b/project/src/utils/HttpResponseUtil.ts index 5549dfa0..c2ed1011 100644 --- a/project/src/utils/HttpResponseUtil.ts +++ b/project/src/utils/HttpResponseUtil.ts @@ -41,7 +41,7 @@ export class HttpResponseUtil public getUnclearedBody(data: any, err = 0, errmsg = null): string { - return this.jsonUtil.serialize({err: err, errmsg: errmsg, data: data}); + return this.jsonUtil.serialize({ err: err, errmsg: errmsg, data: data }); } public emptyResponse(): IGetBodyResponseData @@ -65,7 +65,7 @@ export class HttpResponseUtil errorCode = BackendErrorCodes.NONE, ): IItemEventRouterResponse { - output.warnings = [{index: 0, errmsg: message, code: errorCode.toString()}]; + output.warnings = [{ index: 0, errmsg: message, code: errorCode.toString() }]; return output; } diff --git a/project/src/utils/JsonUtil.ts b/project/src/utils/JsonUtil.ts index a4cbe075..534ac2bf 100644 --- a/project/src/utils/JsonUtil.ts +++ b/project/src/utils/JsonUtil.ts @@ -181,7 +181,7 @@ export class JsonUtil { try { - const {data, changed} = fixJson(jsonString); + const { data, changed } = fixJson(jsonString); if (changed) { // data invalid, return it this.logger.error(`${filePath} - Detected faulty json, please fix your json file using VSCodium`); diff --git a/project/src/utils/RandomUtil.ts b/project/src/utils/RandomUtil.ts index 5b45bf82..8323fa53 100644 --- a/project/src/utils/RandomUtil.ts +++ b/project/src/utils/RandomUtil.ts @@ -136,12 +136,12 @@ export class ProbabilityObjectArray extends Array = []): K[] { - const {probArray, keyArray} = this.reduce((acc, x) => + const { probArray, keyArray } = this.reduce((acc, x) => { acc.probArray.push(x.relativeProbability); acc.keyArray.push(x.key); return acc; - }, {probArray: [], keyArray: []}); + }, { probArray: [], keyArray: [] }); let probCumsum = this.cumulativeProbability(probArray); const drawnKeys = []; @@ -257,7 +257,7 @@ export class RandomUtil return this.getArrayValue(Object.keys(node)); } - public getKeyValue(node: {[x: string]: any;}): any + public getKeyValue(node: { [x: string]: any; }): any { return node[this.getKey(node)]; } @@ -374,7 +374,7 @@ export class RandomUtil if (n < 1) { - throw {name: "Invalid argument", message: `'n' must be 1 or greater (received ${n})`}; + throw { name: "Invalid argument", message: `'n' must be 1 or greater (received ${n})` }; } if (min === max) diff --git a/project/src/utils/VFS.ts b/project/src/utils/VFS.ts index fd835750..fa24c8ce 100644 --- a/project/src/utils/VFS.ts +++ b/project/src/utils/VFS.ts @@ -14,14 +14,14 @@ export class VFS { accessFilePromisify: (path: fs.PathLike, mode?: number) => Promise; copyFilePromisify: (src: fs.PathLike, dst: fs.PathLike, flags?: number) => Promise; - mkdirPromisify: (path: fs.PathLike, options: fs.MakeDirectoryOptions & {recursive: true;}) => Promise; + mkdirPromisify: (path: fs.PathLike, options: fs.MakeDirectoryOptions & { recursive: true; }) => Promise; readFilePromisify: (path: fs.PathLike) => Promise; writeFilePromisify: (path: fs.PathLike, data: string, options?: any) => Promise; readdirPromisify: ( path: fs.PathLike, - options?: BufferEncoding | {encoding: BufferEncoding; withFileTypes?: false;}, + options?: BufferEncoding | { encoding: BufferEncoding; withFileTypes?: false; }, ) => Promise; - statPromisify: (path: fs.PathLike, options?: fs.StatOptions & {bigint?: false;}) => Promise; + statPromisify: (path: fs.PathLike, options?: fs.StatOptions & { bigint?: false; }) => Promise; unlinkPromisify: (path: fs.PathLike) => Promise; rmdirPromisify: (path: fs.PathLike) => Promise; renamePromisify: (oldPath: fs.PathLike, newPath: fs.PathLike) => Promise; @@ -50,7 +50,7 @@ export class VFS try { // Create the command to add to the queue - const command = {uuid: crypto.randomUUID(), cmd: async () => await this.accessFilePromisify(filepath)}; + const command = { uuid: crypto.randomUUID(), cmd: async () => await this.accessFilePromisify(filepath) }; // Wait for the command completion await this.asyncQueue.waitFor(command); @@ -71,13 +71,13 @@ export class VFS public async copyAsync(filepath: fs.PathLike, target: fs.PathLike): Promise { - const command = {uuid: crypto.randomUUID(), cmd: async () => await this.copyFilePromisify(filepath, target)}; + const command = { uuid: crypto.randomUUID(), cmd: async () => await this.copyFilePromisify(filepath, target) }; await this.asyncQueue.waitFor(command); } public createDir(filepath: string): void { - fs.mkdirSync(filepath.substr(0, filepath.lastIndexOf("/")), {recursive: true}); + fs.mkdirSync(filepath.substr(0, filepath.lastIndexOf("/")), { recursive: true }); } public async createDirAsync(filepath: string): Promise @@ -85,7 +85,7 @@ export class VFS const command = { uuid: crypto.randomUUID(), cmd: async () => - await this.mkdirPromisify(filepath.substr(0, filepath.lastIndexOf("/")), {recursive: true}), + await this.mkdirPromisify(filepath.substr(0, filepath.lastIndexOf("/")), { recursive: true }), }; await this.asyncQueue.waitFor(command); } @@ -167,7 +167,7 @@ export class VFS public writeFile(filepath: any, data = "", append = false, atomic = true): void { - const options = append ? {flag: "a"} : {flag: "w"}; + const options = append ? { flag: "a" } : { flag: "w" }; if (!this.exists(filepath)) { @@ -194,7 +194,7 @@ export class VFS public async writeFileAsync(filepath: any, data = "", append = false, atomic = true): Promise { - const options = append ? {flag: "a"} : {flag: "w"}; + const options = append ? { flag: "a" } : { flag: "w" }; if (!await this.exists(filepath)) { @@ -376,7 +376,7 @@ export class VFS return files; } - const dirents = fs.readdirSync(directory, {encoding: "utf-8", withFileTypes: true}); + const dirents = fs.readdirSync(directory, { encoding: "utf-8", withFileTypes: true }); for (const dirent of dirents) { const res = resolve(directory, dirent.name); diff --git a/project/src/utils/logging/AbstractWinstonLogger.ts b/project/src/utils/logging/AbstractWinstonLogger.ts index 1facf66a..51a744ef 100644 --- a/project/src/utils/logging/AbstractWinstonLogger.ts +++ b/project/src/utils/logging/AbstractWinstonLogger.ts @@ -17,8 +17,8 @@ export abstract class AbstractWinstonLogger implements ILogger protected showDebugInConsole = false; protected filePath: string; protected logLevels = { - levels: {error: 0, warn: 1, succ: 2, info: 3, custom: 4, debug: 5}, - colors: {error: "red", warn: "yellow", succ: "green", info: "white", custom: "black", debug: "gray"}, + levels: { error: 0, warn: 1, succ: 2, info: 3, custom: 4, debug: 5 }, + colors: { error: "red", warn: "yellow", succ: "green", info: "white", custom: "black", debug: "gray" }, bgColors: { default: "", blackBG: "blackBG", @@ -41,7 +41,7 @@ export abstract class AbstractWinstonLogger implements ILogger this.showDebugInConsole = globalThis.G_DEBUG_CONFIGURATION; if (!fs.existsSync(this.getFilePath())) { - fs.mkdirSync(this.getFilePath(), {recursive: true}); + fs.mkdirSync(this.getFilePath(), { recursive: true }); } const transportsList: winston.transport[] = []; @@ -52,8 +52,8 @@ export abstract class AbstractWinstonLogger implements ILogger new transports.Console({ level: this.showDebugInConsole ? "debug" : "custom", format: format.combine( - format.colorize({all: true, colors: this.logLevels.colors}), - format.printf(({message}) => + format.colorize({ all: true, colors: this.logLevels.colors }), + format.printf(({ message }) => { return `${message}`; }), @@ -75,7 +75,7 @@ export abstract class AbstractWinstonLogger implements ILogger format.timestamp(), format.align(), format.json(), - format.printf(({timestamp, level, message}) => + format.printf(({ timestamp, level, message }) => { return `[${timestamp}] ${level}: ${message}`; }), @@ -85,7 +85,7 @@ export abstract class AbstractWinstonLogger implements ILogger } winston.addColors(this.logLevels.colors); - this.logger = createLogger({levels: this.logLevels.levels, transports: [...transportsList]}); + this.logger = createLogger({ levels: this.logLevels.levels, transports: [...transportsList] }); if (this.isLogExceptions()) { @@ -130,13 +130,13 @@ export abstract class AbstractWinstonLogger implements ILogger { const textColor = `${color} ${backgroundColor}`.trimEnd(); const tmpLogger = createLogger({ - levels: {custom: 0}, + levels: { custom: 0 }, level: "custom", transports: [ new transports.Console({ format: format.combine( - format.colorize({all: true, colors: {custom: textColor}}), - format.printf(({message}) => message), + format.colorize({ all: true, colors: { custom: textColor } }), + format.printf(({ message }) => message), ), }), ], @@ -146,7 +146,7 @@ export abstract class AbstractWinstonLogger implements ILogger if (typeof data === "string") { - command = {uuid: crypto.randomUUID(), cmd: async () => await tmpLogger.log("custom", data)}; + command = { uuid: crypto.randomUUID(), cmd: async () => await tmpLogger.log("custom", data) }; } else { @@ -161,25 +161,25 @@ export abstract class AbstractWinstonLogger implements ILogger public async error(data: string | Record): Promise { - const command: ICommand = {uuid: crypto.randomUUID(), cmd: async () => await this.logger.error(data)}; + const command: ICommand = { uuid: crypto.randomUUID(), cmd: async () => await this.logger.error(data) }; await this.asyncQueue.waitFor(command); } public async warning(data: string | Record): Promise { - const command: ICommand = {uuid: crypto.randomUUID(), cmd: async () => await this.logger.warn(data)}; + const command: ICommand = { uuid: crypto.randomUUID(), cmd: async () => await this.logger.warn(data) }; await this.asyncQueue.waitFor(command); } public async success(data: string | Record): Promise { - const command: ICommand = {uuid: crypto.randomUUID(), cmd: async () => await this.logger.succ(data)}; + const command: ICommand = { uuid: crypto.randomUUID(), cmd: async () => await this.logger.succ(data) }; await this.asyncQueue.waitFor(command); } public async info(data: string | Record): Promise { - const command: ICommand = {uuid: crypto.randomUUID(), cmd: async () => await this.logger.info(data)}; + const command: ICommand = { uuid: crypto.randomUUID(), cmd: async () => await this.logger.info(data) }; await this.asyncQueue.waitFor(command); } @@ -209,11 +209,11 @@ export abstract class AbstractWinstonLogger implements ILogger if (onlyShowInConsole) { - command = {uuid: crypto.randomUUID(), cmd: async () => await this.log(data, this.logLevels.colors.debug)}; + command = { uuid: crypto.randomUUID(), cmd: async () => await this.log(data, this.logLevels.colors.debug) }; } else { - command = {uuid: crypto.randomUUID(), cmd: async () => await this.logger.debug(data)}; + command = { uuid: crypto.randomUUID(), cmd: async () => await this.logger.debug(data) }; } await this.asyncQueue.waitFor(command); diff --git a/project/tests/CustomEnvironment.ts b/project/tests/CustomEnvironment.ts index 4dd917dd..e295b1aa 100644 --- a/project/tests/CustomEnvironment.ts +++ b/project/tests/CustomEnvironment.ts @@ -21,7 +21,7 @@ export default { Container.registerListTypes(container); // Override registration to the container. - container.register("WinstonLogger", WinstonLogger, {lifecycle: Lifecycle.Singleton}); + container.register("WinstonLogger", WinstonLogger, { lifecycle: Lifecycle.Singleton }); // Import the database. await importDatabase(container); diff --git a/project/tests/__factories__/ProfileInsurance.factory.ts b/project/tests/__factories__/ProfileInsurance.factory.ts index 88e8d501..83ea5629 100644 --- a/project/tests/__factories__/ProfileInsurance.factory.ts +++ b/project/tests/__factories__/ProfileInsurance.factory.ts @@ -6,7 +6,7 @@ import { Insurance } from "@spt-aki/models/eft/profile/IAkiProfile"; import { profileInsuranceFixture } from "@tests/__fixture__/profileInsurance.fixture"; import { format } from "date-fns"; -type DateInput = number | number[] | {[index: number]: number;}; +type DateInput = number | number[] | { [index: number]: number; }; export class ProfileInsuranceFactory { diff --git a/project/tests/__fixture__/profileInsurance.fixture.ts b/project/tests/__fixture__/profileInsurance.fixture.ts index 1e9008d2..dd26a560 100644 --- a/project/tests/__fixture__/profileInsurance.fixture.ts +++ b/project/tests/__fixture__/profileInsurance.fixture.ts @@ -9,387 +9,387 @@ export const profileInsuranceFixture: Insurance[] = [{ maxStorageTime: 345600, text: "", profileChangeEvents: [], - systemData: {date: "01.11.2023", time: "10:51", location: "factory4_day"}, + systemData: { date: "01.11.2023", time: "10:51", location: "factory4_day" }, }, items: [{ _id: "3679078e05f5b14466d6a730", _tpl: "5d6d3716a4b9361bc8618872", parentId: "5fe49444ae6628187a2e77b8", slotId: "hideout", - upd: {StackObjectsCount: 1, Repairable: {Durability: 55, MaxDurability: 55}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 55, MaxDurability: 55 } }, }, { _id: "911a0f04d5d9c7e239807ae0", _tpl: "5644bd2b4bdc2d3b4c8b4572", parentId: "5fe49444ae6628187a2e77b8", slotId: "hideout", - upd: {StackObjectsCount: 1, Repairable: {Durability: 97.7862549, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 97.7862549, MaxDurability: 100 } }, }, { _id: "695b13896108f765e8985698", _tpl: "5648a69d4bdc2ded0b8b457b", parentId: "5fe49444ae6628187a2e77b8", slotId: "hideout", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "bb49d6ceb3e87d8563a06455", _tpl: "5df8a4d786f77412672a1e3b", parentId: "5fe49444ae6628187a2e77b8", slotId: "hideout", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "631f8492de748dec852f7ddf", _tpl: "64abd93857958b4249003418", parentId: "5fe49444ae6628187a2e77b8", slotId: "hideout", - upd: {StackObjectsCount: 1, Repairable: {Durability: 49.2865, MaxDurability: 60}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 49.2865, MaxDurability: 60 } }, }, { _id: "a2b0c716162c5e31ec28c55a", _tpl: "5a16b8a9fcdbcb00165aa6ca", parentId: "3679078e05f5b14466d6a730", slotId: "mod_nvg", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "dc565f750342cb2d19eeda06", _tpl: "5d6d3be5a4b9361bc73bc763", parentId: "3679078e05f5b14466d6a730", slotId: "mod_equipment_001", - upd: {StackObjectsCount: 1, Repairable: {Durability: 29.33, MaxDurability: 29.33}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 29.33, MaxDurability: 29.33 } }, }, { _id: "e9ff62601669d9e2ea9c2fbb", _tpl: "5d6d3943a4b9360dbc46d0cc", parentId: "3679078e05f5b14466d6a730", slotId: "mod_equipment_002", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "ac134d7cf6c9d8e25edd0015", _tpl: "5c11046cd174af02a012e42b", parentId: "a2b0c716162c5e31ec28c55a", slotId: "mod_nvg", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "22274b895ecc80d51c3cba1c", _tpl: "5c110624d174af029e69734c", parentId: "ac134d7cf6c9d8e25edd0015", slotId: "mod_nvg", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}, Togglable: {On: true}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 }, Togglable: { On: true } }, }, { _id: "c9278dd8251e99578bf7a274", _tpl: "59c6633186f7740cf0493bb9", parentId: "911a0f04d5d9c7e239807ae0", slotId: "mod_gas_block", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "677c209ebb45445ebb42c405", _tpl: "5649ab884bdc2ded0b8b457f", parentId: "911a0f04d5d9c7e239807ae0", slotId: "mod_muzzle", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "8ada5c9cc26585281577c6eb", _tpl: "5649ae4a4bdc2d1b2b8b4588", parentId: "911a0f04d5d9c7e239807ae0", slotId: "mod_pistol_grip", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "4bd10f89836fd9f86aedcac1", _tpl: "5649af094bdc2df8348b4586", parentId: "911a0f04d5d9c7e239807ae0", slotId: "mod_reciever", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "8b1327270791b142ac341b03", _tpl: "5649d9a14bdc2d79388b4580", parentId: "911a0f04d5d9c7e239807ae0", slotId: "mod_sight_rear", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "566335b3df586f34b47f5e35", _tpl: "5649b2314bdc2d79388b4576", parentId: "911a0f04d5d9c7e239807ae0", slotId: "mod_stock", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "da8cde1b3024c336f6e06152", _tpl: "55d482194bdc2d1d4e8b456b", parentId: "911a0f04d5d9c7e239807ae0", slotId: "mod_magazine", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "1e0b177df108c0c117028812", _tpl: "57cffddc24597763133760c6", parentId: "c9278dd8251e99578bf7a274", slotId: "mod_handguard", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "bc041c0011d76f714b898400", _tpl: "57cffcd624597763133760c5", parentId: "1e0b177df108c0c117028812", slotId: "mod_mount_003", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "9f8d7880a6e0a47a211ec5d3", _tpl: "58491f3324597764bc48fa02", parentId: "8b1327270791b142ac341b03", slotId: "mod_scope", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "402b4086535a50ef7d9cef88", _tpl: "5649be884bdc2d79388b4577", parentId: "566335b3df586f34b47f5e35", slotId: "mod_stock", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "db2ef9442178910eba985b51", _tpl: "58d2946386f774496974c37e", parentId: "402b4086535a50ef7d9cef88", slotId: "mod_stock_000", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "3c32b7d47ad80e83749fa906", _tpl: "58d2912286f7744e27117493", parentId: "db2ef9442178910eba985b51", slotId: "mod_stock", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "574a9b5535585255cde19570", _tpl: "55d482194bdc2d1d4e8b456b", parentId: "695b13896108f765e8985698", slotId: "1", - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "696835b2badfb96623ea887c", _tpl: "55d482194bdc2d1d4e8b456b", parentId: "695b13896108f765e8985698", slotId: "2", - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "c2d5e23c7886e8ff02010731", _tpl: "55d482194bdc2d1d4e8b456b", parentId: "695b13896108f765e8985698", slotId: "3", - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "306de2f475a559610a4f6f1d", _tpl: "55d482194bdc2d1d4e8b456b", parentId: "695b13896108f765e8985698", slotId: "4", - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "eb0445b49a97e84e27d47f3c", _tpl: "5aa2ba71e5b5b000137b758f", parentId: "695b13896108f765e8985698", slotId: "5", - upd: {StackObjectsCount: 1}, - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: { StackObjectsCount: 1 }, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, }, { _id: "fad89a5bdfd23e3248123346", _tpl: "5fc5396e900b1d5091531e72", parentId: "695b13896108f765e8985698", slotId: "6", - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "b16c2a938954cd69c687c51a", _tpl: "5b4736b986f77405cb415c10", parentId: "695b13896108f765e8985698", slotId: "7", - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "a2b3019ac8d340eeb068d429", _tpl: "5ea18c84ecf1982c7712d9a2", parentId: "695b13896108f765e8985698", slotId: "10", - location: {x: 0, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1, Repairable: {Durability: 29, MaxDurability: 33}}, + location: { x: 0, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1, Repairable: { Durability: 29, MaxDurability: 33 } }, }, { _id: "0b3c5d183e8b506d655f85c4", _tpl: "644a3df63b0b6f03e101e065", parentId: "fad89a5bdfd23e3248123346", slotId: "mod_tactical", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "757211a0b648fe27b0475ded", _tpl: "59f8a37386f7747af3328f06", parentId: "b16c2a938954cd69c687c51a", slotId: "mod_foregrip", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "870a887c63ca30fb15736b3d", _tpl: "62a1b7fbc30cfa1d366af586", parentId: "bb49d6ceb3e87d8563a06455", slotId: "main", - upd: {StackObjectsCount: 1}, - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: { StackObjectsCount: 1 }, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, }, { _id: "f3de631a1bb2b74bd0160d9a", _tpl: "5d6d3be5a4b9361bc73bc763", parentId: "bb49d6ceb3e87d8563a06455", slotId: "main", - location: {x: 5, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1, Repairable: {Durability: 22.41, MaxDurability: 22.41}}, + location: { x: 5, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1, Repairable: { Durability: 22.41, MaxDurability: 22.41 } }, }, { _id: "351180f3248d45c71cb2ebdc", _tpl: "57c44b372459772d2b39b8ce", parentId: "870a887c63ca30fb15736b3d", slotId: "main", - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "7237f722106866f2df8dc8d1", _tpl: "56e33680d2720be2748b4576", parentId: "870a887c63ca30fb15736b3d", slotId: "main", - location: {x: 0, y: 3, r: "Horizontal", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 3, r: "Horizontal", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "d0cf00aff56ea520cdd94330", _tpl: "57c44dd02459772d2e0ae249", parentId: "351180f3248d45c71cb2ebdc", slotId: "mod_muzzle", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "5119653b2c66d57ee219e26f", _tpl: "57c44f4f2459772d2c627113", parentId: "351180f3248d45c71cb2ebdc", slotId: "mod_reciever", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "ed1ac0183a8af587110aa74e", _tpl: "5a9e81fba2750c00164f6b11", parentId: "351180f3248d45c71cb2ebdc", slotId: "mod_magazine", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "310a7d1bb07ae0e522f3f8e3", _tpl: "5a69a2ed8dc32e000d46d1f1", parentId: "351180f3248d45c71cb2ebdc", slotId: "mod_pistol_grip", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "8a7e3489197b3b98126447fd", _tpl: "6130ca3fd92c473c77020dbd", parentId: "351180f3248d45c71cb2ebdc", slotId: "mod_charge", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "e818616e11ae07aa05388759", _tpl: "5dff8db859400025ea5150d4", parentId: "351180f3248d45c71cb2ebdc", slotId: "mod_mount_000", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "768812984debf2756bece089", _tpl: "57c44e7b2459772d28133248", parentId: "d0cf00aff56ea520cdd94330", slotId: "mod_sight_rear", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "67c610585ed668baf4604931", _tpl: "59eb7ebe86f7740b373438ce", parentId: "d0cf00aff56ea520cdd94330", slotId: "mod_mount_000", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "80e9dffa49bfe263ab0128c7", _tpl: "6267c6396b642f77f56f5c1c", parentId: "67c610585ed668baf4604931", slotId: "mod_tactical_000", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "dee323443ce23ba8c54b9f1c", _tpl: "5cc9c20cd7f00c001336c65d", parentId: "67c610585ed668baf4604931", slotId: "mod_tactical_001", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "3008088022dd55f1c99e5a32", _tpl: "5c1cd46f2e22164bef5cfedb", parentId: "67c610585ed668baf4604931", slotId: "mod_foregrip", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "71e9f8d005c72940d857fe64", _tpl: "59d790f486f77403cb06aec6", parentId: "80e9dffa49bfe263ab0128c7", slotId: "mod_flashlight", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "8c610c6cc67115a5fc1662ff", _tpl: "56eabf3bd2720b75698b4569", parentId: "310a7d1bb07ae0e522f3f8e3", slotId: "mod_stock_000", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "9bf01177f0c1e346b2d65373", _tpl: "58d2912286f7744e27117493", parentId: "8c610c6cc67115a5fc1662ff", slotId: "mod_stock", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "7dd43ffa6e03c2da6cddc56e", _tpl: "6171407e50224f204c1da3c5", parentId: "e818616e11ae07aa05388759", slotId: "mod_scope", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "fa9da4ccf3630cb173c293f9", _tpl: "5b3b99475acfc432ff4dcbee", parentId: "7dd43ffa6e03c2da6cddc56e", slotId: "mod_scope_000", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "6e2727806fb12e12123e9a57", _tpl: "616554fe50224f204c1da2aa", parentId: "7dd43ffa6e03c2da6cddc56e", slotId: "mod_scope_001", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "2c868d4676adc934f897e9a7", _tpl: "61605d88ffa6e502ac5e7eeb", parentId: "7dd43ffa6e03c2da6cddc56e", slotId: "mod_scope_002", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "1b159fdc14c350f8a4a7e19e", _tpl: "58d39b0386f77443380bf13c", parentId: "6e2727806fb12e12123e9a57", slotId: "mod_scope", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "7691790ffc5290da292cab99", _tpl: "61657230d92c473c770213d7", parentId: "1b159fdc14c350f8a4a7e19e", slotId: "mod_scope", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "012a11e7dcb1280a1ab9d2f6", _tpl: "618168b350224f204c1da4d8", parentId: "7237f722106866f2df8dc8d1", slotId: "main", - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "38ca7415a458c4d22ba2f3c3", _tpl: "6130c43c67085e45ef1405a1", parentId: "012a11e7dcb1280a1ab9d2f6", slotId: "mod_muzzle", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "c5a0621ebf856ce1b0945efc", _tpl: "61816fcad92c473c770215cc", parentId: "012a11e7dcb1280a1ab9d2f6", slotId: "mod_sight_front", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "a74677b17c1c49edc002df9b", _tpl: "5dfa3d2b0dee1b22f862eade", parentId: "38ca7415a458c4d22ba2f3c3", slotId: "mod_muzzle", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }], }, { scheduledTime: 1698945140, @@ -400,272 +400,272 @@ export const profileInsuranceFixture: Insurance[] = [{ maxStorageTime: 518400, text: "", profileChangeEvents: [], - systemData: {date: "01.11.2023", time: "11:18", location: "factory4_day"}, + systemData: { date: "01.11.2023", time: "11:18", location: "factory4_day" }, }, items: [{ _id: "5ae1c2b99a0a339adc620148", _tpl: "5cebec38d7f00c00110a652a", parentId: "ad018df9da0cbf2726394ef1", slotId: "mod_mount_000", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "30f4bcb87bcc4604e27c02c1", _tpl: "5cc70146e4a949000d73bf6b", parentId: "ad018df9da0cbf2726394ef1", slotId: "mod_mount_001", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "ad018df9da0cbf2726394ef1", _tpl: "5cc70102e4a949035e43ba74", parentId: "3bc4ff5bd99f165dc75cbd25", slotId: "main", - upd: {StackObjectsCount: 1}, - location: {x: 3, y: 0, r: "Horizontal", isSearched: true}, + upd: { StackObjectsCount: 1 }, + location: { x: 3, y: 0, r: "Horizontal", isSearched: true }, }, { _id: "12c243bd6b3e486e61325f81", _tpl: "5cc82d76e24e8d00134b4b83", parentId: "5fe49444ae6628187a2e77b8", slotId: "hideout", - upd: {StackObjectsCount: 1, Repairable: {Durability: 99.93771, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 99.93771, MaxDurability: 100 } }, }, { _id: "760652d86ee78eed513e0ad7", _tpl: "5ab8f39486f7745cd93a1cca", parentId: "5fe49444ae6628187a2e77b8", slotId: "hideout", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "61ab4afefac354dfc64c7874", _tpl: "5b432d215acfc4771e1c6624", parentId: "5fe49444ae6628187a2e77b8", slotId: "hideout", - upd: {StackObjectsCount: 1, Repairable: {Durability: 30, MaxDurability: 30}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 30, MaxDurability: 30 } }, }, { _id: "285e9d9ae196ae4e336cd04f", _tpl: "5d5d87f786f77427997cfaef", parentId: "5fe49444ae6628187a2e77b8", slotId: "hideout", - upd: {StackObjectsCount: 1, Repairable: {Durability: 75, MaxDurability: 80}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 75, MaxDurability: 80 } }, }, { _id: "3bc4ff5bd99f165dc75cbd25", _tpl: "5f5e467b0bc58666c37e7821", parentId: "5fe49444ae6628187a2e77b8", slotId: "hideout", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "6bf5d8ee81a3c9aec21bbbad", _tpl: "5d5fca1ea4b93635fd598c07", parentId: "5fe49444ae6628187a2e77b8", slotId: "hideout", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "2371438cf809b5e483bf5d85", _tpl: "5cc70093e4a949033c734312", parentId: "12c243bd6b3e486e61325f81", slotId: "mod_magazine", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "7f890346ea5b2cbc68c3170f", _tpl: "5cc700b9e4a949000f0f0f25", parentId: "12c243bd6b3e486e61325f81", slotId: "mod_stock", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "12fb79a9c4929009ff8d89e1", _tpl: "5cc700ede4a949033c734315", parentId: "12c243bd6b3e486e61325f81", slotId: "mod_reciever", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "d4c5274082ed716e19447f46", _tpl: "5cc701d7e4a94900100ac4e7", parentId: "12c243bd6b3e486e61325f81", slotId: "mod_barrel", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "d819dd4d2b13de10e9d6d805", _tpl: "5cc6ea85e4a949000e1ea3c3", parentId: "12c243bd6b3e486e61325f81", slotId: "mod_charge", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "fc9a664cacc477c4e725a81a", _tpl: "5cc700d4e4a949000f0f0f28", parentId: "7f890346ea5b2cbc68c3170f", slotId: "mod_stock_000", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "372891c593cf14e176b93ce2", _tpl: "5cc7012ae4a949001252b43e", parentId: "12fb79a9c4929009ff8d89e1", slotId: "mod_mount_000", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "bd196435a57bdc433df1e49d", _tpl: "5cc7012ae4a949001252b43e", parentId: "12fb79a9c4929009ff8d89e1", slotId: "mod_mount_001", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "ea3349d29797354d835c2192", _tpl: "58491f3324597764bc48fa02", parentId: "12fb79a9c4929009ff8d89e1", slotId: "mod_scope", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "4ccf7c74ca7d2167deb0ae5c", _tpl: "626becf9582c3e319310b837", parentId: "372891c593cf14e176b93ce2", slotId: "mod_tactical", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "adfd3640fc93daf21c721ca6", _tpl: "5cc9c20cd7f00c001336c65d", parentId: "bd196435a57bdc433df1e49d", slotId: "mod_tactical", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "deeb36b1812790b0145d2532", _tpl: "5a16badafcdbcb001865f72d", parentId: "61ab4afefac354dfc64c7874", slotId: "mod_equipment_000", - upd: {StackObjectsCount: 1, Repairable: {Durability: 12, MaxDurability: 25}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 12, MaxDurability: 25 } }, }, { _id: "4c0e0548df904c384569190c", _tpl: "5ea058e01dbce517f324b3e2", parentId: "61ab4afefac354dfc64c7874", slotId: "mod_nvg", - upd: {StackObjectsCount: 1, Repairable: {Durability: 3, MaxDurability: 39}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 3, MaxDurability: 39 } }, }, { _id: "da82c293cabc705b30fef93a", _tpl: "5a398ab9c4a282000c5a9842", parentId: "61ab4afefac354dfc64c7874", slotId: "mod_mount", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "b8fc94611def6e9ba534a8b3", _tpl: "5a16b8a9fcdbcb00165aa6ca", parentId: "4c0e0548df904c384569190c", slotId: "mod_nvg", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "20d6193c1f399e6326ebbc10", _tpl: "5a16b93dfcdbcbcae6687261", parentId: "b8fc94611def6e9ba534a8b3", slotId: "mod_nvg", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "065c4f13b2bd8be266e1e809", _tpl: "57235b6f24597759bf5a30f1", parentId: "20d6193c1f399e6326ebbc10", slotId: "mod_nvg", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}, Togglable: {On: true}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 }, Togglable: { On: true } }, }, { _id: "1883b955ab202fa099809278", _tpl: "57d17c5e2459775a5c57d17d", parentId: "da82c293cabc705b30fef93a", slotId: "mod_flashlight", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "e3c9e50ce31900c950b4ff6f", _tpl: "5cc70093e4a949033c734312", parentId: "285e9d9ae196ae4e336cd04f", slotId: "1", - location: {x: 0, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "193259b5eb848af4d036bee5", _tpl: "5cc70093e4a949033c734312", parentId: "285e9d9ae196ae4e336cd04f", slotId: "2", - location: {x: 0, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "f97ce69443f63bbe8f8097a7", _tpl: "5cc70093e4a949033c734312", parentId: "285e9d9ae196ae4e336cd04f", slotId: "3", - location: {x: 0, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "5d1c154a8abcfa934e477ac4", _tpl: "5cc70093e4a949033c734312", parentId: "285e9d9ae196ae4e336cd04f", slotId: "4", - location: {x: 0, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "289f7af841690c5388095477", _tpl: "5cc70093e4a949033c734312", parentId: "285e9d9ae196ae4e336cd04f", slotId: "5", - location: {x: 0, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "3e6d578165b61aef9865f677", _tpl: "5cc70093e4a949033c734312", parentId: "285e9d9ae196ae4e336cd04f", slotId: "6", - location: {x: 0, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "338682523f8504f97f84f3ab", _tpl: "5cc70093e4a949033c734312", parentId: "285e9d9ae196ae4e336cd04f", slotId: "7", - location: {x: 0, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "6d18ac01aa04b16e4f0d5d2f", _tpl: "5cc70093e4a949033c734312", parentId: "285e9d9ae196ae4e336cd04f", slotId: "8", - location: {x: 0, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "ac4ed54d61daa0c5219f8522", _tpl: "5cc70093e4a949033c734312", parentId: "285e9d9ae196ae4e336cd04f", slotId: "9", - location: {x: 0, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "2460460ef3d3df5c1ce07edb", _tpl: "5cc70093e4a949033c734312", parentId: "285e9d9ae196ae4e336cd04f", slotId: "10", - location: {x: 0, y: 0, r: "Vertical", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Vertical", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "3aeb18aac0b532f34255f162", _tpl: "5cc70146e4a949000d73bf6b", parentId: "285e9d9ae196ae4e336cd04f", slotId: "11", - upd: {StackObjectsCount: 1}, - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + upd: { StackObjectsCount: 1 }, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, }, { _id: "bdb46107abbf1d92edaaf14e", _tpl: "6272379924e29f06af4d5ecb", parentId: "3aeb18aac0b532f34255f162", slotId: "mod_tactical", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "0caadd8507a36d9ea871e88e", _tpl: "5ab8f04f86f774585f4237d8", parentId: "3bc4ff5bd99f165dc75cbd25", slotId: "main", - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, - upd: {StackObjectsCount: 1}, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, + upd: { StackObjectsCount: 1 }, }, { _id: "240046eebc9040c1d7e58611", _tpl: "5ac66d015acfc400180ae6e4", parentId: "0caadd8507a36d9ea871e88e", slotId: "main", - location: {x: 0, y: 0, r: "Horizontal", isSearched: true}, + location: { x: 0, y: 0, r: "Horizontal", isSearched: true }, upd: { StackObjectsCount: 1, sptPresetId: "5acf7dfc86f774401e19c390", - Repairable: {Durability: 32, MaxDurability: 59}, - Foldable: {Folded: true}, + Repairable: { Durability: 32, MaxDurability: 59 }, + Foldable: { Folded: true }, }, }, { _id: "70b23c628fa17699d9a71e94", @@ -675,14 +675,14 @@ export const profileInsuranceFixture: Insurance[] = [{ upd: { StackObjectsCount: 1, sptPresetId: "5acf7dfc86f774401e19c390", - Repairable: {Durability: 32, MaxDurability: 59}, + Repairable: { Durability: 32, MaxDurability: 59 }, }, }, { _id: "7cc2e24dc6bc0716bdddc472", _tpl: "5943ee5a86f77413872d25ec", parentId: "240046eebc9040c1d7e58611", slotId: "mod_muzzle", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "7a51ebbad703082660d59d27", _tpl: "5649ade84bdc2d1b2b8b4587", @@ -691,14 +691,14 @@ export const profileInsuranceFixture: Insurance[] = [{ upd: { StackObjectsCount: 1, sptPresetId: "5acf7dfc86f774401e19c390", - Repairable: {Durability: 32, MaxDurability: 59}, + Repairable: { Durability: 32, MaxDurability: 59 }, }, }, { _id: "b481bc57436ed9a0c3abe7f3", _tpl: "5d2c76ed48f03532f2136169", parentId: "240046eebc9040c1d7e58611", slotId: "mod_reciever", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "5774ef80597c7f91bff40dbb", _tpl: "5ac50c185acfc400163398d4", @@ -707,20 +707,20 @@ export const profileInsuranceFixture: Insurance[] = [{ upd: { StackObjectsCount: 1, sptPresetId: "5acf7dfc86f774401e19c390", - Repairable: {Durability: 32, MaxDurability: 59}, + Repairable: { Durability: 32, MaxDurability: 59 }, }, }, { _id: "8b7c8e6ba172ac390c99a2ae", _tpl: "5ac66c5d5acfc4001718d314", parentId: "240046eebc9040c1d7e58611", slotId: "mod_magazine", - upd: {StackObjectsCount: 1}, + upd: { StackObjectsCount: 1 }, }, { _id: "1ed3a416b1fc7adbed1160df", _tpl: "6130ca3fd92c473c77020dbd", parentId: "240046eebc9040c1d7e58611", slotId: "mod_charge", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "bbe087661947c0d9c1cde146", _tpl: "5648b1504bdc2d9d488b4584", @@ -729,19 +729,19 @@ export const profileInsuranceFixture: Insurance[] = [{ upd: { StackObjectsCount: 1, sptPresetId: "5acf7dfc86f774401e19c390", - Repairable: {Durability: 32, MaxDurability: 59}, + Repairable: { Durability: 32, MaxDurability: 59 }, }, }, { _id: "724388f8110434efccd79b3a", _tpl: "544a3a774bdc2d3a388b4567", parentId: "b481bc57436ed9a0c3abe7f3", slotId: "mod_scope", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }, { _id: "8581038b0f795618a3d26c94", _tpl: "58d268fc86f774111273f8c2", parentId: "724388f8110434efccd79b3a", slotId: "mod_scope", - upd: {StackObjectsCount: 1, Repairable: {Durability: 100, MaxDurability: 100}}, + upd: { StackObjectsCount: 1, Repairable: { Durability: 100, MaxDurability: 100 } }, }], }]; diff --git a/project/tests/controllers/InsuranceController.test.ts b/project/tests/controllers/InsuranceController.test.ts index af6f94a9..4f2cd9e1 100644 --- a/project/tests/controllers/InsuranceController.test.ts +++ b/project/tests/controllers/InsuranceController.test.ts @@ -34,7 +34,7 @@ describe("InsuranceController", () => { const session1 = "session1"; const session2 = "session2"; - const profiles = {[session1]: {}, [session2]: {}}; + const profiles = { [session1]: {}, [session2]: {} }; const getProfilesSpy = vi.spyOn(insuranceController.saveServer, "getProfiles").mockReturnValue(profiles); const processReturnByProfileSpy = vi.spyOn(insuranceController, "processReturnByProfile").mockReturnValue( vi.fn(), @@ -246,11 +246,11 @@ describe("InsuranceController", () => const insurance = [{ _id: "1", upd: 1234567890, - items: [{_id: "1", parentId: "1", slotId: "1"}, {_id: "2", parentId: "1", slotId: "2"}], + items: [{ _id: "1", parentId: "1", slotId: "1" }, { _id: "2", parentId: "1", slotId: "2" }], }, { _id: "2", upd: 1234567890, - items: [{_id: "3", parentId: "2", slotId: "1"}, {_id: "4", parentId: "2", slotId: "2"}, { + items: [{ _id: "3", parentId: "2", slotId: "1" }, { _id: "4", parentId: "2", slotId: "2" }, { _id: "5", parentId: "2", slotId: "3", @@ -279,7 +279,7 @@ describe("InsuranceController", () => it("should return 0 if there are no items in any of the insurance packages", () => { - const insurance = [{_id: "1", upd: 1234567890, items: []}, {_id: "2", upd: 1234567890, items: []}]; + const insurance = [{ _id: "1", upd: 1234567890, items: [] }, { _id: "2", upd: 1234567890, items: [] }]; const expectedCount = 0; // Execute the method. @@ -295,12 +295,12 @@ describe("InsuranceController", () => it("should remove the specified insurance package from the profile", () => { const sessionID = "session-id"; - const packageToRemove = {date: "01.11.2023", time: "10:51", location: "factory4_day"}; + const packageToRemove = { date: "01.11.2023", time: "10:51", location: "factory4_day" }; const profile = { insurance: [{ - messageContent: {systemData: {date: "01.11.2023", time: "11:18", location: "factory4_day"}}, + messageContent: { systemData: { date: "01.11.2023", time: "11:18", location: "factory4_day" } }, }, { // This one should be removed - messageContent: {systemData: {date: "01.11.2023", time: "10:51", location: "factory4_day"}}, + messageContent: { systemData: { date: "01.11.2023", time: "10:51", location: "factory4_day" } }, }], }; @@ -322,10 +322,10 @@ describe("InsuranceController", () => it("should log a message indicating that the package was removed", () => { const sessionID = "session-id"; - const packageToRemove = {date: "01.11.2023", time: "10:51", location: "factory4_day"}; + const packageToRemove = { date: "01.11.2023", time: "10:51", location: "factory4_day" }; const profile = { insurance: [{ - messageContent: {systemData: {date: "01.11.2023", time: "10:51", location: "factory4_day"}}, + messageContent: { systemData: { date: "01.11.2023", time: "10:51", location: "factory4_day" } }, }], }; @@ -347,10 +347,10 @@ describe("InsuranceController", () => it("should not remove any packages if the specified package is not found", () => { const sessionID = "session-id"; - const packageToRemove = {date: "01.11.2023", time: "10:51", location: "factory4_day"}; + const packageToRemove = { date: "01.11.2023", time: "10:51", location: "factory4_day" }; const profile = { insurance: [{ - messageContent: {systemData: {date: "02.11.2023", time: "10:50", location: "factory4_night"}}, + messageContent: { systemData: { date: "02.11.2023", time: "10:50", location: "factory4_night" } }, }], }; @@ -917,7 +917,7 @@ describe("InsuranceController", () => { it("should log details for each attachment", () => { - const attachments = [{_id: "item1", name: "Item 1", maxPrice: 100}, { + const attachments = [{ _id: "item1", name: "Item 1", maxPrice: 100 }, { _id: "item2", name: "Item 2", maxPrice: 200, @@ -1165,7 +1165,7 @@ describe("InsuranceController", () => // Manually set one of the items to be orphaned. insured.items[0].parentId = "9999"; // Should not exist in the items array. insured.items[0].slotId = "main"; // Should not be "hideout". - insured.items[0].location = {x: 1, y: 2, r: 3, isSearched: true}; // Should be removed. + insured.items[0].location = { x: 1, y: 2, r: 3, isSearched: true }; // Should be removed. // Iterate over the items and find an individual orphaned item. const orphanedItem = insured.items.find((item) => @@ -1396,10 +1396,10 @@ describe("InsuranceController", () => // Setup shared test data. pmcData = { - Inventory: {items: [{_id: "item1", otherProps: "value1"}, {_id: "item2", otherProps: "value2"}]}, + Inventory: { items: [{ _id: "item1", otherProps: "value1" }, { _id: "item2", otherProps: "value2" }] }, InsuredItems: [], }; - body = {items: ["item1", "item2"], tid: "someTraderId"}; + body = { items: ["item1", "item2"], tid: "someTraderId" }; sessionId = "session-id"; // Setup shared mocks. @@ -1424,7 +1424,7 @@ describe("InsuranceController", () => expect(mockPayMoney).toHaveBeenCalledWith( pmcData, { - scheme_items: [{id: "item1", count: 100}, {id: "item2", count: 100}], + scheme_items: [{ id: "item1", count: 100 }, { id: "item2", count: 100 }], tid: "someTraderId", Action: "", type: "", @@ -1433,7 +1433,7 @@ describe("InsuranceController", () => scheme_id: 0, }, sessionId, - {warnings: [], otherProperty: "property-value"}, + { warnings: [], otherProperty: "property-value" }, ); }); @@ -1459,7 +1459,7 @@ describe("InsuranceController", () => // Define the expected payment options structure based on the setup data. const expectedPaymentOptions = { - scheme_items: [{id: "item1", count: 100}, {id: "item2", count: 100}], + scheme_items: [{ id: "item1", count: 100 }, { id: "item2", count: 100 }], tid: body.tid, Action: "", type: "", @@ -1498,7 +1498,7 @@ describe("InsuranceController", () => { // Override the payMoney mock to simulate a payment failure with a warning. const expectedPayMoneyReturn = { - warnings: [{index: 0, errmsg: "Not enough money to complete transaction", code: 500}], + warnings: [{ index: 0, errmsg: "Not enough money to complete transaction", code: 500 }], otherProperty: "property-value", }; mockPayMoney.mockReturnValue(expectedPayMoneyReturn); @@ -1517,7 +1517,7 @@ describe("InsuranceController", () => { // Override the payMoney mock to simulate a payment failure with a warning. const expectedPayMoneyReturn = { - warnings: [{index: 0, errmsg: "Not enough money to complete transaction", code: 500}], + warnings: [{ index: 0, errmsg: "Not enough money to complete transaction", code: 500 }], otherProperty: "property-value", }; mockPayMoney.mockReturnValue(expectedPayMoneyReturn); @@ -1542,18 +1542,18 @@ describe("InsuranceController", () => vi.spyOn(insuranceController.profileHelper, "getPmcProfile").mockReturnValue({ Inventory: { - items: [{_id: "itemId1", _tpl: "itemTpl1", otherProperty: "property-value1"}, { + items: [{ _id: "itemId1", _tpl: "itemTpl1", otherProperty: "property-value1" }, { _id: "itemId2", _tpl: "itemTpl2", otherProperty: "property-value2", - }, {_id: "itemId3", _tpl: "itemTpl3", otherProperty: "property-value3"}], + }, { _id: "itemId3", _tpl: "itemTpl3", otherProperty: "property-value3" }], }, }); }); it("should return an empty object if no traders and items are specified", () => { - const request = {traders: [], items: []}; + const request = { traders: [], items: [] }; const expected = {}; const result = insuranceController.cost(request, sessionId); @@ -1563,8 +1563,8 @@ describe("InsuranceController", () => it("should return an empty object if no items are specified", () => { - const request = {traders: ["prapor"], items: []}; - const expected = {prapor: {}}; + const request = { traders: ["prapor"], items: [] }; + const expected = { prapor: {} }; const result = insuranceController.cost(request, sessionId); @@ -1573,7 +1573,7 @@ describe("InsuranceController", () => it("should return an empty object if no trader is specified but items are", () => { - const request = {traders: [], items: ["itemId1", "itemId2"]}; + const request = { traders: [], items: ["itemId1", "itemId2"] }; const expected = {}; const result = insuranceController.cost(request, sessionId); @@ -1583,10 +1583,10 @@ describe("InsuranceController", () => it("should return the expected cost for each item and trader", () => { - const request = {traders: ["prapor", "therapist"], items: ["itemId1", "itemId2", "itemId3"]}; + const request = { traders: ["prapor", "therapist"], items: ["itemId1", "itemId2", "itemId3"] }; const expected = { - prapor: {itemTpl1: 100, itemTpl2: 200, itemTpl3: 300}, - therapist: {itemTpl1: 150, itemTpl2: 250, itemTpl3: 350}, + prapor: { itemTpl1: 100, itemTpl2: 200, itemTpl3: 300 }, + therapist: { itemTpl1: 150, itemTpl2: 250, itemTpl3: 350 }, }; // Mock the InsuranceService.getPremium method to return the expected values. @@ -1609,7 +1609,7 @@ describe("InsuranceController", () => "itemId4", // Doesn't exist in the player's inventory. ], }; - const expected = {prapor: {itemTpl1: 100, itemTpl2: 200}}; + const expected = { prapor: { itemTpl1: 100, itemTpl2: 200 } }; // Mock the InsuranceService.getPremium method to return the expected values. vi.spyOn(insuranceController.insuranceService, "getPremium").mockReturnValueOnce(100).mockReturnValueOnce( diff --git a/project/tests/generators/BotGenerator.test.ts b/project/tests/generators/BotGenerator.test.ts index c8f72397..05d9f402 100644 --- a/project/tests/generators/BotGenerator.test.ts +++ b/project/tests/generators/BotGenerator.test.ts @@ -59,11 +59,11 @@ describe("BotGenerator", () => { botGenerator.botConfig.chanceAssaultScavHasPlayerScavName = 0; - const mockPlayerProfile = {Info: {Nickname: "Player Nickname", Level: 1}}; + const mockPlayerProfile = { Info: { Nickname: "Player Nickname", Level: 1 } }; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); - const botJsonTemplate = {firstName: ["test"], lastName: []}; + const botJsonTemplate = { firstName: ["test"], lastName: [] }; const sessionId = "sessionId"; const isPlayerScav = false; @@ -77,10 +77,10 @@ describe("BotGenerator", () => { botGenerator.botConfig.showTypeInNickname = true; - const mockPlayerProfile = {Info: {Nickname: "Player Nickname", Level: 1}}; + const mockPlayerProfile = { Info: { Nickname: "Player Nickname", Level: 1 } }; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); - const botJsonTemplate = {firstName: ["test"], lastName: []}; + const botJsonTemplate = { firstName: ["test"], lastName: [] }; const sessionId = "sessionId"; const isPlayerScav = false; @@ -95,11 +95,11 @@ describe("BotGenerator", () => botGenerator.botConfig.showTypeInNickname = false; botGenerator.pmcConfig.addPrefixToSameNamePMCAsPlayerChance = 100; - const mockPlayerProfile = {Info: {Nickname: "Player", Level: 1}}; + const mockPlayerProfile = { Info: { Nickname: "Player", Level: 1 } }; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); vi.spyOn(botGenerator.localisationService, "getRandomTextThatMatchesPartialKey").mockReturnValue("test"); - const botJsonTemplate = {firstName: ["Player"], lastName: []}; + const botJsonTemplate = { firstName: ["Player"], lastName: [] }; const sessionId = "sessionId"; const isPlayerScav = false; @@ -113,10 +113,10 @@ describe("BotGenerator", () => { botGenerator.botConfig.chanceAssaultScavHasPlayerScavName = 100; - const mockPlayerProfile = {Info: {Nickname: "Player", Level: 1}}; + const mockPlayerProfile = { Info: { Nickname: "Player", Level: 1 } }; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); - const botJsonTemplate = {firstName: ["test"], lastName: []}; + const botJsonTemplate = { firstName: ["test"], lastName: [] }; const sessionId = "sessionId"; const isPlayerScav = true; @@ -132,10 +132,10 @@ describe("BotGenerator", () => botGenerator.databaseServer.getTables().bots.types.usec.firstName = ["usec"]; botGenerator.databaseServer.getTables().bots.types.bear.firstName = []; - const mockPlayerProfile = {Info: {Nickname: "Player", Level: 1}}; + const mockPlayerProfile = { Info: { Nickname: "Player", Level: 1 } }; vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(mockPlayerProfile); - const botJsonTemplate = {firstName: ["test"], lastName: []}; + const botJsonTemplate = { firstName: ["test"], lastName: [] }; const sessionId = "sessionId"; const isPlayerScav = false; diff --git a/project/tests/generators/BotLevelGenerator.test.ts b/project/tests/generators/BotLevelGenerator.test.ts index 762cb99f..8d8815a6 100644 --- a/project/tests/generators/BotLevelGenerator.test.ts +++ b/project/tests/generators/BotLevelGenerator.test.ts @@ -27,7 +27,7 @@ describe("BotLevelGenerator", () => { it("should return value between 5 and 10 when player is level 5 and max is 10", () => { - const levelDetails: MinMax = {min: 5, max: 10}; + const levelDetails: MinMax = { min: 5, max: 10 }; const botGenerationDetails: BotGenerationDetails = { isPmc: false, @@ -50,7 +50,7 @@ describe("BotLevelGenerator", () => { it("should return 10 when player level is 5 and delta is 5", () => { - const levelDetails: MinMax = {min: 5, max: 10}; + const levelDetails: MinMax = { min: 5, max: 10 }; const expTable = databaseServer.getTables().globals.config.exp.level.exp_table; @@ -61,7 +61,7 @@ describe("BotLevelGenerator", () => it("should return 79 when player level is above possible max (100), desired max is 100 and delta is 5", () => { - const levelDetails: MinMax = {min: 100, max: 100}; + const levelDetails: MinMax = { min: 100, max: 100 }; const expTable = databaseServer.getTables().globals.config.exp.level.exp_table; const playerLevel = 100; diff --git a/project/tests/helpers/InRaidHelper.test.ts b/project/tests/helpers/InRaidHelper.test.ts index 965ea126..d13f2e91 100644 --- a/project/tests/helpers/InRaidHelper.test.ts +++ b/project/tests/helpers/InRaidHelper.test.ts @@ -24,7 +24,7 @@ describe("InRaidHelper", () => it("should return negative value when player kills 2 scavs as scav", () => { const fenceStanding = 0; - const postRaidPlayerVictims = [{Side: "Savage", Role: "assault"}, {Side: "Savage", Role: "assault"}]; // Kills + const postRaidPlayerVictims = [{ Side: "Savage", Role: "assault" }, { Side: "Savage", Role: "assault" }]; // Kills const databaseServer = container.resolve("DatabaseServer"); const scavStandingChangeOnKill = databaseServer.getTables().bots.types.assault.experience.standingForKill; @@ -37,7 +37,7 @@ describe("InRaidHelper", () => it("should return positive value when player kills 2 PMCs of different sides as scav", () => { const fenceStanding = 0; - const postRaidPlayerVictims = [{Side: "Usec", Role: "sptUsec"}, {Side: "Bear", Role: "sptBear"}]; // Kills + const postRaidPlayerVictims = [{ Side: "Usec", Role: "sptUsec" }, { Side: "Bear", Role: "sptBear" }]; // Kills const databaseServer = container.resolve("DatabaseServer"); const bearStandingChangeOnKill = databaseServer.getTables().bots.types.bear.experience.standingForKill; @@ -51,10 +51,10 @@ describe("InRaidHelper", () => it("should return negative value when player kills 1 PMC, 1 boss and 2 scavs as scav", () => { const fenceStanding = 0; - const postRaidPlayerVictims = [{Side: "Usec", Role: "sptUsec"}, {Side: "savage", Role: "assault"}, { + const postRaidPlayerVictims = [{ Side: "Usec", Role: "sptUsec" }, { Side: "savage", Role: "assault" }, { Side: "savage", Role: "bossBoar", - }, {Side: "savage", Role: "assault"}]; // Kills + }, { Side: "savage", Role: "assault" }]; // Kills const databaseServer = container.resolve("DatabaseServer"); const usecStandingChangeOnKill = databaseServer.getTables().bots.types.bear.experience.standingForKill; @@ -72,7 +72,7 @@ describe("InRaidHelper", () => it("should return 0 when player kills bot with undefined standing as scav", () => { const fenceStanding = 0; - const postRaidPlayerVictims = [{Side: "savage", Role: "testRole"}]; // Kills + const postRaidPlayerVictims = [{ Side: "savage", Role: "testRole" }]; // Kills // Fake getFenceStandingChangeForKillAsScav() returning null vi.spyOn(inraidHelper, "getFenceStandingChangeForKillAsScav").mockReturnValueOnce(null).mockReturnValueOnce( diff --git a/project/tests/helpers/ItemHelper.test.ts b/project/tests/helpers/ItemHelper.test.ts index b00addb7..8e875727 100644 --- a/project/tests/helpers/ItemHelper.test.ts +++ b/project/tests/helpers/ItemHelper.test.ts @@ -249,7 +249,7 @@ describe("ItemHelper", () => { it("should set upd.StackObjectsCount to 1 if upd is undefined", () => { - const initialItem: Item = {_id: "", _tpl: ""}; + const initialItem: Item = { _id: "", _tpl: "" }; const fixedItem = itemHelper.fixItemStackCount(initialItem); expect(fixedItem.upd).toBeDefined(); @@ -258,7 +258,7 @@ describe("ItemHelper", () => it("should set upd.StackObjectsCount to 1 if upd.StackObjectsCount is undefined", () => { - const initialItem: Item = {_id: "", _tpl: "", upd: {}}; + const initialItem: Item = { _id: "", _tpl: "", upd: {} }; const fixedItem = itemHelper.fixItemStackCount(initialItem); expect(fixedItem.upd).toBeDefined(); @@ -267,7 +267,7 @@ describe("ItemHelper", () => it("should not change upd.StackObjectsCount if it is already defined", () => { - const initialItem: Item = {_id: "", _tpl: "", upd: {StackObjectsCount: 5}}; + const initialItem: Item = { _id: "", _tpl: "", upd: { StackObjectsCount: 5 } }; const fixedItem = itemHelper.fixItemStackCount(initialItem); expect(fixedItem.upd).toBeDefined(); @@ -452,7 +452,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "5b40e1525acfc4771e1c6611", // "HighCom Striker ULACH IIIA helmet (Black)" - upd: {Repairable: {Durability: 19, MaxDurability: 38}}, + upd: { Repairable: { Durability: 19, MaxDurability: 38 } }, }; const result = itemHelper.getItemQualityModifier(item); @@ -466,7 +466,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "5a38e6bac4a2826c6e06d79b", // "TOZ-106 20ga bolt-action shotgun" - upd: {Repairable: {Durability: 20, MaxDurability: 100}}, + upd: { Repairable: { Durability: 20, MaxDurability: 100 } }, }; const result = itemHelper.getItemQualityModifier(item); @@ -498,7 +498,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "5780cf7f2459777de4559322", // "Dorm room 314 marked key" - upd: {Key: {NumberOfUsages: 5}}, + upd: { Key: { NumberOfUsages: 5 } }, }; const result = itemHelper.getItemQualityModifier(item); @@ -531,7 +531,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" - upd: {RepairKit: {Resource: 600}}, + upd: { RepairKit: { Resource: 600 } }, }; const result = itemHelper.getItemQualityModifier(item); @@ -545,7 +545,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" - upd: {RepairKit: {Resource: 0}}, + upd: { RepairKit: { Resource: 0 } }, }; const result = itemHelper.getItemQualityModifier(item); @@ -559,7 +559,7 @@ describe("ItemHelper", () => it("should return the correct quality value for armor items", () => { const armor = itemHelper.getItem("5648a7494bdc2d9d488b4583")[1]; // "PACA Soft Armor" - const repairable: Repairable = {Durability: 25, MaxDurability: 50}; + const repairable: Repairable = { Durability: 25, MaxDurability: 50 }; const item: Item = { // Not used for armor, but required for the method. _id: "", _tpl: "", @@ -592,8 +592,8 @@ describe("ItemHelper", () => it("should return the correct quality value for weapon items", () => { const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" - const repairable: Repairable = {Durability: 50, MaxDurability: 100}; - const item: Item = {_id: "", _tpl: ""}; + const repairable: Repairable = { Durability: 50, MaxDurability: 100 }; + const item: Item = { _id: "", _tpl: "" }; // Cast the method to any to allow access to private/protected method. const result = (itemHelper as any).getRepairableItemQualityValue(weapon, repairable, item); @@ -609,7 +609,7 @@ describe("ItemHelper", () => Durability: 50, MaxDurability: 200, // This should be used now. }; - const item: Item = {_id: "", _tpl: ""}; + const item: Item = { _id: "", _tpl: "" }; // Cast the method to any to allow access to private/protected method. const result = (itemHelper as any).getRepairableItemQualityValue(weapon, repairable, item); @@ -625,7 +625,7 @@ describe("ItemHelper", () => Durability: 50, MaxDurability: undefined, // Remove the MaxDurability property value... Technically an invalid Type. }; - const item: Item = {_id: "", _tpl: ""}; + const item: Item = { _id: "", _tpl: "" }; // Mock the logger's error method to prevent it from being actually called. const loggerErrorSpy = vi.spyOn((itemHelper as any).logger, "error").mockImplementation(() => @@ -646,7 +646,7 @@ describe("ItemHelper", () => Durability: 50, MaxDurability: 0, // This is a problem. }; - const item: Item = {_id: "", _tpl: ""}; + const item: Item = { _id: "", _tpl: "" }; // Cast the method to any to allow access to private/protected method. const result = (itemHelper as any).getRepairableItemQualityValue(weapon, repairable, item); @@ -662,7 +662,7 @@ describe("ItemHelper", () => Durability: 50, MaxDurability: undefined, // Remove the MaxDurability property value... Technically an invalid Type. }; - const item: Item = {_id: "", _tpl: ""}; + const item: Item = { _id: "", _tpl: "" }; const loggerErrorSpy = vi.spyOn((itemHelper as any).logger, "error"); @@ -677,7 +677,7 @@ describe("ItemHelper", () => { it("should return an array containing only the parent ID when no children are found", () => { - const items: Item[] = [{_id: "1", _tpl: "", parentId: null}, {_id: "2", _tpl: "", parentId: null}, { + const items: Item[] = [{ _id: "1", _tpl: "", parentId: null }, { _id: "2", _tpl: "", parentId: null }, { _id: "3", _tpl: "", parentId: "2", @@ -688,7 +688,7 @@ describe("ItemHelper", () => it("should return array of child IDs when single-level children are found", () => { - const items: Item[] = [{_id: "1", _tpl: "", parentId: null}, {_id: "2", _tpl: "", parentId: "1"}, { + const items: Item[] = [{ _id: "1", _tpl: "", parentId: null }, { _id: "2", _tpl: "", parentId: "1" }, { _id: "3", _tpl: "", parentId: "1", @@ -699,18 +699,18 @@ describe("ItemHelper", () => it("should return array of child IDs when multi-level children are found", () => { - const items: Item[] = [{_id: "1", _tpl: "", parentId: null}, {_id: "2", _tpl: "", parentId: "1"}, { + const items: Item[] = [{ _id: "1", _tpl: "", parentId: null }, { _id: "2", _tpl: "", parentId: "1" }, { _id: "3", _tpl: "", parentId: "2", - }, {_id: "4", _tpl: "", parentId: "3"}]; + }, { _id: "4", _tpl: "", parentId: "3" }]; const result = itemHelper.findAndReturnChildrenByItems(items, "1"); expect(result).toEqual(["4", "3", "2", "1"]); }); it("should return an array containing only the parent ID when parent ID does not exist in items", () => { - const items: Item[] = [{_id: "1", _tpl: "", parentId: null}, {_id: "2", _tpl: "", parentId: "1"}]; + const items: Item[] = [{ _id: "1", _tpl: "", parentId: null }, { _id: "2", _tpl: "", parentId: "1" }]; const result = itemHelper.findAndReturnChildrenByItems(items, "3"); expect(result).toEqual(["3"]); }); @@ -747,7 +747,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" - upd: {StackObjectsCount: 5}, + upd: { StackObjectsCount: 5 }, }; const result = itemHelper.getItemStackSize(item); expect(result).toBe(5); @@ -762,7 +762,7 @@ describe("ItemHelper", () => const item: Item = { _id: itemId, _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" - upd: {BuyRestrictionCurrent: 0, BuyRestrictionMax: 1}, + upd: { BuyRestrictionCurrent: 0, BuyRestrictionMax: 1 }, }; const result = itemHelper.hasBuyRestrictions(item); expect(result).toBe(true); @@ -1024,7 +1024,7 @@ describe("ItemHelper", () => const mockTemplateItem = { _id: "571a29dc2459771fb2755a6a", _name: "mag_tt_toz_std_762x25tt_8", - _props: {Cartridges: [{_props: {filters: [{Filter: validAmmoItems}]}}]}, + _props: { Cartridges: [{ _props: { filters: [{ Filter: validAmmoItems }] } }] }, }; vi.spyOn((itemHelper as any).randomUtil, "getArrayValue").mockReturnValue(validAmmoItems[0]); @@ -1036,7 +1036,7 @@ describe("ItemHelper", () => it("should return null when passed template has empty cartridge property", () => { - const fakeTemplateItem = {_props: {Cartridges: [{}]}}; + const fakeTemplateItem = { _props: { Cartridges: [{}] } }; const result = itemHelper.getRandomCompatibleCaliberTemplateId(fakeTemplateItem as ITemplateItem); expect(result).toBe(null); diff --git a/project/tests/services/PaymentService.test.ts b/project/tests/services/PaymentService.test.ts index 9e78fa02..cea1dae3 100644 --- a/project/tests/services/PaymentService.test.ts +++ b/project/tests/services/PaymentService.test.ts @@ -50,8 +50,8 @@ describe("PaymentService", () => // Object representing the player's PMC inventory. const pmcData = { - TradersInfo: {[traderId]: {salesSum: 0, unlocked: true, disabled: false}}, - Inventory: {items: [moneyItem]}, + TradersInfo: { [traderId]: { salesSum: 0, unlocked: true, disabled: false } }, + Inventory: { items: [moneyItem] }, } as unknown as IPmcData; // Buy a factory map from Therapist... although it doesn't really matter what the item is as there's no @@ -63,7 +63,7 @@ describe("PaymentService", () => item_id: purchaseItemId, count: purchaseQuantity, scheme_id: 0, - scheme_items: [{id: costItemId, count: costAmount}], + scheme_items: [{ id: costItemId, count: costAmount }], } as IProcessBuyTradeRequestData; // Inconsequential profile ID @@ -71,7 +71,7 @@ describe("PaymentService", () => const itemEventRouterResponse = { warnings: [], - profileChanges: {sessionID: {_id: sessionID, items: {new: [], change: [], del: []}}}, + profileChanges: { sessionID: { _id: sessionID, items: { new: [], change: [], del: [] } } }, } as unknown as IItemEventRouterResponse; // Mock the logger debug method to return void. @@ -80,13 +80,13 @@ describe("PaymentService", () => // Mock the trader helper to return a trader with the currency of Roubles. const traderHelperGetTraderSpy = vi.spyOn((paymentService as any).traderHelper, "getTrader") - .mockReturnValue({tid: traderId, currency: "RUB"} as unknown as ITraderBase); + .mockReturnValue({ tid: traderId, currency: "RUB" } as unknown as ITraderBase); // Mock the addPaymentToOutput method to subtract the item cost from the money stack. const addPaymentToOutputSpy = vi.spyOn(paymentService as any, "addPaymentToOutput").mockImplementation(() => { moneyItem.upd.StackObjectsCount -= costAmount; - return {warnings: [], profileChanges: {[sessionID]: {items: {change: [moneyItem]}}}}; + return { warnings: [], profileChanges: { [sessionID]: { items: { change: [moneyItem] } } } }; }); // Mock the traderHelper lvlUp method to return void. diff --git a/project/vitest.config.ts b/project/vitest.config.ts index 166961b4..d3290ec2 100644 --- a/project/vitest.config.ts +++ b/project/vitest.config.ts @@ -7,7 +7,7 @@ export default defineConfig({ reporters: ["default"], root: "./", include: ["**/*.{test,spec}.?(c|m)[jt]s?(x)"], - cache: {dir: "./tests/__cache__"}, + cache: { dir: "./tests/__cache__" }, environment: "./tests/CustomEnvironment.ts", globals: true, coverage: { @@ -20,7 +20,7 @@ export default defineConfig({ exclude: ["src/models/**", "tests/**"], }, pool: "threads", - poolOptions: {threads: {singleThread: true, isolate: false}}, - alias: {"@spt-aki": path.resolve(__dirname, "src"), "@tests": path.resolve(__dirname, "tests")}, + poolOptions: { threads: { singleThread: true, isolate: false } }, + alias: { "@spt-aki": path.resolve(__dirname, "src"), "@tests": path.resolve(__dirname, "tests") }, }, });