Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

createServerFn.ts

967 lines25.8 KB

1import { mergeHeaders } from '@tanstack/router-core/ssr/client'
2​
3import { isRedirect, parseRedirect } from '@tanstack/router-core'
4import { isServer } from '@tanstack/router-core/isServer'
5import { TSS_SERVER_FUNCTION, TSS_SERVER_FUNCTION_FACTORY } from './constants'
6import { getStartOptions } from './getStartOptions'
7import { getStartContextServerOnly } from './getStartContextServerOnly'
8import { createNullProtoObject, safeObjectMerge } from './safeObjectMerge'
9import type { ClientFnMeta, ServerFnMeta } from './constants'
10import type {
11 AnyValidator,
12 Constrain,
13 Expand,
14 Register,
15 RegisteredSerializableInput,
16 ResolveValidatorInput,
17 ValidateSerializable,
18 ValidateSerializableInput,
19 Validator,
20} from '@tanstack/router-core'
21import type {
22 AnyFunctionMiddleware,
23 AnyRequestMiddleware,
24 AssignAllServerFnContext,
25 IntersectAllValidatorInputs,
26 IntersectAllValidatorOutputs,
27} from './createMiddleware'
28​
29export type ServerFnStrict = boolean | { input?: boolean; output?: boolean }
30​
31export interface ServerFnOptions<
32 TMethod extends Method = Method,
33 TStrict extends ServerFnStrict = true,
34> {
35 method?: TMethod
36 strict?: TStrict
38​
39export type ServerFnStrictInput<TStrict extends ServerFnStrict> =
40 TStrict extends false
41 ? false
42 : TStrict extends { input: infer TInput extends boolean }
43 ? TInput
44 : true
45​
46export type ServerFnStrictOutput<TStrict extends ServerFnStrict> =
47 TStrict extends false
48 ? false
49 : TStrict extends { output: infer TOutput extends boolean }
50 ? TOutput
51 : true
52​
53export type CreateServerFn<TRegister> = <
54 TMethod extends Method,
55 TStrict extends ServerFnStrict = true,
56 TResponse = unknown,
57 TMiddlewares = undefined,
58 TInputValidator = undefined,
59>(
60 options?: ServerFnOptions<TMethod, TStrict>,
61 __opts?: ServerFnBaseOptions<
62 TRegister,
63 TMethod,
64 TResponse,
65 TMiddlewares,
66 TInputValidator,
67 TStrict
68 >,
69) => ServerFnBuilder<TRegister, TMethod, TStrict>
70​
71export const createServerFn: CreateServerFn<Register> = (options, __opts) => {
72 const resolvedOptions = (__opts || options || {}) as ServerFnBaseOptions<
73 any,
74 any,
75 any,
76 any,
77 any,
78 any
79 >
80​
81 if (typeof resolvedOptions.method === 'undefined') {
82 resolvedOptions.method = 'GET' as Method
83 }
84​
85 const setValidator = (validator: any) => {
86 // TODO remove upon stable
87 const newOptions = {
88 ...resolvedOptions,
89 validator,
90 inputValidator: validator,
91 }
92 return createServerFn(undefined, newOptions) as any
93 }
94​
95 const res: ServerFnBuilder<Register, Method, ServerFnStrict> = {
96 options: resolvedOptions,
97 middleware: (middleware) => {
98 // multiple calls to `middleware()` merge the middlewares with the previously supplied ones
99 // this is primarily useful for letting users create their own abstractions on top of `createServerFn`
100​
101 const newMiddleware = [...(resolvedOptions.middleware || [])]
102 // forEach skips holes and ignores items appended during iteration
103 middleware.forEach((item) => {
104 if (TSS_SERVER_FUNCTION_FACTORY in item) {
105 if (item.options.middleware) {
106 newMiddleware.push(...item.options.middleware)
107 }
108 } else {
109 newMiddleware.push(item)
110 }
111 })
112​
113 const newOptions = {
114 ...resolvedOptions,
115 middleware: newMiddleware,
116 }
117 const res = createServerFn(undefined, newOptions)
118 res[TSS_SERVER_FUNCTION_FACTORY] = true
119 return res
120 },
121 validator: setValidator,
122 // TODO remove upon stable
123 inputValidator: setValidator,
124 handler: (...args) => {
125 // This function signature changes due to AST transformations
126 // in the babel plugin. We need to cast it to the correct
127 // function signature post-transformation
128 const [extractedFn, serverFn] = args as unknown as [
129 CompiledFetcherFn<Register, any>,
130 ServerFn<Register, Method, any, any, any>,
131 ]
132​
133 // The compiled client passes the RPC of the server function; anything
134 // else means the compiler missed this call, and the handler shipped.
135 // Tests run uncompiled by design.
136 if (
137 process.env.NODE_ENV !== 'production' &&
138 process.env.NODE_ENV !== 'test' &&
139 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
140 !(isServer ?? typeof window === 'undefined') &&
141 !(extractedFn as any)?.[TSS_SERVER_FUNCTION]
142 ) {
143 console.error(
144 '[TanStack Start] createServerFn().handler() was not compiled, so its server code shipped to the client and the call will not reach the server. Assign the server function to a module-level variable (export const fn = createServerFn().handler(...)), with createServerFn imported directly from your Start package (e.g. @tanstack/react-start).',
145 )
146 }
147​
148 // Keep the original function around so we can use it
149 // in the server environment
150 const newOptions = { ...resolvedOptions, extractedFn, serverFn }
151​
152 const resolvedMiddleware = [
153 ...(newOptions.middleware || []),
154 serverFnBaseToMiddleware(newOptions),
155 ]
156​
157 // We want to make sure the new function has the same
158 // properties as the original function
159​
160 // Propagate the declared HTTP method onto the extracted handler
161 // so the manifest-exported symbol (resolved by getServerFnById)
162 // carries `method`, enabling the server handler to reject
163 // mismatched HTTP methods before parsing request payloads.
164 ;(extractedFn as any).method = resolvedOptions.method
165​
166 return Object.assign(
167 async (opts?: CompiledFetcherFnOptions) => {
168 // Start by executing the client-side middleware chain
169 const result = await executeMiddleware(resolvedMiddleware, 'client', {
170 ...extractedFn,
171 ...newOptions,
172 data: opts?.data,
173 headers: opts?.headers,
174 signal: opts?.signal,
175 fetch: opts?.fetch,
176 context: createNullProtoObject(),
177 })
178​
179 const redirect = parseRedirect(result.error)
180 if (redirect) {
181 throw redirect
182 }
183​
184 if (result.error) throw result.error
185 return result.result
186 },
187 {
188 // This copies over the URL, function ID
189 ...extractedFn,
190 // Expose the declared HTTP method so the server handler
191 // can reject mismatched methods before parsing payloads
192 method: resolvedOptions.method,
193 // The extracted function on the server-side calls
194 // this function
195 __executeServer: async (opts: any) => {
196 const startContext = getStartContextServerOnly()
197 const serverContextAfterGlobalMiddlewares =
198 startContext.contextAfterGlobalMiddlewares
199 const ctx = {
200 ...extractedFn,
201 data: opts.data,
202 method: opts.method ?? resolvedOptions.method,
203 // Ensure we use the full serverFnMeta from the provider file's extractedFn
204 // (which has id, name, filename) rather than the partial one from SSR/client
205 // callers (which only has id)
206 serverFnMeta: extractedFn.serverFnMeta,
207 // Merge client context first so trusted server middleware context wins.
208 context: safeObjectMerge(
209 opts.context,
210 serverContextAfterGlobalMiddlewares,
211 ),
212 request: startContext.request,
213 }
214​
215 const result = await executeMiddleware(
216 resolvedMiddleware,
217 'server',
218 ctx,
219 ).then((d) => ({
220 // Only send the result and sendContext back to the client
221 result: d.result,
222 error: d.error,
223 context: d.sendContext,
224 }))
225​
226 return result
227 },
228 },
229 ) as any
230 },
231 } as ServerFnBuilder<Register, Method, ServerFnStrict>
232 const fun = (options?: ServerFnOptions<Method, ServerFnStrict>) => {
233 const newOptions = {
234 ...resolvedOptions,
235 ...options,
236 }
237 return createServerFn(undefined, newOptions)
238 }
239 return Object.assign(fun, res) as any
241​
242export async function executeMiddleware(
243 middlewares: Array<AnyFunctionMiddleware | AnyRequestMiddleware>,
244 env: 'client' | 'server',
245 opts: ServerFnMiddlewareOptions,
246): Promise<ServerFnMiddlewareResult> {
247 const globalMiddlewares = getStartOptions()?.functionMiddleware || []
248 let flattenedMiddlewares = flattenMiddlewares([
249 ...globalMiddlewares,
250 ...middlewares,
251 ])
252​
253 // On server, filter out middlewares that already executed in the request phase
254 // to prevent duplicate execution (issue #5239)
255 if (env === 'server') {
256 const startContext = getStartContextServerOnly({ throwIfNotFound: false })
257 if (startContext?.executedRequestMiddlewares) {
258 flattenedMiddlewares = flattenedMiddlewares.filter(
259 (m) => !startContext.executedRequestMiddlewares.has(m),
260 )
261 }
262 }
263​
264 const callNextMiddleware: NextFn = async (ctx) => {
265 // Get the next middleware
266 const nextMiddleware = flattenedMiddlewares.shift()
267​
268 // If there are no more middlewares, return the context
269 if (!nextMiddleware) {
270 return ctx
271 }
272​
273 // Execute the middleware
274 try {
275 let validator =
276 'validator' in nextMiddleware.options
277 ? nextMiddleware.options.validator
278 : undefined
279​
280 // TODO remove upon stable
281 if (!validator && 'inputValidator' in nextMiddleware.options) {
282 validator = nextMiddleware.options.inputValidator
283 }
284​
285 if (validator && env === 'server') {
286 // Execute the middleware's input function
287 ctx.data = await execValidator(validator as AnyValidator, ctx.data)
288 }
289​
290 let middlewareFn: MiddlewareFn | undefined = undefined
291 if (env === 'client') {
292 if ('client' in nextMiddleware.options) {
293 middlewareFn = nextMiddleware.options.client as
294 | MiddlewareFn
295 | undefined
296 }
297 }
298 // env === 'server'
299 else if ('server' in nextMiddleware.options) {
300 middlewareFn = nextMiddleware.options.server as MiddlewareFn | undefined
301 }
302​
303 if (middlewareFn) {
304 const userNext = async (
305 userCtx: ServerFnMiddlewareResult | undefined = {} as any,
306 ) => {
307 // Return the next middleware
308 // Use safeObjectMerge for context objects to prevent prototype pollution
309 const nextCtx = {
310 ...ctx,
311 ...userCtx,
312 context: safeObjectMerge(ctx.context, userCtx.context),
313 sendContext: safeObjectMerge(ctx.sendContext, userCtx.sendContext),
314 headers: mergeHeaders(ctx.headers, userCtx.headers),
315 _callSiteFetch: ctx._callSiteFetch,
316 fetch: ctx._callSiteFetch ?? userCtx.fetch ?? ctx.fetch,
317 result:
318 userCtx.result !== undefined
319 ? userCtx.result
320 : userCtx instanceof Response
321 ? userCtx
322 : (ctx as any).result,
323 error: userCtx.error ?? (ctx as any).error,
324 }
325​
326 const result = await callNextMiddleware(nextCtx)
327​
328 if (result.error) {
329 throw result.error
330 }
331​
332 return result
333 }
334​
335 // Execute the middleware
336 const result = await middlewareFn({
337 ...ctx,
338 next: userNext,
339 })
340​
341 // If result is NOT a ctx object, we need to return it as
342 // the { result }
343 if (isRedirect(result)) {
344 return {
345 ...ctx,
346 error: result,
347 }
348 }
349​
350 if (result instanceof Response) {
351 return {
352 ...ctx,
353 result,
354 }
355 }
356​
357 if (!(result as any)) {
358 throw new Error(
359 'User middleware returned undefined. You must call next() or return a result in your middlewares.',
360 )
361 }
362​
363 return result
364 }
365​
366 return callNextMiddleware(ctx)
367 } catch (error: any) {
368 return {
369 ...ctx,
370 error,
371 }
372 }
373 }
374​
375 // Start the middleware chain
376 return callNextMiddleware({
377 ...opts,
378 headers: opts.headers || {},
379 sendContext: opts.sendContext || {},
380 context: opts.context || createNullProtoObject(),
381 _callSiteFetch: opts.fetch,
382 })
384​
385export type CompiledFetcherFnOptions = {
386 method: Method
387 data: unknown
388 headers?: HeadersInit
389 signal?: AbortSignal
390 fetch?: CustomFetch
391 context?: any
393​
394export type Fetcher<TMiddlewares, TInputValidator, TResponse> =
395 undefined extends IntersectAllValidatorInputs<TMiddlewares, TInputValidator>
396 ? OptionalFetcher<TMiddlewares, TInputValidator, TResponse>
397 : RequiredFetcher<TMiddlewares, TInputValidator, TResponse>
398​
399export interface FetcherBase {
400 [TSS_SERVER_FUNCTION]: true
401 url: string
402 method: Method
403 __executeServer: (opts: {
404 method: Method
405 data: unknown
406 headers?: HeadersInit
407 context?: any
408 }) => Promise<unknown>
410​
411export interface OptionalFetcher<
412 TMiddlewares,
413 TInputValidator,
414 TResponse,
415> extends FetcherBase {
416 (
417 options?: OptionalFetcherDataOptions<TMiddlewares, TInputValidator>,
418 ): Promise<Awaited<TResponse>>
420​
421export interface RequiredFetcher<
422 TMiddlewares,
423 TInputValidator,
424 TResponse,
425> extends FetcherBase {
426 (
427 opts: RequiredFetcherDataOptions<TMiddlewares, TInputValidator>,
428 ): Promise<Awaited<TResponse>>
430​
431// Ideally, this type should just be `export type CustomFetch = typeof globalThis.fetch`, but that conflicts with the type overrides the `bun-types` package - a dependency of unplugin.
432// Relevant bun issues:
433// - https://github.com/oven-sh/bun/issues/23500
434// - https://github.com/oven-sh/bun/issues/23741
435export type CustomFetch = typeof fetch extends (...args: infer A) => infer R
436 ? (...args: A) => R
437 : never
438​
439export type FetcherBaseOptions = {
440 headers?: HeadersInit
441 signal?: AbortSignal
442 fetch?: CustomFetch
444​
445export interface OptionalFetcherDataOptions<
446 TMiddlewares,
447 TInputValidator,
448> extends FetcherBaseOptions {
449 data?: Expand<IntersectAllValidatorInputs<TMiddlewares, TInputValidator>>
451​
452export interface RequiredFetcherDataOptions<
453 TMiddlewares,
454 TInputValidator,
455> extends FetcherBaseOptions {
456 data: Expand<IntersectAllValidatorInputs<TMiddlewares, TInputValidator>>
458​
459export type RscStream<T> = {
460 __cacheState: T
462​
463export type Method = 'GET' | 'POST'
464​
465export type ServerFnReturnType<
466 TRegister,
467 TResponse,
468 TStrict extends ServerFnStrict = true,
469> =
470 ServerFnStrictOutput<TStrict> extends false
471 ? TResponse
472 : TResponse extends PromiseLike<infer U>
473 ? Promise<ServerFnReturnType<TRegister, U, TStrict>>
474 : TResponse extends Response
475 ? TResponse
476 : ValidateSerializableInput<TRegister, TResponse>
477​
478export type ServerFn<
479 TRegister,
480 TMethod,
481 TMiddlewares,
482 TInputValidator,
483 TResponse,
484 TStrict extends ServerFnStrict = true,
485> = (
486 ctx: ServerFnCtx<TRegister, TMethod, TMiddlewares, TInputValidator>,
487) => ServerFnReturnType<TRegister, TResponse, TStrict>
488​
489export interface ServerFnCtx<
490 TRegister,
491 TMethod,
492 TMiddlewares,
493 TInputValidator,
494> {
495 data: Expand<IntersectAllValidatorOutputs<TMiddlewares, TInputValidator>>
496 serverFnMeta: ServerFnMeta
497 context: Expand<AssignAllServerFnContext<TRegister, TMiddlewares, {}>>
498 method: TMethod
500​
501export type CompiledFetcherFn<TRegister, TResponse> = {
502 (
503 opts: CompiledFetcherFnOptions & ServerFnBaseOptions<TRegister, Method>,
504 ): Promise<TResponse>
505 url: string
506 serverFnMeta: ServerFnMeta
508​
509export type ServerFnBaseOptions<
510 TRegister,
511 TMethod extends Method = 'GET',
512 TResponse = unknown,
513 TMiddlewares = unknown,
514 TInputValidator = unknown,
515 TStrict extends ServerFnStrict = true,
516> = {
517 method: TMethod
518 strict?: TStrict
519 middleware?: Constrain<
520 TMiddlewares,
521 ReadonlyArray<AnyFunctionMiddleware | AnyRequestMiddleware>
522 >
523 validator?: ConstrainValidator<TRegister, TMethod, TInputValidator, TStrict>
524 // TODO remove upon stable
525 /** @deprecated Use `validator` instead. */
526 inputValidator?: ConstrainValidator<
527 TRegister,
528 TMethod,
529 TInputValidator,
530 TStrict
531 >
532 extractedFn?: CompiledFetcherFn<TRegister, TResponse>
533 serverFn?: ServerFn<
534 TRegister,
535 TMethod,
536 TMiddlewares,
537 TInputValidator,
538 TResponse,
539 TStrict
540 >
542​
543export type ValidateValidatorInput<
544 TRegister,
545 TMethod extends Method,
546 TInputValidator,
547 TStrict extends ServerFnStrict = true,
548> =
549 ServerFnStrictInput<TStrict> extends false
550 ? ResolveValidatorInput<TInputValidator>
551 : TMethod extends 'POST'
552 ? ResolveValidatorInput<TInputValidator> extends FormData
553 ? ResolveValidatorInput<TInputValidator>
554 : ValidateSerializable<
555 ResolveValidatorInput<TInputValidator>,
556 RegisteredSerializableInput<TRegister>
557 >
558 : ValidateSerializable<
559 ResolveValidatorInput<TInputValidator>,
560 RegisteredSerializableInput<TRegister>
561 >
562​
563export type ValidateValidator<
564 TRegister,
565 TMethod extends Method,
566 TInputValidator,
567 TStrict extends ServerFnStrict = true,
568> =
569 ValidateValidatorInput<
570 TRegister,
571 TMethod,
572 TInputValidator,
573 TStrict
574 > extends infer TInput
575 ? Validator<TInput, any>
576 : never
577​
578export type ConstrainValidator<
579 TRegister,
580 TMethod extends Method,
581 TInputValidator,
582 TStrict extends ServerFnStrict = true,
583> =
584 | (unknown extends TInputValidator
585 ? TInputValidator
586 : ResolveValidatorInput<TInputValidator> extends ValidateValidator<
587 TRegister,
588 TMethod,
589 TInputValidator,
590 TStrict
591 >
592 ? TInputValidator
593 : never)
594 | ValidateValidator<TRegister, TMethod, TInputValidator, TStrict>
595​
596export type AppendMiddlewares<TMiddlewares, TNewMiddlewares> =
597 TMiddlewares extends ReadonlyArray<any>
598 ? TNewMiddlewares extends ReadonlyArray<any>
599 ? readonly [...TMiddlewares, ...TNewMiddlewares]
600 : TMiddlewares
601 : TNewMiddlewares
602​
603export interface ServerFnMiddleware<
604 TRegister,
605 TMethod extends Method,
606 TMiddlewares,
607 TInputValidator,
608 TStrict extends ServerFnStrict,
609> {
610 middleware: <const TNewMiddlewares>(
611 middlewares: Constrain<
612 TNewMiddlewares,
613 ReadonlyArray<AnyFunctionMiddleware | AnyRequestMiddleware | AnyServerFn>
614 >,
615 ) => ServerFnAfterMiddleware<
616 TRegister,
617 TMethod,
618 AppendMiddlewares<TMiddlewares, TNewMiddlewares>,
619 TInputValidator,
620 TStrict
621 >
623​
624export interface ServerFnAfterMiddleware<
625 TRegister,
626 TMethod extends Method,
627 TMiddlewares,
628 TInputValidator,
629 TStrict extends ServerFnStrict,
631 extends
632 ServerFnWithTypes<
633 TRegister,
634 TMethod,
635 TMiddlewares,
636 TInputValidator,
637 undefined,
638 TStrict
639 >,
640 ServerFnMiddleware<TRegister, TMethod, TMiddlewares, undefined, TStrict>,
641 ServerFnValidator<TRegister, TMethod, TMiddlewares, TStrict>,
642 ServerFnHandler<
643 TRegister,
644 TMethod,
645 TMiddlewares,
646 TInputValidator,
647 TStrict
648 > {
649 <
650 TNewMethod extends Method = TMethod,
651 TNewStrict extends ServerFnStrict = TStrict,
652 >(
653 options?: ServerFnOptions<TNewMethod, TNewStrict>,
654 ): ServerFnAfterMiddleware<
655 TRegister,
656 TNewMethod,
657 TMiddlewares,
658 TInputValidator,
659 TNewStrict
660 >
662​
663export type ValidatorFn<
664 TRegister,
665 TMethod extends Method,
666 TMiddlewares,
667 TStrict extends ServerFnStrict,
668> = <TInputValidator>(
669 validator: ConstrainValidator<TRegister, TMethod, TInputValidator, TStrict>,
670) => ServerFnAfterValidator<
671 TRegister,
672 TMethod,
673 TMiddlewares,
674 TInputValidator,
675 TStrict
677​
678export interface ServerFnValidator<
679 TRegister,
680 TMethod extends Method,
681 TMiddlewares,
682 TStrict extends ServerFnStrict,
683> {
684 validator: ValidatorFn<TRegister, TMethod, TMiddlewares, TStrict>
685 // TODO remove upon stable
686 /** @deprecated Use `validator` instead. */
687 inputValidator: ValidatorFn<TRegister, TMethod, TMiddlewares, TStrict>
689​
690export interface ServerFnAfterValidator<
691 TRegister,
692 TMethod extends Method,
693 TMiddlewares,
694 TInputValidator,
695 TStrict extends ServerFnStrict,
697 extends
698 ServerFnWithTypes<
699 TRegister,
700 TMethod,
701 TMiddlewares,
702 TInputValidator,
703 undefined,
704 TStrict
705 >,
706 ServerFnMiddleware<
707 TRegister,
708 TMethod,
709 TMiddlewares,
710 TInputValidator,
711 TStrict
712 >,
713 ServerFnHandler<
714 TRegister,
715 TMethod,
716 TMiddlewares,
717 TInputValidator,
718 TStrict
719 > {}
720​
721export interface ServerFnAfterTyper<
722 TRegister,
723 TMethod extends Method,
724 TMiddlewares,
725 TInputValidator,
726 TStrict extends ServerFnStrict,
728 extends
729 ServerFnWithTypes<
730 TRegister,
731 TMethod,
732 TMiddlewares,
733 TInputValidator,
734 undefined,
735 TStrict
736 >,
737 ServerFnHandler<
738 TRegister,
739 TMethod,
740 TMiddlewares,
741 TInputValidator,
742 TStrict
743 > {}
744​
745// Handler
746export interface ServerFnHandler<
747 TRegister,
748 TMethod extends Method,
749 TMiddlewares,
750 TInputValidator,
751 TStrict extends ServerFnStrict,
752> {
753 handler: <TNewResponse>(
754 fn?: ServerFn<
755 TRegister,
756 TMethod,
757 TMiddlewares,
758 TInputValidator,
759 TNewResponse,
760 TStrict
761 >,
762 ) => Fetcher<TMiddlewares, TInputValidator, TNewResponse>
764​
765export interface ServerFnBuilder<
766 TRegister,
767 TMethod extends Method = 'GET',
768 TStrict extends ServerFnStrict = true,
770 extends
771 ServerFnWithTypes<
772 TRegister,
773 TMethod,
774 undefined,
775 undefined,
776 undefined,
777 TStrict
778 >,
779 ServerFnMiddleware<TRegister, TMethod, undefined, undefined, TStrict>,
780 ServerFnValidator<TRegister, TMethod, undefined, TStrict>,
781 ServerFnHandler<TRegister, TMethod, undefined, undefined, TStrict> {
782 <
783 TNewMethod extends Method = TMethod,
784 TNewStrict extends ServerFnStrict = TStrict,
785 >(
786 options?: ServerFnOptions<TNewMethod, TNewStrict>,
787 ): ServerFnBuilder<TRegister, TNewMethod, TNewStrict>
788 options: ServerFnBaseOptions<
789 TRegister,
790 TMethod,
791 unknown,
792 undefined,
793 undefined,
794 TStrict
795 >
797​
798export interface ServerFnWithTypes<
799 in out TRegister,
800 in out TMethod extends Method,
801 in out TMiddlewares,
802 in out TInputValidator,
803 in out TResponse,
804 in out TStrict extends ServerFnStrict,
805> {
806 '~types': ServerFnTypes<
807 TRegister,
808 TMethod,
809 TMiddlewares,
810 TInputValidator,
811 TResponse,
812 TStrict
813 >
814 options: ServerFnBaseOptions<
815 TRegister,
816 TMethod,
817 unknown,
818 undefined,
819 undefined,
820 TStrict
821 >
822 [TSS_SERVER_FUNCTION_FACTORY]: true
824​
825export type AnyServerFn = ServerFnWithTypes<any, any, any, any, any, any>
826​
827export interface ServerFnTypes<
828 in out TRegister,
829 in out TMethod extends Method,
830 in out TMiddlewares,
831 in out TInputValidator,
832 in out TResponse,
833 in out TStrict extends ServerFnStrict,
834> {
835 method: TMethod
836 strict: TStrict
837 middlewares: TMiddlewares
838 validator: TInputValidator
839 // TODO remove upon stable
840 /** @deprecated Use `validator` instead. */
841 inputValidator: TInputValidator
842 response: TResponse
843 allServerContext: AssignAllServerFnContext<TRegister, TMiddlewares>
844 allInput: IntersectAllValidatorInputs<TMiddlewares, TInputValidator>
845 allOutput: IntersectAllValidatorOutputs<TMiddlewares, TInputValidator>
847​
848export function flattenMiddlewares<
849 T extends AnyFunctionMiddleware | AnyRequestMiddleware,
850>(middlewares: Array<T>, maxDepth: number = 100): Array<T> {
851 const seen = new Set<T>()
852 const flattened: Array<T> = []
853​
854 const recurse = (middleware: Array<T>, depth: number) => {
855 if (depth > maxDepth) {
856 throw new Error(
857 `Middleware nesting depth exceeded maximum of ${maxDepth}. Check for circular references.`,
858 )
859 }
860 middleware.forEach((m) => {
861 if (m.options.middleware) {
862 recurse(m.options.middleware as Array<T>, depth + 1)
863 }
864​
865 if (!seen.has(m)) {
866 seen.add(m)
867 flattened.push(m)
868 }
869 })
870 }
871​
872 recurse(middlewares, 0)
873​
874 return flattened
876​
877export type ServerFnMiddlewareOptions = {
878 method: Method
879 data: any
880 headers?: HeadersInit
881 signal?: AbortSignal
882 sendContext?: any
883 context?: any
884 serverFnMeta: ClientFnMeta
885 fetch?: CustomFetch
886 /** @internal - Preserves the call-site fetch to ensure it has highest priority over middleware */
887 _callSiteFetch?: CustomFetch
889​
890export type ServerFnMiddlewareResult = ServerFnMiddlewareOptions & {
891 result?: unknown
892 error?: unknown
894​
895export type NextFn = (
896 ctx: ServerFnMiddlewareResult,
897) => Promise<ServerFnMiddlewareResult>
898​
899export type MiddlewareFn = (
900 ctx: ServerFnMiddlewareOptions & {
901 next: NextFn
902 },
903) => Promise<ServerFnMiddlewareResult>
904​
905export async function execValidator(
906 validator: AnyValidator,
907 input: unknown,
908): Promise<unknown> {
909 if (validator == null) return {}
910​
911 if ('~standard' in validator) {
912 const result = await validator['~standard'].validate(input)
913​
914 if (result.issues)
915 throw new Error(JSON.stringify(result.issues, undefined, 2))
916​
917 return result.value
918 }
919​
920 if ('parse' in validator) {
921 return validator.parse(input)
922 }
923​
924 if (typeof validator === 'function') {
925 return validator(input)
926 }
927​
928 throw new Error('Invalid validator type!')
930​
931function serverFnBaseToMiddleware(
932 options: ServerFnBaseOptions<any, any, any, any, any>,
933): AnyFunctionMiddleware {
934 // TODO remove upon stable
935 const validator = options.validator ?? options.inputValidator
936​
937 return {
938 '~types': undefined!,
939 options: {
940 // TODO remove upon stable
941 inputValidator: validator,
942 client: async ({ next, sendContext, fetch, ...ctx }) => {
943 const payload = {
944 ...ctx,
945 // switch the sendContext over to context
946 context: sendContext,
947 fetch,
948 }
949​
950 // Execute the extracted function
951 // but not before serializing the context
952 const res = await options.extractedFn?.(payload)
953​
954 return next(res)
955 },
956 server: async ({ next, ...ctx }) => {
957 // Execute the server function
958 const result = await options.serverFn?.(ctx)
959​
960 return next({
961 ...ctx,
962 result,
963 } as any)
964 },
965 },
966 }