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:
1 parent
9c813ccf7d
commit
930ea07630
476 files changed
+275
-251
No files matched your search
@@ -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,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user