First commit

This commit is contained in:
2026-10-27 12:42:57 +01:00
commit 7dd9f4b14d
74 changed files with 33018 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { hashPassword, verifyPassword } from '../src/accounts.js'
test('passwords are salted and verified', async () => {
const first = await hashPassword('correct horse battery staple')
const second = await hashPassword('correct horse battery staple')
assert.notEqual(first.salt, second.salt)
assert.notEqual(first.hash, second.hash)
assert.equal(await verifyPassword('correct horse battery staple', first.salt, first.hash), true)
assert.equal(await verifyPassword('wrong password', first.salt, first.hash), false)
})

View File

@@ -0,0 +1,53 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import type { Card } from '../src/cards.js'
import { matchesCardFilters } from '../src/cards.js'
function card(overrides: Partial<Card> = {}): Card {
return {
oracle_id: 'test',
name: 'Test Card',
layout: 'normal',
cmc: 3,
type_line: 'Legendary Creature — Human',
colors: ['G', 'U'],
color_identity: ['G', 'U'],
keywords: [],
rarity: 'rare',
legal_formats: ['commander', 'legacy'],
...overrides,
}
}
const cardByIdentity = card({ color_identity: ['G', 'U'] })
test('card filters match format legality, color identity, type, rarity, and mana value', () => {
assert.equal(matchesCardFilters(cardByIdentity, { format: 'legacy' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { format: 'standard' }), false)
assert.equal(matchesCardFilters(cardByIdentity, {}), true)
assert.equal(matchesCardFilters(cardByIdentity, { color: 'U' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { color: 'M' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { color: 'C' }), false)
assert.equal(matchesCardFilters(card({ color_identity: [] }), { color: 'C' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { type: 'legendary' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { type: 'creature' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { type: 'land' }), false)
const modalCard = card({
type_line: 'Sorcery',
card_faces: [
{ name: 'Front', type_line: 'Sorcery', colors: [] },
{ name: 'Back', type_line: 'Land', colors: [] },
],
})
assert.equal(matchesCardFilters(modalCard, { type: 'land' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { rarity: 'rare' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { rarity: 'common' }), false)
assert.equal(matchesCardFilters(cardByIdentity, { cmcMin: 3, cmcMax: 3 }), true)
assert.equal(matchesCardFilters(cardByIdentity, { cmcMin: 4 }), false)
assert.equal(matchesCardFilters(cardByIdentity, { cmcMax: 2 }), false)
})

View File

@@ -0,0 +1,159 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import type { Card } from '../src/cards.js'
import { canBeCommander, importDeckText, validateCommanderDeck } from '../src/game/commander.js'
import { Game } from '../src/game/game.js'
import type { CardDefinition } from '../src/game/types.js'
function card(name: string, overrides: Partial<Card> = {}): Card {
return {
oracle_id: name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
name,
layout: 'normal',
cmc: 0,
type_line: 'Creature — Test',
colors: [],
color_identity: [],
keywords: [],
...overrides,
}
}
function commanderCard(name: string, overrides: Partial<Card> = {}): Card {
return card(name, {
type_line: 'Legendary Creature — Test',
color_identity: ['G'],
...overrides,
})
}
function basicLand(name: string): Card {
return card(name, { type_line: 'Basic Land — Forest', color_identity: ['G'] })
}
function commanderDefinition(name: string, overrides: Partial<CardDefinition> = {}): CardDefinition {
return {
oracleId: name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
name,
typeLine: 'Legendary Creature — Test',
manaCost: '{1}',
manaValue: 1,
colors: ['G'],
colorIdentity: ['G'],
power: 2,
toughness: 2,
abilities: [],
...overrides,
}
}
test('commander deck validation enforces size, singleton, identity, and commander type', () => {
const commander = commanderCard('Test Commander')
const legal = Array.from({ length: 99 }, () => basicLand('Forest'))
assert.deepEqual(validateCommanderDeck(commander, legal), [])
assert.match(validateCommanderDeck(commander, legal.slice(1)).join(' '), /exactly 100/)
const duplicate = [...legal.slice(1), card('Sol Ring', { color_identity: [] }), card('Sol Ring', { color_identity: [] })]
assert.match(validateCommanderDeck(commander, duplicate).join(' '), /only basic lands may repeat/)
const offColor = [...legal.slice(1), card('Counterspell', { color_identity: ['U'] })]
assert.match(validateCommanderDeck(commander, offColor).join(' '), /outside the commander's color identity/)
assert.match(validateCommanderDeck(card('Not Legendary'), legal).join(' '), /cannot be a commander/)
assert.equal(canBeCommander(card('Planeswalker Commander', { oracle_text: 'This can be your commander.' })), true)
})
test('decklist import reads sections, quantities, and set suffixes', () => {
const known = new Map<string, Card>([
['Test Commander', commanderCard('Test Commander')],
['Sol Ring', card('Sol Ring')],
['Forest', basicLand('Forest')],
])
const result = importDeckText(`
Commander
1 Test Commander (TST) 1
Deck
1 Sol Ring (TST) 2
2 Forest (TST) 3 *F*
`, name => known.get(name))
assert.equal(result.commander?.name, 'Test Commander')
assert.equal(result.cards.length, 3)
assert.equal(result.cards.filter(entry => entry.name === 'Forest').length, 2)
assert.match(result.errors.join(' '), /exactly 100/)
})
test('a commander starts in the command zone, pays tax, and returns there from the graveyard', () => {
const commander = commanderDefinition('Test Commander')
const game = new Game({
seed: 1,
startingHandSize: 0,
commander: true,
players: [
{ id: 'p1', deck: [], commander },
{ id: 'p2', deck: [], commander: commanderDefinition('Other Commander') },
],
})
game.start()
const forest = {
oracleId: 'forest',
name: 'Forest',
typeLine: 'Basic Land — Forest',
abilities: [{
kind: 'activated' as const,
costs: [{ kind: 'tap' as const }],
effects: [{ op: 'add_mana' as const, player: 'you' as const, mana: { kind: 'symbols' as const, symbols: ['{G}'] } }],
optional: false,
text: '{T}: Add {G}.',
}],
}
const player = game.getPlayer('p1')
assert.equal(player.command.length, 1)
const object = game.getObject(player.command[0])
assert.equal(object.isCommander, true)
for (let index = 0; index < 4; index++) game.addCard('p1', forest, 'battlefield')
game.castSpell('p1', object.id)
game.resolveStack()
assert.equal(object.zone, 'battlefield')
assert.equal(player.commanderCasts[object.id], 1)
game.moveToZone(object, 'graveyard')
assert.equal(object.zone, 'command')
assert.equal(player.graveyard.length, 0)
game.castSpell('p1', object.id)
game.resolveStack()
assert.equal(object.zone, 'battlefield')
assert.equal(player.commanderCasts[object.id], 2)
assert.equal(player.battlefield.map(id => game.getObject(id)).filter(land => land.tapped).length, 4)
})
test('twenty-one commander damage loses the game', () => {
const commander = commanderDefinition('Big Commander', { power: 21, manaCost: '{0}', manaValue: 0 })
const game = new Game({
seed: 1,
startingHandSize: 0,
commander: true,
players: [
{ id: 'p1', deck: [], commander },
{ id: 'p2', deck: [], commander: commanderDefinition('Other Commander') },
],
})
game.start()
const object = game.getObject(game.getPlayer('p1').command[0])
game.castSpell('p1', object.id)
game.resolveStack()
object.enteredTurn = 0
game.declareAttackers('p1', [{ attackerId: object.id, defenderId: 'p2' }])
game.declareBlockers('p2', [])
game.resolveCombatDamage()
assert.equal(game.getPlayer('p2').commanderDamage[object.id], 21)
assert.equal(game.getPlayer('p2').lost, true)
assert.equal(game.winner, 'p1')
})

View File

@@ -0,0 +1,297 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { compileText } from '../src/effects/compile.js'
import { formatAbility } from '../src/effects/format.js'
import { parsePseudoCard } from '../src/effects/pseudo.js'
import type { Ability, Effect, Target } from '../src/effects/types.js'
function creature(text: string, keywords: string[] = []): Ability[] {
return compileText(text, 'Test Creature', keywords, 'Creature — Human')
}
function spell(text: string): Ability[] {
return compileText(text, 'Test Spell', [], 'Instant')
}
test('keyword lines become keyword abilities', () => {
const [ability] = creature('Flying, vigilance, lifelink')
assert.equal(ability.kind, 'keywords')
if (ability.kind !== 'keywords') return
assert.deepEqual(ability.keywords.map(keyword => keyword.keyword), ['Flying', 'Vigilance', 'Lifelink'])
})
test('enters trigger with a draw effect', () => {
const [ability] = creature('When this creature enters, draw a card.')
assert.equal(ability.kind, 'triggered')
if (ability.kind !== 'triggered') return
assert.deepEqual(ability.event, { kind: 'enters', subject: { kind: 'self' } })
assert.equal(ability.effects.length, 1)
assert.equal(ability.effects[0].op, 'draw')
})
test('activated mana ability', () => {
const [ability] = creature('{T}: Add {G}.')
assert.equal(ability.kind, 'activated')
if (ability.kind !== 'activated') return
assert.deepEqual(ability.costs, [{ kind: 'tap' }])
assert.deepEqual(ability.effects[0], {
op: 'add_mana',
player: 'you',
mana: { kind: 'symbols', symbols: ['{G}'] },
})
})
test('search effect keeps destination, tapped, and shuffle', () => {
const [ability] = spell('Search your library for a basic land card, put it onto the battlefield tapped, then shuffle.')
assert.equal(ability.kind, 'spell')
if (ability.kind !== 'spell') return
assert.deepEqual(ability.effects[0], {
op: 'search',
player: 'you',
selector: { types: ['land'], supertypes: ['basic'] },
amount: { kind: 'number', value: 1 },
destination: 'battlefield',
tapped: true,
shuffle: true,
})
})
test('"it" refers to the triggering object when unambiguous', () => {
const [ability] = creature('Whenever another creature enters, put a +1/+1 counter on it.')
assert.equal(ability.kind, 'triggered')
if (ability.kind !== 'triggered') return
const effect = ability.effects[0]
assert.equal(effect.op, 'put_counters')
if (effect.op !== 'put_counters') return
assert.deepEqual(effect.target, { kind: 'trigger_subject' })
})
test('ambiguous "it" is left unsupported instead of guessed', () => {
const [ability] = creature(
'When this creature enters, tap target creature an opponent controls and put a stun counter on it.',
)
assert.equal(ability.kind, 'unsupported')
})
test('modal text is unsupported', () => {
const [ability] = creature('Choose one —')
assert.equal(ability.kind, 'unsupported')
if (ability.kind !== 'unsupported') return
assert.equal(ability.reason, 'modal')
})
test('static anthem', () => {
const [ability] = creature('Creatures you control get +1/+1.')
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
assert.equal(ability.effects[0].op, 'pump')
if (ability.effects[0].op !== 'pump') return
assert.equal(ability.effects[0].power.kind, 'number')
const target = ability.effects[0].target as Extract<Target, { kind: 'object' }>
assert.equal(target.mode, 'each')
assert.equal(target.selector.controller, 'you')
})
test('enters-with-counters is a static replacement effect', () => {
const [ability] = creature('This creature enters with X +1/+1 counters on it.')
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
assert.deepEqual(ability.effects[0], {
op: 'enters_with_counters',
target: { kind: 'self' },
counter: '+1/+1',
amount: { kind: 'x' },
})
})
test('trigger condition cards in graveyard', () => {
const [ability] = creature(
'Threshold — As long as there are seven or more cards in your graveyard, this creature gets +1/+1 and has first strike.',
)
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
assert.deepEqual(ability.condition, { kind: 'cards_in_graveyard', player: 'you', atLeast: 7 })
})
test('formatter renders pseudocode', () => {
const [ability] = creature('When this creature enters, draw a card.')
const text = formatAbility(ability)
assert.match(text, /on enters\(this\)/)
assert.match(text, /draw\(you, 1\)/)
})
test('token copy of the triggering nontoken Dragon loses legendary', () => {
const [ability] = creature(
"Whenever another nontoken Dragon you control enters, create a token that's a copy of it, except the token isn't legendary.",
)
assert.equal(ability.kind, 'triggered')
if (ability.kind !== 'triggered') return
assert.deepEqual(ability.event, {
kind: 'enters',
subject: {
kind: 'object',
selector: {
other: true,
controller: 'you',
token: false,
types: ['creature'],
subtypes: ['dragon'],
},
mode: 'each',
},
})
const effect = ability.effects[0]
assert.equal(effect.op, 'create_token')
if (effect.op !== 'create_token') return
assert.deepEqual(effect.copyOf, { kind: 'trigger_subject' })
assert.equal(effect.notLegendary, true)
assert.equal(formatAbility(ability), 'on enters(each other nontoken dragon creature you control):\n create_token(you, 1, copy of the triggering object, not legendary)')
})
test('all effects are typed', () => {
const [ability] = spell('Draw two cards, then discard a card.')
assert.equal(ability.kind, 'spell')
if (ability.kind !== 'spell') return
const effects: Effect[] = ability.effects
assert.deepEqual(effects.map(effect => effect.op), ['draw', 'discard'])
})
test('a leading duration applies to the effect', () => {
const [ability] = spell('Until end of turn, target creature gets +2/+0 and gains first strike.')
assert.equal(ability.kind, 'spell')
if (ability.kind !== 'spell') return
const [pump, grant] = ability.effects
assert.equal(pump.op, 'pump')
assert.equal(grant.op, 'grant')
if (pump.op !== 'pump' || grant.op !== 'grant') return
assert.equal(pump.duration, 'until_end_of_turn')
assert.equal(grant.duration, 'until_end_of_turn')
})
test('"When you do" becomes a reflexive condition and energy costs are payable', () => {
const [ability] = creature(
'Whenever a creature attacks, you may pay {3}. When you do, put a +1/+1 counter on that creature.',
)
assert.equal(ability.kind, 'triggered')
if (ability.kind !== 'triggered') return
const conditional = ability.effects[1]
assert.equal(conditional.op, 'conditional')
if (conditional.op !== 'conditional') return
assert.deepEqual(conditional.condition, { kind: 'if_you_do' })
const [activated] = creature('{T}, Pay {E}{E}: This creature deals 1 damage to target creature.')
assert.equal(activated.kind, 'activated')
if (activated.kind !== 'activated') return
assert.deepEqual(activated.costs, [
{ kind: 'tap' },
{ kind: 'energy', amount: 2 },
])
})
test('for-each pump keeps the zero stat', () => {
const [ability] = creature('This creature gets +1/+0 for each artifact you control.')
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
const effect = ability.effects[0]
assert.equal(effect.op, 'pump')
if (effect.op !== 'pump') return
assert.deepEqual(effect.power, { kind: 'count', selector: { types: ['artifact'], controller: 'you' } })
assert.deepEqual(effect.toughness, { kind: 'number', value: 0 })
})
test('"When <subject>" triggers and bare "gain life" effects parse', () => {
const [dies] = creature('When enchanted creature dies, return this to its owner\'s hand.')
assert.equal(dies.kind, 'triggered')
if (dies.kind !== 'triggered') return
assert.deepEqual(dies.event, {
kind: 'dies',
subject: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
})
const [upkeep] = creature('At the beginning of your upkeep, you may gain 1 life.')
assert.equal(upkeep.kind, 'triggered')
if (upkeep.kind !== 'triggered') return
assert.equal(upkeep.optional, true)
assert.deepEqual(upkeep.effects[0], {
op: 'life',
player: 'you',
amount: { kind: 'number', value: 1 },
mode: 'gain',
})
})
test('a trailing condition becomes a static condition', () => {
const [ability] = creature('This creature cannot attack if defending player controls an untapped land.')
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
assert.deepEqual(ability.condition, {
kind: 'defending_player_controls',
selector: { tapped: false, types: ['land'] },
})
})
test('"until the end of your next turn" gets its own duration', () => {
for (const text of [
'Target creature gets +2/+2 until the end of your next turn.',
'Until the end of your next turn, target creature gets +2/+2.',
]) {
const [ability] = spell(text)
assert.equal(ability.kind, 'spell')
if (ability.kind !== 'spell') return
const effect = ability.effects[0]
assert.equal(effect.op, 'pump')
if (effect.op !== 'pump') return
assert.equal(effect.duration, 'until_end_of_your_next_turn')
const pseudo = formatAbility(ability)
assert.match(pseudo, /until the end of your next turn/)
assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo)
}
})
test('parameterized keywords accept an em dash', () => {
const [escape] = creature('Escape—{2}{R}, Exile three other cards from your graveyard.')
assert.equal(escape.kind, 'keyword')
if (escape.kind !== 'keyword') return
assert.equal(escape.keyword, 'Escape')
const [fabricate] = creature('Fabricate 1')
assert.deepEqual(fabricate, { kind: 'keyword', keyword: 'Fabricate', value: '1' })
})
test('counter-removal costs parse and round-trip through pseudocode', () => {
const [self] = creature('{2}{U}, Remove a +1/+1 counter from this: Draw a card, then discard a card.')
assert.equal(self.kind, 'activated')
if (self.kind !== 'activated') return
assert.deepEqual(self.costs, [
{ kind: 'mana', symbols: '{2}{u}' },
{ kind: 'remove_counters', counter: '+1/+1', amount: { kind: 'number', value: 1 } },
])
const pseudo = formatAbility(self)
assert.match(pseudo, /remove 1 \+1\/\+1 counter\(s\) from this/)
assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo)
const [other] = creature('Remove three spore counters from a creature you control: Create a 1/1 green Saproling creature token.')
assert.equal(other.kind, 'activated')
if (other.kind !== 'activated') return
assert.deepEqual(other.costs, [{
kind: 'remove_counters',
counter: 'spore',
amount: { kind: 'number', value: 3 },
selector: { controller: 'you', types: ['creature'] },
}])
})
test('a trigger returns its own card from the graveyard', () => {
const [ability] = creature('When this dies, return this from your graveyard to the battlefield with a finality counter on it.')
assert.equal(ability.kind, 'triggered')
if (ability.kind !== 'triggered') return
assert.deepEqual(ability.effects, [{
op: 'return_to_battlefield',
target: { kind: 'self' },
tapped: false,
transformed: undefined,
counters: { counter: 'finality', amount: { kind: 'number', value: 1 } },
}])
})

647
backend/test/game.test.ts Normal file
View File

@@ -0,0 +1,647 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { Game, GameError } from '../src/game/game.js'
import type { Ability, Effect } from '../src/effects/types.js'
import type { CardDefinition } from '../src/game/types.js'
function card(name: string, overrides: Partial<CardDefinition> = {}): CardDefinition {
return {
oracleId: name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
name,
typeLine: 'Creature — Test',
manaValue: 0,
colors: [],
abilities: [],
...overrides,
}
}
function creature(name: string, power: number, toughness: number, abilities: Ability[] = []): CardDefinition {
return card(name, { typeLine: 'Creature — Test', power, toughness, abilities })
}
function spell(name: string, effects: Effect[], manaCost = ''): CardDefinition {
return card(name, { typeLine: 'Instant', manaCost, manaValue: 0, abilities: [{ kind: 'spell', effects, optional: false, text: name }] })
}
function land(name: string, color: string): CardDefinition {
return card(name, {
typeLine: `Basic Land — ${name}`,
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: [`{${color}}`] } }],
optional: false,
text: `{T}: Add {${color}}.`,
}],
})
}
function setup(players: { id: string; deck?: CardDefinition[]; life?: number }[]): Game {
const game = new Game({
seed: 7,
startingHandSize: 0,
players: players.map(player => ({ id: player.id, life: player.life, deck: player.deck ?? [card('Filler')] })),
})
return game
}
test('turns start at the first main phase, draw opening hands, and pass to the next player', () => {
const forest = land('Forest', 'G')
const game = new Game({
seed: 1,
startingHandSize: 7,
players: [
{ id: 'p1', deck: Array.from({ length: 10 }, () => forest) },
{ id: 'p2', deck: Array.from({ length: 10 }, () => forest) },
],
})
game.start()
assert.equal(game.turn, 1)
assert.equal(game.activePlayer, 'p1')
assert.equal(game.phase, 'precombat_main')
assert.equal(game.step, 'main')
assert.equal(game.priority, 'p1')
assert.equal(game.getPlayer('p1').life, 40)
assert.equal(game.getPlayer('p1').hand.length, 7)
assert.equal(game.getPlayer('p1').library.length, 3)
game.endTurn('p1')
assert.equal(game.turn, 2)
assert.equal(game.activePlayer, 'p2')
assert.equal(game.getPlayer('p2').hand.length, 8)
assert.equal(game.getPlayer('p1').hand.length, 7)
})
test('passing priority twice advances from the main phase into combat', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
game.pass('p1')
assert.equal(game.priority, 'p2')
game.pass('p2')
assert.equal(game.phase, 'combat')
assert.equal(game.step, 'declare_attackers')
assert.equal(game.priority, 'p1')
})
test('a spell goes on the stack, auto-taps mana, and resolves its compiled effect', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const mountain = game.addCard('p1', land('Mountain', 'R'), 'battlefield')
const bolt = game.addCard('p1', spell('Lightning Bolt', [
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
], '{R}'), 'hand')
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
assert.equal(game.stack.length, 1)
assert.equal(mountain.tapped, true)
assert.equal(game.priority, 'p2')
game.resolveStack()
assert.equal(game.stack.length, 0)
assert.equal(game.getPlayer('p2').life, 37)
assert.ok(game.getPlayer('p1').graveyard.includes(bolt.id))
})
test('permanents can be repositioned by their controller and positions are cleared on zone changes', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
game.movePermanent('p1', bear.id, 0.25, 0.75)
assert.deepEqual(bear.position, { x: 0.25, y: 0.75 })
game.movePermanent('p1', bear.id, -1, 2)
assert.deepEqual(bear.position, { x: 0, y: 1 })
assert.throws(() => game.movePermanent('p2', bear.id, 0.5, 0.5), /control/)
game.moveToZone(bear, 'graveyard')
assert.equal(bear.position, undefined)
})
test('enters triggers from compiled card code fire and resolve through the stack', () => {
const soulWarden = card('Soul Warden', {
typeLine: 'Creature — Human Cleric',
power: 1,
toughness: 1,
colors: ['W'],
abilities: [{
kind: 'triggered',
event: {
kind: 'enters',
subject: { kind: 'object', selector: { other: true, types: ['creature'] }, mode: 'each' },
},
effects: [{ op: 'life', player: 'you', amount: { kind: 'number', value: 1 }, mode: 'gain' }],
optional: false,
text: 'Whenever another creature enters, you gain 1 life.',
}],
})
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
game.addCard('p1', soulWarden, 'battlefield')
const elves = game.addCard('p1', creature('Llanowar Elves', 1, 1), 'hand')
game.castSpell('p1', elves.id)
game.resolveStack()
assert.equal(game.getPlayer('p1').life, 41)
assert.ok(game.getPlayer('p1').battlefield.includes(elves.id))
})
test('activated mana abilities produce mana and creatures have summoning sickness', () => {
const solRing = card('Sol Ring', {
typeLine: 'Artifact',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{C}', '{C}'] } }],
optional: false,
text: '{T}: Add {C}{C}.',
}],
})
const game = setup([{ id: 'p1', deck: Array.from({ length: 5 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 5 }, () => card('Filler')) }])
game.start()
const ring = game.addCard('p1', solRing, 'battlefield')
const elves = game.addCard('p1', creature('Llanowar Elves', 1, 1, [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{G}'] } }],
optional: false,
text: '{T}: Add {G}.',
}]), 'battlefield')
game.activateAbility('p1', ring.id, 0)
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 2 })
assert.equal(ring.tapped, true)
assert.throws(() => game.activateAbility('p1', elves.id, 0), GameError)
game.endTurn('p1')
game.endTurn('p2')
assert.equal(elves.tapped, false)
game.activateAbility('p1', elves.id, 0)
assert.equal(game.getPlayer('p1').manaPool.G, 1)
})
test('static pump effects apply to matching creatures only', () => {
const anthem = card('Glorious Anthem', {
typeLine: 'Enchantment',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'static',
effects: [{
op: 'pump',
target: { kind: 'object', selector: { controller: 'you', types: ['creature'] }, mode: 'each' },
power: { kind: 'number', value: 1 },
toughness: { kind: 'number', value: 1 },
}],
text: 'Creatures you control get +1/+1.',
}],
})
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const anthemObject = game.addCard('p1', anthem, 'battlefield')
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
const enemy = game.addCard('p2', creature('Enemy Bear', 2, 2), 'battlefield')
assert.equal(game.getPower(bear), 3)
assert.equal(game.getToughness(bear), 3)
assert.equal(game.getPower(enemy), 2)
assert.equal(game.getPower(anthemObject), 0)
})
test('temporary pump effects expire at end of turn', () => {
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
game.start()
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
const growth = game.addCard('p1', spell('Giant Growth', [{
op: 'pump',
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
power: { kind: 'number', value: 3 },
toughness: { kind: 'number', value: 3 },
duration: 'until_end_of_turn',
}]), 'hand')
game.castSpell('p1', growth.id, { targets: [{ kind: 'object', id: bear.id }] })
game.resolveStack()
assert.equal(game.getPower(bear), 5)
assert.equal(game.getToughness(bear), 5)
game.endTurn('p1')
assert.equal(game.getPower(bear), 2)
})
test('"until the end of your next turn" lasts through the controller next turn', () => {
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
game.start()
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
const growth = game.addCard('p1', spell('Growth', [{
op: 'pump',
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
power: { kind: 'number', value: 3 },
toughness: { kind: 'number', value: 3 },
duration: 'until_end_of_your_next_turn',
}]), 'hand')
game.castSpell('p1', growth.id, { targets: [{ kind: 'object', id: bear.id }] })
game.resolveStack()
assert.equal(game.getPower(bear), 5)
game.endTurn('p1')
assert.equal(game.getPower(bear), 5)
game.endTurn('p2')
assert.equal(game.getPower(bear), 5)
game.endTurn('p1')
assert.equal(game.getPower(bear), 2)
})
test('combat damage kills creatures and moves them to the graveyard', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
const attacker = game.addCard('p1', creature('Attacker', 2, 2), 'battlefield')
const blocker = game.addCard('p2', creature('Blocker', 2, 2), 'battlefield')
game.start()
game.declareAttackers('p1', [{ attackerId: attacker.id, defenderId: 'p2' }])
assert.equal(game.step, 'declare_blockers')
assert.equal(game.priority, 'p2')
assert.equal(attacker.tapped, true)
game.declareBlockers('p2', [{ blockerId: blocker.id, attackerId: attacker.id }])
game.resolveCombatDamage()
assert.equal(game.getPlayer('p2').life, 40)
assert.equal(game.step, 'end_combat')
assert.ok(game.getPlayer('p1').graveyard.includes(attacker.id))
assert.ok(game.getPlayer('p2').graveyard.includes(blocker.id))
})
test('unblocked attackers deal damage to the defending player', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
const attacker = game.addCard('p1', creature('Attacker', 3, 3), 'battlefield')
game.start()
game.declareAttackers('p1', [{ attackerId: attacker.id, defenderId: 'p2' }])
game.declareBlockers('p2', [])
game.resolveCombatDamage()
assert.equal(game.getPlayer('p2').life, 37)
})
test('counterspell counters a spell on the stack', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
game.addCard('p1', land('Mountain', 'R'), 'battlefield')
game.addCard('p2', land('Island', 'U'), 'battlefield')
game.addCard('p2', land('Island', 'U'), 'battlefield')
const bolt = game.addCard('p1', spell('Lightning Bolt', [
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
], '{R}'), 'hand')
const counterspell = game.addCard('p2', spell('Counterspell', [
{ op: 'counter', what: 'spell', target: { kind: 'spell', selector: { types: [] }, mode: 'target' } },
], '{U}{U}'), 'hand')
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
game.castSpell('p2', counterspell.id)
assert.equal(game.stack.length, 2)
game.resolveStack()
assert.equal(game.getPlayer('p2').life, 40)
assert.equal(game.stack.length, 0)
assert.ok(game.getPlayer('p1').graveyard.includes(bolt.id))
assert.ok(game.getPlayer('p2').graveyard.includes(counterspell.id))
})
test('activated abilities create tokens that enter the battlefield', () => {
const maker = card('Goblin Maker', {
typeLine: 'Artifact',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{
op: 'create_token',
player: 'you',
amount: { kind: 'number', value: 1 },
token: { name: 'Goblin', types: ['creature'], subtypes: ['goblin'], colors: ['R'], power: { kind: 'number', value: 1 }, toughness: { kind: 'number', value: 1 } },
}],
optional: false,
text: '{T}: Create a 1/1 Goblin.',
}],
})
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const source = game.addCard('p1', maker, 'battlefield')
game.activateAbility('p1', source.id, 0)
assert.equal(game.stack.length, 1)
game.resolveStack()
const tokens = game.getPlayer('p1').battlefield.map(id => game.getObject(id)).filter(object => object.isToken)
assert.equal(tokens.length, 1)
assert.equal(tokens[0].definition.name, 'Goblin')
assert.equal(game.getPower(tokens[0]), 1)
})
test('search effects find cards in the library and put them onto the battlefield tapped', () => {
const forest = land('Forest', 'G')
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const found = game.addCard('p1', forest, 'library')
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
op: 'search',
player: 'you',
selector: { types: ['land'], supertypes: ['basic'] },
amount: { kind: 'number', value: 1 },
destination: 'battlefield',
tapped: true,
shuffle: true,
}]), 'hand')
game.castSpell('p1', rampantGrowth.id)
game.resolveStack()
assert.ok(game.getPlayer('p1').battlefield.includes(found.id))
assert.equal(found.tapped, true)
})
test('search effects let the player pick among multiple matching cards', () => {
const forest = land('Forest', 'G')
const island = land('Island', 'U')
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const forestObject = game.addCard('p1', forest, 'library')
const islandObject = game.addCard('p1', island, 'library')
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
op: 'search',
player: 'you',
selector: { types: ['land'], supertypes: ['basic'] },
amount: { kind: 'number', value: 1 },
destination: 'battlefield',
tapped: true,
shuffle: true,
}]), 'hand')
game.castSpell('p1', rampantGrowth.id)
game.resolveStack()
assert.equal(game.pendingSearch?.playerId, 'p1')
assert.deepEqual(
game.searchCandidates('p1').map(object => object.id).sort(),
[forestObject.id, islandObject.id].sort(),
)
assert.equal(forestObject.zone, 'library')
assert.throws(() => game.pass('p1'), GameError)
game.chooseSearchCard('p1', islandObject.id)
assert.equal(game.pendingSearch, undefined)
assert.ok(game.getPlayer('p1').battlefield.includes(islandObject.id))
assert.equal(islandObject.tapped, true)
assert.ok(game.getPlayer('p1').library.includes(forestObject.id))
})
test('autoAdvance stops instead of passing while a search needs a pick', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
game.addCard('p1', land('Forest', 'G'), 'library')
game.addCard('p1', land('Island', 'U'), 'library')
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
op: 'search',
player: 'you',
selector: { types: ['land'], supertypes: ['basic'] },
amount: { kind: 'number', value: 1 },
destination: 'battlefield',
tapped: true,
shuffle: true,
}]), 'hand')
game.castSpell('p1', rampantGrowth.id)
game.autoAdvance()
assert.equal(game.pendingSearch?.playerId, 'p1')
assert.equal(game.priority, 'p1')
})
test('static replacement effects make permanents enter tapped with counters', () => {
const slow = creature('Slow Bear', 2, 2, [{
kind: 'static',
effects: [{ op: 'enters_tapped', target: { kind: 'self' } }],
text: 'This enters tapped.',
}, {
kind: 'static',
effects: [{
op: 'enters_with_counters',
target: { kind: 'self' },
counter: '+1/+1',
amount: { kind: 'number', value: 1 },
}],
text: 'This enters with a +1/+1 counter.',
}])
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const bear = game.addCard('p1', slow, 'hand')
game.castSpell('p1', bear.id)
game.resolveStack()
assert.equal(bear.tapped, true)
assert.equal(bear.counters['+1/+1'], 1)
assert.equal(game.getPower(bear), 3)
assert.equal(game.getToughness(bear), 3)
})
test('a player who runs out of cards loses and the last player wins', () => {
const game = new Game({
seed: 3,
startingHandSize: 0,
players: [
{ id: 'p1', deck: [card('Filler')] },
{ id: 'p2', deck: [] },
],
})
game.start()
game.endTurn('p1')
assert.equal(game.status, 'finished')
assert.equal(game.winner, 'p1')
assert.equal(game.getPlayer('p2').lost, true)
})
test('lethal damage to a player ends the game', () => {
const game = setup([{ id: 'p1' }, { id: 'p2', life: 3 }])
game.start()
game.addCard('p1', land('Mountain', 'R'), 'battlefield')
const bolt = game.addCard('p1', spell('Lightning Bolt', [
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
], '{R}'), 'hand')
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
game.resolveStack()
assert.equal(game.status, 'finished')
assert.equal(game.winner, 'p1')
assert.equal(game.getPlayer('p2').life, 0)
})
test('a failed mana payment leaves mana sources untapped and the pool unchanged', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const mountain = game.addCard('p1', land('Mountain', 'R'), 'battlefield')
const expensive = game.addCard('p1', spell('Expensive Spell', [], '{R}{R}'), 'hand')
assert.throws(() => game.castSpell('p1', expensive.id), GameError)
assert.equal(mountain.tapped, false)
assert.equal(game.getPlayer('p1').manaPool.R, 0)
assert.ok(game.getPlayer('p1').hand.includes(expensive.id))
})
test('phyrexian mana can be paid with exactly enough life', () => {
const game = setup([{ id: 'p1', life: 2 }, { id: 'p2' }])
game.start()
const spellCard = game.addCard('p1', spell('Gitaxian Probe', [], '{W/P}'), 'hand')
assert.doesNotThrow(() => game.castSpell('p1', spellCard.id))
assert.equal(game.getPlayer('p1').life, 0)
assert.equal(game.status, 'finished')
assert.equal(game.winner, 'p2')
})
test('an unless cost auto-taps the mana sources of the payer', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const bear = game.addCard('p2', creature('Grizzly Bears', 2, 2), 'battlefield')
const forests = [
game.addCard('p2', land('Forest', 'G'), 'battlefield'),
game.addCard('p2', land('Forest', 'G'), 'battlefield'),
]
const edict = game.addCard('p1', spell('Edict', [{
op: 'sacrifice',
player: 'opponent',
target: { kind: 'object', selector: { types: ['creature'] } },
unless: { kind: 'mana', symbols: '{2}' },
}]), 'hand')
game.castSpell('p1', edict.id, {
targets: [{ kind: 'player', id: 'p2' }, { kind: 'object', id: bear.id }],
})
game.resolveStack()
assert.equal(bear.zone, 'battlefield')
assert.ok(forests.every(forest => forest.tapped))
assert.equal(game.getPlayer('p2').manaPool.G, 0)
})
test('canPlayCard reports legal lands and spells for the player with priority', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const forest = game.addCard('p1', land('Forest', 'G'), 'hand')
const bear = game.addCard('p1', card('Grizzly Bears', {
typeLine: 'Creature — Bear',
power: 2,
toughness: 2,
manaCost: '{G}',
}), 'hand')
assert.equal(game.canPlayCard('p1', forest.id), true)
assert.equal(game.canPlayCard('p1', bear.id), false)
assert.equal(game.canPlayCard('p2', forest.id), false)
game.playLand('p1', forest.id)
assert.equal(game.canPlayCard('p1', bear.id), true)
})
test('autoAdvance skips empty phases and stops when someone can act', () => {
const expensive = card('Expensive', { manaCost: '{5}' })
const game = new Game({
seed: 3,
startingHandSize: 0,
players: [
{ id: 'p1', deck: [expensive] },
{ id: 'p2', deck: [expensive] },
],
})
game.start()
game.addCard('p1', land('Forest', 'G'), 'battlefield')
// The only action is a mana ability, which should not hold the phase open.
game.autoAdvance()
assert.equal(game.turn, 2)
assert.equal(game.activePlayer, 'p2')
assert.equal(game.phase, 'precombat_main')
assert.equal(game.priority, 'p2')
const hasty = creature('Hasty', 2, 2, [{ kind: 'keyword', keyword: 'Haste' }])
game.addCard('p2', hasty, 'battlefield')
game.autoAdvance()
assert.equal(game.turn, 2)
assert.equal(game.phase, 'combat')
assert.equal(game.step, 'declare_attackers')
assert.equal(game.priority, 'p2')
})
test('every defending player declares blocks before combat damage in multiplayer', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }, { id: 'p3' }])
game.start()
const first = game.addCard('p1', creature('First Attacker', 2, 2), 'battlefield')
const second = game.addCard('p1', creature('Second Attacker', 3, 3), 'battlefield')
first.enteredTurn = 0
second.enteredTurn = 0
game.declareAttackers('p1', [
{ attackerId: first.id, defenderId: 'p2' },
{ attackerId: second.id, defenderId: 'p3' },
])
assert.equal(game.step, 'declare_blockers')
game.declareBlockers('p2', [])
assert.equal(game.step, 'declare_blockers')
assert.equal(game.priority, 'p3')
game.declareBlockers('p3', [])
assert.equal(game.step, 'combat_damage')
game.resolveCombatDamage()
assert.equal(game.getPlayer('p2').life, 38)
assert.equal(game.getPlayer('p3').life, 37)
})
test('counter-removal costs are paid and fail when counters run out', () => {
const vessel = card('Spore Vessel', {
typeLine: 'Artifact',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'remove_counters', counter: 'spore', amount: { kind: 'number', value: 2 } }],
effects: [{ op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } }],
optional: false,
text: 'Remove two spore counters from this: Draw a card.',
}],
})
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2' }])
game.start()
const source = game.addCard('p1', vessel, 'battlefield')
source.counters.spore = 3
game.activateAbility('p1', source.id, 0)
game.resolveStack()
assert.equal(source.counters.spore, 1)
assert.equal(game.getPlayer('p1').hand.length, 1)
assert.throws(() => game.activateAbility('p1', source.id, 0), GameError)
assert.equal(source.counters.spore, 1)
})

View File

@@ -0,0 +1,89 @@
import assert from 'node:assert/strict'
import { createServer } from 'node:http'
import type { AddressInfo } from 'node:net'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import {
PlaymatError,
cardImage,
deletePlaymatImage,
playmatImage,
scryfallArtUrl,
scryfallImageUrl,
storePlaymatImage,
} from '../src/images.js'
const ART = Buffer.from([0xff, 0xd8, 0xff, 0xd9])
test('only https URLs on the Scryfall image host are accepted', () => {
assert.equal(
scryfallImageUrl('https://cards.scryfall.io/normal/front/a/b/art.jpg?123'),
'https://cards.scryfall.io/normal/front/a/b/art.jpg?123',
)
assert.equal(scryfallImageUrl('http://cards.scryfall.io/art.jpg'), undefined)
assert.equal(scryfallImageUrl('https://example.com/art.jpg'), undefined)
assert.equal(scryfallImageUrl('not a url'), undefined)
assert.equal(scryfallImageUrl(undefined), undefined)
})
test('playmat art swaps the card image for the wide Scryfall crop', () => {
assert.equal(
scryfallArtUrl('https://cards.scryfall.io/normal/front/a/b/art.jpg?123'),
'https://cards.scryfall.io/art_crop/front/a/b/art.jpg?123',
)
assert.equal(scryfallArtUrl(undefined), undefined)
assert.equal(scryfallArtUrl('https://example.com/normal/art.jpg'), undefined)
})
test('uploaded playmats are stored, served and deleted', async () => {
const dir = await mkdtemp(join(tmpdir(), 'commander-playmats-'))
const jpeg = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff]), Buffer.from('pixels')])
try {
const id = await storePlaymatImage(`data:image/jpeg;base64,${jpeg.toString('base64')}`, dir)
assert.deepEqual(await playmatImage(id, dir), jpeg)
await deletePlaymatImage(id, dir)
assert.equal(await playmatImage(id, dir), undefined)
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('uploaded playmats must be JPEG data URLs with a JPEG signature', async () => {
const dir = await mkdtemp(join(tmpdir(), 'commander-playmats-'))
try {
await assert.rejects(storePlaymatImage('data:image/png;base64,AAAA', dir), PlaymatError)
await assert.rejects(storePlaymatImage('data:image/jpeg;base64,AAAA', dir), PlaymatError)
await assert.rejects(storePlaymatImage('not an image', dir), PlaymatError)
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('card art is downloaded once and then served from the disk cache', async () => {
let requests = 0
const server = createServer((_request, response) => {
requests++
response.writeHead(200, { 'Content-Type': 'image/jpeg' })
response.end(ART)
})
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
const dir = await mkdtemp(join(tmpdir(), 'commander-images-'))
try {
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/art.jpg`
assert.deepEqual(await cardImage('card-id', url, dir), ART)
assert.deepEqual(await readFile(join(dir, 'card-id.jpg')), ART)
assert.deepEqual(await cardImage('card-id', url, dir), ART)
assert.equal(requests, 1)
} finally {
await new Promise(resolve => server.close(resolve))
await rm(dir, { recursive: true, force: true })
}
})

View File

@@ -0,0 +1,92 @@
import assert from 'node:assert/strict'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import type { Card } from '../src/cards.js'
import { formatCard } from '../src/effects/format.js'
import {
compileImplementation,
deleteOverride,
readAllOverrides,
readOverride,
writeOverride,
} from '../src/effects/implementations.js'
import { parsePseudoCard, PseudoParseError } from '../src/effects/pseudo.js'
const CARD: Card = {
oracle_id: '00000000-0000-4000-8000-000000000001',
name: 'Test Card',
layout: 'normal',
cmc: 1,
type_line: 'Creature — Human',
colors: [],
color_identity: [],
keywords: [],
}
const SOURCE = `on enters(this):
choose 1:
1. exile(target other creature you own); schedule(next_end_step):
return_to_battlefield(the chosen target)
static:
grant_ability(each enchanted land):
on upkeep(you) (may):
pay({W}{W})
if you do:
gain_life(you, 1)`
test('pseudocode round-trips through the compiler and formatter', () => {
const compiled = compileImplementation(CARD, SOURCE)
assert.equal(compiled.manual, true)
assert.equal(compiled.status, 'supported')
const rendered = formatCard(compiled)
const reparsed = compileImplementation(CARD, rendered)
assert.equal(formatCard(reparsed), rendered)
assert.equal(reparsed.abilities.length, 2)
const [triggered] = reparsed.abilities
assert.equal(triggered.kind, 'triggered')
if (triggered.kind !== 'triggered') return
assert.equal(triggered.effects[0].op, 'modal')
if (triggered.effects[0].op !== 'modal') return
assert.equal(triggered.effects[0].modes[0][1].op, 'schedule')
const staticAbility = reparsed.abilities[1]
assert.equal(staticAbility.kind, 'static')
if (staticAbility.kind !== 'static') return
assert.equal(staticAbility.effects[0].op, 'grant_ability')
if (staticAbility.effects[0].op !== 'grant_ability') return
assert.equal(staticAbility.effects[0].ability.kind, 'triggered')
})
test('invalid pseudocode reports its line', () => {
assert.throws(
() => parsePseudoCard('spell:\n draw(you)'),
(error: unknown) => error instanceof PseudoParseError && error.line === 2,
)
})
test('manual implementations persist one file per card', async (t) => {
const dir = await mkdtemp(join(tmpdir(), 'commander-overrides-'))
const previous = process.env.CARD_OVERRIDES_DIR
process.env.CARD_OVERRIDES_DIR = dir
t.after(async () => {
if (previous === undefined) delete process.env.CARD_OVERRIDES_DIR
else process.env.CARD_OVERRIDES_DIR = previous
await rm(dir, { recursive: true, force: true })
})
await writeOverride(CARD.oracle_id, SOURCE)
const stored = await readOverride(CARD.oracle_id)
assert.equal(stored?.source, `${SOURCE}\n`)
assert.equal((await readAllOverrides()).get(CARD.oracle_id), `${SOURCE}\n`)
const compiled = compileImplementation(CARD, stored!.source)
assert.equal(compiled.manual, true)
assert.equal(compiled.status, 'supported')
await deleteOverride(CARD.oracle_id)
assert.equal(await readOverride(CARD.oracle_id), undefined)
})

View File

@@ -0,0 +1,38 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { findCardByName } from '../src/cards.js'
import { createMatch, getMatchView, joinMatch, leaveMatch, setDeck, startMatch } from '../src/game/rooms.js'
function deck(commanderName: string) {
const commander = findCardByName(commanderName)
const forest = findCardByName('Forest')
assert.ok(commander && forest)
return {
commander: commander.oracle_id,
cards: Array.from({ length: 99 }, () => forest.oracle_id),
}
}
test('lobby decks can be swapped and invalid decks are rejected', () => {
const first = deck("Atraxa, Praetors' Voice")
const second = deck('Kenrith, the Returned King')
const { matchId, token } = createMatch('Host', first, 2)
setDeck(matchId, token, second)
assert.equal(getMatchView(matchId, token).players[0].commander?.name, 'Kenrith, the Returned King')
assert.throws(() => setDeck(matchId, token, { ...second, cards: [] }), /100/)
assert.equal(getMatchView(matchId, token).players[0].commander?.name, 'Kenrith, the Returned King')
})
test('leaving a started game forfeits the seat instead of erroring', () => {
const host = createMatch('Host', deck("Atraxa, Praetors' Voice"), 2)
const guest = joinMatch(host.matchId, 'Guest', deck('Kenrith, the Returned King'))
startMatch(host.matchId, host.token)
leaveMatch(host.matchId, host.token)
const view = getMatchView(host.matchId, guest.token)
assert.equal(view.status, 'finished')
assert.equal(view.players.find(player => player.id === host.playerId)?.lost, true)
})

View File

@@ -0,0 +1,117 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import type { Card } from '../src/cards.js'
import { cleanTranslation, TranslationError, translateCard } from '../src/effects/translate.js'
const CARD: Card = {
oracle_id: '00000000-0000-4000-8000-000000000002',
name: 'Test Spell',
layout: 'normal',
cmc: 2,
type_line: 'Sorcery',
colors: ['U'],
color_identity: ['U'],
keywords: [],
oracle_text: 'Draw two cards.',
}
interface RequestBody {
model: string
messages: Array<{ role: string; content: string }>
temperature: number
max_tokens: number
}
function fakeOpenRouter(content: string) {
let body: RequestBody | undefined
let headers: Record<string, string> | undefined
const fetchImpl = async (_input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
body = JSON.parse(String(init?.body)) as RequestBody
headers = init?.headers as Record<string, string>
return new Response(JSON.stringify({ choices: [{ message: { content } }] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
return {
fetchImpl: fetchImpl as typeof fetch,
get body() {
assert.ok(body)
return body
},
get headers() {
assert.ok(headers)
return headers
},
}
}
test('translation asks for pseudocode only and validates the answer', async () => {
const fake = fakeOpenRouter('spell:\n draw(you, 2)')
const source = await translateCard(CARD, {
apiKey: 'test-key',
model: 'test/model',
fetch: fake.fetchImpl,
})
assert.equal(source, 'spell:\n draw(you, 2)')
assert.equal(fake.body.model, 'test/model')
assert.equal(fake.body.temperature, 0)
assert.equal(fake.body.max_tokens, 700)
assert.equal(fake.headers.Authorization, 'Bearer test-key')
assert.match(fake.body.messages[0].content, /pseudocode only/i)
assert.match(fake.body.messages[0].content, /Never invent an operation/)
assert.match(fake.body.messages[1].content, /Draw two cards\./)
})
test('a model code fence is removed before saving', async () => {
const fake = fakeOpenRouter('```\nspell:\n draw(you, 2)\n```')
const source = await translateCard(CARD, {
apiKey: 'test-key',
model: 'test/model',
fetch: fake.fetchImpl,
})
assert.equal(source, 'spell:\n draw(you, 2)')
assert.equal(cleanTranslation(' spell:\n draw(you, 2) '), 'spell:\n draw(you, 2)')
})
test('prose instead of pseudocode is rejected', async () => {
const fake = fakeOpenRouter('Here is the translated card. It draws two cards.')
await assert.rejects(
translateCard(CARD, { apiKey: 'test-key', model: 'test/model', fetch: fake.fetchImpl }),
(error: unknown) => error instanceof TranslationError && /valid pseudocode/.test(error.message),
)
})
test('missing API key is reported before any request', async () => {
let called = false
const fetchImpl = async () => {
called = true
return new Response('{}')
}
await assert.rejects(
translateCard(CARD, { apiKey: '', fetch: fetchImpl as typeof fetch }),
(error: unknown) => error instanceof TranslationError && error.status === 503,
)
assert.equal(called, false)
})
test('multi-face cards receive their face names in the prompt', async () => {
const faces: Card = {
...CARD,
layout: 'transform',
card_faces: [
{ name: 'Front', type_line: 'Creature', oracle_text: 'When this enters, draw a card.', colors: [] },
{ name: 'Back', type_line: 'Creature', oracle_text: 'Flying', colors: [] },
],
}
const fake = fakeOpenRouter('## Front\non enters(this):\n draw(you, 1)\n\n## Back\nkeyword Flying')
const source = await translateCard(faces, {
apiKey: 'test-key',
model: 'test/model',
fetch: fake.fetchImpl,
})
assert.equal(source, '## Front\non enters(this):\n draw(you, 1)\n\n## Back\nkeyword Flying')
assert.match(fake.body.messages[1].content, /## Front/)
assert.match(fake.body.messages[1].content, /## Back/)
})