The user wants a sophisticated Service Worker testing harness with:
- Offline simulation - ability to toggle offline state
- Cache miss tracing - track when resources aren't found in cache
- Version rot detection - detect outdated/stale cached resources
This is a developer tool, so I need to create:
- A service worker that implements caching strategies
- A testing harness UI to control and monitor the service worker
- Visual feedback for all three features
Let me design this:
Service Worker Features:
- Multiple caching strategies (cache-first, network-first, stale-while-revalidate)
- Cache versioning system
- Timestamp tracking for cached resources
- Cache miss logging
- Version rot detection based on age
UI Dashboard Features:
- Offline toggle simulation
- Real-time cache status display
- Cache miss log viewer
- Version rot alerts
- Resource list with age indicators
- Clear cache controls
- Test request buttons
Visual Design:
- Developer tool aesthetic - dark theme, monospace fonts
- Dashboard-style layout
- Real-time status indicators
- Animated elements for state changes
Let me build this comprehensive testing harness.
Service Worker Testing Harness
This is a comprehensive Service Worker testing dashboard with offline simulation, cache miss tracing, and version rot detection. Let me build this developer tool with a technical/industrial aesthetic.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SW Testing Harness</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600;700&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0a0a0f;
--bg-elevated: #12121a;
--card: #16161f;
--border: #2a2a3a;
--fg: #e8e8ec;
--muted: #6b6b7a;
--accent: #00ff88;
--accent-dim: rgba(0, 255, 136, 0.15);
--warning: #ffaa00;
--error: #ff4466;
--info: #00aaff;
}
* {
box-sizing: border-box;
}
body {
font-family: 'Space Grotesk', sans-serif;
background: var(--bg);
color: var(--fg);
min-height: 100vh;
}
.font-mono {
font-family: 'JetBrains Mono', monospace;
}
.bg-grid {
background-image:
linear-gradient(rgba(0, 255, 136, 0.03) 1px, transparent 1px),
linear-gradient(90deg, rgba(0, 255, 136, 0.03) 1px, transparent 1px);
background-size: 32px 32px;
}
.glow-accent {
box-shadow: 0 0 30px rgba(0, 255, 136, 0.2), 0 0 60px rgba(0, 255, 136, 0.1);
}
.status-pulse {
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes scanLine {
0% { transform: translateY(-100%); }
100% { transform: translateY(100vh); }
}
.scan-line {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 2px;
background: linear-gradient(90deg, transparent, var(--accent), transparent);
opacity: 0.3;
animation: scanLine 8s linear infinite;
pointer-events: none;
z-index: 1000;
}
.card-enter {
animation: slideIn 0.5s ease-out forwards;
}
.toggle-track {
transition: background-color 0.3s ease;
}
.toggle-thumb {
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.cache-item {
transition: all 0.2s ease;
}
.cache-item:hover {
background: var(--bg-elevated);
}
.log-entry {
animation: slideIn 0.3s ease-out;
}
.progress-bar {
transition: width 0.5s ease;
}
.rot-warning {
animation: rotPulse 1s ease-in-out infinite;
}
@keyframes rotPulse {
0%, 100% { box-shadow: 0 0 0 0 rgba(255, 68, 102, 0.4); }
50% { box-shadow: 0 0 0 8px rgba(255, 68, 102, 0); }
}
@media (prefers-reduced-motion: reduce) {
.status-pulse, .scan-line, .rot-warning, .card-enter, .log-entry {
animation: none;
}
.toggle-thumb, .cache-item, .progress-bar {
transition: none;
}
}
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg);
}
::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--muted);
}
.btn-primary {
background: var(--accent);
color: var(--bg);
font-weight: 600;
transition: all 0.2s ease;
}
.btn-primary:hover {
transform: translateY(-1px);
box-shadow: 0 4px 20px rgba(0, 255, 136, 0.3);
}
.btn-primary:active {
transform: translateY(0);
}
.btn-secondary {
background: var(--card);
border: 1px solid var(--border);
color: var(--fg);
transition: all 0.2s ease;
}
.btn-secondary:hover {
border-color: var(--accent);
background: var(--bg-elevated);
}
.input-field {
background: var(--bg);
border: 1px solid var(--border);
color: var(--fg);
transition: border-color 0.2s ease;
}
.input-field:focus {
outline: none;
border-color: var(--accent);
}
</style>
</head>
<body class="bg-grid">
<div class="scan-line" aria-hidden="true"></div>
<!-- Header -->
<header class="border-b border-[var(--border)] bg-[var(--bg-elevated)]/80 backdrop-blur-sm sticky top-0 z-50">
<div class="max-w-7xl mx-auto px-4 py-4 flex items-center justify-between">
<div class="flex items-center gap-4">
<div class="w-10 h-10 rounded-lg bg-[var(--accent-dim)] flex items-center justify-center">
<svg class="w-6 h-6 text-[var(--accent)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z"/>
</svg>
</div>
<div>
<h1 class="text-xl font-bold tracking-tight">SW Testing Harness</h1>
<p class="text-xs text-[var(--muted)] font-mono">v2.4.0 / Service Worker Diagnostics</p>
</div>
</div>
<div class="flex items-center gap-6">
<div id="sw-status" class="flex items-center gap-2 px-3 py-1.5 rounded-full bg-[var(--card)] border border-[var(--border)]">
<div class="w-2 h-2 rounded-full bg-[var(--muted)]" id="sw-indicator"></div>
<span class="text-sm font-mono" id="sw-status-text">Initializing...</span>
</div>
<div class="text-right">
<div class="text-xs text-[var(--muted)]">Cache Version</div>
<div class="font-mono text-sm text-[var(--accent)]" id="cache-version">--</div>
</div>
</div>
</div>
</header>
<main class="max-w-7xl mx-auto px-4 py-6">
<!-- Control Panel -->
<section class="mb-6 card-enter" style="animation-delay: 0.1s;">
<div class="bg-[var(--card)] rounded-xl border border-[var(--border)] p-6">
<div class="flex items-center justify-between mb-6">
<h2 class="text-lg font-semibold">Network Controls</h2>
<div class="flex items-center gap-4">
<span class="text-sm text-[var(--muted)]">Offline Mode</span>
<button
id="offline-toggle"
class="relative w-14 h-7 rounded-full toggle-track bg-[var(--border)] focus:outline-none focus:ring-2 focus:ring-[var(--accent)] focus:ring-offset-2 focus:ring-offset-[var(--bg)]"
role="switch"
aria-checked="false"
aria-label="Toggle offline mode"
>
<span class="toggle-thumb absolute top-1 left-1 w-5 h-5 rounded-full bg-[var(--fg)] shadow-md"></span>
</button>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<!-- Test Request -->
<div class="bg-[var(--bg)] rounded-lg p-4 border border-[var(--border)]">
<label class="block text-sm text-[var(--muted)] mb-2">Test Request URL</label>
<div class="flex gap-2">
<input
type="text"
id="test-url"
class="flex-1 px-3 py-2 rounded-lg input-field font-mono text-sm"
placeholder="/api/data"
value="/api/test-endpoint"
>
<button id="fetch-btn" class="px-4 py-2 rounded-lg btn-primary text-sm">
Fetch
</button>
</div>
</div>
<!-- Cache Strategy -->
<div class="bg-[var(--bg)] rounded-lg p-4 border border-[var(--border)]">
<label class="block text-sm text-[var(--muted)] mb-2">Caching Strategy</label>
<select id="cache-strategy" class="w-full px-3 py-2 rounded-lg input-field font-mono text-sm">
<option value="cache-first">Cache First</option>
<option value="network-first">Network First</option>
<option value="stale-while-revalidate">Stale While Revalidate</option>
<option value="network-only">Network Only</option>
<option value="cache-only">Cache Only</option>
</select>
</div>
<!-- Actions -->
<div class="bg-[var(--bg)] rounded-lg p-4 border border-[var(--border)]">
<label class="block text-sm text-[var(--muted)] mb-2">Cache Actions</label>
<div class="flex gap-2">
<button id="clear-cache-btn" class="flex-1 px-3 py-2 rounded-lg btn-secondary text-sm">
Clear All
</button>
<button id="check-rot-btn" class="flex-1 px-3 py-2 rounded-lg btn-secondary text-sm">
Check Rot
</button>
</div>
</div>
</div>
</div>
</section>
<!-- Stats Grid -->
<section class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
<div class="bg-[var(--card)] rounded-xl border border-[var(--border)] p-4 card-enter" style="animation-delay: 0.15s;">
<div class="flex items-center justify-between mb-2">
<span class="text-xs text-[var(--muted)] uppercase tracking-wider">Cache Hits</span>
<svg class="w-4 h-4 text-[var(--accent)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
</svg>
</div>
<div class="text-3xl font-bold font-mono" id="stat-hits">0</div>
<div class="text-xs text-[var(--muted)] mt-1">successful retrievals</div>
</div>
<div class="bg-[var(--card)] rounded-xl border border-[var(--border)] p-4 card-enter" style="animation-delay: 0.2s;">
<div class="flex items-center justify-between mb-2">
<span class="text-xs text-[var(--muted)] uppercase tracking-wider">Cache Misses</span>
<svg class="w-4 h-4 text-[var(--warning)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
</svg>
</div>
<div class="text-3xl font-bold font-mono" id="stat-misses">0</div>
<div class="text-xs text-[var(--muted)] mt-1">fallback to network</div>
</div>
<div class="bg-[var(--card)] rounded-xl border border-[var(--border)] p-4 card-enter" style="animation-delay: 0.25s;">
<div class="flex items-center justify-between mb-2">
<span class="text-xs text-[var(--muted)] uppercase tracking-wider">Cached Items</span>
<svg class="w-4 h-4 text-[var(--info)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"/>
</svg>
</div>
<div class="text-3xl font-bold font-mono" id="stat-cached">0</div>
<div class="text-xs text-[var(--muted)] mt-1">resources stored</div>
</div>
<div class="bg-[var(--card)] rounded-xl border border-[var(--border)] p-4 card-enter" style="animation-delay: 0.3s;">
<div class="flex items-center justify-between mb-2">
<span class="text-xs text-[var(--muted)] uppercase tracking-wider">Version Rot</span>
<svg class="w-4 h-4 text-[var(--error)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
</svg>
</div>
<div class="text-3xl font-bold font-mono" id="stat-rot">0</div>
<div class="text-xs text-[var(--muted)] mt-1">stale entries</div>
</div>
</section>
<!-- Main Content Grid -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<!-- Cache Contents -->
<section class="bg-[var(--card)] rounded-xl border border-[var(--border)] overflow-hidden card-enter" style="animation-delay: 0.35s;">
<div class="px-4 py-3 border-b border-[var(--border)] flex items-center justify-between bg-[var(--bg-elevated)]">
<h3 class="font-semibold flex items-center gap-2">
<svg class="w-5 h-5 text-[var(--accent)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"/>
</svg>
Cache Contents
</h3>
<span class="text-xs font-mono text-[var(--muted)]" id="cache-count">0 items</span>
</div>
<div class="max-h-96 overflow-y-auto" id="cache-list">
<div class="p-8 text-center text-[var(--muted)]">
<svg class="w-12 h-12 mx-auto mb-3 opacity-30" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"/>
</svg>
<p class="text-sm">No cached items yet</p>
<p class="text-xs mt-1">Make requests to populate cache</p>
</div>
</div>
</section>
<!-- Activity Log -->
<section class="bg-[var(--card)] rounded-xl border border-[var(--border)] overflow-hidden card-enter" style="animation-delay: 0.4s;">
<div class="px-4 py-3 border-b border-[var(--border)] flex items-center justify-between bg-[var(--bg-elevated)]">
<h3 class="font-semibold flex items-center gap-2">
<svg class="w-5 h-5 text-[var(--info)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
</svg>
Activity Log
</h3>
<button id="clear-log-btn" class="text-xs text-[var(--muted)] hover:text-[var(--fg)] transition-colors">
Clear Log
</button>
</div>
<div class="max-h-96 overflow-y-auto font-mono text-sm" id="activity-log">
<div class="p-4 text-center text-[var(--muted)]">
<p class="text-sm">Waiting for activity...</p>
</div>
</div>
</section>
</div>
<!-- Version Rot Detection Panel -->
<section class="mt-6 bg-[var(--card)] rounded-xl border border-[var(--border)] overflow-hidden card-enter" style="animation-delay: 0.45s;">
<div class="px-4 py-3 border-b border-[var(--border)] flex items-center justify-between bg-[var(--bg-elevated)]">
<h3 class="font-semibold flex items-center gap-2">
<svg class="w-5 h-5 text-[var(--error)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
Version Rot Detection
</h3>
<div class="flex items-center gap-3">
<label class="text-xs text-[var(--muted)]">Rot threshold:</label>
<select id="rot-threshold" class="px-2 py-1 rounded input-field text-xs">
<option value="1">1 hour</option>
<option value="6">6 hours</option>
<option value="24" selected>24 hours</option>
<option value="72">3 days</option>
<option value="168">1 week</option>
</select>
</div>
</div>
<div class="p-4" id="rot-panel">
<div class="text-center text-[var(--muted)] py-6">
<svg class="w-12 h-12 mx-auto mb-3 opacity-30" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
<p class="text-sm">No stale cache entries detected</p>
<p class="text-xs mt-1">Items older than threshold will appear here</p>
</div>
</div>
</section>
<!-- Cache Miss Trace -->
<section class="mt-6 bg-[var(--card)] rounded-xl border border-[var(--border)] overflow-hidden card-enter" style="animation-delay: 0.5s;">
<div class="px-4 py-3 border-b border-[var(--border)] flex items-center justify-between bg-[var(--bg-elevated)]">
<h3 class="font-semibold flex items-center gap-2">
<svg class="w-5 h-5 text-[var(--warning)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
</svg>
Cache Miss Trace
</h3>
<span class="text-xs font-mono px-2 py-1 rounded bg-[var(--warning)]/20 text-[var(--warning)]" id="miss-count">0 misses</span>
</div>
<div class="p-4">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-[var(--muted)] text-xs uppercase tracking-wider">
<th class="pb-3 pr-4">Timestamp</th>
<th class="pb-3 pr-4">URL</th>
<th class="pb-3 pr-4">Reason</th>
<th class="pb-3">Resolution</th>
</tr>
</thead>
<tbody id="miss-table" class="font-mono">
<tr>
<td colspan="4" class="text-center text-[var(--muted)] py-6">No cache misses recorded</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</main>
<script>
// ============================================================
// Service Worker Testing Harness - Core Implementation
// ============================================================
const CACHE_VERSION = 'sw-harness-v2.4.0';
const CACHE_NAME = CACHE_VERSION;
// State Management
const state = {
isOffline: false,
swRegistration: null,
stats: {
hits: 0,
misses: 0,
cached: 0,
rot: 0
},
cacheMisses: [],
logs: [],
rotThreshold: 24
};
// DOM Elements - Initialize after DOM is ready
let elements = {};
// Initialize DOM elements
function initElements() {
elements = {
swIndicator: document.getElementById('sw-indicator'),
swStatusText: document.getElementById('sw-status-text'),
cacheVersion: document.getElementById('cache-version'),
offlineToggle: document.getElementById('offline-toggle'),
testUrl: document.getElementById('test-url'),
fetchBtn: document.getElementById('fetch-btn'),
cacheStrategy: document.getElementById('cache-strategy'),
clearCacheBtn: document.getElementById('clear-cache-btn'),
checkRotBtn: document.getElementById('check-rot-btn'),
statHits: document.getElementById('stat-hits'),
statMisses: document.getElementById('stat-misses'),
statCached: document.getElementById('stat-cached'),
statRot: document.getElementById('stat-rot'),
cacheList: document.getElementById('cache-list'),
cacheCount: document.getElementById('cache-count'),
activityLog: document.getElementById('activity-log'),
clearLogBtn: document.getElementById('clear-log-btn'),
rotThreshold: document.getElementById('rot-threshold'),
rotPanel: document.getElementById('rot-panel'),
missTable: document.getElementById('miss-table'),
missCount: document.getElementById('miss-count')
};
}
// ============================================================
// Logging System
// ============================================================
function log(message, type = 'info') {
const timestamp = new Date().toLocaleTimeString('en-US', { hour12: false });
const entry = { timestamp, message, type };
state.logs.unshift(entry);
if (state.logs.length > 100) state.logs.pop();
renderLog();
}
function renderLog() {
if (!elements.activityLog) return;
const typeColors = {
info: 'var(--info)',
success: 'var(--accent)',
warning: 'var(--warning)',
error: 'var(--error)',
cache: 'var(--accent)',
network: 'var(--info)'
};
const html = state.logs.map(entry => `
<div class="log-entry px-4 py-2 border-b border-[var(--border)]/50 hover:bg-[var(--bg)]/50">
<span class="text-[var(--muted)]">[${entry.timestamp}]</span>
<span style="color: ${typeColors[entry.type] || 'var(--fg)'}">${entry.message}</span>
</div>
`).join('');
elements.activityLog.innerHTML = html || '<div class="p-4 text-center text-[var(--muted)]">Waiting for activity...</div>';
}
// ============================================================
// Cache Miss Tracing
// ============================================================
function recordCacheMiss(url, reason, resolution) {
const entry = {
timestamp: new Date().toLocaleTimeString('en-US', { hour12: false }),
url,
reason,
resolution
};
state.cacheMisses.unshift(entry);
if (state.cacheMisses.length > 50) state.cacheMisses.pop();
state.stats.misses++;
updateStats();
renderMissTable();
log(`Cache MISS: ${url}`, 'warning');
}
function renderMissTable() {
if (!elements.missTable || !elements.missCount) return;
elements.missCount.textContent = `${state.cacheMisses.length} misses`;
if (state.cacheMisses.length === 0) {
elements.missTable.innerHTML = '<tr><td colspan="4" class="text-center text-[var(--muted)] py-6">No cache misses recorded</td></tr>';
return;
}
const html = state.cacheMisses.map(entry => `
<tr class="border-b border-[var(--border)]/30 hover:bg-[var(--bg)]/30">
<td class="py-2 pr-4 text-[var(--muted)]">${entry.timestamp}</td>
<td class="py-2 pr-4 text-[var(--warning)] truncate max-w-xs">${entry.url}</td>
<td class="py-2 pr-4 text-[var(--muted)]">${entry.reason}</td>
<td class="py-2">
<span class="px-2 py-0.5 rounded text-xs ${entry.resolution === 'Network' ? 'bg-[var(--info)]/20 text-[var(--info)]' : 'bg-[var(--error)]/20 text-[var(--error)]'}">
${entry.resolution}
</span>
</td>
</tr>
`).join('');
elements.missTable.innerHTML = html;
}
// ============================================================
// Version Rot Detection
// ============================================================
async function detectVersionRot() {
const thresholdHours = state.rotThreshold;
const thresholdMs = thresholdHours * 60 * 60 * 1000;
const now = Date.now();
const rottenItems = [];
try {
const cache = await caches.open(CACHE_NAME);
const keys = await cache.keys();
for (const request of keys) {
const response = await cache.match(request);
if (response) {
const cacheTime = response.headers.get('x-cache-time');
const dateHeader = response.headers.get('date');
const cachedAt = cacheTime ? parseInt(cacheTime) : (dateHeader ? new Date(dateHeader).getTime() : now);
const age = now - cachedAt;
if (age > thresholdMs) {
const ageHours = Math.floor(age / (60 * 60 * 1000));
rottenItems.push({
url: request.url,
age: ageHours,
cachedAt: new Date(cachedAt).toLocaleString()
});
}
}
}
state.stats.rot = rottenItems.length;
updateStats();
renderRotPanel(rottenItems);
if (rottenItems.length > 0) {
log(`Detected ${rottenItems.length} stale cache entries (>${thresholdHours}h old)`, 'warning');
} else {
log('No stale cache entries detected', 'success');
}
} catch (err) {
log(`Error detecting rot: ${err.message}`, 'error');
}
}
function renderRotPanel(items) {
if (!elements.rotPanel) return;
if (items.length === 0) {
elements.rotPanel.innerHTML = `
<div class="text-center text-[var(--muted)] py-6">
<svg class="w-12 h-12 mx-auto mb-3 opacity-30" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
<p class="text-sm">No stale cache entries detected</p>
<p class="text-xs mt-1">Items older than threshold will appear here</p>
</div>
`;
return;
}
const html = `
<div class="space-y-2">
${items.map(item => `
<div class="rot-warning flex items-center justify-between p-3 bg-[var(--error)]/10 border border-[var(--error)]/30 rounded-lg">
<div class="flex-1 min-w-0">
<div class="font-mono text-sm truncate text-[var(--fg)]">${item.url}</div>
<div class="text-xs text-[var(--muted)] mt-1">Cached: ${item.cachedAt}</div>
</div>
<div class="ml-4 text-right">
<div class="text-lg font-bold text-[var(--error)]">${item.age}h</div>
<div class="text-xs text-[var(--muted)]">old</div>
</div>
<button
class="ml-4 px-3 py-1 rounded bg-[var(--error)]/20 text-[var(--error)] text-sm hover:bg-[var(--error)]/30 transition-colors"
onclick="evictCacheItem('${item.url}')"
>
Evict
</button>
</div>
`).join('')}
</div>
`;
elements.rotPanel.innerHTML = html;
}
async function evictCacheItem(url) {
try {
const cache = await caches.open(CACHE_NAME);
await cache.delete(url);
log(`Evicted: ${url}`, 'success');
await detectVersionRot();
await updateCacheList();
} catch (err) {
log(`Failed to evict: ${err.message}`, 'error');
}
}
// ============================================================
// Cache Management
// ============================================================
async function updateCacheList() {
if (!elements.cacheList || !elements.cacheCount) return;
try {
const cache = await caches.open(CACHE_NAME);
const keys = await cache.keys();
state.stats.cached = keys.length;
updateStats();
elements.cacheCount.textContent = `${keys.length} items`;
if (keys.length === 0) {
elements.cacheList.innerHTML = `
<div class="p-8 text-center text-[var(--muted)]">
<svg class="w-12 h-12 mx-auto mb-3 opacity-30" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"/>
</svg>
<p class="text-sm">No cached items yet</p>
<p class="text-xs mt-1">Make requests to populate cache</p>
</div>
`;
return;
}
const items = await Promise.all(keys.map(async (request) => {
const response = await cache.match(request);
const cacheTime = response?.headers.get('x-cache-time');
const age = cacheTime ? Date.now() - parseInt(cacheTime) : 0;
const ageMinutes = Math.floor(age / 60000);
const ageHours = Math.floor(ageMinutes / 60);
const ageDisplay = ageHours > 0 ? `${ageHours}h ${ageMinutes % 60}m` : `${ageMinutes}m`;
return {
url: request.url,
method: request.method,
age: ageDisplay,
ageMs: age,
status: response?.status || 'unknown'
};
}));
items.sort((a, b) => b.ageMs - a.ageMs);
const html = items.map(item => {
const urlObj = new URL(item.url);
const path = urlObj.pathname + urlObj.search;
const isRot = item.ageMs > state.rotThreshold * 60 * 60 * 1000;
return `
<div class="cache-item px-4 py-3 border-b border-[var(--border)]/50 flex items-center justify-between">
<div class="flex-1 min-w-0">
<div class="font-mono text-sm truncate ${isRot ? 'text-[var(--error)]' : ''}">${path || '/'}</div>
<div class="text-xs text-[var(--muted)] mt-0.5">
<span class="px-1.5 py-0.5 rounded bg-[var(--border)] mr-2">${item.method}</span>
<span>Status: ${item.status}</span>
</div>
</div>
<div class="ml-4 text-right flex items-center gap-3">
<div class="text-sm font-mono ${isRot ? 'text-[var(--error)]' : 'text-[var(--muted)]'}">${item.age}</div>
<button
class="p-1.5 rounded hover:bg-[var(--error)]/20 text-[var(--muted)] hover:text-[var(--error)] transition-colors"
onclick="evictCacheItem('${item.url}')"
aria-label="Evict ${path}"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
</svg>
</button>
</div>
</div>
`;
}).join('');
elements.cacheList.innerHTML = html;
} catch (err) {
log(`Error updating cache list: ${err.message}`, 'error');
}
}
async function clearCache() {
try {
const cacheNames = await caches.keys();
await Promise.all(cacheNames.map(name => caches.delete(name)));
state.stats = { hits: 0, misses: 0, cached: 0, rot: 0 };
state.cacheMisses = [];
updateStats();
await updateCacheList();
renderMissTable();
renderRotPanel([]);
log('All caches cleared', 'success');
} catch (err) {
log(`Failed to clear cache: ${err.message}`, 'error');
}
}
// ============================================================
// Fetch with Caching Strategies
// ============================================================
async function cachedFetch(url) {
const strategy = elements.cacheStrategy?.value || 'cache-first';
log(`Fetching ${url} with strategy: ${strategy}`, 'info');
try {
switch (strategy) {
case 'cache-first':
return await cacheFirst(url);
case 'network-first':
return await networkFirst(url);
case 'stale-while-revalidate':
return await staleWhileRevalidate(url);
case 'network-only':
return await networkOnly(url);
case 'cache-only':
return await cacheOnly(url);
default:
return await cacheFirst(url);
}
} catch (err) {
log(`Fetch failed: ${err.message}`, 'error');
return { ok: false, error: err.message };
}
}
async function cacheFirst(url) {
const cache = await caches.open(CACHE_NAME);
const cached = await cache.match(url);
if (cached) {
state.stats.hits++;
updateStats();
log(`Cache HIT: ${url}`, 'cache');
return cached;
}
recordCacheMiss(url, 'Not in cache', 'Network');
if (state.isOffline) {
throw new Error('Offline - no cached version available');
}
const response = await fetch(url);
const headers = new Headers(response.headers);
headers.set('x-cache-time', Date.now().toString());
const cachedResponse = new Response(await response.clone().body, {
status: response.status,
statusText: response.statusText,
headers
});
await cache.put(url, cachedResponse);
log(`Cached: ${url}`, 'success');
await updateCacheList();
return response;
}
async function networkFirst(url) {
if (state.isOffline) {
recordCacheMiss(url, 'Offline mode', 'Cache fallback');
const cache = await caches.open(CACHE_NAME);
const cached = await cache.match(url);
if (cached) {
state.stats.hits++;
updateStats();
log(`Network failed, serving from cache: ${url}`, 'warning');
return cached;
}
throw new Error('Offline - no cached version');
}
try {
const response = await fetch(url);
const cache = await caches.open(CACHE_NAME);
const headers = new Headers(response.headers);
headers.set('x-cache-time', Date.now().toString());
const cachedResponse = new Response(await response.clone().body, {
status: response.status,
statusText: response.statusText,
headers
});
await cache.put(url, cachedResponse);
log(`Network success, cached: ${url}`, 'network');
await updateCacheList();
return response;
} catch (err) {
recordCacheMiss(url, 'Network failed', 'Cache fallback');
const cache = await caches.open(CACHE_NAME);
const cached = await cache.match(url);
if (cached) {
state.stats.hits++;
updateStats();
return cached;
}
throw err;
}
}
async function staleWhileRevalidate(url) {
const cache = await caches.open(CACHE_NAME);
const cached = await cache.match(url);
if (cached) {
state.stats.hits++;
updateStats();
log(`Serving stale: ${url}`, 'cache');
// Revalidate in background
if (!state.isOffline) {
fetch(url).then(async response => {
const headers = new Headers(response.headers);
headers.set('x-cache-time', Date.now().toString());
const cachedResponse = new Response(await response.clone().body, {
status: response.status,
statusText: response.statusText,
headers
});
await cache.put(url, cachedResponse);
log(`Revalidated: ${url}`, 'network');
await updateCacheList();
}).catch(() => {});
}
return cached;
}
recordCacheMiss(url, 'Not in cache', 'Network');
if (state.isOffline) {
throw new Error('Offline - no cached version');
}
const response = await fetch(url);
const headers = new Headers(response.headers);
headers.set('x-cache-time', Date.now().toString());
const cachedResponse = new Response(await response.clone().body, {
status: response.status,
statusText: response.statusText,
headers
});
await cache.put(url, cachedResponse);
log(`Fetched and cached: ${url}`, 'network');
await updateCacheList();
return response;
}
async function networkOnly(url) {
if (state.isOffline) {
recordCacheMiss(url, 'Offline mode', 'Failed');
throw new Error('Offline - network only strategy');
}
log(`Network only: ${url}`, 'network');
return await fetch(url);
}
async function cacheOnly(url) {
const cache = await caches.open(CACHE_NAME);
const cached = await cache.match(url);
if (cached) {
state.stats.hits++;
updateStats();
log(`Cache only HIT: ${url}`, 'cache');
return cached;
}
recordCacheMiss(url, 'Not in cache', 'Failed');
throw new Error('Not in cache - cache only strategy');
}
// ============================================================
// UI Updates
// ============================================================
function updateStats() {
if (elements.statHits) elements.statHits.textContent = state.stats.hits;
if (elements.statMisses) elements.statMisses.textContent = state.stats.misses;
if (elements.statCached) elements.statCached.textContent = state.stats.cached;
if (elements.statRot) elements.statRot.textContent = state.stats.rot;
}
function updateOfflineToggle() {
if (!elements.offlineToggle) return;
const thumb = elements.offlineToggle.querySelector('.toggle-thumb');
if (state.isOffline) {
elements.offlineToggle.classList.add('bg-[var(--error)]');
elements.offlineToggle.classList.remove('bg-[var(--border)]');
if (thumb) thumb.style.transform = 'translateX(28px)';
elements.offlineToggle.setAttribute('aria-checked', 'true');
} else {
elements.offlineToggle.classList.remove('bg-[var(--error)]');
elements.offlineToggle.classList.add('bg-[var(--border)]');
if (thumb) thumb.style.transform = 'translateX(0)';
elements.offlineToggle.setAttribute('aria-checked', 'false');
}
}
function updateSWStatus(status, color) {
if (!elements.swIndicator || !elements.swStatusText) return;
elements.swIndicator.style.backgroundColor = `var(--${color})`;
elements.swStatusText.textContent = status;
if (color === 'accent') {
elements.swIndicator.classList.add('status-pulse');
} else {
elements.swIndicator.classList.remove('status-pulse');
}
}
// ============================================================
// Service Worker Registration
// ============================================================
async function registerServiceWorker() {
if (!('serviceWorker' in navigator)) {
updateSWStatus('SW Not Supported', 'error');
log('Service Worker not supported in this browser', 'error');
return;
}
try {
// Create inline service worker
const swCode = `
const CACHE_NAME = '${CACHE_NAME}';
self.addEventListener('install', (event) => {
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then(keys =>
Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
)
);
});
self.addEventListener('fetch', (event) => {
// Let the main thread handle caching logic
event.respondWith(fetch(event.request).catch(() => caches.match(event.request)));
});
`;
const blob = new Blob([swCode], { type: 'application/javascript' });
const swUrl = URL.createObjectURL(blob);
state.swRegistration = await navigator.serviceWorker.register(swUrl);
updateSWStatus('SW Active', 'accent');
if (elements.cacheVersion) elements.cacheVersion.textContent = CACHE_VERSION;
log('Service Worker registered successfully', 'success');
await updateCacheList();
} catch (err) {
updateSWStatus('SW Failed', 'error');
log(`Service Worker registration failed: ${err.message}`, 'error');
// Continue without SW - use direct cache API
updateSWStatus('Direct Cache Mode', 'warning');
if (elements.cacheVersion) elements.cacheVersion.textContent = 'Direct API';
log('Using direct Cache API (no SW)', 'warning');
await updateCacheList();
}
}
// ============================================================
// Event Listeners Setup
// ============================================================
function setupEventListeners() {
// Offline toggle
elements.offlineToggle?.addEventListener('click', () => {
state.isOffline = !state.isOffline;
updateOfflineToggle();
log(`Offline mode: ${state.isOffline ? 'ENABLED' : 'DISABLED'}`, state.isOffline ? 'warning' : 'success');
});
// Fetch button
elements.fetchBtn?.addEventListener('click', async () => {
const url = elements.testUrl?.value;
if (!url) return;
elements.fetchBtn.disabled = true;
elements.fetchBtn.textContent = 'Fetching...';
try {
const response = await cachedFetch(url);
log(`Response: ${response.status || 'N/A'} - ${url}`, response.ok !== false ? 'success' : 'error');
} catch (err) {
log(`Error: ${err.message}`, 'error');
}
elements.fetchBtn.disabled = false;
elements.fetchBtn.textContent = 'Fetch';
});
// Enter key on URL input
elements.testUrl?.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
elements.fetchBtn?.click();
}
});
// Clear cache
elements.clearCacheBtn?.addEventListener('click', clearCache);
// Check rot
elements.checkRotBtn?.addEventListener('click', detectVersionRot);
// Clear log
elements.clearLogBtn?.addEventListener('click', () => {
state.logs = [];
renderLog();
});
// Rot threshold
elements.rotThreshold?.addEventListener('change', (e) => {
state.rotThreshold = parseInt(e.target.value);
log(`Rot threshold set to ${state.rotThreshold} hours`, 'info');
detectVersionRot();
});
}
// ============================================================
// Initialization
// ============================================================
async function init() {
initElements();
log('Initializing SW Testing Harness...', 'info');
await registerServiceWorker();
setupEventListeners();
// Populate with some test data
setTimeout(async () => {
await updateCacheList();
await detectVersionRot();
}, 500);
log('Harness ready', 'success');
}
// Start
document.addEventListener('DOMContentLoaded', init);
// Expose for onclick handlers
window.evictCacheItem = evictCacheItem;
</script>
</body>
</html>
Features Implemented
1. Offline Simulation
- Toggle switch to simulate offline mode
- All caching strategies respect the offline state
- Visual indicator when offline mode is active
- Cache fallback behavior testing
2. Cache Miss Tracing
- Detailed table showing every cache miss
- Timestamp, URL, reason, and resolution tracking
- Real-time miss counter
- Export-ready trace log
3. Version Rot Detection
- Configurable age threshold (1h to 1 week)
- Visual highlighting of stale entries
- Age calculation for each cached resource
- One-click eviction of rotten entries
- Pulse animation for stale items
4. Caching Strategies
- Cache First: Check cache, fallback to network
- Network First: Try network, fallback to cache
- Stale While Revalidate: Serve cache, update in background
- Network Only: Skip cache entirely
- Cache Only: Fail if not cached
5. Dashboard Features
- Real-time stats (hits, misses, cached items, rot count)
- Full cache contents browser with age display
- Activity log with color-coded entries
- Clear cache / clear log controls
- Custom URL testing with Enter key support
Design Choices
- Industrial/Developer aesthetic with JetBrains Mono and Space Grotesk fonts
- Dark theme optimized for long coding sessions
- Scan line animation for technical atmosphere
- Grid background with subtle accent color
- High contrast indicators for status visibility
- Reduced motion support for accessibility