diff --git a/BACKEND_HANDOFF.md b/BACKEND_HANDOFF.md index 0b3e985..69891d2 100644 --- a/BACKEND_HANDOFF.md +++ b/BACKEND_HANDOFF.md @@ -206,3 +206,29 @@ The system's track record — settled grades vs real results. Written by `GET /api/snapshot/:sport` grades may carry `outcome: { result:'hit'|'miss'| 'push', actual:number }` once the game is final. `AccuracyBadge` + `StatStrip.OutcomeChip` render these. Frontend proxy: `web/src/app/api/accuracy`. + +## 8. Public ledger profiles (`src/routes/profiles.js`, A1 Session 10) + +Strava-for-betting v1. Table `public_profiles` (migration 022 — apply +before deploy). PRIVATE BY DEFAULT; one explicit publish toggle in Settings. + +### `GET /api/profiles/:handle` (public, cached 60s) +Published only. Unknown AND unpublished return the SAME 404 body +(`{ error: 'Profile not found' }`) — no existence leak. +``` +{ + handle: string, + aggregate: , + entries: [], + min_sample: 20 // below this, RECORD BUILDING — never a % +} +``` + +### `GET|POST /api/profiles/me` (requireAuth) +GET → `{ profile: { handle, published, created_at } | null }`. +POST `{ handle, published }` → upsert own row (service role). Handle must +match `^[a-z0-9_]{3,20}$` (400); a handle owned by another user → 409. +`published` flips ONLY on boolean `true`. + +Frontend: `/u/[handle]` (OPEN route, server shell + client record + OG card, +Node runtime) via proxies `web/src/app/api/profiles/me|[handle]`. diff --git a/BUILD-STATE.md b/BUILD-STATE.md index 2c9aff3..eb63001 100755 --- a/BUILD-STATE.md +++ b/BUILD-STATE.md @@ -3,6 +3,28 @@ ## Last Updated 2026-07-11 +## Session S10 (a1 board, 2026-07-11) — Public Ledger Profiles v1 ✅ +Stage-3 seed (Strava for betting), zero out-of-pocket. Branch off +day1/a1-board (aaafc3e). 2574 → **2612 tests** (220 suites), web build +exit 0. Spec: `specs/a1-s10-public-profiles.md`. +- **Migration `022_public_profiles.sql`** — COMMITTED, NOT APPLIED (founder + applies migrations). `public_profiles` (user_id PK → auth.users, handle + UNIQUE + regex CHECK, `published` DEFAULT FALSE). RLS: published rows + readable by anyone, own row by owner, writes service-role only. +- **API** — `/api/profiles`: `GET/POST /me` (requireAuth; handle regex 400, + taken handle 409, published only flips on explicit boolean true) and + public `GET /:handle` (published → user-scoped 30d aggregate + settled + rows newest 50, same columns as /api/ledger; unknown AND unpublished → + byte-identical 404 — no existence leak). `getModelAggregate` gained a + `userId` option (public `.is('user_id', null)` default untouched). +- **Frontend** — `/u/[handle]` (PUBLIC, in OPEN_ROUTES): server shell with + "CLV-verified record — @handle · VYNDR" metadata + client record (hit% + + beat-close% at n≥20 else RECORD BUILDING; outcome + CLV chips) + OG card + (Node runtime, never edge). Settings PUBLIC PROFILE section: claim handle + + one explicit publish toggle with the private-by-default copy. +- **Next**: profile OG card could embed the live record once n≥20 profiles + exist; user-scan settlement coverage beyond MLB is the limiting factor. + ## Session S3 (a1 board, 2026-07-11) — Affiliate + Partnership Plumbing ✅ Zero out-of-pocket; everything config-flip-ready but DISABLED/organic. 2398 → **2439 tests** (209 suites), web build exit 0. diff --git a/CLAUDE.md b/CLAUDE.md index f0e4371..0131669 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -880,6 +880,27 @@ phased plan in the Session-57 conversation / BUILD-STATE Next section). - Box-side ops (Uptime Kuma, Coolify deploy-failure webhook, ntfy phone setup) = `docs/OPS-RUNBOOK.md`. +## Public Ledger Profiles v1 (Session 10, A1 board — non-obvious) +- **`public_profiles` (migration 022) is PRIVATE BY DEFAULT** — `published` + DEFAULT FALSE, one explicit toggle in Settings, service-role writes only. + `GET /api/profiles/:handle` returns the SAME 404 body for unknown AND + unpublished handles (no existence leak) — keep them byte-identical; a + test diffs the two responses. A malformed handle 404s WITHOUT a DB query. +- **`getModelAggregate({ userId })`** swaps `.is('user_id', null)` for + `.eq('user_id', uid)` on BOTH the settled and pending queries — the same + 30d window + n≥20 gate over one user's ledger. The no-userId default is + the public model record and must stay untouched. +- **The user's public entries are SETTLED rows only** (`.not('outcome', + 'is', null)`, newest 50, same columns as /api/ledger) — pending reads are + not public until they settle, and nothing is curated: misses included. +- **`/u` is in OPEN_ROUTES on purpose** — the share surface must load + anonymous; the privacy gate is the API's 404, never the router. +- **Jest from a worktree gotcha:** the repo config's `testPathIgnorePatterns` + includes `/.claude/`, which matches EVERY path inside + `.claude/worktrees/...` → "No tests found". Run with + `npx jest --testPathIgnorePatterns "/node_modules/"` from a worktree + (CLI replaces the config array). + ## Active Skills - vyndr-voice (all user-facing output) - prop-analysis (grading methodology) diff --git a/specs/a1-s10-public-profiles.md b/specs/a1-s10-public-profiles.md new file mode 100644 index 0000000..26a1fc5 --- /dev/null +++ b/specs/a1-s10-public-profiles.md @@ -0,0 +1,77 @@ +# A1 Session 10 — Public Ledger Profiles v1 + +Stage-3 seed (NORTH STAR): every bettor gets a CLV-verified public record — +Strava for betting. v1 is the minimum honest version: a handle, one explicit +publish toggle, and the user's ENTIRE settled record on a public page. + +## Operating rules +- Zero out-of-pocket. Existing Supabase + Express + Next only. +- PRIVATE BY DEFAULT. `published` defaults false; publishing is one explicit + toggle with copy that says exactly what it does. +- Same n-gating as the model record: no percentage under 20 settles + (`ledgerService.MIN_AGG_SAMPLE`). +- Data semantics: only real settled ledger rows. Nothing curated — a public + profile shows ALL settled reads including misses. That is the point. +- No existence leak: unknown handle and unpublished handle return the SAME + 404 body. + +## Data +Migration `supabase/migrations/022_public_profiles.sql` (committed, NOT +applied — the founder applies migrations): + +``` +public_profiles ( + user_id uuid PK REFERENCES auth.users ON DELETE CASCADE, + handle text UNIQUE NOT NULL CHECK (handle ~ '^[a-z0-9_]{3,20}$'), + published boolean NOT NULL DEFAULT false, + created_at timestamptz NOT NULL DEFAULT now() +) +``` +RLS: anon + authenticated SELECT where `published = true`; owner SELECTs own +row; NO client write policies — all writes via the service role. + +## Endpoints (`src/routes/profiles.js`, mounted at /api/profiles) +- `GET /api/profiles/me` (requireAuth) → `{ profile: {handle, published, + created_at} | null }`. +- `POST /api/profiles/me` (requireAuth) → upsert own `{ handle, published }`. + Handle validated against `^[a-z0-9_]{3,20}$` (400 on invalid); a handle + owned by another user → 409. Service-role write. +- `GET /api/profiles/:handle` (public, 60/min) → published profile: + `{ handle, aggregate, entries, min_sample }` where + - `aggregate` = `ledgerService.getModelAggregate({ userId })` — a new + `userId` option swaps the `.is('user_id', null)` public scoping for + `.eq('user_id', uid)`. The public default is untouched. + - `entries` = that user's SETTLED rows, newest 50, same columns as + /api/ledger. + Unknown OR unpublished → 404 with the identical body (no existence leak). + +Next proxies: `web/src/app/api/profiles/me/route.ts` (GET/POST, forwards +Authorization) and `web/src/app/api/profiles/[handle]/route.ts` (GET). + +## Frontend +- `/u/[handle]` — PUBLIC (never gated). Server component shell with metadata + `CLV-verified record — @handle · VYNDR` + client content: record header + (hit% + beat-close% at n≥20, else RECORD BUILDING), settled rows with + outcome + CLV chips (ledger card patterns), OG card via + `opengraph-image.tsx` in the segment (Node runtime — NEVER edge, S53 rule). +- `/settings` PUBLIC PROFILE section: claim handle + publish toggle. Copy + makes public-by-choice explicit: "Publishing puts your ENTIRE settled + record on a public page — wins and misses. Private by default." + +## Acceptance criteria +1. Migration committed, unapplied, documented in the report. +2. `getModelAggregate` default scope unchanged; `userId` scope unit-tested + both ways. +3. Unpublished and unknown handles return byte-identical 404 bodies. +4. Handle regex enforced at API AND database CHECK. +5. `/u/...` reachable anonymous; aggregate renders no % under 20 settles. +6. Full jest suite green; `web` build exit 0. + +## Test plan +- `tests/unit/ledgerAggregateScope.test.js` — public vs userId scoping. +- `tests/integration/profilesRoutes.test.js` — handle validation, 409 on + taken handle, publish flow, 404-no-leak (mock supabase per + ledgerRoutes.test.js pattern). +- `tests/unit/publicProfilePage.test.js` — page/OG/settings source + assertions (metadata string, no edge runtime, RECORD BUILDING state, + private-by-default copy, /u stays ungated). diff --git a/src/app.js b/src/app.js index 2c9b68c..1cccdc5 100644 --- a/src/app.js +++ b/src/app.js @@ -165,6 +165,9 @@ app.use('/api/team', require('./routes/team')); // (settled snapshot grades vs real results). Public, cache-only. app.use('/api/accuracy', require('./routes/accuracy')); app.use('/api/ledger', require('./routes/ledger')); +// A1 Session 10 — public ledger profiles: claim a handle, one explicit +// publish toggle, and the ENTIRE settled record on a public page. +app.use('/api/profiles', require('./routes/profiles')); const gameLinesRoutes = require('./routes/gameLines'); app.use('/api/gamelines', gameLinesRoutes); const streaksRoutes = require('./routes/streaks'); diff --git a/src/routes/profiles.js b/src/routes/profiles.js new file mode 100644 index 0000000..8e0f753 --- /dev/null +++ b/src/routes/profiles.js @@ -0,0 +1,134 @@ +'use strict'; + +/** + * /api/profiles — public ledger profiles v1 (A1 Session 10). + * + * Stage-3 seed: a user claims a handle and publishes their ENTIRE settled + * ledger record — wins and misses, nothing curated. Strava for betting. + * + * GET /me (auth) — own public_profiles row (or null). + * POST /me (auth) — upsert own { handle, published }. Handle must + * match ^[a-z0-9_]{3,20}$; a handle owned by + * another user → 409. Service-role write only + * (the table has no client write policies). + * GET /:handle (public) — the published record: the user-scoped 30d + * aggregate (same n≥20 gate as the model record) + * + settled rows, newest 50, same columns as + * /api/ledger. + * + * PRIVACY: PRIVATE BY DEFAULT — `published` only flips via the explicit + * toggle. NO EXISTENCE LEAK: an unknown handle and an unpublished handle + * return the byte-identical 404 body. + */ + +const express = require('express'); +const { createRateLimit } = require('../middleware/rateLimit'); +const { requireAuth } = require('../middleware/auth'); +const ledgerService = require('../services/ledgerService'); + +const router = express.Router(); +router.use(createRateLimit({ windowMs: 60_000, max: 60 })); + +const HANDLE_RE = /^[a-z0-9_]{3,20}$/; +// Same 404 body for unknown AND unpublished — never confirm a handle exists. +const NOT_FOUND = { error: 'Profile not found' }; +// Same columns as /api/ledger (routes/ledger.js ROW_COLUMNS). +const ROW_COLUMNS = 'id, player_key, player_name, sport, stat, line, side, locked_odds, book, grade, edge, confidence, model_value, graded_at, game_id, game_date, closing_line, closing_odds, clv, clv_result, outcome, actual_value, settled_at, revised_from_grade'; +const ENTRY_LIMIT = 50; + +function sbOrNull() { + try { + if (!ledgerService.__internals.isConfigured()) return null; + return require('../utils/supabase').getSupabaseServiceClient(); + } catch { return null; } +} + +// Own row — the owner sees it published or not. +router.get('/me', requireAuth, async (req, res) => { + const sb = sbOrNull(); + if (!sb) return res.json({ profile: null }); + try { + const { data, error } = await sb.from('public_profiles') + .select('handle, published, created_at') + .eq('user_id', req.user.id) + .maybeSingle(); + if (error) throw new Error(error.message); + return res.json({ profile: data || null }); + } catch (err) { + console.error('[profiles/me]', err.message); + return res.status(200).json({ profile: null }); + } +}); + +// Claim/update the handle + the ONE explicit publish toggle. +router.post('/me', requireAuth, async (req, res) => { + const sb = sbOrNull(); + if (!sb) return res.status(503).json({ error: 'Profiles are unavailable right now' }); + try { + const body = req.body || {}; + const handle = String(body.handle || '').trim().toLowerCase(); + if (!HANDLE_RE.test(handle)) { + return res.status(400).json({ error: 'Handle must be 3-20 characters: a-z, 0-9, underscore' }); + } + // PRIVATE BY DEFAULT: published only flips when the body says true. + const published = body.published === true; + const { error } = await sb.from('public_profiles') + .upsert({ user_id: req.user.id, handle, published }, { onConflict: 'user_id' }); + if (error) { + // Unique violation on `handle` → someone else owns it. + if (error.code === '23505' || /duplicate|unique/i.test(error.message || '')) { + return res.status(409).json({ error: 'That handle is taken' }); + } + throw new Error(error.message); + } + return res.json({ ok: true, profile: { handle, published } }); + } catch (err) { + console.error('[profiles/post]', err.message); + return res.status(503).json({ error: 'Could not save profile' }); + } +}); + +// The public record. Cache lightly; the settle pass updates rows a few +// times a day, not per-second. +router.get('/:handle', async (req, res) => { + const handle = String(req.params.handle || '').trim().toLowerCase(); + // Invalid shape can't exist (DB CHECK) → same 404, no query needed. + if (!HANDLE_RE.test(handle)) return res.status(404).json(NOT_FOUND); + const sb = sbOrNull(); + if (!sb) return res.status(404).json(NOT_FOUND); + try { + const { data: row, error } = await sb.from('public_profiles') + .select('user_id, handle, published') + .eq('handle', handle) + .maybeSingle(); + if (error) throw new Error(error.message); + // Unknown and unpublished are indistinguishable from outside. + if (!row || row.published !== true) return res.status(404).json(NOT_FOUND); + + // Same aggregate machinery as the model record — same window, same + // n≥20 gate — scoped to this user's own rows. + const aggregate = await ledgerService.getModelAggregate({ userId: row.user_id, sb }); + + // ALL settled reads, misses included — nothing curated. + const { data: entries, error: entriesErr } = await sb.from('ledger_entries') + .select(ROW_COLUMNS) + .eq('user_id', row.user_id) + .not('outcome', 'is', null) + .order('graded_at', { ascending: false }) + .limit(ENTRY_LIMIT); + if (entriesErr) throw new Error(entriesErr.message); + + res.set('Cache-Control', 'public, max-age=60'); + return res.json({ + handle: row.handle, + aggregate, + entries: entries || [], + min_sample: ledgerService.MIN_AGG_SAMPLE, + }); + } catch (err) { + console.error('[profiles/handle]', err.message); + return res.status(404).json(NOT_FOUND); + } +}); + +module.exports = router; diff --git a/src/services/ledgerService.js b/src/services/ledgerService.js index 642072d..b32d05e 100644 --- a/src/services/ledgerService.js +++ b/src/services/ledgerService.js @@ -386,6 +386,11 @@ async function countRowsForDate(gameDate, opts = {}) { * 30-day aggregate over the PUBLIC model record (user_id NULL): hit rate, * beat-the-close rate, pending count. Percentages are null below * MIN_AGG_SAMPLE — the UI must show "record building" instead. + * + * A1 Session 10 — `opts.userId` swaps the public `.is('user_id', null)` + * scoping for `.eq('user_id', uid)`: the SAME aggregate (same window, same + * n≥20 gate) over one user's own ledger, powering public profiles. The + * public default is untouched. */ async function getModelAggregate(opts = {}) { const empty = { @@ -400,8 +405,9 @@ async function getModelAggregate(opts = {}) { const since = new Date(nowMs - AGG_WINDOW_DAYS * 24 * 3600 * 1000).toISOString().slice(0, 10); let settledQ = sb.from('ledger_entries') - .select('outcome, clv_result, player_key, grade') - .is('user_id', null) + .select('outcome, clv_result, player_key, grade'); + settledQ = opts.userId ? settledQ.eq('user_id', opts.userId) : settledQ.is('user_id', null); + settledQ = settledQ .not('outcome', 'is', null) .gte('game_date', since) .limit(AGG_FETCH_LIMIT); @@ -412,9 +418,9 @@ async function getModelAggregate(opts = {}) { if (error) return { ...empty, error: error.message }; let pendingQ = sb.from('ledger_entries') - .select('id', { count: 'exact', head: true }) - .is('user_id', null) - .is('outcome', null); + .select('id', { count: 'exact', head: true }); + pendingQ = opts.userId ? pendingQ.eq('user_id', opts.userId) : pendingQ.is('user_id', null); + pendingQ = pendingQ.is('outcome', null); if (opts.sport) pendingQ = pendingQ.eq('sport', String(opts.sport).toLowerCase()); if (opts.playerKey) pendingQ = pendingQ.eq('player_key', opts.playerKey); if (opts.team) pendingQ = pendingQ.eq('team', opts.team); diff --git a/supabase/migrations/022_public_profiles.sql b/supabase/migrations/022_public_profiles.sql new file mode 100644 index 0000000..45e232d --- /dev/null +++ b/supabase/migrations/022_public_profiles.sql @@ -0,0 +1,35 @@ +-- --------------------------------------------------------------- +-- 022 — public_profiles (A1 Session 10, public ledger profiles v1). +-- +-- Stage-3 seed: a user may claim a handle and publish their ENTIRE settled +-- ledger record on a public page — wins and misses. Strava for betting. +-- +-- PRIVACY: PRIVATE BY DEFAULT. `published` defaults false and only flips +-- via one explicit toggle in Settings. The profile API returns the SAME +-- 404 for an unknown handle and an unpublished one (no existence leak). +-- +-- All writes go through the service role (the /api/profiles/me route). +-- Clients only read: published rows (anyone) + their own row (owner). +-- --------------------------------------------------------------- + +CREATE TABLE IF NOT EXISTS public.public_profiles ( + user_id uuid PRIMARY KEY REFERENCES auth.users (id) ON DELETE CASCADE, + handle text UNIQUE NOT NULL CHECK (handle ~ '^[a-z0-9_]{3,20}$'), + published boolean NOT NULL DEFAULT false, + created_at timestamptz NOT NULL DEFAULT now() +); + +ALTER TABLE public.public_profiles ENABLE ROW LEVEL SECURITY; + +-- Anyone (anon + authenticated) reads PUBLISHED profiles only. +CREATE POLICY public_profiles_select_published ON public.public_profiles + FOR SELECT TO anon, authenticated + USING (published = true); + +-- The owner reads their own row (published or not). +CREATE POLICY public_profiles_select_own ON public.public_profiles + FOR SELECT TO authenticated + USING (user_id = auth.uid()); + +-- No INSERT/UPDATE/DELETE policies: client-side writes are impossible. +-- The API writes via the service role, which bypasses RLS. diff --git a/tests/integration/profilesRoutes.test.js b/tests/integration/profilesRoutes.test.js new file mode 100644 index 0000000..5aeb730 --- /dev/null +++ b/tests/integration/profilesRoutes.test.js @@ -0,0 +1,219 @@ +// A1 Session 10 — /api/profiles: claim handle + publish toggle (auth) and the +// public record read. Supabase + auth are mocked (ledgerRoutes.test.js +// pattern); under test: handle validation, 409 on a taken handle, +// private-by-default writes, and the no-existence-leak 404 (unknown and +// unpublished handles are byte-identical). + +const express = require('express'); +const request = require('supertest'); + +jest.mock('../../src/middleware/auth', () => ({ + requireAuth: (req, res, next) => { + if (!req.headers.authorization) return res.status(401).json({ error: 'auth required' }); + req.user = { id: 'u1', tier: 'analyst' }; + return next(); + }, +})); + +// Table-aware Supabase stub. Configure via mockState; every query records +// its filters so scoping is assertable. +const mockState = { + profileRow: null, // what public_profiles maybeSingle resolves to + upsertError: null, + upserts: [], + ledgerRows: [], + filters: [], // [table, filters[]] +}; + +function mockChain(table) { + const b = { _filters: [] }; + const rec = (op) => (...args) => { b._filters.push([op, ...args]); return b; }; + b.select = () => b; + b.eq = rec('eq'); + b.is = rec('is'); + b.not = rec('not'); + b.gte = rec('gte'); + b.order = () => b; + b.maybeSingle = () => { + mockState.filters.push([table, b._filters]); + return Promise.resolve({ data: mockState.profileRow, error: null }); + }; + b.limit = () => { + mockState.filters.push([table, b._filters]); + return Promise.resolve({ data: mockState.ledgerRows, error: null, count: 0 }); + }; + b.then = (resolve, reject) => { + mockState.filters.push([table, b._filters]); + return Promise.resolve({ data: mockState.ledgerRows, error: null, count: 0 }).then(resolve, reject); + }; + b.upsert = (row, opts) => { + mockState.upserts.push({ table, row, opts }); + return Promise.resolve({ error: mockState.upsertError }); + }; + return b; +} + +jest.mock('../../src/utils/supabase', () => ({ + getSupabaseServiceClient: () => ({ from: (table) => mockChain(table) }), +})); + +process.env.SUPABASE_URL = 'https://test.supabase.co'; +process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-key'; + +function mountApp() { + delete require.cache[require.resolve('../../src/routes/profiles')]; + const routes = require('../../src/routes/profiles'); + const app = express(); + app.use(express.json()); + app.use('/api/profiles', routes); + return app; +} + +beforeEach(() => { + mockState.profileRow = null; + mockState.upsertError = null; + mockState.upserts.length = 0; + mockState.ledgerRows.length = 0; + mockState.filters.length = 0; +}); + +describe('GET /api/profiles/me', () => { + test('401 without auth', async () => { + const res = await request(mountApp()).get('/api/profiles/me'); + expect(res.status).toBe(401); + }); + + test('returns the own row scoped to the authenticated user', async () => { + mockState.profileRow = { handle: 'kev', published: false, created_at: '2026-07-10' }; + const res = await request(mountApp()) + .get('/api/profiles/me') + .set('Authorization', 'Bearer t'); + expect(res.status).toBe(200); + expect(res.body.profile).toEqual({ handle: 'kev', published: false, created_at: '2026-07-10' }); + const [table, filters] = mockState.filters[0]; + expect(table).toBe('public_profiles'); + expect(filters).toContainEqual(['eq', 'user_id', 'u1']); + }); + + test('no row yet → profile null (not an error)', async () => { + const res = await request(mountApp()) + .get('/api/profiles/me') + .set('Authorization', 'Bearer t'); + expect(res.status).toBe(200); + expect(res.body.profile).toBeNull(); + }); +}); + +describe('POST /api/profiles/me', () => { + test('401 without auth', async () => { + const res = await request(mountApp()).post('/api/profiles/me').send({ handle: 'kev' }); + expect(res.status).toBe(401); + }); + + test.each(['ab', 'way_too_long_for_a_handle', 'has space', 'bad-dash', 'dot.dot', ''])( + 'rejects invalid handle %j with 400 and writes nothing', + async (handle) => { + const res = await request(mountApp()) + .post('/api/profiles/me') + .set('Authorization', 'Bearer t') + .send({ handle }); + expect(res.status).toBe(400); + expect(mockState.upserts).toHaveLength(0); + }, + ); + + test('upserts own row; PRIVATE BY DEFAULT — published false unless explicitly true', async () => { + const res = await request(mountApp()) + .post('/api/profiles/me') + .set('Authorization', 'Bearer t') + .send({ handle: 'Kev_2026' }); // no published flag at all + expect(res.status).toBe(200); + expect(res.body.profile).toEqual({ handle: 'kev_2026', published: false }); + expect(mockState.upserts).toHaveLength(1); + expect(mockState.upserts[0].table).toBe('public_profiles'); + expect(mockState.upserts[0].row).toEqual({ user_id: 'u1', handle: 'kev_2026', published: false }); + expect(mockState.upserts[0].opts).toEqual({ onConflict: 'user_id' }); + }); + + test('published only flips on an explicit boolean true', async () => { + const res = await request(mountApp()) + .post('/api/profiles/me') + .set('Authorization', 'Bearer t') + .send({ handle: 'kev', published: true }); + expect(res.status).toBe(200); + expect(mockState.upserts[0].row.published).toBe(true); + + // truthy-but-not-true must NOT publish + const res2 = await request(mountApp()) + .post('/api/profiles/me') + .set('Authorization', 'Bearer t') + .send({ handle: 'kev', published: 'yes' }); + expect(res2.status).toBe(200); + expect(mockState.upserts[1].row.published).toBe(false); + }); + + test('handle owned by another user → 409', async () => { + mockState.upsertError = { code: '23505', message: 'duplicate key value violates unique constraint "public_profiles_handle_key"' }; + const res = await request(mountApp()) + .post('/api/profiles/me') + .set('Authorization', 'Bearer t') + .send({ handle: 'taken_one' }); + expect(res.status).toBe(409); + }); +}); + +describe('GET /api/profiles/:handle (public)', () => { + test('published profile → handle + user-scoped aggregate + settled entries', async () => { + mockState.profileRow = { user_id: 'u2', handle: 'kev', published: true }; + mockState.ledgerRows.push({ id: 'r1', player_name: 'Judge', outcome: 'hit', grade: 'A' }); + const res = await request(mountApp()).get('/api/profiles/kev'); + expect(res.status).toBe(200); + expect(res.body.handle).toBe('kev'); + expect(res.body.min_sample).toBe(20); + expect(res.body.aggregate).toBeTruthy(); + expect(res.body.aggregate.hit_pct).not.toBeUndefined(); + expect(Array.isArray(res.body.entries)).toBe(true); + + // Every ledger query is scoped to THAT user, never the public record. + const ledgerQueries = mockState.filters.filter(([t]) => t === 'ledger_entries'); + expect(ledgerQueries.length).toBeGreaterThan(0); + for (const [, filters] of ledgerQueries) { + expect(filters).toContainEqual(['eq', 'user_id', 'u2']); + expect(filters.some((f) => f[0] === 'is' && f[1] === 'user_id')).toBe(false); + } + // The entries list is settled rows only. + const entriesQ = ledgerQueries.find(([, f]) => f.some((x) => x[0] === 'not' && x[1] === 'outcome')); + expect(entriesQ).toBeTruthy(); + }); + + test('NO EXISTENCE LEAK — unknown and unpublished return the identical 404', async () => { + // Unknown handle: no row at all. + mockState.profileRow = null; + const unknown = await request(mountApp()).get('/api/profiles/ghost_handle'); + + // Unpublished handle: row exists, published false. + mockState.profileRow = { user_id: 'u3', handle: 'private_kev', published: false }; + const unpublished = await request(mountApp()).get('/api/profiles/private_kev'); + + expect(unknown.status).toBe(404); + expect(unpublished.status).toBe(404); + expect(unknown.body).toEqual(unpublished.body); + }); + + test('an unpublished profile leaks NO ledger data', async () => { + mockState.profileRow = { user_id: 'u3', handle: 'private_kev', published: false }; + mockState.ledgerRows.push({ id: 'r1', player_name: 'Judge', outcome: 'hit', grade: 'A' }); + const res = await request(mountApp()).get('/api/profiles/private_kev'); + expect(res.status).toBe(404); + expect(res.body.entries).toBeUndefined(); + expect(res.body.aggregate).toBeUndefined(); + // The ledger table was never even queried. + expect(mockState.filters.filter(([t]) => t === 'ledger_entries')).toHaveLength(0); + }); + + test('a malformed handle shape gets the same 404 without touching the database', async () => { + const res = await request(mountApp()).get('/api/profiles/NOT%20A%20HANDLE'); + expect(res.status).toBe(404); + expect(mockState.filters).toHaveLength(0); + }); +}); diff --git a/tests/unit/ledgerAggregateScope.test.js b/tests/unit/ledgerAggregateScope.test.js new file mode 100644 index 0000000..19d791a --- /dev/null +++ b/tests/unit/ledgerAggregateScope.test.js @@ -0,0 +1,70 @@ +// A1 Session 10 — getModelAggregate scoping. The public default MUST stay +// `.is('user_id', null)` (the model record); the new `userId` option swaps +// it for `.eq('user_id', uid)` (a user's own public-profile aggregate). +// Same window, same n≥20 gate in both scopes. + +const ledgerService = require('../../src/services/ledgerService'); + +function makeSb(captured, rows) { + return { + from() { + const b = { _filters: [] }; + const rec = (op) => (...args) => { b._filters.push([op, ...args]); return b; }; + b.select = () => b; + b.eq = rec('eq'); + b.is = rec('is'); + b.not = rec('not'); + b.gte = rec('gte'); + b.order = () => b; + b.limit = () => { captured.push(b._filters); return Promise.resolve({ data: rows, error: null, count: 0 }); }; + b.then = (resolve, reject) => { + captured.push(b._filters); + return Promise.resolve({ data: rows, error: null, count: 2 }).then(resolve, reject); + }; + return b; + }, + }; +} + +describe('getModelAggregate scoping', () => { + test('default (no userId) scopes BOTH queries to the public record (user_id IS NULL)', async () => { + const captured = []; + const agg = await ledgerService.getModelAggregate({ sb: makeSb(captured, []) }); + expect(captured.length).toBe(2); // settled + pending + for (const filters of captured) { + expect(filters).toContainEqual(['is', 'user_id', null]); + expect(filters.some((f) => f[0] === 'eq' && f[1] === 'user_id')).toBe(false); + } + expect(agg.hit_pct).toBeNull(); + expect(agg.min_sample).toBe(ledgerService.MIN_AGG_SAMPLE); + }); + + test('userId scopes BOTH queries to that user and never touches the public scope', async () => { + const captured = []; + await ledgerService.getModelAggregate({ sb: makeSb(captured, []), userId: 'u-42' }); + expect(captured.length).toBe(2); + for (const filters of captured) { + expect(filters).toContainEqual(['eq', 'user_id', 'u-42']); + expect(filters.some((f) => f[0] === 'is' && f[1] === 'user_id')).toBe(false); + } + }); + + test('user scope keeps the n≥20 gate — no percentage on a small sample', async () => { + const rows = Array.from({ length: 5 }, () => ({ outcome: 'hit', clv_result: 'beat', grade: 'A' })); + const agg = await ledgerService.getModelAggregate({ sb: makeSb([], rows), userId: 'u-42' }); + expect(agg.settled).toBe(5); + expect(agg.hit_pct).toBeNull(); + expect(agg.beat_close_pct).toBeNull(); + }); + + test('user scope renders percentages at n≥20 like the public record', async () => { + const rows = [ + ...Array.from({ length: 14 }, () => ({ outcome: 'hit', clv_result: 'beat', grade: 'A' })), + ...Array.from({ length: 7 }, () => ({ outcome: 'miss', clv_result: 'faded', grade: 'B' })), + ]; + const agg = await ledgerService.getModelAggregate({ sb: makeSb([], rows), userId: 'u-42' }); + expect(agg.settled).toBe(21); + expect(agg.hit_pct).toBe(Math.round((14 / 21) * 100)); + expect(agg.beat_close_pct).toBe(Math.round((14 / 21) * 100)); + }); +}); diff --git a/tests/unit/publicProfilePage.test.js b/tests/unit/publicProfilePage.test.js new file mode 100644 index 0000000..47113fd --- /dev/null +++ b/tests/unit/publicProfilePage.test.js @@ -0,0 +1,118 @@ +// A1 Session 10 — public ledger profiles: /u/[handle] page + OG card + +// settings claim/publish UI + proxies + migration. The .tsx surfaces are +// asserted against source (plain-JS Jest, no TS transform) — same pattern as +// vyndrAppShell/socialPreview. + +const fs = require('fs'); +const path = require('path'); + +const ROOT = path.join(__dirname, '..', '..'); +const WEB = path.join(ROOT, 'web', 'src'); +const read = (rel) => fs.readFileSync(path.join(WEB, rel), 'utf8'); +const exists = (rel) => fs.existsSync(path.join(WEB, rel)); + +const routes = require('../../web/src/lib/routes'); + +describe('/u routing — the share surface stays public', () => { + it('never gates /u (a public record must load anonymous)', () => { + expect(routes.isGatedRoute('/u')).toBe(false); + expect(routes.isGatedRoute('/u/kev')).toBe(false); + }); + it('declares /u in OPEN_ROUTES', () => { + expect(routes.OPEN_ROUTES).toContain('/u'); + }); +}); + +describe('/u/[handle] server shell', () => { + const src = read('app/u/[handle]/page.tsx'); + it('carries the CLV-verified metadata title', () => { + expect(src).toContain('CLV-verified record — @'); + expect(src).toContain('· VYNDR'); + }); + it('renders the client record component', () => { + expect(src).toContain('PublicProfile'); + expect(exists('app/u/[handle]/PublicProfile.tsx')).toBe(true); + }); +}); + +describe('/u/[handle] client record', () => { + const src = read('app/u/[handle]/PublicProfile.tsx'); + it('honors the n-gate: RECORD BUILDING under min_sample, never a small-sample %', () => { + expect(src).toContain('RECORD BUILDING'); + expect(src).toMatch(/settled >= minSample/); + }); + it('shows outcome + CLV chips on settled rows (ledger card patterns)', () => { + expect(src).toContain('✓ HIT'); + expect(src).toContain('✕ MISS'); + expect(src).toContain('BEAT CLOSE'); + expect(src).toContain('clv_result'); + }); + it('states the uncurated contract and one not-found state for unknown AND unpublished', () => { + expect(src).toContain('Nothing curated'); + expect(src).toContain('private by default'); + expect(src).toMatch(/notfound/); + }); + it('fetches through the Next proxy (S25 rule)', () => { + expect(src).toContain('/api/profiles/'); + }); +}); + +describe('/u/[handle] OG image', () => { + const og = read('app/u/[handle]/opengraph-image.tsx'); + it('is a 1200x630 PNG record card', () => { + expect(og).toContain('width: 1200, height: 630'); + expect(og).toContain("contentType = 'image/png'"); + expect(og).toContain('PUBLIC LEDGER'); + expect(og).toContain('misses included'); + }); + it('does NOT use the edge runtime (self-hosted standalone, S53 rule)', () => { + expect(og).not.toContain("runtime = 'edge'"); + }); +}); + +describe('settings — claim handle + publish toggle', () => { + const src = read('app/settings/page.tsx'); + it('carries the explicit private-by-default publish copy verbatim', () => { + expect(src).toContain('Publishing puts your ENTIRE settled record on a public page — wins and misses. Private by default.'); + }); + it('reads and writes /api/profiles/me with the bearer token', () => { + expect(src).toContain("fetch('/api/profiles/me'"); + expect(src).toMatch(/method: 'POST'[\s\S]*?\/api\/profiles\/me|\/api\/profiles\/me[\s\S]*?method: 'POST'/); + }); + it('sanitizes the handle input to the API shape (a-z 0-9 _ , max 20)', () => { + expect(src).toContain("replace(/[^a-z0-9_]/g, '')"); + expect(src).toContain('.slice(0, 20)'); + }); +}); + +describe('Next proxies (S25 rule — Express is not browser-reachable)', () => { + it('me proxy forwards GET/POST with Authorization', () => { + const src = read('app/api/profiles/me/route.ts'); + expect(src).toContain('BACKEND_URL'); + expect(src).toContain('/api/profiles/me'); + expect(src).toContain('authorization'); + expect(src).toContain('export async function POST'); + }); + it('handle proxy forwards the public read and passes the 404 through untouched', () => { + const src = read('app/api/profiles/[handle]/route.ts'); + expect(src).toContain('BACKEND_URL'); + expect(src).toContain('/api/profiles/'); + expect(src).toContain('status: upstream.status'); + }); +}); + +describe('migration 022 — public_profiles (committed, applied by the founder)', () => { + const sql = fs.readFileSync(path.join(ROOT, 'supabase', 'migrations', '022_public_profiles.sql'), 'utf8'); + it('creates the table with the handle CHECK + private-by-default published', () => { + expect(sql).toContain('public.public_profiles'); + expect(sql).toContain("handle ~ '^[a-z0-9_]{3,20}$'"); + expect(sql).toMatch(/published\s+boolean NOT NULL DEFAULT false/); + expect(sql).toContain('REFERENCES auth.users'); + }); + it('RLS: published rows readable by anyone, own row by owner, writes service-role only', () => { + expect(sql).toContain('ENABLE ROW LEVEL SECURITY'); + expect(sql).toContain('USING (published = true)'); + expect(sql).toContain('USING (user_id = auth.uid())'); + expect(sql).not.toMatch(/FOR (INSERT|UPDATE|DELETE)/); + }); +}); diff --git a/web/public/sw.js b/web/public/sw.js index 5c7cc9d..1c17784 100644 --- a/web/public/sw.js +++ b/web/public/sw.js @@ -1,2 +1,2 @@ (()=>{"use strict";let e,t,a,s,r,i={googleAnalytics:"googleAnalytics",precache:"precache-v2",prefix:"serwist",runtime:"runtime",suffix:"u">typeof registration?registration.scope:""},n=e=>[i.prefix,e,i.suffix].filter(e=>e&&e.length>0).join("-"),c=e=>e||n(i.precache),o=e=>e||n(i.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 f(e,t,a,s){let r=d(t.url,a);if(t.url===r)return e.match(t,s);let i={...s,ignoreSearch:!0};for(let n of(await e.keys(t,i)))if(r===d(n.url,a))return e.match(n,s)}var p=class{promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}};let m=async()=>{for(let e of u)await e()},w="-precache-",g=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),b=new WeakMap,v=new WeakMap,R=new WeakMap,E={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return b.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return q(e[t])},set:(e,t,a)=>(e[t]=a,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function q(e){if(e instanceof IDBRequest){let t;return t=new Promise((t,a)=>{let s=()=>{e.removeEventListener("success",r),e.removeEventListener("error",i)},r=()=>{t(q(e.result)),s()},i=()=>{a(e.error),s()};e.addEventListener("success",r),e.addEventListener("error",i)}),R.set(t,e),t}if(v.has(e))return v.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(x(this),t),q(this.request)}:function(...t){return q(e.apply(x(this),t))};return(e instanceof IDBTransaction&&function(e){if(b.has(e))return;let t=new Promise((t,a)=>{let s=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",i),e.removeEventListener("abort",i)},r=()=>{t(),s()},i=()=>{a(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",r),e.addEventListener("error",i),e.addEventListener("abort",i)});b.set(e,t)}(e),_(e,s||(s=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])))?new Proxy(e,E):e}(e);return t!==e&&(v.set(e,t),R.set(t,e)),t}let x=e=>R.get(e);function D(e,t,{blocked:a,upgrade:s,blocking:r,terminated:i}={}){let n=indexedDB.open(e,t),c=q(n);return s&&n.addEventListener("upgradeneeded",e=>{s(q(n.result),e.oldVersion,e.newVersion,q(n.transaction),e)}),a&&n.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),c.then(e=>{i&&e.addEventListener("close",()=>i()),r&&e.addEventListener("versionchange",e=>r(e.oldVersion,e.newVersion,e))}).catch(()=>{}),c}let S=["get","getKey","getAll","getAllKeys","count"],k=["put","add","delete","clear"],T=new Map;function P(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t))return;if(T.get(t))return T.get(t);let a=t.replace(/FromIndex$/,""),s=t!==a,r=k.includes(a);if(!(a in(s?IDBIndex:IDBObjectStore).prototype)||!(r||S.includes(a)))return;let i=async function(e,...t){let i=this.transaction(e,r?"readwrite":"readonly"),n=i.store;return s&&(n=n.index(t.shift())),(await Promise.all([n[a](...t),r&&i.done]))[0]};return T.set(t,i),i}E={...e=E,get:(t,a,s)=>P(t,a)||e.get(t,a,s),has:(t,a)=>!!P(t,a)||e.has(t,a)};let C=["continue","continuePrimaryKey","advance"],N={},I=new WeakMap,U=new WeakMap,L={get(e,t){if(!C.includes(t))return e[t];let a=N[t];return a||(a=N[t]=function(...e){I.set(this,U.get(this)[t](...e))}),a}};async function*A(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;let a=new Proxy(t,L);for(U.set(a,t),R.set(a,x(t));t;)yield a,t=await (I.get(a)||t.continue()),I.delete(a)}function O(e,t){return t===Symbol.asyncIterator&&_(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&_(e,[IDBIndex,IDBObjectStore])}E={...t=E,get:(e,a,s)=>O(e,a)?A:t.get(e,a,s),has:(e,a)=>O(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(),i={headers:new Headers(r.headers),status:r.status,statusText:r.statusText},n=t?t(i):i,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,n)},B="requests",K="queueName";var F=class{_db=null;async addEntry(e){let t=(await this.getDb()).transaction(B,"readwrite",{durability:"relaxed"});await t.store.add(e),await t.done}async getFirstEntryId(){return(await (await this.getDb()).transaction(B).store.openCursor())?.value.id}async getAllEntriesByQueueName(e){return await (await this.getDb()).getAllFromIndex(B,K,IDBKeyRange.only(e))||[]}async getEntryCountByQueueName(e){return(await this.getDb()).countFromIndex(B,K,IDBKeyRange.only(e))}async deleteEntry(e){await (await this.getDb()).delete(B,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(B).store.index(K).openCursor(e,t))?.value}async getDb(){return this._db||(this._db=await D("serwist-background-sync",3,{upgrade:this._upgradeDb})),this._db}_upgradeDb(e,t){t>0&&t<3&&e.objectStoreNames.contains(B)&&e.deleteObjectStore(B),e.createObjectStore(B,{autoIncrement:!0,keyPath:"id"}).createIndex(K,K,{unique:!1})}},W=class{_queueName;_queueDb;constructor(e){this._queueName=e,this._queueDb=new F}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 H=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 $="serwist-background-sync",V=new Set,Q=e=>{let t={request:new H(e.requestData).toRequest(),timestamp:e.timestamp};return e.metadata&&(t.metadata=e.metadata),t};var G=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(Q(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 H.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):Q(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(`${$}:${this._name}`)}catch(e){}}_addSyncListener(){"sync"in self.registration&&!this._forceSyncFallback?self.addEventListener("sync",e=>{if(e.tag===`${$}:${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 G(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 p,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 i=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:i,response:e});return e}catch(e){throw r&&await this.runCallbacks("fetchDidFail",{error:e,event:t,originalRequest:r.clone(),request:i.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,i=await this.getCacheKey(a,"read"),n={...r,cacheName:s};for(let e of(t=await caches.match(i,n),this.iterateCallbacks("cachedResponseWillBeUsed")))t=await e({cacheName:s,matchOptions:r,cachedResponse:t,request:i,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:i,matchOptions:n}=this._strategy,c=await self.caches.open(i),o=this.hasCallback("cacheDidUpdate"),u=o?await f(c,s.clone(),["__WB_REVISION__"],n):null;try{await c.put(s,o?r.clone():r)}catch(e){if(e instanceof Error)throw"QuotaExceededError"===e.name&&await m(),e}for(let e of this.iterateCallbacks("cacheDidUpdate"))await e({cacheName:i,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 i of e.iterateCallbacks("handlerDidError"))if(void 0!==(s=await i({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,i;try{r=await e}catch{}try{await t.runCallbacks("handlerDidRespond",{event:s,request:a,response:r}),await t.doneWaiting()}catch(e){e instanceof Error&&(i=e)}if(await t.runCallbacks("handlerDidComplete",{event:s,request:a,response:r,error:i}),t.destroy(),i)throw i}},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:i,promise:n}=this._getTimeoutPromise({request:e,logs:s,handler:t});a=i,r.push(n)}let i=this._getNetworkPromise({timeoutId:a,request:e,logs:s,handler:t});r.push(i);let n=await t.waitUntil((async()=>await t.waitUntil(Promise.race(r))||await i)());if(!n)throw new l("no-response",{url:e.url});return n}_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,i;try{i=await s.fetchAndCachePut(t)}catch(e){e instanceof Error&&(r=e)}return e&&clearTimeout(e),(r||!i)&&(i=await s.cacheMatch(t)),i}},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,i=e.integrity,n=!i||i===r;a=await t.fetch(new Request(e,{integrity:"no-cors"!==e.mode?i||r:void 0})),r&&n&&"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)}},ei=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))}},en=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 i=await a(r.item);t.push({result:i,index:r.index})}},i=Array.from({length:e},()=>new Promise(r));return(await Promise.all(i)).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)),q(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 i=a.value;i.cacheName===this._cacheName&&(e&&i.timestamp=t?(a.delete(),s.push(i.url)):r++),a=await a.continue()}return s}async getDb(){return this._db||(this._db=await D("serwist-expiration",1,{upgrade:this._upgradeDbAndDeleteOldDbs.bind(this)})),this._db}},ef=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 ef(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),i=this._getCacheExpiration(t),n="last-used"===this._config.maxAgeFrom,c=(async()=>{n&&await i.updateTimestamp(a.url),await i.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 em=/^\/(\w+\/)?collect/,ew=({serwist:e,cacheName:t,...a})=>{let s,r,c=t||n(i.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,i=new URL(s.url);try{let e="POST"===s.method?new URLSearchParams(await s.clone().text()):i.searchParams,t=r-(Number(e.get("qt"))||0),n=Date.now()-t;if(e.set("qt",String(n)),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(i.origin+i.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&&em.test(e.pathname),r=new et({plugins:[o]}),"GET"),new es(s,r,"POST")])e.registerRoute(t)};var eg=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}}},ey=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}},e_=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 i=new URL(e,location.href);i.hash="",yield i.href;let n=((e,t=[])=>{for(let a of[...e.searchParams.keys()])t.some(e=>e.test(a))&&e.searchParams.delete(a);return e})(i,a);if(yield n.href,t&&n.pathname.endsWith("/")){let e=new URL(n.href);e.pathname+=t,yield e.href}if(s){let e=new URL(n.href);e.pathname+=".html",yield e.href}if(r)for(let e of r({url:i}))yield e.href}(a.url,t)){let t=s.get(r);if(t)return{cacheKey:t,integrity:e.getIntegrityForPrecacheKey(t)}}},e.precacheStrategy)}},eb=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}},ev=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:n,clientsClaim:o=!1,runtimeCaching:l,offlineAnalyticsConfig:h,disableDevLogs:u=!1,fallbacks:d,requestRules:f}={}){const{precacheStrategyOptions:p,precacheRouteOptions:m,precacheMiscOptions:w}=((e,t={})=>{let{cacheName:a,plugins:s=[],fetchOptions:r,matchOptions:i,fallbackToNetwork:n,directoryIndex:o,ignoreURLParametersMatching:l,cleanURLs:h,urlManipulation:u,cleanupOutdatedCaches:d,concurrency:f=10,navigateFallback:p,navigateFallbackAllowlist:m,navigateFallbackDenylist:w}=t??{};return{precacheStrategyOptions:{cacheName:c(a),plugins:[...s,new eb({precacheController:e})],fetchOptions:r,matchOptions:i,fallbackToNetwork:n},precacheRouteOptions:{directoryIndex:o,ignoreURLParametersMatching:l,cleanURLs:h,urlManipulation:u},precacheMiscOptions:{cleanupOutdatedCaches:d,concurrency:f,navigateFallback:p,navigateFallbackAllowlist:m,navigateFallbackDenylist:w}}})(this,t);if(this._concurrentPrecaching=w.concurrency,this._precacheStrategy=new er(p),this._routes=new Map,this._defaultHandlerMap=new Map,this._requestRules=f,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!==n&&(e=>{var t=e;for(let e of Object.keys(i))(e=>{let a=t[e];"string"==typeof a&&(i[e]=a)})(e)})({prefix:n}),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(g(c(e)).then(e=>{}))})})(p.cacheName),this.registerRoute(new e_(this,m)),w.navigateFallback&&this.registerRoute(new ei(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 eg({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),i=new Request(t,{integrity:s,cache:r,credentials:"same-origin"});await Promise.all(this.precacheStrategy.handleAll({event:e,request:i,url:new URL(i.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 en(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:i,route:n}=this.findMatchingRoute({event:t,request:e,sameOrigin:r,url:s}),c=n?.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:i})}catch(e){a=Promise.reject(e)}let l=n?.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:i})}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 i,n=r.match({url:e,sameOrigin:t,request:a,event:s});if(n)return Array.isArray(i=n)&&0===i.length||n.constructor===Object&&0===Object.keys(n).length?i=void 0:"boolean"==typeof n&&(i=void 0),{route:r,params:i}}return{}}};let eR="/offline",eE=["pages","api-responses","next-static","static-media","fallback","offline-fallback"],eq=[{matcher:({url:e,sameOrigin:t})=>t&&e.pathname.startsWith("/api/"),handler:new ee({cacheName:"api-responses",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:100,maxAgeSeconds:3600})]})},{matcher:({request:e})=>"navigate"===e.mode,handler:new ee({cacheName:"pages",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:50,maxAgeSeconds:86400}),{handlerDidError:async()=>await caches.match(eR)||Response.error()}]})},{matcher:({url:e,sameOrigin:t})=>t&&e.pathname.startsWith("/_next/static/"),handler:new ey({cacheName:"next-static",plugins:[new ep({maxEntries:200,maxAgeSeconds:2592e3})]})},{matcher:({url:e})=>e.pathname.startsWith("/images/")||e.pathname.startsWith("/icons/")||/\.(?:png|jpe?g|gif|svg|webp|ico|woff2?)$/.test(e.pathname),handler:new ey({cacheName:"static-media",plugins:[new ep({maxEntries:100,maxAgeSeconds:2592e3})]})},{matcher:()=>!0,handler:new ee({cacheName:"fallback",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:50,maxAgeSeconds:86400})]})}];new ev({precacheEntries:[{'revision':null,'url':'/_next/static/chunks/1079-304a546a4a673437.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/2004-a5d4899ef0da0bd8.js'},{'revision':null,'url':'/_next/static/chunks/2346-36e36720a5f6591a.js'},{'revision':null,'url':'/_next/static/chunks/4180-ed9d37a89d0dc424.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/7363-209a1a709d8f324d.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-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/_not-found/page-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/about/page-072b5f07665fa274.js'},{'revision':null,'url':'/_next/static/chunks/app/account/page-9300f08c33aa8887.js'},{'revision':null,'url':'/_next/static/chunks/app/admin/page-b3b6af59ae9681bb.js'},{'revision':null,'url':'/_next/static/chunks/app/api/accuracy/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/admin/stats/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/books/%5B...path%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/checkout/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/content/%5B...path%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/gamelines/%5Bsport%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/props/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/tonight/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/hero-prop/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/hotlist/%5Bsport%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/intelligence/feed/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/accuracy/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/lines/%5B...path%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/mlb/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/nba/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/soccer/%5Bleague%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/wnba/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/add-leg/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/calculate/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/grade/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/players/search/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/preferences/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/live/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/most-parlayed/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/top-graded/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/scan/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/schedule/%5Bsport%5D/pitchers/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/schedule/%5Bsport%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/snapshot/%5Bsport%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/cascade/%5Bplayer%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/depth/%5Bteam%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/leaders/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/lineup/%5Bteam%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/parlays-graded/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/player/%5Bname%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/public/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/streaks/%5Bsport%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/team/%5Babbr%5D/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ticker/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/profile/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/recent-scans/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/scans/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/waitlist/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/webhook/nexapay/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/api/welcome-email/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/auth/callback/page-e6df9771a50edb87.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/%5Bslug%5D/page-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/page-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/compare/page-5e631b0c698c6f5f.js'},{'revision':null,'url':'/_next/static/chunks/app/dashboard/page-62cd345aa56e5baa.js'},{'revision':null,'url':'/_next/static/chunks/app/explore/page-8856c642532e2773.js'},{'revision':null,'url':'/_next/static/chunks/app/forgot-password/page-a251f52b4206e8d1.js'},{'revision':null,'url':'/_next/static/chunks/app/game/%5Bid%5D/page-3d020b802c020ad8.js'},{'revision':null,'url':'/_next/static/chunks/app/help/page-03c6534f006d09da.js'},{'revision':null,'url':'/_next/static/chunks/app/intelligence/page-772d69c9ecfe1503.js'},{'revision':null,'url':'/_next/static/chunks/app/invite/page-e1e3f46af5f1e44b.js'},{'revision':null,'url':'/_next/static/chunks/app/layout-03d79648328d9ec1.js'},{'revision':null,'url':'/_next/static/chunks/app/ledger/page-47459e4f664b707a.js'},{'revision':null,'url':'/_next/static/chunks/app/login/page-e75dd5939a169485.js'},{'revision':null,'url':'/_next/static/chunks/app/marketplace/page-cbada49ae96a7527.js'},{'revision':null,'url':'/_next/static/chunks/app/not-found-6cf954604c0add96.js'},{'revision':null,'url':'/_next/static/chunks/app/notifications/page-072b5f07665fa274.js'},{'revision':null,'url':'/_next/static/chunks/app/offline/page-a7a57ff039afc1af.js'},{'revision':null,'url':'/_next/static/chunks/app/onboarding/page-3483923fb16d41ff.js'},{'revision':null,'url':'/_next/static/chunks/app/opengraph-image/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/page-5fcb06eec53c778e.js'},{'revision':null,'url':'/_next/static/chunks/app/player/%5Bname%5D/page-a9a1a22752478255.js'},{'revision':null,'url':'/_next/static/chunks/app/pricing/page-5b9fc1cee887f2d3.js'},{'revision':null,'url':'/_next/static/chunks/app/privacy/page-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/profile/page-d607627acb1b73ab.js'},{'revision':null,'url':'/_next/static/chunks/app/report/page-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/responsible-gambling/page-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/scan/page-fa0499b15c4e8210.js'},{'revision':null,'url':'/_next/static/chunks/app/settings/page-eea60cdbf9380312.js'},{'revision':null,'url':'/_next/static/chunks/app/settings/security/page-697d02aa2d05cf7e.js'},{'revision':null,'url':'/_next/static/chunks/app/signup/page-f429c5ddc836e247.js'},{'revision':null,'url':'/_next/static/chunks/app/soccer/page-5a64e650908111d7.js'},{'revision':null,'url':'/_next/static/chunks/app/team/%5Babbr%5D/page-9ab56fcb07ae8687.js'},{'revision':null,'url':'/_next/static/chunks/app/terminal/page-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/terms/page-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/tracker/page-e23baec2b3735bb1.js'},{'revision':null,'url':'/_next/static/chunks/app/twitter-image/route-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/cancel/page-3702e818a6853705.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/desk/page-b88c47031c7d7d63.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/success/page-ea358cb8f714f1ea.js'},{'revision':null,'url':'/_next/static/chunks/app/verify/page-9df376f065215168.js'},{'revision':null,'url':'/_next/static/chunks/app/welcome/page-259277230533599f.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-7eb567e5889fc982.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/forbidden-7eb567e5889fc982.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-7eb567e5889fc982.js'},{'revision':'846118c33b2c0e922d7b3a7676f81f6f','url':'/_next/static/chunks/polyfills-42372ed130431b0a.js'},{'revision':null,'url':'/_next/static/chunks/webpack-42b9616650231776.js'},{'revision':null,'url':'/_next/static/css/6ee3c69ef5f8952b.css'},{'revision':'cd34c7793d9776838308cfbe5d93922b','url':'/_next/static/media/011e180705008d6f-s.woff2'},{'revision':'324703f03c390d2e2a4f387de85fe63d','url':'/_next/static/media/0aa834ed78bf6d07-s.woff2'},{'revision':'9dda5cfc9a46f256d0e131bb535e46f8','url':'/_next/static/media/19cfc7226ec3afaa-s.woff2'},{'revision':'7de6d31e5076eb437418b6e01998ee12','url':'/_next/static/media/20535187d867b7b9-s.woff2'},{'revision':'4e2553027f1d60eff32898367dd4d541','url':'/_next/static/media/21350d82a1f187e9-s.woff2'},{'revision':'0d11e07b5aaafda6ae2efc53256932ec','url':'/_next/static/media/37786be940ec402b-s.p.woff2'},{'revision':'5de0bff80f9f432b5cf52c1c2f80fe20','url':'/_next/static/media/46e154b2fcbd6033-s.woff2'},{'revision':'6041b3192dc3e1a50141d5d418a24199','url':'/_next/static/media/5356a6a4f2c8c8d8-s.woff2'},{'revision':'f572f7b57d27ec7fd8373961f0b762b0','url':'/_next/static/media/58f386aa6b1a2a92-s.woff2'},{'revision':'e829cbe042e8b2b2e6b99c0eec9e230d','url':'/_next/static/media/656feb427634a431-s.woff2'},{'revision':'54f02056e07c55023315568c637e3a96','url':'/_next/static/media/67957d42bae0796d-s.woff2'},{'revision':'e220ad1849c282590e47db0ff88fc3f3','url':'/_next/static/media/704b853f32d191d5-s.woff2'},{'revision':'662cde3543f3375874e26c26845cec22','url':'/_next/static/media/73cb51aac9c97f90-s.woff2'},{'revision':'afac1fab355fe8db5c2dcaa7623dffb3','url':'/_next/static/media/7ba5fb2a8c88521c-s.woff2'},{'revision':'c94e6e6c23e789fcb0fc60d790c9d2c1','url':'/_next/static/media/886030b0b59bc5a7-s.woff2'},{'revision':'01ba6c2a184b8cba08b0d57167664d75','url':'/_next/static/media/8e9860b6e62d6359-s.woff2'},{'revision':'17a5b2a15bf5647b49cadb9a3bb02e1c','url':'/_next/static/media/92eeb95d069020cc-s.woff2'},{'revision':'4a4e74bed5809194e4bc6538eb1a1e30','url':'/_next/static/media/939c4f875ee75fbb-s.woff2'},{'revision':'6708425c446b05de1c2d471a0eaf4099','url':'/_next/static/media/98e207f02528a563-s.p.woff2'},{'revision':'13dface50f6dc0bff1015561c84119e6','url':'/_next/static/media/991629005c80bdf1-s.woff2'},{'revision':'216ee1a35b060106ed2852cdd8c026c7','url':'/_next/static/media/99dcf268bda04fe5-s.woff2'},{'revision':'9e494903d6b0ffec1a1e14d34427d44d','url':'/_next/static/media/ba9851c3c22cd980-s.woff2'},{'revision':'782150e6836b9b074d1a798807adcb18','url':'/_next/static/media/bb3ef058b751a6ad-s.p.woff2'},{'revision':'027a89e9ab733a145db70f09b8a18b42','url':'/_next/static/media/c5fe6dc8356a8c31-s.woff2'},{'revision':'75fa2e527eaae805bbf44e3378d1232c','url':'/_next/static/media/d26bbd13d6b70f89-s.woff2'},{'revision':'0ba762bde65aaa682fcc089f8c57288e','url':'/_next/static/media/d29838c109ef09b4-s.woff2'},{'revision':'814fe1615d4dbc7bbd92d26a6bda0905','url':'/_next/static/media/d3ebbfd689654d3a-s.p.woff2'},{'revision':'e71a597e376ed91862e822b5a5de8c04','url':'/_next/static/media/db96af6b531dc71f-s.p.woff2'},{'revision':'d54db44de5ccb18886ece2fda72bdfe0','url':'/_next/static/media/df0a9ae256c0569c-s.woff2'},{'revision':'9fb609fe01d739bb9df558e1fba2498e','url':'/_next/static/media/e40af3453d7c920a-s.woff2'},{'revision':'65850a373e258f1c897a2b3d75eb74de','url':'/_next/static/media/e4af272ccee01ff0-s.p.woff2'},{'revision':'de1d49f26130d43f91829088086625f4','url':'/_next/static/media/ef4d5661765d0e49-s.woff2'},{'revision':'0f8d347d49960d05c9430d83e49edeb7','url':'/_next/static/media/f911b923c6adde36-s.woff2'},{'revision':'f782881382efdee04951fb8fda52f691','url':'/_next/static/sQM07bLcPmpiV77YU1Tw5/_buildManifest.js'},{'revision':'b6652df95db52feb4daf4eca35380933','url':'/_next/static/sQM07bLcPmpiV77YU1Tw5/_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':'d692f690fbd1564f090131e02be5ba9c','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("install",e=>{e.waitUntil(caches.open("offline-fallback").then(e=>e.add(eR)).catch(()=>{}))}),self.addEventListener("activate",e=>{e.waitUntil(caches.keys().then(e=>Promise.all(e.filter(e=>!eE.includes(e)&&!e.startsWith("serwist")).map(e=>(console.log("[SW] deleting stale cache:",e),caches.delete(e))))))}),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:i="/",tag:n="vyndr-notification"}=t;e.waitUntil(self.registration.showNotification(a,{body:s,icon:r,badge:"/icons/icon-192.png",tag:n,data:{url:i}}))}),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),i=new Request(t,{integrity:s,cache:r,credentials:"same-origin"});await Promise.all(this.precacheStrategy.handleAll({event:e,request:i,url:new URL(i.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 en(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:i,route:n}=this.findMatchingRoute({event:t,request:e,sameOrigin:r,url:s}),c=n?.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:i})}catch(e){a=Promise.reject(e)}let l=n?.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:i})}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 i,n=r.match({url:e,sameOrigin:t,request:a,event:s});if(n)return Array.isArray(i=n)&&0===i.length||n.constructor===Object&&0===Object.keys(n).length?i=void 0:"boolean"==typeof n&&(i=void 0),{route:r,params:i}}return{}}};let eR="/offline",eE=["pages","api-responses","next-static","static-media","fallback","offline-fallback"],eq=[{matcher:({url:e,sameOrigin:t})=>t&&e.pathname.startsWith("/api/"),handler:new ee({cacheName:"api-responses",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:100,maxAgeSeconds:3600})]})},{matcher:({request:e})=>"navigate"===e.mode,handler:new ee({cacheName:"pages",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:50,maxAgeSeconds:86400}),{handlerDidError:async()=>await caches.match(eR)||Response.error()}]})},{matcher:({url:e,sameOrigin:t})=>t&&e.pathname.startsWith("/_next/static/"),handler:new ey({cacheName:"next-static",plugins:[new ep({maxEntries:200,maxAgeSeconds:2592e3})]})},{matcher:({url:e})=>e.pathname.startsWith("/images/")||e.pathname.startsWith("/icons/")||/\.(?:png|jpe?g|gif|svg|webp|ico|woff2?)$/.test(e.pathname),handler:new ey({cacheName:"static-media",plugins:[new ep({maxEntries:100,maxAgeSeconds:2592e3})]})},{matcher:()=>!0,handler:new ee({cacheName:"fallback",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:50,maxAgeSeconds:86400})]})}];new ev({precacheEntries:[{'revision':'77df4417a679028a5d1c7e2cdf21b2be','url':'/_next/static/Svdsmb6FQN9Zi6U6Z_GV9/_buildManifest.js'},{'revision':'b6652df95db52feb4daf4eca35380933','url':'/_next/static/Svdsmb6FQN9Zi6U6Z_GV9/_ssgManifest.js'},{'revision':null,'url':'/_next/static/chunks/1079-4eabb0cad585bc18.js'},{'revision':null,'url':'/_next/static/chunks/1098-7bedeeccda9aece6.js'},{'revision':null,'url':'/_next/static/chunks/1896-4989a39d80811e5e.js'},{'revision':null,'url':'/_next/static/chunks/1942-bc0755f4a7d5b4a6.js'},{'revision':null,'url':'/_next/static/chunks/1958-56cbbb8dba15fd2f.js'},{'revision':null,'url':'/_next/static/chunks/2346-36e36720a5f6591a.js'},{'revision':null,'url':'/_next/static/chunks/4180-289c7e54afc32311.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/7602.2868ff821d53ee09.js'},{'revision':null,'url':'/_next/static/chunks/8388-dcc9375b89010049.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-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/_not-found/page-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/about/page-d71c2e7fa60ae979.js'},{'revision':null,'url':'/_next/static/chunks/app/account/page-73f3b2070394b584.js'},{'revision':null,'url':'/_next/static/chunks/app/admin/page-37cc78f8c5ff5f0b.js'},{'revision':null,'url':'/_next/static/chunks/app/api/accuracy/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/admin/stats/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/books/%5B...path%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/checkout/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/content/%5B...path%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/desk/pack/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/gamelines/%5Bsport%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/props/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/tonight/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/hero-prop/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/hotlist/%5Bsport%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/intelligence/feed/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/accuracy/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/mine/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/model/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/lines/%5B...path%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/newsletter/subscribe/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/mlb/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/nba/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/soccer/%5Bleague%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/wnba/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/add-leg/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/calculate/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/grade/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/players/search/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/preferences/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/profiles/%5Bhandle%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/profiles/me/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/live/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/most-parlayed/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/top-graded/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/scan/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/schedule/%5Bsport%5D/pitchers/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/schedule/%5Bsport%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/snapshot/%5Bsport%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/snapshot/summary/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/cascade/%5Bplayer%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/depth/%5Bteam%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/leaders/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/lineup/%5Bteam%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/parlays-graded/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/player/%5Bname%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/public/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/streaks/%5Bsport%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/team/%5Babbr%5D/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ticker/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/profile/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/recent-scans/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/scan-meter/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/scans/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/waitlist/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/webhook/nexapay/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/api/welcome-email/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/auth/callback/page-a2c15c101f636b81.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/%5Bslug%5D/page-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/page-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/compare/page-f2d43b7780d1bd31.js'},{'revision':null,'url':'/_next/static/chunks/app/dashboard/page-ab0388fc72f01a2b.js'},{'revision':null,'url':'/_next/static/chunks/app/desk/page-4e4a17bc92323461.js'},{'revision':null,'url':'/_next/static/chunks/app/explore/page-61a50b6020fdea5a.js'},{'revision':null,'url':'/_next/static/chunks/app/forgot-password/page-daec5a9eca2533f8.js'},{'revision':null,'url':'/_next/static/chunks/app/game/%5Bid%5D/page-e7931e081ed05554.js'},{'revision':null,'url':'/_next/static/chunks/app/help/page-9a30b826fa0bac2c.js'},{'revision':null,'url':'/_next/static/chunks/app/intelligence/page-91e2a44c2ed6e42c.js'},{'revision':null,'url':'/_next/static/chunks/app/invite/page-dd722848f9b11a8f.js'},{'revision':null,'url':'/_next/static/chunks/app/layout-d53aa89d3477b22f.js'},{'revision':null,'url':'/_next/static/chunks/app/ledger/page-7f5ca26eaa6fa0ce.js'},{'revision':null,'url':'/_next/static/chunks/app/login/page-1353dedc37818465.js'},{'revision':null,'url':'/_next/static/chunks/app/marketplace/page-a033ff766b054d78.js'},{'revision':null,'url':'/_next/static/chunks/app/methodology/page-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/not-found-50232f7747be762d.js'},{'revision':null,'url':'/_next/static/chunks/app/notifications/page-d71c2e7fa60ae979.js'},{'revision':null,'url':'/_next/static/chunks/app/offline/page-5b1314e64bd5b7e8.js'},{'revision':null,'url':'/_next/static/chunks/app/onboarding/page-25016befabb18d70.js'},{'revision':null,'url':'/_next/static/chunks/app/opengraph-image/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/page-40a0d1e7944c253a.js'},{'revision':null,'url':'/_next/static/chunks/app/player/%5Bname%5D/layout-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/player/%5Bname%5D/opengraph-image/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/player/%5Bname%5D/page-37eb3a826c9ff4ee.js'},{'revision':null,'url':'/_next/static/chunks/app/pricing/page-1d2ec3a54fa294ba.js'},{'revision':null,'url':'/_next/static/chunks/app/privacy/page-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/profile/page-6721366003ffc04e.js'},{'revision':null,'url':'/_next/static/chunks/app/report/page-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/responsible-gambling/page-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/scan/page-8a1f4ccd8888ecf6.js'},{'revision':null,'url':'/_next/static/chunks/app/settings/page-d8293dbd139e721b.js'},{'revision':null,'url':'/_next/static/chunks/app/settings/security/page-e8a5ff0fd5d15c55.js'},{'revision':null,'url':'/_next/static/chunks/app/signup/page-1d70d79337ba0a87.js'},{'revision':null,'url':'/_next/static/chunks/app/soccer/page-7504f5a7f545e561.js'},{'revision':null,'url':'/_next/static/chunks/app/team/%5Babbr%5D/page-930ab2b3711d1467.js'},{'revision':null,'url':'/_next/static/chunks/app/terminal/page-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/terms/page-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/tracker/page-9c9d018594b413aa.js'},{'revision':null,'url':'/_next/static/chunks/app/twitter-image/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/u/%5Bhandle%5D/opengraph-image/route-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/app/u/%5Bhandle%5D/page-c54b4e7169ddc8ab.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/cancel/page-d687298827d08cbb.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/desk/page-ad9f00a3b07988bd.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/success/page-84b715ee6d2e0fcb.js'},{'revision':null,'url':'/_next/static/chunks/app/verify/page-f3cf5026d8b3f599.js'},{'revision':null,'url':'/_next/static/chunks/app/welcome/page-c012f52556ce390d.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-fa1041f45e830136.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/app-error-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/forbidden-131165429e61dc72.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/global-error-2931ac77f014a0eb.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/unauthorized-131165429e61dc72.js'},{'revision':'846118c33b2c0e922d7b3a7676f81f6f','url':'/_next/static/chunks/polyfills-42372ed130431b0a.js'},{'revision':null,'url':'/_next/static/chunks/webpack-42b9616650231776.js'},{'revision':null,'url':'/_next/static/css/6c56eebe3e12b49b.css'},{'revision':'cd34c7793d9776838308cfbe5d93922b','url':'/_next/static/media/011e180705008d6f-s.woff2'},{'revision':'324703f03c390d2e2a4f387de85fe63d','url':'/_next/static/media/0aa834ed78bf6d07-s.woff2'},{'revision':'9dda5cfc9a46f256d0e131bb535e46f8','url':'/_next/static/media/19cfc7226ec3afaa-s.woff2'},{'revision':'7de6d31e5076eb437418b6e01998ee12','url':'/_next/static/media/20535187d867b7b9-s.woff2'},{'revision':'4e2553027f1d60eff32898367dd4d541','url':'/_next/static/media/21350d82a1f187e9-s.woff2'},{'revision':'0d11e07b5aaafda6ae2efc53256932ec','url':'/_next/static/media/37786be940ec402b-s.p.woff2'},{'revision':'5de0bff80f9f432b5cf52c1c2f80fe20','url':'/_next/static/media/46e154b2fcbd6033-s.woff2'},{'revision':'6041b3192dc3e1a50141d5d418a24199','url':'/_next/static/media/5356a6a4f2c8c8d8-s.woff2'},{'revision':'f572f7b57d27ec7fd8373961f0b762b0','url':'/_next/static/media/58f386aa6b1a2a92-s.woff2'},{'revision':'e829cbe042e8b2b2e6b99c0eec9e230d','url':'/_next/static/media/656feb427634a431-s.woff2'},{'revision':'54f02056e07c55023315568c637e3a96','url':'/_next/static/media/67957d42bae0796d-s.woff2'},{'revision':'e220ad1849c282590e47db0ff88fc3f3','url':'/_next/static/media/704b853f32d191d5-s.woff2'},{'revision':'662cde3543f3375874e26c26845cec22','url':'/_next/static/media/73cb51aac9c97f90-s.woff2'},{'revision':'afac1fab355fe8db5c2dcaa7623dffb3','url':'/_next/static/media/7ba5fb2a8c88521c-s.woff2'},{'revision':'c94e6e6c23e789fcb0fc60d790c9d2c1','url':'/_next/static/media/886030b0b59bc5a7-s.woff2'},{'revision':'01ba6c2a184b8cba08b0d57167664d75','url':'/_next/static/media/8e9860b6e62d6359-s.woff2'},{'revision':'17a5b2a15bf5647b49cadb9a3bb02e1c','url':'/_next/static/media/92eeb95d069020cc-s.woff2'},{'revision':'4a4e74bed5809194e4bc6538eb1a1e30','url':'/_next/static/media/939c4f875ee75fbb-s.woff2'},{'revision':'6708425c446b05de1c2d471a0eaf4099','url':'/_next/static/media/98e207f02528a563-s.p.woff2'},{'revision':'13dface50f6dc0bff1015561c84119e6','url':'/_next/static/media/991629005c80bdf1-s.woff2'},{'revision':'216ee1a35b060106ed2852cdd8c026c7','url':'/_next/static/media/99dcf268bda04fe5-s.woff2'},{'revision':'9e494903d6b0ffec1a1e14d34427d44d','url':'/_next/static/media/ba9851c3c22cd980-s.woff2'},{'revision':'782150e6836b9b074d1a798807adcb18','url':'/_next/static/media/bb3ef058b751a6ad-s.p.woff2'},{'revision':'027a89e9ab733a145db70f09b8a18b42','url':'/_next/static/media/c5fe6dc8356a8c31-s.woff2'},{'revision':'75fa2e527eaae805bbf44e3378d1232c','url':'/_next/static/media/d26bbd13d6b70f89-s.woff2'},{'revision':'0ba762bde65aaa682fcc089f8c57288e','url':'/_next/static/media/d29838c109ef09b4-s.woff2'},{'revision':'814fe1615d4dbc7bbd92d26a6bda0905','url':'/_next/static/media/d3ebbfd689654d3a-s.p.woff2'},{'revision':'e71a597e376ed91862e822b5a5de8c04','url':'/_next/static/media/db96af6b531dc71f-s.p.woff2'},{'revision':'d54db44de5ccb18886ece2fda72bdfe0','url':'/_next/static/media/df0a9ae256c0569c-s.woff2'},{'revision':'9fb609fe01d739bb9df558e1fba2498e','url':'/_next/static/media/e40af3453d7c920a-s.woff2'},{'revision':'65850a373e258f1c897a2b3d75eb74de','url':'/_next/static/media/e4af272ccee01ff0-s.p.woff2'},{'revision':'de1d49f26130d43f91829088086625f4','url':'/_next/static/media/ef4d5661765d0e49-s.woff2'},{'revision':'0f8d347d49960d05c9430d83e49edeb7','url':'/_next/static/media/f911b923c6adde36-s.woff2'},{'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':'1cd41b3d92ff160c4635a1ee75bbc34b','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("install",e=>{e.waitUntil(caches.open("offline-fallback").then(e=>e.add(eR)).catch(()=>{}))}),self.addEventListener("activate",e=>{e.waitUntil(caches.keys().then(e=>Promise.all(e.filter(e=>!eE.includes(e)&&!e.startsWith("serwist")).map(e=>(console.log("[SW] deleting stale cache:",e),caches.delete(e))))))}),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:i="/",tag:n="vyndr-notification"}=t;e.waitUntil(self.registration.showNotification(a,{body:s,icon:r,badge:"/icons/icon-192.png",tag:n,data:{url:i}}))}),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/profiles/[handle]/route.ts b/web/src/app/api/profiles/[handle]/route.ts new file mode 100644 index 0000000..cec0bb6 --- /dev/null +++ b/web/src/app/api/profiles/[handle]/route.ts @@ -0,0 +1,31 @@ +import { NextRequest, NextResponse } from 'next/server'; + +export const dynamic = 'force-dynamic'; + +const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000'; + +/** + * Public profile proxy (A1 Session 10) — forwards GET /api/profiles/:handle. + * Express owns the privacy rules: unpublished and unknown handles come back + * as the SAME 404 body (no existence leak) — this proxy passes it through + * untouched. + */ +export async function GET( + req: NextRequest, + { params }: { params: Promise<{ handle: string }> }, +) { + const { handle } = await params; + try { + const upstream = await fetch(`${BACKEND_URL}/api/profiles/${encodeURIComponent(handle)}`, { + headers: { Accept: 'application/json' }, + cache: 'no-store', + }); + const data = await upstream.json().catch(() => ({ error: 'Profile not found' })); + return NextResponse.json(data, { + status: upstream.status, + headers: upstream.ok ? { 'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=120' } : undefined, + }); + } catch { + return NextResponse.json({ error: 'Profile not found' }, { status: 404 }); + } +} diff --git a/web/src/app/api/profiles/me/route.ts b/web/src/app/api/profiles/me/route.ts new file mode 100644 index 0000000..eb7ed9a --- /dev/null +++ b/web/src/app/api/profiles/me/route.ts @@ -0,0 +1,37 @@ +import { NextRequest, NextResponse } from 'next/server'; + +export const dynamic = 'force-dynamic'; + +const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000'; + +/** + * Own-profile proxy (A1 Session 10) — forwards GET/POST /api/profiles/me + * with the caller's Authorization header (Express requireAuth resolves the + * user; the publish toggle + handle claim live behind it). + */ +function authHeaders(req: NextRequest): HeadersInit { + const auth = req.headers.get('authorization'); + return { Accept: 'application/json', 'Content-Type': 'application/json', ...(auth ? { Authorization: auth } : {}) }; +} + +export async function GET(req: NextRequest) { + if (!req.headers.get('authorization')) return NextResponse.json({ profile: null }, { status: 401 }); + try { + const upstream = await fetch(`${BACKEND_URL}/api/profiles/me`, { headers: authHeaders(req), cache: 'no-store' }); + const data = await upstream.json().catch(() => ({ profile: null })); + return NextResponse.json(data, { status: upstream.status }); + } catch { + return NextResponse.json({ profile: null }, { status: 200 }); + } +} + +export async function POST(req: NextRequest) { + const body = await req.text(); + try { + const upstream = await fetch(`${BACKEND_URL}/api/profiles/me`, { method: 'POST', headers: authHeaders(req), body }); + const data = await upstream.json().catch(() => ({})); + return NextResponse.json(data, { status: upstream.status }); + } catch { + return NextResponse.json({ error: 'Profile service unreachable.' }, { status: 502 }); + } +} diff --git a/web/src/app/settings/page.tsx b/web/src/app/settings/page.tsx index 61553ae..ec17d39 100644 --- a/web/src/app/settings/page.tsx +++ b/web/src/app/settings/page.tsx @@ -117,6 +117,54 @@ export default function SettingsPage() { } catch { /* best-effort */ } finally { setPrefSaving(false); } }; + // A1 Session 10 — public ledger profile: claim a handle + the ONE explicit + // publish toggle. PRIVATE BY DEFAULT — nothing is public until the user + // flips the toggle and saves. + const [pfHandle, setPfHandle] = useState(''); + const [pfPublished, setPfPublished] = useState(false); + const [pfSaving, setPfSaving] = useState(false); + const [pfMsg, setPfMsg] = useState<{ ok: boolean; text: string } | null>(null); + const [pfLive, setPfLive] = useState<{ handle: string; published: boolean } | null>(null); + + useEffect(() => { + if (!session?.access_token) return; + fetch('/api/profiles/me', { headers: { Authorization: `Bearer ${session.access_token}` } }) + .then((r) => (r.ok ? r.json() : null)) + .then((d) => { + const p = d?.profile; + if (!p) return; + setPfHandle(p.handle || ''); + setPfPublished(Boolean(p.published)); + setPfLive({ handle: p.handle || '', published: Boolean(p.published) }); + }) + .catch(() => {}); + }, [session]); + + const saveProfile = async () => { + setPfSaving(true); + setPfMsg(null); + try { + const res = await fetch('/api/profiles/me', { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...(session?.access_token ? { Authorization: `Bearer ${session.access_token}` } : {}) }, + body: JSON.stringify({ handle: pfHandle, published: pfPublished }), + }); + const data = await res.json().catch(() => ({})); + if (res.ok) { + setPfLive({ handle: pfHandle, published: pfPublished }); + setPfMsg({ ok: true, text: pfPublished ? 'Published. Your settled record is live.' : 'Saved. Your record stays private.' }); + } else if (res.status === 409) { + setPfMsg({ ok: false, text: 'That handle is taken.' }); + } else { + setPfMsg({ ok: false, text: data?.error || 'Could not save profile.' }); + } + } catch { + setPfMsg({ ok: false, text: 'Network error. Try again.' }); + } finally { + setPfSaving(false); + } + }; + const plan = tierLabel(tier || 'free'); const canDelete = deleteText === 'DELETE'; @@ -231,6 +279,46 @@ export default function SettingsPage() { + {/* PUBLIC PROFILE (A1 Session 10) */} +
+

+ Publishing puts your ENTIRE settled record on a public page — wins and misses. Private by default. +

+
Handle
+
+ vyndr.app/u/ + setPfHandle(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20))} + placeholder="your_handle" + aria-label="Public profile handle" + className="mono" + style={{ width: 200, padding: '9px 12px', borderRadius: 8, background: 'var(--bg-2)', border: '1px solid var(--border-hi)', color: '#fff', fontSize: 13, outline: 'none' }} + /> +
+ +
+
Publish my record
+
Every settled read, nothing curated
+
+ setPfPublished((v) => !v)} /> +
+
+ + {pfMsg && ( + {pfMsg.text} + )} + {pfLive?.published && pfLive.handle && ( + + VIEW PUBLIC PAGE → + + )} +
+
+ {/* NOTIFICATIONS */}
diff --git a/web/src/app/u/[handle]/PublicProfile.tsx b/web/src/app/u/[handle]/PublicProfile.tsx new file mode 100644 index 0000000..a0c38b5 --- /dev/null +++ b/web/src/app/u/[handle]/PublicProfile.tsx @@ -0,0 +1,247 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { GradePill } from '@/components/GradeCard'; + +/** + * PublicProfile (A1 Session 10) — the public ledger record for one handle. + * + * DATA SEMANTICS: every row here is a REAL settled ledger entry — outcome, + * actual value, closing-line value. Nothing curated: publishing shows the + * ENTIRE settled record, misses included. The header NEVER renders a + * percentage under min_sample (20) settles — it shows RECORD BUILDING. + * + * Unknown and unpublished handles arrive as the same 404 — the page renders + * one indistinguishable not-found state for both. + */ + +interface ProfileRow { + id: string; + player_name: string; + sport: string; + stat: string; + line: number; + side: 'over' | 'under'; + locked_odds?: string | null; + book?: string | null; + grade: string; + model_value?: number | null; + game_date: string; + closing_line?: number | null; + clv?: number | null; + clv_result?: 'beat' | 'faded' | 'flat' | null; + outcome?: 'hit' | 'miss' | 'push' | null; + actual_value?: number | null; + revised_from_grade?: string | null; +} + +interface ProfileAggregate { + settled: number; + hits: number; + misses: number; + pushes: number; + hit_pct: number | null; + clv_sample: number; + clv_beat: number; + beat_close_pct: number | null; + pending: number; +} + +interface ProfilePayload { + handle: string; + aggregate: ProfileAggregate | null; + entries: ProfileRow[]; + min_sample?: number; +} + +const SPORT_COLOR: Record = { + nba: '#E94B3C', + mlb: '#1E90FF', + wnba: '#FFB347', + soccer: '#7BC96F', +}; + +export default function PublicProfile({ handle }: { handle: string }) { + const [data, setData] = useState(null); + const [state, setState] = useState<'loading' | 'ready' | 'notfound'>('loading'); + + useEffect(() => { + let active = true; + setState('loading'); + fetch(`/api/profiles/${encodeURIComponent(handle)}`) + .then(async (r) => { + if (!active) return; + if (!r.ok) { setState('notfound'); return; } + const d = await r.json(); + if (!active) return; + setData(d); + setState('ready'); + }) + .catch(() => { if (active) setState('notfound'); }); + return () => { active = false; }; + }, [handle]); + + if (state === 'loading') { + return ( +
+

Loading record…

+
+ ); + } + + if (state === 'notfound' || !data) { + // Same state for unknown AND unpublished — the API never tells us which. + return ( +
+

+ NO RECORD HERE +

+

This profile does not exist or is not published.

+

+ VYNDR ledgers are private by default. A record only appears here when its owner publishes it. +

+
+ ); + } + + const agg = data.aggregate; + const minSample = Number(data.min_sample) > 0 ? Number(data.min_sample) : 20; + + return ( +
+
+

+ PUBLIC LEDGER +

+

+ @{data.handle} +

+

+ Every settled read. Wins and misses. Nothing curated. +

+
+ + {/* Record header — never a percentage under min_sample settles. */} + + + {data.entries.length === 0 ? ( +
+

+ NO SETTLED READS YET +

+

+ Reads land here as they settle against real results. +

+
+ ) : ( +
+ {data.entries.map((row, i) => ( + + ))} +
+ )} +
+ ); +} + +function RecordHeader({ agg, minSample }: { agg: ProfileAggregate | null; minSample: number }) { + const ready = Boolean(agg && agg.settled >= minSample && agg.hit_pct != null); + return ( +
+ {ready && agg ? ( +
+ + RECORD · LAST 30D + + + {agg.hits}-{agg.misses} · {agg.hit_pct}% HIT + + {agg.beat_close_pct != null && ( + + {agg.beat_close_pct}% BEAT CLOSE + + )} + + {agg.pending} pending + +
+ ) : ( +
+

+ RECORD BUILDING +

+

+ Percentages render at {minSample} settled reads. + {agg && ( + + {' '}{agg.settled} settled · {agg.pending} pending + + )} +

+
+ )} +
+ ); +} + +function OutcomeChip({ row }: { row: ProfileRow }) { + if (!row.outcome) { + return PENDING; + } + const color = row.outcome === 'hit' ? 'var(--g-a, #00D4A0)' + : row.outcome === 'miss' ? 'var(--miss, #FF6B6B)' : 'var(--text-secondary)'; + const mark = row.outcome === 'hit' ? '✓ HIT' : row.outcome === 'miss' ? '✕ MISS' : '– PUSH'; + return ( + + {mark}{row.actual_value != null ? ` (${row.actual_value})` : ''} + + ); +} + +function ClvChip({ row }: { row: ProfileRow }) { + if (!row.clv_result || row.clv == null) return null; + const color = row.clv_result === 'beat' ? 'var(--g-a, #00D4A0)' + : row.clv_result === 'faded' ? 'var(--miss, #FF6B6B)' : 'var(--text-tertiary)'; + return ( + + CLV {row.clv > 0 ? '+' : ''}{row.clv} · {row.clv_result.toUpperCase()} + + ); +} + +function ProfileCard({ row, index }: { row: ProfileRow; index: number }) { + const sportColor = SPORT_COLOR[row.sport] || 'var(--text-secondary)'; + return ( +
+
+ + {row.sport.toUpperCase()} + + + {row.revised_from_grade && ( + + {row.revised_from_grade} + + )} + + +
+

{row.player_name}

+

+ {row.side} {row.line} {row.stat.replace(/_/g, ' ')} +

+

+ {row.book || '—'}{row.locked_odds ? ` · ${row.locked_odds}` : ''} · {row.game_date} + {row.model_value != null && · MODEL {row.model_value}} +

+
+ + +
+
+ ); +} diff --git a/web/src/app/u/[handle]/opengraph-image.tsx b/web/src/app/u/[handle]/opengraph-image.tsx new file mode 100644 index 0000000..1473020 --- /dev/null +++ b/web/src/app/u/[handle]/opengraph-image.tsx @@ -0,0 +1,53 @@ +import { ImageResponse } from 'next/og'; + +// A1 Session 10 — every shared /u/:handle link unfurls as a record card. +// Self-hosted standalone build → Node runtime (NOT edge; Session-53 rule — +// next/og breaks under edge off Vercel). +export const alt = 'VYNDR Public Ledger'; +export const size = { width: 1200, height: 630 }; +export const contentType = 'image/png'; + +export default async function Image({ params }: { params: Promise<{ handle: string }> }) { + const { handle } = await params; + const h = decodeURIComponent(handle || '').slice(0, 20).toLowerCase() || 'handle'; + return new ImageResponse( + ( +
+
+
+
+ PUBLIC LEDGER +
+
+ @{h} +
+
+ CLV-verified record · every settled read · misses included +
+
+
+
+ VYND + R +
+
+ NOTHING CURATED · NOTHING DELETED +
+
+
+ ), + { ...size }, + ); +} diff --git a/web/src/app/u/[handle]/page.tsx b/web/src/app/u/[handle]/page.tsx new file mode 100644 index 0000000..05b9917 --- /dev/null +++ b/web/src/app/u/[handle]/page.tsx @@ -0,0 +1,28 @@ +import type { Metadata } from 'next'; +import PublicProfile from './PublicProfile'; + +/** + * /u/[handle] (A1 Session 10) — a user's PUBLIC ledger profile. Thin server + * wrapper for metadata (+ the segment's opengraph-image.tsx share card); + * the record itself renders in the PublicProfile client component. + * + * PUBLIC route — never gated. Publishing is the owner's explicit choice; + * once published, the whole settled record is the page. Misses included. + */ +export async function generateMetadata({ params }: { params: Promise<{ handle: string }> }): Promise { + const { handle } = await params; + const h = decodeURIComponent(handle || '').slice(0, 20).toLowerCase(); + const title = `CLV-verified record — @${h} · VYNDR`; + const description = `@${h}'s settled betting record on VYNDR — every read, every result, closing-line value included. Nothing curated, nothing deleted.`; + return { + title, + description, + openGraph: { title, description }, + twitter: { card: 'summary_large_image', title, description }, + }; +} + +export default async function PublicProfilePage({ params }: { params: Promise<{ handle: string }> }) { + const { handle } = await params; + return ; +} diff --git a/web/src/lib/routes.js b/web/src/lib/routes.js index b41c930..bf0f72b 100644 --- a/web/src/lib/routes.js +++ b/web/src/lib/routes.js @@ -53,6 +53,11 @@ const OPEN_ROUTES = [ '/welcome', '/offline', '/upgrade', + /* A1 Session 10 — public ledger profiles. /u/:handle is the SHARE surface: + it must load anonymous (the whole point is a public record). Publishing + is the owner's explicit opt-in; the privacy gate lives in the API + (unpublished → 404), never in the router. */ + '/u', ]; /* Hash deep-link aliases (§C.3.4). The prototype was a single HTML file using