Files
wikideck/server/game/duel-binding.ts

87 lines
4.6 KiB
TypeScript

/**
* Binds the mode host to the Night 2 duel engine (shared/duel; DUEL_API.md "Host binding").
*
* Cards: an owned NFT (`ChainCard`, built by ownership.ts from its block) becomes a `DuelCard`
* through ONE function, `toDuelCard`, shared by the host and the collection API, so PvP, the
* deck builder and the browser bot all see the same card. The card profile (P31 classes,
* categories, description, links) comes from testnet-ops' frozen IdentityStore (#68). On a
* miss it is derived from what the chain itself carries (weaker typing), and nothing is
* fetched inline: no Wikimedia call ever happens at deck validation or match time.
*/
import { derive, type DuelCard } from '../../shared/duel/derive.ts';
import { profileFromSources } from '../../shared/duel/profile.ts';
import { classify } from '../../shared/duel/classify.ts';
import { toProfile, type IdentityStore } from './identity.ts';
import type { ChainCard, EnginePort } from './engine-port.ts';
export type DuelCardSources = {
/** Frozen per-token identities (server/game/identity.ts). */
identity?: Pick<IdentityStore, 'get'>;
};
type AnyPort = EnginePort<any, any, any, any>;
/**
* Generic type hints from the mint-time `article.category` (server/wiki.ts `category()`), used
* only when neither a frozen identity nor the extract's first sentence types the card. They are
* class words, not facts about the subject, and never reach the Connected keys.
*/
const CATEGORY_HINTS: Readonly<Record<string, string>> = {
People: 'person', Nature: 'organism', Space: 'astronomical object', History: 'event', Science: 'concept', Culture: 'organization',
};
/** First sentence of the on-chain extract, as a description-like signal for the classifier. */
function firstSentence(extract: string): string {
const text = extract.replace(/\s+/g, ' ').trim();
return (/^.*?[.!?](?=\s|$)/.exec(text)?.[0] ?? text).slice(0, 300);
}
/**
* The single ChainCard → DuelCard conversion. Deterministic for a given block and identity.
* Miss path (no frozen identity yet): classify from what the block itself carries, the extract's
* first sentence, then the mint-time category hint. No fetch; card faces stay real data only.
*/
export function toDuelCard(card: ChainCard, sources: DuelCardSources = {}): DuelCard {
const article = card.article as { pageId: number; title: string; extract: string; revisionId: number; category?: string } | undefined;
const statsSnapshot = card.statsSnapshot as { pageBytes: number; languageCount: number; stats: any } | undefined;
if (!article || !statsSnapshot) throw new Error(`Card ${card.tokenId} has no on-chain article or stats snapshot`);
const chain = { tokenId: card.tokenId, article, statsSnapshot };
const frozen = sources.identity?.get(card.tokenId);
if (frozen) return derive(chain, toProfile(frozen) as any);
const base = profileFromSources({ enrichment: {
description: null, wikidataId: null, categories: [], revisionId: article.revisionId ?? null } as any });
const sentence = firstSentence(article.extract ?? '');
let profile = { ...base, description: sentence || null };
if (classify(profile).source === 'fallback') {
const hint = CATEGORY_HINTS[article.category ?? ''];
if (hint) profile = { ...profile, instanceOf: [{ id: '', label: hint }] };
}
const out = derive(chain, profile as any);
// The sentence is the flavour text already; it is not a Wikidata short description.
delete (out as { description?: string }).description;
out.connect = { ...out.connect, p31: out.connect.p31.filter(id => id !== '') };
(out as { typedBy?: string }).typedBy = 'fallback';
return out;
}
/** Wrap duel-core's `duelEnginePort` with what the host adds: owned-card building and the copy limit. */
export function duelBinding(port: AnyPort, sources: DuelCardSources = {}): AnyPort {
return {
...port,
fromChain: (_rules, card) => toDuelCard(card, sources),
copyLimit: rules => (rules as { maxCopiesPerPage?: number }).maxCopiesPerPage ?? 4,
// BRIEF "Clock": 60 s per turn plus a 5-minute bank, both ruleset data.
bankSeconds: rules => (rules as { bankSeconds?: number }).bankSeconds ?? 0,
};
}
/**
* The duel engine, if this build has it (`duelEnginePort` from shared/duel/index.ts, the engine
* alpha). Null before that lands: duel modes are then skipped at startup with a log line.
*/
export async function loadDuelEngine(sources: DuelCardSources = {}): Promise<AnyPort | null> {
const mod = await import('../../shared/duel/index.ts') as Record<string, unknown>;
const port = mod.duelEnginePort as AnyPort | undefined;
return port && typeof port.createMatch === 'function' ? duelBinding(port, sources) : null;
}