gigaboard 1.3.3 → 1.4.0

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.
@@ -109,12 +109,34 @@ declare function pieceTypeOf(cell: BoardCell): PieceType;
109
109
  * Optional text label rendered alongside an arrow. Positioned at the
110
110
  * endpoint by default; use `ArrowShape["labelCenter"]` to anchor it on
111
111
  * `"orig"` (source square) or at the arrow's midpoint instead.
112
+ *
113
+ * When `background` is set the renderer draws an opaque rounded pill
114
+ * behind the glyph (engine eval bubbles). The pill — background AND
115
+ * glyph — always renders at full opacity, never faded with the arrow.
112
116
  */
113
117
  interface ArrowLabel {
114
118
  readonly text: string;
115
119
  /** CSS color for the label glyph. Defaults to the arrow's `color`. */
116
120
  readonly fill?: string;
121
+ /** CSS color for the pill background. Unset = bare text (legacy). */
122
+ readonly background?: string;
123
+ /** Label font size in viewBox units. Defaults to the renderer default. */
124
+ readonly fontSize?: number;
125
+ /**
126
+ * Anchor point for the label. Default `"label"` (midpoint).
127
+ * `"dest"` anchors near the arrowhead; `"orig"` near the source square.
128
+ */
129
+ readonly anchor?: "orig" | "dest" | "label";
130
+ /** Optional stroke/border color for the pointer head capsule. */
131
+ readonly borderColor?: string;
132
+ /** Pointing head geometry style (default "aero_chisel"). */
133
+ readonly headStyle?: "aero_chisel" | "chamfer_arrow" | "blunt_wedge" | "stealth" | "bullet" | "hex" | "needle" | "notch";
134
+ /** Text rotation mode along arrow axis: "auto" (default: flips 180° when left-facing), "strict", or "flat". */
135
+ readonly textRotation?: "auto" | "strict" | "flat";
136
+ /** Enable tactile 3D faceted lighting and cylindrical shaft relief (default true when headStyle is "stealth"). */
137
+ readonly style3d?: boolean;
117
138
  }
139
+ type ArrowHeadStyle = NonNullable<ArrowLabel["headStyle"]>;
118
140
  /**
119
141
  * Arbitrary inline SVG payload rendered on top of the canvas overlay.
120
142
  * `html` is injected into an `<svg>` group as a `foreignObject`-free
@@ -167,6 +189,12 @@ interface Arrow {
167
189
  * (analysis boards, pawn-structure overlays).
168
190
  */
169
191
  readonly below?: boolean;
192
+ /**
193
+ * When `true`, enables split-Z rendering for arrows with integrated pointing heads:
194
+ * the shaft renders beneath pieces (`below`), while the arrowhead and evaluation
195
+ * capsule render on top of pieces (`above`).
196
+ */
197
+ readonly splitZ?: boolean;
170
198
  /**
171
199
  * Marks an arrow as owned by the application rather than the user.
172
200
  * "Managed" arrows survive the two reflex-clearing hooks
@@ -672,4 +700,4 @@ interface BoardModel {
672
700
  */
673
701
  declare function createBoardModel(engine: EngineAdapter, options?: BoardModelOptions): BoardModel;
674
702
 
675
- export { createDragController as $, type AnimDescriptor as A, BOARD_CELL_BB as B, type CancelEvent as C, type DragController as D, type EngineAdapter as E, type DragControllerOptions as F, type DragEvent as G, type DragMoveEvent as H, type DragStartEvent as I, type DragState as J, type DropEvent as K, type LegalMoveEntry as L, type LegalMoveIndex as M, type LegalMoveIndexOptions as N, MOVE2_PROMO_BISHOP as O, type PackedMove as P, MOVE2_PROMO_KNIGHT as Q, MOVE2_PROMO_NONE as R, type SquareIndex as S, MOVE2_PROMO_QUEEN as T, MOVE2_PROMO_ROOK as U, type PositionHash as V, type SyncPositionOptions as W, type Unsubscribe as X, createBoardModel as Y, type ZobristKey as Z, createBoardStore as _, PieceType as a, createLegalMoveIndex as a0, encodeBoardCell as a1, isEmptyCell as a2, isSquareIndex as a3, packMove as a4, toSquareIndex as a5, unpackMove as a6, writeBoardCell as a7, type Arrow as b, colorOf as c, type Premove as d, type ArrowCustomSvg as e, type ArrowLabel as f, BOARD_CELL_BK as g, BOARD_CELL_BN as h, BOARD_CELL_BP as i, BOARD_CELL_BQ as j, BOARD_CELL_BR as k, BOARD_CELL_EMPTY as l, BOARD_CELL_WB as m, BOARD_CELL_WK as n, BOARD_CELL_WN as o, pieceTypeOf as p, BOARD_CELL_WP as q, BOARD_CELL_WQ as r, BOARD_CELL_WR as s, type BoardCell as t, type BoardModel as u, type BoardModelOptions as v, type BoardSnapshot as w, type BoardStore as x, type ClickEvent as y, Color as z };
703
+ export { createBoardStore as $, type AnimDescriptor as A, BOARD_CELL_BB as B, type CancelEvent as C, Color as D, type EngineAdapter as E, type DragController as F, type DragControllerOptions as G, type DragEvent as H, type DragMoveEvent as I, type DragStartEvent as J, type DragState as K, type DropEvent as L, type LegalMoveEntry as M, type LegalMoveIndex as N, type LegalMoveIndexOptions as O, type PackedMove as P, MOVE2_PROMO_BISHOP as Q, MOVE2_PROMO_KNIGHT as R, type SquareIndex as S, MOVE2_PROMO_NONE as T, MOVE2_PROMO_QUEEN as U, MOVE2_PROMO_ROOK as V, type PositionHash as W, type SyncPositionOptions as X, type Unsubscribe as Y, type ZobristKey as Z, createBoardModel as _, PieceType as a, createDragController as a0, createLegalMoveIndex as a1, encodeBoardCell as a2, isEmptyCell as a3, isSquareIndex as a4, packMove as a5, toSquareIndex as a6, unpackMove as a7, writeBoardCell as a8, type Arrow as b, colorOf as c, type Premove as d, type ArrowCustomSvg as e, type ArrowHeadStyle as f, type ArrowLabel as g, BOARD_CELL_BK as h, BOARD_CELL_BN as i, BOARD_CELL_BP as j, BOARD_CELL_BQ as k, BOARD_CELL_BR as l, BOARD_CELL_EMPTY as m, BOARD_CELL_WB as n, BOARD_CELL_WK as o, pieceTypeOf as p, BOARD_CELL_WN as q, BOARD_CELL_WP as r, BOARD_CELL_WQ as s, BOARD_CELL_WR as t, type BoardCell as u, type BoardModel as v, type BoardModelOptions as w, type BoardSnapshot as x, type BoardStore as y, type ClickEvent as z };
@@ -109,12 +109,34 @@ declare function pieceTypeOf(cell: BoardCell): PieceType;
109
109
  * Optional text label rendered alongside an arrow. Positioned at the
110
110
  * endpoint by default; use `ArrowShape["labelCenter"]` to anchor it on
111
111
  * `"orig"` (source square) or at the arrow's midpoint instead.
112
+ *
113
+ * When `background` is set the renderer draws an opaque rounded pill
114
+ * behind the glyph (engine eval bubbles). The pill — background AND
115
+ * glyph — always renders at full opacity, never faded with the arrow.
112
116
  */
113
117
  interface ArrowLabel {
114
118
  readonly text: string;
115
119
  /** CSS color for the label glyph. Defaults to the arrow's `color`. */
116
120
  readonly fill?: string;
121
+ /** CSS color for the pill background. Unset = bare text (legacy). */
122
+ readonly background?: string;
123
+ /** Label font size in viewBox units. Defaults to the renderer default. */
124
+ readonly fontSize?: number;
125
+ /**
126
+ * Anchor point for the label. Default `"label"` (midpoint).
127
+ * `"dest"` anchors near the arrowhead; `"orig"` near the source square.
128
+ */
129
+ readonly anchor?: "orig" | "dest" | "label";
130
+ /** Optional stroke/border color for the pointer head capsule. */
131
+ readonly borderColor?: string;
132
+ /** Pointing head geometry style (default "aero_chisel"). */
133
+ readonly headStyle?: "aero_chisel" | "chamfer_arrow" | "blunt_wedge" | "stealth" | "bullet" | "hex" | "needle" | "notch";
134
+ /** Text rotation mode along arrow axis: "auto" (default: flips 180° when left-facing), "strict", or "flat". */
135
+ readonly textRotation?: "auto" | "strict" | "flat";
136
+ /** Enable tactile 3D faceted lighting and cylindrical shaft relief (default true when headStyle is "stealth"). */
137
+ readonly style3d?: boolean;
117
138
  }
139
+ type ArrowHeadStyle = NonNullable<ArrowLabel["headStyle"]>;
118
140
  /**
119
141
  * Arbitrary inline SVG payload rendered on top of the canvas overlay.
120
142
  * `html` is injected into an `<svg>` group as a `foreignObject`-free
@@ -167,6 +189,12 @@ interface Arrow {
167
189
  * (analysis boards, pawn-structure overlays).
168
190
  */
169
191
  readonly below?: boolean;
192
+ /**
193
+ * When `true`, enables split-Z rendering for arrows with integrated pointing heads:
194
+ * the shaft renders beneath pieces (`below`), while the arrowhead and evaluation
195
+ * capsule render on top of pieces (`above`).
196
+ */
197
+ readonly splitZ?: boolean;
170
198
  /**
171
199
  * Marks an arrow as owned by the application rather than the user.
172
200
  * "Managed" arrows survive the two reflex-clearing hooks
@@ -672,4 +700,4 @@ interface BoardModel {
672
700
  */
673
701
  declare function createBoardModel(engine: EngineAdapter, options?: BoardModelOptions): BoardModel;
674
702
 
675
- export { createDragController as $, type AnimDescriptor as A, BOARD_CELL_BB as B, type CancelEvent as C, type DragController as D, type EngineAdapter as E, type DragControllerOptions as F, type DragEvent as G, type DragMoveEvent as H, type DragStartEvent as I, type DragState as J, type DropEvent as K, type LegalMoveEntry as L, type LegalMoveIndex as M, type LegalMoveIndexOptions as N, MOVE2_PROMO_BISHOP as O, type PackedMove as P, MOVE2_PROMO_KNIGHT as Q, MOVE2_PROMO_NONE as R, type SquareIndex as S, MOVE2_PROMO_QUEEN as T, MOVE2_PROMO_ROOK as U, type PositionHash as V, type SyncPositionOptions as W, type Unsubscribe as X, createBoardModel as Y, type ZobristKey as Z, createBoardStore as _, PieceType as a, createLegalMoveIndex as a0, encodeBoardCell as a1, isEmptyCell as a2, isSquareIndex as a3, packMove as a4, toSquareIndex as a5, unpackMove as a6, writeBoardCell as a7, type Arrow as b, colorOf as c, type Premove as d, type ArrowCustomSvg as e, type ArrowLabel as f, BOARD_CELL_BK as g, BOARD_CELL_BN as h, BOARD_CELL_BP as i, BOARD_CELL_BQ as j, BOARD_CELL_BR as k, BOARD_CELL_EMPTY as l, BOARD_CELL_WB as m, BOARD_CELL_WK as n, BOARD_CELL_WN as o, pieceTypeOf as p, BOARD_CELL_WP as q, BOARD_CELL_WQ as r, BOARD_CELL_WR as s, type BoardCell as t, type BoardModel as u, type BoardModelOptions as v, type BoardSnapshot as w, type BoardStore as x, type ClickEvent as y, Color as z };
703
+ export { createBoardStore as $, type AnimDescriptor as A, BOARD_CELL_BB as B, type CancelEvent as C, Color as D, type EngineAdapter as E, type DragController as F, type DragControllerOptions as G, type DragEvent as H, type DragMoveEvent as I, type DragStartEvent as J, type DragState as K, type DropEvent as L, type LegalMoveEntry as M, type LegalMoveIndex as N, type LegalMoveIndexOptions as O, type PackedMove as P, MOVE2_PROMO_BISHOP as Q, MOVE2_PROMO_KNIGHT as R, type SquareIndex as S, MOVE2_PROMO_NONE as T, MOVE2_PROMO_QUEEN as U, MOVE2_PROMO_ROOK as V, type PositionHash as W, type SyncPositionOptions as X, type Unsubscribe as Y, type ZobristKey as Z, createBoardModel as _, PieceType as a, createDragController as a0, createLegalMoveIndex as a1, encodeBoardCell as a2, isEmptyCell as a3, isSquareIndex as a4, packMove as a5, toSquareIndex as a6, unpackMove as a7, writeBoardCell as a8, type Arrow as b, colorOf as c, type Premove as d, type ArrowCustomSvg as e, type ArrowHeadStyle as f, type ArrowLabel as g, BOARD_CELL_BK as h, BOARD_CELL_BN as i, BOARD_CELL_BP as j, BOARD_CELL_BQ as k, BOARD_CELL_BR as l, BOARD_CELL_EMPTY as m, BOARD_CELL_WB as n, BOARD_CELL_WK as o, pieceTypeOf as p, BOARD_CELL_WN as q, BOARD_CELL_WP as r, BOARD_CELL_WQ as s, BOARD_CELL_WR as t, type BoardCell as u, type BoardModel as v, type BoardModelOptions as w, type BoardSnapshot as x, type BoardStore as y, type ClickEvent as z };
@@ -46,7 +46,7 @@ var BOARD_CELL_BR = 10;
46
46
  var BOARD_CELL_BQ = 11;
47
47
  var BOARD_CELL_BK = 12;
48
48
  function toSquareIndex(n) {
49
- if (process.env["NODE_ENV"] !== "production") {
49
+ if (typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production") {
50
50
  if (!Number.isInteger(n) || n < 0 || n > 63) {
51
51
  throw new RangeError(`SquareIndex out of range: ${n}`);
52
52
  }
@@ -178,7 +178,7 @@ function createGigachessAdapter(fen) {
178
178
  return out;
179
179
  };
180
180
  const readBoard = (out) => {
181
- if (process.env["NODE_ENV"] !== "production") {
181
+ if (typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production") {
182
182
  if (out.length !== 64) {
183
183
  throw new RangeError("readBoard: out.length must be 64");
184
184
  }
@@ -236,7 +236,7 @@ var PROMO_PIECE = [
236
236
  PieceType.Queen
237
237
  ];
238
238
  function planAnimations(prev, next, move) {
239
- if (process.env["NODE_ENV"] !== "production") {
239
+ if (typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production") {
240
240
  if (prev.length !== 64 || next.length !== 64) {
241
241
  throw new RangeError("planAnimations: board buffers must be length 64");
242
242
  }
@@ -726,7 +726,8 @@ var EMPTY_SET = Object.freeze(
726
726
  function moveTo(m) {
727
727
  return m >> 6 & 63;
728
728
  }
729
- function normalizeCastlingTarget(from, to) {
729
+ function normalizeCastlingTarget(from, to, isKing) {
730
+ if (!isKing) return to;
730
731
  if (from === 4) {
731
732
  if (to === 6) return 7;
732
733
  if (to === 2) return 0;
@@ -753,6 +754,11 @@ function createBoardModel(engine, options = {}) {
753
754
  engine.readBoard(stageBuffer);
754
755
  return new Uint8Array(stageBuffer);
755
756
  };
757
+ const isKingOn = (sq) => {
758
+ engine.readBoard(stageBuffer);
759
+ const cell = stageBuffer[sq];
760
+ return cell === BOARD_CELL_WK || cell === BOARD_CELL_BK;
761
+ };
756
762
  const computeLegalTargets = (fromBoard) => {
757
763
  if (selected === null) return EMPTY_SET;
758
764
  const pieceOnSquare = fromBoard[selected];
@@ -826,7 +832,7 @@ function createBoardModel(engine, options = {}) {
826
832
  commitWith(null);
827
833
  };
828
834
  const tryMove = (from, to, promotion) => {
829
- const resolvedTo = normalizeCastlingTarget(from, to);
835
+ const resolvedTo = normalizeCastlingTarget(from, to, isKingOn(from));
830
836
  let m = engine.makeMove(from, resolvedTo, promotion);
831
837
  if (m === null && resolvedTo !== to) {
832
838
  m = engine.makeMove(from, to, promotion);
@@ -953,7 +959,7 @@ function createBoardModel(engine, options = {}) {
953
959
  commitWith(null);
954
960
  };
955
961
  const isLegal = (from, to, promotion) => {
956
- const resolvedTo = normalizeCastlingTarget(from, to);
962
+ const resolvedTo = normalizeCastlingTarget(from, to, isKingOn(from));
957
963
  const hash = engine.hash();
958
964
  const cached = legalMoveIndex.get(hash, from);
959
965
  if (cached !== void 0 && promotion === void 0) {
@@ -1100,5 +1106,5 @@ function writeBoardCell(out, index, cell) {
1100
1106
  var PACKAGE_VERSION = "1.3.3";
1101
1107
 
1102
1108
  export { BOARD_CELL_BB, BOARD_CELL_BK, BOARD_CELL_BN, BOARD_CELL_BP, BOARD_CELL_BQ, BOARD_CELL_BR, BOARD_CELL_EMPTY, BOARD_CELL_WB, BOARD_CELL_WK, BOARD_CELL_WN, BOARD_CELL_WP, BOARD_CELL_WQ, BOARD_CELL_WR, Color, MOVE2_PROMO_BISHOP, MOVE2_PROMO_KNIGHT, MOVE2_PROMO_NONE, MOVE2_PROMO_QUEEN, MOVE2_PROMO_ROOK, PACKAGE_VERSION, PieceType, animationInspect, colorOf, createArrowModel, createBoardModel, createBoardStore, createDragController, createGigachessAdapter, createLegalMoveIndex, createPremoveBuffer, decodePackedMove, encodeBoardCell, isEmptyCell, isSquareIndex, makeArrow, makePremove, packMove, pieceTypeOf, planAnimations, preloadGigachessAdapter, toSquareIndex, unpackMove, writeBoardCell };
1103
- //# sourceMappingURL=chunk-BB54XFHQ.js.map
1104
- //# sourceMappingURL=chunk-BB54XFHQ.js.map
1109
+ //# sourceMappingURL=chunk-BNJKX6K7.js.map
1110
+ //# sourceMappingURL=chunk-BNJKX6K7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/types.ts","../src/core/adapters/gigachess.ts","../src/core/animation-planner.ts","../src/core/arrow-model.ts","../src/core/drag-controller.ts","../src/core/legal-move-index.ts","../src/core/premove-buffer.ts","../src/core/subscribe-store.ts","../src/core/board-model.ts","../src/core/engine-adapter.ts","../src/core/index.ts"],"names":["remove","event"],"mappings":";;;;;;AA0BO,IAAM,gBAAA,GAAmB;AACzB,IAAM,kBAAA,GAAqB;AAC3B,IAAM,kBAAA,GAAqB;AAC3B,IAAM,gBAAA,GAAmB;AACzB,IAAM,iBAAA,GAAoB;AAK1B,SAAS,QAAA,CAAS,IAAA,EAAc,EAAA,EAAY,KAAA,GAAQ,gBAAA,EAA8B;AACvF,EAAA,OAAA,CAAU,OAAO,EAAA,GAAA,CAAU,EAAA,GAAK,OAAS,CAAA,GAAA,CAAO,KAAA,GAAQ,OAAS,EAAA,IAAO,KAAA;AAC1E;AAKO,SAAS,WAAW,IAAA,EAIzB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AAA,CAAM,WAAA,EAAY;AAAA,IACrC,SAAA,EAAW,CAAC,CAAA,KAAM,KAAA,CAAM,UAAU,CAAC,CAAA;AAAA,IACnC,iBAAiB,CAAC,CAAA,EAAG,MAAM,KAAA,CAAM,eAAA,CAAgB,GAAG,CAAC,CAAA;AAAA,IAErD,YAAA;AAAA,IACA,OAAA;AAAA,IACA,IAAA;AAAA,IACA,IAAA;AAAA,IACA,IAAA;AAAA,IACA,IAAA;AAAA,IACA,YAAA;AAAA,IACA,KAAA;AAAA,IAEA,OAAA;AAAA,IACA,SAAA;AAAA,IAEA,QAAA;AAAA,IACA,WAAA;AAAA,IACA,WAAA;AAAA,IACA,WAAA;AAAA,IACA,eAAA;AAAA,IACA,kBAAA;AAAA,IACA,SAAA;AAAA,IACA,gBAAA;AAAA,IAEA,YAAA;AAAA,IACA,aAAA;AAAA,IAEA,IAAA;AAAA,IACA,cAAA,EAAgB,cAAA;AAAA,IAChB,MAAA;AAAA,IACA,IAAI,cAAA,GAAiB;AACnB,MAAA,OAAO,cAAA;AAAA,IACT,CAAA;AAAA,IAEA;AAAA,GACF;AACF;;;AC/hBO,SAAS,cAAA,CAAe,GAAA,EAAiB,KAAA,EAAoB,IAAA,EAAuB;AACzF,EAAA,GAAA,CAAI,KAAK,CAAA,GAAI,IAAA;AACf;;;ACUO,IAAM,eAAA,GAAkB","file":"chunk-BNJKX6K7.js","sourcesContent":["/**\n * Public types and branded primitives for `gigaboard/core`.\n *\n * Design goals:\n * - Primitives carry their meaning in the type (`SquareIndex` never silently\n * mixes with a piece code or a file number).\n * - Encoding of a board cell is a single byte suitable for `Uint8Array(64)`.\n * - Every symbol exported here is a type or a zero-cost helper — no classes,\n * no allocations per call, nothing that would eat into the budget.\n */\n\n/**\n * A square on the board, in LERF indexing: `0 = a1`, `7 = h1`, `56 = a8`,\n * `63 = h8`. Aligned with standard 0..63 square indexing.\n */\nexport type SquareIndex = number & { readonly __brand: \"SquareIndex\" };\n\n/**\n * A packed u16 move conforming to the 16-bit Move2 wire format:\n * bits 0–5: from square index (0..63)\n * bits 6–11: to square index (0..63)\n * bits 12–15: promotion code (0 = none, 1 = Knight, 2 = Bishop, 3 = Rook, 4 = Queen).\n */\nexport type PackedMove = number & { readonly __brand: \"PackedMove\" };\n\n/** Move2 promotion codes */\nexport const MOVE2_PROMO_NONE = 0;\nexport const MOVE2_PROMO_KNIGHT = 1;\nexport const MOVE2_PROMO_BISHOP = 2;\nexport const MOVE2_PROMO_ROOK = 3;\nexport const MOVE2_PROMO_QUEEN = 4;\n\n/**\n * Packs from/to/promo into one 16-bit Move2 word.\n */\nexport function packMove(from: number, to: number, promo = MOVE2_PROMO_NONE): PackedMove {\n return (((from & 0x3f) | ((to & 0x3f) << 6) | ((promo & 0x0f) << 12)) & 0xffff) as PackedMove;\n}\n\n/**\n * Unpacks a 16-bit Move2 word into its from/to/promo fields.\n */\nexport function unpackMove(move: PackedMove | number): {\n from: SquareIndex;\n to: SquareIndex;\n promo: number;\n} {\n const w = (move as number) & 0xffff;\n return {\n from: (w & 0x3f) as SquareIndex,\n to: ((w >>> 6) & 0x3f) as SquareIndex,\n promo: (w >>> 12) & 0x0f,\n };\n}\n\n/**\n * 64-bit Zobrist key represented as two 32-bit unsigned integers (zero-BigInt).\n */\nexport type ZobristKey = {\n readonly lo: number;\n readonly hi: number;\n};\n\n/**\n * A single byte representing one square of the board. `0` is empty; values\n * `1..12` encode a piece. The encoding is a stable contract: consumers may\n * rely on `BOARD_CELL_*` constants (below) instead of remembering numbers.\n */\nexport type BoardCell = number & { readonly __brand: \"BoardCell\" };\n\n/** Piece color (White = 0, Black = 1). */\nexport const Color = {\n White: 0,\n Black: 1,\n} as const;\n/** Colour value. */\nexport type Color = (typeof Color)[keyof typeof Color];\n\n/** Piece type (0 = Pawn .. 5 = King). */\nexport const PieceType = {\n Pawn: 0,\n Knight: 1,\n Bishop: 2,\n Rook: 3,\n Queen: 4,\n King: 5,\n} as const;\n/** Piece-type value (0 = Pawn .. 5 = King). */\nexport type PieceType = (typeof PieceType)[keyof typeof PieceType];\n\n/** Board-cell constants for readability at call sites. */\nexport const BOARD_CELL_EMPTY = 0 as BoardCell;\nexport const BOARD_CELL_WP = 1 as BoardCell;\nexport const BOARD_CELL_WN = 2 as BoardCell;\nexport const BOARD_CELL_WB = 3 as BoardCell;\nexport const BOARD_CELL_WR = 4 as BoardCell;\nexport const BOARD_CELL_WQ = 5 as BoardCell;\nexport const BOARD_CELL_WK = 6 as BoardCell;\nexport const BOARD_CELL_BP = 7 as BoardCell;\nexport const BOARD_CELL_BN = 8 as BoardCell;\nexport const BOARD_CELL_BB = 9 as BoardCell;\nexport const BOARD_CELL_BR = 10 as BoardCell;\nexport const BOARD_CELL_BQ = 11 as BoardCell;\nexport const BOARD_CELL_BK = 12 as BoardCell;\n\n/** Narrow a number into a `SquareIndex`. Validates in dev, no-op at runtime. */\nexport function toSquareIndex(n: number): SquareIndex {\n if (typeof process !== \"undefined\" && process.env?.[\"NODE_ENV\"] !== \"production\") {\n if (!Number.isInteger(n) || n < 0 || n > 63) {\n throw new RangeError(`SquareIndex out of range: ${n}`);\n }\n }\n return n as SquareIndex;\n}\n\n/** Type-guard: is `n` a valid square index? */\nexport function isSquareIndex(n: number): n is SquareIndex {\n return Number.isInteger(n) && n >= 0 && n <= 63;\n}\n\n/**\n * Pack a `(color, type)` pair into a `BoardCell`.\n *\n * @remarks Inlined constant arithmetic — stays zero-allocation.\n */\nexport function encodeBoardCell(color: Color, type: PieceType): BoardCell {\n return (1 + type + color * 6) as BoardCell;\n}\n\n/** `true` if the cell is empty. */\nexport function isEmptyCell(cell: BoardCell): boolean {\n return cell === 0;\n}\n\n/** Extract the color from a non-empty `BoardCell`. Undefined for empty cells. */\nexport function colorOf(cell: BoardCell): Color {\n return (cell > 6 ? 1 : 0) as Color;\n}\n\n/** Extract the piece type from a non-empty `BoardCell`. Undefined for empty. */\nexport function pieceTypeOf(cell: BoardCell): PieceType {\n return ((cell - 1) % 6) as PieceType;\n}\n\n/**\n * Optional text label rendered alongside an arrow. Positioned at the\n * endpoint by default; use `ArrowShape[\"labelCenter\"]` to anchor it on\n * `\"orig\"` (source square) or at the arrow's midpoint instead.\n *\n * When `background` is set the renderer draws an opaque rounded pill\n * behind the glyph (engine eval bubbles). The pill — background AND\n * glyph — always renders at full opacity, never faded with the arrow.\n */\nexport interface ArrowLabel {\n readonly text: string;\n /** CSS color for the label glyph. Defaults to the arrow's `color`. */\n readonly fill?: string;\n /** CSS color for the pill background. Unset = bare text (legacy). */\n readonly background?: string;\n /** Label font size in viewBox units. Defaults to the renderer default. */\n readonly fontSize?: number;\n /**\n * Anchor point for the label. Default `\"label\"` (midpoint).\n * `\"dest\"` anchors near the arrowhead; `\"orig\"` near the source square.\n */\n readonly anchor?: \"orig\" | \"dest\" | \"label\";\n /** Optional stroke/border color for the pointer head capsule. */\n readonly borderColor?: string;\n /** Pointing head geometry style (default \"aero_chisel\"). */\n readonly headStyle?:\n | \"aero_chisel\"\n | \"chamfer_arrow\"\n | \"blunt_wedge\"\n | \"stealth\"\n | \"bullet\"\n | \"hex\"\n | \"needle\"\n | \"notch\";\n /** Text rotation mode along arrow axis: \"auto\" (default: flips 180° when left-facing), \"strict\", or \"flat\". */\n readonly textRotation?: \"auto\" | \"strict\" | \"flat\";\n /** Enable tactile 3D faceted lighting and cylindrical shaft relief (default true when headStyle is \"stealth\"). */\n readonly style3d?: boolean;\n}\n\nexport type ArrowHeadStyle = NonNullable<ArrowLabel[\"headStyle\"]>;\n\n/**\n * Arbitrary inline SVG payload rendered on top of the canvas overlay.\n * `html` is injected into an `<svg>` group as a `foreignObject`-free\n * child so downstream CSS animations and `stroke-dasharray` tricks\n * work as-is. The renderer never parses or sanitises the string —\n * consumers are responsible for trusting the source. Typical uses:\n * - Stockfish best-move numerals (\"+1.2\", \"♔\")\n * - Coach annotations (stars, exclamations, `!!`/`??`)\n * - Custom variation markers\n */\nexport interface ArrowCustomSvg {\n /** SVG fragment injected as-is. Must be safe markup — no sanitisation. */\n readonly html: string;\n /**\n * Anchor point for the fragment. Default `\"dest\"`. `\"orig\"` is useful\n * for same-square marks (circles); `\"label\"` centres on the midpoint.\n */\n readonly center?: \"orig\" | \"dest\" | \"label\";\n}\n\n/**\n * An on-board arrow annotation. Identity is the tuple\n * `(from, to, color, brush, label.text, customSvg.html, below)` — two\n * arrows that agree on every field are considered equal.\n *\n * @remarks\n * The original `(from, to, color)` identity is preserved: any arrow\n * that doesn't carry the optional decorations behaves exactly as in\n * M1. Additive-only extension.\n */\nexport interface Arrow {\n readonly from: SquareIndex;\n readonly to: SquareIndex;\n /** Any CSS-legal color string. Common values: `\"green\"`, `\"red\"`, `\"blue\"`. */\n readonly color: string;\n /**\n * Optional palette key that lets the renderer resolve the arrow's\n * visual style (colour, stroke width, opacity) from a user-supplied\n * `ArrowColors` map at draw time. When absent, `color` is used as-is\n * and the modifier-key channels (`default`/`shift`/`alt`/`ctrl`)\n * continue to work.\n */\n readonly brush?: string;\n /** Optional text label. See {@link ArrowLabel}. */\n readonly label?: ArrowLabel;\n /** Optional custom SVG payload. See {@link ArrowCustomSvg}. */\n readonly customSvg?: ArrowCustomSvg;\n /**\n * When `true`, the arrow renders **beneath** the piece layer instead\n * of on top. Useful for \"heatmap\" tints that shouldn't occlude pieces\n * (analysis boards, pawn-structure overlays).\n */\n readonly below?: boolean;\n /**\n * When `true`, enables split-Z rendering for arrows with integrated pointing heads:\n * the shaft renders beneath pieces (`below`), while the arrowhead and evaluation\n * capsule render on top of pieces (`above`).\n */\n readonly splitZ?: boolean;\n /**\n * Marks an arrow as owned by the application rather than the user.\n * \"Managed\" arrows survive the two reflex-clearing hooks\n * (`clearArrowsOnClick`, `clearArrowsOnMove`) — the idiomatic use-case\n * is an engine best-move hint on an analysis board, where the hint\n * should update when the position changes but ignore the user's\n * click-to-dismiss gesture on the board.\n *\n * User-drawn arrows (right-click gesture) always land with\n * `managed: false`; programmatic callers opt in explicitly.\n *\n * A nuclear `model.clearArrows()` still wipes managed arrows —\n * consumers who want a stricter partition call `clearUserArrows()`\n * instead. Default `false` (unset).\n */\n readonly managed?: boolean;\n}\n\n/** A queued premove awaiting the opponent's reply. */\nexport interface Premove {\n readonly from: SquareIndex;\n readonly to: SquareIndex;\n readonly promotion?: PieceType;\n}\n\n/**\n * Immutable snapshot of the board at a single instant. Produced by the store\n * on every commit; never mutated. React's `useSyncExternalStore` relies on\n * referential equality here — a new snapshot object is emitted per commit,\n * but bytes of `board` that didn't change share values with the previous one\n * (read as primitives), so per-square subscribers skip untouched squares.\n */\nexport interface BoardSnapshot {\n /** 64-byte board, LERF-indexed. See {@link BoardCell}. */\n readonly board: Readonly<Uint8Array>;\n /** Side to move. */\n readonly turn: Color;\n /** Zobrist hash of the position (from the engine). */\n readonly hash: ZobristKey | bigint;\n /** The packed move that produced this position, or `null` for the initial. */\n readonly lastMove: PackedMove | null;\n /** Currently-selected square (UI state), or `null`. */\n readonly selected: SquareIndex | null;\n /** Legal target squares from `selected`. Empty set if nothing is selected. */\n readonly legalTargets: ReadonlySet<SquareIndex>;\n /** `true` if the side to move is in check. */\n readonly inCheck: boolean;\n /** `true` if the position ends the game (mate, stalemate, draw). */\n readonly isGameOver: boolean;\n /** How many plies from the initial position we are (includes undos). */\n readonly historyPly: number;\n /** Total history length, including any plies we've undone. */\n readonly historyLength: number;\n /** Active arrows drawn on the board. */\n readonly arrows: readonly Arrow[];\n /** Queued premoves, in FIFO order. */\n readonly premoves: readonly Premove[];\n}\n\n/** Descriptor classifying one animated change between two snapshots. */\nexport type AnimDescriptor =\n | {\n readonly kind: \"move\";\n readonly from: SquareIndex;\n readonly to: SquareIndex;\n readonly piece: BoardCell;\n }\n | {\n readonly kind: \"capture\";\n readonly from: SquareIndex;\n readonly to: SquareIndex;\n readonly piece: BoardCell;\n readonly captured: BoardCell;\n }\n | {\n readonly kind: \"en-passant\";\n readonly from: SquareIndex;\n readonly to: SquareIndex;\n readonly capturedSquare: SquareIndex;\n readonly piece: BoardCell;\n readonly captured: BoardCell;\n }\n | {\n readonly kind: \"castle\";\n readonly kingFrom: SquareIndex;\n readonly kingTo: SquareIndex;\n readonly rookFrom: SquareIndex;\n readonly rookTo: SquareIndex;\n }\n | {\n readonly kind: \"promotion\";\n readonly from: SquareIndex;\n readonly to: SquareIndex;\n readonly pieceBefore: BoardCell;\n readonly pieceAfter: BoardCell;\n readonly captured: BoardCell | null;\n }\n | {\n readonly kind: \"appear\";\n readonly at: SquareIndex;\n readonly piece: BoardCell;\n }\n | {\n readonly kind: \"disappear\";\n readonly at: SquareIndex;\n readonly piece: BoardCell;\n };\n\n/** Pointer-driven drag state. Used by `drag-controller`. */\nexport type DragState =\n | { readonly kind: \"idle\" }\n | {\n readonly kind: \"pending\";\n readonly from: SquareIndex;\n readonly pointerId: number;\n readonly originX: number;\n readonly originY: number;\n }\n | {\n readonly kind: \"dragging\";\n readonly from: SquareIndex;\n readonly pointerId: number;\n readonly x: number;\n readonly y: number;\n };\n","/**\n * Synchronous engine adapter wrapping `gigachess`.\n *\n * Provides a zero-WASM, pure JavaScript chess engine adapter with instant\n * synchronous initialization (<0.5 ms), incremental { lo, hi } Zobrist hashing,\n * and canonical King-captures-Rook castling representation (Move2).\n */\n\nimport { ensureMagicTablesLoaded, ensureZobristLoaded, makeSan, type Role } from \"gigachess\";\nimport { Chess } from \"gigachess/chessjs\";\nimport type { EngineAdapter } from \"../engine-adapter.js\";\nimport type { PackedMove, PieceType, SquareIndex, ZobristKey } from \"../types.js\";\nimport { Color, encodeBoardCell, packMove, unpackMove } from \"../types.js\";\n\n// Eagerly trigger background loading of magic and zobrist tables\nvoid ensureMagicTablesLoaded().catch(() => {});\nvoid ensureZobristLoaded().catch(() => {});\n\n/**\n * Preload gigachess sliding-attack magic tables and Polyglot Zobrist tables ahead of time.\n */\nexport function preloadGigachessAdapter(): Promise<void> {\n return Promise.all([ensureMagicTablesLoaded(), ensureZobristLoaded()]).then(() => undefined);\n}\n\nfunction algebraicOf(sq: SquareIndex): string {\n const file = sq & 7;\n const rank = sq >> 3;\n return `${String.fromCharCode(0x61 + file)}${rank + 1}`;\n}\n\nfunction squareIndexOf(alg: string): SquareIndex {\n const file = alg.charCodeAt(0) - 0x61;\n const rank = alg.charCodeAt(1) - 0x31;\n return (rank * 8 + file) as SquareIndex;\n}\n\nfunction promoRole(code: number): Role | undefined {\n switch (code) {\n case 1:\n return 1 as Role; // Knight\n case 2:\n return 2 as Role; // Bishop\n case 3:\n return 3 as Role; // Rook\n case 4:\n return 4 as Role; // Queen\n default:\n return undefined;\n }\n}\n\nfunction promoChar(piece?: PieceType): string | undefined {\n switch (piece) {\n case 1:\n return \"n\";\n case 2:\n return \"b\";\n case 3:\n return \"r\";\n case 4:\n return \"q\";\n default:\n return undefined;\n }\n}\n\n/**\n * Create a gigachess-backed engine adapter synchronously.\n *\n * @param fen Optional starting FEN.\n */\nexport function createGigachessAdapter(fen?: string): EngineAdapter {\n const chess = fen === undefined ? new Chess() : new Chess(fen);\n\n const makeMove = (\n from: SquareIndex,\n to: SquareIndex,\n promotion?: PieceType,\n ): PackedMove | null => {\n try {\n const fromAlg = algebraicOf(from);\n const toAlg = algebraicOf(to);\n const promo = promoChar(promotion);\n const res = chess.move({\n from: fromAlg,\n to: toAlg,\n ...(promo ? { promotion: promo } : {}),\n });\n if (res === null) return null;\n\n // Canonical King-captures-Rook encoding for castling\n if (res.flags.includes(\"k\")) {\n return res.color === \"w\" ? packMove(4, 7, 0) : packMove(60, 63, 0);\n }\n if (res.flags.includes(\"q\")) {\n return res.color === \"w\" ? packMove(4, 0, 0) : packMove(60, 56, 0);\n }\n\n const pCode = res.promotion\n ? res.promotion === \"n\"\n ? 1\n : res.promotion === \"b\"\n ? 2\n : res.promotion === \"r\"\n ? 3\n : 4\n : 0;\n return packMove(from, to, pCode);\n } catch {\n return null;\n }\n };\n\n const undo = (): PackedMove | null => {\n const res = chess.undo();\n if (res === null) return null;\n if (res.flags.includes(\"k\")) {\n return res.color === \"w\" ? packMove(4, 7, 0) : packMove(60, 63, 0);\n }\n if (res.flags.includes(\"q\")) {\n return res.color === \"w\" ? packMove(4, 0, 0) : packMove(60, 56, 0);\n }\n const from = squareIndexOf(res.from);\n const to = squareIndexOf(res.to);\n const pCode = res.promotion\n ? res.promotion === \"n\"\n ? 1\n : res.promotion === \"b\"\n ? 2\n : res.promotion === \"r\"\n ? 3\n : 4\n : 0;\n return packMove(from, to, pCode);\n };\n\n const legalMoves = (from?: SquareIndex): readonly PackedMove[] => {\n const moves =\n from === undefined\n ? chess.moves({ verbose: true })\n : chess.moves({ verbose: true, square: algebraicOf(from) });\n\n const out: PackedMove[] = [];\n for (let i = 0; i < moves.length; i++) {\n const m = moves[i];\n if (m === undefined) continue;\n if (m.flags.includes(\"k\")) {\n out.push(m.color === \"w\" ? packMove(4, 7, 0) : packMove(60, 63, 0));\n } else if (m.flags.includes(\"q\")) {\n out.push(m.color === \"w\" ? packMove(4, 0, 0) : packMove(60, 56, 0));\n } else {\n const f = squareIndexOf(m.from);\n const t = squareIndexOf(m.to);\n const pCode = m.promotion\n ? m.promotion === \"n\"\n ? 1\n : m.promotion === \"b\"\n ? 2\n : m.promotion === \"r\"\n ? 3\n : 4\n : 0;\n out.push(packMove(f, t, pCode));\n }\n }\n return out;\n };\n\n const readBoard = (out: Uint8Array): void => {\n if (typeof process !== \"undefined\" && process.env?.[\"NODE_ENV\"] !== \"production\") {\n if (out.length !== 64) {\n throw new RangeError(\"readBoard: out.length must be 64\");\n }\n }\n out.fill(0);\n const b = chess.boardInstance;\n for (let sq = 0; sq < 64; sq++) {\n const p = b.pieceAt(sq);\n if (p !== undefined) {\n out[sq] = encodeBoardCell(p.color as unknown as Color, p.role as unknown as PieceType);\n }\n }\n };\n\n const san = (move: PackedMove): string => {\n const { from, to, promo } = unpackMove(move);\n const role = promoRole(promo);\n return makeSan(\n {\n from,\n to,\n ...(role !== undefined ? { promotion: role } : {}),\n },\n chess.pos,\n );\n };\n\n return {\n makeMove,\n undo,\n legalMoves,\n readBoard,\n fen: () => chess.fen(),\n turn: () => (chess.turn() === \"w\" ? Color.White : Color.Black),\n hash: (): ZobristKey => chess.zobrist(),\n inCheck: () => chess.inCheck(),\n san,\n isGameOver: () => chess.isGameOver(),\n load: (f: string): void => chess.load(f),\n reset: (): void => chess.reset(),\n dispose: (): void => {},\n };\n}\n","/**\n * Animation planner: diff two board snapshots and classify the change.\n *\n * The planner is called on every commit. Given `(prevBoard, nextBoard)` and\n * optionally the packed `Move` that was played, it produces an\n * `AnimDescriptor[]` describing what the UI should animate. The React layer\n * feeds the descriptors into WAAPI (`element.animate(...)`) — the planner\n * itself knows nothing about DOM, time, or easing.\n *\n * When the caller supplies the packed move we take the fast path: the kind,\n * source, target, capture, promotion are all encoded in 16 bits. When no\n * move is available (e.g. `load(fen)`, `reset()`, `redo()` of an arbitrary\n * history entry), we fall back to a byte-level diff and classify\n * conservatively as `appear` / `disappear`.\n */\n\nimport type { AnimDescriptor, BoardCell, PackedMove, SquareIndex } from \"./types.js\";\nimport { Color, colorOf, isEmptyCell, PieceType, pieceTypeOf } from \"./types.js\";\n\n/** Bit layout of a packed `Move` in 16-bit Move2 wire format. */\nconst MOVE_FROM_MASK = 0x3f;\nconst MOVE_TO_SHIFT = 6;\nconst MOVE_TO_MASK = 0x3f;\nconst MOVE_PROMO_SHIFT = 12;\nconst MOVE_PROMO_MASK = 0x0f;\n\n/** Promotion piece encoding within Move2 (0 = none, 1 = N, 2 = B, 3 = R, 4 = Q). */\nconst PROMO_PIECE: readonly (PieceType | null)[] = [\n null,\n PieceType.Knight,\n PieceType.Bishop,\n PieceType.Rook,\n PieceType.Queen,\n];\n\n/**\n * Plan animations for the transition `prev → next`.\n *\n * @param prev Previous board bytes (length 64).\n * @param next New board bytes (length 64).\n * @param move Optional packed move that caused the transition. Enables the\n * fast path; without it the planner falls back to a byte-level diff.\n */\nexport function planAnimations(\n prev: Readonly<Uint8Array>,\n next: Readonly<Uint8Array>,\n move: PackedMove | null,\n): AnimDescriptor[] {\n if (typeof process !== \"undefined\" && process.env?.[\"NODE_ENV\"] !== \"production\") {\n if (prev.length !== 64 || next.length !== 64) {\n throw new RangeError(\"planAnimations: board buffers must be length 64\");\n }\n }\n\n if (move !== null) {\n return planFromMove(prev, next, move);\n }\n return planFromDiff(prev, next);\n}\n\n/** Fast path: we know the exact move the engine just played. */\nfunction planFromMove(\n prev: Readonly<Uint8Array>,\n next: Readonly<Uint8Array>,\n move: PackedMove,\n): AnimDescriptor[] {\n const from = (move & MOVE_FROM_MASK) as SquareIndex;\n const to = ((move >> MOVE_TO_SHIFT) & MOVE_TO_MASK) as SquareIndex;\n const promoCode = (move >> MOVE_PROMO_SHIFT) & MOVE_PROMO_MASK;\n\n const pieceBefore = prev[from] as BoardCell;\n const pieceAfter = next[to] as BoardCell;\n const targetBefore = prev[to] as BoardCell;\n\n // 1. Castling detection:\n // Identified from King-captures-Rook canonical moves or 2-square jumps.\n if (!isEmptyCell(pieceBefore) && pieceTypeOf(pieceBefore) === PieceType.King) {\n const isFriendlyRookTarget =\n !isEmptyCell(targetBefore) &&\n colorOf(targetBefore) === colorOf(pieceBefore) &&\n pieceTypeOf(targetBefore) === PieceType.Rook;\n\n const isKingCapturesRookCanonical =\n (from === 4 && (to === 7 || to === 0)) || (from === 60 && (to === 63 || to === 56));\n\n const isKingTwoSquares =\n (from === 4 && (to === 6 || to === 2)) || (from === 60 && (to === 62 || to === 58));\n\n if (isFriendlyRookTarget || isKingCapturesRookCanonical || isKingTwoSquares) {\n const isKingside = (to & 7) > (from & 7);\n const kingRank = from >> 3;\n const base = kingRank << 3;\n const kingFrom = from;\n const kingTo = (base + (isKingside ? 6 : 2)) as SquareIndex;\n const rookFrom = (base + (isKingside ? 7 : 0)) as SquareIndex;\n const rookTo = (base + (isKingside ? 5 : 3)) as SquareIndex;\n return [\n {\n kind: \"castle\",\n kingFrom,\n kingTo,\n rookFrom,\n rookTo,\n },\n ];\n }\n }\n\n // 2. En-passant detection:\n // Pawn moves diagonally onto an empty target square.\n if (\n !isEmptyCell(pieceBefore) &&\n pieceTypeOf(pieceBefore) === PieceType.Pawn &&\n (from & 7) !== (to & 7) &&\n isEmptyCell(targetBefore)\n ) {\n const capturedSquare = ((from & ~7) | (to & 7)) as SquareIndex;\n const captured = prev[capturedSquare] as BoardCell;\n return [\n {\n kind: \"en-passant\",\n from,\n to,\n capturedSquare,\n piece: pieceBefore,\n captured,\n },\n ];\n }\n\n // 3. Promotion:\n if (promoCode > 0) {\n const captured = isEmptyCell(targetBefore) ? null : targetBefore;\n return [\n {\n kind: \"promotion\",\n from,\n to,\n pieceBefore,\n pieceAfter,\n captured,\n },\n ];\n }\n\n // 4. Capture or Normal move:\n if (!isEmptyCell(targetBefore)) {\n return [\n {\n kind: \"capture\",\n from,\n to,\n piece: pieceBefore,\n captured: targetBefore,\n },\n ];\n }\n\n return [{ kind: \"move\", from, to, piece: pieceBefore }];\n}\n\n/**\n * Fallback path: compare two arbitrary boards and describe every changed\n * square as `appear` / `disappear`. The UI renders these as fades rather\n * than glides — we can't recover the original trajectory.\n */\nfunction planFromDiff(prev: Readonly<Uint8Array>, next: Readonly<Uint8Array>): AnimDescriptor[] {\n const descriptors: AnimDescriptor[] = [];\n for (let i = 0; i < 64; i++) {\n const a = prev[i] as BoardCell;\n const b = next[i] as BoardCell;\n if (a === b) continue;\n const at = i as SquareIndex;\n if (!isEmptyCell(a) && isEmptyCell(b)) {\n descriptors.push({ kind: \"disappear\", at, piece: a });\n } else if (isEmptyCell(a) && !isEmptyCell(b)) {\n descriptors.push({ kind: \"appear\", at, piece: b });\n } else {\n // Piece replaced by a different piece — typically a sequence of two\n // moves collapsed by `goto(ply)`. Emit a disappear + appear pair so\n // the UI can fade one out and the other in.\n descriptors.push({ kind: \"disappear\", at, piece: a });\n descriptors.push({ kind: \"appear\", at, piece: b });\n }\n }\n return descriptors;\n}\n\n/**\n * Lightweight, side-effect-free inspector. Used by tests to decompose a\n * packed move without pulling an engine as a runtime dep.\n */\nexport function decodePackedMove(m: PackedMove): {\n from: SquareIndex;\n to: SquareIndex;\n kind: \"normal\" | \"promotion\" | \"en-passant\" | \"castle\";\n promotion: PieceType | null;\n} {\n const from = (m & MOVE_FROM_MASK) as SquareIndex;\n const to = ((m >> MOVE_TO_SHIFT) & MOVE_TO_MASK) as SquareIndex;\n const promoCode = (m >> MOVE_PROMO_SHIFT) & MOVE_PROMO_MASK;\n const promotion = PROMO_PIECE[promoCode] ?? null;\n\n const isCastle =\n (from === 4 && (to === 7 || to === 0 || to === 6 || to === 2)) ||\n (from === 60 && (to === 63 || to === 56 || to === 62 || to === 58));\n\n const kind: \"normal\" | \"promotion\" | \"en-passant\" | \"castle\" =\n promotion !== null ? \"promotion\" : isCastle ? \"castle\" : \"normal\";\n\n return { from, to, kind, promotion };\n}\n\n/**\n * Expose colour / piece-type extraction from a `BoardCell` without re-importing\n * `types.ts`. Used by the React layer when it needs to know \"is this white's\n * pawn?\" cheaply.\n */\nexport const animationInspect = {\n colorOf,\n pieceTypeOf,\n // Re-export the Color / PieceType enums so consumers can compare without\n // extra imports.\n Color,\n PieceType,\n};\n","/**\n * Arrow set with stable identity by `(from, to, color)`.\n *\n * The model is intentionally tiny: it owns nothing the UI cares about (colors,\n * hit-tests, rendering) beyond the three identifying fields. The renderer is\n * responsible for drawing; the model is responsible for *which arrows exist*.\n */\n\nimport type { Arrow, SquareIndex } from \"./types.js\";\n\n/** The arrow-set API. */\nexport interface ArrowModel {\n /** Current set of arrows, oldest first, as a frozen snapshot. */\n readonly arrows: readonly Arrow[];\n /** `true` if an arrow with the same `(from, to, color)` is present. */\n has(arrow: Arrow): boolean;\n /** Add an arrow. No-op if an identical one already exists. */\n add(arrow: Arrow): void;\n /** Remove an arrow. No-op if it isn't present. */\n remove(arrow: Arrow): void;\n /**\n * Convenience: remove if present, add if not. Returns the new presence\n * (`true` if the arrow is in the set after the call).\n */\n toggle(arrow: Arrow): boolean;\n /** Drop every arrow, managed or not. */\n clear(): void;\n /**\n * Drop only **user-drawn** arrows (anything without `managed: true`).\n *\n * Used by the board's reflex-clearing hooks (`clearArrowsOnClick`,\n * `clearArrowsOnMove`) so engine / app-owned annotations survive the\n * user's click-to-dismiss gesture. Reports `lastChanged` like every\n * other mutator.\n */\n clearUser(): void;\n /** Drop only **managed** arrows (those with `managed: true`). */\n clearManaged(): void;\n /**\n * Atomic replace of the **managed** subset. User-drawn arrows are\n * untouched. Every incoming arrow is stamped `managed: true` — callers\n * don't have to set the flag explicitly, and the method's name carries\n * the intent. Identity preservation works the same way as\n * {@link setAll}: arrows whose identity key already exists are reused\n * from the stored frozen instances so consumer `Object.is` checks stay\n * cheap across commits.\n */\n setManaged(arrows: readonly Arrow[]): void;\n /**\n * Replace the entire arrow set in one atomic step. Preserves identity\n * for arrows whose `(from, to, color)` tuple was already present —\n * freshly-provided arrows are frozen and keyed; removed ones are\n * dropped. Single `lastChanged` flag covers the whole batch.\n */\n setAll(arrows: readonly Arrow[]): void;\n /** Whether the last call actually changed the state. */\n readonly lastChanged: boolean;\n}\n\nfunction arrowKey(arrow: Arrow): string {\n // Required fields first; optional decorations fold in only when\n // present. Preserves the three-field key for plain arrows so any\n // caller persisting keys survives the M2 upgrade unchanged.\n //\n // `managed` is **not** part of the identity. An app that re-submits\n // the same (from, to, color) pair should not create a duplicate just\n // because ownership flipped — ownership is metadata, not identity.\n let key = `${arrow.from}|${arrow.to}|${arrow.color}`;\n if (arrow.brush !== undefined) key += `|b:${arrow.brush}`;\n if (arrow.label !== undefined) key += `|l:${arrow.label.text}`;\n if (arrow.customSvg !== undefined) key += `|s:${arrow.customSvg.html}`;\n if (arrow.below === true) key += \"|below\";\n return key;\n}\n\nfunction freezeArrow(a: Arrow): Arrow {\n // Build the frozen shape conditionally so plain arrows still have\n // exactly three own properties (consumers that iterate `Object.keys`\n // shouldn't suddenly see `undefined` entries for the optional fields).\n // Nested records are deep-frozen.\n const out: {\n from: Arrow[\"from\"];\n to: Arrow[\"to\"];\n color: Arrow[\"color\"];\n brush?: string;\n label?: Arrow[\"label\"];\n customSvg?: Arrow[\"customSvg\"];\n below?: boolean;\n managed?: boolean;\n } = { from: a.from, to: a.to, color: a.color };\n if (a.brush !== undefined) out.brush = a.brush;\n if (a.label !== undefined) out.label = Object.freeze({ ...a.label });\n if (a.customSvg !== undefined) out.customSvg = Object.freeze({ ...a.customSvg });\n if (a.below === true) out.below = true;\n if (a.managed === true) out.managed = true;\n return Object.freeze(out) as Arrow;\n}\n\nconst EMPTY_ARROWS: readonly Arrow[] = Object.freeze([]);\n\n/** Create an empty arrow model. */\nexport function createArrowModel(): ArrowModel {\n const byKey = new Map<string, Arrow>();\n let changed = false;\n // Cached materialisation of `arrows`. Invalidated on any mutation so reads\n // return a stable reference while nothing changes — critical for the React\n // layer's `useSyncExternalStore` slice equality.\n let cached: readonly Arrow[] | null = EMPTY_ARROWS;\n const invalidate = (): void => {\n cached = null;\n };\n\n const has = (arrow: Arrow): boolean => byKey.has(arrowKey(arrow));\n\n const add = (arrow: Arrow): void => {\n const key = arrowKey(arrow);\n if (byKey.has(key)) {\n changed = false;\n return;\n }\n byKey.set(key, freezeArrow(arrow));\n changed = true;\n invalidate();\n };\n\n const remove = (arrow: Arrow): void => {\n changed = byKey.delete(arrowKey(arrow));\n if (changed) invalidate();\n };\n\n const toggle = (arrow: Arrow): boolean => {\n const key = arrowKey(arrow);\n if (byKey.has(key)) {\n byKey.delete(key);\n changed = true;\n invalidate();\n return false;\n }\n byKey.set(key, freezeArrow(arrow));\n changed = true;\n invalidate();\n return true;\n };\n\n const clear = (): void => {\n changed = byKey.size > 0;\n byKey.clear();\n if (changed) invalidate();\n };\n\n /**\n * Drop every entry that fails `keep`. One Map pass; zero allocations\n * when nothing changes. The predicate is inlined at each call-site\n * via closure.\n */\n const dropWhere = (remove: (arrow: Arrow) => boolean): void => {\n let mutated = false;\n for (const [key, arrow] of byKey) {\n if (remove(arrow)) {\n byKey.delete(key);\n mutated = true;\n }\n }\n changed = mutated;\n if (mutated) invalidate();\n };\n\n const clearUser = (): void => dropWhere((a) => a.managed !== true);\n const clearManaged = (): void => dropWhere((a) => a.managed === true);\n\n const setManaged = (arrows: readonly Arrow[]): void => {\n // Build the next managed-key set. Existing managed entries not in\n // the incoming list are dropped; user-drawn entries are never\n // touched. Identity of re-appearing managed entries is preserved —\n // we reuse the stored frozen instance instead of re-freezing.\n const nextKeys = new Set<string>();\n let mutated = false;\n for (let i = 0; i < arrows.length; i++) {\n const raw = arrows[i];\n if (raw === undefined) continue;\n // Stamp managed on the way in so callers don't have to.\n const marked: Arrow = raw.managed === true ? raw : { ...raw, managed: true };\n const key = arrowKey(marked);\n if (nextKeys.has(key)) continue;\n nextKeys.add(key);\n if (!byKey.has(key)) {\n byKey.set(key, freezeArrow(marked));\n mutated = true;\n }\n }\n // Sweep: remove any previously-managed entry whose key isn't in the\n // next set. User-drawn arrows (managed !== true) are skipped.\n for (const [key, arrow] of byKey) {\n if (arrow.managed === true && !nextKeys.has(key)) {\n byKey.delete(key);\n mutated = true;\n }\n }\n changed = mutated;\n if (mutated) invalidate();\n };\n\n const setAll = (arrows: readonly Arrow[]): void => {\n // Build the next key set so we can detect adds / removes / churn\n // without re-walking the incoming list twice. Identity of existing\n // entries is preserved: if the incoming arrow already matches a\n // stored one, we reuse the stored frozen instance — keeps consumer\n // `Object.is` checks cheap across commits.\n const nextKeys = new Set<string>();\n let mutated = false;\n for (let i = 0; i < arrows.length; i++) {\n const a = arrows[i];\n if (a === undefined) continue;\n const key = arrowKey(a);\n if (nextKeys.has(key)) continue;\n nextKeys.add(key);\n if (!byKey.has(key)) {\n byKey.set(key, freezeArrow(a));\n mutated = true;\n }\n }\n if (byKey.size !== nextKeys.size) {\n for (const key of byKey.keys()) {\n if (!nextKeys.has(key)) {\n byKey.delete(key);\n mutated = true;\n }\n }\n }\n changed = mutated;\n if (mutated) invalidate();\n };\n\n return {\n get arrows() {\n if (cached === null) {\n cached = Object.freeze([...byKey.values()]);\n }\n return cached;\n },\n has,\n add,\n remove,\n toggle,\n clear,\n clearUser,\n clearManaged,\n setAll,\n setManaged,\n get lastChanged() {\n return changed;\n },\n };\n}\n\n/** Helper: build a frozen `Arrow` literal. Validates branded types in dev. */\nexport function makeArrow(from: SquareIndex, to: SquareIndex, color: string): Arrow {\n return Object.freeze({ from, to, color });\n}\n","/**\n * Pointer-driven drag state machine.\n *\n * States: `idle → pending → dragging → idle`.\n *\n * - `pointerDown` on a source square moves us from `idle` to `pending`. We\n * don't commit to \"this is a drag\" yet — a tap that releases without moving\n * should remain a click.\n * - Once the pointer has moved more than `activationDistance` pixels (default\n * `4`), we transition to `dragging` and emit a `drag-start` event. From\n * there, every `pointerMove` updates the live `(x, y)`.\n * - `pointerUp` in `dragging` emits a `drop` event and returns to `idle`.\n * `pointerUp` in `pending` (no drag happened) returns to `idle` silently.\n * - `cancel()` at any time returns to `idle` and emits a `cancel` event if a\n * drag or pending pick was in flight.\n *\n * Events other than `pointerDown` that arrive with the \"wrong\" `pointerId`\n * are ignored — necessary on touch devices where multiple pointers may be\n * live simultaneously.\n *\n * The controller is a pure reducer that returns its output events. It does\n * **not** subscribe to the board model, and it performs zero DOM reads or\n * writes. The React layer is responsible for wiring `PointerEvent`s to these\n * methods and reacting to the returned events.\n */\n\nimport type { DragState, SquareIndex } from \"./types.js\";\n\n/** The \"activation\" threshold: if the pointer hasn't moved this many pixels,\n * releasing is treated as a click, not a drop. */\nconst DEFAULT_ACTIVATION_DISTANCE = 4;\n\n/** Emitted when the pointer crosses `activationDistance` from its origin. */\nexport interface DragStartEvent {\n readonly kind: \"drag-start\";\n readonly from: SquareIndex;\n}\n\n/** Emitted while dragging, on every `pointerMove`. Coordinates are whatever\n * the caller passed in (no DOM awareness — typically `clientX`/`clientY`). */\nexport interface DragMoveEvent {\n readonly kind: \"drag-move\";\n readonly from: SquareIndex;\n readonly x: number;\n readonly y: number;\n}\n\n/** Emitted on `pointerUp` in `dragging`. `wasDrag` is always `true` here. */\nexport interface DropEvent {\n readonly kind: \"drop\";\n readonly from: SquareIndex;\n readonly x: number;\n readonly y: number;\n readonly wasDrag: true;\n}\n\n/** Emitted on `pointerUp` in `pending` — the user clicked without dragging. */\nexport interface ClickEvent {\n readonly kind: \"click\";\n readonly from: SquareIndex;\n}\n\n/** Emitted by `cancel()` when a pending pick or an in-flight drag existed. */\nexport interface CancelEvent {\n readonly kind: \"cancel\";\n readonly from: SquareIndex;\n}\n\n/** Any event emitted by the drag controller. */\nexport type DragEvent = DragStartEvent | DragMoveEvent | DropEvent | ClickEvent | CancelEvent;\n\n/** Controller options. */\nexport interface DragControllerOptions {\n /** Distance threshold (in CSS pixels) for `pending → dragging`. Default 4. */\n readonly activationDistance?: number;\n}\n\n/** Public controller API. */\nexport interface DragController {\n /** The current drag state. Read-only. */\n readonly state: DragState;\n /**\n * Handle a pointer-down on a source square. Returns `true` if the event was\n * consumed (i.e. we were `idle` and are now `pending`); `false` otherwise.\n */\n pointerDown(from: SquareIndex, pointerId: number, x: number, y: number): boolean;\n /**\n * Handle a pointer-move. Returns the emitted event (`drag-start` on the\n * first crossing of the threshold, `drag-move` afterwards) or `null` if\n * the move did not produce one.\n */\n pointerMove(pointerId: number, x: number, y: number): DragStartEvent | DragMoveEvent | null;\n /**\n * Handle a pointer-up. Returns `drop` when a drag was in flight, `click`\n * when the user released without crossing the threshold, or `null` if the\n * event does not concern us.\n */\n pointerUp(pointerId: number, x: number, y: number): DropEvent | ClickEvent | null;\n /** Abort any pending or in-flight drag. Returns the emitted event, or\n * `null` if there was nothing to cancel. */\n cancel(): CancelEvent | null;\n}\n\n/** Construct a fresh drag controller. */\nexport function createDragController(options: DragControllerOptions = {}): DragController {\n const activationDistance = options.activationDistance ?? DEFAULT_ACTIVATION_DISTANCE;\n if (!Number.isFinite(activationDistance) || activationDistance < 0) {\n throw new RangeError(\n `DragController: activationDistance must be a non-negative number, got ${activationDistance}`,\n );\n }\n const thresholdSq = activationDistance * activationDistance;\n let state: DragState = { kind: \"idle\" };\n\n const pointerDown = (from: SquareIndex, pointerId: number, x: number, y: number): boolean => {\n if (state.kind !== \"idle\") return false;\n state = { kind: \"pending\", from, pointerId, originX: x, originY: y };\n return true;\n };\n\n const pointerMove = (\n pointerId: number,\n x: number,\n y: number,\n ): DragStartEvent | DragMoveEvent | null => {\n if (state.kind === \"idle\") return null;\n if (state.pointerId !== pointerId) return null;\n\n if (state.kind === \"pending\") {\n const dx = x - state.originX;\n const dy = y - state.originY;\n if (dx * dx + dy * dy < thresholdSq) {\n return null;\n }\n const from = state.from;\n state = { kind: \"dragging\", from, pointerId, x, y };\n return { kind: \"drag-start\", from };\n }\n\n state = { kind: \"dragging\", from: state.from, pointerId, x, y };\n return { kind: \"drag-move\", from: state.from, x, y };\n };\n\n const pointerUp = (pointerId: number, x: number, y: number): DropEvent | ClickEvent | null => {\n if (state.kind === \"idle\") return null;\n if (state.pointerId !== pointerId) return null;\n\n if (state.kind === \"dragging\") {\n const event: DropEvent = { kind: \"drop\", from: state.from, x, y, wasDrag: true };\n state = { kind: \"idle\" };\n return event;\n }\n\n const event: ClickEvent = { kind: \"click\", from: state.from };\n state = { kind: \"idle\" };\n return event;\n };\n\n const cancel = (): CancelEvent | null => {\n if (state.kind === \"idle\") return null;\n const event: CancelEvent = { kind: \"cancel\", from: state.from };\n state = { kind: \"idle\" };\n return event;\n };\n\n return {\n get state() {\n return state;\n },\n pointerDown,\n pointerMove,\n pointerUp,\n cancel,\n };\n}\n","/**\n * `hash()`-keyed LRU cache for `(position, from-square) → to-squares`.\n *\n * Every time the user picks up a piece we need the list of legal target squares\n * to paint rings on the board. The engine's `legalMoves(from)` call is cheap\n * but crosses the WASM boundary; caching on `engine.hash()` makes every repeat\n * selection free.\n *\n * Keyed as `(hash << 6n) | BigInt(from)` — 70 bits total, carried as a single\n * `bigint` key. LRU order is preserved by `Map` iteration order: on hit we\n * `delete` + `set` to bump the entry to the most-recently-used end; on write\n * past capacity we evict the oldest (the first key in iteration order).\n */\n\nimport type { SquareIndex, ZobristKey } from \"./types.js\";\n\n/** Lookup outcome from {@link LegalMoveIndex.get}. */\nexport type LegalMoveEntry = Readonly<Uint8Array>;\n\n/** Position hash representation: zero-BigInt { lo, hi } pair or bigint. */\nexport type PositionHash = bigint | ZobristKey;\n\n/** The cache API. */\nexport interface LegalMoveIndex {\n /** Return cached target squares for `(hash, from)`, or `undefined` on miss. */\n get(hash: PositionHash, from: SquareIndex): LegalMoveEntry | undefined;\n /** Store target squares for `(hash, from)`. */\n set(hash: PositionHash, from: SquareIndex, tos: Uint8Array): void;\n /** Drop every entry. */\n clear(): void;\n /** Current number of entries. */\n readonly size: number;\n /** Configured maximum entry count. */\n readonly capacity: number;\n /** Cumulative hit count since construction (or last `resetStats`). */\n readonly hits: number;\n /** Cumulative miss count since construction (or last `resetStats`). */\n readonly misses: number;\n /** Reset `hits` / `misses` to zero. Does not affect stored entries. */\n resetStats(): void;\n}\n\n/** Options for {@link createLegalMoveIndex}. */\nexport interface LegalMoveIndexOptions {\n /** Maximum number of entries retained. Must be ≥ 1. Defaults to `1024`. */\n readonly capacity?: number;\n}\n\n/** Pack `(hash, from)` into a key without BigInt heap allocation on { lo, hi }. */\nfunction makeKey(hash: PositionHash, from: SquareIndex): string {\n if (typeof hash === \"bigint\") {\n return `${hash}_${from}`;\n }\n return `${hash.lo}_${hash.hi}_${from}`;\n}\n\n/** Create an LRU cache. */\nexport function createLegalMoveIndex(options: LegalMoveIndexOptions = {}): LegalMoveIndex {\n const capacity = options.capacity ?? 1024;\n if (!Number.isInteger(capacity) || capacity < 1) {\n throw new RangeError(`LegalMoveIndex: capacity must be a positive integer, got ${capacity}`);\n }\n\n const entries = new Map<string, Uint8Array>();\n let hits = 0;\n let misses = 0;\n\n const get = (hash: bigint, from: SquareIndex): LegalMoveEntry | undefined => {\n const key = makeKey(hash, from);\n const hit = entries.get(key);\n if (hit === undefined) {\n misses++;\n return undefined;\n }\n // Bump to MRU end: re-insert.\n entries.delete(key);\n entries.set(key, hit);\n hits++;\n return hit;\n };\n\n const set = (hash: bigint, from: SquareIndex, tos: Uint8Array): void => {\n const key = makeKey(hash, from);\n if (entries.has(key)) {\n entries.delete(key);\n } else if (entries.size >= capacity) {\n // Evict LRU (first iteration entry).\n const oldest = entries.keys().next().value;\n if (oldest !== undefined) entries.delete(oldest);\n }\n entries.set(key, tos);\n };\n\n const clear = (): void => {\n entries.clear();\n };\n\n const resetStats = (): void => {\n hits = 0;\n misses = 0;\n };\n\n return {\n get,\n set,\n clear,\n resetStats,\n get size() {\n return entries.size;\n },\n capacity,\n get hits() {\n return hits;\n },\n get misses() {\n return misses;\n },\n };\n}\n","/**\n * Premove queue.\n *\n * When it isn't our turn and we drag a piece to a target, the intended move\n * is queued as a `Premove`. After the opponent replies, the board model\n * attempts to apply queued premoves in order; each one that is now legal\n * plays, and on the first illegal premove the queue is cleared (standard\n * lichess/chess.com behaviour — a busted premove discards everything after\n * it too).\n */\n\nimport type { PieceType, Premove, SquareIndex } from \"./types.js\";\n\n/** Premove queue API. */\nexport interface PremoveBuffer {\n /** FIFO snapshot of the current queue. */\n readonly all: readonly Premove[];\n /** The premove at the head of the queue, or `undefined` if empty. */\n peek(): Premove | undefined;\n /** Append a premove. */\n push(premove: Premove): void;\n /** Remove and return the head premove, or `undefined` if empty. */\n shift(): Premove | undefined;\n /** Drop every premove. */\n clear(): void;\n /** Current queue length. */\n readonly length: number;\n}\n\nfunction freezePremove(p: Premove): Premove {\n // Copy to guarantee immutability regardless of what the caller passes in.\n // Preserve the \"no `promotion` field vs `promotion: undefined`\" distinction\n // required by `exactOptionalPropertyTypes`.\n if (p.promotion === undefined) {\n return Object.freeze({ from: p.from, to: p.to });\n }\n return Object.freeze({ from: p.from, to: p.to, promotion: p.promotion });\n}\n\nconst EMPTY_PREMOVES: readonly Premove[] = Object.freeze([]);\n\n/** Create an empty premove buffer. */\nexport function createPremoveBuffer(): PremoveBuffer {\n const queue: Premove[] = [];\n // See `arrow-model.ts` for the motivation — React subscribers need a stable\n // reference across no-op reads for slice equality to work.\n let cached: readonly Premove[] | null = EMPTY_PREMOVES;\n\n const peek = (): Premove | undefined => queue[0];\n\n const push = (premove: Premove): void => {\n queue.push(freezePremove(premove));\n cached = null;\n };\n\n const shift = (): Premove | undefined => {\n const head = queue.shift();\n if (head !== undefined) cached = null;\n return head;\n };\n\n const clear = (): void => {\n if (queue.length > 0) {\n queue.length = 0;\n cached = null;\n }\n };\n\n return {\n get all() {\n if (cached === null) {\n cached = Object.freeze([...queue]);\n }\n return cached;\n },\n peek,\n push,\n shift,\n clear,\n get length() {\n return queue.length;\n },\n };\n}\n\n/** Helper: build a frozen `Premove` literal with safe optional handling. */\nexport function makePremove(from: SquareIndex, to: SquareIndex, promotion?: PieceType): Premove {\n return promotion === undefined\n ? Object.freeze({ from, to })\n : Object.freeze({ from, to, promotion });\n}\n","/**\n * `useSyncExternalStore`-compatible store with byte-level per-square diff.\n *\n * Global listeners fire on every commit. Per-square listeners fire **only** when\n * their byte of `snapshot.board` changed — so a move that touches 2–4 squares\n * wakes only 2–4 Square components instead of all 64.\n */\n\nimport type { BoardSnapshot, SquareIndex } from \"./types.js\";\n\n/** Cleanup returned from a subscription. Idempotent. */\nexport type Unsubscribe = () => void;\n\n/** Internal listener type: a void-returning callback. */\ntype Listener = () => void;\n\n/**\n * The store API. Surface area is intentionally minimal; everything else lives\n * in `board-model`.\n */\nexport interface BoardStore {\n /** Return the current frozen snapshot. Same reference between commits. */\n getSnapshot(): BoardSnapshot;\n /** Subscribe to every commit. Returns an unsubscribe function. */\n subscribe(listener: Listener): Unsubscribe;\n /**\n * Subscribe to commits in which `board[index]` changed. Useful from a\n * per-square React component via `useSyncExternalStore`.\n */\n subscribeSquare(index: SquareIndex, listener: Listener): Unsubscribe;\n /**\n * Install a new snapshot. Diffs `board` bytes against the previous snapshot\n * and fires only the per-square listeners whose byte actually changed, plus\n * every global listener.\n *\n * @remarks\n * Callers must build a fresh snapshot object — mutating the previous one in\n * place would make `getSnapshot()` return `=== previous`, which React treats\n * as \"no change\" and skips the render.\n */\n commit(next: BoardSnapshot): void;\n}\n\n/** Create a new board store initialised with `initial`. */\nexport function createBoardStore(initial: BoardSnapshot): BoardStore {\n let snapshot: BoardSnapshot = initial;\n const globalListeners = new Set<Listener>();\n // 64 slots; lazily allocated per square on first subscriber.\n const squareListeners: Array<Set<Listener> | undefined> = new Array(64);\n\n const notify = (set: Set<Listener>): void => {\n // Snapshot the iteration set before firing. A listener that unsubscribes\n // its neighbour mid-iteration would otherwise skip it.\n for (const l of [...set]) l();\n };\n\n const getSnapshot = (): BoardSnapshot => snapshot;\n\n const subscribe = (listener: Listener): Unsubscribe => {\n globalListeners.add(listener);\n let alive = true;\n return () => {\n if (!alive) return;\n alive = false;\n globalListeners.delete(listener);\n };\n };\n\n const subscribeSquare = (index: SquareIndex, listener: Listener): Unsubscribe => {\n let set = squareListeners[index];\n if (!set) {\n set = new Set();\n squareListeners[index] = set;\n }\n set.add(listener);\n let alive = true;\n return () => {\n if (!alive) return;\n alive = false;\n set.delete(listener);\n };\n };\n\n const commit = (next: BoardSnapshot): void => {\n if (next === snapshot) return;\n const prev = snapshot;\n snapshot = next;\n\n const prevBoard = prev.board;\n const nextBoard = next.board;\n if (prevBoard !== nextBoard) {\n for (let i = 0; i < 64; i++) {\n if (prevBoard[i] !== nextBoard[i]) {\n const set = squareListeners[i];\n if (set && set.size > 0) notify(set);\n }\n }\n }\n if (globalListeners.size > 0) notify(globalListeners);\n };\n\n return { getSnapshot, subscribe, subscribeSquare, commit };\n}\n","/**\n * Board model: the orchestrator.\n *\n * Owns the engine adapter, the subscribe store, the legal-move cache, the\n * arrow set, the premove buffer, and the redo stack. Every public action\n * funnels here: `tryMove`, `undo`, `redo`, `goto`, `load`, `reset`,\n * `selectSquare`, and arrow / premove mutators. Each action produces **at\n * most one** snapshot commit so that React subscribers receive a single,\n * coherent update per user intent.\n *\n * The model is intentionally framework-agnostic: no React, no DOM, no\n * `useState`. Consumers drive it imperatively and subscribe to the store\n * for state.\n */\n\nimport { planAnimations } from \"./animation-planner.js\";\nimport { createArrowModel } from \"./arrow-model.js\";\nimport {\n createDragController,\n type DragController,\n type DragControllerOptions,\n} from \"./drag-controller.js\";\nimport type { EngineAdapter } from \"./engine-adapter.js\";\nimport {\n createLegalMoveIndex,\n type LegalMoveIndex,\n type LegalMoveIndexOptions,\n} from \"./legal-move-index.js\";\nimport { createPremoveBuffer } from \"./premove-buffer.js\";\nimport { type BoardStore, createBoardStore, type Unsubscribe } from \"./subscribe-store.js\";\nimport type {\n AnimDescriptor,\n Arrow,\n BoardSnapshot,\n PackedMove,\n PieceType,\n Premove,\n SquareIndex,\n} from \"./types.js\";\nimport { BOARD_CELL_BK, BOARD_CELL_WK } from \"./types.js\";\n\n/** Frozen empty set singleton — returned when nothing is selected. */\nconst EMPTY_SET: ReadonlySet<SquareIndex> = Object.freeze(\n new Set<SquareIndex>(),\n) as ReadonlySet<SquareIndex>;\n\n/** Extract the \"to\" square from a packed move. */\nfunction moveTo(m: PackedMove): SquareIndex {\n return (((m as unknown as number) >> 6) & 0x3f) as SquareIndex;\n}\n\n/**\n * Resolves King castling drops: if a KING moves two squares (e1g1/e1c1 …),\n * normalize the destination to canonical King-captures-Rook (e1h1/e1a1 …).\n * Gated on the moving piece — any other piece sliding from e1/e8 (e.g. a\n * rook playing Re1-c1) must keep its true destination. Without the gate a\n * rook drop e1→c1 is silently replayed as e1→a1.\n */\nfunction normalizeCastlingTarget(from: SquareIndex, to: SquareIndex, isKing: boolean): SquareIndex {\n if (!isKing) return to;\n if (from === 4) {\n if (to === 6) return 7 as SquareIndex;\n if (to === 2) return 0 as SquareIndex;\n } else if (from === 60) {\n if (to === 62) return 63 as SquareIndex;\n if (to === 58) return 56 as SquareIndex;\n }\n return to;\n}\n\n/** Constructor options for {@link createBoardModel}. */\nexport interface BoardModelOptions {\n /** Options forwarded to the legal-move cache. */\n readonly legalMoveIndex?: LegalMoveIndexOptions;\n /** Options forwarded to the drag controller. */\n readonly dragController?: DragControllerOptions;\n /**\n * In development, freeze every emitted `BoardSnapshot` to catch accidental\n * mutation. Defaults to `true` when `NODE_ENV !== \"production\"`. Turning\n * this off is reserved for profiling; leave it alone otherwise.\n */\n readonly freezeSnapshots?: boolean;\n}\n\n/** Options for one coherent controlled-position update. */\nexport interface SyncPositionOptions {\n /** FEN to load into the underlying engine. */\n readonly fen: string;\n /**\n * Managed, application-owned arrows to install with the position. When\n * omitted, managed arrows are left alone if the FEN is already current\n * and cleared on a real position load, matching `load(fen)` semantics.\n */\n readonly managedArrows?: readonly Arrow[];\n /**\n * Preserve user-drawn arrows across a position load. Defaults to `false`\n * because arrows usually describe the previous position.\n */\n readonly preserveUserArrows?: boolean;\n}\n\n/** The orchestrator API consumed by React. */\nexport interface BoardModel {\n // ---- Store ----\n /** Current snapshot. Stable between commits. */\n getSnapshot(): BoardSnapshot;\n /** Subscribe to every commit. */\n subscribe(listener: () => void): Unsubscribe;\n /** Subscribe to commits that changed `board[index]`. */\n subscribeSquare(index: SquareIndex, listener: () => void): Unsubscribe;\n\n // ---- Actions ----\n /** Select a square. Passing `null` clears the selection. No-op if unchanged. */\n selectSquare(index: SquareIndex | null): void;\n /** Attempt a move. Returns the packed move on success, `null` on illegal. */\n tryMove(from: SquareIndex, to: SquareIndex, promotion?: PieceType): PackedMove | null;\n /** Undo the most recent move. */\n undo(): PackedMove | null;\n /** Redo the most recently undone move. */\n redo(): PackedMove | null;\n /** Jump to ply `n` in the history (0 = initial position). */\n goto(ply: number): void;\n /** Load a FEN; clears history, redo, arrows, and premoves. */\n load(fen: string): void;\n /**\n * Controlled-position sync for analysis/replay viewers. Loads the FEN\n * and replaces the managed arrow subset in the same snapshot commit.\n */\n syncPosition(options: SyncPositionOptions): void;\n /** Reset to the starting position; clears history, redo, arrows, premoves. */\n reset(): void;\n\n // ---- Queries ----\n /** `true` if a move `from → to` (optionally promoting) is legal right now. */\n isLegal(from: SquareIndex, to: SquareIndex, promotion?: PieceType): boolean;\n /** Legal target squares from `from`, cached by position hash. */\n legalFrom(from: SquareIndex): ReadonlySet<SquareIndex>;\n\n // ---- Arrows ----\n addArrow(arrow: Arrow): void;\n removeArrow(arrow: Arrow): void;\n toggleArrow(arrow: Arrow): void;\n /** Drop every arrow, managed or not. Nuclear option. */\n clearArrows(): void;\n /**\n * Drop only **user-drawn** arrows (anything without `managed: true`).\n * The board uses this for its click-to-dismiss behaviour so engine /\n * app-owned hints survive user interaction.\n */\n clearUserArrows(): void;\n /** Drop only **managed** arrows. Leaves user drawings untouched. */\n clearManagedArrows(): void;\n /**\n * Atomic replace of the **entire** arrow set (managed and user). Use\n * this when the board is a pure programmatic surface with no human\n * drawing — a review / replay viewer, a puzzle diagram, tests.\n *\n * For analysis-style boards that stream engine hints alongside human\n * arrow drawings, prefer {@link setManagedArrows}: it replaces only\n * the managed subset and preserves whatever the user has drawn by\n * right-clicking.\n *\n * @remarks\n * Arrows whose identity tuple already exists are preserved by\n * reference across the call, so React subscribers that compare\n * per-arrow references skip unchanged entries. A true no-op (same set\n * in the same order) commits nothing.\n */\n setArrows(arrows: readonly Arrow[]): void;\n /**\n * Atomic replace of **only** the managed subset. User-drawn arrows\n * are untouched; every incoming arrow is implicitly marked\n * `managed: true`. Idiomatic for engine-annotation feeds (Stockfish\n * best-moves, multi-PV fans): the arrow set turns over as a whole per\n * position without racing the user's right-click gesture.\n *\n * @example\n * ```ts\n * game.setManagedArrows(bestLine ? [uciToArrow(bestLine[0])] : []);\n * ```\n */\n setManagedArrows(arrows: readonly Arrow[]): void;\n\n // ---- Premoves ----\n queuePremove(premove: Premove): void;\n clearPremoves(): void;\n\n // ---- Subsystems exposed for the React layer ----\n /** The drag controller; React layer binds pointer events to it. */\n readonly drag: DragController;\n /** Statistics view of the legal-move cache (for benchmarks). */\n readonly legalMoveCache: LegalMoveIndex;\n /** The underlying engine adapter, for escape-hatch callers. */\n readonly engine: EngineAdapter;\n /**\n * The animation descriptors produced by the most recent commit. Empty on\n * the initial snapshot. Consumed by the React layer's `useAnimation` hook.\n */\n readonly lastAnimations: readonly AnimDescriptor[];\n\n /** Release engine resources and drop all subscriptions. */\n dispose(): void;\n}\n\n/**\n * Construct a board model around an engine adapter.\n *\n * The model does **not** create the adapter — the caller does.\n * See `createGigachessAdapter` for standard adapter construction.\n */\nexport function createBoardModel(\n engine: EngineAdapter,\n options: BoardModelOptions = {},\n): BoardModel {\n const freezeSnapshots = options.freezeSnapshots ?? process.env[\"NODE_ENV\"] !== \"production\";\n const legalMoveIndex = createLegalMoveIndex(options.legalMoveIndex ?? {});\n const arrowModel = createArrowModel();\n const premoveBuffer = createPremoveBuffer();\n const drag = createDragController(options.dragController ?? {});\n\n const history: PackedMove[] = [];\n const redoStack: PackedMove[] = [];\n let selected: SquareIndex | null = null;\n let lastMove: PackedMove | null = null;\n let lastAnimations: readonly AnimDescriptor[] = [];\n let disposed = false;\n\n const stageBuffer = new Uint8Array(64);\n\n const readBoardCopy = (): Uint8Array => {\n engine.readBoard(stageBuffer);\n return new Uint8Array(stageBuffer);\n };\n\n /**\n * `true` when the piece currently on `sq` is a king (either color).\n * Used to gate castling-target normalization: any other piece sliding\n * from e1/e8 (e.g. a rook playing Re1-c1) must keep its true destination.\n */\n const isKingOn = (sq: SquareIndex): boolean => {\n engine.readBoard(stageBuffer);\n const cell = stageBuffer[sq];\n return cell === BOARD_CELL_WK || cell === BOARD_CELL_BK;\n };\n\n const computeLegalTargets = (fromBoard: Uint8Array): ReadonlySet<SquareIndex> => {\n if (selected === null) return EMPTY_SET;\n const pieceOnSquare = fromBoard[selected];\n // No piece there → no targets (avoids a WASM call).\n if (pieceOnSquare === 0 || pieceOnSquare === undefined) return EMPTY_SET;\n\n const hash = engine.hash();\n let tos = legalMoveIndex.get(hash, selected);\n if (tos === undefined) {\n const moves = engine.legalMoves(selected);\n const buf = new Uint8Array(moves.length);\n for (let i = 0; i < moves.length; i++) {\n const m = moves[i];\n if (m === undefined) continue;\n buf[i] = moveTo(m);\n }\n legalMoveIndex.set(hash, selected, buf);\n tos = buf;\n }\n if (tos.length === 0) return EMPTY_SET;\n const set = new Set<SquareIndex>();\n for (let i = 0; i < tos.length; i++) {\n const t = tos[i];\n if (t !== undefined) set.add(t as SquareIndex);\n }\n return set;\n };\n\n const buildSnapshot = (): BoardSnapshot => {\n const board = readBoardCopy();\n const legalTargets = computeLegalTargets(board);\n const snap: BoardSnapshot = {\n board,\n turn: engine.turn(),\n hash: engine.hash(),\n lastMove,\n selected,\n legalTargets,\n inCheck: engine.inCheck(),\n isGameOver: engine.isGameOver(),\n historyPly: history.length,\n historyLength: history.length + redoStack.length,\n arrows: arrowModel.arrows,\n premoves: premoveBuffer.all,\n };\n return freezeSnapshots ? Object.freeze(snap) : snap;\n };\n\n const store: BoardStore = createBoardStore(buildSnapshot());\n\n /**\n * Commit a fresh snapshot. If a packed move triggered the change, pass it\n * so the animation planner can take the fast path.\n */\n const commitWith = (triggerMove: PackedMove | null): void => {\n const prev = store.getSnapshot();\n const next = buildSnapshot();\n lastAnimations = planAnimations(prev.board, next.board, triggerMove);\n store.commit(next);\n };\n\n const tryApplyPremoves = (): PackedMove | null => {\n let last: PackedMove | null = null;\n while (premoveBuffer.length > 0) {\n const pm = premoveBuffer.peek();\n if (pm === undefined) break;\n const m = engine.makeMove(pm.from, pm.to, pm.promotion);\n if (m === null) {\n // Lichess semantics: first failure voids every queued premove.\n premoveBuffer.clear();\n break;\n }\n premoveBuffer.shift();\n history.push(m);\n last = m;\n }\n return last;\n };\n\n const selectSquare = (index: SquareIndex | null): void => {\n if (selected === index) return;\n selected = index;\n commitWith(null);\n };\n\n const tryMove = (\n from: SquareIndex,\n to: SquareIndex,\n promotion?: PieceType,\n ): PackedMove | null => {\n const resolvedTo = normalizeCastlingTarget(from, to, isKingOn(from));\n let m = engine.makeMove(from, resolvedTo, promotion);\n if (m === null && resolvedTo !== to) {\n m = engine.makeMove(from, to, promotion);\n }\n if (m === null) return null;\n // A fresh move invalidates the redo line.\n redoStack.length = 0;\n history.push(m);\n lastMove = m;\n selected = null;\n const last = tryApplyPremoves();\n // Animation fast-path uses the triggering user move. Any premoves that\n // auto-applied on top are folded into the same commit; their animation\n // falls back to byte-diff (acceptable for this M1 pass, tightened later).\n if (last === null) {\n commitWith(m);\n } else {\n lastMove = last;\n commitWith(null);\n }\n return m;\n };\n\n const undo = (): PackedMove | null => {\n const m = engine.undo();\n if (m === null) return null;\n redoStack.push(m);\n history.pop();\n lastMove = history[history.length - 1] ?? null;\n selected = null;\n commitWith(null);\n return m;\n };\n\n const redo = (): PackedMove | null => {\n const m = redoStack.pop();\n if (m === undefined) return null;\n const from = ((m as unknown as number) & 0x3f) as SquareIndex;\n const to = moveTo(m);\n const promoBits = ((m as unknown as number) >> 12) & 0x0f;\n const promotion = promoBits > 0 ? (promoBits as PieceType) : undefined;\n const applied = engine.makeMove(from, to, promotion);\n if (applied === null) {\n // Out-of-sync — don't crash; drop the bad entry.\n return null;\n }\n history.push(applied);\n lastMove = applied;\n selected = null;\n commitWith(applied);\n return applied;\n };\n\n const goto = (ply: number): void => {\n if (!Number.isInteger(ply) || ply < 0) return;\n const total = history.length + redoStack.length;\n if (ply > total) return;\n // Walk backwards until history.length === ply, stashing undone onto redo.\n while (history.length > ply) {\n const m = engine.undo();\n if (m === null) break;\n redoStack.push(m);\n history.pop();\n }\n // Walk forwards until history.length === ply, popping off redo.\n while (history.length < ply) {\n const m = redoStack.pop();\n if (m === undefined) break;\n const from = ((m as unknown as number) & 0x3f) as SquareIndex;\n const to = moveTo(m);\n const promoBits = ((m as unknown as number) >> 12) & 0x0f;\n const promotion = promoBits > 0 ? (promoBits as PieceType) : undefined;\n const applied = engine.makeMove(from, to, promotion);\n if (applied === null) break;\n history.push(applied);\n }\n lastMove = history[history.length - 1] ?? null;\n selected = null;\n commitWith(null);\n };\n\n const load = (fen: string): void => {\n engine.load(fen);\n history.length = 0;\n redoStack.length = 0;\n premoveBuffer.clear();\n arrowModel.clear();\n selected = null;\n lastMove = null;\n legalMoveIndex.clear();\n commitWith(null);\n };\n\n const syncPosition = ({\n fen,\n managedArrows,\n preserveUserArrows = false,\n }: SyncPositionOptions): void => {\n const positionChanged = engine.fen() !== fen;\n\n if (positionChanged) {\n engine.load(fen);\n history.length = 0;\n redoStack.length = 0;\n premoveBuffer.clear();\n if (preserveUserArrows) {\n if (managedArrows !== undefined) {\n arrowModel.setManaged(managedArrows);\n }\n } else {\n arrowModel.clear();\n if (managedArrows !== undefined) {\n arrowModel.setManaged(managedArrows);\n }\n }\n selected = null;\n lastMove = null;\n legalMoveIndex.clear();\n commitWith(null);\n return;\n }\n\n if (managedArrows === undefined) {\n return;\n }\n arrowModel.setManaged(managedArrows);\n if (arrowModel.lastChanged) commitWith(null);\n };\n\n const reset = (): void => {\n engine.reset();\n history.length = 0;\n redoStack.length = 0;\n premoveBuffer.clear();\n arrowModel.clear();\n selected = null;\n lastMove = null;\n legalMoveIndex.clear();\n commitWith(null);\n };\n\n const isLegal = (from: SquareIndex, to: SquareIndex, promotion?: PieceType): boolean => {\n const resolvedTo = normalizeCastlingTarget(from, to, isKingOn(from));\n const hash = engine.hash();\n const cached = legalMoveIndex.get(hash, from);\n if (cached !== undefined && promotion === undefined) {\n for (let i = 0; i < cached.length; i++) {\n if (cached[i] === resolvedTo || cached[i] === to) return true;\n }\n return false;\n }\n const moves = engine.legalMoves(from);\n for (let i = 0; i < moves.length; i++) {\n const m = moves[i];\n if (m === undefined) continue;\n const target = moveTo(m);\n if (target !== resolvedTo && target !== to) continue;\n if (promotion === undefined) return true;\n const promoBits = ((m as unknown as number) >> 12) & 0x0f;\n if (promoBits === 0) return true;\n if ((promoBits as PieceType) === promotion) return true;\n }\n return false;\n };\n\n const legalFrom = (from: SquareIndex): ReadonlySet<SquareIndex> => {\n const hash = engine.hash();\n let tos = legalMoveIndex.get(hash, from);\n if (tos === undefined) {\n const moves = engine.legalMoves(from);\n const buf = new Uint8Array(moves.length);\n for (let i = 0; i < moves.length; i++) {\n const m = moves[i];\n if (m === undefined) continue;\n buf[i] = moveTo(m);\n }\n legalMoveIndex.set(hash, from, buf);\n tos = buf;\n }\n if (tos.length === 0) return EMPTY_SET;\n const set = new Set<SquareIndex>();\n for (let i = 0; i < tos.length; i++) {\n const t = tos[i];\n if (t !== undefined) {\n set.add(t as SquareIndex);\n // Dual-input castling: add standard 2-square landing destination\n // when the canonical King-captures-Rook move is legal.\n if (from === 4) {\n if (t === 7) set.add(6 as SquareIndex);\n else if (t === 0) set.add(2 as SquareIndex);\n } else if (from === 60) {\n if (t === 63) set.add(62 as SquareIndex);\n else if (t === 56) set.add(58 as SquareIndex);\n }\n }\n }\n return set;\n };\n\n const addArrow = (arrow: Arrow): void => {\n arrowModel.add(arrow);\n if (arrowModel.lastChanged) commitWith(null);\n };\n const removeArrow = (arrow: Arrow): void => {\n arrowModel.remove(arrow);\n if (arrowModel.lastChanged) commitWith(null);\n };\n const toggleArrow = (arrow: Arrow): void => {\n arrowModel.toggle(arrow);\n if (arrowModel.lastChanged) commitWith(null);\n };\n const clearArrows = (): void => {\n arrowModel.clear();\n if (arrowModel.lastChanged) commitWith(null);\n };\n const clearUserArrows = (): void => {\n arrowModel.clearUser();\n if (arrowModel.lastChanged) commitWith(null);\n };\n const clearManagedArrows = (): void => {\n arrowModel.clearManaged();\n if (arrowModel.lastChanged) commitWith(null);\n };\n const setArrows = (arrows: readonly Arrow[]): void => {\n arrowModel.setAll(arrows);\n if (arrowModel.lastChanged) commitWith(null);\n };\n const setManagedArrows = (arrows: readonly Arrow[]): void => {\n arrowModel.setManaged(arrows);\n if (arrowModel.lastChanged) commitWith(null);\n };\n\n const queuePremove = (premove: Premove): void => {\n premoveBuffer.push(premove);\n commitWith(null);\n };\n const clearPremoves = (): void => {\n if (premoveBuffer.length === 0) return;\n premoveBuffer.clear();\n commitWith(null);\n };\n\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n engine.dispose();\n legalMoveIndex.clear();\n history.length = 0;\n redoStack.length = 0;\n premoveBuffer.clear();\n arrowModel.clear();\n };\n\n return {\n getSnapshot: () => store.getSnapshot(),\n subscribe: (l) => store.subscribe(l),\n subscribeSquare: (i, l) => store.subscribeSquare(i, l),\n\n selectSquare,\n tryMove,\n undo,\n redo,\n goto,\n load,\n syncPosition,\n reset,\n\n isLegal,\n legalFrom,\n\n addArrow,\n removeArrow,\n toggleArrow,\n clearArrows,\n clearUserArrows,\n clearManagedArrows,\n setArrows,\n setManagedArrows,\n\n queuePremove,\n clearPremoves,\n\n drag,\n legalMoveCache: legalMoveIndex,\n engine,\n get lastAnimations() {\n return lastAnimations;\n },\n\n dispose,\n };\n}\n","/**\n * Abstract engine protocol.\n *\n * The board model speaks to a chess engine exclusively through an\n * `EngineAdapter`. Swapping the default `gigachess` adapter for another\n * (chess.js, a variant engine, a custom server-backed validator) should not\n * require changes to `board-model` or any React code.\n *\n * All methods are synchronous: adapter construction absorbs any async init.\n * Every call is expected to be cheap in the steady state. Long-running adapters\n * should cache aggressively on their own side.\n */\n\nimport type { BoardCell, Color, PackedMove, PieceType, SquareIndex, ZobristKey } from \"./types.js\";\n\n/** The engine protocol. */\nexport interface EngineAdapter {\n /**\n * Play a legal move. Returns the packed move on success, `null` if the move\n * is illegal in the current position. Never throws on illegal input —\n * callers may pass arbitrary from/to pairs (e.g. drag-and-drop drops onto\n * any square).\n */\n makeMove(from: SquareIndex, to: SquareIndex, promotion?: PieceType): PackedMove | null;\n\n /** Undo the most recent move. Returns the undone move, or `null` if none. */\n undo(): PackedMove | null;\n\n /**\n * Legal moves from a single origin square (`from` provided) or all legal\n * moves (`from` omitted). The returned array is fresh on every call; the\n * caller is free to retain or discard it.\n */\n legalMoves(from?: SquareIndex): readonly PackedMove[];\n\n /**\n * Fill `out` with the current position as 64 `BoardCell` bytes (LERF). The\n * caller supplies the buffer so adapters can avoid allocating per commit;\n * `out.length` must be `64`.\n */\n readBoard(out: Uint8Array): void;\n\n /** Current FEN. */\n fen(): string;\n\n /** Side to move. */\n turn(): Color;\n\n /** Zobrist hash of the current position. */\n hash(): ZobristKey | bigint;\n\n /** `true` if the side to move is in check. */\n inCheck(): boolean;\n\n /**\n * Render a packed move as SAN (e.g. `\"Nf3\"`, `\"O-O\"`, `\"exd5\"`, `\"e8=Q+\"`).\n * Used by the React layer's screen-reader announcer.\n *\n * Must be called BEFORE the move is played — SAN depends on the\n * pre-move position for disambiguation and check markers.\n */\n san(move: PackedMove): string;\n\n /** `true` if the position ends the game (mate, stalemate, draw). */\n isGameOver(): boolean;\n\n /** Load a FEN into the engine, replacing the current position and history. */\n load(fen: string): void;\n\n /** Reset to the starting position. Clears history. */\n reset(): void;\n\n /** Release engine resources. */\n dispose(): void;\n}\n\n/**\n * Opaque board-cell setter — lets adapters paint individual bytes into `out`\n * without repeatedly importing `types.ts`'s `encodeBoardCell`.\n *\n * @param out Target 64-byte buffer.\n * @param index LERF square index.\n * @param cell The pre-encoded board cell value.\n */\nexport function writeBoardCell(out: Uint8Array, index: SquareIndex, cell: BoardCell): void {\n out[index] = cell;\n}\n","/**\n * `gigaboard/core` — framework-agnostic state machine for Gigaboard.\n *\n * Zero React, zero DOM. This barrel is hand-curated; sub-modules are never\n * re-exported wholesale so consumers can tree-shake aggressively.\n */\n\n// ---- Gigachess adapter ----\nexport {\n createGigachessAdapter,\n preloadGigachessAdapter,\n} from \"./adapters/gigachess.js\";\n// ---- Animation planner ----\nexport { animationInspect, decodePackedMove, planAnimations } from \"./animation-planner.js\";\n// ---- Arrow model ----\nexport type { ArrowModel } from \"./arrow-model.js\";\nexport { createArrowModel, makeArrow } from \"./arrow-model.js\";\n// ---- Board model ----\nexport type { BoardModel, BoardModelOptions, SyncPositionOptions } from \"./board-model.js\";\nexport { createBoardModel } from \"./board-model.js\";\n// ---- Drag controller ----\nexport type {\n CancelEvent,\n ClickEvent,\n DragController,\n DragControllerOptions,\n DragEvent,\n DragMoveEvent,\n DragStartEvent,\n DropEvent,\n} from \"./drag-controller.js\";\nexport { createDragController } from \"./drag-controller.js\";\n// ---- Engine adapter protocol ----\nexport type { EngineAdapter } from \"./engine-adapter.js\";\nexport { writeBoardCell } from \"./engine-adapter.js\";\n// ---- Legal-move cache ----\nexport type {\n LegalMoveEntry,\n LegalMoveIndex,\n LegalMoveIndexOptions,\n PositionHash,\n} from \"./legal-move-index.js\";\nexport { createLegalMoveIndex } from \"./legal-move-index.js\";\n// ---- Premove buffer ----\nexport type { PremoveBuffer } from \"./premove-buffer.js\";\nexport { createPremoveBuffer, makePremove } from \"./premove-buffer.js\";\n// ---- Subscribe store ----\nexport type { BoardStore, Unsubscribe } from \"./subscribe-store.js\";\nexport { createBoardStore } from \"./subscribe-store.js\";\n// ---- Types ----\nexport type {\n AnimDescriptor,\n Arrow,\n ArrowCustomSvg,\n ArrowHeadStyle,\n ArrowLabel,\n BoardCell,\n BoardSnapshot,\n DragState,\n PackedMove,\n Premove,\n SquareIndex,\n ZobristKey,\n} from \"./types.js\";\nexport {\n BOARD_CELL_BB,\n BOARD_CELL_BK,\n BOARD_CELL_BN,\n BOARD_CELL_BP,\n BOARD_CELL_BQ,\n BOARD_CELL_BR,\n BOARD_CELL_EMPTY,\n BOARD_CELL_WB,\n BOARD_CELL_WK,\n BOARD_CELL_WN,\n BOARD_CELL_WP,\n BOARD_CELL_WQ,\n BOARD_CELL_WR,\n Color,\n colorOf,\n encodeBoardCell,\n isEmptyCell,\n isSquareIndex,\n MOVE2_PROMO_BISHOP,\n MOVE2_PROMO_KNIGHT,\n MOVE2_PROMO_NONE,\n MOVE2_PROMO_QUEEN,\n MOVE2_PROMO_ROOK,\n PieceType,\n packMove,\n pieceTypeOf,\n toSquareIndex,\n unpackMove,\n} from \"./types.js\";\n\n/** Package version. Baked in at build time by the consumer's bundler. */\nexport const PACKAGE_VERSION = \"1.3.3\";\n"]}
@@ -48,7 +48,7 @@ var BOARD_CELL_BR = 10;
48
48
  var BOARD_CELL_BQ = 11;
49
49
  var BOARD_CELL_BK = 12;
50
50
  function toSquareIndex(n) {
51
- if (process.env["NODE_ENV"] !== "production") {
51
+ if (typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production") {
52
52
  if (!Number.isInteger(n) || n < 0 || n > 63) {
53
53
  throw new RangeError(`SquareIndex out of range: ${n}`);
54
54
  }
@@ -180,7 +180,7 @@ function createGigachessAdapter(fen) {
180
180
  return out;
181
181
  };
182
182
  const readBoard = (out) => {
183
- if (process.env["NODE_ENV"] !== "production") {
183
+ if (typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production") {
184
184
  if (out.length !== 64) {
185
185
  throw new RangeError("readBoard: out.length must be 64");
186
186
  }
@@ -238,7 +238,7 @@ var PROMO_PIECE = [
238
238
  PieceType.Queen
239
239
  ];
240
240
  function planAnimations(prev, next, move) {
241
- if (process.env["NODE_ENV"] !== "production") {
241
+ if (typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production") {
242
242
  if (prev.length !== 64 || next.length !== 64) {
243
243
  throw new RangeError("planAnimations: board buffers must be length 64");
244
244
  }
@@ -728,7 +728,8 @@ var EMPTY_SET = Object.freeze(
728
728
  function moveTo(m) {
729
729
  return m >> 6 & 63;
730
730
  }
731
- function normalizeCastlingTarget(from, to) {
731
+ function normalizeCastlingTarget(from, to, isKing) {
732
+ if (!isKing) return to;
732
733
  if (from === 4) {
733
734
  if (to === 6) return 7;
734
735
  if (to === 2) return 0;
@@ -755,6 +756,11 @@ function createBoardModel(engine, options = {}) {
755
756
  engine.readBoard(stageBuffer);
756
757
  return new Uint8Array(stageBuffer);
757
758
  };
759
+ const isKingOn = (sq) => {
760
+ engine.readBoard(stageBuffer);
761
+ const cell = stageBuffer[sq];
762
+ return cell === BOARD_CELL_WK || cell === BOARD_CELL_BK;
763
+ };
758
764
  const computeLegalTargets = (fromBoard) => {
759
765
  if (selected === null) return EMPTY_SET;
760
766
  const pieceOnSquare = fromBoard[selected];
@@ -828,7 +834,7 @@ function createBoardModel(engine, options = {}) {
828
834
  commitWith(null);
829
835
  };
830
836
  const tryMove = (from, to, promotion) => {
831
- const resolvedTo = normalizeCastlingTarget(from, to);
837
+ const resolvedTo = normalizeCastlingTarget(from, to, isKingOn(from));
832
838
  let m = engine.makeMove(from, resolvedTo, promotion);
833
839
  if (m === null && resolvedTo !== to) {
834
840
  m = engine.makeMove(from, to, promotion);
@@ -955,7 +961,7 @@ function createBoardModel(engine, options = {}) {
955
961
  commitWith(null);
956
962
  };
957
963
  const isLegal = (from, to, promotion) => {
958
- const resolvedTo = normalizeCastlingTarget(from, to);
964
+ const resolvedTo = normalizeCastlingTarget(from, to, isKingOn(from));
959
965
  const hash = engine.hash();
960
966
  const cached = legalMoveIndex.get(hash, from);
961
967
  if (cached !== void 0 && promotion === void 0) {
@@ -1144,5 +1150,5 @@ exports.preloadGigachessAdapter = preloadGigachessAdapter;
1144
1150
  exports.toSquareIndex = toSquareIndex;
1145
1151
  exports.unpackMove = unpackMove;
1146
1152
  exports.writeBoardCell = writeBoardCell;
1147
- //# sourceMappingURL=chunk-ENYRJ4Q2.cjs.map
1148
- //# sourceMappingURL=chunk-ENYRJ4Q2.cjs.map
1153
+ //# sourceMappingURL=chunk-K7D2C72S.cjs.map
1154
+ //# sourceMappingURL=chunk-K7D2C72S.cjs.map