From 956cdb863af2c518037ad83a00b2c66c47ab1dbd Mon Sep 17 00:00:00 2001 From: Kev Date: Fri, 12 Jun 2026 17:58:55 -0400 Subject: [PATCH] =?UTF-8?q?Session=2025:=20Fix=20all=20data=20rendering=20?= =?UTF-8?q?=E2=80=94=20proxy=20routes,=20Tank01=20normalizer,=20box-score?= =?UTF-8?q?=20bridge,=20inline=20streaks=20(1579=20tests)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BUILD-STATE.md | 71 +++++++++++++++++ CLAUDE.md | 13 +++ data/training/resolutions-2026-06.jsonl | 21 +++++ src/routes/gameLines.js | 82 ++++++++++++++----- src/services/rosterLogs.js | 92 +++++++++++++++++++--- tests/integration/gameLinesRoute.test.js | 51 +++++++++++- tests/unit/rosterLogs.test.js | 75 ++++++++++++++++++ web/public/sw.js | 2 +- web/src/app/api/gamelines/[sport]/route.ts | 27 +++++++ web/src/app/api/hotlist/[sport]/route.ts | 27 +++++++ web/src/app/api/schedule/[sport]/route.ts | 34 ++++++++ web/src/app/api/streaks/[sport]/route.ts | 27 +++++++ web/src/components/GameCard.tsx | 49 +++++++++++- web/src/components/LiveHeroProp.tsx | 14 ++++ web/src/components/Slate.tsx | 56 ++++++++++++- 15 files changed, 602 insertions(+), 39 deletions(-) create mode 100644 web/src/app/api/gamelines/[sport]/route.ts create mode 100644 web/src/app/api/hotlist/[sport]/route.ts create mode 100644 web/src/app/api/schedule/[sport]/route.ts create mode 100644 web/src/app/api/streaks/[sport]/route.ts diff --git a/BUILD-STATE.md b/BUILD-STATE.md index 062ecf6..2727047 100755 --- a/BUILD-STATE.md +++ b/BUILD-STATE.md @@ -4,6 +4,77 @@ 2026-06-12 ## Current Phase +SHIP BUILD v25.0 — Fix every data-rendering bug: the frontend now actually SHOWS the backend's data (Session 25) + +## Session 25 (2026-06-12) — SHIPPED + +Traced data from API response → normalizer → cache → frontend fetch → +render and fixed every break. The backend was serving real data; the +frontend showed "NO SLATE." Root causes found and fixed. + +Backend 1571 → **1579 tests** (+8), 125 suites, zero regressions. +Web build clean. + +### PHASE 1 — Tank01 game-lines normalizer (traced + fixed) +- TRACE: the real Tank01 betting-odds shape puts each sportsbook as a + TOP-LEVEL key on the game object (`{ awayTeam, homeTeam, bet365:{...}, + betmgm:{...} }`), NOT inside a `sportsBooks` array. The old normalizer + looked for the array → `books: {}` every time. +- FIX: `extractBooks()` filters out NON_BOOK_KEYS and treats remaining + object values as books (counted only if they yield a real odds field). + `normalizeBook` now reads `homeTeamML`/`totalOver`/`homeTeamRunLine` + (MLB) alongside the older spellings. Legacy array shape still handled. + +### PHASE 2 — Slate schedule rendering (THE root cause) +- TRACE: the all-day endpoints (`/api/schedule`, `/api/gamelines`, + `/api/streaks`, `/api/hotlist`) existed on Express but had NO Next.js + proxy route — so the browser's `fetch('/api/schedule/mlb')` 404'd on the + Next origin and the slate was always empty. +- FIX: created 4 Next.js proxy route handlers (mirroring `/api/odds/*`). +- Sport tabs now show merged counts ("MLB (8)") from schedule+odds. +- Games already rendered with 0 props (Session 24 merge); now they get data. + +### PHASE 3 — Dashboard +- The Session 24 schedule fallback was 404ing for the same proxy reason; + the Phase 2 proxy unblocks it. Dashboard now shows ESPN schedule games. + +### PHASE 4 — Hero prop +- The static Jokic fallback card is now labelled "EXAMPLE" so its fixed + stats don't read as stale live data when no live hero-prop is flowing. + +### PHASE 5 — Per-game inline streaks +- `GameCard` renders a 🔥 STREAKS section inline (below props/lines), + matched to the game by team abbreviation in the Slate. Renders only when + streaks exist for that game's teams. Sport-wide panels kept as the board. + +### PHASE 6 — Game-log cache key alignment (traced + bridged) +- TRACE: prefetch writes `tank01:{sport}:boxscore:{gameId}`; rosterLogs + read `gamelogs:{sport}:*` / `rosterlogs:{sport}`. NBA/WNBA are fed by + gameLogService (Python) during grading — ALIGNED. MLB had NO writer for + the keys rosterLogs read — MISALIGNED, so MLB streaks were always empty. +- FIX: `rosterLogs` now falls back to aggregating the cached Tank01 box + scores (`tank01:{sport}:boxscore:*`) into per-player multi-game logs, + flattening MLB `_raw` and ordering games most-recent-first by the date + in the gameID. Honest limitation: streaks need 2+ cached games to + surface, so coverage grows as box scores accumulate across prefetch runs. + +### Files created +- `web/src/app/api/schedule/[sport]/route.ts` +- `web/src/app/api/gamelines/[sport]/route.ts` +- `web/src/app/api/streaks/[sport]/route.ts` +- `web/src/app/api/hotlist/[sport]/route.ts` + +### Files modified +- `src/routes/gameLines.js` (normalizer rewrite + extractBooks) +- `src/services/rosterLogs.js` (box-score aggregation bridge) +- `web/src/components/Slate.tsx` (streaks fetch+match, tab counts) +- `web/src/components/GameCard.tsx` (inline streaks section) +- `web/src/components/LiveHeroProp.tsx` (EXAMPLE label) +- `tests/integration/gameLinesRoute.test.js`, `tests/unit/rosterLogs.test.js` + +--- + +## Previous Phase SHIP BUILD v24.0 — Connect Everything: wired the all-day intelligence layer into the live UI + killed stale copy (Session 24) ## Session 24 (2026-06-12) — SHIPPED diff --git a/CLAUDE.md b/CLAUDE.md index 50a0067..d36f70b 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -73,6 +73,19 @@ empty. NONE of these spend odds-api credits: - Dead providers: set `status: 'dead'` in `config/providers.js` to drop a provider from fallback chains + configured list (ParlayAPI host is dead). +## Frontend ↔ Backend Wiring (Session 25 — non-obvious) +A new Express route under `/api/*` is NOT reachable from the browser until +a matching **Next.js proxy route** exists at `web/src/app/api/.../route.ts` +that forwards to `${BACKEND_URL}/api/...`. The browser hits the Next origin, +not Express directly. This bit us: schedule/gamelines/streaks/hotlist +endpoints worked on Express but 404'd in the UI for two sessions. When +adding a backend endpoint the frontend calls, ALWAYS add the proxy too +(pattern: `web/src/app/api/odds/nba/route.ts`). + +Tank01 betting-odds real shape: sportsbooks are TOP-LEVEL keys on each +game object (`{ awayTeam, homeTeam, bet365:{...} }`), not a `sportsBooks` +array. Filter `NON_BOOK_KEYS` to extract books (see `gameLines.js`). + ## Active Skills - vyndr-voice (all user-facing output) - prop-analysis (grading methodology) diff --git a/data/training/resolutions-2026-06.jsonl b/data/training/resolutions-2026-06.jsonl index 471e64b..bfec42a 100644 --- a/data/training/resolutions-2026-06.jsonl +++ b/data/training/resolutions-2026-06.jsonl @@ -696,3 +696,24 @@ {"ts":"2026-06-12T19:39:18.769Z","sport":"nba","player_espn_id":"3136195","player_name":"Karl-Anthony Towns","stat_type":"rebounds","line":13.5,"direction":"under","actual_value":13,"result":"hit","margin":-0.5,"grade":"B+"} {"ts":"2026-06-12T19:39:18.769Z","sport":"nba","player_espn_id":"3062679","player_name":"Josh Hart","stat_type":"pts_reb_ast","line":10.5,"direction":"over","actual_value":10,"result":"miss","margin":-0.5,"grade":"C"} {"ts":"2026-06-12T19:39:18.874Z","sport":"nba","player_espn_id":"999999999","player_name":"Phantom Player","stat_type":"points","line":10.5,"direction":"over","actual_value":null,"result":"void","grade":"C"} +{"ts":"2026-06-12T21:15:48.892Z","sport":"nba","player_espn_id":"3934719","player_name":"OG Anunoby","stat_type":"points","line":16.5,"direction":"over","actual_value":17,"result":"hit","margin":0.5,"grade":"A-"} +{"ts":"2026-06-12T21:15:48.896Z","sport":"nba","player_espn_id":"3136195","player_name":"Karl-Anthony Towns","stat_type":"rebounds","line":13.5,"direction":"under","actual_value":13,"result":"hit","margin":-0.5,"grade":"B+"} +{"ts":"2026-06-12T21:15:48.896Z","sport":"nba","player_espn_id":"3062679","player_name":"Josh Hart","stat_type":"pts_reb_ast","line":10.5,"direction":"over","actual_value":10,"result":"miss","margin":-0.5,"grade":"C"} +{"ts":"2026-06-12T21:15:48.958Z","sport":"nba","player_espn_id":"999999999","player_name":"Phantom Player","stat_type":"points","line":10.5,"direction":"over","actual_value":null,"result":"void","grade":"C"} +{"ts":"2026-06-12T21:15:49.248Z","sport":"nba","player_espn_id":"3934719","player_name":"OG Anunoby","stat_type":"points","line":16.5,"direction":"over","actual_value":17,"result":"hit","margin":0.5,"grade":"A"} +{"ts":"2026-06-12T21:15:49.337Z","sport":"nba","player_espn_id":"99999","player_name":"Phantom","stat_type":"points","line":10.5,"direction":"over","actual_value":null,"result":"void","grade":"B"} +{"ts":"2026-06-12T21:15:50.038Z","sport":"nba","player_espn_id":"3934719","player_name":"OG Anunoby","stat_type":"points","line":16.5,"direction":"over","actual_value":17,"result":"hit","margin":0.5,"grade":"A"} +{"ts":"2026-06-12T21:41:40.018Z","sport":"nba","player_espn_id":"3934719","player_name":"OG Anunoby","stat_type":"points","line":16.5,"direction":"over","actual_value":17,"result":"hit","margin":0.5,"grade":"A"} +{"ts":"2026-06-12T21:41:40.065Z","sport":"nba","player_espn_id":"3934719","player_name":"OG Anunoby","stat_type":"points","line":16.5,"direction":"over","actual_value":17,"result":"hit","margin":0.5,"grade":"A"} +{"ts":"2026-06-12T21:41:40.200Z","sport":"nba","player_espn_id":"99999","player_name":"Phantom","stat_type":"points","line":10.5,"direction":"over","actual_value":null,"result":"void","grade":"B"} +{"ts":"2026-06-12T21:41:40.582Z","sport":"nba","player_espn_id":"3934719","player_name":"OG Anunoby","stat_type":"points","line":16.5,"direction":"over","actual_value":17,"result":"hit","margin":0.5,"grade":"A-"} +{"ts":"2026-06-12T21:41:40.585Z","sport":"nba","player_espn_id":"3136195","player_name":"Karl-Anthony Towns","stat_type":"rebounds","line":13.5,"direction":"under","actual_value":13,"result":"hit","margin":-0.5,"grade":"B+"} +{"ts":"2026-06-12T21:41:40.585Z","sport":"nba","player_espn_id":"3062679","player_name":"Josh Hart","stat_type":"pts_reb_ast","line":10.5,"direction":"over","actual_value":10,"result":"miss","margin":-0.5,"grade":"C"} +{"ts":"2026-06-12T21:41:40.654Z","sport":"nba","player_espn_id":"999999999","player_name":"Phantom Player","stat_type":"points","line":10.5,"direction":"over","actual_value":null,"result":"void","grade":"C"} +{"ts":"2026-06-12T21:43:24.893Z","sport":"nba","player_espn_id":"3934719","player_name":"OG Anunoby","stat_type":"points","line":16.5,"direction":"over","actual_value":17,"result":"hit","margin":0.5,"grade":"A"} +{"ts":"2026-06-12T21:43:24.930Z","sport":"nba","player_espn_id":"3934719","player_name":"OG Anunoby","stat_type":"points","line":16.5,"direction":"over","actual_value":17,"result":"hit","margin":0.5,"grade":"A-"} +{"ts":"2026-06-12T21:43:24.930Z","sport":"nba","player_espn_id":"3136195","player_name":"Karl-Anthony Towns","stat_type":"rebounds","line":13.5,"direction":"under","actual_value":13,"result":"hit","margin":-0.5,"grade":"B+"} +{"ts":"2026-06-12T21:43:24.930Z","sport":"nba","player_espn_id":"3062679","player_name":"Josh Hart","stat_type":"pts_reb_ast","line":10.5,"direction":"over","actual_value":10,"result":"miss","margin":-0.5,"grade":"C"} +{"ts":"2026-06-12T21:43:25.003Z","sport":"nba","player_espn_id":"99999","player_name":"Phantom","stat_type":"points","line":10.5,"direction":"over","actual_value":null,"result":"void","grade":"B"} +{"ts":"2026-06-12T21:43:25.020Z","sport":"nba","player_espn_id":"999999999","player_name":"Phantom Player","stat_type":"points","line":10.5,"direction":"over","actual_value":null,"result":"void","grade":"C"} +{"ts":"2026-06-12T21:43:25.037Z","sport":"nba","player_espn_id":"3934719","player_name":"OG Anunoby","stat_type":"points","line":16.5,"direction":"over","actual_value":17,"result":"hit","margin":0.5,"grade":"A"} diff --git a/src/routes/gameLines.js b/src/routes/gameLines.js index 805c425..a7c9135 100644 --- a/src/routes/gameLines.js +++ b/src/routes/gameLines.js @@ -57,12 +57,28 @@ function teamsFromGameId(gameId) { return { awayTeam: m[1], homeTeam: m[2] }; } +// Session 25 — Tank01's real shape (traced 2026-06-12) puts each +// sportsbook as a TOP-LEVEL key inside the game object, NOT inside a +// `sportsBooks` array: +// { "20260612_ARI@CIN": { +// awayTeam: "ARI", homeTeam: "CIN", gameID: "...", +// bet365: { homeTeamML: "-110", totalOver: "9.5", ... }, +// betmgm: { ... }, caesars: { ... } } } +// These non-book keys must be excluded so they don't get treated as books. +const NON_BOOK_KEYS = new Set([ + 'awayTeam', 'homeTeam', 'gameID', 'gameId', 'gameDate', 'gameTime', + 'gameStatus', 'gameStatusCode', 'teamIDAway', 'teamIDHome', + 'season', 'seasonType', 'last_updated_e_time', 'espnID', 'espnLink', + 'cbsLink', 'sportsBooks', 'books', +]); + /** * Normalize one sportsbook's raw odds object into a flat, UI-ready row. - * Tank01 field names are verbose and occasionally vary; pull defensively. + * Tank01 field names are verbose and vary across feeds — pull defensively, + * tolerating both the MLB run-line and NBA spread spellings. */ function normalizeBook(odds) { - if (!odds || typeof odds !== 'object') return null; + if (!odds || typeof odds !== 'object' || Array.isArray(odds)) return null; const pick = (...keys) => { for (const k of keys) { if (odds[k] !== undefined && odds[k] !== null && odds[k] !== '') return odds[k]; @@ -70,18 +86,53 @@ function normalizeBook(odds) { return null; }; return { - homeML: pick('homeTeamMLOdds', 'homeML', 'moneyLineHome'), - awayML: pick('awayTeamMLOdds', 'awayML', 'moneyLineAway'), - total: pick('totalOver', 'total', 'overUnder'), + homeML: pick('homeTeamML', 'homeTeamMLOdds', 'homeML', 'moneyLineHome'), + awayML: pick('awayTeamML', 'awayTeamMLOdds', 'awayML', 'moneyLineAway'), + total: pick('totalOver', 'totalUnder', 'total', 'overUnder'), overOdds: pick('totalOverOdds', 'overOdds'), underOdds: pick('totalUnderOdds', 'underOdds'), - homeSpread: pick('homeTeamSpread', 'homeSpread'), - awaySpread: pick('awayTeamSpread', 'awaySpread'), - homeSpreadOdds: pick('homeTeamSpreadOdds'), - awaySpreadOdds: pick('awayTeamSpreadOdds'), + homeSpread: pick('homeTeamRunLine', 'homeTeamSpread', 'homeSpread'), + awaySpread: pick('awayTeamRunLine', 'awayTeamSpread', 'awaySpread'), + homeSpreadOdds: pick('homeTeamSpreadOdds', 'homeTeamRunLineOdds'), + awaySpreadOdds: pick('awayTeamSpreadOdds', 'awayTeamRunLineOdds'), }; } +/** + * Extract the books map from a single game object. Handles BOTH shapes: + * 1. (current) sportsbooks as top-level keys on the game object + * 2. (legacy) a `sportsBooks` array of { sportsBook, odds } entries + * A book is only counted if it yields at least one real odds field, so a + * stray non-book object key can't pollute the result. + */ +function extractBooks(game) { + const books = {}; + + // Shape 1 — top-level book keys. + for (const [key, val] of Object.entries(game)) { + if (NON_BOOK_KEYS.has(key)) continue; + if (!val || typeof val !== 'object' || Array.isArray(val)) continue; + const row = normalizeBook(val); + if (row && Object.values(row).some((v) => v !== null)) { + books[String(key).toLowerCase()] = row; + } + } + + // Shape 2 — legacy sportsBooks array (kept for backward compatibility). + const sbList = game.sportsBooks || game.books; + if (Array.isArray(sbList)) { + for (const sb of sbList) { + const name = sb?.sportsBook || sb?.book || sb?.name; + const row = normalizeBook(sb?.odds || sb); + if (name && row && Object.values(row).some((v) => v !== null)) { + books[String(name).toLowerCase()] = row; + } + } + } + + return books; +} + /** * Normalize the Tank01 betting-odds body (a map keyed by gameID) into the * route's `games` shape. Defensive against both the documented map form @@ -98,19 +149,10 @@ function normalizeGameLines(body) { for (const [gameId, game] of entries) { if (!gameId || !game || typeof game !== 'object') continue; const { awayTeam, homeTeam } = teamsFromGameId(gameId); - const books = {}; - const sbList = game.sportsBooks || game.books || []; - if (Array.isArray(sbList)) { - for (const sb of sbList) { - const name = sb?.sportsBook || sb?.book || sb?.name; - const row = normalizeBook(sb?.odds || sb); - if (name && row) books[String(name).toLowerCase()] = row; - } - } games[gameId] = { homeTeam: game.homeTeam || homeTeam, awayTeam: game.awayTeam || awayTeam, - books, + books: extractBooks(game), }; } return games; @@ -141,4 +183,4 @@ router.get('/:sport', async (req, res) => { }); module.exports = router; -module.exports.__internals = { teamsFromGameId, normalizeBook, normalizeGameLines }; +module.exports.__internals = { teamsFromGameId, normalizeBook, normalizeGameLines, extractBooks }; diff --git a/src/services/rosterLogs.js b/src/services/rosterLogs.js index 2d2685f..bd6db86 100644 --- a/src/services/rosterLogs.js +++ b/src/services/rosterLogs.js @@ -6,11 +6,20 @@ * as the grading flow touches them. There's no roster-wide pull, and we * will NOT add API calls to build one (free/cheap-only session). * - * So we read what's ALREADY cached: + * So we read what's ALREADY cached, in priority order: * 1. A precomputed roster blob `rosterlogs:{sport}` if a prefetch wrote * one (fast path — a single read). - * 2. Otherwise SCAN the per-player `gamelogs:{sport}:*` keys and assemble - * a roster from whatever's warm. + * 2. The per-player `gamelogs:{sport}:*` keys (NBA/WNBA: written by + * gameLogService during grading, with real multi-game logs). + * 3. (Session 25) The Tank01 box-score cache `tank01:{sport}:boxscore:*` + * that the prefetch writes. Each key is ONE game; we aggregate by + * player across games into the same roster shape. This closes the + * key-alignment gap Session 25 traced: the prefetch wrote box scores + * under a key rosterLogs never read, so MLB streaks were always empty. + * + * Streaks need 2+ games to surface (MIN_STREAK), so a single cached game + * day yields no streak — correct, not a bug. Coverage grows as box scores + * accumulate across prefetch runs. * * Everything here is Redis-only (free) and defensive — any failure yields * an empty roster, never a throw. An empty roster is a valid state: the @@ -37,11 +46,10 @@ function playerFromKey(key, sport) { return rest.slice(0, lastColon); } -async function scanGameLogKeys(sport) { +async function scanKeys(match) { if (isDegraded && isDegraded()) return []; const redis = getRedisClient(); if (!redis || typeof redis.scan !== 'function') return []; - const match = `gamelogs:${sport}:*`; const keys = []; let cursor = '0'; try { @@ -60,6 +68,63 @@ async function scanGameLogKeys(sport) { return keys; } +function scanGameLogKeys(sport) { + return scanKeys(`gamelogs:${sport}:*`); +} + +// Session 25 — box-score-cache aggregation (the prefetch-alignment bridge). + +// Extract the YYYYMMDD date from a `tank01:{sport}:boxscore:{gameId}` key, +// where gameId is `YYYYMMDD_AWAY@HOME`. Used to order games most-recent-first +// (streaksService counts the streak from games[0] backward). +function boxScoreKeyDate(key) { + const m = String(key || '').match(/boxscore:(\d{8})/); + return m ? m[1] : '0'; +} + +// Project one cached box-score row into a stat row the streaks/hot-list +// engines can read. NBA rows already carry pts/reb/ast/etc. at the top +// level; MLB rows keep stats under `_raw`, so we flatten that up. +function projectBoxRow(sport, row) { + if (!row || typeof row !== 'object') return null; + if (sport === 'mlb') { + const raw = row._raw && typeof row._raw === 'object' ? row._raw : {}; + return { ...raw, team: row.team, playerId: row.playerId, _final: row._final }; + } + // nba / wnba — already flat. + return row; +} + +/** + * Aggregate cached Tank01 box scores into [{ name, playerId, team, games }]. + * One box-score key = one game; a player appearing across N cached games + * accumulates an N-length log. Games are ordered most-recent-first by the + * date embedded in the key. + */ +async function aggregateBoxScores(sport) { + const keys = await scanKeys(`tank01:${sport}:boxscore:*`); + if (keys.length === 0) return []; + // Most-recent game first. + keys.sort((a, b) => boxScoreKeyDate(b).localeCompare(boxScoreKeyDate(a))); + + const byPlayer = new Map(); + for (const k of keys) { + const box = await cacheGet(k); + if (!Array.isArray(box)) continue; + for (const row of box) { + const name = row?.name; + if (!name) continue; + const stat = projectBoxRow(sport, row); + if (!stat) continue; + if (!byPlayer.has(name)) { + byPlayer.set(name, { name, playerId: row.playerId ?? null, team: row.team ?? null, games: [] }); + } + byPlayer.get(name).games.push(stat); + } + } + return Array.from(byPlayer.values()); +} + /** * Returns [{ name, playerId, team, games }] for a sport. Dedupes players * (the highest game-count key wins) so one player isn't double-counted @@ -73,9 +138,8 @@ async function loadRosterLogs(sport) { const blob = await cacheGet(`rosterlogs:${key}`); if (Array.isArray(blob) && blob.length > 0) return blob; + // Per-player game-log keys (NBA/WNBA grading flow writes these). const keys = await scanGameLogKeys(key); - if (keys.length === 0) return []; - const byPlayer = new Map(); for (const k of keys) { const name = playerFromKey(k, key); @@ -89,7 +153,17 @@ async function loadRosterLogs(sport) { byPlayer.set(name, { name, playerId, team, games }); } } - return Array.from(byPlayer.values()); + if (byPlayer.size > 0) return Array.from(byPlayer.values()); + + // Session 25 — fall back to the Tank01 box-score cache the prefetch + // writes. Closes the key-alignment gap that left MLB streaks empty. + return aggregateBoxScores(key); } -module.exports = { loadRosterLogs, __internals: { playerFromKey, scanGameLogKeys } }; +module.exports = { + loadRosterLogs, + __internals: { + playerFromKey, scanGameLogKeys, scanKeys, + boxScoreKeyDate, projectBoxRow, aggregateBoxScores, + }, +}; diff --git a/tests/integration/gameLinesRoute.test.js b/tests/integration/gameLinesRoute.test.js index 8664f4a..38b5e0f 100644 --- a/tests/integration/gameLinesRoute.test.js +++ b/tests/integration/gameLinesRoute.test.js @@ -30,12 +30,26 @@ function mountApp() { return app; } +// Session 25 — the REAL Tank01 shape (traced): sportsbooks are top-level +// keys on the game object, alongside non-book keys (awayTeam, gameID…). const MLB_BODY = { + '20260612_ARI@CIN': { + gameID: '20260612_ARI@CIN', + awayTeam: 'ARI', + homeTeam: 'CIN', + last_updated_e_time: '1718200000', + bet365: { homeTeamML: '-110', awayTeamML: '+100', totalOver: '9.5', totalOverOdds: '-105', totalUnderOdds: '-115', homeTeamRunLine: '-1.5' }, + betmgm: { homeTeamML: '-115', awayTeamML: '-105', totalOver: '9' }, + caesars: { homeTeamML: '-112', awayTeamML: '-102', totalUnder: '9.5' }, + }, +}; + +// Legacy array shape — still supported for backward compatibility. +const MLB_BODY_LEGACY = { '20260612_ARI@CIN': { gameID: '20260612_ARI@CIN', sportsBooks: [ - { sportsBook: 'bet365', odds: { homeTeamMLOdds: '-110', awayTeamMLOdds: '+100', totalOver: '9.5', totalOverOdds: '-105', totalUnderOdds: '-115' } }, - { sportsBook: 'betmgm', odds: { homeTeamMLOdds: '-115', awayTeamMLOdds: '-105', totalOver: '9' } }, + { sportsBook: 'bet365', odds: { homeTeamMLOdds: '-110', awayTeamMLOdds: '+100', totalOver: '9.5' } }, ], }, }; @@ -49,7 +63,7 @@ beforeEach(() => { }); describe('GET /api/gamelines/:sport', () => { - test('mlb returns book-by-book odds with teams parsed from gameID', async () => { + test('mlb returns book-by-book odds from top-level book keys (real shape)', async () => { mlbAdapter.getMLBBettingOdds.mockResolvedValue(MLB_BODY); const res = await request(mountApp()).get('/api/gamelines/mlb'); expect(res.status).toBe(200); @@ -57,9 +71,38 @@ describe('GET /api/gamelines/:sport', () => { const game = res.body.games['20260612_ARI@CIN']; expect(game.homeTeam).toBe('CIN'); expect(game.awayTeam).toBe('ARI'); + // Books must be POPULATED (the Session 25 bug: this was {}). + expect(Object.keys(game.books).sort()).toEqual(['bet365', 'betmgm', 'caesars']); expect(game.books.bet365.homeML).toBe('-110'); + expect(game.books.bet365.awayML).toBe('+100'); expect(game.books.bet365.total).toBe('9.5'); + expect(game.books.bet365.homeSpread).toBe('-1.5'); expect(game.books.betmgm.homeML).toBe('-115'); + expect(game.books.caesars.total).toBe('9.5'); // totalUnder fallback + }); + + test('non-book keys (awayTeam, homeTeam, gameID) are excluded from books', async () => { + mlbAdapter.getMLBBettingOdds.mockResolvedValue(MLB_BODY); + const res = await request(mountApp()).get('/api/gamelines/mlb'); + const books = res.body.games['20260612_ARI@CIN'].books; + expect(books.awayteam).toBeUndefined(); + expect(books.hometeam).toBeUndefined(); + expect(books.gameid).toBeUndefined(); + }); + + test('missing fields normalize to null, never undefined/crash', async () => { + mlbAdapter.getMLBBettingOdds.mockResolvedValue(MLB_BODY); + const res = await request(mountApp()).get('/api/gamelines/mlb'); + const betmgm = res.body.games['20260612_ARI@CIN'].books.betmgm; + expect(betmgm.homeSpread).toBeNull(); + expect(betmgm.overOdds).toBeNull(); + expect(Object.prototype.hasOwnProperty.call(betmgm, 'homeSpread')).toBe(true); + }); + + test('legacy sportsBooks array shape still normalizes', async () => { + mlbAdapter.getMLBBettingOdds.mockResolvedValue(MLB_BODY_LEGACY); + const res = await request(mountApp()).get('/api/gamelines/mlb'); + expect(res.body.games['20260612_ARI@CIN'].books.bet365.homeML).toBe('-110'); }); test('nba returns empty games object off-season (not an error)', async () => { @@ -89,7 +132,7 @@ describe('GET /api/gamelines/:sport', () => { expect(res.status).toBe(404); }); - test('cache works — adapter called once per request (adapter owns TTL)', async () => { + test('adapter called once per request (adapter owns TTL)', async () => { mlbAdapter.getMLBBettingOdds.mockResolvedValue(MLB_BODY); const app = mountApp(); await request(app).get('/api/gamelines/mlb'); diff --git a/tests/unit/rosterLogs.test.js b/tests/unit/rosterLogs.test.js index a982d38..008765e 100644 --- a/tests/unit/rosterLogs.test.js +++ b/tests/unit/rosterLogs.test.js @@ -58,3 +58,78 @@ describe('rosterLogs', () => { expect(__internals.playerFromKey('gamelogs:nba:LeBron James:20', 'nba')).toBe('LeBron James'); }); }); + +// Session 25 — box-score aggregation bridge (prefetch key alignment). +describe('rosterLogs — Tank01 box-score aggregation', () => { + // Route scans by their MATCH pattern (3rd arg) so gamelogs + boxscore + // scans can return different key sets. + function routeScan(map) { + mockScan.mockImplementation(async (_cursor, _m, match) => ['0', map[match] || []]); + } + + test('aggregates MLB box scores into per-player multi-game logs', async () => { + routeScan({ + 'gamelogs:mlb:*': [], + 'tank01:mlb:boxscore:*': [ + 'tank01:mlb:boxscore:20260612_ARI@CIN', + 'tank01:mlb:boxscore:20260611_ARI@LAD', + ], + }); + // Newer game (0612) and older game (0611) for the same batter. + store['tank01:mlb:boxscore:20260612_ARI@CIN'] = [ + { role: 'batter', name: 'Acuna', playerId: 'B1', team: 'ARI', _raw: { H: 2, HR: 1 }, _final: true }, + ]; + store['tank01:mlb:boxscore:20260611_ARI@LAD'] = [ + { role: 'batter', name: 'Acuna', playerId: 'B1', team: 'ARI', _raw: { H: 1, HR: 0 }, _final: true }, + ]; + const roster = await loadRosterLogs('mlb'); + expect(roster).toHaveLength(1); + const acuna = roster[0]; + expect(acuna.name).toBe('Acuna'); + expect(acuna.team).toBe('ARI'); + expect(acuna.games).toHaveLength(2); + // Most-recent first → the 2-hit game leads (flattened from _raw). + expect(acuna.games[0].H).toBe(2); + expect(acuna.games[1].H).toBe(1); + }); + + test('aggregated MLB logs feed the streaks engine (hit streak)', async () => { + routeScan({ + 'gamelogs:mlb:*': [], + 'tank01:mlb:boxscore:*': ['tank01:mlb:boxscore:20260612_A@B', 'tank01:mlb:boxscore:20260611_A@B'], + }); + store['tank01:mlb:boxscore:20260612_A@B'] = [{ role: 'batter', name: 'X', team: 'A', _raw: { H: 2 }, _final: true }]; + store['tank01:mlb:boxscore:20260611_A@B'] = [{ role: 'batter', name: 'X', team: 'A', _raw: { H: 1 }, _final: true }]; + const roster = await loadRosterLogs('mlb'); + const { computeStreaks } = require('../../src/services/streaksService'); + const streaks = computeStreaks(roster, 'mlb'); + const hit = streaks.find((s) => s.type === 'hit_streak'); + expect(hit).toBeDefined(); + expect(hit.currentStreak).toBe(2); + }); + + test('NBA box-score rows are consumed without _raw flattening', async () => { + routeScan({ + 'gamelogs:nba:*': [], + 'tank01:nba:boxscore:*': ['tank01:nba:boxscore:20260612_NYK@SA'], + }); + store['tank01:nba:boxscore:20260612_NYK@SA'] = [ + { playerId: 'W1', name: 'Wemby', team: 'SA', pts: 30, reb: 12, ast: 3, threes: 2, blk: 4, stl: 1 }, + ]; + const roster = await loadRosterLogs('nba'); + expect(roster[0].games[0].pts).toBe(30); + }); + + test('gamelogs path still wins over box scores when present', async () => { + routeScan({ 'gamelogs:mlb:*': ['gamelogs:mlb:Star:20'] }); + store['gamelogs:mlb:Star:20'] = [{ hits: 3 }, { hits: 2 }]; + const roster = await loadRosterLogs('mlb'); + expect(roster[0].name).toBe('Star'); + expect(roster[0].games).toHaveLength(2); + }); + + test('boxScoreKeyDate extracts the date for recency ordering', () => { + expect(__internals.boxScoreKeyDate('tank01:mlb:boxscore:20260612_ARI@CIN')).toBe('20260612'); + expect(__internals.boxScoreKeyDate('tank01:mlb:boxscore:weird')).toBe('0'); + }); +}); diff --git a/web/public/sw.js b/web/public/sw.js index 555562f..c9728cc 100644 --- a/web/public/sw.js +++ b/web/public/sw.js @@ -1,2 +1,2 @@ (()=>{"use strict";let e,t,a,s,r,n={googleAnalytics:"googleAnalytics",precache:"precache-v2",prefix:"serwist",runtime:"runtime",suffix:"u">typeof registration?registration.scope:""},i=e=>[n.prefix,e,n.suffix].filter(e=>e&&e.length>0).join("-"),c=e=>e||i(n.precache),o=e=>e||i(n.runtime);var l=class extends Error{details;constructor(e,t){super(((e,...t)=>{let a=e;return t.length>0&&(a+=` :: ${JSON.stringify(t)}`),a})(e,t)),this.name=e,this.details=t}};function h(e){return new Promise(t=>setTimeout(t,e))}let u=new Set;function d(e,t){let a=new URL(e);for(let e of t)a.searchParams.delete(e);return a.href}async function m(e,t,a,s){let r=d(t.url,a);if(t.url===r)return e.match(t,s);let n={...s,ignoreSearch:!0};for(let i of(await e.keys(t,n)))if(r===d(i.url,a))return e.match(i,s)}var f=class{promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}};let g=async()=>{for(let e of u)await e()},w="-precache-",p=async(e,t=w)=>{let a=(await self.caches.keys()).filter(a=>a.includes(t)&&a.includes(self.registration.scope)&&a!==e);return await Promise.all(a.map(e=>self.caches.delete(e))),a},y=(e,t)=>{let a=t();return e.waitUntil(a),a},_=(e,t)=>t.some(t=>e instanceof t),x=new WeakMap,b=new WeakMap,v=new WeakMap,E={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return x.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return R(e[t])},set:(e,t,a)=>(e[t]=a,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function R(e){if(e instanceof IDBRequest){let t;return t=new Promise((t,a)=>{let s=()=>{e.removeEventListener("success",r),e.removeEventListener("error",n)},r=()=>{t(R(e.result)),s()},n=()=>{a(e.error),s()};e.addEventListener("success",r),e.addEventListener("error",n)}),v.set(t,e),t}if(b.has(e))return b.get(e);let t=function(e){if("function"==typeof e)return(r||(r=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(q(this),t),R(this.request)}:function(...t){return R(e.apply(q(this),t))};return(e instanceof IDBTransaction&&function(e){if(x.has(e))return;let t=new Promise((t,a)=>{let s=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",n),e.removeEventListener("abort",n)},r=()=>{t(),s()},n=()=>{a(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",r),e.addEventListener("error",n),e.addEventListener("abort",n)});x.set(e,t)}(e),_(e,s||(s=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])))?new Proxy(e,E):e}(e);return t!==e&&(b.set(e,t),v.set(t,e)),t}let q=e=>v.get(e);function S(e,t,{blocked:a,upgrade:s,blocking:r,terminated:n}={}){let i=indexedDB.open(e,t),c=R(i);return s&&i.addEventListener("upgradeneeded",e=>{s(R(i.result),e.oldVersion,e.newVersion,R(i.transaction),e)}),a&&i.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),c.then(e=>{n&&e.addEventListener("close",()=>n()),r&&e.addEventListener("versionchange",e=>r(e.oldVersion,e.newVersion,e))}).catch(()=>{}),c}let D=["get","getKey","getAll","getAllKeys","count"],N=["put","add","delete","clear"],C=new Map;function T(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t))return;if(C.get(t))return C.get(t);let a=t.replace(/FromIndex$/,""),s=t!==a,r=N.includes(a);if(!(a in(s?IDBIndex:IDBObjectStore).prototype)||!(r||D.includes(a)))return;let n=async function(e,...t){let n=this.transaction(e,r?"readwrite":"readonly"),i=n.store;return s&&(i=i.index(t.shift())),(await Promise.all([i[a](...t),r&&n.done]))[0]};return C.set(t,n),n}E={...e=E,get:(t,a,s)=>T(t,a)||e.get(t,a,s),has:(t,a)=>!!T(t,a)||e.has(t,a)};let P=["continue","continuePrimaryKey","advance"],k={},A=new WeakMap,I=new WeakMap,U={get(e,t){if(!P.includes(t))return e[t];let a=k[t];return a||(a=k[t]=function(...e){A.set(this,I.get(this)[t](...e))}),a}};async function*L(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;let a=new Proxy(t,U);for(I.set(a,t),v.set(a,q(t));t;)yield a,t=await (A.get(a)||t.continue()),A.delete(a)}function F(e,t){return t===Symbol.asyncIterator&&_(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&_(e,[IDBIndex,IDBObjectStore])}E={...t=E,get:(e,a,s)=>F(e,a)?L:t.get(e,a,s),has:(e,a)=>F(e,a)||t.has(e,a)};let M=async(e,t)=>{let s=null;if(e.url&&(s=new URL(e.url).origin),s!==self.location.origin)throw new l("cross-origin-copy-response",{origin:s});let r=e.clone(),n={headers:new Headers(r.headers),status:r.status,statusText:r.statusText},i=t?t(n):n,c=!function(){if(void 0===a){let e=new Response("");if("body"in e)try{new Response(e.body),a=!0}catch{a=!1}a=!1}return a}()?await r.blob():r.body;return new Response(c,i)},O="requests",B="queueName";var K=class{_db=null;async addEntry(e){let t=(await this.getDb()).transaction(O,"readwrite",{durability:"relaxed"});await t.store.add(e),await t.done}async getFirstEntryId(){return(await (await this.getDb()).transaction(O).store.openCursor())?.value.id}async getAllEntriesByQueueName(e){return await (await this.getDb()).getAllFromIndex(O,B,IDBKeyRange.only(e))||[]}async getEntryCountByQueueName(e){return(await this.getDb()).countFromIndex(O,B,IDBKeyRange.only(e))}async deleteEntry(e){await (await this.getDb()).delete(O,e)}async getFirstEntryByQueueName(e){return await this.getEndEntryFromIndex(IDBKeyRange.only(e),"next")}async getLastEntryByQueueName(e){return await this.getEndEntryFromIndex(IDBKeyRange.only(e),"prev")}async getEndEntryFromIndex(e,t){return(await (await this.getDb()).transaction(O).store.index(B).openCursor(e,t))?.value}async getDb(){return this._db||(this._db=await S("serwist-background-sync",3,{upgrade:this._upgradeDb})),this._db}_upgradeDb(e,t){t>0&&t<3&&e.objectStoreNames.contains(O)&&e.deleteObjectStore(O),e.createObjectStore(O,{autoIncrement:!0,keyPath:"id"}).createIndex(B,B,{unique:!1})}},W=class{_queueName;_queueDb;constructor(e){this._queueName=e,this._queueDb=new K}async pushEntry(e){delete e.id,e.queueName=this._queueName,await this._queueDb.addEntry(e)}async unshiftEntry(e){let t=await this._queueDb.getFirstEntryId();t?e.id=t-1:delete e.id,e.queueName=this._queueName,await this._queueDb.addEntry(e)}async popEntry(){return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName))}async shiftEntry(){return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName))}async getAll(){return await this._queueDb.getAllEntriesByQueueName(this._queueName)}async size(){return await this._queueDb.getEntryCountByQueueName(this._queueName)}async deleteEntry(e){await this._queueDb.deleteEntry(e)}async _removeEntry(e){return e&&await this.deleteEntry(e.id),e}};let j=["method","referrer","referrerPolicy","mode","credentials","cache","redirect","integrity","keepalive"];var $=class e{_requestData;static async fromRequest(t){let a={url:t.url,headers:{}};for(let e of("GET"!==t.method&&(a.body=await t.clone().arrayBuffer()),t.headers.forEach((e,t)=>{a.headers[t]=e}),j))void 0!==t[e]&&(a[e]=t[e]);return new e(a)}constructor(e){"navigate"===e.mode&&(e.mode="same-origin"),this._requestData=e}toObject(){let e=Object.assign({},this._requestData);return e.headers=Object.assign({},this._requestData.headers),e.body&&(e.body=e.body.slice(0)),e}toRequest(){return new Request(this._requestData.url,this._requestData)}clone(){return new e(this.toObject())}};let H="serwist-background-sync",V=new Set,G=e=>{let t={request:new $(e.requestData).toRequest(),timestamp:e.timestamp};return e.metadata&&(t.metadata=e.metadata),t};var Q=class{_name;_onSync;_maxRetentionTime;_queueStore;_forceSyncFallback;_syncInProgress=!1;_requestsAddedDuringSync=!1;constructor(e,{forceSyncFallback:t,onSync:a,maxRetentionTime:s}={}){if(V.has(e))throw new l("duplicate-queue-name",{name:e});V.add(e),this._name=e,this._onSync=a||this.replayRequests,this._maxRetentionTime=s||10080,this._forceSyncFallback=!!t,this._queueStore=new W(this._name),this._addSyncListener()}get name(){return this._name}async pushRequest(e){await this._addRequest(e,"push")}async unshiftRequest(e){await this._addRequest(e,"unshift")}async popRequest(){return this._removeRequest("pop")}async shiftRequest(){return this._removeRequest("shift")}async getAll(){let e=await this._queueStore.getAll(),t=Date.now(),a=[];for(let s of e){let e=60*this._maxRetentionTime*1e3;t-s.timestamp>e?await this._queueStore.deleteEntry(s.id):a.push(G(s))}return a}async size(){return await this._queueStore.size()}async _addRequest({request:e,metadata:t,timestamp:a=Date.now()},s){let r={requestData:(await $.fromRequest(e.clone())).toObject(),timestamp:a};switch(t&&(r.metadata=t),s){case"push":await this._queueStore.pushEntry(r);break;case"unshift":await this._queueStore.unshiftEntry(r)}this._syncInProgress?this._requestsAddedDuringSync=!0:await this.registerSync()}async _removeRequest(e){let t,a=Date.now();switch(e){case"pop":t=await this._queueStore.popEntry();break;case"shift":t=await this._queueStore.shiftEntry()}if(t){let s=60*this._maxRetentionTime*1e3;return a-t.timestamp>s?this._removeRequest(e):G(t)}}async replayRequests(){let e;for(;e=await this.shiftRequest();)try{await fetch(e.request.clone())}catch{throw await this.unshiftRequest(e),new l("queue-replay-failed",{name:this._name})}}async registerSync(){if("sync"in self.registration&&!this._forceSyncFallback)try{await self.registration.sync.register(`${H}:${this._name}`)}catch(e){}}_addSyncListener(){"sync"in self.registration&&!this._forceSyncFallback?self.addEventListener("sync",e=>{if(e.tag===`${H}:${this._name}`){let t=async()=>{let t;this._syncInProgress=!0;try{await this._onSync({queue:this})}catch(e){if(e instanceof Error)throw e}finally{this._requestsAddedDuringSync&&!(t&&!e.lastChance)&&await this.registerSync(),this._syncInProgress=!1,this._requestsAddedDuringSync=!1}};e.waitUntil(t())}}):this._onSync({queue:this})}static get _queueNames(){return V}},z=class{_queue;constructor(e,t){this._queue=new Q(e,t)}async fetchDidFail({request:e}){await this._queue.pushRequest({request:e})}};let Y={cacheWillUpdate:async({response:e})=>200===e.status||0===e.status?e:null};function J(e){return"string"==typeof e?new Request(e):e}var X=class{event;request;url;params;_cacheKeys={};_strategy;_handlerDeferred;_extendLifetimePromises;_plugins;_pluginStateMap;constructor(e,t){for(const a of(this.event=t.event,this.request=t.request,t.url&&(this.url=t.url,this.params=t.params),this._strategy=e,this._handlerDeferred=new f,this._extendLifetimePromises=[],this._plugins=[...e.plugins],this._pluginStateMap=new Map,this._plugins))this._pluginStateMap.set(a,{});this.event.waitUntil(this._handlerDeferred.promise)}async fetch(e){let{event:t}=this,a=J(e),s=await this.getPreloadResponse();if(s)return s;let r=this.hasCallback("fetchDidFail")?a.clone():null;try{for(let e of this.iterateCallbacks("requestWillFetch"))a=await e({request:a.clone(),event:t})}catch(e){if(e instanceof Error)throw new l("plugin-error-request-will-fetch",{thrownErrorMessage:e.message})}let n=a.clone();try{let e;for(let s of(e=await fetch(a,"navigate"===a.mode?void 0:this._strategy.fetchOptions),this.iterateCallbacks("fetchDidSucceed")))e=await s({event:t,request:n,response:e});return e}catch(e){throw r&&await this.runCallbacks("fetchDidFail",{error:e,event:t,originalRequest:r.clone(),request:n.clone()}),e}}async fetchAndCachePut(e){let t=await this.fetch(e),a=t.clone();return this.waitUntil(this.cachePut(e,a)),t}async cacheMatch(e){let t,a=J(e),{cacheName:s,matchOptions:r}=this._strategy,n=await this.getCacheKey(a,"read"),i={...r,cacheName:s};for(let e of(t=await caches.match(n,i),this.iterateCallbacks("cachedResponseWillBeUsed")))t=await e({cacheName:s,matchOptions:r,cachedResponse:t,request:n,event:this.event})||void 0;return t}async cachePut(e,t){let a=J(e);await h(0);let s=await this.getCacheKey(a,"write");if(!t)throw new l("cache-put-with-no-response",{url:new URL(String(s.url),location.href).href.replace(RegExp(`^${location.origin}`),"")});let r=await this._ensureResponseSafeToCache(t);if(!r)return!1;let{cacheName:n,matchOptions:i}=this._strategy,c=await self.caches.open(n),o=this.hasCallback("cacheDidUpdate"),u=o?await m(c,s.clone(),["__WB_REVISION__"],i):null;try{await c.put(s,o?r.clone():r)}catch(e){if(e instanceof Error)throw"QuotaExceededError"===e.name&&await g(),e}for(let e of this.iterateCallbacks("cacheDidUpdate"))await e({cacheName:n,oldResponse:u,newResponse:r.clone(),request:s,event:this.event});return!0}async getCacheKey(e,t){let a=`${e.url} | ${t}`;if(!this._cacheKeys[a]){let s=e;for(let e of this.iterateCallbacks("cacheKeyWillBeUsed"))s=J(await e({mode:t,request:s,event:this.event,params:this.params}));this._cacheKeys[a]=s}return this._cacheKeys[a]}hasCallback(e){for(let t of this._strategy.plugins)if(e in t)return!0;return!1}async runCallbacks(e,t){for(let a of this.iterateCallbacks(e))await a(t)}*iterateCallbacks(e){for(let t of this._strategy.plugins)if("function"==typeof t[e]){let a=this._pluginStateMap.get(t),s=s=>{let r={...s,state:a};return t[e](r)};yield s}}waitUntil(e){return this._extendLifetimePromises.push(e),e}async doneWaiting(){let e;for(;e=this._extendLifetimePromises.shift();)await e}destroy(){this._handlerDeferred.resolve(null)}async getPreloadResponse(){if(this.event instanceof FetchEvent&&"navigate"===this.event.request.mode&&"preloadResponse"in this.event)try{let e=await this.event.preloadResponse;if(e)return e}catch(e){return}}async _ensureResponseSafeToCache(e){let t=e,a=!1;for(let e of this.iterateCallbacks("cacheWillUpdate"))if(t=await e({request:this.request,response:t,event:this.event})||void 0,a=!0,!t)break;return!a&&t&&200!==t.status&&(t=void 0),t}},Z=class{cacheName;plugins;fetchOptions;matchOptions;constructor(e={}){this.cacheName=o(e.cacheName),this.plugins=e.plugins||[],this.fetchOptions=e.fetchOptions,this.matchOptions=e.matchOptions}handle(e){let[t]=this.handleAll(e);return t}handleAll(e){e instanceof FetchEvent&&(e={event:e,request:e.request});let t=e.event,a="string"==typeof e.request?new Request(e.request):e.request,s=new X(this,e.url?{event:t,request:a,url:e.url,params:e.params}:{event:t,request:a}),r=this._getResponse(s,a,t);return[r,this._awaitComplete(r,s,a,t)]}async _getResponse(e,t,a){let s;await e.runCallbacks("handlerWillStart",{event:a,request:t});try{if(s=await this._handle(t,e),void 0===s||"error"===s.type)throw new l("no-response",{url:t.url})}catch(r){if(r instanceof Error){for(let n of e.iterateCallbacks("handlerDidError"))if(void 0!==(s=await n({error:r,event:a,request:t})))break}if(!s)throw r}for(let r of e.iterateCallbacks("handlerWillRespond"))s=await r({event:a,request:t,response:s});return s}async _awaitComplete(e,t,a,s){let r,n;try{r=await e}catch{}try{await t.runCallbacks("handlerDidRespond",{event:s,request:a,response:r}),await t.doneWaiting()}catch(e){e instanceof Error&&(n=e)}if(await t.runCallbacks("handlerDidComplete",{event:s,request:a,response:r,error:n}),t.destroy(),n)throw n}},ee=class extends Z{_networkTimeoutSeconds;constructor(e={}){super(e),this.plugins.some(e=>"cacheWillUpdate"in e)||this.plugins.unshift(Y),this._networkTimeoutSeconds=e.networkTimeoutSeconds||0}async _handle(e,t){let a,s=[],r=[];if(this._networkTimeoutSeconds){let{id:n,promise:i}=this._getTimeoutPromise({request:e,logs:s,handler:t});a=n,r.push(i)}let n=this._getNetworkPromise({timeoutId:a,request:e,logs:s,handler:t});r.push(n);let i=await t.waitUntil((async()=>await t.waitUntil(Promise.race(r))||await n)());if(!i)throw new l("no-response",{url:e.url});return i}_getTimeoutPromise({request:e,logs:t,handler:a}){let s;return{promise:new Promise(t=>{s=setTimeout(async()=>{t(await a.cacheMatch(e))},1e3*this._networkTimeoutSeconds)}),id:s}}async _getNetworkPromise({timeoutId:e,request:t,logs:a,handler:s}){let r,n;try{n=await s.fetchAndCachePut(t)}catch(e){e instanceof Error&&(r=e)}return e&&clearTimeout(e),(r||!n)&&(n=await s.cacheMatch(t)),n}},et=class extends Z{_networkTimeoutSeconds;constructor(e={}){super(e),this._networkTimeoutSeconds=e.networkTimeoutSeconds||0}async _handle(e,t){let a,s;try{let a=[t.fetch(e)];if(this._networkTimeoutSeconds){let e=h(1e3*this._networkTimeoutSeconds);a.push(e)}if(!(s=await Promise.race(a)))throw Error(`Timed out the network response after ${this._networkTimeoutSeconds} seconds.`)}catch(e){e instanceof Error&&(a=e)}if(!s)throw new l("no-response",{url:e.url,error:a});return s}};let ea=e=>e&&"object"==typeof e?e:{handle:e};var es=class{handler;match;method;catchHandler;constructor(e,t,a="GET"){this.handler=ea(t),this.match=e,this.method=a}setCatchHandler(e){this.catchHandler=ea(e)}},er=class e extends Z{_fallbackToNetwork;static defaultPrecacheCacheabilityPlugin={cacheWillUpdate:async({response:e})=>!e||e.status>=400?null:e};static copyRedirectedCacheableResponsesPlugin={cacheWillUpdate:async({response:e})=>e.redirected?await M(e):e};constructor(t={}){t.cacheName=c(t.cacheName),super(t),this._fallbackToNetwork=!1!==t.fallbackToNetwork,this.plugins.push(e.copyRedirectedCacheableResponsesPlugin)}async _handle(e,t){let a=await t.getPreloadResponse();if(a)return a;let s=await t.cacheMatch(e);return s||(t.event&&"install"===t.event.type?await this._handleInstall(e,t):await this._handleFetch(e,t))}async _handleFetch(e,t){let a,s=t.params||{};if(this._fallbackToNetwork){let r=s.integrity,n=e.integrity,i=!n||n===r;a=await t.fetch(new Request(e,{integrity:"no-cors"!==e.mode?n||r:void 0})),r&&i&&"no-cors"!==e.mode&&(this._useDefaultCacheabilityPluginIfNeeded(),await t.cachePut(e,a.clone()))}else throw new l("missing-precache-entry",{cacheName:this.cacheName,url:e.url});return a}async _handleInstall(e,t){this._useDefaultCacheabilityPluginIfNeeded();let a=await t.fetch(e);if(!await t.cachePut(e,a.clone()))throw new l("bad-precaching-response",{url:e.url,status:a.status});return a}_useDefaultCacheabilityPluginIfNeeded(){let t=null,a=0;for(let[s,r]of this.plugins.entries())r!==e.copyRedirectedCacheableResponsesPlugin&&(r===e.defaultPrecacheCacheabilityPlugin&&(t=s),r.cacheWillUpdate&&a++);0===a?this.plugins.push(e.defaultPrecacheCacheabilityPlugin):a>1&&null!==t&&this.plugins.splice(t,1)}},en=class extends es{_allowlist;_denylist;constructor(e,{allowlist:t=[/./],denylist:a=[]}={}){super(e=>this._match(e),e),this._allowlist=t,this._denylist=a}_match({url:e,request:t}){if(t&&"navigate"!==t.mode)return!1;let a=e.pathname+e.search;for(let e of this._denylist)if(e.test(a))return!1;return!!this._allowlist.some(e=>e.test(a))}},ei=class extends es{constructor(e,t,a){super(({url:t})=>{let a=e.exec(t.href);if(a)return t.origin!==location.origin&&0!==a.index?void 0:a.slice(1)},t,a)}};let ec=e=>{if(!e)throw new l("add-to-cache-list-unexpected-type",{entry:e});if("string"==typeof e){let t=new URL(e,location.href);return{cacheKey:t.href,url:t.href}}let{revision:t,url:a}=e;if(!a)throw new l("add-to-cache-list-unexpected-type",{entry:e});if(!t){let e=new URL(a,location.href);return{cacheKey:e.href,url:e.href}}let s=new URL(a,location.href),r=new URL(a,location.href);return s.searchParams.set("__WB_REVISION__",t),{cacheKey:s.href,url:r.href}};var eo=class{updatedURLs=[];notUpdatedURLs=[];handlerWillStart=async({request:e,state:t})=>{t&&(t.originalRequest=e)};cachedResponseWillBeUsed=async({event:e,state:t,cachedResponse:a})=>{if("install"===e.type&&t?.originalRequest&&t.originalRequest instanceof Request){let e=t.originalRequest.url;a?this.notUpdatedURLs.push(e):this.updatedURLs.push(e)}return a}};let el=async(e,t,a)=>{let s=t.map((e,t)=>({index:t,item:e})),r=async e=>{let t=[];for(;;){let r=s.pop();if(!r)return e(t);let n=await a(r.item);t.push({result:n,index:r.index})}},n=Array.from({length:e},()=>new Promise(r));return(await Promise.all(n)).flat().sort((e,t)=>e.indexe.result)};"u">typeof navigator&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent);let eh="cache-entries",eu=e=>{let t=new URL(e,location.href);return t.hash="",t.href};var ed=class{_cacheName;_db=null;constructor(e){this._cacheName=e}_getId(e){return`${this._cacheName}|${eu(e)}`}_upgradeDb(e){let t=e.createObjectStore(eh,{keyPath:"id"});t.createIndex("cacheName","cacheName",{unique:!1}),t.createIndex("timestamp","timestamp",{unique:!1})}_upgradeDbAndDeleteOldDbs(e){this._upgradeDb(e),this._cacheName&&function(e,{blocked:t}={}){let a=indexedDB.deleteDatabase(e);t&&a.addEventListener("blocked",e=>t(e.oldVersion,e)),R(a).then(()=>void 0)}(this._cacheName)}async setTimestamp(e,t){e=eu(e);let a={id:this._getId(e),cacheName:this._cacheName,url:e,timestamp:t},s=(await this.getDb()).transaction(eh,"readwrite",{durability:"relaxed"});await s.store.put(a),await s.done}async getTimestamp(e){return(await (await this.getDb()).get(eh,this._getId(e)))?.timestamp}async expireEntries(e,t){let a=await (await this.getDb()).transaction(eh,"readwrite").store.index("timestamp").openCursor(null,"prev"),s=[],r=0;for(;a;){let n=a.value;n.cacheName===this._cacheName&&(e&&n.timestamp=t?(a.delete(),s.push(n.url)):r++),a=await a.continue()}return s}async getDb(){return this._db||(this._db=await S("serwist-expiration",1,{upgrade:this._upgradeDbAndDeleteOldDbs.bind(this)})),this._db}},em=class{_isRunning=!1;_rerunRequested=!1;_maxEntries;_maxAgeSeconds;_matchOptions;_cacheName;_timestampModel;constructor(e,t={}){this._maxEntries=t.maxEntries,this._maxAgeSeconds=t.maxAgeSeconds,this._matchOptions=t.matchOptions,this._cacheName=e,this._timestampModel=new ed(e)}async expireEntries(){if(this._isRunning){this._rerunRequested=!0;return}this._isRunning=!0;let e=this._maxAgeSeconds?Date.now()-1e3*this._maxAgeSeconds:0,t=await this._timestampModel.expireEntries(e,this._maxEntries),a=await self.caches.open(this._cacheName);for(let e of t)await a.delete(e,this._matchOptions);this._isRunning=!1,this._rerunRequested&&(this._rerunRequested=!1,this.expireEntries())}async updateTimestamp(e){await this._timestampModel.setTimestamp(e,Date.now())}async isURLExpired(e){if(!this._maxAgeSeconds)return!1;let t=await this._timestampModel.getTimestamp(e),a=Date.now()-1e3*this._maxAgeSeconds;return void 0===t||t{u.add(e)})(()=>this.deleteCacheAndMetadata())}_getCacheExpiration(e){if(e===o())throw new l("expire-custom-caches-only");let t=this._cacheExpirations.get(e);return t||(t=new em(e,this._config),this._cacheExpirations.set(e,t)),t}cachedResponseWillBeUsed({event:e,cacheName:t,request:a,cachedResponse:s}){if(!s)return null;let r=this._isResponseDateFresh(s),n=this._getCacheExpiration(t),i="last-used"===this._config.maxAgeFrom,c=(async()=>{i&&await n.updateTimestamp(a.url),await n.expireEntries()})();try{e.waitUntil(c)}catch{}return r?s:null}_isResponseDateFresh(e){if("last-used"===this._config.maxAgeFrom)return!0;let t=Date.now();if(!this._config.maxAgeSeconds)return!0;let a=this._getDateHeaderTimestamp(e);return null===a||a>=t-1e3*this._config.maxAgeSeconds}_getDateHeaderTimestamp(e){if(!e.headers.has("date"))return null;let t=new Date(e.headers.get("date")).getTime();return Number.isNaN(t)?null:t}async cacheDidUpdate({cacheName:e,request:t}){let a=this._getCacheExpiration(e);await a.updateTimestamp(t.url),await a.expireEntries()}async deleteCacheAndMetadata(){for(let[e,t]of this._cacheExpirations)await self.caches.delete(e),await t.delete();this._cacheExpirations=new Map}};let eg=/^\/(\w+\/)?collect/,ew=({serwist:e,cacheName:t,...a})=>{let s,r,c=t||i(n.googleAnalytics),o=new z("serwist-google-analytics",{maxRetentionTime:2880,onSync:async({queue:e})=>{let t;for(;t=await e.shiftRequest();){let{request:s,timestamp:r}=t,n=new URL(s.url);try{let e="POST"===s.method?new URLSearchParams(await s.clone().text()):n.searchParams,t=r-(Number(e.get("qt"))||0),i=Date.now()-t;if(e.set("qt",String(i)),a.parameterOverrides)for(let t of Object.keys(a.parameterOverrides)){let s=a.parameterOverrides[t];e.set(t,s)}"function"==typeof a.hitFilter&&a.hitFilter.call(null,e),await fetch(new Request(n.origin+n.pathname,{body:e.toString(),method:"POST",mode:"cors",credentials:"omit",headers:{"Content-Type":"text/plain"}}))}catch(a){throw await e.unshiftRequest(t),a}}}});for(let t of[new es(({url:e})=>"www.googletagmanager.com"===e.hostname&&"/gtm.js"===e.pathname,new ee({cacheName:c}),"GET"),new es(({url:e})=>"www.google-analytics.com"===e.hostname&&"/analytics.js"===e.pathname,new ee({cacheName:c}),"GET"),new es(({url:e})=>"www.googletagmanager.com"===e.hostname&&"/gtag/js"===e.pathname,new ee({cacheName:c}),"GET"),new es(s=({url:e})=>"www.google-analytics.com"===e.hostname&&eg.test(e.pathname),r=new et({plugins:[o]}),"GET"),new es(s,r,"POST")])e.registerRoute(t)};var ep=class{_fallbackUrls;_serwist;constructor({fallbackUrls:e,serwist:t}){this._fallbackUrls=e,this._serwist=t}async handlerDidError(e){for(let t of this._fallbackUrls)if("string"==typeof t){let e=await this._serwist.matchPrecache(t);if(void 0!==e)return e}else if(t.matcher(e)){let e=await this._serwist.matchPrecache(t.url);if(void 0!==e)return e}}};let ey=async(e,t)=>{try{if(206===t.status)return t;let a=e.headers.get("range");if(!a)throw new l("no-range-header");let s=(e=>{let t=e.trim().toLowerCase();if(!t.startsWith("bytes="))throw new l("unit-must-be-bytes",{normalizedRangeHeader:t});if(t.includes(","))throw new l("single-range-only",{normalizedRangeHeader:t});let a=/(\d*)-(\d*)/.exec(t);if(!a||!(a[1]||a[2]))throw new l("invalid-range-values",{normalizedRangeHeader:t});return{start:""===a[1]?void 0:Number(a[1]),end:""===a[2]?void 0:Number(a[2])}})(a),r=await t.blob(),n=((e,t,a)=>{let s,r,n=e.size;if(a&&a>n||t&&t<0)throw new l("range-not-satisfiable",{size:n,end:a,start:t});return void 0!==t&&void 0!==a?(s=t,r=a+1):void 0!==t&&void 0===a?(s=t,r=n):void 0!==a&&void 0===t&&(s=n-a,r=n),{start:s,end:r}})(r,s.start,s.end),i=r.slice(n.start,n.end),c=i.size,o=new Response(i,{status:206,statusText:"Partial Content",headers:t.headers});return o.headers.set("Content-Length",String(c)),o.headers.set("Content-Range",`bytes ${n.start}-${n.end-1}/${r.size}`),o}catch(e){return new Response("",{status:416,statusText:"Range Not Satisfiable"})}};var e_=class{cachedResponseWillBeUsed=async({request:e,cachedResponse:t})=>t&&e.headers.has("range")?await ey(e,t):t},ex=class extends Z{async _handle(e,t){let a,s=await t.cacheMatch(e);if(s);else try{s=await t.fetchAndCachePut(e)}catch(e){e instanceof Error&&(a=e)}if(!s)throw new l("no-response",{url:e.url,error:a});return s}},eb=class extends Z{constructor(e={}){super(e),this.plugins.some(e=>"cacheWillUpdate"in e)||this.plugins.unshift(Y)}async _handle(e,t){let a,s=t.fetchAndCachePut(e).catch(()=>{});t.waitUntil(s);let r=await t.cacheMatch(e);if(r);else try{r=await s}catch(e){e instanceof Error&&(a=e)}if(!r)throw new l("no-response",{url:e.url,error:a});return r}},ev=class extends es{constructor(e,t){super(({request:a})=>{let s=e.getUrlsToPrecacheKeys();for(let r of function*(e,{directoryIndex:t="index.html",ignoreURLParametersMatching:a=[/^utm_/,/^fbclid$/],cleanURLs:s=!0,urlManipulation:r}={}){let n=new URL(e,location.href);n.hash="",yield n.href;let i=((e,t=[])=>{for(let a of[...e.searchParams.keys()])t.some(e=>e.test(a))&&e.searchParams.delete(a);return e})(n,a);if(yield i.href,t&&i.pathname.endsWith("/")){let e=new URL(i.href);e.pathname+=t,yield e.href}if(s){let e=new URL(i.href);e.pathname+=".html",yield e.href}if(r)for(let e of r({url:n}))yield e.href}(a.url,t)){let t=s.get(r);if(t)return{cacheKey:t,integrity:e.getIntegrityForPrecacheKey(t)}}},e.precacheStrategy)}},eE=class{_precacheController;constructor({precacheController:e}){this._precacheController=e}cacheKeyWillBeUsed=async({request:e,params:t})=>{let a=t?.cacheKey||this._precacheController.getPrecacheKeyForUrl(e.url);return a?new Request(a,{headers:e.headers}):e}},eR=class{_urlsToCacheKeys=new Map;_urlsToCacheModes=new Map;_cacheKeysToIntegrities=new Map;_concurrentPrecaching;_precacheStrategy;_routes;_defaultHandlerMap;_catchHandler;_requestRules;constructor({precacheEntries:e,precacheOptions:t,skipWaiting:a=!1,importScripts:s,navigationPreload:r=!1,cacheId:i,clientsClaim:o=!1,runtimeCaching:l,offlineAnalyticsConfig:h,disableDevLogs:u=!1,fallbacks:d,requestRules:m}={}){const{precacheStrategyOptions:f,precacheRouteOptions:g,precacheMiscOptions:w}=((e,t={})=>{let{cacheName:a,plugins:s=[],fetchOptions:r,matchOptions:n,fallbackToNetwork:i,directoryIndex:o,ignoreURLParametersMatching:l,cleanURLs:h,urlManipulation:u,cleanupOutdatedCaches:d,concurrency:m=10,navigateFallback:f,navigateFallbackAllowlist:g,navigateFallbackDenylist:w}=t??{};return{precacheStrategyOptions:{cacheName:c(a),plugins:[...s,new eE({precacheController:e})],fetchOptions:r,matchOptions:n,fallbackToNetwork:i},precacheRouteOptions:{directoryIndex:o,ignoreURLParametersMatching:l,cleanURLs:h,urlManipulation:u},precacheMiscOptions:{cleanupOutdatedCaches:d,concurrency:m,navigateFallback:f,navigateFallbackAllowlist:g,navigateFallbackDenylist:w}}})(this,t);if(this._concurrentPrecaching=w.concurrency,this._precacheStrategy=new er(f),this._routes=new Map,this._defaultHandlerMap=new Map,this._requestRules=m,this.handleInstall=this.handleInstall.bind(this),this.handleActivate=this.handleActivate.bind(this),this.handleFetch=this.handleFetch.bind(this),this.handleCache=this.handleCache.bind(this),s&&s.length>0&&self.importScripts(...s),r&&self.registration?.navigationPreload&&self.addEventListener("activate",e=>{e.waitUntil(self.registration.navigationPreload.enable().then(()=>{}))}),void 0!==i&&(e=>{var t=e;for(let e of Object.keys(n))(e=>{let a=t[e];"string"==typeof a&&(n[e]=a)})(e)})({prefix:i}),a?self.skipWaiting():self.addEventListener("message",e=>{e.data&&"SKIP_WAITING"===e.data.type&&self.skipWaiting()}),o&&self.addEventListener("activate",()=>self.clients.claim()),e&&e.length>0&&this.addToPrecacheList(e),w.cleanupOutdatedCaches&&(e=>{self.addEventListener("activate",t=>{t.waitUntil(p(c(e)).then(e=>{}))})})(f.cacheName),this.registerRoute(new ev(this,g)),w.navigateFallback&&this.registerRoute(new en(this.createHandlerBoundToUrl(w.navigateFallback),{allowlist:w.navigateFallbackAllowlist,denylist:w.navigateFallbackDenylist})),void 0!==h&&("boolean"==typeof h?h&&ew({serwist:this}):ew({...h,serwist:this})),void 0!==l){if(void 0!==d){const e=new ep({fallbackUrls:d.entries,serwist:this});l.forEach(t=>{t.handler instanceof Z&&!t.handler.plugins.some(e=>"handlerDidError"in e)&&t.handler.plugins.push(e)})}for(const e of l)this.registerCapture(e.matcher,e.handler,e.method)}u&&(self.__WB_DISABLE_DEV_LOGS=!0)}get precacheStrategy(){return this._precacheStrategy}get routes(){return this._routes}addEventListeners(){self.addEventListener("install",this.handleInstall),self.addEventListener("activate",this.handleActivate),self.addEventListener("fetch",this.handleFetch),self.addEventListener("message",this.handleCache)}addToPrecacheList(e){let t=[];for(let a of e){"string"==typeof a?t.push(a):a&&!a.integrity&&void 0===a.revision&&t.push(a.url);let{cacheKey:e,url:s}=ec(a),r="string"!=typeof a&&a.revision?"reload":"default";if(this._urlsToCacheKeys.has(s)&&this._urlsToCacheKeys.get(s)!==e)throw new l("add-to-cache-list-conflicting-entries",{firstEntry:this._urlsToCacheKeys.get(s),secondEntry:e});if("string"!=typeof a&&a.integrity){if(this._cacheKeysToIntegrities.has(e)&&this._cacheKeysToIntegrities.get(e)!==a.integrity)throw new l("add-to-cache-list-conflicting-integrities",{url:s});this._cacheKeysToIntegrities.set(e,a.integrity)}this._urlsToCacheKeys.set(s,e),this._urlsToCacheModes.set(s,r)}t.length>0&&console.warn(`Serwist is precaching URLs without revision info: ${t.join(", ")} -This is generally NOT safe. Learn more at https://bit.ly/wb-precache`)}handleInstall(e){return this.registerRequestRules(e),y(e,async()=>{let t=new eo;this.precacheStrategy.plugins.push(t),await el(this._concurrentPrecaching,Array.from(this._urlsToCacheKeys.entries()),async([t,a])=>{let s=this._cacheKeysToIntegrities.get(a),r=this._urlsToCacheModes.get(t),n=new Request(t,{integrity:s,cache:r,credentials:"same-origin"});await Promise.all(this.precacheStrategy.handleAll({event:e,request:n,url:new URL(n.url),params:{cacheKey:a}}))});let{updatedURLs:a,notUpdatedURLs:s}=t;return{updatedURLs:a,notUpdatedURLs:s}})}async registerRequestRules(e){if(this._requestRules&&e?.addRoutes)try{await e.addRoutes(this._requestRules),this._requestRules=void 0}catch(e){throw e}}handleActivate(e){return y(e,async()=>{let e=await self.caches.open(this.precacheStrategy.cacheName),t=await e.keys(),a=new Set(this._urlsToCacheKeys.values()),s=[];for(let r of t)a.has(r.url)||(await e.delete(r),s.push(r.url));return{deletedCacheRequests:s}})}handleFetch(e){let{request:t}=e,a=this.handleRequest({request:t,event:e});a&&e.respondWith(a)}handleCache(e){if(e.data&&"CACHE_URLS"===e.data.type){let{payload:t}=e.data,a=Promise.all(t.urlsToCache.map(t=>{let a;return a="string"==typeof t?new Request(t):new Request(...t),this.handleRequest({request:a,event:e})}));e.waitUntil(a),e.ports?.[0]&&a.then(()=>e.ports[0].postMessage(!0))}}setDefaultHandler(e,t="GET"){this._defaultHandlerMap.set(t,ea(e))}setCatchHandler(e){this._catchHandler=ea(e)}registerCapture(e,t,a){let s=((e,t,a)=>{if("string"==typeof e){let s=new URL(e,location.href);return new es(({url:e})=>e.href===s.href,t,a)}if(e instanceof RegExp)return new ei(e,t,a);if("function"==typeof e)return new es(e,t,a);if(e instanceof es)return e;throw new l("unsupported-route-type",{moduleName:"serwist",funcName:"parseRoute",paramName:"capture"})})(e,t,a);return this.registerRoute(s),s}registerRoute(e){this._routes.has(e.method)||this._routes.set(e.method,[]),this._routes.get(e.method).push(e)}unregisterRoute(e){if(!this._routes.has(e.method))throw new l("unregister-route-but-not-found-with-method",{method:e.method});let t=this._routes.get(e.method).indexOf(e);if(t>-1)this._routes.get(e.method).splice(t,1);else throw new l("unregister-route-route-not-registered")}getUrlsToPrecacheKeys(){return this._urlsToCacheKeys}getPrecachedUrls(){return[...this._urlsToCacheKeys.keys()]}getPrecacheKeyForUrl(e){let t=new URL(e,location.href);return this._urlsToCacheKeys.get(t.href)}getIntegrityForPrecacheKey(e){return this._cacheKeysToIntegrities.get(e)}async matchPrecache(e){let t=e instanceof Request?e.url:e,a=this.getPrecacheKeyForUrl(t);if(a)return(await self.caches.open(this.precacheStrategy.cacheName)).match(a)}createHandlerBoundToUrl(e){let t=this.getPrecacheKeyForUrl(e);if(!t)throw new l("non-precached-url",{url:e});return a=>(a.request=new Request(e),a.params={cacheKey:t,...a.params},this.precacheStrategy.handle(a))}handleRequest({request:e,event:t}){let a,s=new URL(e.url,location.href);if(!s.protocol.startsWith("http"))return;let r=s.origin===location.origin,{params:n,route:i}=this.findMatchingRoute({event:t,request:e,sameOrigin:r,url:s}),c=i?.handler,o=e.method;if(!c&&this._defaultHandlerMap.has(o)&&(c=this._defaultHandlerMap.get(o)),!c)return;try{a=c.handle({url:s,request:e,event:t,params:n})}catch(e){a=Promise.reject(e)}let l=i?.catchHandler;return a instanceof Promise&&(this._catchHandler||l)&&(a=a.catch(async a=>{if(l)try{return await l.handle({url:s,request:e,event:t,params:n})}catch(e){e instanceof Error&&(a=e)}if(this._catchHandler)return this._catchHandler.handle({url:s,request:e,event:t});throw a})),a}findMatchingRoute({url:e,sameOrigin:t,request:a,event:s}){for(let r of this._routes.get(a.method)||[]){let n,i=r.match({url:e,sameOrigin:t,request:a,event:s});if(i)return Array.isArray(n=i)&&0===n.length||i.constructor===Object&&0===Object.keys(i).length?n=void 0:"boolean"==typeof i&&(n=void 0),{route:r,params:n}}return{}}};let eq=[{matcher:/^https:\/\/fonts\.(?:gstatic)\.com\/.*/i,handler:new ex({cacheName:"google-fonts-webfonts",plugins:[new ef({maxEntries:4,maxAgeSeconds:31536e3,maxAgeFrom:"last-used"})]})},{matcher:/^https:\/\/fonts\.(?:googleapis)\.com\/.*/i,handler:new eb({cacheName:"google-fonts-stylesheets",plugins:[new ef({maxEntries:4,maxAgeSeconds:604800,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:eot|otf|ttc|ttf|woff|woff2|font.css)$/i,handler:new eb({cacheName:"static-font-assets",plugins:[new ef({maxEntries:4,maxAgeSeconds:604800,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:jpg|jpeg|gif|png|svg|ico|webp)$/i,handler:new eb({cacheName:"static-image-assets",plugins:[new ef({maxEntries:64,maxAgeSeconds:2592e3,maxAgeFrom:"last-used"})]})},{matcher:/\/_next\/static.+\.js$/i,handler:new ex({cacheName:"next-static-js-assets",plugins:[new ef({maxEntries:64,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\/_next\/image\?url=.+$/i,handler:new eb({cacheName:"next-image",plugins:[new ef({maxEntries:64,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:mp3|wav|ogg)$/i,handler:new ex({cacheName:"static-audio-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"}),new e_]})},{matcher:/\.(?:mp4|webm)$/i,handler:new ex({cacheName:"static-video-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"}),new e_]})},{matcher:/\.(?:js)$/i,handler:new eb({cacheName:"static-js-assets",plugins:[new ef({maxEntries:48,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:css|less)$/i,handler:new eb({cacheName:"static-style-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\/_next\/data\/.+\/.+\.json$/i,handler:new ee({cacheName:"next-data",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:json|xml|csv)$/i,handler:new ee({cacheName:"static-data-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\/api\/auth\/.*/,handler:new et({networkTimeoutSeconds:10})},{matcher:({sameOrigin:e,url:{pathname:t}})=>e&&t.startsWith("/api/"),method:"GET",handler:new ee({cacheName:"apis",plugins:[new ef({maxEntries:16,maxAgeSeconds:86400,maxAgeFrom:"last-used"})],networkTimeoutSeconds:10})},{matcher:({request:e,url:{pathname:t},sameOrigin:a})=>"1"===e.headers.get("RSC")&&"1"===e.headers.get("Next-Router-Prefetch")&&a&&!t.startsWith("/api/"),handler:new ee({cacheName:"pages-rsc-prefetch",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({request:e,url:{pathname:t},sameOrigin:a})=>"1"===e.headers.get("RSC")&&a&&!t.startsWith("/api/"),handler:new ee({cacheName:"pages-rsc",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({request:e,url:{pathname:t},sameOrigin:a})=>e.headers.get("Content-Type")?.includes("text/html")&&a&&!t.startsWith("/api/"),handler:new ee({cacheName:"pages",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({url:{pathname:e},sameOrigin:t})=>t&&!e.startsWith("/api/"),handler:new ee({cacheName:"others",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({sameOrigin:e})=>!e,handler:new ee({cacheName:"cross-origin",plugins:[new ef({maxEntries:32,maxAgeSeconds:3600})],networkTimeoutSeconds:10})},{matcher:/.*/i,method:"GET",handler:new et}];new eR({precacheEntries:[{'revision':null,'url':'/_next/static/chunks/1896-359ed2e68a8c4f1d.js'},{'revision':null,'url':'/_next/static/chunks/1958-56cbbb8dba15fd2f.js'},{'revision':null,'url':'/_next/static/chunks/2346-d63ba3de1d09a41e.js'},{'revision':null,'url':'/_next/static/chunks/4bd1b696-e356ca5ba0218e27.js'},{'revision':null,'url':'/_next/static/chunks/52774a7f.f2ab7a9b4b8ba576.js'},{'revision':null,'url':'/_next/static/chunks/5838-7e0aa455e9f24259.js'},{'revision':null,'url':'/_next/static/chunks/6810-65ea0987ee90a78b.js'},{'revision':null,'url':'/_next/static/chunks/7602.2868ff821d53ee09.js'},{'revision':null,'url':'/_next/static/chunks/7918-9cfe56e3ee27ed27.js'},{'revision':null,'url':'/_next/static/chunks/8500-f62a38ff68ab7f42.js'},{'revision':null,'url':'/_next/static/chunks/9da6db1e-9623f3245f088d02.js'},{'revision':null,'url':'/_next/static/chunks/app/_global-error/page-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/_not-found/page-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/account/page-f5e2a6d5e729cc87.js'},{'revision':null,'url':'/_next/static/chunks/app/admin/page-7653c5a94021e122.js'},{'revision':null,'url':'/_next/static/chunks/app/api/admin/stats/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/checkout/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/props/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/tonight/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/hero-prop/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/intelligence/feed/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/accuracy/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/mlb/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/nba/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/soccer/%5Bleague%5D/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/wnba/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/add-leg/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/grade/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/players/search/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/live/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/most-parlayed/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/top-graded/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/scan/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/parlays-graded/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/public/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/profile/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/recent-scans/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/scans/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/waitlist/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/webhook/nexapay/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/api/welcome-email/route-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/auth/callback/page-0cb8d3790d034de0.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/%5Bslug%5D/page-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/page-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/dashboard/page-be8c44c2d3ecd74d.js'},{'revision':null,'url':'/_next/static/chunks/app/forgot-password/page-a251f52b4206e8d1.js'},{'revision':null,'url':'/_next/static/chunks/app/game/%5Bid%5D/page-34d758f67cb52da7.js'},{'revision':null,'url':'/_next/static/chunks/app/intelligence/page-5f6c106fd6c53851.js'},{'revision':null,'url':'/_next/static/chunks/app/layout-c72e0130bc50baac.js'},{'revision':null,'url':'/_next/static/chunks/app/ledger/page-3bfc2406ebeb6d2e.js'},{'revision':null,'url':'/_next/static/chunks/app/login/page-69c1ebd6ff5c12d8.js'},{'revision':null,'url':'/_next/static/chunks/app/marketplace/page-cbada49ae96a7527.js'},{'revision':null,'url':'/_next/static/chunks/app/not-found-1fd99a98dab3c771.js'},{'revision':null,'url':'/_next/static/chunks/app/page-e854e880465d9c9e.js'},{'revision':null,'url':'/_next/static/chunks/app/pricing/page-3f26af475b3f8452.js'},{'revision':null,'url':'/_next/static/chunks/app/privacy/page-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/profile/page-44681f894156db65.js'},{'revision':null,'url':'/_next/static/chunks/app/responsible-gambling/page-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/scan/page-fc810e8b5e4f992b.js'},{'revision':null,'url':'/_next/static/chunks/app/settings/security/page-59df87aff0c62ec8.js'},{'revision':null,'url':'/_next/static/chunks/app/signup/page-33e502bb04569f60.js'},{'revision':null,'url':'/_next/static/chunks/app/soccer/page-9ba3b46b0b1dfa59.js'},{'revision':null,'url':'/_next/static/chunks/app/terms/page-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/app/tracker/page-d6937e1faa494c49.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/cancel/page-1fd99a98dab3c771.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/desk/page-0ed948b44f9c64d7.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/success/page-b6baded9f44ae951.js'},{'revision':null,'url':'/_next/static/chunks/app/verify/page-cdeec62ab3a5d8ff.js'},{'revision':null,'url':'/_next/static/chunks/app/welcome/page-e3ab6d5822dee6dc.js'},{'revision':null,'url':'/_next/static/chunks/framework-95da69ac6843d788.js'},{'revision':null,'url':'/_next/static/chunks/main-a354262253293123.js'},{'revision':null,'url':'/_next/static/chunks/main-app-4231d5f500f33972.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/app-error-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/forbidden-cdfd9ff3adbcee2e.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/global-error-756d787dba63aa4d.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/unauthorized-cdfd9ff3adbcee2e.js'},{'revision':'846118c33b2c0e922d7b3a7676f81f6f','url':'/_next/static/chunks/polyfills-42372ed130431b0a.js'},{'revision':null,'url':'/_next/static/chunks/webpack-a41d593db6ea66d4.js'},{'revision':null,'url':'/_next/static/css/f795112d016cc138.css'},{'revision':'2471bb8484e5d20d74f7e2e07e0b8f17','url':'/_next/static/qM5oQbx60U91cObpI9jnn/_buildManifest.js'},{'revision':'b6652df95db52feb4daf4eca35380933','url':'/_next/static/qM5oQbx60U91cObpI9jnn/_ssgManifest.js'},{'revision':'d7bc0f63f9618b8b700d028d7d242de8','url':'/apple-touch-icon.png'},{'revision':'5616f81ec5f8a9f726a17fb7ac66a54a','url':'/favicon-16.png'},{'revision':'1fc285cfb0116a0523eb34c779a7d282','url':'/favicon-32.png'},{'revision':'583b034f36839a8af92841771eef38b6','url':'/favicon.ico'},{'revision':'b15795128b3691e5703d0ce14ce10827','url':'/favicon.png'},{'revision':'44e9d71551be13574ac2e10063d03aa9','url':'/favicon.svg'},{'revision':'252b8f8c4d0f64c7cd120f182a6c74ab','url':'/icon-192.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icon-512.png'},{'revision':'252b8f8c4d0f64c7cd120f182a6c74ab','url':'/icons/icon-192.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icons/icon-512.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icons/icon-maskable-512.png'},{'revision':'bf670b1fafa1b3127bd50abe86d723b9','url':'/images/player-silhouette.svg'},{'revision':'27007d181514e7fe4213035736a8300e','url':'/manifest.json'},{'revision':'9f61cf51298661d5c57a782534216240','url':'/og-image.png'},{'revision':'7c759c20b35840eacf9344692cb51061','url':'/og-image.svg'},{'revision':'9327802333275f11e68c3f19f20c160d','url':'/widget.js'}],skipWaiting:!0,clientsClaim:!0,navigationPreload:!0,runtimeCaching:eq}).addEventListeners(),self.addEventListener("push",e=>{let t;if(!e.data)return;try{t=e.data.json()}catch{t={title:"VYNDR",body:e.data.text()}}let{title:a="VYNDR",body:s="",icon:r="/icons/icon-192.png",url:n="/"}=t;e.waitUntil(self.registration.showNotification(a,{body:s,icon:r,badge:"/icons/icon-192.png",data:{url:n}}))}),self.addEventListener("notificationclick",e=>{e.notification.close();let t=e.notification.data?.url??"/";e.waitUntil(self.clients.matchAll({type:"window",includeUncontrolled:!0}).then(e=>{let a=e.find(e=>e.url.endsWith(t));return a?a.focus():self.clients.openWindow(t)}))})})(); \ No newline at end of file +This is generally NOT safe. Learn more at https://bit.ly/wb-precache`)}handleInstall(e){return this.registerRequestRules(e),y(e,async()=>{let t=new eo;this.precacheStrategy.plugins.push(t),await el(this._concurrentPrecaching,Array.from(this._urlsToCacheKeys.entries()),async([t,a])=>{let s=this._cacheKeysToIntegrities.get(a),r=this._urlsToCacheModes.get(t),n=new Request(t,{integrity:s,cache:r,credentials:"same-origin"});await Promise.all(this.precacheStrategy.handleAll({event:e,request:n,url:new URL(n.url),params:{cacheKey:a}}))});let{updatedURLs:a,notUpdatedURLs:s}=t;return{updatedURLs:a,notUpdatedURLs:s}})}async registerRequestRules(e){if(this._requestRules&&e?.addRoutes)try{await e.addRoutes(this._requestRules),this._requestRules=void 0}catch(e){throw e}}handleActivate(e){return y(e,async()=>{let e=await self.caches.open(this.precacheStrategy.cacheName),t=await e.keys(),a=new Set(this._urlsToCacheKeys.values()),s=[];for(let r of t)a.has(r.url)||(await e.delete(r),s.push(r.url));return{deletedCacheRequests:s}})}handleFetch(e){let{request:t}=e,a=this.handleRequest({request:t,event:e});a&&e.respondWith(a)}handleCache(e){if(e.data&&"CACHE_URLS"===e.data.type){let{payload:t}=e.data,a=Promise.all(t.urlsToCache.map(t=>{let a;return a="string"==typeof t?new Request(t):new Request(...t),this.handleRequest({request:a,event:e})}));e.waitUntil(a),e.ports?.[0]&&a.then(()=>e.ports[0].postMessage(!0))}}setDefaultHandler(e,t="GET"){this._defaultHandlerMap.set(t,ea(e))}setCatchHandler(e){this._catchHandler=ea(e)}registerCapture(e,t,a){let s=((e,t,a)=>{if("string"==typeof e){let s=new URL(e,location.href);return new es(({url:e})=>e.href===s.href,t,a)}if(e instanceof RegExp)return new ei(e,t,a);if("function"==typeof e)return new es(e,t,a);if(e instanceof es)return e;throw new l("unsupported-route-type",{moduleName:"serwist",funcName:"parseRoute",paramName:"capture"})})(e,t,a);return this.registerRoute(s),s}registerRoute(e){this._routes.has(e.method)||this._routes.set(e.method,[]),this._routes.get(e.method).push(e)}unregisterRoute(e){if(!this._routes.has(e.method))throw new l("unregister-route-but-not-found-with-method",{method:e.method});let t=this._routes.get(e.method).indexOf(e);if(t>-1)this._routes.get(e.method).splice(t,1);else throw new l("unregister-route-route-not-registered")}getUrlsToPrecacheKeys(){return this._urlsToCacheKeys}getPrecachedUrls(){return[...this._urlsToCacheKeys.keys()]}getPrecacheKeyForUrl(e){let t=new URL(e,location.href);return this._urlsToCacheKeys.get(t.href)}getIntegrityForPrecacheKey(e){return this._cacheKeysToIntegrities.get(e)}async matchPrecache(e){let t=e instanceof Request?e.url:e,a=this.getPrecacheKeyForUrl(t);if(a)return(await self.caches.open(this.precacheStrategy.cacheName)).match(a)}createHandlerBoundToUrl(e){let t=this.getPrecacheKeyForUrl(e);if(!t)throw new l("non-precached-url",{url:e});return a=>(a.request=new Request(e),a.params={cacheKey:t,...a.params},this.precacheStrategy.handle(a))}handleRequest({request:e,event:t}){let a,s=new URL(e.url,location.href);if(!s.protocol.startsWith("http"))return;let r=s.origin===location.origin,{params:n,route:i}=this.findMatchingRoute({event:t,request:e,sameOrigin:r,url:s}),c=i?.handler,o=e.method;if(!c&&this._defaultHandlerMap.has(o)&&(c=this._defaultHandlerMap.get(o)),!c)return;try{a=c.handle({url:s,request:e,event:t,params:n})}catch(e){a=Promise.reject(e)}let l=i?.catchHandler;return a instanceof Promise&&(this._catchHandler||l)&&(a=a.catch(async a=>{if(l)try{return await l.handle({url:s,request:e,event:t,params:n})}catch(e){e instanceof Error&&(a=e)}if(this._catchHandler)return this._catchHandler.handle({url:s,request:e,event:t});throw a})),a}findMatchingRoute({url:e,sameOrigin:t,request:a,event:s}){for(let r of this._routes.get(a.method)||[]){let n,i=r.match({url:e,sameOrigin:t,request:a,event:s});if(i)return Array.isArray(n=i)&&0===n.length||i.constructor===Object&&0===Object.keys(i).length?n=void 0:"boolean"==typeof i&&(n=void 0),{route:r,params:n}}return{}}};let eq=[{matcher:/^https:\/\/fonts\.(?:gstatic)\.com\/.*/i,handler:new ex({cacheName:"google-fonts-webfonts",plugins:[new ef({maxEntries:4,maxAgeSeconds:31536e3,maxAgeFrom:"last-used"})]})},{matcher:/^https:\/\/fonts\.(?:googleapis)\.com\/.*/i,handler:new eb({cacheName:"google-fonts-stylesheets",plugins:[new ef({maxEntries:4,maxAgeSeconds:604800,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:eot|otf|ttc|ttf|woff|woff2|font.css)$/i,handler:new eb({cacheName:"static-font-assets",plugins:[new ef({maxEntries:4,maxAgeSeconds:604800,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:jpg|jpeg|gif|png|svg|ico|webp)$/i,handler:new eb({cacheName:"static-image-assets",plugins:[new ef({maxEntries:64,maxAgeSeconds:2592e3,maxAgeFrom:"last-used"})]})},{matcher:/\/_next\/static.+\.js$/i,handler:new ex({cacheName:"next-static-js-assets",plugins:[new ef({maxEntries:64,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\/_next\/image\?url=.+$/i,handler:new eb({cacheName:"next-image",plugins:[new ef({maxEntries:64,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:mp3|wav|ogg)$/i,handler:new ex({cacheName:"static-audio-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"}),new e_]})},{matcher:/\.(?:mp4|webm)$/i,handler:new ex({cacheName:"static-video-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"}),new e_]})},{matcher:/\.(?:js)$/i,handler:new eb({cacheName:"static-js-assets",plugins:[new ef({maxEntries:48,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:css|less)$/i,handler:new eb({cacheName:"static-style-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\/_next\/data\/.+\/.+\.json$/i,handler:new ee({cacheName:"next-data",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:json|xml|csv)$/i,handler:new ee({cacheName:"static-data-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\/api\/auth\/.*/,handler:new et({networkTimeoutSeconds:10})},{matcher:({sameOrigin:e,url:{pathname:t}})=>e&&t.startsWith("/api/"),method:"GET",handler:new ee({cacheName:"apis",plugins:[new ef({maxEntries:16,maxAgeSeconds:86400,maxAgeFrom:"last-used"})],networkTimeoutSeconds:10})},{matcher:({request:e,url:{pathname:t},sameOrigin:a})=>"1"===e.headers.get("RSC")&&"1"===e.headers.get("Next-Router-Prefetch")&&a&&!t.startsWith("/api/"),handler:new ee({cacheName:"pages-rsc-prefetch",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({request:e,url:{pathname:t},sameOrigin:a})=>"1"===e.headers.get("RSC")&&a&&!t.startsWith("/api/"),handler:new ee({cacheName:"pages-rsc",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({request:e,url:{pathname:t},sameOrigin:a})=>e.headers.get("Content-Type")?.includes("text/html")&&a&&!t.startsWith("/api/"),handler:new ee({cacheName:"pages",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({url:{pathname:e},sameOrigin:t})=>t&&!e.startsWith("/api/"),handler:new ee({cacheName:"others",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({sameOrigin:e})=>!e,handler:new ee({cacheName:"cross-origin",plugins:[new ef({maxEntries:32,maxAgeSeconds:3600})],networkTimeoutSeconds:10})},{matcher:/.*/i,method:"GET",handler:new et}];new eR({precacheEntries:[{'revision':'4c6932759b995e8c636743c0cf430758','url':'/_next/static/NzfK1dpsplsPsINYVULPM/_buildManifest.js'},{'revision':'b6652df95db52feb4daf4eca35380933','url':'/_next/static/NzfK1dpsplsPsINYVULPM/_ssgManifest.js'},{'revision':null,'url':'/_next/static/chunks/1896-359ed2e68a8c4f1d.js'},{'revision':null,'url':'/_next/static/chunks/1958-56cbbb8dba15fd2f.js'},{'revision':null,'url':'/_next/static/chunks/2346-d63ba3de1d09a41e.js'},{'revision':null,'url':'/_next/static/chunks/4bd1b696-e356ca5ba0218e27.js'},{'revision':null,'url':'/_next/static/chunks/52774a7f.f2ab7a9b4b8ba576.js'},{'revision':null,'url':'/_next/static/chunks/5838-7e0aa455e9f24259.js'},{'revision':null,'url':'/_next/static/chunks/6810-65ea0987ee90a78b.js'},{'revision':null,'url':'/_next/static/chunks/7602.2868ff821d53ee09.js'},{'revision':null,'url':'/_next/static/chunks/7918-9cfe56e3ee27ed27.js'},{'revision':null,'url':'/_next/static/chunks/8500-f62a38ff68ab7f42.js'},{'revision':null,'url':'/_next/static/chunks/9da6db1e-9623f3245f088d02.js'},{'revision':null,'url':'/_next/static/chunks/app/_global-error/page-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/_not-found/page-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/account/page-f5e2a6d5e729cc87.js'},{'revision':null,'url':'/_next/static/chunks/app/admin/page-7653c5a94021e122.js'},{'revision':null,'url':'/_next/static/chunks/app/api/admin/stats/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/checkout/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/gamelines/%5Bsport%5D/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/props/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/tonight/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/hero-prop/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/hotlist/%5Bsport%5D/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/intelligence/feed/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/accuracy/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/mlb/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/nba/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/soccer/%5Bleague%5D/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/wnba/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/add-leg/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/grade/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/players/search/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/live/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/most-parlayed/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/top-graded/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/scan/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/schedule/%5Bsport%5D/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/parlays-graded/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/public/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/streaks/%5Bsport%5D/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/profile/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/recent-scans/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/scans/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/waitlist/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/webhook/nexapay/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/api/welcome-email/route-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/auth/callback/page-0cb8d3790d034de0.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/%5Bslug%5D/page-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/page-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/dashboard/page-199b7863ae37f32d.js'},{'revision':null,'url':'/_next/static/chunks/app/forgot-password/page-a251f52b4206e8d1.js'},{'revision':null,'url':'/_next/static/chunks/app/game/%5Bid%5D/page-34d758f67cb52da7.js'},{'revision':null,'url':'/_next/static/chunks/app/intelligence/page-5f6c106fd6c53851.js'},{'revision':null,'url':'/_next/static/chunks/app/layout-c72e0130bc50baac.js'},{'revision':null,'url':'/_next/static/chunks/app/ledger/page-3bfc2406ebeb6d2e.js'},{'revision':null,'url':'/_next/static/chunks/app/login/page-69c1ebd6ff5c12d8.js'},{'revision':null,'url':'/_next/static/chunks/app/marketplace/page-cbada49ae96a7527.js'},{'revision':null,'url':'/_next/static/chunks/app/not-found-1fd99a98dab3c771.js'},{'revision':null,'url':'/_next/static/chunks/app/page-70c10ec17b5cf43c.js'},{'revision':null,'url':'/_next/static/chunks/app/pricing/page-3f26af475b3f8452.js'},{'revision':null,'url':'/_next/static/chunks/app/privacy/page-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/profile/page-44681f894156db65.js'},{'revision':null,'url':'/_next/static/chunks/app/responsible-gambling/page-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/scan/page-fc810e8b5e4f992b.js'},{'revision':null,'url':'/_next/static/chunks/app/settings/security/page-59df87aff0c62ec8.js'},{'revision':null,'url':'/_next/static/chunks/app/signup/page-33e502bb04569f60.js'},{'revision':null,'url':'/_next/static/chunks/app/soccer/page-9ba3b46b0b1dfa59.js'},{'revision':null,'url':'/_next/static/chunks/app/terms/page-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/app/tracker/page-d6937e1faa494c49.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/cancel/page-1fd99a98dab3c771.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/desk/page-0ed948b44f9c64d7.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/success/page-b6baded9f44ae951.js'},{'revision':null,'url':'/_next/static/chunks/app/verify/page-cdeec62ab3a5d8ff.js'},{'revision':null,'url':'/_next/static/chunks/app/welcome/page-e3ab6d5822dee6dc.js'},{'revision':null,'url':'/_next/static/chunks/framework-95da69ac6843d788.js'},{'revision':null,'url':'/_next/static/chunks/main-a354262253293123.js'},{'revision':null,'url':'/_next/static/chunks/main-app-4231d5f500f33972.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/app-error-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/forbidden-c81f75b48fa88863.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/global-error-756d787dba63aa4d.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/unauthorized-c81f75b48fa88863.js'},{'revision':'846118c33b2c0e922d7b3a7676f81f6f','url':'/_next/static/chunks/polyfills-42372ed130431b0a.js'},{'revision':null,'url':'/_next/static/chunks/webpack-a41d593db6ea66d4.js'},{'revision':null,'url':'/_next/static/css/f795112d016cc138.css'},{'revision':'d7bc0f63f9618b8b700d028d7d242de8','url':'/apple-touch-icon.png'},{'revision':'5616f81ec5f8a9f726a17fb7ac66a54a','url':'/favicon-16.png'},{'revision':'1fc285cfb0116a0523eb34c779a7d282','url':'/favicon-32.png'},{'revision':'583b034f36839a8af92841771eef38b6','url':'/favicon.ico'},{'revision':'b15795128b3691e5703d0ce14ce10827','url':'/favicon.png'},{'revision':'44e9d71551be13574ac2e10063d03aa9','url':'/favicon.svg'},{'revision':'252b8f8c4d0f64c7cd120f182a6c74ab','url':'/icon-192.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icon-512.png'},{'revision':'252b8f8c4d0f64c7cd120f182a6c74ab','url':'/icons/icon-192.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icons/icon-512.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icons/icon-maskable-512.png'},{'revision':'bf670b1fafa1b3127bd50abe86d723b9','url':'/images/player-silhouette.svg'},{'revision':'27007d181514e7fe4213035736a8300e','url':'/manifest.json'},{'revision':'9f61cf51298661d5c57a782534216240','url':'/og-image.png'},{'revision':'7c759c20b35840eacf9344692cb51061','url':'/og-image.svg'},{'revision':'9327802333275f11e68c3f19f20c160d','url':'/widget.js'}],skipWaiting:!0,clientsClaim:!0,navigationPreload:!0,runtimeCaching:eq}).addEventListeners(),self.addEventListener("push",e=>{let t;if(!e.data)return;try{t=e.data.json()}catch{t={title:"VYNDR",body:e.data.text()}}let{title:a="VYNDR",body:s="",icon:r="/icons/icon-192.png",url:n="/"}=t;e.waitUntil(self.registration.showNotification(a,{body:s,icon:r,badge:"/icons/icon-192.png",data:{url:n}}))}),self.addEventListener("notificationclick",e=>{e.notification.close();let t=e.notification.data?.url??"/";e.waitUntil(self.clients.matchAll({type:"window",includeUncontrolled:!0}).then(e=>{let a=e.find(e=>e.url.endsWith(t));return a?a.focus():self.clients.openWindow(t)}))})})(); \ No newline at end of file diff --git a/web/src/app/api/gamelines/[sport]/route.ts b/web/src/app/api/gamelines/[sport]/route.ts new file mode 100644 index 0000000..3c7deec --- /dev/null +++ b/web/src/app/api/gamelines/[sport]/route.ts @@ -0,0 +1,27 @@ +import { NextRequest, NextResponse } from 'next/server'; + +export const dynamic = 'force-dynamic'; + +const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000'; + +/** + * Game-lines proxy (Session 25). Thin forwarder to Express + * `/api/gamelines/:sport` (Tank01 book-by-book moneylines / spreads / + * totals). See the schedule proxy for why these were missing. + */ +export async function GET(req: NextRequest, { params }: { params: Promise<{ sport: string }> }) { + const { sport } = await params; + const sportLc = String(sport || '').toLowerCase(); + const qs = req.nextUrl.search; + try { + const upstream = await fetch(`${BACKEND_URL}/api/gamelines/${encodeURIComponent(sportLc)}${qs}`, { + method: 'GET', + headers: { Accept: 'application/json' }, + }); + const data = await upstream.json().catch(() => ({})); + if (!upstream.ok) return NextResponse.json(data, { status: upstream.status }); + return NextResponse.json(data); + } catch { + return NextResponse.json({ sport: sportLc, games: {}, source: 'tank01' }); + } +} diff --git a/web/src/app/api/hotlist/[sport]/route.ts b/web/src/app/api/hotlist/[sport]/route.ts new file mode 100644 index 0000000..b334f9b --- /dev/null +++ b/web/src/app/api/hotlist/[sport]/route.ts @@ -0,0 +1,27 @@ +import { NextRequest, NextResponse } from 'next/server'; + +export const dynamic = 'force-dynamic'; + +const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000'; + +/** + * Hot-list proxy (Session 25). Forwards to Express `/api/hotlist/:sport`, + * preserving the `?stat=` filter. Computed from cached game logs — no + * odds-api credits. See the schedule proxy for why these were missing. + */ +export async function GET(req: NextRequest, { params }: { params: Promise<{ sport: string }> }) { + const { sport } = await params; + const sportLc = String(sport || '').toLowerCase(); + const qs = req.nextUrl.search; + try { + const upstream = await fetch(`${BACKEND_URL}/api/hotlist/${encodeURIComponent(sportLc)}${qs}`, { + method: 'GET', + headers: { Accept: 'application/json' }, + }); + const data = await upstream.json().catch(() => ({})); + if (!upstream.ok) return NextResponse.json(data, { status: upstream.status }); + return NextResponse.json(data); + } catch { + return NextResponse.json({ sport: sportLc, players: [], source: 'computed' }); + } +} diff --git a/web/src/app/api/schedule/[sport]/route.ts b/web/src/app/api/schedule/[sport]/route.ts new file mode 100644 index 0000000..f0423c5 --- /dev/null +++ b/web/src/app/api/schedule/[sport]/route.ts @@ -0,0 +1,34 @@ +import { NextRequest, NextResponse } from 'next/server'; + +export const dynamic = 'force-dynamic'; + +const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000'; + +/** + * Schedule proxy (Session 25). + * + * The all-day intelligence endpoints (schedule / gamelines / streaks / + * hotlist) were built on the Express backend in Sessions 23-24 but had + * NO Next.js proxy route — so the browser's `fetch('/api/schedule/mlb')` + * 404'd on the Next origin and the slate showed zero games even though + * the backend was serving 8+. This thin forwarder fixes that, mirroring + * the existing `/api/odds/*` proxies. + */ +export async function GET(req: NextRequest, { params }: { params: Promise<{ sport: string }> }) { + const { sport } = await params; + const sportLc = String(sport || '').toLowerCase(); + const qs = req.nextUrl.search; + try { + const upstream = await fetch(`${BACKEND_URL}/api/schedule/${encodeURIComponent(sportLc)}${qs}`, { + method: 'GET', + headers: { Accept: 'application/json' }, + }); + const data = await upstream.json().catch(() => ({})); + if (!upstream.ok) return NextResponse.json(data, { status: upstream.status }); + return NextResponse.json(data); + } catch { + // Schedule is the foundation layer — never blow up the page. Return an + // empty-but-valid slate so the UI degrades to "no games" gracefully. + return NextResponse.json({ sport: sportLc, games: [], source: 'espn' }); + } +} diff --git a/web/src/app/api/streaks/[sport]/route.ts b/web/src/app/api/streaks/[sport]/route.ts new file mode 100644 index 0000000..f841522 --- /dev/null +++ b/web/src/app/api/streaks/[sport]/route.ts @@ -0,0 +1,27 @@ +import { NextRequest, NextResponse } from 'next/server'; + +export const dynamic = 'force-dynamic'; + +const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000'; + +/** + * Streaks proxy (Session 25). Forwards to Express `/api/streaks/:sport`, + * preserving the `?stat=` filter. Computed from cached game logs — no + * odds-api credits. See the schedule proxy for why these were missing. + */ +export async function GET(req: NextRequest, { params }: { params: Promise<{ sport: string }> }) { + const { sport } = await params; + const sportLc = String(sport || '').toLowerCase(); + const qs = req.nextUrl.search; + try { + const upstream = await fetch(`${BACKEND_URL}/api/streaks/${encodeURIComponent(sportLc)}${qs}`, { + method: 'GET', + headers: { Accept: 'application/json' }, + }); + const data = await upstream.json().catch(() => ({})); + if (!upstream.ok) return NextResponse.json(data, { status: upstream.status }); + return NextResponse.json(data); + } catch { + return NextResponse.json({ sport: sportLc, streaks: [], source: 'computed' }); + } +} diff --git a/web/src/components/GameCard.tsx b/web/src/components/GameCard.tsx index 7c40d65..caa5d82 100644 --- a/web/src/components/GameCard.tsx +++ b/web/src/components/GameCard.tsx @@ -52,6 +52,14 @@ export interface GameLines { export type GameStatus = 'pre' | 'in' | 'post'; +// Session 25 — a computed streak for a player whose team is in this game. +export interface GameStreak { + player: string; + team?: string | null; + description: string; + currentStreak: number; +} + export interface GameCardProps { sport: SlateSport; homeTeam: string; @@ -73,6 +81,10 @@ export interface GameCardProps { status?: GameStatus; score?: { home: number; away: number } | null; gameLines?: GameLines | null; + // Session 25 — streaks for players in THIS game, matched by team in the + // Slate. Renders inline below the props/lines so the streak context + // lives with the game it belongs to. + streaks?: GameStreak[]; } // Map ESPN status → a compact, human badge. 'in' is live; 'post' is final. @@ -173,11 +185,12 @@ export default function GameCard(props: GameCardProps) { props: propList, gradedProps, loadingKey, errorByKey, tier = 'free', onGrade, onUpgrade, defaultVisible = 4, - status, score, gameLines, + status, score, gameLines, streaks, } = props; const [expanded, setExpanded] = useState(false); const badge = statusBadge(status, score); const bookRows = gameLines?.books ? Object.entries(gameLines.books) : []; + const streakRows = (streaks || []).filter((s) => s && s.player && s.description); // Session 19 — visibility budget now applies to PLAYERS, not raw // props. Showing the first 4 prop rows that all belonged to the @@ -406,6 +419,40 @@ export default function GameCard(props: GameCardProps) { )} )} + + {/* Session 25 — streaks for players in THIS game, inline. The Slate + matches streaks to games by team, so a card shows the streak + context for the players actually on the floor/field. Renders + only when there's at least one — no empty section. */} + {streakRows.length > 0 && ( +
+
+ 🔥 Streaks +
+ {streakRows.map((s) => ( +
+ + {s.player} + {s.team ? · {s.team} : null} + + {s.description} +
+ ))} +
+ )} ); } diff --git a/web/src/components/LiveHeroProp.tsx b/web/src/components/LiveHeroProp.tsx index 7683a63..3a6fb73 100644 --- a/web/src/components/LiveHeroProp.tsx +++ b/web/src/components/LiveHeroProp.tsx @@ -145,6 +145,20 @@ export default function LiveHeroProp() { marginInline: 'auto', }} > + {/* Session 25 — the static fallback is an ILLUSTRATIVE example, not + a live pick. Labelling it prevents the fixed stats from reading + as stale real data when no live hero-prop is flowing. */} + + Example +
{ + const t = (s.team || '').toUpperCase(); + return t && (t === h || t === a); + }) + .map((s) => ({ player: s.player, team: s.team, description: s.description, currentStreak: s.currentStreak })); +} + function mergeSlate( sport: SlateSport, scheduleGames: ScheduleGame[], oddsGames: SlateGame[], lines?: Record, + streaks?: StreakApiRow[], ): SlateGame[] { const base: SlateGame[] = scheduleGames.map((sg) => ({ sport, homeTeam: sg.homeTeam?.name || '', awayTeam: sg.awayTeam?.name || '', + homeAbbr: sg.homeTeam?.abbreviation || null, + awayAbbr: sg.awayTeam?.abbreviation || null, gameTime: sg.gameTime || undefined, venue: sg.venue || undefined, status: sg.status || undefined, score: sg.score || undefined, props: [], gameLines: findGameLines(sg.homeTeam, sg.awayTeam, lines), + streaks: streaksForGame(sg.homeTeam?.abbreviation, sg.awayTeam?.abbreviation, streaks), })); const unmatched: SlateGame[] = []; @@ -342,17 +374,18 @@ export default function Slate({ initialTab = 'all', tier = 'free' }: SlateProps) const perSport = await Promise.all( sportsToFetch.map(async (sport) => { const oddsUrls = FETCH_URLS[sport] as string[]; - const [oddsResults, schedule, lines] = await Promise.all([ + const [oddsResults, schedule, lines, streaksRes] = await Promise.all([ Promise.all(oddsUrls.map((u) => getJson(u))), SCHEDULE_SPORTS.has(sport) ? getJson(`/api/schedule/${sport}`) : Promise.resolve(null), SCHEDULE_SPORTS.has(sport) ? getJson(`/api/gamelines/${sport}`) : Promise.resolve(null), + SCHEDULE_SPORTS.has(sport) ? getJson(`/api/streaks/${sport}`) : Promise.resolve(null), ]); const oddsOk = oddsResults.some((o) => o !== null); const oddsProps = oddsResults.flatMap((o) => o?.props || []); const oddsGames = groupByGame(oddsProps, sport); const scheduleGames = schedule?.games || []; - const merged = mergeSlate(sport, scheduleGames, oddsGames, lines?.games); + const merged = mergeSlate(sport, scheduleGames, oddsGames, lines?.games, streaksRes?.streaks); return { sport, merged, oddsOk, hadSchedule: scheduleGames.length > 0 }; }), ); @@ -453,6 +486,20 @@ export default function Slate({ initialTab = 'all', tier = 'free' }: SlateProps) .filter((g): g is SlateGame => g !== null); }, [games, searchQuery]); + // Session 25 — per-sport game counts for the tab labels, derived from + // the MERGED list (schedule + odds), so a tab reads "MLB (8)" off the + // free ESPN schedule even when odds are empty. Counts only appear for + // sports currently loaded (the active tab fetches its own sports). + const countBySport = useMemo(() => { + const m: Partial> = {}; + for (const g of games) m[g.sport] = (m[g.sport] || 0) + 1; + return m; + }, [games]); + const tabCount = (id: SlateTab): number | null => { + if (id === 'all') return games.length || null; + return countBySport[id as SlateSport] ?? null; + }; + // Manual scan fallback URL — pre-fills /scan with the search query // so the user lands on a partially-filled form instead of empty. const manualScanHref = `/scan?q=${encodeURIComponent(searchQuery)}`; @@ -522,7 +569,7 @@ export default function Slate({ initialTab = 'all', tier = 'free' }: SlateProps) cursor: 'pointer', }} > - {t.label} + {t.label}{tabCount(t.id) != null ? ` (${tabCount(t.id)})` : ''} ); })} @@ -658,6 +705,7 @@ export default function Slate({ initialTab = 'all', tier = 'free' }: SlateProps) status={g.status} score={g.score} gameLines={g.gameLines} + streaks={g.streaks} gradedProps={gradedProps} loadingKey={gradingKey} errorByKey={errorByKey}