Parse and stringify FEN (Forsyth-Edwards Notation) chess positions. Strict TypeScript, no-throw API.
npm install @echecs/fen
import { parse } from '@echecs/fen';
const position = parse(
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1',
);
// => { board, turn, castlingRights, enPassantSquare, halfmoveClock, fullmoveNumber }
parse('invalid');
// => null
parse never throws. It returns null when the input is not a valid FEN
string. The result can be passed directly to the Position constructor from
@echecs/position:
import { Position } from '@echecs/position';
const position = new Position(parse(fen));
Errors indicate invalid FEN syntax — the string cannot be parsed. Warnings indicate a successfully parsed position that is suspicious (e.g. missing king).
const position = parse(fen, {
onError(error) {
// FEN is malformed — parse returns null.
console.error(`[${error.offset}] ${error.message}`);
},
onWarning(warning) {
// FEN is valid but the position is suspicious.
console.warn(warning.message);
},
});
Errors are reported for:
Warnings are reported for:
import { stringify } from '@echecs/fen';
stringify(position);
// => 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
stringify always succeeds.
import { STARTING_FEN } from '@echecs/fen';
STARTING_FEN;
// => 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
parse(input: string, options?: ParseOptions): PositionData | nullParses a FEN string into a PositionData object. Returns null if the input is
not a valid FEN string.
stringify(position: PositionData): stringSerializes a PositionData object into a FEN string. Omitted fields use
defaults (empty board, white to move, all castling rights, no en passant,
halfmove clock 0, fullmove number 1).
STARTING_FENThe FEN string for the standard starting position.
Chess types (Color, Square, Piece, CastlingRights, PositionData, etc.)
are re-exported from @echecs/position. Parse/stringify types are defined
locally:
import type {
CastlingRights,
Color,
EnPassantSquare,
File,
ParseError,
ParseOptions,
ParseWarning,
Piece,
PieceType,
PositionData,
Rank,
SideCastlingRights,
Square,
} from '@echecs/fen';
interface ParseOptions {
onError?: (error: ParseError) => void;
onWarning?: (warning: ParseWarning) => void;
}
interface ParseError {
column: number; // 1-indexed column in the FEN string
line: number; // Always 1 (FEN is single-line)
message: string;
offset: number; // 0-indexed offset into the FEN string
}
interface ParseWarning {
column: number;
line: number;
message: string;
offset: number;
}
See @echecs/position for the full type definitions of PositionData, Color,
Square, Piece, and other chess types.
MIT