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

createServerFn.ts

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