@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/index.ts ADDED
@@ -0,0 +1,714 @@
1
+ /**
2
+ * Server functions — the builder, and the two stubs the compiler emits.
3
+ *
4
+ * A server function is written once and reachable from both sides. The compiler
5
+ * decides which side a module is being compiled for and replaces the handler
6
+ * with the matching stub: `serverRpc` on the server, where the body runs, and
7
+ * `clientRpc` on the client, where it becomes a fetch. That decision is a
8
+ * compile-time one and is never taken at runtime, so the body cannot reach a
9
+ * client bundle by being unreachable-but-present.
10
+ *
11
+ * Nothing in this file is safe to call from a browser bundle except
12
+ * `clientRpc`. `./server` is where the request handler lives.
13
+ */
14
+
15
+ export {
16
+ type ForwardedForTrust,
17
+ type RequestContext,
18
+ type ResponseDraft,
19
+ appendResponseHeader,
20
+ applyResponseDraft,
21
+ clearResponseHeaders,
22
+ collectRequestCss,
23
+ createResponseDraft,
24
+ deleteCookie,
25
+ draftedStatus,
26
+ getCookie,
27
+ getCookies,
28
+ getGlobalStartContext,
29
+ getRequest,
30
+ getRequestHeader,
31
+ markResponseSent,
32
+ getRequestHeaders,
33
+ getRequestHost,
34
+ getRequestIP,
35
+ getRequestProtocol,
36
+ getRequestUrl,
37
+ getResponseHeader,
38
+ getResponseHeaders,
39
+ getResponseStatus,
40
+ invalidateFrames,
41
+ peekRequest,
42
+ peekResponseDraft,
43
+ removeResponseHeader,
44
+ setCookie,
45
+ setResponseHeader,
46
+ setResponseHeaders,
47
+ installCssSink,
48
+ setRequestMiddlewareContext,
49
+ setResponseStatus,
50
+ takeSendContext,
51
+ withRequest,
52
+ } from "./context.ts";
53
+
54
+ export { type CookieOptions, deleteCookieLine, parseCookies, serializeCookie } from "./cookies.ts";
55
+
56
+ /**
57
+ * Sessions: a sealed cookie, with no store behind it.
58
+ *
59
+ * The interface is TanStack's; the SEALING is not: AES-GCM through WebCrypto rather than iron's AES-CBC plus a separate
60
+ * HMAC, which costs no dependency and has no encrypt-then-MAC composition to get
61
+ * wrong. A cookie sealed by one does not open in the other, and `session.ts`
62
+ * says so where it can be read.
63
+ */
64
+ /**
65
+ * Rate limiting, as a middleware — so one closure guards a server function and a
66
+ * route handler alike. The STORE has no default on purpose; `rate-limit.ts` says
67
+ * why at length.
68
+ */
69
+ export {
70
+ type RateLimitCount,
71
+ type RateLimitOptions,
72
+ type RateLimitStore,
73
+ byIP,
74
+ memoryStore,
75
+ rateLimit,
76
+ } from "./rate-limit.ts";
77
+
78
+ export {
79
+ type Session,
80
+ type SessionConfig,
81
+ type SessionData,
82
+ type SessionManager,
83
+ clearSession,
84
+ getSession,
85
+ sealSession,
86
+ unsealSession,
87
+ updateSession,
88
+ useSession,
89
+ } from "./session.ts";
90
+
91
+ /**
92
+ * The client half lives in `./client.ts` and is re-exported here.
93
+ *
94
+ * SPLIT FOR ONE REASON: the compiler's client stub imports `clientRpc`, and
95
+ * importing it from THIS module dragged `context.ts` — `node:async_hooks` — plus
96
+ * the middleware runner and the validators into every client bundle that
97
+ * reached one server function. Re-exporting keeps `import { createServerFn }
98
+ * from "@barqjs/start"` the only thing an application writes.
99
+ */
100
+ export {
101
+ type AnyServerFn,
102
+ type ChainStep,
103
+ type RpcControl,
104
+ type ServerFn,
105
+ type ServerFnArgs,
106
+ type ServerFnCallOptions,
107
+ type ServerFnMeta,
108
+ type ServerFnMethod,
109
+ type Streamed,
110
+ DATA_SUFFIX,
111
+ LIVE_SUFFIX,
112
+ NOT_FOUND,
113
+ PAYLOAD_PARAM,
114
+ REDIRECT,
115
+ RPC_CALLER,
116
+ RPC_CONTEXT,
117
+ RPC_CONTROL,
118
+ RPC_PREFIX,
119
+ RPC_STREAM,
120
+ RpcNotFound,
121
+ RpcRedirect,
122
+ SERVER_FN,
123
+ STATIC_PREFIX,
124
+ ServerFnError,
125
+ clientRpc,
126
+ isServerFn,
127
+ staticFunctionMiddleware,
128
+ staticUrl,
129
+ } from "./client.ts";
130
+ export type { ServerFnInputAnswer, ServerFnIssue, ServerFnThrown } from "./client.ts";
131
+ export { type ServerTiming, serverTiming } from "./timing.ts";
132
+ export { type BindingSlot, FRAME_APPLIED_EVENT, type Slot, isFrame } from "./frames.ts";
133
+ export { type LiveIterable, type LiveStatus, live } from "./live-client.ts";
134
+
135
+ import {
136
+ type AnyServerFn,
137
+ type ChainStep,
138
+ SERVER_FN,
139
+ SERVER_FN_CHAIN,
140
+ type ServerFn,
141
+ type ServerFnMeta,
142
+ type ServerFnMethod,
143
+ type Streamed,
144
+ callOptionsOf,
145
+ dataOf,
146
+ inlineServerFns,
147
+ urlOf,
148
+ } from "./client.ts";
149
+ import { getGlobalStartContext, offerSendContext, peekRequest } from "./context.ts";
150
+ import { asFrame } from "./frames.ts";
151
+ import {
152
+ type Carries,
153
+ type ChainContribution,
154
+ type Contribution,
155
+ type Empty,
156
+ type Merged,
157
+ type Middleware,
158
+ type NoContribution,
159
+ type OpenContext,
160
+ type StandardInput,
161
+ type StandardOutput,
162
+ type StandardSchemaLike,
163
+ type Validator,
164
+ type ValidatorInput,
165
+ UncheckedInputError,
166
+ applyValidator,
167
+ flattenMiddleware,
168
+ isBuiltMiddleware,
169
+ runMiddleware,
170
+ toValidator,
171
+ } from "./middleware.ts";
172
+ import { type GlobalFunctionContext, startOptions } from "./start-instance.ts";
173
+ import type { Crossable, InputProblem, ResultProblem, StrictOn, Strictness } from "./wire-types.ts";
174
+
175
+ export type {
176
+ Crossable,
177
+ InputProblem,
178
+ ResultProblem,
179
+ StrictOn,
180
+ Strictness,
181
+ WireProblem,
182
+ } from "./wire-types.ts";
183
+
184
+ export {
185
+ type FunctionContextOf,
186
+ type GlobalFunctionContext,
187
+ type GlobalRequestContext,
188
+ type Register,
189
+ type RequestContextOf,
190
+ type StartInstance,
191
+ type StartOptions,
192
+ clearStart,
193
+ createStart,
194
+ startOptions,
195
+ } from "./start-instance.ts";
196
+
197
+ /**
198
+ * Middleware and the validator surface it composes, re-exported so an
199
+ * application still writes one import. `middleware.ts` says why they live apart.
200
+ */
201
+ export {
202
+ type IsomorphicBuilder,
203
+ type IsomorphicFn,
204
+ createClientOnlyFn,
205
+ createIsomorphicFn,
206
+ createServerOnlyFn,
207
+ } from "./env.ts";
208
+
209
+ export {
210
+ type BuiltMiddleware,
211
+ type Carries,
212
+ type ChainContribution,
213
+ type ClientReplaced,
214
+ type DataAt,
215
+ type FreshMiddleware,
216
+ type FromNext,
217
+ type OwnReplaced,
218
+ type Plain,
219
+ type ValidatorReplaced,
220
+ type WithChain,
221
+ type WithClient,
222
+ type WithServer,
223
+ type WithValidator,
224
+ type ClientMiddlewareContext,
225
+ type ContributedBy,
226
+ type Contribution,
227
+ type ContributionOf,
228
+ type Empty,
229
+ type Merged,
230
+ type Middleware,
231
+ type MiddlewareContext,
232
+ type MiddlewareFn,
233
+ type MiddlewareNext,
234
+ type MiddlewareOptions,
235
+ type MiddlewareState,
236
+ type NextOptions,
237
+ type NextResult,
238
+ type NoContribution,
239
+ type OpenContext,
240
+ type RequestMiddleware,
241
+ type RequestMiddlewareContext,
242
+ type RequestMiddlewareFn,
243
+ type RequestMiddlewareNext,
244
+ type RequestMiddlewareStart,
245
+ type StandardInput,
246
+ type StandardOutput,
247
+ type StandardSchema,
248
+ type StandardSchemaLike,
249
+ type Validator,
250
+ type ValidatorInput,
251
+ InputError,
252
+ UncheckedInputError,
253
+ ValidationError,
254
+ applyValidator,
255
+ createMiddleware,
256
+ isInputError,
257
+ flattenMiddleware,
258
+ isBuiltMiddleware,
259
+ runMiddleware,
260
+ runRequestMiddleware,
261
+ toValidator,
262
+ } from "./middleware.ts";
263
+
264
+ export {
265
+ type AnySerializationAdapter,
266
+ type SerializationAdapter,
267
+ createSerializationAdapter,
268
+ } from "@barqjs/server/codec";
269
+
270
+ /** TanStack's `json`: a JSON `Response`, which a handler returns as its answer. */
271
+ export function json(payload: unknown, init?: ResponseInit): Response {
272
+ return Response.json(payload, init);
273
+ }
274
+
275
+ export async function checkInput(
276
+ built: { readonly validator: Validator<unknown> | null },
277
+ raw: unknown,
278
+ /**
279
+ * Whether a MIDDLEWARE in the chain declared a validator.
280
+ *
281
+ * The refusal below asks "does anything expect input?", and before middleware
282
+ * validators existed the function's own was the only thing that could answer.
283
+ * A chain that validates has opened the channel just as surely, so refusing
284
+ * here would make `.validator(schema)` on a middleware unusable by any
285
+ * function that declares none of its own — which is the whole point of
286
+ * putting one there.
287
+ */
288
+ chainValidates = false,
289
+ ): Promise<unknown> {
290
+ if (built.validator === null) {
291
+ // `undefined` is what a no-argument call sends, and it is the only input a
292
+ // function with no validator accepts.
293
+ if (raw !== undefined && !chainValidates) throw new UncheckedInputError();
294
+ return raw;
295
+ }
296
+ return applyValidator(built.validator, raw);
297
+ }
298
+
299
+ /**
300
+ * What a handler is handed, which is TanStack's shape:
301
+ * `.handler(async ({ data }) => …)`.
302
+ *
303
+ * `context` is what the middleware chain contributed, merged outermost-first,
304
+ * and typed by what each middleware passed to `next({ context })`.
305
+ * `signal` aborts with the request, so a handler can hand it to `fetch` and a
306
+ * client that navigates away stops paying for the work.
307
+ */
308
+ export interface HandlerContext<In, Context extends object = Empty> {
309
+ readonly data: In;
310
+ readonly context: OpenContext<Context>;
311
+ readonly signal: AbortSignal;
312
+ /** The method this function answers. */
313
+ readonly method: ServerFnMethod;
314
+ /** Which function is running, by the id it is mounted at. Empty when it is not mounted. */
315
+ readonly serverFnMeta: { readonly id: string };
316
+ }
317
+
318
+ interface Built<Data, Out, Context extends object = Empty> {
319
+ validator: Validator<unknown> | null;
320
+ middleware: readonly Middleware[];
321
+ handler: (context: HandlerContext<Data, Context>) => Out | Promise<Out>;
322
+ }
323
+
324
+ interface Staged {
325
+ readonly validator: Validator<unknown> | null;
326
+ readonly middleware: readonly Middleware[];
327
+ readonly method: ServerFnMethod;
328
+ }
329
+
330
+ /**
331
+ * Where a server function's builder is: its chain, its own validator, its
332
+ * method, and whether what crosses the wire is checked.
333
+ */
334
+ export interface ServerFnState {
335
+ readonly chain: Contribution;
336
+ readonly own: Contribution;
337
+ readonly method: ServerFnMethod;
338
+ readonly strict: Strictness;
339
+ }
340
+
341
+ export interface FreshServerFn<
342
+ Method extends ServerFnMethod,
343
+ Strict extends Strictness = true,
344
+ > extends ServerFnState {
345
+ readonly chain: NoContribution;
346
+ readonly own: NoContribution;
347
+ readonly method: Method;
348
+ readonly strict: Strict;
349
+ }
350
+
351
+ export interface FnWithChain<State extends ServerFnState, Chain> extends ServerFnState {
352
+ readonly chain: Merged<State["chain"], ChainContribution<Chain>>;
353
+ readonly own: State["own"];
354
+ readonly method: State["method"];
355
+ readonly strict: State["strict"];
356
+ }
357
+
358
+ export interface Validates<In, Out> extends Contribution {
359
+ readonly context: Empty;
360
+ readonly sent: Empty;
361
+ readonly clientContext: Empty;
362
+ readonly input: In;
363
+ readonly output: Out;
364
+ readonly validates: true;
365
+ }
366
+
367
+ export interface FnWithValidator<State extends ServerFnState, In, Out> extends ServerFnState {
368
+ readonly chain: State["chain"];
369
+ readonly own: Validates<In, Out>;
370
+ readonly method: State["method"];
371
+ readonly strict: State["strict"];
372
+ }
373
+
374
+ /**
375
+ * What a validator's input must also be: anything, unless it holds something
376
+ * the codec cannot carry, when it must be a type naming that, which nothing is.
377
+ */
378
+ export type InputCheck<State extends ServerFnState, In> =
379
+ StrictOn<State["strict"], "input"> extends true
380
+ ? Crossable<InputProblem<In, State["method"]>>
381
+ : unknown;
382
+
383
+ /** The same, for what a handler returns. */
384
+ export type ResultCheck<State extends ServerFnState, Result> =
385
+ StrictOn<State["strict"], "output"> extends true ? Crossable<ResultProblem<Result>> : unknown;
386
+
387
+ /**
388
+ * What the caller passes: the input of the first validator that runs, which is
389
+ * a middleware's when the chain validates. `undefined` when nothing validates,
390
+ * since a function that declares no validator accepts no argument.
391
+ */
392
+ export type CallerInput<State extends ServerFnState> = State["chain"]["validates"] extends true
393
+ ? State["chain"]["input"]
394
+ : State["own"]["validates"] extends true
395
+ ? State["own"]["input"]
396
+ : undefined;
397
+
398
+ /** What the handler is handed: the last validator's output. */
399
+ export type HandlerData<State extends ServerFnState> = State["own"]["validates"] extends true
400
+ ? State["own"]["output"]
401
+ : State["chain"]["validates"] extends true
402
+ ? State["chain"]["output"]
403
+ : undefined;
404
+
405
+ /** What the handler's `context` holds: the global middleware's, then its own chain's. */
406
+ export type HandlerContextOf<State extends ServerFnState> = GlobalFunctionContext &
407
+ State["chain"]["context"];
408
+
409
+ /**
410
+ * The three-state discriminator, which is SvelteKit's idea and the best value
411
+ * in the survey: no validator means any argument is a 400, and opening the
412
+ * channel costs a schema or the literal `'unchecked'`.
413
+ *
414
+ * Every step is typed: the schema decides what a caller passes and what the
415
+ * handler is handed, and each middleware's `next({ context })` decides what the
416
+ * handler's `context` holds.
417
+ */
418
+ export interface ServerFnBuilder<State extends ServerFnState = ServerFnState> {
419
+ /**
420
+ * Middleware that runs before the handler, after any listed before. A server
421
+ * function in the list stands for the middleware it declared: its guards
422
+ * run here, its handler does not.
423
+ */
424
+ middleware<const Chain extends readonly ChainStep[]>(
425
+ chain: Chain,
426
+ ): ServerFnBuilder<FnWithChain<State, Chain>>;
427
+ /**
428
+ * Open the input channel: a Standard Schema, a function that returns the
429
+ * validated value or throws, an object with a `parse`, or `"unchecked"`.
430
+ * What a caller passes is the schema's input, and what it produces is the
431
+ * type of `data` in the handler. The schema form is tried first: an arktype
432
+ * type is callable as well, and read as a function its input would be lost.
433
+ */
434
+ validator<Schema extends StandardSchemaLike>(
435
+ schema: Schema & InputCheck<State, StandardInput<Schema>>,
436
+ ): ServerFnBuilder<FnWithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;
437
+ validator<In, Out>(
438
+ validate: ((input: In) => Out) & InputCheck<State, In>,
439
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
440
+ validator<In, Out>(
441
+ schema: { readonly parse: (input: In) => Out } & InputCheck<State, In>,
442
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
443
+ validator(unchecked: "unchecked"): ServerFnBuilder<FnWithValidator<State, unknown, unknown>>;
444
+ /** `validator` under the name TanStack's release candidates used. */
445
+ inputValidator<Schema extends StandardSchemaLike>(
446
+ schema: Schema & InputCheck<State, StandardInput<Schema>>,
447
+ ): ServerFnBuilder<FnWithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;
448
+ inputValidator<In, Out>(
449
+ validate: ((input: In) => Out) & InputCheck<State, In>,
450
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
451
+ inputValidator<In, Out>(
452
+ schema: { readonly parse: (input: In) => Out } & InputCheck<State, In>,
453
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
454
+ inputValidator(unchecked: "unchecked"): ServerFnBuilder<FnWithValidator<State, unknown, unknown>>;
455
+ /**
456
+ * The body. What it returns must cross the wire: a function, a symbol, or an
457
+ * instance of a class the codec refuses is a type error here, naming where
458
+ * it is. `createServerFn({ strict: false })` turns the check off.
459
+ */
460
+ handler<Result>(
461
+ fn: ((
462
+ context: HandlerContext<HandlerData<State>, HandlerContextOf<State>>,
463
+ ) => Result | Promise<Result>) &
464
+ ResultCheck<State, Result>,
465
+ ): ServerFn<CallerInput<State>, Streamed<Awaited<Result>>, State["method"]> &
466
+ Carries<State["chain"]>;
467
+ }
468
+
469
+ /**
470
+ * What `createServerFn` accepts.
471
+ *
472
+ * `method` is TanStack's, with TanStack's default: `GET`. A function that
473
+ * writes declares `POST`, which is also the only method a form can reach. A
474
+ * link still cannot reach a `GET` one: every call carries the
475
+ * {@link RPC_CALLER} header, which nothing but script can set, and the server
476
+ * refuses a `GET` without it.
477
+ */
478
+ export interface ServerFnOptions<
479
+ Method extends ServerFnMethod = ServerFnMethod,
480
+ Strict extends Strictness = Strictness,
481
+ > {
482
+ readonly method?: Method;
483
+ /**
484
+ * Whether the types refuse an input or a result the codec cannot carry. On
485
+ * by default; `false` turns both off, `{ input: false }` or
486
+ * `{ output: false }` one side. The codec still refuses at runtime what it
487
+ * cannot carry: this only says the author knows, as for a class a
488
+ * `createSerializationAdapter` carries.
489
+ */
490
+ readonly strict?: Strict;
491
+ }
492
+
493
+ /**
494
+ * Author a server function. The value this returns is replaced by the compiler
495
+ * on both sides, so what it does when compiled by nothing is only the
496
+ * uncompiled-development path: it runs the handler in-process.
497
+ */
498
+ export function createServerFn<
499
+ Method extends ServerFnMethod = "GET",
500
+ const Strict extends Strictness = true,
501
+ >(options: ServerFnOptions<Method, Strict> = {}): ServerFnBuilder<FreshServerFn<Method, Strict>> {
502
+ // A runtime refusal beside the type one, because a JavaScript application has
503
+ // no type to fail.
504
+ const method = options.method ?? "GET";
505
+ if (method !== "POST" && method !== "GET") {
506
+ throw new TypeError(
507
+ `[barq] \`createServerFn({ method: ${JSON.stringify(method)} })\` is not supported: a server function answers GET or POST. ` +
508
+ "Use a route's `server.handlers` for any other method.",
509
+ );
510
+ }
511
+ return builderAt<FreshServerFn<Method, Strict>>({ validator: null, middleware: [], method });
512
+ }
513
+
514
+ /**
515
+ * A NEW BUILDER PER STEP, as `createMiddleware` is: one that mutated a shared
516
+ * record would let a base kept in a variable and finished twice hand the first
517
+ * function the second one's handler, validator and chain.
518
+ */
519
+ function builderAt<State extends ServerFnState>(staged: Staged): ServerFnBuilder<State> {
520
+ function validated<Schema extends StandardSchemaLike>(
521
+ schema: Schema & InputCheck<State, StandardInput<Schema>>,
522
+ ): ServerFnBuilder<FnWithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;
523
+ function validated<In, Out>(
524
+ validate: ((input: In) => Out) & InputCheck<State, In>,
525
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
526
+ function validated<In, Out>(
527
+ schema: { readonly parse: (input: In) => Out } & InputCheck<State, In>,
528
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
529
+ function validated(
530
+ unchecked: "unchecked",
531
+ ): ServerFnBuilder<FnWithValidator<State, unknown, unknown>>;
532
+ function validated(
533
+ schema: ValidatorInput<unknown>,
534
+ ): ServerFnBuilder<FnWithValidator<State, unknown, unknown>> {
535
+ return builderAt({ ...staged, validator: toValidator(schema) });
536
+ }
537
+ return {
538
+ middleware: <const Chain extends readonly ChainStep[]>(chain: Chain) =>
539
+ builderAt<FnWithChain<State, Chain>>({
540
+ ...staged,
541
+ middleware: [...staged.middleware, ...inlineServerFns(chain)],
542
+ }),
543
+ validator: validated,
544
+ inputValidator: validated,
545
+ handler: <Result>(
546
+ fn: ((
547
+ context: HandlerContext<HandlerData<State>, HandlerContextOf<State>>,
548
+ ) => Result | Promise<Result>) &
549
+ ResultCheck<State, Result>,
550
+ ) =>
551
+ serverRpc<
552
+ CallerInput<State>,
553
+ Result,
554
+ HandlerData<State>,
555
+ HandlerContextOf<State>,
556
+ State["method"]
557
+ >(staged.method === "GET" ? { id: "", method: "GET" } : { id: "" }, {
558
+ validator: staged.validator,
559
+ middleware: staged.middleware,
560
+ handler: fn,
561
+ }),
562
+ };
563
+ }
564
+
565
+ /**
566
+ * The server half. The compiler emits this in a module compiled for the server,
567
+ * with the real handler and the id it assigned.
568
+ *
569
+ * `In` is what a caller passes and `Data` what the handler is handed; the
570
+ * validator is what turns one into the other, at runtime.
571
+ */
572
+ export function serverRpc<
573
+ In,
574
+ Out,
575
+ Data = In,
576
+ Context extends object = Empty,
577
+ Method extends ServerFnMethod = "POST",
578
+ >(
579
+ meta: ServerFnMeta,
580
+ built: Built<Data, Out, Context>,
581
+ ): ServerFn<In, Streamed<Awaited<Out>>, Method> {
582
+ // The application's global function middleware runs ahead of the function's
583
+ // own, and is read when it is first needed: `src/start.ts` may be evaluated
584
+ // after the module that declares this function. Flattening drops a step the
585
+ // function lists again, so a guard named in both places runs once.
586
+ let composed: {
587
+ readonly from: readonly Middleware[] | undefined;
588
+ readonly chain: readonly Middleware[];
589
+ /** Whether a bare argument has somewhere to be validated before the handler. */
590
+ readonly validates: boolean;
591
+ } | null = null;
592
+ const composition = (): NonNullable<typeof composed> => {
593
+ const global = startOptions().functionMiddleware;
594
+ if (composed !== null && composed.from === global) return composed;
595
+ const chain = flattenMiddleware([...(global ?? []), ...built.middleware]);
596
+ composed = {
597
+ from: global,
598
+ chain,
599
+ validates: chain.some(
600
+ (step) => isBuiltMiddleware(step) && step.options.validator !== undefined,
601
+ ),
602
+ };
603
+ return composed;
604
+ };
605
+
606
+ const call = async (
607
+ options?: unknown,
608
+ /**
609
+ * What the CLIENT's halves sent, and it is UNTRUSTED.
610
+ *
611
+ * A second positional rather than a property of `options`, so it is
612
+ * invisible to the public `ServerFn` signature and cannot be reached by
613
+ * writing `fn({ data, context })` in application code. The request handler
614
+ * is the only caller that passes it.
615
+ *
616
+ * Handed to the chain BESIDE `context` and never merged into it. Merging it
617
+ * under would let it survive wherever no server step set the same key on
618
+ * this request, and a middleware that names the user only for a signed-in
619
+ * caller would leave `context.user` to whoever is not signed in.
620
+ */
621
+ clientContext?: Record<string, unknown>,
622
+ ): Promise<Streamed<Awaited<Out>>> => {
623
+ const input = dataOf(options);
624
+ const { chain, validates: chainValidates } = composition();
625
+ // What the chain contributed, merged as it unwinds inward. One object the
626
+ // chain mutates rather than one per step: `next({ context })` is additive
627
+ // by definition, and a handler wants the union of everything above it. It
628
+ // starts from what the request's own middleware already said.
629
+ const context: Record<string, unknown> = { ...getGlobalStartContext() };
630
+ const sendContext: Record<string, unknown> = {};
631
+ // The call's own when it named one, which only an in-process caller can.
632
+ // Otherwise the request's, so a caller that goes away stops the work it
633
+ // asked for; with neither there is nothing to abort it.
634
+ const signal =
635
+ callOptionsOf(options)?.signal ?? peekRequest()?.signal ?? new AbortController().signal;
636
+
637
+ // Middleware runs BEFORE the function's own validation. An unauthenticated
638
+ // caller should be refused without the server parsing its payload first,
639
+ // and a rejection that depended on the payload being well-formed would be
640
+ // one an attacker could skip by sending a malformed one. A MIDDLEWARE's own
641
+ // validator is the exception and has to be: its body is handed `data`.
642
+ const method = meta.method ?? "POST";
643
+ const result = await runMiddleware(chain, "server", {
644
+ data: input,
645
+ meta,
646
+ method,
647
+ signal,
648
+ context,
649
+ clientContext,
650
+ sendContext,
651
+ run: async (data) =>
652
+ built.handler({
653
+ // What the validators produced and what the chain wrote: the two
654
+ // facts the builder's types describe, which exist only at runtime.
655
+ data: (await checkInput(built, data, chainValidates)) as Data,
656
+ context: context as OpenContext<Context>,
657
+ signal,
658
+ method,
659
+ serverFnMeta: { id: meta.id },
660
+ }),
661
+ });
662
+
663
+ offerSendContext(sendContext);
664
+ // A `ReadableStream` is handed on as the async iterable every caller is
665
+ // told to expect, so one in process reads what one in a browser does, and
666
+ // a component is a frame, which a route renders and a browser asks for.
667
+ if (result instanceof ReadableStream) return valuesOf(result) as Streamed<Awaited<Out>>;
668
+ return asFrame(meta.id, input, result) as Streamed<Awaited<Out>>;
669
+ };
670
+
671
+ const fn = Object.assign(call, {
672
+ [SERVER_FN]: true as const,
673
+ [SERVER_FN_CHAIN]: built.middleware,
674
+ meta,
675
+ serverFnMeta: meta,
676
+ method: meta.method ?? "POST",
677
+ built,
678
+ url: "",
679
+ });
680
+ // Read when asked: the id is stamped when the function is mounted.
681
+ Object.defineProperty(fn, "url", { enumerable: true, get: () => urlOf(meta.id) });
682
+ return fn;
683
+ }
684
+
685
+ /**
686
+ * The middleware chain a server function carries, by REFERENCE.
687
+ *
688
+ * `serverRpc` attaches `built` to the function object, so the chain is the real
689
+ * array of closures rather than something re-derived. That matters: a build
690
+ * cannot read a chain out of source. `.middleware([m])`, `.middleware([...c])`
691
+ * and `.middleware(c.filter(Boolean))` are all runtime expressions, and
692
+ * `Middleware` is an anonymous closure with no build-visible identity — so the
693
+ * only sound comparison is `===` against the same closure the route declared.
694
+ *
695
+ * Empty for a client stub, which carries no chain because it carries no handler.
696
+ */
697
+ export function middlewareOf(fn: AnyServerFn): readonly Middleware[] {
698
+ const built = (fn as unknown as { built?: Built<unknown, unknown> }).built;
699
+ return built?.middleware ?? [];
700
+ }
701
+
702
+ /** A stream's values, releasing it when the reader leaves early. */
703
+ async function* valuesOf(stream: ReadableStream<unknown>): AsyncIterableIterator<unknown> {
704
+ const reader = stream.getReader();
705
+ try {
706
+ for (;;) {
707
+ const { done, value } = await reader.read();
708
+ if (done) return;
709
+ yield value;
710
+ }
711
+ } finally {
712
+ void reader.cancel().catch(() => {});
713
+ }
714
+ }