Session 23: All-day intelligence layer — schedule, game lines, streaks, hot lists, stat filtering, ParlayAPI dead (1567 tests)
This commit is contained in:
+12
@@ -138,6 +138,18 @@ app.use('/api/grading', express.json({ limit: '10mb' }), gradingRoutes);
|
||||
app.use('/api/grading', express.json({ limit: '256kb' }), correctionRoutes);
|
||||
const widgetRoutes = require('./routes/widget');
|
||||
app.use('/api/widget', widgetRoutes);
|
||||
// Session 23 — all-day intelligence layer. Free/cheap content surfaces
|
||||
// that keep the platform alive when odds-api is empty: schedule (ESPN),
|
||||
// game lines (Tank01), streaks + hot lists (cached game logs), and the
|
||||
// stat-filtered views over all of them.
|
||||
const scheduleRoutes = require('./routes/schedule');
|
||||
app.use('/api/schedule', scheduleRoutes);
|
||||
const gameLinesRoutes = require('./routes/gameLines');
|
||||
app.use('/api/gamelines', gameLinesRoutes);
|
||||
const streaksRoutes = require('./routes/streaks');
|
||||
app.use('/api/streaks', streaksRoutes);
|
||||
const hotListRoutes = require('./routes/hotlist');
|
||||
app.use('/api/hotlist', hotListRoutes);
|
||||
// Session 18 — internal ops endpoints (admin dashboard triggers,
|
||||
// shared-key auth via `VYNDR_INTERNAL_KEY`). Never reachable from
|
||||
// the public surface; the Next.js admin route proxies through with
|
||||
|
||||
+15
-1
@@ -61,9 +61,16 @@ const PROVIDERS = {
|
||||
// /historical/player_props → hit rate enrichment
|
||||
// /historical/closing_lines → CLV reference
|
||||
// Base URL: https://api.parlayapi.io/v1. Auth: X-Api-Key header.
|
||||
// Session 23 — DEAD. Chrome Claude confirmed on 2026-06-12 that
|
||||
// `api.parlayapi.io` no longer resolves (domain unreachable). We keep
|
||||
// the entry so the adapter code + its (network-mocked) tests still
|
||||
// resolve a config, but `status: 'dead'` removes it from every
|
||||
// fallback chain and the configured-providers list, so the gateway
|
||||
// never routes a live call to a host that doesn't exist.
|
||||
'parlayapi': {
|
||||
name: 'ParlayAPI (historical)',
|
||||
envKey: 'PARLAYAPI_KEY',
|
||||
status: 'dead',
|
||||
quotaType: 'monthly',
|
||||
quotaLimit: 1000,
|
||||
resetDay: 1,
|
||||
@@ -131,10 +138,15 @@ function listProviderIds() {
|
||||
*/
|
||||
function getConfiguredProviders() {
|
||||
return Object.entries(PROVIDERS)
|
||||
.filter(([, cfg]) => !!process.env[cfg.envKey])
|
||||
.filter(([, cfg]) => !!process.env[cfg.envKey] && cfg.status !== 'dead')
|
||||
.map(([id, cfg]) => ({ id, ...cfg }));
|
||||
}
|
||||
|
||||
/** True when a provider is retired (e.g. its host no longer resolves). */
|
||||
function isDeadProvider(providerId) {
|
||||
return PROVIDERS[providerId]?.status === 'dead';
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback chain for a capability + sport, in priority order,
|
||||
* excluding `excludeId`. Used by the gateway to walk down to the
|
||||
@@ -144,6 +156,7 @@ function getFallbackChain(capability, sport, excludeId) {
|
||||
return Object.entries(PROVIDERS)
|
||||
.filter(([id, cfg]) =>
|
||||
id !== excludeId &&
|
||||
cfg.status !== 'dead' && // Session 23 — skip retired providers
|
||||
cfg.capabilities.includes(capability) &&
|
||||
(!sport || cfg.sports.includes(sport)) &&
|
||||
!!process.env[cfg.envKey],
|
||||
@@ -159,4 +172,5 @@ module.exports = {
|
||||
listProviderIds,
|
||||
getConfiguredProviders,
|
||||
getFallbackChain,
|
||||
isDeadProvider,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Stat-filter categories per sport (Session 23).
|
||||
*
|
||||
* The stat filter is VYNDR's navigation system — users browse by what
|
||||
* they care about ("show me everyone on a 3-point streak"), not by sport
|
||||
* alone. These categories drive:
|
||||
* - the StatFilterPills UI
|
||||
* - the `?stat=` param on /api/streaks and /api/hotlist
|
||||
*
|
||||
* Category strings here MUST match the `category` field the streaks &
|
||||
* hot-list engines emit, or the filter silently returns nothing. Mirror
|
||||
* any change in `web/src/config/statFilters.ts`.
|
||||
*/
|
||||
|
||||
const STAT_FILTERS = Object.freeze({
|
||||
nba: ['all', 'points', 'rebounds', 'assists', 'threes', 'blocks', 'steals', 'pra'],
|
||||
wnba: ['all', 'points', 'rebounds', 'assists', 'threes', 'blocks', 'steals'],
|
||||
mlb: ['all', 'hits', 'home_runs', 'stolen_bases', 'rbis', 'strikeouts', 'total_bases', 'on_base'],
|
||||
soccer: ['all', 'goals', 'assists', 'shots', 'tackles', 'saves'],
|
||||
nfl: ['all', 'passing_yards', 'rushing_yards', 'receiving_yards', 'touchdowns', 'interceptions'],
|
||||
});
|
||||
|
||||
function getStatFilters(sport) {
|
||||
return STAT_FILTERS[String(sport || '').toLowerCase()] || ['all'];
|
||||
}
|
||||
|
||||
/** Is `stat` a valid category for `sport`? 'all' is always valid. */
|
||||
function isValidStat(sport, stat) {
|
||||
if (!stat || stat === 'all') return true;
|
||||
return getStatFilters(sport).includes(String(stat).toLowerCase());
|
||||
}
|
||||
|
||||
module.exports = { STAT_FILTERS, getStatFilters, isValidStat };
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* /api/gamelines/:sport (Session 23)
|
||||
*
|
||||
* Today's game-level betting odds from Tank01 — book-by-book moneylines,
|
||||
* run/point spreads, and totals. Separate budget from odds-api player
|
||||
* props: this uses the RAPID_API_KEY quota via the Tank01 adapters.
|
||||
*
|
||||
* Chrome Claude confirmed (2026-06-12) Tank01 MLB serves LIVE lines from
|
||||
* bet365 / betmgm / caesars. NBA carries the same in-season — an empty
|
||||
* result off-season is correct, not an error.
|
||||
*
|
||||
* Response shape:
|
||||
* {
|
||||
* sport: 'mlb',
|
||||
* date: '2026-06-12',
|
||||
* games: {
|
||||
* '20260612_ARI@CIN': {
|
||||
* homeTeam: 'CIN', awayTeam: 'ARI',
|
||||
* books: {
|
||||
* bet365: { homeML, awayML, total, overOdds, underOdds,
|
||||
* homeSpread, awaySpread },
|
||||
* betmgm: { ... },
|
||||
* },
|
||||
* },
|
||||
* },
|
||||
* source: 'tank01',
|
||||
* }
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const nbaAdapter = require('../services/adapters/tank01NbaAdapter');
|
||||
const mlbAdapter = require('../services/adapters/tank01MlbAdapter');
|
||||
const scheduleService = require('../services/scheduleService');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const MISSION_HEADER = { 'X-VYNDR-Mission': 'Lines keep the slate alive' };
|
||||
|
||||
// Sports that have a Tank01 game-lines feed wired up.
|
||||
const FETCHERS = {
|
||||
nba: (date) => nbaAdapter.getNBABettingOdds(date),
|
||||
mlb: (date) => mlbAdapter.getMLBBettingOdds(date),
|
||||
};
|
||||
|
||||
const HAS_KEY = {
|
||||
nba: () => nbaAdapter.hasApiKey(),
|
||||
mlb: () => mlbAdapter.hasApiKey(),
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse `YYYYMMDD_AWAY@HOME` → { awayTeam, homeTeam }. Tank01 keys every
|
||||
* game this way. Falls back to nulls on an unexpected key.
|
||||
*/
|
||||
function teamsFromGameId(gameId) {
|
||||
const m = String(gameId || '').match(/_([A-Za-z0-9]+)@([A-Za-z0-9]+)/);
|
||||
if (!m) return { awayTeam: null, homeTeam: null };
|
||||
return { awayTeam: m[1], homeTeam: m[2] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize one sportsbook's raw odds object into a flat, UI-ready row.
|
||||
* Tank01 field names are verbose and occasionally vary; pull defensively.
|
||||
*/
|
||||
function normalizeBook(odds) {
|
||||
if (!odds || typeof odds !== 'object') return null;
|
||||
const pick = (...keys) => {
|
||||
for (const k of keys) {
|
||||
if (odds[k] !== undefined && odds[k] !== null && odds[k] !== '') return odds[k];
|
||||
}
|
||||
return null;
|
||||
};
|
||||
return {
|
||||
homeML: pick('homeTeamMLOdds', 'homeML', 'moneyLineHome'),
|
||||
awayML: pick('awayTeamMLOdds', 'awayML', 'moneyLineAway'),
|
||||
total: pick('totalOver', 'total', 'overUnder'),
|
||||
overOdds: pick('totalOverOdds', 'overOdds'),
|
||||
underOdds: pick('totalUnderOdds', 'underOdds'),
|
||||
homeSpread: pick('homeTeamSpread', 'homeSpread'),
|
||||
awaySpread: pick('awayTeamSpread', 'awaySpread'),
|
||||
homeSpreadOdds: pick('homeTeamSpreadOdds'),
|
||||
awaySpreadOdds: pick('awayTeamSpreadOdds'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the Tank01 betting-odds body (a map keyed by gameID) into the
|
||||
* route's `games` shape. Defensive against both the documented map form
|
||||
* and a bare array of game objects.
|
||||
*/
|
||||
function normalizeGameLines(body) {
|
||||
const games = {};
|
||||
if (!body || typeof body !== 'object') return games;
|
||||
|
||||
const entries = Array.isArray(body)
|
||||
? body.map((g) => [g.gameID || g.gameId, g])
|
||||
: Object.entries(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,
|
||||
};
|
||||
}
|
||||
return games;
|
||||
}
|
||||
|
||||
router.get('/:sport', async (req, res) => {
|
||||
const sport = String(req.params.sport || '').toLowerCase();
|
||||
const date = req.query.date || scheduleService.todayET();
|
||||
|
||||
const fetcher = FETCHERS[sport];
|
||||
if (!fetcher) {
|
||||
return res.status(404).set(MISSION_HEADER).json({ error: `No game lines for sport: ${sport}` });
|
||||
}
|
||||
|
||||
// Missing RAPID_API_KEY → graceful empty, never a crash.
|
||||
if (HAS_KEY[sport] && !HAS_KEY[sport]()) {
|
||||
return res.set(MISSION_HEADER).json({ sport, date, games: {}, source: 'tank01', configured: false });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await fetcher(date);
|
||||
const games = normalizeGameLines(body);
|
||||
return res.set(MISSION_HEADER).json({ sport, date, games, source: 'tank01' });
|
||||
} catch (err) {
|
||||
console.error(`[gamelines/${sport}]`, err.message);
|
||||
return res.set(MISSION_HEADER).json({ sport, date, games: {}, source: 'tank01' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports.__internals = { teamsFromGameId, normalizeBook, normalizeGameLines };
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* /api/hotlist/:sport (Session 23)
|
||||
*
|
||||
* Rolling recent-window leaders, ranked by how far ABOVE baseline each
|
||||
* player is trending. NO API calls — reads warm cached game logs and runs
|
||||
* the pure hot-list engine. Supports `?stat=points` and `?limit=N`.
|
||||
*
|
||||
* Response: { sport, stat, players: [...], source: 'computed' }
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const hotListService = require('../services/hotListService');
|
||||
const { loadRosterLogs } = require('../services/rosterLogs');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const MISSION_HEADER = { 'X-VYNDR-Mission': 'Hot right now' };
|
||||
|
||||
const SUPPORTED = new Set(['nba', 'wnba', 'mlb', 'soccer']);
|
||||
|
||||
router.get('/:sport', async (req, res) => {
|
||||
const sport = String(req.params.sport || '').toLowerCase();
|
||||
if (!SUPPORTED.has(sport)) {
|
||||
return res.status(404).set(MISSION_HEADER).json({ error: `No hot list for sport: ${sport}` });
|
||||
}
|
||||
const stat = req.query.stat ? String(req.query.stat).toLowerCase() : 'all';
|
||||
const limit = req.query.limit ? Math.max(0, parseInt(req.query.limit, 10) || 0) : 0;
|
||||
|
||||
try {
|
||||
const roster = await loadRosterLogs(sport);
|
||||
const players = hotListService.computeHotList(roster, sport, { stat, limit });
|
||||
return res.set(MISSION_HEADER).json({ sport, stat, players, source: 'computed' });
|
||||
} catch (err) {
|
||||
console.error(`[hotlist/${sport}]`, err.message);
|
||||
return res.set(MISSION_HEADER).json({ sport, stat, players: [], source: 'computed' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* /api/schedule/:sport (Session 23)
|
||||
*
|
||||
* Returns today's game schedule from cached/free ESPN data. NO odds-api
|
||||
* credits burned. The PM2 pollers warm this cache every 60s; on a miss
|
||||
* the schedule service self-heals by fetching the free ESPN scoreboard.
|
||||
*
|
||||
* Each game carries two boolean flags read from OTHER caches (no fetch):
|
||||
* hasOdds — odds-api player props exist for this slate
|
||||
* hasGameLines — Tank01 game-level lines exist for this slate
|
||||
*
|
||||
* Response shape:
|
||||
* {
|
||||
* sport: 'nba',
|
||||
* date: '2026-06-12',
|
||||
* games: [ { id, homeTeam, awayTeam, gameTime, status, score,
|
||||
* venue, broadcast, hasOdds, hasGameLines } ],
|
||||
* source: 'espn',
|
||||
* }
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const scheduleService = require('../services/scheduleService');
|
||||
const { SPORT_CONFIG } = require('../config/sports');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const MISSION_HEADER = { 'X-VYNDR-Mission': 'The slate is never empty' };
|
||||
|
||||
router.get('/:sport', async (req, res) => {
|
||||
const sport = String(req.params.sport || '').toLowerCase();
|
||||
const date = req.query.date || scheduleService.todayET();
|
||||
|
||||
if (!SPORT_CONFIG[sport]) {
|
||||
return res.status(404).set(MISSION_HEADER).json({ error: `Unknown sport: ${sport}` });
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = await scheduleService.getSchedule(sport, date);
|
||||
// null → unsupported sport (already guarded above); treat defensively.
|
||||
const games = await scheduleService.enrichFlags(sport, date, raw || []);
|
||||
return res.set(MISSION_HEADER).json({
|
||||
sport,
|
||||
date,
|
||||
games,
|
||||
source: 'espn',
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(`[schedule/${sport}]`, err.message);
|
||||
// Even on error we return an empty slate, not a 5xx — the platform
|
||||
// is NEVER down. Other layers (game lines, props) keep it alive.
|
||||
return res.set(MISSION_HEADER).json({ sport, date, games: [], source: 'espn' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,10 +1,19 @@
|
||||
const express = require('express');
|
||||
const { getSupabaseServiceClient } = require('../utils/supabase');
|
||||
const { getStatFilters } = require('../config/statFilters');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const MISSION_HEADER = { 'X-VYNDR-Mission': 'Kill bad satisfieds before they satisfieds you' };
|
||||
|
||||
// GET /filters/:sport — stat-filter categories for the StatFilterPills UI
|
||||
// (Session 23). Lets the frontend stay data-driven without re-declaring
|
||||
// the category list. NO auth / NO DB — pure config.
|
||||
router.get('/filters/:sport', (req, res) => {
|
||||
const sport = String(req.params.sport || '').toLowerCase();
|
||||
res.set(MISSION_HEADER).json({ sport, filters: getStatFilters(sport) });
|
||||
});
|
||||
|
||||
// GET /parlays-graded — total scan count
|
||||
router.get('/parlays-graded', async (req, res) => {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* /api/streaks/:sport (Session 23)
|
||||
*
|
||||
* Computed player streaks from cached game logs. NO API calls — reads
|
||||
* warm Redis logs and runs the pure streaks engine over them. Supports
|
||||
* `?stat=points` to narrow to one category, and `?limit=N`.
|
||||
*
|
||||
* Response: { sport, stat, streaks: [...], source: 'computed' }
|
||||
*
|
||||
* An empty `streaks` array is a valid, non-error state — the platform
|
||||
* leans on the other layers (schedule, game lines, props) when no logs
|
||||
* are warm yet.
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const streaksService = require('../services/streaksService');
|
||||
const { loadRosterLogs } = require('../services/rosterLogs');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const MISSION_HEADER = { 'X-VYNDR-Mission': 'Streaks are the heartbeat' };
|
||||
|
||||
const SUPPORTED = new Set(['nba', 'wnba', 'mlb', 'nfl', 'soccer']);
|
||||
|
||||
router.get('/:sport', async (req, res) => {
|
||||
const sport = String(req.params.sport || '').toLowerCase();
|
||||
if (!SUPPORTED.has(sport)) {
|
||||
return res.status(404).set(MISSION_HEADER).json({ error: `No streaks for sport: ${sport}` });
|
||||
}
|
||||
const stat = req.query.stat ? String(req.query.stat).toLowerCase() : 'all';
|
||||
const limit = req.query.limit ? Math.max(0, parseInt(req.query.limit, 10) || 0) : 0;
|
||||
|
||||
try {
|
||||
const roster = await loadRosterLogs(sport);
|
||||
const streaks = streaksService.computeStreaks(roster, sport, { stat, limit });
|
||||
return res.set(MISSION_HEADER).json({ sport, stat, streaks, source: 'computed' });
|
||||
} catch (err) {
|
||||
console.error(`[streaks/${sport}]`, err.message);
|
||||
return res.set(MISSION_HEADER).json({ sport, stat, streaks: [], source: 'computed' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -28,6 +28,7 @@ const TTL = Object.freeze({
|
||||
boxScoreFinal: 24 * 3600,
|
||||
scoreboard: 1 * 3600,
|
||||
bvp: 24 * 3600, // BvP doesn't change mid-day — 24h cache is fine
|
||||
odds: 15 * 60, // Session 23 — book-by-book game lines, 15min
|
||||
});
|
||||
|
||||
function getHost() {
|
||||
@@ -178,10 +179,32 @@ async function getMLBDailyScoreboard(date) {
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* getMLBBettingOdds — Tank01's game-level odds feed (book-by-book).
|
||||
* Chrome Claude confirmed this serves LIVE moneylines, run lines, and
|
||||
* totals from bet365 / betmgm / caesars (Session 23). Separate from the
|
||||
* odds-api player-props pipeline; shares the RAPID_API_KEY quota.
|
||||
*
|
||||
* Returns the raw `body` (a map keyed by gameID, each carrying a
|
||||
* per-sportsbook odds object). The gameLines route normalizes it.
|
||||
*/
|
||||
async function getMLBBettingOdds(date) {
|
||||
if (!date) return null;
|
||||
const ymd = String(date).replace(/-/g, '');
|
||||
const data = await fetchWithCache(
|
||||
`/getMLBBettingOdds?gameDate=${ymd}`,
|
||||
`tank01:mlb:odds:${ymd}`,
|
||||
TTL.odds,
|
||||
);
|
||||
if (data === null) return null;
|
||||
return data?.body || data;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getMLBBoxScore,
|
||||
getMLBBatterVsPitcher,
|
||||
getMLBDailyScoreboard,
|
||||
getMLBBettingOdds,
|
||||
hasApiKey,
|
||||
__internals: {
|
||||
TTL,
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Hot lists (Session 23).
|
||||
*
|
||||
* Rolling recent-window leaders — but through VYNDR's lens. "Hot" does
|
||||
* NOT mean "highest raw number." It means performing ABOVE the player's
|
||||
* own baseline in the recent window. A 20-PPG player going 28/31/25 is
|
||||
* hot; a 30-PPG player who dropped 28 is not.
|
||||
*
|
||||
* Baseline preference:
|
||||
* 1. explicit `player.seasonAvg[stat]` if supplied
|
||||
* 2. else the player's own games OUTSIDE the recent window (recent vs rest)
|
||||
*
|
||||
* If neither baseline is available (a player with only window-length
|
||||
* history and no season avg) the player is excluded — we can't claim
|
||||
* "trending up" without something to trend against.
|
||||
*
|
||||
* Pure & deterministic. The route supplies cached logs; this does math.
|
||||
*/
|
||||
|
||||
const { __internals } = require('./streaksService');
|
||||
const { nba, mlb, soccer } = __internals;
|
||||
|
||||
// category → accessor fn, per sport. Mirrors STAT_FILTERS categories.
|
||||
const HOT_STATS = {
|
||||
nba: {
|
||||
points: nba.points, rebounds: nba.rebounds, assists: nba.assists,
|
||||
threes: nba.threes, blocks: nba.blocks, steals: nba.steals, pra: nba.pra,
|
||||
},
|
||||
wnba: {
|
||||
points: nba.points, rebounds: nba.rebounds, assists: nba.assists,
|
||||
threes: nba.threes, blocks: nba.blocks, steals: nba.steals,
|
||||
},
|
||||
mlb: {
|
||||
hits: mlb.hits, home_runs: mlb.homeRuns, stolen_bases: mlb.stolenBases,
|
||||
rbis: mlb.rbi, total_bases: mlb.totalBases, strikeouts: mlb.strikeouts,
|
||||
on_base: mlb.onBase,
|
||||
},
|
||||
soccer: {
|
||||
goals: soccer.goals, assists: soccer.assists, shots: soccer.shotsOnTarget,
|
||||
},
|
||||
};
|
||||
|
||||
// Headline stat per sport when the caller asks for 'all'.
|
||||
const DEFAULT_STAT = { nba: 'points', wnba: 'points', mlb: 'hits', soccer: 'goals' };
|
||||
|
||||
const STAT_LABEL = {
|
||||
points: 'pts', rebounds: 'reb', assists: 'ast', threes: '3PM',
|
||||
blocks: 'blk', steals: 'stl', pra: 'PRA',
|
||||
hits: 'H', home_runs: 'HR', stolen_bases: 'SB', rbis: 'RBI',
|
||||
total_bases: 'TB', strikeouts: 'K', on_base: 'OB',
|
||||
goals: 'G', shots: 'SOT',
|
||||
};
|
||||
|
||||
function mean(rows, fn) {
|
||||
if (!rows.length) return 0;
|
||||
return rows.reduce((acc, r) => acc + fn(r), 0) / rows.length;
|
||||
}
|
||||
|
||||
function round1(n) { return Math.round(n * 10) / 10; }
|
||||
|
||||
function resolveStat(sport, stat) {
|
||||
const table = HOT_STATS[sport] || {};
|
||||
if (!stat || stat === 'all') return DEFAULT_STAT[sport] || Object.keys(table)[0] || null;
|
||||
return table[stat] ? stat : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a ranked list of hot players for one stat.
|
||||
* players = [{ name, playerId, team, games, seasonAvg? }]
|
||||
* opts = { stat, window=7, limit, now, windowDays }
|
||||
*
|
||||
* When rows carry a `date` and `windowDays`+`now` are supplied, the recent
|
||||
* window is date-based; otherwise it's the last `window` games.
|
||||
*/
|
||||
function computeHotList(players, sport, opts = {}) {
|
||||
const key = String(sport || '').toLowerCase();
|
||||
const stat = resolveStat(key, opts.stat);
|
||||
if (!stat || !Array.isArray(players)) return [];
|
||||
const fn = HOT_STATS[key][stat];
|
||||
const window = opts.window && opts.window > 0 ? opts.window : 7;
|
||||
|
||||
const rows = [];
|
||||
for (const p of players) {
|
||||
const games = Array.isArray(p?.games) ? p.games.slice() : [];
|
||||
if (games.length === 0) continue;
|
||||
if (opts.chronological) games.reverse();
|
||||
|
||||
let recent;
|
||||
let rest;
|
||||
if (opts.windowDays && opts.now && games[0]?.date) {
|
||||
const cutoff = opts.now - opts.windowDays * 86_400_000;
|
||||
recent = games.filter((g) => new Date(g.date).getTime() >= cutoff);
|
||||
rest = games.filter((g) => new Date(g.date).getTime() < cutoff);
|
||||
} else {
|
||||
recent = games.slice(0, window);
|
||||
rest = games.slice(window);
|
||||
}
|
||||
if (recent.length === 0) continue;
|
||||
|
||||
const recentAvg = mean(recent, fn);
|
||||
|
||||
// Baseline: explicit season avg, else the player's older games.
|
||||
let baseline = null;
|
||||
const sa = p.seasonAvg && p.seasonAvg[stat];
|
||||
if (sa !== undefined && sa !== null && Number.isFinite(Number(sa))) {
|
||||
baseline = Number(sa);
|
||||
} else if (rest.length > 0) {
|
||||
baseline = mean(rest, fn);
|
||||
}
|
||||
if (baseline === null) continue; // nothing to trend against
|
||||
if (recentAvg <= baseline) continue; // not hot — at or below baseline
|
||||
|
||||
const delta = recentAvg - baseline;
|
||||
rows.push({
|
||||
sport: key,
|
||||
stat,
|
||||
name: p.name || p.player || null,
|
||||
playerId: p.playerId ?? p.id ?? null,
|
||||
team: p.team || null,
|
||||
recentAvg: round1(recentAvg),
|
||||
baseline: round1(baseline),
|
||||
delta: round1(delta),
|
||||
window: recent.length,
|
||||
statLine: `${round1(recentAvg)} ${STAT_LABEL[stat] || stat} over last ${recent.length}`,
|
||||
trendDescription: `+${round1(delta)} above ${round1(baseline)} avg`,
|
||||
});
|
||||
}
|
||||
|
||||
// Rank by how far above baseline (the "trending" signal), then by raw
|
||||
// recent average as the tie-breaker (secondary stat).
|
||||
rows.sort((a, b) => (b.delta - a.delta) || (b.recentAvg - a.recentAvg));
|
||||
const limited = opts.limit && opts.limit > 0 ? rows.slice(0, opts.limit) : rows;
|
||||
return limited.map((r, i) => ({ rank: i + 1, ...r }));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
computeHotList,
|
||||
resolveStat,
|
||||
__internals: { HOT_STATS, DEFAULT_STAT, mean },
|
||||
};
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Roster game-log loader (Session 23).
|
||||
*
|
||||
* Streaks and hot lists both need "every player's recent game log" — but
|
||||
* VYNDR caches logs per-player on demand (`gamelogs:{sport}:{player}:{n}`)
|
||||
* 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:
|
||||
* 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.
|
||||
*
|
||||
* 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
|
||||
* streaks/hot-list panels simply render nothing while other layers carry
|
||||
* the slate.
|
||||
*/
|
||||
|
||||
const { cacheGet, getRedisClient, isDegraded } = require('../utils/redis');
|
||||
|
||||
const SCAN_COUNT = 200;
|
||||
const MAX_KEYS = 600; // safety cap so a huge cache can't stall a request
|
||||
|
||||
/**
|
||||
* Parse a player display name out of a gamelogs key.
|
||||
* Key shape: `gamelogs:{sport}:{playerName}:{count}` — playerName may
|
||||
* itself contain colons in theory, so split off the known head/tail.
|
||||
*/
|
||||
function playerFromKey(key, sport) {
|
||||
const prefix = `gamelogs:${sport}:`;
|
||||
if (!key.startsWith(prefix)) return null;
|
||||
const rest = key.slice(prefix.length);
|
||||
const lastColon = rest.lastIndexOf(':');
|
||||
if (lastColon === -1) return rest;
|
||||
return rest.slice(0, lastColon);
|
||||
}
|
||||
|
||||
async function scanGameLogKeys(sport) {
|
||||
if (isDegraded && isDegraded()) return [];
|
||||
const redis = getRedisClient();
|
||||
if (!redis || typeof redis.scan !== 'function') return [];
|
||||
const match = `gamelogs:${sport}:*`;
|
||||
const keys = [];
|
||||
let cursor = '0';
|
||||
try {
|
||||
do {
|
||||
const [next, batch] = await redis.scan(cursor, 'MATCH', match, 'COUNT', SCAN_COUNT);
|
||||
cursor = next;
|
||||
for (const k of batch) {
|
||||
if (!keys.includes(k)) keys.push(k);
|
||||
if (keys.length >= MAX_KEYS) return keys;
|
||||
}
|
||||
} while (cursor !== '0');
|
||||
} catch (err) {
|
||||
console.warn('[rosterLogs] scan failed:', err.message);
|
||||
return keys;
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns [{ name, playerId, team, games }] for a sport. Dedupes players
|
||||
* (the highest game-count key wins) so one player isn't double-counted
|
||||
* across `:10` / `:20` cache variants.
|
||||
*/
|
||||
async function loadRosterLogs(sport) {
|
||||
const key = String(sport || '').toLowerCase();
|
||||
if (!key) return [];
|
||||
|
||||
// Fast path — a prefetched roster blob.
|
||||
const blob = await cacheGet(`rosterlogs:${key}`);
|
||||
if (Array.isArray(blob) && blob.length > 0) return blob;
|
||||
|
||||
const keys = await scanGameLogKeys(key);
|
||||
if (keys.length === 0) return [];
|
||||
|
||||
const byPlayer = new Map();
|
||||
for (const k of keys) {
|
||||
const name = playerFromKey(k, key);
|
||||
if (!name) continue;
|
||||
const games = await cacheGet(k);
|
||||
if (!Array.isArray(games) || games.length === 0) continue;
|
||||
const existing = byPlayer.get(name);
|
||||
if (!existing || games.length > existing.games.length) {
|
||||
const playerId = games[0]?.playerId ?? games[0]?.player_id ?? null;
|
||||
const team = games[0]?.team ?? games[0]?.teamAbv ?? null;
|
||||
byPlayer.set(name, { name, playerId, team, games });
|
||||
}
|
||||
}
|
||||
return Array.from(byPlayer.values());
|
||||
}
|
||||
|
||||
module.exports = { loadRosterLogs, __internals: { playerFromKey, scanGameLogKeys } };
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* Schedule service (Session 23).
|
||||
*
|
||||
* Today's game schedule from FREE ESPN scoreboards. NO odds-api credits
|
||||
* burned. Cache-aside: reads `schedule:{sport}:{date}` from Redis first;
|
||||
* on a miss it fetches the ESPN scoreboard directly (the same free
|
||||
* endpoint the PM2 pollers hit every 60s), normalizes, caches, returns.
|
||||
*
|
||||
* This dual path is deliberate. The pollers warm the cache during game
|
||||
* hours, but the endpoint must NEVER be empty just because a poller is
|
||||
* down or off-hours — so it self-heals by fetching ESPN on a cache miss.
|
||||
*
|
||||
* Everything here is free. The only paid/quota'd layer (Tank01 game
|
||||
* lines, odds-api props) is checked separately via the hasGameLines /
|
||||
* hasOdds flags, which read OTHER caches without ever triggering a fetch.
|
||||
*/
|
||||
|
||||
const axios = require('axios');
|
||||
const { cacheGet, cacheSet } = require('../utils/redis');
|
||||
const { SPORT_CONFIG } = require('../config/sports');
|
||||
|
||||
function getSportConfig(sport) {
|
||||
return SPORT_CONFIG[String(sport || '').toLowerCase()] || null;
|
||||
}
|
||||
|
||||
const HTTP_TIMEOUT_MS = 10_000;
|
||||
const SCHEDULE_TTL = 60; // 60s — mirrors poller cadence; live scores stay fresh
|
||||
const STALE_TTL = 6 * 3600; // stale-while-error fallback
|
||||
|
||||
/**
|
||||
* Today's date in ET as YYYY-MM-DD. Sports days roll over on ET, not UTC,
|
||||
* so a late west-coast game still counts as "today" past midnight UTC.
|
||||
*/
|
||||
function todayET() {
|
||||
const fmt = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'America/New_York',
|
||||
year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
});
|
||||
return fmt.format(new Date()); // en-CA → YYYY-MM-DD
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize one ESPN scoreboard event into VYNDR's schedule shape.
|
||||
* Defensive throughout — ESPN omits fields freely (no venue for neutral
|
||||
* sites, no broadcast until close to tip). A missing field becomes null,
|
||||
* never a throw.
|
||||
*/
|
||||
function normalizeEvent(ev) {
|
||||
if (!ev) return null;
|
||||
const comp = ev.competitions?.[0] || {};
|
||||
const competitors = comp.competitors || [];
|
||||
const home = competitors.find((c) => c.homeAway === 'home') || competitors[0] || {};
|
||||
const away = competitors.find((c) => c.homeAway === 'away') || competitors[1] || {};
|
||||
|
||||
const team = (c) => ({
|
||||
name: c?.team?.displayName || c?.team?.name || c?.team?.shortDisplayName || null,
|
||||
abbreviation: c?.team?.abbreviation || null,
|
||||
});
|
||||
|
||||
const score = (c) => {
|
||||
const n = Number(c?.score);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
};
|
||||
|
||||
const state = ev.status?.type?.state || comp.status?.type?.state || null; // pre|in|post
|
||||
const hasScore = state === 'in' || state === 'post';
|
||||
|
||||
// Broadcast: ESPN scatters this across competitions[].broadcasts and
|
||||
// geoBroadcasts. Take the first network name we can find.
|
||||
let broadcast = null;
|
||||
const bcasts = comp.broadcasts || [];
|
||||
if (bcasts[0]?.names?.[0]) broadcast = bcasts[0].names[0];
|
||||
else if (comp.geoBroadcasts?.[0]?.media?.shortName) broadcast = comp.geoBroadcasts[0].media.shortName;
|
||||
|
||||
return {
|
||||
id: String(ev.id),
|
||||
homeTeam: team(home),
|
||||
awayTeam: team(away),
|
||||
gameTime: ev.date || comp.date || null,
|
||||
status: state,
|
||||
score: hasScore ? { home: score(home), away: score(away) } : null,
|
||||
venue: comp.venue?.fullName || null,
|
||||
broadcast,
|
||||
hasOdds: false, // filled by enrichFlags
|
||||
hasGameLines: false, // filled by enrichFlags
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch + normalize the ESPN scoreboard for a sport. Free endpoint.
|
||||
*/
|
||||
async function fetchScheduleFromEspn(sport) {
|
||||
const cfg = getSportConfig(sport);
|
||||
if (!cfg || !cfg.espnScoreboard) return null;
|
||||
const res = await axios.get(cfg.espnScoreboard, { timeout: HTTP_TIMEOUT_MS });
|
||||
const events = res.data?.events || [];
|
||||
return events.map(normalizeEvent).filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache-aside schedule read. Returns an array of normalized games
|
||||
* (possibly empty — empty is a valid "no games today", not an error).
|
||||
* Returns null only when the sport is unknown / unsupported.
|
||||
*/
|
||||
async function getSchedule(sport, date) {
|
||||
const cfg = getSportConfig(sport);
|
||||
if (!cfg || !cfg.espnScoreboard) return null;
|
||||
const key = `schedule:${sport}:${date}`;
|
||||
|
||||
const cached = await cacheGet(key);
|
||||
if (cached !== null) return cached;
|
||||
|
||||
try {
|
||||
const games = await fetchScheduleFromEspn(sport);
|
||||
if (Array.isArray(games)) {
|
||||
await cacheSet(key, games, SCHEDULE_TTL);
|
||||
await cacheSet(`${key}:stale`, games, STALE_TTL);
|
||||
return games;
|
||||
}
|
||||
return [];
|
||||
} catch (err) {
|
||||
console.warn(`[schedule] ESPN fetch failed for ${sport}:`, err.message);
|
||||
const stale = await cacheGet(`${key}:stale`);
|
||||
return stale !== null ? stale : [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-game enrichment: set hasOdds / hasGameLines by peeking at the OTHER
|
||||
* caches. Reads only — never triggers a fetch, never burns quota. The
|
||||
* odds-api props cache and the Tank01 game-lines cache are date-keyed
|
||||
* (one blob per sport+date), so a single read tells us whether ANY game
|
||||
* that day has data; we apply it to every game in the slate.
|
||||
*
|
||||
* A future refinement could match per-game, but the date-level flag is
|
||||
* the honest signal today: "props exist for this slate" / "lines exist
|
||||
* for this slate".
|
||||
*/
|
||||
async function enrichFlags(sport, date, games) {
|
||||
if (!Array.isArray(games) || games.length === 0) return games;
|
||||
const ymd = String(date).replace(/-/g, '');
|
||||
|
||||
// odds-api props cache — oddsService writes `odds:{sport}:{utcDate}`
|
||||
// as `{ updated_at, props, spreads }`. The slate `date` is ET, so try
|
||||
// the ET key first then the UTC key (they differ only past midnight).
|
||||
const utcDate = new Date().toISOString().split('T')[0];
|
||||
const oddsCache =
|
||||
(await cacheGet(`odds:${sport}:${date}`)) ??
|
||||
(await cacheGet(`odds:${sport}:${utcDate}`)) ??
|
||||
(await cacheGet(`odds:${sport}`));
|
||||
const hasOdds = hasPropsData(oddsCache);
|
||||
|
||||
// Tank01 game-lines cache — adapters write tank01:{sport}:odds:{ymd}.
|
||||
const linesCache = await cacheGet(`tank01:${sport}:odds:${ymd}`);
|
||||
const hasGameLines = hasLinesData(linesCache);
|
||||
|
||||
return games.map((g) => ({ ...g, hasOdds, hasGameLines }));
|
||||
}
|
||||
|
||||
function hasPropsData(cache) {
|
||||
if (!cache) return false;
|
||||
if (Array.isArray(cache)) return cache.length > 0;
|
||||
if (Array.isArray(cache.props)) return cache.props.length > 0;
|
||||
if (Array.isArray(cache.games)) return cache.games.length > 0;
|
||||
if (typeof cache === 'object') return Object.keys(cache).length > 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
function hasLinesData(cache) {
|
||||
if (!cache) return false;
|
||||
const body = cache.body || cache;
|
||||
if (Array.isArray(body)) return body.length > 0;
|
||||
if (typeof body === 'object') return Object.keys(body).length > 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getSchedule,
|
||||
enrichFlags,
|
||||
todayET,
|
||||
__internals: { normalizeEvent, fetchScheduleFromEspn, hasPropsData, hasLinesData },
|
||||
};
|
||||
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Streaks engine (Session 23).
|
||||
*
|
||||
* Computes player streaks from cached game-log data. Everything analyzed
|
||||
* through VYNDR's lens — not "Wemby 31 PPG" but "Wemby on a 4-game 28+
|
||||
* scoring streak." A streak is a CONSECUTIVE run of recent games meeting
|
||||
* a threshold; we count from the most recent game backward and stop at
|
||||
* the first miss.
|
||||
*
|
||||
* Pure & deterministic. `computePlayerStreaks` operates on one player's
|
||||
* game array; `computeStreaks` fans out across a roster and returns a
|
||||
* flat, sorted, optionally stat-filtered list. NO API calls live here —
|
||||
* the route layer supplies cached logs.
|
||||
*
|
||||
* Game logs are expected MOST-RECENT-FIRST (index 0 = latest). Pass
|
||||
* `{ chronological: true }` to reverse oldest-first input.
|
||||
*/
|
||||
|
||||
// ---- defensive numeric field reader -------------------------------------
|
||||
function num(row, ...keys) {
|
||||
if (!row) return 0;
|
||||
for (const k of keys) {
|
||||
if (row[k] !== undefined && row[k] !== null && row[k] !== '') {
|
||||
const n = Number(row[k]);
|
||||
if (Number.isFinite(n)) return n;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// NBA/WNBA stat accessors — tolerate the several field spellings the
|
||||
// Python stats service and Tank01 use.
|
||||
const nba = {
|
||||
points: (r) => num(r, 'points', 'pts', 'PTS'),
|
||||
rebounds: (r) => num(r, 'rebounds', 'reb', 'REB', 'totReb'),
|
||||
assists: (r) => num(r, 'assists', 'ast', 'AST'),
|
||||
threes: (r) => num(r, 'threes', 'threes_made', 'fg3m', 'tptfgm', 'threePointersMade'),
|
||||
blocks: (r) => num(r, 'blocks', 'blk', 'BLK'),
|
||||
steals: (r) => num(r, 'steals', 'stl', 'STL'),
|
||||
fgPct: (r) => {
|
||||
const pct = num(r, 'fg_pct', 'fgPct', 'fieldGoalPct');
|
||||
if (pct > 0) return pct > 1 ? pct / 100 : pct; // accept 0–1 or 0–100
|
||||
const m = num(r, 'fgm', 'field_goals_made');
|
||||
const a = num(r, 'fga', 'field_goals_attempted');
|
||||
return a > 0 ? m / a : 0;
|
||||
},
|
||||
};
|
||||
nba.pra = (r) => nba.points(r) + nba.rebounds(r) + nba.assists(r);
|
||||
nba.doubleCount = (r) =>
|
||||
[nba.points(r), nba.rebounds(r), nba.assists(r), nba.steals(r), nba.blocks(r)]
|
||||
.filter((v) => v >= 10).length;
|
||||
|
||||
const mlb = {
|
||||
hits: (r) => num(r, 'hits', 'H', 'h'),
|
||||
homeRuns: (r) => num(r, 'homeRuns', 'home_runs', 'HR', 'hr'),
|
||||
stolenBases: (r) => num(r, 'stolenBases', 'stolen_bases', 'SB', 'sb'),
|
||||
rbi: (r) => num(r, 'rbi', 'RBI'),
|
||||
walks: (r) => num(r, 'walks', 'baseOnBalls', 'BB', 'bb'),
|
||||
hbp: (r) => num(r, 'hitByPitch', 'hbp', 'HBP'),
|
||||
totalBases: (r) => num(r, 'totalBases', 'total_bases', 'TB'),
|
||||
strikeouts: (r) => num(r, 'strikeOuts', 'strikeouts', 'pitcherK', 'K', 'so'),
|
||||
inningsPitched: (r) => num(r, 'inningsPitched', 'ip', 'IP'),
|
||||
earnedRuns: (r) => num(r, 'earnedRuns', 'er', 'ER'),
|
||||
};
|
||||
mlb.onBase = (r) => mlb.hits(r) + mlb.walks(r) + mlb.hbp(r);
|
||||
mlb.isQualityStart = (r) => mlb.inningsPitched(r) >= 6 && mlb.earnedRuns(r) <= 3;
|
||||
|
||||
const nfl = {
|
||||
passTd: (r) => num(r, 'passTD', 'passing_touchdowns', 'pass_td'),
|
||||
rushTd: (r) => num(r, 'rushTD', 'rushing_touchdowns', 'rush_td'),
|
||||
recTd: (r) => num(r, 'recTD', 'receiving_touchdowns', 'rec_td'),
|
||||
rushYds:(r) => num(r, 'rushYds', 'rushing_yards', 'rush_yards'),
|
||||
recYds: (r) => num(r, 'recYds', 'receiving_yards', 'rec_yards'),
|
||||
ints: (r) => num(r, 'interceptions', 'int', 'passInt'),
|
||||
};
|
||||
nfl.anyTd = (r) => nfl.passTd(r) + nfl.rushTd(r) + nfl.recTd(r);
|
||||
|
||||
const soccer = {
|
||||
goals: (r) => num(r, 'goals', 'G'),
|
||||
assists: (r) => num(r, 'assists', 'A'),
|
||||
shotsOnTarget: (r) => num(r, 'shotsOnTarget', 'shots_on_target', 'sot'),
|
||||
goalsConceded: (r) => num(r, 'goalsConceded', 'goals_conceded', 'ga'),
|
||||
minutes: (r) => num(r, 'minutes', 'min', 'MIN'),
|
||||
};
|
||||
|
||||
// ---- streak specs -------------------------------------------------------
|
||||
// Each spec: { key, category, threshold, label, value, mode }.
|
||||
// value(row) → number; the game counts toward the streak when value >= threshold.
|
||||
// mode 'consecutive' (default) counts the run from the latest game.
|
||||
// mode 'rate' marks "hot" when the mean over the last `window` games >= threshold.
|
||||
const SPECS = {
|
||||
nba: [
|
||||
{ key: 'points_25', category: 'points', collapse: 'points', threshold: 25, label: '25+ pts', value: nba.points },
|
||||
{ key: 'points_20', category: 'points', collapse: 'points', threshold: 20, label: '20+ pts', value: nba.points },
|
||||
{ key: 'assists_8', category: 'assists', collapse: 'assists', threshold: 8, label: '8+ ast', value: nba.assists },
|
||||
{ key: 'assists_6', category: 'assists', collapse: 'assists', threshold: 6, label: '6+ ast', value: nba.assists },
|
||||
{ key: 'rebounds_10',category: 'rebounds', collapse: 'rebounds', threshold: 10, label: '10+ reb', value: nba.rebounds },
|
||||
{ key: 'rebounds_8', category: 'rebounds', collapse: 'rebounds', threshold: 8, label: '8+ reb', value: nba.rebounds },
|
||||
{ key: 'threes_4', category: 'threes', collapse: 'threes', threshold: 4, label: '4+ threes', value: nba.threes },
|
||||
{ key: 'threes_3', category: 'threes', collapse: 'threes', threshold: 3, label: '3+ threes', value: nba.threes },
|
||||
{ key: 'blocks_2', category: 'blocks', threshold: 2, label: '2+ blk', value: nba.blocks },
|
||||
{ key: 'steals_2', category: 'steals', threshold: 2, label: '2+ stl', value: nba.steals },
|
||||
{ key: 'pra_40', category: 'pra', threshold: 40, label: '40+ PRA', value: nba.pra },
|
||||
{ key: 'double_double', category: 'all', threshold: 2, label: 'double-double', value: nba.doubleCount, noun: 'double-double' },
|
||||
{ key: 'triple_double', category: 'all', threshold: 3, label: 'triple-double', value: nba.doubleCount, noun: 'triple-double' },
|
||||
{ key: 'hot_shooter', category: 'points', threshold: 0.5, label: 'hot shooter (FG% > 50%)', value: nba.fgPct, mode: 'rate', window: 5 },
|
||||
],
|
||||
// WNBA shares NBA's stat layout (no PRA/triple-double headline emphasis,
|
||||
// but the specs are harmless if a player never hits them).
|
||||
wnba: null, // filled below = nba minus the rate spec quirks
|
||||
mlb: [
|
||||
{ key: 'hit_streak', category: 'hits', collapse: 'hits', threshold: 1, label: 'hit', value: mlb.hits },
|
||||
{ key: 'multi_hit', category: 'hits', collapse: 'hits', threshold: 2, label: 'multi-hit', value: mlb.hits },
|
||||
{ key: 'hr_streak', category: 'home_runs', threshold: 1, label: 'HR', value: mlb.homeRuns },
|
||||
{ key: 'sb_streak', category: 'stolen_bases', threshold: 1, label: 'SB', value: mlb.stolenBases },
|
||||
{ key: 'rbi_streak', category: 'rbis', threshold: 1, label: 'RBI', value: mlb.rbi },
|
||||
{ key: 'onbase_streak',category: 'on_base', threshold: 1, label: 'on-base', value: mlb.onBase },
|
||||
{ key: 'tb_streak', category: 'total_bases', threshold: 2, label: '2+ total bases', value: mlb.totalBases },
|
||||
{ key: 'k_streak', category: 'strikeouts', threshold: 7, label: '7+ K', value: mlb.strikeouts },
|
||||
{ key: 'qs_streak', category: 'strikeouts', threshold: 1, label: 'quality start', value: (r) => (mlb.isQualityStart(r) ? 1 : 0) },
|
||||
],
|
||||
nfl: [
|
||||
{ key: 'td_streak', category: 'touchdowns', threshold: 1, label: 'TD', value: nfl.anyTd },
|
||||
{ key: 'multi_td', category: 'touchdowns', threshold: 2, label: 'multi-TD', value: nfl.anyTd },
|
||||
{ key: 'rush_100', category: 'rushing_yards', threshold: 100, label: '100-yd rushing', value: nfl.rushYds },
|
||||
{ key: 'rec_100', category: 'receiving_yards', threshold: 100, label: '100-yd receiving', value: nfl.recYds },
|
||||
{ key: 'clean_qb', category: 'interceptions', threshold: 1, label: 'INT-free', value: (r) => (nfl.ints(r) === 0 ? 1 : 0) },
|
||||
],
|
||||
soccer: [
|
||||
{ key: 'goal_streak', category: 'goals', threshold: 1, label: 'goal', value: soccer.goals },
|
||||
{ key: 'assist_streak', category: 'assists', threshold: 1, label: 'assist', value: soccer.assists },
|
||||
{ key: 'sot_streak', category: 'shots', threshold: 1, label: 'shot-on-target', value: soccer.shotsOnTarget },
|
||||
{ key: 'clean_sheet', category: 'saves', threshold: 1, label: 'clean sheet',
|
||||
value: (r) => (soccer.minutes(r) > 0 && soccer.goalsConceded(r) === 0 ? 1 : 0) },
|
||||
],
|
||||
};
|
||||
SPECS.wnba = SPECS.nba;
|
||||
|
||||
function specsFor(sport) {
|
||||
return SPECS[String(sport || '').toLowerCase()] || [];
|
||||
}
|
||||
|
||||
// ---- core streak math ---------------------------------------------------
|
||||
function consecutiveRun(games, valueFn, threshold) {
|
||||
let run = 0;
|
||||
for (const g of games) {
|
||||
if (valueFn(g) >= threshold) run += 1;
|
||||
else break;
|
||||
}
|
||||
return run;
|
||||
}
|
||||
|
||||
function rateOverWindow(games, valueFn, window) {
|
||||
const slice = games.slice(0, window);
|
||||
if (slice.length < window) return { value: 0, count: slice.length };
|
||||
const sum = slice.reduce((acc, g) => acc + valueFn(g), 0);
|
||||
return { value: sum / slice.length, count: slice.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimum run length to surface a streak. A "1-game streak" is just a
|
||||
* stat line, not a streak — require at least 2 to count as VYNDR signal,
|
||||
* except double/triple-double which are notable at any length >= 2.
|
||||
*/
|
||||
const MIN_STREAK = 2;
|
||||
|
||||
function describe(spec, run) {
|
||||
if (spec.noun) return `${run}-game ${spec.noun} streak`;
|
||||
if (spec.mode === 'rate') return spec.label;
|
||||
return `${run}-game ${spec.label} streak`;
|
||||
}
|
||||
|
||||
/**
|
||||
* All streaks for ONE player. Returns the strongest streak per stat
|
||||
* CATEGORY (so a player with a 20+ and a 25+ points streak surfaces only
|
||||
* the more impressive one) — keeps the feed signal-dense.
|
||||
*/
|
||||
function computePlayerStreaks(player, sport, opts = {}) {
|
||||
const specs = specsFor(sport);
|
||||
let games = Array.isArray(player?.games) ? player.games.slice() : [];
|
||||
if (opts.chronological) games.reverse();
|
||||
if (games.length === 0) return [];
|
||||
|
||||
const found = [];
|
||||
for (const spec of specs) {
|
||||
if (spec.mode === 'rate') {
|
||||
const { value, count } = rateOverWindow(games, spec.value, spec.window);
|
||||
if (count >= spec.window && value >= spec.threshold) {
|
||||
found.push(makeStreak(player, sport, spec, spec.window, value));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const run = consecutiveRun(games, spec.value, spec.threshold);
|
||||
if (run >= MIN_STREAK) found.push(makeStreak(player, sport, spec, run));
|
||||
}
|
||||
|
||||
// Collapse tiered specs (e.g. 25+ and 20+ points) to one entry per
|
||||
// collapse group — prefer the MORE IMPRESSIVE streak (higher threshold),
|
||||
// tie-broken by the longer run. Non-tiered specs each have a unique
|
||||
// collapse key, so they pass through untouched.
|
||||
const best = new Map();
|
||||
for (const s of found) {
|
||||
const cur = best.get(s._collapse);
|
||||
if (!cur ||
|
||||
s.threshold > cur.threshold ||
|
||||
(s.threshold === cur.threshold && s.currentStreak > cur.currentStreak)) {
|
||||
best.set(s._collapse, s);
|
||||
}
|
||||
}
|
||||
return Array.from(best.values()).map(({ _collapse, ...rest }) => rest);
|
||||
}
|
||||
|
||||
function makeStreak(player, sport, spec, run, rateValue) {
|
||||
return {
|
||||
sport,
|
||||
player: player.name || player.player || null,
|
||||
playerId: player.playerId ?? player.id ?? null,
|
||||
team: player.team || null,
|
||||
type: spec.key,
|
||||
category: spec.category,
|
||||
threshold: spec.threshold,
|
||||
currentStreak: run,
|
||||
rate: rateValue ?? null,
|
||||
description: describe(spec, run),
|
||||
active: true,
|
||||
_collapse: spec.collapse || spec.key, // internal — stripped before return
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fan out across a roster. `players` = [{ name, playerId, team, games }].
|
||||
* Returns a flat list sorted by streak length desc, optionally narrowed
|
||||
* to a single stat category and capped at `limit`.
|
||||
*/
|
||||
function computeStreaks(players, sport, opts = {}) {
|
||||
if (!Array.isArray(players)) return [];
|
||||
const stat = opts.stat && opts.stat !== 'all' ? String(opts.stat).toLowerCase() : null;
|
||||
let all = [];
|
||||
for (const p of players) {
|
||||
all = all.concat(computePlayerStreaks(p, sport, opts));
|
||||
}
|
||||
if (stat) all = all.filter((s) => s.category === stat);
|
||||
all.sort((a, b) => b.currentStreak - a.currentStreak);
|
||||
if (opts.limit && opts.limit > 0) all = all.slice(0, opts.limit);
|
||||
return all;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
computeStreaks,
|
||||
computePlayerStreaks,
|
||||
specsFor,
|
||||
__internals: { consecutiveRun, rateOverWindow, nba, mlb, nfl, soccer, MIN_STREAK },
|
||||
};
|
||||
Reference in New Issue
Block a user