Session 27: PWA autopilot — NetworkFirst cache policy, stale bucket cleanup, offline fallback, push helper, manifest polish, tier fix (1584 tests)
This commit is contained in:
@@ -24,7 +24,7 @@ export const metadata: Metadata = {
|
||||
template: '%s · VYNDR',
|
||||
},
|
||||
description:
|
||||
"Grade NBA, MLB, WNBA, and soccer props with intelligence the books don't want you to have. World Cup 2026 intelligence: xG regression, altitude, referee, penalty taker. Built in Detroit.",
|
||||
"Grade your props across every sport with intelligence the books don't want you to have. NBA, MLB, WNBA, and soccer today — NFL and more through 2026. World Cup 2026 intelligence: xG regression, altitude, referee, penalty taker. Built in Detroit.",
|
||||
applicationName: 'VYNDR',
|
||||
authors: [{ name: 'VYNDR', url: 'https://vyndr.app' }],
|
||||
manifest: '/manifest.json',
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* Offline fallback (Session 27).
|
||||
*
|
||||
* Served by the service worker's navigation handler when a page request
|
||||
* fails on the network AND misses the runtime cache. Pre-cached on SW
|
||||
* install so it's always available. Kept dependency-free so it renders
|
||||
* with zero network.
|
||||
*/
|
||||
export default function OfflinePage() {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: 'var(--bg-0, #06060B)',
|
||||
color: 'var(--text-0, #F0F0F5)',
|
||||
padding: 24,
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="mono"
|
||||
style={{
|
||||
fontSize: 11,
|
||||
letterSpacing: '0.18em',
|
||||
textTransform: 'uppercase',
|
||||
color: 'var(--grade-a, #00D4A0)',
|
||||
marginBottom: 16,
|
||||
}}
|
||||
>
|
||||
VYNDR
|
||||
</div>
|
||||
<h1 style={{ fontSize: 28, fontWeight: 800, marginBottom: 8, letterSpacing: '-0.02em' }}>
|
||||
You're offline
|
||||
</h1>
|
||||
<p
|
||||
style={{
|
||||
fontSize: 16,
|
||||
color: 'var(--text-secondary, #8A8A9A)',
|
||||
maxWidth: 400,
|
||||
marginBottom: 24,
|
||||
lineHeight: 1.5,
|
||||
}}
|
||||
>
|
||||
Scores and grades will refresh the moment you reconnect. Anything you
|
||||
loaded earlier is still cached and available.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.location.reload()}
|
||||
style={{
|
||||
padding: '12px 24px',
|
||||
background: 'var(--grade-a, #00D4A0)',
|
||||
color: '#06060B',
|
||||
border: 'none',
|
||||
borderRadius: 6,
|
||||
fontWeight: 700,
|
||||
fontSize: 14,
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -85,8 +85,11 @@ export default function ProfilePage() {
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
|
||||
<div>
|
||||
<p className="mono" style={{ fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '0.08em' }}>YOUR TIER</p>
|
||||
<h2 style={{ fontSize: 28, fontWeight: 800, marginTop: 4, textTransform: 'capitalize', color: tierColor(profile.tier) }}>
|
||||
{profile.tier}
|
||||
{/* Session 27 — always render a tier label. When the profile
|
||||
API returns null/undefined tier (free users sometimes do),
|
||||
fall back to 'free' so the field is never blank. */}
|
||||
<h2 style={{ fontSize: 28, fontWeight: 800, marginTop: 4, textTransform: 'capitalize', color: tierColor(profile.tier || 'free') }}>
|
||||
{profile.tier || 'free'}
|
||||
{profile.founder_pricing && (
|
||||
<span
|
||||
className="mono"
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Push notification subscription (Session 27).
|
||||
*
|
||||
* Client-side helpers to request permission and (un)subscribe to Web Push
|
||||
* via the active service worker. The SW already handles incoming `push`
|
||||
* and `notificationclick` events (see web/src/sw.ts); these helpers manage
|
||||
* the browser→push-service subscription handshake.
|
||||
*
|
||||
* VAPID: subscription requires NEXT_PUBLIC_VAPID_PUBLIC_KEY. Until that
|
||||
* key is generated and set (a future session), subscribeToPush returns
|
||||
* null rather than throwing — callers degrade gracefully.
|
||||
*
|
||||
* The resulting PushSubscription is meant to be POSTed to the backend and
|
||||
* stored (Supabase) so the notification trigger system can target it.
|
||||
*/
|
||||
|
||||
/** Browser support check — both SW and PushManager must exist. */
|
||||
export function isPushSupported(): boolean {
|
||||
return (
|
||||
typeof window !== 'undefined' &&
|
||||
'serviceWorker' in navigator &&
|
||||
'PushManager' in window &&
|
||||
'Notification' in window
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* VAPID public keys are base64url; the subscribe API wants a BufferSource.
|
||||
* We return the backing ArrayBuffer so the type is unambiguously
|
||||
* ArrayBuffer (not ArrayBufferLike) for `applicationServerKey`.
|
||||
*/
|
||||
function vapidKeyToBuffer(base64String: string): ArrayBuffer {
|
||||
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
|
||||
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
const raw = window.atob(base64);
|
||||
const buffer = new ArrayBuffer(raw.length);
|
||||
const view = new Uint8Array(buffer);
|
||||
for (let i = 0; i < raw.length; i += 1) view[i] = raw.charCodeAt(i);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request permission and subscribe. Returns the PushSubscription on
|
||||
* success, or null when unsupported / denied / VAPID key missing.
|
||||
*/
|
||||
export async function subscribeToPush(): Promise<PushSubscription | null> {
|
||||
if (!isPushSupported()) return null;
|
||||
|
||||
const vapidKey = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;
|
||||
if (!vapidKey) {
|
||||
console.warn('[push] NEXT_PUBLIC_VAPID_PUBLIC_KEY not set — cannot subscribe yet.');
|
||||
return null;
|
||||
}
|
||||
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission !== 'granted') return null;
|
||||
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
|
||||
// Reuse an existing subscription if the browser already has one.
|
||||
const existing = await registration.pushManager.getSubscription();
|
||||
if (existing) return existing;
|
||||
|
||||
return registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: vapidKeyToBuffer(vapidKey),
|
||||
});
|
||||
}
|
||||
|
||||
/** Unsubscribe the active push subscription, if any. Idempotent. */
|
||||
export async function unsubscribeFromPush(): Promise<boolean> {
|
||||
if (!isPushSupported()) return true;
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
const subscription = await registration.pushManager.getSubscription();
|
||||
if (!subscription) return true;
|
||||
return subscription.unsubscribe();
|
||||
}
|
||||
|
||||
/** Current permission state without prompting — for UI affordances. */
|
||||
export function pushPermission(): NotificationPermission | 'unsupported' {
|
||||
if (!isPushSupported()) return 'unsupported';
|
||||
return Notification.permission;
|
||||
}
|
||||
+137
-8
@@ -1,41 +1,170 @@
|
||||
/// <reference lib="webworker" />
|
||||
/// <reference types="@serwist/next/typings" />
|
||||
|
||||
import { defaultCache } from '@serwist/next/worker';
|
||||
import { Serwist } from 'serwist';
|
||||
import {
|
||||
Serwist,
|
||||
NetworkFirst,
|
||||
CacheFirst,
|
||||
ExpirationPlugin,
|
||||
type RuntimeCaching,
|
||||
} from 'serwist';
|
||||
|
||||
declare const self: ServiceWorkerGlobalScope & {
|
||||
__SW_MANIFEST: (string | { url: string; revision: string | null })[];
|
||||
};
|
||||
|
||||
/**
|
||||
* VYNDR service worker (Session 27 — deployment-aware rewrite).
|
||||
*
|
||||
* The PWA stays — it powers push, offline, fast assets, and installs.
|
||||
* The bug was the CACHE POLICY, not the SW. Sports data is time-
|
||||
* sensitive: a 4-hour-old score is wrong, not stale. So pages + API +
|
||||
* everything-dynamic are NetworkFirst (always fresh, cache only as an
|
||||
* offline fallback). Only content-hashed static assets (which change
|
||||
* URL every build) are CacheFirst.
|
||||
*
|
||||
* skipWaiting + clientsClaim mean a new build takes over on the very
|
||||
* next navigation — no "close all tabs and hard-refresh" ritual.
|
||||
*/
|
||||
|
||||
const OFFLINE_URL = '/offline';
|
||||
|
||||
// The complete set of caches this SW version owns. The activate handler
|
||||
// below deletes anything else (the old defaultCache buckets:
|
||||
// start-url, next-data, apis, pages-rsc, static-js-assets, …) so a
|
||||
// returning user isn't served by a stale bucket from a prior version.
|
||||
const CURRENT_CACHES = [
|
||||
'pages',
|
||||
'api-responses',
|
||||
'next-static',
|
||||
'static-media',
|
||||
'fallback',
|
||||
'offline-fallback',
|
||||
];
|
||||
|
||||
// Navigation NetworkFirst, with a last-resort offline page when both the
|
||||
// network AND the runtime cache miss (e.g. first visit to a never-cached
|
||||
// route while offline).
|
||||
const offlineFallbackPlugin = {
|
||||
handlerDidError: async () => (await caches.match(OFFLINE_URL)) || Response.error(),
|
||||
};
|
||||
|
||||
const runtimeCaching: RuntimeCaching[] = [
|
||||
// API responses — ALWAYS network-first. Schedule, game lines, odds,
|
||||
// streaks must be fresh; the cache is only an offline courtesy.
|
||||
{
|
||||
matcher: ({ url, sameOrigin }) => sameOrigin && url.pathname.startsWith('/api/'),
|
||||
handler: new NetworkFirst({
|
||||
cacheName: 'api-responses',
|
||||
networkTimeoutSeconds: 5,
|
||||
plugins: [new ExpirationPlugin({ maxEntries: 100, maxAgeSeconds: 60 * 60 })],
|
||||
}),
|
||||
},
|
||||
// HTML navigations — network-first so scores/copy are never stale.
|
||||
{
|
||||
matcher: ({ request }) => request.mode === 'navigate',
|
||||
handler: new NetworkFirst({
|
||||
cacheName: 'pages',
|
||||
networkTimeoutSeconds: 5,
|
||||
plugins: [
|
||||
new ExpirationPlugin({ maxEntries: 50, maxAgeSeconds: 24 * 60 * 60 }),
|
||||
offlineFallbackPlugin,
|
||||
],
|
||||
}),
|
||||
},
|
||||
// Next.js content-hashed static JS/CSS — cache-first is safe AND fast:
|
||||
// a new build changes the URL, so old URLs are simply never requested.
|
||||
{
|
||||
matcher: ({ url, sameOrigin }) => sameOrigin && url.pathname.startsWith('/_next/static/'),
|
||||
handler: new CacheFirst({
|
||||
cacheName: 'next-static',
|
||||
plugins: [new ExpirationPlugin({ maxEntries: 200, maxAgeSeconds: 30 * 24 * 60 * 60 })],
|
||||
}),
|
||||
},
|
||||
// Images + fonts — cache-first (slow to change, expensive to refetch).
|
||||
{
|
||||
matcher: ({ url }) =>
|
||||
url.pathname.startsWith('/images/') ||
|
||||
url.pathname.startsWith('/icons/') ||
|
||||
/\.(?:png|jpe?g|gif|svg|webp|ico|woff2?)$/.test(url.pathname),
|
||||
handler: new CacheFirst({
|
||||
cacheName: 'static-media',
|
||||
plugins: [new ExpirationPlugin({ maxEntries: 100, maxAgeSeconds: 30 * 24 * 60 * 60 })],
|
||||
}),
|
||||
},
|
||||
// Everything else (incl. RSC / _next/data payloads) — network-first so
|
||||
// dynamic content stays fresh; cache is offline insurance only.
|
||||
{
|
||||
matcher: () => true,
|
||||
handler: new NetworkFirst({
|
||||
cacheName: 'fallback',
|
||||
networkTimeoutSeconds: 5,
|
||||
plugins: [new ExpirationPlugin({ maxEntries: 50, maxAgeSeconds: 24 * 60 * 60 })],
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
||||
const serwist = new Serwist({
|
||||
precacheEntries: self.__SW_MANIFEST,
|
||||
skipWaiting: true,
|
||||
clientsClaim: true,
|
||||
navigationPreload: true,
|
||||
runtimeCaching: defaultCache,
|
||||
runtimeCaching,
|
||||
});
|
||||
|
||||
serwist.addEventListeners();
|
||||
|
||||
// Web Push handler — fires when the push service delivers a notification.
|
||||
// Pre-cache the offline page so the navigation fallback always has it.
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(
|
||||
caches.open('offline-fallback').then((cache) => cache.add(OFFLINE_URL)).catch(() => {}),
|
||||
);
|
||||
});
|
||||
|
||||
// On activation, delete cache buckets from prior SW versions. We keep our
|
||||
// CURRENT_CACHES and anything Serwist manages (its precache cache is
|
||||
// prefixed `serwist`), and drop the rest — clearing the legacy buckets a
|
||||
// previous deploy left behind so users never get served from them.
|
||||
self.addEventListener('activate', (event) => {
|
||||
event.waitUntil(
|
||||
caches.keys().then((names) =>
|
||||
Promise.all(
|
||||
names
|
||||
.filter((name) => !CURRENT_CACHES.includes(name) && !name.startsWith('serwist'))
|
||||
.map((name) => {
|
||||
console.log('[SW] deleting stale cache:', name);
|
||||
return caches.delete(name);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ---- Web Push (Session 27 keeps the existing handlers) ----
|
||||
// Pushes are emitted server-side by src/services/distribution/webPush.js.
|
||||
self.addEventListener('push', (event) => {
|
||||
if (!event.data) return;
|
||||
let payload: { title?: string; body?: string; icon?: string; url?: string };
|
||||
let payload: { title?: string; body?: string; icon?: string; url?: string; tag?: string };
|
||||
try {
|
||||
payload = event.data.json();
|
||||
} catch {
|
||||
payload = { title: 'VYNDR', body: event.data.text() };
|
||||
}
|
||||
const { title = 'VYNDR', body = '', icon = '/icons/icon-192.png', url = '/' } = payload;
|
||||
const {
|
||||
title = 'VYNDR',
|
||||
body = '',
|
||||
icon = '/icons/icon-192.png',
|
||||
url = '/',
|
||||
tag = 'vyndr-notification',
|
||||
} = payload;
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(title, {
|
||||
body,
|
||||
icon,
|
||||
badge: '/icons/icon-192.png',
|
||||
tag,
|
||||
data: { url },
|
||||
})
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -47,6 +176,6 @@ self.addEventListener('notificationclick', (event) => {
|
||||
const existing = clients.find((c) => c.url.endsWith(url));
|
||||
if (existing) return existing.focus();
|
||||
return self.clients.openWindow(url);
|
||||
})
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user