Files
joke-app/apps/web/src/sw.test.ts
EJClaw 2ed1a7ed33 M9: PWA — 홈 화면에 추가, 오프라인 안내
- 매니페스트·아이콘(192/512/maskable/apple-touch, scripts/pwa-icons.ts로 다시 만들기)
- 손으로 쓴 서비스 워커(apps/web/sw.js): 빌드 때 Vite 플러그인이 빌드 ID를 넣음.
  페이지는 네트워크만(오프라인이면 offline.html), /assets/*만 캐시 먼저(200개까지),
  /api·/ws·/healthz·/internal은 손대지 않음
- 오프라인 안내 페이지, 방 밖에서도 "인터넷 연결이 없어요" 띠
- 홈 아래 "홈 화면에 추가" 카드(설치 버튼, iOS는 공유 메뉴 안내, 닫으면 기억)
- 테스트: apps/web/src/sw.test.ts, e2e/pwa.e2e.ts(E2E_PORT), a11y.e2e.ts도 E2E_PORT 읽기
- 문서: 07 §11, 11 배포(no-cache 대상), README 확인 목록

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:12:23 +09:00

138 lines
6.0 KiB
TypeScript

/** Service worker cache rules (docs/07 §11), run against fake caches/fetch. */
import { beforeEach, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
const ORIGIN = 'https://game.test';
const SRC = readFileSync(join(import.meta.dir, '../sw.js'), 'utf8');
class FakeCache {
map = new Map<string, Response>();
async match(req: { url: string } | string) {
return this.map.get(typeof req === 'string' ? new URL(req, ORIGIN).href : req.url)?.clone();
}
async put(req: { url: string }, res: Response) {
this.map.set(req.url, res);
}
async add(req: Request) {
this.put(req, await net(req));
}
async keys() {
return [...this.map.keys()].map((url) => ({ url }));
}
async delete(req: { url: string }) {
return this.map.delete(req.url);
}
}
let stores: Map<string, FakeCache>;
let net: (req: { url: string }) => Promise<Response>;
let fetched: string[];
let handlers: Record<string, (e: unknown) => void>;
const caches = {
open: async (name: string) => stores.get(name) ?? stores.set(name, new FakeCache()).get(name)!,
keys: async () => [...stores.keys()],
delete: async (name: string) => stores.delete(name),
match: async (req: string, opts: { cacheName: string }) => stores.get(opts.cacheName)?.match(req),
};
const fetchFn = (req: { url: string }) => {
fetched.push(new URL(req.url).pathname);
return net(req);
};
class RelRequest extends Request {
constructor(url: string, init?: RequestInit) {
super(new URL(url, ORIGIN), init);
}
}
beforeEach(() => {
stores = new Map();
fetched = [];
handlers = {};
net = async (req) => new Response(`body of ${new URL(req.url).pathname}`, { headers: { 'Content-Type': 'text/javascript' } });
const self = {
location: new URL(ORIGIN),
addEventListener: (type: string, fn: (e: unknown) => void) => (handlers[type] = fn),
skipWaiting: async () => {},
clients: { claim: async () => {} },
};
new Function('self', 'caches', 'fetch', 'Request', SRC)(self, caches, fetchFn, RelRequest);
});
async function lifecycle(type: 'install' | 'activate') {
const pending: Promise<unknown>[] = [];
handlers[type]!({ waitUntil: (p: Promise<unknown>) => pending.push(p) });
await Promise.all(pending);
}
/** Dispatches a fetch; returns undefined when the worker leaves the request to the browser. */
async function request(path: string, opts: { mode?: string; method?: string; origin?: string } = {}) {
let res: Promise<Response> | undefined;
const pending: Promise<unknown>[] = [];
handlers.fetch!({
request: { url: new URL(path, opts.origin ?? ORIGIN).href, method: opts.method ?? 'GET', mode: opts.mode ?? 'cors' },
respondWith: (p: Promise<Response>) => (res = p),
waitUntil: (p: Promise<unknown>) => pending.push(p),
});
const out = await res;
await Promise.all(pending);
return out;
}
test('install keeps the offline page; activate drops old caches only', async () => {
stores.set('bg-shell-old', new FakeCache());
stores.set('bg-assets-v0', new FakeCache());
stores.set('someone-else', new FakeCache());
await lifecycle('install');
await lifecycle('activate');
const names = [...stores.keys()];
expect(names).toContain('someone-else');
expect(names.filter((n) => n.startsWith('bg-'))).toEqual([expect.stringMatching(/^bg-shell-/)]);
expect(await (await caches.match('/offline.html', { cacheName: names.find((n) => n.startsWith('bg-shell-'))! }))?.text()).toBe('body of /offline.html');
});
test('API, WebSocket, health, internal, non-GET and other origins are never handled', async () => {
await lifecycle('install');
for (const path of ['/api/me', '/api/admin/stats', '/ws', '/healthz', '/internal/metrics']) {
expect(await request(path)).toBeUndefined();
expect(await request(path, { mode: 'navigate' })).toBeUndefined();
}
expect(await request('/assets/a.js', { method: 'POST' })).toBeUndefined();
expect(await request('/assets/a.js', { origin: 'https://cdn.discordapp.com' })).toBeUndefined();
expect([...stores.keys()].filter((n) => n.startsWith('bg-assets'))).toEqual([]);
});
test('pages come from the network and are never cached; offline shows the offline page', async () => {
await lifecycle('install');
net = async () => new Response('<!doctype html>v1', { headers: { 'Content-Type': 'text/html' } });
expect(await (await request('/r/123456', { mode: 'navigate' }))!.text()).toBe('<!doctype html>v1');
net = async () => new Response('<!doctype html>v2', { headers: { 'Content-Type': 'text/html' } });
expect(await (await request('/', { mode: 'navigate' }))!.text()).toBe('<!doctype html>v2');
net = () => Promise.reject(new TypeError('Failed to fetch'));
expect(await (await request('/', { mode: 'navigate' }))!.text()).toBe('body of /offline.html');
expect([...stores.values()].flatMap((c) => [...c.map.keys()]).map((u) => new URL(u).pathname)).toEqual(['/offline.html']);
});
test('hashed assets are cache-first; HTML fallbacks and partial responses are not kept', async () => {
expect(await (await request('/assets/a-1.js'))!.text()).toBe('body of /assets/a-1.js');
expect(await (await request('/assets/a-1.js'))!.text()).toBe('body of /assets/a-1.js');
expect(fetched).toEqual(['/assets/a-1.js']);
net = async () => new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } });
await request('/assets/gone.js');
net = async () => new Response('part', { status: 206, headers: { 'Content-Type': 'audio/mpeg' } });
await request('/assets/s.mp3');
net = async () => new Response('err', { status: 500 });
await request('/assets/b.js');
expect([...stores.get('bg-assets-v1')!.map.keys()].map((u) => new URL(u).pathname)).toEqual(['/assets/a-1.js']);
});
test('asset cache is bounded, oldest out first', async () => {
for (let i = 0; i < 205; i++) await request(`/assets/f${i}.js`);
const kept = [...stores.get('bg-assets-v1')!.map.keys()].map((u) => new URL(u).pathname);
expect(kept.length).toBe(200);
expect(kept[0]).toBe('/assets/f5.js');
expect(kept.at(-1)).toBe('/assets/f204.js');
});