First commit
This commit is contained in:
17
.env.example
Normal file
17
.env.example
Normal file
@@ -0,0 +1,17 @@
|
||||
# Public URL the browser uses to reach the API.
|
||||
NUXT_PUBLIC_API_BASE=http://localhost:4000
|
||||
|
||||
# Browser origin(s) allowed to call the API, comma separated.
|
||||
CORS_ORIGIN=http://localhost:3000
|
||||
|
||||
# MongoDB connection. Compose reaches a MongoDB running on the host machine by default.
|
||||
# Set this only when using a different database.
|
||||
# MONGODB_URI=mongodb://localhost:27017/commander
|
||||
|
||||
# OpenRouter key and model for the card editor's "Draft with AI" button.
|
||||
# Leave the key empty to disable the route (it returns 503).
|
||||
OPENROUTER_API_KEY=
|
||||
OPENROUTER_MODEL=google/gemini-2.5-flash-lite
|
||||
|
||||
# Host port used by docker-compose.yml (production).
|
||||
FRONTEND_PORT=3000
|
||||
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
.env
|
||||
.DS_Store
|
||||
node_modules
|
||||
29
AGENTS.md
Normal file
29
AGENTS.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# AGENTS.md
|
||||
|
||||
Online multiplayer Magic: The Gathering (Commander) emulator: Nuxt frontend + Fastify API with a synchronous rules engine that executes compiled card effects.
|
||||
|
||||
## Layout
|
||||
|
||||
- `backend/` — Node 24, Fastify 5, TypeScript (ESM, NodeNext). `src/effects/` is the oracle-text compiler/pseudocode DSL, `src/game/` the rules engine and in-memory match manager.
|
||||
- `frontend/` — Nuxt 4 / Vue 3, sources under `app/`.
|
||||
- `backend/docs/card-effects.md` and `backend/docs/game-engine.md` are the detailed references for those subsystems; `README.md` has the full API and config tables.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.dev.yml up --build # full dev stack (:3000, :4000)
|
||||
cd backend && npm install && npm run dev # API only
|
||||
cd frontend && npm install && npm run dev # UI only
|
||||
cd backend && npm test # all backend tests
|
||||
cd backend && npm run import:cards # Scryfall bulk data -> data/cards.json
|
||||
cd backend && npm run compile:cards # oracle text -> data/card-effects.json + pseudo.txt
|
||||
```
|
||||
|
||||
## Things to know
|
||||
|
||||
- Backend imports need `.js` extensions (`NodeNext`) even though sources are `.ts`.
|
||||
- `backend/data/cards.json` (~21 MB) and `card-effects.json` are generated, not committed; run the import/compile scripts after changing the importer or compiler. Missing card data makes `/cards` return `503`.
|
||||
- Manual card implementations live in `backend/data/card-overrides/` (one file per card, pseudocode DSL) and take precedence over generated output when compiling.
|
||||
- The effect compiler is conservative: unparseable oracle lines become `unsupported` with original text — never guess or silently drop them.
|
||||
- Matches are in memory and lost on restart; accounts, saved decks, playmat preferences, and per-deck card backs are in MongoDB through `backend/src/accounts.ts`. Game seats still use a per-seat token in the frontend's `sessionStorage`; the account login token is in a cookie so the server can gate pages.
|
||||
- Keep style of surrounding code: 2-space indent, single quotes. No linter or formatter is configured.
|
||||
309
README.md
Normal file
309
README.md
Normal file
@@ -0,0 +1,309 @@
|
||||
# Commander
|
||||
|
||||
Online multiplayer Magic: The Gathering (Commander) emulator.
|
||||
|
||||
This repository holds a Nuxt frontend, a Fastify API, and a working Magic rules
|
||||
engine that executes the compiled card effects. You can build or import a
|
||||
Commander deck in the browser and play a 2–4 player match against other clients.
|
||||
|
||||
## Stack
|
||||
|
||||
- **frontend/** — Nuxt 4, Vue 3, TypeScript, server-side rendering
|
||||
- **backend/** — Node 24, Fastify 5, TypeScript, Mongoose
|
||||
- **MongoDB** — accounts, saved decks, playmat and card-back preferences
|
||||
- **Docker Compose** — hot-reloading development stack and standalone production images
|
||||
|
||||
## Requirements
|
||||
|
||||
- Docker with Compose v2
|
||||
- Node 24 + npm only if you want to run the apps outside Docker
|
||||
- MongoDB reachable on `localhost:27017` (the Compose backend uses host
|
||||
networking to reach it)
|
||||
|
||||
## Development
|
||||
|
||||
Start both services with hot reload:
|
||||
|
||||
```bash
|
||||
cp .env.example .env # optional: adjust public URLs and ports
|
||||
docker compose -f docker-compose.dev.yml up --build
|
||||
```
|
||||
|
||||
| Service | URL |
|
||||
| -------- | ---------------------------- |
|
||||
| Frontend | http://localhost:3000 |
|
||||
| API | http://localhost:4000 |
|
||||
| Health | http://localhost:4000/health |
|
||||
| MongoDB | mongodb://localhost:27017 |
|
||||
|
||||
Source directories are bind-mounted, so edits reload automatically. Dependencies
|
||||
live in named volumes and are synced on container start. If the volumes get into
|
||||
a bad state, reset them with:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.dev.yml down -v
|
||||
```
|
||||
|
||||
Stop the stack with `docker compose -f docker-compose.dev.yml down`.
|
||||
|
||||
### Without Docker
|
||||
|
||||
```bash
|
||||
# terminal 1
|
||||
cd backend && npm install && npm run dev
|
||||
|
||||
# terminal 2
|
||||
cd frontend && npm install && npm run dev
|
||||
```
|
||||
|
||||
The backend listens on port `4000` and the frontend on `3000` by default. It
|
||||
connects to MongoDB at `mongodb://localhost:27017/commander`; start a local
|
||||
MongoDB or set `MONGODB_URI` to point somewhere else.
|
||||
|
||||
## Card data
|
||||
|
||||
Cards come from Scryfall's
|
||||
[Oracle Cards bulk export](https://scryfall.com/docs/api/bulk-data) — one card
|
||||
per Oracle ID, filtered to cards legal in Commander.
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm run import:cards
|
||||
```
|
||||
|
||||
This downloads the bulk file and writes `backend/data/cards.json` (about 21 MB,
|
||||
not committed). It stores each card's rarity and the formats it is legal in, so
|
||||
re-run it after pulling changes to the importer. Re-run it whenever you want a
|
||||
fresh card pool.
|
||||
|
||||
In the dev stack the file is visible through the bind mount. For production, run
|
||||
the import before `docker compose build` so the API image includes the data. If
|
||||
the file is missing, the card endpoints return `503` with a reminder to run it.
|
||||
|
||||
Card art is not bundled. The first time a card's art is requested, the API
|
||||
downloads its image from Scryfall and stores it in `backend/data/images/`. The
|
||||
production Compose stack keeps that directory in the `card_images` named volume,
|
||||
so the cache survives restarts. Delete the directory to reclaim the space;
|
||||
images are downloaded again when needed.
|
||||
|
||||
## Card effects
|
||||
|
||||
Oracle text is compiled into a machine-readable effect AST for the game engine.
|
||||
The compiler is conservative: a line it cannot parse is marked `unsupported`
|
||||
with its original text, never guessed.
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm run compile:cards # data/card-effects.json + data/card-effects.pseudo.txt
|
||||
npm test
|
||||
```
|
||||
|
||||
`data/card-effects.pseudo.txt` is the human-readable pseudocode view. The
|
||||
pseudocode is also an input format: the frontend editor saves one override file
|
||||
per card under `backend/data/card-overrides/`, and `npm run compile:cards`
|
||||
validates those files and uses them instead of generated output. See
|
||||
[backend/docs/card-effects.md](backend/docs/card-effects.md) for the DSL,
|
||||
current coverage, and how to add support for more cards.
|
||||
|
||||
The `/cards` page has an **Editor** view and a **Guide** view that summarizes the
|
||||
pseudocode syntax. **Draft with AI** sends the selected card's oracle text to an
|
||||
OpenRouter model and loads the returned pseudocode into the editor without
|
||||
saving it. The model is instructed to answer with pseudocode only — no
|
||||
explanations, Markdown or code fences — and the answer must parse before the API
|
||||
returns it. Set `OPENROUTER_API_KEY` on the backend to enable the button;
|
||||
`OPENROUTER_MODEL` defaults to `google/gemini-2.5-flash-lite`.
|
||||
|
||||
## Game engine
|
||||
|
||||
`backend/src/game/` is a synchronous rules engine built on that AST. It covers
|
||||
zones, turns, priority, the stack, mana and costs, triggered/activated/static
|
||||
abilities, combat, state-based actions, and effect resolution.
|
||||
|
||||
```ts
|
||||
import { Game } from './src/game/game.js'
|
||||
import { deckFromOracleIds } from './src/game/catalog.js'
|
||||
|
||||
const game = new Game({
|
||||
seed: 1,
|
||||
players: [
|
||||
{ id: 'p1', deck: deckFromOracleIds(decklist1) },
|
||||
{ id: 'p2', deck: deckFromOracleIds(decklist2) },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
game.playLand('p1', cardId)
|
||||
game.castSpell('p1', spellId, { targets: [{ kind: 'player', id: 'p2' }] })
|
||||
game.resolveStack()
|
||||
```
|
||||
|
||||
Commander is a first-class format: the commander starts in the command zone, pays
|
||||
`{2}` more for each previous cast from that zone, returns to the command zone
|
||||
instead of the graveyard or exile, and loses the game at 21 combat damage from a
|
||||
single commander. Deck construction checks 100 cards, singleton, color identity,
|
||||
and a legendary-creature commander.
|
||||
|
||||
See [backend/docs/game-engine.md](backend/docs/game-engine.md) for the action API,
|
||||
turn and combat flow, supported mechanics, and known limitations. The engine tests
|
||||
live in `backend/test/game.test.ts` and `backend/test/commander.test.ts`:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npx tsx --test test/game.test.ts test/commander.test.ts
|
||||
```
|
||||
|
||||
## Playing online
|
||||
|
||||
The frontend has five pages:
|
||||
|
||||
- `/account` — create an account or sign in. The API stores only a username, a
|
||||
salted password hash, and the player's saved data in MongoDB.
|
||||
- `/` — create a 2–4 player game, join an open lobby, and pick your playmat.
|
||||
- `/decks` — build a deck, import a Moxfield/Archidekt/Arena text export, and
|
||||
export it again. Decks are stored with your account.
|
||||
- `/cards` — the existing card implementation editor and pseudocode guide.
|
||||
- `/games/:id` — lobby and game board. The page can also be used as an invite
|
||||
link; a player with no seat gets a join form.
|
||||
|
||||
Matches live in the API process and are lost on restart. Each player only
|
||||
receives their own hand and libraries as counts; the server sends personalized
|
||||
state over server-sent events (SSE), and actions come back over `POST`. The
|
||||
browser keeps the login token and a random per-seat game token in
|
||||
`localStorage`/`sessionStorage`; accounts and saved decks, playmat choices, and
|
||||
each deck's card back live in MongoDB. Each player can pick card art or upload
|
||||
a JPEG as their own playmat; the choice is shown to everyone in the match and
|
||||
remembered in the account for new games you host or join. Card backs are chosen
|
||||
per deck in the deck editor and used for that deck's library pile.
|
||||
|
||||
## Production
|
||||
|
||||
Build and run the optimized images:
|
||||
|
||||
```bash
|
||||
cp .env.example .env # optional: adjust public URLs and ports
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
| Service | Default URL |
|
||||
| -------- | ---------------------------- |
|
||||
| Frontend | http://localhost:3000 |
|
||||
| API | http://localhost:4000 |
|
||||
|
||||
```bash
|
||||
docker compose ps # status and health
|
||||
docker compose logs -f # follow logs
|
||||
docker compose down # stop
|
||||
```
|
||||
|
||||
The production frontend image runs the built Nuxt output directly. The backend
|
||||
image builds TypeScript and installs production dependencies only.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Used by | Description |
|
||||
| ---------------------- | ----------------------- | ---------------- | ---------------------------------------------------- |
|
||||
| `NUXT_PUBLIC_API_BASE` | `http://localhost:4000` | frontend | Public, browser-facing URL of the API |
|
||||
| `CORS_ORIGIN` | `http://localhost:3000` | backend | Allowed browser origin(s), comma separated |
|
||||
| `MONGODB_URI` | `mongodb://localhost:27017/commander` | backend | MongoDB connection string |
|
||||
| `FRONTEND_PORT` | `3000` | production | Host port for the frontend |
|
||||
| `BACKEND_PORT` | `4000` | production | Host port for the API |
|
||||
| `PORT` | `4000` | backend | Port the API listens on inside the container |
|
||||
| `CARD_OVERRIDES_DIR` | `backend/data/card-overrides` | backend | Where manual implementations are stored |
|
||||
| `OPENROUTER_API_KEY` | — | backend | Enables the editor's AI pseudocode draft |
|
||||
| `OPENROUTER_MODEL` | `google/gemini-2.5-flash-lite` | backend | OpenRouter model used for translation |
|
||||
|
||||
When deploying to a real host, set `NUXT_PUBLIC_API_BASE` and `CORS_ORIGIN` to
|
||||
your public URLs. Both values are applied at runtime in the production image.
|
||||
|
||||
## Project layout
|
||||
|
||||
```text
|
||||
.
|
||||
├── backend/
|
||||
│ ├── scripts/import-cards.ts # Scryfall bulk importer
|
||||
│ ├── scripts/compile-cards.ts # oracle text -> effect AST + pseudocode
|
||||
│ ├── src/cards.ts # card store, lookup, and search
|
||||
│ ├── src/images.ts # on-disk cache for Scryfall card art
|
||||
│ ├── src/effects/ # effect DSL, compiler, formatter, pseudocode parser
|
||||
│ ├── src/effects/translate.ts # natural language -> pseudocode through OpenRouter
|
||||
│ ├── src/game/ # rules engine, commander rules, match manager
|
||||
│ ├── src/accounts.ts # Mongo models, auth, decks, and preferences
|
||||
│ ├── src/server.ts # Fastify entry point and game/deck routes
|
||||
│ ├── test/ # compiler, pseudocode, engine, and commander tests
|
||||
│ ├── docs/card-effects.md # DSL reference and coverage
|
||||
│ ├── docs/game-engine.md # engine API, rules coverage, limitations
|
||||
│ ├── data/cards.json # generated by npm run import:cards
|
||||
│ ├── data/card-overrides/ # human-authored implementations, one file per card
|
||||
│ ├── Dockerfile # dev, build, and production stages
|
||||
│ └── package.json
|
||||
├── frontend/
|
||||
│ ├── app/app.vue # app shell and navigation
|
||||
│ ├── app/assets/main.css # shared theme and layout
|
||||
│ ├── app/pages/index.vue # create/join a game
|
||||
│ ├── app/pages/account.vue # sign in, register, and sign out
|
||||
│ ├── app/pages/decks.vue # deck builder and decklist import/export
|
||||
│ ├── app/pages/games/[id].vue # lobby, board, and live match client
|
||||
│ ├── app/pages/cards.vue # card implementation editor and guide
|
||||
│ ├── app/middleware/auth.ts # redirect signed-out visitors to /account
|
||||
│ ├── app/utils/auth.ts # login token storage and headers
|
||||
│ ├── app/utils/decks.ts # account deck API and validation
|
||||
│ ├── app/components/PseudoGuide.vue # pseudocode guide view
|
||||
│ ├── nuxt.config.ts # runtime config (API base URL)
|
||||
│ ├── Dockerfile # dev, build, and production stages
|
||||
│ └── package.json
|
||||
├── docker-compose.dev.yml # hot-reload development stack
|
||||
├── docker-compose.yml # production stack
|
||||
├── .env.example
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
`/auth/me` and every `/me/*` route require the
|
||||
`Authorization: Bearer <token>` header returned by `/auth/register` or
|
||||
`/auth/login`.
|
||||
|
||||
| Method | Path | Response |
|
||||
| ------ | --------------------- | ------------------------------------------------------- |
|
||||
| `GET` | `/health` | `{ "status": "ok", "service": "commander-api" }` |
|
||||
| `GET` | `/cards?q=atraxa` | `{ total, cards }` name search, `limit` capped at 200 |
|
||||
| `GET` | `/cards/:oracleId` | One card object, or `404` |
|
||||
| `GET` | `/cards/:oracleId/image` | Card face as JPEG; downloaded from Scryfall once and cached on disk |
|
||||
| `GET` | `/cards/:oracleId/art` | Wide card art crop used for playmats, cached on disk |
|
||||
| `GET` | `/cards?status=needs-work` | Filter by `supported`, `partial`, `unsupported`, `needs-work`, `manual`, `all` |
|
||||
| `GET` | `/cards?format=modern&color=U&type=creature&rarity=rare&cmcMin=1&cmcMax=3` | Format legality, color identity (`WUBRG` includes that color, `C` colorless, `M` multicolor), card type, rarity, and mana value filters |
|
||||
| `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, pseudocode source, manual flag |
|
||||
| `PUT` | `/cards/:oracleId/implementation` | Validate `{ "source": "..." }` and save the override |
|
||||
| `DELETE` | `/cards/:oracleId/implementation` | Delete the override and restore generated output |
|
||||
| `POST` | `/cards/:oracleId/translate` | Ask OpenRouter for pseudocode from the card's oracle text |
|
||||
| `GET` | `/cards/:oracleId/override` | Raw override source, or `404` |
|
||||
| `GET` | `/stats` | Supported, partial, unsupported, and manual counts |
|
||||
| `POST` | `/auth/register` | Create an account with `{ username, password }`, returns `{ token, username }` |
|
||||
| `POST` | `/auth/login` | Sign in with `{ username, password }`, returns `{ token, username }` |
|
||||
| `POST` | `/auth/logout` | Invalidate the current bearer token |
|
||||
| `GET` | `/auth/me` | Current account, requires `Authorization: Bearer <token>` |
|
||||
| `GET` | `/me/decks` | The account's saved decks |
|
||||
| `PUT` | `/me/decks/:id` | Create or replace a saved deck |
|
||||
| `DELETE` | `/me/decks/:id` | Delete a saved deck |
|
||||
| `GET` | `/me/preferences` | Saved playmat and card back |
|
||||
| `PUT` | `/me/preferences` | Update `{ playmat?, cardBack? }` |
|
||||
| `POST` | `/decks/import` | Parse a text decklist into `{ commander, cards, errors }` |
|
||||
| `POST` | `/cards/resolve` | Resolve exact card names: `{ names: string[] }` |
|
||||
| `GET` | `/games` | Open and active matches |
|
||||
| `POST` | `/games` | Create a match from `{ name, deck, maxPlayers, playmat? }` |
|
||||
| `POST` | `/games/:id/join` | Join a lobby with `{ name, deck, playmat? }` |
|
||||
| `POST` | `/games/:id/leave` | Leave a lobby or forfeit an active game with `{ token }` |
|
||||
| `POST` | `/games/:id/deck` | Change your lobby deck with `{ token, deck }` |
|
||||
| `POST` | `/games/:id/start` | Host starts the match with `{ token }` |
|
||||
| `POST` | `/games/:id/playmat` | Set your playmat with `{ token, playmat: { kind: "card", oracleId } \| { kind: "upload", data } \| { kind: "none" } }` |
|
||||
| `GET` | `/playmats/:id` | Uploaded playmat image |
|
||||
| `POST` | `/games/:id/actions` | Submit `{ token, action }` |
|
||||
| `GET` | `/games/:id/state` | Personalized state, requires `?token=` |
|
||||
| `GET` | `/games/:id/events` | Personalized SSE stream, requires `?token=` |
|
||||
|
||||
## Next steps
|
||||
|
||||
- More compiled effects and rules coverage (prevention, control changes, planeswalkers)
|
||||
- WebSocket transport if SSE backpressure becomes a problem
|
||||
- Persistence for live games and match history
|
||||
- Matchmaking, spectators, and reconnect/afk handling
|
||||
- Partner commanders, companion, and the rest of the Commander variants
|
||||
6
backend/.dockerignore
Normal file
6
backend/.dockerignore
Normal file
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
dist
|
||||
.env
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
data/images
|
||||
9
backend/.gitignore
vendored
Normal file
9
backend/.gitignore
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
node_modules
|
||||
dist
|
||||
.env
|
||||
data/cards.json
|
||||
data/card-effects.json
|
||||
data/card-effects.pseudo.txt
|
||||
data/images/
|
||||
data/playmats/
|
||||
data/*.tmp
|
||||
23
backend/Dockerfile
Normal file
23
backend/Dockerfile
Normal file
@@ -0,0 +1,23 @@
|
||||
FROM node:24-alpine AS base
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
FROM base AS dev
|
||||
COPY . .
|
||||
EXPOSE 4000
|
||||
CMD ["npm", "run", "dev"]
|
||||
|
||||
FROM base AS build
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:24-alpine AS production
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY --from=build /app/data ./data
|
||||
EXPOSE 4000
|
||||
CMD ["node", "dist/server.js"]
|
||||
0
backend/data/.gitkeep
Normal file
0
backend/data/.gitkeep
Normal file
@@ -0,0 +1,4 @@
|
||||
# Miirym, Sentinel Wyrm [supported]
|
||||
keywords Flying, Ward {2}
|
||||
on enters(each other nontoken dragon you control):
|
||||
create_token(you, 1, copy of the triggering object, not legendary)
|
||||
260
backend/docs/card-effects.md
Normal file
260
backend/docs/card-effects.md
Normal file
@@ -0,0 +1,260 @@
|
||||
# Card effect compiler
|
||||
|
||||
The card database from Scryfall is English prose. The game engine cannot execute
|
||||
prose, so `backend/src/effects/` compiles every oracle-text line into a small
|
||||
JSON AST. The AST is the canonical form for the engine. A pretty-printer renders
|
||||
the same AST as readable pseudocode, and a matching parser reads that pseudocode
|
||||
back, so a human can replace the generated implementation of a card without
|
||||
touching JSON.
|
||||
|
||||
This is deliberately **not** a rules engine. It answers "what does the card
|
||||
say?" in machine-readable form. "What happens when it resolves?" belongs to the
|
||||
engine that consumes these nodes.
|
||||
|
||||
## Pipeline
|
||||
|
||||
```text
|
||||
Scryfall oracle text
|
||||
-> normalize (card name, "this creature", contractions, reminder text)
|
||||
-> classify (keyword / triggered / activated / static / spell effect)
|
||||
-> parse targets, values, costs, conditions, durations
|
||||
-> JSON AST + pseudocode rendering
|
||||
|
||||
data/card-overrides/<oracle_id>.pseudo.txt
|
||||
-> pseudocode parser
|
||||
-> JSON AST used instead of the generated one
|
||||
```
|
||||
|
||||
Every line is parsed as a whole. If any part of a line is not understood, the
|
||||
line becomes `{ "kind": "unsupported", "reason": ..., "text": ... }` instead of
|
||||
a guessed effect. A wrong effect is worse than a missing one.
|
||||
|
||||
## Commands
|
||||
|
||||
From `backend/`:
|
||||
|
||||
```bash
|
||||
npm run compile:cards # writes data/card-effects.json and .pseudo.txt
|
||||
npm test # compiler, pseudocode parser, and engine tests
|
||||
npm run dev # API for the frontend editor
|
||||
```
|
||||
|
||||
Current output over the imported Commander pool (32,116 cards):
|
||||
|
||||
```text
|
||||
Cards: 14,141 supported, 10,119 partial, 7,856 unsupported
|
||||
Ability lines: 37,983/60,470 parsed (62.8%)
|
||||
```
|
||||
|
||||
- **supported** — every ability line parsed.
|
||||
- **partial** — at least one line parsed, at least one unsupported.
|
||||
- **unsupported** — no line parsed.
|
||||
|
||||
The unsupported lines are the work queue. Re-running the compiler after adding
|
||||
patterns updates the numbers.
|
||||
|
||||
## Output files
|
||||
|
||||
| File | Contents |
|
||||
| ---- | -------- |
|
||||
| `data/card-effects.json` | Array of `CompiledCard` ASTs, one per oracle card |
|
||||
| `data/card-effects.pseudo.txt` | The same cards rendered as pseudocode |
|
||||
| `data/card-overrides/<oracle_id>.pseudo.txt` | Human-authored implementations, one file per card |
|
||||
|
||||
The two generated files are git-ignored. Overrides are ordinary source files and
|
||||
should be committed.
|
||||
|
||||
## Pseudocode
|
||||
|
||||
```text
|
||||
# Soul Warden [supported]
|
||||
on enters(each other creature):
|
||||
gain_life(you, 1)
|
||||
|
||||
# Llanowar Elves [supported]
|
||||
activate {T}:
|
||||
add_mana(you, {G})
|
||||
|
||||
# Krenko, Mob Boss [supported]
|
||||
activate {T}:
|
||||
create_token(you, count(creature goblin you control), 1/1 red goblin creature)
|
||||
```
|
||||
|
||||
Pseudocode is a two-way format. `formatCard` writes it, `parsePseudoCard` reads
|
||||
it back into the same AST the compiler produces. Blocks are indented two spaces.
|
||||
A leading `# Card [status]` line is ignored, and `## Face Name [status]` starts a
|
||||
new section for a multi-face card. Use `(no abilities)` when a face has none.
|
||||
|
||||
## Manual implementations
|
||||
|
||||
The frontend at `/cards` lists cards and filters to `needs-work` by default. Select a
|
||||
card, edit its pseudocode, and save. The editor toggles between the text view and a
|
||||
node canvas where sockets are wired to define effect order and nested bodies; both
|
||||
edit the same source. The API validates the source before writing it, so a typo
|
||||
never replaces a working file. Overrides take precedence during
|
||||
`npm run compile:cards`; invalid override files stop the compile with the line
|
||||
number.
|
||||
|
||||
| Method | Path | Purpose |
|
||||
| ------ | ---- | ------- |
|
||||
| `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, source, manual flag |
|
||||
| `PUT` | `/cards/:oracleId/implementation` | Validate and save `{ "source": "..." }` |
|
||||
| `DELETE` | `/cards/:oracleId/implementation` | Delete the override, restore generated output |
|
||||
| `POST` | `/cards/:oracleId/translate` | Ask OpenRouter for pseudocode from the card's oracle text |
|
||||
| `GET` | `/cards/:oracleId/override` | Raw saved source, `404` when absent |
|
||||
| `GET` | `/stats` | Supported, partial, unsupported, and manual counts |
|
||||
|
||||
`CARD_OVERRIDES_DIR` changes the storage directory (useful for tests).
|
||||
|
||||
### AI drafts
|
||||
|
||||
The editor's **Draft with AI** button calls
|
||||
`POST /cards/:oracleId/translate`. The backend sends the card's oracle text to
|
||||
an [OpenRouter](https://openrouter.ai/) model and returns pseudocode, without
|
||||
saving it. The response is parsed before it reaches the browser, so prose or a
|
||||
non-parseable guess is reported as an error instead of replacing the editor.
|
||||
|
||||
Set `OPENROUTER_API_KEY` on the backend to enable the route. `OPENROUTER_MODEL`
|
||||
defaults to `google/gemini-2.5-flash-lite`.
|
||||
|
||||
The system prompt contains the syntax reference and a strict output contract:
|
||||
pseudocode only, no explanations, Markdown, code fences or card header, and no
|
||||
invented operations. Output is capped at 700 tokens. A fenced answer is
|
||||
unwrapped defensively, but an invalid answer is not retried (that would spend
|
||||
more tokens). The translator uses the default model only; there is no per-request
|
||||
model picker.
|
||||
|
||||
|
||||
## AST
|
||||
|
||||
The types live in `src/effects/types.ts`. A card contains one or more abilities:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"oracle_id": "...",
|
||||
"name": "Soul Warden",
|
||||
"status": "supported",
|
||||
"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."
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Ability kinds
|
||||
|
||||
| Kind | Meaning | Example |
|
||||
| ---- | ------- | ------- |
|
||||
| `keyword` | One parameterless or parameterized keyword | `Flying`, `Ward {2}`, `Crew 3` |
|
||||
| `keywords` | Several keywords on one oracle line | `Flying, vigilance` |
|
||||
| `triggered` | `When`/`Whenever`/`At` ability | `When this enters, draw a card.` |
|
||||
| `activated` | Cost `:` effect, including loyalty | `{T}: Add {G}.` |
|
||||
| `static` | Continuous effect or restriction | `Creatures you control get +1/+1.` |
|
||||
| `spell` | Effect line of an instant or sorcery | `Draw two cards.` |
|
||||
| `unsupported` | Preserved text plus a reason | `Choose one —` |
|
||||
|
||||
### Effects
|
||||
|
||||
| `op` | Payload |
|
||||
| ---- | ------- |
|
||||
| `damage` | `target`, `amount`, optional `source` |
|
||||
| `draw`, `discard`, `mill` | `player`, `amount` |
|
||||
| `life` | `player`, `amount`, `mode: gain \| lose` |
|
||||
| `pump` | `target`, `power`, `toughness`, `duration` |
|
||||
| `grant` | `target`, `keyword`, optional `value`, `duration` |
|
||||
| `put_counters`, `remove_counters` | `target`, `counter`, `amount` |
|
||||
| `create_token` | `player`, `amount`, `token` |
|
||||
| `destroy`, `exile`, `tap`, `untap`, `regenerate` | `target` |
|
||||
| `sacrifice` | `player`, `target`, optional `unless` cost |
|
||||
| `counter` | `what`, `target`, optional `unless` cost |
|
||||
| `return_to_hand`, `return_to_battlefield`, `put_on_top` | `target` |
|
||||
| `search`, `shuffle` | player, selector, destination |
|
||||
| `add_mana` | `player`, `mana` (`symbols` or `any_color`) |
|
||||
| `scry`, `surveil` | `player`, `amount` |
|
||||
| `fight` | two targets |
|
||||
| `energy` | `player`, `amount` |
|
||||
| `attach` | target to attach this/trigger object to |
|
||||
| `restriction` | target, rule, duration |
|
||||
| `keyword_action` | `action`, optional `amount`, `detail`, `target` |
|
||||
| `proliferate` | no payload |
|
||||
|
||||
### Targets, values, costs
|
||||
|
||||
- **Targets** are `self`, `trigger_subject`, `any`, `player`, `spell`, `ability`,
|
||||
or `object` with an `ObjectSelector` and mode `target` / `each` / `choose`.
|
||||
- **Selectors** carry types, subtypes, controller, colors, zone, tapped/attacking
|
||||
state, `other`, `attached: equipped|enchanted`, and `includeSelf`.
|
||||
- **Values** are `number`, `x`, `count(selector)`, `source_power`,
|
||||
`source_toughness`, `cards_in_hand`, or `event_amount`.
|
||||
- **Costs** are mana symbols, tap/untap, tapping another permanent, energy,
|
||||
loyalty, life, discard, sacrifice, self-exile, mill, and removing counters.
|
||||
- **Conditions** cover controlling permanents, turn ownership, tapped source,
|
||||
life totals, and graveyard size.
|
||||
- **Durations** cover permanent, end of turn, your next turn, the end of your
|
||||
next turn, end of combat, controller's next untap step, and while the source
|
||||
remains.
|
||||
|
||||
## How a line is parsed
|
||||
|
||||
1. Reminder text in parentheses is removed. Card names and "this creature" /
|
||||
"this permanent" become `this`.
|
||||
2. Pure keyword lines are recognized from Scryfall's keyword list plus the
|
||||
parameterized keyword table.
|
||||
3. Trigger prefixes (`When this enters`, `Whenever this attacks`, `At the
|
||||
beginning of your upkeep`, ...) become a `TriggerEvent`.
|
||||
4. A colon splits an activated ability into costs and effects.
|
||||
5. A leading duration (`Until end of turn, ...`) moves to the end of the
|
||||
effect, where the duration parser expects it.
|
||||
6. Otherwise a static effect is attempted.
|
||||
7. Instant/sorcery lines fall back to a one-shot effect (`kind: "spell"`).
|
||||
8. Anything left over is `unsupported`.
|
||||
|
||||
Effects are split on sentences, `, then`, and `and` only when both sides parse.
|
||||
`When you do, ...` becomes a reflexive `if you do` condition. `it` becomes the
|
||||
trigger subject only when no explicit target/`that` appears in the same effect;
|
||||
ambiguous pronouns stay unsupported.
|
||||
|
||||
## Adding support
|
||||
|
||||
For a single card, open the frontend editor, edit the pseudocode, and save; no
|
||||
compiler change is needed. For a whole class of cards:
|
||||
|
||||
1. Run `npm run compile:cards` and pick a frequent unsupported pattern.
|
||||
2. Add a regex + AST builder in `src/effects/compile.ts` (or a target/value
|
||||
parser in `src/effects/parse.ts`).
|
||||
3. Add a focused test in `test/effects.test.ts`.
|
||||
4. Run `npm test` and `npm run compile:cards`.
|
||||
|
||||
Prefer narrow, anchored patterns. A broad pattern that misreads one card is a
|
||||
game bug that is hard to find later.
|
||||
|
||||
## Known gaps
|
||||
|
||||
The remaining unsupported lines are mostly:
|
||||
|
||||
- modal abilities (`Choose one —` and bullets)
|
||||
- replacement effects (`If ... instead`, `As ... enters, ...`)
|
||||
- continuous-effect layers and dependency rules
|
||||
- copy, control-change, and type-change effects
|
||||
- alternative/additional costs and cost modifiers
|
||||
- level/class/saga structures and chapter abilities
|
||||
- quoted token abilities and copying tokens
|
||||
- complex pronoun/context resolution and "for each" scaling beyond simple counts
|
||||
- dice, stickers, attractions, dungeons, and other supplemental mechanics
|
||||
|
||||
None of these are blocked by the AST; each needs a parser pattern and an engine
|
||||
implementation.
|
||||
158
backend/docs/game-engine.md
Normal file
158
backend/docs/game-engine.md
Normal file
@@ -0,0 +1,158 @@
|
||||
# Game engine
|
||||
|
||||
`backend/src/game/` is a small but real Magic rules engine. It consumes the compiled
|
||||
effect AST from `backend/src/effects/types.ts` directly — there is no second card
|
||||
language. Card definitions are immutable input; a `GameObject` is the per-game
|
||||
instance that moves between zones.
|
||||
|
||||
## Quick start
|
||||
|
||||
Run the data imports first (see the root README), then:
|
||||
|
||||
```ts
|
||||
import { Game } from './src/game/game.js'
|
||||
import { deckFromOracleIds } from './src/game/catalog.js'
|
||||
|
||||
const game = new Game({
|
||||
seed: 1,
|
||||
startingLife: 40,
|
||||
startingHandSize: 7,
|
||||
commander: true,
|
||||
players: [
|
||||
{ id: 'p1', deck: deckFromOracleIds(decklist1), commander: commanderCard1 },
|
||||
{ id: 'p2', deck: deckFromOracleIds(decklist2), commander: commanderCard2 },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
```
|
||||
|
||||
`commander: true` creates each supplied commander in that player's command zone. The
|
||||
`deck` should contain the other 99 cards; `validateCommanderDeck(commander, cards)`
|
||||
in `commander.ts` checks size, singleton, color identity, and the commander type.
|
||||
|
||||
`catalog.ts` merges Scryfall card data with `data/card-effects.json`. It also adds
|
||||
intrinsic mana abilities for basic lands, because Scryfall's oracle text only has
|
||||
reminder text for them and the compiler produces no ability.
|
||||
|
||||
For tests or hand-authored cards, build a `CardDefinition` yourself:
|
||||
|
||||
```ts
|
||||
const bolt: CardDefinition = {
|
||||
oracleId: 'lightning-bolt',
|
||||
name: 'Lightning Bolt',
|
||||
typeLine: 'Instant',
|
||||
manaCost: '{R}',
|
||||
manaValue: 1,
|
||||
abilities: [{
|
||||
kind: 'spell',
|
||||
optional: false,
|
||||
text: 'Lightning Bolt deals 3 damage to any target.',
|
||||
effects: [{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } }],
|
||||
}],
|
||||
}
|
||||
```
|
||||
|
||||
## Actions
|
||||
|
||||
| Method | Purpose |
|
||||
| ------ | ------- |
|
||||
| `start()` | Shuffles libraries, draws opening hands, begins turn 1. |
|
||||
| `playLand(playerId, cardId)` | Plays a land from hand; once per turn, main phase, empty stack. |
|
||||
| `castSpell(playerId, cardId, { targets, x, mode })` | Puts a spell on the stack and pays its mana cost. Accepts a commander in the command zone and adds commander tax. |
|
||||
| `activateAbility(playerId, sourceId, abilityIndex, { targets, x, mode })` | Activates an ability on a permanent. Mana abilities resolve immediately. |
|
||||
| `movePermanent(playerId, cardId, x, y)` | Cosmetic board layout for a permanent you control; coordinates are 0..1 within the battlefield. |
|
||||
| `declareAttackers(playerId, [{ attackerId, defenderId }])` | Starts combat from the precombat main if needed. |
|
||||
| `declareBlockers(playerId, [{ blockerId, attackerId }])` | Declares blocks for one defending player. In multiplayer, combat damage waits until every defending player has declared or passed. |
|
||||
| `resolveCombatDamage()` | Deals combat damage manually; passing priority also does this. |
|
||||
| `pass(playerId?)` | Passes priority; when everyone passes, resolves the top of the stack or advances the phase. |
|
||||
| `chooseSearchCard(playerId, cardId)` | Finishes one pick of a paused library search. |
|
||||
| `resolveStack()` | Convenience for tests/scripts: passes priority until the stack is empty. Does not advance phases. |
|
||||
| `endTurn(playerId)` | Ends the active player's turn, skipping remaining phases. Requires an empty stack. |
|
||||
| `canPlayCard(playerId, cardId)` | Whether a hand or command-zone card can legally be played now, including timing, mana, and targets. |
|
||||
| `autoAdvance()` | Passes priority for players with nothing meaningful to do; stops when someone can act or the turn ends. |
|
||||
| `getPower`, `getToughness`, `hasKeyword` | Current characteristics after static and continuous effects. |
|
||||
| `addCard`, `moveToZone` | Setup helpers for placing cards directly into zones. |
|
||||
|
||||
Actions that use the stack move priority to the next living player. Non-instant,
|
||||
non-flash spells can only be cast in the active player's main phase with an empty
|
||||
stack. Targets may be supplied explicitly; if omitted, the first legal target is
|
||||
chosen automatically, which keeps scripted games short. A search effect that matches
|
||||
several cards pauses instead: other actions are refused until its controller calls
|
||||
`chooseSearchCard` (the match API uses the `choose_search` action).
|
||||
|
||||
## Turn structure
|
||||
|
||||
```text
|
||||
untap -> upkeep -> draw -> precombat main -> begin combat -> declare attackers
|
||||
-> declare blockers -> combat damage -> end combat -> postcombat main
|
||||
-> end step -> cleanup -> next player's turn
|
||||
```
|
||||
|
||||
The starting player skips their first draw. Cleanup discards down to seven cards,
|
||||
clears damage, expires `until_end_of_turn` and `until_end_of_your_next_turn`
|
||||
effects, and empties mana pools. The engine advances phases when every living
|
||||
player passes in turn; it does not stop at every rules-defined priority window.
|
||||
The match manager calls `autoAdvance()` after each action, so priority is only
|
||||
shown to players who can actually do something.
|
||||
|
||||
## Supported
|
||||
|
||||
- Zones: library, hand, battlefield, graveyard, exile, stack, and command zone. Tokens
|
||||
cease to exist when they leave the battlefield.
|
||||
- Commander: command-zone casting, `{2}` tax per previous cast from the command
|
||||
zone, return to the command zone instead of graveyard/exile/hand/library, and a
|
||||
loss at 21 combat damage from one commander. Deck construction is validated by
|
||||
`validateCommanderDeck`.
|
||||
- Mana: colored, generic, hybrid, Phyrexian, `{X}`, and `{S}` costs; manual mana
|
||||
abilities plus automatic tapping of untapped mana sources when paying.
|
||||
- Costs: tap, untap, tap another permanent, pay life, discard, sacrifice, exile,
|
||||
putting/removing counters, mill, energy, and choice costs.
|
||||
- Abilities: spell effects, activated abilities, triggered abilities (enters,
|
||||
leaves, dies, attacks, blocks, cast, draw, life, upkeep, end step, combat), static
|
||||
effects, and basic replacement effects for entering tapped/with counters.
|
||||
- Effects: damage, draw, discard, mill, life, pump/set P/T, grant keyword,
|
||||
counters, proliferate, tokens, destroy, exile, sacrifice, counter spell/ability,
|
||||
zone returns, tap/untap, search/shuffle, add mana, fight, regenerate, energy,
|
||||
attach, restrictions, conditional and modal effects, dig, and divided damage.
|
||||
- Combat keywords: flying, reach, first strike, double strike, trample, deathtouch,
|
||||
lifelink, vigilance, haste, indestructible. Regeneration shields replace
|
||||
destruction.
|
||||
- State-based actions: life at or below zero, ten poison counters, 21 commander
|
||||
damage from one commander, lethal or deathtouch damage, zero toughness, and
|
||||
drawing from an empty library.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- Some effect nodes are accepted but intentionally do nothing yet:
|
||||
`prevent_damage`, `gain_control`, `emblem`, `transform`, `schedule`, `level_up`,
|
||||
`put_from_among`, `look_top`, `scry`, `surveil`, and `keyword_action`.
|
||||
Unsupported oracle lines are already marked by the compiler and never reach here.
|
||||
- Commander support covers single commanders. Partner, backgrounds, companions,
|
||||
and "choose a commander" variants are not modelled. The engine always takes the
|
||||
command-zone replacement instead of asking.
|
||||
- The legend rule, planeswalker loyalty abilities, attacking planeswalkers, and
|
||||
protection/menace/defender are not implemented unless expressed as a compiled
|
||||
restriction.
|
||||
- Modal spells choose a mode by index (`options.mode`); optional "you may" choices
|
||||
are not modelled. An optional `pay` is simply not paid when unaffordable. Search
|
||||
effects with several matching cards do pause for the player's pick.
|
||||
- Opening hands are kept automatically; there is no mulligan flow.
|
||||
- Replacement/prevention effects, layers, and dependency ordering are simplified.
|
||||
Continuous effects apply in creation order rather than in full rules order.
|
||||
- The engine is synchronous and exposes full state. `rooms.ts` owns the in-memory
|
||||
multiplayer matches, validates decks, and sends each player a personalized view
|
||||
(own hand only, libraries as counts) over SSE.
|
||||
- There is no persistence, account system, or reconnect grace period; a server
|
||||
restart drops all matches.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npx tsx --test test/game.test.ts test/commander.test.ts
|
||||
```
|
||||
|
||||
The tests cover turn flow, priority, spell resolution, triggers, mana and summoning
|
||||
sickness, static and temporary pumps, combat, counterspells, tokens, searching,
|
||||
entering tapped/with counters, decking, lethal damage, commander tax and damage,
|
||||
decklist import, and multi-defender combat.
|
||||
1809
backend/package-lock.json
generated
Normal file
1809
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
24
backend/package.json
Normal file
24
backend/package.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "commander-backend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/server.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/server.js",
|
||||
"import:cards": "tsx scripts/import-cards.ts",
|
||||
"compile:cards": "tsx scripts/compile-cards.ts",
|
||||
"test": "tsx --test test/*.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^11.3.1",
|
||||
"fastify": "^5.12.7",
|
||||
"mongoose": "^9.11.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.19.2",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^7.0.2"
|
||||
}
|
||||
}
|
||||
103
backend/scripts/compile-cards.ts
Normal file
103
backend/scripts/compile-cards.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import type { Card } from '../src/cards.js'
|
||||
import { compileCard } from '../src/effects/compile.js'
|
||||
import { formatCard } from '../src/effects/format.js'
|
||||
import { compileImplementation, readAllOverrides } from '../src/effects/implementations.js'
|
||||
import { PseudoParseError } from '../src/effects/pseudo.js'
|
||||
import type { Ability, CompiledCard } from '../src/effects/types.js'
|
||||
|
||||
const DATA_DIR = join(process.cwd(), 'data')
|
||||
const CARDS_FILE = join(DATA_DIR, 'cards.json')
|
||||
const AST_FILE = join(DATA_DIR, 'card-effects.json')
|
||||
const PSEUDO_FILE = join(DATA_DIR, 'card-effects.pseudo.txt')
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
let cards: Card[]
|
||||
try {
|
||||
cards = JSON.parse(await readFile(CARDS_FILE, 'utf8')) as Card[]
|
||||
} catch {
|
||||
console.error(`Card data not found at ${CARDS_FILE}. Run "npm run import:cards" first.`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const overrides = await readAllOverrides()
|
||||
const cardsById = new Map(cards.map(card => [card.oracle_id, card]))
|
||||
for (const oracleId of overrides.keys()) {
|
||||
if (!cardsById.has(oracleId)) {
|
||||
console.warn(`Ignoring override for unknown oracle id: ${oracleId}`)
|
||||
}
|
||||
}
|
||||
|
||||
const compiled: CompiledCard[] = []
|
||||
const cardCounts = { supported: 0, partial: 0, unsupported: 0 }
|
||||
const reasons = new Map<string, number>()
|
||||
const samples: string[] = []
|
||||
let abilityCount = 0
|
||||
let manualCount = 0
|
||||
let parsedCount = 0
|
||||
|
||||
function abilitiesOf(card: CompiledCard): Ability[] {
|
||||
return card.faces ? card.faces.flatMap(face => face.abilities) : card.abilities
|
||||
}
|
||||
|
||||
function sourceLines(ability: Ability): number {
|
||||
if (ability.kind === 'keyword' || ability.kind === 'keywords') return 1
|
||||
return ability.text.split('\n').length
|
||||
}
|
||||
|
||||
for (const card of cards) {
|
||||
const source = overrides.get(card.oracle_id)
|
||||
let result: CompiledCard
|
||||
try {
|
||||
result = source === undefined ? compileCard(card) : compileImplementation(card, source)
|
||||
} catch (error) {
|
||||
if (error instanceof PseudoParseError) {
|
||||
console.error(`Invalid manual implementation for ${card.name} (${card.oracle_id}):`)
|
||||
console.error(` ${error.message}`)
|
||||
process.exit(1)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
if (result.manual) manualCount++
|
||||
compiled.push(result)
|
||||
cardCounts[result.status]++
|
||||
|
||||
for (const ability of abilitiesOf(result)) {
|
||||
const lines = sourceLines(ability)
|
||||
abilityCount += lines
|
||||
if (ability.kind === 'unsupported') {
|
||||
reasons.set(ability.reason, (reasons.get(ability.reason) ?? 0) + lines)
|
||||
if (samples.length < 10 && ability.reason === 'unmatched line') samples.push(ability.text)
|
||||
} else {
|
||||
parsedCount += lines
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await mkdir(DATA_DIR, { recursive: true })
|
||||
const astOutput = JSON.stringify(compiled)
|
||||
const pseudoOutput = compiled.map(formatCard).join('\n\n')
|
||||
await writeFile(AST_FILE, astOutput)
|
||||
await writeFile(PSEUDO_FILE, pseudoOutput)
|
||||
|
||||
console.log(`Compiled ${compiled.length} cards (${manualCount} with manual implementations).`)
|
||||
console.log(
|
||||
`Cards: ${cardCounts.supported} supported, ${cardCounts.partial} partial, ${cardCounts.unsupported} unsupported.`,
|
||||
)
|
||||
console.log(
|
||||
`Ability lines: ${parsedCount}/${abilityCount} parsed (${((100 * parsedCount) / abilityCount).toFixed(1)}%).`,
|
||||
)
|
||||
console.log('Unsupported reasons:')
|
||||
for (const [reason, count] of [...reasons.entries()].sort((a, b) => b[1] - a[1])) {
|
||||
console.log(` ${reason}: ${count}`)
|
||||
}
|
||||
if (samples.length) {
|
||||
console.log('Sample unsupported lines:')
|
||||
for (const sample of samples) console.log(` - ${sample}`)
|
||||
}
|
||||
console.log(`Wrote ${formatBytes(Buffer.byteLength(astOutput))} to ${AST_FILE}`)
|
||||
console.log(`Wrote ${formatBytes(Buffer.byteLength(pseudoOutput))} to ${PSEUDO_FILE}`)
|
||||
166
backend/scripts/import-cards.ts
Normal file
166
backend/scripts/import-cards.ts
Normal file
@@ -0,0 +1,166 @@
|
||||
import { mkdir, rename, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { createInterface } from 'node:readline'
|
||||
import { Readable } from 'node:stream'
|
||||
import { createGunzip } from 'node:zlib'
|
||||
import type { Card, CardFace } from '../src/cards.js'
|
||||
|
||||
const BULK_API = 'https://api.scryfall.com/bulk-data'
|
||||
const OUT_FILE = join(process.cwd(), 'data', 'cards.json')
|
||||
const HEADERS = {
|
||||
'User-Agent': 'commander-import/0.1',
|
||||
Accept: 'application/json',
|
||||
}
|
||||
|
||||
interface BulkData {
|
||||
type: string
|
||||
name: string
|
||||
updated_at: string
|
||||
compressed_size: number
|
||||
jsonl_download_uri?: string
|
||||
}
|
||||
|
||||
interface RawFace {
|
||||
name: string
|
||||
mana_cost?: string
|
||||
type_line?: string
|
||||
oracle_text?: string
|
||||
colors?: string[]
|
||||
power?: string
|
||||
toughness?: string
|
||||
loyalty?: string
|
||||
defense?: string
|
||||
image_uris?: { normal?: string }
|
||||
}
|
||||
|
||||
interface RawCard {
|
||||
oracle_id: string
|
||||
name: string
|
||||
layout?: string
|
||||
mana_cost?: string
|
||||
cmc?: number
|
||||
type_line?: string
|
||||
oracle_text?: string
|
||||
colors?: string[]
|
||||
color_identity?: string[]
|
||||
keywords?: string[]
|
||||
rarity?: string
|
||||
power?: string
|
||||
toughness?: string
|
||||
loyalty?: string
|
||||
defense?: string
|
||||
image_uris?: { normal?: string }
|
||||
card_faces?: RawFace[]
|
||||
legalities?: Record<string, string>
|
||||
}
|
||||
|
||||
function toFace(face: RawFace): CardFace {
|
||||
return {
|
||||
name: face.name,
|
||||
mana_cost: face.mana_cost,
|
||||
type_line: face.type_line,
|
||||
oracle_text: face.oracle_text,
|
||||
colors: face.colors ?? [],
|
||||
power: face.power,
|
||||
toughness: face.toughness,
|
||||
loyalty: face.loyalty,
|
||||
defense: face.defense,
|
||||
image_uri: face.image_uris?.normal,
|
||||
}
|
||||
}
|
||||
|
||||
function toCard(raw: RawCard): Card {
|
||||
return {
|
||||
oracle_id: raw.oracle_id,
|
||||
name: raw.name,
|
||||
layout: raw.layout ?? 'normal',
|
||||
cmc: raw.cmc ?? 0,
|
||||
type_line: raw.type_line ?? '',
|
||||
colors: raw.colors ?? [],
|
||||
color_identity: raw.color_identity ?? [],
|
||||
keywords: raw.keywords ?? [],
|
||||
rarity: raw.rarity,
|
||||
legal_formats: Object.entries(raw.legalities ?? {})
|
||||
.filter(([, status]) => status === 'legal' || status === 'restricted')
|
||||
.map(([format]) => format),
|
||||
mana_cost: raw.mana_cost,
|
||||
oracle_text: raw.oracle_text,
|
||||
power: raw.power,
|
||||
toughness: raw.toughness,
|
||||
loyalty: raw.loyalty,
|
||||
defense: raw.defense,
|
||||
image_uri: raw.image_uris?.normal ?? raw.card_faces?.[0]?.image_uris?.normal,
|
||||
card_faces: raw.card_faces?.map(toFace),
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
const metaResponse = await fetch(BULK_API, { headers: HEADERS })
|
||||
if (!metaResponse.ok) {
|
||||
throw new Error(`Scryfall bulk-data request failed: ${metaResponse.status}`)
|
||||
}
|
||||
|
||||
const meta = (await metaResponse.json()) as { data: BulkData[] }
|
||||
const bulk = meta.data.find(entry => entry.type === 'oracle_cards')
|
||||
if (!bulk?.jsonl_download_uri) {
|
||||
throw new Error('Scryfall oracle_cards bulk export not found')
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Downloading ${bulk.name} (${formatBytes(bulk.compressed_size)}, updated ${bulk.updated_at})...`,
|
||||
)
|
||||
|
||||
const response = await fetch(bulk.jsonl_download_uri, { headers: HEADERS })
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`Scryfall card download failed: ${response.status}`)
|
||||
}
|
||||
|
||||
const body = response.body as Parameters<typeof Readable.fromWeb>[0]
|
||||
const lines = createInterface({
|
||||
input: Readable.fromWeb(body).pipe(createGunzip()),
|
||||
crlfDelay: Infinity,
|
||||
})
|
||||
|
||||
const cards: Card[] = []
|
||||
const seen = new Set<string>()
|
||||
let skipped = 0
|
||||
|
||||
for await (const line of lines) {
|
||||
if (!line.trim()) continue
|
||||
|
||||
const raw = JSON.parse(line) as RawCard
|
||||
if (!raw.oracle_id || !raw.name) {
|
||||
throw new Error(`Scryfall card is missing oracle_id or name: ${line.slice(0, 120)}`)
|
||||
}
|
||||
if (seen.has(raw.oracle_id)) {
|
||||
throw new Error(`Duplicate oracle_id in Scryfall export: ${raw.oracle_id}`)
|
||||
}
|
||||
seen.add(raw.oracle_id)
|
||||
|
||||
if (raw.legalities?.commander !== 'legal') {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
cards.push(toCard(raw))
|
||||
}
|
||||
|
||||
if (cards.length < 15_000) {
|
||||
throw new Error(`Imported only ${cards.length} cards, expected at least 15000`)
|
||||
}
|
||||
|
||||
cards.sort((a, b) => a.name.localeCompare(b.name) || a.oracle_id.localeCompare(b.oracle_id))
|
||||
|
||||
const output = JSON.stringify(cards)
|
||||
const tmpFile = `${OUT_FILE}.tmp`
|
||||
await mkdir(dirname(OUT_FILE), { recursive: true })
|
||||
await writeFile(tmpFile, output)
|
||||
await rename(tmpFile, OUT_FILE)
|
||||
|
||||
console.log(
|
||||
`Imported ${cards.length} Commander-legal cards (skipped ${skipped} other cards, ${seen.size} total).`,
|
||||
)
|
||||
console.log(`Wrote ${formatBytes(Buffer.byteLength(output))} to ${OUT_FILE}`)
|
||||
336
backend/src/accounts.ts
Normal file
336
backend/src/accounts.ts
Normal file
@@ -0,0 +1,336 @@
|
||||
import { createHash, randomBytes, scrypt as scryptCallback, timingSafeEqual } from 'node:crypto'
|
||||
import { promisify } from 'node:util'
|
||||
import mongoose, { Schema } from 'mongoose'
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify'
|
||||
import { implementationIndex, type ImplementationSummary } from './effects/implementations.js'
|
||||
|
||||
const scrypt = promisify(scryptCallback)
|
||||
const USERNAME = /^[a-zA-Z0-9_.-]{3,32}$/
|
||||
const JPEG_DATA_URL = /^data:image\/jpeg;base64,[A-Za-z0-9+/]+={0,2}$/
|
||||
const MAX_PLAYMAT_LENGTH = 4_500_000
|
||||
const MAX_CARD_BACK_LENGTH = 1_500_000
|
||||
|
||||
export class AuthError extends Error {
|
||||
constructor(message: string, readonly status = 401) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export interface DeckCardInput {
|
||||
oracleId: string
|
||||
name: string
|
||||
manaCost?: string
|
||||
typeLine: string
|
||||
colorIdentity: string[]
|
||||
oracleText?: string
|
||||
imageUri?: string
|
||||
}
|
||||
|
||||
export interface DeckInput {
|
||||
name: string
|
||||
commander: DeckCardInput
|
||||
cards: DeckCardInput[]
|
||||
cardBack?: string | null
|
||||
}
|
||||
|
||||
export type PlaymatInput =
|
||||
| { kind: 'card'; oracleId: string }
|
||||
| { kind: 'upload'; data: string }
|
||||
|
||||
const userSchema = new Schema({
|
||||
username: { type: String, required: true, trim: true },
|
||||
salt: { type: String, required: true },
|
||||
passwordHash: { type: String, required: true },
|
||||
playmat: { type: Schema.Types.Mixed, default: null, select: false },
|
||||
cardBack: { type: String, default: null, select: false },
|
||||
}, { timestamps: true })
|
||||
userSchema.index({ username: 1 }, { unique: true, collation: { locale: 'en', strength: 2 } })
|
||||
|
||||
const sessionSchema = new Schema({
|
||||
tokenHash: { type: String, required: true, unique: true },
|
||||
userId: { type: Schema.Types.ObjectId, required: true, index: true },
|
||||
createdAt: { type: Date, default: Date.now, expires: '30d' },
|
||||
})
|
||||
|
||||
const deckCardSchema = new Schema({
|
||||
oracleId: { type: String, required: true },
|
||||
name: { type: String, required: true },
|
||||
manaCost: String,
|
||||
typeLine: { type: String, required: true },
|
||||
colorIdentity: [String],
|
||||
oracleText: String,
|
||||
imageUri: String,
|
||||
}, { _id: false })
|
||||
|
||||
const deckSchema = new Schema({
|
||||
owner: { type: Schema.Types.ObjectId, required: true, index: true },
|
||||
deckId: { type: String, required: true },
|
||||
name: { type: String, required: true },
|
||||
commander: { type: deckCardSchema, required: true },
|
||||
cards: { type: [deckCardSchema], default: [] },
|
||||
cardBack: { type: String, default: null },
|
||||
updatedAt: { type: Number, required: true },
|
||||
})
|
||||
deckSchema.index({ owner: 1, deckId: 1 }, { unique: true })
|
||||
|
||||
const User = mongoose.models.User ?? mongoose.model('User', userSchema)
|
||||
const Session = mongoose.models.Session ?? mongoose.model('Session', sessionSchema)
|
||||
const Deck = mongoose.models.Deck ?? mongoose.model('Deck', deckSchema)
|
||||
|
||||
interface DeckRow {
|
||||
deckId: string
|
||||
name: string
|
||||
commander: DeckCardInput
|
||||
cards: DeckCardInput[]
|
||||
cardBack?: string | null
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export async function connectDatabase(
|
||||
uri = process.env.MONGODB_URI || 'mongodb://localhost:27017/commander',
|
||||
): Promise<void> {
|
||||
await mongoose.connect(uri)
|
||||
await Promise.all([User.init(), Session.init(), Deck.init()])
|
||||
}
|
||||
|
||||
export async function closeDatabase(): Promise<void> {
|
||||
await mongoose.disconnect()
|
||||
}
|
||||
|
||||
export async function hashPassword(password: string): Promise<{ salt: string; hash: string }> {
|
||||
const salt = randomBytes(16).toString('hex')
|
||||
const hash = (await scrypt(password, salt, 64)) as Buffer
|
||||
return { salt, hash: hash.toString('hex') }
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, salt: string, hash: string): Promise<boolean> {
|
||||
const actual = (await scrypt(password, salt, 64)) as Buffer
|
||||
const expected = Buffer.from(hash, 'hex')
|
||||
return actual.length === expected.length && timingSafeEqual(actual, expected)
|
||||
}
|
||||
|
||||
function tokenHash(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex')
|
||||
}
|
||||
|
||||
function bearerToken(request: FastifyRequest): string | undefined {
|
||||
const header = request.headers.authorization
|
||||
return header?.startsWith('Bearer ') ? header.slice(7).trim() || undefined : undefined
|
||||
}
|
||||
|
||||
async function startSession(userId: string): Promise<string> {
|
||||
const token = randomBytes(32).toString('hex')
|
||||
await Session.create({ tokenHash: tokenHash(token), userId })
|
||||
return token
|
||||
}
|
||||
|
||||
async function authenticate(request: FastifyRequest): Promise<{ id: string; username: string }> {
|
||||
const token = bearerToken(request)
|
||||
if (!token) throw new AuthError('Sign in required')
|
||||
const session = await Session.findOne({ tokenHash: tokenHash(token) }).lean()
|
||||
if (!session) throw new AuthError('Your session has expired; sign in again')
|
||||
const user = await User.findById(session.userId).select('_id username').lean()
|
||||
if (!user) throw new AuthError('User not found')
|
||||
return { id: String(user._id), username: user.username }
|
||||
}
|
||||
|
||||
function credentials(body: unknown): { username: string; password: string } {
|
||||
const input = body as { username?: unknown; password?: unknown } | null | undefined
|
||||
if (typeof input?.username !== 'string' || typeof input?.password !== 'string') {
|
||||
throw new AuthError('Send a username and a password', 400)
|
||||
}
|
||||
const username = input.username.trim()
|
||||
if (!USERNAME.test(username)) {
|
||||
throw new AuthError('Username must be 3-32 letters, numbers, dots, dashes or underscores', 400)
|
||||
}
|
||||
if (input.password.length < 8 || input.password.length > 200) {
|
||||
throw new AuthError('Password must be 8-200 characters', 400)
|
||||
}
|
||||
return { username, password: input.password }
|
||||
}
|
||||
|
||||
function limitedText(value: unknown, max: number): string | undefined {
|
||||
return typeof value === 'string' && value.length <= max ? value : undefined
|
||||
}
|
||||
|
||||
function parseDeckCard(value: unknown): DeckCardInput | null {
|
||||
if (!value || typeof value !== 'object') return null
|
||||
const card = value as Record<string, unknown>
|
||||
const oracleId = limitedText(card.oracleId, 100)
|
||||
const name = limitedText(card.name, 200)
|
||||
const typeLine = limitedText(card.typeLine, 300)
|
||||
if (!oracleId || !name || !typeLine) return null
|
||||
return {
|
||||
oracleId,
|
||||
name,
|
||||
manaCost: limitedText(card.manaCost, 100),
|
||||
typeLine,
|
||||
colorIdentity: Array.isArray(card.colorIdentity)
|
||||
? card.colorIdentity.filter((color): color is string => typeof color === 'string' && color.length <= 2).slice(0, 8)
|
||||
: [],
|
||||
oracleText: limitedText(card.oracleText, 5_000),
|
||||
imageUri: limitedText(card.imageUri, 500),
|
||||
}
|
||||
}
|
||||
|
||||
function parseDeck(value: unknown): DeckInput | null {
|
||||
if (!value || typeof value !== 'object') return null
|
||||
const deck = value as Record<string, unknown>
|
||||
const name = limitedText(deck.name, 60)
|
||||
const commander = parseDeckCard(deck.commander)
|
||||
if (!name || !commander || !Array.isArray(deck.cards) || deck.cards.length > 250) return null
|
||||
const cards = deck.cards.map(parseDeckCard)
|
||||
if (cards.some(card => !card)) return null
|
||||
const cardBack = 'cardBack' in deck ? parseCardBack(deck.cardBack) : undefined
|
||||
if ('cardBack' in deck && cardBack === undefined) return null
|
||||
return { name, commander, cards: cards as DeckCardInput[], cardBack }
|
||||
}
|
||||
|
||||
function parsePlaymat(value: unknown): PlaymatInput | null | undefined {
|
||||
if (value === null) return null
|
||||
if (!value || typeof value !== 'object') return undefined
|
||||
const choice = value as Record<string, unknown>
|
||||
if (choice.kind === 'card' && typeof choice.oracleId === 'string' && choice.oracleId.length <= 100) {
|
||||
return { kind: 'card', oracleId: choice.oracleId }
|
||||
}
|
||||
if (choice.kind === 'upload' && typeof choice.data === 'string'
|
||||
&& choice.data.length <= MAX_PLAYMAT_LENGTH && JPEG_DATA_URL.test(choice.data)) {
|
||||
return { kind: 'upload', data: choice.data }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function parseCardBack(value: unknown): string | null | undefined {
|
||||
if (value === null) return null
|
||||
if (typeof value !== 'string' || value.length > MAX_CARD_BACK_LENGTH) return undefined
|
||||
if (/^#[0-9a-fA-F]{3,8}$/.test(value)) return value
|
||||
if (JPEG_DATA_URL.test(value)) return value
|
||||
return undefined
|
||||
}
|
||||
|
||||
function toDeck(row: DeckRow, index?: Map<string, ImplementationSummary>) {
|
||||
const enrich = (card: DeckCardInput) => {
|
||||
const implementation = index?.get(card.oracleId)
|
||||
return implementation ? { ...card, implementation } : card
|
||||
}
|
||||
return {
|
||||
id: row.deckId,
|
||||
name: row.name,
|
||||
commander: enrich(row.commander),
|
||||
cards: row.cards.map(enrich),
|
||||
cardBack: row.cardBack ?? null,
|
||||
updatedAt: row.updatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
async function preferences(userId: string) {
|
||||
const user = await User.findById(userId)
|
||||
.select('+playmat +cardBack')
|
||||
.lean<{ playmat?: PlaymatInput | null; cardBack?: string | null }>()
|
||||
if (!user) throw new AuthError('User not found')
|
||||
return { playmat: user.playmat ?? null, cardBack: user.cardBack ?? null }
|
||||
}
|
||||
|
||||
export function registerAccountRoutes(app: FastifyInstance): void {
|
||||
app.post<{ Body: { username?: unknown; password?: unknown } }>('/auth/register', async (request, reply) => {
|
||||
const { username, password } = credentials(request.body)
|
||||
const existing = await User.findOne({ username }).collation({ locale: 'en', strength: 2 }).select('_id').lean()
|
||||
if (existing) return reply.code(409).send({ error: 'That username is taken' })
|
||||
|
||||
const { salt, hash } = await hashPassword(password)
|
||||
try {
|
||||
const user = await User.create({ username, salt, passwordHash: hash })
|
||||
const token = await startSession(String(user._id))
|
||||
return reply.code(201).send({ token, username: user.username })
|
||||
} catch (error) {
|
||||
if ((error as { code?: number }).code === 11000) {
|
||||
return reply.code(409).send({ error: 'That username is taken' })
|
||||
}
|
||||
throw error
|
||||
}
|
||||
})
|
||||
|
||||
app.post<{ Body: { username?: unknown; password?: unknown } }>('/auth/login', async (request, reply) => {
|
||||
const { username, password } = credentials(request.body)
|
||||
const user = await User.findOne({ username }).collation({ locale: 'en', strength: 2 })
|
||||
if (!user || !(await verifyPassword(password, user.salt, user.passwordHash))) {
|
||||
return reply.code(401).send({ error: 'Wrong username or password' })
|
||||
}
|
||||
return { token: await startSession(String(user._id)), username: user.username }
|
||||
})
|
||||
|
||||
app.post('/auth/logout', async request => {
|
||||
const token = bearerToken(request)
|
||||
if (token) await Session.deleteOne({ tokenHash: tokenHash(token) })
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
app.get('/auth/me', async request => {
|
||||
const user = await authenticate(request)
|
||||
return { username: user.username }
|
||||
})
|
||||
|
||||
app.get('/me/decks', async request => {
|
||||
const user = await authenticate(request)
|
||||
const decks = await Deck.find({ owner: user.id }).sort({ updatedAt: -1 }).lean<DeckRow[]>()
|
||||
const index = await implementationIndex()
|
||||
return { decks: decks.map(deck => toDeck(deck, index)) }
|
||||
})
|
||||
|
||||
app.put<{ Params: { id: string } }>(
|
||||
'/me/decks/:id',
|
||||
{ bodyLimit: 6_500_000 },
|
||||
async (request, reply) => {
|
||||
const user = await authenticate(request)
|
||||
const deckId = request.params.id
|
||||
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(deckId)) {
|
||||
return reply.code(400).send({ error: 'Invalid deck id' })
|
||||
}
|
||||
const deck = parseDeck(request.body)
|
||||
if (!deck) return reply.code(400).send({ error: 'Invalid deck' })
|
||||
|
||||
const row = await Deck.findOneAndUpdate(
|
||||
{ owner: user.id, deckId },
|
||||
{ ...deck, updatedAt: Date.now() },
|
||||
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
|
||||
).lean<DeckRow>()
|
||||
if (!row) throw new AuthError('Could not save the deck', 500)
|
||||
return { deck: toDeck(row) }
|
||||
},
|
||||
)
|
||||
|
||||
app.delete<{ Params: { id: string } }>('/me/decks/:id', async request => {
|
||||
const user = await authenticate(request)
|
||||
await Deck.deleteOne({ owner: user.id, deckId: request.params.id })
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
app.get('/me/preferences', async request => {
|
||||
const user = await authenticate(request)
|
||||
return preferences(user.id)
|
||||
})
|
||||
|
||||
app.put<{ Body: Record<string, unknown> }>(
|
||||
'/me/preferences',
|
||||
{ bodyLimit: 6_500_000 },
|
||||
async (request, reply) => {
|
||||
const user = await authenticate(request)
|
||||
const body = request.body ?? {}
|
||||
const update: Record<string, unknown> = {}
|
||||
|
||||
if ('playmat' in body) {
|
||||
const playmat = parsePlaymat(body.playmat)
|
||||
if (playmat === undefined) return reply.code(400).send({ error: 'Invalid playmat' })
|
||||
update.playmat = playmat
|
||||
}
|
||||
if ('cardBack' in body) {
|
||||
const cardBack = parseCardBack(body.cardBack)
|
||||
if (cardBack === undefined) return reply.code(400).send({ error: 'Invalid card back' })
|
||||
update.cardBack = cardBack
|
||||
}
|
||||
|
||||
if (Object.keys(update).length) await User.updateOne({ _id: user.id }, { $set: update })
|
||||
return preferences(user.id)
|
||||
},
|
||||
)
|
||||
}
|
||||
139
backend/src/cards.ts
Normal file
139
backend/src/cards.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
export interface CardFace {
|
||||
name: string
|
||||
mana_cost?: string
|
||||
type_line?: string
|
||||
oracle_text?: string
|
||||
colors: string[]
|
||||
power?: string
|
||||
toughness?: string
|
||||
loyalty?: string
|
||||
defense?: string
|
||||
image_uri?: string
|
||||
}
|
||||
|
||||
export interface Card {
|
||||
oracle_id: string
|
||||
name: string
|
||||
layout: string
|
||||
cmc: number
|
||||
type_line: string
|
||||
colors: string[]
|
||||
color_identity: string[]
|
||||
keywords: string[]
|
||||
rarity?: string
|
||||
legal_formats?: string[]
|
||||
mana_cost?: string
|
||||
oracle_text?: string
|
||||
power?: string
|
||||
toughness?: string
|
||||
loyalty?: string
|
||||
defense?: string
|
||||
image_uri?: string
|
||||
card_faces?: CardFace[]
|
||||
}
|
||||
|
||||
export interface CardFilters {
|
||||
format?: string
|
||||
color?: string
|
||||
type?: string
|
||||
rarity?: string
|
||||
cmcMin?: number
|
||||
cmcMax?: number
|
||||
}
|
||||
|
||||
/** Color filter matches color identity: C is colorless, M is more than one color. */
|
||||
export function matchesCardFilters(card: Card, filters: CardFilters): boolean {
|
||||
if (filters.format && !card.legal_formats?.includes(filters.format)) return false
|
||||
|
||||
if (filters.color) {
|
||||
const identity = card.color_identity
|
||||
const matches = filters.color === 'C'
|
||||
? identity.length === 0
|
||||
: filters.color === 'M'
|
||||
? identity.length > 1
|
||||
: identity.includes(filters.color)
|
||||
if (!matches) return false
|
||||
}
|
||||
|
||||
const type = filters.type
|
||||
if (type) {
|
||||
const typeLines = [card.type_line, ...(card.card_faces?.map(face => face.type_line ?? '') ?? [])]
|
||||
if (!typeLines.some(line => line.toLowerCase().includes(type))) return false
|
||||
}
|
||||
if (filters.rarity && card.rarity !== filters.rarity) return false
|
||||
if (filters.cmcMin !== undefined && card.cmc < filters.cmcMin) return false
|
||||
if (filters.cmcMax !== undefined && card.cmc > filters.cmcMax) return false
|
||||
return true
|
||||
}
|
||||
|
||||
export class CardsUnavailableError extends Error {}
|
||||
|
||||
const DATA_FILE = join(import.meta.dirname, '..', 'data', 'cards.json')
|
||||
|
||||
let data: { cards: Card[]; byId: Map<string, Card>; byName: Map<string, Card> } | undefined
|
||||
|
||||
function namesOf(card: Card): string[] {
|
||||
const names = new Set([card.name, ...(card.card_faces?.map(face => face.name) ?? [])])
|
||||
for (const name of [...names]) {
|
||||
const front = name.split(' // ')[0]
|
||||
if (front) names.add(front)
|
||||
}
|
||||
return [...names]
|
||||
}
|
||||
|
||||
function load() {
|
||||
if (data) return data
|
||||
|
||||
let raw: string
|
||||
try {
|
||||
raw = readFileSync(DATA_FILE, 'utf8')
|
||||
} catch {
|
||||
throw new CardsUnavailableError(
|
||||
`Card data not found at ${DATA_FILE}. Run "npm run import:cards" in backend/.`,
|
||||
)
|
||||
}
|
||||
|
||||
const cards = JSON.parse(raw) as Card[]
|
||||
if (!Array.isArray(cards)) throw new Error(`Invalid card data at ${DATA_FILE}`)
|
||||
|
||||
const byName = new Map<string, Card>()
|
||||
for (const card of cards) {
|
||||
for (const name of namesOf(card)) {
|
||||
const key = name.toLowerCase()
|
||||
if (!byName.has(key)) byName.set(key, card)
|
||||
}
|
||||
}
|
||||
|
||||
data = { cards, byId: new Map(cards.map(card => [card.oracle_id, card])), byName }
|
||||
return data
|
||||
}
|
||||
|
||||
export function getCard(oracleId: string): Card | undefined {
|
||||
return load().byId.get(oracleId)
|
||||
}
|
||||
|
||||
/** Case-insensitive exact lookup; also accepts a split card's front face. */
|
||||
export function findCardByName(name: string): Card | undefined {
|
||||
return load().byName.get(name.trim().toLowerCase())
|
||||
}
|
||||
|
||||
export function allCards(): Card[] {
|
||||
return load().cards
|
||||
}
|
||||
|
||||
export function searchCards(
|
||||
query: string,
|
||||
limit: number,
|
||||
offset = 0,
|
||||
filter?: (card: Card) => boolean,
|
||||
): { total: number; cards: Card[] } {
|
||||
const { cards } = load()
|
||||
const needle = query.trim().toLowerCase()
|
||||
const matches = cards.filter(card =>
|
||||
(!needle || card.name.toLowerCase().includes(needle)) && (!filter || filter(card)),
|
||||
)
|
||||
return { total: matches.length, cards: matches.slice(offset, offset + limit) }
|
||||
}
|
||||
2375
backend/src/effects/compile.ts
Normal file
2375
backend/src/effects/compile.ts
Normal file
File diff suppressed because it is too large
Load Diff
603
backend/src/effects/format.ts
Normal file
603
backend/src/effects/format.ts
Normal file
@@ -0,0 +1,603 @@
|
||||
import type {
|
||||
Ability,
|
||||
CompiledCard,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
} from './types.js'
|
||||
|
||||
const COLOR_NAMES: Record<string, string> = { W: 'white', U: 'blue', B: 'black', R: 'red', G: 'green', C: 'colorless' }
|
||||
|
||||
function formatValue(value: Value): string {
|
||||
switch (value.kind) {
|
||||
case 'number':
|
||||
return String(value.value)
|
||||
case 'x':
|
||||
return 'X'
|
||||
case 'count':
|
||||
return `count(${formatSelector(value.selector)})`
|
||||
case 'source_power':
|
||||
return 'its power'
|
||||
case 'source_toughness':
|
||||
return 'its toughness'
|
||||
case 'cards_in_hand':
|
||||
return `cards in ${value.player === 'you' ? 'your' : "that player's"} hand`
|
||||
case 'max_cards_in_hand':
|
||||
return 'cards in the hand of the opponent with the most cards'
|
||||
case 'max_opponent_count':
|
||||
return `greatest number of ${formatSelector(value.selector)} an opponent controls`
|
||||
case 'total_mana_value':
|
||||
return `total mana value of ${formatSelector(value.selector)}`
|
||||
case 'total_power':
|
||||
return `total power of ${formatSelector(value.selector)}`
|
||||
case 'any_number':
|
||||
return 'any number'
|
||||
case 'event_amount':
|
||||
return 'that much'
|
||||
}
|
||||
}
|
||||
|
||||
function isBareSelector(selector: ObjectSelector): boolean {
|
||||
return selector.types?.length === 0 && Object.keys(selector).every(key => key === 'types')
|
||||
}
|
||||
|
||||
function formatSelector(selector: ObjectSelector): string {
|
||||
const parts: string[] = []
|
||||
if (selector.other) parts.push('other')
|
||||
if (selector.tapped === true) parts.push('tapped')
|
||||
if (selector.tapped === false) parts.push('untapped')
|
||||
if (selector.attacking) parts.push('attacking')
|
||||
if (selector.token) parts.push('token')
|
||||
if (selector.token === false) parts.push('nontoken')
|
||||
if (selector.attached) parts.push(selector.attached)
|
||||
if (selector.colors?.length) {
|
||||
parts.push(selector.colors.map(color => COLOR_NAMES[color] ?? color).join(' and '))
|
||||
}
|
||||
if (selector.supertypes?.length) parts.push(...selector.supertypes)
|
||||
if (selector.subtypes?.length) parts.push(selector.subtypes.join(' '))
|
||||
if (selector.types?.length) {
|
||||
parts.push(selector.types.join(selector.match === 'any' ? ' or ' : ' '))
|
||||
}
|
||||
if (selector.excludeTypes?.length) parts.push(`non-${selector.excludeTypes.join('/')}`)
|
||||
if (selector.counters) parts.push(`with ${selector.counters.atLeast}+ ${selector.counters.counter} counters`)
|
||||
if (selector.keywords?.length) parts.push(`with ${selector.keywords.join(' and ')}`)
|
||||
if (selector.excludeKeywords?.length) parts.push(`without ${selector.excludeKeywords.join(' and ')}`)
|
||||
if (selector.power?.atLeast !== undefined) parts.push(`power ${selector.power.atLeast}+`)
|
||||
if (selector.power?.atMost !== undefined) parts.push(`power ${selector.power.atMost} or less`)
|
||||
if (selector.toughness?.atLeast !== undefined) parts.push(`toughness ${selector.toughness.atLeast}+`)
|
||||
if (selector.toughness?.atMost !== undefined) parts.push(`toughness ${selector.toughness.atMost} or less`)
|
||||
if (selector.manaValue?.atLeast !== undefined) parts.push(`mana value ${selector.manaValue.atLeast}+`)
|
||||
if (selector.manaValue?.atMost !== undefined) parts.push(`mana value ${selector.manaValue.atMost} or less`)
|
||||
if (selector.name) parts.push(`named ${selector.name}`)
|
||||
|
||||
let text = parts.filter(Boolean).join(' ')
|
||||
if (selector.controller === 'you') text += ' you control'
|
||||
else if (selector.controller === 'opponent') text += ' an opponent controls'
|
||||
if (selector.owner === 'you') text += ' you own'
|
||||
else if (selector.owner === 'opponent') text += " you don't own"
|
||||
|
||||
if (!text) text = 'card'
|
||||
|
||||
if (selector.zone === 'graveyard') text += ' from a graveyard'
|
||||
else if (selector.zone === 'library') text += ' from a library'
|
||||
else if (selector.zone === 'hand') text += ' from a hand'
|
||||
else if (selector.zone === 'exile') text += ' in exile'
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
export function formatTarget(target: Target): string {
|
||||
switch (target.kind) {
|
||||
case 'self':
|
||||
return 'this'
|
||||
case 'trigger_subject':
|
||||
return 'the triggering object'
|
||||
case 'previous_target':
|
||||
return 'the chosen target'
|
||||
case 'any':
|
||||
return 'any target'
|
||||
case 'player':
|
||||
if (target.mode === 'each') {
|
||||
if (target.who === 'each_opponent') return 'each opponent'
|
||||
if (target.who === 'each_player') return 'each player'
|
||||
}
|
||||
if (target.who === 'you') return 'you'
|
||||
if (target.who === 'target_player') return 'target player'
|
||||
if (target.who === 'that_player') return 'that player'
|
||||
if (target.who === 'opponent') return 'target opponent'
|
||||
if (target.who === 'its_controller') return 'its controller'
|
||||
if (target.who === 'its_owner') return 'its owner'
|
||||
return target.who
|
||||
case 'player_or_planeswalker':
|
||||
return 'target player or planeswalker'
|
||||
case 'object': {
|
||||
const prefix = target.mode === 'target' ? 'target ' : target.mode === 'each' ? 'each ' : ''
|
||||
const count = target.count ? `${target.upTo ? 'up to ' : ''}${target.count} ` : ''
|
||||
const includeSelf = target.includeSelf ? 'this or ' : ''
|
||||
return `${prefix}${count}${includeSelf}${formatSelector(target.selector)}`
|
||||
}
|
||||
case 'spell':
|
||||
return isBareSelector(target.selector) ? 'target spell' : `target ${formatSelector(target.selector)} spell`
|
||||
case 'ability':
|
||||
return 'target ability'
|
||||
case 'divided':
|
||||
return `divided(${target.max === 'any' ? 'any number' : target.max}${target.selector ? `, ${formatSelector(target.selector)}` : ''})`
|
||||
}
|
||||
}
|
||||
|
||||
function formatMana(mana: ManaSpec): string {
|
||||
if (mana.kind === 'symbols') {
|
||||
return `${mana.symbols.join('')}${mana.restriction ? ` (only ${mana.restriction})` : ''}`
|
||||
}
|
||||
return `${formatValue(mana.amount)} mana of any${mana.oneColor ? ' one' : ''} color${mana.restriction ? ` (only ${mana.restriction})` : ''}`
|
||||
}
|
||||
|
||||
function formatCost(cost: Cost): string {
|
||||
switch (cost.kind) {
|
||||
case 'mana':
|
||||
return cost.symbols
|
||||
case 'tap':
|
||||
return '{T}'
|
||||
case 'untap':
|
||||
return '{Q}'
|
||||
case 'tap_other':
|
||||
return `tap ${formatSelector(cost.selector)}`
|
||||
case 'energy':
|
||||
return `{E} x${cost.amount}`
|
||||
case 'loyalty':
|
||||
return `${cost.amount > 0 ? '+' : ''}${cost.amount} loyalty`
|
||||
case 'pay_life':
|
||||
return `pay ${formatValue(cost.amount)} life`
|
||||
case 'discard':
|
||||
if (cost.amount.kind === 'cards_in_hand' && cost.amount.player === 'you') {
|
||||
return `discard your hand${cost.random ? ' at random' : ''}`
|
||||
}
|
||||
return `discard ${formatValue(cost.amount)} card(s)${cost.random ? ' at random' : ''}`
|
||||
case 'sacrifice':
|
||||
return `sacrifice ${formatSelector(cost.selector)}`
|
||||
case 'sacrifice_self':
|
||||
return 'sacrifice this'
|
||||
case 'exile_self':
|
||||
return 'exile this from a graveyard'
|
||||
case 'exile_from_graveyard':
|
||||
return `exile ${cost.amount ? `${formatValue(cost.amount)} ` : ''}${formatSelector(cost.selector)} from your graveyard`
|
||||
case 'reveal':
|
||||
return `reveal ${formatSelector(cost.selector)} from your hand`
|
||||
case 'choice':
|
||||
return `(${cost.options.map(option => option.map(formatCost).join(' + ')).join(' or ')})`
|
||||
case 'return_to_hand':
|
||||
return `return ${formatSelector(cost.selector)} to its owner's hand`
|
||||
case 'behold':
|
||||
return `behold ${formatSelector(cost.selector)}`
|
||||
case 'waterbend':
|
||||
return `waterbend ${formatValue(cost.amount)}`
|
||||
case 'blight':
|
||||
return `blight ${formatValue(cost.amount)}`
|
||||
case 'choose':
|
||||
return `choose ${cost.what}`
|
||||
case 'put_counter':
|
||||
return `put ${cost.counter} counter on ${formatSelector(cost.selector)}`
|
||||
case 'remove_counters':
|
||||
return `remove ${formatValue(cost.amount)} ${cost.counter} counter(s) from ${cost.selector ? formatSelector(cost.selector) : 'this'}`
|
||||
case 'forage':
|
||||
return 'forage'
|
||||
case 'collect_evidence':
|
||||
return `collect evidence ${cost.amount}`
|
||||
case 'mill':
|
||||
return `mill ${formatValue(cost.amount)} card(s)`
|
||||
}
|
||||
}
|
||||
|
||||
function formatDuration(duration: Duration): string {
|
||||
switch (duration) {
|
||||
case 'permanent':
|
||||
return ''
|
||||
case 'until_end_of_turn':
|
||||
return ', until end of turn'
|
||||
case 'until_your_next_turn':
|
||||
return ', until your next turn'
|
||||
case 'until_end_of_your_next_turn':
|
||||
return ', until the end of your next turn'
|
||||
case 'until_end_of_combat':
|
||||
return ', until end of combat'
|
||||
case 'until_controllers_next_untap_step':
|
||||
return ", until its controller's next untap step"
|
||||
case 'while_source_on_battlefield':
|
||||
return ', for as long as this remains on the battlefield'
|
||||
}
|
||||
}
|
||||
|
||||
function formatToken(token: TokenSpec): string {
|
||||
const parts: string[] = []
|
||||
if (token.tapped) parts.push('tapped')
|
||||
if (token.power && token.toughness) parts.push(`${formatValue(token.power)}/${formatValue(token.toughness)}`)
|
||||
if (token.colors?.length) parts.push(token.colors.map(color => COLOR_NAMES[color] ?? color).join(' and '))
|
||||
if (token.subtypes.length) parts.push(...token.subtypes)
|
||||
if (token.types.length) parts.push(...token.types)
|
||||
if (token.keywords?.length) parts.push(`with ${token.keywords.join(', ')}`)
|
||||
return parts.join(' ')
|
||||
}
|
||||
|
||||
export function formatEffect(effect: Effect): string {
|
||||
switch (effect.op) {
|
||||
case 'damage':
|
||||
return `damage(${formatTarget(effect.target)}, ${formatValue(effect.amount)}${effect.source ? `, from ${formatTarget(effect.source)}` : ''})`
|
||||
case 'draw':
|
||||
return `draw(${effect.player}, ${formatValue(effect.amount)})`
|
||||
case 'discard':
|
||||
return `discard(${effect.player}, ${formatValue(effect.amount)}${effect.random ? ', at random' : ''})`
|
||||
case 'mill':
|
||||
return `mill(${effect.player}, ${formatValue(effect.amount)})`
|
||||
case 'life':
|
||||
return `${effect.mode === 'gain' ? 'gain_life' : 'lose_life'}(${effect.player}, ${formatValue(effect.amount)})`
|
||||
case 'pump':
|
||||
return `pump(${formatTarget(effect.target)}, ${formatValue(effect.power)}/${formatValue(effect.toughness)}${formatDuration(effect.duration)})`
|
||||
case 'grant':
|
||||
return `grant(${formatTarget(effect.target)}, ${effect.keyword}${effect.value ? ` ${effect.value}` : ''}${formatDuration(effect.duration)})`
|
||||
case 'put_counters':
|
||||
return `put_counters(${formatTarget(effect.target)}, ${effect.counter}, ${formatValue(effect.amount)})`
|
||||
case 'remove_counters':
|
||||
return `remove_counters(${formatTarget(effect.target)}, ${effect.counter}, ${formatValue(effect.amount)})`
|
||||
case 'proliferate':
|
||||
return 'proliferate()'
|
||||
case 'create_token':
|
||||
return effect.copyOf
|
||||
? `create_token(${effect.player}, ${formatValue(effect.amount)}, copy of ${formatTarget(effect.copyOf)}${effect.notLegendary ? ', not legendary' : ''})`
|
||||
: `create_token(${effect.player}, ${formatValue(effect.amount)}, ${formatToken(effect.token)})`
|
||||
case 'destroy':
|
||||
return `destroy(${formatTarget(effect.target)})`
|
||||
case 'exile':
|
||||
return `exile(${formatTarget(effect.target)})`
|
||||
case 'sacrifice':
|
||||
return `sacrifice(${effect.player}, ${formatTarget(effect.target)}${effect.unless ? ` unless ${formatCost(effect.unless)}` : ''})`
|
||||
case 'counter':
|
||||
return `counter(${effect.what}, ${formatTarget(effect.target)}${effect.unless ? ` unless ${formatCost(effect.unless)}` : ''})`
|
||||
case 'return_to_hand':
|
||||
return `return_to_hand(${formatTarget(effect.target)})`
|
||||
case 'return_to_battlefield': {
|
||||
const counters = effect.counters
|
||||
? `, ${effect.counters.amount.kind === 'number' ? effect.counters.amount.value : formatValue(effect.counters.amount)} ${effect.counters.counter} counters`
|
||||
: ''
|
||||
return `return_to_battlefield(${formatTarget(effect.target)}${effect.tapped ? ', tapped' : ''}${effect.transformed ? ', transformed' : ''}${counters})`
|
||||
}
|
||||
case 'set_pt':
|
||||
return `set_pt(${formatTarget(effect.target)}, ${formatValue(effect.power)}/${formatValue(effect.toughness)}${formatDuration(effect.duration)})`
|
||||
case 'put_on_top':
|
||||
return `put_on_top(${formatTarget(effect.target)})`
|
||||
case 'tap':
|
||||
return `tap(${formatTarget(effect.target)})`
|
||||
case 'untap':
|
||||
return `untap(${formatTarget(effect.target)})`
|
||||
case 'scry':
|
||||
return `scry(${effect.player}, ${formatValue(effect.amount)})`
|
||||
case 'surveil':
|
||||
return `surveil(${effect.player}, ${formatValue(effect.amount)})`
|
||||
case 'search':
|
||||
return `search(${effect.player}, ${formatSelector(effect.selector)}, ${formatValue(effect.amount)}, to ${effect.destination}${effect.zones?.length === 2 ? ', library+graveyard' : ''}${effect.tapped ? ', tapped' : ''}${effect.shuffle ? ', shuffle' : ''})`
|
||||
case 'shuffle':
|
||||
return `shuffle(${effect.player})`
|
||||
case 'add_mana':
|
||||
return `add_mana(${effect.player}, ${formatMana(effect.mana)})`
|
||||
case 'fight':
|
||||
return `fight(${formatTarget(effect.a)}, ${formatTarget(effect.b)})`
|
||||
case 'regenerate':
|
||||
return `regenerate(${formatTarget(effect.target)})`
|
||||
case 'energy':
|
||||
return `energy(${effect.player}, ${formatValue(effect.amount)})`
|
||||
case 'attach':
|
||||
return `attach(this, ${formatTarget(effect.target)})`
|
||||
case 'restriction':
|
||||
return `restrict(${formatTarget(effect.target)}, ${effect.rule}${formatDuration(effect.duration)})`
|
||||
case 'keyword_action':
|
||||
return `${effect.action.replace(/ /g, '_')}(${effect.target ? formatTarget(effect.target) : ''}${effect.amount ? `${effect.target ? ', ' : ''}${formatValue(effect.amount)}` : ''}${effect.detail ? `, ${effect.detail}` : ''})`
|
||||
case 'level_up':
|
||||
return `level_up(${effect.level})`
|
||||
case 'put_from_among':
|
||||
return `put_from_among(${formatValue(effect.amount)}${effect.selector ? `, ${formatSelector(effect.selector)}` : ''}, to ${effect.destination})`
|
||||
case 'dig':
|
||||
return `dig(${formatValue(effect.amount)}, ${effect.upTo ? 'up to ' : ''}${formatValue(effect.pick)}${effect.pickSelector ? ` ${formatSelector(effect.pickSelector)}` : ''} to ${effect.to}${effect.tapped ? ' tapped' : ''}, rest ${effect.rest}${effect.order ? ` ${effect.order}` : ''}${effect.optional ? ', optional' : ''})`
|
||||
case 'prevent_damage':
|
||||
return `prevent_${effect.combatOnly ? 'combat_' : ''}damage(${formatTarget(effect.target)}, ${effect.amount === 'all' ? 'all' : formatValue(effect.amount)}${formatDuration(effect.duration)})`
|
||||
case 'gain_control':
|
||||
return `gain_control(${formatTarget(effect.target)}${formatDuration(effect.duration)})`
|
||||
case 'emblem':
|
||||
return `emblem("${effect.text}")`
|
||||
case 'transform':
|
||||
return `transform(${formatTarget(effect.target)})`
|
||||
case 'pay':
|
||||
return `pay(${effect.costs.map(formatCost).join(', ')})`
|
||||
case 'conditional':
|
||||
return `if ${formatCondition(effect.condition)}:\n${indent(effect.effects.map(formatEffect).join('\n'))}`
|
||||
case 'modal': {
|
||||
const choose = effect.min === effect.max ? String(effect.min) : `${effect.min}-${effect.max}`
|
||||
const body = effect.modes
|
||||
.map((mode, index) => `${index + 1}. ${mode.map(formatEffect).join('; ')}`)
|
||||
.join('\n')
|
||||
return `choose ${choose}:\n${indent(body)}`
|
||||
}
|
||||
case 'look_top':
|
||||
return `look_top(${effect.player}, ${formatValue(effect.amount)}${effect.reorder ? ', reorder' : ''})`
|
||||
case 'schedule':
|
||||
return `schedule(${effect.when}):\n${indent(effect.effects.map(formatEffect).join('\n'))}`
|
||||
case 'damage_divided':
|
||||
return `damage_divided(${formatValue(effect.amount)}, ${formatTarget(effect.target)})`
|
||||
}
|
||||
}
|
||||
|
||||
function formatCondition(condition: Condition): string {
|
||||
switch (condition.kind) {
|
||||
case 'you_control':
|
||||
return `you control ${condition.atLeast ? `at least ${condition.atLeast} ` : ''}${formatSelector(condition.selector)}`
|
||||
case 'opponent_controls':
|
||||
return `an opponent controls ${formatSelector(condition.selector)}`
|
||||
case 'your_turn':
|
||||
return 'it is your turn'
|
||||
case 'not_your_turn':
|
||||
return "it isn't your turn"
|
||||
case 'source_tapped':
|
||||
return 'this is tapped'
|
||||
case 'life_at_least':
|
||||
return `${condition.player} has at least ${condition.amount} life`
|
||||
case 'life_at_most':
|
||||
return `${condition.player} has at most ${condition.amount} life`
|
||||
case 'cards_in_graveyard':
|
||||
return `${condition.player} has ${condition.atLeast}+ cards in their graveyard`
|
||||
case 'source_untapped':
|
||||
return 'this is untapped'
|
||||
case 'source_attacking':
|
||||
return 'this is attacking'
|
||||
case 'life_above_starting':
|
||||
return `${condition.player} has at least ${condition.amount} life more than their starting life total`
|
||||
case 'hand_empty':
|
||||
return `${condition.player} has no cards in hand`
|
||||
case 'creature_died_this_turn':
|
||||
return `${condition.controller === 'you' ? 'a creature you control' : condition.controller === 'opponent' ? 'a creature an opponent controls' : 'a creature'} died this turn`
|
||||
case 'you_gained_life_this_turn':
|
||||
return `you gained ${condition.atLeast ? `at least ${condition.atLeast} ` : ''}life this turn`
|
||||
case 'you_drew_cards_this_turn':
|
||||
return `you drew ${condition.atLeast ? `${condition.atLeast}+ ` : 'a '}cards this turn`
|
||||
case 'spells_cast_last_turn':
|
||||
return `${condition.who} cast ${condition.atLeast}+ spells last turn`
|
||||
case 'no_spells_last_turn':
|
||||
return 'no spells were cast last turn'
|
||||
case 'attacked_this_turn':
|
||||
return 'this attacked this turn'
|
||||
case 'you_attacked_this_turn':
|
||||
return 'you attacked this turn'
|
||||
case 'defending_player_controls':
|
||||
return `defending player controls ${formatSelector(condition.selector)}`
|
||||
case 'targets':
|
||||
return `it targets ${formatSelector(condition.selector)}`
|
||||
case 'was_kicked':
|
||||
return 'this was kicked'
|
||||
case 'cast':
|
||||
return condition.fromHand ? 'you cast it from your hand' : 'you cast it'
|
||||
case 'in_graveyard':
|
||||
return 'this is in your graveyard'
|
||||
case 'on_battlefield':
|
||||
return 'this is on the battlefield'
|
||||
case 'monarch':
|
||||
return "you're the monarch"
|
||||
case 'initiative':
|
||||
return 'you have the initiative'
|
||||
case 'citys_blessing':
|
||||
return "you have the city's blessing"
|
||||
case 'suspended':
|
||||
return 'this is suspended'
|
||||
case 'bargained':
|
||||
return 'it was bargained'
|
||||
case 'was_creature':
|
||||
return 'it was a creature'
|
||||
case 'opponent_lost_life_this_turn':
|
||||
return 'an opponent lost life this turn'
|
||||
case 'life_changed_this_turn':
|
||||
return 'you gained or lost life this turn'
|
||||
case 'descended_this_turn':
|
||||
return 'you descended this turn'
|
||||
case 'permanent_left_battlefield_this_turn':
|
||||
return 'a permanent you controlled left the battlefield this turn'
|
||||
case 'nonland_permanents_entered_this_turn':
|
||||
return `${condition.atLeast}+ nonland permanents entered the battlefield under your control this turn`
|
||||
case 'attacked_with_total_power':
|
||||
return `you attacked with total power ${condition.atLeast}+ this combat`
|
||||
case 'total_power':
|
||||
return `creatures you control have total power ${condition.atLeast}+`
|
||||
case 'opponent_controls_more_lands':
|
||||
return 'an opponent controls more lands than you'
|
||||
case 'distinct_powers':
|
||||
return `you control ${condition.atLeast}+ creatures with different powers`
|
||||
case 'graveyard_card_types':
|
||||
return `there are ${condition.atLeast}+ card types in your graveyard`
|
||||
case 'no_objects':
|
||||
return `no ${formatSelector(condition.selector)} on the battlefield`
|
||||
case 'cards_in_hand_at_most':
|
||||
return `${condition.who} has ${condition.atMost} or fewer cards in hand`
|
||||
case 'not_their_turn':
|
||||
return 'it is not their turn'
|
||||
case 'no_attackers':
|
||||
return 'no creatures attacked this turn'
|
||||
case 'opponent_poison':
|
||||
return `an opponent has ${condition.atLeast}+ poison counters`
|
||||
case 'tribute_not_paid':
|
||||
return "tribute wasn't paid"
|
||||
case 'had_counters':
|
||||
return condition.counter ? `it had a ${condition.counter} counter on it` : 'it had counters on it'
|
||||
case 'mana_from_treasure':
|
||||
return 'mana from a Treasure was spent to cast it'
|
||||
case 'mana_spent':
|
||||
return `at least ${condition.atLeast} mana was spent to cast it`
|
||||
case 'no_mana_spent':
|
||||
return 'no mana was spent to cast it'
|
||||
case 'mana_symbol_spent':
|
||||
return `${condition.symbols} was spent to cast it`
|
||||
case 'kicked_with':
|
||||
return `it was kicked with ${condition.cost}`
|
||||
case 'more_cards_than_each_opponent':
|
||||
return 'you have more cards in hand than each opponent'
|
||||
case 'first_combat_phase':
|
||||
return 'it is the first combat phase of the turn'
|
||||
case 'not_token':
|
||||
return 'it is not a token'
|
||||
case 'cast_spell_this_turn':
|
||||
return `you've cast ${condition.noncreature ? 'a noncreature ' : 'a '}spell this turn`
|
||||
case 'full_party':
|
||||
return 'you have a full party'
|
||||
case 'graveyard_count':
|
||||
return `there are ${condition.atLeast}+ ${formatSelector(condition.selector)} in your graveyard`
|
||||
case 'creature_power_greater_than_base':
|
||||
return `you control a creature with ${condition.stat} greater than its base ${condition.stat}`
|
||||
case 'if_you_do':
|
||||
return 'you do'
|
||||
case 'if_you_dont':
|
||||
return "you don't"
|
||||
case 'otherwise':
|
||||
return 'otherwise'
|
||||
}
|
||||
}
|
||||
|
||||
function formatTrigger(event: TriggerEvent): string {
|
||||
switch (event.kind) {
|
||||
case 'enters':
|
||||
return `enters(${formatTarget(event.subject)})`
|
||||
case 'dies':
|
||||
return `dies(${formatTarget(event.subject)})`
|
||||
case 'attacks':
|
||||
return `attacks(${formatTarget(event.subject)})`
|
||||
case 'blocks':
|
||||
return `blocks(${formatTarget(event.subject)})`
|
||||
case 'attacks_or_blocks':
|
||||
return `attacks_or_blocks(${formatTarget(event.subject)})`
|
||||
case 'enters_or_attacks':
|
||||
return `enters_or_attacks(${formatTarget(event.subject)})`
|
||||
case 'enters_or_dies':
|
||||
return `enters_or_dies(${formatTarget(event.subject)})`
|
||||
case 'leaves_battlefield':
|
||||
return `leaves_battlefield(${formatTarget(event.subject)})`
|
||||
case 'deals_damage':
|
||||
return `deals_${event.combat ? 'combat_' : ''}damage(${formatTarget(event.subject)}, ${event.recipient})`
|
||||
case 'upkeep':
|
||||
return `upkeep(${event.who})`
|
||||
case 'end_step':
|
||||
return `end_step(${event.who})`
|
||||
case 'begin_combat':
|
||||
return `begin_combat(${event.who})`
|
||||
case 'main_phase':
|
||||
return `${event.phase}_main_phase(${event.who})`
|
||||
case 'cast':
|
||||
return `cast(${event.who}, ${isBareSelector(event.spell) ? 'any spell' : formatSelector(event.spell)}${event.targetsSelf ? ', targets this' : ''}${event.orCopy ? ', or copy' : ''}${event.ordinal ? `, #${event.ordinal} each turn` : ''})`
|
||||
case 'becomes_level':
|
||||
return `becomes_level(${event.level})`
|
||||
case 'draw':
|
||||
return `draw(${event.who}${event.ordinal ? `, #${event.ordinal} each turn` : ''})`
|
||||
case 'counter_placed':
|
||||
return `counter_placed(${formatTarget(event.subject)}${event.counter ? `, ${event.counter}` : ''})`
|
||||
case 'becomes_target':
|
||||
return `becomes_target(${formatTarget(event.subject)})`
|
||||
case 'life':
|
||||
return `${event.mode}_life(${event.who})`
|
||||
}
|
||||
}
|
||||
|
||||
function formatStaticEffect(effect: StaticEffect): string {
|
||||
switch (effect.op) {
|
||||
case 'pump':
|
||||
return `pump(${formatTarget(effect.target)}, ${formatValue(effect.power)}/${formatValue(effect.toughness)})`
|
||||
case 'grant':
|
||||
return `grant(${formatTarget(effect.target)}, ${effect.keyword}${effect.value ? ` ${effect.value}` : ''})`
|
||||
case 'restriction': {
|
||||
const extra = [
|
||||
effect.value ? formatValue(effect.value) : '',
|
||||
effect.comparison ? effect.comparison.replace(/_/g, ' ') : '',
|
||||
effect.detail ?? '',
|
||||
effect.condition ? `if ${formatCondition(effect.condition)}` : '',
|
||||
].filter(Boolean).join(' ')
|
||||
return `restrict(${formatTarget(effect.target)}, ${effect.rule}${extra ? ` ${extra}` : ''})`
|
||||
}
|
||||
case 'enters_tapped':
|
||||
return `enters_tapped(${formatTarget(effect.target)}${effect.unless ? `, unless ${formatCondition(effect.unless)}` : ''})`
|
||||
case 'enters_with_counters':
|
||||
return `enters_with_counters(${formatTarget(effect.target)}, ${effect.counter}, ${formatValue(effect.amount)})`
|
||||
case 'grant_ability':
|
||||
return `grant_ability(${formatTarget(effect.target)}):\n${indent(formatAbility(effect.ability))}`
|
||||
case 'set_pt':
|
||||
return `set_pt(${formatTarget(effect.target)}${effect.base ? ', base' : ''}, ${effect.power ? formatValue(effect.power) : '?'}/${effect.toughness ? formatValue(effect.toughness) : '?'})`
|
||||
case 'control':
|
||||
return `control(${formatTarget(effect.target)})`
|
||||
case 'choose':
|
||||
return `choose(${effect.what})`
|
||||
case 'replacement':
|
||||
return `replace(${effect.what}${effect.target ? `, ${formatTarget(effect.target)}` : ''}, instead ${effect.instead})`
|
||||
case 'cost_reduction':
|
||||
return `cost_reduction(${formatTarget(effect.target)}, ${formatValue(effect.amount)}${effect.condition ? `, if ${formatCondition(effect.condition)}` : ''})`
|
||||
}
|
||||
}
|
||||
|
||||
function indent(text: string, spaces = 2): string {
|
||||
const pad = ' '.repeat(spaces)
|
||||
return text
|
||||
.split('\n')
|
||||
.map(line => `${pad}${line}`)
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
export function formatAbility(ability: Ability): string {
|
||||
switch (ability.kind) {
|
||||
case 'keyword':
|
||||
return `keyword ${ability.keyword}${ability.value ? ` ${ability.value}` : ''}`
|
||||
case 'keywords':
|
||||
return `keywords ${ability.keywords.map(keyword => `${keyword.keyword}${keyword.value ? ` ${keyword.value}` : ''}`).join(', ')}`
|
||||
case 'triggered': {
|
||||
const condition = ability.condition ? ` if ${formatCondition(ability.condition)}` : ''
|
||||
const body = ability.effects.map(formatEffect).join('\n')
|
||||
return `on ${formatTrigger(ability.event)}${condition}${ability.optional ? ' (may)' : ''}:\n${indent(body)}`
|
||||
}
|
||||
case 'activated': {
|
||||
const costs = ability.costs.map(formatCost).join(', ')
|
||||
const condition = ability.condition ? ` if ${formatCondition(ability.condition)}` : ''
|
||||
const limit = ability.activationsPerTurn ? ` (${ability.activationsPerTurn}/turn)` : ''
|
||||
const timing = ability.timing === 'sorcery' ? ' (sorcery speed)' : ''
|
||||
const body = ability.effects.map(formatEffect).join('\n')
|
||||
return `activate ${costs}${condition}${limit}${timing}${ability.optional ? ' (may)' : ''}:\n${indent(body)}`
|
||||
}
|
||||
case 'static': {
|
||||
const condition = ability.condition ? ` if ${formatCondition(ability.condition)}` : ''
|
||||
return `static${condition}:\n${indent(ability.effects.map(formatStaticEffect).join('\n'))}`
|
||||
}
|
||||
case 'spell':
|
||||
return `spell${ability.optional ? ' (may)' : ''}:\n${indent(ability.effects.map(formatEffect).join('\n'))}`
|
||||
case 'additional_cost':
|
||||
return `additional cost${ability.optional ? ' (may)' : ''}: ${ability.costs.map(formatCost).join(', ')}`
|
||||
case 'chapter':
|
||||
return `chapter ${ability.chapters.join(', ')}${ability.optional ? ' (may)' : ''}:\n${indent(ability.effects.map(formatEffect).join('\n'))}`
|
||||
case 'level_band': {
|
||||
const band = ability.max !== undefined ? `${ability.min}-${ability.max}` : `${ability.min}+`
|
||||
const pt = ability.power ? `: ${formatValue(ability.power)}/${formatValue(ability.toughness!)}` : ''
|
||||
return `level ${band}${pt}`
|
||||
}
|
||||
case 'level_pt':
|
||||
return `level_pt(${formatValue(ability.power)}/${formatValue(ability.toughness)})`
|
||||
case 'unsupported':
|
||||
return `unsupported (${ability.reason}): ${ability.text.replace(/\n/g, '\n ')}`
|
||||
}
|
||||
}
|
||||
|
||||
export function formatCard(card: CompiledCard): string {
|
||||
const lines = [`# ${card.name} [${card.status}]`]
|
||||
if (card.faces?.length) {
|
||||
for (const face of card.faces) {
|
||||
lines.push('', `## ${face.name} [${face.status}]`)
|
||||
lines.push(face.abilities.map(formatAbility).join('\n') || '(no abilities)')
|
||||
}
|
||||
} else {
|
||||
lines.push(card.abilities.map(formatAbility).join('\n') || '(no abilities)')
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
236
backend/src/effects/implementations.ts
Normal file
236
backend/src/effects/implementations.ts
Normal file
@@ -0,0 +1,236 @@
|
||||
// Human-authored card implementations live in one plain-text file per oracle
|
||||
// id under data/card-overrides/. The file is pseudocode in the same syntax the
|
||||
// formatter prints, so it stays readable and can be re-compiled by the engine.
|
||||
|
||||
import { readFileSync, statSync } from 'node:fs'
|
||||
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { allCards } from '../cards.js'
|
||||
import type { Card } from '../cards.js'
|
||||
import { compileCard, statusOf } from './compile.js'
|
||||
import { formatCard } from './format.js'
|
||||
import { parsePseudoCard, PseudoParseError } from './pseudo.js'
|
||||
import type { CompiledCard, CompiledFace } from './types.js'
|
||||
|
||||
export type ImplementationStatus = 'supported' | 'partial' | 'unsupported'
|
||||
|
||||
export interface ImplementationSummary {
|
||||
status: ImplementationStatus
|
||||
manual: boolean
|
||||
}
|
||||
|
||||
export interface Implementation {
|
||||
compiled: CompiledCard
|
||||
source: string
|
||||
manual: boolean
|
||||
updatedAt?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
const DEFAULT_DIR = join(import.meta.dirname, '..', '..', 'data', 'card-overrides')
|
||||
const COMPILED_FILE = join(import.meta.dirname, '..', '..', 'data', 'card-effects.json')
|
||||
const ORACLE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
|
||||
export function overridesDir(): string {
|
||||
return process.env.CARD_OVERRIDES_DIR ?? DEFAULT_DIR
|
||||
}
|
||||
|
||||
function overrideFile(oracleId: string): string {
|
||||
if (!ORACLE_ID.test(oracleId)) throw new Error(`Invalid oracle id: ${oracleId}`)
|
||||
return join(overridesDir(), `${oracleId}.pseudo.txt`)
|
||||
}
|
||||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return (error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT'
|
||||
}
|
||||
|
||||
export async function readOverride(oracleId: string): Promise<{ source: string; updatedAt: string } | undefined> {
|
||||
if (!ORACLE_ID.test(oracleId)) return undefined
|
||||
const file = overrideFile(oracleId)
|
||||
try {
|
||||
const [source, info] = await Promise.all([readFile(file, 'utf8'), stat(file)])
|
||||
return { source, updatedAt: info.mtime.toISOString() }
|
||||
} catch (error) {
|
||||
if (isMissing(error)) return undefined
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function readAllOverrides(): Promise<Map<string, string>> {
|
||||
const result = new Map<string, string>()
|
||||
let names: string[]
|
||||
try {
|
||||
names = await readdir(overridesDir())
|
||||
} catch (error) {
|
||||
if (isMissing(error)) return result
|
||||
throw error
|
||||
}
|
||||
|
||||
for (const name of names) {
|
||||
const oracleId = name.replace(/\.pseudo\.txt$/, '')
|
||||
if (name === oracleId || !ORACLE_ID.test(oracleId)) continue
|
||||
const override = await readOverride(oracleId)
|
||||
if (override) result.set(oracleId, override.source)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export async function writeOverride(oracleId: string, source: string): Promise<void> {
|
||||
const file = overrideFile(oracleId)
|
||||
await mkdir(overridesDir(), { recursive: true })
|
||||
const tmp = `${file}.tmp`
|
||||
await writeFile(tmp, source.endsWith('\n') ? source : `${source}\n`, 'utf8')
|
||||
await rename(tmp, file)
|
||||
}
|
||||
|
||||
export async function deleteOverride(oracleId: string): Promise<void> {
|
||||
const file = overrideFile(oracleId)
|
||||
try {
|
||||
await unlink(file)
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error
|
||||
}
|
||||
}
|
||||
|
||||
function facesStatus(faces: CompiledFace[]): ImplementationStatus {
|
||||
if (faces.some(face => face.status === 'unsupported')) {
|
||||
return faces.every(face => face.status === 'unsupported') ? 'unsupported' : 'partial'
|
||||
}
|
||||
return faces.some(face => face.status === 'partial') ? 'partial' : 'supported'
|
||||
}
|
||||
|
||||
/** Parses manual pseudocode and turns it into the same AST the compiler emits. */
|
||||
export function compileImplementation(card: Card, source: string): CompiledCard {
|
||||
const parsed = parsePseudoCard(source)
|
||||
|
||||
if (card.card_faces?.length) {
|
||||
if (!parsed.faces?.length) {
|
||||
throw new PseudoParseError(
|
||||
`this card has ${card.card_faces.length} faces; add "## <face name>" sections`,
|
||||
1,
|
||||
)
|
||||
}
|
||||
if (parsed.faces.length !== card.card_faces.length) {
|
||||
throw new PseudoParseError(
|
||||
`expected ${card.card_faces.length} faces, found ${parsed.faces.length}`,
|
||||
1,
|
||||
)
|
||||
}
|
||||
|
||||
const faces: CompiledFace[] = card.card_faces.map((face, index) => {
|
||||
const manualFace = parsed.faces![index]
|
||||
if (manualFace.name.toLowerCase() !== face.name.toLowerCase()) {
|
||||
throw new PseudoParseError(`expected face "${face.name}", found "${manualFace.name}"`, 1)
|
||||
}
|
||||
return {
|
||||
name: face.name,
|
||||
status: statusOf(manualFace.abilities),
|
||||
abilities: manualFace.abilities,
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
oracle_id: card.oracle_id,
|
||||
name: card.name,
|
||||
status: facesStatus(faces),
|
||||
abilities: [],
|
||||
faces,
|
||||
manual: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (parsed.faces?.length) {
|
||||
throw new PseudoParseError('this card has no faces; remove the "##" sections', 1)
|
||||
}
|
||||
|
||||
return {
|
||||
oracle_id: card.oracle_id,
|
||||
name: card.name,
|
||||
status: statusOf(parsed.abilities),
|
||||
abilities: parsed.abilities,
|
||||
manual: true,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getImplementation(card: Card): Promise<Implementation> {
|
||||
const override = await readOverride(card.oracle_id)
|
||||
if (!override) {
|
||||
const compiled = compileCard(card)
|
||||
return { compiled, source: formatCard(compiled), manual: false }
|
||||
}
|
||||
|
||||
try {
|
||||
return {
|
||||
compiled: compileImplementation(card, override.source),
|
||||
source: override.source,
|
||||
manual: true,
|
||||
updatedAt: override.updatedAt,
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
compiled: compileCard(card),
|
||||
source: override.source,
|
||||
manual: true,
|
||||
updatedAt: override.updatedAt,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface CompiledIndex {
|
||||
byId: Map<string, CompiledCard>
|
||||
mtimeMs: number
|
||||
}
|
||||
|
||||
let compiledIndex: CompiledIndex | undefined
|
||||
|
||||
function loadCompiledIndex(): CompiledIndex {
|
||||
try {
|
||||
const info = statSync(COMPILED_FILE)
|
||||
if (compiledIndex?.mtimeMs === info.mtimeMs) return compiledIndex
|
||||
const cards = JSON.parse(readFileSync(COMPILED_FILE, 'utf8')) as CompiledCard[]
|
||||
compiledIndex = {
|
||||
byId: new Map(cards.map(card => [card.oracle_id, card])),
|
||||
mtimeMs: info.mtimeMs,
|
||||
}
|
||||
} catch {
|
||||
compiledIndex = { byId: new Map(), mtimeMs: 0 }
|
||||
}
|
||||
return compiledIndex
|
||||
}
|
||||
|
||||
async function buildStatusIndex(): Promise<Map<string, ImplementationSummary>> {
|
||||
const cards = allCards()
|
||||
const auto = loadCompiledIndex().byId
|
||||
const overrides = await readAllOverrides()
|
||||
const result = new Map<string, ImplementationSummary>()
|
||||
|
||||
for (const card of cards) {
|
||||
const source = overrides.get(card.oracle_id)
|
||||
if (source !== undefined) {
|
||||
try {
|
||||
const compiled = compileImplementation(card, source)
|
||||
result.set(card.oracle_id, { status: compiled.status, manual: true })
|
||||
} catch {
|
||||
result.set(card.oracle_id, { status: auto.get(card.oracle_id)?.status ?? compileCard(card).status, manual: true })
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const compiled = auto.get(card.oracle_id) ?? compileCard(card)
|
||||
result.set(card.oracle_id, { status: compiled.status, manual: Boolean(compiled.manual) })
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
let statusIndex: Promise<Map<string, ImplementationSummary>> | undefined
|
||||
|
||||
export function implementationIndex(): Promise<Map<string, ImplementationSummary>> {
|
||||
statusIndex ??= buildStatusIndex()
|
||||
return statusIndex
|
||||
}
|
||||
|
||||
export function invalidateImplementationIndex(): void {
|
||||
statusIndex = undefined
|
||||
}
|
||||
1142
backend/src/effects/parse.ts
Normal file
1142
backend/src/effects/parse.ts
Normal file
File diff suppressed because it is too large
Load Diff
1811
backend/src/effects/pseudo.ts
Normal file
1811
backend/src/effects/pseudo.ts
Normal file
File diff suppressed because it is too large
Load Diff
269
backend/src/effects/translate.ts
Normal file
269
backend/src/effects/translate.ts
Normal file
@@ -0,0 +1,269 @@
|
||||
// Natural language -> card pseudocode through an OpenRouter-hosted model.
|
||||
// The model is told to emit pseudocode only, and the answer is parsed before
|
||||
// it reaches the editor, so prose or a guess never becomes an implementation.
|
||||
|
||||
import type { Card } from '../cards.js'
|
||||
import { compileImplementation } from './implementations.js'
|
||||
|
||||
export const DEFAULT_MODEL = 'google/gemini-2.5-flash-lite'
|
||||
const ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions'
|
||||
const MAX_TOKENS = 700
|
||||
|
||||
export class TranslationError extends Error {
|
||||
readonly status: number
|
||||
|
||||
constructor(message: string, status = 502) {
|
||||
super(message)
|
||||
this.name = 'TranslationError'
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
// Kept compact: it is both the model's only context and the format contract.
|
||||
// Anything not listed here is rejected by the parser, so the model must not
|
||||
// invent operations.
|
||||
export const PSEUDO_GUIDE = `Pseudocode is line-oriented. Ability headers sit at column 0 and end with a colon. Their effects are indented two spaces, one call per line. Semicolons separate multiple effects on one line.
|
||||
|
||||
Multi-face cards use "## <exact face name>" lines, one section per face, in card order. Use "(no abilities)" for a face with none. A leading "# Card [status]" line is optional and not needed.
|
||||
|
||||
Ability headers:
|
||||
on <trigger>[ if <condition>][ (may)]:
|
||||
activate <cost>[, <cost>...][ if <condition>][ (N/turn)][ (sorcery speed)][ (may)]:
|
||||
static[ if <condition>]:
|
||||
spell[(may)]:
|
||||
keyword <Keyword>[ value]
|
||||
keywords <Keyword>, <Keyword>
|
||||
additional cost[(may)]: <cost>
|
||||
chapter <I>, <II>[(may)]:
|
||||
level <min>-<max>[: <power>/<toughness>]
|
||||
level <min>+[: <power>/<toughness>]
|
||||
level_pt(<power>/<toughness>)
|
||||
|
||||
Triggers:
|
||||
enters(target), dies(target), attacks(target), blocks(target), attacks_or_blocks(target),
|
||||
enters_or_attacks(target), enters_or_dies(target), leaves_battlefield(target),
|
||||
deals_damage(target, player|creature|permanent|any), deals_combat_damage(...),
|
||||
upkeep(you|opponent|each_player), end_step(...), begin_combat(...),
|
||||
first_main_phase(...), postcombat_main_phase(...), becomes_level(N),
|
||||
cast(you|opponent|each_player, <spell selector>|any spell[, targets this][, or copy][, #N each turn]),
|
||||
draw(you|opponent|each_player[, #N each turn]), counter_placed(target[, counter]),
|
||||
becomes_target(target), gain_life(you|opponent|each_player), lose_life(...)
|
||||
|
||||
Targets:
|
||||
this, the triggering object, the chosen target, any target, target player,
|
||||
target opponent, each opponent, each player, target player or planeswalker,
|
||||
target spell, target ability, target <selector>, each <selector>,
|
||||
up to N target <selector>, N <selector>, this or <selector>, divided(<max>[, <selector>])
|
||||
|
||||
Selectors begin with optional state words: other, tapped, untapped, attacking, token,
|
||||
equipped, enchanted. Then optional colors (white blue black red green colorless),
|
||||
supertypes, subtypes, and types. Suffixes: "you control", "an opponent controls",
|
||||
"you own", "you don't own", "with <keyword>", "without <keyword>",
|
||||
"power N+" / "power N or less", "toughness N+" / "toughness N or less",
|
||||
"mana value N+" / "mana value N or less", "named <name>",
|
||||
"from a graveyard", "from a library", "from a hand", "in exile", "on the battlefield", "on the stack".
|
||||
|
||||
Values: a number, X, count(<selector>), its power, its toughness,
|
||||
cards in your hand, cards in that player's hand, total power of <selector>,
|
||||
total mana value of <selector>, greatest number of <selector> an opponent controls,
|
||||
that much, any number.
|
||||
|
||||
Costs: {T}, {Q}, {2}{G}, {E} xN, +1 loyalty, -2 loyalty, pay N life,
|
||||
discard N card(s)[ at random], discard your hand, sacrifice this, sacrifice <selector>,
|
||||
tap <selector>, exile this from a graveyard, exile N <selector> from your graveyard,
|
||||
reveal <selector> from your hand, return <selector> to its owner's hand,
|
||||
behold <selector>, waterbend <value>, blight <value>, choose <text>,
|
||||
put <counter> counter on <selector>, forage, collect evidence N, mill N card(s).
|
||||
A choice is written (cost or cost) or (cost + cost).
|
||||
|
||||
Effects, one call per line:
|
||||
damage(target, amount[, from source])
|
||||
damage_divided(amount, target)
|
||||
draw(player, amount)
|
||||
discard(player, amount[, at random])
|
||||
mill(player, amount)
|
||||
gain_life(player, amount)
|
||||
lose_life(player, amount)
|
||||
pump(target, power/toughness[, duration])
|
||||
set_pt(target, power/toughness[, duration])
|
||||
grant(target, Keyword[ value][, duration])
|
||||
put_counters(target, counter, amount)
|
||||
remove_counters(target, counter, amount)
|
||||
proliferate()
|
||||
create_token(player, amount, [tapped ]power/toughness colors subtypes types[ with keyword, keyword])
|
||||
destroy(target), exile(target), tap(target), untap(target), regenerate(target)
|
||||
sacrifice(player, target[, unless cost])
|
||||
counter(spell|ability, target[, unless cost])
|
||||
return_to_hand(target), put_on_top(target)
|
||||
return_to_battlefield(target[, tapped][, transformed][, amount counter counters])
|
||||
scry(player, amount), surveil(player, amount)
|
||||
search(player, selector, amount, to hand|battlefield|graveyard|top|bottom[, tapped][, shuffle])
|
||||
shuffle(player)
|
||||
add_mana(player, {G}{G} | amount mana of any color)
|
||||
fight(a, b)
|
||||
energy(player, amount)
|
||||
attach(this, target)
|
||||
restrict(target, cant_attack|cant_block|doesnt_untap[, duration])
|
||||
prevent_damage(target, amount|all[, duration])
|
||||
prevent_combat_damage(target, amount|all[, duration])
|
||||
gain_control(target[, duration])
|
||||
emblem("text")
|
||||
transform(target)
|
||||
pay(cost)
|
||||
look_top(player, amount[, reorder])
|
||||
level_up(N)
|
||||
put_from_among(amount[, selector], to hand|graveyard|battlefield|top|bottom)
|
||||
dig(amount, up to? pick [selector] to hand|battlefield[ tapped], rest bottom|graveyard|top[ any|random][, optional])
|
||||
Other keyword actions: action_name(target) or action_name(amount, detail)
|
||||
|
||||
Nested blocks:
|
||||
if <condition>:
|
||||
<effects>
|
||||
choose <min>[-<max>]:
|
||||
1. <effects separated by ;>
|
||||
2. <effects separated by ;>
|
||||
schedule(next_upkeep|next_end_step):
|
||||
<effects>
|
||||
|
||||
Static effects:
|
||||
pump(target, power/toughness)
|
||||
grant(target, Keyword[ value])
|
||||
restrict(target, rule[ detail][ if <condition>])
|
||||
enters_tapped(target[, unless <condition>])
|
||||
enters_with_counters(target, counter, amount)
|
||||
grant_ability(target):
|
||||
<one ability block>
|
||||
set_pt(target[, base], power/toughness|?)
|
||||
control(target)
|
||||
choose(creature_type|color|card_name|player|opponent|number)
|
||||
replace(dies|leaves_battlefield|discard|draw[, target], instead exile|return_to_hand|return_to_library|prevent)
|
||||
cost_reduction(target, amount[, if <condition>])
|
||||
|
||||
Common conditions: you control <selector>, you control at least N <selector>,
|
||||
an opponent controls <selector>, it is your turn, it isn't your turn,
|
||||
this is tapped, this is untapped, this is attacking, <player> has at least N life,
|
||||
<player> has at most N life, <player> has N+ cards in their graveyard,
|
||||
<player> has no cards in hand, a creature died this turn,
|
||||
you gained at least N life this turn, you drew N+ cards this turn,
|
||||
you cast it from your hand, this is in your graveyard, this is on the battlefield,
|
||||
you're the monarch, you have the initiative, it was kicked,
|
||||
you've cast a spell this turn, you've cast a noncreature spell this turn,
|
||||
no creatures attacked this turn, you do, you don't, otherwise.
|
||||
|
||||
Durations: permanent (default), until end of turn, until your next turn,
|
||||
until end of combat, until its controller's next untap step,
|
||||
for as long as this remains on the battlefield.
|
||||
|
||||
Players: you, opponent, each_opponent, each_player, target_player, that_player,
|
||||
its_controller, its_owner.
|
||||
|
||||
Example:
|
||||
on enters(this):
|
||||
gain_life(you, 1)
|
||||
|
||||
activate {T}:
|
||||
add_mana(you, {G})
|
||||
|
||||
spell:
|
||||
draw(you, 2)`
|
||||
|
||||
const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the card pseudocode language below.
|
||||
|
||||
Output rules:
|
||||
- Answer with pseudocode only. No explanation, no code fences, no card header, no comments.
|
||||
- Use only the syntax below. Never invent an operation or a keyword argument.
|
||||
- If an ability cannot be expressed, use: unsupported (<short reason>): <original oracle text>
|
||||
- For multi-face cards, output only the "## <face name>" sections in the given order.
|
||||
|
||||
${PSEUDO_GUIDE}`
|
||||
|
||||
function describeCard(card: Card): string {
|
||||
if (card.card_faces?.length) {
|
||||
const faces = card.card_faces.map(face => [
|
||||
`## ${face.name}`,
|
||||
face.type_line ? `Type: ${face.type_line}` : '',
|
||||
face.oracle_text || '(no abilities)',
|
||||
].filter(Boolean).join('\n'))
|
||||
return [`Card: ${card.name}`, `Layout: ${card.layout}`, ...faces].join('\n\n')
|
||||
}
|
||||
|
||||
return [
|
||||
`Card: ${card.name}`,
|
||||
`Type: ${card.type_line}`,
|
||||
`Oracle text:\n${card.oracle_text || '(no abilities)'}`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/** Removes the code fence models add out of habit. Everything else is kept. */
|
||||
export function cleanTranslation(text: string): string {
|
||||
const trimmed = text.trim()
|
||||
const fenced = trimmed.match(/^```[^\n]*\n([\s\S]*?)\n```$/)
|
||||
return (fenced ? fenced[1] : trimmed).trim()
|
||||
}
|
||||
|
||||
interface ChatResponse {
|
||||
choices?: Array<{ message?: { content?: unknown } }>
|
||||
error?: { message?: string }
|
||||
}
|
||||
|
||||
export interface TranslateOptions {
|
||||
apiKey?: string
|
||||
model?: string
|
||||
fetch?: typeof fetch
|
||||
}
|
||||
|
||||
export async function translateCard(card: Card, options: TranslateOptions = {}): Promise<string> {
|
||||
const apiKey = options.apiKey ?? process.env.OPENROUTER_API_KEY
|
||||
if (!apiKey) {
|
||||
throw new TranslationError('OPENROUTER_API_KEY is not set on the backend.', 503)
|
||||
}
|
||||
|
||||
const fetchImpl = options.fetch ?? fetch
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetchImpl(ENDPOINT, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Title': 'Commander card pseudocode translator',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: options.model ?? process.env.OPENROUTER_MODEL ?? DEFAULT_MODEL,
|
||||
messages: [
|
||||
{ role: 'system', content: SYSTEM_PROMPT },
|
||||
{ role: 'user', content: describeCard(card) },
|
||||
],
|
||||
temperature: 0,
|
||||
max_tokens: MAX_TOKENS,
|
||||
}),
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
})
|
||||
} catch (error) {
|
||||
throw new TranslationError(`Could not reach OpenRouter: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
|
||||
const data = await response.json().catch(() => undefined) as ChatResponse | undefined
|
||||
if (!response.ok) {
|
||||
const detail = data?.error?.message ? `: ${data.error.message}` : ''
|
||||
throw new TranslationError(`OpenRouter returned ${response.status}${detail}`)
|
||||
}
|
||||
|
||||
const content = data?.choices?.[0]?.message?.content
|
||||
if (typeof content !== 'string') {
|
||||
throw new TranslationError('OpenRouter returned no text.')
|
||||
}
|
||||
|
||||
const source = cleanTranslation(content)
|
||||
if (!source) throw new TranslationError('OpenRouter returned an empty answer.')
|
||||
|
||||
try {
|
||||
compileImplementation(card, source)
|
||||
} catch (error) {
|
||||
throw new TranslationError(
|
||||
`The model did not return valid pseudocode: ${error instanceof Error ? error.message : String(error)}`,
|
||||
)
|
||||
}
|
||||
|
||||
return source
|
||||
}
|
||||
336
backend/src/effects/types.ts
Normal file
336
backend/src/effects/types.ts
Normal file
@@ -0,0 +1,336 @@
|
||||
// Canonical card-effect AST. The oracle-text compiler emits these nodes and the
|
||||
// game engine consumes them. Keep this file free of parsing logic.
|
||||
|
||||
export type Zone = 'battlefield' | 'hand' | 'graveyard' | 'library' | 'exile' | 'stack' | 'command'
|
||||
|
||||
export type PlayerRef =
|
||||
| 'you'
|
||||
| 'opponent'
|
||||
| 'each_opponent'
|
||||
| 'each_player'
|
||||
| 'target_player'
|
||||
| 'that_player'
|
||||
| 'its_controller'
|
||||
| 'its_owner'
|
||||
|
||||
export interface ObjectSelector {
|
||||
/** Type-line words that must all match unless `match` is 'any'. */
|
||||
types?: string[]
|
||||
match?: 'all' | 'any'
|
||||
excludeTypes?: string[]
|
||||
supertypes?: string[]
|
||||
subtypes?: string[]
|
||||
controller?: 'you' | 'opponent' | 'any'
|
||||
owner?: 'you' | 'opponent'
|
||||
colors?: string[]
|
||||
other?: boolean
|
||||
attached?: 'equipped' | 'enchanted'
|
||||
zone?: Zone
|
||||
tapped?: boolean
|
||||
attacking?: boolean
|
||||
token?: boolean
|
||||
name?: string
|
||||
counters?: { counter: string; atLeast: number }
|
||||
power?: { atLeast?: number; atMost?: number }
|
||||
toughness?: { atLeast?: number; atMost?: number }
|
||||
manaValue?: { atLeast?: number; atMost?: number }
|
||||
keywords?: string[]
|
||||
excludeKeywords?: string[]
|
||||
}
|
||||
|
||||
export type Target =
|
||||
| { kind: 'self' }
|
||||
| { kind: 'trigger_subject' }
|
||||
| { kind: 'previous_target' }
|
||||
| { kind: 'object'; selector: ObjectSelector; mode: 'target' | 'each' | 'choose'; count?: number; upTo?: boolean; includeSelf?: boolean }
|
||||
| { kind: 'player'; who: PlayerRef; mode: 'target' | 'each' }
|
||||
| { kind: 'player_or_planeswalker'; mode: 'target' }
|
||||
| { kind: 'any' }
|
||||
| { kind: 'spell'; selector: ObjectSelector; mode: 'target' | 'each' }
|
||||
| { kind: 'ability'; selector?: ObjectSelector; mode: 'target' }
|
||||
| { kind: 'divided'; max: number | 'any'; selector?: ObjectSelector }
|
||||
|
||||
export type Value =
|
||||
| { kind: 'number'; value: number }
|
||||
| { kind: 'x' }
|
||||
| { kind: 'count'; selector: ObjectSelector }
|
||||
| { kind: 'source_power' }
|
||||
| { kind: 'source_toughness' }
|
||||
| { kind: 'cards_in_hand'; player: PlayerRef }
|
||||
| { kind: 'max_cards_in_hand' }
|
||||
| { kind: 'max_opponent_count'; selector: ObjectSelector }
|
||||
| { kind: 'total_mana_value'; selector: ObjectSelector }
|
||||
| { kind: 'total_power'; selector: ObjectSelector }
|
||||
| { kind: 'any_number' }
|
||||
| { kind: 'event_amount' }
|
||||
|
||||
export type ManaSpec =
|
||||
| { kind: 'symbols'; symbols: string[]; restriction?: string }
|
||||
| { kind: 'any_color'; amount: Value; oneColor: boolean; restriction?: string }
|
||||
|
||||
export interface TokenSpec {
|
||||
name?: string
|
||||
types: string[]
|
||||
subtypes: string[]
|
||||
colors: string[]
|
||||
power?: Value
|
||||
toughness?: Value
|
||||
keywords?: string[]
|
||||
tapped?: boolean
|
||||
}
|
||||
|
||||
export type Duration =
|
||||
| 'permanent'
|
||||
| 'until_end_of_turn'
|
||||
| 'until_your_next_turn'
|
||||
| 'until_end_of_your_next_turn'
|
||||
| 'until_end_of_combat'
|
||||
| 'until_controllers_next_untap_step'
|
||||
| 'while_source_on_battlefield'
|
||||
|
||||
export interface KeywordAbility {
|
||||
kind: 'keyword'
|
||||
keyword: string
|
||||
value?: string
|
||||
}
|
||||
|
||||
export type Cost =
|
||||
| { kind: 'mana'; symbols: string }
|
||||
| { kind: 'tap' }
|
||||
| { kind: 'untap' }
|
||||
| { kind: 'tap_other'; selector: ObjectSelector }
|
||||
| { kind: 'energy'; amount: number }
|
||||
| { kind: 'loyalty'; amount: number }
|
||||
| { kind: 'pay_life'; amount: Value }
|
||||
| { kind: 'discard'; amount: Value; player: PlayerRef; random?: boolean }
|
||||
| { kind: 'sacrifice'; selector: ObjectSelector }
|
||||
| { kind: 'sacrifice_self' }
|
||||
| { kind: 'exile_self' }
|
||||
| { kind: 'exile_from_graveyard'; selector: ObjectSelector; amount?: Value }
|
||||
| { kind: 'reveal'; selector: ObjectSelector }
|
||||
| { kind: 'choice'; options: Cost[][] }
|
||||
| { kind: 'return_to_hand'; selector: ObjectSelector }
|
||||
| { kind: 'behold'; selector: ObjectSelector }
|
||||
| { kind: 'waterbend'; amount: Value }
|
||||
| { kind: 'blight'; amount: Value }
|
||||
| { kind: 'choose'; what: string }
|
||||
| { kind: 'put_counter'; counter: string; selector: ObjectSelector }
|
||||
| { kind: 'remove_counters'; counter: string; amount: Value; selector?: ObjectSelector }
|
||||
| { kind: 'forage' }
|
||||
| { kind: 'collect_evidence'; amount: number }
|
||||
| { kind: 'mill'; amount: Value }
|
||||
|
||||
export type Condition =
|
||||
| { kind: 'you_control'; selector: ObjectSelector; atLeast?: number }
|
||||
| { kind: 'opponent_controls'; selector: ObjectSelector; atLeast?: number }
|
||||
| { kind: 'your_turn' }
|
||||
| { kind: 'not_your_turn' }
|
||||
| { kind: 'source_tapped' }
|
||||
| { kind: 'source_untapped' }
|
||||
| { kind: 'source_attacking' }
|
||||
| { kind: 'life_at_least'; player: PlayerRef; amount: number }
|
||||
| { kind: 'life_at_most'; player: PlayerRef; amount: number }
|
||||
| { kind: 'life_above_starting'; player: PlayerRef; amount: number }
|
||||
| { kind: 'cards_in_graveyard'; player: PlayerRef; atLeast: number }
|
||||
| { kind: 'hand_empty'; player: PlayerRef }
|
||||
| { kind: 'creature_died_this_turn'; controller?: 'you' | 'opponent' }
|
||||
| { kind: 'you_gained_life_this_turn'; atLeast?: number }
|
||||
| { kind: 'you_drew_cards_this_turn'; atLeast?: number }
|
||||
| { kind: 'spells_cast_last_turn'; who: 'you' | 'opponent' | 'each_player' | 'a_player'; atLeast: number }
|
||||
| { kind: 'no_spells_last_turn' }
|
||||
| { kind: 'attacked_this_turn' }
|
||||
| { kind: 'you_attacked_this_turn' }
|
||||
| { kind: 'defending_player_controls'; selector: ObjectSelector }
|
||||
| { kind: 'targets'; selector: ObjectSelector }
|
||||
| { kind: 'was_kicked' }
|
||||
| { kind: 'cast'; fromHand?: boolean }
|
||||
| { kind: 'in_graveyard' }
|
||||
| { kind: 'on_battlefield' }
|
||||
| { kind: 'monarch' }
|
||||
| { kind: 'initiative' }
|
||||
| { kind: 'citys_blessing' }
|
||||
| { kind: 'suspended' }
|
||||
| { kind: 'bargained' }
|
||||
| { kind: 'was_creature' }
|
||||
| { kind: 'opponent_lost_life_this_turn' }
|
||||
| { kind: 'life_changed_this_turn' }
|
||||
| { kind: 'descended_this_turn' }
|
||||
| { kind: 'permanent_left_battlefield_this_turn'; controller: 'you' }
|
||||
| { kind: 'nonland_permanents_entered_this_turn'; atLeast: number }
|
||||
| { kind: 'attacked_with_total_power'; atLeast: number }
|
||||
| { kind: 'total_power'; controller: 'you'; atLeast: number }
|
||||
| { kind: 'opponent_controls_more_lands' }
|
||||
| { kind: 'distinct_powers'; atLeast: number }
|
||||
| { kind: 'graveyard_card_types'; atLeast: number }
|
||||
| { kind: 'no_objects'; selector: ObjectSelector }
|
||||
| { kind: 'cards_in_hand_at_most'; who: PlayerRef; atMost: number }
|
||||
| { kind: 'not_their_turn' }
|
||||
| { kind: 'no_attackers' }
|
||||
| { kind: 'opponent_poison'; atLeast: number }
|
||||
| { kind: 'tribute_not_paid' }
|
||||
| { kind: 'had_counters'; counter?: string }
|
||||
| { kind: 'mana_from_treasure' }
|
||||
| { kind: 'mana_spent'; atLeast: number }
|
||||
| { kind: 'no_mana_spent' }
|
||||
| { kind: 'mana_symbol_spent'; symbols: string }
|
||||
| { kind: 'kicked_with'; cost: string }
|
||||
| { kind: 'more_cards_than_each_opponent' }
|
||||
| { kind: 'first_combat_phase' }
|
||||
| { kind: 'not_token' }
|
||||
| { kind: 'cast_spell_this_turn'; noncreature?: boolean }
|
||||
| { kind: 'full_party' }
|
||||
| { kind: 'graveyard_count'; selector: ObjectSelector; atLeast: number }
|
||||
| { kind: 'creature_power_greater_than_base'; controller: 'you'; stat: 'power' | 'toughness' }
|
||||
| { kind: 'if_you_do' }
|
||||
| { kind: 'if_you_dont' }
|
||||
| { kind: 'otherwise' }
|
||||
|
||||
export type TriggerEvent =
|
||||
| { kind: 'enters'; subject: Target }
|
||||
| { kind: 'dies'; subject: Target }
|
||||
| { kind: 'attacks'; subject: Target }
|
||||
| { kind: 'blocks'; subject: Target }
|
||||
| { kind: 'attacks_or_blocks'; subject: Target }
|
||||
| { kind: 'enters_or_attacks'; subject: Target }
|
||||
| { kind: 'enters_or_dies'; subject: Target }
|
||||
| { kind: 'leaves_battlefield'; subject: Target }
|
||||
| { kind: 'deals_damage'; subject: Target; recipient: 'player' | 'creature' | 'permanent' | 'any'; combat: boolean }
|
||||
| { kind: 'upkeep'; who: 'you' | 'opponent' | 'each_player' }
|
||||
| { kind: 'end_step'; who: 'you' | 'opponent' | 'each_player' }
|
||||
| { kind: 'begin_combat'; who: 'you' | 'opponent' | 'each_player' }
|
||||
| { kind: 'main_phase'; who: 'you' | 'opponent' | 'each_player'; phase: 'first' | 'postcombat' }
|
||||
| { kind: 'cast'; who: 'you' | 'opponent' | 'each_player'; spell: ObjectSelector; targetsSelf?: boolean; ordinal?: number; orCopy?: boolean }
|
||||
| { kind: 'becomes_level'; level: number }
|
||||
| { kind: 'draw'; who: 'you' | 'opponent' | 'each_player'; ordinal?: number }
|
||||
| { kind: 'counter_placed'; subject: Target; counter?: string }
|
||||
| { kind: 'becomes_target'; subject: Target }
|
||||
| { kind: 'life'; who: 'you' | 'opponent' | 'each_player'; mode: 'gain' | 'lose' }
|
||||
|
||||
export type Effect =
|
||||
| { op: 'damage'; target: Target; amount: Value; source?: Target }
|
||||
| { op: 'draw'; player: PlayerRef; amount: Value }
|
||||
| { op: 'discard'; player: PlayerRef; amount: Value; random?: boolean }
|
||||
| { op: 'mill'; player: PlayerRef; amount: Value }
|
||||
| { op: 'life'; player: PlayerRef; amount: Value; mode: 'gain' | 'lose' }
|
||||
| { op: 'pump'; target: Target; power: Value; toughness: Value; duration: Duration }
|
||||
| { op: 'set_pt'; target: Target; power: Value; toughness: Value; duration: Duration }
|
||||
| { op: 'grant'; target: Target; keyword: string; value?: string; duration: Duration }
|
||||
| { op: 'put_counters'; target: Target; counter: string; amount: Value }
|
||||
| { op: 'remove_counters'; target: Target; counter: string; amount: Value }
|
||||
| { op: 'proliferate' }
|
||||
| { op: 'create_token'; player: PlayerRef; amount: Value; token: TokenSpec; copyOf?: Target; notLegendary?: boolean }
|
||||
| { op: 'destroy'; target: Target }
|
||||
| { op: 'exile'; target: Target }
|
||||
| { op: 'sacrifice'; player: PlayerRef; target: Target; unless?: Cost }
|
||||
| { op: 'counter'; what: 'spell' | 'ability'; target: Target; unless?: Cost }
|
||||
| { op: 'return_to_hand'; target: Target }
|
||||
| { op: 'return_to_battlefield'; target: Target; tapped: boolean; transformed?: boolean; counters?: { counter: string; amount: Value } }
|
||||
| { op: 'put_on_top'; target: Target }
|
||||
| { op: 'tap'; target: Target }
|
||||
| { op: 'untap'; target: Target }
|
||||
| { op: 'scry'; player: PlayerRef; amount: Value }
|
||||
| { op: 'surveil'; player: PlayerRef; amount: Value }
|
||||
| { op: 'search'; player: PlayerRef; selector: ObjectSelector; amount: Value; destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean; shuffle: boolean; zones?: ('library' | 'graveyard')[] }
|
||||
| { op: 'shuffle'; player: PlayerRef }
|
||||
| { op: 'add_mana'; player: PlayerRef; mana: ManaSpec }
|
||||
| { op: 'fight'; a: Target; b: Target }
|
||||
| { op: 'regenerate'; target: Target }
|
||||
| { op: 'energy'; player: PlayerRef; amount: Value }
|
||||
| { op: 'attach'; target: Target }
|
||||
| { op: 'restriction'; target: Target; rule: 'cant_attack' | 'cant_block' | 'doesnt_untap'; duration: Duration }
|
||||
| { op: 'keyword_action'; action: string; amount?: Value; detail?: string; target?: Target }
|
||||
| { op: 'prevent_damage'; target: Target; amount: Value | 'all'; combatOnly?: boolean; duration: Duration }
|
||||
| { op: 'gain_control'; target: Target; duration: Duration }
|
||||
| { op: 'emblem'; text: string }
|
||||
| { op: 'transform'; target: Target }
|
||||
| { op: 'pay'; costs: Cost[] }
|
||||
| { op: 'conditional'; condition: Condition; effects: Effect[] }
|
||||
| { op: 'modal'; min: number; max: number; modes: Effect[][] }
|
||||
| { op: 'look_top'; player: PlayerRef; amount: Value; reorder?: boolean }
|
||||
| { op: 'schedule'; when: 'next_upkeep' | 'next_end_step'; effects: Effect[] }
|
||||
| { op: 'level_up'; level: number }
|
||||
| { op: 'put_from_among'; player: PlayerRef; selector?: ObjectSelector; amount: Value; destination: 'hand' | 'graveyard' | 'battlefield' | 'top' | 'bottom' }
|
||||
| { op: 'dig'; player: PlayerRef; amount: Value; pick: Value; upTo?: boolean; pickSelector?: ObjectSelector; to: 'hand' | 'battlefield'; rest: 'bottom' | 'graveyard' | 'top'; order?: 'any' | 'random'; optional?: boolean; tapped?: boolean }
|
||||
| { op: 'damage_divided'; amount: Value; target: Target }
|
||||
|
||||
export type StaticEffect =
|
||||
| { op: 'pump'; target: Target; power: Value; toughness: Value }
|
||||
| { op: 'grant'; target: Target; keyword: string; value?: string }
|
||||
| { op: 'grant_ability'; target: Target; ability: Ability }
|
||||
| { op: 'restriction'; target: Target; rule: string; value?: Value; comparison?: 'or_greater' | 'or_less'; detail?: string; condition?: Condition }
|
||||
| { op: 'enters_tapped'; target: Target; unless?: Condition }
|
||||
| { op: 'enters_with_counters'; target: Target; counter: string; amount: Value }
|
||||
| { op: 'set_pt'; target: Target; power?: Value; toughness?: Value; base?: boolean }
|
||||
| { op: 'control'; target: Target }
|
||||
| { op: 'choose'; what: 'creature_type' | 'color' | 'card_name' | 'player' | 'opponent' | 'number' }
|
||||
| { op: 'replacement'; what: 'dies' | 'leaves_battlefield' | 'discard' | 'draw'; instead: 'exile' | 'return_to_hand' | 'return_to_library' | 'prevent'; target?: Target }
|
||||
| { op: 'cost_reduction'; target: Target; amount: Value; condition?: Condition }
|
||||
|
||||
export type Ability =
|
||||
| KeywordAbility
|
||||
| {
|
||||
kind: 'keywords'
|
||||
keywords: KeywordAbility[]
|
||||
}
|
||||
| {
|
||||
kind: 'triggered'
|
||||
event: TriggerEvent
|
||||
condition?: Condition
|
||||
effects: Effect[]
|
||||
optional: boolean
|
||||
text: string
|
||||
}
|
||||
| {
|
||||
kind: 'activated'
|
||||
costs: Cost[]
|
||||
effects: Effect[]
|
||||
condition?: Condition
|
||||
timing?: 'instant' | 'sorcery'
|
||||
activationsPerTurn?: number
|
||||
optional: boolean
|
||||
text: string
|
||||
}
|
||||
| {
|
||||
kind: 'static'
|
||||
effects: StaticEffect[]
|
||||
condition?: Condition
|
||||
text: string
|
||||
}
|
||||
| {
|
||||
kind: 'spell'
|
||||
effects: Effect[]
|
||||
optional: boolean
|
||||
text: string
|
||||
}
|
||||
| {
|
||||
kind: 'additional_cost'
|
||||
costs: Cost[]
|
||||
optional: boolean
|
||||
text: string
|
||||
}
|
||||
| {
|
||||
kind: 'chapter'
|
||||
chapters: string[]
|
||||
effects: Effect[]
|
||||
optional: boolean
|
||||
text: string
|
||||
}
|
||||
| { kind: 'level_band'; min: number; max?: number; power?: Value; toughness?: Value; text: string }
|
||||
| { kind: 'level_pt'; power: Value; toughness: Value; text: string }
|
||||
| { kind: 'unsupported'; reason: string; text: string }
|
||||
|
||||
export interface CompiledFace {
|
||||
name: string
|
||||
status: 'supported' | 'partial' | 'unsupported'
|
||||
abilities: Ability[]
|
||||
}
|
||||
|
||||
export interface CompiledCard {
|
||||
oracle_id: string
|
||||
name: string
|
||||
status: 'supported' | 'partial' | 'unsupported'
|
||||
abilities: Ability[]
|
||||
faces?: CompiledFace[]
|
||||
/** True when a human edited the implementation instead of the oracle parser. */
|
||||
manual?: boolean
|
||||
}
|
||||
110
backend/src/game/catalog.ts
Normal file
110
backend/src/game/catalog.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import type { Card, CardFace } from '../cards.js'
|
||||
import { CardsUnavailableError } from '../cards.js'
|
||||
import type { Ability, CompiledCard } from '../effects/types.js'
|
||||
import type { CardDefinition } from './types.js'
|
||||
|
||||
const DATA_DIR = join(import.meta.dirname, '..', '..', 'data')
|
||||
const CARDS_FILE = join(DATA_DIR, 'cards.json')
|
||||
const EFFECTS_FILE = join(DATA_DIR, 'card-effects.json')
|
||||
const BASIC_MANA: Record<string, string> = {
|
||||
plains: 'W',
|
||||
island: 'U',
|
||||
swamp: 'B',
|
||||
mountain: 'R',
|
||||
forest: 'G',
|
||||
}
|
||||
|
||||
let catalog: Map<string, CardDefinition> | undefined
|
||||
|
||||
function numberOrUndefined(value: string | undefined): number | undefined {
|
||||
if (value === undefined || value === '') return undefined
|
||||
const parsed = Number(value)
|
||||
return Number.isFinite(parsed) ? parsed : undefined
|
||||
}
|
||||
|
||||
function basicLandAbility(typeLine: string): Ability[] {
|
||||
if (!/basic land/i.test(typeLine)) return []
|
||||
const subtype = typeLine.toLowerCase().split('—').pop()?.trim().split(/\s+/)[0] ?? ''
|
||||
const color = BASIC_MANA[subtype] ?? (subtype === 'wastes' ? 'C' : undefined)
|
||||
if (!color) return []
|
||||
return [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: [`{${color}}`] } }],
|
||||
optional: false,
|
||||
text: `{T}: Add {${color}}.`,
|
||||
}]
|
||||
}
|
||||
|
||||
function definitionFrom(
|
||||
card: Card,
|
||||
compiled: CompiledCard | undefined,
|
||||
face?: CardFace,
|
||||
faceAbilities?: Ability[],
|
||||
): CardDefinition {
|
||||
const typeLine = face?.type_line ?? card.type_line
|
||||
return {
|
||||
oracleId: card.oracle_id,
|
||||
name: face?.name ?? card.name,
|
||||
typeLine,
|
||||
manaCost: face?.mana_cost ?? card.mana_cost,
|
||||
manaValue: card.cmc,
|
||||
colors: face?.colors ?? card.colors,
|
||||
colorIdentity: card.color_identity,
|
||||
power: numberOrUndefined(face?.power ?? card.power),
|
||||
toughness: numberOrUndefined(face?.toughness ?? card.toughness),
|
||||
loyalty: numberOrUndefined(face?.loyalty ?? card.loyalty),
|
||||
oracleText: face?.oracle_text ?? card.oracle_text,
|
||||
abilities: [...(faceAbilities ?? compiled?.abilities ?? []), ...basicLandAbility(typeLine)],
|
||||
}
|
||||
}
|
||||
|
||||
export function cardDefinitionFromCard(card: Card, compiled?: CompiledCard): CardDefinition {
|
||||
const face = card.card_faces?.[0]
|
||||
const compiledFace = compiled?.faces?.[0]
|
||||
return definitionFrom(card, compiled, face, compiledFace?.abilities)
|
||||
}
|
||||
|
||||
function load(): Map<string, CardDefinition> {
|
||||
if (catalog) return catalog
|
||||
|
||||
let cards: Card[]
|
||||
let compiled: CompiledCard[]
|
||||
try {
|
||||
cards = JSON.parse(readFileSync(CARDS_FILE, 'utf8')) as Card[]
|
||||
} catch {
|
||||
throw new CardsUnavailableError(
|
||||
`Card data not found at ${CARDS_FILE}. Run "npm run import:cards" in backend/.`,
|
||||
)
|
||||
}
|
||||
try {
|
||||
compiled = JSON.parse(readFileSync(EFFECTS_FILE, 'utf8')) as CompiledCard[]
|
||||
} catch {
|
||||
throw new CardsUnavailableError(
|
||||
`Compiled card effects not found at ${EFFECTS_FILE}. Run "npm run compile:cards" in backend/.`,
|
||||
)
|
||||
}
|
||||
|
||||
const effects = new Map(compiled.map(card => [card.oracle_id, card]))
|
||||
catalog = new Map(cards.map(card => [card.oracle_id, cardDefinitionFromCard(card, effects.get(card.oracle_id))]))
|
||||
return catalog
|
||||
}
|
||||
|
||||
export function getCardDefinition(oracleId: string): CardDefinition | undefined {
|
||||
return load().get(oracleId)
|
||||
}
|
||||
|
||||
/** Resolves a list of oracle ids into deck definitions, rejecting unknown cards. */
|
||||
export function deckFromOracleIds(oracleIds: string[]): CardDefinition[] {
|
||||
const missing: string[] = []
|
||||
const deck: CardDefinition[] = []
|
||||
for (const oracleId of oracleIds) {
|
||||
const definition = getCardDefinition(oracleId)
|
||||
if (definition) deck.push(definition)
|
||||
else missing.push(oracleId)
|
||||
}
|
||||
if (missing.length) throw new Error(`Unknown oracle ids: ${missing.join(', ')}`)
|
||||
return deck
|
||||
}
|
||||
174
backend/src/game/commander.ts
Normal file
174
backend/src/game/commander.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
import { findCardByName, type Card } from '../cards.js'
|
||||
|
||||
export interface ImportedDeck {
|
||||
commander?: Card
|
||||
cards: Card[]
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
export function isBasicLand(card: Card): boolean {
|
||||
return /\bbasic\b/i.test(card.type_line) && /\bland\b/i.test(card.type_line)
|
||||
}
|
||||
|
||||
export function canBeCommander(card: Card): boolean {
|
||||
const text = [card.oracle_text, ...(card.card_faces?.map(face => face.oracle_text) ?? [])]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
return (/\blegendary\b/i.test(card.type_line) && /\bcreature\b/i.test(card.type_line))
|
||||
|| /can be your commander/i.test(text)
|
||||
}
|
||||
|
||||
/** Checks the Commander deck-construction rules the engine can enforce. */
|
||||
export function validateCommanderDeck(commander: Card, cards: Card[]): string[] {
|
||||
const errors: string[] = []
|
||||
if (!canBeCommander(commander)) errors.push(`${commander.name} cannot be a commander.`)
|
||||
if (cards.length + 1 !== 100) {
|
||||
errors.push(`Deck has ${cards.length + 1} cards; Commander decks need exactly 100 including the commander.`)
|
||||
}
|
||||
|
||||
const identity = new Set(commander.color_identity)
|
||||
const counts = new Map<string, number>()
|
||||
for (const card of cards) {
|
||||
counts.set(card.oracle_id, (counts.get(card.oracle_id) ?? 0) + 1)
|
||||
if (card.oracle_id === commander.oracle_id) {
|
||||
errors.push(`${card.name} cannot be both the commander and a deck card.`)
|
||||
}
|
||||
const outside = card.color_identity.filter(color => !identity.has(color))
|
||||
if (outside.length) errors.push(`${card.name} is outside the commander's color identity.`)
|
||||
}
|
||||
|
||||
for (const [oracleId, count] of counts) {
|
||||
if (count < 2) continue
|
||||
const card = cards.find(entry => entry.oracle_id === oracleId)
|
||||
if (card && !isBasicLand(card)) {
|
||||
errors.push(`${card.name} appears ${count} times; only basic lands may repeat.`)
|
||||
}
|
||||
}
|
||||
|
||||
return [...new Set(errors)]
|
||||
}
|
||||
|
||||
const SECTION_HEADERS = new Set([
|
||||
'commander', 'commanders', 'deck', 'mainboard', 'main', 'main deck',
|
||||
'sideboard', 'maybeboard', 'tokens', 'creatures', 'instants', 'sorceries',
|
||||
'artifacts', 'enchantments', 'planeswalkers', 'lands', 'battle', 'other',
|
||||
])
|
||||
|
||||
interface Entry {
|
||||
quantity: number
|
||||
name: string
|
||||
section: 'commander' | 'deck' | 'ignore'
|
||||
}
|
||||
|
||||
function cleanName(raw: string): string {
|
||||
return raw
|
||||
.replace(/\s*\*[fF]\*\s*$/, '')
|
||||
.replace(/\s+\([A-Z0-9]{2,8}\)\s+[A-Z0-9-]+.*$/, '')
|
||||
.replace(/\s+\[[A-Z0-9]{2,8}\].*$/, '')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function parseEntries(
|
||||
text: string,
|
||||
resolve: (name: string) => Card | undefined,
|
||||
): { entries: Entry[]; unresolved: string[] } {
|
||||
const entries: Entry[] = []
|
||||
const unresolved: string[] = []
|
||||
let section: Entry['section'] = 'deck'
|
||||
|
||||
for (const rawLine of text.split(/\r?\n/)) {
|
||||
const line = rawLine.trim()
|
||||
if (!line || line.startsWith('//') || line.startsWith('#')) continue
|
||||
|
||||
const header = line.replace(/:$/, '').replace(/\s*\(\d+\)$/, '').toLowerCase()
|
||||
if (SECTION_HEADERS.has(header)) {
|
||||
section = header.startsWith('commander') ? 'commander'
|
||||
: header === 'sideboard' || header === 'maybeboard' || header === 'tokens' ? 'ignore'
|
||||
: 'deck'
|
||||
continue
|
||||
}
|
||||
|
||||
const match = line.match(/^(\d+)\s*[xX]?\s*(.+)$/) ?? line.match(/^()(.+)$/)
|
||||
if (!match) continue
|
||||
const quantity = Number(match[1] || 1)
|
||||
if (!Number.isFinite(quantity) || quantity <= 0) continue
|
||||
const name = cleanName(match[2])
|
||||
if (!name) continue
|
||||
|
||||
const card = resolve(name)
|
||||
if (!card) {
|
||||
unresolved.push(name)
|
||||
continue
|
||||
}
|
||||
entries.push({ quantity, name: card.name, section })
|
||||
}
|
||||
|
||||
return { entries, unresolved }
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses common decklist exports (Moxfield, Archidekt, Arena, plain text):
|
||||
*
|
||||
* Commander
|
||||
* 1 Atraxa, Praetors' Voice
|
||||
*
|
||||
* Deck
|
||||
* 1 Sol Ring
|
||||
* 10 Forest
|
||||
*
|
||||
* Without a Commander section, a single legendary creature in the list is
|
||||
* inferred as the commander.
|
||||
*/
|
||||
export function importDeckText(
|
||||
text: string,
|
||||
resolve: (name: string) => Card | undefined = findCardByName,
|
||||
): ImportedDeck {
|
||||
const { entries, unresolved } = parseEntries(text, resolve)
|
||||
const errors: string[] = []
|
||||
if (unresolved.length) {
|
||||
errors.push(`Unrecognized cards: ${[...new Set(unresolved)].join(', ')}`)
|
||||
}
|
||||
|
||||
const commanderEntries = entries.filter(entry => entry.section === 'commander')
|
||||
const deckEntries = entries.filter(entry => entry.section === 'deck')
|
||||
let commander = commanderEntries[0] ? resolve(commanderEntries[0].name) : undefined
|
||||
|
||||
if (commanderEntries.length > 1 || commanderEntries.some(entry => entry.quantity > 1)) {
|
||||
errors.push('A deck can only have one commander.')
|
||||
}
|
||||
|
||||
if (!commander) {
|
||||
const candidates = new Map<string, Card>()
|
||||
for (const entry of deckEntries) {
|
||||
const card = resolve(entry.name)
|
||||
if (card && entry.quantity === 1 && canBeCommander(card)) candidates.set(card.oracle_id, card)
|
||||
}
|
||||
if (candidates.size === 1) {
|
||||
commander = [...candidates.values()][0]
|
||||
} else if (candidates.size > 1 && deckEntries.length) {
|
||||
errors.push('Multiple possible commanders found; put the commander in a Commander section.')
|
||||
}
|
||||
}
|
||||
|
||||
const cards: Card[] = []
|
||||
let commanderRemoved = false
|
||||
for (const entry of deckEntries) {
|
||||
const card = resolve(entry.name)
|
||||
if (!card) continue
|
||||
for (let index = 0; index < entry.quantity; index++) {
|
||||
if (!commanderRemoved && commander && card.oracle_id === commander.oracle_id) {
|
||||
commanderRemoved = true
|
||||
continue
|
||||
}
|
||||
cards.push(card)
|
||||
}
|
||||
}
|
||||
|
||||
if (!commander) {
|
||||
errors.push('No commander found. Add a "Commander" section with one legendary creature.')
|
||||
} else {
|
||||
errors.push(...validateCommanderDeck(commander, cards))
|
||||
}
|
||||
|
||||
return { commander, cards, errors: [...new Set(errors)] }
|
||||
}
|
||||
2999
backend/src/game/game.ts
Normal file
2999
backend/src/game/game.ts
Normal file
File diff suppressed because it is too large
Load Diff
602
backend/src/game/rooms.ts
Normal file
602
backend/src/game/rooms.ts
Normal file
@@ -0,0 +1,602 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { getCard, type Card } from '../cards.js'
|
||||
import { deletePlaymatImage, PlaymatError, scryfallArtUrl, storePlaymatImage } from '../images.js'
|
||||
import { getCardDefinition } from './catalog.js'
|
||||
import { validateCommanderDeck } from './commander.js'
|
||||
import { Game, GameError } from './game.js'
|
||||
import type { CardDefinition, GameObject, ManaPool, TargetChoice } from './types.js'
|
||||
|
||||
export class MatchError extends Error {
|
||||
constructor(message: string, readonly status = 400) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export interface DeckSubmission {
|
||||
commander: string
|
||||
cards: string[]
|
||||
}
|
||||
|
||||
export interface ActionPayload {
|
||||
type: string
|
||||
cardId?: string
|
||||
sourceId?: string
|
||||
abilityIndex?: number
|
||||
targets?: TargetChoice[]
|
||||
x?: number
|
||||
mode?: number
|
||||
position?: { x?: unknown; y?: unknown }
|
||||
attackers?: { attackerId: string; defenderId: string }[]
|
||||
blocks?: { blockerId: string; attackerId: string }[]
|
||||
}
|
||||
|
||||
export interface CardView {
|
||||
id: string
|
||||
oracleId: string
|
||||
name: string
|
||||
typeLine: string
|
||||
manaCost?: string
|
||||
manaValue?: number
|
||||
colors: string[]
|
||||
colorIdentity: string[]
|
||||
oracleText?: string
|
||||
power?: number
|
||||
toughness?: number
|
||||
tapped: boolean
|
||||
damage: number
|
||||
counters: Record<string, number>
|
||||
isToken: boolean
|
||||
isCommander: boolean
|
||||
zone: string
|
||||
controller: string
|
||||
owner: string
|
||||
position?: { x: number; y: number }
|
||||
attacking?: string
|
||||
blockedBy: string[]
|
||||
blocking?: string
|
||||
abilities: { index: number; kind: string; text?: string }[]
|
||||
/** Viewer-specific: can this card be played from hand right now? */
|
||||
playable?: boolean
|
||||
}
|
||||
|
||||
export type Playmat =
|
||||
| { kind: 'card'; oracleId: string }
|
||||
| { kind: 'upload'; id: string }
|
||||
|
||||
export interface PlaymatSubmission {
|
||||
kind?: unknown
|
||||
oracleId?: unknown
|
||||
data?: unknown
|
||||
}
|
||||
|
||||
export interface PlayerView {
|
||||
id: string
|
||||
name: string
|
||||
/** Present while the match is in the lobby. */
|
||||
commander?: { oracleId: string; name: string }
|
||||
playmat?: Playmat
|
||||
life?: number
|
||||
lost?: boolean
|
||||
handCount?: number
|
||||
libraryCount?: number
|
||||
battlefield?: CardView[]
|
||||
graveyard?: CardView[]
|
||||
exile?: CardView[]
|
||||
command?: CardView[]
|
||||
commanderId?: string
|
||||
commanderDamage?: { commanderId: string; commanderName: string; amount: number }[]
|
||||
commanderCasts?: Record<string, number>
|
||||
landPlayedThisTurn?: boolean
|
||||
}
|
||||
|
||||
export interface MatchView {
|
||||
id: string
|
||||
status: 'lobby' | 'active' | 'finished'
|
||||
version: number
|
||||
viewerId: string
|
||||
hostId: string
|
||||
maxPlayers: number
|
||||
players: PlayerView[]
|
||||
game?: {
|
||||
turn: number
|
||||
activePlayer: string
|
||||
phase: string
|
||||
step: string
|
||||
priority: string
|
||||
status: string
|
||||
winner?: string
|
||||
stack: { id: string; kind: string; label: string; controller: string }[]
|
||||
log: string[]
|
||||
hand: CardView[]
|
||||
manaPool: ManaPool
|
||||
/** Present while a search waits for a pick; `cards` is populated only for its chooser. */
|
||||
pendingSearch?: {
|
||||
player: string
|
||||
remaining: number
|
||||
destination: string
|
||||
cards: CardView[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface MatchSummary {
|
||||
id: string
|
||||
hostName: string
|
||||
status: 'lobby' | 'active' | 'finished'
|
||||
playerCount: number
|
||||
maxPlayers: number
|
||||
players: string[]
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
interface Seat {
|
||||
playerId: string
|
||||
token: string
|
||||
name: string
|
||||
commander: CardDefinition
|
||||
cards: CardDefinition[]
|
||||
playmat?: Playmat
|
||||
}
|
||||
|
||||
interface Match {
|
||||
id: string
|
||||
hostId: string
|
||||
maxPlayers: number
|
||||
status: 'lobby' | 'active' | 'finished'
|
||||
seats: Seat[]
|
||||
game?: Game
|
||||
version: number
|
||||
createdAt: number
|
||||
listeners: Map<string, Set<(state: MatchView) => void>>
|
||||
}
|
||||
|
||||
const matches = new Map<string, Match>()
|
||||
|
||||
function requireMatch(matchId: string): Match {
|
||||
const match = matches.get(matchId)
|
||||
if (!match) throw new MatchError('Game not found', 404)
|
||||
return match
|
||||
}
|
||||
|
||||
function requireSeat(match: Match, token: string | undefined): Seat {
|
||||
const seat = match.seats.find(entry => entry.token === token)
|
||||
if (!seat) throw new MatchError('You are not seated in this game', 403)
|
||||
return seat
|
||||
}
|
||||
|
||||
function playerName(name: unknown): string {
|
||||
const clean = typeof name === 'string' ? name.trim().slice(0, 30) : ''
|
||||
return clean || 'Player'
|
||||
}
|
||||
|
||||
function resolveDeck(deck: DeckSubmission | undefined): { commander: CardDefinition; cards: CardDefinition[] } {
|
||||
if (!deck || typeof deck.commander !== 'string' || !Array.isArray(deck.cards)) {
|
||||
throw new MatchError('A commander deck is required')
|
||||
}
|
||||
if (deck.cards.length > 250 || deck.cards.some(id => typeof id !== 'string')) {
|
||||
throw new MatchError('Invalid deck')
|
||||
}
|
||||
|
||||
const commander = getCard(deck.commander)
|
||||
if (!commander) throw new MatchError('Commander not found')
|
||||
const cards: Card[] = []
|
||||
const missing: string[] = []
|
||||
for (const oracleId of deck.cards) {
|
||||
const card = getCard(oracleId)
|
||||
if (card) cards.push(card)
|
||||
else missing.push(oracleId)
|
||||
}
|
||||
if (missing.length) {
|
||||
throw new MatchError(`Unknown cards: ${[...new Set(missing)].join(', ')}`)
|
||||
}
|
||||
|
||||
const errors = validateCommanderDeck(commander, cards)
|
||||
if (errors.length) throw new MatchError(errors.join('\n'))
|
||||
|
||||
const commanderDefinition = getCardDefinition(deck.commander)
|
||||
if (!commanderDefinition) throw new MatchError('Commander effects are unavailable')
|
||||
const definitions = deck.cards.map(id => {
|
||||
const definition = getCardDefinition(id)
|
||||
if (!definition) throw new MatchError(`Effects are unavailable for ${id}`)
|
||||
return definition
|
||||
})
|
||||
return { commander: commanderDefinition, cards: definitions }
|
||||
}
|
||||
|
||||
function makeSeat(name: unknown, deck: DeckSubmission | undefined): Seat {
|
||||
const resolved = resolveDeck(deck)
|
||||
return {
|
||||
playerId: randomUUID(),
|
||||
token: randomUUID(),
|
||||
name: playerName(name),
|
||||
commander: resolved.commander,
|
||||
cards: resolved.cards,
|
||||
}
|
||||
}
|
||||
|
||||
export function listMatches(): MatchSummary[] {
|
||||
return [...matches.values()]
|
||||
.filter(match => match.status !== 'finished')
|
||||
.sort((a, b) => b.createdAt - a.createdAt)
|
||||
.slice(0, 50)
|
||||
.map(match => ({
|
||||
id: match.id,
|
||||
hostName: match.seats.find(seat => seat.playerId === match.hostId)?.name ?? 'Unknown',
|
||||
status: match.status,
|
||||
playerCount: match.seats.length,
|
||||
maxPlayers: match.maxPlayers,
|
||||
players: match.seats.map(seat => seat.name),
|
||||
createdAt: match.createdAt,
|
||||
}))
|
||||
}
|
||||
|
||||
export function createMatch(
|
||||
name: unknown,
|
||||
deck: DeckSubmission | undefined,
|
||||
maxPlayers: unknown,
|
||||
): { matchId: string; playerId: string; token: string } {
|
||||
const limit = Math.min(4, Math.max(2, Number(maxPlayers) || 4))
|
||||
const seat = makeSeat(name, deck)
|
||||
const match: Match = {
|
||||
id: randomUUID(),
|
||||
hostId: seat.playerId,
|
||||
maxPlayers: limit,
|
||||
status: 'lobby',
|
||||
seats: [seat],
|
||||
version: 0,
|
||||
createdAt: Date.now(),
|
||||
listeners: new Map(),
|
||||
}
|
||||
matches.set(match.id, match)
|
||||
return { matchId: match.id, playerId: seat.playerId, token: seat.token }
|
||||
}
|
||||
|
||||
export function joinMatch(
|
||||
matchId: string,
|
||||
name: unknown,
|
||||
deck: DeckSubmission | undefined,
|
||||
): { matchId: string; playerId: string; token: string } {
|
||||
const match = requireMatch(matchId)
|
||||
if (match.status !== 'lobby') throw new MatchError('This game has already started')
|
||||
if (match.seats.length >= match.maxPlayers) throw new MatchError('This game is full')
|
||||
const seat = makeSeat(name, deck)
|
||||
match.seats.push(seat)
|
||||
broadcast(match)
|
||||
return { matchId: match.id, playerId: seat.playerId, token: seat.token }
|
||||
}
|
||||
|
||||
export function leaveMatch(matchId: string, token: string | undefined): void {
|
||||
const match = requireMatch(matchId)
|
||||
const seat = requireSeat(match, token)
|
||||
// A started game can't drop the seat without breaking its state: forfeit instead.
|
||||
if (match.status === 'active' && match.game) {
|
||||
match.game.concede(seat.playerId)
|
||||
match.game.autoAdvance()
|
||||
if (match.game.status === 'finished') match.status = 'finished'
|
||||
broadcast(match)
|
||||
return
|
||||
}
|
||||
match.seats = match.seats.filter(entry => entry !== seat)
|
||||
if (!match.seats.length) {
|
||||
matches.delete(match.id)
|
||||
return
|
||||
}
|
||||
if (match.hostId === seat.playerId) match.hostId = match.seats[0].playerId
|
||||
broadcast(match)
|
||||
}
|
||||
|
||||
export function setDeck(matchId: string, token: string | undefined, deck: DeckSubmission | undefined): void {
|
||||
const match = requireMatch(matchId)
|
||||
const seat = requireSeat(match, token)
|
||||
if (match.status !== 'lobby') throw new MatchError('You can only change your deck in the lobby')
|
||||
const resolved = resolveDeck(deck)
|
||||
seat.commander = resolved.commander
|
||||
seat.cards = resolved.cards
|
||||
broadcast(match)
|
||||
}
|
||||
|
||||
export async function setPlaymat(
|
||||
matchId: string,
|
||||
token: string | undefined,
|
||||
submission: PlaymatSubmission | undefined,
|
||||
): Promise<Playmat | undefined> {
|
||||
const match = requireMatch(matchId)
|
||||
const seat = requireSeat(match, token)
|
||||
if (!submission) throw new MatchError('Invalid playmat selection')
|
||||
const kind = submission.kind
|
||||
|
||||
let next: Playmat | undefined
|
||||
if (kind === 'none') {
|
||||
next = undefined
|
||||
} else if (kind === 'card') {
|
||||
if (typeof submission.oracleId !== 'string') throw new MatchError('Missing card id')
|
||||
const card = getCard(submission.oracleId)
|
||||
if (!card || !scryfallArtUrl(card.image_uri)) throw new MatchError('Card art not found')
|
||||
next = { kind: 'card', oracleId: card.oracle_id }
|
||||
} else if (kind === 'upload') {
|
||||
if (typeof submission.data !== 'string') throw new MatchError('Missing playmat image')
|
||||
try {
|
||||
next = { kind: 'upload', id: await storePlaymatImage(submission.data) }
|
||||
} catch (error) {
|
||||
if (error instanceof PlaymatError) throw new MatchError(error.message)
|
||||
throw error
|
||||
}
|
||||
} else {
|
||||
throw new MatchError('Invalid playmat selection')
|
||||
}
|
||||
|
||||
const previous = seat.playmat
|
||||
seat.playmat = next
|
||||
broadcast(match)
|
||||
if (previous?.kind === 'upload' && previous.id !== (next?.kind === 'upload' ? next.id : '')) {
|
||||
await deletePlaymatImage(previous.id)
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
export function startMatch(matchId: string, token: string | undefined): void {
|
||||
const match = requireMatch(matchId)
|
||||
const seat = requireSeat(match, token)
|
||||
if (seat.playerId !== match.hostId) throw new MatchError('Only the host can start the game')
|
||||
if (match.status !== 'lobby') throw new MatchError('This game has already started')
|
||||
if (match.seats.length < 2) throw new MatchError('At least two players are needed')
|
||||
|
||||
const game = new Game({
|
||||
seed: Date.now(),
|
||||
startingLife: 40,
|
||||
startingHandSize: 7,
|
||||
firstPlayer: match.seats[0].playerId,
|
||||
commander: true,
|
||||
players: match.seats.map(entry => ({
|
||||
id: entry.playerId,
|
||||
name: entry.name,
|
||||
deck: entry.cards,
|
||||
commander: entry.commander,
|
||||
})),
|
||||
})
|
||||
game.start()
|
||||
game.autoAdvance()
|
||||
match.game = game
|
||||
match.status = game.status === 'finished' ? 'finished' : 'active'
|
||||
broadcast(match)
|
||||
}
|
||||
|
||||
export function getMatchView(matchId: string, token: string | undefined): MatchView {
|
||||
const match = requireMatch(matchId)
|
||||
const seat = requireSeat(match, token)
|
||||
return serialize(match, seat.playerId)
|
||||
}
|
||||
|
||||
export function subscribe(
|
||||
matchId: string,
|
||||
token: string | undefined,
|
||||
send: (state: MatchView) => void,
|
||||
): () => void {
|
||||
const match = requireMatch(matchId)
|
||||
const seat = requireSeat(match, token)
|
||||
let listeners = match.listeners.get(seat.playerId)
|
||||
if (!listeners) {
|
||||
listeners = new Set()
|
||||
match.listeners.set(seat.playerId, listeners)
|
||||
}
|
||||
listeners.add(send)
|
||||
send(serialize(match, seat.playerId))
|
||||
return () => {
|
||||
listeners?.delete(send)
|
||||
if (listeners && listeners.size === 0) match.listeners.delete(seat.playerId)
|
||||
}
|
||||
}
|
||||
|
||||
export function performAction(matchId: string, token: string | undefined, action: ActionPayload): void {
|
||||
const match = requireMatch(matchId)
|
||||
const seat = requireSeat(match, token)
|
||||
const game = match.game
|
||||
if (match.status !== 'active' || !game) throw new MatchError('This game is not active')
|
||||
|
||||
const targets = Array.isArray(action.targets)
|
||||
? action.targets.filter((target): target is TargetChoice => Boolean(target)
|
||||
&& typeof target.id === 'string'
|
||||
&& (target.kind === 'player' || target.kind === 'object' || target.kind === 'spell'))
|
||||
: []
|
||||
|
||||
const options = {
|
||||
targets,
|
||||
x: Number.isFinite(action.x) ? Number(action.x) : 0,
|
||||
mode: Number.isFinite(action.mode) ? Number(action.mode) : 0,
|
||||
}
|
||||
|
||||
try {
|
||||
switch (action.type) {
|
||||
case 'play_land':
|
||||
game.playLand(seat.playerId, requireId(action.cardId))
|
||||
break
|
||||
case 'cast':
|
||||
game.castSpell(seat.playerId, requireId(action.cardId), options)
|
||||
break
|
||||
case 'activate':
|
||||
if (!Number.isInteger(action.abilityIndex)) throw new MatchError('Invalid ability')
|
||||
game.activateAbility(seat.playerId, requireId(action.sourceId), Number(action.abilityIndex), options)
|
||||
break
|
||||
case 'move_permanent':
|
||||
game.movePermanent(seat.playerId, requireId(action.cardId), Number(action.position?.x), Number(action.position?.y))
|
||||
// Layout only: skip autoAdvance so dragging never passes priority.
|
||||
broadcast(match)
|
||||
return
|
||||
case 'choose_search':
|
||||
game.chooseSearchCard(seat.playerId, requireId(action.cardId))
|
||||
break
|
||||
case 'attack':
|
||||
if (!Array.isArray(action.attackers)) throw new MatchError('Invalid attackers')
|
||||
game.declareAttackers(seat.playerId, action.attackers.map(entry => ({
|
||||
attackerId: requireId(entry?.attackerId),
|
||||
defenderId: requireId(entry?.defenderId),
|
||||
})))
|
||||
break
|
||||
case 'block':
|
||||
if (!Array.isArray(action.blocks)) throw new MatchError('Invalid blocks')
|
||||
game.declareBlockers(seat.playerId, action.blocks.map(entry => ({
|
||||
blockerId: requireId(entry?.blockerId),
|
||||
attackerId: requireId(entry?.attackerId),
|
||||
})))
|
||||
break
|
||||
case 'pass':
|
||||
game.pass(seat.playerId)
|
||||
break
|
||||
case 'end_turn':
|
||||
game.endTurn(seat.playerId)
|
||||
break
|
||||
default:
|
||||
throw new MatchError(`Unknown action: ${action.type}`)
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof GameError) throw new MatchError(error.message)
|
||||
throw error
|
||||
}
|
||||
|
||||
game.autoAdvance()
|
||||
if (game.status === 'finished') match.status = 'finished'
|
||||
broadcast(match)
|
||||
}
|
||||
|
||||
function requireId(id: unknown): string {
|
||||
if (typeof id !== 'string' || !id) throw new MatchError('Missing card or player id')
|
||||
return id
|
||||
}
|
||||
|
||||
function cardView(game: Game, object: GameObject, abilities = true): CardView {
|
||||
const definition = object.definition
|
||||
const creature = /creature/i.test(definition.typeLine)
|
||||
return {
|
||||
id: object.id,
|
||||
oracleId: definition.oracleId,
|
||||
name: definition.name,
|
||||
typeLine: definition.typeLine,
|
||||
manaCost: definition.manaCost,
|
||||
manaValue: definition.manaValue,
|
||||
colors: definition.colors ?? [],
|
||||
colorIdentity: definition.colorIdentity ?? [],
|
||||
oracleText: definition.oracleText,
|
||||
power: creature ? game.getPower(object) : undefined,
|
||||
toughness: creature ? game.getToughness(object) : undefined,
|
||||
tapped: object.tapped,
|
||||
damage: object.damage,
|
||||
counters: { ...object.counters },
|
||||
isToken: object.isToken,
|
||||
isCommander: Boolean(object.isCommander),
|
||||
zone: object.zone,
|
||||
controller: object.controller,
|
||||
owner: object.owner,
|
||||
position: object.position ? { ...object.position } : undefined,
|
||||
attacking: object.attacking,
|
||||
blockedBy: [...object.blockedBy],
|
||||
blocking: object.blocking,
|
||||
abilities: abilities
|
||||
? (definition.abilities ?? []).map((ability, index) => ({
|
||||
index,
|
||||
kind: ability.kind,
|
||||
text: 'text' in ability ? ability.text : undefined,
|
||||
}))
|
||||
: [],
|
||||
}
|
||||
}
|
||||
|
||||
function serialize(match: Match, viewerId: string): MatchView {
|
||||
const view: MatchView = {
|
||||
id: match.id,
|
||||
status: match.status,
|
||||
version: match.version,
|
||||
viewerId,
|
||||
hostId: match.hostId,
|
||||
maxPlayers: match.maxPlayers,
|
||||
players: match.seats.map(seat => ({
|
||||
id: seat.playerId,
|
||||
name: seat.name,
|
||||
commander: { oracleId: seat.commander.oracleId, name: seat.commander.name },
|
||||
playmat: seat.playmat,
|
||||
})),
|
||||
}
|
||||
|
||||
const game = match.game
|
||||
if (!game) return view
|
||||
|
||||
view.players = match.seats.map(seat => {
|
||||
const player = game.getPlayer(seat.playerId)
|
||||
return {
|
||||
id: player.id,
|
||||
name: player.name,
|
||||
playmat: seat.playmat,
|
||||
life: player.life,
|
||||
lost: player.lost,
|
||||
handCount: player.hand.length,
|
||||
libraryCount: player.library.length,
|
||||
battlefield: player.battlefield.map(id => cardView(game, game.getObject(id))),
|
||||
graveyard: player.graveyard.map(id => cardView(game, game.getObject(id), false)),
|
||||
exile: player.exile.map(id => cardView(game, game.getObject(id), false)),
|
||||
command: player.command.map(id => cardView(game, game.getObject(id), false)),
|
||||
commanderId: player.commanderId,
|
||||
commanderDamage: Object.entries(player.commanderDamage)
|
||||
.filter(([, amount]) => amount > 0)
|
||||
.map(([commanderId, amount]) => ({
|
||||
commanderId,
|
||||
commanderName: game.objects.get(commanderId)?.definition.name ?? 'Commander',
|
||||
amount,
|
||||
})),
|
||||
commanderCasts: { ...player.commanderCasts },
|
||||
landPlayedThisTurn: player.landPlayedThisTurn,
|
||||
}
|
||||
})
|
||||
|
||||
const viewer = game.getPlayer(viewerId)
|
||||
const search = game.pendingSearch
|
||||
view.game = {
|
||||
turn: game.turn,
|
||||
activePlayer: game.activePlayer,
|
||||
phase: game.phase,
|
||||
step: game.step,
|
||||
priority: game.priority,
|
||||
status: game.status,
|
||||
winner: game.winner,
|
||||
stack: game.stack.map(item => ({
|
||||
id: item.id,
|
||||
kind: item.kind,
|
||||
label: item.label,
|
||||
controller: item.controller,
|
||||
})),
|
||||
log: game.log.slice(-80),
|
||||
hand: viewer.hand.map(id => ({
|
||||
...cardView(game, game.getObject(id)),
|
||||
playable: game.canPlayCard(viewerId, id),
|
||||
})),
|
||||
manaPool: { ...viewer.manaPool },
|
||||
pendingSearch: search
|
||||
? {
|
||||
player: search.playerId,
|
||||
remaining: search.remaining,
|
||||
destination: search.destination,
|
||||
cards: search.playerId === viewerId
|
||||
? game.searchCandidates(viewerId).map(object => cardView(game, object, false))
|
||||
: [],
|
||||
}
|
||||
: undefined,
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
function broadcast(match: Match): void {
|
||||
match.version++
|
||||
for (const [playerId, listeners] of match.listeners) {
|
||||
let state: MatchView
|
||||
try {
|
||||
state = serialize(match, playerId)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
for (const send of [...listeners]) {
|
||||
try {
|
||||
send(state)
|
||||
} catch {
|
||||
listeners.delete(send)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
156
backend/src/game/types.ts
Normal file
156
backend/src/game/types.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
// The runtime game model. Card definitions are immutable input; objects are the
|
||||
// per-game instances that move between zones.
|
||||
import type { Ability, Effect, ObjectSelector, TokenSpec, Zone } from '../effects/types.js'
|
||||
|
||||
export type ManaColor = 'W' | 'U' | 'B' | 'R' | 'G' | 'C'
|
||||
export type ManaPool = Record<ManaColor, number>
|
||||
|
||||
export interface CardDefinition {
|
||||
oracleId: string
|
||||
name: string
|
||||
typeLine: string
|
||||
manaCost?: string
|
||||
manaValue?: number
|
||||
colors?: string[]
|
||||
colorIdentity?: string[]
|
||||
power?: number
|
||||
toughness?: number
|
||||
loyalty?: number
|
||||
oracleText?: string
|
||||
/** Compiled oracle-text abilities, or hand-written abilities in tests. */
|
||||
abilities?: Ability[]
|
||||
}
|
||||
|
||||
export interface PlayerConfig {
|
||||
id: string
|
||||
name?: string
|
||||
deck: CardDefinition[]
|
||||
/** Creates this card in the command zone when the game uses commander rules. */
|
||||
commander?: CardDefinition
|
||||
life?: number
|
||||
}
|
||||
|
||||
export interface GameConfig {
|
||||
players: PlayerConfig[]
|
||||
startingLife?: number
|
||||
startingHandSize?: number
|
||||
seed?: number
|
||||
firstPlayer?: string
|
||||
/** Enables command-zone casting, commander tax, and commander damage. */
|
||||
commander?: boolean
|
||||
}
|
||||
|
||||
export interface PlayerState {
|
||||
id: string
|
||||
name: string
|
||||
life: number
|
||||
lost: boolean
|
||||
manaPool: ManaPool
|
||||
library: string[]
|
||||
hand: string[]
|
||||
graveyard: string[]
|
||||
exile: string[]
|
||||
battlefield: string[]
|
||||
command: string[]
|
||||
commanderId?: string
|
||||
/** Damage received from each commander, keyed by the commander's object id. */
|
||||
commanderDamage: Record<string, number>
|
||||
/** Times each commander has been cast from the command zone. */
|
||||
commanderCasts: Record<string, number>
|
||||
landPlayedThisTurn: boolean
|
||||
cardsDrawnThisTurn: number
|
||||
lifeGainedThisTurn: number
|
||||
spellsCastThisTurn: number
|
||||
creaturesDiedThisTurn: number
|
||||
nonlandPermanentsEnteredThisTurn: number
|
||||
attackedThisTurn: boolean
|
||||
energy: number
|
||||
poison: number
|
||||
}
|
||||
|
||||
export interface GameObject {
|
||||
id: string
|
||||
definition: CardDefinition
|
||||
owner: string
|
||||
controller: string
|
||||
zone: Zone
|
||||
tapped: boolean
|
||||
damage: number
|
||||
/** Set when this object has been dealt damage by a source with deathtouch. */
|
||||
deathtouched: boolean
|
||||
counters: Record<string, number>
|
||||
isToken: boolean
|
||||
token?: TokenSpec
|
||||
isCommander?: boolean
|
||||
enteredTurn: number
|
||||
/** Normalized center on the controller's mat; absent means auto-arranged. */
|
||||
position?: { x: number; y: number }
|
||||
attacking?: string
|
||||
blockedBy: string[]
|
||||
blocking?: string
|
||||
attachments: string[]
|
||||
attachedTo?: string
|
||||
regenerationShields: number
|
||||
activations: Record<number, number>
|
||||
}
|
||||
|
||||
export type TargetChoice =
|
||||
| { kind: 'player'; id: string }
|
||||
| { kind: 'object'; id: string }
|
||||
| { kind: 'spell'; id: string }
|
||||
|
||||
export interface StackItem {
|
||||
id: string
|
||||
kind: 'spell' | 'ability'
|
||||
source: GameObject
|
||||
controller: string
|
||||
label: string
|
||||
effects: Effect[]
|
||||
targets: TargetChoice[]
|
||||
x: number
|
||||
mode: number
|
||||
triggerSubject?: GameObject
|
||||
eventPlayer?: string
|
||||
eventAmount?: number
|
||||
}
|
||||
|
||||
export interface ActionOptions {
|
||||
targets?: TargetChoice[]
|
||||
x?: number
|
||||
mode?: number
|
||||
}
|
||||
|
||||
/** A search that is waiting for its player to pick one of several matching cards. */
|
||||
export interface PendingSearch {
|
||||
playerId: string
|
||||
selector: ObjectSelector
|
||||
remaining: number
|
||||
destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'
|
||||
tapped: boolean
|
||||
shuffle: boolean
|
||||
zones?: ('library' | 'graveyard')[]
|
||||
}
|
||||
|
||||
export interface CombatAttack {
|
||||
attackerId: string
|
||||
defenderId: string
|
||||
}
|
||||
|
||||
export interface CombatBlock {
|
||||
blockerId: string
|
||||
attackerId: string
|
||||
}
|
||||
|
||||
export type Phase = 'beginning' | 'precombat_main' | 'combat' | 'postcombat_main' | 'ending'
|
||||
export type Step =
|
||||
| 'untap'
|
||||
| 'upkeep'
|
||||
| 'draw'
|
||||
| 'main'
|
||||
| 'begin_combat'
|
||||
| 'declare_attackers'
|
||||
| 'declare_blockers'
|
||||
| 'combat_damage'
|
||||
| 'end_combat'
|
||||
| 'end_step'
|
||||
| 'cleanup'
|
||||
108
backend/src/images.ts
Normal file
108
backend/src/images.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
|
||||
export const IMAGE_DIR = join(import.meta.dirname, '..', 'data', 'images')
|
||||
export const PLAYMAT_DIR = join(import.meta.dirname, '..', 'data', 'playmats')
|
||||
|
||||
const MAX_PLAYMAT_BYTES = 3_000_000
|
||||
const PLAYMAT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
||||
const PLAYMAT_DATA_URL = /^data:image\/jpeg;base64,([A-Za-z0-9+/]+={0,2})$/
|
||||
const JPEG_SIGNATURE = Buffer.from([0xff, 0xd8, 0xff])
|
||||
|
||||
export class PlaymatError extends Error {}
|
||||
|
||||
const downloads = new Map<string, Promise<Buffer>>()
|
||||
|
||||
/** Only accept art from Scryfall's image host, never an arbitrary URL from the data file. */
|
||||
export function scryfallImageUrl(uri: string | undefined): string | undefined {
|
||||
if (!uri) return undefined
|
||||
try {
|
||||
const url = new URL(uri)
|
||||
const scryfall = url.hostname === 'scryfall.io' || url.hostname.endsWith('.scryfall.io')
|
||||
return url.protocol === 'https:' && scryfall ? url.href : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Scryfall serves the same art wider for playmats; swap the size segment of a normal image URL. */
|
||||
export function scryfallArtUrl(uri: string | undefined): string | undefined {
|
||||
const source = scryfallImageUrl(uri)
|
||||
if (!source) return undefined
|
||||
return scryfallImageUrl(source.replace('/normal/', '/art_crop/'))
|
||||
}
|
||||
|
||||
async function cachedImage(key: string, source: string, dir: string): Promise<Buffer> {
|
||||
const file = join(dir, `${key}.jpg`)
|
||||
|
||||
try {
|
||||
return await readFile(file)
|
||||
} catch {
|
||||
// Not cached yet.
|
||||
}
|
||||
|
||||
let download = downloads.get(file)
|
||||
if (!download) {
|
||||
download = (async () => {
|
||||
const response = await fetch(source, {
|
||||
headers: { 'User-Agent': 'commander-api/0.1', Accept: 'image/jpeg,image/*' },
|
||||
})
|
||||
if (!response.ok || !response.headers.get('content-type')?.startsWith('image/')) {
|
||||
throw new Error(`Scryfall image request failed: ${response.status}`)
|
||||
}
|
||||
|
||||
const data = Buffer.from(await response.arrayBuffer())
|
||||
await mkdir(dir, { recursive: true })
|
||||
const temp = `${file}.tmp`
|
||||
await writeFile(temp, data)
|
||||
await rename(temp, file)
|
||||
return data
|
||||
})().finally(() => downloads.delete(file))
|
||||
downloads.set(file, download)
|
||||
}
|
||||
|
||||
return download
|
||||
}
|
||||
|
||||
/** Return a card's face, downloading it from Scryfall once and keeping a copy on disk. */
|
||||
export function cardImage(oracleId: string, source: string, dir = IMAGE_DIR): Promise<Buffer> {
|
||||
return cachedImage(encodeURIComponent(oracleId), source, dir)
|
||||
}
|
||||
|
||||
/** Wide art crop used as a playmat. Cached separately from the card face. */
|
||||
export function cardArt(oracleId: string, source: string, dir = IMAGE_DIR): Promise<Buffer> {
|
||||
return cachedImage(`art-${encodeURIComponent(oracleId)}`, source, dir)
|
||||
}
|
||||
|
||||
/** Validate and store an uploaded playmat, returning the id used in its URL. */
|
||||
export async function storePlaymatImage(dataUrl: string, dir = PLAYMAT_DIR): Promise<string> {
|
||||
const match = PLAYMAT_DATA_URL.exec(dataUrl)
|
||||
if (!match) throw new PlaymatError('Playmat must be a base64 JPEG image')
|
||||
const data = Buffer.from(match[1], 'base64')
|
||||
if (!data.length || data.length > MAX_PLAYMAT_BYTES) {
|
||||
throw new PlaymatError('Playmat image must be under 3 MB')
|
||||
}
|
||||
if (!data.subarray(0, JPEG_SIGNATURE.length).equals(JPEG_SIGNATURE)) {
|
||||
throw new PlaymatError('Playmat image is not a JPEG')
|
||||
}
|
||||
|
||||
const id = randomUUID()
|
||||
await mkdir(dir, { recursive: true })
|
||||
await writeFile(join(dir, `${id}.jpg`), data)
|
||||
return id
|
||||
}
|
||||
|
||||
export async function playmatImage(id: string, dir = PLAYMAT_DIR): Promise<Buffer | undefined> {
|
||||
if (!PLAYMAT_ID.test(id)) return undefined
|
||||
try {
|
||||
return await readFile(join(dir, `${id}.jpg`))
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export async function deletePlaymatImage(id: string, dir = PLAYMAT_DIR): Promise<void> {
|
||||
if (!PLAYMAT_ID.test(id)) return
|
||||
await rm(join(dir, `${id}.jpg`), { force: true })
|
||||
}
|
||||
458
backend/src/server.ts
Normal file
458
backend/src/server.ts
Normal file
@@ -0,0 +1,458 @@
|
||||
import Fastify from 'fastify'
|
||||
import cors from '@fastify/cors'
|
||||
import {
|
||||
AuthError,
|
||||
closeDatabase,
|
||||
connectDatabase,
|
||||
registerAccountRoutes,
|
||||
} from './accounts.js'
|
||||
import {
|
||||
CardsUnavailableError,
|
||||
findCardByName,
|
||||
getCard,
|
||||
matchesCardFilters,
|
||||
searchCards,
|
||||
} from './cards.js'
|
||||
import {
|
||||
compileImplementation,
|
||||
deleteOverride,
|
||||
getImplementation,
|
||||
implementationIndex,
|
||||
invalidateImplementationIndex,
|
||||
readOverride,
|
||||
writeOverride,
|
||||
type ImplementationStatus,
|
||||
} from './effects/implementations.js'
|
||||
import { PseudoParseError } from './effects/pseudo.js'
|
||||
import { translateCard, TranslationError } from './effects/translate.js'
|
||||
import { importDeckText } from './game/commander.js'
|
||||
import { cardArt, cardImage, playmatImage, scryfallArtUrl, scryfallImageUrl } from './images.js'
|
||||
import {
|
||||
MatchError,
|
||||
createMatch,
|
||||
getMatchView,
|
||||
joinMatch,
|
||||
leaveMatch,
|
||||
listMatches,
|
||||
performAction,
|
||||
setDeck,
|
||||
setPlaymat,
|
||||
startMatch,
|
||||
subscribe,
|
||||
type ActionPayload,
|
||||
type DeckSubmission,
|
||||
type MatchView,
|
||||
type PlaymatSubmission,
|
||||
} from './game/rooms.js'
|
||||
|
||||
const app = Fastify({ logger: true })
|
||||
const STATUS_FILTERS = new Set<ImplementationStatus | 'needs-work' | 'manual' | 'all'>([
|
||||
'supported',
|
||||
'partial',
|
||||
'unsupported',
|
||||
'needs-work',
|
||||
'manual',
|
||||
'all',
|
||||
])
|
||||
const COLOR_FILTERS = new Set(['W', 'U', 'B', 'R', 'G', 'C', 'M'])
|
||||
const TYPE_FILTERS = new Set([
|
||||
'artifact', 'battle', 'creature', 'enchantment', 'instant', 'kindred', 'land',
|
||||
'planeswalker', 'sorcery', 'legendary',
|
||||
])
|
||||
const RARITY_FILTERS = new Set(['common', 'uncommon', 'rare', 'mythic', 'special', 'bonus'])
|
||||
|
||||
function parseCmc(value: string | undefined): number | undefined | null {
|
||||
if (value === undefined || value === '') return undefined
|
||||
const parsed = Number(value)
|
||||
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null
|
||||
}
|
||||
|
||||
await app.register(cors, {
|
||||
origin: process.env.CORS_ORIGIN?.split(',').map(origin => origin.trim())
|
||||
?? ['http://localhost:3000'],
|
||||
// @fastify/cors defaults to GET,HEAD,POST; decks and preferences are saved with PUT.
|
||||
methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
|
||||
})
|
||||
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
if (error instanceof CardsUnavailableError) {
|
||||
return reply.code(503).send({ error: error.message })
|
||||
}
|
||||
if (error instanceof PseudoParseError) {
|
||||
return reply.code(400).send({ error: error.message, line: error.line })
|
||||
}
|
||||
if (error instanceof TranslationError || error instanceof MatchError || error instanceof AuthError) {
|
||||
return reply.code(error.status).send({ error: error.message })
|
||||
}
|
||||
|
||||
request.log.error(error)
|
||||
return reply.code(500).send({ error: 'Internal server error' })
|
||||
})
|
||||
|
||||
registerAccountRoutes(app)
|
||||
|
||||
app.get('/health', async () => ({ status: 'ok', service: 'commander-api' }))
|
||||
|
||||
app.get<{
|
||||
Querystring: {
|
||||
q?: string
|
||||
limit?: string
|
||||
offset?: string
|
||||
status?: string
|
||||
format?: string
|
||||
color?: string
|
||||
type?: string
|
||||
rarity?: string
|
||||
cmcMin?: string
|
||||
cmcMax?: string
|
||||
}
|
||||
}>(
|
||||
'/cards',
|
||||
async (request, reply) => {
|
||||
const { q = '', limit, offset, status = 'all' } = request.query
|
||||
if (!STATUS_FILTERS.has(status as ImplementationStatus | 'needs-work' | 'manual' | 'all')) {
|
||||
return reply.code(400).send({ error: `Unknown status filter: ${status}` })
|
||||
}
|
||||
|
||||
const format = request.query.format?.trim().toLowerCase() || undefined
|
||||
if (format && !/^[a-z][a-z0-9_]{0,31}$/.test(format)) {
|
||||
return reply.code(400).send({ error: `Invalid format filter: ${format}` })
|
||||
}
|
||||
|
||||
const color = request.query.color?.trim().toUpperCase() || undefined
|
||||
if (color && !COLOR_FILTERS.has(color)) {
|
||||
return reply.code(400).send({ error: `Unknown color filter: ${color}` })
|
||||
}
|
||||
|
||||
const type = request.query.type?.trim().toLowerCase() || undefined
|
||||
if (type && !TYPE_FILTERS.has(type)) {
|
||||
return reply.code(400).send({ error: `Unknown type filter: ${type}` })
|
||||
}
|
||||
|
||||
const rarity = request.query.rarity?.trim().toLowerCase() || undefined
|
||||
if (rarity && !RARITY_FILTERS.has(rarity)) {
|
||||
return reply.code(400).send({ error: `Unknown rarity filter: ${rarity}` })
|
||||
}
|
||||
|
||||
const cmcMin = parseCmc(request.query.cmcMin)
|
||||
const cmcMax = parseCmc(request.query.cmcMax)
|
||||
if (cmcMin === null || cmcMax === null) {
|
||||
return reply.code(400).send({ error: 'Mana value filters must be non-negative numbers' })
|
||||
}
|
||||
|
||||
const parsedLimit = Number.parseInt(limit ?? '50', 10)
|
||||
const pageSize = Number.isFinite(parsedLimit) ? Math.min(Math.max(parsedLimit, 1), 200) : 50
|
||||
const parsedOffset = Number.parseInt(offset ?? '0', 10)
|
||||
const start = Number.isFinite(parsedOffset) ? Math.max(parsedOffset, 0) : 0
|
||||
const index = await implementationIndex()
|
||||
|
||||
const result = searchCards(q, pageSize, start, card => {
|
||||
const summary = index.get(card.oracle_id)
|
||||
if (status === 'manual' && !summary?.manual) return false
|
||||
if (status === 'needs-work' && summary?.status === 'supported') return false
|
||||
if (status !== 'all' && status !== 'manual' && status !== 'needs-work' && summary?.status !== status) {
|
||||
return false
|
||||
}
|
||||
return matchesCardFilters(card, { format, color, type, rarity, cmcMin, cmcMax })
|
||||
})
|
||||
|
||||
return {
|
||||
total: result.total,
|
||||
cards: result.cards.map(card => ({
|
||||
...card,
|
||||
implementation: index.get(card.oracle_id) ?? null,
|
||||
})),
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
app.get('/stats', async () => {
|
||||
const index = await implementationIndex()
|
||||
const stats = { supported: 0, partial: 0, unsupported: 0, manual: 0 }
|
||||
for (const summary of index.values()) {
|
||||
stats[summary.status]++
|
||||
if (summary.manual) stats.manual++
|
||||
}
|
||||
return stats
|
||||
})
|
||||
|
||||
app.get<{ Params: { id: string } }>('/cards/:id', async (request, reply) => {
|
||||
const card = getCard(request.params.id)
|
||||
if (!card) return reply.code(404).send({ error: 'Card not found' })
|
||||
return card
|
||||
})
|
||||
|
||||
/** Only fetch art from Scryfall's image host, never an arbitrary URL from the data file. */
|
||||
app.get<{ Params: { id: string } }>('/cards/:id/image', async (request, reply) => {
|
||||
const card = getCard(request.params.id)
|
||||
if (!card) return reply.code(404).send({ error: 'Card not found' })
|
||||
|
||||
const source = scryfallImageUrl(card.image_uri)
|
||||
if (!source) return reply.code(404).send({ error: 'Card image not available' })
|
||||
|
||||
try {
|
||||
const image = await cardImage(card.oracle_id, source)
|
||||
return reply
|
||||
.header('Cache-Control', 'public, max-age=31536000, immutable')
|
||||
.type('image/jpeg')
|
||||
.send(image)
|
||||
} catch (error) {
|
||||
request.log.warn({ err: error, card: card.oracle_id }, 'Card image download failed')
|
||||
return reply.code(502).send({ error: 'Card image unavailable' })
|
||||
}
|
||||
})
|
||||
|
||||
app.get<{ Params: { id: string } }>('/cards/:id/art', async (request, reply) => {
|
||||
const card = getCard(request.params.id)
|
||||
if (!card) return reply.code(404).send({ error: 'Card not found' })
|
||||
|
||||
const source = scryfallArtUrl(card.image_uri)
|
||||
if (!source) return reply.code(404).send({ error: 'Card art not available' })
|
||||
|
||||
try {
|
||||
const image = await cardArt(card.oracle_id, source)
|
||||
return reply
|
||||
.header('Cache-Control', 'public, max-age=31536000, immutable')
|
||||
.type('image/jpeg')
|
||||
.send(image)
|
||||
} catch (error) {
|
||||
request.log.warn({ err: error, card: card.oracle_id }, 'Card art download failed')
|
||||
return reply.code(502).send({ error: 'Card art unavailable' })
|
||||
}
|
||||
})
|
||||
|
||||
app.get<{ Params: { id: string } }>('/cards/:id/implementation', async (request, reply) => {
|
||||
const card = getCard(request.params.id)
|
||||
if (!card) return reply.code(404).send({ error: 'Card not found' })
|
||||
return { card, ...(await getImplementation(card)) }
|
||||
})
|
||||
|
||||
app.put<{ Params: { id: string }; Body: { source?: unknown } }>(
|
||||
'/cards/:id/implementation',
|
||||
async (request, reply) => {
|
||||
const card = getCard(request.params.id)
|
||||
if (!card) return reply.code(404).send({ error: 'Card not found' })
|
||||
|
||||
const source = request.body?.source
|
||||
if (typeof source !== 'string') {
|
||||
return reply.code(400).send({ error: 'Body must be JSON with a "source" string' })
|
||||
}
|
||||
if (source.length > 1_000_000) {
|
||||
return reply.code(413).send({ error: 'Implementation is too large' })
|
||||
}
|
||||
|
||||
// Validate before touching the existing file, so a typo cannot lose work.
|
||||
compileImplementation(card, source)
|
||||
await writeOverride(card.oracle_id, source)
|
||||
invalidateImplementationIndex()
|
||||
return { card, ...(await getImplementation(card)) }
|
||||
},
|
||||
)
|
||||
|
||||
app.post<{ Params: { id: string } }>('/cards/:id/translate', async (request, reply) => {
|
||||
const card = getCard(request.params.id)
|
||||
if (!card) return reply.code(404).send({ error: 'Card not found' })
|
||||
return { source: await translateCard(card) }
|
||||
})
|
||||
|
||||
app.delete<{ Params: { id: string } }>('/cards/:id/implementation', async (request, reply) => {
|
||||
const card = getCard(request.params.id)
|
||||
if (!card) return reply.code(404).send({ error: 'Card not found' })
|
||||
await deleteOverride(card.oracle_id)
|
||||
invalidateImplementationIndex()
|
||||
return { card, ...(await getImplementation(card)) }
|
||||
})
|
||||
|
||||
// Kept for scripts and debugging: a card has an override even if nobody asked
|
||||
// for the whole implementation payload.
|
||||
app.get<{ Params: { id: string } }>('/cards/:id/override', async (request, reply) => {
|
||||
const override = await readOverride(request.params.id)
|
||||
if (!override) return reply.code(404).send({ error: 'No manual implementation' })
|
||||
return override
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Decks and Commander games
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
app.post<{ Body: { text?: unknown } }>('/decks/import', async (request, reply) => {
|
||||
const text = request.body?.text
|
||||
if (typeof text !== 'string') {
|
||||
return reply.code(400).send({ error: 'Body must be JSON with a "text" string' })
|
||||
}
|
||||
if (text.length > 200_000) {
|
||||
return reply.code(413).send({ error: 'Decklist is too large' })
|
||||
}
|
||||
return importDeckText(text)
|
||||
})
|
||||
|
||||
app.post<{ Body: { names?: unknown } }>('/cards/resolve', async (request, reply) => {
|
||||
const names = request.body?.names
|
||||
if (!Array.isArray(names) || names.some(name => typeof name !== 'string')) {
|
||||
return reply.code(400).send({ error: 'Body must be JSON with a "names" string array' })
|
||||
}
|
||||
return { cards: names.slice(0, 100).map(name => findCardByName(String(name)) ?? null) }
|
||||
})
|
||||
|
||||
app.get('/games', async () => ({ games: listMatches() }))
|
||||
|
||||
/** A stale or invalid browser preference must never block creating or joining a game. */
|
||||
async function applyPlaymat(
|
||||
match: { matchId: string; token: string },
|
||||
playmat: PlaymatSubmission | undefined,
|
||||
): Promise<void> {
|
||||
if (!playmat) return
|
||||
try {
|
||||
await setPlaymat(match.matchId, match.token, playmat)
|
||||
} catch (error) {
|
||||
if (!(error instanceof MatchError)) throw error
|
||||
}
|
||||
}
|
||||
|
||||
app.post<{
|
||||
Body: { name?: unknown; deck?: DeckSubmission; maxPlayers?: unknown; playmat?: PlaymatSubmission }
|
||||
}>(
|
||||
'/games',
|
||||
{ bodyLimit: 4_500_000 },
|
||||
async (request, reply) => {
|
||||
try {
|
||||
const match = createMatch(request.body?.name, request.body?.deck, request.body?.maxPlayers)
|
||||
await applyPlaymat(match, request.body?.playmat)
|
||||
return match
|
||||
} catch (error) {
|
||||
if (error instanceof MatchError) return reply.code(error.status).send({ error: error.message })
|
||||
throw error
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
app.post<{
|
||||
Params: { id: string }
|
||||
Body: { name?: unknown; deck?: DeckSubmission; playmat?: PlaymatSubmission }
|
||||
}>(
|
||||
'/games/:id/join',
|
||||
{ bodyLimit: 4_500_000 },
|
||||
async (request, reply) => {
|
||||
try {
|
||||
const match = joinMatch(request.params.id, request.body?.name, request.body?.deck)
|
||||
await applyPlaymat(match, request.body?.playmat)
|
||||
return match
|
||||
} catch (error) {
|
||||
if (error instanceof MatchError) return reply.code(error.status).send({ error: error.message })
|
||||
throw error
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
app.post<{ Params: { id: string }; Body: { token?: string } }>(
|
||||
'/games/:id/leave',
|
||||
async (request, reply) => {
|
||||
leaveMatch(request.params.id, request.body?.token)
|
||||
return { ok: true }
|
||||
},
|
||||
)
|
||||
|
||||
app.post<{ Params: { id: string }; Body: { token?: string } }>(
|
||||
'/games/:id/start',
|
||||
async (request, reply) => {
|
||||
startMatch(request.params.id, request.body?.token)
|
||||
return { ok: true }
|
||||
},
|
||||
)
|
||||
|
||||
app.post<{ Params: { id: string }; Body: { token?: string; action?: ActionPayload } }>(
|
||||
'/games/:id/actions',
|
||||
async (request, reply) => {
|
||||
if (!request.body?.action) {
|
||||
return reply.code(400).send({ error: 'Body must include an action' })
|
||||
}
|
||||
performAction(request.params.id, request.body.token, request.body.action)
|
||||
return { ok: true }
|
||||
},
|
||||
)
|
||||
|
||||
app.post<{ Params: { id: string }; Body: { token?: string; deck?: DeckSubmission } }>(
|
||||
'/games/:id/deck',
|
||||
async (request, reply) => {
|
||||
setDeck(request.params.id, request.body?.token, request.body?.deck)
|
||||
return { ok: true }
|
||||
},
|
||||
)
|
||||
|
||||
app.post<{ Params: { id: string }; Body: { token?: string; playmat?: PlaymatSubmission } }>(
|
||||
'/games/:id/playmat',
|
||||
{ bodyLimit: 4_500_000 },
|
||||
async (request, reply) => {
|
||||
try {
|
||||
const playmat = await setPlaymat(request.params.id, request.body?.token, request.body?.playmat)
|
||||
return { playmat }
|
||||
} catch (error) {
|
||||
if (error instanceof MatchError) return reply.code(error.status).send({ error: error.message })
|
||||
throw error
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
app.get<{ Params: { id: string } }>('/playmats/:id', async (request, reply) => {
|
||||
const image = await playmatImage(request.params.id)
|
||||
if (!image) return reply.code(404).send({ error: 'Playmat not found' })
|
||||
return reply
|
||||
.header('Cache-Control', 'public, max-age=31536000, immutable')
|
||||
.header('X-Content-Type-Options', 'nosniff')
|
||||
.type('image/jpeg')
|
||||
.send(image)
|
||||
})
|
||||
|
||||
app.get<{ Params: { id: string }; Querystring: { token?: string } }>(
|
||||
'/games/:id/state',
|
||||
async request => getMatchView(request.params.id, request.query.token),
|
||||
)
|
||||
|
||||
app.get<{ Params: { id: string }; Querystring: { token?: string } }>(
|
||||
'/games/:id/events',
|
||||
(request, reply) => {
|
||||
const token = request.query.token
|
||||
// Validate before hijacking so errors keep their status codes.
|
||||
getMatchView(request.params.id, token)
|
||||
|
||||
const origin = request.headers.origin
|
||||
const allowed = process.env.CORS_ORIGIN?.split(',').map(entry => entry.trim())
|
||||
?? ['http://localhost:3000']
|
||||
const allowOrigin = origin && allowed.includes(origin) ? origin : allowed[0]
|
||||
|
||||
reply.hijack()
|
||||
reply.raw.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache, no-transform',
|
||||
Connection: 'keep-alive',
|
||||
'X-Accel-Buffering': 'no',
|
||||
'Access-Control-Allow-Origin': allowOrigin,
|
||||
})
|
||||
reply.raw.write(': connected\n\n')
|
||||
|
||||
const send = (state: MatchView): void => {
|
||||
reply.raw.write(`data: ${JSON.stringify(state)}\n\n`)
|
||||
}
|
||||
const unsubscribe = subscribe(request.params.id, token, send)
|
||||
const ping = setInterval(() => reply.raw.write(': ping\n\n'), 25_000)
|
||||
request.raw.on('close', () => {
|
||||
clearInterval(ping)
|
||||
unsubscribe()
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
await connectDatabase()
|
||||
|
||||
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
||||
process.on(signal, async () => {
|
||||
await app.close()
|
||||
await closeDatabase()
|
||||
process.exit(0)
|
||||
})
|
||||
}
|
||||
|
||||
await app.listen({
|
||||
port: Number(process.env.PORT ?? 4000),
|
||||
host: '0.0.0.0',
|
||||
})
|
||||
13
backend/test/accounts.test.ts
Normal file
13
backend/test/accounts.test.ts
Normal 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)
|
||||
})
|
||||
53
backend/test/cards.test.ts
Normal file
53
backend/test/cards.test.ts
Normal 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)
|
||||
})
|
||||
159
backend/test/commander.test.ts
Normal file
159
backend/test/commander.test.ts
Normal 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')
|
||||
})
|
||||
297
backend/test/effects.test.ts
Normal file
297
backend/test/effects.test.ts
Normal 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
647
backend/test/game.test.ts
Normal 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)
|
||||
})
|
||||
89
backend/test/images.test.ts
Normal file
89
backend/test/images.test.ts
Normal 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 })
|
||||
}
|
||||
})
|
||||
92
backend/test/pseudo.test.ts
Normal file
92
backend/test/pseudo.test.ts
Normal 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)
|
||||
})
|
||||
38
backend/test/rooms.test.ts
Normal file
38
backend/test/rooms.test.ts
Normal 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)
|
||||
})
|
||||
117
backend/test/translate.test.ts
Normal file
117
backend/test/translate.test.ts
Normal 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/)
|
||||
})
|
||||
13
backend/tsconfig.json
Normal file
13
backend/tsconfig.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
40
docker-compose.dev.yml
Normal file
40
docker-compose.dev.yml
Normal file
@@ -0,0 +1,40 @@
|
||||
name: commander-dev
|
||||
|
||||
services:
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
target: dev
|
||||
command: sh -c "npm install --no-audit --no-fund && npm run dev"
|
||||
volumes:
|
||||
- ./backend:/app
|
||||
- backend_node_modules:/app/node_modules
|
||||
# Host networking lets the container reach a MongoDB bound to 127.0.0.1.
|
||||
network_mode: host
|
||||
environment:
|
||||
PORT: ${PORT:-4000}
|
||||
CORS_ORIGIN: ${CORS_ORIGIN:-http://localhost:3000}
|
||||
MONGODB_URI: ${MONGODB_URI:-mongodb://localhost:27017/commander}
|
||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
||||
OPENROUTER_MODEL: ${OPENROUTER_MODEL:-google/gemini-2.5-flash-lite}
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
target: dev
|
||||
command: sh -c "npm install --no-audit --no-fund && npm run dev -- --host 0.0.0.0"
|
||||
volumes:
|
||||
- ./frontend:/app
|
||||
- frontend_node_modules:/app/node_modules
|
||||
- frontend_nuxt:/app/.nuxt
|
||||
ports:
|
||||
- "${FRONTEND_PORT:-3000}:3000"
|
||||
environment:
|
||||
NUXT_PUBLIC_API_BASE: ${NUXT_PUBLIC_API_BASE:-http://localhost:4000}
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
volumes:
|
||||
backend_node_modules:
|
||||
frontend_node_modules:
|
||||
frontend_nuxt:
|
||||
44
docker-compose.yml
Normal file
44
docker-compose.yml
Normal file
@@ -0,0 +1,44 @@
|
||||
name: commander
|
||||
|
||||
services:
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
target: production
|
||||
# Host networking lets the container reach a MongoDB bound to 127.0.0.1.
|
||||
network_mode: host
|
||||
environment:
|
||||
PORT: 4000
|
||||
CORS_ORIGIN: ${CORS_ORIGIN:-http://localhost:3000}
|
||||
MONGODB_URI: ${MONGODB_URI:-mongodb://localhost:27017/commander}
|
||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
||||
OPENROUTER_MODEL: ${OPENROUTER_MODEL:-google/gemini-2.5-flash-lite}
|
||||
volumes:
|
||||
- card_images:/app/data/images
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO /dev/null http://127.0.0.1:4000/health"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
target: production
|
||||
ports:
|
||||
- "${FRONTEND_PORT:-3000}:3000"
|
||||
environment:
|
||||
NUXT_PUBLIC_API_BASE: ${NUXT_PUBLIC_API_BASE:-http://localhost:4000}
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO /dev/null http://127.0.0.1:3000/"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
volumes:
|
||||
card_images:
|
||||
6
frontend/.dockerignore
Normal file
6
frontend/.dockerignore
Normal file
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
.nuxt
|
||||
.output
|
||||
.env
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
24
frontend/.gitignore
vendored
Normal file
24
frontend/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Nuxt dev/build outputs
|
||||
.output
|
||||
.data
|
||||
.nuxt
|
||||
.nitro
|
||||
.cache
|
||||
dist
|
||||
|
||||
# Node dependencies
|
||||
node_modules
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
||||
# Misc
|
||||
.DS_Store
|
||||
.fleet
|
||||
.idea
|
||||
|
||||
# Local env files
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
22
frontend/Dockerfile
Normal file
22
frontend/Dockerfile
Normal file
@@ -0,0 +1,22 @@
|
||||
FROM node:24-alpine AS base
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
FROM base AS dev
|
||||
COPY . .
|
||||
EXPOSE 3000
|
||||
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0"]
|
||||
|
||||
FROM base AS build
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:24-alpine AS production
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
ENV HOST=0.0.0.0
|
||||
ENV PORT=3000
|
||||
COPY --from=build /app/.output ./.output
|
||||
EXPOSE 3000
|
||||
CMD ["node", ".output/server/index.mjs"]
|
||||
71
frontend/app/app.vue
Normal file
71
frontend/app/app.vue
Normal file
@@ -0,0 +1,71 @@
|
||||
<script setup lang="ts">
|
||||
import { AUTH_CHANGED, authToken } from '~/utils/auth'
|
||||
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
const route = useRoute()
|
||||
const SESSION_PREFIX = 'commander-session-'
|
||||
|
||||
const authCookie = useCookie('commander-auth-token')
|
||||
const signedIn = ref(Boolean(authCookie.value))
|
||||
|
||||
const seatedGames = ref<{ id: string; label: string }[]>([])
|
||||
let poll: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
function syncAuth() {
|
||||
signedIn.value = Boolean(authToken())
|
||||
}
|
||||
|
||||
function seatedGameIds(): string[] {
|
||||
return Object.keys(sessionStorage)
|
||||
.filter(key => key.startsWith(SESSION_PREFIX))
|
||||
.map(key => key.slice(SESSION_PREFIX.length))
|
||||
}
|
||||
|
||||
async function refreshSeatedGames() {
|
||||
const ids = seatedGameIds()
|
||||
const known = ids.length === seatedGames.value.length && ids.every(id => seatedGames.value.some(game => game.id === id))
|
||||
if (known) return
|
||||
if (!ids.length) {
|
||||
seatedGames.value = []
|
||||
return
|
||||
}
|
||||
try {
|
||||
const { games } = await $fetch<{ games: { id: string; hostName: string }[] }>(`${apiBase}/games`)
|
||||
seatedGames.value = ids.flatMap(id => {
|
||||
const game = games.find(entry => entry.id === id)
|
||||
return game ? [{ id, label: `${game.hostName}'s game` }] : []
|
||||
})
|
||||
} catch {
|
||||
// Keep the current tabs when the game list is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
syncAuth()
|
||||
window.addEventListener(AUTH_CHANGED, syncAuth)
|
||||
void refreshSeatedGames()
|
||||
poll = setInterval(refreshSeatedGames, 5000)
|
||||
})
|
||||
watch(() => route.fullPath, refreshSeatedGames)
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener(AUTH_CHANGED, syncAuth)
|
||||
if (poll) clearInterval(poll)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NuxtRouteAnnouncer />
|
||||
<nav v-if="signedIn" class="app-nav">
|
||||
<strong>Commander</strong>
|
||||
<NuxtLink to="/">Play</NuxtLink>
|
||||
<NuxtLink to="/decks">Decks</NuxtLink>
|
||||
<NuxtLink to="/cards">Cards</NuxtLink>
|
||||
<NuxtLink to="/account">Account</NuxtLink>
|
||||
<div v-if="seatedGames.length" class="nav-games">
|
||||
<NuxtLink v-for="game in seatedGames" :key="game.id" :to="`/games/${game.id}`">
|
||||
{{ game.label }}
|
||||
</NuxtLink>
|
||||
</div>
|
||||
</nav>
|
||||
<NuxtPage />
|
||||
</template>
|
||||
411
frontend/app/assets/main.css
Normal file
411
frontend/app/assets/main.css
Normal file
@@ -0,0 +1,411 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #0f1117;
|
||||
--panel: #171a23;
|
||||
--panel-2: #11151d;
|
||||
--line: #2a2f3d;
|
||||
--text: #e8e6e3;
|
||||
--muted: #9aa2b1;
|
||||
--accent: #7aa2f7;
|
||||
--ok: #7dd3a0;
|
||||
--warn: #e8c07d;
|
||||
--bad: #e07a7a;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#__nuxt {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: system-ui, sans-serif;
|
||||
}
|
||||
|
||||
h1, h2, h3, p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.35rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.app-nav {
|
||||
height: 3rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 0 1.25rem;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: #12151d;
|
||||
}
|
||||
|
||||
.app-nav strong {
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
.app-nav a {
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
font-size: 0.9rem;
|
||||
padding: 0.25rem 0;
|
||||
}
|
||||
|
||||
.app-nav a.router-link-active {
|
||||
color: var(--text);
|
||||
border-bottom: 2px solid var(--accent);
|
||||
}
|
||||
|
||||
.nav-games {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
margin-left: auto;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.nav-games a {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.head-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.tabs button {
|
||||
padding: 0.3rem 0.6rem;
|
||||
background: transparent;
|
||||
border-color: transparent;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.tabs button.active {
|
||||
color: var(--text);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
main.fill-page {
|
||||
height: calc(100vh - 3rem);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 1rem 1.25rem;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
main.page {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
main > header {
|
||||
display: flex;
|
||||
align-items: start;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--bad);
|
||||
font-size: 0.85rem;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.ok {
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
.warn {
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
.layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(18rem, 26rem) 1fr;
|
||||
gap: 1rem;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.list-panel,
|
||||
.detail-panel,
|
||||
.panel {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 0.85rem;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.search {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.filters {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.filters select {
|
||||
flex: 1 1 8rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
input, select, textarea, button {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
padding: 0.45rem 0.6rem;
|
||||
}
|
||||
|
||||
input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
button:not(:disabled):hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
button.primary {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
button.danger {
|
||||
border-color: var(--bad);
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
.list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.card-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.detail-head {
|
||||
display: flex;
|
||||
align-items: start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.card-row {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
text-align: left;
|
||||
background: transparent;
|
||||
border-color: transparent;
|
||||
padding: 0.45rem 0.5rem;
|
||||
}
|
||||
|
||||
.card-row.selected {
|
||||
background: #202636;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.card-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.card-main {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.card-main .card-name {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.badges {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 0.7rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
border-radius: 99px;
|
||||
padding: 0.1rem 0.45rem;
|
||||
border: 1px solid currentColor;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.badge.supported {
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
.badge.partial {
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
.badge.unsupported {
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
.badge.manual {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.pager {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.oracle {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
border-left: 2px solid var(--line);
|
||||
padding-left: 0.75rem;
|
||||
font-size: 0.9rem;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
textarea {
|
||||
min-height: 12rem;
|
||||
resize: vertical;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.saved-at {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.wrap {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.grow {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.tag {
|
||||
font-size: 0.75rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 99px;
|
||||
padding: 0.1rem 0.45rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.tag.good {
|
||||
color: var(--ok);
|
||||
border-color: currentColor;
|
||||
}
|
||||
|
||||
.tag.bad {
|
||||
color: var(--bad);
|
||||
border-color: currentColor;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
main.fill-page {
|
||||
height: auto;
|
||||
min-height: calc(100vh - 3rem);
|
||||
}
|
||||
|
||||
.layout {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.list {
|
||||
max-height: 40vh;
|
||||
}
|
||||
|
||||
.detail-panel {
|
||||
min-height: 60vh;
|
||||
}
|
||||
}
|
||||
1094
frontend/app/components/CardGraphEditor.vue
Normal file
1094
frontend/app/components/CardGraphEditor.vue
Normal file
File diff suppressed because it is too large
Load Diff
77
frontend/app/components/CardHover.vue
Normal file
77
frontend/app/components/CardHover.vue
Normal file
@@ -0,0 +1,77 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{ oracleId: string; name: string }>()
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
|
||||
const PREVIEW_WIDTH = 244
|
||||
const PREVIEW_HEIGHT = 340
|
||||
|
||||
const visible = ref(false)
|
||||
const failed = ref(false)
|
||||
const left = ref(0)
|
||||
const top = ref(0)
|
||||
|
||||
const src = computed(() => `${apiBase}/cards/${encodeURIComponent(props.oracleId)}/image`)
|
||||
|
||||
function follow(event: MouseEvent) {
|
||||
left.value = Math.max(8, Math.min(
|
||||
event.clientX + 20,
|
||||
window.innerWidth - PREVIEW_WIDTH - 8,
|
||||
))
|
||||
top.value = Math.max(8, Math.min(
|
||||
event.clientY - PREVIEW_HEIGHT / 2,
|
||||
window.innerHeight - PREVIEW_HEIGHT - 8,
|
||||
))
|
||||
}
|
||||
|
||||
function enter(event: MouseEvent) {
|
||||
failed.value = false
|
||||
follow(event)
|
||||
visible.value = true
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
class="card-hover"
|
||||
@mouseenter="enter"
|
||||
@mousemove="follow"
|
||||
@mouseleave="visible = false"
|
||||
@pointerdown="visible = false"
|
||||
>
|
||||
<slot />
|
||||
<Teleport to="body">
|
||||
<img
|
||||
v-if="visible && !failed"
|
||||
class="card-art"
|
||||
:src="src"
|
||||
:alt="`${name} card art`"
|
||||
:style="{ left: `${left}px`, top: `${top}px` }"
|
||||
@error="failed = true"
|
||||
>
|
||||
</Teleport>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.card-hover {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.card-art {
|
||||
position: fixed;
|
||||
z-index: 100;
|
||||
width: 244px;
|
||||
height: auto;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.55);
|
||||
pointer-events: none;
|
||||
animation: card-art-in 140ms ease-out;
|
||||
}
|
||||
|
||||
@keyframes card-art-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.96);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
98
frontend/app/components/GameCard.vue
Normal file
98
frontend/app/components/GameCard.vue
Normal file
@@ -0,0 +1,98 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
oracleId: string
|
||||
name: string
|
||||
tapped?: boolean
|
||||
}>()
|
||||
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
|
||||
const failed = ref(false)
|
||||
const src = computed(() => `${apiBase}/cards/${encodeURIComponent(props.oracleId)}/image`)
|
||||
const token = computed(() => props.oracleId.startsWith('token:'))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="game-card" :class="{ tapped, token }">
|
||||
<div class="card-face">
|
||||
<img
|
||||
v-if="!failed && !token"
|
||||
:src="src"
|
||||
:alt="name"
|
||||
loading="lazy"
|
||||
draggable="false"
|
||||
@error="failed = true"
|
||||
>
|
||||
<div v-else class="card-fallback">
|
||||
<span class="fallback-name">{{ name }}</span>
|
||||
<span v-if="token" class="fallback-kind">Token</span>
|
||||
</div>
|
||||
</div>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.game-card {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 488 / 680;
|
||||
}
|
||||
|
||||
.game-card.tapped {
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.card-face {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
transform-origin: center;
|
||||
transition: transform 150ms ease;
|
||||
}
|
||||
|
||||
.game-card.tapped .card-face {
|
||||
transform: rotate(90deg) scale(0.7);
|
||||
}
|
||||
|
||||
img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 6px;
|
||||
object-fit: cover;
|
||||
background: #0b0d12;
|
||||
box-shadow: 0 3px 10px rgb(0 0 0 / 45%);
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
|
||||
.card-fallback {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.35rem;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 0.6rem;
|
||||
border: 1px solid #5b563f;
|
||||
border-radius: 6px;
|
||||
background:
|
||||
radial-gradient(circle at 50% 30%, rgb(232 192 125 / 14%), transparent 70%),
|
||||
#1d211b;
|
||||
box-shadow: 0 3px 10px rgb(0 0 0 / 45%);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.fallback-name {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.fallback-kind {
|
||||
font-size: 0.6rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--muted);
|
||||
}
|
||||
</style>
|
||||
54
frontend/app/components/ManaCost.vue
Normal file
54
frontend/app/components/ManaCost.vue
Normal file
@@ -0,0 +1,54 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{ cost?: string }>()
|
||||
|
||||
const groups = computed(() => (props.cost ?? '')
|
||||
.split('//')
|
||||
.map(group => group.match(/\{([^}]+)\}/g)?.map(token => token.slice(1, -1)) ?? [])
|
||||
.filter(group => group.length > 0))
|
||||
|
||||
/** mana-font names a few symbols differently from Scryfall's code. */
|
||||
const ALIASES: Record<string, string> = { T: 'tap', Q: 'untap', '∞': 'infinity' }
|
||||
|
||||
function classOf(symbol: string): string {
|
||||
return ALIASES[symbol.toUpperCase()] ?? symbol.replaceAll('/', '').toLowerCase()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
v-if="groups.length"
|
||||
class="mana-cost"
|
||||
role="img"
|
||||
:aria-label="`Mana cost ${cost}`"
|
||||
>
|
||||
<template v-for="(group, groupIndex) in groups" :key="groupIndex">
|
||||
<span v-if="groupIndex" class="mana-separator" aria-hidden="true">//</span>
|
||||
<i
|
||||
v-for="(symbol, index) in group"
|
||||
:key="`${symbol}-${index}`"
|
||||
class="ms ms-cost mana-symbol"
|
||||
:class="`ms-${classOf(symbol)}`"
|
||||
:title="`{${symbol}}`"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</template>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.mana-cost {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.mana-symbol {
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
|
||||
.mana-separator {
|
||||
color: var(--muted);
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
</style>
|
||||
199
frontend/app/components/PlaymatPicker.vue
Normal file
199
frontend/app/components/PlaymatPicker.vue
Normal file
@@ -0,0 +1,199 @@
|
||||
<script setup lang="ts">
|
||||
import type { PlaymatSelection } from '~/utils/playmat'
|
||||
import { resizeImage } from '~/utils/image'
|
||||
|
||||
interface CardSummary {
|
||||
oracle_id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
current?: { kind: 'card'; oracleId: string } | { kind: 'upload'; url: string } | null
|
||||
busy?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ select: [selection: PlaymatSelection] }>()
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
|
||||
const query = ref('')
|
||||
const results = ref<CardSummary[]>([])
|
||||
const searching = ref(false)
|
||||
const localError = ref('')
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const previewUrl = computed(() => {
|
||||
const current = props.current
|
||||
if (!current) return undefined
|
||||
return current.kind === 'card'
|
||||
? `${apiBase}/cards/${encodeURIComponent(current.oracleId)}/art`
|
||||
: current.url
|
||||
})
|
||||
|
||||
async function search() {
|
||||
const term = query.value.trim()
|
||||
if (term.length < 2) {
|
||||
results.value = []
|
||||
searching.value = false
|
||||
return
|
||||
}
|
||||
searching.value = true
|
||||
try {
|
||||
const data = await $fetch<{ cards: CardSummary[] }>(`${apiBase}/cards`, {
|
||||
query: { q: term, limit: 24 },
|
||||
})
|
||||
if (query.value.trim() === term) results.value = data.cards
|
||||
} catch {
|
||||
if (query.value.trim() === term) results.value = []
|
||||
} finally {
|
||||
if (query.value.trim() === term) searching.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(query, () => {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(search, 300)
|
||||
})
|
||||
|
||||
onUnmounted(() => clearTimeout(searchTimer))
|
||||
|
||||
function choose(card: CardSummary) {
|
||||
results.value = []
|
||||
query.value = ''
|
||||
emit('select', { kind: 'card', oracleId: card.oracle_id })
|
||||
}
|
||||
|
||||
/** The API caps uploaded JPEG playmats at 3 MB, so shrink large images first. */
|
||||
async function upload(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
input.value = ''
|
||||
if (!file) return
|
||||
localError.value = ''
|
||||
if (!file.type.startsWith('image/')) {
|
||||
localError.value = 'Choose an image file.'
|
||||
return
|
||||
}
|
||||
try {
|
||||
const data = await resizeImage(file, 1920)
|
||||
if (data.length > 4_000_000) {
|
||||
localError.value = 'That image is too large. Try a smaller one.'
|
||||
return
|
||||
}
|
||||
emit('select', { kind: 'upload', data })
|
||||
} catch {
|
||||
localError.value = 'Could not read that image.'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="playmat-picker">
|
||||
<div
|
||||
class="preview"
|
||||
role="img"
|
||||
:aria-label="previewUrl ? 'Current playmat' : 'No playmat selected'"
|
||||
:style="previewUrl ? { backgroundImage: `url('${previewUrl}')` } : undefined"
|
||||
>
|
||||
<span v-if="!previewUrl" class="muted">No playmat</span>
|
||||
</div>
|
||||
<input
|
||||
v-model="query"
|
||||
type="search"
|
||||
placeholder="Search Magic art…"
|
||||
aria-label="Search Magic art"
|
||||
>
|
||||
<p v-if="busy || searching" class="muted">Working…</p>
|
||||
<p v-else-if="query.trim().length >= 2 && !results.length" class="muted">No cards found.</p>
|
||||
<div v-if="results.length" class="results">
|
||||
<button
|
||||
v-for="card in results"
|
||||
:key="card.oracle_id"
|
||||
type="button"
|
||||
:disabled="busy"
|
||||
:title="`Use ${card.name} as your playmat`"
|
||||
@click="choose(card)"
|
||||
>
|
||||
<img :src="`${apiBase}/cards/${card.oracle_id}/art`" :alt="card.name" loading="lazy">
|
||||
<span>{{ card.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<label class="field">
|
||||
<span class="muted">Upload an image</span>
|
||||
<input type="file" accept="image/*" :disabled="busy" @change="upload">
|
||||
</label>
|
||||
<p v-if="localError" class="error">{{ localError }}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="remove"
|
||||
:disabled="busy || !current"
|
||||
@click="emit('select', { kind: 'none' })"
|
||||
>Remove playmat</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.playmat-picker {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
aspect-ratio: 16 / 7;
|
||||
max-height: 14rem;
|
||||
border: 1px dashed var(--line);
|
||||
border-radius: 6px;
|
||||
background: var(--panel-2) center / cover no-repeat;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.field input[type="file"] {
|
||||
padding: 0.3rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.results {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.4rem;
|
||||
max-height: 18rem;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.results button {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
padding: 0.25rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.results img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
aspect-ratio: 626 / 457;
|
||||
border-radius: 4px;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.results span {
|
||||
overflow: hidden;
|
||||
font-size: 0.72rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.remove {
|
||||
align-self: flex-start;
|
||||
padding: 0.2rem 0.45rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
</style>
|
||||
212
frontend/app/components/PseudoGuide.vue
Normal file
212
frontend/app/components/PseudoGuide.vue
Normal file
@@ -0,0 +1,212 @@
|
||||
<template>
|
||||
<section class="pseudo-guide">
|
||||
<header class="guide-head">
|
||||
<h2>Card pseudocode guide</h2>
|
||||
<p class="muted">
|
||||
The editor and the compiler use the same two-way format. The
|
||||
<strong>Visual</strong> tab is a node canvas: drag sockets to connect an ability to its
|
||||
effects, and drag green value nodes (players, targets, selectors, costs) into argument
|
||||
sockets. Selector <strong>OR</strong>/<strong>AND</strong> nodes can combine two selector
|
||||
slots. It writes the same source as the text editor. Use <strong>Draft with AI</strong> for
|
||||
a first pass, then review and save.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<article>
|
||||
<h3>Shape</h3>
|
||||
<p>
|
||||
One ability per block. The header starts at column 0 and ends with a colon; effects are
|
||||
indented two spaces, one call per line. A leading <code># Card [status]</code> line is
|
||||
optional and ignored. Multi-face cards use <code>## Face Name [status]</code> sections in
|
||||
card order. Use <code>(no abilities)</code> for an empty face.
|
||||
</p>
|
||||
<pre># Soul Warden [supported]
|
||||
on enters(each other creature):
|
||||
gain_life(you, 1)
|
||||
|
||||
# Llanowar Elves [supported]
|
||||
activate {T}:
|
||||
add_mana(you, {G})</pre>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Ability blocks</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Header</th><th>Example</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td><code>on <trigger>:</code></td><td><code>on dies(this):</code></td></tr>
|
||||
<tr><td><code>activate <cost>:</code></td><td><code>activate {2}, {T}:</code></td></tr>
|
||||
<tr><td><code>static:</code></td><td><code>static:</code></td></tr>
|
||||
<tr><td><code>spell:</code></td><td>An instant or sorcery effect line.</td></tr>
|
||||
<tr><td><code>keyword <name></code></td><td><code>keyword Flying</code></td></tr>
|
||||
<tr><td><code>keywords <a>, <b></code></td><td><code>keywords Flying, vigilance</code></td></tr>
|
||||
<tr><td><code>additional cost: <cost></code></td><td><code>additional cost: pay 2 life</code></td></tr>
|
||||
<tr><td><code>if <condition>:</code></td><td>Nested effects, indented below.</td></tr>
|
||||
<tr><td><code>choose <n>:</code></td><td>Numbered modes <code>1.</code>, <code>2.</code></td></tr>
|
||||
<tr><td><code>schedule(next_upkeep):</code></td><td>Delayed effects.</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Effect calls</h3>
|
||||
<p>Effects are lowercase calls. Separate several on one line with <code>;</code>.</p>
|
||||
<pre>damage(target creature, 3)
|
||||
draw(you, 2)
|
||||
gain_life(you, 1)
|
||||
create_token(you, 1, 1/1 red goblin creature)
|
||||
put_counters(target creature, +1/+1, 2)
|
||||
destroy(target creature)
|
||||
exile(target artifact you control)
|
||||
add_mana(you, {G}{G})
|
||||
search(you, creature, 1, to hand, shuffle)
|
||||
scry(you, 2)
|
||||
pump(each creature you control, 1/1, until end of turn)</pre>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Targets, values and costs</h3>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<th>Targets</th>
|
||||
<td><code>this</code>, <code>the triggering object</code>, <code>target creature</code>, <code>each opponent</code>, <code>up to 2 target creatures</code>, <code>any target</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Selectors</th>
|
||||
<td><code>other tapped creature you control</code>, <code>red instant from a graveyard</code>, <code>creature with power 4 or greater</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Values</th>
|
||||
<td><code>2</code>, <code>X</code>, <code>count(creature you control)</code>, <code>its power</code>, <code>that much</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Costs</th>
|
||||
<td><code>{2}{U}</code>, <code>{T}</code>, <code>pay 3 life</code>, <code>discard 1 card(s)</code>, <code>sacrifice this</code>, <code>remove 1 +1/+1 counter(s) from this</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Durations</th>
|
||||
<td><code>until end of turn</code>, <code>until your next turn</code>, <code>until the end of your next turn</code>, <code>for as long as this remains on the battlefield</code></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Triggers, conditions and modes</h3>
|
||||
<pre>on attacks(this):
|
||||
create_token(you, 1, tapped 1/1 red goblin creature)
|
||||
|
||||
on upkeep(you):
|
||||
if you control at least 3 artifacts:
|
||||
draw(you, 1)
|
||||
|
||||
spell:
|
||||
choose 1:
|
||||
1. draw(you, 2)
|
||||
2. gain_life(you, 3)
|
||||
|
||||
static:
|
||||
grant(each creature you control, Flying)</pre>
|
||||
<p class="muted">
|
||||
Common triggers: <code>enters</code>, <code>dies</code>, <code>attacks</code>,
|
||||
<code>upkeep</code>, <code>end_step</code>, <code>cast</code>,
|
||||
<code>deals_damage</code>. Always check the generated line after saving.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>When the syntax cannot express it</h3>
|
||||
<p>
|
||||
Never guess a wrong effect. Use the preserved form and leave the line unsupported:
|
||||
</p>
|
||||
<pre>unsupported (modal bullet outside a choose block): Choose one — ...</pre>
|
||||
<p class="muted">
|
||||
The full reference lives in <code>backend/docs/card-effects.md</code>.
|
||||
</p>
|
||||
</article>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.pseudo-guide {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 1rem 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.guide-head {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
p {
|
||||
line-height: 1.5;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 0.85em;
|
||||
background: #11151d;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
padding: 0.05rem 0.3rem;
|
||||
}
|
||||
|
||||
pre {
|
||||
margin: 0.5rem 0 0;
|
||||
padding: 0.65rem 0.8rem;
|
||||
background: #11151d;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding: 0.35rem 0.5rem;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
th {
|
||||
white-space: nowrap;
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
tbody th {
|
||||
width: 7rem;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
tbody th {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
27
frontend/app/components/SymbolText.vue
Normal file
27
frontend/app/components/SymbolText.vue
Normal file
@@ -0,0 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{ text?: string }>()
|
||||
|
||||
/** Runs of {symbols} render through ManaCost; everything else stays text. */
|
||||
const parts = computed(() => (props.text ?? '')
|
||||
.split(/((?:\{[^}]+\})+)/)
|
||||
.filter(Boolean))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="symbol-text">
|
||||
<template v-for="(part, index) in parts" :key="index">
|
||||
<ManaCost v-if="part.startsWith('{')" :cost="part" />
|
||||
<template v-else>{{ part }}</template>
|
||||
</template>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.symbol-text {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.symbol-text :deep(.mana-cost) {
|
||||
vertical-align: -0.15em;
|
||||
}
|
||||
</style>
|
||||
7
frontend/app/middleware/auth.ts
Normal file
7
frontend/app/middleware/auth.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { authToken } from '~/utils/auth'
|
||||
|
||||
export default defineNuxtRouteMiddleware(to => {
|
||||
const token = import.meta.server ? useCookie('commander-auth-token').value : authToken()
|
||||
if (token) return
|
||||
return navigateTo({ path: '/account', query: { next: to.fullPath } })
|
||||
})
|
||||
370
frontend/app/pages/account.vue
Normal file
370
frontend/app/pages/account.vue
Normal file
@@ -0,0 +1,370 @@
|
||||
<script setup lang="ts">
|
||||
import { authHeaders, hasAuth, setAuthToken } from '~/utils/auth'
|
||||
import { saveDeck, type SavedDeck } from '~/utils/decks'
|
||||
import { loadPlaymatChoice, savePlaymatChoice, type PlaymatChoice, type PlaymatSelection } from '~/utils/playmat'
|
||||
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
const route = useRoute()
|
||||
|
||||
const mode = ref<'login' | 'register'>('login')
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const signedIn = ref('')
|
||||
const busy = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
const playmat = ref<PlaymatChoice>()
|
||||
const playmatError = ref('')
|
||||
const playmatPreview = computed(() => {
|
||||
if (playmat.value?.kind === 'card') return playmat.value
|
||||
if (playmat.value?.kind === 'upload') return { kind: 'upload' as const, url: playmat.value.data }
|
||||
return null
|
||||
})
|
||||
|
||||
async function choosePlaymat(selection: PlaymatSelection) {
|
||||
playmatError.value = ''
|
||||
if (selection.kind === 'none') {
|
||||
if (!(await savePlaymatChoice(apiBase, undefined))) {
|
||||
playmatError.value = 'Could not save that playmat to your account.'
|
||||
return
|
||||
}
|
||||
playmat.value = undefined
|
||||
return
|
||||
}
|
||||
const choice: PlaymatChoice = selection.kind === 'card'
|
||||
? { kind: 'card', oracleId: selection.oracleId }
|
||||
: { kind: 'upload', data: selection.data }
|
||||
if (!(await savePlaymatChoice(apiBase, choice))) {
|
||||
playmatError.value = 'Could not save that playmat to your account. Try a smaller image.'
|
||||
return
|
||||
}
|
||||
playmat.value = choice
|
||||
}
|
||||
|
||||
function nextPath(): string {
|
||||
const next = route.query.next
|
||||
return typeof next === 'string' && next.startsWith('/') && !next.startsWith('//') ? next : '/'
|
||||
}
|
||||
|
||||
function message(caught: unknown): string {
|
||||
const data = (caught as { data?: { error?: string } })?.data
|
||||
return data?.error ?? 'Could not reach the server.'
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
if (!hasAuth()) return
|
||||
try {
|
||||
const data = await $fetch<{ username: string }>(`${apiBase}/auth/me`, { headers: authHeaders() })
|
||||
signedIn.value = data.username
|
||||
} catch {
|
||||
setAuthToken(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
/** Move decks and cosmetic preferences saved by older browser-only versions. */
|
||||
async function migrateLocalData() {
|
||||
if (typeof localStorage === 'undefined') return
|
||||
|
||||
const decks = localStorage.getItem('commander-decks-v1')
|
||||
if (decks !== null) {
|
||||
try {
|
||||
const parsed = JSON.parse(decks) as SavedDeck[]
|
||||
if (Array.isArray(parsed)) {
|
||||
for (const deck of parsed) await saveDeck(apiBase, deck)
|
||||
localStorage.removeItem('commander-decks-v1')
|
||||
}
|
||||
} catch {
|
||||
// Keep corrupt data in place rather than deleting it.
|
||||
}
|
||||
}
|
||||
|
||||
const playmat = localStorage.getItem('commander-playmat-v1')
|
||||
if (playmat !== null) {
|
||||
try {
|
||||
const choice = JSON.parse(playmat) as PlaymatChoice | null
|
||||
if (await savePlaymatChoice(apiBase, choice ?? undefined)) {
|
||||
localStorage.removeItem('commander-playmat-v1')
|
||||
}
|
||||
} catch {
|
||||
// Keep corrupt data in place rather than deleting it.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await $fetch<{ token: string; username: string }>(`${apiBase}/auth/${mode.value}`, {
|
||||
method: 'POST',
|
||||
body: { username: username.value, password: password.value },
|
||||
})
|
||||
setAuthToken(data.token)
|
||||
signedIn.value = data.username
|
||||
try {
|
||||
await migrateLocalData()
|
||||
} catch {
|
||||
// A failed migration must not block signing in.
|
||||
}
|
||||
await navigateTo(nextPath())
|
||||
} catch (caught) {
|
||||
error.value = message(caught)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await $fetch(`${apiBase}/auth/logout`, { method: 'POST', headers: authHeaders() })
|
||||
} catch {
|
||||
// Clearing the token locally is enough.
|
||||
}
|
||||
setAuthToken(undefined)
|
||||
password.value = ''
|
||||
signedIn.value = ''
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await refresh()
|
||||
if (!signedIn.value) return
|
||||
playmat.value = await loadPlaymatChoice(apiBase)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="page account-page">
|
||||
<section class="auth-card" :class="{ wide: signedIn }">
|
||||
<header class="auth-head">
|
||||
<span class="auth-mark" aria-hidden="true">◆</span>
|
||||
<p v-if="signedIn" class="muted">
|
||||
Signed in as <strong>{{ signedIn }}</strong>
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<template v-if="signedIn">
|
||||
<div class="signed-actions">
|
||||
<NuxtLink class="auth-link" to="/">Play</NuxtLink>
|
||||
<NuxtLink class="auth-link" to="/decks">Decks</NuxtLink>
|
||||
<button type="button" class="mini" @click="logout">Sign out</button>
|
||||
</div>
|
||||
|
||||
<section class="prefs">
|
||||
<h2>Playmat</h2>
|
||||
<p class="muted">
|
||||
Your mat for new games. Pick card art or upload an image; you can still change it in-game.
|
||||
</p>
|
||||
<p v-if="playmatError" class="error">{{ playmatError }}</p>
|
||||
<PlaymatPicker :current="playmatPreview" @select="choosePlaymat" />
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="auth-tabs" role="tablist" aria-label="Account mode">
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="mode === 'login'"
|
||||
:class="{ active: mode === 'login' }"
|
||||
@click="mode = 'login'"
|
||||
>Sign in</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="mode === 'register'"
|
||||
:class="{ active: mode === 'register' }"
|
||||
@click="mode = 'register'"
|
||||
>Create account</button>
|
||||
</div>
|
||||
|
||||
<form @submit.prevent="submit">
|
||||
<label class="field">
|
||||
<span>Username</span>
|
||||
<input
|
||||
v-model="username"
|
||||
autocomplete="username"
|
||||
minlength="3"
|
||||
maxlength="32"
|
||||
placeholder="your name"
|
||||
required
|
||||
>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>Password</span>
|
||||
<input
|
||||
v-model="password"
|
||||
type="password"
|
||||
:autocomplete="mode === 'login' ? 'current-password' : 'new-password'"
|
||||
minlength="8"
|
||||
maxlength="200"
|
||||
placeholder="••••••••"
|
||||
required
|
||||
>
|
||||
</label>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<button type="submit" class="primary" :disabled="busy">
|
||||
{{ busy ? 'Working…' : mode === 'login' ? 'Sign in' : 'Create account' }}
|
||||
</button>
|
||||
</form>
|
||||
</template>
|
||||
</section>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
main.account-page {
|
||||
min-height: calc(100vh - 3rem);
|
||||
max-width: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 2rem 1.25rem;
|
||||
background: radial-gradient(60rem 32rem at 50% -12%, rgba(122, 162, 247, 0.13), transparent 70%);
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
width: 100%;
|
||||
max-width: 26rem;
|
||||
padding: 1.75rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(180deg, #1b1f2b, var(--panel));
|
||||
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
.auth-card.wide {
|
||||
max-width: 42rem;
|
||||
}
|
||||
|
||||
.prefs {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
padding-top: 1.25rem;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.prefs h2 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.auth-head {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.auth-head h1 {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.auth-head p {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.auth-mark {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(135deg, rgba(122, 162, 247, 0.35), rgba(122, 162, 247, 0.08));
|
||||
color: var(--accent);
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.auth-tabs {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.25rem;
|
||||
padding: 0.25rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
background: var(--panel-2);
|
||||
}
|
||||
|
||||
.auth-tabs button {
|
||||
padding: 0.5rem;
|
||||
border: 0;
|
||||
border-radius: 7px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.auth-tabs button:hover {
|
||||
border: 0;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.auth-tabs button.active {
|
||||
color: var(--text);
|
||||
background: rgba(122, 162, 247, 0.16);
|
||||
box-shadow: inset 0 0 0 1px rgba(122, 162, 247, 0.35);
|
||||
}
|
||||
|
||||
.auth-card form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.85rem;
|
||||
}
|
||||
|
||||
.auth-card .field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.auth-card .field span {
|
||||
color: var(--muted);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.auth-card .field input {
|
||||
width: 100%;
|
||||
padding: 0.65rem 0.75rem;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.auth-card .field input:focus {
|
||||
border-color: var(--accent);
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(122, 162, 247, 0.16);
|
||||
}
|
||||
|
||||
.auth-card button[type="submit"] {
|
||||
margin-top: 0.25rem;
|
||||
padding: 0.65rem;
|
||||
border-radius: 8px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.auth-card .error {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.signed-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.auth-link {
|
||||
padding: 0.45rem 0.7rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.auth-link:hover {
|
||||
border-color: var(--accent);
|
||||
color: var(--text);
|
||||
}
|
||||
</style>
|
||||
445
frontend/app/pages/cards.vue
Normal file
445
frontend/app/pages/cards.vue
Normal file
@@ -0,0 +1,445 @@
|
||||
<script setup lang="ts">
|
||||
import CardGraphEditor from '../components/CardGraphEditor.vue'
|
||||
import PseudoGuide from '../components/PseudoGuide.vue'
|
||||
|
||||
type Status = 'supported' | 'partial' | 'unsupported'
|
||||
|
||||
interface CardSummary {
|
||||
oracle_id: string
|
||||
name: string
|
||||
mana_cost?: string
|
||||
type_line: string
|
||||
oracle_text?: string
|
||||
card_faces?: Array<{
|
||||
name: string
|
||||
mana_cost?: string
|
||||
type_line?: string
|
||||
oracle_text?: string
|
||||
}>
|
||||
implementation: { status: Status; manual: boolean } | null
|
||||
}
|
||||
|
||||
interface ImplementationResponse {
|
||||
card: CardSummary
|
||||
compiled: { status: Status }
|
||||
source: string
|
||||
manual: boolean
|
||||
updatedAt?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
interface Stats {
|
||||
supported: number
|
||||
partial: number
|
||||
unsupported: number
|
||||
manual: number
|
||||
}
|
||||
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
const pageSize = 50
|
||||
|
||||
const formatOptions = [
|
||||
{ value: 'commander', label: 'Commander' },
|
||||
{ value: 'brawl', label: 'Brawl' },
|
||||
{ value: 'standard', label: 'Standard' },
|
||||
{ value: 'pioneer', label: 'Pioneer' },
|
||||
{ value: 'modern', label: 'Modern' },
|
||||
{ value: 'legacy', label: 'Legacy' },
|
||||
{ value: 'vintage', label: 'Vintage' },
|
||||
{ value: 'pauper', label: 'Pauper' },
|
||||
{ value: 'historic', label: 'Historic' },
|
||||
{ value: 'timeless', label: 'Timeless' },
|
||||
{ value: 'explorer', label: 'Explorer' },
|
||||
{ value: 'alchemy', label: 'Alchemy' },
|
||||
{ value: 'oathbreaker', label: 'Oathbreaker' },
|
||||
{ value: 'duel', label: 'Duel Commander' },
|
||||
{ value: 'paupercommander', label: 'Pauper Commander' },
|
||||
{ value: 'standardbrawl', label: 'Standard Brawl' },
|
||||
{ value: 'gladiator', label: 'Gladiator' },
|
||||
{ value: 'competitivebrawl', label: 'Competitive Brawl' },
|
||||
{ value: 'premodern', label: 'Premodern' },
|
||||
{ value: 'predh', label: 'PreDH' },
|
||||
{ value: 'oldschool', label: 'Old School' },
|
||||
{ value: 'penny', label: 'Penny Dreadful' },
|
||||
]
|
||||
const colorOptions = [
|
||||
{ value: 'W', label: 'White' },
|
||||
{ value: 'U', label: 'Blue' },
|
||||
{ value: 'B', label: 'Black' },
|
||||
{ value: 'R', label: 'Red' },
|
||||
{ value: 'G', label: 'Green' },
|
||||
{ value: 'M', label: 'Multicolor' },
|
||||
{ value: 'C', label: 'Colorless' },
|
||||
]
|
||||
const typeOptions = [
|
||||
{ value: 'creature', label: 'Creature' },
|
||||
{ value: 'instant', label: 'Instant' },
|
||||
{ value: 'sorcery', label: 'Sorcery' },
|
||||
{ value: 'artifact', label: 'Artifact' },
|
||||
{ value: 'enchantment', label: 'Enchantment' },
|
||||
{ value: 'planeswalker', label: 'Planeswalker' },
|
||||
{ value: 'battle', label: 'Battle' },
|
||||
{ value: 'land', label: 'Land' },
|
||||
{ value: 'kindred', label: 'Kindred' },
|
||||
{ value: 'legendary', label: 'Legendary' },
|
||||
]
|
||||
const rarityOptions = ['common', 'uncommon', 'rare', 'mythic', 'special', 'bonus']
|
||||
const cmcOptions = ['0', '1', '2', '3', '4', '5', '6', '7+']
|
||||
|
||||
const view = ref<'editor' | 'guide'>('editor')
|
||||
const editorMode = ref<'text' | 'visual'>('text')
|
||||
const search = ref('')
|
||||
const statusFilter = ref('needs-work')
|
||||
const formatFilter = ref('')
|
||||
const colorFilter = ref('')
|
||||
const typeFilter = ref('')
|
||||
const rarityFilter = ref('')
|
||||
const cmcFilter = ref('')
|
||||
const cards = ref<CardSummary[]>([])
|
||||
const total = ref(0)
|
||||
const offset = ref(0)
|
||||
const loadingList = ref(false)
|
||||
const listError = ref('')
|
||||
|
||||
const stats = ref<Stats | null>(null)
|
||||
const selectedId = ref('')
|
||||
const detail = ref<ImplementationResponse | null>(null)
|
||||
const source = ref('')
|
||||
const detailLoading = ref(false)
|
||||
const saving = ref(false)
|
||||
const translating = ref(false)
|
||||
const editorError = ref('')
|
||||
|
||||
const page = computed(() => Math.floor(offset.value / pageSize) + 1)
|
||||
const pageCount = computed(() => Math.max(1, Math.ceil(total.value / pageSize)))
|
||||
const dirty = computed(() => Boolean(detail.value) && source.value !== detail.value!.source)
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
const data = (error as { data?: { error?: string } })?.data
|
||||
return data?.error ?? (error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
|
||||
function manaCostOf(card: CardSummary): string | undefined {
|
||||
const faces = card.card_faces?.map(face => face.mana_cost).filter(Boolean) ?? []
|
||||
return card.mana_cost ?? (faces.length ? faces.join(' // ') : undefined)
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
try {
|
||||
stats.value = await $fetch<Stats>(`${apiBase}/stats`)
|
||||
} catch {
|
||||
stats.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function loadCards(reset = false) {
|
||||
loadingList.value = true
|
||||
listError.value = ''
|
||||
if (reset) offset.value = 0
|
||||
try {
|
||||
const data = await $fetch<{ total: number; cards: CardSummary[] }>(`${apiBase}/cards`, {
|
||||
query: {
|
||||
q: search.value,
|
||||
status: statusFilter.value,
|
||||
format: formatFilter.value || undefined,
|
||||
color: colorFilter.value || undefined,
|
||||
type: typeFilter.value || undefined,
|
||||
rarity: rarityFilter.value || undefined,
|
||||
cmcMin: cmcFilter.value === '7+' ? '7' : cmcFilter.value || undefined,
|
||||
cmcMax: cmcFilter.value === '7+' ? undefined : cmcFilter.value || undefined,
|
||||
limit: pageSize,
|
||||
offset: offset.value,
|
||||
},
|
||||
})
|
||||
cards.value = data.cards
|
||||
total.value = data.total
|
||||
} catch (error) {
|
||||
listError.value = errorMessage(error)
|
||||
} finally {
|
||||
loadingList.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function selectCard(card: CardSummary) {
|
||||
selectedId.value = card.oracle_id
|
||||
detailLoading.value = true
|
||||
editorError.value = ''
|
||||
try {
|
||||
detail.value = await $fetch<ImplementationResponse>(
|
||||
`${apiBase}/cards/${card.oracle_id}/implementation`,
|
||||
)
|
||||
source.value = detail.value.source
|
||||
} catch (error) {
|
||||
detail.value = null
|
||||
editorError.value = errorMessage(error)
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!detail.value || saving.value) return
|
||||
saving.value = true
|
||||
editorError.value = ''
|
||||
try {
|
||||
const data = await $fetch<ImplementationResponse>(
|
||||
`${apiBase}/cards/${detail.value.card.oracle_id}/implementation`,
|
||||
{ method: 'PUT', body: { source: source.value } },
|
||||
)
|
||||
detail.value = data
|
||||
source.value = data.source
|
||||
updateSummary(data)
|
||||
await loadStats()
|
||||
} catch (error) {
|
||||
editorError.value = errorMessage(error)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function translate() {
|
||||
if (!detail.value || translating.value) return
|
||||
if (dirty.value && !window.confirm('Replace the current edits with an AI draft?')) return
|
||||
translating.value = true
|
||||
editorError.value = ''
|
||||
try {
|
||||
const data = await $fetch<{ source: string }>(
|
||||
`${apiBase}/cards/${detail.value.card.oracle_id}/translate`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
source.value = data.source
|
||||
} catch (error) {
|
||||
editorError.value = errorMessage(error)
|
||||
} finally {
|
||||
translating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function reset() {
|
||||
if (!detail.value || saving.value) return
|
||||
if (!window.confirm('Delete the manual implementation and restore the generated one?')) return
|
||||
saving.value = true
|
||||
editorError.value = ''
|
||||
try {
|
||||
const data = await $fetch<ImplementationResponse>(
|
||||
`${apiBase}/cards/${detail.value.card.oracle_id}/implementation`,
|
||||
{ method: 'DELETE' },
|
||||
)
|
||||
detail.value = data
|
||||
source.value = data.source
|
||||
updateSummary(data)
|
||||
await loadStats()
|
||||
} catch (error) {
|
||||
editorError.value = errorMessage(error)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function updateSummary(data: ImplementationResponse) {
|
||||
const card = cards.value.find(entry => entry.oracle_id === data.card.oracle_id)
|
||||
if (card) card.implementation = { status: data.compiled.status, manual: data.manual }
|
||||
}
|
||||
|
||||
function previousPage() {
|
||||
if (offset.value === 0) return
|
||||
offset.value = Math.max(0, offset.value - pageSize)
|
||||
loadCards()
|
||||
}
|
||||
|
||||
function nextPage() {
|
||||
if (offset.value + pageSize >= total.value) return
|
||||
offset.value += pageSize
|
||||
loadCards()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadStats()
|
||||
loadCards(true)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="fill-page">
|
||||
<header>
|
||||
<div>
|
||||
<h1>Card implementations</h1>
|
||||
<p class="muted">
|
||||
<template v-if="stats">
|
||||
{{ stats.supported.toLocaleString() }} supported ·
|
||||
{{ stats.partial.toLocaleString() }} partial ·
|
||||
{{ stats.unsupported.toLocaleString() }} unsupported ·
|
||||
{{ stats.manual.toLocaleString() }} manual
|
||||
</template>
|
||||
<template v-else>Loading stats…</template>
|
||||
</p>
|
||||
</div>
|
||||
<div class="head-actions">
|
||||
<div class="tabs">
|
||||
<button type="button" :class="{ active: view === 'editor' }" @click="view = 'editor'">Editor</button>
|
||||
<button type="button" :class="{ active: view === 'guide' }" @click="view = 'guide'">Guide</button>
|
||||
</div>
|
||||
<a :href="`${apiBase}/health`" target="_blank" rel="noreferrer">API health</a>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div v-if="view === 'editor'" class="layout">
|
||||
<section class="list-panel">
|
||||
<form class="search" @submit.prevent="loadCards(true)">
|
||||
<input v-model="search" type="search" placeholder="Search card names…">
|
||||
<select v-model="statusFilter" aria-label="Implementation status" @change="loadCards(true)">
|
||||
<option value="needs-work">Needs work</option>
|
||||
<option value="unsupported">Not implemented</option>
|
||||
<option value="partial">Partial</option>
|
||||
<option value="supported">Supported</option>
|
||||
<option value="manual">Manual</option>
|
||||
<option value="all">All cards</option>
|
||||
</select>
|
||||
<button type="submit">Search</button>
|
||||
</form>
|
||||
|
||||
<div class="filters">
|
||||
<select v-model="formatFilter" aria-label="Format legality" @change="loadCards(true)">
|
||||
<option value="">Any format</option>
|
||||
<option v-for="format in formatOptions" :key="format.value" :value="format.value">
|
||||
{{ format.label }}
|
||||
</option>
|
||||
</select>
|
||||
<select v-model="colorFilter" aria-label="Color identity" @change="loadCards(true)">
|
||||
<option value="">Any color</option>
|
||||
<option v-for="color in colorOptions" :key="color.value" :value="color.value">
|
||||
{{ color.label }}
|
||||
</option>
|
||||
</select>
|
||||
<select v-model="typeFilter" aria-label="Card type" @change="loadCards(true)">
|
||||
<option value="">Any type</option>
|
||||
<option v-for="type in typeOptions" :key="type.value" :value="type.value">
|
||||
{{ type.label }}
|
||||
</option>
|
||||
</select>
|
||||
<select v-model="rarityFilter" aria-label="Rarity" @change="loadCards(true)">
|
||||
<option value="">Any rarity</option>
|
||||
<option v-for="rarity in rarityOptions" :key="rarity" :value="rarity">
|
||||
{{ rarity }}
|
||||
</option>
|
||||
</select>
|
||||
<select v-model="cmcFilter" aria-label="Mana value" @change="loadCards(true)">
|
||||
<option value="">Any mana value</option>
|
||||
<option v-for="cmc in cmcOptions" :key="cmc" :value="cmc">
|
||||
{{ cmc === '7+' ? '7 or more' : cmc }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<p v-if="listError" class="error">{{ listError }}</p>
|
||||
<p v-else-if="loadingList" class="muted">Loading…</p>
|
||||
<p v-else-if="!cards.length" class="muted">No cards match.</p>
|
||||
|
||||
<ul class="card-list">
|
||||
<li v-for="card in cards" :key="card.oracle_id">
|
||||
<CardHover :oracle-id="card.oracle_id" :name="card.name">
|
||||
<button
|
||||
type="button"
|
||||
class="card-row"
|
||||
:class="{ selected: card.oracle_id === selectedId }"
|
||||
@click="selectCard(card)"
|
||||
>
|
||||
<span class="card-main">
|
||||
<span class="card-name">{{ card.name }}</span>
|
||||
<ManaCost :cost="manaCostOf(card)" />
|
||||
</span>
|
||||
<span class="badges">
|
||||
<span
|
||||
v-if="card.implementation"
|
||||
class="badge"
|
||||
:class="card.implementation.status"
|
||||
>{{ card.implementation.status }}</span>
|
||||
<span v-if="card.implementation?.manual" class="badge manual">manual</span>
|
||||
</span>
|
||||
</button>
|
||||
</CardHover>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="pager">
|
||||
<button type="button" :disabled="offset === 0 || loadingList" @click="previousPage">Previous</button>
|
||||
<span class="muted">Page {{ page }} of {{ pageCount }} · {{ total.toLocaleString() }} cards</span>
|
||||
<button type="button" :disabled="offset + pageSize >= total || loadingList" @click="nextPage">Next</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="detail-panel">
|
||||
<p v-if="!selectedId" class="muted">Select a card to view or edit its implementation.</p>
|
||||
<p v-else-if="detailLoading" class="muted">Loading card…</p>
|
||||
<template v-else-if="detail">
|
||||
<div class="detail-head">
|
||||
<div>
|
||||
<h2>{{ detail.card.name }}</h2>
|
||||
<p class="muted">
|
||||
{{ detail.card.type_line }}
|
||||
<ManaCost :cost="manaCostOf(detail.card)" />
|
||||
</p>
|
||||
</div>
|
||||
<div class="badges">
|
||||
<span class="badge" :class="detail.compiled.status">{{ detail.compiled.status }}</span>
|
||||
<span v-if="detail.manual" class="badge manual">manual</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="detail.card.card_faces?.length">
|
||||
<div v-for="face in detail.card.card_faces" :key="face.name" class="oracle">
|
||||
<h3>{{ face.name }}</h3>
|
||||
<p class="muted">{{ face.type_line }}</p>
|
||||
<p><SymbolText :text="face.oracle_text" /></p>
|
||||
</div>
|
||||
</template>
|
||||
<div v-else class="oracle">
|
||||
<p><SymbolText :text="detail.card.oracle_text" /></p>
|
||||
</div>
|
||||
|
||||
<p v-if="detail.error" class="error">
|
||||
The saved implementation does not parse: {{ detail.error }}
|
||||
</p>
|
||||
<p v-else-if="editorError" class="error">{{ editorError }}</p>
|
||||
|
||||
<div class="row">
|
||||
<div class="tabs">
|
||||
<button type="button" :class="{ active: editorMode === 'text' }" @click="editorMode = 'text'">Text</button>
|
||||
<button type="button" :class="{ active: editorMode === 'visual' }" @click="editorMode = 'visual'">Visual</button>
|
||||
</div>
|
||||
<span class="muted grow">{{ editorMode === 'text' ? 'Pseudocode' : 'Node graph' }}</span>
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
v-if="editorMode === 'text'"
|
||||
v-model="source"
|
||||
spellcheck="false"
|
||||
aria-label="Card implementation"
|
||||
@keydown.ctrl.s.prevent="save"
|
||||
@keydown.meta.s.prevent="save"
|
||||
/>
|
||||
<CardGraphEditor v-else :key="detail.card.oracle_id" v-model="source" />
|
||||
|
||||
<div class="actions">
|
||||
<button type="button" class="primary" :disabled="saving || !dirty" @click="save">
|
||||
{{ saving ? 'Saving…' : 'Save' }}
|
||||
</button>
|
||||
<span class="muted">{{ dirty ? 'Unsaved changes' : 'Saved' }}</span>
|
||||
<button type="button" :disabled="saving || translating" @click="translate">
|
||||
{{ translating ? 'Drafting…' : 'Draft with AI' }}
|
||||
</button>
|
||||
<button type="button" :disabled="saving || !detail.manual" @click="reset">
|
||||
Reset to generated
|
||||
</button>
|
||||
<span v-if="detail.updatedAt" class="muted saved-at">
|
||||
Updated {{ new Date(detail.updatedAt).toLocaleString() }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<PseudoGuide v-else />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
1002
frontend/app/pages/decks.vue
Normal file
1002
frontend/app/pages/decks.vue
Normal file
File diff suppressed because it is too large
Load Diff
2236
frontend/app/pages/games/[id].vue
Normal file
2236
frontend/app/pages/games/[id].vue
Normal file
File diff suppressed because it is too large
Load Diff
258
frontend/app/pages/index.vue
Normal file
258
frontend/app/pages/index.vue
Normal file
@@ -0,0 +1,258 @@
|
||||
<script setup lang="ts">
|
||||
import { deckValidation, loadDecks, type SavedDeck } from '~/utils/decks'
|
||||
import { loadPlaymatChoice, type PlaymatChoice } from '~/utils/playmat'
|
||||
|
||||
interface MatchSummary {
|
||||
id: string
|
||||
hostName: string
|
||||
status: 'lobby' | 'active' | 'finished'
|
||||
playerCount: number
|
||||
maxPlayers: number
|
||||
players: string[]
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
definePageMeta({ middleware: 'auth' })
|
||||
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
const SESSION_PREFIX = 'commander-session-'
|
||||
|
||||
const playerName = ref('')
|
||||
const maxPlayers = ref(4)
|
||||
const decks = ref<SavedDeck[]>([])
|
||||
const selectedDeckId = ref('')
|
||||
const games = ref<MatchSummary[]>([])
|
||||
const loading = ref(false)
|
||||
const starting = ref(false)
|
||||
const error = ref('')
|
||||
let poll: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
const selectedDeck = computed(() => decks.value.find(deck => deck.id === selectedDeckId.value))
|
||||
const deckErrors = computed(() => selectedDeck.value ? deckValidation(selectedDeck.value) : ['Choose a deck.'])
|
||||
const canStart = computed(() => Boolean(playerName.value.trim() && selectedDeck.value && !deckErrors.value.length))
|
||||
|
||||
const playmat = ref<PlaymatChoice>()
|
||||
|
||||
function deckPayload(deck: SavedDeck) {
|
||||
return {
|
||||
commander: deck.commander.oracleId,
|
||||
cards: deck.cards.map(card => card.oracleId),
|
||||
}
|
||||
}
|
||||
|
||||
async function loadGames() {
|
||||
try {
|
||||
const data = await $fetch<{ games: MatchSummary[] }>(`${apiBase}/games`)
|
||||
games.value = data.games
|
||||
} catch (caught) {
|
||||
error.value = errorMessage(caught)
|
||||
}
|
||||
}
|
||||
|
||||
async function createGame() {
|
||||
if (!canStart.value || !selectedDeck.value) return
|
||||
starting.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await $fetch<{ matchId: string; playerId: string; token: string }>(`${apiBase}/games`, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: playerName.value,
|
||||
maxPlayers: maxPlayers.value,
|
||||
deck: deckPayload(selectedDeck.value),
|
||||
playmat: playmat.value,
|
||||
},
|
||||
})
|
||||
enterGame(data.matchId, data)
|
||||
} catch (caught) {
|
||||
error.value = errorMessage(caught)
|
||||
} finally {
|
||||
starting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function joinGame(game: MatchSummary) {
|
||||
if (!canStart.value || !selectedDeck.value) {
|
||||
error.value = 'Choose a valid deck and enter your name first.'
|
||||
return
|
||||
}
|
||||
starting.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await $fetch<{ matchId: string; playerId: string; token: string }>(
|
||||
`${apiBase}/games/${game.id}/join`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: { name: playerName.value, deck: deckPayload(selectedDeck.value), playmat: playmat.value },
|
||||
},
|
||||
)
|
||||
enterGame(data.matchId, data)
|
||||
} catch (caught) {
|
||||
error.value = errorMessage(caught)
|
||||
} finally {
|
||||
starting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function enterGame(matchId: string, data: { playerId: string; token: string }) {
|
||||
sessionStorage.setItem(`${SESSION_PREFIX}${matchId}`, JSON.stringify(data))
|
||||
void navigateTo(`/games/${matchId}`)
|
||||
}
|
||||
|
||||
function errorMessage(caught: unknown): string {
|
||||
const data = (caught as { data?: { error?: string } })?.data
|
||||
return data?.error ?? (caught instanceof Error ? caught.message : String(caught))
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
playerName.value = localStorage.getItem('commander-player-name') ?? ''
|
||||
playmat.value = await loadPlaymatChoice(apiBase)
|
||||
decks.value = (await loadDecks(apiBase)).sort((a, b) => b.updatedAt - a.updatedAt)
|
||||
selectedDeckId.value = decks.value.find(deck => !deckValidation(deck).length)?.id
|
||||
?? decks.value[0]?.id
|
||||
?? ''
|
||||
void loadGames()
|
||||
poll = setInterval(loadGames, 5000)
|
||||
})
|
||||
|
||||
watch(playerName, value => {
|
||||
if (typeof localStorage !== 'undefined') localStorage.setItem('commander-player-name', value)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (poll) clearInterval(poll)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="page">
|
||||
<header>
|
||||
<h1>Play Commander</h1>
|
||||
<p class="muted">
|
||||
Four-player free-for-all with 40 life, command zones, commander tax, and
|
||||
21 commander damage. Games live in the API process and disappear on restart.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
|
||||
<div class="home-grid">
|
||||
<section class="panel">
|
||||
<h2>Start or join</h2>
|
||||
<label class="field">
|
||||
<span class="muted">Your name</span>
|
||||
<input v-model="playerName" maxlength="30" placeholder="Player">
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="muted">Deck</span>
|
||||
<select v-model="selectedDeckId">
|
||||
<option v-for="deck in decks" :key="deck.id" :value="deck.id">
|
||||
{{ deck.name }} ({{ deck.cards.length + 1 }})
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-if="!decks.length" class="warn">
|
||||
No decks yet. <NuxtLink to="/decks">Create or import one</NuxtLink>.
|
||||
</p>
|
||||
<ul v-else-if="deckErrors.length" class="errors">
|
||||
<li v-for="message in deckErrors.slice(0, 3)" :key="message" class="warn">{{ message }}</li>
|
||||
</ul>
|
||||
<label v-else class="field">
|
||||
<span class="muted">Seats</span>
|
||||
<select v-model.number="maxPlayers">
|
||||
<option :value="2">2 players</option>
|
||||
<option :value="3">3 players</option>
|
||||
<option :value="4">4 players</option>
|
||||
</select>
|
||||
</label>
|
||||
<button type="button" class="primary" :disabled="!canStart || starting" @click="createGame">
|
||||
{{ starting ? 'Starting…' : 'Create game' }}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="row">
|
||||
<h2 class="grow">Open games</h2>
|
||||
<button type="button" class="mini" @click="loadGames">Refresh</button>
|
||||
</div>
|
||||
<p v-if="!games.length" class="muted">No games yet. Create one and send the link to your friends.</p>
|
||||
<ul class="games">
|
||||
<li v-for="game in games" :key="game.id" class="game-row">
|
||||
<div class="grow">
|
||||
<div class="row wrap">
|
||||
<strong>{{ game.hostName }}'s game</strong>
|
||||
<span class="tag">{{ game.status }}</span>
|
||||
<span class="tag">{{ game.playerCount }}/{{ game.maxPlayers }}</span>
|
||||
</div>
|
||||
<p class="muted">{{ game.players.join(', ') || 'Waiting for players' }}</p>
|
||||
</div>
|
||||
<button
|
||||
v-if="game.status === 'lobby' && game.playerCount < game.maxPlayers"
|
||||
type="button"
|
||||
:disabled="!canStart || starting"
|
||||
@click="joinGame(game)"
|
||||
>Join</button>
|
||||
<span v-else class="muted">{{ game.status === 'active' ? 'In progress' : 'Full' }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.home-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(18rem, 24rem) 1fr;
|
||||
gap: 1rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.field select,
|
||||
.field input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.errors {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.games {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.game-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 0.6rem 0;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.game-row:first-child {
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.mini {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.2rem 0.45rem;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.home-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
29
frontend/app/utils/auth.ts
Normal file
29
frontend/app/utils/auth.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
const TOKEN_KEY = 'commander-auth-token'
|
||||
export const AUTH_CHANGED = 'commander-auth-change'
|
||||
|
||||
// Stored in a cookie (not localStorage) so the server can redirect before rendering.
|
||||
export function authToken(): string | undefined {
|
||||
if (typeof document === 'undefined') return undefined
|
||||
const value = document.cookie
|
||||
.split('; ')
|
||||
.find(cookie => cookie.startsWith(`${TOKEN_KEY}=`))
|
||||
?.slice(TOKEN_KEY.length + 1)
|
||||
return value ? decodeURIComponent(value) : undefined
|
||||
}
|
||||
|
||||
export function setAuthToken(token: string | undefined): void {
|
||||
if (typeof document === 'undefined') return
|
||||
document.cookie = token
|
||||
? `${TOKEN_KEY}=${encodeURIComponent(token)}; path=/; max-age=31536000; SameSite=Lax`
|
||||
: `${TOKEN_KEY}=; path=/; max-age=0; SameSite=Lax`
|
||||
window.dispatchEvent(new Event(AUTH_CHANGED))
|
||||
}
|
||||
|
||||
export function hasAuth(): boolean {
|
||||
return Boolean(authToken())
|
||||
}
|
||||
|
||||
export function authHeaders(): Record<string, string> {
|
||||
const token = authToken()
|
||||
return token ? { Authorization: `Bearer ${token}` } : {}
|
||||
}
|
||||
10
frontend/app/utils/cardBack.ts
Normal file
10
frontend/app/utils/cardBack.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
/** Plain backs offered in the menu; the first is the default when nothing is stored. */
|
||||
export const CARD_BACK_COLORS = ['#26304a', '#1f3a2e', '#4a1f24', '#33244f', '#4a3520', '#14161c']
|
||||
|
||||
/** CSS variables for a stored back: `data:` values are images, anything else a plain colour. */
|
||||
export function cardBackVars(back: string | null | undefined): Record<string, string> | undefined {
|
||||
if (!back) return undefined
|
||||
return back.startsWith('data:')
|
||||
? { '--card-back-image': `url("${back}")` }
|
||||
: { '--card-back-color': back }
|
||||
}
|
||||
846
frontend/app/utils/cardGraph.ts
Normal file
846
frontend/app/utils/cardGraph.ts
Normal file
@@ -0,0 +1,846 @@
|
||||
// Line-level model behind the visual card editor. It mirrors the canonical
|
||||
// formatter output (abilities at column 0, nested calls indented two spaces) so
|
||||
// editing a node and serializing it back keeps the pseudocode valid.
|
||||
|
||||
export interface GraphNode {
|
||||
id: number
|
||||
text: string
|
||||
kind: 'ability' | 'effect' | 'raw'
|
||||
children: GraphNode[]
|
||||
}
|
||||
|
||||
let nextId = 1
|
||||
|
||||
export function nextNodeId(): number {
|
||||
return nextId++
|
||||
}
|
||||
|
||||
export function makeNode(text: string, kind: GraphNode['kind'], children: GraphNode[] = []): GraphNode {
|
||||
return { id: nextNodeId(), text, kind, children }
|
||||
}
|
||||
|
||||
export function parseGraph(source: string): GraphNode[] {
|
||||
const roots: GraphNode[] = []
|
||||
const stack: Array<{ indent: number; node: GraphNode }> = []
|
||||
|
||||
for (const raw of source.split('\n')) {
|
||||
if (!raw.trim()) continue
|
||||
const indent = (raw.match(/^[ \t]*/)?.[0] ?? '').replace(/\t/g, ' ').length
|
||||
const text = raw.trim()
|
||||
const kind: GraphNode['kind'] =
|
||||
text.startsWith('#') || text === '(no abilities)' ? 'raw' : indent === 0 ? 'ability' : 'effect'
|
||||
const node = makeNode(text, kind)
|
||||
|
||||
while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop()
|
||||
if (stack.length) stack[stack.length - 1].node.children.push(node)
|
||||
else roots.push(node)
|
||||
stack.push({ indent, node })
|
||||
}
|
||||
|
||||
return roots
|
||||
}
|
||||
|
||||
export function serializeGraph(list: GraphNode[], depth = 0): string {
|
||||
return list
|
||||
.map(node => {
|
||||
const line = ' '.repeat(depth) + node.text
|
||||
return node.children.length ? `${line}\n${serializeGraph(node.children, depth + 1)}` : line
|
||||
})
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
/** Inserted at the top level by the visual editor's "Add ability" menu. */
|
||||
export const ABILITY_PALETTE = [
|
||||
{
|
||||
group: 'Triggered',
|
||||
items: [
|
||||
{ label: 'Enters the battlefield', value: 'on enters(this):' },
|
||||
{ label: 'Dies', value: 'on dies(this):' },
|
||||
{ label: 'Attacks', value: 'on attacks(this):' },
|
||||
{ label: 'Upkeep', value: 'on upkeep(you):' },
|
||||
{ label: 'Cast a spell', value: 'on cast(you, any spell):' },
|
||||
{ label: 'Deals damage', value: 'on deals_damage(this, any):' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Other',
|
||||
items: [
|
||||
{ label: 'Activated {T}', value: 'activate {T}:' },
|
||||
{ label: 'Activated {2}, {T}', value: 'activate {2}, {T}:' },
|
||||
{ label: 'Static', value: 'static:' },
|
||||
{ label: 'Static if a condition', value: 'static if it is your turn:' },
|
||||
{ label: 'Spell effect', value: 'spell:' },
|
||||
{ label: 'Keyword: Flying', value: 'keyword Flying' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
/** Appended below an ability or nested block. Keep every value parseable. */
|
||||
export const EFFECT_PALETTE = [
|
||||
{
|
||||
group: 'Removal',
|
||||
items: [
|
||||
{ label: 'Damage', value: 'damage(target creature, 3)' },
|
||||
{ label: 'Destroy', value: 'destroy(target creature)' },
|
||||
{ label: 'Exile', value: 'exile(target permanent)' },
|
||||
{ label: 'Tap', value: 'tap(target creature)' },
|
||||
{ label: 'Counter spell', value: 'counter(spell, target spell)' },
|
||||
{ label: 'Sacrifice', value: 'sacrifice(you, target creature)' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Cards and life',
|
||||
items: [
|
||||
{ label: 'Draw', value: 'draw(you, 1)' },
|
||||
{ label: 'Discard', value: 'discard(you, 1)' },
|
||||
{ label: 'Mill', value: 'mill(you, 1)' },
|
||||
{ label: 'Scry', value: 'scry(you, 2)' },
|
||||
{ label: 'Surveil', value: 'surveil(you, 1)' },
|
||||
{ label: 'Search library', value: 'search(you, creature, 1, to hand, shuffle)' },
|
||||
{ label: 'Look at top', value: 'look_top(you, 3)' },
|
||||
{ label: 'Gain life', value: 'gain_life(you, 2)' },
|
||||
{ label: 'Lose life', value: 'lose_life(opponent, 2)' },
|
||||
{ label: 'Energy', value: 'energy(you, 2)' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Board',
|
||||
items: [
|
||||
{ label: 'Create token', value: 'create_token(you, 1, 1/1 white soldier creature)' },
|
||||
{ label: 'Create copy token', value: 'create_token(you, 1, copy of the triggering object, not legendary)' },
|
||||
{ label: 'Put counters', value: 'put_counters(target creature, +1/+1, 1)' },
|
||||
{ label: 'Pump', value: 'pump(target creature, 2/2, until end of turn)' },
|
||||
{ label: 'Grant keyword', value: 'grant(each creature you control, Flying)' },
|
||||
{ label: 'Untap', value: 'untap(target permanent you control)' },
|
||||
{ label: 'Return to hand', value: 'return_to_hand(target creature)' },
|
||||
{ label: 'Add mana', value: 'add_mana(you, {G})' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Flow',
|
||||
items: [
|
||||
{ label: 'If condition', value: 'if you control at least 3 artifacts:' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
/** Static abilities accept a different effect vocabulary than triggered/spell ones. */
|
||||
export const STATIC_EFFECT_PALETTE = [
|
||||
{
|
||||
group: 'Static effects',
|
||||
items: [
|
||||
{ label: 'Pump', value: 'pump(each creature you control, 1/1)' },
|
||||
{ label: 'Grant keyword', value: 'grant(each creature you control, Flying)' },
|
||||
{ label: 'Enters tapped', value: 'enters_tapped(this)' },
|
||||
{ label: 'Enters with counters', value: 'enters_with_counters(this, +1/+1, 1)' },
|
||||
{ label: 'Restrict', value: 'restrict(target creature, cant_attack)' },
|
||||
{ label: 'Set base P/T', value: 'set_pt(target creature, base, 1/1)' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
/** Value nodes that can be wired into argument sockets. */
|
||||
export const VALUE_PALETTE = [
|
||||
{
|
||||
group: 'Players',
|
||||
items: [
|
||||
{ label: 'A player', value: 'target player' },
|
||||
{ label: 'Each opponent', value: 'each opponent' },
|
||||
{ label: 'Each player', value: 'each player' },
|
||||
{ label: 'You', value: 'you' },
|
||||
{ label: 'That player', value: 'that player' },
|
||||
{ label: 'Its controller', value: 'its controller' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Targets',
|
||||
items: [
|
||||
{ label: 'A creature', value: 'target creature' },
|
||||
{ label: 'A permanent', value: 'target permanent' },
|
||||
{ label: 'An artifact', value: 'target artifact' },
|
||||
{ label: 'A land', value: 'target land' },
|
||||
{ label: 'A spell', value: 'target spell' },
|
||||
{ label: 'An ability', value: 'target ability' },
|
||||
{ label: 'Any target', value: 'any target' },
|
||||
{ label: 'This', value: 'this' },
|
||||
{ label: 'The triggering object', value: 'the triggering object' },
|
||||
{ label: 'Each creature you control', value: 'each creature you control' },
|
||||
{ label: 'Each creature an opponent controls', value: 'each creature an opponent controls' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Selectors',
|
||||
items: [
|
||||
{ label: 'Creature', value: 'creature' },
|
||||
{ label: 'Artifact', value: 'artifact' },
|
||||
{ label: 'Enchantment', value: 'enchantment' },
|
||||
{ label: 'Land', value: 'land' },
|
||||
{ label: 'Red', value: 'red' },
|
||||
{ label: 'Creature you control', value: 'creature you control' },
|
||||
{ label: 'Artifact you control', value: 'artifact you control' },
|
||||
{ label: 'Tapped creature', value: 'tapped creature' },
|
||||
{ label: 'Power 4 or greater', value: 'creature with power 4 or greater' },
|
||||
{ label: 'Nontoken Dragon', value: 'each other nontoken dragon creature you control' },
|
||||
{ label: 'Nontoken Angel', value: "each nontoken angel you don't control" },
|
||||
{ label: 'Selector builder', value: '__selector__' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Tokens',
|
||||
items: [
|
||||
{ label: '1/1 white Soldier', value: '1/1 white soldier creature' },
|
||||
{ label: '1/1 red Goblin', value: '1/1 red goblin creature' },
|
||||
{ label: 'Copy of the triggering object', value: 'copy of the triggering object' },
|
||||
{ label: 'Copy, not legendary', value: 'copy of the triggering object, not legendary' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Values',
|
||||
items: [
|
||||
{ label: '1', value: '1' },
|
||||
{ label: '2', value: '2' },
|
||||
{ label: '3', value: '3' },
|
||||
{ label: 'X', value: 'X' },
|
||||
{ label: 'That much', value: 'that much' },
|
||||
{ label: 'Its power', value: 'its power' },
|
||||
{ label: 'Its toughness', value: 'its toughness' },
|
||||
{ label: 'Count creatures you control', value: 'count(creature you control)' },
|
||||
{ label: 'Cards in your hand', value: 'cards in your hand' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Costs',
|
||||
items: [
|
||||
{ label: 'Tap', value: '{T}' },
|
||||
{ label: 'Mana {2}', value: '{2}' },
|
||||
{ label: 'Pay 2 life', value: 'pay 2 life' },
|
||||
{ label: 'Sacrifice this', value: 'sacrifice this' },
|
||||
{ label: 'Discard 1 card(s)', value: 'discard 1 card(s)' },
|
||||
{ label: 'Mill 1 card(s)', value: 'mill 1 card(s)' },
|
||||
{ label: 'Remove 1 +1/+1 counter(s)', value: 'remove 1 +1/+1 counter(s) from this' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Conditions',
|
||||
items: [
|
||||
{ label: 'It is your turn', value: 'it is your turn' },
|
||||
{ label: 'This is tapped', value: 'this is tapped' },
|
||||
{ label: 'You control at least 3 artifacts', value: 'you control at least 3 artifacts' },
|
||||
{ label: 'You have at least 10 life', value: 'you have at least 10 life' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Durations',
|
||||
items: [
|
||||
{ label: 'Until end of turn', value: 'until end of turn' },
|
||||
{ label: 'Until your next turn', value: 'until your next turn' },
|
||||
{ label: 'Until the end of your next turn', value: 'until the end of your next turn' },
|
||||
{ label: 'While this remains', value: 'for as long as this remains on the battlefield' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Logic',
|
||||
items: [
|
||||
{ label: 'Selector OR', value: '__or__' },
|
||||
{ label: 'Selector AND', value: '__and__' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
/** Human labels for effect/ability argument sockets. */
|
||||
export const ARG_HINTS: Record<string, string[]> = {
|
||||
damage: ['target', 'amount', 'source'],
|
||||
damage_divided: ['amount', 'target'],
|
||||
draw: ['player', 'amount'],
|
||||
discard: ['player', 'amount'],
|
||||
mill: ['player', 'amount'],
|
||||
gain_life: ['player', 'amount'],
|
||||
lose_life: ['player', 'amount'],
|
||||
pump: ['target', 'power/toughness', 'duration'],
|
||||
set_pt: ['target', 'power/toughness', 'duration'],
|
||||
grant: ['target', 'keyword', 'duration'],
|
||||
put_counters: ['target', 'counter', 'amount'],
|
||||
remove_counters: ['target', 'counter', 'amount'],
|
||||
create_token: ['player', 'amount', 'token', 'options'],
|
||||
destroy: ['target'],
|
||||
exile: ['target'],
|
||||
tap: ['target'],
|
||||
untap: ['target'],
|
||||
regenerate: ['target'],
|
||||
return_to_hand: ['target'],
|
||||
put_on_top: ['target'],
|
||||
sacrifice: ['player', 'target'],
|
||||
counter: ['spell|ability', 'target'],
|
||||
return_to_battlefield: ['target', 'options'],
|
||||
scry: ['player', 'amount'],
|
||||
surveil: ['player', 'amount'],
|
||||
search: ['player', 'selector', 'amount', 'destination', 'options'],
|
||||
add_mana: ['player', 'mana'],
|
||||
fight: ['target', 'target'],
|
||||
energy: ['player', 'amount'],
|
||||
attach: ['target'],
|
||||
restrict: ['target', 'rule'],
|
||||
prevent_damage: ['target', 'amount', 'duration'],
|
||||
gain_control: ['target', 'duration'],
|
||||
look_top: ['player', 'amount', 'options'],
|
||||
pay: ['cost'],
|
||||
transform: ['target'],
|
||||
}
|
||||
|
||||
/** Human labels for trigger event arguments. */
|
||||
const TRIGGER_ARG_HINTS: Record<string, string[]> = {
|
||||
enters: ['subject'],
|
||||
dies: ['subject'],
|
||||
attacks: ['subject'],
|
||||
blocks: ['subject'],
|
||||
attacks_or_blocks: ['subject'],
|
||||
enters_or_attacks: ['subject'],
|
||||
enters_or_dies: ['subject'],
|
||||
leaves_battlefield: ['subject'],
|
||||
deals_damage: ['subject', 'recipient'],
|
||||
deals_combat_damage: ['subject', 'recipient'],
|
||||
upkeep: ['player'],
|
||||
end_step: ['player'],
|
||||
begin_combat: ['player'],
|
||||
first_main_phase: ['player'],
|
||||
postcombat_main_phase: ['player'],
|
||||
cast: ['player', 'spell'],
|
||||
becomes_level: ['level'],
|
||||
draw: ['player'],
|
||||
counter_placed: ['subject', 'counter'],
|
||||
becomes_target: ['subject'],
|
||||
gain_life: ['player'],
|
||||
lose_life: ['player'],
|
||||
}
|
||||
|
||||
const TRIGGER_SUBJECT_OPTIONS = [
|
||||
'this',
|
||||
'each other creature',
|
||||
'each creature you control',
|
||||
'each other nontoken dragon creature you control',
|
||||
"each nontoken angel you don't control",
|
||||
]
|
||||
|
||||
const PLAYER_OPTIONS = ['you', 'target player', 'each opponent', 'each player', 'that player', 'its controller']
|
||||
const AMOUNT_OPTIONS = ['1', '2', '3', '4', '5', 'X', 'that much', 'count(creature you control)']
|
||||
const TOKEN_OPTIONS = [
|
||||
'1/1 white soldier creature',
|
||||
'1/1 red goblin creature',
|
||||
'copy of the triggering object',
|
||||
]
|
||||
|
||||
/** Argument slots with fixed choices become dropdowns in the visual editor. */
|
||||
export const SLOT_OPTIONS: Record<string, string[][]> = {
|
||||
enters: [TRIGGER_SUBJECT_OPTIONS],
|
||||
create_token: [PLAYER_OPTIONS, AMOUNT_OPTIONS, TOKEN_OPTIONS, ['not legendary']],
|
||||
}
|
||||
|
||||
/** Splits on `separator` outside parentheses, brackets, braces and quotes. */
|
||||
export function splitTopLevel(text: string, separator: string): string[] {
|
||||
const parts: string[] = []
|
||||
let depth = 0
|
||||
let quote = false
|
||||
let escape = false
|
||||
let start = 0
|
||||
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
const char = text[index]
|
||||
if (quote) {
|
||||
if (escape) escape = false
|
||||
else if (char === '\\') escape = true
|
||||
else if (char === '"') quote = false
|
||||
continue
|
||||
}
|
||||
if (char === '"') {
|
||||
quote = true
|
||||
continue
|
||||
}
|
||||
if (char === '(' || char === '[' || char === '{') depth++
|
||||
else if (char === ')' || char === ']' || char === '}') depth--
|
||||
else if (depth === 0 && text.startsWith(separator, index)) {
|
||||
parts.push(text.slice(start, index))
|
||||
index += separator.length - 1
|
||||
start = index + 1
|
||||
}
|
||||
}
|
||||
parts.push(text.slice(start))
|
||||
return parts
|
||||
}
|
||||
|
||||
export function blockOf(text: string): { kind: 'if' | 'choose' | 'schedule'; value: string } | undefined {
|
||||
const ifMatch = text.match(/^if (.+):$/)
|
||||
if (ifMatch) return { kind: 'if', value: ifMatch[1] }
|
||||
const chooseMatch = text.match(/^choose (\d+(?:-\d+)?):$/)
|
||||
if (chooseMatch) return { kind: 'choose', value: chooseMatch[1] }
|
||||
const scheduleMatch = text.match(/^schedule\((next_upkeep|next_end_step)\):$/)
|
||||
if (scheduleMatch) return { kind: 'schedule', value: scheduleMatch[1] }
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** True for nodes that carry an indented body. Mode lines can nest too. */
|
||||
export function isBlockText(text: string): boolean {
|
||||
return Boolean(blockOf(text)) || /^grant_ability\(.*\):$/.test(text) || /^\d+\.\s/.test(text)
|
||||
}
|
||||
|
||||
/** Blocks that are invalid without at least one nested effect. */
|
||||
function requiresBody(text: string): boolean {
|
||||
return Boolean(blockOf(text)) || /^grant_ability\(.*\):$/.test(text)
|
||||
}
|
||||
|
||||
export function abilityRequiresEffects(text: string): boolean {
|
||||
return /^(?:on |activate |static|spell|chapter )/.test(text)
|
||||
}
|
||||
|
||||
/** Reads a `name(arg, arg)` prefix, leaving any suffix after the closing paren. */
|
||||
export function readCallPrefix(text: string): { name: string; args: string[]; end: number } | undefined {
|
||||
const match = text.match(/^([a-z][a-z0-9_]*)\s*\(/)
|
||||
if (!match) return undefined
|
||||
|
||||
const open = match[0].length - 1
|
||||
let depth = 0
|
||||
let quote = false
|
||||
let escape = false
|
||||
|
||||
for (let index = open; index < text.length; index++) {
|
||||
const char = text[index]
|
||||
if (quote) {
|
||||
if (escape) escape = false
|
||||
else if (char === '\\') escape = true
|
||||
else if (char === '"') quote = false
|
||||
continue
|
||||
}
|
||||
if (char === '"') {
|
||||
quote = true
|
||||
continue
|
||||
}
|
||||
if (char === '(') depth++
|
||||
else if (char === ')') {
|
||||
depth--
|
||||
if (depth === 0) {
|
||||
const inner = text.slice(open + 1, index).trim()
|
||||
return {
|
||||
name: match[1],
|
||||
args: inner ? splitTopLevel(inner, ',').map(arg => arg.trim()) : [],
|
||||
end: index + 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Reads a complete `name(arg, arg)` call; returns undefined for block headers. */
|
||||
export function parseCall(text: string): { name: string; args: string[] } | undefined {
|
||||
const trimmed = text.trim()
|
||||
const call = readCallPrefix(trimmed)
|
||||
return call && call.end === trimmed.length ? { name: call.name, args: call.args } : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a supported line into fixed text plus argument slots. Unsupported
|
||||
* lines return undefined and stay as free text.
|
||||
*/
|
||||
export function shapeFromText(text: string): NodeShape | undefined {
|
||||
if (text.startsWith('on ') && text.endsWith(':')) {
|
||||
const inner = text.slice(3, -1)
|
||||
const call = readCallPrefix(inner)
|
||||
if (call) {
|
||||
const suffix = inner.slice(call.end)
|
||||
return {
|
||||
name: `on ${call.name}`,
|
||||
head: `on ${call.name}(`,
|
||||
tail: `)${suffix}:`,
|
||||
separator: ', ',
|
||||
slots: call.args.map((arg, index) => {
|
||||
const options = SLOT_OPTIONS[call.name]?.[index]
|
||||
return {
|
||||
label: TRIGGER_ARG_HINTS[call.name]?.[index] ?? `arg${index + 1}`,
|
||||
text: arg,
|
||||
...(options ? { options } : {}),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (text.startsWith('activate ') && text.endsWith(':')) {
|
||||
return {
|
||||
head: 'activate ',
|
||||
tail: ':',
|
||||
separator: ', ',
|
||||
slots: [{ label: 'cost', text: text.slice('activate '.length, -1) }],
|
||||
}
|
||||
}
|
||||
|
||||
if (text.startsWith('static if ') && text.endsWith(':')) {
|
||||
return {
|
||||
head: 'static if ',
|
||||
tail: ':',
|
||||
separator: ', ',
|
||||
slots: [{ label: 'condition', text: text.slice('static if '.length, -1) }],
|
||||
}
|
||||
}
|
||||
|
||||
const block = blockOf(text)
|
||||
if (block) {
|
||||
if (block.kind === 'if') {
|
||||
return { head: 'if ', tail: ':', separator: ', ', slots: [{ label: 'condition', text: block.value }] }
|
||||
}
|
||||
if (block.kind === 'choose') {
|
||||
return { head: 'choose ', tail: ':', separator: ', ', slots: [{ label: 'modes', text: block.value }] }
|
||||
}
|
||||
return { head: 'schedule(', tail: '):', separator: ', ', slots: [{ label: 'when', text: block.value }] }
|
||||
}
|
||||
|
||||
const call = parseCall(text)
|
||||
if (call) {
|
||||
return {
|
||||
head: `${call.name}(`,
|
||||
tail: ')',
|
||||
separator: ', ',
|
||||
slots: call.args.map((arg, index) => {
|
||||
const options = SLOT_OPTIONS[call.name]?.[index]
|
||||
return {
|
||||
label: ARG_HINTS[call.name]?.[index] ?? `arg${index + 1}`,
|
||||
text: arg,
|
||||
...(options ? { options } : {}),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuilds every shaped line from its slots and connected value nodes. Value
|
||||
* nodes are evaluated recursively, so `or`/`and` combinators can nest.
|
||||
*/
|
||||
export function syncTexts(model: GraphModel): void {
|
||||
const byId = new Map(model.nodes.map(node => [node.id, node]))
|
||||
const valueEdges = new Map<string, number>()
|
||||
for (const edge of model.edges) {
|
||||
if (edge.port === 'value' && edge.slot !== undefined) {
|
||||
valueEdges.set(`${edge.to}:${edge.slot}`, edge.from)
|
||||
}
|
||||
}
|
||||
|
||||
function renderSlot(node: CanvasNode, index: number, stack: Set<number>): string {
|
||||
const childId = valueEdges.get(`${node.id}:${index}`)
|
||||
const child = childId !== undefined ? byId.get(childId) : undefined
|
||||
return child ? render(child, stack) : node.shape?.slots[index]?.text ?? ''
|
||||
}
|
||||
|
||||
function render(node: CanvasNode | undefined, stack: Set<number>): string {
|
||||
if (!node) return ''
|
||||
if (stack.has(node.id)) return node.kind === 'value' ? node.literal ?? '' : ''
|
||||
stack.add(node.id)
|
||||
|
||||
let text: string
|
||||
if (node.kind === 'value' && node.combine) {
|
||||
text = `${renderSlot(node, 0, stack)} ${node.combine} ${renderSlot(node, 1, stack)}`
|
||||
} else if (node.shape) {
|
||||
text = node.shape.head
|
||||
+ node.shape.slots.map((_, index) => renderSlot(node, index, stack)).join(node.shape.separator)
|
||||
+ node.shape.tail
|
||||
} else if (node.kind === 'value') {
|
||||
text = node.literal ?? node.text
|
||||
} else {
|
||||
text = node.text
|
||||
}
|
||||
|
||||
stack.delete(node.id)
|
||||
node.text = text
|
||||
return text
|
||||
}
|
||||
|
||||
for (const node of model.nodes) render(node, new Set())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Node canvas. The tree above is converted into flat nodes with explicit
|
||||
// `next` (sibling) and `body` (indented) links. Source is regenerated by
|
||||
// following those links, so the canvas and the pseudocode stay in sync.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface NodeSlot {
|
||||
label: string
|
||||
text: string
|
||||
/** Fixed choices rendered as a dropdown instead of a free-text input. */
|
||||
options?: string[]
|
||||
}
|
||||
|
||||
/** A line split into a fixed shell and the slots a value node can fill. */
|
||||
export interface NodeShape {
|
||||
name?: string
|
||||
head: string
|
||||
tail: string
|
||||
separator: string
|
||||
slots: NodeSlot[]
|
||||
}
|
||||
|
||||
export interface CanvasNode {
|
||||
id: number
|
||||
text: string
|
||||
kind: 'ability' | 'effect' | 'raw' | 'value'
|
||||
x: number
|
||||
y: number
|
||||
shape?: NodeShape
|
||||
/** Value nodes: literal source text. */
|
||||
literal?: string
|
||||
/** Value nodes: combines its two slots instead of using a literal. */
|
||||
combine?: 'or' | 'and'
|
||||
valueLabel?: string
|
||||
}
|
||||
|
||||
export type GraphPort = 'next' | 'body' | 'value'
|
||||
|
||||
export interface GraphEdge {
|
||||
id: number
|
||||
from: number
|
||||
port: GraphPort
|
||||
to: number
|
||||
/** Target argument index when port is 'value'. */
|
||||
slot?: number
|
||||
}
|
||||
|
||||
export interface GraphModel {
|
||||
nodes: CanvasNode[]
|
||||
edges: GraphEdge[]
|
||||
}
|
||||
|
||||
export interface GraphSource {
|
||||
source: string
|
||||
unlinked: number
|
||||
problems: string[]
|
||||
}
|
||||
|
||||
export const NODE_WIDTH = 230
|
||||
const CHAIN_GAP = 70
|
||||
const BODY_INDENT = NODE_WIDTH + 20
|
||||
const BODY_GAP = 70
|
||||
const ROOT_GAP = 70
|
||||
|
||||
let nextEdgeId = 1
|
||||
|
||||
export function estimateNodeHeight(text: string, slots?: number, hasName?: boolean): number {
|
||||
const count = slots ?? parseCall(text)?.args.length ?? 0
|
||||
if (!count) return hasName ? 84 : 74
|
||||
return 64 + count * 48 + (hasName ? 24 : 0)
|
||||
}
|
||||
|
||||
export function hasBodyPort(model: GraphModel, node: CanvasNode): boolean {
|
||||
return node.kind === 'effect'
|
||||
&& (isBlockText(node.text) || model.edges.some(edge => edge.from === node.id && edge.port === 'body'))
|
||||
}
|
||||
|
||||
/** Converts pseudocode into nodes and links, laid out roughly left to right. */
|
||||
export function graphFromSource(source: string): GraphModel {
|
||||
const model: GraphModel = { nodes: [], edges: [] }
|
||||
let y = 40
|
||||
|
||||
for (const root of parseGraph(source)) {
|
||||
if (root.kind === 'raw') {
|
||||
model.nodes.push({ id: root.id, text: root.text, kind: 'raw', x: 40, y })
|
||||
y += 64
|
||||
continue
|
||||
}
|
||||
const bounds = layoutTreeChain(model, [root], 40, y, 0)
|
||||
y += bounds.height + ROOT_GAP
|
||||
}
|
||||
|
||||
return model
|
||||
}
|
||||
|
||||
function layoutTreeChain(
|
||||
model: GraphModel,
|
||||
list: GraphNode[],
|
||||
x: number,
|
||||
y: number,
|
||||
depth: number,
|
||||
): { width: number; height: number } {
|
||||
let cursorX = x
|
||||
let maxHeight = 0
|
||||
let previous: number | undefined
|
||||
|
||||
for (const treeNode of list) {
|
||||
const kind: CanvasNode['kind'] = depth === 0 ? treeNode.kind : 'effect'
|
||||
const node: CanvasNode = {
|
||||
id: treeNode.id,
|
||||
text: treeNode.text,
|
||||
kind,
|
||||
x: cursorX,
|
||||
y,
|
||||
shape: shapeFromText(treeNode.text),
|
||||
}
|
||||
model.nodes.push(node)
|
||||
|
||||
if (previous !== undefined) {
|
||||
model.edges.push({ id: nextEdgeId++, from: previous, port: 'next', to: node.id })
|
||||
}
|
||||
previous = node.id
|
||||
|
||||
const height = estimateNodeHeight(node.text, node.shape?.slots.length, Boolean(node.shape?.name))
|
||||
let totalHeight = height
|
||||
let advance = NODE_WIDTH
|
||||
|
||||
if (treeNode.children.length) {
|
||||
if (depth === 0) {
|
||||
// An ability's output is its effect chain, laid out to the right.
|
||||
const chain = layoutTreeChain(model, treeNode.children, cursorX + NODE_WIDTH + CHAIN_GAP, y, 1)
|
||||
model.edges.push({ id: nextEdgeId++, from: node.id, port: 'next', to: treeNode.children[0].id })
|
||||
totalHeight = Math.max(totalHeight, chain.height)
|
||||
advance = NODE_WIDTH + CHAIN_GAP + chain.width
|
||||
} else {
|
||||
// Blocks own an indented body below and just right of their socket.
|
||||
const body = layoutTreeChain(model, treeNode.children, cursorX + BODY_INDENT, y + height + BODY_GAP, depth + 1)
|
||||
model.edges.push({ id: nextEdgeId++, from: node.id, port: 'body', to: treeNode.children[0].id })
|
||||
totalHeight = Math.max(totalHeight, height + BODY_GAP + body.height)
|
||||
}
|
||||
}
|
||||
|
||||
maxHeight = Math.max(maxHeight, totalHeight)
|
||||
cursorX += advance + CHAIN_GAP
|
||||
}
|
||||
|
||||
return { width: cursorX - x, height: maxHeight }
|
||||
}
|
||||
|
||||
/** Rebuilds pseudocode by walking next/body links from every ability root. */
|
||||
export function sourceFromGraph(model: GraphModel): GraphSource {
|
||||
syncTexts(model)
|
||||
const byId = new Map(model.nodes.map(node => [node.id, node]))
|
||||
const outgoing = new Map<string, GraphEdge>()
|
||||
for (const edge of model.edges) {
|
||||
outgoing.set(`${edge.from}:${edge.port}`, edge)
|
||||
}
|
||||
|
||||
const lines: string[] = []
|
||||
const visited = new Set<number>()
|
||||
const problems: string[] = []
|
||||
|
||||
const label = (text: string) => (text.length > 52 ? `${text.slice(0, 49)}…` : text)
|
||||
|
||||
const checkModes = (startId: number) => {
|
||||
let mode = byId.get(startId)
|
||||
let expected = 1
|
||||
const seenModes = new Set<number>()
|
||||
while (mode && !seenModes.has(mode.id)) {
|
||||
seenModes.add(mode.id)
|
||||
const number = mode.text.match(/^(\d+)\.\s/)
|
||||
if (!number || Number(number[1]) !== expected) {
|
||||
problems.push('A choose body must be numbered 1, 2, 3…')
|
||||
return
|
||||
}
|
||||
expected++
|
||||
const next = outgoing.get(`${mode.id}:next`)
|
||||
mode = next ? byId.get(next.to) : undefined
|
||||
}
|
||||
}
|
||||
|
||||
const emitChain = (startId: number, depth: number) => {
|
||||
let current: number | undefined = startId
|
||||
while (current !== undefined) {
|
||||
if (visited.has(current)) {
|
||||
problems.push(`Cycle at ${label(byId.get(current)?.text ?? 'node')}`)
|
||||
return
|
||||
}
|
||||
const node = byId.get(current)
|
||||
if (!node) return
|
||||
visited.add(current)
|
||||
lines.push(`${' '.repeat(depth)}${node.text}`)
|
||||
|
||||
const body = outgoing.get(`${current}:body`)
|
||||
if (body) {
|
||||
if (blockOf(node.text)?.kind === 'choose') checkModes(body.to)
|
||||
emitChain(body.to, depth + 1)
|
||||
} else if (requiresBody(node.text)) {
|
||||
problems.push(`"${label(node.text)}" has no body`)
|
||||
}
|
||||
|
||||
current = outgoing.get(`${current}:next`)?.to
|
||||
}
|
||||
}
|
||||
|
||||
for (const node of model.nodes) {
|
||||
if (node.kind === 'raw') {
|
||||
if (!visited.has(node.id)) {
|
||||
visited.add(node.id)
|
||||
lines.push(node.text)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (node.kind !== 'ability' || visited.has(node.id)) continue
|
||||
|
||||
visited.add(node.id)
|
||||
lines.push(node.text)
|
||||
const next = outgoing.get(`${node.id}:next`)
|
||||
if (next) emitChain(next.to, 1)
|
||||
else if (abilityRequiresEffects(node.text)) problems.push(`"${label(node.text)}" has no effects`)
|
||||
}
|
||||
|
||||
const usedValues = new Set(model.edges.filter(edge => edge.port === 'value').map(edge => edge.from))
|
||||
const unlinked = model.nodes.filter(node =>
|
||||
(node.kind === 'effect' && !visited.has(node.id))
|
||||
|| (node.kind === 'value' && !usedValues.has(node.id)),
|
||||
).length
|
||||
if (unlinked) {
|
||||
problems.push(`${unlinked} unconnected node${unlinked === 1 ? '' : 's'} will be ignored`)
|
||||
}
|
||||
|
||||
return { source: lines.join('\n'), unlinked, problems }
|
||||
}
|
||||
|
||||
function reaches(model: GraphModel, start: number, target: number): boolean {
|
||||
const stack = [start]
|
||||
const seen = new Set<number>()
|
||||
while (stack.length) {
|
||||
const id = stack.pop()!
|
||||
if (id === target) return true
|
||||
if (seen.has(id)) continue
|
||||
seen.add(id)
|
||||
for (const edge of model.edges) {
|
||||
if (edge.from === id) stack.push(edge.to)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Links an output socket to a node input or an argument slot. */
|
||||
export function connectNodes(
|
||||
model: GraphModel,
|
||||
from: number,
|
||||
port: GraphPort,
|
||||
to: number,
|
||||
slot?: number,
|
||||
): boolean {
|
||||
if (from === to) return false
|
||||
const source = model.nodes.find(node => node.id === from)
|
||||
const target = model.nodes.find(node => node.id === to)
|
||||
if (!source || !target) return false
|
||||
|
||||
if (port === 'value') {
|
||||
if (source.kind !== 'value' || !target.shape || slot === undefined || !target.shape.slots[slot]) {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
if (target.kind !== 'effect') return false
|
||||
if (port === 'body' && !hasBodyPort(model, source)) return false
|
||||
}
|
||||
if (reaches(model, to, from)) return false
|
||||
|
||||
if (port === 'value') {
|
||||
model.edges = model.edges.filter(edge =>
|
||||
!(edge.port === 'value' && edge.to === to && edge.slot === slot)
|
||||
&& !(edge.from === from && edge.port === 'value'),
|
||||
)
|
||||
model.edges.push({ id: nextEdgeId++, from, port, to, slot })
|
||||
} else {
|
||||
model.edges = model.edges.filter(edge =>
|
||||
!((edge.port === 'next' || edge.port === 'body') && edge.to === to)
|
||||
&& !(edge.from === from && edge.port === port),
|
||||
)
|
||||
model.edges.push({ id: nextEdgeId++, from, port, to })
|
||||
}
|
||||
return true
|
||||
}
|
||||
132
frontend/app/utils/decks.ts
Normal file
132
frontend/app/utils/decks.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { authHeaders } from './auth'
|
||||
|
||||
export interface CardImplementation {
|
||||
status: 'supported' | 'partial' | 'unsupported'
|
||||
manual: boolean
|
||||
}
|
||||
|
||||
export interface DeckCard {
|
||||
oracleId: string
|
||||
name: string
|
||||
manaCost?: string
|
||||
typeLine: string
|
||||
colorIdentity: string[]
|
||||
oracleText?: string
|
||||
imageUri?: string
|
||||
implementation?: CardImplementation | null
|
||||
}
|
||||
|
||||
export interface SavedDeck {
|
||||
id: string
|
||||
name: string
|
||||
commander: DeckCard
|
||||
cards: DeckCard[]
|
||||
cardBack?: string | null
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export interface ApiCard {
|
||||
oracle_id: string
|
||||
name: string
|
||||
mana_cost?: string
|
||||
type_line: string
|
||||
color_identity?: string[]
|
||||
oracle_text?: string
|
||||
image_uri?: string
|
||||
implementation?: CardImplementation | null
|
||||
}
|
||||
|
||||
export function deckCardFromApi(card: ApiCard): DeckCard {
|
||||
return {
|
||||
oracleId: card.oracle_id,
|
||||
name: card.name,
|
||||
manaCost: card.mana_cost,
|
||||
typeLine: card.type_line,
|
||||
colorIdentity: card.color_identity ?? [],
|
||||
oracleText: card.oracle_text,
|
||||
imageUri: card.image_uri,
|
||||
implementation: card.implementation,
|
||||
}
|
||||
}
|
||||
|
||||
export function newDeckId(): string {
|
||||
return typeof crypto !== 'undefined' && 'randomUUID' in crypto
|
||||
? crypto.randomUUID()
|
||||
: `deck-${Date.now()}-${Math.random().toString(16).slice(2)}`
|
||||
}
|
||||
|
||||
export async function loadDecks(apiBase: string): Promise<SavedDeck[]> {
|
||||
const { Authorization } = authHeaders()
|
||||
if (!Authorization) return []
|
||||
try {
|
||||
const data = await $fetch<{ decks: SavedDeck[] }>(`${apiBase}/me/decks`, {
|
||||
headers: { Authorization },
|
||||
})
|
||||
return Array.isArray(data.decks) ? data.decks : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveDeck(apiBase: string, deck: SavedDeck): Promise<void> {
|
||||
await $fetch(`${apiBase}/me/decks/${encodeURIComponent(deck.id)}`, {
|
||||
method: 'PUT',
|
||||
headers: authHeaders(),
|
||||
body: { name: deck.name, commander: deck.commander, cards: deck.cards, cardBack: deck.cardBack ?? null },
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteDeck(apiBase: string, id: string): Promise<void> {
|
||||
await $fetch(`${apiBase}/me/decks/${encodeURIComponent(id)}`, {
|
||||
method: 'DELETE',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
}
|
||||
|
||||
export function isBasicLand(card: DeckCard): boolean {
|
||||
return /\bbasic\b/i.test(card.typeLine) && /\bland\b/i.test(card.typeLine)
|
||||
}
|
||||
|
||||
export function canBeCommander(card: DeckCard): boolean {
|
||||
return (/\blegendary\b/i.test(card.typeLine) && /\bcreature\b/i.test(card.typeLine))
|
||||
|| /can be your commander/i.test(card.oracleText ?? '')
|
||||
}
|
||||
|
||||
export function deckValidation(deck: SavedDeck): string[] {
|
||||
const errors: string[] = []
|
||||
if (!canBeCommander(deck.commander)) errors.push('The commander must be a legendary creature.')
|
||||
if (deck.cards.length + 1 !== 100) {
|
||||
errors.push(`The deck has ${deck.cards.length + 1} cards; it needs exactly 100.`)
|
||||
}
|
||||
|
||||
const identity = new Set(deck.commander.colorIdentity)
|
||||
const counts = new Map<string, number>()
|
||||
for (const card of deck.cards) {
|
||||
counts.set(card.oracleId, (counts.get(card.oracleId) ?? 0) + 1)
|
||||
if (card.oracleId === deck.commander.oracleId) {
|
||||
errors.push('The commander cannot also be in the deck.')
|
||||
}
|
||||
if (card.colorIdentity.some(color => !identity.has(color))) {
|
||||
errors.push(`${card.name} is outside the commander's color identity.`)
|
||||
}
|
||||
}
|
||||
for (const [oracleId, count] of counts) {
|
||||
if (count < 2) continue
|
||||
const card = deck.cards.find(entry => entry.oracleId === oracleId)
|
||||
if (card && !isBasicLand(card)) {
|
||||
errors.push(`${card.name} appears ${count} times; only basic lands may repeat.`)
|
||||
}
|
||||
}
|
||||
return [...new Set(errors)]
|
||||
}
|
||||
|
||||
export function exportDeckText(deck: SavedDeck): string {
|
||||
const counts = new Map<string, { card: DeckCard; count: number }>()
|
||||
for (const card of deck.cards) {
|
||||
const entry = counts.get(card.oracleId)
|
||||
if (entry) entry.count++
|
||||
else counts.set(card.oracleId, { card, count: 1 })
|
||||
}
|
||||
const deckLines = [...counts.values()].map(entry => `${entry.count} ${entry.card.name}`)
|
||||
return [`Commander`, `1 ${deck.commander.name}`, '', 'Deck', ...deckLines].join('\n')
|
||||
}
|
||||
21
frontend/app/utils/image.ts
Normal file
21
frontend/app/utils/image.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/** Downscale an image file to a JPEG data URL with its long side at most `max` pixels. */
|
||||
export async function resizeImage(file: File, max: number, quality = 0.82): Promise<string> {
|
||||
const url = URL.createObjectURL(file)
|
||||
try {
|
||||
const image = new Image()
|
||||
image.src = url
|
||||
await image.decode()
|
||||
const scale = Math.min(1, max / Math.max(image.naturalWidth, image.naturalHeight))
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = Math.max(1, Math.round(image.naturalWidth * scale))
|
||||
canvas.height = Math.max(1, Math.round(image.naturalHeight * scale))
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) throw new Error('Canvas unavailable')
|
||||
context.fillStyle = '#11151d'
|
||||
context.fillRect(0, 0, canvas.width, canvas.height)
|
||||
context.drawImage(image, 0, 0, canvas.width, canvas.height)
|
||||
return canvas.toDataURL('image/jpeg', quality)
|
||||
} finally {
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
}
|
||||
42
frontend/app/utils/playmat.ts
Normal file
42
frontend/app/utils/playmat.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { authHeaders } from './auth'
|
||||
|
||||
export type PlaymatChoice =
|
||||
| { kind: 'card'; oracleId: string }
|
||||
| { kind: 'upload'; data: string }
|
||||
|
||||
export type PlaymatSelection = PlaymatChoice | { kind: 'none' }
|
||||
|
||||
export async function loadPlaymatChoice(apiBase: string): Promise<PlaymatChoice | undefined> {
|
||||
const { Authorization } = authHeaders()
|
||||
if (!Authorization) return undefined
|
||||
try {
|
||||
const data = await $fetch<{ playmat: PlaymatChoice | null }>(`${apiBase}/me/preferences`, {
|
||||
headers: { Authorization },
|
||||
})
|
||||
const saved = data.playmat
|
||||
if (saved?.kind === 'card' && typeof saved.oracleId === 'string') {
|
||||
return { kind: 'card', oracleId: saved.oracleId }
|
||||
}
|
||||
if (saved?.kind === 'upload' && typeof saved.data === 'string') {
|
||||
return { kind: 'upload', data: saved.data }
|
||||
}
|
||||
} catch {
|
||||
// An unavailable account should not block the page.
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** False when the account cannot store the image; the caller should say so. */
|
||||
export async function savePlaymatChoice(apiBase: string, choice: PlaymatChoice | undefined): Promise<boolean> {
|
||||
if (!authHeaders().Authorization) return false
|
||||
try {
|
||||
await $fetch(`${apiBase}/me/preferences`, {
|
||||
method: 'PUT',
|
||||
headers: authHeaders(),
|
||||
body: { playmat: choice ?? null },
|
||||
})
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
11
frontend/nuxt.config.ts
Normal file
11
frontend/nuxt.config.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
// https://nuxt.com/docs/api/configuration/nuxt-config
|
||||
export default defineNuxtConfig({
|
||||
compatibilityDate: '2025-07-15',
|
||||
devtools: { enabled: true },
|
||||
css: ['mana-font/css/mana.css', '~/assets/main.css'],
|
||||
runtimeConfig: {
|
||||
public: {
|
||||
apiBase: 'http://localhost:4000',
|
||||
},
|
||||
},
|
||||
})
|
||||
8684
frontend/package-lock.json
generated
Normal file
8684
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
19
frontend/package.json
Normal file
19
frontend/package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "nuxt build",
|
||||
"dev": "nuxt dev",
|
||||
"test": "node --test test/*.test.ts",
|
||||
"generate": "nuxt generate",
|
||||
"preview": "nuxt preview",
|
||||
"postinstall": "nuxt prepare"
|
||||
},
|
||||
"dependencies": {
|
||||
"mana-font": "^1.18.0",
|
||||
"nuxt": "^4.6.2",
|
||||
"vue": "^3.5.44",
|
||||
"vue-router": "^5.4.0"
|
||||
}
|
||||
}
|
||||
BIN
frontend/public/favicon.ico
Normal file
BIN
frontend/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
2
frontend/public/robots.txt
Normal file
2
frontend/public/robots.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
User-Agent: *
|
||||
Disallow:
|
||||
215
frontend/test/cardGraph.test.ts
Normal file
215
frontend/test/cardGraph.test.ts
Normal file
@@ -0,0 +1,215 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
connectNodes,
|
||||
graphFromSource,
|
||||
nextNodeId,
|
||||
parseCall,
|
||||
parseGraph,
|
||||
serializeGraph,
|
||||
shapeFromText,
|
||||
sourceFromGraph,
|
||||
syncTexts,
|
||||
} from '../app/utils/cardGraph.ts'
|
||||
import type { GraphModel } from '../app/utils/cardGraph.ts'
|
||||
|
||||
const SOURCE = `# Soul Warden [supported]
|
||||
on enters(each other creature):
|
||||
gain_life(you, 1)
|
||||
|
||||
on upkeep(you):
|
||||
if you control at least 3 artifacts:
|
||||
draw(you, 1)
|
||||
create_token(you, 1, 1/1 white soldier creature)`
|
||||
|
||||
test('parseGraph builds ability and nested effect nodes', () => {
|
||||
const roots = parseGraph(SOURCE)
|
||||
|
||||
assert.equal(roots.length, 3)
|
||||
assert.equal(roots[0].kind, 'raw')
|
||||
assert.equal(roots[1].kind, 'ability')
|
||||
assert.equal(roots[1].text, 'on enters(each other creature):')
|
||||
assert.deepEqual(roots[1].children.map(node => node.text), ['gain_life(you, 1)'])
|
||||
|
||||
const upkeep = roots[2]
|
||||
assert.equal(upkeep.children[0].text, 'if you control at least 3 artifacts:')
|
||||
assert.deepEqual(upkeep.children[0].children.map(node => node.text), ['draw(you, 1)'])
|
||||
assert.equal(upkeep.children[1].text, 'create_token(you, 1, 1/1 white soldier creature)')
|
||||
})
|
||||
|
||||
test('serializeGraph round-trips formatter output and normalizes indentation', () => {
|
||||
assert.equal(serializeGraph(parseGraph(SOURCE)), SOURCE.replace('\n\n', '\n'))
|
||||
assert.equal(
|
||||
serializeGraph(parseGraph('on dies(this):\n draw(you, 1)')),
|
||||
'on dies(this):\n draw(you, 1)',
|
||||
)
|
||||
})
|
||||
|
||||
test('graph conversion round-trips abilities, chains and nested bodies', () => {
|
||||
const model = graphFromSource(SOURCE)
|
||||
const result = sourceFromGraph(model)
|
||||
|
||||
assert.equal(result.source, SOURCE.replace('\n\n', '\n'))
|
||||
assert.equal(result.unlinked, 0)
|
||||
assert.deepEqual(result.problems, [])
|
||||
})
|
||||
|
||||
test('connectNodes replaces an input link and rejects cycles', () => {
|
||||
const model = graphFromSource(SOURCE)
|
||||
const ability = model.nodes.find(node => node.kind === 'ability' && node.text.startsWith('on enters'))
|
||||
const first = model.nodes.find(node => node.text === 'gain_life(you, 1)')
|
||||
const second = model.nodes.find(node => node.text === 'create_token(you, 1, 1/1 white soldier creature)')
|
||||
assert.ok(ability && first && second)
|
||||
|
||||
assert.equal(connectNodes(model, ability.id, 'next', second.id), true)
|
||||
assert.equal(sourceFromGraph(model).unlinked, 1)
|
||||
|
||||
assert.equal(connectNodes(model, first.id, 'next', second.id), true)
|
||||
assert.equal(connectNodes(model, second.id, 'next', first.id), false)
|
||||
})
|
||||
|
||||
test('shapeFromText exposes trigger and effect arguments', () => {
|
||||
const trigger = shapeFromText('on attacks(this):')
|
||||
assert.equal(trigger?.name, 'on attacks')
|
||||
assert.deepEqual(trigger?.slots, [{ label: 'subject', text: 'this' }])
|
||||
|
||||
const damage = shapeFromText('damage(target creature, 3)')
|
||||
assert.deepEqual(damage?.slots.map(slot => slot.label), ['target', 'amount'])
|
||||
})
|
||||
|
||||
test('shapeFromText adds dropdown choices for constant slots', () => {
|
||||
const enters = shapeFromText('on enters(each other nontoken dragon creature you control):')
|
||||
assert.deepEqual(enters?.slots[0]?.options, [
|
||||
'this',
|
||||
'each other creature',
|
||||
'each creature you control',
|
||||
'each other nontoken dragon creature you control',
|
||||
"each nontoken angel you don't control",
|
||||
])
|
||||
|
||||
const copy = shapeFromText("create_token(you, 1, copy of the triggering object, not legendary)")
|
||||
assert.deepEqual(copy?.slots.map(slot => slot.label), ['player', 'amount', 'token', 'options'])
|
||||
assert.ok(copy?.slots[2]?.options?.includes('copy of the triggering object'))
|
||||
assert.deepEqual(copy?.slots[3]?.options, ['not legendary'])
|
||||
})
|
||||
|
||||
test('value nodes fill trigger and effect argument sockets', () => {
|
||||
const model = graphFromSource(`# Test [supported]
|
||||
on attacks(this):
|
||||
damage(target creature, 3)`)
|
||||
const trigger = model.nodes.find(node => node.kind === 'ability')
|
||||
const damage = model.nodes.find(node => node.text.startsWith('damage('))
|
||||
assert.ok(trigger && damage)
|
||||
|
||||
const player = {
|
||||
id: nextNodeId(),
|
||||
kind: 'value' as const,
|
||||
text: 'target player',
|
||||
literal: 'target player',
|
||||
valueLabel: 'Players',
|
||||
x: 0,
|
||||
y: 0,
|
||||
}
|
||||
model.nodes.push(player)
|
||||
assert.equal(connectNodes(model, player.id, 'value', trigger.id, 0), true)
|
||||
|
||||
const artifact = {
|
||||
id: nextNodeId(),
|
||||
kind: 'value' as const,
|
||||
text: 'target artifact',
|
||||
literal: 'target artifact',
|
||||
valueLabel: 'Targets',
|
||||
x: 0,
|
||||
y: 0,
|
||||
}
|
||||
model.nodes.push(artifact)
|
||||
assert.equal(connectNodes(model, artifact.id, 'value', damage.id, 0), true)
|
||||
|
||||
assert.equal(sourceFromGraph(model).source, `# Test [supported]
|
||||
on attacks(target player):
|
||||
damage(target artifact, 3)`)
|
||||
})
|
||||
|
||||
test('or and and value nodes combine selector slots', () => {
|
||||
const model = graphFromSource(`# Test [supported]
|
||||
spell:
|
||||
search(you, creature, 1, to hand, shuffle)`)
|
||||
const search = model.nodes.find(node => node.text.startsWith('search('))
|
||||
assert.ok(search)
|
||||
|
||||
const combo: GraphModel['nodes'][number] = {
|
||||
id: nextNodeId(),
|
||||
kind: 'value',
|
||||
text: '',
|
||||
combine: 'or',
|
||||
valueLabel: 'Logic',
|
||||
x: 0,
|
||||
y: 0,
|
||||
shape: {
|
||||
head: '',
|
||||
tail: '',
|
||||
separator: ' or ',
|
||||
slots: [
|
||||
{ label: 'left', text: 'creature' },
|
||||
{ label: 'right', text: 'artifact' },
|
||||
],
|
||||
},
|
||||
}
|
||||
model.nodes.push(combo)
|
||||
assert.equal(connectNodes(model, combo.id, 'value', search.id, 1), true)
|
||||
|
||||
assert.match(sourceFromGraph(model).source, /search\(you, creature or artifact, 1, to hand, shuffle\)/)
|
||||
|
||||
syncTexts(model)
|
||||
assert.equal(combo.text, 'creature or artifact')
|
||||
|
||||
combo.combine = 'and'
|
||||
combo.shape!.slots[0].text = 'red'
|
||||
combo.shape!.slots[1].text = 'creature'
|
||||
syncTexts(model)
|
||||
assert.equal(combo.text, 'red and creature')
|
||||
})
|
||||
|
||||
test('structured selector value nodes render their slots', () => {
|
||||
const model = graphFromSource(`# Test [supported]
|
||||
on enters(this):`)
|
||||
const trigger = model.nodes.find(node => node.kind === 'ability')
|
||||
assert.ok(trigger)
|
||||
|
||||
const selector: GraphModel['nodes'][number] = {
|
||||
id: nextNodeId(),
|
||||
kind: 'value',
|
||||
text: '',
|
||||
valueLabel: 'Selector',
|
||||
x: 0,
|
||||
y: 0,
|
||||
shape: {
|
||||
head: '',
|
||||
tail: '',
|
||||
separator: ' ',
|
||||
slots: [
|
||||
{ label: 'prefix', text: 'each' },
|
||||
{ label: 'state', text: 'nontoken' },
|
||||
{ label: 'type', text: 'angel' },
|
||||
{ label: 'controller', text: "you don't control" },
|
||||
],
|
||||
},
|
||||
}
|
||||
model.nodes.push(selector)
|
||||
assert.equal(connectNodes(model, selector.id, 'value', trigger.id, 0), true)
|
||||
|
||||
syncTexts(model)
|
||||
assert.equal(selector.text, "each nontoken angel you don't control")
|
||||
assert.equal(sourceFromGraph(model).source, `# Test [supported]
|
||||
on enters(each nontoken angel you don't control):`)
|
||||
})
|
||||
|
||||
test('parseCall splits arguments outside nested groups', () => {
|
||||
assert.deepEqual(parseCall('draw(you, 1)'), { name: 'draw', args: ['you', '1'] })
|
||||
assert.deepEqual(parseCall('proliferate()'), { name: 'proliferate', args: [] })
|
||||
assert.deepEqual(parseCall('damage(divided(any number, creature), 3)'), {
|
||||
name: 'damage',
|
||||
args: ['divided(any number, creature)', '3'],
|
||||
})
|
||||
assert.equal(parseCall('if you control at least 3 artifacts:'), undefined)
|
||||
})
|
||||
18
frontend/tsconfig.json
Normal file
18
frontend/tsconfig.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
// https://nuxt.com/docs/guide/concepts/typescript
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./.nuxt/tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./.nuxt/tsconfig.server.json"
|
||||
},
|
||||
{
|
||||
"path": "./.nuxt/tsconfig.shared.json"
|
||||
},
|
||||
{
|
||||
"path": "./.nuxt/tsconfig.node.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user