Split the repository into apps, packages and patches

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.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 03:20:54 +08:00
1 parent f6cdab7ec7
commit 27fc535301
476 files changed
+275 -251

No files matched your search

@@ -0,0 +1,10 @@
/** Resolving the player a char request is for (the uidhint header, implementation notes). */
import type { Account, AccountStore } from '../../accounts/account-store.ts';
import type { CharAnswer } from '../char-answers.ts';
import type { CharActionContext } from '../char-action.ts';
/** Run the handler for the request's account; an unknown or missing user id is an authorisation error. */
export function withAccount(context: CharActionContext, accounts: AccountStore, run: (account: Account) => CharAnswer): CharAnswer {
const account = context.userId === undefined ? undefined : accounts.byUserId(context.userId);
return account ? run(account) : { kind: 'error', code: 'AUTH_REQ_ERROR' };
}
@@ -0,0 +1,202 @@
/** Char action names mapped to their protocol handlers (full list of names: implementation notes). */
import type { AccountStore } from '../../accounts/account-store.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import type { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import type { DecorShop } from '../../decor/decor-purchase.ts';
import type { ClanEconomy } from '../../game-data/datasets/clan-economy.ts';
import type { InventoryCatalogue } from '../../inventory/itemdef-catalogue.ts';
import type { TrophyCatalogue } from '../../inventory/trophy-catalogue.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import type { StoreCatalogue } from '../../store/store-catalogue.ts';
import type { UnlockShop } from '../../unlocks/unlock-purchase.ts';
import type { CharActionHandler } from '../char-action.ts';
import { acceptEula } from './agreement-actions.ts';
import {
clanChangeInfoAction,
clanCreateAction,
clanDisbandAction,
clanFindByPrefixAction,
clanGetAction,
clanGetLeaderboardAction,
clanGetLogAction,
clanLeaveAction,
clanMembershipRequestAction,
clanMembersUpgradeAction,
clansListShortInfoAction,
clanSetMembershipReqAction,
clanSyncProfileAction,
clanUpgradeAction,
} from './clan-actions.ts';
import {
clanAcceptCandidateAction,
clanChangeMemberRoleAction,
clanDismissMemberAction,
clanEditBlacklistAction,
clanRejectCandidateAction,
setClanBestRewardsAction,
} from './clan-moderation-actions.ts';
import { clientUpdateAction } from './client-update-actions.ts';
import { bulkSetGblkAction, getGeneralBlkAction, getMetaBlkAction, setGeneralBlkAction } from './cloud-settings-actions.ts';
import { bulkTrainCrews, trainCrew } from './crew-actions.ts';
import { purchaseSkillPointsAction, specializeCrewAction, upgradeCrewAction } from './crew-skill-actions.ts';
import { buyResourceAction } from './decor-actions.ts';
import { saveDecorLayoutsAction } from './decor-layout-actions.ts';
import {
buyTrophyAction,
consumeInventoryItemAction,
inventoryExchangeAction,
multiConsumeInventoryItemsAction,
purchaseInventoryItemAction,
recycleItemsAction,
} from './inventory-actions.ts';
import { activateBoosterAction, activateDiscountAction, applySpareItemAction, buyItemAction, startWagerAction } from './item-actions.ts';
import {
buyAllModificationsAction,
buyModificationAction,
buySparesAction,
buyWeaponsAction,
enableModificationsAction,
saveWeaponPresetsAction,
} from './modification-actions.ts';
import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts';
import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts';
import { priceEx } from './price-actions.ts';
import { buyAircraft, buySlot } from './purchase-actions.ts';
import { convertExp, moveExpToModuleAction, moveExpToUnitAction, resetResearchable, setResearchable } from './research-actions.ts';
import { buyNotResearchedClanUnitAction, flushClanExpToUnitAction, setResearchClanUnitAction } from './squadron-research-actions.ts';
import { setStartingInfo } from './starting-info-actions.ts';
import { buyEntitlementAction, entitlementsPriceEx } from './store-actions.ts';
import { buyUnlockAction } from './unlock-actions.ts';
import type { RepairRules } from '../../repair/repair-rules.ts';
import { finishBattleAction, type BattleActionDependencies } from './battle-actions.ts';
import { hangarMiscActionEntries } from './hangar-misc-actions.ts';
export interface ClanActionDependencies {
readonly store: ClanStore;
readonly economy: ClanEconomy;
}
export interface ActionDependencies {
readonly profiles: PlayerProfiles;
readonly accounts: AccountStore;
readonly research: ResearchRules;
readonly equipment: EquipmentCatalogue;
readonly crew: CrewSkillCatalogue;
readonly decor: DecorShop;
readonly unlocks: UnlockShop;
readonly items: ItemCatalogue;
readonly repair: RepairRules;
readonly store: StoreCatalogue;
readonly inventory: InventoryCatalogue;
readonly trophies: TrophyCatalogue;
readonly clans?: ClanActionDependencies;
readonly cloudSettings?: CloudSettingsStore;
readonly battle?: BattleActionDependencies;
readonly notifyInventoryChanged?: () => void;
}
export function actionTable(deps: ActionDependencies): ReadonlyMap<string, CharActionHandler> {
const entries: Array<[string, CharActionHandler]> = [
...coreActionEntries(deps),
...hangarMiscActionEntries(deps),
...(deps.clans ? clanActionEntries(deps, deps.clans) : []),
...(deps.cloudSettings ? cloudActionEntries(deps.accounts, deps.cloudSettings) : []),
...(deps.battle ? [['cln_wto_finish_battle', finishBattleAction(deps, deps.battle)] as [string, CharActionHandler]] : []),
];
return new Map<string, CharActionHandler>(entries);
}
function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionHandler]> {
const notifyInventory = deps.notifyInventoryChanged ?? (() => {});
const { techTree } = deps.research;
return [
['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)],
['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)],
['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)],
['cln_update', clientUpdateAction(deps.profiles, deps.accounts)],
['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)],
['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)],
['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.crew)],
['cln_train_aircraft', trainCrew(deps.profiles, deps.accounts, deps.crew)],
['cln_set_researchable', setResearchable(deps.profiles, deps.accounts, deps.research, deps.equipment)],
['cln_reset_researchable', resetResearchable(deps.profiles, deps.accounts, deps.research)],
['cln_convert_exp', convertExp(deps.profiles, deps.accounts, deps.research)],
['cln_move_exp_to_unit', moveExpToUnitAction(deps.profiles, deps.accounts, deps.research)],
['cln_move_exp_to_module', moveExpToModuleAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_buy_aircraft', buyAircraft(deps.profiles, deps.accounts, deps.research)],
['cln_buy_slot', buySlot(deps.profiles, deps.accounts, deps.research)],
['cln_get_price_ex', priceEx({ techTree, equipment: deps.equipment, decor: deps.decor, crew: deps.crew, unlocks: deps.unlocks, items: deps.items, trophies: deps.trophies, repair: deps.repair })],
['cln_buy_modification', buyModificationAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_buy_all_modification', buyAllModificationsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_buy_spare_aircrafts', buySparesAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_buy_unlock', buyUnlockAction(deps.profiles, deps.accounts, deps.unlocks)],
['cln_buy_weapon', buyWeaponsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_save_weapon_presets', saveWeaponPresetsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_enable_modifications', enableModificationsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_upgrade_crew', upgradeCrewAction(deps.profiles, deps.accounts, deps.crew)],
['cln_purchase_skill_points', purchaseSkillPointsAction(deps.profiles, deps.accounts, deps.crew)],
['cln_specialize_crew', specializeCrewAction(deps.profiles, deps.accounts, deps.crew)],
['cln_select_title', selectTitleAction(deps.profiles, deps.accounts)],
['cln_save_pilot_appearance', savePilotAppearanceAction(deps.profiles, deps.accounts)],
['cln_get_users_terse_info', usersTerseInfoAction(deps.profiles, deps.accounts, techTree, deps.clans?.store)],
['cln_save_profile_showcase', saveShowcaseAction(deps.profiles, deps.accounts)],
['cln_get_showcases', showcasesAction(deps.profiles, deps.accounts, techTree)],
['cln_buy_resource', buyResourceAction(deps.profiles, deps.accounts, deps.decor)],
['cln_save_decals', saveDecorLayoutsAction(deps.profiles, deps.accounts, 'decals')],
['cln_save_attachables', saveDecorLayoutsAction(deps.profiles, deps.accounts, 'attachables')],
['cln_buy_item', buyItemAction(deps.profiles, deps.accounts, deps.items)],
['cln_set_current_booster', activateBoosterAction(deps.profiles, deps.accounts)],
['cln_set_current_personal_discount', activateDiscountAction(deps.profiles, deps.accounts, deps.items)],
['cln_set_current_wager', startWagerAction(deps.profiles, deps.accounts, deps.items)],
['cln_apply_spare_item', applySpareItemAction(deps.profiles, deps.accounts, deps.items, techTree)],
['cln_get_entitlements_price_ex', entitlementsPriceEx(deps.store)],
['cln_buy_entitlement', buyEntitlementAction(deps.profiles, deps.accounts, deps.store)],
['cln_consume_inventory_item', consumeInventoryItemAction(deps.profiles, deps.accounts, deps.inventory, deps.items, notifyInventory)],
['cln_multi_consume_inventory_item_json', multiConsumeInventoryItemsAction(deps.profiles, deps.accounts, deps.inventory, deps.items, notifyInventory)],
['cln_inventory_purchase_item', purchaseInventoryItemAction(deps.profiles, deps.accounts, deps.inventory, notifyInventory)],
['cln_recycle_items', recycleItemsAction(deps.profiles, deps.accounts, deps.items, notifyInventory)],
['cln_inventory_exchange_items', inventoryExchangeAction(deps.profiles, deps.accounts, deps.inventory)],
['cln_buy_trophy', buyTrophyAction(deps.profiles, deps.accounts, deps.trophies, deps.items)],
];
}
function clanActionEntries(deps: ActionDependencies, clans: ClanActionDependencies): Array<[string, CharActionHandler]> {
return [
['cln_clan_get', clanGetAction(deps.accounts, clans.store)],
['cln_clan_get_leaderboard', clanGetLeaderboardAction(clans.store)],
['cln_clan_find_by_prefix', clanFindByPrefixAction(clans.store)],
['cln_clans_list_get_short_info', clansListShortInfoAction(clans.store)],
['cln_clan_get_log', clanGetLogAction(deps.accounts, clans.store)],
['cln_clan_create', clanCreateAction(deps.profiles, deps.accounts, clans.store, clans.economy)],
['cln_clan_change_info', clanChangeInfoAction(deps.profiles, deps.accounts, clans.store, clans.economy)],
['cln_clan_upgrade', clanUpgradeAction(deps.profiles, deps.accounts, clans.store, clans.economy)],
['cln_clan_members_upgrade', clanMembersUpgradeAction(deps.profiles, deps.accounts, clans.store, clans.economy)],
['cln_clan_set_membership_requirements', clanSetMembershipReqAction(deps.accounts, clans.store)],
['cln_clan_membership_request', clanMembershipRequestAction(deps.profiles, deps.accounts, clans.store)],
['cln_clan_leave', clanLeaveAction(deps.profiles, deps.accounts, clans.store)],
['cln_clan_disband', clanDisbandAction(deps.profiles, deps.accounts, clans.store)],
['cln_clan_sync_profile_and_clan', clanSyncProfileAction(deps.profiles, deps.accounts, clans.store)],
['ano_clan_accept_membership_request', clanAcceptCandidateAction(deps.profiles, deps.accounts, clans.store)],
['ano_clan_reject_membership_request', clanRejectCandidateAction(deps.profiles, deps.accounts, clans.store)],
['ano_clan_dismiss_member', clanDismissMemberAction(deps.profiles, deps.accounts, clans.store)],
['ano_clan_change_member_role', clanChangeMemberRoleAction(deps.profiles, deps.accounts, clans.store)],
['ano_clan_edit_blacklist', clanEditBlacklistAction(deps.accounts, clans.store)],
['cln_set_clan_best_rewards', setClanBestRewardsAction(deps.accounts, clans.store)],
['cln_set_research_clan_unit', setResearchClanUnitAction(deps.profiles, deps.accounts, clans.store, deps.research)],
['cln_flush_clan_exp_to_unit', flushClanExpToUnitAction(deps.profiles, deps.accounts, clans.store, deps.research)],
['cln_buy_not_researched_clans_unit', buyNotResearchedClanUnitAction(deps.profiles, deps.accounts, clans.store, deps.research)],
];
}
function cloudActionEntries(accounts: AccountStore, cloudSettings: CloudSettingsStore): Array<[string, CharActionHandler]> {
return [
['cln_get_meta_blk', getMetaBlkAction(accounts, cloudSettings)],
['cln_get_general_blk', getGeneralBlkAction(accounts, cloudSettings)],
['cln_set_general_blk', setGeneralBlkAction(accounts, cloudSettings)],
['cln_bulk_set_gblk', bulkSetGblkAction(accounts, cloudSettings)],
];
}
@@ -0,0 +1,57 @@
/**
* The player's acceptance of the end-user licence agreement.
*
* The client keeps the accepted version in its save object (offset 0xe970, read by the
* script function getAgreedEulaVersion at aces.exe 2.61.0.37 0x1c3e580) and fills it from
* exactly two places:
* - the profile's top-level int eulaVersionAccepted, when a profile is loaded (0x917870,
* called by the profile serializer 0x917740);
* - the answer to cln_accept_eula: GameSaveData::onAsyncEconTransComplete (0xeb5f60) reads
* eulaVersionAccepted and ndaVersionAccepted from the answer's top level when the job
* (type 12) succeeds (0xeb79bd..0xeb7a05).
* The stock login script (scripts/login/loginpseudothreadsconfig.nut) waits until the
* accepted version reaches the current one, so the acceptance has to be stored in the save
* and sent back.
*/
import { emptyBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
const EULA_VERSION = 'eulaVersionAccepted';
const NDA_VERSION = 'ndaVersionAccepted';
/**
* The only sender is the script function setAgreedEulaVersion (0x1c3e560), which always
* passes agreement type 0 (the EULA) to the request builder 0x298ea0; the body is
* {version:i, type:i}. Other types have no sender in 2.61.0.37 and are refused.
*/
const EULA_AGREEMENT_TYPE = 0;
/** cln_accept_eula: store the accepted EULA version and answer with the accepted versions. */
export function acceptEula(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const version = intParam(context.payload, 'version');
const type = intParam(context.payload, 'type');
if (version === undefined || type !== EULA_AGREEMENT_TYPE) return { kind: 'error', code: 'BAD_PARAMS' };
const profile = profiles.update(account.userId, (saved) => {
setParam(saved, EULA_VERSION, { type: 'int', value: version });
});
return { kind: 'data', blk: acceptedVersions(profile) };
});
}
/** Both versions, because the client overwrites both from the answer (a missing one reads as 0). */
function acceptedVersions(profile: BlkBlock): BlkBlock {
const answer = emptyBlock();
setParam(answer, EULA_VERSION, { type: 'int', value: intParam(profile, EULA_VERSION) ?? 0 });
setParam(answer, NDA_VERSION, { type: 'int', value: intParam(profile, NDA_VERSION) ?? 0 });
return answer;
}
function intParam(block: BlkBlock | undefined, name: string): number | undefined {
const value = block ? findParam(block, name)?.value : undefined;
return value?.type === 'int' ? value.value : undefined;
}
@@ -0,0 +1,69 @@
/**
* Char action `cln_wto_finish_battle`: receives the facts of a local battle (battle-report.ts),
* settles them into the player's save (battle-settlement.ts) and answers the updated profile,
* whose new `EULT_SESSION_RESULT` log carries the debriefing table.
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { parseBattleReport } from '../../battle/battle-report.ts';
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-settlement.ts';
import type { BattleEconomy } from '../../battle/battle-economy.ts';
import type { BattleStreaks } from '../../battle/battle-streaks.ts';
import { withoutSupportPlanes } from '../../battle/battle-support-planes.ts';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { ResearchEfficiency } from '../../research/research-efficiency.ts';
import type { RepairRules } from '../../repair/repair-rules.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
export interface BattleActionDependencies {
readonly sessions: BattleSessionStore;
readonly economy: BattleEconomy;
readonly efficiency: ResearchEfficiency;
readonly streaks: BattleStreaks;
/** Units whose lives and events are not settled (battle-support-planes.ts). */
readonly supportPlanes: ReadonlySet<string>;
}
export interface FinishBattleContext {
readonly profiles: PlayerProfiles;
readonly accounts: AccountStore;
readonly research: ResearchRules;
readonly equipment: EquipmentCatalogue;
readonly crew: CrewSkillCatalogue;
readonly items: ItemCatalogue;
readonly repair: RepairRules;
}
export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler {
const settlementDeps: BattleSettlementDeps = {
research: ctx.research,
efficiency: battle.efficiency,
equipment: ctx.equipment,
crew: ctx.crew,
economy: battle.economy,
streaks: battle.streaks,
items: ctx.items,
repair: ctx.repair,
};
return (context) => withAccount(context, ctx.accounts, (account) => {
const parsed = context.payload && parseBattleReport(context.payload);
if (!parsed) return { kind: 'error', code: 'BAD_PARAMS' };
const report = withoutSupportPlanes(parsed, battle.supportPlanes);
const session = battle.sessions.findForUser(report.sessionId, account.userId);
if (!session) return { kind: 'error', code: 'BAD_PARAMS' };
if (session.settled) {
return { kind: 'data', blk: clientProfile(ctx.profiles.profileOf(account.userId), account) };
}
const updated = ctx.profiles.update(account.userId, (profile) => {
settleBattle(profile, report, session, settlementDeps);
});
battle.sessions.markSettled(session.sessionId);
return { kind: 'data', blk: clientProfile(updated, account) };
});
}
@@ -0,0 +1,224 @@
/**
* Char action handlers for squadron (clan) directory, creation, upgrades, and player
* membership requests. Officer moderation and squadron vehicle
* research live in `clan-moderation-actions.ts` and `squadron-research-actions.ts`.
*/
import { emptyBlock, findBlock, type BlkBlock } from '@wto/blk';
import type { Account, AccountStore } from '../../accounts/account-store.ts';
import {
toClanInfoBlk,
toClanLeaderboardRowBlk,
toClanLogBlk,
toClanShortInfoBlk,
} from '../../clans/clan-blk.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import type { ClanEconomy } from '../../game-data/datasets/clan-economy.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { Price } from '../../profile/profile-currency.ts';
import type { RuleOutcome } from '../../research/rule-outcome.ts';
import type { CharActionContext, CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import {
boolParam,
headerOrPayloadBool,
headerOrPayloadId,
headerOrPayloadInt,
headerOrPayloadString,
intParam,
stringParam,
} from './payload-params.ts';
export function priceFromClanPayload(payload: BlkBlock): Price {
return {
silverLions: intParam(payload, 'cost') ?? 0,
goldenEagles: intParam(payload, 'costGold') ?? 0,
};
}
export function clanProfileRuleAction(
profiles: PlayerProfiles,
accounts: AccountStore,
_clans: ClanStore,
run: (context: CharActionContext, profile: BlkBlock, account: Account) => RuleOutcome,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' };
const updated = profiles.updateWhen(account.userId, (saved) => {
outcome = run(context, saved, account);
return outcome.ok;
});
if (!updated) return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
return { kind: 'data', blk: clientProfile(updated, account) };
});
}
export function clanGetAction(accounts: AccountStore, clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const clanId = headerOrPayloadId(context, 'clanId') ?? headerOrPayloadId(context, '_id');
const clanName = headerOrPayloadString(context, 'clanName');
const clanTag = headerOrPayloadString(context, 'clanTag');
const clan = (!clanId && !clanName && !clanTag)
? clans.clanOfUser(account.userId)?.clan
: clans.findClan({ clanId, clanName, clanTag });
if (!clan) return { kind: 'error', code: 'CLAN_NOT_FOUND' };
return { kind: 'data', blk: toClanInfoBlk(clan, clans.tuning) };
});
}
export function clanGetLeaderboardAction(clans: ClanStore): CharActionHandler {
return (context) => {
const rows = clans.queryLeaderboard({
start: headerOrPayloadInt(context, 'start') ?? 0,
count: headerOrPayloadInt(context, 'count') ?? 20,
sortField: headerOrPayloadString(context, 'sortField') ?? 'dr_era5_hist',
clanId: headerOrPayloadId(context, 'clanId'),
filterOpen: headerOrPayloadBool(context, 'filterOpen') ?? false,
filterNotFull: headerOrPayloadBool(context, 'filterNotFull') ?? false,
filterAutoAccept: headerOrPayloadBool(context, 'filterAutoAccept') ?? false,
});
return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos, clans.tuning)) } };
};
}
export function clanFindByPrefixAction(clans: ClanStore): CharActionHandler {
return (context) => {
const prefix = headerOrPayloadString(context, 'namePrefix') ?? headerOrPayloadString(context, 'tagPrefix') ?? '';
const rows = clans.queryLeaderboard({
start: headerOrPayloadInt(context, 'start') ?? 0,
count: headerOrPayloadInt(context, 'count') ?? 20,
sortField: 'activity',
prefix,
filterOpen: headerOrPayloadBool(context, 'filterOpen') ?? false,
filterNotFull: headerOrPayloadBool(context, 'filterNotFull') ?? false,
filterAutoAccept: headerOrPayloadBool(context, 'filterAutoAccept') ?? false,
});
return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos, clans.tuning)) } };
};
}
export function clansListShortInfoAction(clans: ClanStore): CharActionHandler {
return (context) => {
const body = context.payload && findBlock(context.payload, 'body');
const requestedIds = (body?.params ?? [])
.filter((p) => p.name === 'clanId' && p.value.type === 'string')
.map((p) => (p.value as { type: 'string'; value: string }).value);
const blocks = requestedIds.flatMap((id) => {
const clan = clans.byId(id);
return clan ? [toClanShortInfoBlk(clan, clans.tuning)] : [];
});
return { kind: 'data', blk: { name: '', params: [], blocks } };
};
}
export function clanGetLogAction(accounts: AccountStore, clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const clanId = headerOrPayloadId(context, '_id') ?? headerOrPayloadId(context, 'clanId');
const clan = clanId && clanId !== '-1' ? clans.byId(clanId) : clans.clanOfUser(account.userId)?.clan;
if (!clan) return { kind: 'data', blk: emptyBlock() };
const count = headerOrPayloadInt(context, 'count') ?? 20;
const events = headerOrPayloadString(context, 'events');
const last = headerOrPayloadString(context, 'last');
return { kind: 'data', blk: toClanLogBlk(clan, count, events, last) };
});
}
export function clanCreateAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, clanEconomy: ClanEconomy): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const payload = context.payload;
const offered = payload && priceFromClanPayload(payload);
const rawType = payload && stringParam(payload, 'type');
if (!payload || !offered || (rawType !== 'normal' && rawType !== 'battalion')) {
return { ok: false, refusal: 'BAD_PARAMS' };
}
return clans.createClan(profile, account, clanEconomy, {
name: stringParam(payload, 'name') ?? '',
tag: stringParam(payload, 'tag') ?? '',
slogan: stringParam(payload, 'slogan') ?? '',
region: stringParam(payload, 'region') ?? '',
desc: stringParam(payload, 'desc') ?? '',
announcement: stringParam(payload, 'announcement') ?? '',
type: rawType,
offered,
});
});
}
export function clanChangeInfoAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, clanEconomy: ClanEconomy): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const payload = context.payload;
if (!payload) return { ok: false, refusal: 'BAD_PARAMS' };
const clanId = headerOrPayloadId(context, '_id') ?? '-1';
const rawStatus = stringParam(payload, 'status');
return clans.editClanInfo(profile, account, clanEconomy, clanId, {
name: stringParam(payload, 'name'),
tag: stringParam(payload, 'tag'),
desc: stringParam(payload, 'desc'),
slogan: stringParam(payload, 'slogan'),
announcement: stringParam(payload, 'announcement'),
region: stringParam(payload, 'region'),
status: rawStatus === 'closed' ? 'closed' : rawStatus === 'open' ? 'open' : undefined,
});
});
}
export function clanUpgradeAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, clanEconomy: ClanEconomy): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const payload = context.payload;
if (!payload) return { ok: false, refusal: 'BAD_PARAMS' };
const clanId = headerOrPayloadId(context, '_id') ?? '-1';
return clans.upgradeClanToNormal(profile, account, clanEconomy, clanId, {
tag: stringParam(payload, 'tag') ?? '',
desc: stringParam(payload, 'desc') ?? '',
announcement: stringParam(payload, 'announcement') ?? '',
});
});
}
export function clanMembersUpgradeAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, clanEconomy: ClanEconomy): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const clanId = headerOrPayloadId(context, '_id') ?? '-1';
return clans.upgradeMembersLimit(profile, account, clanEconomy, clanId);
});
}
export function clanSetMembershipReqAction(accounts: AccountStore, clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const payload = context.payload;
const clanId = headerOrPayloadId(context, '_id') ?? '-1';
const reqBlk = payload && findBlock(payload, 'membership_req');
const autoaccept = (payload && boolParam(payload, 'autoaccept')) ?? false;
if (!clans.setMembershipRequirements(clanId, account, reqBlk, autoaccept)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
return { kind: 'done' };
});
}
export function clanMembershipRequestAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const clanId = headerOrPayloadId(context, '_id') ?? headerOrPayloadId(context, 'requestedClanId');
const clanName = headerOrPayloadString(context, 'name');
const clanTag = headerOrPayloadString(context, 'tag');
const cancel = headerOrPayloadBool(context, 'cancelRequest') ?? false;
const comment = headerOrPayloadString(context, 'comments');
return clans.requestOrCancelMembership(profile, account, { clanId, clanName, clanTag, cancel, comment });
});
}
export function clanLeaveAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (_context, profile, account) =>
clans.leaveClan(profile, account));
}
export function clanDisbandAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) =>
clans.disbandClan(profile, account, headerOrPayloadId(context, 'requestedClanId') ?? headerOrPayloadId(context, '_id')));
}
export function clanSyncProfileAction(profiles: PlayerProfiles, accounts: AccountStore, _clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const updated = profiles.profileOf(account.userId);
return { kind: 'data', blk: clientProfile(updated, account) };
});
}
@@ -0,0 +1,125 @@
/**
* Char action handlers for squadron officer moderation, blacklist, and best-rewards metadata
* (`ano_clan_*`, `cln_set_clan_best_rewards`; implementation notes; aces.exe 0x29d150, 0x29d540).
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import { ClanRole, roleCodeFromString, type ClanBestReward } from '../../clans/clan-types.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionContext, CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { headerOrPayloadId, headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts';
export function clanAcceptCandidateAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const targetUid = headerOrPayloadId(context, 'userid') ?? '';
const clanId = headerOrPayloadId(context, '_id');
const role = parseRoleParam(context) ?? ClanRole.REGULAR;
const targetAccount = accounts.byUserId(targetUid);
if (!targetUid || !clans.acceptCandidate(account, clanId, targetUid, targetAccount?.nick ?? `Pilot_${targetUid}`, role)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
if (targetAccount) profiles.profileOf(targetAccount.userId);
return { kind: 'done' };
});
}
export function clanRejectCandidateAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const targetUid = headerOrPayloadId(context, 'userid') ?? '';
const clanId = headerOrPayloadId(context, '_id');
const comments = headerOrPayloadString(context, 'comments') ?? '';
if (!targetUid || !clans.rejectCandidate(account, clanId, targetUid, comments)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
const targetAccount = accounts.byUserId(targetUid);
if (targetAccount) profiles.profileOf(targetAccount.userId);
return { kind: 'done' };
});
}
export function clanDismissMemberAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const targetUid = headerOrPayloadId(context, 'userid') ?? '';
const comments = headerOrPayloadString(context, 'comments') ?? '';
if (!targetUid || !clans.dismissMember(account, targetUid, comments)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
const targetAccount = accounts.byUserId(targetUid);
if (targetAccount) profiles.profileOf(targetAccount.userId);
return { kind: 'done' };
});
}
export function clanChangeMemberRoleAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const targetUid = headerOrPayloadId(context, 'userid') ?? '';
const newRole = parseRoleParam(context);
if (!targetUid || newRole === undefined || !clans.changeMemberRole(account, targetUid, newRole)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
const targetAccount = accounts.byUserId(targetUid);
if (targetAccount) profiles.profileOf(targetAccount.userId);
return { kind: 'done' };
});
}
export function clanEditBlacklistAction(accounts: AccountStore, clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const targetUid = headerOrPayloadId(context, 'userid') ?? '';
const clanId = headerOrPayloadId(context, '_id');
const mode = headerOrPayloadString(context, 'mode');
if (mode !== 'addToBlackList' && mode !== 'delFromBlackList') {
return { kind: 'error', code: 'BAD_PARAMS' };
}
const comments = headerOrPayloadString(context, 'comments') ?? '';
const targetNick = accounts.byUserId(targetUid)?.nick ?? '';
if (!targetUid || !clans.editBlacklist(account, clanId, targetUid, targetNick, mode === 'addToBlackList', comments)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
return { kind: 'done' };
});
}
export function setClanBestRewardsAction(accounts: AccountStore, clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
let parsed: { clanId?: string; bestRewards?: ClanBestReward[] };
try {
parsed = JSON.parse(context.rawText || '{}') as { clanId?: string; bestRewards?: ClanBestReward[] };
} catch {
return { kind: 'error', code: 'BAD_JSON' };
}
const clanId = parsed.clanId ?? clans.clanOfUser(account.userId)?.clan.id;
if (!clanId || !Array.isArray(parsed.bestRewards) || !clans.setBestRewards(clanId, account.userId, parsed.bestRewards)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
return { kind: 'done' };
});
}
/**
* Native `0x29d150` and `0x29d540` write `role:i=<ECMR_*>` into the request DataBlock; also
* accept role name strings in case a script caller passes `"REGULAR"` / `"OFFICER"` in headers.
*/
function parseRoleParam(context: CharActionContext): number | undefined {
const intRole = headerOrPayloadInt(context, 'role');
if (intRole !== undefined && intRole >= 1 && intRole <= 6) return intRole;
const strRole = headerOrPayloadString(context, 'role');
return strRole ? roleCodeFromString(strRole) : undefined;
}
@@ -0,0 +1,20 @@
/**
* `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`):
* triggered by `save_online_single_job` when the client marks seen user logs as disabled
* (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar
* auto-repair / auto-refill / auto-buy-modifications and map preferences. Answers the whole
* updated profile.
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { applyClientProfileUpdate } from '../../profile/profile-client-settings.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { ACCEPTED } from '../../research/rule-outcome.ts';
import type { CharActionHandler } from '../char-action.ts';
import { ruleAction } from './rule-answer.ts';
export function clientUpdateAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => (profile) => {
applyClientProfileUpdate(profile, payload);
return ACCEPTED;
});
}
@@ -0,0 +1,81 @@
/**
* Char actions for `online_storage` / `generalBlk` cloud settings sync (implementation notes;
* aces.exe 2.61.0.37: `cln_get_meta_blk` 0x4662b3f, `cln_get_general_blk` 0x46677df,
* `cln_set_general_blk` 0x4666c51, `cln_bulk_set_gblk` 0x4663cfd).
*/
import { emptyBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { isSupportedGeneralBlkType, type CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
import type { CharActionHandler } from '../char-action.ts';
import {
buildContainerBlk,
computeContentHash,
isPbbdStream,
normalizeContainerBlk,
parsePbbdBulkUploads,
unpackCloudBlk,
} from '../pbbd-stream.ts';
import { withAccount } from './account-context.ts';
import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts';
/**
* `cln_get_meta_blk`: returns schema, compression negotiation, and saved block versions/hashes.
* `GetMetaHandler::handleResponse` (0x46659c0 -> 0x3280a50) parses the raw HTTP body directly
* with `DataBlock::loadFromStream` without stripping the `'i'` char compression marker.
*/
export function getMetaBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => ({
kind: 'raw-blk',
blk: cloudSettings.buildMetaBlk(account.userId),
}));
}
/**
* `cln_get_general_blk`: returns `ContainerBlk` (`version:i`, `content { ... }`) for a valid `blkType`.
* `LoadingHandler::handleResponse` (0x4667930 -> `ContainerBlk::load` 0x466a9e0 -> 0x3280a50)
* likewise reads bare binary BLK directly from the HTTP response buffer.
*/
export function getGeneralBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const blkType = headerOrPayloadString(context, 'blkType');
if (!blkType || !isSupportedGeneralBlkType(blkType)) return { kind: 'error', code: 'BAD_PARAM' };
const stored = cloudSettings.loadContainer(account.userId, blkType) ?? buildContainerBlk(1, emptyBlock('content'));
return { kind: 'raw-blk', blk: stored };
});
}
/** `cln_set_general_blk`: stores a single `ContainerBlk` uploaded by the client and answers `!OK`. */
export function setGeneralBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const blkType = headerOrPayloadString(context, 'type') ?? headerOrPayloadString(context, 'blkType');
if (!blkType || !isSupportedGeneralBlkType(blkType)) return { kind: 'error', code: 'BAD_PARAM' };
const rawVer = headerOrPayloadInt(context, 'version');
const headerVersion = rawVer !== undefined && rawVer > 0 ? rawVer : 1;
const rawBody = context.rawBody ?? new Uint8Array(0);
const decoded = unpackCloudBlk(rawBody, context.headerParam('compr')) ?? context.payload;
if (!decoded) return { kind: 'error', code: 'BAD_PARAM' };
const normalized = normalizeContainerBlk(decoded, headerVersion);
const contentHash = headerOrPayloadString(context, 'contentHash') ?? computeContentHash(normalized.content);
const ok = cloudSettings.saveUpload(account.userId, {
blkType,
version: normalized.version,
contentHash,
container: normalized.container,
});
return ok ? { kind: 'done' } : { kind: 'error', code: 'BAD_PARAM' };
});
}
/** `cln_bulk_set_gblk`: unpacks a `PBBD` batch stream (`store_gblk` / `bigquery` / `logout`) and answers `!OK`. */
export function bulkSetGblkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const rawBody = context.rawBody ?? new Uint8Array(0);
if (rawBody.byteLength === 0 || !isPbbdStream(rawBody)) return { kind: 'error', code: 'BAD_PARAM' };
const uploads = parsePbbdBulkUploads(rawBody);
if (uploads.length > 0) cloudSettings.saveBulkUploads(account.userId, uploads);
return { kind: 'done' };
});
}
@@ -0,0 +1,70 @@
/**
* Crew actions. The client applies the answer to each as a profile update (aces.exe
* 2.61.0.37 GameSaveData::onAsyncEconTransComplete 0xeb5f60: job types 11 and 13 are both in
* the profile set, mask 0x301800822fbf at 0xeb61c4), so each answers the whole updated profile.
*
* cln_bulk_train_aircraft (job type 13, sent with char_send_blk, 0x2991f0): put vehicles into
* several crew slots at once; the stock slotbar sends it when the player applies a slotbar
* preset (gui.vromfs.bin scripts/crew/crewTrain.nut batchTrainCrew). Body: the crew slot list
* (crew-slots-payload.ts).
*
* cln_train_aircraft (job type 11, sent by the native chard.trainCrewAircraft, 0x299b40):
* take a vehicle into one crew slot, or clear the slot (scripts/crew/crewTakeUnitProcess.nut),
* or only train the crew for it (scripts/crew/crewActionsWithMsgBox.nut
* trainCrewUnitWithoutSwitchCurrUnit). Body:
* aircraft:t the vehicle; "" clears the slot
* idx:i the crew id
* keep_curr:b yes: train the crew for the vehicle, leave the slot as it is
*/
import { findParam, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import { trainingFee } from '../../crew/crew-training.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import { assignCrewSlots, canAssignCrewSlots, trainCrewKeepingSlot, type CrewSlotAssignment } from '../../profile/crew-slots.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { canAfford, pay } from '../../profile/profile-currency.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { readCrewSlots } from './crew-slots-payload.ts';
export function bulkTrainCrews(profiles: PlayerProfiles, accounts: AccountStore, crew: CrewSkillCatalogue): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const assignments = context.payload && readCrewSlots(context.payload);
const current = profiles.profileOf(account.userId);
if (!assignments || !canAssignCrewSlots(current, assignments)) return { kind: 'error', code: 'BAD_PARAMS' };
const fee = trainingFee(current, crew, assignments);
if (!canAfford(current, fee)) return { kind: 'error', code: 'NOT_ENOUGH_MONEY' };
const profile = profiles.update(account.userId, (saved) => {
pay(saved, fee);
assignCrewSlots(saved, assignments);
});
return { kind: 'data', blk: clientProfile(profile, account) };
});
}
export function trainCrew(profiles: PlayerProfiles, accounts: AccountStore, crew: CrewSkillCatalogue): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const request = context.payload && readTrainCrew(context.payload);
if (!request || (request.keepCurrent && request.vehicle === '')) return { kind: 'error', code: 'BAD_PARAMS' };
const { keepCurrent, ...assignment } = request;
const current = profiles.profileOf(account.userId);
if (!canAssignCrewSlots(current, [assignment])) return { kind: 'error', code: 'BAD_PARAMS' };
const fee = trainingFee(current, crew, [assignment]);
if (!canAfford(current, fee)) return { kind: 'error', code: 'NOT_ENOUGH_MONEY' };
const profile = profiles.update(account.userId, (saved) => {
pay(saved, fee);
if (keepCurrent) trainCrewKeepingSlot(saved, assignment);
else assignCrewSlots(saved, [assignment]);
});
return { kind: 'data', blk: clientProfile(profile, account) };
});
}
function readTrainCrew(payload: BlkBlock): (CrewSlotAssignment & { readonly keepCurrent: boolean }) | undefined {
const vehicle = findParam(payload, 'aircraft')?.value;
const crewId = findParam(payload, 'idx')?.value;
const keepCurrent = findParam(payload, 'keep_curr')?.value;
if (vehicle?.type !== 'string' || crewId?.type !== 'int') return undefined;
return { crewId: crewId.value, vehicle: vehicle.value, keepCurrent: keepCurrent?.type === 'bool' && keepCurrent.value };
}
@@ -0,0 +1,42 @@
/**
* Crew skill actions. All three are sent by native functions with job
* type 1, a profile update, so each answers the whole profile. The crew is id:i (crews/c<id>).
*
* cln_upgrade_crew (shop_upgrade_crew, aces.exe 0x29aad0): <page>{ <skill>:i=levels to add } ... id:i
* cln_purchase_skill_points (shop_purchase_skillpoints, 0x29e220): id:i pack:t
* cln_specialize_crew (shop_specialize_crew, 0x29ad40): id:i aircraft:t
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { buySkillPoints, specializeCrew, upgradeCrewSkills, type CrewSkillCatalogue, type SkillRaise } from '../../crew/crew-skill-rules.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function upgradeCrewAction(profiles: PlayerProfiles, accounts: AccountStore, crew: CrewSkillCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const crewId = intParam(payload, 'id');
if (crewId === undefined) return undefined;
const raises: SkillRaise[] = payload.blocks.flatMap((page) => page.params.flatMap((param) =>
param.value.type === 'int' && param.value.value > 0 ? [{ page: page.name, skill: param.name, levels: param.value.value }] : []));
return (profile) => upgradeCrewSkills(profile, crew, crewId, raises);
});
}
export function purchaseSkillPointsAction(profiles: PlayerProfiles, accounts: AccountStore, crew: CrewSkillCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const crewId = intParam(payload, 'id');
const pack = stringParam(payload, 'pack');
if (crewId === undefined || pack === undefined) return undefined;
return (profile) => buySkillPoints(profile, crew, crewId, pack);
});
}
export function specializeCrewAction(profiles: PlayerProfiles, accounts: AccountStore, crew: CrewSkillCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const crewId = intParam(payload, 'id');
const vehicle = stringParam(payload, 'aircraft');
if (crewId === undefined || vehicle === undefined) return undefined;
return (profile) => specializeCrew(profile, crew, crewId, vehicle);
});
}
@@ -0,0 +1,26 @@
/**
* The crew slot list in a char request body, written by the stock scripts
* (gui.vromfs.bin scripts/crew/crewTrain.nut createBatchTrainCrewRequestBlk):
*
* batchTrainCrew{
* trainCrew{ crewId:i=10 unitName:t="cr_32" }
* trainCrew{ crewId:i=11 unitName:t="" } empty: leave the slot empty
* }
*/
import { findBlock, findParam, type BlkBlock } from '@wto/blk';
import type { CrewSlotAssignment } from '../../profile/crew-slots.ts';
/** The list, empty when the body has none, or undefined when an entry is malformed. */
export function readCrewSlots(payload: BlkBlock): CrewSlotAssignment[] | undefined {
const batch = findBlock(payload, 'batchTrainCrew');
if (!batch) return [];
const result: CrewSlotAssignment[] = [];
for (const entry of batch.blocks) {
if (entry.name !== 'trainCrew') continue;
const crewId = findParam(entry, 'crewId')?.value;
const vehicle = findParam(entry, 'unitName')?.value;
if (crewId?.type !== 'int' || vehicle?.type !== 'string') return undefined;
result.push({ crewId: crewId.value, vehicle: vehicle.value });
}
return result;
}
@@ -0,0 +1,27 @@
/**
* Buying decorations. cln_buy_resource is sent with char_send_blk (job
* type 13), so the answer is the whole profile.
*
* cln_buy_resource (scripts customization/decoratorAcquire.nut buyResourceImpl):
* name:t the skin, decal or attachable
* type:t skin | decal | attachable
* unitName:t the vehicle (skins)
* cost:i costGold:i
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { buyDecoration, decorKey, isDecorKind, type DecorShop } from '../../decor/decor-purchase.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function buyResourceAction(profiles: PlayerProfiles, accounts: AccountStore, decor: DecorShop): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const name = stringParam(payload, 'name');
const type = stringParam(payload, 'type');
if (name === undefined || type === undefined || !isDecorKind(type)) return undefined;
const key = decorKey(type, name, stringParam(payload, 'unitName') ?? '');
const offered = { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
return (profile) => buyDecoration(profile, decor, type, key, offered);
});
}
@@ -0,0 +1,23 @@
/**
* Saving decal and attachable layouts. Both are sent by native functions
* whose job types are not profile updates: cln_save_decals is type 0x1f (aces.exe 0x2a1910),
* cln_save_attachables type 0x20 (0x2a1c30); the client takes the whole answer as its decals or
* attachables block (GameSaveData::onAsyncEconTransComplete 0xeb7a14 / 0xeb7a45). So each answers
* the full block of its kind after storing the request.
*
* Request (lab round 21): <vehicle>{ <skin>{ ... } }
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { decorLayouts, saveDecorLayouts, type DecorLayoutKind } from '../../profile/profile-decor-layouts.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
export function saveDecorLayoutsAction(profiles: PlayerProfiles, accounts: AccountStore, kind: DecorLayoutKind): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const changes = context.payload;
if (!changes) return { kind: 'error', code: 'BAD_PARAMS' };
const profile = profiles.update(account.userId, (saved) => saveDecorLayouts(saved, kind, changes));
return { kind: 'data', blk: decorLayouts(profile, kind) };
});
}
@@ -0,0 +1,221 @@
/**
* Miscellaneous hangar char actions that mutate the player's profile and return the full
* updated clientProfile:
* - GameSaveData::onAsyncEconTransComplete (aces.exe 2.61.0.37 0xeb5f60, profile mask
* 0x301800822fbf at 0xeb61c4) applies both job type 13 (char_send_blk, 0x2991f0) and job
* type 7 (shop_repair_all 0x29a370 / shop_repair_aircraft 0x29a610) as full profile updates.
*
* Covered actions:
* - cln_set_dest_rp_unit_type (scripts/shop/shop.nut:2353, job type 13)
* - cln_unlock_crew (scripts/crew/crewActions.nut:18, job type 13)
* - cln_prepare_aircraft (scripts/unit/unitActions.nut:147 job 13; 0x29a610 job 7)
* - cln_repair_all (shop_repair_all 0x29a370, job type 7)
* - cln_repair_all_in_slots (shop_repair_all 0x29a370, job type 7)
* The repair requests carry no price (0x29a370 sends country, 0x29a610 name and weapon): the
* repair costs what the client shows for it (repair/repair-rules.ts currentCost).
* - cln_add_to_wish_list (scripts/wishlist/wishlistManager.nut:39, job type 13)
* - cln_remove_from_wish_list (scripts/wishlist/wishlistManager.nut:48, job type 13)
*/
import { findBlock, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { int64Field, removeParam } from '../../profile/blk-fields.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { allCrews, crewOf, crewVehiclesOfCountry } from '../../profile/profile-crews.ts';
import { canAfford, pay } from '../../profile/profile-currency.ts';
import { applySetDestinationRpRule } from '../../profile/profile-dest-rp.ts';
import { ownsVehicle } from '../../profile/profile-hangar.ts';
import {
addWishlistUnit,
DEFAULT_WISHLIST_LIMITS,
removeWishlistUnit,
type WishlistLimits,
} from '../../profile/profile-wishlist.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../../profile/server-time.ts';
import { clearVehicleDamage, isDamaged } from '../../profile/profile-vehicle-condition.ts';
import type { RepairRules } from '../../repair/repair-rules.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../../research/rule-outcome.ts';
import type { TechTree } from '../../research/tech-tree.ts';
import type { CharActionContext, CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import {
headerOrPayloadBool,
headerOrPayloadInt,
headerOrPayloadString,
} from './payload-params.ts';
export type ActionEntry = [string, CharActionHandler];
export interface HangarMiscActionDependencies {
readonly profiles: PlayerProfiles;
readonly accounts: AccountStore;
readonly research: ResearchRules;
readonly repair: RepairRules;
readonly wishlistLimits?: WishlistLimits;
}
const HANGAR_BLOCK = 'hangar';
const ALL_COUNTRIES = 'all';
const WISHLIST_UNIT_TYPE = 'unit';
export function hangarMiscActionEntries(deps: HangarMiscActionDependencies): ActionEntry[] {
const { profiles, accounts, research, repair } = deps;
const { techTree } = research;
const limits = deps.wishlistLimits ?? DEFAULT_WISHLIST_LIMITS;
return [
['cln_set_dest_rp_unit_type', setDestRpUnitTypeAction(profiles, accounts, techTree)],
['cln_unlock_crew', unlockCrewAction(profiles, accounts)],
['cln_prepare_aircraft', prepareAircraftAction(profiles, accounts, repair)],
['cln_repair_all', repairVehiclesAction(profiles, accounts, techTree, repair, false)],
['cln_repair_all_in_slots', repairVehiclesAction(profiles, accounts, techTree, repair, true)],
['cln_add_to_wish_list', addToWishlistAction(profiles, accounts, techTree, limits)],
['cln_remove_from_wish_list', removeFromWishlistAction(profiles, accounts)],
];
}
function runProfileRule(
context: CharActionContext,
profiles: PlayerProfiles,
accounts: AccountStore,
rule: (profile: BlkBlock) => RuleOutcome,
) {
return withAccount(context, accounts, (account) => {
let outcome: RuleOutcome = refused('BAD_PARAMS');
const updated = profiles.updateWhen(account.userId, (saved) => {
outcome = rule(saved);
return outcome.ok;
});
if (updated) return { kind: 'data', blk: clientProfile(updated, account) };
return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
});
}
function setDestRpUnitTypeAction(profiles: PlayerProfiles, accounts: AccountStore, techTree: TechTree): CharActionHandler {
return (context) => {
const country = headerOrPayloadString(context, 'country');
const srcType = headerOrPayloadInt(context, 'srcType');
const destType = headerOrPayloadInt(context, 'destType');
if (!country || srcType === undefined || destType === undefined) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) =>
applySetDestinationRpRule(saved, techTree, country, srcType, destType));
};
}
function unlockCrewAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => {
const crewId = headerOrPayloadInt(context, 'crew');
const byGold = headerOrPayloadBool(context, 'gold') ?? false;
const cost = headerOrPayloadInt(context, 'cost') ?? 0;
const costGold = headerOrPayloadInt(context, 'costGold') ?? 0;
if (crewId === undefined || crewId < 0 || cost < 0 || costGold < 0) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => {
const crew = crewOf(saved, crewId);
if (!crew) return refused('BAD_PARAMS');
const nowSec = BigInt(serverTimeToUnixSeconds(serverTimeNow()));
const lockedTill = int64Field(crew, 'lockedTill', 0n);
if (lockedTill > nowSec) {
const price = { silverLions: byGold ? 0 : cost, goldenEagles: byGold ? costGold : 0 };
if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY');
pay(saved, price);
}
// Crew lock state in profile.blk (aces.exe 0x8fa632, 0x93ae07..0x93ae1b): lockedTill:i64, lockedRoomId:i64.
removeParam(crew, 'lockedTill');
removeParam(crew, 'lockedRoomId');
return ACCEPTED;
});
};
}
function prepareAircraftAction(profiles: PlayerProfiles, accounts: AccountStore, repair: RepairRules): CharActionHandler {
return (context) => {
const unit = headerOrPayloadString(context, 'name') ?? headerOrPayloadString(context, 'aircraft');
if (!unit) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => {
if (!ownsVehicle(saved, unit)) return refused('NOT_AVAILABLE');
if (!isDamaged(saved, unit)) return ACCEPTED;
const price = { silverLions: repair.currentCost(saved, unit), goldenEagles: 0 };
if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY');
pay(saved, price);
clearVehicleDamage(saved, unit);
return ACCEPTED;
});
};
}
function repairVehiclesAction(
profiles: PlayerProfiles,
accounts: AccountStore,
techTree: TechTree,
repair: RepairRules,
inSlotsOnly: boolean,
): CharActionHandler {
return (context) => {
const rawCountry = headerOrPayloadString(context, 'country');
const country = rawCountry && rawCountry.length > 0 ? rawCountry : ALL_COUNTRIES;
if (country !== ALL_COUNTRIES && !techTree.hasCountry(country)) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => {
const hangar = findBlock(saved, HANGAR_BLOCK);
if (!hangar) return ACCEPTED;
const targets = [...collectRepairTargetUnits(saved, hangar, techTree, country, inSlotsOnly)].filter((unit) => isDamaged(saved, unit));
const price = { silverLions: targets.reduce((sum, unit) => sum + repair.currentCost(saved, unit), 0), goldenEagles: 0 };
if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY');
pay(saved, price);
for (const unit of targets) clearVehicleDamage(saved, unit);
return ACCEPTED;
});
};
}
function collectRepairTargetUnits(
profile: BlkBlock,
hangar: BlkBlock,
techTree: TechTree,
country: string,
inSlotsOnly: boolean,
): Set<string> {
if (inSlotsOnly) {
if (country !== ALL_COUNTRIES) return new Set(crewVehiclesOfCountry(profile, country));
const slotted = new Set<string>();
for (const crew of allCrews(profile)) {
const current = findBlock(crew, 'aircrafts')?.params.find((param) => param.name === 'current')?.value;
if (current?.type === 'string' && current.value.length > 0) slotted.add(current.value);
}
return slotted;
}
if (country === ALL_COUNTRIES) return new Set(hangar.blocks.map((entry) => entry.name));
return new Set(
hangar.blocks
.filter((entry) => techTree.vehicle(entry.name)?.country === country)
.map((entry) => entry.name),
);
}
function addToWishlistAction(
profiles: PlayerProfiles,
accounts: AccountStore,
techTree: TechTree,
limits: WishlistLimits,
): CharActionHandler {
return (context) => {
const itemType = headerOrPayloadString(context, 'type') ?? WISHLIST_UNIT_TYPE;
const unit = headerOrPayloadString(context, 'unit');
const comment = headerOrPayloadString(context, 'comment') ?? '';
if (itemType !== WISHLIST_UNIT_TYPE || !unit) return { kind: 'error', code: 'BAD_PARAMS' };
const nowSec = serverTimeToUnixSeconds(serverTimeNow());
return runProfileRule(context, profiles, accounts, (saved) =>
addWishlistUnit(saved, techTree, unit, comment, nowSec, limits));
};
}
function removeFromWishlistAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => {
const itemType = headerOrPayloadString(context, 'type') ?? WISHLIST_UNIT_TYPE;
const unit = headerOrPayloadString(context, 'unit');
if (itemType !== WISHLIST_UNIT_TYPE || !unit) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => removeWishlistUnit(saved, unit));
};
}
@@ -0,0 +1,202 @@
/**
* Char actions for external inventory, item recycling, and classic trophies
*:
* - cln_consume_inventory_item itemId:i quantity:i -> full profile
* - cln_multi_consume_inventory_item_json text BLK items{ item{ itemId:i quantity:i } } -> JSON {"revertedItems":[]}
* - cln_inventory_purchase_item key:t itemDefId:i wpCost:i goldCost:i [amount:i] -> full profile
* - cln_recycle_items items{ item{ itemId:t [count:i] } } -> full profile
* - cln_inventory_exchange_items JSON { outputitemdefid, quantity, materials } -> JSON item_json delta
* - cln_buy_trophy name:t index:i cost:i costGold:i -> full profile
*/
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import {
consumeInventoryCoupon,
exchangeInventoryItems,
multiConsumeInventoryItems,
purchaseExternalInventoryItem,
recycleClassicItems,
type ExchangeItemDelta,
} from '../../inventory/inventory-rules.ts';
import { deltaToInventoryJson, parseExchangeItemsRequest } from '../../inventory/inventory-wire.ts';
import type { InventoryCatalogue } from '../../inventory/itemdef-catalogue.ts';
import { buyTrophy, type TrophyCatalogue } from '../../inventory/trophy-catalogue.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { serverTimeNow } from '../../profile/server-time.ts';
import type { RuleOutcome } from '../../research/rule-outcome.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
function profileRuleWithNotify(
profiles: PlayerProfiles,
accounts: AccountStore,
notifyInventoryChanged: () => void,
fromPayload: (payload: BlkBlock) => ((profile: BlkBlock) => RuleOutcome) | undefined,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const rule = context.payload && fromPayload(context.payload);
if (!rule) return { kind: 'error', code: 'BAD_PARAMS' };
let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' };
const saved = profiles.updateWhen(account.userId, (profile) => {
outcome = rule(profile);
return outcome.ok;
});
if (!saved) return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
notifyInventoryChanged();
return { kind: 'data', blk: clientProfile(saved, account) };
});
}
export function consumeInventoryItemAction(
profiles: PlayerProfiles,
accounts: AccountStore,
inventory: InventoryCatalogue,
items: ItemCatalogue,
notifyInventoryChanged: () => void,
): CharActionHandler {
return profileRuleWithNotify(profiles, accounts, notifyInventoryChanged, (payload) => {
const itemId = intParam(payload, 'itemId');
const quantity = intParam(payload, 'quantity') ?? 1;
if (itemId === undefined) return undefined;
return (profile) => consumeInventoryCoupon(profile, inventory, items, String(itemId), quantity, serverTimeNow());
});
}
export function purchaseInventoryItemAction(
profiles: PlayerProfiles,
accounts: AccountStore,
inventory: InventoryCatalogue,
notifyInventoryChanged: () => void,
): CharActionHandler {
return profileRuleWithNotify(profiles, accounts, notifyInventoryChanged, (payload) => {
const itemDefId = intParam(payload, 'itemDefId');
if (itemDefId === undefined) return undefined;
const amount = intParam(payload, 'amount') ?? 1;
const wpCost = intParam(payload, 'wpCost') ?? 0;
const goldCost = intParam(payload, 'goldCost') ?? 0;
return (profile) => purchaseExternalInventoryItem(profile, inventory, itemDefId, amount, wpCost, goldCost);
});
}
export function recycleItemsAction(
profiles: PlayerProfiles,
accounts: AccountStore,
items: ItemCatalogue,
notifyInventoryChanged: () => void,
): CharActionHandler {
return profileRuleWithNotify(profiles, accounts, notifyInventoryChanged, (payload) => {
const itemsBlock = payload.blocks.find((b) => b.name === 'items');
if (!itemsBlock) return undefined;
const requests = itemsBlock.blocks
.filter((b) => b.name === 'item')
.map((b) => ({
uid: stringParam(b, 'itemId') ?? '',
count: intParam(b, 'count') ?? 1,
}));
if (requests.length === 0) return undefined;
return (profile) => recycleClassicItems(profile, items, requests);
});
}
export function multiConsumeInventoryItemsAction(
profiles: PlayerProfiles,
accounts: AccountStore,
inventory: InventoryCatalogue,
items: ItemCatalogue,
notifyInventoryChanged: () => void,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const requests = parseMultiConsumeItems(context.payload, context.rawText);
if (requests.length === 0) return { kind: 'json', data: { revertedItems: [] } };
let revertedItems: number[] = [];
profiles.update(account.userId, (saved) => {
const res = multiConsumeInventoryItems(saved, inventory, items, requests, serverTimeNow());
revertedItems = res.revertedItems;
});
notifyInventoryChanged();
return { kind: 'json', data: { revertedItems } };
});
}
export function inventoryExchangeAction(
profiles: PlayerProfiles,
accounts: AccountStore,
inventory: InventoryCatalogue,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const parsed = parseExchangeItemsRequest(context.rawText);
if (!parsed) return { kind: 'error', code: 'BAD_JSON' };
let delta: ExchangeItemDelta[] | undefined;
let errorCode = 'EXCHANGE_FAILED';
profiles.updateWhen(account.userId, (saved) => {
const res = exchangeInventoryItems(
saved,
inventory,
parsed.outputItemDefId,
parsed.quantity,
parsed.materials,
);
if (!res.ok) {
errorCode = res.code;
return false;
}
delta = res.delta;
return true;
});
if (!delta) return { kind: 'error', code: errorCode };
return { kind: 'json', data: { response: { item_json: deltaToInventoryJson(delta, account.userId) } } };
});
}
export function buyTrophyAction(
profiles: PlayerProfiles,
accounts: AccountStore,
trophies: TrophyCatalogue,
items: ItemCatalogue,
): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const name = stringParam(payload, 'name');
if (!name) return undefined;
const cost = intParam(payload, 'cost') ?? 0;
const costGold = intParam(payload, 'costGold') ?? 0;
return (profile) => buyTrophy(profile, trophies, items, name, cost, costGold, serverTimeNow());
});
}
function parseMultiConsumeItems(
blk: BlkBlock | undefined,
rawText: string,
): Array<{ readonly itemId: number; readonly quantity: number }> {
const fromBlk = blk?.blocks.find((b) => b.name === 'items');
if (fromBlk) {
return fromBlk.blocks
.filter((b) => b.name === 'item')
.flatMap((b) => {
const itemId = intParam(b, 'itemId');
const quantity = intParam(b, 'quantity') ?? 1;
return itemId !== undefined && quantity > 0 ? [{ itemId, quantity }] : [];
});
}
// `DataBlock.formatAsString()` emits `item{\n itemId:i=1\n quantity:i=1\n}` text blocks.
const results: Array<{ readonly itemId: number; readonly quantity: number }> = [];
const blockRegex = /item\s*\{([^}]*)\}/g;
let match: RegExpExecArray | null;
while ((match = blockRegex.exec(rawText)) !== null) {
const body = match[1] ?? '';
const idMatch = /itemId:i\s*=\s*(\d+)/.exec(body);
const qtyMatch = /quantity:i\s*=\s*(\d+)/.exec(body);
if (idMatch) {
const itemId = Number(idMatch[1]);
const quantity = qtyMatch ? Number(qtyMatch[1]) : 1;
if (Number.isSafeInteger(itemId) && quantity > 0) results.push({ itemId, quantity });
}
}
return results;
}
@@ -0,0 +1,66 @@
/**
* Classic item actions. All are sent with char_send_blk (job type
* 13), so each answers the whole profile.
*
* cln_buy_item name:t count:i cost:i costGold:i
* cln_set_current_booster name:t (uid)
* cln_set_current_personal_discount name:t (uid)
* cln_set_current_wager name:t (uid) wager:i
* cln_apply_spare_item uid:t unit:t useItemsCount:i
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { activateBooster, activateDiscount, startWager } from '../../items/item-activation.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import { buyItem } from '../../items/item-purchase.ts';
import { applyUniversalSpares } from '../../items/universal-spares.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { serverTimeNow } from '../../profile/server-time.ts';
import type { TechTree } from '../../research/tech-tree.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function buyItemAction(profiles: PlayerProfiles, accounts: AccountStore, items: ItemCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const name = stringParam(payload, 'name');
const pieces = intParam(payload, 'count');
if (name === undefined || pieces === undefined) return undefined;
const offered = { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
return (profile) => buyItem(profile, items, name, pieces, offered, serverTimeNow());
});
}
export function activateBoosterAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const uid = stringParam(payload, 'name');
if (uid === undefined) return undefined;
return (profile) => activateBooster(profile, uid);
});
}
export function activateDiscountAction(profiles: PlayerProfiles, accounts: AccountStore, items: ItemCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const uid = stringParam(payload, 'name');
if (uid === undefined) return undefined;
return (profile) => activateDiscount(profile, items, uid, serverTimeNow());
});
}
export function startWagerAction(profiles: PlayerProfiles, accounts: AccountStore, items: ItemCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const uid = stringParam(payload, 'name');
const stake = intParam(payload, 'wager');
if (uid === undefined || stake === undefined) return undefined;
return (profile) => startWager(profile, items, uid, stake);
});
}
export function applySpareItemAction(profiles: PlayerProfiles, accounts: AccountStore, items: ItemCatalogue, techTree: TechTree): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const uid = stringParam(payload, 'uid');
const vehicle = stringParam(payload, 'unit');
const pieces = intParam(payload, 'useItemsCount');
if (uid === undefined || vehicle === undefined || pieces === undefined) return undefined;
return (profile) => applyUniversalSpares(profile, items, techTree, uid, vehicle, pieces);
});
}
@@ -0,0 +1,86 @@
/**
* Modification, ammunition, weapon preset and spare actions. The
* purchases are sent with char_send_blk (job type 13); cln_enable_modifications by a native function with job type
* 0x17 (aces.exe 0x29aa21). Both types are profile updates, so each answers the whole profile.
*
* cln_buy_modification (scripts weaponry/weaponsPurchase.nut):
* aircraft:t modification:t open:b count:i cost:i costGold:i
* cln_buy_all_modification: unit:t forceOpen:b cost:i costGold:i
* cln_buy_spare_aircrafts: aircraft:t count:i cost:i costGold:i
* cln_buy_weapon: aircraft:t weapon:t count:i cost:i costGold:i
* cln_enable_modifications (shop_enable_modifications, 0x17a5020 -> 0x29a890; lab round 18):
* <vehicle>{ <modification>:b=yes ... } ...
*/
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { buyAllModifications, buyModification, enableModifications } from '../../modifications/modification-purchase.ts';
import { buySpares } from '../../modifications/spare-purchase.ts';
import { saveWeaponPresets } from '../../modifications/weapon-presets.ts';
import { buyWeapons } from '../../modifications/weapon-purchase.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { boolParam, intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function buyModificationAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'aircraft');
const modification = stringParam(payload, 'modification');
if (vehicle === undefined || modification === undefined) return undefined;
const order = {
vehicle,
modification,
outright: boolParam(payload, 'open') ?? false,
amount: intParam(payload, 'count') ?? 1,
offered: offeredPrice(payload),
};
return (profile) => buyModification(profile, equipment, order);
});
}
export function buyAllModificationsAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
if (vehicle === undefined) return undefined;
const outright = boolParam(payload, 'forceOpen') ?? false;
const offered = offeredPrice(payload);
return (profile) => buyAllModifications(profile, equipment, vehicle, outright, offered);
});
}
export function buySparesAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'aircraft');
if (vehicle === undefined) return undefined;
const amount = intParam(payload, 'count') ?? 1;
const offered = offeredPrice(payload);
return (profile) => buySpares(profile, equipment, vehicle, amount, offered);
});
}
export function buyWeaponsAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'aircraft');
const weapon = stringParam(payload, 'weapon');
if (vehicle === undefined || weapon === undefined) return undefined;
const order = { vehicle, weapon, amount: intParam(payload, 'count') ?? 1, offered: offeredPrice(payload) };
return (profile) => buyWeapons(profile, equipment, order);
});
}
export function enableModificationsAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const switches = payload.blocks.flatMap((vehicle) => vehicle.params.flatMap((param) =>
param.value.type === 'bool' ? [{ vehicle: vehicle.name, modification: param.name, enabled: param.value.value }] : []));
return (profile) => enableModifications(profile, equipment, switches);
});
}
export function saveWeaponPresetsAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => (profile) => saveWeaponPresets(profile, equipment, payload));
}
function offeredPrice(payload: BlkBlock) {
return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
}
@@ -0,0 +1,57 @@
/**
* Char actions of the online initialisation after sign-in, up to the profile
*.
*/
import { emptyBlock, setParam } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import type { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
/**
* cln_get_initial_meta: server-side metadata the client reads in GameSaveData's initial-meta
* handling (aces.exe 0xeb5f60). binaryDataMetainfo lists server-side binary files the client
* must fetch and compare by hash; the local server has none, so the list is empty and no
* downloads follow. generalBlkMeta carries the cloud-settings schema and saved versions/hashes
*.
*/
export function initialMeta(accounts?: AccountStore, cloudSettings?: CloudSettingsStore): CharActionHandler {
return (context) => {
const meta = emptyBlock();
setParam(meta, 'machineId', { type: 'string', value: 'wto_local_machine' });
setParam(meta, 'bestCompression', { type: 'string', value: 'zstd' });
const account = context.userId !== undefined ? accounts?.byUserId(context.userId) : undefined;
const generalBlkMeta = cloudSettings
? cloudSettings.buildMetaBlk(account?.userId, 'generalBlkMeta')
: emptyBlock('generalBlkMeta');
meta.blocks.push(emptyBlock('binaryDataMetainfo'), generalBlkMeta);
return { kind: 'data', blk: meta };
};
}
/**
* cln_upd_entitlements_full: the profile request of the online initialisation stage
* CHAR_PROFILE_RECEIVED (sent at aces.exe 0x29f920 with headers onLogin and resetToken; the
* request body is the client's machine description). The answer is the whole profile: the
* job (EconomicSerializeJob, type 4) loads it as a BLK, and EconomicSerializeAction::
* performAction (0x295ef0) reads it into the client's profile with the profile serializer
* (0x917740) when it is not empty.
*/
export function entitlementsFull(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return profileAnswer(profiles, accounts);
}
/** cln_legacy_get_userdata: the whole profile (ClientEconomicState::loadOnline, aces.exe 0x2a23b0). */
export function legacyUserData(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return profileAnswer(profiles, accounts);
}
function profileAnswer(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => ({
kind: 'data',
blk: clientProfile(profiles.profileOf(account.userId), account),
}));
}
@@ -0,0 +1,71 @@
/** Read typed parameters from a char action's BLK payload or HTTP request headers. */
import { findParam, type BlkBlock } from '@wto/blk';
import type { CharActionContext } from '../char-action.ts';
export function stringParam(payload: BlkBlock, name: string): string | undefined {
const param = findParam(payload, name)?.value;
return param?.type === 'string' ? param.value : undefined;
}
export function intParam(payload: BlkBlock, name: string): number | undefined {
const param = findParam(payload, name)?.value;
return param?.type === 'int' ? param.value : undefined;
}
export function realParam(payload: BlkBlock, name: string): number | undefined {
const param = findParam(payload, name)?.value;
if (param?.type === 'real' || param?.type === 'int') {
return Number.isFinite(param.value) ? param.value : undefined;
}
return undefined;
}
export function boolParam(payload: BlkBlock, name: string): boolean | undefined {
const param = findParam(payload, name)?.value;
return param?.type === 'bool' ? param.value : undefined;
}
export function headerOrPayloadString(context: CharActionContext, name: string): string | undefined {
const fromPayload = context.payload ? stringParam(context.payload, name) : undefined;
return fromPayload ?? context.headerParam(name);
}
export function headerOrPayloadInt(context: CharActionContext, name: string): number | undefined {
if (context.payload) {
const fromPayload = intParam(context.payload, name);
if (fromPayload !== undefined) return fromPayload;
}
const hdr = context.headerParam(name)?.trim();
if (hdr !== undefined && /^-?\d+$/.test(hdr)) {
const parsed = Number(hdr);
if (Number.isSafeInteger(parsed)) return parsed;
}
return undefined;
}
export function headerOrPayloadBool(context: CharActionContext, name: string): boolean | undefined {
if (context.payload) {
const fromBool = boolParam(context.payload, name);
if (fromBool !== undefined) return fromBool;
const fromStr = stringParam(context.payload, name);
if (fromStr !== undefined) return parseTruthyFlag(fromStr);
}
const hdr = context.headerParam(name);
return hdr !== undefined ? parseTruthyFlag(hdr) : undefined;
}
export function headerOrPayloadId(context: CharActionContext, name: string): string | undefined {
if (context.payload) {
const param = findParam(context.payload, name)?.value;
if (param?.type === 'string' && param.value !== '') return param.value;
if (param?.type === 'int64') return param.value.toString();
if (param?.type === 'int') return String(param.value);
}
const hdr = context.headerParam(name);
return hdr && hdr !== '' ? hdr : undefined;
}
function parseTruthyFlag(raw: string): boolean {
const lower = raw.trim().toLowerCase();
return lower === 'yes' || lower === 'true' || lower === 'on' || lower === '1';
}
@@ -0,0 +1,112 @@
/**
* Player card actions. cln_select_title and cln_save_pilot_appearance
* are sent with char_send_blk (job type 13) and answer the whole profile; cln_get_users_terse_info
* (scripts user/usersInfoManager.nut, charRequestBlk) answers one block per requested user:
* request usersList="<uid>;<uid>", sent as a request header (char-action.ts headerParam)
* answer <uid>{ nick:t pilotIcon:t pilotId:t title:t clanTag:t clanName:t background:t frame:t
* shcType:t showcase{...} }
* or <uid>{ failed:b=yes } for unknown users
* cln_save_profile_showcase (scripts user/profileShowcase.nut saveShowcase, charSendBlk): one
* showcase type and its choices, answered with the whole profile; cln_get_showcases (scripts
* user/profileShowcasesData.nut, charRequestBlk): every saved showcase (showcase-rules.ts).
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { Account, AccountStore } from '../../accounts/account-store.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import type { ClanMemberRecord, ClanRecord } from '../../clans/clan-types.ts';
import { chooseTitle, saveAppearance } from '../../player-card/player-card-rules.ts';
import { currentShowcaseView, saveShowcase, showcasesAnswer } from '../../player-card/showcase-rules.ts';
import { appearance, chosenTitle } from '../../profile/profile-appearance.ts';
import { clanMembershipOf } from '../../profile/profile-clan.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { TechTree } from '../../research/tech-tree.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function selectTitleAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const title = stringParam(payload, 'name');
if (title === undefined) return undefined;
return (profile) => chooseTitle(profile, title);
});
}
export function savePilotAppearanceAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const choices = payload.params.flatMap((param) => param.value.type === 'string' ? [{ field: param.name, image: param.value.value }] : []);
return (profile) => saveAppearance(profile, choices);
});
}
export function saveShowcaseAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => (profile) => saveShowcase(profile, payload));
}
export function showcasesAction(profiles: PlayerProfiles, accounts: AccountStore, techTree: TechTree): CharActionHandler {
return (context) => withAccount(context, accounts, (account) =>
({ kind: 'data', blk: showcasesAnswer(profiles.profileOf(account.userId), techTree) }));
}
export function usersTerseInfoAction(profiles: PlayerProfiles, accounts: AccountStore, techTree: TechTree, clans?: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, () => {
const list = (context.payload ? stringParam(context.payload, 'usersList') : undefined) ?? context.headerParam('usersList');
if (list === undefined) return { kind: 'error', code: 'BAD_PARAMS' };
const blocks = list.split(';').filter((uid) => uid !== '').map((uid): BlkBlock => {
const account = accounts.byUserId(uid);
if (account) return accountTerseInfoBlk(uid, account, profiles, techTree, clans);
const npc = clans?.npcMemberByUid(uid);
if (npc) return npcTerseInfoBlk(uid, npc.clan, npc.member);
return { name: uid, params: [{ name: 'failed', value: { type: 'bool', value: true } }], blocks: [] };
});
return { kind: 'data', blk: { name: '', params: [], blocks } };
});
}
function accountTerseInfoBlk(
uid: string,
account: Account,
profiles: PlayerProfiles,
techTree: TechTree,
clans?: ClanStore,
): BlkBlock {
const profile = profiles.profileOf(account.userId);
clans?.syncProfile(profile, account);
const clanInfo = clanMembershipOf(profile);
const inClan = clanInfo.clanId !== '-1';
const looks = appearance(profile);
const { type, showcase } = currentShowcaseView(profile, techTree);
const fields: ReadonlyArray<readonly [string, string]> = [
['nick', account.nick],
['pilotIcon', looks.pilotIcon ?? ''],
['title', chosenTitle(profile)],
['clanTag', inClan ? clanInfo.clanTag : ''],
['clanName', inClan ? clanInfo.clanName : ''],
['background', looks.background ?? ''],
['frame', looks.frame ?? ''],
['shcType', type],
];
return { name: uid, params: toStringParams(fields), blocks: [showcase] };
}
function npcTerseInfoBlk(uid: string, clan: ClanRecord, member: ClanMemberRecord): BlkBlock {
const fields: ReadonlyArray<readonly [string, string]> = [
['nick', member.nick],
['pilotIcon', member.npcPilotIcon ?? 'cardicon_default'],
['title', member.npcTitle ?? ''],
['clanTag', clan.tag],
['clanName', clan.name],
['background', ''],
['frame', member.npcFrame ?? ''],
['shcType', member.npcShowcaseUnit ? 'favorite_unit' : 'none'],
];
const showcase: BlkBlock = member.npcShowcaseUnit
? { name: 'showcase', params: [{ name: 'unit', value: { type: 'string', value: member.npcShowcaseUnit } }], blocks: [] }
: { name: 'showcase', params: [], blocks: [] };
return { name: uid, params: toStringParams(fields), blocks: [showcase] };
}
function toStringParams(fields: ReadonlyArray<readonly [string, string]>): BlkParam[] {
return fields.map(([name, value]) => ({ name, value: { type: 'string', value } }));
}
@@ -0,0 +1,13 @@
/**
* cln_get_price_ex: the price table (implementation notes; char/actions/price-table.ts).
* Sent at sign-in with an empty body and again by the stock scripts when a purchase fails
* (scripts/unit/unitActions.nut impl_buyUnit: PRICE.update). The table only depends on the
* game files and tuning, so it is built once.
*/
import type { CharActionHandler } from '../char-action.ts';
import { priceTable, type PriceTableSources } from './price-table.ts';
export function priceEx(sources: PriceTableSources): CharActionHandler {
const table = priceTable(sources);
return () => ({ kind: 'data', blk: table });
}
+209
View File
@@ -0,0 +1,209 @@
/**
* The price table the char server sends for cln_get_price_ex (implementation notes,
* implementation notes).
*
* The client keeps the answer whole as its price table (aces.exe 2.61.0.37 0xeb7a88, job type
* 0x21; stored in the save-data object at +0x3f5c0, which warpoints::init makes the price
* source, 0x105bb4d..0x105bb67). Every price reader goes through one lookup (0x908a20 ->
* 0x908d10): it first takes a top-level block named after a client-side string (default
* "English"), else the top-level block "Common", else finds nothing; the path is looked up
* inside that block. So the whole table sits in Common:
*
* Common{
* aircrafts{
* <vehicle>{
* cost:i costGold:i the vehicle
* mods{ <modification>{ cost:i costGold:i openCostGold:i } }
* weapons{ <preset>{ cost:i costGold:i } }
* spare{ cost:i costGold:i }
* repair{ arcade{ cost:i } historical{ cost:i } simulation{ cost:i } } full repair cost per
* mode before modifications (0x10517b0, 0x90e0b0)
* specialization{ spec_expert{ cost:i } spec_ace{ costGold:i } }
* }
* }
* skins{ "<vehicle>/<skin>"{ cost:i costGold:i } } decorations (get_skin_cost_*, 0x17a8910...)
* decals{ <decal>{ ... } }
* attachable{ <attachable>{ ... } }
* skills{ <pack>{ costGold:i } } skill point packs (0x916380)
* unlocks{ <unlock>{ cost:i costGold:i } } unlocks for sale (0x9170c0)
* items{ <item>{ cost:i costGold:i } } classic items for sale, price per piece
* (wp_get_item_cost, 0x10531e0; implementation notes)
* trophy{ <id>{ cost:i costGold:i } } classic trophy prices
* }
* trophy{ <id>{ ... } } classic trophy definitions & drop weights
*
* Every entry is read as cost:i (silver lions), costGold:i (golden eagles), discount:i (percent
* off, not sent: no discounts), each 0 when missing (so zero prices are left out); openCostGold
* is the outright price of a modification before research progress (0xec0910). Anything the
* lookup does not find costs 0 for the client, which then offers it at 0 (lab round 20). The
* prices are config/wpcost.blk value and costGold (decorations: config/skins.blk, decals.blk,
* attachable.blk; unlocks: config/unlocks.blk), the same the purchase rules charge.
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import type { DecorShop } from '../../decor/decor-purchase.ts';
import type { TrophyCatalogue, TrophyDefinition, TrophyPrize } from '../../inventory/trophy-catalogue.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { REPAIR_MODES } from '../../game-data/datasets/vehicle-repair.ts';
import type { RepairRules } from '../../repair/repair-rules.ts';
import type { TechTree } from '../../research/tech-tree.ts';
import type { UnlockShop } from '../../unlocks/unlock-purchase.ts';
/** The top-level block every client lookup falls back to (0x908e28). */
const COMMON_SECTION = 'Common';
export interface PriceTableSources {
readonly techTree: TechTree;
readonly equipment: EquipmentCatalogue;
readonly decor: DecorShop;
readonly crew: CrewSkillCatalogue;
readonly unlocks: UnlockShop;
readonly items: ItemCatalogue;
readonly trophies: TrophyCatalogue;
readonly repair: RepairRules;
}
export function priceTable(sources: PriceTableSources): BlkBlock {
return {
name: '',
params: [],
blocks: [
{
name: COMMON_SECTION,
params: [],
blocks: [
vehicleSection(sources.techTree, sources.equipment, sources.crew, sources.repair),
...decorSections(sources.decor),
skillPackSection(sources.crew),
unlockSection(sources.unlocks),
itemSection(sources.items),
trophyPriceSection(sources.trophies),
],
},
trophyDefinitionsSection(sources.trophies),
],
};
}
function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue, crew: CrewSkillCatalogue, repair: RepairRules): BlkBlock {
const vehicles: BlkBlock[] = [];
for (const vehicle of techTree.all()) {
const entry: BlkBlock = { name: vehicle.name, params: priceParams(vehicle.silverLions, vehicle.goldenEagles), blocks: [] };
const fitted = equipment.vehicle(vehicle.name);
if (fitted) {
const mods = fitted.modifications.filter((mod) => mod.silverLions > 0 || mod.goldenEagles > 0 || mod.openGoldenEagles > 0).map((mod) => ({
name: mod.name,
params: [...priceParams(mod.silverLions, mod.goldenEagles), ...(mod.openGoldenEagles > 0 ? [intParam('openCostGold', mod.openGoldenEagles)] : [])],
blocks: [],
}));
const weapons = fitted.weapons.filter((weapon) => weapon.silverLions > 0 || weapon.goldenEagles > 0)
.map((weapon) => ({ name: weapon.name, params: priceParams(weapon.silverLions, weapon.goldenEagles), blocks: [] }));
if (mods.length) entry.blocks.push({ name: 'mods', params: [], blocks: mods });
if (weapons.length) entry.blocks.push({ name: 'weapons', params: [], blocks: weapons });
if (fitted.spare) entry.blocks.push({ name: 'spare', params: priceParams(fitted.spare.silverLions, fitted.spare.goldenEagles), blocks: [] });
}
const repairCost = repair.vehicle(vehicle.name)?.cost;
if (repairCost) {
const modes = REPAIR_MODES.filter((mode) => repairCost[mode] > 0)
.map((mode) => ({ name: mode.toLowerCase(), params: priceParams(repairCost[mode], 0), blocks: [] }));
if (modes.length) entry.blocks.push({ name: 'repair', params: [], blocks: modes });
}
const training = crew.training(vehicle.name);
if (training && (training.expert > 0 || training.aceGoldenEagles > 0)) {
const specBlocks: BlkBlock[] = [];
if (training.expert > 0) specBlocks.push({ name: 'spec_expert', params: priceParams(training.expert, 0), blocks: [] });
if (training.aceGoldenEagles > 0) specBlocks.push({ name: 'spec_ace', params: priceParams(0, training.aceGoldenEagles), blocks: [] });
entry.blocks.push({ name: 'specialization', params: [], blocks: specBlocks });
}
if (entry.blocks.length || vehicle.silverLions > 0 || vehicle.goldenEagles > 0) vehicles.push(entry);
}
return { name: 'aircrafts', params: [], blocks: vehicles };
}
/** Zero prices are left out: the client reads a missing value as 0, and the table stays small. */
function priceParams(silverLions: number, goldenEagles: number): BlkParam[] {
return [
...(silverLions ? [intParam('cost', silverLions)] : []),
...(goldenEagles ? [intParam('costGold', goldenEagles)] : []),
];
}
function intParam(name: string, value: number): BlkParam {
return { name, value: { type: 'int', value } };
}
/** The price-table section each decoration kind is looked up in. */
const DECOR_SECTIONS = { skin: 'skins', decal: 'decals', attachable: 'attachable' } as const;
function decorSections(decor: DecorShop): BlkBlock[] {
const sections = new Map<string, BlkBlock>();
for (const price of decor.all()) {
const name = DECOR_SECTIONS[price.kind];
let section = sections.get(name);
if (!section) sections.set(name, section = { name, params: [], blocks: [] });
section.blocks.push({ name: price.key, params: priceParams(price.silverLions, price.goldenEagles), blocks: [] });
}
return [...sections.values()];
}
function skillPackSection(crew: CrewSkillCatalogue): BlkBlock {
return { name: 'skills', params: [], blocks: [...crew.packs()].map((pack) => ({ name: pack.name, params: priceParams(0, pack.goldenEagles), blocks: [] })) };
}
function unlockSection(unlocks: UnlockShop): BlkBlock {
return { name: 'unlocks', params: [], blocks: [...unlocks.all()].map((price) => ({ name: price.id, params: priceParams(price.silverLions, price.goldenEagles), blocks: [] })) };
}
function itemSection(items: ItemCatalogue): BlkBlock {
return { name: 'items', params: [], blocks: items.forSale().map((item) => ({ name: item.name, params: priceParams(item.silverLions, item.goldenEagles), blocks: [] })) };
}
function trophyPriceSection(trophies: TrophyCatalogue): BlkBlock {
return {
name: 'trophy',
params: [],
blocks: trophies.all().map((trophy) => ({ name: trophy.id, params: priceParams(trophy.silverLions, trophy.goldenEagles), blocks: [] })),
};
}
function trophyDefinitionsSection(trophies: TrophyCatalogue): BlkBlock {
return {
name: 'trophy',
params: [],
blocks: trophies.all().map(toTrophyDefinitionBlk),
};
}
function toTrophyDefinitionBlk(trophy: TrophyDefinition): BlkBlock {
const params: BlkParam[] = [
{ name: 'iconStyle', value: { type: 'string', value: trophy.iconStyle } },
{ name: 'showChances', value: { type: 'bool', value: trophy.showChances } },
{ name: 'repeatable', value: { type: 'bool', value: trophy.repeatable } },
{ name: 'instantOpening', value: { type: 'bool', value: trophy.instantOpening } },
];
if (trophy.numTotal > 0) params.push(intParam('numTotal', trophy.numTotal));
if (trophy.countryFlag) params.push({ name: 'showCountryFlag', value: { type: 'string', value: trophy.countryFlag } });
if (trophy.prizes.length === 1 && trophy.prizes[0]!.kind === 'unit') {
params.push({ name: 'showTypeInName', value: { type: 'bool', value: true } });
}
return {
name: trophy.id,
params,
blocks: [{ name: 'prizes', params: [], blocks: trophy.prizes.map(prizeToBlk) }],
};
}
function prizeToBlk(prize: TrophyPrize): BlkBlock {
// calculate_drop_chances (aces.exe 0x95a510 -> 0x95c27c..0x95c28f) checks paramType == TYPE_REAL (3)
// on `weight` (defaulting to 1.0f when non-real) and writes normalized `percent:i` (0..10000).
const params: BlkParam[] = [{ name: 'weight', value: { type: 'real', value: prize.weight } }];
if (prize.kind === 'warpoints') params.push(intParam('warpoints', prize.amount));
else if (prize.kind === 'gold') params.push(intParam('gold', prize.amount));
else if (prize.kind === 'item') {
params.push({ name: 'item', value: { type: 'string', value: prize.itemName } }, intParam('count', prize.count));
} else {
params.push({ name: 'unit', value: { type: 'string', value: prize.unitName } });
}
return { name: 'i', params, blocks: [] };
}
@@ -0,0 +1,38 @@
/**
* Purchase actions; the client applies each answer as a profile
* update, so each answers the whole profile.
*
* cln_buy_aircraft (char_send_blk, job type 13; gui.vromfs.bin scripts/unit/unitActions.nut
* impl_buyUnit):
* name:t the vehicle
* cost:i the silver lion price the client showed
* costGold:i the golden eagle price the client showed
* cln_buy_slot (purchase_crew_slot, aces.exe 2.61.0.37 0x1555a90 -> 0x2998f0, job type 10):
* country:t the country that gets one more crew slot
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { buyCrewSlot } from '../../research/crew-slot-purchase.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import { buyVehicle } from '../../research/vehicle-purchase.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function buyAircraft(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'name');
const silverLions = intParam(payload, 'cost') ?? 0;
const goldenEagles = intParam(payload, 'costGold') ?? 0;
if (vehicle === undefined) return undefined;
return (profile) => buyVehicle(profile, rules, vehicle, { silverLions, goldenEagles });
});
}
export function buySlot(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const country = stringParam(payload, 'country');
if (country === undefined) return undefined;
return (profile) => buyCrewSlot(profile, rules, country);
});
}
@@ -0,0 +1,87 @@
/**
* Research actions. All are sent with char_send_blk (job type 13),
* so the client applies each answer as a profile update and each answers the whole profile.
*
* cln_set_researchable (shop_set_researchable_unit, aces.exe 2.61.0.37 0x17a3e80):
* unit:t the vehicle to research
* type:i its vehicle type number
* or, for a modification (shop_set_researchable_unit_module, 0x17a3e00; implementation notes):
* unit:t the owned vehicle
* mod:t the modification to research
* cln_reset_researchable (shop_reset_researchable_unit, 0x17a3f00): the player closed the
* "research finished" prompt without choosing.
* country:t, type:i
* cln_convert_exp (shop_convert_free_exp_for_unit, 0x17a4ec0): free research points into a
* vehicle, paid with golden eagles.
* unit:t, amount:i research points
* cln_move_exp_to_unit (scripts/unit/unitActions.nut flushExcessExpToUnit): put the branch's
* banked excess research points (researchUnits/<country>/exp<Type>) into a vehicle.
* unit:t
* cln_move_exp_to_module (flushExcessExpToModule): put a vehicle's banked excess research
* points (hangar/<vehicle>/excessExp) into one of its modifications.
* unit:t, mod:t
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { chooseModuleResearch, moveExcessExpToModule } from '../../modifications/module-research-target.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { chooseResearchTarget, convertFreeResearchPoints, dismissFinishedResearch, moveExcessExpToUnit } from '../../research/research-progress.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function setResearchable(
profiles: PlayerProfiles,
accounts: AccountStore,
rules: ResearchRules,
equipment: EquipmentCatalogue,
): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
const modification = stringParam(payload, 'mod');
if (vehicle !== undefined && modification !== undefined) return (profile) => chooseModuleResearch(profile, equipment, vehicle, modification);
const type = intParam(payload, 'type');
if (vehicle === undefined || type === undefined) return undefined;
return (profile) => chooseResearchTarget(profile, rules, vehicle, type);
});
}
export function resetResearchable(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const country = stringParam(payload, 'country');
const type = intParam(payload, 'type');
if (country === undefined || type === undefined) return undefined;
return (profile) => dismissFinishedResearch(profile, rules, country, type);
});
}
export function convertExp(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
const amount = intParam(payload, 'amount');
if (vehicle === undefined || amount === undefined) return undefined;
return (profile) => convertFreeResearchPoints(profile, rules, vehicle, amount);
});
}
export function moveExpToUnitAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
if (vehicle === undefined) return undefined;
return (profile) => moveExcessExpToUnit(profile, rules, vehicle);
});
}
export function moveExpToModuleAction(
profiles: PlayerProfiles,
accounts: AccountStore,
equipment: EquipmentCatalogue,
): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
const modification = stringParam(payload, 'mod');
if (vehicle === undefined || modification === undefined) return undefined;
return (profile) => moveExcessExpToModule(profile, equipment, vehicle, modification);
});
}
@@ -0,0 +1,28 @@
/**
* Actions that run one rule on the player's profile and answer the whole updated profile
* (job types the client applies as profile updates, implementation notes). A refused
* rule changes nothing and answers "!ERROR:<refusal>".
*/
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { RuleOutcome } from '../../research/rule-outcome.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
/** Read the request into a rule (undefined: malformed request), run it, answer the outcome. */
export function ruleAction(profiles: PlayerProfiles, accounts: AccountStore,
readRequest: (payload: BlkBlock) => ((profile: BlkBlock) => RuleOutcome) | undefined): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const rule = context.payload && readRequest(context.payload);
if (!rule) return { kind: 'error', code: 'BAD_PARAMS' };
let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' };
const profile = profiles.updateWhen(account.userId, (saved) => {
outcome = rule(saved);
return outcome.ok;
});
if (profile) return { kind: 'data', blk: clientProfile(profile, account) };
return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
});
}
@@ -0,0 +1,55 @@
/**
* Char action handlers for squadron (clan) vehicle research and Golden-Eagle buyout
* (`cln_set_research_clan_unit`, `cln_flush_clan_exp_to_unit`, `cln_buy_not_researched_clans_unit`;
* implementation notes).
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import {
buyNotResearchedSquadronUnit,
chooseSquadronResearchTarget,
flushSquadronExpToUnit,
} from '../../research/squadron-research.ts';
import type { CharActionHandler } from '../char-action.ts';
import { clanProfileRuleAction, priceFromClanPayload } from './clan-actions.ts';
import { boolParam, stringParam } from './payload-params.ts';
export function setResearchClanUnitAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
rules: ResearchRules,
): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const unit = context.payload && stringParam(context.payload, 'unit');
if (!unit) return { ok: false, refusal: 'BAD_PARAMS' };
const auto = (context.payload && boolParam(context.payload, 'auto')) ?? false;
return chooseSquadronResearchTarget(profile, rules, unit, auto, clans.earnedSquadronExpOf(account.userId));
});
}
export function flushClanExpToUnitAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
rules: ResearchRules,
): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (_context, profile, account) =>
flushSquadronExpToUnit(profile, rules, clans.earnedSquadronExpOf(account.userId)));
}
export function buyNotResearchedClanUnitAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
rules: ResearchRules,
): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile) => {
const unit = context.payload && stringParam(context.payload, 'unit');
const offered = context.payload && priceFromClanPayload(context.payload);
if (!unit || !offered) return { ok: false, refusal: 'BAD_PARAMS' };
return buyNotResearchedSquadronUnit(profile, rules, unit, offered);
});
}
@@ -0,0 +1,54 @@
/**
* The new player's first choice (implementation notes, step 6).
*
* The stock "first choice" window (gui.vromfs.bin scripts/firstChoice/unitTypeChoiceHandler.nut,
* clnSetStartingInfo) sends cln_set_starting_info with:
* country:t the country picked
* unitType:i the vehicle type picked
* unlock:t repeated: every country, and "chosen_unit_type_<type>" for the type picked
* batchTrainCrew{ trainCrew{ crewId:i unitName:t } ... } the vehicle for every crew slot
* (crew-slots-payload.ts; "" leaves the slot empty)
* The login script waits until the vehicle type counts as chosen, which the client reads as
* the unlock "chosen_unit_type_<type>" being earned (scripts/unit/unitTypesList.nut
* isFirstChosen). The client applies the answer as a profile update
* (GameSaveData::onAsyncEconTransComplete -> onUpdateProfile, job type 13), so the answer is
* the whole updated profile.
*
* The country picked is also recorded as chosen ("chosen_country_<country>", defined in
* config/unlocks.blk). The stock scripts start the base tutorial by force for a player who
* has a chosen vehicle type but no chosen country (scripts/tutorials.nut checkTutorialOnStart:
* needAutoStartTutorial = !hasRunTutorialDialog(), which is false while
* scripts/user/newbieTutorialDisplay.nut reqFirstCountryChoice() holds). With the country
* chosen, they offer the tutorial. The build enables AllowedToSkipBaseTutorials so the
* player can skip it.
*/
import { findParam } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import { assignCrewSlots, canAssignCrewSlots } from '../../profile/crew-slots.ts';
import { addUnlock } from '../../profile/profile-unlocks.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { readCrewSlots } from './crew-slots-payload.ts';
export function setStartingInfo(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const payload = context.payload;
if (!payload) return { kind: 'error', code: 'BAD_PARAMS' };
const unlocks = payload.params.flatMap((param) => (param.name === 'unlock' && param.value.type === 'string' ? [param.value.value] : []));
const country = findParam(payload, 'country')?.value;
const assignments = readCrewSlots(payload);
if (unlocks.length === 0 || assignments === undefined || country?.type !== 'string' || !country.value.startsWith('country_')) {
return { kind: 'error', code: 'BAD_PARAMS' };
}
unlocks.push(`chosen_${country.value}`);
if (!canAssignCrewSlots(profiles.profileOf(account.userId), assignments)) return { kind: 'error', code: 'BAD_PARAMS' };
const profile = profiles.update(account.userId, (saved) => {
for (const unlock of unlocks) addUnlock(saved, unlock);
assignCrewSlots(saved, assignments);
});
return { kind: 'data', blk: clientProfile(profile, account) };
});
}
@@ -0,0 +1,85 @@
/**
* Store char actions:
* - cln_get_entitlements_price_ex: encodes the store catalogue into Gaijin's entitlements BLK;
* - cln_buy_entitlement: Golden-Eagle entitlement purchase (aces.exe 0x17a0f50 -> 0x2a1240
* sends `entitlement` and `costGold` in the HTTP headers, job type 5, answer applied as a
* full profile update). Note: `cln_buy_entitlement_and_get_reward_for_day` is not referenced
* anywhere in 2.61.0.37 GUI scripts and is intentionally not registered.
*/
import { appendParam, emptyBlock, setParam, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { serverTimeNow } from '../../profile/server-time.ts';
import type { RuleOutcome } from '../../research/rule-outcome.ts';
import type { StoreCatalogue, StoreProduct } from '../../store/store-catalogue.ts';
import { buyGoldEntitlement } from '../../store/store-purchase.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts';
export function entitlementsPriceEx(store: StoreCatalogue): CharActionHandler {
const table = buildEntitlementsPriceBlk(store.allProducts());
return () => ({ kind: 'data', blk: table });
}
export function buyEntitlementAction(profiles: PlayerProfiles, accounts: AccountStore, store: StoreCatalogue): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const entitlement = headerOrPayloadString(context, 'entitlement');
const offeredGold = headerOrPayloadInt(context, 'costGold');
if (!entitlement || offeredGold === undefined || offeredGold < 0) {
return { kind: 'error', code: 'BAD_PARAMS' };
}
let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' };
const now = serverTimeNow();
const updated = profiles.updateWhen(account.userId, (saved) => {
outcome = buyGoldEntitlement(saved, store, entitlement, offeredGold, now);
return outcome.ok;
});
if (updated) return { kind: 'data', blk: clientProfile(updated, account) };
return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
});
}
function buildEntitlementsPriceBlk(products: readonly StoreProduct[]): BlkBlock {
const root = emptyBlock();
for (const product of products) {
const block = emptyBlock(product.id);
setParam(block, 'chapter', { type: 'string', value: product.chapter });
if (product.kind === 'eagles') {
setParam(block, 'onlinePurchase', { type: 'bool', value: true });
setParam(block, 'group', { type: 'string', value: 'eagles100' });
setParam(block, 'useGroupAmount', { type: 'bool', value: true });
setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome! });
} else if (product.kind === 'warpoints') {
setParam(block, 'group', { type: 'string', value: '1KWP' });
setParam(block, 'useGroupAmount', { type: 'bool', value: true });
setParam(block, 'wpIncome', { type: 'int', value: product.silverIncome! });
setParam(block, 'goldCost', { type: 'int', value: product.goldCost! });
} else if (product.kind === 'premium-gold') {
setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'group', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'ttl', { type: 'int', value: product.premiumDays! });
setParam(block, 'goldCost', { type: 'int', value: product.goldCost! });
} else if (product.kind === 'premium-gjn') {
setParam(block, 'onlinePurchase', { type: 'bool', value: true });
setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'group', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'ttl', { type: 'int', value: product.premiumDays! });
} else if (product.kind === 'vehicle-pack' && product.vehicles) {
setParam(block, 'onlinePurchase', { type: 'bool', value: true });
setParam(block, 'wtoTitleEn', { type: 'string', value: product.title.en });
setParam(block, 'wtoTitleZh', { type: 'string', value: product.title.zh });
for (const vehicle of product.vehicles) {
appendParam(block, 'aircraftGift', { type: 'string', value: vehicle.name });
}
if (product.goldIncome) setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome });
if (product.silverIncome) setParam(block, 'wpIncome', { type: 'int', value: product.silverIncome });
}
root.blocks.push(block);
}
return root;
}
@@ -0,0 +1,25 @@
/**
* Buying unlocks. cln_buy_unlock is sent with charSendBlk (job type
* 13), so the answer is the whole profile.
*
* cln_buy_unlock (scripts unlocks/unlocksAction.nut buyUnlockImpl; ship flags from
* customization/decoratorAcquire.nut, icons from chooseImage.nut, awards, smokes...):
* name:t the unlock
* unitName:t the vehicle in the hangar (flags); not needed to buy
* wpCost:i goldCost:i
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { buyUnlock, type UnlockShop } from '../../unlocks/unlock-purchase.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function buyUnlockAction(profiles: PlayerProfiles, accounts: AccountStore, unlocks: UnlockShop): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const name = stringParam(payload, 'name');
if (name === undefined) return undefined;
const offered = { silverLions: intParam(payload, 'wpCost') ?? 0, goldenEagles: intParam(payload, 'goldCost') ?? 0 };
return (profile) => buyUnlock(profile, unlocks, name, offered);
});
}
+23
View File
@@ -0,0 +1,23 @@
/** What a char action handler gets and returns. Handlers belong to the rules layer's domains. */
import type { BlkBlock } from '@wto/blk';
import type { CharAnswer } from './char-answers.ts';
export interface CharActionContext {
/** From the request's uidhint header; undefined when the client sent none. */
readonly userId: string | undefined;
/** The request's BLK parameters, when the body carried a BLK. */
readonly payload: BlkBlock | undefined;
/** Raw UTF-8 request body text, for EATT_JSON_REQUEST custom actions. */
readonly rawText: string;
/** Raw request body bytes, for compressed or PBBD-framed cloud-settings uploads. */
readonly rawBody?: Uint8Array;
/**
* A request parameter sent as an HTTP header: char_request_blk_from_server (scripts
* charRequestBlk) sends the top-level parameters of its BLK that way and no body (lab round
* 22: cln_get_users_terse_info with a "usersList" header). Header names arrive lower-cased,
* so the lookup ignores case.
*/
readonly headerParam: (name: string) => string | undefined;
}
export type CharActionHandler = (context: CharActionContext) => CharAnswer;
+41
View File
@@ -0,0 +1,41 @@
/**
* The char service's answer shapes (implementation notes; aces.exe 2.61.0.37,
* CharServerClient::handleReqResult at 0x336d590):
* - data: HTTP 200, a compression marker ('i') and a binary BLK (`loadBlkFromAnswer`, 0x336fd60);
* - raw-blk: HTTP 200, a bare binary BLK with no compression marker, for `online_storage`
* endpoints (`GetMetaHandler` 0x46659c0 and `LoadingHandler` 0x4667930 -> `0x3280a50`);
* - json: HTTP 200, UTF-8 JSON for custom JSON actions;
* - done: HTTP 200 with a body starting "!OK", for requests that expect no data;
* - error: a body starting "!ERROR:" followed by an error code.
*/
import { encodeBlk, formatBlkText, type BlkBlock } from '@wto/blk';
import type { ServiceResponse } from '../transport/exchange.ts';
import { encodeDataAnswer } from './char-payload.ts';
export type CharAnswer =
| { readonly kind: 'data'; readonly blk: BlkBlock }
| { readonly kind: 'raw-blk'; readonly blk: BlkBlock }
| { readonly kind: 'json'; readonly data: unknown }
| { readonly kind: 'done' }
| { readonly kind: 'error'; readonly code: string };
export function toResponse(answer: CharAnswer): ServiceResponse {
switch (answer.kind) {
case 'data':
return { status: 200, headers: BINARY, body: encodeDataAnswer(answer.blk), logNotes: { responseText: formatBlkText(answer.blk) } };
case 'raw-blk':
return { status: 200, headers: BINARY, body: encodeBlk(answer.blk), logNotes: { responseText: formatBlkText(answer.blk) } };
case 'json': {
const body = JSON.stringify(answer.data);
return { status: 200, headers: JSON_HEADERS, body, logNotes: { responseText: body } };
}
case 'done':
return { status: 200, headers: TEXT, body: '!OK' };
case 'error':
return { status: 200, headers: TEXT, body: `!ERROR:${answer.code}` };
}
}
const BINARY = { 'content-type': 'application/octet-stream' };
const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8' };
const TEXT = { 'content-type': 'text/plain' };
+50
View File
@@ -0,0 +1,50 @@
/**
* Bodies exchanged with the char service.
*
* Answers carrying data are a compression marker followed by a binary BLK; the client loads
* them with loadBlkFromAnswer (aces.exe 0x336fd60). We always send them uncompressed.
*
* What the client sends in request bodies is not established yet, so
* decoding is attempted in the forms that are plausible (marked or bare binary BLK, form
* text) and the traffic log records which form it was.
*/
import { decodeBlk, encodeBlk, formatBlkText, type BlkBlock } from '@wto/blk';
import { markUncompressed, unpackMarked } from './compression-marker.ts';
import { describePbbdForLog, isPbbdStream } from './pbbd-stream.ts';
export function encodeDataAnswer(blk: BlkBlock): Uint8Array {
return markUncompressed(encodeBlk(blk));
}
export interface DecodedPayload {
/** How the body was laid out, for the traffic log. */
readonly form: string;
readonly blk?: BlkBlock;
/** Readable rendering for the traffic log. */
readonly text: string;
}
const BINARY_BLK_LABELS = new Set([1, 2, 3, 6]);
export function decodeRequestPayload(body: Uint8Array): DecodedPayload {
if (body.length === 0) return { form: 'empty', text: '' };
try {
if (isPbbdStream(body)) {
return { form: 'PBBD stream', text: describePbbdForLog(body) };
}
const marked = unpackMarked(body);
if (marked) {
if (!marked.data) return { form: `marked ${marked.method}, not unpacked`, text: '' };
return describeBlk(`marked ${marked.method}`, marked.data);
}
if (BINARY_BLK_LABELS.has(body[0]!)) return describeBlk('bare binary BLK', body);
} catch (error) {
return { form: `undecodable (${(error as Error).message})`, text: '' };
}
return { form: 'text', text: Buffer.from(body).toString('utf8') };
}
function describeBlk(form: string, bytes: Uint8Array): DecodedPayload {
const blk = decodeBlk(bytes);
return { form, blk, text: formatBlkText(blk) };
}
+65
View File
@@ -0,0 +1,65 @@
/**
* char service: profiles and player actions.
*
* The client names the action in the request header "action" (request headers assembled at
* aces.exe 0x336c590). Requests carry no "userid" header; the player is identified by
* "uidhint", the user id from the sign-in answer (implementation notes; added by
* EconomicSerializeJob::doJob, 0x2968a5). The local server trusts uidhint as it is: there
* is nothing to protect on a single-player machine.
*
* An action with no handler yet gets a data answer holding an empty BLK and is marked
* unhandled in the traffic log. handleReqResult treats any 200 answer that is not "!ERROR:"
* or "!RETRY" as success for both data requests and requests that expect "!OK", so this
* default lets the client continue and reveal what it asks for next.
*/
import { emptyBlock } from '@wto/blk';
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
import type { CharActionHandler } from './char-action.ts';
import { toResponse, type CharAnswer } from './char-answers.ts';
import { decodeRequestPayload } from './char-payload.ts';
const CHAR_HOST = /^char-[a-z0-9-]+\.warthunder\.com$/;
export class CharService implements Service {
readonly name = 'char';
readonly #actions: ReadonlyMap<string, CharActionHandler>;
constructor(actions: ReadonlyMap<string, CharActionHandler>) {
this.#actions = actions;
}
accepts(request: ServiceRequest): boolean {
return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost);
}
handle(request: ServiceRequest): ServiceResponse {
const action = header(request, 'action') ?? '(no action header)';
const payload = decodeRequestPayload(request.body);
const handler = this.#actions.get(action);
const answer: CharAnswer = handler
? handler({
userId: header(request, 'uidhint'),
payload: payload.blk,
rawText: payload.text,
rawBody: request.body,
headerParam: (name) => header(request, name.toLowerCase()),
})
: { kind: 'data', blk: emptyBlock() };
const response = toResponse(answer);
return {
...response,
logNotes: {
...response.logNotes,
summary: `${action} [request body: ${payload.form}] -> ${answer.kind}${answer.kind === 'error' ? ` ${answer.code}` : ''}`,
unhandled: !handler,
requestText: payload.text,
},
};
}
}
function header(request: ServiceRequest, name: string): string | undefined {
const value = request.headers[name];
const text = Array.isArray(value) ? value[0] : value;
return text ? text : undefined;
}
@@ -0,0 +1,45 @@
/**
* Data answers of the char service start with one byte naming how the rest is compressed.
*
* Source: aces.exe 2.61.0.37. The client's table of compression methods is filled at
* 0x3373cd0 (name, implementation, marker byte); the answer is unpacked by
* processPotentiallyCompressedAnswer (0x3372190), which takes the bytes after an 'i' marker
* as they are. Only the methods Node can unpack are decoded here.
*/
import { gunzipSync, inflateSync, zstdDecompressSync } from 'node:zlib';
export const MARKER_NONE = 0x69; // 'i'
const DECODERS: ReadonlyMap<number, { readonly name: string; readonly unpack?: (data: Uint8Array) => Uint8Array }> = new Map([
[MARKER_NONE, { name: 'none', unpack: (data: Uint8Array) => data }],
[0x5a, { name: 'zstd', unpack: (data: Uint8Array) => zstdDecompressSync(data) }], // 'Z'
[0x7a, { name: 'zlib', unpack: (data: Uint8Array) => inflateSync(data) }], // 'z'
[0x1f, { name: 'gzip', unpack: (data: Uint8Array) => gunzipSync(data) }],
[0x4c, { name: 'lz4hc' }], // 'L'
[0x6c, { name: 'lz4' }], // 'l'
[0x73, { name: 'snappy' }], // 's'
[0x62, { name: 'bzip2' }], // 'b'
[0x56, { name: 'vromfs' }], // 'V'
]);
export interface UnpackResult {
readonly method: string;
/** Undefined when the method is known but cannot be unpacked here. */
readonly data: Uint8Array | undefined;
}
/** Undefined when the first byte is not a compression marker. */
export function unpackMarked(bytes: Uint8Array): UnpackResult | undefined {
const decoder = DECODERS.get(bytes[0] ?? -1);
if (!decoder) return undefined;
// gzip's marker is the first byte of the gzip stream itself.
const rest = decoder.name === 'gzip' ? bytes : bytes.subarray(1);
return { method: decoder.name, data: decoder.unpack ? decoder.unpack(rest) : undefined };
}
export function markUncompressed(data: Uint8Array): Uint8Array {
const marked = new Uint8Array(data.length + 1);
marked[0] = MARKER_NONE;
marked.set(data, 1);
return marked;
}
+136
View File
@@ -0,0 +1,136 @@
/**
* Protocol-layer wire codecs for `online_storage` (`cln_set_general_blk` and `PBBD` batch
* streams on `cln_bulk_set_gblk`; implementation notes; aces.exe 0x4662a70..0x466b2ec,
* 0x41537d0..0x4154020).
*/
import { createHash } from 'node:crypto';
import { gunzipSync, inflateSync, zstdDecompressSync } from 'node:zlib';
import { decodeBlk, emptyBlock, encodeBlk, findBlock, setParam, type BlkBlock } from '@wto/blk';
import type { ParsedGblkUpload } from '../cloud-settings/cloud-settings-store.ts';
import { intField, stringField } from '../profile/blk-fields.ts';
import { unpackMarked } from './compression-marker.ts';
export const PBBD_MAGIC = 0x44424250; // "PBBD" little-endian (0x4663427: 0x144424250)
export function isPbbdStream(bytes: Uint8Array): boolean {
if (bytes.byteLength < 8) return false;
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
return view.getUint32(0, true) === PBBD_MAGIC && view.getUint16(4, true) === 1;
}
export function unpackCloudBlk(bytes: Uint8Array, comprHeader: string | undefined): BlkBlock | undefined {
if (bytes.byteLength === 0) return undefined;
const raw = decompressCloudBytes(bytes, comprHeader);
if (!raw || raw.byteLength === 0) return undefined;
try {
return decodeBlk(raw);
} catch {
return undefined;
}
}
export function parsePbbdBulkUploads(bytes: Uint8Array): ReadonlyArray<ParsedGblkUpload> {
if (!isPbbdStream(bytes)) return [];
const chunks = readPbbdChunks(bytes);
const uploads: ParsedGblkUpload[] = [];
for (let i = 0; i < chunks.length; i++) {
const meta = chunks[i];
if (!meta) continue;
const desc = stringField(meta, 'desc');
if (desc === 'store_gblk') {
const containerCandidate = chunks[i + 1];
i += 1;
const blkType = stringField(meta, 'blkType');
if (!blkType || !containerCandidate) continue;
const fallbackVersion = intField(meta, 'version', 1) || 1;
const extracted = normalizeContainerBlk(containerCandidate, fallbackVersion);
const contentHash = stringField(meta, 'contentHash') || computeContentHash(extracted.content);
uploads.push({ blkType, version: extracted.version, contentHash, container: extracted.container });
} else if (desc === 'bigquery' || desc === 'logout') {
i += 1;
}
}
return uploads;
}
export function normalizeContainerBlk(
incoming: BlkBlock,
fallbackVersion: number,
): { readonly version: number; readonly content: BlkBlock; readonly container: BlkBlock } {
const existingContent = findBlock(incoming, 'content');
const rawVersion = intField(incoming, 'version', fallbackVersion);
const version = rawVersion > 0 ? rawVersion : Math.max(1, fallbackVersion);
const content = cloneAsContent(existingContent ?? incoming);
return { version, content, container: buildContainerBlk(version, content) };
}
export function buildContainerBlk(version: number, content: BlkBlock): BlkBlock {
const container = emptyBlock();
setParam(container, 'version', { type: 'int', value: Math.max(1, Math.trunc(version)) });
container.blocks.push(cloneAsContent(content));
return container;
}
export function computeContentHash(content: BlkBlock): string {
const rootCopy = emptyBlock();
rootCopy.params.push(...content.params);
rootCopy.blocks.push(...content.blocks);
return createHash('md5').update(encodeBlk(rootCopy)).digest('hex');
}
export function describePbbdForLog(bytes: Uint8Array): string {
const uploads = parsePbbdBulkUploads(bytes);
if (uploads.length === 0) return 'PBBD stream (0 store_gblk items)';
return uploads.map((u) => `${u.blkType} v${u.version} (${u.contentHash})`).join(', ');
}
function readPbbdChunks(bytes: Uint8Array): Array<BlkBlock | undefined> {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const chunkCount = view.getUint16(6, true);
const chunks: Array<BlkBlock | undefined> = [];
let offset = 8;
for (let i = 0; i < chunkCount; i++) {
if (offset + 5 > bytes.byteLength) break;
const payloadLen = view.getUint32(offset, true);
const marker = bytes[offset + 4]!;
offset += 5;
if (offset + payloadLen > bytes.byteLength) break;
const slice = bytes.subarray(offset, offset + payloadLen);
offset += payloadLen;
chunks.push(decodeMarkedChunk(marker, slice));
}
return chunks;
}
function cloneAsContent(source: BlkBlock): BlkBlock {
return { name: 'content', params: [...source.params], blocks: [...source.blocks] };
}
function decompressCloudBytes(bytes: Uint8Array, comprHeader: string | undefined): Uint8Array | undefined {
const method = comprHeader?.trim().toLowerCase();
try {
if (method === 'zstd') return zstdDecompressSync(bytes);
if (method === 'zlib') return bytes.byteLength > 4 ? inflateSync(bytes.subarray(4)) : undefined;
if (method === 'gzip') return gunzipSync(bytes);
if (!method || method === 'none') return unpackMarked(bytes)?.data ?? bytes;
return unpackMarked(bytes)?.data;
} catch {
return unpackMarked(bytes)?.data;
}
}
function decodeMarkedChunk(marker: number, payload: Uint8Array): BlkBlock | undefined {
if (payload.byteLength === 0) return emptyBlock();
try {
let raw: Uint8Array | undefined;
if (marker === 0x69) raw = payload;
else if (marker === 0x5a) raw = zstdDecompressSync(payload);
else if (marker === 0x7a) raw = payload.byteLength > 4 ? inflateSync(payload.subarray(4)) : undefined;
else if (marker === 0x1f) raw = gunzipSync(payload);
return raw ? decodeBlk(raw) : undefined;
} catch {
return undefined;
}
}