Skip to content

Commit 5f9e777

Browse files
ryansolidClaude via Cursorcursoragent
committed
fix(web): unwrap respond() on direct calls; make its envelope a Response
A server function called in-process during SSR that returned respond(value) handed its caller the ResponseEnvelope itself, while an HTTP caller decoded the value. A server component wrapped for its headers (respond(View, { headers })) reached the render as an object, so the frames policy never branded it and hydration serialization failed on it. The direct leg now resolves with the value (a thrown envelope rejects with it) before transformDirectResult runs, and appends the envelope's Set-Cookie headers to the render's response head; other headers and the status are the function's address's and the page's, not the document's. ResponseEnvelope now extends Response (built lazily, so the module stays free of side effects and safe where the global is missing), carrying the given response's body, status and headers. A fetch-style consumer with no Solid knowledge, such as a filesystem router's API dispatch, answers with it as-is instead of JSON-encoding the wrapper. The helpers are typed by what they mean to the caller: respond<T>() returns T, and redirect()/reload() are <T = never>(...): T, vanishing from inferred unions while taking a type from context (annotated returns, Response-typed handlers). A bare "use server" function's signature is its callers' type, with no wrapper narrowing needed. Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 8d23a5a commit 5f9e777

7 files changed

Lines changed: 363 additions & 60 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
`respond()` is typed as its value and its envelope is a real `Response`; direct calls unwrap it.
6+
7+
- **Direct calls unwrap envelopes.** A server function called in-process during SSR that returned `respond(value)` handed its caller the `ResponseEnvelope` itself, while an HTTP caller decoded `value` — and a server component wrapped for its headers (`respond(View, { headers })`) reached the render as an object, so the frames policy never branded it and the hydration serializer failed on the envelope. The direct leg now resolves with the value (a thrown envelope rejects with it) before `transformDirectResult` runs. Of the metadata, `Set-Cookie` is appended to the render's response head; other headers describe the function's own address and the status is the page's, so neither is applied to the document.
8+
- **The envelope is a `Response`.** `ResponseEnvelope` now extends `Response`, carrying the given response's body, status and headers, so a consumer with no Solid knowledge (a fetch-style API dispatch) answers with it as-is instead of JSON-encoding the wrapper. `new ResponseEnvelope(response, value)` keeps its signature; `response` is the envelope itself, or `undefined` when constructed without one. Solid's own consumers still recognize it with `isResponseEnvelope()`.
9+
- **The helpers are typed by what they mean to the caller.** `respond<T>()` returns `T`, and `redirect()`/`reload()` are `<T = never>(…): T` — control flow, not values, so they vanish from the returning function's inferred type, while an annotated return or a `Response`-typed request handler supplies `T` (a literal `never` would also mark code after a bare call unreachable). A bare `"use server"` function's own signature is therefore its callers' type, with no wrapper narrowing (`NarrowResponse`) needed. At runtime the helpers are unchanged.

‎documentation/solid-2.0/10-server-functions.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,9 @@ return reload({ revalidate: "todos" });
9494
return respond(item, { status: 201, revalidate: "items" });
9595
```
9696

97-
`respond()` produces a `ResponseEnvelope` — HTTP metadata paired with an in-memory value. The handler forwards the envelope’s headers and status and encodes the value as the body, while scripted callers receive the value transparently. Crucially, the carried response holds a **real JSON body**, so progressive-enhancement consumers (no-JS form posts, direct HTTP) get real JSON while scripted calls get the in-memory value — no reparse. Thrown envelopes ride the same path with an error tag (`X-Server-Function-Error`) and their status forwarded. Check with `isResponseEnvelope()` (a registered-symbol brand, correct across duplicated bundles — always prefer it over `instanceof`).
97+
`respond()` produces a `ResponseEnvelope` — HTTP metadata paired with an in-memory value. The handler forwards the envelope’s headers and status and encodes the value as the body, while scripted callers receive the value transparently. Crucially, the envelope **is a real `Response`** with a JSON body, so progressive-enhancement consumers (no-JS form posts, direct HTTP) get real JSON while scripted calls get the in-memory value — no reparse — and a consumer that knows nothing of Solid (a filesystem router's API dispatch, any fetch-style handler) answers with it as-is. Thrown envelopes ride the same path with an error tag (`X-Server-Function-Error`) and their status forwarded. Check with `isResponseEnvelope()` (a registered-symbol brand, correct across duplicated bundles — always prefer it over `instanceof`).
98+
99+
The helpers are typed by what they mean to the caller, not as the objects they build: `respond(value)` is typed as `value`, and `redirect()`/`reload()` — control flow for the integration, not values — never show up in the returning function's type (`<T = never>(…): T`: the `never` vanishes from the inferred union, and where the context names a type, such as an annotated return or a `Response`-typed request handler, `T` takes it). So a bare `"use server"` function returning `respond(item)` on one branch and `redirect("/login")` on another is typed `Promise<Item>`, with no wrapper needed to narrow it. A direct call during SSR receives `respond()`'s value too (a thrown envelope rejects with it), and the envelope's `Set-Cookie` headers reach the page's response; its other headers and its status describe the function's own address and are not applied to the document.
98100

99101
**Redirects to scripted callers ride a dedicated carrier.** fetch follows the redirect statuses (301/302/303/307/308) before the transport can read them, so a scripted answer masks the 3xx to 200 and carries the redirect in `X-Server-Function-Redirect`: the author’s status plus the target **resolved against the request URL** — exactly the meaning HTTP assigns the `Location` a form post would have received. Resolving server-side means `redirect("/")` and `redirect(new URL("/", url).href)` arrive identical, so an integration compares origins on a real URL instead of guessing navigation strategy from how the author spelled the target (#3102, #3107); decode with `decodeRedirectHeaderValue`. `Location` itself never rides a masked answer — on a 200 it has no HTTP meaning, and an authored `Location` on a forwarding status (a 201’s created-at) stays what it is: data. Unscripted callers get the real 3xx, and the non-followable 3xx band (304) forwards untouched for everyone.
100102

‎packages/web/server-functions/src/server.ts‎

Lines changed: 50 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1364,20 +1364,34 @@ export function createServerReference({ id, fn, name }) {
13641364
// provideEventOnce): a broken hook used to double-commit or skip the
13651365
// body silently during a render, where there is no status line to
13661366
// notice it by.
1367-
let result = provideEventOnce(provideEvent, evt, () => {
1368-
const run = () => fn.apply(thisArg, args);
1369-
// The wrapper must return run()'s value (this path stays
1370-
// synchronous for synchronous functions). Observed as a whole —
1371-
// policy included — as the `"invocation"` record on `OBSERVE.records`;
1372-
// a no-op with no listener and outside observe builds.
1373-
return observeInvocation({ id, direct: true, event: evt, args }, () =>
1374-
reportDirectFailure(
1375-
() => (wrap ? wrap(run, { id, args, event: evt, direct: true }) : run()),
1376-
id,
1377-
hook
1378-
)
1379-
);
1380-
});
1367+
let result;
1368+
try {
1369+
result = provideEventOnce(provideEvent, evt, () => {
1370+
const run = () => fn.apply(thisArg, args);
1371+
// The wrapper must return run()'s value (this path stays
1372+
// synchronous for synchronous functions). Observed as a whole —
1373+
// policy included — as the `"invocation"` record on `OBSERVE.records`;
1374+
// a no-op with no listener and outside observe builds.
1375+
return observeInvocation({ id, direct: true, event: evt, args }, () =>
1376+
reportDirectFailure(
1377+
() => (wrap ? wrap(run, { id, args, event: evt, direct: true }) : run()),
1378+
id,
1379+
hook
1380+
)
1381+
);
1382+
});
1383+
} catch (error) {
1384+
throw directEnvelopeValue(error, evt);
1385+
}
1386+
result =
1387+
result && typeof result.then === "function"
1388+
? result.then(
1389+
value => directEnvelopeValue(value, evt),
1390+
error => {
1391+
throw directEnvelopeValue(error, evt);
1392+
}
1393+
)
1394+
: directEnvelopeValue(result, evt);
13811395
// A generator or stream body runs when the caller pulls it, after the
13821396
// call-time scope above has gone. Bind the WRAPPER'S result (not merely
13831397
// fn's) so a deferred wrapInvocation keeps the same semantics.
@@ -3446,6 +3460,28 @@ function reportDirectFailure(run, id, hook) {
34463460
return result && typeof result.then === "function" ? result.then(undefined, report) : result;
34473461
}
34483462

3463+
/**
3464+
* A `respond()` envelope a direct call returned or threw, as its caller
3465+
* receives it: the value, exactly as an HTTP caller decodes it — the
3466+
* in-process leg has no Response to hand over. Of the metadata, only
3467+
* `Set-Cookie` reaches the render's response head: a cookie is state the
3468+
* function established, and the browser must receive it whichever leg ran
3469+
* the call. The rest describes the function's own address (a GET's
3470+
* `Cache-Control` is about that url, not the page composed from it) and the
3471+
* status is the page's, so neither is applied to the document.
3472+
*/
3473+
function directEnvelopeValue(result, event) {
3474+
if (!isResponseEnvelope(result)) return result;
3475+
const { response, value } = result;
3476+
const stub = event.response;
3477+
if (response && stub && stub.headers && response.headers.getSetCookie) {
3478+
for (const cookie of response.headers.getSetCookie()) {
3479+
stub.headers.append("Set-Cookie", cookie);
3480+
}
3481+
}
3482+
return value;
3483+
}
3484+
34493485
export function sanitizeServerError(value) {
34503486
if (DEV) return value;
34513487
if (isSafeError(value)) return value;

‎packages/web/src/response.ts‎

Lines changed: 79 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -22,35 +22,48 @@ const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
2222
* payloads); the HTTP handler forwards `response`'s headers and
2323
* (non-redirect) status and encodes `value` as the body through the codec,
2424
* while client-only integrations read `value` directly — no reparse.
25+
*
26+
* The envelope IS a `Response` — the given response's body, status and
27+
* headers — so a consumer that knows nothing of Solid (a filesystem
28+
* router's API dispatch, any fetch-style handler) answers with it as-is.
29+
* `response` is the envelope itself, or `undefined` when constructed
30+
* without one.
2531
*/
26-
// PURE-annotated factory (same convention as solid's MockPromise): the brand
27-
// lives on the prototype, but a bare top-level `C.prototype[X] = true` is a
28-
// module side effect that pins the class into every bundle including this
29-
// module — client bundles that never construct or brand-check an envelope
30-
// were retaining it. Wrapping the declaration and the brand assignment in one
31-
// pure expression lets the whole thing shake when unreferenced. (A `static {}`
32-
// block would NOT work: bundlers treat static blocks as side-effectful.)
33-
export interface ResponseEnvelope<T = unknown> {
32+
export interface ResponseEnvelope<T = unknown> extends Response {
3433
response: Response | undefined;
3534
value: T;
3635
}
3736

37+
// Built on first construction: `extends Response` evaluated at module load
38+
// would throw wherever the global is missing, and a top-level class with a
39+
// prototype write is a side effect that pins it into every bundle importing
40+
// this module.
41+
let EnvelopeClass: any;
42+
3843
export const ResponseEnvelope: {
3944
new <T>(response: Response | undefined, value: T): ResponseEnvelope<T>;
40-
} = /* @__PURE__ */ (() => {
41-
class ResponseEnvelope {
42-
response: Response | undefined;
43-
value: unknown;
44-
constructor(response: Response | undefined, value: unknown) {
45-
this.response = response;
46-
this.value = value;
47-
}
45+
} = function ResponseEnvelope(response: Response | undefined, value: unknown) {
46+
if (!EnvelopeClass) {
47+
EnvelopeClass = class extends Response {
48+
response: Response | undefined;
49+
value: unknown;
50+
constructor(response: Response | undefined, value: unknown) {
51+
super(
52+
response ? response.body : null,
53+
response && {
54+
status: response.status,
55+
statusText: response.statusText,
56+
headers: copyHeaders(response.headers)
57+
}
58+
);
59+
this.response = response ? this : undefined;
60+
this.value = value;
61+
}
62+
};
63+
EnvelopeClass.prototype[ENVELOPE] = true;
4864
}
49-
(ResponseEnvelope.prototype as any)[ENVELOPE] = true;
50-
return ResponseEnvelope;
51-
})() as {
52-
new <T>(response: Response | undefined, value: T): ResponseEnvelope<T>;
53-
};
65+
return new EnvelopeClass(response, value);
66+
} as any;
5467

5568
/** Whether `value` is a `ResponseEnvelope` (robust across module copies). */
5669
export function isResponseEnvelope(value: unknown): value is ResponseEnvelope {
@@ -167,25 +180,25 @@ export interface ResponseHelperInit extends ResponseInit {
167180
/** @internal */
168181
export const RESPONSE_HEADER_VALUE_LIMIT = 4096;
169182

183+
// Copy preserving multiple Set-Cookie values: Headers-to-Headers copying
184+
// through the constructor folds them into one comma-joined entry on some
185+
// runtimes (a folded Set-Cookie is corrupt). Plain-object inits cannot
186+
// carry duplicates and pass through as-is.
187+
function copyHeaders(init: HeadersInit | undefined): Headers {
188+
const source = init as Headers | undefined;
189+
if (!source || !source.getSetCookie) return new Headers(init);
190+
const headers = new Headers();
191+
source.forEach((value, key) => {
192+
if (key !== "set-cookie") headers.append(key, value);
193+
});
194+
for (const cookie of source.getSetCookie()) headers.append("Set-Cookie", cookie);
195+
return headers;
196+
}
197+
170198
function initWithRevalidate(init: number | ResponseHelperInit = {}) {
171199
const resolved: any = typeof init === "number" ? { status: init } : init;
172200
const { revalidate, ...responseInit } = resolved;
173-
// Copy preserving multiple Set-Cookie values: Headers-to-Headers copying
174-
// through the constructor folds them into one comma-joined entry on some
175-
// runtimes (a folded Set-Cookie is corrupt). Plain-object inits cannot
176-
// carry duplicates and pass through as-is.
177-
let headers: Headers;
178-
if (responseInit.headers && responseInit.headers.getSetCookie) {
179-
headers = new Headers();
180-
responseInit.headers.forEach((value: string, key: string) => {
181-
if (key !== "set-cookie") headers.append(key, value);
182-
});
183-
for (const cookie of responseInit.headers.getSetCookie()) {
184-
headers.append("Set-Cookie", cookie);
185-
}
186-
} else {
187-
headers = new Headers(responseInit.headers);
188-
}
201+
const headers = copyHeaders(responseInit.headers);
189202
if (revalidate !== undefined) {
190203
const list = Array.isArray(revalidate) ? revalidate : [revalidate];
191204
if (list.length > 1 && list.includes(REVALIDATE_ALL)) {
@@ -213,8 +226,19 @@ function initWithRevalidate(init: number | ResponseHelperInit = {}) {
213226
/**
214227
* Response redirecting to `url` (default 302). `revalidate` names the
215228
* cache keys the mutation invalidated.
229+
*
230+
* Typed so it never shows up in the type of the function returning it: a
231+
* redirect is control flow for the integration to act on, not a value.
232+
* `T` defaults to `never`, which vanishes from the inferred return type's
233+
* union; where the context expects a type (an annotated return, a
234+
* `Response`-typed request handler) `T` takes it. A literal `never` return
235+
* would also mark code after a bare call unreachable; a type parameter
236+
* does not. At runtime it is a real `Response`.
216237
*/
217-
export function redirect(url: string | Href, init: number | ResponseHelperInit = 302) {
238+
export function redirect<T = never>(
239+
url: string | Href,
240+
init: number | ResponseHelperInit = 302
241+
): T {
218242
if (typeof url !== "string" && !isHref(url)) {
219243
throw new TypeError(
220244
"redirect() expects a string URL or an Href-branded value (Symbol.for('solid.Href'))."
@@ -256,16 +280,19 @@ export function redirect(url: string | Href, init: number | ResponseHelperInit =
256280
);
257281
}
258282
headers.set("Location", encoded);
259-
return new Response(null, { ...responseInit, headers });
283+
return new Response(null, { ...responseInit, headers }) as T;
260284
}
261285

262286
/**
263287
* Empty response requesting revalidation of the named cache keys (all of
264288
* them when omitted).
289+
*
290+
* Typed as `redirect` is, for the same reason: it never shows up in the
291+
* type of the function returning it. At runtime it is a real `Response`.
265292
*/
266-
export function reload(init: ResponseHelperInit = {}) {
293+
export function reload<T = never>(init: ResponseHelperInit = {}): T {
267294
const { responseInit, headers } = initWithRevalidate(init);
268-
return new Response(null, { ...responseInit, headers });
295+
return new Response(null, { ...responseInit, headers }) as T;
269296
}
270297

271298
/**
@@ -284,8 +311,13 @@ export const NULL_BODY_STATUSES: ReadonlySet<number> = new Set([204, 205, 304]);
284311
* stays invisible: the carried response holds a plain JSON body so
285312
* consumers without the client runtime (no-JS form posts, direct HTTP)
286313
* get real JSON, while integrations read `value` — no reparse.
314+
*
315+
* Typed as `value`'s type: every caller of the function returning it —
316+
* over HTTP or in-process — receives the value, never the envelope. At
317+
* runtime it is a `ResponseEnvelope`, a real `Response` that integrations
318+
* recognize with `isResponseEnvelope()`.
287319
*/
288-
export function respond<T>(value: T, init: ResponseHelperInit = {}) {
320+
export function respond<T>(value: T, init: ResponseHelperInit = {}): T {
289321
const { responseInit, headers } = initWithRevalidate(init);
290322
// A null-body status cannot carry the passthrough JSON body — building it
291323
// would throw right here, at 200, masking the author's intent (#3095).
@@ -296,11 +328,14 @@ export function respond<T>(value: T, init: ResponseHelperInit = {}) {
296328
// else — and on a null-body status there is no body at all (#3197).
297329
for (const header of COMPOSED_BODY_FRAMING) headers.delete(header);
298330
if (NULL_BODY_STATUSES.has(responseInit.status)) {
299-
return new ResponseEnvelope(new Response(null, { ...responseInit, headers }), value);
331+
return new ResponseEnvelope(
332+
new Response(null, { ...responseInit, headers }),
333+
value
334+
) as unknown as T;
300335
}
301336
headers.set("Content-Type", "application/json");
302337
return new ResponseEnvelope(
303338
new Response(JSON.stringify(value), { ...responseInit, headers }),
304339
value
305-
);
340+
) as unknown as T;
306341
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// The response helpers are typed by what they mean to the caller of the
2+
// function returning them: `respond(value)` is `value`, and a `redirect()`
3+
// or `reload()` — control flow, not a value — never shows up. That holds
4+
// for a bare `"use server"` function, typed by its own signature, as much
5+
// as through `GET()`. Compile-only, under `test-types`.
6+
import { GET as clientGET } from "../server-functions/src/client.js";
7+
import { GET as serverGET } from "../server-functions/src/server.js";
8+
import { redirect, reload, respond } from "../src/response.js";
9+
10+
type Equal<X, Y> =
11+
(<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : false;
12+
function assertType<T extends true>(): T | void {}
13+
type Resolved<F extends (...args: any[]) => any> = Awaited<ReturnType<F>>;
14+
type User = { id: string };
15+
16+
assertType<Equal<ReturnType<typeof respond<{ id: number }>>, { id: number }>>();
17+
const redirected = () => redirect("/login");
18+
const reloaded = () => reload({ revalidate: "users" });
19+
assertType<Equal<ReturnType<typeof redirected>, never>>();
20+
assertType<Equal<ReturnType<typeof reloaded>, never>>();
21+
// A type parameter defaulting to `never`, not a literal `never` return: the
22+
// latter would also mark code after a bare call unreachable.
23+
assertType<Equal<ReturnType<typeof redirect<Response>>, Response>>();
24+
assertType<Equal<ReturnType<typeof reload<Response>>, Response>>();
25+
26+
// A bare server function's type is the caller's type.
27+
async function getStory(id: number) {
28+
"use server";
29+
return respond({ id }, { headers: { "cache-control": "public, max-age=60" } });
30+
}
31+
assertType<Equal<Resolved<typeof getStory>, { id: number }>>();
32+
33+
// Control flow on any branch leaves only the value.
34+
async function rename(id: string) {
35+
"use server";
36+
if (!id) return redirect("/login");
37+
if (id === "stale") return reload({ revalidate: "users" });
38+
return respond({ id, renamed: true }, { status: 201 });
39+
}
40+
assertType<Equal<Resolved<typeof rename>, { id: string; renamed: boolean }>>();
41+
42+
// Where the context names a type, the helper takes it: an annotated
43+
// return, or a request handler that must answer with a Response.
44+
async function annotated(id: string): Promise<User> {
45+
"use server";
46+
if (!id) return redirect("/login");
47+
return { id };
48+
}
49+
annotated;
50+
const handler: (request: Request) => Response = request =>
51+
request.headers.has("cookie") ? Response.json({ ok: true }) : redirect("/login");
52+
handler;
53+
54+
// A component wrapped for its headers is still a component to the caller.
55+
for (const GET of [clientGET, serverGET]) {
56+
const getView = GET(async () => respond(() => "view"));
57+
assertType<Equal<Resolved<typeof getView>, () => "view">>();
58+
}

0 commit comments

Comments
 (0)