Skip to content

Commit ae024fb

Browse files
committed
Preserve fragments in action redirects, closes #810.
1 parent 29374c6 commit ae024fb

17 files changed

Lines changed: 396 additions & 32 deletions

‎packages/void/AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ Pages navigation payloads keep `url` as a path and query string. The render call
4747

4848
Pages clients and prerender requests send `X-VoidPages: true` with `X-VoidPages-Version` set to the shared `PAGES_PROTOCOL_VERSION` from `@void/edge` for devalue payloads. Missing or unsupported versions receive an uncached, empty `200 text/plain` response without `X-VoidPages`, which makes released clients load the document. Run legacy mutations once before that response; return validation errors as plain `422` JSON so forms retain their input. Native and hosted ISR must bypass JSON cache reads for unsupported versions without evicting current entries. HTML and JSON responses vary by both headers.
4949

50+
Pages and island actions opt in to `X-VoidPages-Redirect: manual`. The routing middleware carries the original redirect status and `Location` in an uncached response; the shared client transport follows it while preserving fragments and HTTP method/body rules. Keep external navigation out of the fetch loop and ordinary HTTP clients on standard redirects.
51+
5052
`submitAction()` appends the current page query to an action URL on the same path and names the added segments in `X-VoidPages-Preserved-Query`. Exclude that suffix when selecting an action and when marking its key before middleware; the action and loader still receive the full query. Named-action `c.redirect()` also strips the suffix before merging the request query. Rewrites with their own query clear this metadata so their explicit parameters can select an action. Keep the segments verbatim: history and scroll preservation compare the returned page URL with `location.pathname + location.search` as strings.
5153

5254
Pages `_not-found`/`_error` recovery uses finite render plans that retain logical layout slots. Never serialize original exceptions through framework hydration helpers, rerun a failed loader/action, or cache an error document. Native client boundaries reset on every visit/refresh and preserve healthy ancestor layouts.

‎packages/void/src/pages/island-action.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
type VoidActionError,
55
} from './action-result.ts';
66
import { getValidationErrors } from './adapter-helpers.ts';
7+
import { fetchPages } from './redirect.ts';
78

89
export type IslandActionResult =
910
| { kind: 'redirect'; url: string }
@@ -16,14 +17,18 @@ export async function submitIslandAction(
1617
method: string,
1718
data: Record<string, unknown>,
1819
): Promise<IslandActionResult> {
19-
const response = await fetch(url, {
20-
method,
21-
headers: { 'Content-Type': 'application/json' },
22-
body: JSON.stringify(data),
23-
});
20+
const { response, redirectedTo } = await fetchPages(
21+
url,
22+
{
23+
method,
24+
headers: { 'Content-Type': 'application/json' },
25+
body: JSON.stringify(data),
26+
},
27+
false,
28+
);
2429

25-
if (response.redirected) {
26-
return { kind: 'redirect', url: response.url };
30+
if (redirectedTo) {
31+
return { kind: 'redirect', url: redirectedTo };
2732
}
2833
if (response.ok) {
2934
return { kind: 'success' };

‎packages/void/src/pages/navigation-engine.ts‎

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import type { HeadDescriptor } from './head.ts';
1010
import { PrefetchCache, parseCacheFor } from './prefetch.ts';
1111
import type { CacheForInput, CacheForResult, LinkPrefetchValue } from './prefetch.ts';
1212
import type { PageObject } from './protocol.ts';
13+
import { fetchPages, type PagesFetchOptions, type PagesFetchResult } from './redirect.ts';
1314
import { createScrollRestoration } from './scroll-restoration.ts';
1415
import { decodePageData, deserializePageData, serializePageData } from './serialize.ts';
1516
import { decodePagePath, isSameOrigin } from './url.ts';
@@ -43,7 +44,7 @@ type DeferredWindow = Window & {
4344
__deferredQueue?: Array<[string, unknown] | [string, 0, unknown] | [string, unknown, 0, true]>;
4445
};
4546

46-
type PageFetchOptions = RequestInit & { headers: Record<string, string> };
47+
type PageFetchOptions = PagesFetchOptions;
4748

4849
type StaticPageDataResult = { pageData: PageData; resolvedDeferred: boolean };
4950

@@ -241,9 +242,12 @@ function abortSignalPromise(signal: AbortSignal): Promise<never> {
241242
});
242243
}
243244

244-
async function fetchPageResponse(fetchUrl: string, init: RequestInit): Promise<Response | null> {
245+
async function fetchPageResponse(
246+
fetchUrl: string,
247+
init: PagesFetchOptions,
248+
): Promise<PagesFetchResult | null> {
245249
try {
246-
return await fetch(fetchUrl, init);
250+
return await fetchPages(fetchUrl, init);
247251
} catch (error) {
248252
if (init.signal?.aborted || isAbortError(error)) {
249253
throw abortError();
@@ -610,8 +614,9 @@ export async function createPageNavigationEngine(
610614
if (pageData !== undefined) {
611615
return pageData;
612616
}
613-
return fetchPageResponse(url, { method: 'GET', headers }).then(async (r) => {
614-
if (!r || r.redirected) {
617+
return fetchPageResponse(url, { method: 'GET', headers }).then(async (result) => {
618+
const r = result?.response;
619+
if (!r || result?.redirectedTo) {
615620
return null;
616621
}
617622
if (!r.headers.get('X-VoidPages')) {
@@ -779,25 +784,26 @@ export async function createPageNavigationEngine(
779784
}
780785
}
781786

782-
const response =
787+
const fetched =
783788
pageData === undefined
784789
? method === 'GET'
785-
? await fetchPageResponse(fetchUrl, fetchOptions)
786-
: await fetch(fetchUrl, fetchOptions)
790+
? await fetchPageResponse(url, fetchOptions)
791+
: await fetchPages(url, fetchOptions)
787792
: null;
793+
const response = fetched?.response ?? null;
788794

789795
if (pageData === undefined && !response) {
790796
window.location.href = url;
791797
return undefined;
792798
}
793799

794-
if (response?.redirected) {
795-
const redirectUrl = new URL(response.url, window.location.origin);
800+
if (fetched?.redirectedTo) {
801+
const redirectUrl = new URL(fetched.redirectedTo, window.location.origin);
796802
if (!isSameOrigin(redirectUrl, window.location.origin)) {
797-
window.location.href = method === 'GET' ? url : response.url;
803+
window.location.href = fetched.redirectedTo;
798804
return undefined;
799805
}
800-
// The browser already followed the redirect: treat the final response as the GET
806+
// The fetch transport followed the redirect: treat the final response as the GET
801807
// result for the destination instead of fetching it a second time.
802808
method = 'GET';
803809
fetchUrl = redirectUrl.pathname + redirectUrl.search;
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { isSameOrigin } from './url.ts';
2+
3+
const REDIRECT_HEADER = 'X-VoidPages-Redirect';
4+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
5+
6+
/** Opt-in transport: fetch hides redirect Location headers and drops fragments from response.url. */
7+
export function pagesRedirectResponse(request: Request, response: Response): Response {
8+
if (!REDIRECT_STATUSES.has(response.status) || !response.headers.has('Location')) {
9+
return response;
10+
}
11+
const headers = new Headers(response.headers);
12+
headers.append('Vary', REDIRECT_HEADER);
13+
if (request.headers.get(REDIRECT_HEADER) !== 'manual') {
14+
return new Response(response.body, {
15+
status: response.status,
16+
statusText: response.statusText,
17+
headers,
18+
});
19+
}
20+
headers.set(REDIRECT_HEADER, String(response.status));
21+
headers.set('Cache-Control', 'no-store');
22+
return new Response(response.body, { status: 200, headers });
23+
}
24+
25+
export type PagesFetchResult = { response: Response; redirectedTo?: string };
26+
export type PagesFetchOptions = Omit<RequestInit, 'headers'> & { headers: Record<string, string> };
27+
28+
/** Follow negotiated redirects with HTTP method rules and origin checks. */
29+
export async function fetchPages(
30+
url: string,
31+
options: PagesFetchOptions,
32+
followGetRedirects = true,
33+
): Promise<PagesFetchResult> {
34+
const headers: Record<string, string> = { ...options.headers, [REDIRECT_HEADER]: 'manual' };
35+
const init = { ...options, headers };
36+
let redirectedTo: string | undefined;
37+
for (let redirects = 0; redirects <= 20; redirects++) {
38+
const response = await fetch(url.split('#')[0], init);
39+
const status = Number(response.headers.get(REDIRECT_HEADER));
40+
const location = response.headers.get('Location');
41+
if (response.status !== 200 || !REDIRECT_STATUSES.has(status) || location === null) {
42+
if (response.redirected) {
43+
// Older servers still use HTTP redirects. Preserve a fragment already known to us.
44+
const destination = new URL(response.url);
45+
const hash = url.indexOf('#');
46+
if (hash !== -1) {
47+
destination.hash = url.slice(hash);
48+
}
49+
redirectedTo = destination.href;
50+
}
51+
return { response, redirectedTo };
52+
}
53+
await response.body?.cancel();
54+
const base = new URL(
55+
url,
56+
window.location.origin + window.location.pathname + window.location.search,
57+
);
58+
const destination = new URL(location, response.url || base.href);
59+
if (!['http:', 'https:', 'capacitor:'].includes(destination.protocol)) {
60+
throw new Error(`Void Pages: refusing to redirect to a ${destination.protocol} URL.`);
61+
}
62+
if (!location.includes('#')) {
63+
destination.hash = base.hash;
64+
}
65+
redirectedTo = destination.href;
66+
const method = (init.method ?? 'GET').toUpperCase();
67+
const get =
68+
(status === 303 && method !== 'GET' && method !== 'HEAD') ||
69+
((status === 301 || status === 302) && method === 'POST');
70+
if (
71+
!isSameOrigin(destination, window.location.origin) ||
72+
(!followGetRedirects && (get || method === 'GET' || method === 'HEAD'))
73+
) {
74+
return { response, redirectedTo };
75+
}
76+
if (get) {
77+
for (const name of Object.keys(headers)) {
78+
if (/^content-(?:type|length|encoding|language|location)$/i.test(name)) {
79+
delete headers[name];
80+
}
81+
}
82+
init.method = 'GET';
83+
init.body = undefined;
84+
}
85+
url = destination.href;
86+
}
87+
throw new TypeError('Too many Pages redirects.');
88+
}

‎packages/void/src/runtime/routing.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
searchWithoutActionKey,
2020
searchWithoutPreservedQuery,
2121
} from '../pages/action-key.ts';
22+
import { pagesRedirectResponse } from '../pages/redirect.ts';
2223
import { SHARED_CACHE_HEADERS, authDependentRequests } from './auth-response.ts';
2324
import { VoidAssetRewriteError, type CloudContext } from './handler.ts';
2425
import { convertReturnValue } from './response.ts';
@@ -341,6 +342,7 @@ export function createRoutingRuntime(
341342
c.originalUrl = () => originalUrls.get(c.req.raw) ?? null;
342343
c.isRewritten = () => originalUrls.has(c.req.raw);
343344
await next();
345+
c.res = pagesRedirectResponse(c.req.raw, c.res);
344346
if (!trackAssetMisses) {
345347
return;
346348
}

‎packages/void/test/unit/island-action.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ describe('submitIslandAction', () => {
2424
).resolves.toEqual({ kind: 'success' });
2525
expect(fetchMock).toHaveBeenCalledExactlyOnceWith('/posts?save', {
2626
method,
27-
headers: { 'Content-Type': 'application/json' },
27+
headers: { 'Content-Type': 'application/json', 'X-VoidPages-Redirect': 'manual' },
2828
body: '{"title":"Hello","tags":["news"],"published":false}',
2929
});
3030
});

‎packages/void/test/unit/pages-client.test.ts‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -547,15 +547,28 @@ describe('createVoidRouter', () => {
547547
const documentStub = stubClientGlobals();
548548
window.location.pathname = '/editor';
549549
const scrollIntoView = vi.fn();
550-
const response = pageJson({ component: 'home', props: {}, url: '/destination', errors: null });
551-
Object.defineProperties(response, {
552-
redirected: { value: true },
553-
url: { value: 'http://localhost/destination#details' },
554-
});
555-
vi.stubGlobal(
556-
'fetch',
557-
vi.fn(async () => response),
550+
const app = new Hono();
551+
app.use(createRoutingRuntime(app, { nodeTarget: true }).contextMiddleware);
552+
app.post('/editor', (c) => c.redirect('/destination#details'));
553+
app.get('/destination', () =>
554+
pageJson({ component: 'home', props: {}, url: '/destination', errors: null }),
558555
);
556+
vi.stubGlobal('fetch', async (url: string, init: RequestInit) => {
557+
const request = new Request(new URL(url, window.location.origin), init);
558+
const response = await app.fetch(request);
559+
if (response.status >= 300 && response.status < 400) {
560+
const destination = new URL(response.headers.get('Location')!, request.url);
561+
// Browsers follow Location but never expose its fragment in response.url.
562+
destination.hash = '';
563+
const followed = await app.fetch(new Request(destination, { headers: init.headers }));
564+
Object.defineProperties(followed, {
565+
redirected: { value: true },
566+
url: { value: destination.href },
567+
});
568+
return followed;
569+
}
570+
return response;
571+
});
559572
const { router } = await createTestRouter();
560573
vi.stubGlobal('document', {
561574
...documentStub,
@@ -1729,6 +1742,7 @@ describe('createVoidRouter', () => {
17291742
headers: {
17301743
'X-VoidPages': 'true',
17311744
'X-VoidPages-Version': PAGES_PROTOCOL_VERSION,
1745+
'X-VoidPages-Redirect': 'manual',
17321746
Accept: 'application/json',
17331747
},
17341748
}),
@@ -1829,6 +1843,7 @@ describe('createVoidRouter', () => {
18291843
headers: {
18301844
'X-VoidPages': 'true',
18311845
'X-VoidPages-Version': PAGES_PROTOCOL_VERSION,
1846+
'X-VoidPages-Redirect': 'manual',
18321847
Accept: 'application/json',
18331848
},
18341849
}),

0 commit comments

Comments
 (0)