Skip to content

Commit 7f8ab2d

Browse files
ryansolidclaude
andauthored
feat(web): a server function reference can declare its own client send (#4170)
* feat(web): wrapServerFunctionsFetch, a send layer that composes with the app's fetch An integration that answers some server-function requests itself (a prerendered build's static artifacts) had to install itself as the transport fetch, so it and an app's own configureServerFunctionsClient ({ fetch }) replaced each other depending on which ran last. A layer wraps a send that reads the configured fetch at call time, so the order no longer matters. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01NkjGmX4hAoiU9VhXNt7j3E * perf(web): leave the transport's direct send in place until a layer is added An unlayered app now ships no extra bytes: with wrapServerFunctionsFetch tree-shaken, the send variable is never assigned and minifies away. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01NkjGmX4hAoiU9VhXNt7j3E * refactor(web): a per-reference send instead of a global send layer wrapServerFunctionsFetch added a second, global transport hook. A reference can now declare its own send in its metadata instead (withMeta(fn, { fetch: (address, init, next) => ... })): the transport uses it for that function's requests with the app's configured send as next. The intent lives on the declaration, the app's fetch stays the app's, and there is nothing to order. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01NkjGmX4hAoiU9VhXNt7j3E --------- Co-authored-by: Claude <[email protected]>
1 parent 5a4b2e8 commit 7f8ab2d

4 files changed

Lines changed: 80 additions & 4 deletions

File tree

‎.changeset/reference-fetch-meta.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
A server function reference can declare its own client send with `withMeta(fn, { fetch: (address, init, next) => ... })`. The transport uses it for that function's requests, with the configured send (the app's `fetch`, or the global) as `next`, so an integration that answers some calls itself (a prerendered build's static artifacts) no longer competes with the app's `configureServerFunctionsClient({ fetch })`. Exported type `ServerFunctionsSend`.

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

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,12 @@ export type PrepareRequestHook = (
150150
context: PrepareRequestContext
151151
) => RequestInit | Promise<RequestInit>;
152152

153+
/** How the transport sends a request: `fetch`'s shape, as the runtime calls it. */
154+
export type ServerFunctionsSend = (
155+
address: string,
156+
init: RequestInit
157+
) => Response | Promise<Response>;
158+
153159
/** Options for `configureServerFunctionsClient`. */
154160
export interface ServerFunctionsClientConfig {
155161
/**
@@ -184,9 +190,10 @@ export interface ServerFunctionsClientConfig {
184190
codec?: JSONCodecOptions;
185191
/**
186192
* Sends every server-function request — retries, telemetry, a test
187-
* double, or an app's own route. Always called as `(address, init)`, the
193+
* double, or an app's own route. Called as `(address, init)`, the
188194
* address relative to the document as the global one receives it, so
189-
* `parseServerFunctionActionUrl` reads the id back out for telemetry. `null`
195+
* `parseServerFunctionActionUrl` reads the id back out for telemetry (a
196+
* trailing third argument is the transport's own; ignore it). `null`
190197
* restores the global.
191198
*
192199
* ```ts
@@ -210,7 +217,7 @@ export interface ServerFunctionsClientConfig {
210217
* The wrapper replaces delivery for the requests the runtime chooses to
211218
* send; the call-to-request mapping itself is not contractual.
212219
*/
213-
fetch?: ((address: string, init: RequestInit) => Response | Promise<Response>) | null;
220+
fetch?: ServerFunctionsSend | null;
214221
/**
215222
* Runs before every server-function fetch. Return (or mutate and return)
216223
* the RequestInit the transport will use; `context.meta` is the
@@ -656,8 +663,12 @@ async function createRequest(base, id, options, meta) {
656663
// The send, as observed: the `"request"` record leaves from here — the
657664
// final address and init, immediately before `fetch` receives them.
658665
if (IS_OBSERVE && observation) observation.request(base, init);
666+
// A reference may declare its own send (`withMeta(fn, { fetch })`): it
667+
// receives the app's as `next`, so the app's transport policy still
668+
// applies to whatever it passes on. (The app's send ignores the extra
669+
// argument, as `fetch` does.)
659670
const send = config.fetch || fetch;
660-
return send(base, init);
671+
return (meta.fetch || send)(base, init, send);
661672
}
662673

663674
async function initializeResponse(base, id, options, args, meta) {

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,29 @@ export interface ServerFunctionMetadata {
182182
* `withMeta` write wins.
183183
*/
184184
readonly name?: string;
185+
/**
186+
* This function's own send, client side: the transport calls it instead
187+
* of the configured `fetch` for every request the function makes, with
188+
* the configured send (the app's `fetch`, or the global) as `next`. For
189+
* an integration that answers a declared function's calls itself — a
190+
* prerendered build's static artifacts, a cache — while the app's
191+
* transport `fetch` stays the app's: pass on what you don't answer
192+
* through `next`. The contract is `fetch`'s (see
193+
* `ServerFunctionsClientConfig.fetch`); hydration adopts a
194+
* server-rendered read only if the send reaches the global `fetch` in the
195+
* same tick.
196+
*
197+
* ```ts
198+
* withMeta(getPosts, {
199+
* fetch: (address, init, next) => cached(address) ?? next(address, init)
200+
* });
201+
* ```
202+
*/
203+
readonly fetch?: (
204+
address: string,
205+
init: RequestInit,
206+
next: (address: string, init: RequestInit) => Response | Promise<Response>
207+
) => Response | Promise<Response>;
185208
/** User-declared transport metadata attached with `withMeta`. */
186209
readonly [key: string]: unknown;
187210
}

‎packages/web/test/server/server-functions-extensions.spec.tsx‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,43 @@ describe("server-function extension surface (built bundles)", () => {
222222
}
223223
});
224224

225+
it("sends a reference's calls through its declared fetch, with the app's as next", async () => {
226+
registerServerFunction("ext-fetch-9", async (word: string) => word);
227+
const order: string[] = [];
228+
// the reference's own send, declared before the app configures its fetch
229+
const ref = withMeta(createServerReference("ext-fetch-9"), {
230+
fetch: (address: string, init: RequestInit, next: (a: string, i: RequestInit) => any) => {
231+
order.push("own");
232+
return init.body === undefined || String(init.body).includes("cached")
233+
? new Response(JSON.stringify("from own send"), {
234+
headers: { "X-Server-Function-Format": "8" }
235+
})
236+
: next(address, init);
237+
}
238+
});
239+
configureServerFunctionsClient({
240+
fetch(address, init) {
241+
order.push("app");
242+
return deliver(address, init);
243+
}
244+
});
245+
try {
246+
expect(await ref("live")).toBe("live");
247+
expect(order).toEqual(["own", "app"]);
248+
order.length = 0;
249+
// what the reference's send answers never reaches the app's
250+
expect(await ref("cached")).toBe("from own send");
251+
expect(order).toEqual(["own"]);
252+
order.length = 0;
253+
// other references are untouched
254+
registerServerFunction("ext-fetch-10", async () => "plain");
255+
expect(await createServerReference("ext-fetch-10")()).toBe("plain");
256+
expect(order).toEqual(["app"]);
257+
} finally {
258+
configureServerFunctionsClient({ fetch: null });
259+
}
260+
});
261+
225262
it("hands the fetch the (address, init) shape", async () => {
226263
registerServerFunction("ext-fetch-1", async () => "ok");
227264
const shapes: string[] = [];

0 commit comments

Comments
 (0)