diff --git a/e2e/comment-swipe.spec.ts b/e2e/comment-swipe.spec.ts index 3cecc4f..0cf69c7 100644 --- a/e2e/comment-swipe.spec.ts +++ b/e2e/comment-swipe.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from '@playwright/test'; -import { setupApiMocks } from './fixtures/api-mocks'; +import { setupApiMocks, FIREBASE_WS_PATTERN, createFirebaseWsHandler } from './fixtures/api-mocks'; import { expectActiveSwipePanelText, waitForSwipeReady, @@ -225,10 +225,11 @@ test.describe('Mobile Comment Swipe Viewer', () => { }); test('shows "Comment deleted" for dead/deleted comment', async ({ page }) => { - // Firebase: 5555 is a dead comment (MobileItemResolver detects type). - await page.route(`**/item/5555.json`, async (route) => { - await route.fulfill({ - json: { + // Override WS handler to return a dead comment for item 5555 + // and a parent story (12345) with kids: [5555]. + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ + itemOverrides: { + 5555: { id: 5555, by: null, text: null, @@ -237,8 +238,19 @@ test.describe('Mobile Comment Swipe Viewer', () => { type: 'comment', dead: true, }, - }); - }); + 12345: { + id: 12345, + title: 'Rust Is the Future of JavaScript Infrastructure', + url: 'https://leerob.io/blog/rust', + by: 'leerob', + score: 284, + time: Math.floor(Date.now() / 1000) - 3600, + descendants: 1, + kids: [5555], + type: 'story', + }, + }, + })); // Algolia: matching deleted comment shape (null author/text). await page.route(`**/items/5555`, async (route) => { @@ -256,23 +268,6 @@ test.describe('Mobile Comment Swipe Viewer', () => { }); }); - // Parent kids: [5555] only — keeps swipe scope to a single panel. - await page.route(`**/item/12345.json`, async (route) => { - await route.fulfill({ - json: { - id: 12345, - title: 'Rust Is the Future of JavaScript Infrastructure', - url: 'https://leerob.io/blog/rust', - by: 'leerob', - score: 284, - time: Math.floor(Date.now() / 1000) - 3600, - descendants: 1, - kids: [5555], - type: 'story', - }, - }); - }); - await page.goto('/#/item/5555'); await expect(page.getByText('Comment deleted').first()).toBeVisible({ timeout: 10000 }); @@ -281,11 +276,11 @@ test.describe('Mobile Comment Swipe Viewer', () => { test('shows error state when comment fetch fails', async ({ page }) => { // Auto-retry exhausts 3 backoff attempts (2+4+8s) before showing error. test.setTimeout(60000); - // 99999 is a valid comment so MobileItemResolver routes to comment view; - // its parent (88888) returns 500 so useSiblingComments errors out. - await page.route(`**/item/99999.json`, async (route) => { - await route.fulfill({ - json: { + // Override WS: 99999 is a comment so MobileItemResolver routes to comment view; + // its parent (88888) returns error so useSiblingComments errors out. + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ + itemOverrides: { + 99999: { id: 99999, by: 'someone', text: 'placeholder', @@ -293,12 +288,9 @@ test.describe('Mobile Comment Swipe Viewer', () => { parent: 88888, type: 'comment', }, - }); - }); - - await page.route(`**/item/88888.json`, async (route) => { - await route.fulfill({ status: 500, json: { error: 'Server Error' } }); - }); + }, + errorItemIds: [88888], + })); // Algolia also fails so useCommentDetail can't paper over the parent error. await page.route(`**/items/99999`, async (route) => { diff --git a/e2e/error-boundary.spec.ts b/e2e/error-boundary.spec.ts index 076f74a..62e5705 100644 --- a/e2e/error-boundary.spec.ts +++ b/e2e/error-boundary.spec.ts @@ -1,5 +1,6 @@ import { test, expect } from '@playwright/test'; -import { FIREBASE_API, ALGOLIA_API, mockTopItemIds, mockAlgoliaItem1, mockAlgoliaItem2, mockAlgoliaItem3 } from './fixtures/mock-data'; +import { createFirebaseWsHandler, FIREBASE_WS_PATTERN } from './fixtures/api-mocks'; +import { ALGOLIA_API, mockAlgoliaItem1, mockAlgoliaItem2, mockAlgoliaItem3 } from './fixtures/mock-data'; test.describe('Error Boundary', () => { test.use({ viewport: { width: 1280, height: 720 } }); @@ -7,21 +8,11 @@ test.describe('Error Boundary', () => { test('displays error UI when a component crashes', async ({ page }) => { // Malformed title (object instead of string) makes React throw // "Objects are not valid as a React child" when rendering {item.title}. - await page.route(`${FIREBASE_API}/topstories.json`, async (route) => { - await route.fulfill({ json: mockTopItemIds }); - }); - await page.route(`${FIREBASE_API}/beststories.json`, async (route) => { - await route.fulfill({ json: [12345] }); - }); - await page.route(`${FIREBASE_API}/item/*.json`, async (route) => { - const url = route.request().url(); - const match = url.match(/\/item\/(\d+)\.json/); - const id = match ? parseInt(match[1], 10) : 0; - - await route.fulfill({ - json: { - id, - title: { nested: 'this will crash React render' }, + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ + itemOverrides: { + 12345: { + id: 12345, + title: { nested: 'this will crash React render' } as unknown as string, url: 'https://example.com', by: 'testuser', score: 100, @@ -29,8 +20,9 @@ test.describe('Error Boundary', () => { descendants: 5, type: 'story', }, - }); - }); + }, + })); + await page.route(`${ALGOLIA_API}/search*`, async (route) => { await route.fulfill({ json: { diff --git a/e2e/fixtures/api-mocks.ts b/e2e/fixtures/api-mocks.ts index 46c367f..7ab5141 100644 --- a/e2e/fixtures/api-mocks.ts +++ b/e2e/fixtures/api-mocks.ts @@ -1,7 +1,6 @@ -import { Page } from '@playwright/test'; +import { Page, WebSocketRoute } from '@playwright/test'; import { ALGOLIA_API, - FIREBASE_API, mockItem1, mockItem2, mockItem3, @@ -35,164 +34,267 @@ import { mockUserStory2, } from './mock-data'; +/** Firebase RTDB WebSocket URL pattern */ +export const FIREBASE_WS_PATTERN = /firebaseio\.com\/\.ws/; + /** - * Set up all API mocks for E2E tests - * Intercepts both Algolia and Firebase HN API calls + * Attach Firebase RTDB frame-buffering to a WebSocket route. + * The Firebase wire protocol sends a frame-count string followed by that many + * JSON payload strings. This helper reassembles them before invoking `handler`. */ -export async function setupApiMocks(page: Page) { - // Firebase: Top items - await page.route(`${FIREBASE_API}/topstories.json`, async (route) => { - await route.fulfill({ json: mockTopItemIds }); - }); +function attachFrameBuffering(ws: WebSocketRoute, handler: (raw: string) => void | Promise) { + let expectedFrames = 0; + let frameBuffer: string[] = []; - // Firebase: Best items - await page.route(`${FIREBASE_API}/beststories.json`, async (route) => { - await route.fulfill({ json: mockBestItemIds }); - }); - - // Firebase: Individual items - await page.route(`${FIREBASE_API}/item/*.json`, async (route) => { - const url = route.request().url(); - const match = url.match(/\/item\/(\d+)\.json/); - const id = match ? parseInt(match[1], 10) : 0; + ws.onMessage(async (message) => { + if (typeof message !== 'string') return; - // 99999999 / 0 are reserved as "not found" sentinels in tests. - if (id === 99999999 || id === 0) { - await route.fulfill({ json: null }); + const asNum = parseInt(message, 10); + if (expectedFrames === 0 && !isNaN(asNum) && String(asNum) === message.trim()) { + expectedFrames = asNum; + frameBuffer = []; return; } - const items: Record = { - 12345: mockItem1, - 12346: mockItem2, - 12347: mockItem3, - 1001: mockComment, - 2001: mockNestedComment, - // Best items use distinct IDs so /best and / serve different data. - 33001: mockBestItem1, - 33002: mockBestItem2, - 33003: mockBestItem3, - // Firebase shape for Show HN items (Algolia → Firebase translation). - 99999: { - id: 99999, - title: mockShowHNItem1.title, - url: mockShowHNItem1.url, - by: mockShowHNItem1.author, - score: mockShowHNItem1.points, - time: mockShowHNItem1.created_at_i, - descendants: mockShowHNItem1.num_comments, - type: 'story', - }, - 99998: { - id: 99998, - title: mockShowHNItem2.title, - url: mockShowHNItem2.url, - by: mockShowHNItem2.author, - score: mockShowHNItem2.points, - time: mockShowHNItem2.created_at_i, - descendants: mockShowHNItem2.num_comments, - type: 'story', - }, - // Ask HN items include `text` (text-only posts have no URL). - 88888: { - id: 88888, - title: mockAskHNItem1.title, - url: mockAskHNItem1.url, - by: mockAskHNItem1.author, - score: mockAskHNItem1.points, - time: mockAskHNItem1.created_at_i, - descendants: mockAskHNItem1.num_comments, - text: mockAskHNItem1.story_text, - type: 'story', - }, - 88887: { - id: 88887, - title: mockAskHNItem2.title, - url: mockAskHNItem2.url, - by: mockAskHNItem2.author, - score: mockAskHNItem2.points, - time: mockAskHNItem2.created_at_i, - descendants: mockAskHNItem2.num_comments, - type: 'story', - }, - 77777: { - id: 77777, - title: mockDomainItem.title, - url: mockDomainItem.url, - by: mockDomainItem.author, - score: mockDomainItem.points, - time: mockDomainItem.created_at_i, - descendants: mockDomainItem.num_comments, - type: 'story', - }, - // Type=job triggers SwipeStoryViewer's "not a story" error path. - 55555: mockJobItem, - // User-submitted stories — pinned so desktop tests clicking a - // comments link from /submitted/pg land on a real-titled /item/:id - // (not the generic fallback below). - 66666: { - id: 66666, - title: mockUserStory1.title, - url: mockUserStory1.url, - by: mockUserStory1.author, - score: mockUserStory1.points, - time: mockUserStory1.created_at_i, - descendants: mockUserStory1.num_comments, - type: 'story', - }, - 66667: { - id: 66667, - title: mockUserStory2.title, - url: mockUserStory2.url, - by: mockUserStory2.author, - score: mockUserStory2.points, - time: mockUserStory2.created_at_i, - descendants: mockUserStory2.num_comments, - type: 'story', - }, + if (expectedFrames > 0) { + frameBuffer.push(message); + if (frameBuffer.length < expectedFrames) return; + const fullMessage = frameBuffer.join(''); + expectedFrames = 0; + frameBuffer = []; + await handler(fullMessage); + } else { + await handler(message); + } + }); +} + +/** + * Build the item lookup table used by the WebSocket mock. + */ +function buildItemsMap(): Record { + return { + 12345: mockItem1, + 12346: mockItem2, + 12347: mockItem3, + 1001: mockComment, + 2001: mockNestedComment, + 33001: mockBestItem1, + 33002: mockBestItem2, + 33003: mockBestItem3, + 99999: { + id: 99999, + title: mockShowHNItem1.title, + url: mockShowHNItem1.url, + by: mockShowHNItem1.author, + score: mockShowHNItem1.points, + time: mockShowHNItem1.created_at_i, + descendants: mockShowHNItem1.num_comments, + type: 'story', + }, + 99998: { + id: 99998, + title: mockShowHNItem2.title, + url: mockShowHNItem2.url, + by: mockShowHNItem2.author, + score: mockShowHNItem2.points, + time: mockShowHNItem2.created_at_i, + descendants: mockShowHNItem2.num_comments, + type: 'story', + }, + 88888: { + id: 88888, + title: mockAskHNItem1.title, + url: mockAskHNItem1.url, + by: mockAskHNItem1.author, + score: mockAskHNItem1.points, + time: mockAskHNItem1.created_at_i, + descendants: mockAskHNItem1.num_comments, + text: mockAskHNItem1.story_text, + type: 'story', + }, + 88887: { + id: 88887, + title: mockAskHNItem2.title, + url: mockAskHNItem2.url, + by: mockAskHNItem2.author, + score: mockAskHNItem2.points, + time: mockAskHNItem2.created_at_i, + descendants: mockAskHNItem2.num_comments, + type: 'story', + }, + 77777: { + id: 77777, + title: mockDomainItem.title, + url: mockDomainItem.url, + by: mockDomainItem.author, + score: mockDomainItem.points, + time: mockDomainItem.created_at_i, + descendants: mockDomainItem.num_comments, + type: 'story', + }, + 55555: mockJobItem, + 66666: { + id: 66666, + title: mockUserStory1.title, + url: mockUserStory1.url, + by: mockUserStory1.author, + score: mockUserStory1.points, + time: mockUserStory1.created_at_i, + descendants: mockUserStory1.num_comments, + type: 'story', + }, + 66667: { + id: 66667, + title: mockUserStory2.title, + url: mockUserStory2.url, + by: mockUserStory2.author, + score: mockUserStory2.points, + time: mockUserStory2.created_at_i, + descendants: mockUserStory2.num_comments, + type: 'story', + }, + }; +} + +/** + * Resolve a Firebase path to mock data. + * Paths from the SDK have a leading slash: `/v0/topstories`, `/v0/item/12345`, `/v0/user/pg` + */ +function resolveFirebasePath( + path: string, + items: Record, + opts?: { userResolver?: (username: string) => object | null }, +): unknown { + // Strip leading slash — the SDK sends `/v0/...` but our constants use `v0/...` + const p = path.replace(/^\//, ''); + + if (p === 'v0/topstories') return mockTopItemIds; + if (p === 'v0/beststories') return mockBestItemIds; + if (p === 'v0/showstories') return [99999, 99998]; + if (p === 'v0/askstories') return [88888, 88887]; + + const itemMatch = /^v0\/item\/(\d+)$/.exec(p); + if (itemMatch) { + const id = parseInt(itemMatch[1], 10); + if (id === 99999999 || id === 0) return null; + if (items[id]) return items[id]; + if (id === 1002 || id === 1003) { + return { + id, + by: `user${id}`, + text: `Comment ${id}`, + time: Math.floor(Date.now() / 1000) - 600, + parent: 12345, + type: 'comment', + }; + } + if (id === 1004) { + return { + id: 1004, + by: 'leerob', + text: 'Author here — thanks for the discussion! I updated the benchmarks section based on feedback.', + time: Math.floor(Date.now() / 1000) - 300, + parent: 12345, + type: 'comment', + }; + } + // Generic story fallback + return { + id, + title: `Item ${id}`, + url: `https://example.com/item/${id}`, + by: 'testuser', + score: 50, + time: Math.floor(Date.now() / 1000) - 7200, + descendants: 5, + type: 'story', }; + } - if (items[id]) { - await route.fulfill({ json: items[id] }); - } else if (id === 1002 || id === 1003) { - await route.fulfill({ - json: { - id, - by: `user${id}`, - text: `Comment ${id}`, - time: Math.floor(Date.now() / 1000) - 600, - parent: 12345, - type: 'comment', - }, - }); - } else if (id === 1004) { - await route.fulfill({ - json: { - id: 1004, - by: 'leerob', - text: 'Author here — thanks for the discussion! I updated the benchmarks section based on feedback.', - time: Math.floor(Date.now() / 1000) - 300, - parent: 12345, - type: 'comment', - }, - }); - } else { - // Generic story for unknown IDs so byline/comments-link clicks - // never 404 in tests that don't pin them. - await route.fulfill({ - json: { - id, - title: `Item ${id}`, - url: `https://example.com/item/${id}`, - by: 'testuser', - score: 50, - time: Math.floor(Date.now() / 1000) - 7200, - descendants: 5, - type: 'story', - }, + const userMatch = /^v0\/user\/(.+)$/.exec(p); + if (userMatch) { + const username = decodeURIComponent(userMatch[1]); + if (opts?.userResolver) return opts.userResolver(username); + if (username === 'pg') return mockUserProfile; + return { id: username, created: 1160418092, karma: 1, submitted: [] }; + } + + return null; +} + +/** + * Handle a Firebase RTDB WebSocket connection. Speaks the Firebase wire protocol: + * - Server sends handshake: {"t":"c","d":{"t":"h","d":{...}}} + * - Client sends framed messages: frame-count string, then JSON payload + * - Server responds to "g" (get) requests: {"t":"d","d":{"r":N,"b":{"s":"ok","d":...}}} + */ +export function createFirebaseWsHandler(opts?: { + userResolver?: (username: string) => object | null; + delayMs?: number; + itemOverrides?: Record; + errorItemIds?: number[]; +}) { + const items = { ...buildItemsMap(), ...(opts?.itemOverrides ?? {}) }; + + return (ws: WebSocketRoute) => { + // Send handshake immediately + const handshake = JSON.stringify({ + t: 'c', + d: { t: 'h', d: { ts: Date.now(), v: '5', h: 's-mock.firebaseio.com', s: 'mock-session' } }, + }); + ws.send(handshake); + + attachFrameBuffering(ws, async (raw) => { + await handleClientMessage(raw); + }); + + async function handleClientMessage(raw: string) { + let msg: { t: string; d: { r?: number; a?: string; b?: { p?: string; q?: unknown } } }; + try { + msg = JSON.parse(raw); + } catch { + return; // Ignore malformed messages + } + + if (msg.t !== 'd' || !msg.d) return; + + const { r: reqId, a: action, b: body } = msg.d; + if (action !== 'g' || reqId == null || !body?.p) return; + + if (opts?.delayMs) { + await new Promise((resolve) => setTimeout(resolve, opts.delayMs)); + } + + // Check if this is an item request for an error item + const pathStr = body.p?.replace(/^\//, '') ?? ''; + const errorItemMatch = /^v0\/item\/(\d+)$/.exec(pathStr); + if (errorItemMatch && opts?.errorItemIds?.includes(parseInt(errorItemMatch[1], 10))) { + const errorResponse = JSON.stringify({ + t: 'd', + d: { r: reqId, b: { s: 'permission_denied', d: 'Simulated error' } }, + }); + ws.send(errorResponse); + return; + } + + const data = resolveFirebasePath(body.p, items, { userResolver: opts?.userResolver }); + const response = JSON.stringify({ + t: 'd', + d: { r: reqId, b: { s: 'ok', d: data } }, }); + ws.send(response); } - }); + }; +} + +/** + * Set up all API mocks for E2E tests. + * Intercepts Firebase WebSocket connections and Algolia HTTP calls. + */ +export async function setupApiMocks(page: Page) { + // Firebase: intercept WebSocket connection used by the SDK + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler()); await page.route(`${ALGOLIA_API}/search*`, async (route) => { const url = new URL(route.request().url()); @@ -367,35 +469,6 @@ export async function setupApiMocks(page: Page) { }); }); - // Firebase: user profile (`/user/:id.json`) - // Returns `mockUserProfile` for `pg`, `null` for `nope` (HN's "no such user" - // signal — `useUserProfile` translates this to NotFoundError → isNotFound=true), - // and a synthesized profile for everything else so author-byline links from - // arbitrary fixtures (e.g. `leerob`) don't 404 in tests that don't pin them. - await page.route(`${FIREBASE_API}/user/*.json`, async (route) => { - const url = route.request().url(); - const idMatch = /\/user\/([^/]+)\.json/.exec(url); - const id = idMatch ? decodeURIComponent(idMatch[1]) : ''; - - if (id === 'pg') { - await route.fulfill({ json: mockUserProfile }); - return; - } - - if (id === 'nope') { - await route.fulfill({ json: null }); - return; - } - - await route.fulfill({ - json: { - id, - created: 1160418092, - karma: 1, - submitted: [], - }, - }); - }); } /** @@ -421,18 +494,18 @@ export async function stubEmptyUserSubmissions(page: Page, username: string) { } /** - * Stub the Firebase `/user/:id.json` endpoint to return `null` for a specific - * username (HN's "no such user" signal). Any other request is passed through. + * Stub the Firebase user endpoint to return `null` for a specific username. + * Must be called AFTER setupApiMocks since routeWebSocket uses LIFO ordering + * (most recently registered handler wins). */ export async function stubNotFoundUser(page: Page, username: string) { - await page.route(`${FIREBASE_API}/user/*.json`, async (route) => { - const url = route.request().url(); - if (url.includes(`/user/${encodeURIComponent(username)}.json`)) { - await route.fulfill({ json: null }); - } else { - await route.continue(); - } - }); + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ + userResolver: (u) => { + if (u === username) return null; + if (u === 'pg') return mockUserProfile; + return { id: u, created: 1160418092, karma: 1, submitted: [] }; + }, + })); } /** @@ -457,10 +530,24 @@ export async function stubEmptyDomainSearch(page: Page, domain: string) { }); } -/** Mock an empty items response. */ +/** Mock an empty items response (Firebase returns empty arrays, Algolia returns empty hits). */ export async function mockEmptyItems(page: Page) { - await page.route(`${FIREBASE_API}/topstories.json`, async (route) => { - await route.fulfill({ json: [] }); + // Firebase WS mock that returns empty arrays for ranked lists + await page.routeWebSocket(FIREBASE_WS_PATTERN, (ws: WebSocketRoute) => { + ws.send(JSON.stringify({ + t: 'c', + d: { t: 'h', d: { ts: Date.now(), v: '5', h: 's-mock.firebaseio.com', s: 'mock-session' } }, + })); + + attachFrameBuffering(ws, (raw) => { + let msg: { t: string; d: { r?: number; a?: string; b?: { p?: string } } }; + try { msg = JSON.parse(raw); } catch { return; } + if (msg.t !== 'd' || msg.d?.a !== 'g' || msg.d?.r == null) return; + // Return empty array for all ranked lists, null for items + const path = msg.d.b?.p ?? ''; + const data = path.includes('stories') ? [] : null; + ws.send(JSON.stringify({ t: 'd', d: { r: msg.d.r, b: { s: 'ok', d: data } } })); + }); }); await page.route(`${ALGOLIA_API}/search*`, async (route) => { @@ -476,11 +563,31 @@ export async function mockEmptyItems(page: Page) { }); } -/** Mock API error responses (Firebase 500 + Algolia 503). */ +/** Mock API error responses. Firebase WS responds with errors; Algolia returns 503. */ +/** + * Create a WebSocket handler that sends a handshake then responds to all + * Firebase get requests with a `permission_denied` error. Shared between + * page-level {@link mockApiError} and context-level `errorMockedPage` fixture. + */ +export function createErrorWsHandler() { + return (ws: WebSocketRoute) => { + ws.send(JSON.stringify({ + t: 'c', + d: { t: 'h', d: { ts: Date.now(), v: '5', h: 's-mock.firebaseio.com', s: 'mock-session' } }, + })); + + attachFrameBuffering(ws, (raw) => { + let msg: { t: string; d: { r?: number; a?: string } }; + try { msg = JSON.parse(raw); } catch { return; } + if (msg.t !== 'd' || msg.d?.a !== 'g' || msg.d?.r == null) return; + // Respond with error status for all get requests + ws.send(JSON.stringify({ t: 'd', d: { r: msg.d.r, b: { s: 'permission_denied', d: 'Simulated error' } } })); + }); + }; +} + export async function mockApiError(page: Page) { - await page.route(`${FIREBASE_API}/**`, async (route) => { - await route.fulfill({ status: 500, json: { error: 'Internal Server Error' } }); - }); + await page.routeWebSocket(FIREBASE_WS_PATTERN, createErrorWsHandler()); await page.route(`${ALGOLIA_API}/**`, async (route) => { await route.fulfill({ status: 503, json: { message: 'Service unavailable' } }); @@ -489,45 +596,8 @@ export async function mockApiError(page: Page) { /** Set up API mocks with artificial delay so loading states are observable. */ export async function setupApiMocksWithDelay(page: Page, delayMs: number = 1500) { - await page.route(`${FIREBASE_API}/topstories.json`, async (route) => { - await new Promise((r) => setTimeout(r, delayMs)); - await route.fulfill({ json: mockTopItemIds }); - }); - - await page.route(`${FIREBASE_API}/beststories.json`, async (route) => { - await new Promise((r) => setTimeout(r, delayMs)); - await route.fulfill({ json: mockBestItemIds }); - }); - - await page.route(`${FIREBASE_API}/item/*.json`, async (route) => { - await new Promise((r) => setTimeout(r, delayMs)); - const url = route.request().url(); - const match = url.match(/\/item\/(\d+)\.json/); - const id = match ? parseInt(match[1], 10) : 0; - - const items: Record = { - 12345: mockItem1, - 12346: mockItem2, - 12347: mockItem3, - }; - - if (items[id]) { - await route.fulfill({ json: items[id] }); - } else { - await route.fulfill({ - json: { - id, - title: `Item ${id}`, - url: `https://example.com/item/${id}`, - by: 'testuser', - score: 50, - time: Math.floor(Date.now() / 1000) - 7200, - descendants: 5, - type: 'story', - }, - }); - } - }); + // Firebase WS mock with delay + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ delayMs })); await page.route(`${ALGOLIA_API}/search*`, async (route) => { await new Promise((r) => setTimeout(r, delayMs)); diff --git a/e2e/fixtures/mock-data.ts b/e2e/fixtures/mock-data.ts index deb2ae6..530fb61 100644 --- a/e2e/fixtures/mock-data.ts +++ b/e2e/fixtures/mock-data.ts @@ -1,7 +1,6 @@ /** Mock data for E2E tests */ export const ALGOLIA_API = 'https://hn.algolia.com/api/v1'; -export const FIREBASE_API = 'https://hacker-news.firebaseio.com/v0'; const now = () => Math.floor(Date.now() / 1000); diff --git a/e2e/fixtures/test.ts b/e2e/fixtures/test.ts index 0ffb5e5..de107b7 100644 --- a/e2e/fixtures/test.ts +++ b/e2e/fixtures/test.ts @@ -5,8 +5,8 @@ */ import { test as base, expect, Page } from '@playwright/test'; import AxeBuilder from '@axe-core/playwright'; -import { mockEmptyItems, mockApiError } from './api-mocks'; -import { FIREBASE_API, ALGOLIA_API } from './mock-data'; +import { mockEmptyItems, mockApiError, createErrorWsHandler, FIREBASE_WS_PATTERN } from './api-mocks'; +import { ALGOLIA_API } from './mock-data'; /** * Extended test fixture types @@ -52,9 +52,8 @@ export const test = base.extend({ * `page.route()` may not be active by the time `page.goto()` fires. */ errorMockedPage: async ({ context }, use) => { - await context.route(`${FIREBASE_API}/**`, async (route) => { - await route.fulfill({ status: 500, json: { error: 'Internal Server Error' } }); - }); + // Use the shared error handler with proper frame-count buffering + await context.routeWebSocket(FIREBASE_WS_PATTERN, createErrorWsHandler()); await context.route(`${ALGOLIA_API}/**`, async (route) => { await route.fulfill({ status: 503, json: { message: 'Service unavailable' } }); }); diff --git a/e2e/network-status-bar.spec.ts b/e2e/network-status-bar.spec.ts index 14f7775..999e318 100644 --- a/e2e/network-status-bar.spec.ts +++ b/e2e/network-status-bar.spec.ts @@ -12,6 +12,14 @@ test.describe('Network Status Bar - Viewport Switch', () => { test.beforeEach(async ({ page }) => { await setupApiMocks(page); + // Pre-load lazy-loaded mobile chunks (SwipeStoryViewer, etc.) while still + // online. Without this, resizing to mobile viewport while offline causes a + // dynamic import failure that triggers the Error Boundary instead of the + // network status bar. + await page.setViewportSize({ width: 375, height: 667 }); + await page.goto('/#/'); + await page.waitForLoadState('networkidle'); + await page.setViewportSize({ width: 1280, height: 720 }); }); test('no horizontal overflow when going offline on desktop then switching to mobile', async ({ page, context }) => { diff --git a/package-lock.json b/package-lock.json index 81e0224..c41753f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "dompurify": "^3.4.5", + "firebase": "^12.13.0", "lucide-react": "^1.16.0", "radix-ui": "^1.4.3", "react": "^19.2.6", @@ -785,6 +786,617 @@ "npm": ">=10" } }, + "node_modules/@firebase/ai": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@firebase/ai/-/ai-2.12.0.tgz", + "integrity": "sha512-b+OL4vdyiSLZL/7dLd67V55CjKJvU9MpNmwnday7eA6GG2+J4iwUEsEHgw0/jKY3A41FfkF0SrnYFvtKbQZ65A==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app-check-interop-types": "0.3.4", + "@firebase/component": "0.7.3", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@firebase/app": "0.x", + "@firebase/app-types": "0.x" + } + }, + "node_modules/@firebase/analytics": { + "version": "0.10.22", + "resolved": "https://registry.npmjs.org/@firebase/analytics/-/analytics-0.10.22.tgz", + "integrity": "sha512-8BSaq/QRGU1+xyi8L2PTLTJU7MH9aMA72RQdIxrbhWFauOZY9OXo8f2YDN/972xA8d588tlnNVEQ2Mo69pT9Ow==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/installations": "0.6.22", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@firebase/app": "0.x" + } + }, + "node_modules/@firebase/analytics-compat": { + "version": "0.2.28", + "resolved": "https://registry.npmjs.org/@firebase/analytics-compat/-/analytics-compat-0.2.28.tgz", + "integrity": "sha512-lIAlqUUbBu93FJMlQfslryQtBwwzdzvp23ePC6FNgymXk6Ook5v4Uvc0vdutvoIeqmyA3LfP0ZeRFK8+11kOOQ==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/analytics": "0.10.22", + "@firebase/analytics-types": "0.8.4", + "@firebase/component": "0.7.3", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@firebase/app-compat": "0.x" + } + }, + "node_modules/@firebase/analytics-types": { + "version": "0.8.4", + "resolved": "https://registry.npmjs.org/@firebase/analytics-types/-/analytics-types-0.8.4.tgz", + "integrity": "sha512-zQ+XTgkwH6CY/eUSHJRP7e4LxM30RCxlCmob5sy2axs25GE3Ny0XdgpDscMTHHQIGqWkxPXad4w2Mw9sCgT8zQ==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/app": { + "version": "0.14.12", + "resolved": "https://registry.npmjs.org/@firebase/app/-/app-0.14.12.tgz", + "integrity": "sha512-FT+HoNp1NdaZ/N26hCwV3WbxS1m6gTn3p2QRBQ3KH7YqyCQqJx0iT7126RgVk68/Rq+9DeL/zCFnHZ0C4u1nLQ==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "idb": "7.1.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/app-check": { + "version": "0.11.3", + "resolved": "https://registry.npmjs.org/@firebase/app-check/-/app-check-0.11.3.tgz", + "integrity": "sha512-aJ4DfubWfTO8/2vhEhIAizOoOmiycESTU32e+OUgbWcS/G3PA4Vxlr/9zaiN2wfUG2AptQ7DTvj00tyuFZP5Bg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@firebase/app": "0.x" + } + }, + "node_modules/@firebase/app-check-compat": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@firebase/app-check-compat/-/app-check-compat-0.4.3.tgz", + "integrity": "sha512-L3AKIRTJxT9b7cDUH3OyV8gWTnmW3vYkwdzRsukWt4kbPBTct12xalnyvHDkm1lKkr+cQq/4uzBx1bOWsQ2ciw==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app-check": "0.11.3", + "@firebase/app-check-types": "0.5.4", + "@firebase/component": "0.7.3", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@firebase/app-compat": "0.x" + } + }, + "node_modules/@firebase/app-check-interop-types": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@firebase/app-check-interop-types/-/app-check-interop-types-0.3.4.tgz", + "integrity": "sha512-zz3i6e13B8BfWiLy8MABtTh8aGIACgKbf9UVnyHcWs+yQzJXgQcl8A46b0zfaiJHdQ+niF0ouAfcpuf+3LMPQg==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/app-check-types": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/@firebase/app-check-types/-/app-check-types-0.5.4.tgz", + "integrity": "sha512-xV7JsIyzVr15aA7f3Pi0rB9gdBuVubs89FGA8VkRYA4g0l78poADgdfrScgf7NndSg9mm7cR7PJyY0+t22KaGw==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/app-compat": { + "version": "0.5.12", + "resolved": "https://registry.npmjs.org/@firebase/app-compat/-/app-compat-0.5.12.tgz", + "integrity": "sha512-Pe513OBerK/CIBxz4/za9atd5MsZtd6DzHz4cmqkvkrcDWhQChAoHBpZ3McuZNuSP8YZiKwfX/J1frR07l15/w==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app": "0.14.12", + "@firebase/component": "0.7.3", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/app-types": { + "version": "0.9.5", + "resolved": "https://registry.npmjs.org/@firebase/app-types/-/app-types-0.9.5.tgz", + "integrity": "sha512-YevqTjvo7Iujsa9Dwowmd6dSoElhzmD63ZSrq6bzjvQ6POjYgNjOFHLmNIgJs48eNO093NCERibuFnxbfOvU7A==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/logger": "0.5.1" + } + }, + "node_modules/@firebase/auth": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@firebase/auth/-/auth-1.13.1.tgz", + "integrity": "sha512-/1nkKY/MicI+I9WWcx6R4NKs77AaW9NQ0IwsFdUBomWrW0/cXEmopfM2dtLm2oI1qG6z6vom3CXZDHJIJXoMuw==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@firebase/app": "0.x", + "@react-native-async-storage/async-storage": "^2.2.0 || ^3.0.0" + }, + "peerDependenciesMeta": { + "@react-native-async-storage/async-storage": { + "optional": true + } + } + }, + "node_modules/@firebase/auth-compat": { + "version": "0.6.6", + "resolved": "https://registry.npmjs.org/@firebase/auth-compat/-/auth-compat-0.6.6.tgz", + "integrity": "sha512-KDJ/GAf/rt7galOpn3DRb2buFfGkZCsHTryKjXDG0eeRnok4+2B4nnkMOMdjRnPkElmcJv2Ao0vEA6kp5m98PQ==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/auth": "1.13.1", + "@firebase/auth-types": "0.13.1", + "@firebase/component": "0.7.3", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@firebase/app-compat": "0.x" + } + }, + "node_modules/@firebase/auth-interop-types": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/@firebase/auth-interop-types/-/auth-interop-types-0.2.5.tgz", + "integrity": "sha512-1Li/YuBDBAXcKv7BzY4U28gontUmAaw53sYiqbaVOMCFb2lFKK/c3CGMUWqtwe7+TXrl3poWnTCL5umYBg85Eg==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/auth-types": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/@firebase/auth-types/-/auth-types-0.13.1.tgz", + "integrity": "sha512-0c1Mnid0uMDfGJHeUS4zfvBa4/CedJXotGy/n/NZJnBjwiJawt0ZYU+wH2VAVLiRCEfG2ncCkAX3yd1/2nrB7g==", + "license": "Apache-2.0", + "peerDependencies": { + "@firebase/app-types": "0.x", + "@firebase/util": "1.x" + } + }, + "node_modules/@firebase/component": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/@firebase/component/-/component-0.7.3.tgz", + "integrity": "sha512-wFofIaa2879ogD/WvkjYXJxRmfnL0scen6ORgaC3na1FNOR9ASIUANQdhqQcmWu/h77/pVHY7ch5flewa5Bcew==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/data-connect": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@firebase/data-connect/-/data-connect-0.7.0.tgz", + "integrity": "sha512-ar9sNOJh5poQCSMSVlnVE8eo8+usTD1POWDCv65omkKUvnFMcdXaQ7J/e7WGKqJzcEMgiezSX/TZiKHZkItMbQ==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/auth-interop-types": "0.2.5", + "@firebase/component": "0.7.3", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@firebase/app": "0.x" + } + }, + "node_modules/@firebase/database": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@firebase/database/-/database-1.1.3.tgz", + "integrity": "sha512-XwWCa+E4TvNGpGwXrycLRNfdogADwFcvuhyow6wDWma9W54roaQIhe+4PM0KiLsIftBdSCGI7OKCXrdSRHbIhw==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app-check-interop-types": "0.3.4", + "@firebase/auth-interop-types": "0.2.5", + "@firebase/component": "0.7.3", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "faye-websocket": "0.11.4", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/database-compat": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@firebase/database-compat/-/database-compat-2.1.4.tgz", + "integrity": "sha512-3pK35F1MAgmqFJQlf2nhQl44vtAXQO1uaCaQOEUI9kCRtLFqi7N+QRKR7lFZPg+xIZIyubgxQaxY69YgfZRZWg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/database": "1.1.3", + "@firebase/database-types": "1.0.20", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/database-types": { + "version": "1.0.20", + "resolved": "https://registry.npmjs.org/@firebase/database-types/-/database-types-1.0.20.tgz", + "integrity": "sha512-kegbOk/w8iU64pr0q6k2ItyNGjnQBMHFhwS7ohdWI4W+pc0/zhhdGXTdFj6X1oxItRjPoYOsSQmERgBkn/ihxw==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app-types": "0.9.5", + "@firebase/util": "1.15.1" + } + }, + "node_modules/@firebase/firestore": { + "version": "4.14.1", + "resolved": "https://registry.npmjs.org/@firebase/firestore/-/firestore-4.14.1.tgz", + "integrity": "sha512-PouS0NJZ3NYOZE/tPDvXa8VUeJ10Ll//7jIdFvMYdhQkd/P3O7nlqhyoTmY0h8Xa9hxg+H0j6gxUytJcoZ9YOg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "@firebase/webchannel-wrapper": "1.0.6", + "@grpc/grpc-js": "~1.9.0", + "@grpc/proto-loader": "^0.7.8", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@firebase/app": "0.x" + } + }, + "node_modules/@firebase/firestore-compat": { + "version": "0.4.9", + "resolved": "https://registry.npmjs.org/@firebase/firestore-compat/-/firestore-compat-0.4.9.tgz", + "integrity": "sha512-NPtBuFr79BbIQJXFWhW4xFC6rBksK8/ewqCTYbbAYfZBDDx0/iHTUj4WpKi5D4d0Pn2Md/3T/e5V9379G5N/Zg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/firestore": "4.14.1", + "@firebase/firestore-types": "3.0.4", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@firebase/app-compat": "0.x" + } + }, + "node_modules/@firebase/firestore-types": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@firebase/firestore-types/-/firestore-types-3.0.4.tgz", + "integrity": "sha512-jGn+JSS4X9zZsrfu7Yw66v5YRdOLD1oyQh4USR0xWl4CUqV/DA6bNIXRPpxH/cUl3iVTNiP6MN7g+EL42A4qfA==", + "license": "Apache-2.0", + "peerDependencies": { + "@firebase/app-types": "0.x", + "@firebase/util": "1.x" + } + }, + "node_modules/@firebase/functions": { + "version": "0.13.4", + "resolved": "https://registry.npmjs.org/@firebase/functions/-/functions-0.13.4.tgz", + "integrity": "sha512-oB5rpm2Emxn2+IS1gRelAeT/5tSZMwM/KhqC5LnJsmTNnS1ZDhD7ZMZNgCI8vchTW6PbaXIwEnpUryGuIQsNbg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app-check-interop-types": "0.3.4", + "@firebase/auth-interop-types": "0.2.5", + "@firebase/component": "0.7.3", + "@firebase/messaging-interop-types": "0.2.4", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@firebase/app": "0.x" + } + }, + "node_modules/@firebase/functions-compat": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/@firebase/functions-compat/-/functions-compat-0.4.4.tgz", + "integrity": "sha512-Be+MwhseVf/eFAZwGrFJGok6S7cmsLrAPK8MgyM8LjM0MewTsx2n01WOOca9jio1UsCZOJ0aVyQobnINcdNuIQ==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/functions": "0.13.4", + "@firebase/functions-types": "0.6.4", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@firebase/app-compat": "0.x" + } + }, + "node_modules/@firebase/functions-types": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/@firebase/functions-types/-/functions-types-0.6.4.tgz", + "integrity": "sha512-zV6kgqtduR4rUAdC/ilS7kmb93XD7bEZoJDlVBZqlOw2uGGGCNBQBuleww2rr0Ulr3L9o2TDjumEt68/l1f9DQ==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/installations": { + "version": "0.6.22", + "resolved": "https://registry.npmjs.org/@firebase/installations/-/installations-0.6.22.tgz", + "integrity": "sha512-ef6nn3GGQTdReCfotRMG77PJZu8CqEbiK5pEoBnM0gTu/Z9v0i/az2p3HABsa/1beQmmyh1OsOjf7P5+pgwdZw==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/util": "1.15.1", + "idb": "7.1.1", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@firebase/app": "0.x" + } + }, + "node_modules/@firebase/installations-compat": { + "version": "0.2.22", + "resolved": "https://registry.npmjs.org/@firebase/installations-compat/-/installations-compat-0.2.22.tgz", + "integrity": "sha512-C/zpAuTP5S9OgKSPvXRupw3hoY/JZSlA1wFjD/Sb7LIQE0FNbcMdO8Y4KXVEkjVzma/DDDDIAzxEXqKMAzc88w==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/installations": "0.6.22", + "@firebase/installations-types": "0.5.4", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@firebase/app-compat": "0.x" + } + }, + "node_modules/@firebase/installations-types": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/@firebase/installations-types/-/installations-types-0.5.4.tgz", + "integrity": "sha512-U2eFapdHwjb43Vx9o+Pmj4dFfvcHEK1IirEFLqMtWrTHvmdrS3gBpBD1kmJk/9HjsOtoHZxJ2Paoe79e+L1ZPg==", + "license": "Apache-2.0", + "peerDependencies": { + "@firebase/app-types": "0.x" + } + }, + "node_modules/@firebase/logger": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@firebase/logger/-/logger-0.5.1.tgz", + "integrity": "sha512-vZKLsqE1ABOy8OjQiE7cUTFn4gvaqlk88yp8N94Pk/sDpq61YqZGqmVFZTvOyflTwuYFcWirBdYGoJgbDaXKYQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/messaging": { + "version": "0.12.26", + "resolved": "https://registry.npmjs.org/@firebase/messaging/-/messaging-0.12.26.tgz", + "integrity": "sha512-lHVTO9uLofymHVWkYeUtMddIPcmJvSzVbHRB88W6XKfxbcKF+p3QrfqKhDxremSB4NQjUla1Gwn7d9umSMmt/w==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/installations": "0.6.22", + "@firebase/messaging-interop-types": "0.2.4", + "@firebase/util": "1.15.1", + "idb": "7.1.1", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@firebase/app": "0.x" + } + }, + "node_modules/@firebase/messaging-compat": { + "version": "0.2.26", + "resolved": "https://registry.npmjs.org/@firebase/messaging-compat/-/messaging-compat-0.2.26.tgz", + "integrity": "sha512-fn0XvWOfK4tsDLSipwJUW9Cp6ahWA6z+iJHxZ0pHp9MzMSUNQx85yuxZAuI7gkGXfqs7+DqEDHyyS7jDGswrmQ==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/messaging": "0.12.26", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@firebase/app-compat": "0.x" + } + }, + "node_modules/@firebase/messaging-interop-types": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/@firebase/messaging-interop-types/-/messaging-interop-types-0.2.4.tgz", + "integrity": "sha512-wrzITQq+xw5LtygX7O0fu43/k9ABQ4x5H9/sR5m1SbNnhIRI5xd3+raSNJaJkYC4BUhM9A4ZNSnyR2sjhxnb2Q==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/performance": { + "version": "0.7.12", + "resolved": "https://registry.npmjs.org/@firebase/performance/-/performance-0.7.12.tgz", + "integrity": "sha512-fe7nV8teUU3OBHlMUZ9Lw4gLhCW2k4m5Uc3pfWGV+fl8uwJQBGp9Q3lqsJ+HSrFu3Q2pJyLAgrClPGSKyDeYgQ==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/installations": "0.6.22", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0", + "web-vitals": "^4.2.4" + }, + "peerDependencies": { + "@firebase/app": "0.x" + } + }, + "node_modules/@firebase/performance-compat": { + "version": "0.2.25", + "resolved": "https://registry.npmjs.org/@firebase/performance-compat/-/performance-compat-0.2.25.tgz", + "integrity": "sha512-q6NjTXpIPoFuUmCmMN/maCdTgzT6aExs9xZo+PxfVLj6uLVGvpyAD6XWjmcrb7jChsFBYbq7E5dyNDF7Zhy9kA==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/logger": "0.5.1", + "@firebase/performance": "0.7.12", + "@firebase/performance-types": "0.2.4", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@firebase/app-compat": "0.x" + } + }, + "node_modules/@firebase/performance-types": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/@firebase/performance-types/-/performance-types-0.2.4.tgz", + "integrity": "sha512-kJSEk7b0uhpcPRyL4SQ/GPujLqk52XNKcXlnsKDbWGAb9vugcLvOU3u6zfEdwd+d8hWJb5S5ZizV1JFFI0nkKg==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/remote-config": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/@firebase/remote-config/-/remote-config-0.8.3.tgz", + "integrity": "sha512-ggGKAaLy9YNOvpFoQZgm5p5SiFw3ZFtwti08dojnBQmQicpThTxvG5xZMSpCTYMj2o3gM/yK9CVd2w+kZub8YA==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/installations": "0.6.22", + "@firebase/logger": "0.5.1", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@firebase/app": "0.x" + } + }, + "node_modules/@firebase/remote-config-compat": { + "version": "0.2.24", + "resolved": "https://registry.npmjs.org/@firebase/remote-config-compat/-/remote-config-compat-0.2.24.tgz", + "integrity": "sha512-EWZTt6fJ7YmPHodQNsSxAIDZY2x8P5kRPvXAc5CmzzBm+NyPFhODbfDsNllDXDL8jlzp50bVWjDY+BXepZS9Mg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/logger": "0.5.1", + "@firebase/remote-config": "0.8.3", + "@firebase/remote-config-types": "0.5.1", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@firebase/app-compat": "0.x" + } + }, + "node_modules/@firebase/remote-config-types": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@firebase/remote-config-types/-/remote-config-types-0.5.1.tgz", + "integrity": "sha512-cX/1LT6KQwkXzck2eSzeKnuvXZCyr8qaPpDcikoJs7jmI+oBOXixpDLeDtWj1U6GNMkIoXrEDNoyT2Ypcyp5/A==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/storage": { + "version": "0.14.3", + "resolved": "https://registry.npmjs.org/@firebase/storage/-/storage-0.14.3.tgz", + "integrity": "sha512-YX4/YL6P6/fufSSeGnVhjWddcIXbFq2cWIhMKFTZo1E/Rtcl2mJj/BYUQTwJfcE1Tl8un1FOya4L05jcSLN/Eg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@firebase/app": "0.x" + } + }, + "node_modules/@firebase/storage-compat": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@firebase/storage-compat/-/storage-compat-0.4.3.tgz", + "integrity": "sha512-gruVqjtUGX8tEoeNbaWXZm0Zfcfcb7fvmDmBxV8yPAbWvExRnZYLO2+qw9idxNE7BvPXt5csyjSYHy//dAizxw==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.3", + "@firebase/storage": "0.14.3", + "@firebase/storage-types": "0.8.4", + "@firebase/util": "1.15.1", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@firebase/app-compat": "0.x" + } + }, + "node_modules/@firebase/storage-types": { + "version": "0.8.4", + "resolved": "https://registry.npmjs.org/@firebase/storage-types/-/storage-types-0.8.4.tgz", + "integrity": "sha512-BT7cwxJOx8SWwlQfrlC+bD/Sk3Cw+1odCi8UZNFNWTVZoPsBnA5W+mqtZzVnvsdJpXCFGSGQ7R7vOR6dtM/BRA==", + "license": "Apache-2.0", + "peerDependencies": { + "@firebase/app-types": "0.x", + "@firebase/util": "1.x" + } + }, + "node_modules/@firebase/util": { + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/@firebase/util/-/util-1.15.1.tgz", + "integrity": "sha512-LUdM4Wg7YM9Pq/49nGYySJA0CSQEKnGffFzWV8+6gXN7mGxn+FL1IqvFbuZUtAQcfZgHYDwCE1wwlK7rB7gl2g==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/webchannel-wrapper": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@firebase/webchannel-wrapper/-/webchannel-wrapper-1.0.6.tgz", + "integrity": "sha512-Vr/Mqu79dMwGRAyGbJ4uN4+BtXB3/mRTdzetD1daWNeG8QaWuzhhbG77GltO5c0yYmYls8i250iX73624GJd7Q==", + "license": "Apache-2.0" + }, "node_modules/@floating-ui/core": { "version": "1.7.5", "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz", @@ -823,6 +1435,37 @@ "integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==", "license": "MIT" }, + "node_modules/@grpc/grpc-js": { + "version": "1.9.16", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.9.16.tgz", + "integrity": "sha512-wE4Ut/olIzfKqp631XrG+wbF0v1vWFN4YL9FyXC2LJiG33DsV7PLzURjrCvY/6je2ntdRkeLpPDluzSRGaVltQ==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/proto-loader": "^0.7.8", + "@types/node": ">=12.12.47" + }, + "engines": { + "node": "^8.13.0 || >=10.10.0" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.7.15", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz", + "integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==", + "license": "Apache-2.0", + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.2.5", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/@humanfs/core": { "version": "0.19.1", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", @@ -1597,6 +2240,69 @@ "dev": true, "license": "MIT" }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/inquire": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.2.tgz", + "integrity": "sha512-pa0vFRuws4wkvaXKK1uXZMAwAX4/t8ANaJo45iw/oQHNQ9q5xUzwgFmVJGXiga2BeN+zpX7Vf9vmsiIa2J+MUw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.1.tgz", + "integrity": "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==", + "license": "BSD-3-Clause" + }, "node_modules/@radix-ui/number": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz", @@ -3767,7 +4473,6 @@ "version": "25.9.1", "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.1.tgz", "integrity": "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg==", - "dev": true, "license": "MIT", "dependencies": { "undici-types": ">=7.24.0 <7.24.7" @@ -4362,7 +5067,6 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -4372,7 +5076,6 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, "license": "MIT", "dependencies": { "color-convert": "^2.0.1" @@ -4842,7 +5545,6 @@ "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, "license": "ISC", "dependencies": { "string-width": "^4.2.0", @@ -4857,7 +5559,6 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", @@ -4884,7 +5585,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, "license": "MIT", "dependencies": { "color-name": "~1.1.4" @@ -4897,7 +5597,6 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, "license": "MIT" }, "node_modules/concat-map": { @@ -5194,7 +5893,6 @@ "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, "license": "MIT" }, "node_modules/enhanced-resolve": { @@ -5412,7 +6110,6 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -5800,6 +6497,18 @@ "fast-string-width": "^3.0.2" } }, + "node_modules/faye-websocket": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", + "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", + "license": "Apache-2.0", + "dependencies": { + "websocket-driver": ">=0.5.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -5855,6 +6564,42 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/firebase": { + "version": "12.13.0", + "resolved": "https://registry.npmjs.org/firebase/-/firebase-12.13.0.tgz", + "integrity": "sha512-iutR8ejvAqk6qUClnsPz3U3VIjTWp243AX4cD3iifak5t56to1J29xUIQgSDDzaAqKvhshZerzSahwMQj2TlvA==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/ai": "2.12.0", + "@firebase/analytics": "0.10.22", + "@firebase/analytics-compat": "0.2.28", + "@firebase/app": "0.14.12", + "@firebase/app-check": "0.11.3", + "@firebase/app-check-compat": "0.4.3", + "@firebase/app-compat": "0.5.12", + "@firebase/app-types": "0.9.5", + "@firebase/auth": "1.13.1", + "@firebase/auth-compat": "0.6.6", + "@firebase/data-connect": "0.7.0", + "@firebase/database": "1.1.3", + "@firebase/database-compat": "2.1.4", + "@firebase/firestore": "4.14.1", + "@firebase/firestore-compat": "0.4.9", + "@firebase/functions": "0.13.4", + "@firebase/functions-compat": "0.4.4", + "@firebase/installations": "0.6.22", + "@firebase/installations-compat": "0.2.22", + "@firebase/messaging": "0.12.26", + "@firebase/messaging-compat": "0.2.26", + "@firebase/performance": "0.7.12", + "@firebase/performance-compat": "0.2.25", + "@firebase/remote-config": "0.8.3", + "@firebase/remote-config-compat": "0.2.24", + "@firebase/storage": "0.14.3", + "@firebase/storage-compat": "0.4.3", + "@firebase/util": "1.15.1" + } + }, "node_modules/flat-cache": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", @@ -5972,7 +6717,6 @@ "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, "license": "ISC", "engines": { "node": "6.* || 8.* || >= 10.*" @@ -6266,6 +7010,18 @@ "dev": true, "license": "MIT" }, + "node_modules/http-parser-js": { + "version": "0.5.10", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.10.tgz", + "integrity": "sha512-Pysuw9XpUq5dVc/2SMHpuTY01RFl8fttgcyunjL7eEMhGM3cI4eOmiCycJDVCo/7O7ClfQD3SaI6ftDzqOXYMA==", + "license": "MIT" + }, + "node_modules/idb": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/idb/-/idb-7.1.1.tgz", + "integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==", + "license": "ISC" + }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", @@ -6493,7 +7249,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -7263,6 +8018,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "license": "MIT" + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -7270,6 +8031,12 @@ "dev": true, "license": "MIT" }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, "node_modules/loose-envify": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", @@ -7958,6 +8725,30 @@ "dev": true, "license": "MIT" }, + "node_modules/protobufjs": { + "version": "7.6.1", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.1.tgz", + "integrity": "sha512-4K0myLaWL5EteuSAro91EGFgcfVgxb64Jx+7oDAY6GOkXD4M69yuSEljNcInGVCA5sOPxmZ/EqDLj2x0Q0+Ygg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -8257,7 +9048,6 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -8368,6 +9158,26 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/safe-push-apply": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz", @@ -8738,7 +9548,6 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", @@ -8866,7 +9675,6 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" @@ -9285,7 +10093,6 @@ "version": "7.24.6", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", - "dev": true, "license": "MIT" }, "node_modules/until-async": { @@ -9572,6 +10379,12 @@ "node": ">=18" } }, + "node_modules/web-vitals": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-4.2.4.tgz", + "integrity": "sha512-r4DIlprAGwJ7YM11VZp4R884m0Vmgr6EAKe3P+kO0PPj3Unqyvv59rczf6UiGcb9Z8QxZVcqKNwv/g0WNdWwsw==", + "license": "Apache-2.0" + }, "node_modules/webidl-conversions": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", @@ -9582,6 +10395,29 @@ "node": ">=20" } }, + "node_modules/websocket-driver": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", + "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", + "license": "Apache-2.0", + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/websocket-extensions": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8.0" + } + }, "node_modules/whatwg-mimetype": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", @@ -9760,7 +10596,6 @@ "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, "license": "ISC", "engines": { "node": ">=10" @@ -9777,7 +10612,6 @@ "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "dev": true, "license": "MIT", "dependencies": { "cliui": "^8.0.1", @@ -9796,7 +10630,6 @@ "version": "21.1.1", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, "license": "ISC", "engines": { "node": ">=12" diff --git a/package.json b/package.json index 9681ba0..a4aa8bc 100644 --- a/package.json +++ b/package.json @@ -9,20 +9,21 @@ "typecheck": "tsc --noEmit", "lint": "eslint .", "preview": "vite preview", - "test": "vitest", - "test:run": "vitest run", - "test:ui": "vitest --ui", - "test:coverage": "vitest run --coverage", - "e2e": "playwright test", - "e2e:ui": "playwright test --ui", - "e2e:debug": "playwright test --debug", - "e2e:headed": "playwright test --headed", + "test": "NODE_OPTIONS='--disable-warning=ExperimentalWarning --disable-warning=DEP0205' vitest", + "test:run": "NODE_OPTIONS='--disable-warning=ExperimentalWarning --disable-warning=DEP0205' vitest run", + "test:ui": "NODE_OPTIONS='--disable-warning=ExperimentalWarning --disable-warning=DEP0205' vitest --ui", + "test:coverage": "NODE_OPTIONS='--disable-warning=ExperimentalWarning --disable-warning=DEP0205' vitest run --coverage", + "e2e": "NODE_OPTIONS='--disable-warning=DEP0205' playwright test", + "e2e:ui": "NODE_OPTIONS='--disable-warning=DEP0205' playwright test --ui", + "e2e:debug": "NODE_OPTIONS='--disable-warning=DEP0205' playwright test --debug", + "e2e:headed": "NODE_OPTIONS='--disable-warning=DEP0205' playwright test --headed", "icons": "node scripts/generate-icons.js" }, "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "dompurify": "^3.4.5", + "firebase": "^12.13.0", "lucide-react": "^1.16.0", "radix-ui": "^1.4.3", "react": "^19.2.6", diff --git a/playwright.config.ts b/playwright.config.ts index 82b9225..49c735a 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -62,10 +62,11 @@ export default defineConfig({ webServer: { command: 'npm run build && npm run preview', url: 'http://localhost:4173', - reuseExistingServer: false, + reuseExistingServer: !process.env.CI, timeout: 120 * 1000, stdout: 'pipe', stderr: 'pipe', + env: { ...process.env, NODE_OPTIONS: '--disable-warning=DEP0205' }, }, timeout: 30 * 1000, expect: { diff --git a/src/App.tsx b/src/App.tsx index 61e143c..38ecf54 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,13 +1,23 @@ import { HashRouter, Routes, Route, useParams, useLocation, useNavigate } from 'react-router-dom'; -import { useState, useEffect, type ReactNode } from 'react'; +import { lazy, Suspense, useState, useEffect, type ReactNode } from 'react'; import { ThemeProvider } from './context/ThemeContext'; import { ScrollContainerProvider } from './context/ScrollContainerContext'; import { useScrollContainer } from './hooks/useScrollContainer'; -import { Header, ErrorBoundary, SwipeStoryViewer, SwipeDomainStoryViewer, SwipeUserSubmissionsViewer, SwipeCommentViewer, FullScreenCommentSkeletonPanel, StateView, NetworkStatusBar } from './components'; +import { Header, ErrorBoundary, FullScreenCommentSkeletonPanel, Spinner, StateView, NetworkStatusBar } from './components'; import { TooltipProvider } from './components/ui'; -import { StoryList, ItemDetail, DomainStories, UserProfile, UserSubmissions } from './pages'; +import { StoryList } from './pages'; import { useIsMobile } from './hooks/useIsMobile'; import { useDocumentTitle } from './hooks/useDocumentTitle'; + +// Lazy-loaded route components for code splitting +const ItemDetail = lazy(() => import('./pages/ItemDetail').then(m => ({ default: m.ItemDetail }))); +const DomainStories = lazy(() => import('./pages/DomainStories').then(m => ({ default: m.DomainStories }))); +const UserProfile = lazy(() => import('./pages/UserProfile').then(m => ({ default: m.UserProfile }))); +const UserSubmissions = lazy(() => import('./pages/UserSubmissions').then(m => ({ default: m.UserSubmissions }))); +const SwipeStoryViewer = lazy(() => import('./components/SwipeStoryViewer').then(m => ({ default: m.SwipeStoryViewer }))); +const SwipeDomainStoryViewer = lazy(() => import('./components/SwipeDomainStoryViewer').then(m => ({ default: m.SwipeDomainStoryViewer }))); +const SwipeUserSubmissionsViewer = lazy(() => import('./components/SwipeUserSubmissionsViewer').then(m => ({ default: m.SwipeUserSubmissionsViewer }))); +const SwipeCommentViewer = lazy(() => import('./components/SwipeCommentViewer').then(m => ({ default: m.SwipeCommentViewer }))); import { NetworkStatusProvider } from './context/NetworkStatusContext'; import { fetchItemOnly } from './api/hn'; import type { FeedType, LocationState } from './types'; @@ -193,17 +203,19 @@ function App() {
- - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - + }> + + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts index b9cc208..ac352f4 100644 --- a/src/api/hn.test.ts +++ b/src/api/hn.test.ts @@ -13,14 +13,42 @@ import { fetchFirebaseItem, fetchItemOnly, fetchAlgoliaItem, + fetchCommentsForItem, normalizeAlgoliaItemChildren, NotFoundError, + __resetFetchCachesForTests, } from './hn'; -import { http, HttpResponse } from 'msw'; -import { server } from '../mocks/server'; -import { FIREBASE_API } from '../config/api'; +import { hnSdk } from './hnSdk'; +import type { FirebaseItem } from '../types'; + +const mockFirebaseItem: FirebaseItem = { + id: 12345, + title: 'Rust Is the Future of JavaScript Infrastructure', + url: 'https://leerob.io/blog/rust', + by: 'leerob', + score: 284, + time: Math.floor(Date.now() / 1000) - 3600, + descendants: 137, + kids: [1001, 1002, 1003, 1004], + type: 'story', +}; + +const mockCommentItem: FirebaseItem = { + id: 1001, + by: 'patio11', + text: 'The wasm-bindgen approach is really interesting.', + time: Math.floor(Date.now() / 1000) - 1800, + parent: 12345, + kids: [2001], + type: 'comment', +}; describe('hn API utilities', () => { + beforeEach(() => { + __resetFetchCachesForTests(); + vi.restoreAllMocks(); + }); + describe('formatTimeAgo', () => { beforeEach(() => { vi.useFakeTimers(); @@ -416,13 +444,25 @@ describe('hn API utilities', () => { }); describe('fetchShowStories', () => { + const mockShowIds = [99999, 99998, 99997]; + const mockShowItems: Record = { + 99999: { id: 99999, title: 'Show HN: My Awesome Project', url: 'https://github.com/andydunstall/piko', by: 'andydunstall', score: 312, time: Math.floor(Date.now() / 1000) - 7200, descendants: 89, type: 'story' }, + 99998: { id: 99998, title: 'Show HN: Another Cool Demo', url: 'https://github.com/opticdev/optic', by: 'aidan_cully', score: 143, time: Math.floor(Date.now() / 1000) - 3600, descendants: 47, type: 'story' }, + 99997: { id: 99997, title: 'Show HN: Third Project', url: 'https://example.com', by: 'user3', score: 50, time: Math.floor(Date.now() / 1000) - 1800, descendants: 10, type: 'story' }, + }; + + beforeEach(() => { + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(mockShowIds); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => mockShowItems[Number(id)] ?? null); + }); + it('returns normalized Show HN items', async () => { const result = await fetchShowStories(0); expect(result.stories).toBeDefined(); expect(result.stories.length).toBeGreaterThan(0); expect(result.hasMore).toBeDefined(); - expect(result.nextWindow).toBe(1); + expect(result.nextOffset).toBe(20); }); it('returns items with show type', async () => { @@ -445,42 +485,59 @@ describe('hn API utilities', () => { expect(item).toHaveProperty('commentCount'); }); - it('sorts items by gravity score', async () => { + it('returns items in ranked order (same order as ID list)', async () => { const result = await fetchShowStories(0); - // With 2 mock items: - // - Item1: 312 pts, 2hr ago → gravity = (312-1)/(2+2)^1.8 ≈ 27.5 - // - Item2: 143 pts, 1hr ago → gravity = (143-1)/(1+2)^1.8 ≈ 22.8 - // Higher gravity score ranks first - expect(result.stories.length).toBe(2); - expect(result.stories[0].points).toBe(312); // Higher gravity score first - expect(result.stories[1].points).toBe(143); + expect(result.stories.length).toBe(3); + expect(result.stories[0].id).toBe(99999); + expect(result.stories[1].id).toBe(99998); + expect(result.stories[2].id).toBe(99997); }); it('returns correct pagination info', async () => { const result = await fetchShowStories(0); - expect(result.nextWindow).toBe(1); - expect(result.hasMore).toBe(true); // Always true when items are found (skips empty days) + expect(result.nextOffset).toBe(20); + expect(result.hasMore).toBe(false); }); - it('increments window index for next page', async () => { + it('paginates by offset', async () => { + const manyIds = Array.from({ length: 25 }, (_, i) => 90000 + i); + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(manyIds); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => ({ + id: Number(id), title: `Item ${id}`, by: 'user', score: 10, time: Math.floor(Date.now() / 1000), descendants: 0, type: 'story', + })); + const result1 = await fetchShowStories(0); - expect(result1.nextWindow).toBe(1); + expect(result1.nextOffset).toBe(20); + expect(result1.hasMore).toBe(true); - const result2 = await fetchShowStories(result1.nextWindow); - expect(result2.nextWindow).toBe(2); + const result2 = await fetchShowStories(result1.nextOffset); + expect(result2.stories.length).toBe(5); + expect(result2.hasMore).toBe(false); }); }); describe('fetchAskStories', () => { + const mockAskIds = [88888, 88887, 88886]; + const mockAskItems: Record = { + 88888: { id: 88888, title: 'Ask HN: What are you working on?', text: 'Tell me!', by: 'whoishiring', score: 245, time: Math.floor(Date.now() / 1000) - 7200, descendants: 312, type: 'story' }, + 88887: { id: 88887, title: 'Ask HN: Best resources to learn Rust?', text: 'Looking for help', by: 'rustlearner', score: 178, time: Math.floor(Date.now() / 1000) - 3600, descendants: 95, type: 'story' }, + 88886: { id: 88886, title: 'Ask HN: Favorite editor?', text: 'vim or emacs?', by: 'curious', score: 50, time: Math.floor(Date.now() / 1000) - 1800, descendants: 20, type: 'story' }, + }; + + beforeEach(() => { + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(mockAskIds); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => mockAskItems[Number(id)] ?? null); + }); + it('returns normalized Ask HN items', async () => { const result = await fetchAskStories(0); expect(result.stories).toBeDefined(); expect(result.stories.length).toBeGreaterThan(0); expect(result.hasMore).toBeDefined(); - expect(result.nextWindow).toBe(1); + expect(result.nextOffset).toBe(20); }); it('returns items with ask type', async () => { @@ -506,43 +563,57 @@ describe('hn API utilities', () => { it('handles Ask HN posts without URL', async () => { const result = await fetchAskStories(0); - // Ask HN posts typically have no external URL result.stories.forEach(item => { - // url can be null or undefined for Ask HN expect(item.url === null || item.url === undefined).toBe(true); }); }); - it('sorts items by gravity score', async () => { + it('returns items in ranked order (same order as ID list)', async () => { const result = await fetchAskStories(0); - // With 2 mock items: - // - Item1: 245 pts, 2hr ago → gravity = (245-1)/(2+2)^1.8 ≈ 17.5 - // - Item2: 178 pts, 1hr ago → gravity = (178-1)/(1+2)^1.8 ≈ 24.5 - // Higher gravity score ranks first - expect(result.stories.length).toBe(2); - expect(result.stories[0].points).toBe(178); // Higher gravity score first - expect(result.stories[1].points).toBe(245); + expect(result.stories.length).toBe(3); + expect(result.stories[0].id).toBe(88888); + expect(result.stories[1].id).toBe(88887); + expect(result.stories[2].id).toBe(88886); }); it('returns correct pagination info', async () => { const result = await fetchAskStories(0); - expect(result.nextWindow).toBe(1); - expect(result.hasMore).toBe(true); // Always true when items are found (skips empty days) + expect(result.nextOffset).toBe(20); + expect(result.hasMore).toBe(false); }); - it('increments window index for next page', async () => { + it('paginates by offset', async () => { + const manyIds = Array.from({ length: 25 }, (_, i) => 80000 + i); + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(manyIds); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => ({ + id: Number(id), title: `Item ${id}`, by: 'user', score: 10, time: Math.floor(Date.now() / 1000), descendants: 0, type: 'story', + })); + const result1 = await fetchAskStories(0); - expect(result1.nextWindow).toBe(1); + expect(result1.nextOffset).toBe(20); - const result2 = await fetchAskStories(result1.nextWindow); - expect(result2.nextWindow).toBe(2); + const result2 = await fetchAskStories(result1.nextOffset); + expect(result2.stories.length).toBe(5); + expect(result2.hasMore).toBe(false); }); }); describe('fetchTopStories', () => { - it('returns normalized items from Algolia', async () => { + const mockTopIds = [12345, 12346, 12347]; + const mockTopItems: Record = { + 12345: mockFirebaseItem, + 12346: { id: 12346, title: 'SQLite Does Not Do Full FSYNC by Default', url: 'https://sqlite.org/draft/wal.html', by: 'ingve', score: 198, time: Math.floor(Date.now() / 1000) - 7200, descendants: 73, type: 'story' }, + 12347: { id: 12347, title: 'Why We Moved from React to htmx', url: 'https://htmx.org/essays/react-to-htmx/', by: 'carsongross', score: 156, time: Math.floor(Date.now() / 1000) - 10800, descendants: 241, type: 'story' }, + }; + + beforeEach(() => { + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(mockTopIds); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => mockTopItems[Number(id)] ?? null); + }); + + it('returns normalized items from ranked list', async () => { const result = await fetchTopStories(20); expect(result).toBeDefined(); @@ -569,14 +640,26 @@ describe('hn API utilities', () => { expect(result.length).toBeLessThanOrEqual(20); }); - it('sorts items by gravity score', async () => { + it('returns items in ranked order (same as ID list)', async () => { const result = await fetchTopStories(20); - expect(result.length).toBeGreaterThan(0); + expect(result.length).toBe(3); + expect(result[0].id).toBe(12345); + expect(result[1].id).toBe(12346); + expect(result[2].id).toBe(12347); }); }); describe('fetchBestStories', () => { + const mockBestIds = [12345, 12346, 12347, 12348, 12349]; + + beforeEach(() => { + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(mockBestIds); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => ({ + id: Number(id), title: `Item ${id}`, by: 'testuser', score: 50, time: Math.floor(Date.now() / 1000) - 7200, descendants: 5, type: 'story', + })); + }); + it('returns items with pagination info', async () => { const result = await fetchBestStories(0, 30); @@ -614,6 +697,14 @@ describe('hn API utilities', () => { }); describe('fetchFirebaseItem', () => { + beforeEach(() => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345) return mockFirebaseItem; + if (Number(id) === 1001) return mockCommentItem; + return null; + }); + }); + it('fetches an item by ID', async () => { const result = await fetchFirebaseItem(12345); @@ -638,19 +729,20 @@ describe('hn API utilities', () => { .rejects.toThrow(); }); - it('throws NotFoundError when Firebase returns null for non-existent item', async () => { - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.json(null); - }), - ); - + it('throws NotFoundError when SDK returns null for non-existent item', async () => { await expect(fetchFirebaseItem(99999)).rejects.toThrow(NotFoundError); await expect(fetchFirebaseItem(99999)).rejects.toThrow('Item 99999 not found'); }); }); describe('fetchItemOnly', () => { + beforeEach(() => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345) return mockFirebaseItem; + return null; + }); + }); + it('returns item metadata without comments', async () => { const result = await fetchItemOnly(12345); @@ -668,18 +760,14 @@ describe('hn API utilities', () => { expect(result.type).not.toBe('comment'); if (result.type === 'comment') throw new Error('unexpected'); - // Firebase uses 'score' but we return 'points' expect(result.points).toBe(284); - // Firebase uses 'by' but we return 'author' expect(result.author).toBe('leerob'); - // Firebase uses 'descendants' but we return 'commentCount' expect(result.type !== 'job' ? result.commentCount : 0).toBe(137); }); it('converts Unix timestamp to milliseconds', async () => { const result = await fetchItemOnly(12345); - // createdAt should be in milliseconds (> 1 trillion) expect(result.createdAt).toBeGreaterThan(1000000000000); }); @@ -797,4 +885,59 @@ describe('hn API utilities', () => { expect(result).toEqual([]); }); }); + + describe('fetchCommentsForItem', () => { + it('drops orphaned comments whose parent is dead (not in Algolia)', async () => { + const itemId = 9000; + + // Item has 3 root-level kids: 101 (alive), 102 (dead), 103 (alive) + const firebaseItem: FirebaseItem = { + id: itemId, + title: 'Test Story', + by: 'author', + score: 10, + time: 1700000000, + descendants: 5, + kids: [101, 102, 103], + type: 'story', + }; + + // Comment 102 is dead — Algolia won't return it. + // Comments 201, 202 are children of the dead comment 102. + const algoliaHits = [ + { objectID: '101', author: 'alice', comment_text: 'Alive root', created_at_i: 1700000100, parent_id: itemId }, + { objectID: '103', author: 'bob', comment_text: 'Also alive root', created_at_i: 1700000200, parent_id: itemId }, + { objectID: '201', author: 'charlie', comment_text: 'Reply to dead parent', created_at_i: 1700000300, parent_id: 102 }, + { objectID: '202', author: 'dave', comment_text: 'Another reply to dead parent', created_at_i: 1700000400, parent_id: 102 }, + ]; + + // Mock hnSdk.readItem for the initial item fetch and kids ordering + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === itemId) return firebaseItem; + return null; + }); + + // Mock fetch for Algolia search + const mockFetch = vi.spyOn(globalThis, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ hits: algoliaHits, nbHits: algoliaHits.length }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }), + ); + + const comments = await fetchCommentsForItem(itemId); + + // Only the 2 alive root comments should appear; orphans 201/202 are dropped + expect(comments).toHaveLength(2); + expect(comments[0].id).toBe(101); + expect(comments[1].id).toBe(103); + + // Orphaned comments should NOT be promoted to root + const allIds = comments.map(c => c.id); + expect(allIds).not.toContain(201); + expect(allIds).not.toContain(202); + + mockFetch.mockRestore(); + }); + }); }); diff --git a/src/api/hn.ts b/src/api/hn.ts index 9ccc114..c2ddae9 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -1,4 +1,5 @@ -import { ALGOLIA_API, FIREBASE_API } from '../config/api'; +import { ALGOLIA_API } from '../config/api'; +import { hnSdk } from './hnSdk'; import type { Item, StoryItem, Comment, AlgoliaHit, AlgoliaComment, AlgoliaSearchResponse, FirebaseItem, PrefetchResult, AlgoliaItemResponse, AlgoliaItemChild } from '../types'; export class NotFoundError extends Error { @@ -9,15 +10,15 @@ export class NotFoundError extends Error { } let bestStoriesCache: { ids: number[] | null; timestamp: number } = { ids: null, timestamp: 0 }; +let showStoriesCache: { ids: number[] | null; timestamp: number } = { ids: null, timestamp: 0 }; +let askStoriesCache: { ids: number[] | null; timestamp: number } = { ids: null, timestamp: 0 }; const CACHE_TTL = 5 * 60 * 1000; // 5 minutes -// HN's gravity constant for ranking -const HN_GRAVITY = 1.8; - -// score = (points - 1) / pow((hoursAgo + 2), gravity) -function calculateHNScore(points: number, createdAtMs: number): number { - const hoursAgo = (Date.now() - createdAtMs) / (1000 * 60 * 60); - return (points - 1) / Math.pow(hoursAgo + 2, HN_GRAVITY); +/** @internal Testing helper to reset module-level caches between tests. */ +export function __resetFetchCachesForTests() { + bestStoriesCache = { ids: null, timestamp: 0 }; + showStoriesCache = { ids: null, timestamp: 0 }; + askStoriesCache = { ids: null, timestamp: 0 }; } function getDayRange(daysAgo = 0) { @@ -92,34 +93,30 @@ function normalizeFirebaseItem(fbItem: FirebaseItem): Item { } /** - * Current front page stories from Algolia. Sorted by HN's gravity algorithm - * for approximate ranking (HN's actual ranking isn't exposed via the API). + * Top stories from HN's official ranked list. Items are returned in HN's + * native ranking order (no local gravity approximation needed). */ export async function fetchTopStories(limit = 20): Promise { - const url = `${ALGOLIA_API}/search?tags=front_page&hitsPerPage=${limit}`; - - const response = await fetch(url); - if (!response.ok) { - throw new Error(`Failed to fetch top stories: ${response.status}`); + const allIds = await hnSdk.readRankedIds('topstories'); + const stories: StoryItem[] = []; + let cursor = 0; + + while (stories.length < limit && cursor < allIds.length) { + const batchIds = allIds.slice(cursor, cursor + limit * 2); + const items = await Promise.all( + batchIds.map(id => hnSdk.readItem(id).catch(() => null)) + ); + for (const item of items) { + if (stories.length >= limit) break; + if (!item || item.deleted || item.dead) continue; + if (item.type === 'job') continue; + const title = (item.title ?? '').toLowerCase(); + if (title.includes('who is hiring') || title.includes('who wants to be hired')) continue; + stories.push(normalizeFirebaseToStoryItem(item)); + } + cursor += batchIds.length; } - - const data = await response.json() as AlgoliaSearchResponse; - - const stories = data.hits - .filter((hit) => { - if (hit.type === 'job' || hit._tags?.includes('job')) return false; - const title = (hit.title || '').toLowerCase(); - if (title.includes('who is hiring') || title.includes('who wants to be hired')) return false; - return true; - }) - .map(normalizeAlgoliaHit); - - stories.sort((a, b) => { - const scoreA = calculateHNScore(a.points, a.createdAt); - const scoreB = calculateHNScore(b.points, b.createdAt); - return scoreB - scoreA; - }); - + return stories; } @@ -161,11 +158,7 @@ export async function fetchBestStories(offset = 0, limit = 30) { const now = Date.now(); if (!bestStoriesCache.ids || (now - bestStoriesCache.timestamp) >= CACHE_TTL) { - const response = await fetch(`${FIREBASE_API}/beststories.json`); - if (!response.ok) { - throw new Error(`Failed to fetch best stories: ${response.status}`); - } - bestStoriesCache = { ids: await response.json() as number[], timestamp: now }; + bestStoriesCache = { ids: await hnSdk.readRankedIds('beststories'), timestamp: now }; } const allIds = bestStoriesCache.ids ?? []; @@ -176,7 +169,7 @@ export async function fetchBestStories(offset = 0, limit = 30) { } const fetched = await Promise.all( - pageIds.map((id: number) => fetchFirebaseItem(id).catch(() => null)) + pageIds.map((id: number) => hnSdk.readItem(id).catch(() => null)) ); const stories = fetched @@ -204,68 +197,54 @@ function normalizeFirebaseToStoryItem(fb: FirebaseItem): StoryItem { }; } -// Top 20 stories per 24-hour window, sorted by HN gravity. Skips empty days -// (up to 30 consecutive) so users don't dead-end on a quiet day. -async function fetchTaggedStories(tag: string, windowIndex = 0) { - const now = Math.floor(Date.now() / 1000); - const maxEmptyDays = 30; - - let currentWindow = windowIndex; - let attempts = 0; - - while (attempts < maxEmptyDays) { - const windowStart = now - ((currentWindow + 1) * 24 * 60 * 60); - const windowEnd = now - (currentWindow * 24 * 60 * 60); - - const url = `${ALGOLIA_API}/search?tags=${tag}&numericFilters=created_at_i>${windowStart},created_at_i<=${windowEnd}&hitsPerPage=100`; - - const response = await fetch(url); - if (!response.ok) { - throw new Error(`Failed to fetch ${tag} stories: ${response.status}`); - } - - const data = await response.json() as AlgoliaSearchResponse; - const stories = data.hits.map(normalizeAlgoliaHit); - - if (stories.length > 0) { - stories.sort((a, b) => { - const scoreA = calculateHNScore(a.points, a.createdAt); - const scoreB = calculateHNScore(b.points, b.createdAt); - return scoreB - scoreA; - }); - - return { - stories: stories.slice(0, 20), - hasMore: true, - nextWindow: currentWindow + 1, - }; - } - - currentWindow++; - attempts++; +async function fetchRankedStories( + list: string, + cache: { ids: number[] | null; timestamp: number }, + type: 'show' | 'ask', + offset = 0, + limit = 20, +) { + const now = Date.now(); + if (!cache.ids || (now - cache.timestamp) >= CACHE_TTL) { + cache.ids = await hnSdk.readRankedIds(list); + cache.timestamp = now; } - + + const allIds = cache.ids ?? []; + const pageIds = allIds.slice(offset, offset + limit); + + if (pageIds.length === 0) { + return { stories: [] as StoryItem[], hasMore: false, nextOffset: offset }; + } + + const items = await Promise.all( + pageIds.map(id => hnSdk.readItem(id).catch(() => null)) + ); + + const stories = items + .filter((fb): fb is FirebaseItem => fb != null && !fb.deleted && !fb.dead) + .map(fb => ({ ...normalizeFirebaseToStoryItem(fb), type: type })); + return { - stories: [] as StoryItem[], - hasMore: false, - nextWindow: currentWindow, + stories, + hasMore: offset + limit < allIds.length, + nextOffset: offset + limit, }; } -export function fetchShowStories(windowIndex = 0) { - return fetchTaggedStories('show_hn', windowIndex); +export function fetchShowStories(offset = 0) { + return fetchRankedStories('showstories', showStoriesCache, 'show', offset); } -export function fetchAskStories(windowIndex = 0) { - return fetchTaggedStories('ask_hn', windowIndex); +export function fetchAskStories(offset = 0) { + return fetchRankedStories('askstories', askStoriesCache, 'ask', offset); } export async function fetchFirebaseItem(id: number | string, signal?: AbortSignal): Promise { - const response = await fetch(`${FIREBASE_API}/item/${id}.json`, { signal }); - if (!response.ok) { - throw new Error(`Failed to fetch item ${id}: ${response.status}`); + if (signal?.aborted) { + throw new DOMException('Aborted', 'AbortError'); } - const item = await response.json() as FirebaseItem | null; + const item = await hnSdk.readItem(id); if (item == null) { throw new NotFoundError(`Item ${id} not found`); } @@ -330,10 +309,10 @@ function buildCommentTree(comments: AlgoliaComment[], itemId: number, kidsOrder const parent = commentMap.get(comment.parentId); if (parent) { parent.children.push(comment); - } else { - // Parent not found (might be deleted), treat as root - rootComments.push(comment); } + // Parent not in map → parent is dead/deleted. HN hides the entire + // subtree under a dead comment, so we drop the orphan (its children + // still attach to it in the map but the subtree is unreachable). } }); @@ -452,7 +431,7 @@ async function fetchKidsOrdering(commentIds: number[], signal?: AbortSignal): Pr const results = await Promise.all( batch.map(async (id) => { try { - const item = await fetchFirebaseItem(id, signal); + const item = await hnSdk.readItem(id); if (item?.kids) { return { id: item.id, kids: item.kids }; } diff --git a/src/api/hnSdk.test.ts b/src/api/hnSdk.test.ts new file mode 100644 index 0000000..c65ae7d --- /dev/null +++ b/src/api/hnSdk.test.ts @@ -0,0 +1,35 @@ +import { describe, it, expect } from 'vitest'; +import { hnSdk } from './hnSdk'; + +/** + * Tests for the username validation guard in hnSdk.readUser. + * Invalid usernames should return null WITHOUT hitting Firebase. + * We test this by verifying that invalid inputs return null synchronously-fast, + * which proves the guard short-circuits before the network call. + */ +describe('hnSdk.readUser input validation', () => { + it('rejects usernames containing slashes (path traversal)', async () => { + expect(await hnSdk.readUser('pg/karma')).toBeNull(); + }); + + it('rejects dot-dot traversal attempts', async () => { + expect(await hnSdk.readUser('../item/12345')).toBeNull(); + expect(await hnSdk.readUser('foo/../bar')).toBeNull(); + }); + + it('rejects usernames that are too long', async () => { + expect(await hnSdk.readUser('a'.repeat(16))).toBeNull(); + }); + + it('rejects empty or single-char usernames', async () => { + expect(await hnSdk.readUser('')).toBeNull(); + expect(await hnSdk.readUser('x')).toBeNull(); + }); + + it('rejects usernames with special characters', async () => { + expect(await hnSdk.readUser('user.name')).toBeNull(); + expect(await hnSdk.readUser('user name')).toBeNull(); + expect(await hnSdk.readUser('user#1')).toBeNull(); + expect(await hnSdk.readUser('user$1')).toBeNull(); + }); +}); diff --git a/src/api/hnSdk.ts b/src/api/hnSdk.ts new file mode 100644 index 0000000..95329f9 --- /dev/null +++ b/src/api/hnSdk.ts @@ -0,0 +1,36 @@ +import { getApps, initializeApp } from 'firebase/app'; +import { get, getDatabase, ref } from 'firebase/database'; +import type { FirebaseItem, UserProfile } from '../types'; + +const APP_NAME = 'hn-sdk'; + +function getDb() { + const existing = getApps().find(app => app.name === APP_NAME); + const app = existing + ?? initializeApp( + { databaseURL: 'https://hacker-news.firebaseio.com' }, + APP_NAME, + ); + return getDatabase(app); +} + +const db = getDb(); + +// Object seam — tests can vi.spyOn(hnSdk, 'readItem') without module-mock hoisting issues +export const hnSdk = { + async readRankedIds(list: string): Promise { + const snapshot = await get(ref(db, `v0/${list}`)); + return (snapshot.val() as number[] | null) ?? []; + }, + + async readItem(id: number | string): Promise { + const snapshot = await get(ref(db, `v0/item/${id}`)); + return snapshot.val() as FirebaseItem | null; + }, + + async readUser(username: string): Promise { + if (!/^[a-zA-Z0-9_-]{2,15}$/.test(username)) return null; + const snapshot = await get(ref(db, `v0/user/${username}`)); + return snapshot.val() as UserProfile | null; + }, +}; diff --git a/src/components/FullScreenComment.test.tsx b/src/components/FullScreenComment.test.tsx index 154ed29..a9c982d 100644 --- a/src/components/FullScreenComment.test.tsx +++ b/src/components/FullScreenComment.test.tsx @@ -1,14 +1,36 @@ -import { describe, it, expect, afterEach } from 'vitest'; +import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'; import { screen, waitFor } from '@testing-library/react'; import { render } from '../test/test-utils'; import { FullScreenComment } from './FullScreenComment'; import { http, HttpResponse } from 'msw'; import { server } from '../mocks/server'; import { ALGOLIA_API } from '../config/api'; +import { hnSdk } from '../api/hnSdk'; +import type { FirebaseItem } from '../types'; + +const mockItem: FirebaseItem = { + id: 12345, + title: 'Rust Is the Future of JavaScript Infrastructure', + url: 'https://leerob.io/blog/rust', + by: 'leerob', + score: 284, + time: Math.floor(Date.now() / 1000) - 3600, + descendants: 137, + kids: [1001, 1002, 1003, 1004], + type: 'story', +}; describe('FullScreenComment', () => { + beforeEach(() => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345) return mockItem; + return null; + }); + }); + afterEach(() => { server.resetHandlers(); + vi.restoreAllMocks(); }); it('renders comment author and text', async () => { diff --git a/src/components/FullScreenItem.test.tsx b/src/components/FullScreenItem.test.tsx index 68bc8f3..e33afaf 100644 --- a/src/components/FullScreenItem.test.tsx +++ b/src/components/FullScreenItem.test.tsx @@ -1,15 +1,34 @@ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'; import { screen, waitFor, fireEvent } from '@testing-library/react'; import { render } from '../test/test-utils'; import { FullScreenItem } from './FullScreenItem'; import { clearViewed, markViewed, isViewed } from '../utils/viewedItems'; -import { http, HttpResponse } from 'msw'; -import { server } from '../mocks/server'; -import { FIREBASE_API } from '../config/api'; +import { hnSdk } from '../api/hnSdk'; +import type { FirebaseItem } from '../types'; + +const defaultItem: FirebaseItem = { + id: 12345, + title: 'Rust Is the Future of JavaScript Infrastructure', + url: 'https://leerob.io/blog/rust', + by: 'leerob', + score: 284, + time: Math.floor(Date.now() / 1000) - 3600, + descendants: 137, + kids: [1001, 1002, 1003, 1004], + type: 'story', +}; describe('FullScreenItem', () => { beforeEach(() => { clearViewed(); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345) return defaultItem; + return null; + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); }); describe('viewed state', () => { @@ -48,30 +67,12 @@ describe('FullScreenItem', () => { describe('comment handling', () => { it('shows "Item not found" when item type is comment', async () => { - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, ({ params }) => { - const id = parseInt(params.id as string, 10); - if (id === 1001) { - return HttpResponse.json({ - id: 1001, - by: 'patio11', - text: 'The wasm-bindgen approach is really interesting.', - time: Math.floor(Date.now() / 1000) - 1800, - parent: 12345, - type: 'comment', - }); - } - return HttpResponse.json({ - id, - title: 'Rust Is the Future of JavaScript Infrastructure', - by: 'leerob', - score: 284, - time: Math.floor(Date.now() / 1000) - 3600, - descendants: 137, - type: 'story', - }); - }), - ); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 1001) { + return { id: 1001, by: 'patio11', text: 'The wasm-bindgen approach is really interesting.', time: Math.floor(Date.now() / 1000) - 1800, parent: 12345, type: 'comment' }; + } + return { id: Number(id), title: 'Rust Is the Future of JavaScript Infrastructure', by: 'leerob', score: 284, time: Math.floor(Date.now() / 1000) - 3600, descendants: 137, type: 'story' }; + }); render(); diff --git a/src/components/SwipeCommentViewer.test.tsx b/src/components/SwipeCommentViewer.test.tsx index 0051dfc..a29ca92 100644 --- a/src/components/SwipeCommentViewer.test.tsx +++ b/src/components/SwipeCommentViewer.test.tsx @@ -4,7 +4,9 @@ import { render } from '../test/test-utils'; import { SwipeCommentViewer } from './SwipeCommentViewer'; import { http, HttpResponse } from 'msw'; import { server } from '../mocks/server'; -import { ALGOLIA_API, FIREBASE_API } from '../config/api'; +import { hnSdk } from '../api/hnSdk'; +import { ALGOLIA_API } from '../config/api'; +import type { FirebaseItem } from '../types'; // SwipeCommentViewer uses window.innerWidth for scroll calculations. // jsdom defaults to 0, so set a meaningful width for virtualization tests. @@ -15,12 +17,25 @@ beforeEach(() => { Element.prototype.scrollTo = vi.fn(); }); +const defaultItems: Record = { + 1001: { id: 1001, by: 'patio11', text: 'The wasm-bindgen approach is really interesting.', time: Math.floor(Date.now() / 1000) - 1800, parent: 12345, kids: [2001], type: 'comment' }, + 1002: { id: 1002, by: 'jgrahamc', text: 'Great point about performance.', time: Math.floor(Date.now() / 1000) - 600, parent: 12345, type: 'comment' }, + 1003: { id: 1003, by: 'dang', text: 'Worth reading the follow-up.', time: Math.floor(Date.now() / 1000) - 300, parent: 12345, type: 'comment' }, + 1004: { id: 1004, by: 'leerob', text: 'Author here — thanks!', time: Math.floor(Date.now() / 1000) - 100, parent: 12345, type: 'comment' }, + 12345: { id: 12345, title: 'Rust Is the Future of JavaScript Infrastructure', by: 'leerob', score: 284, time: Math.floor(Date.now() / 1000) - 3600, descendants: 137, kids: [1001, 1002, 1003, 1004], type: 'story' }, +}; + describe('SwipeCommentViewer', () => { + beforeEach(() => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => defaultItems[Number(id)] ?? null); + }); + afterEach(() => { + vi.restoreAllMocks(); server.resetHandlers(); }); - it('renders swipe container with skeleton while loading', () => { + it('renders swipe container with skeleton while loading', async () => { render(, { initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }], }); @@ -30,6 +45,11 @@ describe('SwipeCommentViewer', () => { const panels = screen.getAllByTestId('swipe-panel'); expect(panels.length).toBeGreaterThanOrEqual(1); + + // Let async updates settle to avoid act() warnings + await waitFor(() => { + expect(screen.getAllByTestId('swipe-panel').length).toBeGreaterThanOrEqual(1); + }); }); it('renders sibling comment panels after loading', async () => { @@ -49,14 +69,7 @@ describe('SwipeCommentViewer', () => { }); it('shows error state when Firebase fetch fails', async () => { - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.json( - { status: 500, error: 'Server Error' }, - { status: 500 }, - ); - }), - ); + vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('Server Error')); render(, { initialEntries: [{ pathname: '/item/999', state: { isComment: true } }], @@ -69,21 +82,14 @@ describe('SwipeCommentViewer', () => { }, 35000); it('renders single panel when comment has no parent', async () => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 7777) { + return { id: 7777, by: 'solo', text: 'Top-level comment with no parent.', time: Math.floor(Date.now() / 1000) - 300, type: 'comment' }; + } + return null; + }); + server.use( - http.get(`${FIREBASE_API}/item/:id.json`, ({ params }) => { - const id = parseInt(params.id as string, 10); - if (id === 7777) { - return HttpResponse.json({ - id: 7777, - by: 'solo', - text: 'Top-level comment with no parent.', - time: Math.floor(Date.now() / 1000) - 300, - type: 'comment', - // No parent → single-panel branch. - }); - } - return HttpResponse.json(null); - }), // FullScreenComment's useCommentDetail hits Algolia. http.get(`${ALGOLIA_API}/items/:id`, () => { return HttpResponse.json({ @@ -115,27 +121,16 @@ describe('SwipeCommentViewer', () => { // 7 kids exercises the BUFFER=±2 boundary: 3 real, 4 skeleton. const manyKids = [3001, 3002, 3003, 3004, 3005, 3006, 3007]; + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 50000) { + return { id: 50000, title: 'Big Thread', by: 'poster', type: 'story', kids: manyKids }; + } + return { + id: Number(id), by: `user${id}`, text: `Comment ${id}`, time: Math.floor(Date.now() / 1000) - 300, parent: 50000, type: 'comment', + }; + }); + server.use( - http.get(`${FIREBASE_API}/item/:id.json`, ({ params }) => { - const id = parseInt(params.id as string, 10); - if (id === 50000) { - return HttpResponse.json({ - id: 50000, - title: 'Big Thread', - by: 'poster', - type: 'story', - kids: manyKids, - }); - } - return HttpResponse.json({ - id, - by: `user${id}`, - text: `Comment ${id}`, - time: Math.floor(Date.now() / 1000) - 300, - parent: 50000, - type: 'comment', - }); - }), http.get(`${ALGOLIA_API}/items/:id`, ({ params }) => { const id = parseInt(params.id as string, 10); return HttpResponse.json({ diff --git a/src/components/index.ts b/src/components/index.ts index aa1493c..c8ec494 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -15,10 +15,6 @@ export { FullScreenChrome } from './FullScreenChrome'; export { FullScreenItem, FullScreenItemSkeleton, FullScreenItemSkeletonPanel } from './FullScreenItem'; export { ItemArticle } from './ItemArticle'; export { FullScreenComment, FullScreenCommentSkeleton, FullScreenCommentSkeletonPanel } from './FullScreenComment'; -export { SwipeStoryViewer } from './SwipeStoryViewer'; -export { SwipeDomainStoryViewer } from './SwipeDomainStoryViewer'; -export { SwipeUserSubmissionsViewer } from './SwipeUserSubmissionsViewer'; -export { SwipeCommentViewer } from './SwipeCommentViewer'; export { CommentsSection } from './CommentsSection'; export { StateView } from './StateView'; export { NetworkStatusBar } from './NetworkStatusBar'; diff --git a/src/config/api.ts b/src/config/api.ts index ba4710b..a9db856 100644 --- a/src/config/api.ts +++ b/src/config/api.ts @@ -1,2 +1 @@ export const ALGOLIA_API = 'https://hn.algolia.com/api/v1'; -export const FIREBASE_API = 'https://hacker-news.firebaseio.com/v0'; diff --git a/src/hooks/useCommentDetail.test.ts b/src/hooks/useCommentDetail.test.ts index 035902c..a437882 100644 --- a/src/hooks/useCommentDetail.test.ts +++ b/src/hooks/useCommentDetail.test.ts @@ -1,12 +1,33 @@ -import { describe, it, expect, afterEach } from 'vitest'; +import { describe, it, expect, afterEach, vi, beforeEach } from 'vitest'; import { renderHook, waitFor } from '@testing-library/react'; import { http, HttpResponse } from 'msw'; import { useCommentDetail } from './useCommentDetail'; +import { hnSdk } from '../api/hnSdk'; import { server } from '../mocks/server'; -import { ALGOLIA_API, FIREBASE_API } from '../config/api'; +import { ALGOLIA_API } from '../config/api'; +import type { FirebaseItem } from '../types'; + +const mockStoryItem: FirebaseItem = { + id: 12345, + title: 'Rust Is the Future of JavaScript Infrastructure', + by: 'leerob', + score: 284, + time: Math.floor(Date.now() / 1000) - 3600, + descendants: 137, + kids: [1001, 1002, 1003, 1004], + type: 'story', +}; describe('useCommentDetail', () => { + beforeEach(() => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345) return mockStoryItem; + return null; + }); + }); + afterEach(() => { + vi.restoreAllMocks(); server.resetHandlers(); }); @@ -78,12 +99,8 @@ describe('useCommentDetail', () => { }); it('degrades gracefully when item title fetch fails', async () => { - // Only Firebase fails — Algolia (comment + replies) still succeeds. - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.json(null, { status: 500 }); - }), - ); + // Only the SDK item fetch fails — Algolia (comment + replies) still succeeds. + vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('SDK error')); const { result } = renderHook(() => useCommentDetail(1001)); diff --git a/src/hooks/useInfiniteStories.test.ts b/src/hooks/useInfiniteStories.test.ts index 8c399a9..7175a00 100644 --- a/src/hooks/useInfiniteStories.test.ts +++ b/src/hooks/useInfiniteStories.test.ts @@ -1,10 +1,29 @@ -import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { renderHook, act } from '@testing-library/react'; import { useInfiniteStories } from './useInfiniteStories'; import { setCachedFeed, clearFeedCache } from '../utils/feedCache'; import { clearListSessionState } from '../utils/itemCache'; import { createStoryItem } from '../test/factories'; import { server } from '../mocks/server'; +import { hnSdk } from '../api/hnSdk'; +import { __resetFetchCachesForTests } from '../api/hn'; +import type { FirebaseItem } from '../types'; + +function makeFirebaseItem(id: number): FirebaseItem { + return { + id, + title: `Story ${id}`, + url: `https://example.com/${id}`, + by: 'testuser', + score: 50 + id, + time: Math.floor(Date.now() / 1000) - 3600, + descendants: 5, + type: 'story', + }; +} + +// Generate 50 item IDs for ranked lists +const rankedIds = Array.from({ length: 50 }, (_, i) => i + 1); describe('useInfiniteStories', () => { beforeEach(() => { @@ -13,11 +32,15 @@ describe('useInfiniteStories', () => { clearListSessionState('best'); clearListSessionState('show'); clearListSessionState('ask'); + __resetFetchCachesForTests(); + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(rankedIds); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => makeFirebaseItem(Number(id))); }); afterEach(() => { server.resetHandlers(); clearFeedCache(); + vi.restoreAllMocks(); }); it('loads stories on first loadMore when no cache', async () => { diff --git a/src/hooks/useInfiniteStories.ts b/src/hooks/useInfiniteStories.ts index 0ed47b7..e911557 100644 --- a/src/hooks/useInfiniteStories.ts +++ b/src/hooks/useInfiniteStories.ts @@ -215,7 +215,7 @@ export function useInfiniteStories(type: FeedType = 'top') { hasStaleCacheRef.current = false; } - positionRef.current = result.nextWindow; + positionRef.current = result.nextOffset; setHasMore(result.hasMore); if (uniqueStories.length > 0) { diff --git a/src/hooks/useItemWithComments.test.tsx b/src/hooks/useItemWithComments.test.tsx index 776c053..bf482b3 100644 --- a/src/hooks/useItemWithComments.test.tsx +++ b/src/hooks/useItemWithComments.test.tsx @@ -5,12 +5,25 @@ import { useItemWithComments } from './useItemWithComments'; import { setCachedItem, getCachedItem, ITEM_CACHE_KEY_PREFIX } from '../utils/itemCache'; import { _resetForTesting, isPriorityFetchActive } from '../utils/fetchPriority'; import { server } from '../mocks/server'; -import { FIREBASE_API, ALGOLIA_API } from '../config/api'; -import type { Comment } from '../types'; +import { hnSdk } from '../api/hnSdk'; +import { ALGOLIA_API } from '../config/api'; +import type { Comment, FirebaseItem } from '../types'; import { createStoryItem, createComment } from '../test/factories'; import { NetworkStatusProvider } from '../context/NetworkStatusContext'; import type { ReactNode } from 'react'; +const mockFirebaseStory: FirebaseItem = { + id: 12345, + title: 'Sample HN Post', + url: 'https://example.com', + by: 'testuser', + score: 100, + time: Math.floor(Date.now() / 1000) - 3600, + descendants: 3, + kids: [1001, 1002], + type: 'story', +}; + const testItem = createStoryItem({ id: 12345, title: 'Sample HN Post', @@ -31,10 +44,15 @@ describe('useItemWithComments', () => { beforeEach(() => { localStorage.clear(); _resetForTesting(); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345) return mockFirebaseStory; + return null; + }); }); afterEach(() => { _resetForTesting(); + vi.restoreAllMocks(); }); describe('basic fetching', () => { @@ -175,11 +193,7 @@ describe('useItemWithComments', () => { }); it('unregisters priority on item fetch failure', async () => { - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.json(null, { status: 500 }); - }) - ); + vi.spyOn(hnSdk, 'readItem').mockResolvedValue(null); expect(isPriorityFetchActive()).toBe(false); @@ -271,7 +285,7 @@ describe('useItemWithComments', () => { return originalAbort.call(this); }; - const { rerender } = renderHook( + const { result, rerender } = renderHook( ({ itemId }) => useItemWithComments(itemId), { initialProps: { itemId: 12345 } } ); @@ -281,6 +295,11 @@ describe('useItemWithComments', () => { expect(abortSpy).toHaveBeenCalled(); AbortController.prototype.abort = originalAbort; + + // Let async updates settle to avoid act() warnings + await waitFor(() => { + expect(result.current.itemLoading).toBe(false); + }); }); it('does NOT abort when deferComments changes to true (same itemId)', async () => { @@ -345,11 +364,7 @@ describe('useItemWithComments', () => { describe('error handling', () => { it('sets error state on item fetch failure', async () => { - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.error(); - }) - ); + vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('Network error')); const { result } = renderHook(() => useItemWithComments(12345)); @@ -622,10 +637,10 @@ describe('useItemWithComments', () => { // 50ms delay simulates a real network round trip so the test can // observe the "loading null" intermediate state. - server.use( - http.get('https://hacker-news.firebaseio.com/v0/item/44444.json', async () => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 44444) { await new Promise(resolve => setTimeout(resolve, 50)); - return HttpResponse.json({ + return { id: 44444, type: 'story', title: 'Fresh Item B', @@ -633,10 +648,11 @@ describe('useItemWithComments', () => { score: 200, by: 'user2', time: Math.floor(Date.now() / 1000), - descendants: 10 - }); - }) - ); + descendants: 10, + }; + } + return mockFirebaseStory; + }); const { result, rerender } = renderHook( ({ itemId }) => useItemWithComments(itemId), @@ -650,6 +666,11 @@ describe('useItemWithComments', () => { // Either null (loading) or the new B is acceptable; the old A is not. expect(result.current.item?.id).not.toBe(33333); + + // Let async updates settle to avoid act() warnings + await waitFor(() => { + expect(result.current.itemLoading).toBe(false); + }); }); }); @@ -784,12 +805,10 @@ describe('useItemWithComments', () => { expect(result.current.commentsLoading).toBe(true); // Both endpoints must fail since fetchCommentsForItem touches Firebase too. + vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('Offline')); server.use( http.get(`${ALGOLIA_API}/search`, () => { return new HttpResponse(null, { status: 500 }); - }), - http.get(`${FIREBASE_API}/item/:id.json`, () => { - return new HttpResponse(null, { status: 500 }); }) ); @@ -815,15 +834,10 @@ describe('useItemWithComments', () => { expect(result.current.itemLoading).toBe(false); // Slow the refresh fetch so the synchronous loading flip is observable. - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, async () => { - await new Promise(r => setTimeout(r, 200)); - return HttpResponse.json({ - id: 12345, type: 'story', title: 'Sample HN Post', url: 'https://example.com', - score: 100, by: 'testuser', time: Math.floor(Date.now() / 1000), descendants: 3, - }); - }) - ); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async () => { + await new Promise(r => setTimeout(r, 200)); + return mockFirebaseStory; + }); // Loading states must flip BEFORE the await, not after the fetch settles. let refreshPromise: Promise; @@ -841,11 +855,7 @@ describe('useItemWithComments', () => { }); it('clears error and commentsError during refresh', async () => { - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.error(); - }) - ); + vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('Network error')); const { result } = renderHook(() => useItemWithComments(12345)); @@ -853,7 +863,7 @@ describe('useItemWithComments', () => { expect(result.current.error).toBeTruthy(); }); - server.resetHandlers(); + vi.spyOn(hnSdk, 'readItem').mockResolvedValue(mockFirebaseStory); let refreshPromise: Promise; act(() => { @@ -880,11 +890,7 @@ describe('useItemWithComments', () => { expect(result.current.commentsLoading).toBe(false); }); - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.error(); - }) - ); + vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('Network error')); await act(async () => { await result.current.refresh().catch(() => { /* error set internally */ }); diff --git a/src/hooks/useSiblingComments.test.ts b/src/hooks/useSiblingComments.test.ts index c2d4fcd..8eb6f1f 100644 --- a/src/hooks/useSiblingComments.test.ts +++ b/src/hooks/useSiblingComments.test.ts @@ -1,22 +1,38 @@ -import { describe, it, expect, afterEach, vi } from 'vitest'; +import { describe, it, expect, afterEach, vi, beforeEach } from 'vitest'; import { renderHook, waitFor } from '@testing-library/react'; -import { http, HttpResponse } from 'msw'; import { useSiblingComments } from './useSiblingComments'; -import { server } from '../mocks/server'; -import { FIREBASE_API } from '../config/api'; +import { hnSdk } from '../api/hnSdk'; +import type { FirebaseItem } from '../types'; + +const mockItems: Record = { + 1001: { id: 1001, by: 'patio11', text: 'Great comment', time: Math.floor(Date.now() / 1000) - 1800, parent: 12345, kids: [2001], type: 'comment' }, + 1002: { id: 1002, by: 'jgrahamc', text: 'Another comment', time: Math.floor(Date.now() / 1000) - 600, parent: 12345, type: 'comment' }, + 1003: { id: 1003, by: 'dang', text: 'Mod comment', time: Math.floor(Date.now() / 1000) - 300, parent: 12345, type: 'comment' }, + 1004: { id: 1004, by: 'leerob', text: 'Author comment', time: Math.floor(Date.now() / 1000) - 100, parent: 12345, type: 'comment' }, + 12345: { id: 12345, title: 'Sample Story', by: 'poster', score: 100, time: Math.floor(Date.now() / 1000) - 3600, descendants: 137, kids: [1001, 1002, 1003, 1004], type: 'story' }, +}; describe('useSiblingComments', () => { + beforeEach(() => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => mockItems[Number(id)] ?? null); + }); + afterEach(() => { - server.resetHandlers(); + vi.restoreAllMocks(); }); - it('returns the target comment immediately while loading', () => { + it('returns the target comment immediately while loading', async () => { const { result } = renderHook(() => useSiblingComments(1001)); expect(result.current.siblingIds).toEqual([1001]); expect(result.current.currentIndex).toBe(0); expect(result.current.loading).toBe(true); expect(result.current.error).toBeNull(); + + // Let async updates settle to avoid act() warnings + await waitFor(() => { + expect(result.current.loading).toBe(false); + }); }); it('accepts string IDs (from URL params)', async () => { @@ -57,22 +73,12 @@ describe('useSiblingComments', () => { }); it('returns single comment when parent_id is null', async () => { - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, ({ params }) => { - const id = parseInt(params.id as string, 10); - if (id === 7777) { - return HttpResponse.json({ - id: 7777, - by: 'someone', - text: 'A top-level comment.', - time: Math.floor(Date.now() / 1000) - 300, - type: 'comment', - // omitted parent → top-level - }); - } - return HttpResponse.json(null); - }), - ); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 7777) { + return { id: 7777, by: 'someone', text: 'A top-level comment.', time: Math.floor(Date.now() / 1000) - 300, type: 'comment' }; + } + return null; + }); const { result } = renderHook(() => useSiblingComments(7777)); @@ -85,31 +91,15 @@ describe('useSiblingComments', () => { }); it('returns single comment when parent has no kids', async () => { - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, ({ params }) => { - const id = parseInt(params.id as string, 10); - if (id === 8888) { - return HttpResponse.json({ - id: 8888, - by: 'test', - text: 'Lone comment.', - time: Math.floor(Date.now() / 1000) - 100, - parent: 9999, - type: 'comment', - }); - } - if (id === 9999) { - // Parent without `kids` → siblings should fall back to [self]. - return HttpResponse.json({ - id: 9999, - title: 'A Story', - by: 'poster', - type: 'story', - }); - } - return HttpResponse.json(null); - }), - ); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 8888) { + return { id: 8888, by: 'test', text: 'Lone comment.', time: Math.floor(Date.now() / 1000) - 100, parent: 9999, type: 'comment' }; + } + if (Number(id) === 9999) { + return { id: 9999, title: 'A Story', by: 'poster', type: 'story' }; + } + return null; + }); const { result } = renderHook(() => useSiblingComments(8888)); @@ -122,14 +112,7 @@ describe('useSiblingComments', () => { }); it('sets error on fetch failure', async () => { - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.json( - { status: 500, error: 'Server Error' }, - { status: 500 }, - ); - }), - ); + vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('Network error')); const { result } = renderHook(() => useSiblingComments(999)); @@ -141,11 +124,7 @@ describe('useSiblingComments', () => { }); it('sets error on network failure', async () => { - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.error(); - }), - ); + vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('Failed to fetch')); const { result } = renderHook(() => useSiblingComments(1001)); @@ -178,21 +157,12 @@ describe('useSiblingComments', () => { }); expect(result.current.siblingIds).toEqual([1001, 1002, 1003, 1004]); - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, ({ params }) => { - const id = parseInt(params.id as string, 10); - if (id === 7777) { - return HttpResponse.json({ - id: 7777, - by: 'someone', - text: 'A top-level comment.', - time: Math.floor(Date.now() / 1000) - 300, - type: 'comment', - }); - } - return HttpResponse.json(null); - }), - ); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 7777) { + return { id: 7777, by: 'someone', text: 'A top-level comment.', time: Math.floor(Date.now() / 1000) - 300, type: 'comment' }; + } + return null; + }); rerender({ id: 7777 }); diff --git a/src/hooks/useUserProfile.test.ts b/src/hooks/useUserProfile.test.ts index 6201562..a7f6faf 100644 --- a/src/hooks/useUserProfile.test.ts +++ b/src/hooks/useUserProfile.test.ts @@ -5,6 +5,7 @@ import { __resetUserProfileCacheForTests, __getUserProfileCacheForTests, } from './useUserProfile'; +import { hnSdk } from '../api/hnSdk'; import type { UserProfile } from '../types'; function profileBody(overrides: Partial = {}): UserProfile { @@ -18,16 +19,6 @@ function profileBody(overrides: Partial = {}): UserProfile { }; } -// Mirrors the helper in useUserInfiniteStories.test.ts. fetch's input can be a -// string, URL, or Request — covering all three keeps lint quiet about -// "[object Object]" stringification on the Request branch. -function fetchInputToUrl(input: RequestInfo | URL | undefined): string { - if (!input) return ''; - if (input instanceof URL) return input.href; - if (typeof input === 'string') return input; - return input.url; -} - describe('useUserProfile', () => { beforeEach(() => { __resetUserProfileCacheForTests(); @@ -38,9 +29,7 @@ describe('useUserProfile', () => { }); it('loads a user profile on mount', async () => { - vi.spyOn(globalThis, 'fetch').mockResolvedValue( - new Response(JSON.stringify(profileBody())), - ); + vi.spyOn(hnSdk, 'readUser').mockResolvedValue(profileBody()); const { result } = renderHook(() => useUserProfile('pg')); @@ -52,10 +41,8 @@ describe('useUserProfile', () => { expect(result.current.isNotFound).toBe(false); }); - it('treats Firebase null as NotFound (isNotFound=true) and surfaces the error', async () => { - vi.spyOn(globalThis, 'fetch').mockResolvedValue( - new Response('null', { status: 200 }), - ); + it('treats null return as NotFound (isNotFound=true) and surfaces the error', async () => { + vi.spyOn(hnSdk, 'readUser').mockResolvedValue(null); const { result } = renderHook(() => useUserProfile('nope')); @@ -66,45 +53,38 @@ describe('useUserProfile', () => { expect(result.current.error).toMatch(/not found/i); }); - it('surfaces a generic error on non-2xx response', async () => { - vi.spyOn(globalThis, 'fetch').mockResolvedValue( - new Response('Service Unavailable', { status: 503 }), - ); + it('surfaces a generic error on SDK rejection', async () => { + vi.spyOn(hnSdk, 'readUser').mockRejectedValue(new Error('Network error')); const { result } = renderHook(() => useUserProfile('pg')); await waitFor(() => expect(result.current.loading).toBe(false)); - expect(result.current.error).toMatch(/503/); + expect(result.current.error).toMatch(/Network error/); expect(result.current.isNotFound).toBe(false); expect(result.current.profile).toBeNull(); }); it('preserves username case (HN is case-sensitive)', async () => { - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue( - new Response(JSON.stringify(profileBody({ id: 'PaulG' }))), - ); + const spy = vi.spyOn(hnSdk, 'readUser').mockResolvedValue(profileBody({ id: 'PaulG' })); const { result } = renderHook(() => useUserProfile('PaulG')); await waitFor(() => expect(result.current.loading).toBe(false)); expect(result.current.profile?.id).toBe('PaulG'); - const url = fetchSpy.mock.calls[0]?.[0]; - expect(typeof url === 'string' ? url : (url as URL).href).toMatch(/\/user\/PaulG\.json/); + expect(spy).toHaveBeenCalledWith('PaulG'); }); describe('cache', () => { it('returns cached profile synchronously on remount and skips the fetch', async () => { - const fetchSpy = vi - .spyOn(globalThis, 'fetch') - .mockResolvedValue(new Response(JSON.stringify(profileBody()))); + const spy = vi.spyOn(hnSdk, 'readUser').mockResolvedValue(profileBody()); const first = renderHook(() => useUserProfile('pg')); await waitFor(() => expect(first.result.current.loading).toBe(false)); - expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(spy).toHaveBeenCalledTimes(1); first.unmount(); - fetchSpy.mockClear(); + spy.mockClear(); const second = renderHook(() => useUserProfile('pg')); @@ -113,26 +93,22 @@ describe('useUserProfile', () => { await Promise.resolve(); await Promise.resolve(); - expect(fetchSpy).not.toHaveBeenCalled(); + expect(spy).not.toHaveBeenCalled(); }); it('does not cache failed responses', async () => { - vi.spyOn(globalThis, 'fetch').mockResolvedValue( - new Response('Service Unavailable', { status: 503 }), - ); + vi.spyOn(hnSdk, 'readUser').mockRejectedValue(new Error('Network error')); const { result, unmount } = renderHook(() => useUserProfile('pg')); await waitFor(() => expect(result.current.loading).toBe(false)); - expect(result.current.error).toMatch(/503/); + expect(result.current.error).toMatch(/Network error/); unmount(); expect(__getUserProfileCacheForTests().has('pg')).toBe(false); }); it('does not cache NotFound responses', async () => { - vi.spyOn(globalThis, 'fetch').mockResolvedValue( - new Response('null', { status: 200 }), - ); + vi.spyOn(hnSdk, 'readUser').mockResolvedValue(null); const { result, unmount } = renderHook(() => useUserProfile('nope')); await waitFor(() => expect(result.current.loading).toBe(false)); @@ -145,12 +121,9 @@ describe('useUserProfile', () => { describe('username change', () => { it('discards stale state when username changes between renders', async () => { - vi.spyOn(globalThis, 'fetch').mockImplementation((input) => { - const url = fetchInputToUrl(input); - const id = /\/user\/([^/]+)\.json/.exec(url)?.[1] ?? ''; - return Promise.resolve( - new Response(JSON.stringify(profileBody({ id, karma: id === 'pg' ? 1 : 2 }))), - ); + vi.spyOn(hnSdk, 'readUser').mockImplementation(async (username) => { + const id = username; + return profileBody({ id, karma: id === 'pg' ? 1 : 2 }); }); const { result, rerender } = renderHook( @@ -165,28 +138,15 @@ describe('useUserProfile', () => { expect(result.current.profile?.karma).toBe(2); }); - // Pins the `versionRef` invalidation logic on lines 86, 91, 98, 106. The - // existing "discards stale state" test exercises a sequential race where - // each fetch resolves before the next one starts; this test exercises - // the actual interleaving — fetch A is in-flight when username changes, - // fetch B resolves first, then fetch A resolves. Without `versionRef`, - // fetch A's `setProfile` would clobber B's data because `setProfile` - // doesn't otherwise know its caller is stale. Both `if (versionRef.current - // !== currentVersion) return` guards must hold for B's data to survive. it('does not commit a stale in-flight response when username changes mid-fetch', async () => { - // Manual deferred promises so the test controls resolution order - // independently of the rerender — a real concurrent network race. - let resolvePg!: (response: Response) => void; - const pgPromise = new Promise((resolve) => { + let resolvePg!: (value: UserProfile | null) => void; + const pgPromise = new Promise((resolve) => { resolvePg = resolve; }); - const dangResponse = new Response(JSON.stringify(profileBody({ id: 'dang', karma: 999 }))); - vi.spyOn(globalThis, 'fetch').mockImplementation((input) => { - const url = fetchInputToUrl(input); - const id = /\/user\/([^/]+)\.json/.exec(url)?.[1] ?? ''; - if (id === 'pg') return pgPromise; - return Promise.resolve(dangResponse.clone()); + vi.spyOn(hnSdk, 'readUser').mockImplementation(async (username) => { + if (username === 'pg') return pgPromise; + return profileBody({ id: 'dang', karma: 999 }); }); const { result, rerender } = renderHook( @@ -194,31 +154,21 @@ describe('useUserProfile', () => { { initialProps: { username: 'pg' } }, ); - // pg's fetch is in-flight (still pending) — switch to dang BEFORE - // pg resolves. The hook's prop-derived state pattern bumps versionRef - // synchronously and immediately starts dang's fetch. expect(result.current.loading).toBe(true); rerender({ username: 'dang' }); - // dang resolves first → state should reflect dang. await waitFor(() => expect(result.current.profile?.id).toBe('dang')); expect(result.current.profile?.karma).toBe(999); - // Now resolve pg's stale promise. Without invalidation, pg's data - // would overwrite dang's. With invalidation, both `versionRef` guards - // (after `await fetch` and after `await response.json`) short-circuit - // and pg's data is dropped. await act(async () => { - resolvePg(new Response(JSON.stringify(profileBody({ id: 'pg', karma: 1 })))); - // Microtasks must flush so any (incorrect) setProfile would commit. + resolvePg(profileBody({ id: 'pg', karma: 1 })); await Promise.resolve(); await Promise.resolve(); }); expect(result.current.profile?.id).toBe('dang'); expect(result.current.profile?.karma).toBe(999); - // Cache should also reflect only dang — pg's stale write is suppressed. expect(__getUserProfileCacheForTests().get('pg')).toBeUndefined(); expect(__getUserProfileCacheForTests().get('dang')?.karma).toBe(999); }); @@ -226,10 +176,9 @@ describe('useUserProfile', () => { describe('refresh', () => { it('clears the cache entry and re-fetches', async () => { - const fetchSpy = vi - .spyOn(globalThis, 'fetch') - .mockResolvedValueOnce(new Response(JSON.stringify(profileBody({ karma: 100 })))) - .mockResolvedValueOnce(new Response(JSON.stringify(profileBody({ karma: 200 })))); + const spy = vi.spyOn(hnSdk, 'readUser') + .mockResolvedValueOnce(profileBody({ karma: 100 })) + .mockResolvedValueOnce(profileBody({ karma: 200 })); const { result } = renderHook(() => useUserProfile('pg')); await waitFor(() => expect(result.current.profile?.karma).toBe(100)); @@ -239,15 +188,13 @@ describe('useUserProfile', () => { }); expect(result.current.profile?.karma).toBe(200); - expect(fetchSpy).toHaveBeenCalledTimes(2); + expect(spy).toHaveBeenCalledTimes(2); }); }); describe('empty username', () => { it('does not fetch and stays in idle state', async () => { - const fetchSpy = vi - .spyOn(globalThis, 'fetch') - .mockResolvedValue(new Response(JSON.stringify(profileBody()))); + const spy = vi.spyOn(hnSdk, 'readUser').mockResolvedValue(profileBody()); const { result } = renderHook(() => useUserProfile('')); @@ -256,7 +203,7 @@ describe('useUserProfile', () => { await Promise.resolve(); await Promise.resolve(); - expect(fetchSpy).not.toHaveBeenCalled(); + expect(spy).not.toHaveBeenCalled(); }); }); }); diff --git a/src/hooks/useUserProfile.ts b/src/hooks/useUserProfile.ts index 9ae1677..47f777e 100644 --- a/src/hooks/useUserProfile.ts +++ b/src/hooks/useUserProfile.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; -import { FIREBASE_API } from '../config/api'; +import { hnSdk } from '../api/hnSdk'; import { NotFoundError } from '../api/hn'; import type { UserProfile } from '../types'; @@ -69,19 +69,7 @@ export function useUserProfile(username: string): UseUserProfileResult { setIsNotFound(false); try { - // Encode the username for URL safety. HN usernames are validated upstream - // (USERNAME_REGEX in sanitize.ts allows only `[a-zA-Z0-9_-]{2,15}`, all - // encoding-stable), so this is a no-op on the happy path. It exists for - // defense-in-depth against hand-crafted URLs whose `:id` decodes to - // characters that would otherwise truncate the path (e.g. `?` becomes a - // query string, `#` strips the `.json` suffix, `/` extends the path). - // Mirrors `useUserInfiniteStories.ts`'s author tag encoding. - const response = await fetch(`${FIREBASE_API}/user/${encodeURIComponent(username)}.json`); - if (versionRef.current !== currentVersion) return; - if (!response.ok) { - throw new Error(`Failed to fetch user ${username}: ${response.status}`); - } - const data = (await response.json()) as UserProfile | null; + const data = await hnSdk.readUser(username); if (versionRef.current !== currentVersion) return; if (data === null) { throw new NotFoundError(`User ${username} not found`); diff --git a/src/mocks/handlers.ts b/src/mocks/handlers.ts index 93bf258..b3d07d4 100644 --- a/src/mocks/handlers.ts +++ b/src/mocks/handlers.ts @@ -1,5 +1,5 @@ import { http, HttpResponse } from 'msw'; -import { ALGOLIA_API, FIREBASE_API } from '../config/api'; +import { ALGOLIA_API } from '../config/api'; export const mockItem = { id: 12345, @@ -207,65 +207,6 @@ export const mockUserStory2 = { }; export const handlers = [ - // Firebase: Get top items - http.get(`${FIREBASE_API}/topstories.json`, () => { - return HttpResponse.json(mockTopItemIds); - }), - - // Firebase: Get best items - http.get(`${FIREBASE_API}/beststories.json`, () => { - return HttpResponse.json(mockTopItemIds); - }), - - // Firebase: Get individual item - http.get(`${FIREBASE_API}/item/:id.json`, ({ params }) => { - const id = parseInt(params.id as string, 10); - - if (id === 12345) { - return HttpResponse.json(mockItem); - } - if (id === 1001) { - return HttpResponse.json(mockComment); - } - if (id === 2001) { - return HttpResponse.json(mockNestedComment); - } - if (id === 1002 || id === 1003) { - return HttpResponse.json({ - id, - by: id === 1002 ? 'jgrahamc' : 'dang', - text: id === 1002 - ? 'This is a great point. The performance characteristics of the new compiler are impressive — especially the cold-start times.' - : 'We discussed this on HN a while back. The context from the original thread is worth reading.', - time: Math.floor(Date.now() / 1000) - 600, - parent: 12345, - type: 'comment', - }); - } - if (id === 1004) { - return HttpResponse.json({ - id: 1004, - by: 'leerob', - text: 'Author here — thanks for the discussion! I updated the benchmarks section based on feedback.', - time: Math.floor(Date.now() / 1000) - 300, - parent: 12345, - type: 'comment', - }); - } - - // Return a generic item for other IDs - return HttpResponse.json({ - id, - title: `Item ${id}`, - url: `https://example.com/item/${id}`, - by: 'testuser', - score: 50, - time: Math.floor(Date.now() / 1000) - 7200, - descendants: 5, - type: 'story', - }); - }), - // Algolia: Search (used for front page items and show items) http.get(`${ALGOLIA_API}/search`, ({ request }) => { const url = new URL(request.url); @@ -350,34 +291,6 @@ export const handlers = [ }); }), - // Firebase: Get user profile - http.get(`${FIREBASE_API}/user/:id.json`, ({ params }) => { - const id = params.id as string; - if (id === 'leerob') { - return HttpResponse.json(mockUserProfile); - } - if (id === 'pg') { - return HttpResponse.json({ - id: 'pg', - created: 1160418092, - karma: 155555, - about: 'Founder of Y Combinator.', - submitted: [12345], - }); - } - if (id === 'minimaluser') { - // No `about` field — exercises the conditional-render path in UserProfile. - return HttpResponse.json({ - id: 'minimaluser', - created: 1160418092, - karma: 1, - submitted: [], - }); - } - // Unknown users → Firebase's "no such user" response is JSON `null`. - return HttpResponse.json(null); - }), - // Algolia: Items endpoint (used for comment detail) http.get(`${ALGOLIA_API}/items/:id`, ({ params }) => { const id = parseInt(params.id as string, 10); @@ -403,32 +316,9 @@ export const handlers = [ /** * Error handlers for testing error states. - * Use server.use(...errorHandlers.notFound) in tests to override default handlers. + * Use server.use(...errorHandlers.algoliaError) in tests to override default handlers. */ export const errorHandlers = { - // 404 Not Found for item - notFound: http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.json(null); - }), - - // 500 Server Error - serverError: http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.json( - { error: 'Internal Server Error' }, - { status: 500 } - ); - }), - - // Network Error (connection failure) - networkError: http.get(`${FIREBASE_API}/item/:id.json`, () => { - return HttpResponse.error(); - }), - - // Empty items list - emptyItems: http.get(`${FIREBASE_API}/topstories.json`, () => { - return HttpResponse.json([]); - }), - // Algolia API error algoliaError: http.get(`${ALGOLIA_API}/search`, () => { return HttpResponse.json( @@ -436,9 +326,4 @@ export const errorHandlers = { { status: 503 } ); }), - - // Firebase: User not found (returns JSON null per HN convention) - userNotFound: http.get(`${FIREBASE_API}/user/:id.json`, () => { - return HttpResponse.json(null); - }), }; diff --git a/src/pages/ItemDetail.test.tsx b/src/pages/ItemDetail.test.tsx index 7c25aae..4bdf8d6 100644 --- a/src/pages/ItemDetail.test.tsx +++ b/src/pages/ItemDetail.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'; import { screen, waitFor, fireEvent } from '@testing-library/react'; import { render } from '../test/test-utils'; import { Routes, Route } from 'react-router-dom'; @@ -6,8 +6,22 @@ import { ItemDetail } from './ItemDetail'; import { clearViewed, markViewed, isViewed } from '../utils/viewedItems'; import { http, HttpResponse } from 'msw'; import { server } from '../mocks/server'; -import { FIREBASE_API, ALGOLIA_API } from '../config/api'; +import { hnSdk } from '../api/hnSdk'; +import { ALGOLIA_API } from '../config/api'; import { mockAlgoliaCommentItem } from '../mocks/handlers'; +import type { FirebaseItem } from '../types'; + +const defaultItem: FirebaseItem = { + id: 12345, + title: 'Rust Is the Future of JavaScript Infrastructure', + url: 'https://leerob.io/blog/rust', + by: 'leerob', + score: 284, + time: Math.floor(Date.now() / 1000) - 3600, + descendants: 137, + kids: [1001, 1002, 1003, 1004], + type: 'story', +}; // Render ItemDetail inside a route so useParams() resolves :id function renderItemDetail(itemId: number) { @@ -22,6 +36,15 @@ function renderItemDetail(itemId: number) { describe('ItemDetail', () => { beforeEach(() => { clearViewed(); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345) return defaultItem; + return null; + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + server.resetHandlers(); }); describe('viewed state', () => { @@ -62,9 +85,7 @@ describe('ItemDetail', () => { describe('back-to-home action on not-found', () => { beforeEach(() => { - server.use( - http.get(`${FIREBASE_API}/item/:id.json`, () => HttpResponse.json(null)), - ); + vi.spyOn(hnSdk, 'readItem').mockResolvedValue(null); }); it('links to / with "Back to Home" label', async () => { @@ -77,30 +98,14 @@ describe('ItemDetail', () => { describe('comment detection', () => { it('renders CommentDetail when item.type is comment', async () => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 1001) { + return { id: 1001, by: 'patio11', text: 'The wasm-bindgen approach is really interesting.', time: Math.floor(Date.now() / 1000) - 1800, parent: 12345, type: 'comment' }; + } + return { id: Number(id), title: 'Rust Is the Future of JavaScript Infrastructure', by: 'leerob', score: 284, time: Math.floor(Date.now() / 1000) - 3600, descendants: 137, type: 'story' }; + }); + server.use( - http.get(`${FIREBASE_API}/item/:id.json`, ({ params }) => { - const id = parseInt(params.id as string, 10); - if (id === 1001) { - return HttpResponse.json({ - id: 1001, - by: 'patio11', - text: 'The wasm-bindgen approach is really interesting.', - time: Math.floor(Date.now() / 1000) - 1800, - parent: 12345, - type: 'comment', - }); - } - // Fallback handler covers the parent-story fetch (item title lookup). - return HttpResponse.json({ - id, - title: 'Rust Is the Future of JavaScript Infrastructure', - by: 'leerob', - score: 284, - time: Math.floor(Date.now() / 1000) - 3600, - descendants: 137, - type: 'story', - }); - }), http.get(`${ALGOLIA_API}/items/:id`, () => { return HttpResponse.json(mockAlgoliaCommentItem); }), diff --git a/src/pages/UserProfile.test.tsx b/src/pages/UserProfile.test.tsx index 2b414b2..95cc551 100644 --- a/src/pages/UserProfile.test.tsx +++ b/src/pages/UserProfile.test.tsx @@ -1,14 +1,27 @@ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'; import { screen, waitFor } from '@testing-library/react'; import { render } from '../test/test-utils'; import { Routes, Route } from 'react-router-dom'; import { UserProfile } from './UserProfile'; import { __resetUserProfileCacheForTests } from '../hooks/useUserProfile'; import { ScrollContainerProvider } from '../context/ScrollContainerContext'; -import { http, HttpResponse } from 'msw'; -import { server } from '../mocks/server'; -import { errorHandlers } from '../mocks/handlers'; -import { FIREBASE_API } from '../config/api'; +import { hnSdk } from '../api/hnSdk'; +import type { UserProfile as UserProfileType } from '../types'; + +const mockUserProfile: UserProfileType = { + id: 'leerob', + created: 1160418092, + karma: 12345, + about: 'Engineer at Vercel. leerob.io', + submitted: [12345, 99999, 88888], +}; + +const mockMinimalUser: UserProfileType = { + id: 'minimaluser', + created: 1160418092, + karma: 1, + submitted: [], +}; function renderProfile(username: string) { // ScrollContainerProvider matches the production tree (App.tsx wraps the @@ -29,6 +42,16 @@ describe('UserProfile', () => { __resetUserProfileCacheForTests(); document.documentElement.classList.remove('swipe-mode'); document.body.classList.remove('swipe-mode'); + vi.spyOn(hnSdk, 'readUser').mockImplementation(async (username) => { + if (username === 'leerob') return mockUserProfile; + if (username === 'minimaluser') return mockMinimalUser; + if (username === 'pg') return { id: 'pg', created: 1160418092, karma: 155555, submitted: [12345] }; + return null; + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); }); describe('loaded profile', () => { @@ -85,17 +108,12 @@ describe('UserProfile', () => { }); it('preserves username case (HN is case-sensitive)', async () => { - server.use( - http.get(`${FIREBASE_API}/user/:id.json`, ({ params }) => { - const id = params.id as string; - return HttpResponse.json({ - id, - created: 1160418092, - karma: 1, - submitted: [], - }); - }), - ); + vi.spyOn(hnSdk, 'readUser').mockImplementation(async (username) => ({ + id: username, + created: 1160418092, + karma: 1, + submitted: [], + })); renderProfile('PaulG'); @@ -110,7 +128,7 @@ describe('UserProfile', () => { describe('not found', () => { beforeEach(() => { - server.use(errorHandlers.userNotFound); + vi.spyOn(hnSdk, 'readUser').mockResolvedValue(null); }); it('renders the "user not found" StateView when Firebase returns null', async () => { @@ -133,11 +151,7 @@ describe('UserProfile', () => { describe('error', () => { beforeEach(() => { - server.use( - http.get(`${FIREBASE_API}/user/:id.json`, () => - HttpResponse.json({ error: 'boom' }, { status: 503 }), - ), - ); + vi.spyOn(hnSdk, 'readUser').mockRejectedValue(new Error('Service unavailable')); }); it('renders the error StateView with a Try Again action', async () => { diff --git a/src/pages/index.ts b/src/pages/index.ts index 6ae3fa6..72a99e0 100644 --- a/src/pages/index.ts +++ b/src/pages/index.ts @@ -1,5 +1 @@ export { StoryList } from './StoryList'; -export { ItemDetail } from './ItemDetail'; -export { DomainStories } from './DomainStories'; -export { UserProfile } from './UserProfile'; -export { UserSubmissions } from './UserSubmissions'; diff --git a/src/test/setup.ts b/src/test/setup.ts index 892aec5..07540ed 100644 --- a/src/test/setup.ts +++ b/src/test/setup.ts @@ -1,3 +1,4 @@ +/// import { afterEach, beforeAll, afterAll, vi } from 'vitest'; import { cleanup } from '@testing-library/react'; import '@testing-library/jest-dom/vitest'; @@ -118,9 +119,27 @@ class MockResizeObserver { globalThis.ResizeObserver = MockResizeObserver; // Mock requestAnimationFrame (basic implementation for jsdom) -globalThis.requestAnimationFrame = vi.fn((cb: FrameRequestCallback) => setTimeout(() => cb(performance.now()), 16)); +globalThis.requestAnimationFrame = vi.fn((cb: FrameRequestCallback) => setTimeout(() => cb(performance.now()), 16) as unknown as number); globalThis.cancelAnimationFrame = vi.fn((id: number) => clearTimeout(id)); +// Stub window.scrollTo (not implemented in jsdom) +window.scrollTo = vi.fn() as typeof window.scrollTo; + +// Suppress jsdom "Not implemented: navigation" errors (triggered by anchor clicks / form submits). +// jsdom writes these directly to stderr via its VirtualConsole, bypassing console.error. +const origStderrWrite = process.stderr.write; +process.stderr.write = function ( + chunk: Uint8Array | string, + encodingOrCb?: BufferEncoding | ((error?: Error | null) => void), + cb?: (error?: Error | null) => void, +): boolean { + if (typeof chunk === 'string' && chunk.includes('Not implemented: navigation')) return true; + if (typeof encodingOrCb === 'function') { + return origStderrWrite.call(process.stderr, chunk, undefined, encodingOrCb); + } + return origStderrWrite.call(process.stderr, chunk, encodingOrCb, cb); +}; + // Start MSW server before all tests beforeAll(() => { server.listen({ onUnhandledRequest: 'warn' }); diff --git a/vite.config.js b/vite.config.js index bde5512..ffe1f80 100644 --- a/vite.config.js +++ b/vite.config.js @@ -28,4 +28,18 @@ export default defineConfig({ exclude: ['node_modules/', 'src/test/'], }, }, + build: { + rollupOptions: { + output: { + manualChunks(id) { + if (id.includes('node_modules/firebase') || id.includes('node_modules/@firebase')) { + return 'firebase'; + } + if (id.includes('node_modules/react-dom') || id.includes('node_modules/react-router') || id.includes('node_modules/react/')) { + return 'react'; + } + }, + }, + }, + }, })