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

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