@@ -5,8 +5,10 @@ import {
55} from '@angular/core' ;
66import { BASE_URL , LOCALE , REQUEST , RESPONSE } from '@analogjs/router/tokens' ;
77import type { H3Event } from 'h3' ;
8+ import type { ServerResponse } from 'node:http' ;
89
910import { detectLocale , getBaseUrl } from '../provide-server-context' ;
11+ import type { AnalogRequestContext } from '../request-handler' ;
1012import { serverFnRegistry } from './registry' ;
1113import { assertNodeContext , nodeContext } from './node-context' ;
1214import { SERVER_FN_INTERCEPTORS , runInterceptors } from './interceptors' ;
@@ -76,12 +78,22 @@ export async function dispatchServerFn(
7678 rawInput : unknown ,
7779 event : Pick < H3Event , 'node' > & { req ?: unknown } ,
7880 options : DispatchServerFnOptions = { } ,
81+ ) : Promise < DispatchResult > {
82+ if ( event . node ?. req || ! ( event . req instanceof Request ) ) {
83+ return dispatchInContext ( id , rawInput , assertNodeContext ( event ) , options ) ;
84+ }
85+ const context = nodeContext ( event . req , new URL ( event . req . url ) ) ;
86+ const result = await dispatchInContext ( id , rawInput , context , options ) ;
87+ return withContextHeaders ( result , context . res ) ;
88+ }
89+
90+ async function dispatchInContext (
91+ id : string ,
92+ rawInput : unknown ,
93+ node : AnalogRequestContext ,
94+ options : DispatchServerFnOptions ,
7995) : Promise < DispatchResult > {
8096 const { parent, providers = [ ] , method, allowedOrigins = [ ] } = options ;
81- const node =
82- event . node ?. req || ! ( event . req instanceof Request )
83- ? assertNodeContext ( event )
84- : nodeContext ( event . req , new URL ( event . req . url ) ) ;
8597 const headers = ( node . req . headers ?? { } ) as HeaderBag ;
8698
8799 // Same-origin guard runs first — before we even confirm the function exists —
@@ -189,6 +201,24 @@ export async function dispatchServerFn(
189201 return { status : 200 , body : outcome } ;
190202}
191203
204+ /** Headers set through `RESPONSE`, under those of a returned `Response`. */
205+ function withContextHeaders (
206+ result : DispatchResult ,
207+ res : ServerResponse ,
208+ ) : DispatchResult {
209+ const headers : Record < string , string | string [ ] > = { } ;
210+ for ( const [ key , value ] of Object . entries ( res . getHeaders ( ) ) ) {
211+ if ( value !== undefined ) {
212+ headers [ key ] = Array . isArray ( value ) ? value : String ( value ) ;
213+ }
214+ }
215+ for ( const [ key , value ] of Object . entries ( result . headers ?? { } ) ) {
216+ headers [ key ] =
217+ key === 'set-cookie' ? [ headers [ key ] ?? [ ] , value ] . flat ( ) : value ;
218+ }
219+ return Object . keys ( headers ) . length ? { ...result , headers } : result ;
220+ }
221+
192222function isJsonContentType ( headers : HeaderBag ) : boolean {
193223 const contentType = headers [ 'content-type' ] ;
194224 const value = Array . isArray ( contentType ) ? contentType [ 0 ] : contentType ;
0 commit comments