refactor(repo)!: move apps, shared packages, and patch definitions

Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:

  apps/server        the local server (was packages/local-service),
                     package @wto/server
  packages/patcher   builds the game copy (was packages/build),
                     package @wto/patcher
  patches/exe        exe patch definitions (was exe-patches)
  patches/gui        GUI script patches (was gui-patches)

Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".

The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.

The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.


Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.

BREAKING CHANGE: Use @wto/server and @wto/patcher from the new workspace paths. Run the development build with scripts/build-game-copy.ts and pass --data.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 03:20:54 +08:00
1 parent 9c813ccf7d
commit 930ea07630
476 files changed
+275 -251

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
/**
* Activating classic items. Each request names the item by uid.
*
* cln_set_current_booster name:t (scripts items/itemsClasses/itemBooster.nut)
* Any number of boosters can be active (the scripts only warn that stacking lowers their
* effect). What they do in battle: battle/battle-boosters.ts.
* cln_set_current_personal_discount name:t (itemDiscount.nut)
* The item's lifetime after activation (expiredTimeHAfterActivation) starts now. The
* discount itself applies to purchases (items/personal-discounts.ts).
* cln_set_current_wager name:t wager:i (itemWager.nut)
* The stake is paid now, in golden eagles for goldWager contracts and in silver lions
* otherwise; it must be minWager, or (when maxWager is set) a minWager + k x wagerStep
* up to maxWager, as the scripts' stake slider offers. Only one contract runs: starting
* another replaces it, and the replaced one is gone (the scripts ask the player first,
* msgbox/conflictingWager). Counting stages and paying out: battle/battle-wager.ts.
*/
import { setParam, type BlkBlock } from '@wto/blk';
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
import { activate, activeUids, itemRecord, ownedItem, removeItem, setItemExpiry } from '../profile/profile-items.ts';
import { hoursToTicks, type ServerTime } from '../profile/server-time.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { ItemCatalogue } from './item-catalogue.ts';
export function activateBooster(profile: BlkBlock, uid: string): RuleOutcome {
const owned = ownedItem(profile, uid);
if (!owned || owned.type !== 'rateBooster' || owned.count < 1) return refused('BAD_PARAMS');
if (activeUids(profile, 'itemActiveBoosters').includes(uid)) return refused('NOT_AVAILABLE');
activate(profile, 'itemActiveBoosters', uid);
return ACCEPTED;
}
export function activateDiscount(profile: BlkBlock, catalogue: ItemCatalogue, uid: string, now: ServerTime): RuleOutcome {
const owned = ownedItem(profile, uid);
const item = owned && catalogue.item(owned.id);
if (!owned || !item || owned.type !== 'personalDiscounts') return refused('BAD_PARAMS');
if (activeUids(profile, 'itemActiveDiscounts').includes(uid)) return refused('NOT_AVAILABLE');
if (item.lifetimeHoursAfterActivation !== undefined) {
const end = now + hoursToTicks(item.lifetimeHoursAfterActivation);
if (owned.expiresAt === undefined || end < owned.expiresAt) setItemExpiry(profile, uid, end);
}
activate(profile, 'itemActiveDiscounts', uid);
return ACCEPTED;
}
export function startWager(profile: BlkBlock, catalogue: ItemCatalogue, uid: string, stake: number): RuleOutcome {
const owned = ownedItem(profile, uid);
const limits = owned && catalogue.item(owned.id)?.wager;
const record = itemRecord(profile, uid);
if (!owned || !limits || !record || owned.type !== 'wager') return refused('BAD_PARAMS');
const current = activeUids(profile, 'itemActiveWagers');
if (current.includes(uid)) return refused('NOT_AVAILABLE');
if (!isOfferedStake(stake, limits.minStake, limits.maxStake, limits.stakeStep)) return refused('BAD_PARAMS');
const price: Price = limits.goldenEagles ? { silverLions: 0, goldenEagles: stake } : { silverLions: stake, goldenEagles: 0 };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
for (const replaced of current) removeItem(profile, replaced);
setParam(record, 'wager', { type: 'int', value: stake });
setParam(record, 'numWins', { type: 'int', value: 0 });
setParam(record, 'numBattles', { type: 'int', value: 0 });
activate(profile, 'itemActiveWagers', uid);
return ACCEPTED;
}
function isOfferedStake(stake: number, min: number, max: number, step: number): boolean {
if (max === 0 || max === min) return stake === min;
return stake >= min && stake <= max && ((stake - min) % step === 0 || stake === max);
}
+37
View File
@@ -0,0 +1,37 @@
/**
* The classic items as the item rules see them: the definitions of
* config/items.blk by name, and which of them the shop sells.
*
* The shop sells an item that has a price and no purchase_feature: items behind a feature
* ("devItemShop") are only offered to accounts that have it (scripts items/itemsBase.nut
* checkPurchaseFeature), which players do not.
*/
import type { ItemDefinition } from '../game-data/datasets/item-catalogue.ts';
/** Item types the client's item storage knows (type table aces.exe 2.61.0.37 0x72b6240) that config/items.blk uses. */
export const ITEM_TYPES = ['rateBooster', 'personalDiscounts', 'wager', 'missionOrder', 'universalSpare'] as const;
export class ItemCatalogue {
readonly #items: ReadonlyMap<string, ItemDefinition>;
/** The most pieces one cln_buy_item may ask for (tuning/limits.jsonc). */
readonly maxPiecesPerPurchase: number;
constructor(definitions: readonly ItemDefinition[], maxPiecesPerPurchase: number) {
this.maxPiecesPerPurchase = maxPiecesPerPurchase;
const known = new Set<string>(ITEM_TYPES);
this.#items = new Map(definitions.filter((item) => known.has(item.type)).map((item) => [item.name, item]));
}
item(name: string): ItemDefinition | undefined {
return this.#items.get(name);
}
/** Items the shop sells, with their price per piece. */
forSale(): ItemDefinition[] {
return [...this.#items.values()].filter(isForSale);
}
}
export function isForSale(item: ItemDefinition): boolean {
return item.purchaseFeature === undefined && (item.silverLions > 0 || item.goldenEagles > 0);
}
+14
View File
@@ -0,0 +1,14 @@
/**
* Removing classic items whose time is up (items/<uid>/expiredTimeH, implementation notes section
* 4.2), together with their place in the active lists. Run whenever a profile is handed out
* or changed, so the client never gets an expired item.
*/
import type { BlkBlock } from '@wto/blk';
import { ownedItems, removeItem } from '../profile/profile-items.ts';
import type { ServerTime } from '../profile/server-time.ts';
export function removeExpiredItems(profile: BlkBlock, now: ServerTime): void {
for (const item of ownedItems(profile)) {
if (item.expiresAt !== undefined && item.expiresAt <= now) removeItem(profile, item.uid);
}
}
+81
View File
@@ -0,0 +1,81 @@
/**
* Giving the player classic items: purchases, the save editor and,
* later, rewards all go through here.
*
* Items that stack (canPacked: universal spares) are kept as one uid whose instCount grows;
* every other piece gets its own uid with instCount 1, because activation works per uid (the
* scripts activate uids[0] and the client marks a whole uid active), so pieces under one uid
* could not be activated one at a time.
*
* Expiry: expiredTimeH hours from now, but not after expiredAt (scripts items/itemsBase.nut
* takes the earlier of the two).
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { DiscountDefinition, ItemDefinition } from '../game-data/datasets/item-catalogue.ts';
import { addItem, ownedItems, setItemCount, type NewItem } from '../profile/profile-items.ts';
import { hoursToTicks, serverTimeFromUnixMs, type ServerTime } from '../profile/server-time.ts';
export function grantItem(profile: BlkBlock, item: ItemDefinition, pieces: number, now: ServerTime): void {
if (!Number.isSafeInteger(pieces) || pieces < 1) throw new RangeError(`pieces out of range: ${pieces}`);
if (item.stacks) {
const stack = ownedItems(profile).find((owned) => owned.id === item.name);
if (stack) {
setItemCount(profile, stack.uid, stack.count + pieces);
return;
}
addItem(profile, newItem(item, pieces, now), now);
return;
}
for (let piece = 0; piece < pieces; piece++) addItem(profile, newItem(item, 1, now), now);
}
/** When an item given now expires, or undefined for never. */
export function expiryOf(item: ItemDefinition, now: ServerTime): ServerTime | undefined {
const fromLifetime = item.lifetimeHours !== undefined ? now + hoursToTicks(item.lifetimeHours) : undefined;
const fixed = item.expiresAt !== undefined ? serverTimeFromUnixMs(item.expiresAt) : undefined;
if (fromLifetime === undefined) return fixed;
if (fixed === undefined) return fromLifetime;
return fixed < fromLifetime ? fixed : fromLifetime;
}
function newItem(item: ItemDefinition, count: number, now: ServerTime): NewItem {
const expiresAt = expiryOf(item, now);
return {
id: item.name,
type: item.type,
count,
...(expiresAt !== undefined ? { expiresAt } : {}),
...typeFields(item),
};
}
/** Per-type fields a new item starts with (the client's readers: implementation notes). */
function typeFields(item: ItemDefinition): { params?: BlkParam[]; blocks?: BlkBlock[] } {
if (item.type === 'wager') return { params: [intParam('numWins', 0), intParam('numBattles', 0), intParam('wager', 0)] };
if (item.type === 'personalDiscounts' && item.discount) {
return {
params: [intParam('purchasesCount', 0), intParam('purchasesMaxCount', item.discount.maxPurchases)],
blocks: [discountDescription(item.discount)],
};
}
return {};
}
/** discountsDesc{ <category>{ <key>:i aircrafts{ <vehicle>:i } } }, as config/items.blk has it. */
function discountDescription(discount: DiscountDefinition): BlkBlock {
return {
name: 'discountsDesc',
params: [],
blocks: discount.categories.map((category) => ({
name: category.name,
params: Object.entries(category.keys).map(([key, percent]) => intParam(key, percent)),
blocks: Object.keys(category.vehicles).length
? [{ name: 'aircrafts', params: Object.entries(category.vehicles).map(([vehicle, percent]) => intParam(vehicle, percent)), blocks: [] }]
: [],
})),
};
}
function intParam(name: string, value: number): BlkParam {
return { name, value: { type: 'int', value } };
}
+26
View File
@@ -0,0 +1,26 @@
/**
* Buying classic items (cln_buy_item, implementation notes; scripts items/itemsBase.nut
* _requestBuy): name:t count:i cost:i costGold:i.
*
* The client prices a purchase as the price-table price of one piece times the pieces it buys
* (getCost: wp_get_item_cost x sell_count_step; count is sell_count_step), so the offered price
* must be the piece price times count.
*/
import type { BlkBlock } from '@wto/blk';
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
import type { ServerTime } from '../profile/server-time.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import { isForSale, type ItemCatalogue } from './item-catalogue.ts';
import { grantItem } from './item-grants.ts';
export function buyItem(profile: BlkBlock, catalogue: ItemCatalogue, name: string, pieces: number, offered: Price, now: ServerTime): RuleOutcome {
const item = catalogue.item(name);
if (!item || pieces < 1 || pieces > catalogue.maxPiecesPerPurchase) return refused('BAD_PARAMS');
if (!isForSale(item)) return refused('NOT_AVAILABLE');
const price: Price = { silverLions: item.silverLions * pieces, goldenEagles: item.goldenEagles * pieces };
if (price.silverLions !== offered.silverLions || price.goldenEagles !== offered.goldenEagles) return refused('PRICE_CHANGED');
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
grantItem(profile, item, pieces, now);
return ACCEPTED;
}
@@ -0,0 +1,93 @@
/**
* What active personal discounts take off a vehicle's price, the
* same way the client prices it (wp_get_cost -> aces.exe 2.61.0.37 0x9158a0, key lookup 0x908590).
*
* Every active discount item is looked up in its "buy" category; the largest percentage wins.
* Inside one item, keys are tried in this order and a later match replaces an earlier one
* ("premium" = the vehicle has a golden eagle price):
* all, all_premium (premium only), rank<N> (premium: rank<N>_premium), <country>,
* <country>_premium (premium only), <country>_rank<N> (premium: <country>_rank<N>_premium),
* aircrafts{ <vehicle> }
* The price is then cut by floor(price x percent / 100) in both currencies.
*
* The client keeps each item's own discountsDesc (items/<uid>/discountsDesc), so the lookup
* reads the copy in the profile. A purchase made with a discount counts against the item that
* gave it (purchasesCount); when it reaches purchasesMaxCount the item is used up.
*/
import { findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
import { activeUids, itemRecord, removeItem } from '../profile/profile-items.ts';
import type { Price } from '../profile/profile-currency.ts';
import type { TreeVehicle } from '../research/tech-tree.ts';
const BUY = 'buy';
export interface VehicleDiscount {
readonly percent: number;
/** The active item that gives it; undefined when there is no discount. */
readonly uid?: string;
}
export function vehicleDiscount(profile: BlkBlock, vehicle: TreeVehicle): VehicleDiscount {
let best: VehicleDiscount = { percent: 0 };
for (const uid of activeUids(profile, 'itemActiveDiscounts')) {
const description = itemRecord(profile, uid);
const category = description && findBlock(findBlock(description, 'discountsDesc') ?? emptyBlock(), BUY);
if (!category) continue;
const percent = percentFor(category, vehicle);
if (percent > best.percent) best = { percent, uid };
}
return best;
}
export function discountedPrice(price: Price, percent: number): Price {
if (percent <= 0) return price;
return { silverLions: cut(price.silverLions, percent), goldenEagles: cut(price.goldenEagles, percent) };
}
/** Count a purchase against the discount item that gave the discount. */
export function recordDiscountUse(profile: BlkBlock, uid: string): void {
const record = itemRecord(profile, uid);
if (!record) return;
const used = intOf(record, 'purchasesCount') + 1;
const allowed = intOf(record, 'purchasesMaxCount');
if (allowed > 0 && used >= allowed) {
removeItem(profile, uid);
return;
}
setParam(record, 'purchasesCount', { type: 'int', value: used });
}
function percentFor(category: BlkBlock, vehicle: TreeVehicle): number {
const premium = vehicle.goldenEagles > 0;
const suffix = premium ? '_premium' : '';
const keys = [
'all',
...(premium ? ['all_premium'] : []),
...(vehicle.rank > 0 ? [`rank${vehicle.rank}${suffix}`] : []),
vehicle.country,
...(premium ? [`${vehicle.country}_premium`] : []),
...(vehicle.rank > 0 ? [`${vehicle.country}_rank${vehicle.rank}${suffix}`] : []),
];
let percent = 0;
for (const key of keys) percent = found(category, key) ?? percent;
const byVehicle = findBlock(category, 'aircrafts');
return (byVehicle && found(byVehicle, vehicle.name)) ?? percent;
}
function found(block: BlkBlock, key: string): number | undefined {
const value = findParam(block, key)?.value;
return value?.type === 'int' && value.value >= 0 ? value.value : undefined;
}
function cut(amount: number, percent: number): number {
return Math.max(0, amount - Math.floor((amount * percent) / 100));
}
function intOf(block: BlkBlock, name: string): number {
const value = findParam(block, name)?.value;
return value?.type === 'int' ? value.value : 0;
}
function emptyBlock(): BlkBlock {
return { name: '', params: [], blocks: [] };
}
+48
View File
@@ -0,0 +1,48 @@
/**
* Using universal spares on a vehicle (cln_apply_spare_item: uid:t unit:t useItemsCount:i;
* scripts items/itemsClasses/itemUniversalSpare.nut activateOnUnit).
*
* The vehicle must be owned and fit the item's conditions as the scripts check them
* (itemModBase.nut initConditions, itemUniversalSpare.nut canActivateOnUnit): one of its
* countries, its rank range, one of its unit types. Each piece used adds numSpares spares to
* hangar/<vehicle>/spareAircraftsCount, which stays within MAX_SPARE_AMOUNT like bought spares.
*/
import type { BlkBlock } from '@wto/blk';
import { ownsVehicle } from '../profile/profile-hangar.ts';
import { ownedItem, removeItem, setItemCount } from '../profile/profile-items.ts';
import { setSpareCount, spareCount } from '../profile/profile-vehicle-state.ts';
import { MAX_SPARE_AMOUNT } from '../modifications/spare-purchase.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { TechTree, TreeVehicle } from '../research/tech-tree.ts';
import type { VehicleType } from '../research/vehicle-types.ts';
import type { SpareConditions } from '../game-data/datasets/item-catalogue.ts';
import type { ItemCatalogue } from './item-catalogue.ts';
/** The scripts' unitType.lowerName (scripts unit/unitTypesList.nut). */
const UNIT_TYPE_NAME: Partial<Record<VehicleType, string>> = {
Aircraft: 'aircraft', Tank: 'tank', Ship: 'ship', Helicopter: 'helicopter', Boat: 'boat',
};
export function applyUniversalSpares(profile: BlkBlock, catalogue: ItemCatalogue, techTree: TechTree,
uid: string, vehicleName: string, pieces: number): RuleOutcome {
const owned = ownedItem(profile, uid);
const conditions = owned && catalogue.item(owned.id)?.spare;
const vehicle = techTree.vehicle(vehicleName);
if (!owned || !conditions || !vehicle || owned.type !== 'universalSpare') return refused('BAD_PARAMS');
if (pieces < 1 || pieces > owned.count) return refused('BAD_PARAMS');
if (!ownsVehicle(profile, vehicle.name) || !fits(vehicle, conditions)) return refused('NOT_AVAILABLE');
const spares = spareCount(profile, vehicle.name) + conditions.spares * pieces;
if (spares > MAX_SPARE_AMOUNT) return refused('NOT_AVAILABLE');
setSpareCount(profile, vehicle.name, spares);
if (owned.count === pieces) removeItem(profile, uid);
else setItemCount(profile, uid, owned.count - pieces);
return ACCEPTED;
}
function fits(vehicle: TreeVehicle, conditions: SpareConditions): boolean {
if (conditions.countries.length && !conditions.countries.includes(vehicle.country)) return false;
if (conditions.minRank !== undefined && vehicle.rank < conditions.minRank) return false;
if (conditions.maxRank !== undefined && vehicle.rank > conditions.maxRank) return false;
const typeName = UNIT_TYPE_NAME[vehicle.type];
return !conditions.unitTypes.length || (typeName !== undefined && conditions.unitTypes.includes(typeName));
}