2026-03-21 09:44:05 -07:00
|
|
|
import type { Socket } from "socket.io";
|
|
|
|
|
import { Server as SocketIOServer } from "socket.io";
|
2025-10-18 22:16:04 -07:00
|
|
|
import type { Server as HTTPServer } from "http";
|
2026-02-23 23:23:24 -08:00
|
|
|
import * as schema from "~/database/schema";
|
fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms (#48)
* fix: sync all draft state on mobile reconnection
After a mobile browser returns from a long background period, the draft
room had stale picks, wrong "on the clock" display, and inaccurate
available player lists. The root cause was that reconnection relied
solely on an HTTP revalidation that could fail (expired JWT, flaky
network), and the timer-update handler ignored currentPickNumber.
Changes:
- Server emits draft-state-sync on join-draft with full picks, timers,
and season state, giving the client an immediate socket-based sync
path that doesn't depend on HTTP revalidation
- timer-update handler now syncs currentPickNumber, fixing the "on the
clock" display within 1 second of reconnection
- Revalidation retry with 3s delay ensures the HTTP path succeeds even
when the network is slow to stabilize on mobile return
- Revalidation completion now also syncs teamTimers and autodraftStatus
- Added draft-state-sync client handler that applies the server snapshot
immediately (skipped when revalidation is in-flight to avoid conflicts)
Tests: 32 new tests covering reconnection sync, pick buffering/merge,
timer-update currentPickNumber sync, draft-state-sync handling,
available player filtering, on-the-clock correctness, and revalidation
retry logic.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
* fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-01 12:23:24 -08:00
|
|
|
import { eq, and, asc } from "drizzle-orm";
|
2026-03-21 13:41:39 -07:00
|
|
|
import { logger } from "./logger";
|
Add CS2 Major Qualifying Points simulator and stage management (#260)
* Add CS2 Major qualifying points simulator
Implements a full CS2 Major tournament simulator with:
- 3-stage Swiss format (Opening Bo1, Elimination Bo1/Bo3, Decider all Bo3)
+ Champions Stage 8-team single-elimination (QF Bo3, SF Bo3, GF Bo5)
- Monte Carlo simulation (10,000 iterations) accumulating QP across 2 majors/season
- Sampled 24-team field per iteration: top 12 guaranteed, remaining weighted by 1/rank
- Stage 3 exits (placements 9-16) sub-ranked by W-L record (2-3 > 1-3 > 0-3)
- Stage assignments stored per-event so actual field composition drives simulation
- Admin CS Elo form for entering team Elo + HLTV world rankings
- Admin CS2 stage setup page for assigning teams to stages and tracking advancement
- Database migration: cs2_major_qualifying_points enum value + cs2_major_stage_results table
- 24 unit tests covering all exported pure functions
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate Elo + ranking input into generic elo-ratings page
The darts-elo and cs-elo pages were unreachable from the admin nav,
which always links to the generic elo-ratings page. Extended elo-ratings
to conditionally show world ranking fields for simulator types that need
it (darts_bracket, cs2_major_qualifying_points), then deleted the
redundant sport-specific pages.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate server postgres connections into one shared pool
Four separate postgres() clients were open simultaneously (app, timer,
snapshots, socket), each defaulting to 10 connections, exhausting the
database's max_connections limit. Replaced with a single shared lazy-
initialized client in server/db.ts using a Proxy to defer the
DATABASE_URL check until first use (preserving test compatibility).
Also bumps the CS2 Champions Stage stochastic test from 200 → 1000
iterations to eliminate flakiness.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix and() bug and add Swiss loop safety guard
- cs2-major-stage.ts: markCs2StageEliminations and setCs2FinalPlacements
were using JS && instead of Drizzle and(), causing WHERE to filter only
by participantId (not scoringEventId), which would update rows across
all events instead of just the target event
- cs-major-simulator.ts: add break guard in simulateSwiss while loop to
prevent infinite loop if pairGroups returns no pairs
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix all remaining code review issues
- cs2-major-stage.ts: use schema column reference for stageEliminated
in markCs2StageEliminations instead of raw SQL string
- cs-major-simulator.ts: simulateOneMajor now locks in known stage
results when a stage is complete (8 recorded eliminations), only
simulating the remaining stages during live events
- admin event page: add CS2 Stage Setup button for cs2_major_qualifying_points
simulator types; expose simulatorType in server loader type cast
- cs2-setup.tsx: replace document.getElementById DOM manipulation with
React state (eliminatedChecked map) for checkbox show/hide logic;
remove unused stageMap and unassignedParticipants variables
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix oxlint errors: non-null assertions, sort→toSorted, unused vars
- cs-major-simulator.ts: replace 5 non-null assertions (!) with safe
optional chaining / if-guards; replace 6 .sort() with .toSorted()
- cs2-major-stage.ts: remove unused `inArray` import
- cs2-setup.tsx: remove unused `assignedIds` variable
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix flaky Champions Stage stochastic test
The makeTeams(8) helper creates only a 70-pt Elo spread (1800→1730).
With the Champions Stage bracket math this gives team-0 a ~19.6% win
rate — right at the 0.2 threshold, causing the test to fail ~63% of
the time in CI despite 1000 iterations.
Use 100-pt steps (1800→1100) instead, giving team-0 a ~40% win rate
and raising the assertion threshold to 0.25 for a clear safety margin.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 13:40:05 -07:00
|
|
|
import { db } from "./db";
|
2025-10-16 18:15:04 -07:00
|
|
|
|
2025-10-18 22:16:04 -07:00
|
|
|
// Socket event types
|
|
|
|
|
interface ServerToClientEvents {
|
|
|
|
|
"test-message": (data: {
|
2026-03-21 09:44:05 -07:00
|
|
|
originalMessage: unknown;
|
2025-10-18 22:16:04 -07:00
|
|
|
serverResponse: string;
|
|
|
|
|
serverTimestamp: string;
|
|
|
|
|
socketId: string;
|
|
|
|
|
}) => void;
|
2026-03-21 09:44:05 -07:00
|
|
|
"pick-made": (data: unknown) => void;
|
2025-10-18 22:16:04 -07:00
|
|
|
"draft-started": (data: { seasonId: string; currentPickNumber: number }) => void;
|
|
|
|
|
"draft-completed": () => void;
|
2026-04-30 10:14:14 -07:00
|
|
|
"draft-room-closed": () => void;
|
2025-10-18 22:16:04 -07:00
|
|
|
"timer-update": (data: {
|
|
|
|
|
seasonId: string;
|
|
|
|
|
teamId: string;
|
|
|
|
|
timeRemaining: number;
|
|
|
|
|
currentPickNumber: number;
|
|
|
|
|
}) => void;
|
2025-10-21 23:22:17 -07:00
|
|
|
"autodraft-updated": (data: {
|
|
|
|
|
teamId: string;
|
|
|
|
|
isEnabled: boolean;
|
|
|
|
|
mode: "next_pick" | "while_on";
|
Claude/redesign autodraft queue c4 kp r (#40)
* Redesign autodraft queue system with three-state control and queue-only constraint
Core Logic & Database:
- Add `queue_only` boolean column to `autodraft_settings` (migration 0031)
- Rename autodraft UI states: Off / Next Pick / All Picks (while_on mode maps to All Picks)
- `autoPickForTeam`: respects new `queueOnly` param — skips EV fallback when enabled
- `executeAutoPick`: auto-disables autodraft + emits socket event when queue empties with queueOnly ON (AC3)
- `autodraft-updated` socket event now includes `queueOnly` field
Mobile UI Overhaul:
- Rename "Lobby" tab → "Available" (AC6)
- Add new "Queue" tab to mobile bottom nav with drag-reorder, per-item Draft buttons, and autodraft controls (AC5)
- Controls tab retains commissioner tools, notifications, exit; queue controls moved to Queue tab
- Turn indicator appears on both Available and Queue tabs
Components:
- `AutodraftSettings`: replaces toggle+radio with three-state button group (Off | Next Pick | All Picks) + "Only autodraft from queue" switch (AC1, AC2)
- `QueueSection`: adds `canPick` prop + per-item Draft buttons for instant drafting when on the clock
Desktop (AC4):
- Sidebar QueueSection unchanged in position; gains same three-state controls and Draft buttons
Tests (AC7):
- `autodraft.test.ts`: updated for queueOnly field and socket event shape
- `timer-autodraft.test.ts`: new tests for queue-only constraint, auto-shutoff transitions, and all three autodraft states
https://claude.ai/code/session_01PYhJicAStoJ2u6q6dV1naB
* fix: remove erroneous ?? fallbacks in autodraft socket emissions and add autoPickForTeam tests
- Remove `?? true` default on queueOnly in queue-empty auto-disable socket emit
(line 488) — was dead code since the column is NOT NULL, but semantically wrong
and would have caused client-side UI desync if the type ever relaxed
- Remove `?? false` default on the next_pick auto-disable path for consistency
- Add app/models/__tests__/auto-pick.test.ts with 6 tests covering the queueOnly
constraint: empty queue, all items drafted, partial queue skip, and EV fallback
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: add missing queueOnly prop to AutodraftSettings test fixtures
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* test: rewrite AutodraftSettings tests for three-state button group UI
The component was redesigned from a switch + radio buttons to Off/Next Pick/All Picks
buttons with a separate queue-only Switch toggle. Updated 17 stale tests and added 5
new tests covering the queue-only toggle and the All Picks/Off button interactions.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-02-27 22:16:26 -08:00
|
|
|
queueOnly: boolean;
|
2026-03-03 20:14:38 -08:00
|
|
|
source?: "commissioner" | "user";
|
2025-10-21 23:22:17 -07:00
|
|
|
}) => void;
|
|
|
|
|
"team-connected": (data: { teamId: string }) => void;
|
|
|
|
|
"team-disconnected": (data: { teamId: string }) => void;
|
2025-10-24 21:31:57 -07:00
|
|
|
"connected-teams-list": (data: { teamIds: string[] }) => void;
|
Claude/fix pick timer ghll n (#29)
* Fix force-manual-pick resetting next team's timer to initial time
When a commissioner forced a manual pick, the next team's timer was
being reset to the initial time (2 minutes) instead of carrying
forward their existing time bank balance.
This aligns force-manual-pick with the behavior of regular user picks
and force-autopick: the picking team gets their increment added, and
the next team's timer is left untouched so their bank carries forward.
https://claude.ai/code/session_01X7gwWmafUSEvVHcV7Raz5p
* Add regression tests for draft.force-manual-pick timer behavior
18 tests across 5 describe blocks covering:
- Authorization (401/403)
- Input validation (missing fields, bad participant, ineligible sport)
- Successful pick (response shape, draft-complete detection, socket events)
- Timer behavior (increment added to picking team, new timer creation, additive not reset)
- Two regression tests confirming the next team's timer is never touched:
draftTimers.findFirst called exactly once, no timer-update emitted for
next team, db.update called exactly twice (not three times)
https://claude.ai/code/session_01X7gwWmafUSEvVHcV7Raz5p
* Add TypeScript types and improve draft validation (#28)
* Code review fixes: type safety, security hardening, and dead code removal
- Fix Socket.IO event types: draft-paused and draft-resumed were typed as
() => void but are emitted with { seasonId, paused } data payloads
- Fix draft.force-manual-pick: add missing season.status === "draft" guard
so commissioners cannot force picks outside an active draft; add duplicate
pick-number check so a slot cannot be assigned two picks (the previous
code only checked participant uniqueness, not slot uniqueness)
- Replace args: any with ActionFunctionArgs / Route.LoaderArgs across all
API routes and league loaders; replace (auth as any).userId casts with
proper const { userId } = await getAuth(args) destructuring
- Remove unused isSnakeDraft = true dead variable from draft.make-pick
- Replace autodraftSettings: any and draftSlots: any[] in draft-utils with
properly typed InferSelectModel / DraftSlot types
- Update force-manual-pick tests: sequence draftPicks.findFirst mock for
the two-call flow; add new tests for status-check and slot-uniqueness
https://claude.ai/code/session_01FKq2gPFYpgdfxr8cw4Z2AZ
* Fix RouterContextProvider type errors in action test files
Cast context argument to RouterContextProvider in test helpers so
ActionFunctionArgs strict typing is satisfied without weakening the
production action signatures back to any.
https://claude.ai/code/session_01FKq2gPFYpgdfxr8cw4Z2AZ
---------
Co-authored-by: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-02-22 19:29:29 -08:00
|
|
|
"draft-paused": (data: { seasonId: string; paused: boolean }) => void;
|
|
|
|
|
"draft-resumed": (data: { seasonId: string; paused: boolean }) => void;
|
2025-10-24 21:46:55 -07:00
|
|
|
"participant-removed-from-queues": (data: { participantId: string }) => void;
|
2026-03-04 21:39:54 -08:00
|
|
|
"queue-updated": (data: { queue: Array<{ id: string; teamId: string; seasonId: string; participantId: string; queuePosition: number }> }) => void;
|
2026-04-29 11:49:26 -07:00
|
|
|
"watchlist-updated": (data: { participantIds: string[] }) => void;
|
fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms (#48)
* fix: sync all draft state on mobile reconnection
After a mobile browser returns from a long background period, the draft
room had stale picks, wrong "on the clock" display, and inaccurate
available player lists. The root cause was that reconnection relied
solely on an HTTP revalidation that could fail (expired JWT, flaky
network), and the timer-update handler ignored currentPickNumber.
Changes:
- Server emits draft-state-sync on join-draft with full picks, timers,
and season state, giving the client an immediate socket-based sync
path that doesn't depend on HTTP revalidation
- timer-update handler now syncs currentPickNumber, fixing the "on the
clock" display within 1 second of reconnection
- Revalidation retry with 3s delay ensures the HTTP path succeeds even
when the network is slow to stabilize on mobile return
- Revalidation completion now also syncs teamTimers and autodraftStatus
- Added draft-state-sync client handler that applies the server snapshot
immediately (skipped when revalidation is in-flight to avoid conflicts)
Tests: 32 new tests covering reconnection sync, pick buffering/merge,
timer-update currentPickNumber sync, draft-state-sync handling,
available player filtering, on-the-clock correctness, and revalidation
retry logic.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
* fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-01 12:23:24 -08:00
|
|
|
"draft-state-sync": (data: {
|
|
|
|
|
currentPickNumber: number;
|
|
|
|
|
isPaused: boolean;
|
|
|
|
|
status: string;
|
|
|
|
|
picks: Array<{
|
|
|
|
|
id: string;
|
|
|
|
|
pickNumber: number;
|
|
|
|
|
round: number;
|
|
|
|
|
pickInRound: number;
|
|
|
|
|
timeUsed: number;
|
2026-03-21 09:44:05 -07:00
|
|
|
team: unknown;
|
|
|
|
|
participant: unknown;
|
|
|
|
|
sport: unknown;
|
fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms (#48)
* fix: sync all draft state on mobile reconnection
After a mobile browser returns from a long background period, the draft
room had stale picks, wrong "on the clock" display, and inaccurate
available player lists. The root cause was that reconnection relied
solely on an HTTP revalidation that could fail (expired JWT, flaky
network), and the timer-update handler ignored currentPickNumber.
Changes:
- Server emits draft-state-sync on join-draft with full picks, timers,
and season state, giving the client an immediate socket-based sync
path that doesn't depend on HTTP revalidation
- timer-update handler now syncs currentPickNumber, fixing the "on the
clock" display within 1 second of reconnection
- Revalidation retry with 3s delay ensures the HTTP path succeeds even
when the network is slow to stabilize on mobile return
- Revalidation completion now also syncs teamTimers and autodraftStatus
- Added draft-state-sync client handler that applies the server snapshot
immediately (skipped when revalidation is in-flight to avoid conflicts)
Tests: 32 new tests covering reconnection sync, pick buffering/merge,
timer-update currentPickNumber sync, draft-state-sync handling,
available player filtering, on-the-clock correctness, and revalidation
retry logic.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
* fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-01 12:23:24 -08:00
|
|
|
}>;
|
|
|
|
|
timers: Array<{
|
|
|
|
|
teamId: string;
|
|
|
|
|
timeRemaining: number;
|
|
|
|
|
}>;
|
2026-03-04 21:39:54 -08:00
|
|
|
queue?: Array<{
|
|
|
|
|
id: string;
|
|
|
|
|
teamId: string;
|
|
|
|
|
seasonId: string;
|
|
|
|
|
participantId: string;
|
|
|
|
|
queuePosition: number;
|
|
|
|
|
}>;
|
2026-04-29 11:49:26 -07:00
|
|
|
watchlistParticipantIds?: string[];
|
fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms (#48)
* fix: sync all draft state on mobile reconnection
After a mobile browser returns from a long background period, the draft
room had stale picks, wrong "on the clock" display, and inaccurate
available player lists. The root cause was that reconnection relied
solely on an HTTP revalidation that could fail (expired JWT, flaky
network), and the timer-update handler ignored currentPickNumber.
Changes:
- Server emits draft-state-sync on join-draft with full picks, timers,
and season state, giving the client an immediate socket-based sync
path that doesn't depend on HTTP revalidation
- timer-update handler now syncs currentPickNumber, fixing the "on the
clock" display within 1 second of reconnection
- Revalidation retry with 3s delay ensures the HTTP path succeeds even
when the network is slow to stabilize on mobile return
- Revalidation completion now also syncs teamTimers and autodraftStatus
- Added draft-state-sync client handler that applies the server snapshot
immediately (skipped when revalidation is in-flight to avoid conflicts)
Tests: 32 new tests covering reconnection sync, pick buffering/merge,
timer-update currentPickNumber sync, draft-state-sync handling,
available player filtering, on-the-clock correctness, and revalidation
retry logic.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
* fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-01 12:23:24 -08:00
|
|
|
}) => void;
|
2025-10-18 22:16:04 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface ClientToServerEvents {
|
2025-10-21 23:22:17 -07:00
|
|
|
"join-draft": (seasonId: string, teamId?: string) => void;
|
2025-10-18 22:16:04 -07:00
|
|
|
"leave-draft": (seasonId: string) => void;
|
2026-03-21 09:44:05 -07:00
|
|
|
"test-event": (data: unknown) => void;
|
2025-10-18 22:16:04 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Global type augmentation
|
|
|
|
|
declare global {
|
|
|
|
|
var __socketIO: SocketIOServer | undefined;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let io: SocketIOServer<ClientToServerEvents, ServerToClientEvents> | null = null;
|
2025-10-16 18:15:04 -07:00
|
|
|
|
2026-04-30 10:14:14 -07:00
|
|
|
function scheduleDraftRoomClosure(seasonId: string) {
|
|
|
|
|
if (draftRoomClosureTimers.has(seasonId)) return;
|
|
|
|
|
|
|
|
|
|
const timeout = setTimeout(() => {
|
|
|
|
|
logger.log(`[Socket] Draft room closure: emitting draft-room-closed for ${seasonId}`);
|
|
|
|
|
io?.to(`draft-${seasonId}`).emit("draft-room-closed");
|
|
|
|
|
draftRoomClosureTimers.delete(seasonId);
|
|
|
|
|
}, ROOM_CLOSURE_DELAY_MS);
|
|
|
|
|
|
|
|
|
|
draftRoomClosureTimers.set(seasonId, timeout);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export { scheduleDraftRoomClosure };
|
|
|
|
|
|
2026-02-23 23:23:24 -08:00
|
|
|
// Track connected teams per season (in-memory, single-instance only).
|
|
|
|
|
// If the server restarts or runs as multiple instances this map resets.
|
|
|
|
|
// For multi-instance deployments, replace with a Redis-backed Socket.IO adapter.
|
2025-10-24 21:31:57 -07:00
|
|
|
const connectedTeams = new Map<string, Set<string>>(); // seasonId -> Set<teamId>
|
|
|
|
|
|
2026-04-30 10:14:14 -07:00
|
|
|
const ROOM_CLOSURE_DELAY_MS = 5 * 60 * 1000; // 5 minutes
|
|
|
|
|
const draftRoomClosureTimers = new Map<string, NodeJS.Timeout>(); // seasonId -> timeout
|
|
|
|
|
|
2025-10-16 18:15:04 -07:00
|
|
|
/**
|
|
|
|
|
* Initialize Socket.IO server
|
|
|
|
|
*/
|
2025-10-18 22:16:04 -07:00
|
|
|
export function initializeSocketIO(httpServer: HTTPServer): SocketIOServer {
|
2025-10-16 18:15:04 -07:00
|
|
|
if (io) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log("Socket.IO already initialized");
|
2025-10-16 18:15:04 -07:00
|
|
|
return io;
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-18 22:16:04 -07:00
|
|
|
// Create typed Socket.IO server
|
|
|
|
|
io = new SocketIOServer<ClientToServerEvents, ServerToClientEvents>(httpServer, {
|
2026-02-24 12:24:04 -08:00
|
|
|
// Faster dead-connection detection than the defaults (20s/25s).
|
|
|
|
|
// pingTimeout: how long to wait for a pong before declaring the connection dead.
|
|
|
|
|
// pingInterval: how often to send a ping.
|
|
|
|
|
// Together these detect a crashed server in ~15s instead of ~45s.
|
|
|
|
|
// Trade-off: more heartbeat traffic at scale; revisit if server load becomes a concern.
|
|
|
|
|
pingTimeout: 5000,
|
|
|
|
|
pingInterval: 10000,
|
2025-10-16 18:15:04 -07:00
|
|
|
cors: process.env.NODE_ENV === "production" && process.env.APP_URL
|
|
|
|
|
? {
|
|
|
|
|
origin: process.env.APP_URL,
|
|
|
|
|
credentials: true,
|
|
|
|
|
}
|
2025-10-18 22:16:04 -07:00
|
|
|
: undefined,
|
2025-10-16 18:15:04 -07:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Connection handling
|
2025-10-18 22:16:04 -07:00
|
|
|
io.on("connection", (socket: Socket<ClientToServerEvents, ServerToClientEvents>) => {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log("Client connected:", socket.id);
|
2025-10-16 18:15:04 -07:00
|
|
|
|
2025-10-21 23:22:17 -07:00
|
|
|
// Store team ID for this socket
|
|
|
|
|
let currentTeamId: string | undefined;
|
|
|
|
|
let currentSeasonId: string | undefined;
|
|
|
|
|
|
2026-02-23 23:23:24 -08:00
|
|
|
socket.on("join-draft", async (seasonId: string, teamId?: string) => {
|
2025-10-16 18:15:04 -07:00
|
|
|
if (!seasonId) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("No seasonId provided for join-draft");
|
2025-10-16 18:15:04 -07:00
|
|
|
return;
|
|
|
|
|
}
|
2026-04-30 10:14:14 -07:00
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const seasonData = await db.query.seasons.findFirst({
|
|
|
|
|
where: eq(schema.seasons.id, seasonId),
|
|
|
|
|
columns: { id: true, status: true, draftCompletedAt: true },
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (seasonData?.draftCompletedAt) {
|
|
|
|
|
const elapsed = Date.now() - seasonData.draftCompletedAt.getTime();
|
|
|
|
|
if (elapsed >= ROOM_CLOSURE_DELAY_MS) {
|
|
|
|
|
socket.emit("draft-room-closed");
|
|
|
|
|
logger.log(`[Socket] join-draft rejected for ${seasonId}: room closed (completed ${Math.round(elapsed / 60000)}m ago)`);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!draftRoomClosureTimers.has(seasonId)) {
|
|
|
|
|
const remaining = ROOM_CLOSURE_DELAY_MS - elapsed;
|
|
|
|
|
const timeout = setTimeout(() => {
|
|
|
|
|
logger.log(`[Socket] Draft room closure: emitting draft-room-closed for ${seasonId}`);
|
|
|
|
|
io?.to(`draft-${seasonId}`).emit("draft-room-closed");
|
|
|
|
|
draftRoomClosureTimers.delete(seasonId);
|
|
|
|
|
}, remaining);
|
|
|
|
|
draftRoomClosureTimers.set(seasonId, timeout);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
|
|
|
|
logger.error("[Socket] join-draft room-closure check failed:", err);
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-16 18:15:04 -07:00
|
|
|
socket.join(`draft-${seasonId}`);
|
2025-10-21 23:22:17 -07:00
|
|
|
currentSeasonId = seasonId;
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log(`Socket ${socket.id} joined draft-${seasonId}`);
|
2025-10-21 23:22:17 -07:00
|
|
|
|
2026-02-23 23:23:24 -08:00
|
|
|
// If teamId provided, validate it belongs to this season before tracking
|
2025-10-21 23:22:17 -07:00
|
|
|
if (teamId) {
|
2026-02-23 23:23:24 -08:00
|
|
|
try {
|
|
|
|
|
const team = await db.query.teams.findFirst({
|
|
|
|
|
where: and(eq(schema.teams.id, teamId), eq(schema.teams.seasonId, seasonId)),
|
|
|
|
|
});
|
|
|
|
|
if (!team) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.warn(`[Socket] join-draft rejected: team ${teamId} does not belong to season ${seasonId}`);
|
2026-02-23 23:23:24 -08:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("[Socket] join-draft team validation failed:", err);
|
2026-02-23 23:23:24 -08:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-21 23:22:17 -07:00
|
|
|
currentTeamId = teamId;
|
|
|
|
|
socket.join(`team-${teamId}`);
|
2025-10-24 21:31:57 -07:00
|
|
|
|
|
|
|
|
// Initialize the season's connected teams set if it doesn't exist
|
|
|
|
|
if (!connectedTeams.has(seasonId)) {
|
|
|
|
|
connectedTeams.set(seasonId, new Set());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Get current connected teams for this season
|
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196)
* Fix no-shadow and consistent-function-scoping lint violations
Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint
warnings and promotes both rules to errors in .oxlintrc.json.
no-shadow: renamed Drizzle callback params (sports→s, matches→m,
seasons→s) to avoid shadowing outer imports; removed shadowed
destructures (eq, inArray) from where callbacks; renamed inner
template→bracketTemplate, prev→currentTimers, season→ss, name→teamName
(with name: teamName fix to preserve semantics).
consistent-function-scoping: moved formatDate, getRankBadge,
getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr,
elo (×2), weightedPick, sortByMatchNumber (×2) to module scope;
moved formatTime (×2), isValidLeagueName, getDraftTimes,
makeSeasonQueues to file scope in test files.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix no-non-null-assertion lint violations and promote to error
Eliminates all 208 no-non-null-assertion warnings across 38 files.
Promotes typescript/no-non-null-assertion from warn to error in
.oxlintrc.json.
Fix patterns applied:
- Map.get(key)! after .has() check → extract with get() + null guard
- Map.get(key)! on pre-populated count maps → ?? 0 default
- .set(id, map.get(id)! + 1) increment → ?? 0 before adding
- participant1Id!/participant2Id! on DB matches → ?? "" fallback
- array.find()! in tests → guard + throw or expect().toBeDefined()
- bracketTemplateCache.get(id)! → null guard extract
- Various nullable field accesses → optional chain or ?? default
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers
Resolves all 9 remaining non-console lint warnings and promotes all
three rules to errors in .oxlintrc.json.
- prefer-add-event-listener: converted onchange/onclick/onload
assignments to addEventListener in useDraftNotifications.ts and
admin.data-sync.tsx; stored changeHandler ref for proper cleanup
with removeEventListener
- no-unassigned-import: configured rule with allow list for legitimate
side-effect imports (*.css, @testing-library/jest-dom,
@testing-library/cypress/add-commands)
- require-module-specifiers: removed redundant `export {}` from
cypress/support/e2e.ts (file already has an import)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TypeScript errors from no-non-null-assertion fixes
Two fixes introduced by the non-null assertion cleanup produced type
errors:
- scoring-event.ts: `?? ""` was wrong type for a participant object map;
restructured to explicit null guards so TypeScript can narrow correctly
- standings-sync/index.ts: `?? null` after name-match lookup lost the
truthy guarantee, causing TS18047 on the write-back block; added
`participant &&` guard before accessing its properties
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add npm run typecheck as Stop hook in Claude settings
Runs a full project typecheck at the end of each Claude turn so type
errors surface as feedback before the next message.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00
|
|
|
const seasonConnectedTeams = connectedTeams.get(seasonId) ?? new Set<string>();
|
|
|
|
|
if (!connectedTeams.has(seasonId)) connectedTeams.set(seasonId, seasonConnectedTeams);
|
2025-10-24 21:31:57 -07:00
|
|
|
|
|
|
|
|
// Send the list of already-connected teams to this socket
|
|
|
|
|
socket.emit("connected-teams-list", { teamIds: Array.from(seasonConnectedTeams) });
|
|
|
|
|
|
|
|
|
|
// Add this team to the connected teams set
|
|
|
|
|
seasonConnectedTeams.add(teamId);
|
|
|
|
|
|
|
|
|
|
// Broadcast to everyone else that this team connected
|
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196)
* Fix no-shadow and consistent-function-scoping lint violations
Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint
warnings and promotes both rules to errors in .oxlintrc.json.
no-shadow: renamed Drizzle callback params (sports→s, matches→m,
seasons→s) to avoid shadowing outer imports; removed shadowed
destructures (eq, inArray) from where callbacks; renamed inner
template→bracketTemplate, prev→currentTimers, season→ss, name→teamName
(with name: teamName fix to preserve semantics).
consistent-function-scoping: moved formatDate, getRankBadge,
getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr,
elo (×2), weightedPick, sortByMatchNumber (×2) to module scope;
moved formatTime (×2), isValidLeagueName, getDraftTimes,
makeSeasonQueues to file scope in test files.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix no-non-null-assertion lint violations and promote to error
Eliminates all 208 no-non-null-assertion warnings across 38 files.
Promotes typescript/no-non-null-assertion from warn to error in
.oxlintrc.json.
Fix patterns applied:
- Map.get(key)! after .has() check → extract with get() + null guard
- Map.get(key)! on pre-populated count maps → ?? 0 default
- .set(id, map.get(id)! + 1) increment → ?? 0 before adding
- participant1Id!/participant2Id! on DB matches → ?? "" fallback
- array.find()! in tests → guard + throw or expect().toBeDefined()
- bracketTemplateCache.get(id)! → null guard extract
- Various nullable field accesses → optional chain or ?? default
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers
Resolves all 9 remaining non-console lint warnings and promotes all
three rules to errors in .oxlintrc.json.
- prefer-add-event-listener: converted onchange/onclick/onload
assignments to addEventListener in useDraftNotifications.ts and
admin.data-sync.tsx; stored changeHandler ref for proper cleanup
with removeEventListener
- no-unassigned-import: configured rule with allow list for legitimate
side-effect imports (*.css, @testing-library/jest-dom,
@testing-library/cypress/add-commands)
- require-module-specifiers: removed redundant `export {}` from
cypress/support/e2e.ts (file already has an import)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TypeScript errors from no-non-null-assertion fixes
Two fixes introduced by the non-null assertion cleanup produced type
errors:
- scoring-event.ts: `?? ""` was wrong type for a participant object map;
restructured to explicit null guards so TypeScript can narrow correctly
- standings-sync/index.ts: `?? null` after name-match lookup lost the
truthy guarantee, causing TS18047 on the write-back block; added
`participant &&` guard before accessing its properties
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add npm run typecheck as Stop hook in Claude settings
Runs a full project typecheck at the end of each Claude turn so type
errors surface as feedback before the next message.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00
|
|
|
io?.to(`draft-${seasonId}`).emit("team-connected", { teamId });
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log(`Team ${teamId} connected to draft-${seasonId}. Total connected: ${seasonConnectedTeams.size}`);
|
2025-10-21 23:22:17 -07:00
|
|
|
}
|
fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms (#48)
* fix: sync all draft state on mobile reconnection
After a mobile browser returns from a long background period, the draft
room had stale picks, wrong "on the clock" display, and inaccurate
available player lists. The root cause was that reconnection relied
solely on an HTTP revalidation that could fail (expired JWT, flaky
network), and the timer-update handler ignored currentPickNumber.
Changes:
- Server emits draft-state-sync on join-draft with full picks, timers,
and season state, giving the client an immediate socket-based sync
path that doesn't depend on HTTP revalidation
- timer-update handler now syncs currentPickNumber, fixing the "on the
clock" display within 1 second of reconnection
- Revalidation retry with 3s delay ensures the HTTP path succeeds even
when the network is slow to stabilize on mobile return
- Revalidation completion now also syncs teamTimers and autodraftStatus
- Added draft-state-sync client handler that applies the server snapshot
immediately (skipped when revalidation is in-flight to avoid conflicts)
Tests: 32 new tests covering reconnection sync, pick buffering/merge,
timer-update currentPickNumber sync, draft-state-sync handling,
available player filtering, on-the-clock correctness, and revalidation
retry logic.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
* fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-01 12:23:24 -08:00
|
|
|
|
|
|
|
|
// Send full draft state to the joining client so it can sync immediately.
|
|
|
|
|
// This is critical for mobile reconnection: the client may have been in the
|
|
|
|
|
// background for minutes/hours and missed many picks. The revalidate() path
|
|
|
|
|
// (HTTP loader re-fetch) covers this too, but it can fail due to expired auth
|
|
|
|
|
// tokens or flaky mobile networks. This socket-based sync provides an
|
|
|
|
|
// additional, more reliable path since the socket is already connected.
|
|
|
|
|
try {
|
2026-04-29 11:49:26 -07:00
|
|
|
const [seasonData, picks, timerRows, queueItems, watchlistItems] = await Promise.all([
|
fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms (#48)
* fix: sync all draft state on mobile reconnection
After a mobile browser returns from a long background period, the draft
room had stale picks, wrong "on the clock" display, and inaccurate
available player lists. The root cause was that reconnection relied
solely on an HTTP revalidation that could fail (expired JWT, flaky
network), and the timer-update handler ignored currentPickNumber.
Changes:
- Server emits draft-state-sync on join-draft with full picks, timers,
and season state, giving the client an immediate socket-based sync
path that doesn't depend on HTTP revalidation
- timer-update handler now syncs currentPickNumber, fixing the "on the
clock" display within 1 second of reconnection
- Revalidation retry with 3s delay ensures the HTTP path succeeds even
when the network is slow to stabilize on mobile return
- Revalidation completion now also syncs teamTimers and autodraftStatus
- Added draft-state-sync client handler that applies the server snapshot
immediately (skipped when revalidation is in-flight to avoid conflicts)
Tests: 32 new tests covering reconnection sync, pick buffering/merge,
timer-update currentPickNumber sync, draft-state-sync handling,
available player filtering, on-the-clock correctness, and revalidation
retry logic.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
* fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-01 12:23:24 -08:00
|
|
|
db.query.seasons.findFirst({
|
|
|
|
|
where: eq(schema.seasons.id, seasonId),
|
|
|
|
|
}),
|
|
|
|
|
db
|
|
|
|
|
.select({
|
|
|
|
|
id: schema.draftPicks.id,
|
|
|
|
|
pickNumber: schema.draftPicks.pickNumber,
|
|
|
|
|
round: schema.draftPicks.round,
|
|
|
|
|
pickInRound: schema.draftPicks.pickInRound,
|
|
|
|
|
timeUsed: schema.draftPicks.timeUsed,
|
|
|
|
|
team: schema.teams,
|
|
|
|
|
participant: schema.participants,
|
|
|
|
|
sport: schema.sports,
|
|
|
|
|
})
|
|
|
|
|
.from(schema.draftPicks)
|
|
|
|
|
.innerJoin(schema.teams, eq(schema.draftPicks.teamId, schema.teams.id))
|
|
|
|
|
.innerJoin(
|
|
|
|
|
schema.participants,
|
|
|
|
|
eq(schema.draftPicks.participantId, schema.participants.id)
|
|
|
|
|
)
|
|
|
|
|
.innerJoin(
|
|
|
|
|
schema.sportsSeasons,
|
|
|
|
|
eq(schema.participants.sportsSeasonId, schema.sportsSeasons.id)
|
|
|
|
|
)
|
|
|
|
|
.innerJoin(
|
|
|
|
|
schema.sports,
|
|
|
|
|
eq(schema.sportsSeasons.sportId, schema.sports.id)
|
|
|
|
|
)
|
|
|
|
|
.where(eq(schema.draftPicks.seasonId, seasonId))
|
|
|
|
|
.orderBy(asc(schema.draftPicks.pickNumber)),
|
|
|
|
|
db.query.draftTimers.findMany({
|
|
|
|
|
where: eq(schema.draftTimers.seasonId, seasonId),
|
|
|
|
|
}),
|
2026-03-04 21:39:54 -08:00
|
|
|
teamId
|
|
|
|
|
? db.query.draftQueue.findMany({
|
|
|
|
|
where: and(
|
|
|
|
|
eq(schema.draftQueue.teamId, teamId),
|
|
|
|
|
eq(schema.draftQueue.seasonId, seasonId)
|
|
|
|
|
),
|
|
|
|
|
orderBy: asc(schema.draftQueue.queuePosition),
|
|
|
|
|
})
|
|
|
|
|
: Promise.resolve([]),
|
2026-04-29 11:49:26 -07:00
|
|
|
teamId
|
|
|
|
|
? db.query.watchlist.findMany({
|
|
|
|
|
where: and(
|
|
|
|
|
eq(schema.watchlist.teamId, teamId),
|
|
|
|
|
eq(schema.watchlist.seasonId, seasonId)
|
|
|
|
|
),
|
|
|
|
|
})
|
|
|
|
|
: Promise.resolve([]),
|
fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms (#48)
* fix: sync all draft state on mobile reconnection
After a mobile browser returns from a long background period, the draft
room had stale picks, wrong "on the clock" display, and inaccurate
available player lists. The root cause was that reconnection relied
solely on an HTTP revalidation that could fail (expired JWT, flaky
network), and the timer-update handler ignored currentPickNumber.
Changes:
- Server emits draft-state-sync on join-draft with full picks, timers,
and season state, giving the client an immediate socket-based sync
path that doesn't depend on HTTP revalidation
- timer-update handler now syncs currentPickNumber, fixing the "on the
clock" display within 1 second of reconnection
- Revalidation retry with 3s delay ensures the HTTP path succeeds even
when the network is slow to stabilize on mobile return
- Revalidation completion now also syncs teamTimers and autodraftStatus
- Added draft-state-sync client handler that applies the server snapshot
immediately (skipped when revalidation is in-flight to avoid conflicts)
Tests: 32 new tests covering reconnection sync, pick buffering/merge,
timer-update currentPickNumber sync, draft-state-sync handling,
available player filtering, on-the-clock correctness, and revalidation
retry logic.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
* fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-01 12:23:24 -08:00
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
if (seasonData) {
|
|
|
|
|
socket.emit("draft-state-sync", {
|
|
|
|
|
currentPickNumber: seasonData.currentPickNumber || 1,
|
|
|
|
|
isPaused: seasonData.draftPaused || false,
|
|
|
|
|
status: seasonData.status,
|
|
|
|
|
picks,
|
|
|
|
|
timers: timerRows.map((t) => ({
|
|
|
|
|
teamId: t.teamId,
|
|
|
|
|
timeRemaining: t.timeRemaining,
|
|
|
|
|
})),
|
2026-03-04 21:39:54 -08:00
|
|
|
queue: teamId ? queueItems : undefined,
|
2026-04-29 11:49:26 -07:00
|
|
|
watchlistParticipantIds: teamId ? watchlistItems.map((w) => w.participantId) : undefined,
|
fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms (#48)
* fix: sync all draft state on mobile reconnection
After a mobile browser returns from a long background period, the draft
room had stale picks, wrong "on the clock" display, and inaccurate
available player lists. The root cause was that reconnection relied
solely on an HTTP revalidation that could fail (expired JWT, flaky
network), and the timer-update handler ignored currentPickNumber.
Changes:
- Server emits draft-state-sync on join-draft with full picks, timers,
and season state, giving the client an immediate socket-based sync
path that doesn't depend on HTTP revalidation
- timer-update handler now syncs currentPickNumber, fixing the "on the
clock" display within 1 second of reconnection
- Revalidation retry with 3s delay ensures the HTTP path succeeds even
when the network is slow to stabilize on mobile return
- Revalidation completion now also syncs teamTimers and autodraftStatus
- Added draft-state-sync client handler that applies the server snapshot
immediately (skipped when revalidation is in-flight to avoid conflicts)
Tests: 32 new tests covering reconnection sync, pick buffering/merge,
timer-update currentPickNumber sync, draft-state-sync handling,
available player filtering, on-the-clock correctness, and revalidation
retry logic.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
* fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-01 12:23:24 -08:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("[Socket] draft-state-sync query failed:", err);
|
fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms (#48)
* fix: sync all draft state on mobile reconnection
After a mobile browser returns from a long background period, the draft
room had stale picks, wrong "on the clock" display, and inaccurate
available player lists. The root cause was that reconnection relied
solely on an HTTP revalidation that could fail (expired JWT, flaky
network), and the timer-update handler ignored currentPickNumber.
Changes:
- Server emits draft-state-sync on join-draft with full picks, timers,
and season state, giving the client an immediate socket-based sync
path that doesn't depend on HTTP revalidation
- timer-update handler now syncs currentPickNumber, fixing the "on the
clock" display within 1 second of reconnection
- Revalidation retry with 3s delay ensures the HTTP path succeeds even
when the network is slow to stabilize on mobile return
- Revalidation completion now also syncs teamTimers and autodraftStatus
- Added draft-state-sync client handler that applies the server snapshot
immediately (skipped when revalidation is in-flight to avoid conflicts)
Tests: 32 new tests covering reconnection sync, pick buffering/merge,
timer-update currentPickNumber sync, draft-state-sync handling,
available player filtering, on-the-clock correctness, and revalidation
retry logic.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
* fix: guard against stale revalidation overwriting fresh socket data
Add a reference-equality check so that if HTTP revalidation fails (network
error, expired token), the sync effect does not overwrite fresh data that
draft-state-sync already applied. Also adds missing dependency array entries
(userQueue, timers, autodraftSettings) to the revalidation sync effect.
https://claude.ai/code/session_01JxJ1CYTiFWV4KTPxTnjrms
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-01 12:23:24 -08:00
|
|
|
// Non-fatal — the client will fall back to HTTP revalidation
|
|
|
|
|
}
|
2025-10-16 18:15:04 -07:00
|
|
|
});
|
|
|
|
|
|
2025-10-18 22:16:04 -07:00
|
|
|
socket.on("leave-draft", (seasonId: string) => {
|
2025-10-16 18:15:04 -07:00
|
|
|
if (!seasonId) return;
|
|
|
|
|
socket.leave(`draft-${seasonId}`);
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log(`Socket ${socket.id} left draft-${seasonId}`);
|
2025-10-21 23:22:17 -07:00
|
|
|
|
|
|
|
|
// Emit disconnection event if team was tracked
|
|
|
|
|
if (currentTeamId) {
|
|
|
|
|
socket.leave(`team-${currentTeamId}`);
|
2025-10-24 21:31:57 -07:00
|
|
|
|
|
|
|
|
// Remove team from connected teams tracking
|
|
|
|
|
const seasonConnectedTeams = connectedTeams.get(seasonId);
|
|
|
|
|
if (seasonConnectedTeams) {
|
|
|
|
|
seasonConnectedTeams.delete(currentTeamId);
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log(`Team ${currentTeamId} removed from tracking. Remaining: ${seasonConnectedTeams.size}`);
|
2025-10-24 21:31:57 -07:00
|
|
|
|
|
|
|
|
// Clean up empty sets
|
|
|
|
|
if (seasonConnectedTeams.size === 0) {
|
|
|
|
|
connectedTeams.delete(seasonId);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196)
* Fix no-shadow and consistent-function-scoping lint violations
Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint
warnings and promotes both rules to errors in .oxlintrc.json.
no-shadow: renamed Drizzle callback params (sports→s, matches→m,
seasons→s) to avoid shadowing outer imports; removed shadowed
destructures (eq, inArray) from where callbacks; renamed inner
template→bracketTemplate, prev→currentTimers, season→ss, name→teamName
(with name: teamName fix to preserve semantics).
consistent-function-scoping: moved formatDate, getRankBadge,
getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr,
elo (×2), weightedPick, sortByMatchNumber (×2) to module scope;
moved formatTime (×2), isValidLeagueName, getDraftTimes,
makeSeasonQueues to file scope in test files.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix no-non-null-assertion lint violations and promote to error
Eliminates all 208 no-non-null-assertion warnings across 38 files.
Promotes typescript/no-non-null-assertion from warn to error in
.oxlintrc.json.
Fix patterns applied:
- Map.get(key)! after .has() check → extract with get() + null guard
- Map.get(key)! on pre-populated count maps → ?? 0 default
- .set(id, map.get(id)! + 1) increment → ?? 0 before adding
- participant1Id!/participant2Id! on DB matches → ?? "" fallback
- array.find()! in tests → guard + throw or expect().toBeDefined()
- bracketTemplateCache.get(id)! → null guard extract
- Various nullable field accesses → optional chain or ?? default
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers
Resolves all 9 remaining non-console lint warnings and promotes all
three rules to errors in .oxlintrc.json.
- prefer-add-event-listener: converted onchange/onclick/onload
assignments to addEventListener in useDraftNotifications.ts and
admin.data-sync.tsx; stored changeHandler ref for proper cleanup
with removeEventListener
- no-unassigned-import: configured rule with allow list for legitimate
side-effect imports (*.css, @testing-library/jest-dom,
@testing-library/cypress/add-commands)
- require-module-specifiers: removed redundant `export {}` from
cypress/support/e2e.ts (file already has an import)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TypeScript errors from no-non-null-assertion fixes
Two fixes introduced by the non-null assertion cleanup produced type
errors:
- scoring-event.ts: `?? ""` was wrong type for a participant object map;
restructured to explicit null guards so TypeScript can narrow correctly
- standings-sync/index.ts: `?? null` after name-match lookup lost the
truthy guarantee, causing TS18047 on the write-back block; added
`participant &&` guard before accessing its properties
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add npm run typecheck as Stop hook in Claude settings
Runs a full project typecheck at the end of each Claude turn so type
errors surface as feedback before the next message.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00
|
|
|
io?.to(`draft-${seasonId}`).emit("team-disconnected", { teamId: currentTeamId });
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log(`Team ${currentTeamId} disconnected from draft-${seasonId}`);
|
2025-10-21 23:22:17 -07:00
|
|
|
}
|
2025-10-16 18:15:04 -07:00
|
|
|
});
|
|
|
|
|
|
2026-03-21 09:44:05 -07:00
|
|
|
socket.on("test-event", (data: unknown) => {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log("📨 Received test-event from client:", socket.id, data);
|
2025-10-17 12:15:07 -07:00
|
|
|
|
|
|
|
|
socket.emit("test-message", {
|
|
|
|
|
originalMessage: data,
|
|
|
|
|
serverResponse: "Hello from server!",
|
|
|
|
|
serverTimestamp: new Date().toISOString(),
|
|
|
|
|
socketId: socket.id,
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log("✅ Sent test-message response to client:", socket.id);
|
2025-10-17 12:15:07 -07:00
|
|
|
});
|
|
|
|
|
|
2025-10-16 18:15:04 -07:00
|
|
|
socket.on("disconnect", () => {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log("Client disconnected:", socket.id);
|
2025-10-21 23:22:17 -07:00
|
|
|
|
|
|
|
|
// Emit disconnection event if team was tracked
|
|
|
|
|
if (currentTeamId && currentSeasonId) {
|
2025-10-24 21:31:57 -07:00
|
|
|
// Remove team from connected teams tracking
|
|
|
|
|
const seasonConnectedTeams = connectedTeams.get(currentSeasonId);
|
|
|
|
|
if (seasonConnectedTeams) {
|
|
|
|
|
seasonConnectedTeams.delete(currentTeamId);
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log(`Team ${currentTeamId} removed from tracking on disconnect. Remaining: ${seasonConnectedTeams.size}`);
|
2025-10-24 21:31:57 -07:00
|
|
|
|
|
|
|
|
// Clean up empty sets
|
|
|
|
|
if (seasonConnectedTeams.size === 0) {
|
|
|
|
|
connectedTeams.delete(currentSeasonId);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196)
* Fix no-shadow and consistent-function-scoping lint violations
Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint
warnings and promotes both rules to errors in .oxlintrc.json.
no-shadow: renamed Drizzle callback params (sports→s, matches→m,
seasons→s) to avoid shadowing outer imports; removed shadowed
destructures (eq, inArray) from where callbacks; renamed inner
template→bracketTemplate, prev→currentTimers, season→ss, name→teamName
(with name: teamName fix to preserve semantics).
consistent-function-scoping: moved formatDate, getRankBadge,
getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr,
elo (×2), weightedPick, sortByMatchNumber (×2) to module scope;
moved formatTime (×2), isValidLeagueName, getDraftTimes,
makeSeasonQueues to file scope in test files.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix no-non-null-assertion lint violations and promote to error
Eliminates all 208 no-non-null-assertion warnings across 38 files.
Promotes typescript/no-non-null-assertion from warn to error in
.oxlintrc.json.
Fix patterns applied:
- Map.get(key)! after .has() check → extract with get() + null guard
- Map.get(key)! on pre-populated count maps → ?? 0 default
- .set(id, map.get(id)! + 1) increment → ?? 0 before adding
- participant1Id!/participant2Id! on DB matches → ?? "" fallback
- array.find()! in tests → guard + throw or expect().toBeDefined()
- bracketTemplateCache.get(id)! → null guard extract
- Various nullable field accesses → optional chain or ?? default
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers
Resolves all 9 remaining non-console lint warnings and promotes all
three rules to errors in .oxlintrc.json.
- prefer-add-event-listener: converted onchange/onclick/onload
assignments to addEventListener in useDraftNotifications.ts and
admin.data-sync.tsx; stored changeHandler ref for proper cleanup
with removeEventListener
- no-unassigned-import: configured rule with allow list for legitimate
side-effect imports (*.css, @testing-library/jest-dom,
@testing-library/cypress/add-commands)
- require-module-specifiers: removed redundant `export {}` from
cypress/support/e2e.ts (file already has an import)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TypeScript errors from no-non-null-assertion fixes
Two fixes introduced by the non-null assertion cleanup produced type
errors:
- scoring-event.ts: `?? ""` was wrong type for a participant object map;
restructured to explicit null guards so TypeScript can narrow correctly
- standings-sync/index.ts: `?? null` after name-match lookup lost the
truthy guarantee, causing TS18047 on the write-back block; added
`participant &&` guard before accessing its properties
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add npm run typecheck as Stop hook in Claude settings
Runs a full project typecheck at the end of each Claude turn so type
errors surface as feedback before the next message.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00
|
|
|
io?.to(`draft-${currentSeasonId}`).emit("team-disconnected", { teamId: currentTeamId });
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log(`Team ${currentTeamId} disconnected from draft-${currentSeasonId}`);
|
2025-10-21 23:22:17 -07:00
|
|
|
}
|
2025-10-16 18:15:04 -07:00
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2025-10-18 22:16:04 -07:00
|
|
|
// Store globally for route handlers
|
2025-10-16 18:15:04 -07:00
|
|
|
global.__socketIO = io;
|
|
|
|
|
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.log("Socket.IO initialized");
|
2025-11-14 09:15:58 -08:00
|
|
|
|
2025-10-18 23:13:04 -07:00
|
|
|
// Start the draft timer system (async import but don't await)
|
|
|
|
|
import("./timer").then(({ startDraftTimerSystem }) => {
|
|
|
|
|
startDraftTimerSystem();
|
|
|
|
|
}).catch((error) => {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Failed to start timer system:", error);
|
2025-10-18 23:13:04 -07:00
|
|
|
});
|
2025-11-14 09:15:58 -08:00
|
|
|
|
|
|
|
|
// Start the daily snapshot system
|
|
|
|
|
import("./snapshots").then(({ startSnapshotSystem }) => {
|
|
|
|
|
startSnapshotSystem();
|
|
|
|
|
}).catch((error) => {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Failed to start snapshot system:", error);
|
2025-11-14 09:15:58 -08:00
|
|
|
});
|
|
|
|
|
|
2025-10-16 18:15:04 -07:00
|
|
|
return io;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Get the Socket.IO server instance
|
|
|
|
|
*/
|
2025-10-18 22:16:04 -07:00
|
|
|
export function getSocketIO(): SocketIOServer {
|
2025-10-16 18:15:04 -07:00
|
|
|
const instance = io || global.__socketIO;
|
|
|
|
|
if (!instance) {
|
|
|
|
|
throw new Error("Socket.IO not initialized. Call initializeSocketIO first.");
|
|
|
|
|
}
|
|
|
|
|
return instance;
|
|
|
|
|
}
|