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