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

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

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

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

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

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


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

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

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
/**
* Load redemption codes and their rewards from tuning/redeem-codes.jsonc. Player-facing
* descriptions use the same values.
*/
import type { BlkBlock } from '@wto/blk';
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
import { addGjnCents, addGoldenEagles, addSilverLions } from '../profile/profile-currency.ts';
import { extendPremiumAccount, hasEntitlement, recordEntitlementPurchase } from '../profile/profile-entitlements.ts';
import type { CodeReward, PatternCodeTuning, RedeemTuning } from './redeem-tuning.ts';
export type RedeemOutcome =
| { readonly ok: true; readonly message: LocalizedText }
| { readonly ok: false; readonly reason: 'INVALID_CODE' | 'ALREADY_REDEEMED'; readonly message: LocalizedText };
export function redeemStoreCode(profile: BlkBlock, rawCode: string, nowFiletime: bigint, tuning: RedeemTuning): RedeemOutcome {
const code = rawCode.trim().toUpperCase();
if (!code) return { ok: false, reason: 'INVALID_CODE', message: { en: 'Enter a redeem code.', zh: '请输入兑换码。' } };
const fixed = tuning.fixedCodes.get(code);
if (fixed) return redeemFixedCode(profile, code, fixed, nowFiletime);
const days = patternAmount(code, tuning.premiumDays, 'D');
if (days !== undefined) return grant(profile, code, { ...NOTHING, premiumDays: days }, nowFiletime);
const gjn = patternAmount(code, tuning.gjn, '');
if (gjn !== undefined) return grant(profile, code, { ...NOTHING, gjnCents: gjn * 100 }, nowFiletime);
const examples = [...tuning.premiumDays.examples, ...tuning.gjn.examples, ...tuning.fixedCodes.keys()];
return {
ok: false,
reason: 'INVALID_CODE',
message: { en: `Unknown redeem code. Examples: ${examples.join(', ')}.`, zh: `无效的兑换码。可用示例:${examples.join('、')}。` },
};
}
/** One line per kind of code, for the store page. */
export function describeRedeemCodes(tuning: RedeemTuning): LocalizedText[] {
const premiumForm = `${tuning.premiumDays.prefixes[0]}-<N>D`;
const gjnForm = `${tuning.gjn.prefixes[0]}-<N>`;
return [
{
zh: `高级账户天数:${tuning.premiumDays.examples.join('、')}(或任意 ${premiumForm},最多 ${tuning.premiumDays.max} 天)`,
en: `Premium Account days: ${tuning.premiumDays.examples.join(', ')} (or any ${premiumForm}, up to ${tuning.premiumDays.max} days)`,
},
{
zh: `GJN 充值作弊码:${tuning.gjn.examples.join('、')}(或任意 ${gjnForm},最多 ${tuning.gjn.max.toLocaleString('en-US')})`,
en: `GJN cheat code: ${tuning.gjn.examples.join(', ')} (or any ${gjnForm}, up to ${tuning.gjn.max.toLocaleString('en-US')})`,
},
...[...tuning.fixedCodes].map(([code, reward]) => {
const text = rewardText(reward);
return { zh: `${code}(每个存档一次):${text.zh}`, en: `${code} (once per save): ${text.en}` };
}),
];
}
const NOTHING: CodeReward = { premiumDays: 0, goldenEagles: 0, silverLions: 0, gjnCents: 0 };
/** The amount in "<prefix>-<amount><suffix>" when the code has that form and the amount is in range. */
function patternAmount(code: string, pattern: PatternCodeTuning, suffix: string): number | undefined {
for (const prefix of pattern.prefixes) {
if (!code.startsWith(`${prefix}-`) || !code.endsWith(suffix)) continue;
const digits = code.slice(prefix.length + 1, code.length - suffix.length);
if (!/^\d+$/.test(digits)) continue;
const amount = Number(digits);
if (amount >= 1 && amount <= pattern.max) return amount;
}
return undefined;
}
function redeemFixedCode(profile: BlkBlock, code: string, reward: CodeReward, nowFiletime: bigint): RedeemOutcome {
const marker = `wto_redeem_${code.toLowerCase().replace(/-/g, '_')}`;
if (hasEntitlement(profile, marker, nowFiletime)) {
return { ok: false, reason: 'ALREADY_REDEEMED', message: { en: `${code} has already been redeemed on this save.`, zh: `当前存档已经用过 ${code}。` } };
}
recordEntitlementPurchase(profile, marker);
return grant(profile, code, reward, nowFiletime);
}
function grant(profile: BlkBlock, code: string, reward: CodeReward, nowFiletime: bigint): RedeemOutcome {
if (reward.premiumDays) extendPremiumAccount(profile, reward.premiumDays, nowFiletime);
if (reward.goldenEagles) addGoldenEagles(profile, reward.goldenEagles);
if (reward.silverLions) addSilverLions(profile, reward.silverLions);
if (reward.gjnCents) addGjnCents(profile, reward.gjnCents);
const text = rewardText(reward);
return { ok: true, message: { en: `Redeemed ${code}: ${text.en}.`, zh: `兑换成功(${code}):${text.zh}。` } };
}
function rewardText(reward: CodeReward): LocalizedText {
const parts: LocalizedText[] = [];
const n = (value: number) => value.toLocaleString('en-US');
if (reward.premiumDays) parts.push({ zh: `高级账户 +${reward.premiumDays} 天`, en: `+${reward.premiumDays} days of Premium Account` });
if (reward.goldenEagles) parts.push({ zh: `金鹰 +${n(reward.goldenEagles)}`, en: `+${n(reward.goldenEagles)} Golden Eagles` });
if (reward.silverLions) parts.push({ zh: `银狮 +${n(reward.silverLions)}`, en: `+${n(reward.silverLions)} Silver Lions` });
if (reward.gjnCents) parts.push({ zh: `GJN +${gjnText(reward.gjnCents)}`, en: `+${gjnText(reward.gjnCents)} GJN` });
return { zh: parts.map((part) => part.zh).join('、'), en: parts.map((part) => part.en).join(', ') };
}
/** A GJN amount in hundredths as the player reads it: 100 -> "1", 1299 -> "12.99". */
export function gjnText(cents: number): string {
return (cents / 100).toLocaleString('en-US', { minimumFractionDigits: cents % 100 ? 2 : 0, maximumFractionDigits: 2 });
}
+48
View File
@@ -0,0 +1,48 @@
/** Typed redemption code settings from tuning/redeem-codes.jsonc. */
import type { TuningReader } from '../tuning/tuning-reader.ts';
export interface PatternCodeTuning {
readonly prefixes: readonly string[];
readonly max: number;
readonly examples: readonly string[];
}
/** What a code grants; every amount is 0 or more. */
export interface CodeReward {
readonly premiumDays: number;
readonly goldenEagles: number;
readonly silverLions: number;
/** GJN in hundredths. */
readonly gjnCents: number;
}
export interface RedeemTuning {
readonly premiumDays: PatternCodeTuning;
readonly gjn: PatternCodeTuning;
/** Upper-case code -> reward; each can be used once per save. */
readonly fixedCodes: ReadonlyMap<string, CodeReward>;
}
export function readRedeemTuning(file: TuningReader): RedeemTuning {
const premium = file.object('premiumDays');
const gjn = file.object('gjn');
return {
premiumDays: { prefixes: upper(premium.stringList('prefixes')), max: premium.int('maxDays', { min: 1 }), examples: premium.stringList('examples') },
gjn: { prefixes: upper(gjn.stringList('prefixes')), max: gjn.int('maxAmount', { min: 1 }), examples: gjn.stringList('examples') },
fixedCodes: new Map([...file.table('fixedCodes', readReward)].map(([code, reward]) => [code.toUpperCase(), reward])),
};
}
function readReward(entry: TuningReader): CodeReward {
const amount = (key: string) => (entry.has(key) ? entry.int(key, { min: 0 }) : 0);
return {
premiumDays: amount('premiumDays'),
goldenEagles: amount('goldenEagles'),
silverLions: amount('silverLions'),
gjnCents: entry.has('gjn') ? entry.money('gjn', { min: 0 }) : 0,
};
}
function upper(values: readonly string[]): string[] {
return values.map((value) => value.toUpperCase());
}
+216
View File
@@ -0,0 +1,216 @@
/**
* Local store catalogue: Golden Eagles packs, Silver Lions
* packs, Premium Account durations (both Golden Eagles and GJN), multi-vehicle bundles/starter
* packs, and one vehicle pack per remaining gift vehicle in the tech tree. What is sold and for
* how much is tuning (tuning/store.jsonc); which vehicles get a single-vehicle pack follows the
* game data (isPackVehicle).
*
* Pure domain catalogue: protocol-layer DataBlock serialization for `cln_get_entitlements_price_ex`
* lives in `char/actions/store-actions.ts`.
*/
import { singleVehiclePackId, stableGuid } from '@wto/blk';
import type { StoreBundleGuids } from '../game-data/datasets/store-bundles.ts';
import type { UiLabels } from '../game-data/datasets/ui-labels.ts';
import type { LocalizedText, UnitNamesMap } from '../game-data/datasets/unit-names.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import { TuningError } from '../tuning/tuning-reader.ts';
import { vehiclePackContent, type MultiPackNaming, type StoreTuning } from './store-tuning.ts';
export type StoreProductKind = 'eagles' | 'warpoints' | 'premium-gold' | 'premium-gjn' | 'vehicle-pack';
export interface StoreProduct {
readonly id: string;
readonly kind: StoreProductKind;
readonly chapter: string;
readonly title: LocalizedText;
/** Store item GUID when offered via item_info.php / item_purchase.php. */
readonly guid?: string;
/** Price in Golden Eagles (in-game purchase via cln_buy_entitlement). */
readonly goldCost?: number;
/** Price in GJN (onlinePurchase via item_purchase.php or the local web store). */
readonly gjnCostCents?: number;
/** Golden Eagles granted on purchase. */
readonly goldIncome?: number;
/** Silver Lions granted on purchase. */
readonly silverIncome?: number;
/** Premium Account days granted on purchase. */
readonly premiumDays?: number;
/** Vehicles granted on purchase (1 for single packs, 2-3 for starter/bundle packs), with any split-vehicle parts. */
readonly vehicles?: readonly CatalogueVehicle[];
/** Stock group artwork resource name for a multi-vehicle pack. */
readonly artworkGroup?: string;
/** Localized names of `vehicles` in the same order. */
readonly vehicleTitles?: readonly LocalizedText[];
}
export class StoreCatalogue {
readonly #byId = new Map<string, StoreProduct>();
readonly #byGuid = new Map<string, StoreProduct>();
constructor(
vehicles: readonly CatalogueVehicle[],
bundleGuids: StoreBundleGuids,
names: UnitNamesMap,
labels: UiLabels,
tuning: StoreTuning,
) {
const products: StoreProduct[] = [
...buildEaglesProducts(tuning, bundleGuids),
...buildSilverProducts(tuning),
...buildPremiumGoldProducts(tuning),
...buildPremiumGjnProducts(tuning, bundleGuids),
...buildVehiclePackProducts(tuning, vehicles, names, labels),
];
for (const product of products) {
if (this.#byId.has(product.id)) throw new TuningError(`store catalogue: duplicate product id "${product.id}"`);
this.#byId.set(product.id, product);
if (product.guid) this.#byGuid.set(product.guid.toUpperCase(), product);
}
}
allProducts(): readonly StoreProduct[] {
return [...this.#byId.values()];
}
byId(id: string): StoreProduct | undefined {
return this.#byId.get(id);
}
byGuid(guid: string): StoreProduct | undefined {
return this.#byGuid.get(guid.trim().toUpperCase());
}
}
function buildEaglesProducts(tuning: StoreTuning, bundleGuids: StoreBundleGuids): StoreProduct[] {
return tuning.goldenEaglePacks.map((pack) => {
const guid = bundleGuids[pack.id];
return {
id: pack.id,
kind: 'eagles',
chapter: 'eagles',
title: { en: `${pack.goldenEagles.toLocaleString('en-US')} Golden Eagles`, zh: `${pack.goldenEagles.toLocaleString('en-US')} 金鹰` },
...(guid ? { guid } : {}),
gjnCostCents: pack.gjnCents,
goldIncome: pack.goldenEagles,
};
});
}
function buildSilverProducts(tuning: StoreTuning): StoreProduct[] {
return tuning.silverLionPacks.map((pack) => ({
id: pack.id,
kind: 'warpoints',
chapter: 'warpoints',
title: { en: `${pack.silverLions.toLocaleString('en-US')} Silver Lions`, zh: `${pack.silverLions.toLocaleString('en-US')} 银狮` },
goldCost: pack.goldenEagles,
silverIncome: pack.silverLions,
}));
}
function buildPremiumGoldProducts(tuning: StoreTuning): StoreProduct[] {
return tuning.premiumForGoldenEagles.map((tier) => ({
id: tier.id,
kind: 'premium-gold',
chapter: 'premium',
title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` },
goldCost: tier.price,
premiumDays: tier.days,
}));
}
function buildPremiumGjnProducts(tuning: StoreTuning, bundleGuids: StoreBundleGuids): StoreProduct[] {
return tuning.premiumForGjn.map((tier) => {
const guid = bundleGuids[tier.id];
return {
id: tier.id,
kind: 'premium-gjn',
chapter: 'premium',
title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` },
...(guid ? { guid } : {}),
gjnCostCents: tier.price,
premiumDays: tier.days,
};
});
}
function buildVehiclePackProducts(
tuning: StoreTuning,
vehicles: readonly CatalogueVehicle[],
names: UnitNamesMap,
labels: UiLabels,
): StoreProduct[] {
const byName = new Map(vehicles.map((vehicle) => [vehicle.name, vehicle]));
const inMultiPack = new Set<string>();
const multiPacks: StoreProduct[] = tuning.multiVehiclePacks.map((pack) => {
const packVehicles = pack.vehicles.map((unitName) => {
const found = byName.get(unitName);
if (!found) throw new TuningError(`tuning file store.jsonc: multiVehiclePacks (${pack.id}) references unknown vehicle "${unitName}"`);
inMultiPack.add(unitName);
return found;
});
return {
id: pack.id,
guid: stableGuid(pack.id),
kind: 'vehicle-pack',
chapter: 'bonuses',
title: resolveMultiPackTitle(pack.id, pack.naming, packVehicles[0]!, names, labels),
...(pack.naming.kind === 'group' ? { artworkGroup: pack.naming.groupKey.slice('shop/group/'.length) } : {}),
gjnCostCents: pack.gjnCents,
...(pack.goldenEagles ? { goldIncome: pack.goldenEagles } : {}),
...(pack.silverLions ? { silverIncome: pack.silverLions } : {}),
...(pack.premiumDays ? { premiumDays: pack.premiumDays } : {}),
vehicles: packVehicles,
vehicleTitles: packVehicles.map((vehicle) => names[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name }),
};
});
const singlePacks: StoreProduct[] = vehicles
.filter((vehicle) => isPackVehicle(vehicle) && !inMultiPack.has(vehicle.name))
.map((vehicle) => {
const content = vehiclePackContent(tuning, vehicle.name, vehicle.rank);
const unitLabel = names[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name };
const id = singleVehiclePackId(vehicle.name);
return {
id,
guid: stableGuid(id),
kind: 'vehicle-pack',
chapter: 'bonuses',
title: { en: `${unitLabel.en} Pack`, zh: `${unitLabel.zh} 礼包` },
gjnCostCents: content.gjnCents,
...(content.goldenEagles ? { goldIncome: content.goldenEagles } : {}),
...(content.silverLions ? { silverIncome: content.silverLions } : {}),
...(content.premiumDays ? { premiumDays: content.premiumDays } : {}),
vehicles: [vehicle],
vehicleTitles: [unitLabel],
};
});
return [...multiPacks, ...singlePacks];
}
function resolveMultiPackTitle(
packId: string,
naming: MultiPackNaming,
firstVehicle: CatalogueVehicle,
names: UnitNamesMap,
labels: UiLabels,
): LocalizedText {
if (naming.kind === 'custom') return naming.title;
if (naming.kind === 'group') {
const group = names[naming.groupKey];
if (!group) throw new Error(`lang/units.csv has no "${naming.groupKey}" entry for multi-vehicle pack "${packId}"`);
return { en: `${group.en} Pack`, zh: `${group.zh}礼包` };
}
const country = labels[firstVehicle.country];
if (!country) throw new Error(`lang/menu.csv has no "${firstVehicle.country}" entry for starter pack "${packId}"`);
return { en: `${country.en} Starter Pack`, zh: `${country.zh}新手礼包` };
}
function isPackVehicle(vehicle: CatalogueVehicle): boolean {
return vehicle.inTechTree
&& vehicle.gift
&& !vehicle.event
&& vehicle.marketplaceItemdefId === undefined
&& !vehicle.onlyShownWhenOwned;
}
+14
View File
@@ -0,0 +1,14 @@
/**
* The ids of the multi-vehicle packs the store sells, from tuning/store.jsonc with the player's
* overrides in <data folder>/tuning/ laid over it, exactly as the running server reads them.
*
* Whoever builds the game copy needs them: the client looks a pack up only when config/gui.blk
* `bundles/guid` registers a GUID for its id, so the build must register every pack this server
* will sell from the same data folder.
*/
import { tuningFiles } from '../tuning/tuning-loader.ts';
import { readStoreTuning } from './store-tuning.ts';
export function multiVehiclePackIds(dataFolder: string, report: (line: string) => void): string[] {
return readStoreTuning(tuningFiles(dataFolder, report).read('store')).multiVehiclePacks.map((pack) => pack.id);
}
+126
View File
@@ -0,0 +1,126 @@
/**
* Store purchase rules:
* - buyGoldEntitlement: Golden-Eagle-priced entitlements (Premium Account days, Silver Lions packs)
* bought through cln_buy_entitlement;
* - buyGjnProduct: GJN-priced products (Golden Eagles packs, GJN Premium Account, vehicle packs)
* bought through item_purchase.php or the local web store.
*/
import type { BlkBlock } from '@wto/blk';
import { addGoldenEagles, addSilverLions, balanceOf, canAfford, pay, payGjnCents } from '../profile/profile-currency.ts';
import { extendPremiumAccount, hasEntitlement, recordEntitlementPurchase } from '../profile/profile-entitlements.ts';
import { addOwnedVehicle, ownsVehicle } from '../profile/profile-hangar.ts';
import { appendEntitlementPurchase } from '../profile/profile-trophies-log.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts';
export function buyGoldEntitlement(
profile: BlkBlock,
catalogue: StoreCatalogue,
entitlementId: string,
offeredGoldCost: number,
nowFiletime: bigint,
): RuleOutcome {
const product = catalogue.byId(entitlementId);
if (!product || product.goldCost === undefined || !Number.isSafeInteger(offeredGoldCost) || offeredGoldCost < 0) {
return refused('BAD_PARAMS');
}
if (offeredGoldCost !== product.goldCost) return refused('PRICE_CHANGED');
const price = { silverLions: 0, goldenEagles: product.goldCost };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
grantProductRewards(profile, product, nowFiletime);
return ACCEPTED;
}
export type GjnPurchaseOutcome =
| { readonly ok: true }
| { readonly ok: false; readonly reason: 'NOT_FOUND' | 'ALREADY_BOUGHT' | 'NOT_ENOUGH_GJN' };
export function canBuyGjnProduct(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): boolean {
if (product.gjnCostCents === undefined) return false;
if (product.kind === 'vehicle-pack' && product.vehicles) {
if (hasEntitlement(profile, product.id, nowFiletime)) return false;
return !product.vehicles.every((vehicle) => ownsVehicle(profile, vehicle.name));
}
return true;
}
export function buyGjnProduct(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): GjnPurchaseOutcome {
if (product.gjnCostCents === undefined) return { ok: false, reason: 'NOT_FOUND' };
if (!canBuyGjnProduct(profile, product, nowFiletime)) return { ok: false, reason: 'ALREADY_BOUGHT' };
if (balanceOf(profile).gjnCents < product.gjnCostCents) return { ok: false, reason: 'NOT_ENOUGH_GJN' };
payGjnCents(profile, product.gjnCostCents);
grantProductRewards(profile, product, nowFiletime);
return { ok: true };
}
/** Grant a store product using the free offline payment method. */
export function buyFreeStoreProduct(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): GjnPurchaseOutcome {
if (product.gjnCostCents === undefined) return { ok: false, reason: 'NOT_FOUND' };
if (!canBuyGjnProduct(profile, product, nowFiletime)) return { ok: false, reason: 'ALREADY_BOUGHT' };
grantProductRewards(profile, product, nowFiletime);
return { ok: true };
}
export type StoreCheckoutOutcome =
| { readonly ok: true; readonly costCents: number }
| { readonly ok: false; readonly reason: 'NOT_FOUND' | 'ALREADY_BOUGHT'; readonly productId: string }
| { readonly ok: false; readonly reason: 'NOT_ENOUGH_GJN'; readonly costCents: number };
/** Stage every grant before committing the rewards and charge to the player's profile. */
export function buyStoreCart(
profile: BlkBlock,
products: readonly StoreProduct[],
payMethod: 'gjn' | 'free',
nowFiletime: bigint,
): StoreCheckoutOutcome {
const draft = structuredClone(profile);
let costCents = 0;
for (const product of products) {
const price = product.gjnCostCents;
if (price === undefined) return { ok: false, reason: 'NOT_FOUND', productId: product.id };
if (!canBuyGjnProduct(draft, product, nowFiletime)) return { ok: false, reason: 'ALREADY_BOUGHT', productId: product.id };
grantProductRewards(draft, product, nowFiletime);
costCents += price;
}
if (payMethod === 'gjn') {
if (balanceOf(draft).gjnCents < costCents) return { ok: false, reason: 'NOT_ENOUGH_GJN', costCents };
payGjnCents(draft, costCents);
}
profile.params = draft.params;
profile.blocks = draft.blocks;
return { ok: true, costCents: payMethod === 'gjn' ? costCents : 0 };
}
function grantProductRewards(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): void {
const before = balanceOf(profile);
const newVehicles: string[] = [];
if (product.id !== 'PremiumAccount') recordEntitlementPurchase(profile, product.id);
if (product.goldIncome) addGoldenEagles(profile, product.goldIncome);
if (product.silverIncome) addSilverLions(profile, product.silverIncome);
if (product.premiumDays) extendPremiumAccount(profile, product.premiumDays, nowFiletime);
if (product.vehicles) {
for (const vehicle of product.vehicles) {
if (!ownsVehicle(profile, vehicle.name)) {
addOwnedVehicle(profile, vehicle.name);
newVehicles.push(vehicle.name);
}
for (const part of vehicle.parts) {
if (!ownsVehicle(profile, part)) addOwnedVehicle(profile, part);
}
}
}
const after = balanceOf(profile);
appendEntitlementPurchase(profile, {
productId: product.id,
goldenEagleCost: product.goldCost,
goldenEagles: after.goldenEagles - before.goldenEagles,
silverLions: after.silverLions - before.silverLions,
premiumDays: product.premiumDays ?? 0,
vehicles: newVehicles,
}, nowFiletime);
}
+50
View File
@@ -0,0 +1,50 @@
/**
* Store service (implementation notes; implementation notes): routes the game's
* yuplay2 store requests (yuplay-store-api.ts) and the local store page (/store: its files
* from web/, its JSON requests in store-web-api.ts).
*/
import type { AccountStore } from '../accounts/account-store.ts';
import { redactLoginForm } from '../login/form-redaction.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
import { createStaticWebSite, notFound } from '../web-ui/web-helpers.ts';
import type { RedeemTuning } from './redeem-tuning.ts';
import type { StoreCatalogue } from './store-catalogue.ts';
import { StoreWebApi } from './store-web-api.ts';
import { YUPLAY_STORE_PATHS, YuplayStoreApi } from './yuplay-store-api.ts';
const PAGE_PREFIX = '/store';
const STORE_PAGE = createStaticWebSite(new URL('./web/', import.meta.url), [
'index.html', 'styles.css', 'product.css', 'checkout.css', 'app.js', 'products.js', 'gallery.js', 'checkout.js',
]);
const STORE_API_HOSTS = new Set(['api.gaijinent.com', 'store.gaijin.net']);
export class StoreService implements Service {
readonly name = 'store';
readonly #yuplay: YuplayStoreApi;
readonly #web: StoreWebApi;
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning, port: number) {
this.#yuplay = new YuplayStoreApi(accounts, profiles, catalogue, redeemCodes, `http://127.0.0.1:${port}${PAGE_PREFIX}`);
this.#web = new StoreWebApi(accounts, profiles, catalogue, redeemCodes);
}
accepts(request: ServiceRequest): boolean {
if (isPagePath(request.path)) return true;
return YUPLAY_STORE_PATHS.has(request.path) && (request.originalHost === undefined || STORE_API_HOSTS.has(request.originalHost));
}
handle(request: ServiceRequest): ServiceResponse {
if (isPagePath(request.path)) {
const subPath = request.path.slice(PAGE_PREFIX.length) || '/';
return this.#web.handle(subPath, request) ?? STORE_PAGE.serve(subPath, 'store page') ?? notFound(`store page 404: ${subPath}`);
}
const redacted = redactLoginForm(request.body);
const response = this.#yuplay.handle(request);
return { ...response, logNotes: { ...response.logNotes, redactedRequestBody: redacted, requestText: redacted } };
}
}
function isPagePath(path: string): boolean {
return path === PAGE_PREFIX || path.startsWith(`${PAGE_PREFIX}/`);
}
+164
View File
@@ -0,0 +1,164 @@
/** Typed content of tuning/store.jsonc. */
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
export interface GoldenEaglePack {
readonly id: string;
readonly goldenEagles: number;
readonly gjnCents: number;
}
export interface SilverLionPack {
readonly id: string;
readonly silverLions: number;
readonly goldenEagles: number;
}
export interface PremiumTier {
readonly id: string;
readonly days: number;
/** Price: golden eagles for premiumForGoldenEagles, GJN hundredths for premiumForGjn. */
readonly price: number;
}
export interface VehiclePackContent {
readonly gjnCents: number;
readonly goldenEagles: number;
readonly premiumDays: number;
readonly silverLions?: number;
}
export type MultiPackNaming =
| { readonly kind: 'group'; readonly groupKey: string }
| { readonly kind: 'starter' }
| { readonly kind: 'custom'; readonly title: LocalizedText };
export interface MultiVehiclePack extends VehiclePackContent {
readonly id: string;
readonly naming: MultiPackNaming;
readonly vehicles: readonly string[];
}
export interface StoreTuning {
readonly goldenEaglePacks: readonly GoldenEaglePack[];
readonly silverLionPacks: readonly SilverLionPack[];
readonly premiumForGoldenEagles: readonly PremiumTier[];
readonly premiumForGjn: readonly PremiumTier[];
/** Multi-vehicle bundles and starter packs sold as a single pack. */
readonly multiVehiclePacks: readonly MultiVehiclePack[];
/** Sorted by upToRank. */
readonly vehiclePacksByRank: readonly (VehiclePackContent & { readonly upToRank: number })[];
/** Per-vehicle content; a field left out comes from the vehicle's rank tier. */
readonly vehiclePacksByVehicle: ReadonlyMap<string, Partial<VehiclePackContent>>;
}
export function readStoreTuning(file: TuningReader): StoreTuning {
const packs = file.object('vehiclePacks');
const byRank = packs.list('byRank', (entry) => ({ upToRank: entry.int('upToRank', { min: 1 }), ...packContent(entry) }))
.sort((a, b) => a.upToRank - b.upToRank);
if (byRank.length === 0) throw new TuningError('tuning file store.jsonc: vehiclePacks.byRank must have at least one tier');
const goldenEaglePacks = file.list('goldenEaglePacks', (entry) => ({ id: entry.string('id'), goldenEagles: entry.int('goldenEagles', { min: 1 }), gjnCents: entry.money('gjn', { min: 0.01 }) }));
const silverLionPacks = file.list('silverLionPacks', (entry) => ({ id: entry.string('id'), silverLions: entry.int('silverLions', { min: 1 }), goldenEagles: entry.int('goldenEagles', { min: 1 }) }));
const premiumForGoldenEagles = file.list('premiumForGoldenEagles', (entry) => premiumTier(entry, 'goldenEagles'));
const premiumForGjn = file.list('premiumForGjn', (entry) => premiumTier(entry, 'gjn'));
const multiVehiclePacks = packs.list('multiVehiclePacks', readMultiVehiclePack);
const vehiclePacksByVehicle = packs.table('byVehicle', partialPackContent);
validateStoreUniqueness(goldenEaglePacks, silverLionPacks, premiumForGoldenEagles, premiumForGjn, multiVehiclePacks);
return {
goldenEaglePacks,
silverLionPacks,
premiumForGoldenEagles,
premiumForGjn,
multiVehiclePacks,
vehiclePacksByRank: byRank,
vehiclePacksByVehicle,
};
}
/** The pack content for a vehicle: its own entry over the first rank tier that covers its rank (the last tier above the highest). */
export function vehiclePackContent(tuning: StoreTuning, vehicle: string, rank: number): VehiclePackContent {
const tier = tuning.vehiclePacksByRank.find((entry) => rank <= entry.upToRank) ?? tuning.vehiclePacksByRank[tuning.vehiclePacksByRank.length - 1]!;
const own = tuning.vehiclePacksByVehicle.get(vehicle) ?? {};
const silverLions = own.silverLions ?? tier.silverLions;
return {
gjnCents: own.gjnCents ?? tier.gjnCents,
goldenEagles: own.goldenEagles ?? tier.goldenEagles,
premiumDays: own.premiumDays ?? tier.premiumDays,
...(silverLions ? { silverLions } : {}),
};
}
function premiumTier(entry: TuningReader, currency: 'goldenEagles' | 'gjn'): PremiumTier {
const price = currency === 'gjn' ? entry.money('gjn', { min: 0.01 }) : entry.int('goldenEagles', { min: 1 });
return { id: entry.string('id'), days: entry.int('days', { min: 1 }), price };
}
function packContent(entry: TuningReader): VehiclePackContent {
const silverLions = entry.has('silverLions') ? entry.int('silverLions', { min: 0 }) : 0;
return {
gjnCents: entry.money('gjn', { min: 0.01 }),
goldenEagles: entry.int('goldenEagles', { min: 0 }),
premiumDays: entry.int('premiumDays', { min: 0 }),
...(silverLions > 0 ? { silverLions } : {}),
};
}
function readMultiVehiclePack(entry: TuningReader): MultiVehiclePack {
const id = entry.string('id');
const naming = readMultiPackNaming(entry, id);
const vehicles = entry.stringList('vehicles');
if (vehicles.length === 0) throw new TuningError(`tuning file store.jsonc: multiVehiclePacks (${id}) must list at least one vehicle`);
const uniqueInPack = new Set(vehicles);
if (uniqueInPack.size !== vehicles.length) {
throw new TuningError(`tuning file store.jsonc: multiVehiclePacks (${id}) lists duplicate vehicles`);
}
return { id, naming, vehicles, ...packContent(entry) };
}
function readMultiPackNaming(entry: TuningReader, id: string): MultiPackNaming {
const hasGroup = entry.has('groupKey');
const hasStarter = entry.has('starter') && entry.bool('starter');
const hasTitle = entry.has('title');
const chosen = Number(hasGroup) + Number(hasStarter) + Number(hasTitle);
if (chosen !== 1) {
throw new TuningError(`tuning file store.jsonc: multiVehiclePacks (${id}) must set exactly one of groupKey, starter: true, or title`);
}
if (hasGroup) return { kind: 'group', groupKey: entry.string('groupKey') };
if (hasStarter) return { kind: 'starter' };
const titleObj = entry.object('title');
return { kind: 'custom', title: { en: titleObj.string('en'), zh: titleObj.string('zh') } };
}
function validateStoreUniqueness(
eagles: readonly GoldenEaglePack[],
silver: readonly SilverLionPack[],
premGold: readonly PremiumTier[],
premGjn: readonly PremiumTier[],
multiPacks: readonly MultiVehiclePack[],
): void {
const ids = new Set<string>();
for (const item of [...eagles, ...silver, ...premGold, ...premGjn, ...multiPacks]) {
if (ids.has(item.id)) throw new TuningError(`tuning file store.jsonc: duplicate product id "${item.id}"`);
ids.add(item.id);
}
// Vehicles in multiVehiclePacks automatically take precedence over byVehicle in StoreCatalogue,
// allowing <data>/tuning/store.jsonc overrides to bundle vehicles that were single packs by default.
const vehiclesInMulti = new Map<string, string>();
for (const pack of multiPacks) {
for (const unit of pack.vehicles) {
const earlier = vehiclesInMulti.get(unit);
if (earlier) throw new TuningError(`tuning file store.jsonc: vehicle "${unit}" appears in both "${earlier}" and "${pack.id}"`);
vehiclesInMulti.set(unit, pack.id);
}
}
}
function partialPackContent(entry: TuningReader): Partial<VehiclePackContent> {
return {
...(entry.has('gjn') ? { gjnCents: entry.money('gjn', { min: 0.01 }) } : {}),
...(entry.has('goldenEagles') ? { goldenEagles: entry.int('goldenEagles', { min: 0 }) } : {}),
...(entry.has('premiumDays') ? { premiumDays: entry.int('premiumDays', { min: 0 }) } : {}),
...(entry.has('silverLions') ? { silverLions: entry.int('silverLions', { min: 0 }) } : {}),
};
}
+258
View File
@@ -0,0 +1,258 @@
/**
* The JSON requests of the local store page (/store, shown in the game's built-in browser;
* implementation notes):
* GET /store/api/state?userId= balances, products and redeem code help for one account
* POST /store/api/buy { userId, productId }
* POST /store/api/cart { userId, productId, action }
* POST /store/api/checkout { userId, productIds, payMethod }
* POST /store/api/redeem { userId, code }
* Texts for the player come in both page languages ({ en, zh }); the page picks one.
*/
import type { AccountStore } from '../accounts/account-store.ts';
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { balanceOf } from '../profile/profile-currency.ts';
import { remainingPremiumDays } from '../profile/profile-entitlements.ts';
import { clearStoreCart, setStoreCart, storeCartIds } from '../profile/profile-store-cart.ts';
import { serverTimeNow } from '../profile/server-time.ts';
import type { ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
import { jsonResponse, parseJsonBody, requireWebActionAccount, selectWebViewAccount } from '../web-ui/web-helpers.ts';
import { describeRedeemCodes, gjnText, redeemStoreCode, type RedeemOutcome } from './redeem-codes.ts';
import type { RedeemTuning } from './redeem-tuning.ts';
import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts';
import { buyFreeStoreProduct, buyGjnProduct, buyStoreCart, canBuyGjnProduct, type GjnPurchaseOutcome, type StoreCheckoutOutcome } from './store-purchase.ts';
const NO_ACCOUNT: LocalizedText = { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' };
const NO_PRODUCT: LocalizedText = { zh: '没有找到这个商品。', en: 'Product not found.' };
const CART_CHANGED: LocalizedText = { zh: '购物车内容已变化,请核对后再结算。', en: 'Your cart has changed. Review it before checking out.' };
export class StoreWebApi {
readonly #accounts: AccountStore;
readonly #profiles: PlayerProfiles;
readonly #catalogue: StoreCatalogue;
readonly #redeemCodes: RedeemTuning;
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning) {
this.#accounts = accounts;
this.#profiles = profiles;
this.#catalogue = catalogue;
this.#redeemCodes = redeemCodes;
}
/** The answer for /store/api/<name>, or undefined when it is not an API request. */
handle(apiPath: string, request: ServiceRequest): ServiceResponse | undefined {
if (apiPath === '/api/state' && request.method === 'GET') return this.#state(request);
if (apiPath === '/api/buy' && request.method === 'POST') return this.#buy(request);
if (apiPath === '/api/cart' && request.method === 'POST') return this.#cart(request);
if (apiPath === '/api/checkout' && request.method === 'POST') return this.#checkout(request);
if (apiPath === '/api/redeem' && request.method === 'POST') return this.#redeem(request);
return undefined;
}
#state(request: ServiceRequest): ServiceResponse {
const account = selectWebViewAccount(this.#accounts, request.query.get('userId'));
const now = serverTimeNow();
const profile = account ? this.#profiles.profileOf(account.userId) : undefined;
const products = this.#catalogue.allProducts()
.filter((product) => product.gjnCostCents !== undefined)
.map((product) => webProduct(product, profile ? !canBuyGjnProduct(profile, product, now) : false));
return jsonResponse({
accounts: this.#accounts.all().map((entry) => ({ userId: entry.userId, login: entry.login, nick: entry.nick })),
activeUserId: account?.userId ?? '',
balance: profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjnCents: 0 },
premiumDays: profile ? remainingPremiumDays(profile, now) : 0,
products,
cartProductIds: profile ? storeCartIds(profile) : [],
redeemHelp: describeRedeemCodes(this.#redeemCodes),
}, `store web state (${account?.userId ?? 'no account'})`);
}
#buy(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const account = requireWebActionAccount(this.#accounts, body.userId);
const product = typeof body.productId === 'string' ? this.#catalogue.byId(body.productId) : undefined;
if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store web buy: unknown account');
if (!product || product.gjnCostCents === undefined) {
return jsonResponse({ ok: false, message: NO_PRODUCT }, 'store web buy: unknown product');
}
if (body.payMethod !== undefined && body.payMethod !== 'gjn' && body.payMethod !== 'free') {
return jsonResponse({ ok: false, message: { zh: '不支持这种支付方式。', en: 'Unsupported payment method.' } }, 'store web buy: bad payMethod');
}
const isFree = body.payMethod === 'free';
let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' };
let cartProductIds: readonly string[] = [];
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
outcome = isFree ? buyFreeStoreProduct(saved, product, now) : buyGjnProduct(saved, product, now);
cartProductIds = storeCartIds(saved);
if (!outcome.ok) return false;
if (cartProductIds.includes(product.id)) {
cartProductIds = cartProductIds.filter((id) => id !== product.id);
setStoreCart(saved, cartProductIds);
}
return true;
});
const modeTag = isFree ? 'free' : 'gjn';
return jsonResponse({ ok: outcome.ok, cartProductIds, message: purchaseMessage(outcome, product, isFree) }, `store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`);
}
#cart(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const account = requireWebActionAccount(this.#accounts, body.userId);
if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store cart: unknown account');
const { action, productId } = body;
if ((action !== 'add' && action !== 'remove') || typeof productId !== 'string' || !productId) {
return jsonResponse({ ok: false }, 'store cart: invalid action');
}
const product = this.#catalogue.byId(productId);
let cartProductIds: readonly string[] = [];
let message: LocalizedText | undefined;
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
const previous = storeCartIds(saved);
cartProductIds = previous;
if (action === 'add') {
if (!product || product.gjnCostCents === undefined) {
message = NO_PRODUCT;
return false;
}
if (!canBuyGjnProduct(saved, product, now)) {
message = alreadyBoughtMessage(product);
return false;
}
if (previous.includes(productId)) return false;
cartProductIds = [...previous, productId];
} else {
if (!previous.includes(productId)) return false;
cartProductIds = previous.filter((id) => id !== productId);
}
setStoreCart(saved, cartProductIds);
return true;
});
return jsonResponse({ ok: !message, cartProductIds, message }, `store cart ${action} ${productId}`);
}
#checkout(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const account = requireWebActionAccount(this.#accounts, body.userId);
if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store checkout: unknown account');
const { productIds, payMethod } = body;
if (!Array.isArray(productIds) || productIds.length === 0 || (payMethod !== 'gjn' && payMethod !== 'free')) {
return jsonResponse({ ok: false, message: CART_CHANGED }, 'store checkout: invalid order');
}
const now = serverTimeNow();
let cartProductIds: readonly string[] = [];
let message = CART_CHANGED;
const saved = this.#profiles.updateWhen(account.userId, (profile) => {
cartProductIds = storeCartIds(profile);
if (cartProductIds.length !== productIds.length || cartProductIds.some((id, i) => id !== productIds[i])) return false;
const products = cartProductIds.map((id) => this.#catalogue.byId(id));
if (!products.every((product): product is StoreProduct => product !== undefined)) {
message = NO_PRODUCT;
return false;
}
const outcome = buyStoreCart(profile, products, payMethod, now);
message = checkoutMessage(outcome, products, payMethod);
if (!outcome.ok) return false;
clearStoreCart(profile);
cartProductIds = [];
return true;
});
return jsonResponse({ ok: !!saved, cartProductIds, message }, `store checkout (${payMethod}): ${saved ? 'OK' : 'refused'}`);
}
#redeem(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const account = requireWebActionAccount(this.#accounts, body.userId);
if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store web redeem: unknown account');
const code = typeof body.code === 'string' ? body.code : '';
let outcome: RedeemOutcome | undefined;
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
outcome = redeemStoreCode(saved, code, now, this.#redeemCodes);
return outcome.ok;
});
return jsonResponse({ ok: outcome?.ok ?? false, message: outcome?.message }, `store web redeem ${code.trim() || '(empty)'}`);
}
}
function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct, isFree: boolean): LocalizedText {
const cost = gjnText(product.gjnCostCents ?? 0);
if (outcome.ok) {
return isFree
? {
zh: `老福爷付过了!已直接获得「${product.title.zh}」。关闭商店窗口后机库会自动刷新。`,
en: `Paid by 老福爷! Claimed "${product.title.en}". Close the store window to refresh the hangar.`,
}
: {
zh: `已购买「${product.title.zh}」,花费 ${cost} GJN。关闭商店窗口后机库会自动刷新。`,
en: `Bought "${product.title.en}" for ${cost} GJN. Close the store window to refresh the hangar.`,
};
}
if (outcome.reason === 'NOT_ENOUGH_GJN') {
return { zh: `GJN 不够:需要 ${cost} GJN。可直接点「老福爷付过了」,或在"兑换码"页用 GJN 充值码补充。`, en: `Not enough GJN: ${cost} GJN needed. Use "老福爷付过了" or a GJN code on the Redeem tab.` };
}
if (outcome.reason === 'ALREADY_BOUGHT') return alreadyBoughtMessage(product);
return { zh: '这个商品现在买不了。', en: 'This product cannot be bought right now.' };
}
function alreadyBoughtMessage(product: StoreProduct): LocalizedText {
return {
zh: `你已经拥有「${product.title.zh}」中的载具。`,
en: `You already own the vehicles in "${product.title.en}".`,
};
}
function checkoutMessage(
outcome: StoreCheckoutOutcome,
products: readonly StoreProduct[],
payMethod: 'gjn' | 'free',
): LocalizedText {
if (outcome.ok) {
const count = products.length;
const cost = gjnText(outcome.costCents);
return payMethod === 'free'
? { zh: `老福爷付过了!已领取 ${count} 件商品。关闭商城窗口后机库会自动刷新。`,
en: `Paid by 老福爷! Claimed ${count} items. Close the store to refresh the hangar.` }
: { zh: `已购买 ${count} 件商品,花费 ${cost} GJN。关闭商城窗口后机库会自动刷新。`,
en: `Bought ${count} items for ${cost} GJN. Close the store to refresh the hangar.` };
}
if (outcome.reason === 'NOT_ENOUGH_GJN') {
const cost = gjnText(outcome.costCents);
return { zh: `购物车共需 ${cost} GJN,当前余额不足。`, en: `Your cart costs ${cost} GJN. Your balance is too low.` };
}
const product = products.find((item) => item.id === outcome.productId);
return outcome.reason === 'ALREADY_BOUGHT' && product ? alreadyBoughtMessage(product) : NO_PRODUCT;
}
function webProduct(product: StoreProduct, owned: boolean): Record<string, unknown> {
const vehicles = product.vehicles;
const firstVehicle = vehicles?.[0];
const ranks = vehicles ? [...new Set(vehicles.map((vehicle) => vehicle.rank))].sort((a, b) => a - b) : undefined;
return {
id: product.id,
...(product.guid ? { guid: product.guid } : {}),
...(product.artworkGroup ? { artworkGroup: product.artworkGroup } : {}),
kind: product.kind,
title: product.title,
gjnCostCents: product.gjnCostCents,
...(product.goldIncome ? { goldIncome: product.goldIncome } : {}),
...(product.silverIncome ? { silverIncome: product.silverIncome } : {}),
...(product.premiumDays ? { premiumDays: product.premiumDays } : {}),
...(firstVehicle && vehicles ? {
unitName: firstVehicle.name,
country: firstVehicle.country,
rank: ranks![ranks!.length - 1]!,
ranks,
vehicles: vehicles.map((vehicle, index) => ({
unitName: vehicle.name,
country: vehicle.country,
rank: vehicle.rank,
title: product.vehicleTitles?.[index] ?? { en: vehicle.name, zh: vehicle.name },
})),
} : {}),
owned,
};
}
+239
View File
@@ -0,0 +1,239 @@
// The in-game browser can open the storefront or deep-link to a pack by its GUID.
'use strict';
const T = {
zh: {
store: '商城', toMarket: '交易所', account: '本地账号', eagles: '金鹰', lions: '银狮', premium: '高级账户',
premiumOff: '未开通', premiumLeft: '剩余 {days} 天',
tabPacks: '高级载具', tabEagles: '金鹰', tabPremium: '高级账户', tabRedeem: '兑换码',
search: '搜索礼包或载具', allCountries: '所有国家', allRanks: '所有等级', rank: '{rank} 级',
sort: '商品排序', sortBest: '最畅销', sortNewest: '最新上架', sortPriceAsc: '价格从低到高', sortPriceDesc: '价格从高到低',
containsEagles: '{n} 金鹰', containsSilver: '{n} 银狮', containsPremium: '{days} 天高级账户',
buy: '购买', freeBuy: '老福爷付过了', owned: '已拥有', pickAccount: '请先选择账号',
redeem: '兑换', codePlaceholder: '输入兑换码', empty: '没有符合条件的商品',
featured: '推荐礼包', bestSeller: '畅销', viewPack: '查看礼包', related: '更多推荐', packPrice: '礼包价格',
includes: '礼包内容', back: '返回目录', bonusTitle: '高级载具权益',
bonusText: '驾驶高级载具可在战斗中获得额外的研发点和银狮。',
footer: '购买后关闭商城窗口,机库会自动刷新。',
gallery: '礼包媒体', cover: '封面', screenshot: '截图 {index}', screenshotLoading: '正在加载官方截图…', screenshotUnavailable: '官方截图暂不可用,当前显示游戏载具图。', previousMedia: '上一项', nextMedia: '下一项',
video: '演示视频', videoNumber: '演示视频 {index}', playVideo: '播放演示',
videoLoading: '正在加载演示视频…', videoUnavailable: '暂时无法播放官方视频,可以继续浏览其他素材。',
cart: '购物车', addCart: '加入购物车', inCart: '已在购物车', confirmPurchase: '确认购买',
cartEmpty: '购物车里还没有商品。', remove: '移除', removeItem: '移除 {name}', unavailable: '商品已下架',
total: '合计', balance: 'GJN 余额', payGjn: '用 GJN 结算', close: '关闭', keepShopping: '继续逛商城',
cartBlocked: '移除已拥有或已下架的商品后即可结算。', lowBalance: 'GJN 余额不足。',
buyFailed: '暂时无法确认结果,商城会重新读取账号状态。', loadFailed: '商城加载失败,请重新打开商城。',
},
en: {
store: 'Store', toMarket: 'Market', account: 'Local account', eagles: 'Golden Eagles', lions: 'Silver Lions', premium: 'Premium',
premiumOff: 'Inactive', premiumLeft: '{days} days left',
tabPacks: 'Premium vehicles', tabEagles: 'Golden Eagles', tabPremium: 'Premium account', tabRedeem: 'Redeem code',
search: 'Search packs or vehicles', allCountries: 'All nations', allRanks: 'All ranks', rank: 'Rank {rank}',
sort: 'Sort products', sortBest: 'Top sellers', sortNewest: 'Newest', sortPriceAsc: 'Price: low to high', sortPriceDesc: 'Price: high to low',
containsEagles: '{n} Golden Eagles', containsSilver: '{n} Silver Lions', containsPremium: '{days} days of Premium Account',
buy: 'Buy', freeBuy: '老福爷付过了', owned: 'Owned', pickAccount: 'Pick an account first',
redeem: 'Redeem', codePlaceholder: 'Enter a code', empty: 'Nothing matches the filters',
featured: 'Featured packs', bestSeller: 'Top seller', viewPack: 'View pack', related: 'Explore other packs', packPrice: 'Pack price',
includes: 'Pack contents', back: 'Back to catalog', bonusTitle: 'Premium bonuses',
bonusText: 'Premium vehicles earn extra research points and Silver Lions in battle.',
footer: 'Close the store window after buying to refresh the hangar.',
gallery: 'Pack media', cover: 'Cover', screenshot: 'Screenshot {index}', screenshotLoading: 'Loading official screenshot…', screenshotUnavailable: 'The official screenshot is unavailable. Showing game artwork.', previousMedia: 'Previous item', nextMedia: 'Next item',
video: 'Demo video', videoNumber: 'Demo video {index}', playVideo: 'Play demo',
videoLoading: 'Loading demo video…', videoUnavailable: 'The official video is unavailable. You can still browse the other media.',
cart: 'Cart', addCart: 'Add to cart', inCart: 'In cart', confirmPurchase: 'Confirm purchase',
cartEmpty: 'Your cart is empty.', remove: 'Remove', removeItem: 'Remove {name}', unavailable: 'No longer available',
total: 'Total', balance: 'GJN balance', payGjn: 'Pay with GJN', close: 'Close', keepShopping: 'Continue shopping',
cartBlocked: 'Remove owned or unavailable products to check out.', lowBalance: 'Your GJN balance is too low.',
buyFailed: 'The result could not be confirmed. The store will reload your account.', loadFailed: 'The store could not load. Reopen the store to retry.',
},
};
const TAB_LABEL = { 'vehicle-pack': 'tabPacks', eagles: 'tabEagles', 'premium-gjn': 'tabPremium' };
const ROMAN = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'];
const t = (key, params) => WtoUi.tr(T, key, params);
const $ = (id) => document.getElementById(id);
let initialGuid = (WtoUi.query.get('item') || '').toUpperCase();
let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0 }, products: [], cartProductIds: [], redeemHelp: [] };
let currentTab = 'vehicle-pack';
let detailId = '';
let catalogScroll = 0;
let loadVersion = 0;
let loading = true;
const checkout = createStoreCheckout(loadState);
function applyStaticTexts() {
for (const el of document.querySelectorAll('[data-t]')) el.textContent = t(el.dataset.t);
for (const el of document.querySelectorAll('[data-label]')) el.setAttribute('aria-label', t(el.dataset.label));
$('searchInput').placeholder = t('search');
$('codeInput').placeholder = t('codePlaceholder');
$('marketLink').href = WtoUi.pageLink('/trade.gaijin.net/');
}
function setLoading(value) {
loading = value;
$('accountSelect').disabled = value || !state.accounts.length;
$('redeemBtn').disabled = value || !state.activeUserId;
checkout.setAccountLoading(value);
}
async function loadState(userId) {
const version = ++loadVersion;
setLoading(true);
try {
const next = await WtoUi.getJson('/store/api/state' + (userId ? '?userId=' + encodeURIComponent(userId) : ''));
if (version !== loadVersion) return;
if (!Array.isArray(next?.accounts) || !Array.isArray(next.products)) throw new Error('Invalid store state');
if (userId && !next.activeUserId) {
WtoUi.clearSavedAccount();
return await loadState('');
}
state = next;
WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.activeUserId);
$('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents);
$('goldVal').textContent = WtoUi.num(state.balance.goldenEagles);
$('silverVal').textContent = WtoUi.num(state.balance.silverLions);
$('premVal').textContent = state.premiumDays > 0 ? t('premiumLeft', { days: state.premiumDays }) : t('premiumOff');
if (initialGuid) {
const wanted = state.products.find((p) => (p.guid || '').toUpperCase() === initialGuid);
if (wanted) { detailId = wanted.id; currentTab = wanted.kind; }
initialGuid = '';
}
checkout.setState(state);
renderFilters();
render();
} catch (error) {
if (version !== loadVersion) return;
$('accountSelect').value = state.activeUserId;
WtoUi.showNotice($('notice'), t('loadFailed'), false);
} finally {
if (version === loadVersion) setLoading(false);
}
}
function fillSelect(select, firstText, values, textOf) {
const previous = select.value;
select.replaceChildren(new Option(firstText, ''));
for (const value of values) select.appendChild(new Option(textOf(value), String(value), false, String(value) === previous));
}
function renderFilters() {
const packs = state.products.filter((p) => p.kind === 'vehicle-pack');
const countries = packs.flatMap((p) => p.vehicles.map((vehicle) => vehicle.country)).filter(Boolean);
const ranks = [...new Set(packs.flatMap((p) => p.ranks || []))].sort((a, b) => a - b);
fillSelect($('countryFilter'), t('allCountries'), [...new Set(countries)], WtoUi.label);
fillSelect($('rankFilter'), t('allRanks'), ranks, rankLabel);
}
function matchesPack(product) {
const query = $('searchInput').value.trim().toLowerCase();
const country = $('countryFilter').value;
const rank = $('rankFilter').value;
if (country && !product.vehicles.some((vehicle) => vehicle.country === country)) return false;
if (rank && !product.ranks.map(String).includes(rank)) return false;
if (!query) return true;
const terms = [product.title.zh, product.title.en];
for (const vehicle of product.vehicles) terms.push(vehicle.unitName, vehicle.title.zh, vehicle.title.en);
return terms.some((term) => (term || '').toLowerCase().includes(query));
}
function render() {
stopStoreGallery($('detail'));
for (const tab of $('tabs').querySelectorAll('[data-tab]')) tab.setAttribute('aria-pressed', String(tab.dataset.tab === currentTab));
const product = state.products.find((item) => item.id === detailId);
const redeeming = currentTab === 'redeem';
$('catalog').hidden = redeeming || !!product;
$('detail').hidden = !product;
$('redeemPanel').hidden = !redeeming;
if (!product) $('detail').replaceChildren();
if (redeeming) return renderRedeemHelp();
if (product) return renderPackDetail($('detail'), product, checkout, state.products, openProduct, backToCatalog);
renderCatalog();
}
function renderCatalog() {
const isPacks = currentTab === 'vehicle-pack';
$('catalogTitle').textContent = t(TAB_LABEL[currentTab]);
$('packFilters').hidden = !isPacks;
const sort = $('sortSelect').value;
const filtered = $('countryFilter').value || $('rankFilter').value || $('searchInput').value.trim();
const items = state.products.filter((p) => p.kind === currentTab && (!isPacks || matchesPack(p)));
if (isPacks) sortPacks(items, sort);
const cards = items.map((item) => productCard(item, checkout, openProduct));
if (isPacks && !filtered && sort === 'best' && items.length) {
const featured = items.find((item) => item.id === 'wto_pack_f-4s') || items[0];
cards.unshift(featuredBanner(featured, openProduct));
}
if (!cards.length) cards.push(makeElement('p', 'empty', t('empty')));
$('grid').replaceChildren(...cards);
}
function sortPacks(items, mode) {
const ids = WtoUi.storeOrder(mode === 'newest' ? 'newest' : 'best');
const positions = new Map(ids.map((id, index) => [id, index]));
items.sort((a, b) => (positions.get(a.id) ?? ids.length) - (positions.get(b.id) ?? ids.length));
if (mode === 'priceAsc') items.sort((a, b) => a.gjnCostCents - b.gjnCostCents);
if (mode === 'priceDesc') items.sort((a, b) => b.gjnCostCents - a.gjnCostCents);
}
function openProduct(product) {
if (!detailId) catalogScroll = window.scrollY;
detailId = product.id;
currentTab = product.kind;
render();
window.scrollTo(0, 0);
$('detail').querySelector('h1').focus({ preventScroll: true });
}
function backToCatalog() {
detailId = '';
render();
window.scrollTo(0, catalogScroll);
$('catalogTitle').focus({ preventScroll: true });
}
function selectTab(tab) {
currentTab = tab;
detailId = '';
render();
window.scrollTo(0, 0);
}
function renderRedeemHelp() {
$('redeemHelp').replaceChildren(...state.redeemHelp.map((line) => makeElement('li', '', WtoUi.text(line))));
}
async function redeem() {
const userId = state.activeUserId;
if (!userId || loading) return;
$('redeemBtn').disabled = true;
try {
const result = await WtoUi.postJson('/store/api/redeem', { userId, code: $('codeInput').value });
if ($('accountSelect').value !== userId) return;
WtoUi.showNotice($('notice'), WtoUi.text(result.message), result.ok);
if (result.ok) $('codeInput').value = '';
} catch (error) {
if ($('accountSelect').value !== userId) return;
WtoUi.showNotice($('notice'), t('buyFailed'), false);
}
if ($('accountSelect').value === userId) await loadState(userId);
}
$('accountSelect').onchange = (event) => {
$('notice').className = 'notice';
WtoUi.saveAccount(event.target.value);
void loadState(event.target.value);
};
$('storeHome').onclick = () => selectTab('vehicle-pack');
$('searchInput').oninput = renderCatalog;
for (const id of ['countryFilter', 'rankFilter', 'sortSelect']) $(id).onchange = renderCatalog;
$('redeemBtn').onclick = redeem;
$('tabs').onclick = (event) => {
const tab = event.target.closest('[data-tab]');
if (tab) selectTab(tab.dataset.tab);
};
window.addEventListener('pagehide', () => stopStoreGallery($('detail')));
applyStaticTexts();
render();
Promise.allSettled([WtoUi.loadLabels(), WtoUi.loadImageSources(true)]).then(() => loadState(WtoUi.savedAccount()));
+64
View File
@@ -0,0 +1,64 @@
.checkout {
position: fixed;
inset: 0 0 0 auto;
width: min(100%, 480px);
max-width: 100%;
height: 100%;
max-height: 100%;
margin: 0;
padding: 0;
border: 0;
border-left: 1px solid var(--line);
background: var(--surface);
color: var(--text);
box-shadow: -16px 0 56px #0008;
}
.checkout[open] { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; }
.checkout::backdrop { background: #060c14b3; }
.checkout-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 18px 20px; border-bottom: 1px solid var(--line); }
.checkout-head h2 { margin: 0; font-size: 24px; }
.checkout-close {
width: 36px;
height: 36px;
padding: 0;
border: 1px solid var(--line);
border-radius: 6px;
background: #1a2530;
font-size: 24px;
line-height: 1;
}
.checkout-close:hover:not(:disabled) { background: var(--surface-raised); }
.checkout-body { overflow: auto; }
.checkout-empty { margin: 18px 20px; color: var(--muted); }
.checkout-list { display: grid; gap: 1px; margin: 0; padding: 0; list-style: none; background: var(--line); }
.checkout-item {
display: grid;
grid-template-columns: min(85px, 20%) minmax(0, 1fr) auto;
align-items: center;
gap: 12px;
padding: 14px 20px;
background: var(--surface);
}
.checkout-art {
display: grid;
place-items: center;
aspect-ratio: 2 / 1;
overflow: hidden;
border-radius: 4px;
background: #304553;
}
.checkout-art img { width: 100%; height: 100%; object-fit: cover; }
.checkout-item-copy { display: grid; gap: 3px; overflow-wrap: anywhere; }
.checkout-item-status { color: #ffc5b5; font-size: 13px; }
.checkout-item-actions { display: grid; gap: 4px; justify-items: end; color: var(--gold); white-space: nowrap; }
.checkout-remove { padding: 1px 0; border: 0; background: transparent; color: var(--muted); font-size: 13px; }
.checkout-remove:hover:not(:disabled) { color: var(--text); text-decoration: underline; }
.checkout-footer { padding: 16px 20px 20px; border-top: 1px solid var(--line); background: #16242d; }
.checkout-footer .notice { margin: 0 0 12px; }
.checkout-total, .checkout-balance { display: flex; justify-content: space-between; align-items: baseline; flex-wrap: wrap; gap: 5px 10px; }
.checkout-total strong { color: var(--gold); font-size: 25px; }
.checkout-balance { margin: 4px 0 13px; color: var(--muted); font-size: 13px; }
.checkout-hint { margin: 6px 0 12px; color: #ffd5b3; font-size: 13px; }
.checkout-footer button { display: block; width: 100%; }
.checkout-footer #payFree { margin-top: 8px; }
+184
View File
@@ -0,0 +1,184 @@
// The server tracks the cart per account and settles it with a single request.
'use strict';
function createStoreCheckout(refreshAccount) {
const dialog = $('checkout');
const cartButton = $('cartBtn');
let active;
let products = new Map();
let accountLoading = true;
let processing = false;
let directProductId = '';
let complete = false;
let opener;
const cartIds = () => active?.cartProductIds || [];
const locked = () => processing || accountLoading || !active?.activeUserId;
const showsAccount = (userId) => active?.activeUserId === userId && $('accountSelect').value === userId;
function syncProductButton(button, product) {
const adding = button.dataset.cartAction === 'add';
const inCart = adding && cartIds().includes(product.id);
const buyLabel = product.owned ? 'owned' : (active?.activeUserId ? 'buy' : 'pickAccount');
button.disabled = locked() || (product.owned && !inCart);
button.textContent = t(adding ? (inCart ? 'inCart' : 'addCart') : buyLabel);
button.classList.toggle('in-cart', inCart);
button.setAttribute('aria-haspopup', !adding || inCart ? 'dialog' : 'false');
}
function syncControls() {
cartButton.disabled = locked();
$('cartCount').textContent = WtoUi.num(cartIds().length);
for (const button of document.querySelectorAll('[data-cart-action]')) {
const product = products.get(button.dataset.product);
if (product) syncProductButton(button, product);
}
if (dialog.open) renderCheckout();
}
function setState(next) {
active = next;
products = new Map(next.products.map((product) => [product.id, product]));
syncControls();
}
function setAccountLoading(value) {
accountLoading = value;
syncControls();
}
function setProcessing(value) {
processing = value;
syncControls();
}
function productButtons(product, layout) {
const buy = storeButton(layout === 'detail' ? 'btn-main' : 'card-buy');
const add = storeButton(layout === 'detail' ? 'btn-outline' : 'card-add');
buy.dataset.cartAction = 'buy';
add.dataset.cartAction = 'add';
for (const button of [buy, add]) {
button.dataset.product = product.id;
syncProductButton(button, product);
}
buy.onclick = () => open(product.id);
add.onclick = () => {
if (cartIds().includes(product.id)) open();
else void changeCart(product.id, 'add');
};
return [buy, add];
}
function productRow(id) {
const product = products.get(id);
const row = makeElement('li', 'checkout-item');
const title = product ? WtoUi.text(product.title) : id;
const info = makeElement('div', 'checkout-item-copy');
info.append(makeElement('strong', '', title));
if (!product || product.owned) {
info.append(makeElement('span', 'checkout-item-status', t(product ? 'owned' : 'unavailable')));
}
const amounts = makeElement('div', 'checkout-item-actions');
if (product) amounts.append(makeElement('strong', '', storePrice(product.gjnCostCents)));
if (!directProductId) {
const remove = storeButton('checkout-remove', t('remove'));
remove.disabled = locked();
remove.setAttribute('aria-label', t('removeItem', { name: title }));
remove.onclick = () => changeCart(id, 'remove');
amounts.append(remove);
}
const art = makeElement('div', 'checkout-art');
if (product) art.append(productImage(product));
row.append(art, info, amounts);
return row;
}
function renderCheckout() {
const ids = complete ? [] : (directProductId ? [directProductId] : cartIds());
$('checkoutList').replaceChildren(...ids.map(productRow));
$('checkoutTitle').textContent = t(directProductId ? 'confirmPurchase' : 'cart');
$('checkoutClose').disabled = processing;
$('checkoutEmpty').hidden = complete || ids.length > 0;
$('checkoutDone').hidden = !complete;
$('checkoutDone').disabled = processing;
$('checkoutTotals').hidden = ids.length === 0;
if (!ids.length) return;
const items = ids.map((id) => products.get(id));
const total = items.reduce((sum, product) => sum + (product?.gjnCostCents || 0), 0);
const balance = active.balance.gjnCents;
const unavailable = items.some((product) => !product || product.owned);
const hint = unavailable ? t(directProductId ? 'owned' : 'cartBlocked') : (balance < total ? t('lowBalance') : '');
$('checkoutTotal').textContent = storePrice(total);
$('checkoutBalance').textContent = storePrice(balance);
$('checkoutHint').textContent = hint;
$('checkoutHint').hidden = !hint;
$('payGjn').disabled = locked() || unavailable || balance < total;
$('payFree').disabled = locked() || unavailable;
}
function open(productId = '') {
if (locked()) return;
directProductId = productId;
complete = false;
$('checkoutNotice').className = 'notice';
opener = document.activeElement;
renderCheckout();
dialog.showModal();
}
function applyCart(result) {
if (Array.isArray(result.cartProductIds)) active.cartProductIds = result.cartProductIds;
}
async function changeCart(productId, action) {
if (locked()) return;
const userId = active.activeUserId;
const notice = dialog.open ? $('checkoutNotice') : $('notice');
setProcessing(true);
try {
const result = await WtoUi.postJson('/store/api/cart', { userId, productId, action });
if (!showsAccount(userId)) return;
applyCart(result);
if (result.ok) notice.className = 'notice';
else WtoUi.showNotice(notice, WtoUi.text(result.message) || t('buyFailed'), false);
} catch (error) {
if (!showsAccount(userId)) return;
WtoUi.showNotice(notice, t('buyFailed'), false);
await refreshAccount(userId);
} finally {
setProcessing(false);
}
}
async function pay(payMethod) {
if (locked()) return;
const userId = active.activeUserId;
const body = directProductId ? { productId: directProductId } : { productIds: cartIds().slice() };
const route = directProductId ? 'buy' : 'checkout';
const notice = $('checkoutNotice');
setProcessing(true);
try {
const result = await WtoUi.postJson('/store/api/' + route, { userId, payMethod, ...body });
if (!showsAccount(userId)) return;
applyCart(result);
complete = result.ok;
WtoUi.showNotice(notice, WtoUi.text(result.message) || t('buyFailed'), result.ok);
} catch (error) {
WtoUi.showNotice(notice, t('buyFailed'), false);
} finally {
if (showsAccount(userId)) await refreshAccount(userId);
setProcessing(false);
if (complete) $('checkoutDone').focus();
}
}
cartButton.onclick = () => open();
$('checkoutClose').onclick = $('checkoutDone').onclick = () => dialog.close();
$('payGjn').onclick = () => pay('gjn');
$('payFree').onclick = () => pay('free');
dialog.oncancel = (event) => { if (processing) event.preventDefault(); };
dialog.onclose = () => { if (opener?.isConnected && !opener.disabled) opener.focus(); else cartButton.focus(); };
return { productButtons, setState, setAccountLoading };
}
+230
View File
@@ -0,0 +1,230 @@
// Images and demo clips for pack details.
'use strict';
const galleryPlayers = new WeakMap();
const CLIP_TIMEOUT_MS = 23_000;
function stopStoreGallery(root) {
const stage = root.querySelector('.media-stage');
galleryPlayers.get(stage)?.();
}
function galleryItems(product) {
const { screenshots, videos } = WtoUi.storeMedia(product.id);
const cover = () => productImage(product);
const demoStill = screenshots[0] ? () => productScreenshot(product, screenshots[0]) : cover;
const entries = videos.map((sources, index) => ({
label: videos.length === 1 ? t('video') : t('videoNumber', { index: index + 1 }),
image: demoStill,
sources,
}));
screenshots.forEach((url, index) => {
entries.push({ label: t('screenshot', { index: index + 1 }), screenshot: url });
});
entries.push({ label: t('cover'), image: cover });
if (product.vehicles && (videos.length || screenshots.length || product.vehicles.length > 1)) {
for (const vehicle of product.vehicles) {
entries.push({ label: WtoUi.text(vehicle.title), image: () => WtoUi.vehicleImg(vehicle.unitName, '') });
}
}
return entries;
}
function createClipVideoElement(poster, autoplay) {
const video = document.createElement('video');
video.controls = true;
video.playsInline = true;
if (autoplay) {
video.autoplay = true;
video.defaultMuted = true;
video.muted = true;
video.loop = true;
}
if (poster) video.poster = poster;
return video;
}
function playStoreClip(stage, sources, poster, autoplay, onReady, onUnavailable) {
galleryPlayers.get(stage)?.();
const video = createClipVideoElement(poster, autoplay);
const playable = sources.filter((url) => video.canPlayType(/\.webm(?:$|\?)/i.test(url) ? 'video/webm' : 'video/mp4'));
let nextSource = 0;
let timer;
function dispose() {
clearTimeout(timer);
galleryPlayers.delete(stage);
video.onerror = video.oncanplay = null;
video.pause();
video.removeAttribute('src');
video.load();
video.remove();
}
function attempt() {
clearTimeout(timer);
const url = playable[nextSource++];
if (!url) {
dispose();
onUnavailable();
return;
}
video.src = url;
timer = setTimeout(attempt, CLIP_TIMEOUT_MS);
void video.play().catch(() => {});
}
video.onerror = attempt;
video.oncanplay = () => { clearTimeout(timer); onReady(); };
stage.replaceChildren(video);
galleryPlayers.set(stage, dispose);
attempt();
}
function appendScreenshot(container, item, loaded, eager = false) {
const candidates = storeImageCandidates(item.screenshot);
const image = makeElement('img', 'gallery-screenshot');
image.alt = eager ? item.label : '';
image.loading = eager ? 'eager' : 'lazy';
image.crossOrigin = 'anonymous';
image.referrerPolicy = 'no-referrer';
let index = 0;
function tryNext() {
const nextUrl = candidates[index++];
if (!nextUrl) {
image.onload = image.onerror = null;
image.remove();
loaded(false);
return;
}
image.src = nextUrl;
}
image.onload = () => {
image.onload = image.onerror = null;
image.classList.add('ready');
loaded(true);
};
image.onerror = tryNext;
container.append(image);
tryNext();
return image;
}
function renderStageScreenshot(stage, status, product, item) {
const gameArt = WtoUi.tieredImg([], productArtwork(product), '');
gameArt.loading = 'eager';
stage.append(gameArt);
status.textContent = t('screenshotLoading');
status.hidden = false;
const image = appendScreenshot(stage, item, (ok) => {
if (image.parentNode !== stage) return;
if (ok) {
gameArt.remove();
status.hidden = true;
} else {
status.textContent = t('screenshotUnavailable');
}
}, true);
}
function renderStageMedia(stage, status, product, item, showPlay, onPlay) {
stage.replaceChildren();
if (item.screenshot) {
renderStageScreenshot(stage, status, product, item);
return;
}
const image = item.image();
image.loading = 'eager';
image.alt = item.label;
stage.append(image);
if (!showPlay) return;
const play = storeButton('media-play', '▶ ' + t('playVideo'));
play.onclick = () => onPlay(item, false);
stage.append(play);
}
function startStageVideo(stage, status, product, item, autoplay) {
const image = stage.querySelector('img');
const poster = image?.currentSrc || image?.getAttribute('src');
status.textContent = t('videoLoading');
status.hidden = false;
playStoreClip(stage, item.sources, poster, autoplay, () => { status.hidden = true; }, () => {
renderStageMedia(stage, status, product, item, true, (target, auto) => startStageVideo(stage, status, product, target, auto));
status.textContent = t('videoUnavailable');
status.hidden = false;
});
}
function createGalleryThumb(item, index, onSelect) {
const button = storeButton('media-thumb');
button.setAttribute('aria-label', item.label);
button.setAttribute('aria-pressed', 'false');
button.title = item.label;
if (item.screenshot) {
const label = makeElement('span', 'media-placeholder', item.label);
button.append(label);
appendScreenshot(button, item, (ok) => { if (ok) label.remove(); });
} else {
button.append(item.image());
}
if (item.sources) button.append(makeElement('span', 'thumb-play', '▶'));
button.onclick = () => onSelect(index, true);
return button;
}
function bindGalleryControls(nav, rail, prev, next, buttons, itemsLength, getActive, onSelect) {
prev.setAttribute('aria-label', t('previousMedia'));
next.setAttribute('aria-label', t('nextMedia'));
prev.onclick = () => onSelect(getActive() - 1);
next.onclick = () => onSelect(getActive() + 1);
rail.append(...buttons);
rail.onkeydown = (event) => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
event.preventDefault();
onSelect(getActive() + (event.key === 'ArrowRight' ? 1 : -1));
buttons[getActive()].focus({ preventScroll: true });
};
nav.hidden = itemsLength === 1;
}
function mountStoreGallery(root, product, autoplay) {
const items = galleryItems(product);
root.innerHTML = '<div class="media-stage"></div><div class="media-navigation"><button type="button">‹</button>'
+ '<div class="media-thumbs"></div><button type="button">›</button></div>'
+ '<div class="media-caption"><span class="media-label"></span><span class="media-position"></span></div>'
+ '<p class="media-status" role="status" hidden></p>';
root.setAttribute('aria-label', t('gallery'));
const stage = root.querySelector('.media-stage');
const nav = root.querySelector('.media-navigation');
const rail = root.querySelector('.media-thumbs');
const [prev, next] = nav.querySelectorAll('button');
const caption = root.querySelector('.media-caption');
const status = root.querySelector('.media-status');
let active = 0;
const playItem = (item, auto = false) => startStageVideo(stage, status, product, item, auto);
function select(index, play = false, scroll = true) {
if (index < 0 || index >= items.length) return;
stopStoreGallery(root);
buttons[active].setAttribute('aria-pressed', 'false');
active = index;
const item = items[index];
buttons[index].setAttribute('aria-pressed', 'true');
if (scroll) buttons[index].scrollIntoView({ block: 'nearest', inline: 'nearest' });
prev.disabled = index === 0;
next.disabled = index === items.length - 1;
caption.querySelector('.media-label').textContent = item.label;
caption.querySelector('.media-position').textContent = (index + 1) + ' / ' + items.length;
status.hidden = true;
renderStageMedia(stage, status, product, item, !!item.sources, playItem);
if (play && item.sources) playItem(item, false);
}
const buttons = items.map((item, index) => createGalleryThumb(item, index, select));
bindGalleryControls(nav, rail, prev, next, buttons, items.length, () => active, select);
caption.hidden = items.length === 1;
select(0, false, false);
if (autoplay && items[0].sources) playItem(items[0], true);
}
+103
View File
@@ -0,0 +1,103 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="referrer" content="no-referrer" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>WTOffline Store</title>
<link rel="stylesheet" href="/store/styles.css" />
<link rel="stylesheet" href="/store/product.css" />
<link rel="stylesheet" href="/store/checkout.css" />
</head>
<body>
<div class="page">
<header class="store-header">
<button type="button" class="store-brand" id="storeHome">
<span class="store-mark" aria-hidden="true">WT</span>
<span>WTOffline <span data-t="store"></span></span>
</button>
<div class="account-strip">
<span class="balance">GJN <b id="gjnVal">0</b></span>
<span class="balance"><span data-t="eagles"></span> <b id="goldVal">0</b></span>
<span class="balance"><span data-t="lions"></span> <b id="silverVal">0</b></span>
<span class="balance"><span data-t="premium"></span> <b id="premVal"></b></span>
<select id="accountSelect" data-label="account" disabled></select>
</div>
</header>
<nav class="store-nav" data-label="store">
<div class="tabs" id="tabs">
<button type="button" data-tab="vehicle-pack" data-t="tabPacks"></button>
<button type="button" data-tab="eagles" data-t="tabEagles"></button>
<button type="button" data-tab="premium-gjn" data-t="tabPremium"></button>
<button type="button" data-tab="redeem" data-t="tabRedeem"></button>
</div>
<div class="store-links">
<a id="marketLink" data-t="toMarket"></a>
<button type="button" class="cart-link" id="cartBtn" aria-haspopup="dialog" disabled>
<span class="cart-icon" aria-hidden="true"></span>
<span data-t="cart"></span>
<b id="cartCount" aria-live="polite">0</b>
</button>
</div>
</nav>
<div class="notice" id="notice" role="status"></div>
<main>
<section id="catalog" aria-labelledby="catalogTitle">
<div class="catalog-head">
<h1 id="catalogTitle" tabindex="-1"></h1>
<div class="filters" id="packFilters">
<select id="countryFilter" data-label="allCountries"></select>
<select id="rankFilter" data-label="allRanks"></select>
<input id="searchInput" type="search" data-label="search" />
<select id="sortSelect" data-label="sort">
<option value="best" data-t="sortBest"></option>
<option value="newest" data-t="sortNewest"></option>
<option value="priceAsc" data-t="sortPriceAsc"></option>
<option value="priceDesc" data-t="sortPriceDesc"></option>
</select>
</div>
</div>
<div class="grid" id="grid"></div>
</section>
<section class="detail" id="detail" hidden></section>
<section class="redeem" id="redeemPanel" aria-labelledby="redeemTitle" hidden>
<h1 id="redeemTitle" data-t="tabRedeem"></h1>
<div class="redeem-row">
<input id="codeInput" type="text" data-label="codePlaceholder" />
<button type="button" class="btn-main" id="redeemBtn" data-t="redeem" disabled></button>
</div>
<ul class="redeem-help" id="redeemHelp"></ul>
</section>
</main>
<footer class="foot" data-t="footer"></footer>
</div>
<dialog class="checkout" id="checkout" aria-labelledby="checkoutTitle">
<header class="checkout-head">
<h2 id="checkoutTitle"></h2>
<button type="button" class="checkout-close" id="checkoutClose" data-label="close">×</button>
</header>
<div class="checkout-body">
<p class="checkout-empty" id="checkoutEmpty" data-t="cartEmpty" hidden></p>
<ul class="checkout-list" id="checkoutList"></ul>
</div>
<div class="checkout-footer">
<p class="notice" id="checkoutNotice" role="status"></p>
<div id="checkoutTotals" hidden>
<div class="checkout-total"><span data-t="total"></span><strong id="checkoutTotal"></strong></div>
<div class="checkout-balance"><span data-t="balance"></span><span id="checkoutBalance"></span></div>
<p class="checkout-hint" id="checkoutHint" role="status" hidden></p>
<button type="button" class="btn-main" id="payGjn" data-t="payGjn"></button>
<button type="button" class="btn-outline" id="payFree" data-t="freeBuy"></button>
</div>
<button type="button" class="btn-main" id="checkoutDone" data-t="keepShopping" hidden></button>
</div>
</dialog>
<script src="/_wto/ui/common.js"></script>
<script src="/store/gallery.js"></script>
<script src="/store/products.js"></script>
<script src="/store/checkout.js"></script>
<script src="/store/app.js"></script>
</body>
</html>
+134
View File
@@ -0,0 +1,134 @@
.detail { padding: 18px 0 38px; }
.detail-head { margin-bottom: 14px; }
.detail-head h1 { margin: 5px 0 7px; font-size: clamp(27px, 3.5vw, 41px); line-height: 1.14; overflow-wrap: anywhere; }
.detail-meta:empty { display: none; }
.back { padding: 2px 0; border: 0; background: transparent; color: var(--accent); font-weight: 600; }
.back:hover { text-decoration: underline; }
.detail-grid { display: grid; grid-template-columns: minmax(0, 2.25fr) minmax(250px, 1fr); gap: 20px; align-items: start; }
.detail-main, .detail-grid > aside { min-width: 0; }
.gallery {
min-width: 0;
padding-bottom: 5px;
border-bottom: 1px solid var(--line);
}
.media-stage {
position: relative;
display: grid;
place-items: center;
aspect-ratio: 16 / 9;
overflow: hidden;
border-radius: 4px;
background: radial-gradient(ellipse, #405368, #182632);
}
.media-stage img, .media-stage video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; }
.media-stage video { background: #000; }
.gallery-screenshot { visibility: hidden; }
.gallery-screenshot.ready { visibility: visible; }
.media-placeholder { color: var(--muted); text-align: center; }
.media-thumb .media-placeholder { position: absolute; inset: 0; display: grid; place-items: center; padding: 3px; font-size: 12px; }
.media-play {
position: relative;
min-height: 44px;
padding: 8px 18px;
border: 1px solid #e0bf82;
border-radius: 18px;
background: #251f1be8;
color: #ffe9bd;
font-weight: 700;
}
.media-play:hover { background: #463527; }
.media-navigation { display: grid; grid-template-columns: 34px minmax(0, 1fr) 34px; align-items: stretch; gap: 6px; margin-top: 8px; }
.media-navigation > button {
padding: 0;
border: 1px solid var(--line);
border-radius: 5px;
background: var(--surface);
font-size: 27px;
}
.media-navigation > button:hover:not(:disabled) { background: var(--surface-raised); }
.media-thumbs { display: flex; gap: 6px; overflow: auto hidden; scrollbar-width: thin; }
.media-thumbs::-webkit-scrollbar { height: 5px; }
.media-thumbs::-webkit-scrollbar-thumb { border-radius: 4px; background: #48606d; }
.media-thumb {
position: relative;
flex: 0 0 clamp(76px, 12vw, 126px);
aspect-ratio: 16 / 9;
overflow: hidden;
padding: 0;
border: 2px solid transparent;
border-radius: 5px;
background: #283b48;
}
.media-thumb[aria-pressed="true"] { border-color: var(--gold); }
.media-thumb:focus-visible { outline-offset: -4px; }
.media-thumb img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
.thumb-play {
position: absolute;
top: 50%;
left: 50%;
display: grid;
place-items: center;
width: 28px;
height: 28px;
padding-left: 2px;
border-radius: 50%;
background: #382d22ec;
color: var(--gold);
transform: translate(-50%, -50%);
}
.media-caption { display: flex; justify-content: space-between; gap: 8px; padding: 7px 3px 0; color: var(--muted); font-size: 13px; }
.media-position { white-space: nowrap; }
.media-status { margin: 8px 3px 2px; color: #ffd5b3; font-size: 13px; }
.buy-panel { padding: 17px 17px 15px; border: 1px solid #546371; border-top: 2px solid #c0a570; border-radius: 5px; background: linear-gradient(#303c49, #23303d); }
.detail-price { display: flex; justify-content: space-between; align-items: baseline; flex-wrap: wrap; gap: 5px 10px; padding-bottom: 14px; color: var(--muted); }
.detail-price strong { color: var(--gold); font-size: 25px; }
.detail-actions { display: grid; gap: 9px; }
.includes { margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--line); }
.includes h2, .detail-recommendations h2 { margin: 0 0 10px; font-size: 16px; }
.includes ul { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; }
.included-vehicle { display: grid; grid-template-columns: 58px minmax(0, 1fr); gap: 10px; align-items: center; }
.included-vehicle strong { display: block; margin-bottom: 4px; font-weight: 600; overflow-wrap: anywhere; }
.included-art { width: 58px; height: 43px; object-fit: contain; border-radius: 4px; background: #283b48; }
.included-reward { color: var(--muted); }
.detail-recommendations { display: grid; gap: 8px; margin-top: 18px; }
.detail-recommendations h2 { margin-bottom: 0; }
.bonus {
position: relative;
min-height: 158px;
display: flex;
align-items: center;
overflow: hidden;
isolation: isolate;
margin-top: 18px;
padding: 25px 26px;
border: 1px solid #e1c38d;
border-radius: 5px;
background: linear-gradient(108deg, #e6cf9b, #d7b474 62%, #a17948);
color: #2e2214;
}
.bonus-art {
position: absolute;
z-index: -1;
right: -4%;
top: -12%;
width: 68%;
height: 125%;
object-fit: cover;
-webkit-mask-image: linear-gradient(90deg, transparent, #000 40%);
mix-blend-mode: multiply;
filter: sepia(1) contrast(1.15);
opacity: .63;
}
.bonus-copy { max-width: 63%; }
.bonus-copy h2 { margin: 0 0 6px; font-size: clamp(21px, 3vw, 29px); }
.bonus-copy p { margin: 0; font-size: 15px; font-weight: 550; }
@media (max-width: 760px) {
.detail-grid { grid-template-columns: minmax(0, 1fr); }
.detail-main { display: contents; }
.detail-grid > aside { grid-row: 2; }
.bonus { margin-top: 0; }
}
+176
View File
@@ -0,0 +1,176 @@
// Presentation of store products shared by the catalog, detail view, and checkout.
'use strict';
const FEATURED_PACKS = ['wto_pack_fa_18d_late', 'wto_pack_us_stingray_2', 'wto_pack_cn_ztz_96b', 'wto_pack_f-4s'];
function makeElement(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
function storeButton(className, text) {
const button = makeElement('button', className, text);
button.type = 'button';
return button;
}
function storePrice(cents) {
return WtoUi.gjn(cents) + ' GJN';
}
function rankLabel(rank) {
return t('rank', { rank: ROMAN[rank] || rank });
}
const LOCAL_STORE_MEDIA_PREFIX = '/_wto/ui/store-media/';
const PUBLIC_STORE_CDN = 'https://static-store.gaijin.net/';
function storeImageCandidates(localUrl) {
if (!localUrl) return [];
if (!localUrl.startsWith(LOCAL_STORE_MEDIA_PREFIX)) return [localUrl];
return [localUrl, PUBLIC_STORE_CDN + localUrl.slice(LOCAL_STORE_MEDIA_PREFIX.length)];
}
function productArtwork(product) {
const image = product.unitName ? WtoUi.artworkUrl('vehicle', product.unitName) : WtoUi.artworkUrl('product', product.kind);
const fallbacks = product.artworkGroup ? [WtoUi.artworkUrl('group', product.artworkGroup), image] : [image];
if (product.unitName) fallbacks.push('/_wto/ui/vehicle/' + encodeURIComponent(product.unitName) + '.svg');
return fallbacks;
}
function productImage(product, className = '') {
const { cover } = WtoUi.storeMedia(product.id);
const candidates = storeImageCandidates(cover);
const urls = product.unitName ? [...candidates, ...WtoUi.vehicleUrls(product.unitName)] : candidates;
return WtoUi.tieredImg(urls, productArtwork(product), className);
}
function productScreenshot(product, url, className = '') {
return WtoUi.tieredImg(storeImageCandidates(url), productArtwork(product), className);
}
function vehicleMeta(vehicle) {
const meta = makeElement('span', 'product-meta');
if (vehicle.country) {
meta.append(WtoUi.iconImg('flag', vehicle.country, ''), makeElement('span', '', WtoUi.label(vehicle.country)));
}
if (vehicle.rank) meta.append(makeElement('span', 'rank', rankLabel(vehicle.rank)));
return meta;
}
function productRewards(product) {
const rewards = [];
if (product.premiumDays) rewards.push(t('containsPremium', { days: product.premiumDays }));
if (product.goldIncome) rewards.push(t('containsEagles', { n: WtoUi.num(product.goldIncome) }));
if (product.silverIncome) rewards.push(t('containsSilver', { n: WtoUi.num(product.silverIncome) }));
return rewards;
}
function productCard(product, checkout, openProduct) {
const card = makeElement('article', 'product-card');
const open = storeButton('product-open');
const art = makeElement('span', 'product-art');
art.append(productImage(product));
if (WtoUi.storeOrder('bestSellers').includes(product.id)) {
art.append(makeElement('span', 'product-badge', t('bestSeller')));
}
const info = makeElement('span', 'product-info');
info.append(makeElement('span', 'product-title', WtoUi.text(product.title)));
if (product.unitName) {
info.append(vehicleMeta(product));
const rewards = productRewards(product);
if (rewards.length) info.append(makeElement('span', 'product-rewards', rewards.join(' · ')));
}
open.append(art, info);
open.onclick = () => openProduct(product);
const actions = makeElement('div', 'card-actions');
actions.append(...checkout.productButtons(product, ''));
card.append(open, makeElement('div', 'card-price', storePrice(product.gjnCostCents)), actions);
return card;
}
function recommendedPacks(products) {
return FEATURED_PACKS.map((id) => products.find((product) => product.id === id)).filter(Boolean);
}
function recommendationTile(product, openProduct) {
const tile = storeButton('recommendation-tile');
const copy = makeElement('span', 'recommendation-copy');
copy.append(makeElement('strong', '', WtoUi.text(product.title)), makeElement('span', '', storePrice(product.gjnCostCents)));
tile.append(productImage(product), copy);
tile.onclick = () => openProduct(product);
return tile;
}
function featuredBanner(lead, openProduct) {
const hero = storeButton('featured-hero');
const { screenshots } = WtoUi.storeMedia(lead.id);
const image = screenshots.length ? productScreenshot(lead, screenshots[0]) : productImage(lead);
image.loading = 'eager';
const copy = makeElement('span', 'featured-copy');
copy.append(
makeElement('span', 'featured-label', t('featured')),
makeElement('strong', 'featured-title', WtoUi.text(lead.title)),
vehicleMeta(lead),
makeElement('span', 'featured-link', t('viewPack') + ' →'),
);
hero.append(image, copy);
hero.onclick = () => openProduct(lead);
return hero;
}
function renderPackDetail(root, product, checkout, products, openProduct, backToCatalog) {
const autoplay = !root.firstElementChild || root.dataset.productId !== product.id;
root.dataset.productId = product.id;
root.innerHTML = '<header class="detail-head"><button type="button" class="back"></button><h1 tabindex="-1"></h1><div class="detail-meta"></div></header>'
+ '<div class="detail-grid"><div class="detail-main"><section class="gallery"></section><section class="bonus" hidden></section></div>'
+ '<aside><div class="buy-panel"><div class="detail-price"></div><div class="detail-actions"></div><div class="includes"></div></div>'
+ '<section class="detail-recommendations" hidden></section></aside></div>';
const back = root.querySelector('.back');
back.textContent = '‹ ' + t('back');
back.onclick = backToCatalog;
root.querySelector('h1').textContent = WtoUi.text(product.title);
if (product.unitName) root.querySelector('.detail-meta').append(vehicleMeta(product));
mountStoreGallery(root.querySelector('.gallery'), product, autoplay);
const price = root.querySelector('.detail-price');
price.append(makeElement('span', '', t('packPrice')), makeElement('strong', '', storePrice(product.gjnCostCents)));
root.querySelector('.detail-actions').append(...checkout.productButtons(product, 'detail'));
renderPackContents(root.querySelector('.includes'), product);
if (product.kind !== 'vehicle-pack') return;
renderPremiumBonus(root.querySelector('.bonus'), product);
const related = recommendedPacks(products).filter((item) => item.id !== product.id).slice(0, 2);
if (related.length) {
const section = root.querySelector('.detail-recommendations');
section.hidden = false;
section.append(makeElement('h2', '', t('related')), ...related.map((item) => recommendationTile(item, openProduct)));
}
}
function renderPackContents(root, product) {
const list = makeElement('ul', '');
for (const vehicle of product.vehicles || []) {
const item = makeElement('li', 'included-vehicle');
item.append(
WtoUi.tieredImg([], [WtoUi.artworkUrl('vehicle', vehicle.unitName)], 'included-art'),
);
const vehicleText = makeElement('div', '');
vehicleText.append(makeElement('strong', '', WtoUi.text(vehicle.title)), vehicleMeta(vehicle));
item.append(vehicleText);
list.append(item);
}
for (const reward of productRewards(product)) list.append(makeElement('li', 'included-reward', reward));
root.append(makeElement('h2', '', t('includes')), list);
}
function renderPremiumBonus(root, product) {
const art = WtoUi.tieredImg([], productArtwork(product), 'bonus-art');
const copy = makeElement('div', 'bonus-copy');
copy.append(makeElement('h2', '', t('bonusTitle')), makeElement('p', '', t('bonusText')));
root.hidden = false;
root.replaceChildren(art, copy);
}
+272
View File
@@ -0,0 +1,272 @@
:root {
color-scheme: dark;
--background: #222d39;
--surface: #303e4d;
--surface-raised: #3c4b5a;
--line: #4a5b6a;
--text: #f2f4f7;
--muted: #bac7d2;
--accent: #78d6e3;
--accent-hover: #afeef5;
--gold: #f0d396;
--font: "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", sans-serif;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
html, body { margin: 0; }
body {
min-height: 100vh;
background: radial-gradient(ellipse at 50% 0, #455463, var(--background) 620px);
color: var(--text);
font: 15px/1.45 var(--font);
}
button, select, input { font: inherit; }
button { color: inherit; cursor: pointer; }
button:disabled { cursor: default; opacity: .55; }
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 3px;
}
a { color: var(--accent); text-decoration: none; }
.page { width: min(1248px, calc(100% - 56px)); margin: 0 auto; }
.store-header {
min-height: 52px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 8px 12px;
background: #141e29;
}
.store-brand {
display: inline-flex;
align-items: center;
gap: 12px;
padding: 0;
border: 0;
background: transparent;
font-size: 17px;
font-weight: 650;
white-space: nowrap;
}
.store-mark {
display: grid;
place-items: center;
width: 31px;
height: 31px;
border: 1px solid #b99c65;
border-radius: 5px;
background: #352e23;
color: var(--gold);
font-size: 14px;
letter-spacing: .03em;
}
.account-strip {
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
min-width: 0;
gap: 6px 12px;
color: var(--muted);
font-size: 13px;
}
.balance { white-space: nowrap; }
.account-strip select { max-width: min(230px, 100%); }
.balance b { margin-left: 3px; color: var(--text); font-weight: 600; }
.account-strip select, .filters select, .filters input, .redeem-row input {
min-height: 38px;
padding: 0 10px;
border: 1px solid var(--line);
border-radius: 6px;
background: #15212b;
color: var(--text);
}
.store-nav { display: flex; justify-content: space-between; gap: 8px 16px; padding: 0 3px; border-bottom: 1px solid var(--line); }
.tabs, .store-links { display: flex; align-items: center; gap: 8px; }
.tabs { flex-wrap: wrap; }
.tabs button {
min-height: 56px;
padding: 0 13px;
border: 0;
border-bottom: 2px solid transparent;
background: transparent;
color: var(--muted);
font-weight: 600;
}
.tabs button:hover, .tabs button[aria-pressed="true"] { color: var(--accent); }
.tabs button[aria-pressed="true"] { border-color: var(--accent); }
.store-links { gap: 15px; white-space: nowrap; }
.cart-link {
min-height: 38px;
display: inline-flex;
align-items: center;
gap: 9px;
padding: 4px 10px;
border: 1px solid #5c8b9b;
border-radius: 4px;
background: #283e4e;
color: var(--accent-hover);
font-weight: 650;
}
.cart-link:hover:not(:disabled) { background: #35566a; }
.cart-link b {
min-width: 22px;
padding: 1px 5px;
border-radius: 12px;
background: #172c3a;
text-align: center;
font-size: 12px;
}
.cart-icon { position: relative; width: 16px; height: 16px; }
.cart-icon::before {
content: "";
position: absolute;
inset: 2px 0 6px 1px;
border: 2px solid currentColor;
border-top-width: 1px;
transform: skewX(-12deg);
}
.cart-icon::after {
content: "";
position: absolute;
left: 3px;
bottom: 1px;
width: 3px;
height: 3px;
border-radius: 50%;
background: currentColor;
box-shadow: 8px 0 currentColor;
}
.catalog-head { display: grid; gap: 11px; padding: 18px 0; }
.catalog-head h1, .redeem h1 { margin: 0; font-size: clamp(24px, 3vw, 32px); line-height: 1.2; }
.filters { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 7px 0; border-block: 1px solid var(--line); font-size: 13px; }
.filters input { width: clamp(130px, 22vw, 270px); }
.filters input::placeholder { color: var(--muted); }
.filters #sortSelect { margin-left: auto; }
.featured-hero {
position: relative;
grid-column: span 2;
min-height: 275px;
display: flex;
align-items: flex-end;
overflow: hidden;
padding: 24px;
border: 1px solid #617987;
border-radius: 5px;
background: #2b4051;
text-align: left;
isolation: isolate;
}
.featured-hero > img { position: absolute; z-index: -2; inset: 0; width: 100%; height: 100%; object-fit: cover; object-position: center 45%; }
.featured-hero::after {
content: "";
position: absolute;
z-index: -1;
inset: 0;
background: linear-gradient(86deg, #131c2be8 4%, #263344aa 36%, transparent 75%),
linear-gradient(0deg, #101a27dc, transparent 64%);
}
.featured-copy { display: flex; flex-direction: column; align-items: flex-start; gap: 7px; }
.featured-label { color: var(--gold); font-size: 13px; font-weight: 650; }
.featured-title { max-width: 540px; font-size: clamp(25px, 3.4vw, 42px); line-height: 1.13; overflow-wrap: anywhere; }
.featured-link { margin-top: 6px; color: var(--accent-hover); font-weight: 650; }
.featured-hero:hover .featured-link { text-decoration: underline; }
.recommendation-tile {
display: grid;
grid-template-columns: min(38%, 132px) minmax(0, 1fr);
align-items: center;
gap: 12px;
width: 100%;
padding: 0 12px 0 0;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 5px;
background: var(--surface);
text-align: left;
}
.recommendation-tile:hover { border-color: #779498; background: var(--surface-raised); }
.recommendation-tile img { width: 100%; height: 100%; min-height: 68px; max-height: 91px; object-fit: cover; background: #304856; }
.recommendation-copy { display: grid; gap: 4px; padding: 5px 0; overflow-wrap: anywhere; }
.recommendation-copy > span { color: var(--gold); font-size: 13px; }
.grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 18px; padding-bottom: 38px; }
.product-card {
display: flex;
flex-direction: column;
min-width: 0;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 5px;
background: var(--surface);
}
.product-card:hover { border-color: #627e89; }
.product-open { display: block; width: 100%; padding: 0; border: 0; background: transparent; text-align: left; }
.product-open:focus-visible { outline-offset: -3px; }
.product-art { position: relative; display: block; aspect-ratio: 16 / 9; background: radial-gradient(ellipse, #465866, #293b4a); }
.product-art::after { content: ""; position: absolute; inset: auto 0 0; height: 24%; background: linear-gradient(transparent, var(--surface)); pointer-events: none; }
.product-badge { position: absolute; z-index: 1; top: 10px; left: 10px; padding: 3px 8px; border: 1px solid #b28f5a; border-radius: 4px; background: #362f28f2; color: var(--gold); font-size: 12px; font-weight: 650; }
.product-art img { display: block; width: 100%; height: 100%; object-fit: cover; }
.product-info { display: grid; gap: 6px; padding: 12px 13px 8px; }
.product-title { font-size: 17px; font-weight: 650; line-height: 1.25; overflow-wrap: anywhere; }
.product-meta { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 5px 8px; color: var(--muted); font-size: 13px; }
.product-meta img { width: 25px; height: 16px; object-fit: contain; }
.product-meta .rank { padding: 1px 6px; border-radius: 4px; background: #ffffff13; color: var(--text); white-space: nowrap; }
.product-rewards { color: var(--muted); font-size: 12px; }
.card-price { margin-top: auto; padding: 10px 13px; color: var(--gold); font-size: 19px; font-weight: 650; text-align: right; }
.card-actions { display: grid; grid-template-columns: minmax(0, .9fr) minmax(0, 1.35fr); border-top: 1px solid var(--line); }
.card-actions button { min-height: 41px; padding: 6px; border: 0; background: transparent; font-size: 14px; font-weight: 600; }
.card-actions .card-buy { color: var(--gold); border-right: 1px solid var(--line); }
.card-actions .card-add { color: #e6edf0; }
.card-actions button:hover:not(:disabled), .card-actions .in-cart { background: #415365; }
.empty { grid-column: 1 / -1; color: var(--muted); }
.btn-main, .btn-outline {
min-height: 45px;
padding: 9px 14px;
border: 1px solid transparent;
border-radius: 6px;
font-weight: 650;
}
.btn-main { border-color: #c47359; background: linear-gradient(#ad513c, #923e30); color: #fff; }
.btn-main:hover:not(:disabled) { background: linear-gradient(#bc5f47, #a24937); }
.btn-outline { border-color: #bca674; background: transparent; color: var(--gold); }
.btn-outline:hover:not(:disabled), .btn-outline.in-cart { background: #3b4c5a; }
.notice { display: none; margin: 14px 0 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 5px; }
.notice.ok { display: block; background: #18362f; color: #b4eed9; }
.notice.err { display: block; background: #3b2b2b; color: #ffc5b5; }
.redeem { padding: 26px 0 42px; max-width: 740px; }
.redeem-row { display: flex; gap: 10px; margin: 18px 0; }
.redeem-row input { flex: 1; min-width: 0; }
.redeem-help { padding-left: 20px; color: var(--muted); }
.foot { padding: 20px 0 30px; border-top: 1px solid var(--line); color: var(--muted); font-size: 13px; }
@media (max-width: 1000px) {
.page { width: calc(100% - 36px); }
.grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
}
@media (max-width: 880px) {
.store-header { flex-wrap: wrap; gap: 7px 16px; }
.account-strip { justify-content: flex-start; }
}
@media (max-width: 730px) {
.store-nav { flex-wrap: wrap; }
.store-links { padding-bottom: 7px; }
.featured-hero { min-height: 215px; }
.grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
}
@media (max-width: 410px) {
.page { width: calc(100% - 24px); }
.grid { grid-template-columns: minmax(0, 1fr); }
.featured-hero { grid-column: 1; }
.filters #sortSelect { margin-left: 0; }
}
+124
View File
@@ -0,0 +1,124 @@
/**
* The game's own store requests (yuplay2, implementation notes), sent to api.gaijinent.com
* and routed here by wto_ws.dll:
* POST /item_info.php GJN prices of the bundle GUIDs (scripts/onlineShop/entitlementsInfo.nut)
* POST /item_purchase.php pay=gjn purchase from the in-game payment window
* POST /redeem_code.php the in-game redeem code window
* The player is identified by the session token or JWT the local login service issued; a
* request whose player cannot be identified is refused.
*/
import type { Account, AccountStore } from '../accounts/account-store.ts';
import { userIdFromJwt, userIdFromToken } from '../login/session-credentials.ts';
import { yuplayAnswer } from '../login/yuplay-answer.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { serverTimeNow } from '../profile/server-time.ts';
import type { ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
import { gjnText, redeemStoreCode, type RedeemOutcome } from './redeem-codes.ts';
import type { RedeemTuning } from './redeem-tuning.ts';
import type { StoreCatalogue } from './store-catalogue.ts';
import { buyFreeStoreProduct, buyGjnProduct, canBuyGjnProduct, type GjnPurchaseOutcome } from './store-purchase.ts';
export const YUPLAY_STORE_PATHS: ReadonlySet<string> = new Set(['/item_info.php', '/item_purchase.php', '/redeem_code.php']);
export class YuplayStoreApi {
readonly #accounts: AccountStore;
readonly #profiles: PlayerProfiles;
readonly #catalogue: StoreCatalogue;
readonly #redeemCodes: RedeemTuning;
/** Base of the local store page, e.g. http://127.0.0.1:47115/store; item_info.php `url` points into it. */
readonly #storePageBase: string;
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning, storePageBase: string) {
this.#storePageBase = storePageBase;
this.#accounts = accounts;
this.#profiles = profiles;
this.#catalogue = catalogue;
this.#redeemCodes = redeemCodes;
}
handle(request: ServiceRequest): ServiceResponse {
if (request.method !== 'POST') return yuplayAnswer('ERROR', {}, `${request.method} ${request.path} not supported`);
const form = new URLSearchParams(request.body.toString('utf8'));
if (request.path === '/item_info.php') return this.#itemInfo(form);
if (request.path === '/item_purchase.php') return this.#itemPurchase(form);
return this.#redeemCode(form);
}
#itemInfo(form: URLSearchParams): ServiceResponse {
const guids = [...form.getAll('guids[]'), ...form.getAll('guids'), ...form.getAll('guid')].filter(Boolean);
const account = this.#account(form);
const profile = account ? this.#profiles.profileOf(account.userId) : undefined;
const now = serverTimeNow();
const items: Record<string, unknown> = {};
let numericId = 1;
for (const guid of guids) {
const product = this.#catalogue.byGuid(guid);
if (!product || product.gjnCostCents === undefined) continue;
items[guid] = {
item_id: numericId++,
shop_price: product.gjnCostCents / 100,
price_usd: product.gjnCostCents / 100,
discount_mul: 1.0,
discount_till: 0,
title: product.title.en,
// The game opens this page for the pack's own store entry (onlineShopModel.nut
// doBrowserPurchaseByGuid → get_url_for_purchase → yu_itemInfo.cpp `url`).
url: `${this.#storePageBase}?item=${encodeURIComponent(guid)}`,
short_desc: product.title.en,
shop_price_curr: 'gjn',
multi_purch: product.kind !== 'vehicle-pack',
can_be_bought: profile ? canBuyGjnProduct(profile, product, now) : true,
};
}
return yuplayAnswer('OK', { items }, `item_info (${Object.keys(items).length}/${guids.length} items)`);
}
#itemPurchase(form: URLSearchParams): ServiceResponse {
const account = this.#account(form);
if (!account) return yuplayAnswer('LOGINERROR', {}, 'item_purchase: unknown token');
const rawPay = form.get('pay');
// The free offline payment method passes YU2_PAY_NONE, so PurchaseAction::run omits `pay`.
const payMethod = rawPay === null ? 'free' : rawPay.toLowerCase();
if (payMethod !== 'gjn' && payMethod !== 'free') {
return yuplayAnswer('BADPAYMENT', {}, `item_purchase: unsupported pay=${rawPay}`);
}
const guid = form.get('guid') ?? '';
const product = this.#catalogue.byGuid(guid);
if (!product) return yuplayAnswer('NOTFOUND', {}, `item_purchase: unknown guid ${guid}`);
let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' };
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
outcome = payMethod === 'free'
? buyFreeStoreProduct(saved, product, now)
: buyGjnProduct(saved, product, now);
return outcome.ok;
});
if (outcome.ok) {
const costSummary = payMethod === 'free' ? 'free' : `${gjnText(product.gjnCostCents ?? 0)} GJN`;
return yuplayAnswer('OK', {}, `item_purchase ${product.id} (${costSummary})`);
}
if (outcome.reason === 'NOT_ENOUGH_GJN') return yuplayAnswer('NOMONEY', {}, `item_purchase ${product.id}: insufficient GJN`);
if (outcome.reason === 'ALREADY_BOUGHT') return yuplayAnswer('ALREADY', {}, `item_purchase ${product.id}: already owned`);
return yuplayAnswer('NOTFOUND', {}, `item_purchase ${product.id}: not available`);
}
#redeemCode(form: URLSearchParams): ServiceResponse {
const account = this.#account(form);
if (!account) return yuplayAnswer('LOGINERROR', {}, 'redeem_code: unknown token');
const code = form.get('code') ?? '';
let outcome: RedeemOutcome | undefined;
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
outcome = redeemStoreCode(saved, code, now, this.#redeemCodes);
return outcome.ok;
});
if (outcome?.ok) return yuplayAnswer('OK', {}, `redeem_code ${code} -> OK`);
return yuplayAnswer(outcome?.reason === 'ALREADY_REDEEMED' ? 'ALREADY' : 'NOTFOUND', {}, `redeem_code ${code} -> ${outcome?.reason ?? 'INVALID_CODE'}`);
}
#account(form: URLSearchParams): Account | undefined {
const userId = userIdFromToken(form.get('token') ?? undefined) ?? userIdFromJwt(form.get('jwt') ?? undefined);
return userId ? this.#accounts.byUserId(userId) : undefined;
}
}