gigachess 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +183 -0
  3. package/dist/attacks.d.ts +40 -0
  4. package/dist/attacks.d.ts.map +1 -0
  5. package/dist/attacks.js +389 -0
  6. package/dist/bishopMagicBlob.d.ts +2 -0
  7. package/dist/bishopMagicBlob.d.ts.map +1 -0
  8. package/dist/bishopMagicBlob.js +11 -0
  9. package/dist/board.d.ts +73 -0
  10. package/dist/board.d.ts.map +1 -0
  11. package/dist/board.js +237 -0
  12. package/dist/chess.d.ts +215 -0
  13. package/dist/chess.d.ts.map +1 -0
  14. package/dist/chess.js +1453 -0
  15. package/dist/chess960.d.ts +10 -0
  16. package/dist/chess960.d.ts.map +1 -0
  17. package/dist/chess960.js +18 -0
  18. package/dist/chessops/board.d.ts +49 -0
  19. package/dist/chessops/board.d.ts.map +1 -0
  20. package/dist/chessops/board.js +138 -0
  21. package/dist/chessops/chess.d.ts +104 -0
  22. package/dist/chessops/chess.d.ts.map +1 -0
  23. package/dist/chessops/chess.js +435 -0
  24. package/dist/chessops/compat.d.ts +19 -0
  25. package/dist/chessops/compat.d.ts.map +1 -0
  26. package/dist/chessops/compat.js +25 -0
  27. package/dist/chessops/convert.d.ts +42 -0
  28. package/dist/chessops/convert.d.ts.map +1 -0
  29. package/dist/chessops/convert.js +114 -0
  30. package/dist/chessops/debug.d.ts +17 -0
  31. package/dist/chessops/debug.d.ts.map +1 -0
  32. package/dist/chessops/debug.js +67 -0
  33. package/dist/chessops/fen.d.ts +28 -0
  34. package/dist/chessops/fen.d.ts.map +1 -0
  35. package/dist/chessops/fen.js +74 -0
  36. package/dist/chessops/fenInternal.d.ts +15 -0
  37. package/dist/chessops/fenInternal.d.ts.map +1 -0
  38. package/dist/chessops/fenInternal.js +42 -0
  39. package/dist/chessops/index.d.ts +12 -0
  40. package/dist/chessops/index.d.ts.map +1 -0
  41. package/dist/chessops/index.js +17 -0
  42. package/dist/chessops/san.d.ts +7 -0
  43. package/dist/chessops/san.d.ts.map +1 -0
  44. package/dist/chessops/san.js +33 -0
  45. package/dist/chessops/setup.d.ts +64 -0
  46. package/dist/chessops/setup.d.ts.map +1 -0
  47. package/dist/chessops/setup.js +158 -0
  48. package/dist/chessops/squareSet.d.ts +48 -0
  49. package/dist/chessops/squareSet.d.ts.map +1 -0
  50. package/dist/chessops/squareSet.js +192 -0
  51. package/dist/chessops/transform.d.ts +12 -0
  52. package/dist/chessops/transform.d.ts.map +1 -0
  53. package/dist/chessops/transform.js +53 -0
  54. package/dist/chessops/types.d.ts +47 -0
  55. package/dist/chessops/types.d.ts.map +1 -0
  56. package/dist/chessops/types.js +12 -0
  57. package/dist/chessops/util.d.ts +19 -0
  58. package/dist/chessops/util.d.ts.map +1 -0
  59. package/dist/chessops/util.js +52 -0
  60. package/dist/chesstree.d.ts +143 -0
  61. package/dist/chesstree.d.ts.map +1 -0
  62. package/dist/chesstree.js +514 -0
  63. package/dist/core.d.ts +10 -0
  64. package/dist/core.d.ts.map +1 -0
  65. package/dist/core.js +11 -0
  66. package/dist/fen.d.ts +10 -0
  67. package/dist/fen.d.ts.map +1 -0
  68. package/dist/fen.js +600 -0
  69. package/dist/index.d.ts +17 -0
  70. package/dist/index.d.ts.map +1 -0
  71. package/dist/index.js +22 -0
  72. package/dist/packedMove.d.ts +31 -0
  73. package/dist/packedMove.d.ts.map +1 -0
  74. package/dist/packedMove.js +88 -0
  75. package/dist/pgn.d.ts +24 -0
  76. package/dist/pgn.d.ts.map +1 -0
  77. package/dist/pgn.js +361 -0
  78. package/dist/rookMagicBlob.d.ts +2 -0
  79. package/dist/rookMagicBlob.d.ts.map +1 -0
  80. package/dist/rookMagicBlob.js +11 -0
  81. package/dist/san.d.ts +6 -0
  82. package/dist/san.d.ts.map +1 -0
  83. package/dist/san.js +484 -0
  84. package/dist/squareSet.d.ts +48 -0
  85. package/dist/squareSet.d.ts.map +1 -0
  86. package/dist/squareSet.js +154 -0
  87. package/dist/types.d.ts +147 -0
  88. package/dist/types.d.ts.map +1 -0
  89. package/dist/types.js +88 -0
  90. package/dist/util.d.ts +11 -0
  91. package/dist/util.d.ts.map +1 -0
  92. package/dist/util.js +59 -0
  93. package/dist/zobrist.d.ts +45 -0
  94. package/dist/zobrist.d.ts.map +1 -0
  95. package/dist/zobrist.js +271 -0
  96. package/dist/zobristBlob.d.ts +2 -0
  97. package/dist/zobristBlob.d.ts.map +1 -0
  98. package/dist/zobristBlob.js +11 -0
  99. package/package.json +135 -0
package/dist/chess.js ADDED
@@ -0,0 +1,1453 @@
1
+ // src/chess.ts — core chess rules, Position/Setup, dests, isLegal, isCheck, perft etc
2
+ // MIT turbochess, clean-room from specs + FIDE notes (no G P L)
3
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
4
+ if (kind === "m") throw new TypeError("Private method is not writable");
5
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
6
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
7
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
8
+ };
9
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
10
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
11
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
12
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
13
+ };
14
+ var _Chess_instances, _Chess_startFen, _Chess_history, _Chess_pos, _Chess_movetext, _Chess_positions, _Chess_describe, _Chess_fenOf;
15
+ import * as sq from "./squareSet.js";
16
+ import * as board from "./board.js";
17
+ import * as attacks from "./attacks.js";
18
+ import { Color, Role } from "./types.js";
19
+ import { opposite, squareFile, squareRank, parseSquare, squareName } from "./util.js";
20
+ import { zobristTablesLoaded, zobristAfterMove, calculateZobrist, zobristHex } from "./zobrist.js";
21
+ import { parseFen, makeFen } from "./fen.js";
22
+ import { parseSan, makeSan, parseUci, makeUci } from "./san.js";
23
+ import { packOf, packedToMoves } from "./packedMove.js";
24
+ import { build as buildTreeWrapper, pgnImport as pgnImportData } from "./chesstree.js";
25
+ import { pieceAt } from "./board.js";
26
+ // helpers
27
+ export function isCheck(pos) {
28
+ const ksq = board.kingSquare(pos.board, pos.turn);
29
+ if (ksq === undefined)
30
+ return false;
31
+ const attacker = opposite(pos.turn);
32
+ return attacks.isAttacked(pos.board, ksq, attacker);
33
+ }
34
+ export function kingAttackers(pos, color) {
35
+ return attacks.kingAttackers(pos.board, color);
36
+ }
37
+ // insufficient material per spec
38
+ export function isInsufficientMaterial(pos) {
39
+ const b = pos.board;
40
+ // only kings
41
+ if (sq.equals(b.occupied, b.king))
42
+ return true;
43
+ // count pieces
44
+ const whitePawns = sq.popcnt(sq.and(b.white, b.pawn));
45
+ const blackPawns = sq.popcnt(sq.and(b.black, b.pawn));
46
+ const whiteRooks = sq.popcnt(sq.and(b.white, b.rook));
47
+ const blackRooks = sq.popcnt(sq.and(b.black, b.rook));
48
+ const whiteQueens = sq.popcnt(sq.and(b.white, b.queen));
49
+ const blackQueens = sq.popcnt(sq.and(b.black, b.queen));
50
+ if (whitePawns > 0 || blackPawns > 0 || whiteRooks > 0 || blackRooks > 0 || whiteQueens > 0 || blackQueens > 0) {
51
+ return false;
52
+ }
53
+ const whiteKnights = sq.popcnt(sq.and(b.white, b.knight));
54
+ const blackKnights = sq.popcnt(sq.and(b.black, b.knight));
55
+ const whiteBishops = sq.popcnt(sq.and(b.white, b.bishop));
56
+ const blackBishops = sq.popcnt(sq.and(b.black, b.bishop));
57
+ const totalKnights = whiteKnights + blackKnights;
58
+ const totalBishops = whiteBishops + blackBishops;
59
+ // K vs K already handled
60
+ // K+B vs K, K+N vs K
61
+ if (totalKnights === 1 && totalBishops === 0)
62
+ return true;
63
+ if (totalBishops === 1 && totalKnights === 0)
64
+ return true;
65
+ // K+B vs K+B same color bishops
66
+ if (totalBishops === 2 && totalKnights === 0) {
67
+ // find bishop squares
68
+ let firstB = sq.first(sq.or(sq.and(b.white, b.bishop), sq.and(b.black, b.bishop)));
69
+ // Actually need both bishops
70
+ const bishops = sq.or(sq.and(b.white, b.bishop), sq.and(b.black, b.bishop));
71
+ const iter = [...sq.iter(bishops)];
72
+ if (iter.length === 2) {
73
+ const c1 = (squareFile(iter[0]) + squareRank(iter[0])) % 2;
74
+ const c2 = (squareFile(iter[1]) + squareRank(iter[1])) % 2;
75
+ if (c1 === c2)
76
+ return true;
77
+ }
78
+ }
79
+ // K+B vs K+B same color insufficient, opposite color sufficient -> false
80
+ // K+N vs K+N etc not insufficient
81
+ return false;
82
+ }
83
+ export function isFiftyMoveDraw(pos) {
84
+ return (pos.halfmoves ?? pos.halfmove ?? 0) >= 100;
85
+ }
86
+ export function isSeventyFiveMoveDraw(pos) {
87
+ return (pos.halfmoves ?? pos.halfmove ?? 0) >= 150;
88
+ }
89
+ export function isThreefoldRepetition(history) {
90
+ if (history.length < 3)
91
+ return false;
92
+ const last = history[history.length - 1];
93
+ let count = 0;
94
+ for (const h of history) {
95
+ if (positionsEqualForRepetition(h, last))
96
+ count++;
97
+ if (count >= 3)
98
+ return true;
99
+ }
100
+ return false;
101
+ }
102
+ export function isFivefoldRepetition(history) {
103
+ if (history.length < 5)
104
+ return false;
105
+ const last = history[history.length - 1];
106
+ let count = 0;
107
+ for (const h of history)
108
+ if (positionsEqualForRepetition(h, last))
109
+ count++;
110
+ return count >= 5;
111
+ }
112
+ function positionsEqualForRepetition(a, b) {
113
+ if (a.turn !== b.turn)
114
+ return false;
115
+ if (a.epSquare !== b.epSquare)
116
+ return false;
117
+ if (!board.boardEquals(a.board, b.board))
118
+ return false;
119
+ // castling sets equality
120
+ if (a.castling.white.size !== b.castling.white.size)
121
+ return false;
122
+ if (a.castling.black.size !== b.castling.black.size)
123
+ return false;
124
+ for (const s of a.castling.white)
125
+ if (!b.castling.white.has(s))
126
+ return false;
127
+ for (const s of a.castling.black)
128
+ if (!b.castling.black.has(s))
129
+ return false;
130
+ return true;
131
+ }
132
+ function castlingPlanFor(color, ks, rs) {
133
+ const rank = squareRank(ks);
134
+ const isKingSide = squareFile(rs) > squareFile(ks);
135
+ return {
136
+ side: isKingSide ? "king" : "queen",
137
+ kingFrom: ks,
138
+ kingTo: isKingSide ? (rank << 3) | 6 : (rank << 3) | 2,
139
+ rookFrom: rs,
140
+ rookTo: isKingSide ? (rank << 3) | 5 : (rank << 3) | 3,
141
+ };
142
+ }
143
+ /** Finds the position's castling plan (if any) targeting square `to` (either
144
+ * the rook origin or the normalized landing square). Shared by the hot loops. */
145
+ function planForDest(plans, to) {
146
+ for (let i = 0; i < plans.length; i++) {
147
+ const p = plans[i];
148
+ if (p.rookFrom === to || p.kingTo === to)
149
+ return p;
150
+ }
151
+ return null;
152
+ }
153
+ /**
154
+ * Single source of truth for castling detection, shared by makeMove, isLegal,
155
+ * makeSan, destsFast and genLegalMoves (design D2). Accepts both input
156
+ * representations:
157
+ * - king→own-rook square (baseline / 960 input, e1h1), and
158
+ * - king→normalized landing square (e1g1; a two-file king step),
159
+ * provided the corresponding castling right exists and the rook is actually
160
+ * on its origin square. Returns null for every non-castling move — in
161
+ * particular for an ordinary one-square king step to g1/c1/g8/c8, which the
162
+ * previous per-call-site heuristics misclassified when ANY color (even the
163
+ * opponent) held castling rights (root cause of the perft parity defect).
164
+ */
165
+ export function detectCastling(pos, from, to) {
166
+ if (pos.castling.white.size === 0 && pos.castling.black.size === 0)
167
+ return null;
168
+ const piece = board.pieceAt(pos.board, from);
169
+ if (!piece || piece.role !== Role.King || piece.color !== pos.turn)
170
+ return null;
171
+ const rights = piece.color === Color.White ? pos.castling.white : pos.castling.black;
172
+ if (rights.size === 0)
173
+ return null;
174
+ const rank = squareRank(from);
175
+ // Input form 1: king captures own rook on its origin square (baseline/960).
176
+ if (rights.has(to) && squareRank(to) === rank) {
177
+ const target = board.pieceAt(pos.board, to);
178
+ if (target && target.color === piece.color && target.role === Role.Rook) {
179
+ return castlingPlanFor(piece.color, from, to);
180
+ }
181
+ }
182
+ // Input form 2: normalized landing square — a two-file step on the same rank.
183
+ if (squareRank(to) === rank && Math.abs(squareFile(to) - squareFile(from)) === 2) {
184
+ // The landing square must be empty for castling.
185
+ if (!board.pieceAt(pos.board, to)) {
186
+ for (const rs of rights) {
187
+ const plan = castlingPlanFor(piece.color, from, rs);
188
+ if (plan.kingTo !== to)
189
+ continue;
190
+ // The right's rook must actually be present on its origin square.
191
+ const rp = board.pieceAt(pos.board, rs);
192
+ if (rp && rp.color === piece.color && rp.role === Role.Rook)
193
+ return plan;
194
+ }
195
+ }
196
+ }
197
+ return null;
198
+ }
199
+ // ---------- move execution (play) ----------
200
+ /**
201
+ * Shared board-edit sequence used by BOTH the pure `makeMove` and the
202
+ * hot-loop scratch tester below — a single source of truth so the fast path
203
+ * can never drift from the pure path.
204
+ */
205
+ function computeCaptured(pos, origTo, to, isCastling, piece) {
206
+ // capture handling (re-evaluate after normalization; for castling, captured is the rook but we handle rook move separately)
207
+ // if we normalized 960 castling, original captured is rook but normalized to is now empty dest, so captured should be undefined for that case
208
+ if (isCastling && piece.role === Role.King) {
209
+ // For 960 normalized, the original rook capture is not a capture in normal sense; we should not treat as capture
210
+ // Check if original move was king-captures-rook: then captured was rook, but after normalization we don't want to treat as capture of piece on dest (dest is empty)
211
+ const origTarget = board.pieceAt(pos.board, origTo);
212
+ if (origTarget && origTarget.color === piece.color && origTarget.role === Role.Rook) {
213
+ return undefined;
214
+ }
215
+ return board.pieceAt(pos.board, to);
216
+ }
217
+ return board.pieceAt(pos.board, to);
218
+ }
219
+ function applyBoardEdits(nb, pos, from, to, // normalized dest (castling → G1/C1/G8/C8)
220
+ origTo, // move.to before normalization (for capture removal)
221
+ piece, isEnPassant, plan, // non-null ⇒ castling, with the full king+rook plan
222
+ isPromotion, promotion, captured) {
223
+ // remove moving piece from from
224
+ board.clearSquareInPlace(nb, from);
225
+ // if en passant, remove captured pawn which is not on to square
226
+ if (isEnPassant) {
227
+ const epCaptureRank = pos.turn === Color.White ? squareRank(to) - 1 : squareRank(to) + 1;
228
+ const epCaptureSq = epCaptureRank * 8 + squareFile(to);
229
+ board.clearSquareInPlace(nb, epCaptureSq);
230
+ }
231
+ else if (captured) {
232
+ // captured is only ever non-undefined when to === origTo (capture removal
233
+ // square), so removing at origTo is exactly equivalent to the original
234
+ // `removePiece(nb, to)`.
235
+ board.clearSquareInPlace(nb, origTo);
236
+ }
237
+ // handle castling: king + rook relocation + rights context all come from the
238
+ // single detectCastling plan (design D2) — no per-site rook scanning left.
239
+ if (plan) {
240
+ board.clearSquareInPlace(nb, plan.rookFrom);
241
+ board.putPieceInPlace(nb, plan.rookTo, { color: pos.turn, role: Role.Rook });
242
+ // place king on destination (to)
243
+ board.putPieceInPlace(nb, to, { color: pos.turn, role: Role.King });
244
+ }
245
+ else {
246
+ // normal move: place moving piece (with promotion)
247
+ let role = piece.role;
248
+ if (isPromotion && promotion !== undefined && promotion !== null) {
249
+ role = promotion;
250
+ }
251
+ board.putPieceInPlace(nb, to, { color: piece.color, role });
252
+ }
253
+ }
254
+ export function makeMove(pos, move) {
255
+ let from = move.from;
256
+ let to = move.to;
257
+ let piece = board.pieceAt(pos.board, from);
258
+ if (!piece)
259
+ throw new Error("no piece at from");
260
+ // Single castling detection for BOTH input representations (normalized
261
+ // landing e1g1 and baseline/960 king-captures-rook e1h1) — fixes the defect
262
+ // where `makeMove(pos, {from: king, to: landing})` moved only the king and
263
+ // left the rook behind.
264
+ let isEnPassant = !!move.isEnPassant;
265
+ // Robust ep derivation: a pawn moving DIAGONALLY onto the ep square is an
266
+ // en-passant capture even when the caller did not set the flag (external
267
+ // move objects) — keeps the board edit AND the Zobrist delta correct.
268
+ if (!isEnPassant &&
269
+ piece.role === Role.Pawn &&
270
+ pos.epSquare !== null &&
271
+ move.to === pos.epSquare &&
272
+ squareFile(move.from) !== squareFile(move.to)) {
273
+ isEnPassant = true;
274
+ }
275
+ // Single castling detection for BOTH input representations (normalized
276
+ // landing e1g1 and baseline/960 king-captures-rook e1h1) — fixes the defect
277
+ // where `makeMove(pos, {from: king, to: landing})` moved only the king and
278
+ // left the rook behind. detectCastling is the ONLY castling apply path
279
+ // (design D2: no second castling code path); a move explicitly flagged
280
+ // isCastling whose rights no longer support detection is not castling.
281
+ let plan = null;
282
+ if (piece.role === Role.King) {
283
+ plan = detectCastling(pos, from, to);
284
+ }
285
+ const isCastling = plan !== null;
286
+ if (plan)
287
+ to = plan.kingTo;
288
+ const isPromotion = !!move.isPromotion || move.promotion !== undefined && move.promotion !== null;
289
+ // Board construction: clone→mutate-clone (spec-sanctioned technique). `nb`
290
+ // is a fresh writable board owned locally and returned as a read-only Board;
291
+ // the input position is never touched, so the observable contract stays pure.
292
+ // The edit sequence itself lives in applyBoardEdits (shared with the
293
+ // hot-loop scratch tester).
294
+ const nb = board.cloneAsWritable(pos.board);
295
+ const captured = computeCaptured(pos, move.to, to, isCastling, piece);
296
+ applyBoardEdits(nb, pos, from, to, move.to, piece, isEnPassant, plan, isPromotion, move.promotion ?? null, captured);
297
+ // handle promotion: pawn must promote if reaching back rank
298
+ // Already handled via move.promotion
299
+ // update castling rights — copy a Set ONLY when it actually changes; the
300
+ // common case (rights unchanged) shares the existing Set reference. This
301
+ // structural sharing is part of the public contract (ADR-012 §4): the
302
+ // library never mutates these sets, and the public CastlingRights type
303
+ // exposes ReadonlySet so callers cannot mutate shared sub-objects through
304
+ // the API either.
305
+ let newWhite = pos.castling.white;
306
+ let newBlack = pos.castling.black;
307
+ // if king moves, remove all rights for that color — a fresh empty set; no
308
+ // copy of the old one is needed
309
+ if (piece.role === Role.King) {
310
+ if (pos.turn === Color.White) {
311
+ if (newWhite.size > 0)
312
+ newWhite = new Set();
313
+ }
314
+ else {
315
+ if (newBlack.size > 0)
316
+ newBlack = new Set();
317
+ }
318
+ }
319
+ // if rook moves from origin, remove that right (clone → delete on the
320
+ // owned copy — never on the input's set)
321
+ if (piece.role === Role.Rook) {
322
+ if (pos.turn === Color.White) {
323
+ if (newWhite.has(from)) {
324
+ const next = new Set(newWhite);
325
+ next.delete(from);
326
+ newWhite = next;
327
+ }
328
+ }
329
+ else {
330
+ if (newBlack.has(from)) {
331
+ const next = new Set(newBlack);
332
+ next.delete(from);
333
+ newBlack = next;
334
+ }
335
+ }
336
+ }
337
+ // if rook captured on origin, remove opponent right
338
+ if (captured && captured.role === Role.Rook) {
339
+ if (captured.color === Color.White) {
340
+ if (newWhite.has(to)) {
341
+ const next = new Set(newWhite);
342
+ next.delete(to);
343
+ newWhite = next;
344
+ }
345
+ }
346
+ else {
347
+ if (newBlack.has(to)) {
348
+ const next = new Set(newBlack);
349
+ next.delete(to);
350
+ newBlack = next;
351
+ }
352
+ }
353
+ }
354
+ // en passant capture already handled (captured pawn not rook, so no)
355
+ // if rook moved in castling, its origin already removed, but rook destination not relevant
356
+ // en passant square for next position
357
+ let newEp = null;
358
+ if (piece.role === Role.Pawn && Math.abs(squareRank(to) - squareRank(from)) === 2) {
359
+ // double push
360
+ const epRank = pos.turn === Color.White ? squareRank(from) + 1 : squareRank(from) - 1;
361
+ newEp = epRank * 8 + squareFile(from);
362
+ }
363
+ // halfmove
364
+ const isCapture = !!captured || isEnPassant;
365
+ const isPawnMove = piece.role === Role.Pawn;
366
+ const newHalf = isCapture || isPawnMove ? 0 : (pos.halfmoves ?? pos.halfmove ?? 0) + 1;
367
+ // fullmove
368
+ const newFull = pos.turn === Color.Black ? (pos.fullmoves ?? pos.fullmove ?? 1) + 1 : (pos.fullmoves ?? pos.fullmove ?? 1);
369
+ const newTurn = opposite(pos.turn);
370
+ const newCastling = {
371
+ white: newWhite,
372
+ black: newBlack,
373
+ whiteKing: newWhite.has(7),
374
+ whiteQueen: newWhite.has(0),
375
+ blackKing: newBlack.has(63),
376
+ blackQueen: newBlack.has(56),
377
+ };
378
+ const newPos = {
379
+ board: nb,
380
+ turn: newTurn,
381
+ castling: newCastling,
382
+ epSquare: newEp,
383
+ halfmoves: newHalf,
384
+ fullmoves: newFull,
385
+ halfmove: newHalf,
386
+ fullmove: newFull,
387
+ };
388
+ // Incremental O(1) Zobrist maintenance (design D2). Skipped (positions
389
+ // carry no zobrist fields) until the Polyglot key tables have loaded via
390
+ // ensureZobristLoaded() — the same lazy-loading contract as the magic
391
+ // tables. The input position is never mutated: the key is attached to the
392
+ // freshly built newPos before it escapes.
393
+ if (zobristTablesLoaded()) {
394
+ const zk = zobristAfterMove(pos, move, plan, isEnPassant, captured, newPos);
395
+ newPos.zobristLo = zk.lo;
396
+ newPos.zobristHi = zk.hi;
397
+ }
398
+ return newPos;
399
+ }
400
+ // alias play
401
+ export const play = makeMove;
402
+ // ---------- pseudo-legal generation ----------
403
+ function pawnPseudoDests(pos, from, color) {
404
+ // color passed in (genPseudoDests already looked the piece up) and target
405
+ // occupancy tested with raw set membership — zero allocations per target.
406
+ const dir = color === Color.White ? 1 : -1;
407
+ const rank = squareRank(from);
408
+ const file = squareFile(from);
409
+ const occ = pos.board.occupied;
410
+ const whiteOcc = pos.board.white;
411
+ const isWhite = color === Color.White;
412
+ let lo = 0, hi = 0;
413
+ const add = (sqIdx) => {
414
+ if (sqIdx < 32)
415
+ lo |= (1 << sqIdx) >>> 0;
416
+ else
417
+ hi |= (1 << (sqIdx - 32)) >>> 0;
418
+ };
419
+ // forward one
420
+ const oneRank = rank + dir;
421
+ if (oneRank >= 0 && oneRank < 8) {
422
+ const oneSq = oneRank * 8 + file;
423
+ if (!sq.has(occ, oneSq)) {
424
+ add(oneSq);
425
+ // double from starting rank
426
+ const startRank = color === Color.White ? 1 : 6;
427
+ if (rank === startRank) {
428
+ const twoRank = rank + dir * 2;
429
+ const twoSq = twoRank * 8 + file;
430
+ if (!sq.has(occ, twoSq))
431
+ add(twoSq);
432
+ }
433
+ }
434
+ }
435
+ // captures
436
+ for (const df of [-1, 1]) {
437
+ const nf = file + df;
438
+ const nr = rank + dir;
439
+ if (nf < 0 || nf >= 8 || nr < 0 || nr >= 8)
440
+ continue;
441
+ const capSq = nr * 8 + nf;
442
+ if (sq.has(occ, capSq)) {
443
+ // target color via color-occupancy membership instead of pieceAt object
444
+ if (sq.has(whiteOcc, capSq) !== isWhite)
445
+ add(capSq);
446
+ }
447
+ else if (pos.epSquare !== null && capSq === pos.epSquare) {
448
+ // en passant capture destination is epSquare, which is empty but capturable
449
+ add(capSq);
450
+ }
451
+ }
452
+ return { lo: lo >>> 0, hi: hi >>> 0 };
453
+ }
454
+ function genPseudoDests(pos, from) {
455
+ const p = board.pieceAt(pos.board, from);
456
+ if (!p || p.color !== pos.turn)
457
+ return sq.empty();
458
+ const occ = pos.board.occupied;
459
+ const own = p.color === Color.White ? pos.board.white : pos.board.black;
460
+ let pseudo;
461
+ switch (p.role) {
462
+ case Role.Pawn:
463
+ pseudo = pawnPseudoDests(pos, from, p.color);
464
+ break;
465
+ case Role.Knight:
466
+ pseudo = attacks.knightAttacks(from);
467
+ pseudo = sq.minus(pseudo, own);
468
+ break;
469
+ case Role.Bishop:
470
+ pseudo = attacks.bishopAttacks(from, occ);
471
+ pseudo = sq.minus(pseudo, own);
472
+ break;
473
+ case Role.Rook:
474
+ pseudo = attacks.rookAttacks(from, occ);
475
+ pseudo = sq.minus(pseudo, own);
476
+ break;
477
+ case Role.Queen:
478
+ pseudo = attacks.queenAttacks(from, occ);
479
+ pseudo = sq.minus(pseudo, own);
480
+ break;
481
+ case Role.King: {
482
+ pseudo = attacks.kingAttacks(from);
483
+ pseudo = sq.minus(pseudo, own);
484
+ // castling destinations
485
+ const ks = from;
486
+ // `from` IS this color's king square by definition (invariant: exactly
487
+ // one king per color), so no kingSquare lookup is needed here.
488
+ // Conditions to add castling dest: rights exist, between empty, not in check, traversal not attacked
489
+ if (p.color === Color.White) {
490
+ // white castling
491
+ // king-side to G1 (6)
492
+ if (pos.castling.white.size > 0) {
493
+ // find rook(s) for each side, check conditions
494
+ // We'll check each rook square in white set
495
+ for (const rs of pos.castling.white) {
496
+ // The right's rook must actually be on its origin square (guards
497
+ // against stale rights in hand-written FENs).
498
+ const rp = board.pieceAt(pos.board, rs);
499
+ if (!rp || rp.color !== p.color || rp.role !== Role.Rook)
500
+ continue;
501
+ const rookFile = squareFile(rs);
502
+ const kingFile = squareFile(ks);
503
+ const isKingSide = rookFile > kingFile;
504
+ const dest = rs; // king-captures-rook (ADR-013 as amended)
505
+ // Only generate dest once per side, but if multiple rooks on same side? For now handle
506
+ // Check between empty
507
+ const between = attacks.between(ks, rs);
508
+ if (!sq.isEmpty(sq.and(between, occ)))
509
+ continue;
510
+ // Also need squares between king and dest empty? That's subset of between check? For queen-side, dest C1 is between, but need B1 also empty? Between already covers B1-D1 etc, so ok
511
+ // Check king not in check
512
+ if (isCheck(pos))
513
+ continue;
514
+ // Check traversal squares not attacked
515
+ const traversal = isKingSide ? [5, 6] : [3, 2]; // F1,G1 or D1,C1
516
+ let attacked = false;
517
+ for (const t of traversal) {
518
+ if (attacks.isAttacked(pos.board, t, Color.Black)) {
519
+ attacked = true;
520
+ break;
521
+ }
522
+ }
523
+ if (attacked)
524
+ continue;
525
+ // Also need dest not occupied by own? already filtered via own? But G1/C1 between empty ensures not occupied, but check if dest is occupied by opponent capture? Castling destination should be empty, but could be rook capture? No, destination must be empty per between check. For queen-side, B1 may be occupied but dest C1 must be empty; between includes B1,C1,D1, so if B1 occupied, fails. So okay.
526
+ // Add dest
527
+ const bit = sq.singleton(dest);
528
+ pseudo = sq.or(pseudo, bit);
529
+ }
530
+ }
531
+ }
532
+ else if (p.color === Color.Black) {
533
+ for (const rs of pos.castling.black) {
534
+ // The right's rook must actually be on its origin square (guards
535
+ // against stale rights in hand-written FENs).
536
+ const rp = board.pieceAt(pos.board, rs);
537
+ if (!rp || rp.color !== p.color || rp.role !== Role.Rook)
538
+ continue;
539
+ const rookFile = squareFile(rs);
540
+ const kingFile = squareFile(ks);
541
+ const isKingSide = rookFile > kingFile;
542
+ const dest = rs; // king-captures-rook (ADR-013 as amended)
543
+ const between = attacks.between(ks, rs);
544
+ if (!sq.isEmpty(sq.and(between, occ)))
545
+ continue;
546
+ if (isCheck(pos))
547
+ continue;
548
+ const traversal = isKingSide ? [61, 62] : [59, 58];
549
+ let attacked = false;
550
+ for (const t of traversal) {
551
+ if (attacks.isAttacked(pos.board, t, Color.White)) {
552
+ attacked = true;
553
+ break;
554
+ }
555
+ }
556
+ if (attacked)
557
+ continue;
558
+ pseudo = sq.or(pseudo, sq.singleton(dest));
559
+ }
560
+ }
561
+ break;
562
+ }
563
+ default:
564
+ pseudo = sq.empty();
565
+ }
566
+ return pseudo;
567
+ }
568
+ // ---------- dests filtered for legality ----------
569
+ // ---- Hot-loop scratch (see FP policy in board.ts) ---------------------------
570
+ // `destScratch` is owned exclusively by moveLeavesKingSafe, a leaf function:
571
+ // while the scratch is live it only calls board/attacks helpers that never
572
+ // re-enter movegen, so no re-entrant caller can observe intermediate state.
573
+ // The public API remains pure — the scratch never escapes and its state is
574
+ // fully rewritten from the input position before each use.
575
+ const destScratch = board.newScratchBoard();
576
+ /**
577
+ * Hot-loop legality tester: applies the shared board-edit sequence
578
+ * (applyBoardEdits — same code path as makeMove) to the reusable scratch
579
+ * board, then checks whether our king is left attacked. Semantically
580
+ * identical to `makeMove(pos, mv)` + `!isAttacked(our king)`, minus all the
581
+ * per-pseudo-move allocation (Position, Sets, Move object, 3 board spreads).
582
+ * Mutation is sanctioned here per the FP policy: hot loop, locally owned
583
+ * scratch, inputs never mutated.
584
+ */
585
+ function moveLeavesKingSafe(pos, piece, from, to, // normalized dest
586
+ origTo, // move.to before normalization
587
+ isEnPassant, plan, // non-null ⇒ castling (exact king+rook apply)
588
+ isPromotion, promotion) {
589
+ board.copyBoardInto(destScratch, pos.board);
590
+ const captured = computeCaptured(pos, origTo, to, plan !== null, piece);
591
+ applyBoardEdits(destScratch, pos, from, to, origTo, piece, isEnPassant, plan, isPromotion, promotion, captured);
592
+ const ksq = board.kingSquare(destScratch, pos.turn);
593
+ if (ksq === undefined)
594
+ return false;
595
+ return !attacks.isAttacked(destScratch, ksq, opposite(pos.turn));
596
+ }
597
+ // Module-level scratch, sanctioned by the FP policy for hot loops: owned by
598
+ // analyzeCheckContext (a leaf — no re-entrant movegen runs while a context is
599
+ // live within one dests/allDests/genLegalMoves call) and cleared before every
600
+ // use. Never escapes the enclosing call.
601
+ const scratchPinRays = new Map();
602
+ // Reused castling plan scratch (same ownership discipline): avoids allocating
603
+ // two plan objects per analyzed position in the perft/movegen hot loop. The
604
+ // referenced position data is read-only and consumed within the same call.
605
+ const scratchCastlingPlans = [];
606
+ const scratchCastlingPlanA = { side: "king", kingFrom: 0, kingTo: 0, rookFrom: 0, rookTo: 0 };
607
+ const scratchCastlingPlanB = { side: "king", kingFrom: 0, kingTo: 0, rookFrom: 0, rookTo: 0 };
608
+ export function analyzeCheckContext(pos) {
609
+ const us = pos.turn;
610
+ const them = opposite(us);
611
+ scratchPinRays.clear();
612
+ const ksq = board.kingSquare(pos.board, us);
613
+ if (ksq === undefined) {
614
+ // degenerate (kingless) position: no pins, no masks
615
+ return { us, ksq: -1, doubleCheck: false, checkMask: sq.FULL, kingSafe: sq.EMPTY, pinRays: scratchPinRays, castlingPlans: [] };
616
+ }
617
+ const ctx = { us, ksq, doubleCheck: false, checkMask: sq.FULL, kingSafe: sq.EMPTY, pinRays: scratchPinRays, castlingPlans: [] };
618
+ // Precompute the position's castling plans once (design D2): the hot loops
619
+ // (destsFast king branch, genLegalMoves) look them up instead of re-running
620
+ // the full detectCastling per king move. Plans are written into the reused
621
+ // scratch array — no allocation in the hot loop.
622
+ ctx.castlingPlans = scratchCastlingPlans;
623
+ ctx.castlingPlans.length = 0;
624
+ const rights = us === Color.White ? pos.castling.white : pos.castling.black;
625
+ if (rights.size > 0) {
626
+ for (const rs of rights) {
627
+ const rp = board.pieceAt(pos.board, rs);
628
+ if (rp && rp.color === us && rp.role === Role.Rook) {
629
+ // write into the preallocated scratch slots — no hot-loop allocation
630
+ const slot = ctx.castlingPlans.length === 0 ? scratchCastlingPlanA : scratchCastlingPlanB;
631
+ const next = castlingPlanFor(us, ksq, rs);
632
+ slot.side = next.side;
633
+ slot.kingFrom = next.kingFrom;
634
+ slot.kingTo = next.kingTo;
635
+ slot.rookFrom = next.rookFrom;
636
+ slot.rookTo = next.rookTo;
637
+ ctx.castlingPlans.push(slot);
638
+ }
639
+ }
640
+ }
641
+ const checkers = attacks.kingAttackers(pos.board, us);
642
+ const nCheckers = sq.popcount(checkers);
643
+ if (nCheckers === 1) {
644
+ const c = sq.first(checkers);
645
+ ctx.checkMask = sq.or(attacks.between(ksq, c), sq.singleton(c));
646
+ }
647
+ else if (nCheckers >= 2) {
648
+ ctx.doubleCheck = true;
649
+ }
650
+ // Pinned pieces: enemy slider "snipers" x-raying our king with exactly one
651
+ // blocker between; if the blocker is ours, it is pinned to the sniper's ray.
652
+ const themOcc = them === Color.White ? pos.board.white : pos.board.black;
653
+ const themBQ = sq.or(sq.and(themOcc, pos.board.bishop), sq.and(themOcc, pos.board.queen));
654
+ const themRQ = sq.or(sq.and(themOcc, pos.board.rook), sq.and(themOcc, pos.board.queen));
655
+ const noOcc = sq.EMPTY;
656
+ const snipers = sq.or(sq.and(themRQ, attacks.rookAttacks(ksq, noOcc)), sq.and(themBQ, attacks.bishopAttacks(ksq, noOcc)));
657
+ for (const sniper of sq.iter(snipers)) {
658
+ const b = attacks.between(ksq, sniper);
659
+ const blockers = sq.and(b, pos.board.occupied);
660
+ if (sq.popcount(blockers) !== 1)
661
+ continue;
662
+ const blockerSq = sq.first(blockers);
663
+ if (sq.has(themOcc, blockerSq))
664
+ continue; // enemy blocker: not a pin
665
+ scratchPinRays.set(blockerSq, sq.or(b, sq.singleton(sniper)));
666
+ }
667
+ // King-safe mask: attackedness evaluated with our king removed from the
668
+ // occupancy, so sliders x-raying the king keep it attacked on the far side.
669
+ const occWithoutKing = sq.minus(pos.board.occupied, sq.singleton(ksq));
670
+ const usOcc = us === Color.White ? pos.board.white : pos.board.black;
671
+ let kingLo = 0, kingHi = 0;
672
+ sq.forEachSquare(attacks.kingAttacks(ksq), (d) => {
673
+ if (sq.has(usOcc, d))
674
+ return;
675
+ if (sq.isEmpty(attacks.attackersTo(pos.board, d, them, occWithoutKing))) {
676
+ if (d < 32)
677
+ kingLo |= (1 << d) >>> 0;
678
+ else
679
+ kingHi |= (1 << (d - 32)) >>> 0;
680
+ }
681
+ });
682
+ ctx.kingSafe = { lo: kingLo >>> 0, hi: kingHi >>> 0 };
683
+ return ctx;
684
+ }
685
+ /**
686
+ * dests for one piece, given the per-position CheckContext. Legality is a
687
+ * pure set intersection for all cases except the trap cases listed above.
688
+ */
689
+ export function destsFast(pos, from, piece, ctx) {
690
+ const pseudo = genPseudoDests(pos, from);
691
+ if (sq.isEmpty(pseudo))
692
+ return pseudo;
693
+ if (piece.role === Role.King) {
694
+ // Castling dests (detected by the shared detectCastling path — fixes the
695
+ // defect where ANY king move to {6,2,62,58} was treated as castling while
696
+ // ANY color held rights, corrupting the scratch board via fallback rook
697
+ // placement) keep the exact play-and-test semantics; other king dests come
698
+ // from the precomputed king-safe mask.
699
+ let lo = 0, hi = 0;
700
+ const plans = ctx.castlingPlans;
701
+ sq.forEachSquare(pseudo, (to) => {
702
+ // Castling dests (precomputed per-position plans — the shared
703
+ // detectCastling semantics, without the per-move cost) keep the exact
704
+ // play-and-test semantics; other king dests come from the precomputed
705
+ // king-safe mask.
706
+ const plan = planForDest(plans, to);
707
+ if (plan) {
708
+ if (moveLeavesKingSafe(pos, piece, from, plan.kingTo, to, false, plan, false, null)) {
709
+ if (to < 32)
710
+ lo |= (1 << to) >>> 0;
711
+ else
712
+ hi |= (1 << (to - 32)) >>> 0;
713
+ }
714
+ }
715
+ else if (sq.has(ctx.kingSafe, to)) {
716
+ if (to < 32)
717
+ lo |= (1 << to) >>> 0;
718
+ else
719
+ hi |= (1 << (to - 32)) >>> 0;
720
+ }
721
+ });
722
+ return { lo: lo >>> 0, hi: hi >>> 0 };
723
+ }
724
+ // Any single non-king move can never resolve a double check.
725
+ if (ctx.doubleCheck)
726
+ return { lo: 0, hi: 0 };
727
+ let nonEp = pseudo;
728
+ let epLegal = false;
729
+ const epSquare = pos.epSquare;
730
+ if (piece.role === Role.Pawn && epSquare !== null && sq.has(pseudo, epSquare)) {
731
+ nonEp = sq.minus(pseudo, sq.singleton(epSquare));
732
+ epLegal = moveLeavesKingSafe(pos, piece, from, epSquare, epSquare, true, null, false, null);
733
+ }
734
+ let result = sq.and(nonEp, ctx.checkMask);
735
+ const pin = ctx.pinRays.get(from);
736
+ if (pin)
737
+ result = sq.and(result, pin);
738
+ if (epLegal && epSquare !== null)
739
+ result = sq.or(result, sq.singleton(epSquare));
740
+ return result;
741
+ }
742
+ export function dests(pos, from) {
743
+ const piece = board.pieceAt(pos.board, from);
744
+ if (!piece)
745
+ return { lo: 0, hi: 0 };
746
+ return destsFast(pos, from, piece, analyzeCheckContext(pos));
747
+ }
748
+ export function allDests(pos) {
749
+ const m = new Map();
750
+ const ctx = analyzeCheckContext(pos);
751
+ const own = pos.turn === Color.White ? pos.board.white : pos.board.black;
752
+ sq.forEachSquare(own, (sqIdx) => {
753
+ const piece = board.pieceAt(pos.board, sqIdx);
754
+ if (!piece)
755
+ return;
756
+ const d = destsFast(pos, sqIdx, piece, ctx);
757
+ if (!sq.isEmpty(d))
758
+ m.set(sqIdx, d);
759
+ });
760
+ return m;
761
+ }
762
+ export function isLegal(pos, move) {
763
+ // Single castling path (design D2): both the normalized (e1g1) and the
764
+ // baseline/960 (e1h1) input forms resolve through detectCastling.
765
+ const castling = detectCastling(pos, move.from, move.to);
766
+ if (castling) {
767
+ const d = dests(pos, move.from);
768
+ // dests emits the rook-square representation (ADR-013 as amended); the
769
+ // normalized e1g1 input form is accepted via the plan's rook square.
770
+ return sq.has(d, castling.rookFrom);
771
+ }
772
+ const piece = board.pieceAt(pos.board, move.from);
773
+ const to = move.to;
774
+ const d = dests(pos, move.from);
775
+ if (!sq.has(d, to))
776
+ return false;
777
+ if (piece && piece.role === Role.Pawn) {
778
+ const destRank = squareRank(to);
779
+ const isPromoRank = (piece.color === Color.White && destRank === 7) || (piece.color === Color.Black && destRank === 0);
780
+ if (isPromoRank && !move.promotion)
781
+ return false;
782
+ }
783
+ return true;
784
+ }
785
+ // helpers for checkmate/stalemate
786
+ function hasAnyLegalMove(pos) {
787
+ const own = pos.turn === Color.White ? pos.board.white : pos.board.black;
788
+ for (const from of sq.iter(own)) {
789
+ const d = dests(pos, from);
790
+ if (!sq.isEmpty(d))
791
+ return true;
792
+ }
793
+ return false;
794
+ }
795
+ export function isCheckmate(pos) {
796
+ return isCheck(pos) && !hasAnyLegalMove(pos);
797
+ }
798
+ export function isStalemate(pos) {
799
+ return !isCheck(pos) && !hasAnyLegalMove(pos);
800
+ }
801
+ // ---------- perft ----------
802
+ export function perft(pos, depth) {
803
+ if (depth === 0)
804
+ return 1;
805
+ if (depth === 1) {
806
+ return countLegalMoves(pos);
807
+ }
808
+ let nodes = 0;
809
+ const moves = genLegalMoves(pos);
810
+ for (const m of moves) {
811
+ const next = makeMove(pos, m);
812
+ nodes += perft(next, depth - 1);
813
+ }
814
+ return nodes;
815
+ }
816
+ function countLegalMoves(pos) {
817
+ let count = 0;
818
+ const ctx = analyzeCheckContext(pos);
819
+ const own = pos.turn === Color.White ? pos.board.white : pos.board.black;
820
+ const isWhite = pos.turn === Color.White;
821
+ let ownLo = own.lo >>> 0, ownHi = own.hi >>> 0;
822
+ while (ownLo !== 0 || ownHi !== 0) {
823
+ let from;
824
+ if (ownLo !== 0) {
825
+ const lsb = (ownLo & -ownLo) >>> 0;
826
+ from = 31 - Math.clz32(lsb);
827
+ ownLo ^= lsb;
828
+ }
829
+ else {
830
+ const lsb = (ownHi & -ownHi) >>> 0;
831
+ from = 32 + (31 - Math.clz32(lsb));
832
+ ownHi ^= lsb;
833
+ }
834
+ const piece = board.pieceAt(pos.board, from);
835
+ if (!piece)
836
+ continue;
837
+ if (piece.role !== Role.King && ctx.doubleCheck)
838
+ continue;
839
+ const legal = destsFast(pos, from, piece, ctx);
840
+ if (legal.lo === 0 && legal.hi === 0)
841
+ continue;
842
+ if (piece.role === Role.Pawn) {
843
+ let lo = legal.lo >>> 0, hi = legal.hi >>> 0;
844
+ while (lo !== 0 || hi !== 0) {
845
+ let to;
846
+ if (lo !== 0) {
847
+ const lsb = (lo & -lo) >>> 0;
848
+ to = 31 - Math.clz32(lsb);
849
+ lo ^= lsb;
850
+ }
851
+ else {
852
+ const lsb = (hi & -hi) >>> 0;
853
+ to = 32 + (31 - Math.clz32(lsb));
854
+ hi ^= lsb;
855
+ }
856
+ const destRank = to >> 3;
857
+ if ((isWhite && destRank === 7) || (!isWhite && destRank === 0)) {
858
+ count += 4;
859
+ }
860
+ else {
861
+ count += 1;
862
+ }
863
+ }
864
+ }
865
+ else {
866
+ count += sq.popcount(legal);
867
+ }
868
+ }
869
+ return count;
870
+ }
871
+ // Promotion pieces in generation order (hoisted module constant — the old
872
+ // per-call array literal allocated on every promotion move in the hot loop).
873
+ const PROMO_ROLES = [Role.Queen, Role.Rook, Role.Bishop, Role.Knight];
874
+ function genLegalMoves(pos) {
875
+ const moves = [];
876
+ // Per-position check/pin-mask analysis replaces the per-move play-and-test;
877
+ // only ep (validated inside destsFast) keeps exact semantics.
878
+ const ctx = analyzeCheckContext(pos);
879
+ const own = pos.turn === Color.White ? pos.board.white : pos.board.black;
880
+ // Direct LSB bit iteration (ascending square order, same as forEachSquare)
881
+ // — no closure allocation per piece in this hot loop.
882
+ const plans = ctx.castlingPlans;
883
+ const isWhite = pos.turn === Color.White;
884
+ let ownLo = own.lo >>> 0, ownHi = own.hi >>> 0;
885
+ while (ownLo !== 0 || ownHi !== 0) {
886
+ let from;
887
+ if (ownLo !== 0) {
888
+ const lsb = (ownLo & -ownLo) >>> 0;
889
+ from = 31 - Math.clz32(lsb);
890
+ ownLo ^= lsb;
891
+ }
892
+ else {
893
+ const lsb = (ownHi & -ownHi) >>> 0;
894
+ from = 32 + (31 - Math.clz32(lsb));
895
+ ownHi ^= lsb;
896
+ }
897
+ const piece = board.pieceAt(pos.board, from);
898
+ if (!piece)
899
+ continue;
900
+ // A non-king move can never resolve a double check.
901
+ if (piece.role !== Role.King && ctx.doubleCheck)
902
+ continue;
903
+ const legal = destsFast(pos, from, piece, ctx);
904
+ const isPawn = piece.role === Role.Pawn;
905
+ const isKing = piece.role === Role.King;
906
+ let lo = legal.lo >>> 0, hi = legal.hi >>> 0;
907
+ while (lo !== 0 || hi !== 0) {
908
+ let to;
909
+ if (lo !== 0) {
910
+ const lsb = (lo & -lo) >>> 0;
911
+ to = 31 - Math.clz32(lsb);
912
+ lo ^= lsb;
913
+ }
914
+ else {
915
+ const lsb = (hi & -hi) >>> 0;
916
+ to = 32 + (31 - Math.clz32(lsb));
917
+ hi ^= lsb;
918
+ }
919
+ const destRank = to >> 3;
920
+ if (isPawn && ((isWhite && destRank === 7) || (!isWhite && destRank === 0))) {
921
+ // generate 4 promotions (legality is promotion-independent: every
922
+ // promoted piece lands on the same square, so king safety is identical)
923
+ for (const promo of PROMO_ROLES) {
924
+ // promotion capture can't be en passant (ep rank not back rank)
925
+ moves.push({ from, to, promotion: promo, isPromotion: true, isEnPassant: false, isCastling: false });
926
+ }
927
+ }
928
+ else {
929
+ // determine flags
930
+ let isEnPassant = false;
931
+ let isCastling = false;
932
+ if (isPawn && pos.epSquare !== null && to === pos.epSquare) {
933
+ // check if pawn capture to ep square
934
+ const fileDiff = Math.abs((to & 7) - (from & 7));
935
+ const dir = isWhite ? 1 : -1;
936
+ if (fileDiff === 1 && destRank - (from >> 3) === dir)
937
+ isEnPassant = true;
938
+ }
939
+ else if (isKing && plans.length > 0) {
940
+ // Precomputed per-position plans (design D2) — replaces the old
941
+ // dest-matches-a-right heuristic, which flagged ordinary king steps
942
+ // to {6,2,62,58} as castling whenever any color held rights.
943
+ isCastling = planForDest(plans, to) !== null;
944
+ }
945
+ // Legality is already guaranteed by destsFast (exact play-and-test for
946
+ // the ep/castling trap cases, check/pin masks otherwise) — no re-test.
947
+ moves.push({ from, to, promotion: null, isEnPassant, isCastling, isPromotion: false });
948
+ }
949
+ }
950
+ }
951
+ return moves;
952
+ }
953
+ // Promotion pieces in generation order (hoisted module constant — the old
954
+ // per-call array literal allocated on every promotion move in the hot loop).
955
+ export const INITIAL_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
956
+ // Deterministic unique 2-char node id (same alphabet/contract the
957
+ // workstation's `createUniqueMoveNodeId` relies on — mirrors chesstree.ts).
958
+ const TREE_ID_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
959
+ function nextTreeNodeId(siblings) {
960
+ const used = new Set(siblings.map((x) => x.id));
961
+ for (const first of TREE_ID_ALPHABET) {
962
+ for (const second of TREE_ID_ALPHABET) {
963
+ const id = first + second;
964
+ if (!used.has(id))
965
+ return id;
966
+ }
967
+ }
968
+ return "zz";
969
+ }
970
+ const ROLE_CHARS = {
971
+ 0: "p", 1: "n", 2: "b", 3: "r", 4: "q", 5: "k",
972
+ };
973
+ const PROMO_ORDER = [4, 3, 2, 1]; // Role.Queen, Role.Rook, Role.Bishop, Role.Knight
974
+ function colorName(turn) {
975
+ return turn === Color.White ? "w" : "b";
976
+ }
977
+ /** Ascending square iteration over a {lo,hi} pair. */
978
+ function* iterSet(set) {
979
+ let lo = set.lo >>> 0;
980
+ let hi = set.hi >>> 0;
981
+ while (lo !== 0) {
982
+ const lsb = (lo & -lo) >>> 0;
983
+ yield 31 - Math.clz32(lsb);
984
+ lo ^= lsb;
985
+ }
986
+ while (hi !== 0) {
987
+ const lsb = (hi & -hi) >>> 0;
988
+ yield 32 + (31 - Math.clz32(lsb));
989
+ hi ^= lsb;
990
+ }
991
+ }
992
+ /** Expands pawn back-rank destinations into the four promotions. */
993
+ function buildMoves(pos, role, from, to) {
994
+ const toRank = to >> 3;
995
+ if (role === 0 && (toRank === 7 || toRank === 0)) {
996
+ return PROMO_ORDER.map((promotion) => ({
997
+ from,
998
+ to,
999
+ promotion: promotion,
1000
+ isPromotion: true,
1001
+ isEnPassant: false,
1002
+ isCastling: false,
1003
+ }));
1004
+ }
1005
+ const isEp = role === 0 &&
1006
+ pos.epSquare !== null &&
1007
+ to === pos.epSquare &&
1008
+ (to & 7) !== (from & 7);
1009
+ const isCastling = role === 5 ? detectCastling(pos, from, to) !== null : false;
1010
+ return [{ from, to, promotion: null, isPromotion: false, isEnPassant: isEp, isCastling }];
1011
+ }
1012
+ function parseFullmove(fen) {
1013
+ const fields = fen.split(/\s+/);
1014
+ const n = Number(fields[5]);
1015
+ return Number.isFinite(n) && n > 0 ? n : 1;
1016
+ }
1017
+ /** True when a LEGAL en passant capture onto `pos.epSquare` exists. */
1018
+ function hasLegalEpCapture(pos) {
1019
+ const ep = pos.epSquare;
1020
+ if (ep === null || ep === undefined)
1021
+ return false;
1022
+ for (const [from, set] of allDests(pos)) {
1023
+ if ((from & 7) === (ep & 7))
1024
+ continue; // ep capture is diagonal
1025
+ const p = pieceAt(pos.board, from);
1026
+ if (!p || p.role !== 0)
1027
+ continue;
1028
+ for (const to of iterSet(set)) {
1029
+ if (to === ep)
1030
+ return true; // allDests is fully legal, no re-test needed
1031
+ }
1032
+ }
1033
+ return false;
1034
+ }
1035
+ /**
1036
+ * Unified root `Chess` (design D1): the chess.js-ergonomic mutable façade
1037
+ * over the immutable engine core, extended with the high-performance
1038
+ * bitboard surface, zero-alloc Zobrist hashing and 16-bit packed moves2, and
1039
+ * native tree navigation. Lives at the ROOT entrypoint so the tree-shakeable
1040
+ * `turbochess/core` graph stays free of FEN/PGN/tree facade code.
1041
+ */
1042
+ export class Chess {
1043
+ constructor(fen = INITIAL_FEN) {
1044
+ _Chess_instances.add(this);
1045
+ _Chess_startFen.set(this, void 0);
1046
+ _Chess_history.set(this, []);
1047
+ _Chess_pos.set(this, void 0);
1048
+ if (typeof fen === "string") {
1049
+ const r = parseFen(fen);
1050
+ if (!r.ok)
1051
+ throw new Error(`Invalid FEN: ${fen}`);
1052
+ __classPrivateFieldSet(this, _Chess_pos, r.value, "f");
1053
+ }
1054
+ else {
1055
+ __classPrivateFieldSet(this, _Chess_pos, fen, "f");
1056
+ }
1057
+ __classPrivateFieldSet(this, _Chess_startFen, __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, __classPrivateFieldGet(this, _Chess_pos, "f")), "f");
1058
+ }
1059
+ /** Replaces the current position (throws on an invalid FEN). */
1060
+ load(fen) {
1061
+ const r = parseFen(fen);
1062
+ if (!r.ok)
1063
+ throw new Error(`Invalid FEN: ${fen}`);
1064
+ __classPrivateFieldSet(this, _Chess_pos, r.value, "f");
1065
+ __classPrivateFieldSet(this, _Chess_startFen, __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, r.value), "f");
1066
+ __classPrivateFieldSet(this, _Chess_history, [], "f");
1067
+ }
1068
+ /** Resets to the initial position and clears history. */
1069
+ reset() {
1070
+ this.load(INITIAL_FEN);
1071
+ }
1072
+ /** Current FEN (byte-identical to the engine's makeFen modulo ep filtering). */
1073
+ fen() {
1074
+ return __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, __classPrivateFieldGet(this, _Chess_pos, "f"));
1075
+ }
1076
+ /** Side to move: "w" | "b". */
1077
+ turn() {
1078
+ return colorName(__classPrivateFieldGet(this, _Chess_pos, "f").turn);
1079
+ }
1080
+ /** Current fullmove number (starts at 1). */
1081
+ moveNumber() {
1082
+ return __classPrivateFieldGet(this, _Chess_pos, "f").fullmoves ?? __classPrivateFieldGet(this, _Chess_pos, "f").fullmove ?? 1;
1083
+ }
1084
+ /**
1085
+ * Plays a move given as SAN (tolerant: `+`/`#` suffixes, `x` on quiet moves,
1086
+ * `0-0`/`O-O`), as UCI (`e2e4`, `e7e8q`), or as a {from,to,promotion?}
1087
+ * object. Returns the verbose move, or null when the move is illegal.
1088
+ */
1089
+ move(input) {
1090
+ const pos = __classPrivateFieldGet(this, _Chess_pos, "f");
1091
+ let mv = null;
1092
+ if (typeof input === "string") {
1093
+ const sanRes = parseSan(input, pos);
1094
+ if (sanRes.ok) {
1095
+ mv = sanRes.value;
1096
+ }
1097
+ else {
1098
+ const uciRes = parseUci(input);
1099
+ if (uciRes.ok && isLegal(pos, uciRes.value))
1100
+ mv = uciRes.value;
1101
+ }
1102
+ }
1103
+ else {
1104
+ const from = parseSquare(input.from);
1105
+ const to = parseSquare(input.to);
1106
+ if (from !== undefined && to !== undefined) {
1107
+ const piece = pieceAt(pos.board, from);
1108
+ const promotion = input.promotion
1109
+ ? { q: 4, r: 3, b: 2, n: 1 }[input.promotion.toLowerCase()]
1110
+ : undefined;
1111
+ for (const cand of buildMoves(pos, piece ? piece.role : -1, from, to)) {
1112
+ if (cand.promotion !== null && cand.promotion !== undefined && promotion !== undefined && cand.promotion !== promotion)
1113
+ continue;
1114
+ if (isLegal(pos, cand)) {
1115
+ mv = cand;
1116
+ break;
1117
+ }
1118
+ }
1119
+ }
1120
+ }
1121
+ if (!mv)
1122
+ return null;
1123
+ const san = makeSan(mv, pos);
1124
+ const after = makeMove(pos, mv);
1125
+ __classPrivateFieldSet(this, _Chess_pos, after, "f");
1126
+ __classPrivateFieldGet(this, _Chess_history, "f").push({ before: pos, after, move: mv, san });
1127
+ return __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_describe).call(this, pos, mv, after, san);
1128
+ }
1129
+ moves(options) {
1130
+ const pos = __classPrivateFieldGet(this, _Chess_pos, "f");
1131
+ const out = [];
1132
+ const emit = (from, set) => {
1133
+ const piece = pieceAt(pos.board, from);
1134
+ if (!piece)
1135
+ return;
1136
+ for (const to of iterSet(set)) {
1137
+ for (const mv of buildMoves(pos, piece.role, from, to)) {
1138
+ const san = makeSan(mv, pos);
1139
+ if (options?.verbose)
1140
+ out.push(__classPrivateFieldGet(this, _Chess_instances, "m", _Chess_describe).call(this, pos, mv, makeMove(pos, mv), san));
1141
+ else
1142
+ out.push(san);
1143
+ }
1144
+ }
1145
+ };
1146
+ if (options?.square !== undefined) {
1147
+ const sqIdx = parseSquare(options.square);
1148
+ if (sqIdx === undefined)
1149
+ return [];
1150
+ emit(sqIdx, dests(pos, sqIdx));
1151
+ }
1152
+ else {
1153
+ for (const [from, set] of allDests(pos))
1154
+ emit(from, set);
1155
+ }
1156
+ return out;
1157
+ }
1158
+ history(options) {
1159
+ if (options?.verbose) {
1160
+ return __classPrivateFieldGet(this, _Chess_history, "f").map((h) => __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_describe).call(this, h.before, h.move, h.after, h.san));
1161
+ }
1162
+ return __classPrivateFieldGet(this, _Chess_history, "f").map((h) => h.san);
1163
+ }
1164
+ /** Reverts the last move; returns it in verbose shape, or null if none. */
1165
+ undo() {
1166
+ const last = __classPrivateFieldGet(this, _Chess_history, "f").pop();
1167
+ if (!last)
1168
+ return null;
1169
+ __classPrivateFieldSet(this, _Chess_pos, last.before, "f");
1170
+ return __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_describe).call(this, last.before, last.move, last.after, last.san);
1171
+ }
1172
+ isCheck() { return isCheck(__classPrivateFieldGet(this, _Chess_pos, "f")); }
1173
+ isCheckmate() { return isCheckmate(__classPrivateFieldGet(this, _Chess_pos, "f")); }
1174
+ isStalemate() { return isStalemate(__classPrivateFieldGet(this, _Chess_pos, "f")); }
1175
+ /** Draw by insufficient material, the fifty-move rule, or threefold repetition. */
1176
+ isDraw() {
1177
+ if (isInsufficientMaterial(__classPrivateFieldGet(this, _Chess_pos, "f")))
1178
+ return true;
1179
+ if (isFiftyMoveDraw(__classPrivateFieldGet(this, _Chess_pos, "f")))
1180
+ return true;
1181
+ if (isThreefoldRepetition(__classPrivateFieldGet(this, _Chess_instances, "m", _Chess_positions).call(this)))
1182
+ return true;
1183
+ return false;
1184
+ }
1185
+ /** Draw by the fifty-move rule. */
1186
+ isDrawByFiftyMoves() { return isFiftyMoveDraw(__classPrivateFieldGet(this, _Chess_pos, "f")); }
1187
+ /** Draw by insufficient material. */
1188
+ isInsufficientMaterial() { return isInsufficientMaterial(__classPrivateFieldGet(this, _Chess_pos, "f")); }
1189
+ /** Draw by threefold repetition over the game's position history. */
1190
+ isThreefoldRepetition() { return isThreefoldRepetition(__classPrivateFieldGet(this, _Chess_instances, "m", _Chess_positions).call(this)); }
1191
+ /** Game over: checkmate, stalemate, or draw. */
1192
+ isGameOver() { return this.isCheckmate() || this.isStalemate() || this.isDraw(); }
1193
+ /** Piece on a square ("e2"), or undefined. */
1194
+ get(square) {
1195
+ const sqIdx = parseSquare(square);
1196
+ if (sqIdx === undefined)
1197
+ return undefined;
1198
+ const p = pieceAt(__classPrivateFieldGet(this, _Chess_pos, "f").board, sqIdx);
1199
+ if (!p)
1200
+ return undefined;
1201
+ return { type: ROLE_CHARS[p.role], color: colorName(p.color) };
1202
+ }
1203
+ /** 8x8 board, rank 8 first; null on empty squares. */
1204
+ board() {
1205
+ const rows = [];
1206
+ for (let rank = 7; rank >= 0; rank--) {
1207
+ const row = [];
1208
+ for (let file = 0; file < 8; file++) {
1209
+ const sqIdx = rank * 8 + file;
1210
+ const p = pieceAt(__classPrivateFieldGet(this, _Chess_pos, "f").board, sqIdx);
1211
+ row.push(p ? { square: squareName(sqIdx), type: ROLE_CHARS[p.role], color: colorName(p.color) } : null);
1212
+ }
1213
+ rows.push(row);
1214
+ }
1215
+ return rows;
1216
+ }
1217
+ /** "light" | "dark" square color ("a1" is light, like the consumer baseline). */
1218
+ squareColor(square) {
1219
+ const sqIdx = parseSquare(square);
1220
+ if (sqIdx === undefined)
1221
+ return undefined;
1222
+ return (((sqIdx & 7) + (sqIdx >> 3)) & 1) === 0 ? "light" : "dark";
1223
+ }
1224
+ /** PGN: Seven Tag Roster defaults, FEN/SetUp for non-default starts, numbered movetext. */
1225
+ pgn() {
1226
+ const headers = new Map([
1227
+ ["Event", "?"],
1228
+ ["Site", "?"],
1229
+ ["Date", "????.??.??"],
1230
+ ["Round", "?"],
1231
+ ["White", "?"],
1232
+ ["Black", "?"],
1233
+ ["Result", "*"],
1234
+ ]);
1235
+ if (__classPrivateFieldGet(this, _Chess_startFen, "f") !== INITIAL_FEN) {
1236
+ headers.set("SetUp", "1");
1237
+ headers.set("FEN", __classPrivateFieldGet(this, _Chess_startFen, "f"));
1238
+ }
1239
+ let out = "";
1240
+ for (const [k, v] of headers)
1241
+ out += `[${k} "${v}"]\n`;
1242
+ out += "\n";
1243
+ out += __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_movetext).call(this);
1244
+ return out;
1245
+ }
1246
+ // ---- unified high-performance surface (design D1) ----
1247
+ /** Legal destinations for one square ("e2" or index). */
1248
+ dests(square) {
1249
+ const sqIdx = typeof square === "number" ? square : parseSquare(square);
1250
+ if (sqIdx === undefined)
1251
+ return { lo: 0, hi: 0 };
1252
+ return dests(__classPrivateFieldGet(this, _Chess_pos, "f"), sqIdx);
1253
+ }
1254
+ /** Legal destinations for every piece of the side to move. */
1255
+ allDests() { return allDests(__classPrivateFieldGet(this, _Chess_pos, "f")); }
1256
+ /** True when `move` is legal in the current position. */
1257
+ isLegal(move) { return isLegal(__classPrivateFieldGet(this, _Chess_pos, "f"), move); }
1258
+ /** Genuine recursive perft node count (no shortcuts). */
1259
+ perft(depth) { return perft(__classPrivateFieldGet(this, _Chess_pos, "f"), depth); }
1260
+ /** Applies an engine move in place (immutable core stays pure underneath). */
1261
+ play(move) {
1262
+ const san = makeSan(move, __classPrivateFieldGet(this, _Chess_pos, "f"));
1263
+ const after = makeMove(__classPrivateFieldGet(this, _Chess_pos, "f"), move);
1264
+ __classPrivateFieldSet(this, _Chess_pos, after, "f");
1265
+ __classPrivateFieldGet(this, _Chess_history, "f").push({ before: __classPrivateFieldGet(this, _Chess_pos, "f"), after, move, san });
1266
+ return this;
1267
+ }
1268
+ /** Current 64-bit Zobrist key (zero-BigInt {lo, hi} halves). */
1269
+ zobrist() {
1270
+ if (__classPrivateFieldGet(this, _Chess_pos, "f").zobristLo !== undefined && __classPrivateFieldGet(this, _Chess_pos, "f").zobristHi !== undefined) {
1271
+ return { lo: __classPrivateFieldGet(this, _Chess_pos, "f").zobristLo >>> 0, hi: __classPrivateFieldGet(this, _Chess_pos, "f").zobristHi >>> 0 };
1272
+ }
1273
+ return calculateZobrist(__classPrivateFieldGet(this, _Chess_pos, "f"));
1274
+ }
1275
+ /** Current Zobrist key as 16 zero-padded hex digits (hi first). */
1276
+ zobristHex() { return zobristHex(this.zobrist()); }
1277
+ /** Packs the game's move history into a 16-bit moves2 stream. */
1278
+ toMoves2() {
1279
+ const words = new Uint16Array(__classPrivateFieldGet(this, _Chess_history, "f").length);
1280
+ for (let i = 0; i < __classPrivateFieldGet(this, _Chess_history, "f").length; i++)
1281
+ words[i] = packOf(__classPrivateFieldGet(this, _Chess_history, "f")[i].move);
1282
+ return words;
1283
+ }
1284
+ /** Replays a moves2 stream (Uint16Array or little-endian Uint8Array) in place. */
1285
+ loadMoves2(buffer, startFen = INITIAL_FEN) {
1286
+ this.load(startFen);
1287
+ __classPrivateFieldSet(this, _Chess_startFen, startFen, "f");
1288
+ for (const mv of packedToMoves(buffer)) {
1289
+ if (!isLegal(__classPrivateFieldGet(this, _Chess_pos, "f"), mv))
1290
+ throw new Error(`moves2 replay: illegal move ${mv.from}->${mv.to}`);
1291
+ this.play(mv);
1292
+ }
1293
+ }
1294
+ /** Builds a Chess game from a moves2 stream (startpos, or a custom start FEN). */
1295
+ static fromMoves2(buffer, startFen = INITIAL_FEN) {
1296
+ const game = new Chess(startFen);
1297
+ game.loadMoves2(buffer, startFen);
1298
+ return game;
1299
+ }
1300
+ /** Wraps an arbitrary engine Setup. */
1301
+ static fromSetup(setup) {
1302
+ return new Chess(setup);
1303
+ }
1304
+ /** Fresh game from the standard initial position. */
1305
+ static default() {
1306
+ return new Chess(INITIAL_FEN);
1307
+ }
1308
+ /** FEN the game started from (for tree roots / PGN headers). */
1309
+ get startFen() { return __classPrivateFieldGet(this, _Chess_startFen, "f"); }
1310
+ /** Live engine position (read-only view over the internal state). */
1311
+ get pos() { return __classPrivateFieldGet(this, _Chess_pos, "f"); }
1312
+ /** Internal history log (read-only view; used by toTree). */
1313
+ get historyEntries() { return __classPrivateFieldGet(this, _Chess_history, "f"); }
1314
+ /**
1315
+ * Exports the live game as a chesstree wrapper: recursive variation
1316
+ * navigation (`nodeAtPath`, `getNodeList`, `addNode`, `setCommentAt`, …)
1317
+ * and full recursive PGN rendering via `tree.pgn()`.
1318
+ */
1319
+ toTree() {
1320
+ const root = { id: "", ply: 0, fen: __classPrivateFieldGet(this, _Chess_startFen, "f"), uci: "", children: [] };
1321
+ let ply = 0;
1322
+ let node = root;
1323
+ for (const h of __classPrivateFieldGet(this, _Chess_history, "f")) {
1324
+ const child = {
1325
+ id: nextTreeNodeId(node.children),
1326
+ ply: ++ply,
1327
+ san: h.san,
1328
+ fen: makeFen(h.after),
1329
+ uci: makeUci(h.move),
1330
+ children: [],
1331
+ };
1332
+ node.children.push(child);
1333
+ node = child;
1334
+ }
1335
+ return buildTreeWrapper(root);
1336
+ }
1337
+ /**
1338
+ * Imports a PGN (headers + recursive variations), loads the mainline into
1339
+ * this game, and returns the analysis tree wrapper.
1340
+ */
1341
+ loadTree(pgn) {
1342
+ const data = pgnImportData(pgn);
1343
+ const root = data.treeParts[0];
1344
+ this.reset();
1345
+ if (root && root.fen && root.fen !== INITIAL_FEN) {
1346
+ const r = parseFen(root.fen);
1347
+ if (r.ok)
1348
+ this.load(root.fen);
1349
+ }
1350
+ let node = root?.children[0];
1351
+ while (node) {
1352
+ if (node.san)
1353
+ this.move(node.san);
1354
+ node = node.children[0];
1355
+ }
1356
+ return buildTreeWrapper(root ?? { id: "", ply: 0, fen: INITIAL_FEN, uci: "", children: [] });
1357
+ }
1358
+ }
1359
+ _Chess_startFen = new WeakMap(), _Chess_history = new WeakMap(), _Chess_pos = new WeakMap(), _Chess_instances = new WeakSet(), _Chess_movetext = function _Chess_movetext() {
1360
+ const sans = __classPrivateFieldGet(this, _Chess_history, "f").map((h) => h.san);
1361
+ let fullmove = parseFullmove(__classPrivateFieldGet(this, _Chess_startFen, "f"));
1362
+ const blackToStart = __classPrivateFieldGet(this, _Chess_startFen, "f").split(/\s+/)[1] === "b";
1363
+ let s = "";
1364
+ let ply = 0;
1365
+ if (blackToStart && sans.length > 0) {
1366
+ s += `${fullmove}... ${sans[0]} `;
1367
+ ply = 1;
1368
+ fullmove++;
1369
+ }
1370
+ while (ply < sans.length) {
1371
+ s += `${fullmove}. ${sans[ply]} `;
1372
+ ply++;
1373
+ if (ply < sans.length) {
1374
+ s += `${sans[ply]} `;
1375
+ ply++;
1376
+ }
1377
+ fullmove++;
1378
+ }
1379
+ s = s.trimEnd();
1380
+ return s + (s ? " " : "") + "*";
1381
+ }, _Chess_positions = function _Chess_positions() {
1382
+ const out = [];
1383
+ if (__classPrivateFieldGet(this, _Chess_history, "f").length > 0)
1384
+ out.push(__classPrivateFieldGet(this, _Chess_history, "f")[0].before);
1385
+ for (const h of __classPrivateFieldGet(this, _Chess_history, "f"))
1386
+ out.push(h.after);
1387
+ return out;
1388
+ }, _Chess_describe = function _Chess_describe(pos, mv, after, san) {
1389
+ const piece = pieceAt(pos.board, mv.from);
1390
+ if (!piece)
1391
+ throw new Error("corrupt move: missing origin piece");
1392
+ const target = pieceAt(pos.board, mv.to);
1393
+ const isEp = !!mv.isEnPassant ||
1394
+ (piece.role === 0 && pos.epSquare !== null && mv.to === pos.epSquare && (mv.to & 7) !== (mv.from & 7));
1395
+ const isCapture = !!target && target.color !== pos.turn && !isEp;
1396
+ const isDoublePush = piece.role === 0 && Math.abs((mv.to >> 3) - (mv.from >> 3)) === 2;
1397
+ let castlingKingside = null;
1398
+ if (mv.isCastling) {
1399
+ const plan = detectCastling(pos, mv.from, mv.to);
1400
+ castlingKingside = plan ? plan.side === "king" : (mv.to & 7) === 6;
1401
+ }
1402
+ // Baseline flag semantics: castling is exclusively "k"/"q"; otherwise one
1403
+ // base flag — "e" (en passant), "c" (capture), "b" (double pawn push) or
1404
+ // "n" (quiet) — plus "p" appended for promotions ("np"/"cp").
1405
+ const flags = [];
1406
+ if (castlingKingside !== null) {
1407
+ flags.push(castlingKingside ? "k" : "q");
1408
+ }
1409
+ else {
1410
+ if (isEp)
1411
+ flags.push("e");
1412
+ else if (isCapture)
1413
+ flags.push("c");
1414
+ else if (isDoublePush)
1415
+ flags.push("b");
1416
+ else
1417
+ flags.push("n");
1418
+ if (mv.promotion)
1419
+ flags.push("p");
1420
+ }
1421
+ // consumer-baseline parity: castling reports the king's landing square
1422
+ // ("e1g1") for both `to` and `lan`, not the engine's rook-capture form
1423
+ const landingSq = castlingKingside !== null ? (mv.from >> 3) * 8 + (castlingKingside ? 6 : 2) : null;
1424
+ const lan = landingSq !== null ? squareName(mv.from) + squareName(landingSq) : makeUci(mv);
1425
+ const out = {
1426
+ color: colorName(pos.turn),
1427
+ from: squareName(mv.from),
1428
+ to: landingSq !== null ? squareName(landingSq) : squareName(mv.to),
1429
+ piece: ROLE_CHARS[piece.role],
1430
+ flags: flags.join(""),
1431
+ san,
1432
+ lan,
1433
+ before: __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, pos),
1434
+ after: __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, after),
1435
+ };
1436
+ if (isCapture || isEp)
1437
+ out.captured = isEp || !target ? "p" : ROLE_CHARS[target.role];
1438
+ if (mv.promotion)
1439
+ out.promotion = ROLE_CHARS[mv.promotion];
1440
+ return out;
1441
+ }, _Chess_fenOf = function _Chess_fenOf(pos) {
1442
+ const fen = makeFen(pos);
1443
+ const ep = pos.epSquare;
1444
+ if (ep === null || ep === undefined)
1445
+ return fen;
1446
+ const fields = fen.split(" ");
1447
+ if (fields[3] !== squareName(ep))
1448
+ return fen; // engine already suppressed it
1449
+ if (!hasLegalEpCapture(pos)) {
1450
+ fields[3] = "-";
1451
+ }
1452
+ return fields.join(" ");
1453
+ };