Open History to see the last commit
1import {
2 createRawStreamRPCPlugin,
3 invariant,
4 isNotFound,
5 isRedirect,
6} from '@tanstack/router-core'
7import {
8 TSS_FORMDATA_CONTEXT,
9 X_TSS_RAW_RESPONSE,
10 X_TSS_SERIALIZED,
11 getDefaultSerovalPlugins,
12 safeObjectMerge,
13} from '@tanstack/start-client-core'
14import { fromJSON, toCrossJSONAsync, toCrossJSONStream } from 'seroval'
15import { getResponse } from './request-response'
16import { getServerFnById } from './getServerFnById'
17import {
18 TSS_CONTENT_TYPE_FRAMED_VERSIONED,
19 createMultiplexedStream,
20} from './frame-protocol'
21import type { LateStreamRegistration } from './frame-protocol'
22import type { Plugin as SerovalPlugin } from 'seroval'
23β
24// Cache serovalPlugins at module level to avoid repeated calls
25let serovalPlugins: Array<SerovalPlugin<any, any>> | undefined = undefined
26β
27// Known FormData 'Content-Type' header values - module-level constant
28const FORM_DATA_CONTENT_TYPES = [
29 'multipart/form-data',
30 'application/x-www-form-urlencoded',
31]
32β
33// Maximum payload size for GET requests (1MB)
34const MAX_PAYLOAD_SIZE = 1_000_000
35β
36export const handleServerAction = async ({
37 request,
38 context,
39 serverFnId,
40}: {
41 request: Request
42 context: any
43 serverFnId: string
44}) => {
45 const method = request.method
46 const methodUpper = method.toUpperCase()
47 const url = new URL(request.url)
48β
49 const action = await getServerFnById(serverFnId, { origin: 'client' })
50β
51 // Early method check: reject mismatched HTTP methods before parsing
52 // the request payload (FormData, JSON, query string, etc.)
53 if (action.method && methodUpper !== action.method) {
54 return new Response(
55 `expected ${action.method} method. Got ${methodUpper}`,
56 {
57 status: 405,
58 headers: {
59 Allow: action.method,
60 },
61 },
62 )
63 }
64β
65 const isServerFn = request.headers.get('x-tsr-serverFn') === 'true'
66β
67 // Initialize serovalPlugins lazily (cached at module level)
68 if (!serovalPlugins) {
69 serovalPlugins = getDefaultSerovalPlugins()
70 }
71β
72 const contentType = request.headers.get('Content-Type')
73β
74 function parsePayload(payload: any) {
75 const parsedPayload = fromJSON(payload, { plugins: serovalPlugins })
76 return parsedPayload as any
77 }
78β
79 const response = await (async () => {
80 try {
81 let res = await (async () => {
82 // FormData
83 if (
84 FORM_DATA_CONTENT_TYPES.some(
85 (type) => contentType && contentType.includes(type),
86 )
87 ) {
88 // We don't support GET requests with FormData payloads... that seems impossible
89 if (methodUpper === 'GET') {
90 if (process.env.NODE_ENV !== 'production') {
91 throw new Error(
92 'Invariant failed: GET requests with FormData payloads are not supported',
93 )
94 }
95β
96 invariant()
97 }
98 const formData = await request.formData()
99 const serializedContext = formData.get(TSS_FORMDATA_CONTEXT)
100 formData.delete(TSS_FORMDATA_CONTEXT)
101β
102 const params = {
103 context,
104 data: formData,
105 method: methodUpper,
106 }
107 if (typeof serializedContext === 'string') {
108 try {
109 const parsedContext = JSON.parse(serializedContext)
110 const deserializedContext = fromJSON(parsedContext, {
111 plugins: serovalPlugins,
112 })
113 if (
114 typeof deserializedContext === 'object' &&
115 deserializedContext
116 ) {
117 params.context = safeObjectMerge(
118 deserializedContext as Record<string, unknown>,
119 context,
120 )
121 }
122 } catch (e) {
123 // Log warning for debugging but don't expose to client
124 if (process.env.NODE_ENV === 'development') {
125 console.warn('Failed to parse FormData context:', e)
126 }
127 }
128 }
129β
130 return await action(params)
131 }
132β
133 // Get requests use the query string
134 if (methodUpper === 'GET') {
135 // Get payload directly from searchParams
136 const payloadParam = url.searchParams.get('payload')
137 // Reject oversized payloads to prevent DoS
138 if (payloadParam && payloadParam.length > MAX_PAYLOAD_SIZE) {
139 throw new Error('Payload too large')
140 }
141 // If there's a payload, we should try to parse it
142 const payload: any = payloadParam
143 ? parsePayload(JSON.parse(payloadParam))
144 : {}
145 payload.context = safeObjectMerge(payload.context, context)
146 payload.method = methodUpper
147 // Send it through!
148 return await action(payload)
149 }
150β
151 let jsonPayload
152 if (contentType?.includes('application/json')) {
153 jsonPayload = await request.json()
154 }
155β
156 const payload = jsonPayload ? parsePayload(jsonPayload) : {}
157 payload.context = safeObjectMerge(payload.context, context)
158 payload.method = methodUpper
159 return await action(payload)
160 })()
161β
162 const unwrapped = res.result || res.error
163β
164 if (isNotFound(res)) {
165 res = isNotFoundResponse(res)
166 }
167β
168 if (!isServerFn) {
169 return unwrapped
170 }
171β
172 if (unwrapped instanceof Response) {
173 if (isRedirect(unwrapped)) {
174 return unwrapped
175 }
176 unwrapped.headers.set(X_TSS_RAW_RESPONSE, 'true')
177 return unwrapped
178 }
179β
180 return serializeResult(res)
181β
182 function serializeResult(res: unknown): Response {
183 let nonStreamingBody: any = undefined
184β
185 const alsResponse = getResponse()
186 if (res !== undefined) {
187 // Collect raw streams encountered during initial synchronous serialization
188 const rawStreams = new Map<number, ReadableStream<Uint8Array>>()
189β
190 // Track whether we're still in the initial synchronous phase
191 // After initial phase, new RawStreams go to lateStreamWriter
192 let initialPhase = true
193β
194 // Late stream registration for RawStreams discovered after initial pass
195 // (e.g., from resolved Promises)
196 let lateStreamWriter:
197 | WritableStreamDefaultWriter<LateStreamRegistration>
198 | undefined
199 let lateStreamReadable:
200 | ReadableStream<LateStreamRegistration>
201 | undefined = undefined
202 const pendingLateStreams: Array<LateStreamRegistration> = []
203β
204 const rawStreamPlugin = createRawStreamRPCPlugin(
205 (id: number, stream: ReadableStream<Uint8Array>) => {
206 if (initialPhase) {
207 rawStreams.set(id, stream)
208 return
209 }
210β
211 if (lateStreamWriter) {
212 // Late stream - write to the late stream channel
213 lateStreamWriter.write({ id, stream }).catch(() => {
214 // Ignore write errors - stream may be closed
215 })
216 return
217 }
218β
219 // Discovered after initial phase but before writer exists.
220 pendingLateStreams.push({ id, stream })
221 },
222 )
223β
224 // Build plugins with RawStreamRPCPlugin first (before default SSR plugin)
225 const plugins = [rawStreamPlugin, ...(serovalPlugins || [])]
226β
227 // first run without the stream in case `result` does not need streaming
228 let done = false as boolean
229 const callbacks: {
230 onParse: (value: any) => void
231 onDone: () => void
232 onError: (error: any) => void
233 } = {
234 onParse: (value) => {
235 nonStreamingBody = value
236 },
237 onDone: () => {
238 done = true
239 },
240 onError: (error) => {
241 throw error
242 },
243 }
244 toCrossJSONStream(res, {
245 refs: new Map(),
246 plugins,
247 onParse(value) {
248 callbacks.onParse(value)
249 },
250 onDone() {
251 callbacks.onDone()
252 },
253 onError: (error) => {
254 callbacks.onError(error)
255 },
256 })
257β
258 // End of initial synchronous phase - any new RawStreams are "late"
259 initialPhase = false
260β
261 // If any RawStreams are discovered after this point but before the
262 // late-stream writer exists, we buffer them and flush once the writer
263 // is ready. This avoids an occasional missed-stream race.
264β
265 // If no raw streams and done synchronously, return simple JSON
266 if (done && rawStreams.size === 0) {
267 return new Response(
268 nonStreamingBody ? JSON.stringify(nonStreamingBody) : undefined,
269 {
270 status: alsResponse.status,
271 statusText: alsResponse.statusText,
272 headers: {
273 'Content-Type': 'application/json',
274 [X_TSS_SERIALIZED]: 'true',
275 },
276 },
277 )
278 }
279β
280 // Not done synchronously or has raw streams - use framed protocol
281 // This supports late RawStreams from resolved Promises
282 const { readable, writable } =
283 new TransformStream<LateStreamRegistration>()
284 lateStreamReadable = readable
285 lateStreamWriter = writable.getWriter()
286β
287 // Flush any late streams that were discovered in the small window
288 // between end of initial serialization and writer setup.
289 for (const registration of pendingLateStreams) {
290 lateStreamWriter.write(registration).catch(() => {
291 // Ignore write errors - stream may be closed
292 })
293 }
294 pendingLateStreams.length = 0
295β
296 // Create a stream of JSON chunks
297 const jsonStream = new ReadableStream<string>({
298 start(controller) {
299 callbacks.onParse = (value) => {
300 controller.enqueue(JSON.stringify(value) + '\n')
301 }
302 callbacks.onDone = () => {
303 try {
304 controller.close()
305 } catch {
306 // Already closed
307 }
308 // Close late stream writer when JSON serialization is done
309 // Any RawStreams not yet discovered won't be sent
310 lateStreamWriter
311 ?.close()
312 .catch(() => {
313 // Ignore close errors
314 })
315 .finally(() => {
316 lateStreamWriter = undefined
317 })
318 }
319β
320 callbacks.onError = (error) => {
321 controller.error(error)
322 lateStreamWriter
323 ?.abort(error)
324 .catch(() => {
325 // Ignore abort errors
326 })
327 .finally(() => {
328 lateStreamWriter = undefined
329 })
330 }
331β
332 // Emit initial body if we have one
333 if (nonStreamingBody !== undefined) {
334 callbacks.onParse(nonStreamingBody)
335 }
336 // If serialization already completed synchronously, close now
337 // This handles the case where onDone was called during toCrossJSONStream
338 // before we overwrote callbacks.onDone
339 if (done) {
340 callbacks.onDone()
341 }
342 },
343 cancel() {
344 lateStreamWriter?.abort().catch(() => {})
345 lateStreamWriter = undefined
346 },
347 })
348β
349 // Create multiplexed stream with JSON, initial raw streams, and late streams
350 const multiplexedStream = createMultiplexedStream(
351 jsonStream,
352 rawStreams,
353 lateStreamReadable,
354 )
355β
356 return new Response(multiplexedStream, {
357 status: alsResponse.status,
358 statusText: alsResponse.statusText,
359 headers: {
360 'Content-Type': TSS_CONTENT_TYPE_FRAMED_VERSIONED,
361 [X_TSS_SERIALIZED]: 'true',
362 },
363 })
364 }
365β
366 return new Response(undefined, {
367 status: alsResponse.status,
368 statusText: alsResponse.statusText,
369 })
370 }
371 } catch (error: any) {
372 if (error instanceof Response) {
373 return error
374 }
375 // else if (
376 // isPlainObject(error) &&
377 // 'result' in error &&
378 // error.result instanceof Response
379 // ) {
380 // return error.result
381 // }
382β
383 // Currently this server-side context has no idea how to
384 // build final URLs, so we need to defer that to the client.
385 // The client will check for __redirect and __notFound keys,
386 // and if they exist, it will handle them appropriately.
387β
388 if (isNotFound(error)) {
389 return isNotFoundResponse(error)
390 }
391β
392 console.info()
393 console.info('Server Fn Error!')
394 console.info()
395 console.error(error)
396 console.info()
397β
398 const serializedError = JSON.stringify(
399 await Promise.resolve(
400 toCrossJSONAsync(error, {
401 refs: new Map(),
402 plugins: serovalPlugins,
403 }),
404 ),
405 )
406 const response = getResponse()
407 return new Response(serializedError, {
408 status: response.status ?? 500,
409 statusText: response.statusText,
410 headers: {
411 'Content-Type': 'application/json',
412 [X_TSS_SERIALIZED]: 'true',
413 },
414 })
415 }
416 })()
417β
418 return response
419}
420β
421function isNotFoundResponse(error: any) {
422 const { headers, ...rest } = error
423β
424 return new Response(JSON.stringify(rest), {
425 status: 404,
426 headers: {
427 'Content-Type': 'application/json',
428 ...(headers || {}),
429 },
430 })
431}