Repository navigation
build: phrase 3 - #2
Conversation
…ming rendering capabilities
|
Warning Review limit reached
Next review available in: 24 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (6)
📝 WalkthroughWalkthroughPhase 3 adds API route dispatch, streaming SSR, route loaders, middleware composition, server-function clients and handlers, TTL-based HTML caching, cache invalidation, and related tests and exports. ChangesPhase 3 server runtime
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant createApp
participant RouteLoader
participant renderStreamingPage
Client->>createApp: Request page route
createApp->>RouteLoader: Load route data
RouteLoader-->>createApp: Return loader data
createApp->>renderStreamingPage: Render page
renderStreamingPage-->>Client: Stream HTML response
sequenceDiagram
participant GeneratedClient
participant serverFnHandler
participant ACTION_ROUTES
participant ServerFunction
GeneratedClient->>serverFnHandler: POST action arguments
serverFnHandler->>ACTION_ROUTES: Resolve route and action
ACTION_ROUTES->>ServerFunction: Invoke handler
ServerFunction-->>GeneratedClient: Return JSON result
Possibly related PRs
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…agement and testing
…ng for route islands
There was a problem hiding this comment.
Actionable comments posted: 14
🧹 Nitpick comments (5)
packages/core/src/router.ts (1)
137-155: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
findMiddlewareChainduplicatesfindLayoutChainverbatim.Lines 137-155 are identical to Lines 96-114 apart from the entry type. Both entry types share
{ filePath, dirPath }, so a single generic walker would do.♻️ Suggested consolidation
+function findChain<T extends { dirPath: string }>( + routeFilePath: string, + entries: T[], + routesDir: string, +): T[] { + const chain: T[] = []; + let current = join(routeFilePath, ".."); + while (current.startsWith(routesDir)) { + const found = entries.find((e) => e.dirPath === current); + if (found) chain.unshift(found); + const parent = join(current, ".."); + if (parent === current) break; + current = parent; + } + return chain; +} + export function findMiddlewareChain( routeFilePath: string, middleware: MiddlewareEntry[], routesDir: string, ): MiddlewareEntry[] { - const routeDir = join(routeFilePath, ".."); - const chain: MiddlewareEntry[] = []; - - let current = routeDir; - while (current.startsWith(routesDir)) { - const mw = middleware.find((m) => m.dirPath === current); - if (mw) chain.unshift(mw); - const parent = join(current, ".."); - if (parent === current) break; - current = parent; - } - - return chain; + return findChain(routeFilePath, middleware, routesDir); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/router.ts` around lines 137 - 155, Consolidate the duplicated directory-walking logic in findMiddlewareChain and findLayoutChain into one generic helper that operates on entries sharing filePath and dirPath, then have both functions delegate to it while preserving their existing return types and chain ordering.packages/core/src/middleware.ts (1)
10-27: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
composeMiddlewarediscards thenextit advertises.The returned function is typed
MiddlewareFn, so callers must supply anext, but_nextis never invoked — the terminal handler is alwayshandler. IncreateApp.tsLines 254-257 theNot foundfallback is therefore dead code. Return(ctx: MiddlewareContext) => Promise<Response>instead so the contract matches behaviour.♻️ Suggested change
export function composeMiddleware( fns: MiddlewareFn[], handler: (ctx: MiddlewareContext) => Promise<Response>, -): MiddlewareFn { - return async (ctx, _next) => { +): (ctx: MiddlewareContext) => Promise<Response> { + return async (ctx) => {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/middleware.ts` around lines 10 - 27, Update composeMiddleware so its returned function is typed as (ctx: MiddlewareContext) => Promise<Response> rather than MiddlewareFn, matching the implementation that ignores _next and always terminates through handler. Keep the existing dispatch and middleware chaining behavior unchanged.packages/core/src/phase3.test.ts (2)
170-177: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win
{ ...res }spreads nothing.
Responseexposes its fields via prototype getters, so the spread contributes no own enumerable properties —statussilently falls back to 200 rather than being copied. Copy explicitly if that was the intent.♻️ Suggested change
return new Response(res.body, { - ...res, - headers: { "x-custom": "true" }, + status: res.status, + statusText: res.statusText, + headers: { "x-custom": "true" }, });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/phase3.test.ts` around lines 170 - 177, Update the response reconstruction in the “single middleware works” test to copy the intended Response properties explicitly instead of spreading res. Preserve the existing response body and custom header while ensuring status and other relevant metadata from the result of next() are retained.
302-319: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTest asserts only the response text, not that the cache was cleared.
Add a follow-up request asserting
X-Revalidated: missfor both/isr-staticand/pure-staticafter the flush; otherwise this passes even ifstaticCache.clear()is removed.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/phase3.test.ts` around lines 302 - 319, Extend the test “/__x/revalidate with no path clears all caches” after the revalidation response by fetching both /isr-static and /pure-static again and asserting each response has X-Revalidated set to “miss”, while retaining the existing “Revalidated all” assertion.packages/core/src/render.ts (1)
104-120: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winPrefer a loop over recursive
pump, and release the reader.Each chunk adds a retained async frame for the lifetime of the response; a
whileloop is flat and lets youreleaseLock()/controller.error()on failure.♻️ Suggested change
return new ReadableStream({ async start(controller) { controller.enqueue(encoder.encode(header)); const reader = reactStream.getReader(); - async function pump(): Promise<void> { - const { done, value } = await reader.read(); - if (done) { - controller.enqueue(encoder.encode(`</div>\n ${footer}`)); - controller.close(); - return; - } - controller.enqueue(value); - await pump(); - } - await pump(); + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + controller.enqueue(value); + } + controller.enqueue(encoder.encode(`</div>\n ${footer}`)); + controller.close(); + } catch (err) { + controller.error(err); + } finally { + reader.releaseLock(); + } }, });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/render.ts` around lines 104 - 120, Update the ReadableStream start handler around the local pump function to replace recursive reads with a loop that processes chunks until done, preserving the footer enqueue and controller close behavior. Ensure the reader lock is released after processing, and route read or enqueue failures through controller.error() while still releasing the reader.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/core/src/build.ts`:
- Around line 306-317: Update handleApiRoute to return Response |
Promise<Response> | null and preserve the handler’s async result when invoking
handlers; keep the 405 response for unsupported methods and null result for
unmatched routes unchanged.
- Around line 283-292: Update the apiImports generation in the build flow to use
namespace imports for each API module, matching the named-export contract
consumed by apiEntries and createApp. Keep the existing
Api${i}.GET/POST/PUT/PATCH/DELETE handler references unchanged.
- Line 309: Update the route pattern construction in toRouteEntry to escape
literal route text, preserve named parameter replacement as a capturing segment,
and translate emitted catch-all "*" segments into an explicit capture matching
the remaining path. Ensure regex metacharacters in literal route portions are
treated literally.
In `@packages/core/src/createApp.ts`:
- Around line 62-67: Change isServerFunction and the related registration flow
to opt in only explicitly declared server actions, such as functions listed in
an actions export or originating from files with a "use server" directive,
instead of treating every non-reserved export as callable. Update the action
request handling around the server-action registration and POST endpoint so
requests pass through the existing middleware chain before invocation, while
preserving the current reserved-export and HTTP-method exclusions.
- Around line 224-241: Use the resolved request pathname from new
URL(ctx.request.url).pathname as the staticCache key in the cache lookup and
write flow around the revalidation logic, replacing route.routePath. Keep the
invalidation logic around staticCache.delete(body.path) unchanged because it
will then target the same key; apply the key change at
packages/core/src/createApp.ts lines 224-241, with
packages/core/src/createApp.ts lines 284-295 requiring no direct change.
- Around line 216-222: Update the server branch around renderStreamingPage in
createApp so rejected streaming renders are caught and converted into a 500
error response, or fall back to renderPage using the existing error-handling
behavior. Preserve the successful streaming Response path and ensure
shell/render exceptions do not escape as unhandled rejections.
- Around line 141-150: Update the request handler around handlerFn so results
that are undefined do not pass to Response.json, which rejects them. Return an
appropriate successful empty Response for undefined results, while preserving
direct Response returns and JSON conversion for defined values.
- Around line 284-295: Secure handleRevalidation by requiring the established
application authentication mechanism before allowing cache deletion, returning
an appropriate unauthorized response for unauthenticated requests. Also parse
the request body defensively so empty or malformed JSON does not throw an
unhandled error; preserve path-specific deletion for valid bodies and only clear
the entire staticCache when the request is valid and intentionally omits a path.
In `@packages/core/src/render.ts`:
- Around line 29-47: Update htmlShell to stop escaping its title argument, since
renderPage and renderStaticPage already pass escaped titles and
renderStreamingPage follows the same contract. Preserve the existing title
interpolation while ensuring each title is escaped exactly once.
- Line 100: Update renderStreamingPage around renderToReadableStream to provide
an onError callback for component and Suspense rendering failures, and wrap the
streaming call in try/catch so fatal shell errors produce the established safe
error response instead of propagating an errored stream directly to
createApp.ts.
In `@packages/core/src/router.ts`:
- Around line 44-47: Update isApi in toRouteEntry to derive API detection from
the existing segments array, matching only an exact "api" path segment and using
the platform-independent split result. Preserve non-API names such as apiary and
apis.tsx as regular pages, while correctly detecting nested API directories on
all platforms.
In `@packages/core/src/server-functions.ts`:
- Around line 43-54: Update the ACTION_ROUTES registry lifecycle so rebuilds do
not retain deleted, renamed, or stale server actions. Either export a reset
function for ACTION_ROUTES and invoke it at the start of createApp’s
buildHandlers flow, or replace each route’s map rather than merging; ensure
every rebuild reflects only the currently registered functions.
- Around line 56-72: Update getServerFunctionHandler so action routes resolve
using the registered route pattern, not only an exact concrete routePath lookup.
Reuse the existing normal-route pattern matching mechanism to match
parameterized paths such as /posts/:id, then retrieve the action by actionName
from the matched route’s actions while preserving null for unmatched routes.
- Around line 74-81: Update the server-function request handler to validate the
HTTP method before registry lookups, returning 405 for every non-POST request.
Safely parse the body and require an array before invoking fn(...args); convert
empty or malformed JSON and non-array payloads into a controlled 4xx response
instead of allowing req.json() or the spread call to throw.
---
Nitpick comments:
In `@packages/core/src/middleware.ts`:
- Around line 10-27: Update composeMiddleware so its returned function is typed
as (ctx: MiddlewareContext) => Promise<Response> rather than MiddlewareFn,
matching the implementation that ignores _next and always terminates through
handler. Keep the existing dispatch and middleware chaining behavior unchanged.
In `@packages/core/src/phase3.test.ts`:
- Around line 170-177: Update the response reconstruction in the “single
middleware works” test to copy the intended Response properties explicitly
instead of spreading res. Preserve the existing response body and custom header
while ensuring status and other relevant metadata from the result of next() are
retained.
- Around line 302-319: Extend the test “/__x/revalidate with no path clears all
caches” after the revalidation response by fetching both /isr-static and
/pure-static again and asserting each response has X-Revalidated set to “miss”,
while retaining the existing “Revalidated all” assertion.
In `@packages/core/src/render.ts`:
- Around line 104-120: Update the ReadableStream start handler around the local
pump function to replace recursive reads with a loop that processes chunks until
done, preserving the footer enqueue and controller close behavior. Ensure the
reader lock is released after processing, and route read or enqueue failures
through controller.error() while still releasing the reader.
In `@packages/core/src/router.ts`:
- Around line 137-155: Consolidate the duplicated directory-walking logic in
findMiddlewareChain and findLayoutChain into one generic helper that operates on
entries sharing filePath and dirPath, then have both functions delegate to it
while preserving their existing return types and chain ordering.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: ab5c3692-eed7-4c48-86c8-5bbb69d3271a
📒 Files selected for processing (10)
TASKS.mdpackages/core/src/build.tspackages/core/src/createApp.tspackages/core/src/index.tspackages/core/src/middleware.tspackages/core/src/phase3.test.tspackages/core/src/render.tspackages/core/src/router.tspackages/core/src/server-functions.tspackages/core/tsconfig.json
| : ""; | ||
| const footer = `${propsScript ? ` ${propsScript}\n` : ""}${scripts ? ` ${scripts}\n` : ""} </body>\n</html>`; | ||
|
|
||
| const reactStream = await renderToReadableStream(node); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== files =="
git ls-files | rg '(^|/)render\.ts$|(^|/)createApp\.ts$|package\.json$' || true
echo "== render.ts outline =="
for f in $(git ls-files | rg '(^|/)render\.ts$'); do
echo "--- $f"
wc -l "$f"
ast-grep outline "$f" || true
echo "--- relevant lines"
sed -n '1,220p' "$f" | cat -n
done
echo "== createApp.ts files and render usage =="
for f in $(git ls-files | rg '(^|/)createApp\.ts$'); do
echo "--- $f"
wc -l "$f"
ast-grep outline "$f" || true
rg -n "renderToReadableStream|try\\b|catch|onError|render|node" "$f" -C 5 || true
done
echo "== renderToReadableStream references =="
rg -n "renderToReadableStream|onError" . -g '!node_modules' -g '!dist' -g '!build' || trueRepository: abdelkabirouadoukou/x
Length of output: 14169
🌐 Web query:
React renderToReadableStream options.onError stream reported error promise rejected documentation
💡 Result:
In React, the renderToReadableStream API provides an optional onError callback used for logging and error reporting [1][2]. Key behaviors regarding the onError callback and promise rejection: 1. onError Callback: This callback is triggered whenever a server-side error occurs during the rendering process, regardless of whether the error is recoverable (e.g., inside a Suspense boundary) or fatal [1][3]. It is primarily intended for logging errors to your monitoring service [1][2][3]. You should ensure you call console.error within this callback if you override it, as the default behavior performs this action [1][3]. 2. Promise Rejection: The renderToReadableStream function returns a Promise that resolves to a ReadableStream [1][4][3]. - If the initial "shell" of your application renders successfully, the Promise resolves [3][5]. - If a fatal error occurs while generating the shell—meaning React cannot produce a meaningful initial HTML response—the Promise will reject [3][5]. 3. Handling Errors: Because both onError and a catch block will fire if the shell fails to render, you should adopt a strategy that separates reporting from recovery [1][3]: - Use the onError callback for logging crash reports and observability [1][2][3]. - Wrap the renderToReadableStream call in a try/catch block to handle fatal shell rendering errors [1][3]. In the catch block, you should return a fallback HTML document or an alternative shell that allows the application to render on the client side [1][3][5]. Example Usage: async function handler(request) { try { const stream = await renderToReadableStream(, { onError(error) { console.error(error); // Log the error for observability [1][3] logServerCrashReport(error); } }); return new Response(stream, { headers: { 'content-type': 'text/html' } }); } catch (error) { // Handle fatal shell failure [1][3] return new Response('
Something went wrong
', { status: 500, headers: { 'content-type': 'text/html' } }); } }Citations:
- 1: https://react.dev/reference/react-dom/server/renderToReadableStream
- 2: https://facebook-react.mintlify.app/api/server/render-to-readable-stream
- 3: https://az.react.dev/reference/react-dom/server/renderToReadableStream
- 4: https://legacy.reactjs.org/docs/react-dom-server.html
- 5: Handling Root Errors in SSR Streaming Rendering reactwg/react-18#122
🌐 Web query:
React 17 renderToReadableStream does onError default console.error option documentation
💡 Result:
In React, the renderToReadableStream API includes an optional onError callback option. This callback is triggered whenever a server-side error occurs during rendering, whether the error is recoverable or non-recoverable [1][2]. Key details regarding the onError option: Default Behavior: By default, if no onError callback is provided, React automatically logs the error using console.error [1][2]. Overriding: If you choose to provide a custom onError callback to handle tasks like logging crash reports or tracking metrics, it is recommended to manually call console.error(error) within your implementation to maintain the standard error logging behavior [1][2]. Function Signature: The callback receives the error object, and in some definitions, an additional errorInfo object containing more context [3]. Usage for Status Codes: You can use the onError callback to track whether an error has occurred, which allows you to adjust the HTTP status code (e.g., to 500) before the initial shell is emitted to the client [1][2]. It is important to note that if an error occurs while generating the shell itself, both the onError callback and any surrounding try...catch block (wrapping the renderToReadableStream call) will fire. React documentation suggests using onError specifically for error reporting/logging and utilizing a try...catch block to send fallback HTML to the client [1][2].
Citations:
- 1: https://react.dev/reference/react-dom/server/renderToReadableStream
- 2: https://az.react.dev/reference/react-dom/server/renderToReadableStream
- 3: https://facebook-react.mintlify.app/api/server/render-to-readable-stream
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== package react-dom versions =="
for f in package.json examples/basic/package.json packages/cli/package.json packages/core/package.json; do
echo "--- $f"
jq -r '.dependencies."react-dom", .devDependencies."react-dom", .peerDependencies."react-dom"' "$f" 2>/dev/null || cat "$f"
done
echo "== createApp failure paths around handlers =="
sed -n '137,360p' packages/core/src/createApp.ts | cat -n
echo "== import/type usage for React DOM version =="
rg -n '"react-dom"|react-dom/server' packages/core/src createApp.ts render.ts package.json -C 2 || trueRepository: abdelkabirouadoukou/x
Length of output: 10216
🌐 Web query:
React server components renderToReadableStream without onError callback error silently node_modules react-dom/server onError
💡 Result:
The onError callback in renderToReadableStream is not intended to handle all types of failures, which can sometimes give the impression of silent errors if you rely solely on it [1][2]. Key aspects of error handling with renderToReadableStream: 1. onError vs. try...catch: The onError callback is designed to capture errors that occur during rendering (both recoverable errors within Suspense boundaries and some unrecoverable ones) [1][3]. However, if an error occurs while generating the initial shell, the promise returned by renderToReadableStream will reject [3]. You must wrap the renderToReadableStream call in a try...catch block to handle these shell-generation errors, as the onError callback alone may not be sufficient or triggered in time for fatal startup issues [2][3][4]. 2. Default Behavior: By default, the onError callback calls console.error [1]. If you override it, you must manually call console.error if you want to maintain the default logging behavior [1][3]. 3. Node.js Environment Context: Historically, renderToReadableStream was not fully supported or intended for use in Node.js, which led to confusion and potential issues with imports in older versions (pre-React 19.2) [5][6][7]. Ensure you are using a modern version of React (19.2+) that officially supports Web Streams in Node.js to avoid environment-specific bugs [6]. 4. Recommended Pattern: To ensure no errors are handled silently, use both a try...catch block and the onError callback [2][4]: - try...catch: Handles errors that prevent the stream promise from resolving (e.g., shell generation failure). - onError: Handles errors that occur during the streaming process (e.g., components inside Suspense boundaries failing). Example Implementation: async function handler(request) { let didError = false; try { const stream = await renderToReadableStream(, { onError(error) { didError = true; console.error(error); // Ensure logging } }); return new Response(stream, { status: didError? 500: 200, headers: { 'content-type': 'text/html' }, }); } catch (error) { // Handle fatal shell rendering errors return new Response('
Internal Server Error
', { status: 500, headers: { 'content-type': 'text/html' }, }); } }Citations:
- 1: https://react.dev/reference/react-dom/server/renderToReadableStream
- 2: https://az.react.dev/reference/react-dom/server/renderToReadableStream
- 3: https://uk.react.dev/reference/react-dom/server/renderToReadableStream
- 4: https://legacy.reactjs.org/docs/react-dom-server.html
- 5: Bug:
react-dom@18.0.0/serverdoesn't exportrenderToReadableStreamreact/react#24226 - 6: Bug: there is no renderToReadableStream function in react-dom@18.2.0 in Node.js react/react#26906
- 7: https://stackoverflow.com/questions/76411558/why-react-dom-server-18-2-0-does-not-contains-rendertoreadablestream
Add render error handling for renderStreamingPage.
renderStreamingPage passes no onError to renderToReadableStream, so component/Suspense rendering errors can be logged only by React’s default handler or surfacing as an errored stream; the route handler in createApp.ts also forwards stream failures directly to the response without a fallback or 500 handling. Pass an onError callback, and wrap the React streaming call in try/catch to return a safe error response for fatal shell rendering failures.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/core/src/render.ts` at line 100, Update renderStreamingPage around
renderToReadableStream to provide an onError callback for component and Suspense
rendering failures, and wrap the streaming call in try/catch so fatal shell
errors produce the established safe error response instead of propagating an
errored stream directly to createApp.ts.
| if (req.method !== "POST") { | ||
| return new Response("Method not allowed", { status: 405 }); | ||
| } | ||
|
|
||
| const args = (await req.json()) as unknown[]; | ||
| const result = await fn(...args); | ||
| return Response.json(result); | ||
| }; |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Unvalidated request body and late method check.
await req.json() (Line 78) throws on an empty/malformed body and fn(...args) throws TypeError when the payload isn't an array — both surface as unhandled 500s from attacker-controlled input. The method check also runs after the registry lookups, so a GET to an unknown action returns 404 while a known one returns 405; move it up.
🛡️ Proposed fix
- const routeActions = ACTION_ROUTES.get(routePath);
+ if (req.method !== "POST") {
+ return new Response("Method not allowed", { status: 405 });
+ }
+
+ const routeActions = ACTION_ROUTES.get(routePath);
if (!routeActions) return null;
const fn = routeActions.get(actionName);
if (!fn) return null;
- if (req.method !== "POST") {
- return new Response("Method not allowed", { status: 405 });
- }
-
- const args = (await req.json()) as unknown[];
- const result = await fn(...args);
- return Response.json(result);
+ let args: unknown;
+ try {
+ args = await req.json();
+ } catch {
+ return new Response("Invalid JSON body", { status: 400 });
+ }
+ if (!Array.isArray(args)) {
+ return new Response("Expected an array of arguments", { status: 400 });
+ }
+
+ const result = await fn(...args);
+ return Response.json(result ?? null);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/core/src/server-functions.ts` around lines 74 - 81, Update the
server-function request handler to validate the HTTP method before registry
lookups, returning 405 for every non-POST request. Safely parse the body and
require an array before invoking fn(...args); convert empty or malformed JSON
and non-array payloads into a controlled 4xx response instead of allowing
req.json() or the spread call to throw.
…entries directory and client entry generation
…ling with improved action management and error handling
…ports and type assertions
Summary by CodeRabbit