From e8d95bc1f266c518a8d8abe16ae983417da2a2ab Mon Sep 17 00:00:00 2001 From: Micha Mailaender <87228994+mmailaender@users.noreply.github.com> Date: Sat, 26 Sep 2026 12:37:52 +0200 Subject: [PATCH 1/6] convexLoad: one subscription per query, SSR payload for hydration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - On client-side navigation, open the live subscription and await its first value instead of a one-shot client.query() followed by a second subscription (Add → Remove → Add). convexLoadPaginated no longer fetches the first page twice. - New convexLoadHydration handle (convex-svelte/sveltekit/server) embeds convexLoad results of universal loads in the SSR HTML. Loads re-running during hydration reuse them instead of querying before setupAuth, and the live subscription is deferred until auth is set up. Server-load results (transport) are not embedded twice. hydrate: false opts out. - A load awaiting its first value holds its query (no unclaimed timeout while e.g. offline). --- ...onvexload-hydration-single-subscription.md | 13 + e2e/convexLoadHydration.test.ts | 93 +++++ e2e/convexLoadRelease.test.ts | 46 ++- e2e/helpers/websocket.ts | 81 +++++ src/hooks.server.ts | 5 + src/lib/internal/singleton.ts | 15 + src/lib/sveltekit/hydration-server.spec.ts | 144 ++++++++ src/lib/sveltekit/hydration-server.ts | 51 +++ src/lib/sveltekit/hydration.spec.ts | 223 ++++++++++++ src/lib/sveltekit/hydration.ts | 124 +++++++ .../paginated-query-detached.svelte.ts | 131 ++++--- src/lib/sveltekit/query-detached.spec.ts | 267 ++++++++++++++- src/lib/sveltekit/query-detached.svelte.ts | 105 ++++-- src/lib/sveltekit/query-key.ts | 23 ++ src/lib/sveltekit/query-lifecycle.spec.ts | 45 +++ src/lib/sveltekit/query-lifecycle.ts | 15 + src/lib/sveltekit/server-token.ts | 2 + src/lib/sveltekit/transport.spec.ts | 320 ++++++++++++------ src/lib/sveltekit/transport.svelte.ts | 133 +++++--- src/routes/tests/+page.svelte | 10 + .../tests/convex-load-auth/+layout.svelte | 22 ++ .../tests/convex-load-auth/+page.svelte | 18 + src/routes/tests/convex-load-auth/+page.ts | 6 + .../tests/convex-load-server/+page.server.ts | 8 + .../tests/convex-load-server/+page.svelte | 18 + 25 files changed, 1699 insertions(+), 219 deletions(-) create mode 100644 .changeset/convexload-hydration-single-subscription.md create mode 100644 e2e/convexLoadHydration.test.ts create mode 100644 e2e/helpers/websocket.ts create mode 100644 src/hooks.server.ts create mode 100644 src/lib/sveltekit/hydration-server.spec.ts create mode 100644 src/lib/sveltekit/hydration-server.ts create mode 100644 src/lib/sveltekit/hydration.spec.ts create mode 100644 src/lib/sveltekit/hydration.ts create mode 100644 src/lib/sveltekit/query-key.ts create mode 100644 src/routes/tests/convex-load-auth/+layout.svelte create mode 100644 src/routes/tests/convex-load-auth/+page.svelte create mode 100644 src/routes/tests/convex-load-auth/+page.ts create mode 100644 src/routes/tests/convex-load-server/+page.server.ts create mode 100644 src/routes/tests/convex-load-server/+page.svelte diff --git a/.changeset/convexload-hydration-single-subscription.md b/.changeset/convexload-hydration-single-subscription.md new file mode 100644 index 0000000..f72cbfb --- /dev/null +++ b/.changeset/convexload-hydration-single-subscription.md @@ -0,0 +1,13 @@ +--- +'convex-svelte': minor +--- + +### Fixes + +- **`convexLoad` in `+page.ts` no longer queries without auth during hydration** - SvelteKit re-runs universal load functions in the browser during hydration, before `setupAuth()` has authenticated the client. `convexLoad` / `convexLoadPaginated` therefore queried Convex unauthenticated, replacing the server-rendered data with anonymous results (or failing the load for auth-protected queries). With the new `convexLoadHydration` handle, the server embeds its results in the HTML and hydration reuses them. The live subscription starts after auth, and the page becomes interactive without waiting for the WebSocket. +- **One subscription per `convexLoad`** - on client-side navigation, `convexLoad` ran a one-shot query and then subscribed again (Add → Remove → Add on the WebSocket), executing the query twice. It now opens the live subscription and awaits its first value. `convexLoadPaginated` no longer fetches the first page twice. + +### Features + +- **`convexLoadHydration`** - new SvelteKit `handle` exported from `convex-svelte/sveltekit/server`. Add it to `hooks.server.ts` (combine with your own handle via `sequence()`) to embed `convexLoad` results of universal loads in the SSR HTML. Results of server loads (`+page.server.ts`) already reach the browser through the transport and are not embedded again. +- **`hydrate: false`** - `convexLoad` / `convexLoadPaginated` option to leave a result out of the SSR payload, e.g. for large results. diff --git a/e2e/convexLoadHydration.test.ts b/e2e/convexLoadHydration.test.ts new file mode 100644 index 0000000..65f4e8e --- /dev/null +++ b/e2e/convexLoadHydration.test.ts @@ -0,0 +1,93 @@ +import { expect, test } from '@playwright/test'; +import { convexUrl, recordWebSocket, withMuteWord } from './helpers/websocket.js'; + +// --------------------------------------------------------------------------- +// convexLoad SSR hydration payload (convexLoadHydration handle in +// src/hooks.server.ts). +// +// SvelteKit re-runs universal loads (+page.ts) in the browser during +// hydration — before setupAuth() authenticated the client. They must reuse +// the server's results instead of querying unauthenticated, and open exactly +// one live subscription each. +// --------------------------------------------------------------------------- + +test.describe('convexLoad — SSR hydration payload', () => { + test('embeds results of universal loads in the HTML', async ({ page }) => { + const response = await page.goto('/tests/convex-load-release/a'); + const html = (await response?.text()) ?? ''; + + expect(html).toContain('data-convex-load'); + expect(html).toContain('__e2e_release_a__'); + }); + + test('does not embed server-load results again (they use the transport)', async ({ page }) => { + const websocket = recordWebSocket(page); + const response = await page.goto('/tests/convex-load-server'); + const html = (await response?.text()) ?? ''; + + expect(html).not.toContain('data-convex-load'); + // Still rendered from SSR and upgraded to a live subscription. + await expect(page.getByTestId('data')).toBeVisible(); + await expect(page.getByTestId('hydrated')).toContainText('true'); + await expect + .poll(() => websocket.queryEvents(withMuteWord('__e2e_server_load__')).length) + .toBe(1); + }); + + test('hydration never queries before auth is set up', async ({ page }) => { + const websocket = recordWebSocket(page); + await page.goto('/tests/convex-load-auth'); + await expect(page.getByTestId('hydrated')).toContainText('true', { timeout: 10000 }); + // SSR data is shown right away — no loading state after hydration either. + await expect(page.getByTestId('data')).toBeVisible(); + await expect(page.getByTestId('loading')).not.toBeVisible(); + await expect.poll(() => websocket.events.some((e) => e.type === 'Authenticate')).toBe(true); + await expect + .poll(() => websocket.queryEvents(withMuteWord('__e2e_auth_hydration__')).length) + .toBeGreaterThan(0); + + const firstAuthenticate = websocket.events.findIndex((e) => e.type === 'Authenticate'); + const firstQuery = websocket.events.findIndex( + (e) => e.type !== 'Authenticate' && withMuteWord('__e2e_auth_hydration__')(e) + ); + expect(firstQuery).toBeGreaterThan(firstAuthenticate); + }); + + test('hydration opens exactly one subscription per query', async ({ page }) => { + const websocket = recordWebSocket(page); + await page.goto('/tests/convex-load-release/a'); + await expect(page.getByTestId('hydrated')).toContainText('true', { timeout: 5000 }); + await expect + .poll(() => websocket.queryEvents(withMuteWord('__e2e_release_a__')).length) + .toBe(1); + await page.waitForTimeout(1000); + + expect(websocket.queryEvents(withMuteWord('__e2e_release_a__')).map((e) => e.type)).toEqual([ + 'Add' + ]); + }); + + test('embedded data cannot inject scripts', async ({ page, request }) => { + const author = '__e2e_hydration_xss__'; + const mutation = (path: string, args: Record) => + request.post(`${convexUrl()}/api/mutation`, { data: { path, args, format: 'json' } }); + await mutation('messages:send', { + author, + body: ''], + ['a style element', ''], + ['a title', '</head> </head> demo'] + ])('ignores inside %s', async (_name, html) => { + const { hydration } = await loadModules(); + + expect(hydration.findTag(html, '')); + }); + + it('is case-insensitive and requires a tag boundary', async () => { + const { hydration } = await loadModules(); + + expect(hydration.findTag('', '', '""', ' { + const { hydration } = await loadModules(); + + expect(hydration.findTag('

x

', '', '', '${json}`; } +/** Elements whose content the HTML parser treats as text: tags inside don't count. */ +const rawTextElement = /^<(script|style|textarea|title|noscript|iframe|noembed|noframes|xmp)[\s>/]/; + +/** + * Index of the first real `tag` (e.g. `` — `""` inside + * a script string is not the end of the head. `-1` if there is none. + */ +export function findTag(html: string, tag: string): number { + const lower = html.toLowerCase(); + for (let i = lower.indexOf('<'); i !== -1; i = lower.indexOf('<', i + 1)) { + if (lower.startsWith('', i + 4); + if (end === -1) return -1; + i = end + 2; + continue; + } + if (lower.startsWith(tag, i) && /[\s>/]/.test(lower[i + tag.length] ?? '>')) return i; + const raw = rawTextElement.exec(lower.slice(i, i + 12)); + if (raw) { + const end = lower.indexOf(``, so the parser * has created it before SvelteKit's start script (in ``) can run the @@ -76,8 +104,8 @@ export function serializeHydrationPayload(collector: HydrationCollector): string */ export function injectHydrationPayload(html: string, collector: HydrationCollector): string { const script = serializeHydrationPayload(collector); - for (const tag of ['', ' { expect(result).toBe('async-token'); }); }); + +describe('convex-svelte/sveltekit/server entry', () => { + it('does not depend on SvelteKit internals (older SvelteKit versions keep working)', async () => { + vi.resetModules(); + vi.doMock('@sveltejs/kit/internal/server', () => { + throw new Error('Missing "./internal/server" specifier in "@sveltejs/kit" package'); + }); + + await expect(import('./server-token.js')).resolves.toHaveProperty('withServerConvexToken'); + + vi.doUnmock('@sveltejs/kit/internal/server'); + }); +}); diff --git a/src/lib/sveltekit/server-token.ts b/src/lib/sveltekit/server-token.ts index 6679f39..7eae4c9 100644 --- a/src/lib/sveltekit/server-token.ts +++ b/src/lib/sveltekit/server-token.ts @@ -22,8 +22,6 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import { _setServerTokenGetter } from '../internal/singleton.js'; -export { convexLoadHydration } from './hydration-server.js'; - const tokenStorage = new AsyncLocalStorage(); // Register the getter so convexLoad / createConvexHttpClient can access diff --git a/src/routes/tests/+page.svelte b/src/routes/tests/+page.svelte index 6b364a9..8d987f3 100644 --- a/src/routes/tests/+page.svelte +++ b/src/routes/tests/+page.svelte @@ -105,6 +105,11 @@ path: '/tests/convex-load-auth', description: 'Tests that hydration reuses SSR data instead of querying before auth' }, + { + title: 'ConvexLoad Nested Loads', + path: '/tests/convex-load-nested', + description: 'Tests hydration with universal + server layouts and parent()' + }, { title: 'ConvexLoad Server Load', path: '/tests/convex-load-server', diff --git a/src/routes/tests/convex-load-nested/+layout.server.ts b/src/routes/tests/convex-load-nested/+layout.server.ts new file mode 100644 index 0000000..a8f6fbe --- /dev/null +++ b/src/routes/tests/convex-load-nested/+layout.server.ts @@ -0,0 +1,10 @@ +import { convexLoad } from '$lib/sveltekit/index.js'; +import { api } from '../../../convex/_generated/api.js'; + +// Server layout load: uses a result only internally — must never be embedded. +export const load = async () => { + const privateResult = await convexLoad(api.messages.list, { + muteWords: ['__e2e_nested_server_private__'] + }); + return { serverCount: privateResult.data?.length ?? 0 }; +}; diff --git a/src/routes/tests/convex-load-nested/+layout.svelte b/src/routes/tests/convex-load-nested/+layout.svelte new file mode 100644 index 0000000..a5c3d08 --- /dev/null +++ b/src/routes/tests/convex-load-nested/+layout.svelte @@ -0,0 +1,9 @@ + + +{#if !layoutMessages.isLoading} +

layout: {layoutMessages.data?.length ?? 0} messages

+{/if} +{@render children()} diff --git a/src/routes/tests/convex-load-nested/+layout.ts b/src/routes/tests/convex-load-nested/+layout.ts new file mode 100644 index 0000000..b9279f8 --- /dev/null +++ b/src/routes/tests/convex-load-nested/+layout.ts @@ -0,0 +1,10 @@ +import { convexLoad } from '$lib/sveltekit/index.js'; +import { api } from '../../../convex/_generated/api.js'; + +// Universal layout load alongside a server layout load. +export const load = async ({ data }) => ({ + ...data, + layoutMessages: await convexLoad(api.messages.list, { + muteWords: ['__e2e_nested_layout__'] + }) +}); diff --git a/src/routes/tests/convex-load-nested/+page.svelte b/src/routes/tests/convex-load-nested/+page.svelte new file mode 100644 index 0000000..550fa15 --- /dev/null +++ b/src/routes/tests/convex-load-nested/+page.svelte @@ -0,0 +1,18 @@ + + + + ConvexLoad Nested Loads Test + + +

hydrated: {hydrated}

+{#if pageMessages.isLoading} +

Loading...

+{:else} +

page: {pageMessages.data?.length ?? 0} messages

+{/if} diff --git a/src/routes/tests/convex-load-nested/+page.ts b/src/routes/tests/convex-load-nested/+page.ts new file mode 100644 index 0000000..5d72a2f --- /dev/null +++ b/src/routes/tests/convex-load-nested/+page.ts @@ -0,0 +1,10 @@ +import { convexLoad } from '$lib/sveltekit/index.js'; +import { api } from '../../../convex/_generated/api.js'; + +// Universal page load that waits for its parents first. +export const load = async ({ parent }) => { + await parent(); + return { + pageMessages: await convexLoad(api.messages.list, { muteWords: ['__e2e_nested_page__'] }) + }; +}; From c41b0194e63a437215c488417d85b1160bf57c78 Mon Sep 17 00:00:00 2001 From: Micha Mailaender <87228994+mmailaender@users.noreply.github.com> Date: Sat, 26 Sep 2026 13:30:35 +0200 Subject: [PATCH 4/6] Address review round 3: exact tag scanner, paginated SSR loading flash MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - findTag: ASCII-only case folding (toLowerCase() can change the length, e.g. 'İ', shifting the insertion point), skip whole tags respecting quoted attribute values, and require a tag boundary for raw-text end tags ( doesn't close a script). - Paginated state machine: SSR initialData is current data, not previous data — the initial args no longer mark it as loading, and the hydration guard runs before keepPreviousData. Fixes a loading flash right after hydration for convexLoadPaginated and usePaginatedQuery with initialData. - e2e: no loading state from SSR through hydration and the first live update (regular and paginated). --- ...onvexload-hydration-single-subscription.md | 2 + e2e/convexLoadHydration.test.ts | 35 ++++++++- src/lib/shared/paginated_query_state.spec.ts | 56 ++++++++++++++ src/lib/shared/paginated_query_state.ts | 32 ++++---- src/lib/sveltekit/hydration.spec.ts | 24 ++++++ src/lib/sveltekit/hydration.ts | 76 +++++++++++++++---- 6 files changed, 197 insertions(+), 28 deletions(-) diff --git a/.changeset/convexload-hydration-single-subscription.md b/.changeset/convexload-hydration-single-subscription.md index 2a40ed7..fd572d8 100644 --- a/.changeset/convexload-hydration-single-subscription.md +++ b/.changeset/convexload-hydration-single-subscription.md @@ -7,6 +7,8 @@ - **`convexLoad` in `+page.ts` no longer queries without auth during hydration** - SvelteKit re-runs universal load functions in the browser during hydration, before `setupAuth()` has authenticated the client. `convexLoad` / `convexLoadPaginated` therefore queried Convex unauthenticated, replacing the server-rendered data with anonymous results (or failing the load for auth-protected queries). With the new `convexLoadHydration` handle, the server embeds its results in the HTML and hydration reuses them. The live subscription starts after auth, and the page becomes interactive without waiting for the WebSocket. - **One subscription per `convexLoad`** - on client-side navigation, `convexLoad` ran a one-shot query and then subscribed again (Add → Remove → Add on the WebSocket), executing the query twice. It now opens the live subscription and awaits its first value. `convexLoadPaginated` no longer fetches the first page twice. +- **No loading flash for paginated SSR data** - with SSR `initialData`, `convexLoadPaginated` (and `usePaginatedQuery` with `initialData`) briefly reported `isLoading: true` / `LoadingFirstPage` right after hydration, so pages rendered their loading state over the server-rendered results. The initial args and the subscription's first empty snapshot now keep the SSR results visible and not loading. + ### Features - **`convexLoadHydration`** - new SvelteKit `handle` exported from the new entry point `convex-svelte/sveltekit/server/hydration` (requires SvelteKit 2.56 or later). Add it to `hooks.server.ts` (combine with your own handle via `sequence()`) to embed `convexLoad` results of universal loads in the SSR HTML. Everything `convexLoad` fetches while a universal load runs is embedded, including calls in helpers it invokes. Server loads (`+page.server.ts`) never contribute, not even results they use internally, and the ones they return reach the browser through the transport. Universal loads are detected via SvelteKit's internal `is_in_universal_load` request-store flag (also used by SvelteKit's remote functions). If it can't be read, nothing is embedded and a warning is logged. It's a separate entry point so that `convex-svelte/sveltekit/server` keeps working on older SvelteKit versions. A streamed (not awaited) `convexLoad` result is only embedded if it finished before the page HTML was generated; in development, a warning points out loads that miss the payload during hydration. diff --git a/e2e/convexLoadHydration.test.ts b/e2e/convexLoadHydration.test.ts index cd4731d..46d28f3 100644 --- a/e2e/convexLoadHydration.test.ts +++ b/e2e/convexLoadHydration.test.ts @@ -1,5 +1,5 @@ import { expect, test } from '@playwright/test'; -import { convexUrl, recordWebSocket, withMuteWord } from './helpers/websocket.js'; +import { convexUrl, recordWebSocket, withMuteWord, type QueryEvent } from './helpers/websocket.js'; // --------------------------------------------------------------------------- // convexLoad SSR hydration payload (convexLoadHydration handle in @@ -97,6 +97,39 @@ test.describe('convexLoad — SSR hydration payload', () => { } }); + for (const [name, url, predicate] of [ + ['convexLoad', '/tests/convex-load-release/a', withMuteWord('__e2e_release_a__')], + [ + 'convexLoadPaginated', + '/tests/convex-load-paginated', + (e: QueryEvent) => e.udfPath === 'messages:paginatedList' + ] + ] as const) { + test(`${name}: no loading state from SSR through hydration and the live subscription`, async ({ + page + }) => { + // Watch from the very first byte whether a loading state ever renders. + await page.addInitScript(() => { + const w = window as Window & { __sawLoading?: boolean }; + new MutationObserver(() => { + if (document.querySelector('[data-testid="loading"]')) w.__sawLoading = true; + }).observe(document, { childList: true, subtree: true }); + }); + const websocket = recordWebSocket(page); + + await page.goto(url); + await expect(page.getByTestId('hydrated')).toContainText('true', { timeout: 5000 }); + // The live subscription is up and has delivered its first update. + await expect.poll(() => websocket.queryEvents(predicate).length).toBe(1); + await page.waitForTimeout(1000); + + await expect(page.getByTestId('data')).toBeVisible(); + expect( + await page.evaluate(() => (window as Window & { __sawLoading?: boolean }).__sawLoading) + ).toBeUndefined(); + }); + } + test('embedded data cannot inject scripts', async ({ page, request }) => { const author = '__e2e_hydration_xss__'; const mutation = (path: string, args: Record) => diff --git a/src/lib/shared/paginated_query_state.spec.ts b/src/lib/shared/paginated_query_state.spec.ts index d054ae5..d30953a 100644 --- a/src/lib/shared/paginated_query_state.spec.ts +++ b/src/lib/shared/paginated_query_state.spec.ts @@ -60,6 +60,62 @@ describe('PaginatedQueryStateMachine keepPreviousData', () => { }); }); + it.each([true, false])( + 'does not mark SSR initialData as loading when the initial args are set (keepPreviousData: %s)', + (keepPreviousData) => { + const machine = new PaginatedQueryStateMachine({ + initialNumItems: 3, + keepPreviousData, + initialData: { page: ['a', 'b', 'c'], isDone: false, continueCursor: 'cursor-1' } + }); + + machine.onArgsChange(JSON.stringify({})); + + expect(machine.getSnapshot()).toMatchObject({ + results: ['a', 'b', 'c'], + status: 'CanLoadMore', + isLoading: false + }); + } + ); + + it('keeps SSR initialData visible (not loading) on the first empty snapshot', () => { + // Detached (convexLoadPaginated) queries use keepPreviousData: the SSR + // page must not be treated as "previous" data and flash a loading state. + const machine = new PaginatedQueryStateMachine({ + initialNumItems: 3, + keepPreviousData: true, + initialData: { page: ['a', 'b', 'c'], isDone: false, continueCursor: 'cursor-1' } + }); + machine.onArgsChange(JSON.stringify({})); + + machine.onUpdate({ results: [], status: 'LoadingFirstPage', loadMore: () => false }); + + expect(machine.getSnapshot()).toMatchObject({ + results: ['a', 'b', 'c'], + status: 'CanLoadMore', + isLoading: false + }); + }); + + it('still keeps previous data as loading once args changed (initialData no longer applies)', () => { + const machine = new PaginatedQueryStateMachine({ + initialNumItems: 3, + keepPreviousData: true, + initialData: { page: ['a', 'b', 'c'], isDone: false, continueCursor: 'cursor-1' } + }); + machine.onArgsChange(JSON.stringify({ search: '' })); + machine.onArgsChange(JSON.stringify({ search: 'x' })); + + machine.onUpdate({ results: [], status: 'LoadingFirstPage', loadMore: () => false }); + + expect(machine.getSnapshot()).toMatchObject({ + results: ['a', 'b', 'c'], + status: 'LoadingFirstPage', + isLoading: true + }); + }); + it('queues loadMore called before the live subscription is ready', () => { // SSR initialData reports CanLoadMore immediately, but the underlying // subscription has no working loadMore until its first server update. diff --git a/src/lib/shared/paginated_query_state.ts b/src/lib/shared/paginated_query_state.ts index 52d3158..643ad78 100644 --- a/src/lib/shared/paginated_query_state.ts +++ b/src/lib/shared/paginated_query_state.ts @@ -276,10 +276,12 @@ export class PaginatedQueryStateMachine { error: undefined }; } else { - // Keep previous data, but mark as loading + // Keep previous data, but mark as loading — except for the initial + // args of SSR initialData, which is current, not previous, data + // (marking it loading would flash a loading state on hydration). this.state = { ...this.state, - isLoading: true, + isLoading: !this.isUsingInitialData(), error: undefined }; } @@ -295,35 +297,37 @@ export class PaginatedQueryStateMachine { * "empty loading" snapshot to keep SSR-rendered content visible. */ onUpdate(update: PaginatedQueryUpdate): void { + // Hydration guard: if using initial data, ignore empty loading snapshots + // This keeps SSR-rendered content visible until real data arrives. + // Checked before keepPreviousData: SSR data is not "previous" data, and + // marking it as loading would flash a loading state after hydration. if ( - this.config.keepPreviousData && - this.state.results.length > 0 && + this.isUsingInitialData() && update.results.length === 0 && update.status === 'LoadingFirstPage' ) { + // Just update loadMore so it can be called, but don't clear results this.state = { ...this.state, - status: update.status, - isLoading: true, - error: undefined, - loadMore: update.loadMore + loadMore: update.loadMore, + isLoading: false }; this.notify(); return; } - // Hydration guard: if using initial data, ignore empty loading snapshots - // This keeps SSR-rendered content visible until real data arrives if ( - this.isUsingInitialData() && + this.config.keepPreviousData && + this.state.results.length > 0 && update.results.length === 0 && update.status === 'LoadingFirstPage' ) { - // Just update loadMore so it can be called, but don't clear results this.state = { ...this.state, - loadMore: update.loadMore, - isLoading: false + status: update.status, + isLoading: true, + error: undefined, + loadMore: update.loadMore }; this.notify(); return; diff --git a/src/lib/sveltekit/hydration.spec.ts b/src/lib/sveltekit/hydration.spec.ts index 5b5c9f4..e664485 100644 --- a/src/lib/sveltekit/hydration.spec.ts +++ b/src/lib/sveltekit/hydration.spec.ts @@ -155,6 +155,30 @@ describe('findTag — server', () => { expect(hydration.findTag(html, '')); }); + it.each([ + ['an attribute value', ``], + ['a quoted ">" in an attribute', ''], + [ + 'a script, after a non-closing "' + ] + ])('ignores inside %s', async (_name, html) => { + const { hydration } = await loadModules(); + + expect(hydration.findTag(html, '')); + }); + + it('keeps indices exact when lowercasing would change the length ("İ")', async () => { + const { hydration } = await loadModules(); + const html = 'İstanbul'; + const collector = collectorWith(hydration, { 'a|{}': 1 }); + + expect(hydration.findTag(html, '')); + expect(hydration.injectHydrationPayload(html, collector)).toMatch( + /<\/title>', - collector - ); - - expect(html).toMatch( - /^t<\/title><script [^>]*data-convex-load>.*<\/script><\/head><body><script>start\(\)/ - ); - }); - - it('falls back to before <body>, then to the start of the document', async () => { - const { hydration } = await loadModules(); - const collector = collectorWith(hydration, { 'a|{}': 1 }); - - expect(hydration.injectHydrationPayload('<body><p>x</p></body>', collector)).toMatch( - /^<script [^>]*data-convex-load>.*<\/script><body>/ - ); - expect(hydration.injectHydrationPayload('<p>x</p>', collector)).toMatch( - /^<script [^>]*data-convex-load>.*<\/script><p>x<\/p>$/ - ); - }); - - it('does not insert into a head script that contains "</head>"', async () => { - const { hydration } = await loadModules(); - const collector = collectorWith(hydration, { 'a|{}': 1 }); - const script = '<script>window.example = "</head>";</script>'; - - const html = hydration.injectHydrationPayload( - `<html><head>${script}</head><body></body></html>`, - collector - ); - - expect(html).toContain(script); - expect(html).toMatch(/<\/script><script [^>]*data-convex-load>.*<\/script><\/head><body>/); - }); -}); - -describe('findTag — server', () => { - it.each([ - ['a script string', '<head><script>const s = "</head>";</script></head><body>'], - ['a comment', '<head><!-- </head> --></head><body>'], - ['a style element', '<head><style>/* </head> */</style></head><body>'], - ['a title', '<head><title></head> </head> demo'] - ])('ignores inside %s', async (_name, html) => { - const { hydration } = await loadModules(); - - expect(hydration.findTag(html, '')); - }); - - it.each([ - ['an attribute value', ``], - ['a quoted ">" in an attribute', ''], - [ - 'a script, after a non-closing "' - ] - ])('ignores inside %s', async (_name, html) => { - const { hydration } = await loadModules(); - - expect(hydration.findTag(html, '')); - }); - - it.each([ - ['a doctype', '', 21], - // Bogus comments end at the first `>`, for the browser's parser too. - ['a processing instruction', '', 19], - ['a CDATA-like declaration', ' ]]>', 27] - ])('handles %s like the HTML parser', async (_name, html, expected) => { - const { hydration } = await loadModules(); - - expect(hydration.findTag(html, ' { - const { hydration } = await loadModules(); - const html = 'İstanbul'; - const collector = collectorWith(hydration, { 'a|{}': 1 }); - - expect(hydration.findTag(html, '')); - expect(hydration.injectHydrationPayload(html, collector)).toMatch( - /<\/title>', ' { - const { hydration } = await loadModules(); - - expect(hydration.findTag('

x

', '', '', ' { it('round-trips Convex values exactly (int64, bytes, nested, null)', async () => { const { hydration } = await loadModules(); @@ -270,6 +164,19 @@ describe('takeHydratedValue — browser', () => { expect(hydration.takeHydratedValue('k|{}')).toBeUndefined(); }); + it('is a miss (not a crash) for a value that is not valid Convex JSON, and warns once in dev', async () => { + env.dev = true; + const { hydration } = await loadModules(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + installDocument(JSON.stringify({ 'a|{}': { $integer: 5 }, 'b|{}': { $bytes: 7 } })); + + expect(hydration.takeHydratedValue('a|{}')).toBeUndefined(); + expect(hydration.takeHydratedValue('b|{}')).toBeUndefined(); + + expect(warn).toHaveBeenCalledOnce(); + warn.mockRestore(); + }); + it('is never used after setupConvex / setupAuth flushed (client-side navigation)', async () => { const { hydration, singleton } = await loadModules(); installDocument(JSON.stringify({ 'k|{}': 1 })); @@ -292,11 +199,11 @@ describe('takeHydratedValue — browser', () => { }); describe('warnHydrationMiss — browser, dev only', () => { - it('warns when the handle is active but a hydration load found no result', async () => { + it('warns when the server embedded results but a hydration load found none', async () => { env.dev = true; const { hydration } = await loadModules(); const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - installDocument('{}'); + installDocument(JSON.stringify({ 'other|{}': 1 })); hydration.takeHydratedValue('k|{}'); hydration.warnHydrationMiss('messages:list'); @@ -306,7 +213,7 @@ describe('warnHydrationMiss — browser, dev only', () => { warn.mockRestore(); }); - it('stays quiet without the handle, in production, or after hydration', async () => { + it('stays quiet without embedded results (no handle, ssr = false), in production, or after hydration', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); env.dev = true; diff --git a/src/lib/sveltekit/hydration.ts b/src/lib/sveltekit/hydration.ts index 027b336..c6fdeee 100644 --- a/src/lib/sveltekit/hydration.ts +++ b/src/lib/sveltekit/hydration.ts @@ -46,6 +46,13 @@ export function recordForHydration(key: string, value: unknown): void { export const PAYLOAD_ATTRIBUTE = 'data-convex-load'; +/** + * Placeholder in the `` of `src/app.html` that `convexLoadHydration` + * replaces with the payload. A placeholder replaced in `transformPageChunk` is + * how SvelteKit's docs inject request-specific markup (e.g. `%lang%`). + */ +export const HYDRATION_PLACEHOLDER = '%convex.hydration%'; + // Inside a