@barqjs/start 0.0.0-stage → 0.2.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +791 -2
  3. package/dist/client-BHyIiYxt.js +1527 -0
  4. package/dist/client-BHyIiYxt.js.map +1 -0
  5. package/dist/client-DHCV7yvQ.d.ts +440 -0
  6. package/dist/client-DHCV7yvQ.d.ts.map +1 -0
  7. package/dist/client.d.ts +3 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-qA8EyOr1.d.ts +49 -0
  10. package/dist/env-qA8EyOr1.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +44 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-Bm_-MTj6.d.ts +915 -0
  15. package/dist/index-Bm_-MTj6.d.ts.map +1 -0
  16. package/dist/index.d.ts +5 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-BdVlE8qm.d.ts +576 -0
  19. package/dist/middleware-BdVlE8qm.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +282 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +98 -0
  24. package/dist/prerender.d.ts.map +1 -0
  25. package/dist/prerender.js +289 -0
  26. package/dist/prerender.js.map +1 -0
  27. package/dist/protocol.d.ts +58 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +26 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +135 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +223 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-BV3xKmLa.js +1148 -0
  36. package/dist/server-BV3xKmLa.js.map +1 -0
  37. package/dist/server.d.ts +142 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-ChnB_xug.js +1140 -0
  41. package/dist/src-ChnB_xug.js.map +1 -0
  42. package/dist/static-fn-DgjNArBe.js +123 -0
  43. package/dist/static-fn-DgjNArBe.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +672 -0
  46. package/src/context.ts +666 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +97 -0
  50. package/src/frames-client.ts +1216 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +714 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +182 -0
  56. package/src/middleware.ts +994 -0
  57. package/src/prerender.ts +477 -0
  58. package/src/protocol.ts +61 -0
  59. package/src/rate-limit.ts +202 -0
  60. package/src/serve.ts +153 -0
  61. package/src/server.ts +990 -0
  62. package/src/session.ts +449 -0
  63. package/src/start-instance.ts +147 -0
  64. package/src/static-fn.ts +181 -0
  65. package/src/static.ts +302 -0
  66. package/src/stubs.ts +32 -0
  67. package/src/timing.ts +29 -0
  68. package/src/wire-types.ts +139 -0
package/src/client.ts ADDED
@@ -0,0 +1,672 @@
1
+ /**
2
+ * The client half of a server function, and NOTHING the server half needs.
3
+ *
4
+ * Its own module because of what importing it costs. The compiler replaces a
5
+ * server-function module's contents with `export const x = clientRpc("<id>")`,
6
+ * and that stub used to import from `@barqjs/start` — whose index re-exports
7
+ * `context.ts`, which is `node:async_hooks`. Every client bundle that reached
8
+ * one server function therefore pulled the request-context machinery, the
9
+ * middleware runner, the validators and the error classes, and Vite printed
10
+ * "node:async_hooks has been externalized for browser compatibility" on every
11
+ * build.
12
+ *
13
+ * That was survivable while a route module was `lazy()`, because the cost sat
14
+ * in that route's own chunk. It stopped being survivable when `routeTree.gen.ts`
15
+ * started importing route modules STATICALLY: measured on
16
+ * `packages/kitchen-sink`, 25.7 kB of it moved into the set every page
17
+ * preloads, for an application with two server functions on one route.
18
+ *
19
+ * So the stub imports from here. `index.ts` re-exports every name below, so an
20
+ * application still writes `import { createServerFn } from "@barqjs/start"` and
21
+ * nothing about the authoring surface changes.
22
+ */
23
+
24
+ import { decodeWire, encodeWire } from "@barqjs/server/codec";
25
+ import {
26
+ type FailedAnswer,
27
+ type ServerFnIssue,
28
+ type ServerFnThrown,
29
+ ServerFnError,
30
+ } from "./fn-error.ts";
31
+ import { applyFlight, applyFrameResponse, mountedFramesHeader } from "./frames-client.ts";
32
+ import { LIVE_CALL, type LiveRequest, registerStub } from "./stubs.ts";
33
+ import { FRAMES_HEADER, RPC_FLIGHT, RPC_FRAME } from "./frames.ts";
34
+ import {
35
+ type Middleware,
36
+ NOT_FOUND,
37
+ REDIRECT,
38
+ flattenMiddleware,
39
+ runMiddleware,
40
+ } from "./middleware.ts";
41
+ import { startOptions } from "./start-instance.ts";
42
+
43
+ export { STATIC_PREFIX, staticFunctionMiddleware, staticUrl } from "./static-fn.ts";
44
+ export { NOT_FOUND, REDIRECT } from "./middleware.ts";
45
+ export { ServerFnError, type ServerFnIssue, type ServerFnThrown } from "./fn-error.ts";
46
+ export { LIVE_CALL, type LiveRequest, clientStub } from "./stubs.ts";
47
+ export { type FrameComponent, applyFrameResponse, frameAdapter } from "./frames-client.ts";
48
+ export { type LiveIterable, type LiveStatus, live } from "./live-client.ts";
49
+ export { type BindingSlot, FRAME_APPLIED_EVENT, type Slot, isFrame } from "./frames.ts";
50
+
51
+ export const SERVER_FN: unique symbol = Symbol.for("barq.server-fn");
52
+
53
+ /** Where mounted server functions answer. */
54
+ export const RPC_PREFIX = "/_barq/fn/";
55
+
56
+ /**
57
+ * What distinguishes an RPC call from a form submission: the URL, not a header.
58
+ *
59
+ * `/_barq/fn/<id>` is what `<form action={fn}>` writes, takes `FormData`, and
60
+ * answers with a redirect a browser can follow with JS disabled.
61
+ * `/_barq/fn/<id>.data` is the JSON channel and answers with a value.
62
+ *
63
+ * React Router's `.data` suffix, and the reason is its reason: a header decides
64
+ * the response shape invisibly, and a form cannot set one. RedwoodSDK shows the
65
+ * failure — it emits the right hidden fields for a no-JS submit and never reads
66
+ * them, so the form posts, returns 200, and nothing happens.
67
+ */
68
+ export const DATA_SUFFIX = ".data";
69
+
70
+ /**
71
+ * `/_barq/fn/<id>.live` is the live address: the data address's answer, framed
72
+ * as server-sent events for as long as it stands. Its own URL, because a cache
73
+ * keys on the URL and not on a header nothing tells it to vary by.
74
+ */
75
+ export const LIVE_SUFFIX = ".live";
76
+
77
+ /**
78
+ * How the data channel says "the answer is an instruction, not a value".
79
+ *
80
+ * A HEADER rather than a body sniff, so a caller that does not care never
81
+ * parses the body to find out, and so a handler returning a plain object that
82
+ * happens to have a `to` field is never mistaken for a redirect.
83
+ */
84
+ export const RPC_CONTROL = "x-barq-rpc";
85
+
86
+ /**
87
+ * The {@link RPC_CONTROL} value for a `Response` the handler returned.
88
+ *
89
+ * The response IS the result then, and its body is whatever the handler wrote,
90
+ * so the stub hands it back whole rather than reading it as a wire value. No
91
+ * body rides under this one, which is why it is not an {@link RpcControl} kind.
92
+ */
93
+ export const RPC_RESPONSE = "response";
94
+
95
+ /**
96
+ * The {@link RPC_CONTROL} value for a `Response` a handler, a validator or a
97
+ * middleware THREW: the call rejects with that response itself, as TanStack's
98
+ * does. Its body and status are what the author wrote for the caller.
99
+ */
100
+ export const RPC_THROWN = "thrown";
101
+
102
+ /**
103
+ * The {@link RPC_CONTROL} value for an answer that arrives over time.
104
+ *
105
+ * The body is then one JSON line for each value the function yielded, each
106
+ * holding a wire-encoded value, and the stub hands the caller an async iterable
107
+ * of them. A line that says the function failed ends it with a
108
+ * {@link ServerFnError}.
109
+ */
110
+ export const RPC_STREAM = "stream";
111
+
112
+ /** One line of a streamed answer: a value, the chain's `sendContext`, or a failure. */
113
+ export type RpcStreamLine =
114
+ | { readonly v: unknown }
115
+ | { readonly c: unknown }
116
+ | { readonly e: 1; readonly t?: ServerFnThrown };
117
+
118
+ /** The body of a 400 for refused input. */
119
+ export interface ServerFnInputAnswer {
120
+ readonly error: "invalid input";
121
+ readonly message: string;
122
+ readonly issues: readonly ServerFnIssue[];
123
+ }
124
+
125
+ /**
126
+ * What a caller is handed for a handler's result.
127
+ *
128
+ * A function that returns a `ReadableStream` or an async iterable answers over
129
+ * time, and both arrive as an async iterable of the values, in the browser and
130
+ * in process alike.
131
+ */
132
+ export type Streamed<Out> =
133
+ Out extends ReadableStream<infer Value>
134
+ ? AsyncIterableIterator<Value>
135
+ : Out extends AsyncIterable<infer Value>
136
+ ? AsyncIterableIterator<Value>
137
+ : Out;
138
+
139
+ /**
140
+ * Present when a middleware's `sendContext` rides back with the result.
141
+ *
142
+ * A HEADER flagging a different body shape, which is what `RPC_CONTROL` already
143
+ * does and for the same reason: an ordinary call — every call, in almost every
144
+ * application — must not pay a second parse or a wrapper object to carry
145
+ * something it does not have. With the flag the body is `{ result, context }`;
146
+ * without it the body IS the result, byte for byte as before.
147
+ */
148
+ export const RPC_CONTEXT = "x-barq-ctx";
149
+
150
+ /** The body shape {@link RPC_CONTEXT} announces. */
151
+ export interface RpcEnvelope {
152
+ readonly result: unknown;
153
+ readonly context: unknown;
154
+ }
155
+
156
+ /**
157
+ * What rides in the body under {@link RPC_CONTROL}.
158
+ *
159
+ * `options` and `data` are wire-encoded, so a `Date` in a redirect's search or
160
+ * in a not-found's data arrives as one. Each is absent when the thrown value
161
+ * carried none, which leaves the body the two fields it otherwise is.
162
+ */
163
+ export type RpcControl =
164
+ | {
165
+ readonly kind: "redirect";
166
+ readonly to: string;
167
+ readonly status: number;
168
+ readonly options?: unknown;
169
+ }
170
+ | {
171
+ readonly kind: "not-found";
172
+ readonly message: string;
173
+ readonly data?: unknown;
174
+ readonly routeId?: string;
175
+ };
176
+
177
+ /**
178
+ * A redirect that arrived over the wire, rebuilt on the client.
179
+ *
180
+ * NOT `@barqjs/router`'s `Redirect` — this package cannot construct that one.
181
+ * It carries the same brand, so `isRedirect` from the router accepts it and the
182
+ * router navigates on it exactly as it would on a redirect a loader threw. That
183
+ * interchangeability is the whole reason those predicates are brand checks
184
+ * rather than `instanceof`.
185
+ */
186
+ export class RpcRedirect extends Error {
187
+ readonly [REDIRECT] = true as const;
188
+ readonly to: string;
189
+ readonly status: number;
190
+ readonly statusCode: number;
191
+ /**
192
+ * The navigation an options-form redirect described: `to`, `params`,
193
+ * `search`, `hash`, `replace`, `reloadDocument`, `href`. The router goes
194
+ * there in place of `to` when it is present.
195
+ */
196
+ readonly options?: Record<string, unknown>;
197
+ constructor(to: string, status: number, options?: Record<string, unknown>) {
198
+ super(`redirect to ${to}`);
199
+ this.name = "Redirect";
200
+ this.to = to;
201
+ this.status = status;
202
+ this.statusCode = status;
203
+ this.options = options;
204
+ }
205
+ }
206
+
207
+ /** The `notFound()` counterpart, branded for the same reason. */
208
+ export class RpcNotFound extends Error {
209
+ readonly [NOT_FOUND] = true as const;
210
+ readonly isNotFound = true as const;
211
+ /** What `notFound({ data })` carried, for the `notFoundComponent` that renders this. */
212
+ readonly data?: unknown;
213
+ /** The route whose `notFoundComponent` answers, when the thrower named one. */
214
+ readonly routeId?: string;
215
+ constructor(message: string, data?: unknown, routeId?: string) {
216
+ super(message);
217
+ this.name = "NotFound";
218
+ this.data = data;
219
+ this.routeId = routeId;
220
+ }
221
+ }
222
+
223
+ /** The JSON a failed call answered with, read from a copy so `error.response` stays unread. */
224
+ async function failedAnswer(response: Response): Promise<FailedAnswer | undefined> {
225
+ if (!(response.headers.get("content-type") ?? "").includes("application/json")) return undefined;
226
+ try {
227
+ return (await response.clone().json()) as FailedAnswer;
228
+ } catch {
229
+ return undefined;
230
+ }
231
+ }
232
+
233
+ /**
234
+ * The HTTP methods a server function answers. `GET` is the default, for a read
235
+ * the browser and a CDN may cache; see {@link RPC_CALLER} for what keeps a link
236
+ * from reaching one. `POST` is for a write and is the only one a form can reach.
237
+ */
238
+ export type ServerFnMethod = "GET" | "POST";
239
+
240
+ export interface ServerFnMeta {
241
+ /** Stable across edits and deploys: the module path and the export name. */
242
+ id: string;
243
+ /** Absent for `POST`, which is every function that did not ask for `GET`. */
244
+ readonly method?: ServerFnMethod;
245
+ }
246
+
247
+ /**
248
+ * The request header every GET call the stub makes carries, and is refused
249
+ * without.
250
+ *
251
+ * A link, an `<img>`, a prefetch and a navigation cannot set a header; only
252
+ * script can, and a cross-origin script that sets one is preflighted and
253
+ * refused by the origin check. So a `GET` server function stays out of reach
254
+ * of everything that is not this application's own code, which is the reason
255
+ * `GET` was once refused outright: a mutation reachable by navigation is a
256
+ * one-click CSRF carrying `SameSite=Lax` cookies.
257
+ */
258
+ export const RPC_CALLER = "x-barq-fn";
259
+
260
+ /** Where a GET call's payload rides, since a GET has no body. */
261
+ export const PAYLOAD_PARAM = "payload";
262
+
263
+ /**
264
+ * How a server function is CALLED: `fn({ data })`, and `fn()` when it takes
265
+ * none.
266
+ *
267
+ * TanStack's convention, and worth matching for a reason beyond fidelity: a
268
+ * named field leaves room for the options that
269
+ * come after it without ever changing the call shape again, and it removes the
270
+ * `adminStats(undefined)` the bare form forced on every no-argument call.
271
+ */
272
+ /**
273
+ * What a call may carry beside its `data`. TanStack's three, under their names.
274
+ */
275
+ export interface ServerFnCallOptions {
276
+ /**
277
+ * Aborts the call. In the browser the fetch is cancelled, and the server sees
278
+ * its request go away, which is what the handler's own `signal` follows.
279
+ */
280
+ readonly signal?: AbortSignal;
281
+ /**
282
+ * Sent with the request. A name set here wins over the same name from a
283
+ * client middleware's `next({ headers })`, since the call is the more
284
+ * specific of the two.
285
+ */
286
+ readonly headers?: HeadersInit;
287
+ /** Used in place of the global `fetch`, for this call alone. */
288
+ readonly fetch?: typeof fetch;
289
+ }
290
+
291
+ export type ServerFnArgs<In, Method extends ServerFnMethod = "POST"> = [undefined] extends [In]
292
+ ? // The argument is OPTIONAL exactly when `undefined` is an acceptable input,
293
+ // which covers both cases that want it: no validator at all (`In` is
294
+ // `undefined`), and `.validator("unchecked")`, whose `In` is `unknown` and
295
+ // which therefore admits `undefined` too. Asking `[In] extends [undefined]`
296
+ // instead got the first and not the second, so every `unchecked` function
297
+ // that takes nothing still had to be called with an argument.
298
+ //
299
+ // An optional ELEMENT, not a `void` one: a rest tuple with a `void` member
300
+ // does not make the parameter optional, and `fn()` stayed "Expected 1
301
+ // arguments, but got 0" until it was written this way.
302
+ [options?: ({ readonly data?: In } & ServerFnCallOptions) | FormFor<Method>]
303
+ : [options: ({ readonly data: In } & ServerFnCallOptions) | FormFor<Method>];
304
+
305
+ /** A form is a body, so only a `POST` function takes one. */
306
+ type FormFor<Method extends ServerFnMethod> = Method extends "POST" ? FormData : never;
307
+
308
+ /**
309
+ * A server function, from either side.
310
+ *
311
+ * A bare `FormData` is accepted BESIDE the options object, and only there. It is
312
+ * what `<form action={fn}>` hands the function on the enhanced path, and a
313
+ * `FormData` can never be mistaken for an options object — so the no-JS
314
+ * submission and the JS one reach the handler identically, which is the whole
315
+ * point of that path. TanStack has no counterpart to match here.
316
+ */
317
+ export type ServerFn<In, Out, Method extends ServerFnMethod = "POST"> = ((
318
+ ...args: ServerFnArgs<In, Method>
319
+ ) => Promise<Out>) & {
320
+ readonly [SERVER_FN]: true;
321
+ readonly meta: ServerFnMeta;
322
+ /** TanStack's name for `meta`: the id this function is mounted at. */
323
+ readonly serverFnMeta: ServerFnMeta;
324
+ /** The method this function answers. */
325
+ readonly method: ServerFnMethod;
326
+ /**
327
+ * Where a form posts to reach this function: what `<form action={fn}>`
328
+ * writes. Empty for a function that is not mounted, which has no endpoint.
329
+ */
330
+ readonly url: string;
331
+ };
332
+
333
+ /**
334
+ * Any server function, whatever it takes and returns.
335
+ *
336
+ * `never` in, because the input sits in a parameter: a function that takes a
337
+ * string does not accept `unknown`, and every function accepts `never`. The
338
+ * method is `never` for the same reason: it decides whether a form is a
339
+ * parameter.
340
+ */
341
+ export type AnyServerFn = ServerFn<never, unknown, never>;
342
+
343
+ /** The form endpoint of a mounted id, or nothing for a function with none. */
344
+ export function urlOf(id: string): string {
345
+ return id === "" ? "" : RPC_PREFIX + encodeURIComponent(id);
346
+ }
347
+
348
+ /** The `data` out of a call, whichever of the two shapes it arrived in. */
349
+ export function dataOf(options: unknown): unknown {
350
+ if (options instanceof FormData) return options;
351
+ if (options === undefined || options === null) return undefined;
352
+ return (options as { data?: unknown }).data;
353
+ }
354
+
355
+ /** What a call asked for beside its `data`. A bare `FormData` asks for nothing. */
356
+ export function callOptionsOf(options: unknown): ServerFnCallOptions | undefined {
357
+ if (options instanceof FormData || options === undefined || options === null) return undefined;
358
+ return options;
359
+ }
360
+
361
+ /**
362
+ * The client half. The compiler emits this in a module compiled for the client,
363
+ * with the id, the chain, and nothing else — no handler body, no validator, no
364
+ * imports the body needed.
365
+ *
366
+ * `chain` is the middlewares the function declared, and it is here so a
367
+ * `.client()` half can run around the fetch. Only the CLIENT halves survive the
368
+ * compile: `createMiddleware(...).server(fn)` has its `server` argument deleted
369
+ * in the client build, so a middleware may hold both without the server body —
370
+ * or the database import it needed — reaching the browser.
371
+ */
372
+ export function clientRpc<In, Out, Method extends ServerFnMethod = "POST">(
373
+ id: string,
374
+ declaredChain: readonly ChainStep[] = [],
375
+ declared?: { readonly method?: Method },
376
+ ): ServerFn<In, Out, Method> {
377
+ const method: ServerFnMethod = declared?.method ?? "POST";
378
+ const chain = inlineServerFns(declaredChain);
379
+ // With the application's global function middleware ahead of the function's
380
+ // own, read when first needed for the reason `serverRpc` gives.
381
+ let composed: { from: readonly Middleware[] | undefined; chain: readonly Middleware[] } | null =
382
+ null;
383
+ const composition = (): readonly Middleware[] => {
384
+ const global = startOptions().functionMiddleware;
385
+ if (composed === null || composed.from !== global) {
386
+ composed = { from: global, chain: flattenMiddleware([...(global ?? []), ...chain]) };
387
+ }
388
+ return composed.chain;
389
+ };
390
+
391
+ /**
392
+ * The fetch, as the INNERMOST step of the chain.
393
+ *
394
+ * A client middleware therefore wraps the request the way a server one wraps
395
+ * the handler: it can read what it is about to send, add to `sendContext`,
396
+ * and see the result on the way back. TanStack reaches the same arrangement
397
+ * by appending the server function itself to the chain as a middleware.
398
+ */
399
+ const send = async (
400
+ input: unknown,
401
+ sendContext: Record<string, unknown>,
402
+ /**
403
+ * THIS call's context, which is where the server chain's answer is merged.
404
+ * Absent on the path with no chain, where nothing could read it.
405
+ */
406
+ context?: Record<string, unknown>,
407
+ asked?: ServerFnCallOptions,
408
+ /** What the client halves passed to `next({ headers })`. */
409
+ chainHeaders?: Headers,
410
+ /** What the client halves passed to `next({ fetch })`, the last one winning. */
411
+ chainFetch?: typeof fetch,
412
+ /** A call at the live address, whose answer is handed back whole for `live`'s loop to read. */
413
+ live?: LiveRequest,
414
+ ): Promise<Out> => {
415
+ // FormData goes as FormData. Routing it through the value codec would hand
416
+ // the handler a plain OBJECT here and a real `FormData` on the no-JS path —
417
+ // the same function seeing two input types depending on whether JS ran,
418
+ // which is the divergence progressive enhancement exists to avoid. It also
419
+ // keeps files, which no value codec in this class carries.
420
+ const form = input instanceof FormData;
421
+ if (form && method === "GET") {
422
+ throw new TypeError(
423
+ `[barq] The server function \`${id}\` answers GET, and a GET has no body to carry a form. ` +
424
+ 'Declare it `createServerFn({ method: "POST" })` to accept a `FormData`.',
425
+ );
426
+ }
427
+ // Otherwise seroval's JSON channel, so an argument carries a Date, a Map or
428
+ // a cycle the same way a hydration seed does — and reconstructs through
429
+ // `fromJSON`, which evaluates nothing.
430
+ //
431
+ // `context` is what the CLIENT halves asked to send. It is absent from the
432
+ // payload when they asked for nothing, so an application with no client
433
+ // middleware sends exactly the bytes it sent before.
434
+ const payload = form
435
+ ? undefined
436
+ : JSON.stringify(
437
+ Object.keys(sendContext).length === 0
438
+ ? { input: encodeWire(input) }
439
+ : { input: encodeWire(input), context: encodeWire(sendContext) },
440
+ );
441
+ // No content-type for the form case: the browser sets the multipart
442
+ // boundary, and setting it by hand produces a body nothing can parse. None
443
+ // for a GET either, which has no body to describe.
444
+ let headers: HeadersInit | undefined = method === "GET" ? CALLER : form ? undefined : JSON_BODY;
445
+ // A mutation names the frames the page has mounted, so its answer can
446
+ // carry the ones it changed.
447
+ const mountedFrames = method === "POST" && live === undefined ? mountedFramesHeader() : null;
448
+ if (mountedFrames !== null) {
449
+ const withFrames = new Headers(headers);
450
+ withFrames.set(FRAMES_HEADER, mountedFrames);
451
+ headers = withFrames;
452
+ }
453
+ if (chainHeaders !== undefined || asked?.headers !== undefined) {
454
+ const merged = new Headers(chainHeaders);
455
+ if (mountedFrames !== null) merged.set(FRAMES_HEADER, mountedFrames);
456
+ if (asked?.headers !== undefined) {
457
+ for (const [name, value] of new Headers(asked.headers)) merged.set(name, value);
458
+ }
459
+ // Ours either way: the body is what this function encoded, whatever a
460
+ // caller or a middleware believes it is sending.
461
+ if (form || method === "GET") merged.delete("content-type");
462
+ else merged.set("content-type", "application/json");
463
+ if (method === "GET") merged.set(RPC_CALLER, "1");
464
+ headers = merged;
465
+ }
466
+ if (live !== undefined) {
467
+ const withPosition = new Headers(headers);
468
+ if (live.lastEventId !== null) withPosition.set("last-event-id", live.lastEventId);
469
+ headers = withPosition;
470
+ }
471
+ const endpoint =
472
+ RPC_PREFIX + encodeURIComponent(id) + (live === undefined ? DATA_SUFFIX : LIVE_SUFFIX);
473
+ const response = await (asked?.fetch ?? chainFetch ?? startOptions().serverFns?.fetch ?? fetch)(
474
+ method === "GET"
475
+ ? `${endpoint}?${PAYLOAD_PARAM}=${encodeURIComponent(payload ?? "")}`
476
+ : endpoint,
477
+ {
478
+ method,
479
+ headers,
480
+ signal: live?.signal ?? asked?.signal,
481
+ body: method === "GET" ? undefined : form ? input : payload,
482
+ credentials: "same-origin",
483
+ // `manual` so a handler that answers with its OWN 3xx — a real
484
+ // `new Response(null, { status: 302 })`, not a `throw redirect(...)` —
485
+ // is handed back as a response rather than silently followed. The
486
+ // default `follow` would fetch the target and hand the CALLER that
487
+ // page's body, which is how TanStack's fetcher turns a redirecting
488
+ // server function into an opaque HTML string.
489
+ redirect: "manual",
490
+ },
491
+ );
492
+ // A control answer is an INSTRUCTION rather than a value, and it is read
493
+ // off the header so an ordinary result never pays a second body parse.
494
+ // A BROWSER hides a redirect it was told not to follow: status 0 and no
495
+ // headers, so nothing below can recognise it. It is still the handler's
496
+ // answer, and the status check would report it as a failure with no status.
497
+ if (response.type === "opaqueredirect") return response as Out;
498
+ if (live !== undefined) return response as Out;
499
+ const control = response.headers.get(RPC_CONTROL);
500
+ // Before the status check: a response the handler returned is its answer
501
+ // whatever status it chose.
502
+ if (control === RPC_RESPONSE) return response as Out;
503
+ if (control === RPC_THROWN) throw response;
504
+ if (control === RPC_STREAM) return received(response, id, context) as Out;
505
+ if (control === RPC_FRAME) return (await applyFrameResponse(response)) as Out;
506
+ if (control === RPC_FLIGHT) {
507
+ const flown = await applyFlight(response);
508
+ if (response.headers.get(RPC_CONTEXT) === null) return flown as Out;
509
+ const envelope = flown as RpcEnvelope;
510
+ if (context !== undefined) Object.assign(context, envelope.context);
511
+ return envelope.result as Out;
512
+ }
513
+ if (control !== null) throw fromControl((await response.json()) as RpcControl);
514
+ if (!response.ok) {
515
+ throw new ServerFnError(id, response.status, response, await failedAnswer(response));
516
+ }
517
+ if (response.headers.get(RPC_CONTEXT) === null) return decodeWire<Out>(await response.json());
518
+ const envelope = decodeWire<RpcEnvelope>(await response.json());
519
+ // What the SERVER's chain sent back, merged into the same object the client
520
+ // halves have been writing. A client middleware reads it on the way out
521
+ // through the `context` it was handed, which is that object.
522
+ if (context !== undefined) Object.assign(context, envelope.context);
523
+ return envelope.result as Out;
524
+ };
525
+
526
+ const call = async (options?: unknown, live?: LiveRequest): Promise<Out> => {
527
+ const input = dataOf(options);
528
+ // NO CHAIN, NO RUNNER. Every application without a client middleware takes
529
+ // this line, and it is the line the compiler emitted before any of this
530
+ // existed — one fetch, no closures built, no objects allocated.
531
+ const asked = callOptionsOf(options);
532
+ const flattened = composition();
533
+ if (flattened.length === 0)
534
+ return send(input, EMPTY_CONTEXT, undefined, asked, undefined, undefined, live);
535
+
536
+ const context: Record<string, unknown> = {};
537
+ const sendContext: Record<string, unknown> = {};
538
+ const headers = new Headers();
539
+ const chosen: { current: typeof fetch | undefined } = { current: undefined };
540
+ return (await runMiddleware(flattened, "client", {
541
+ data: input,
542
+ meta: { id },
543
+ method,
544
+ signal: asked?.signal ?? new AbortController().signal,
545
+ context,
546
+ sendContext,
547
+ headers,
548
+ fetch: chosen,
549
+ run: (data) => send(data, sendContext, context, asked, headers, chosen.current, live),
550
+ })) as Out;
551
+ };
552
+
553
+ const meta: ServerFnMeta = method === "GET" ? { id, method } : { id };
554
+ const stub = Object.assign((options?: unknown) => call(options), {
555
+ [SERVER_FN]: true as const,
556
+ [SERVER_FN_CHAIN]: chain,
557
+ [LIVE_CALL]: (options: unknown, live: LiveRequest): Promise<Response> =>
558
+ call(options, live) as Promise<Response>,
559
+ meta,
560
+ serverFnMeta: meta,
561
+ method,
562
+ url: urlOf(id),
563
+ });
564
+ registerStub(id, stub);
565
+ return stub;
566
+ }
567
+
568
+ /**
569
+ * A streamed answer, as the values it carries.
570
+ *
571
+ * Read a line at a time, so a value is handed over when its line has arrived
572
+ * rather than when the answer is complete. Leaving the loop early cancels the
573
+ * body, which is what tells the server to stop producing.
574
+ */
575
+ async function* received(
576
+ response: Response,
577
+ id: string,
578
+ context: Record<string, unknown> | undefined,
579
+ ): AsyncIterableIterator<unknown> {
580
+ const body = response.body;
581
+ if (body === null) return;
582
+ const reader = body.getReader();
583
+ const decoder = new TextDecoder();
584
+ let pending = "";
585
+ try {
586
+ for (;;) {
587
+ const { done, value } = await reader.read();
588
+ pending += done ? decoder.decode() : decoder.decode(value, { stream: true });
589
+ let end = pending.indexOf("\n");
590
+ while (end !== -1) {
591
+ const line = JSON.parse(pending.slice(0, end)) as RpcStreamLine;
592
+ pending = pending.slice(end + 1);
593
+ if ("e" in line) throw new ServerFnError(id, 500, undefined, { thrown: line.t });
594
+ if ("c" in line) {
595
+ if (context !== undefined) Object.assign(context, decodeWire(line.c));
596
+ } else yield decodeWire(line.v);
597
+ end = pending.indexOf("\n");
598
+ }
599
+ if (done) return;
600
+ }
601
+ } finally {
602
+ void reader.cancel().catch(() => {});
603
+ }
604
+ }
605
+
606
+ /** One object for every JSON call, which only ever reads it. */
607
+ const JSON_BODY = { "content-type": "application/json" };
608
+
609
+ /** What a GET call carries in place of a body's type. */
610
+ const CALLER = { [RPC_CALLER]: "1" };
611
+
612
+ /** Shared, because the no-middleware path never writes to it. */
613
+ const EMPTY_CONTEXT: Record<string, unknown> = {};
614
+
615
+ /**
616
+ * Rebuild the throwable a control answer describes.
617
+ *
618
+ * An UNKNOWN kind is an error rather than a pass-through: it means the server is
619
+ * newer than the client and is describing something this build cannot act on,
620
+ * and returning it as a value would let a navigation instruction be rendered as
621
+ * data.
622
+ */
623
+ function fromControl(control: RpcControl): Error {
624
+ if (control.kind === "redirect") {
625
+ return new RpcRedirect(
626
+ control.to,
627
+ control.status,
628
+ control.options === undefined ? undefined : decodeWire(control.options),
629
+ );
630
+ }
631
+ if (control.kind === "not-found") {
632
+ return new RpcNotFound(
633
+ control.message,
634
+ control.data === undefined ? undefined : decodeWire(control.data),
635
+ control.routeId,
636
+ );
637
+ }
638
+ return new Error(
639
+ `[barq] server function answered with an unrecognised ${RPC_CONTROL} kind ` +
640
+ `${JSON.stringify((control as { kind: string }).kind)}; the server is newer than this client bundle.`,
641
+ );
642
+ }
643
+
644
+ /** Where a server function keeps the middleware it declared, for another to inline. */
645
+ export const SERVER_FN_CHAIN: unique symbol = Symbol.for("barq.server-fn-chain");
646
+
647
+ /** What `.middleware([...])` takes: a middleware, or a server function whose chain it inlines. */
648
+ export type ChainStep = Middleware | AnyServerFn;
649
+
650
+ /**
651
+ * A chain with each server function in it replaced by the middleware that
652
+ * function declared, which is TanStack's rule: listing a function lists its
653
+ * guards, never its handler.
654
+ */
655
+ export function inlineServerFns(chain: readonly ChainStep[]): readonly Middleware[] {
656
+ return chain.flatMap((step): readonly Middleware[] =>
657
+ isServerFn(step) ? chainOf(step) : [step as Middleware],
658
+ );
659
+ }
660
+
661
+ function chainOf(fn: AnyServerFn | ServerFn<unknown, unknown>): readonly Middleware[] {
662
+ return (
663
+ (fn as unknown as Record<symbol, readonly Middleware[] | undefined>)[SERVER_FN_CHAIN] ?? []
664
+ );
665
+ }
666
+
667
+ /** Whether a value is a server function, by brand rather than by shape. */
668
+ export function isServerFn(value: unknown): value is ServerFn<unknown, unknown> {
669
+ return (
670
+ typeof value === "function" && (value as unknown as Record<symbol, unknown>)[SERVER_FN] === true
671
+ );
672
+ }