@eserstack/laroux-server 0.0.0-stage → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +410 -2
  3. package/dist/adapters/react/error-chunk.d.ts +11 -0
  4. package/dist/adapters/react/error-chunk.js +12 -0
  5. package/dist/adapters/react/html-shell.d.ts +15 -0
  6. package/dist/adapters/react/html-shell.js +109 -0
  7. package/dist/adapters/react/inline-rsc-emitter.d.ts +62 -0
  8. package/dist/adapters/react/inline-rsc-emitter.js +120 -0
  9. package/dist/adapters/react/mod.d.ts +30 -0
  10. package/dist/adapters/react/mod.js +36 -0
  11. package/dist/adapters/react/render-app.d.ts +46 -0
  12. package/dist/adapters/react/render-app.js +44 -0
  13. package/dist/adapters/react/renderer.d.ts +15 -0
  14. package/dist/adapters/react/renderer.js +86 -0
  15. package/dist/adapters/react/rsc-flight-renderer.d.ts +64 -0
  16. package/dist/adapters/react/rsc-flight-renderer.js +623 -0
  17. package/dist/adapters/react/rsc-handler.d.ts +47 -0
  18. package/dist/adapters/react/rsc-handler.js +114 -0
  19. package/dist/adapters/react/script-json.d.ts +12 -0
  20. package/dist/adapters/react/script-json.js +18 -0
  21. package/dist/adapters/react/ssr-renderer.d.ts +63 -0
  22. package/dist/adapters/react/ssr-renderer.js +625 -0
  23. package/dist/bin-main.d.ts +1 -0
  24. package/dist/bin-main.js +18 -0
  25. package/dist/cli.d.ts +26 -0
  26. package/dist/cli.js +48 -0
  27. package/dist/commands/build.d.ts +78 -0
  28. package/dist/commands/build.js +221 -0
  29. package/dist/commands/dev.d.ts +50 -0
  30. package/dist/commands/dev.js +133 -0
  31. package/dist/commands/init.d.ts +29 -0
  32. package/dist/commands/init.js +228 -0
  33. package/dist/commands/serve.d.ts +47 -0
  34. package/dist/commands/serve.js +124 -0
  35. package/dist/config/load-config.d.ts +14 -0
  36. package/dist/config/load-config.js +67 -0
  37. package/dist/domain/action-registry.d.ts +83 -0
  38. package/dist/domain/action-registry.js +124 -0
  39. package/dist/domain/build-module.d.ts +30 -0
  40. package/dist/domain/build-module.js +50 -0
  41. package/dist/domain/hmr-manager.d.ts +51 -0
  42. package/dist/domain/hmr-manager.js +90 -0
  43. package/dist/domain/html-shell.d.ts +56 -0
  44. package/dist/domain/html-shell.js +15 -0
  45. package/dist/domain/middleware-dispatcher.d.ts +42 -0
  46. package/dist/domain/middleware-dispatcher.js +150 -0
  47. package/dist/domain/rebuild-handler.d.ts +52 -0
  48. package/dist/domain/rebuild-handler.js +52 -0
  49. package/dist/domain/renderer.d.ts +62 -0
  50. package/dist/domain/renderer.js +15 -0
  51. package/dist/domain/route-dispatcher.d.ts +40 -0
  52. package/dist/domain/route-dispatcher.js +134 -0
  53. package/dist/domain/server-modules.d.ts +65 -0
  54. package/dist/domain/server-modules.js +208 -0
  55. package/dist/main.d.ts +40 -0
  56. package/dist/main.js +256 -0
  57. package/dist/module.d.ts +24 -0
  58. package/dist/module.js +140 -0
  59. package/dist/options.d.ts +53 -0
  60. package/dist/options.js +14 -0
  61. package/dist/package.json +98 -0
  62. package/dist/proxy/types.d.ts +19 -0
  63. package/dist/proxy/types.js +3 -0
  64. package/dist/runtime/action-guard.d.ts +49 -0
  65. package/dist/runtime/action-guard.js +115 -0
  66. package/dist/runtime/html-shell.d.ts +66 -0
  67. package/dist/runtime/html-shell.js +246 -0
  68. package/dist/runtime/media-types.d.ts +13 -0
  69. package/dist/runtime/media-types.js +83 -0
  70. package/dist/runtime/path-containment.d.ts +11 -0
  71. package/dist/runtime/path-containment.js +27 -0
  72. package/dist/runtime/seo/generate-meta.d.ts +16 -0
  73. package/dist/runtime/seo/generate-meta.js +121 -0
  74. package/dist/runtime/seo/index.d.ts +5 -0
  75. package/dist/runtime/seo/index.js +5 -0
  76. package/dist/runtime/seo/types.d.ts +25 -0
  77. package/dist/runtime/seo/types.js +5 -0
  78. package/dist/runtime/server.d.ts +58 -0
  79. package/dist/runtime/server.js +699 -0
  80. package/package.json +81 -3
@@ -0,0 +1,699 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * HTTP Server for React Server Components
4
+ * Handles routing for HTML, RSC payloads, static assets, and Server Actions
5
+ */
6
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
7
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
8
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
9
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
10
+ });
11
+ }
12
+ return path;
13
+ };
14
+ import * as scriptJson from "../adapters/react/script-json.js";
15
+ import * as logging from "@eserstack/logging";
16
+ import * as react from "../adapters/react/mod.js";
17
+ import * as htmlShell from "./html-shell.js";
18
+ import * as crossRuntime from "@eserstack/standards/cross-runtime";
19
+ import * as pathContainment from "./path-containment.js";
20
+ import * as mediaTypes from "./media-types.js";
21
+ import * as actionGuard from "./action-guard.js";
22
+ import * as http from "@eserstack/http";
23
+ import * as buildModule from "../domain/build-module.js";
24
+ // Loggers
25
+ const serverLogger = logging.logger.getLogger(["laroux-server", "server"]);
26
+ const rscLogger = logging.logger.getLogger(["laroux-server", "rsc"]);
27
+ /**
28
+ * Create a streaming Response for streaming-optimal mode
29
+ */
30
+ function createStreamingOptimalResponse(options) {
31
+ const { element, moduleMap, shellOptions } = options;
32
+ const encoder = new TextEncoder();
33
+ const { readable, writable } = new TransformStream();
34
+ const writer = writable.getWriter();
35
+ (async () => {
36
+ try {
37
+ const shellStart = htmlShell.createStreamingHtmlShellStart(shellOptions);
38
+ await writer.write(encoder.encode(shellStart));
39
+ const ssrResult = await react.renderSSR(element, moduleMap, {
40
+ streamMode: "streaming-classic",
41
+ });
42
+ await writer.write(encoder.encode(ssrResult.html));
43
+ const bootstrapScript = react.generateInlineBootstrapScript();
44
+ await writer.write(encoder.encode(bootstrapScript));
45
+ const syncChunks = ssrResult.rscPayload.filter((chunk) => {
46
+ if (chunk.value &&
47
+ typeof chunk.value === "object" &&
48
+ chunk.value["__rsc_pending"]) {
49
+ return false;
50
+ }
51
+ return true;
52
+ });
53
+ if (syncChunks.length > 0) {
54
+ serverLogger.debug(`Embedding ${syncChunks.length} sync RSC chunks inline`);
55
+ const inlinePayload = `<script id="__RSC_PAYLOAD__" type="application/json">${scriptJson.escapeJsonForScript(JSON.stringify(syncChunks))}</script>\n`;
56
+ await writer.write(encoder.encode(inlinePayload));
57
+ }
58
+ const manifestScript = shellOptions.chunkManifest
59
+ ? `<script>globalThis.__CHUNK_MANIFEST__ = ${JSON.stringify(shellOptions.chunkManifest)};</script>\n`
60
+ : "";
61
+ await writer.write(encoder.encode(manifestScript));
62
+ const cacheBuster = shellOptions.chunkManifest?.buildId
63
+ ? `?v=${shellOptions.chunkManifest.buildId}`
64
+ : `?v=${Date.now()}`;
65
+ const clientScript = `<script type="module" src="${shellOptions.entrypoint ?? "/client.js"}${cacheBuster}"></script>\n`;
66
+ await writer.write(encoder.encode(clientScript));
67
+ const shellEnd = htmlShell.createStreamingHtmlShellEnd(shellOptions);
68
+ await writer.write(encoder.encode(shellEnd));
69
+ await writer.close();
70
+ }
71
+ catch (error) {
72
+ serverLogger
73
+ .with({ error })
74
+ .error("stream the page in streaming-optimal mode; aborting the response");
75
+ try {
76
+ await writer.abort(error);
77
+ }
78
+ catch {
79
+ // Ignore abort errors
80
+ }
81
+ }
82
+ })();
83
+ return new Response(readable, {
84
+ headers: {
85
+ "Content-Type": "text/html; charset=utf-8",
86
+ "Transfer-Encoding": "chunked",
87
+ },
88
+ });
89
+ }
90
+ // Constants
91
+ /** A JSON error response with the given status. */
92
+ function jsonResponse(body, status) {
93
+ return new Response(JSON.stringify(body), {
94
+ status,
95
+ headers: { "Content-Type": "application/json" },
96
+ });
97
+ }
98
+ const CACHE_CONTROL_STATIC = "public, no-cache, must-revalidate";
99
+ const CACHE_CONTROL_DYNAMIC = "no-cache, no-store, must-revalidate";
100
+ const SECURITY_HEADERS = {
101
+ "X-Frame-Options": "DENY",
102
+ "X-Content-Type-Options": "nosniff",
103
+ "X-XSS-Protection": "1; mode=block",
104
+ "Referrer-Policy": "strict-origin-when-cross-origin",
105
+ "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
106
+ };
107
+ function withSecurityHeaders(response, additionalHeaders) {
108
+ const headers = new Headers(response.headers);
109
+ for (const [key, value] of Object.entries(SECURITY_HEADERS)) {
110
+ if (!headers.has(key)) {
111
+ headers.set(key, value);
112
+ }
113
+ }
114
+ if (additionalHeaders) {
115
+ for (const [key, value] of Object.entries(additionalHeaders)) {
116
+ headers.set(key, value);
117
+ }
118
+ }
119
+ return new Response(response.body, {
120
+ status: response.status,
121
+ statusText: response.statusText,
122
+ headers,
123
+ });
124
+ }
125
+ /**
126
+ * Top-level entries of distDir that are never served: server/ holds the
127
+ * bundled server components, server actions and their manifests, and the
128
+ * others are build inputs that laroux-bundler writes (its VIRTUAL_SRC_DIR,
129
+ * BOOTSTRAP_COPY_DIR and transform manifest). Browser assets live in client/
130
+ * and at the top level, next to the copied public assets.
131
+ */
132
+ const INTERNAL_DIST_ENTRIES = new Set([
133
+ "server",
134
+ "_bundle_src",
135
+ "_laroux-react",
136
+ "_client-entry.tsx",
137
+ "transform-manifest.json",
138
+ ]);
139
+ /**
140
+ * Whether a resolved path inside distDir points into an internal entry. The
141
+ * name is compared in lower case and without trailing dots and spaces,
142
+ * because a case-insensitive file system (macOS, Windows) finds "SERVER" as
143
+ * "server", and Windows drops a trailing "." or " ".
144
+ */
145
+ function isInternalDistPath(distDir, filePath) {
146
+ const relativePath = crossRuntime.runtime.path.relative(crossRuntime.runtime.path.resolve(distDir), filePath);
147
+ const topLevel = relativePath.split(/[\\/]/)[0] ?? "";
148
+ return INTERNAL_DIST_ENTRIES.has(topLevel.toLowerCase().replace(/[. ]+$/, ""));
149
+ }
150
+ async function serveStatic(config, pathname) {
151
+ try {
152
+ const relativePath = pathname.replace(/^\/dist\//, "");
153
+ const filePath = pathContainment.resolveWithin(config.distDir, relativePath);
154
+ if (filePath === null) {
155
+ serverLogger.warn(`Path traversal attempt blocked: ${pathname}`);
156
+ return new Response("Forbidden", { status: 403 });
157
+ }
158
+ // Answered like a missing file, so the response does not confirm that
159
+ // server code exists at that path.
160
+ if (isInternalDistPath(config.distDir, filePath)) {
161
+ return null;
162
+ }
163
+ const fileInfo = await crossRuntime.runtime.fs.stat(filePath);
164
+ const lastModified = fileInfo.mtime?.toUTCString() ?? new Date().toUTCString();
165
+ const etag = `"${fileInfo.size}-${fileInfo.mtime?.getTime() ?? 0}"`;
166
+ const file = await crossRuntime.runtime.fs.readFile(filePath);
167
+ const ext = crossRuntime.runtime.path.extname(filePath);
168
+ const mimeType = mediaTypes.contentType(ext) ?? "application/octet-stream";
169
+ const headers = {
170
+ "Content-Type": mimeType,
171
+ "Cache-Control": CACHE_CONTROL_STATIC,
172
+ "Last-Modified": lastModified,
173
+ ETag: etag,
174
+ };
175
+ if (ext === ".js") {
176
+ const mapFilePath = `${filePath}.map`;
177
+ try {
178
+ await crossRuntime.runtime.fs.stat(mapFilePath);
179
+ const mapFileName = crossRuntime.runtime.path.basename(mapFilePath);
180
+ headers["SourceMap"] = mapFileName;
181
+ }
182
+ catch {
183
+ // No source map file exists
184
+ }
185
+ }
186
+ return new Response(file, { headers });
187
+ }
188
+ catch (error) {
189
+ if (error instanceof crossRuntime.NotFoundError ||
190
+ (error instanceof Error && error.name === "NotFoundError")) {
191
+ return null;
192
+ }
193
+ throw error;
194
+ }
195
+ }
196
+ async function servePublicAsset(config, pathname) {
197
+ try {
198
+ const relativePath = pathname.replace(/^\//, "");
199
+ const publicDir = crossRuntime.runtime.path.resolve(config.projectRoot, "public");
200
+ const filePath = pathContainment.resolveWithin(publicDir, relativePath);
201
+ if (filePath === null) {
202
+ serverLogger.warn(`Path traversal attempt blocked: ${pathname}`);
203
+ return new Response("Forbidden", { status: 403 });
204
+ }
205
+ const fileInfo = await crossRuntime.runtime.fs.stat(filePath);
206
+ const lastModified = fileInfo.mtime?.toUTCString() ?? new Date().toUTCString();
207
+ const etag = `"${fileInfo.size}-${fileInfo.mtime?.getTime() ?? 0}"`;
208
+ const file = await crossRuntime.runtime.fs.readFile(filePath);
209
+ const ext = crossRuntime.runtime.path.extname(filePath);
210
+ const mimeType = mediaTypes.contentType(ext) ?? "application/octet-stream";
211
+ return new Response(file, {
212
+ headers: {
213
+ "Content-Type": mimeType,
214
+ "Cache-Control": CACHE_CONTROL_STATIC,
215
+ "Last-Modified": lastModified,
216
+ ETag: etag,
217
+ },
218
+ });
219
+ }
220
+ catch (error) {
221
+ if (error instanceof crossRuntime.NotFoundError ||
222
+ (error instanceof Error && error.name === "NotFoundError")) {
223
+ return null;
224
+ }
225
+ throw error;
226
+ }
227
+ }
228
+ /**
229
+ * Create request handler with injected dependencies
230
+ */
231
+ export function createHandler(deps, options = {}) {
232
+ // The actions manifest of the build being served, read once per build id.
233
+ let actionManifest = null;
234
+ const getActionManifest = (serverDir, buildId) => {
235
+ if (actionManifest === null || actionManifest.buildId !== buildId) {
236
+ actionManifest = {
237
+ buildId,
238
+ manifest: actionGuard.readActionManifest(serverDir),
239
+ };
240
+ }
241
+ return actionManifest.manifest;
242
+ };
243
+ const rateLimiter = deps.rateLimitConfig !== false
244
+ ? // Key on the socket peer. Forwarded headers are believed only from a
245
+ // trusted proxy (loopback by default), so a direct client can neither
246
+ // exempt itself with a forged X-Forwarded-For nor share one bucket with
247
+ // every other direct client.
248
+ http.middlewares.rateLimiter.createRateLimiter({
249
+ trustProxy: true,
250
+ ...(deps.rateLimitConfig ?? {}),
251
+ })
252
+ : null;
253
+ if (rateLimiter !== null) {
254
+ if (options.signal?.aborted === true) {
255
+ rateLimiter.stop();
256
+ }
257
+ else {
258
+ options.signal?.addEventListener("abort", () => rateLimiter.stop(), {
259
+ once: true,
260
+ });
261
+ }
262
+ }
263
+ return async (req, info) => {
264
+ const url = new URL(req.url);
265
+ let { pathname } = url;
266
+ const { config, bundler, getApp, getBuildId, hmrManager, apiHandler, middlewareDispatcher, } = deps;
267
+ serverLogger.debug(`${req.method} ${pathname}`);
268
+ // The handshake response runtime.http.upgradeWebSocket returned. The Node
269
+ // adapter recognizes it by identity, so it is returned without a copy.
270
+ let upgradeResponse = null;
271
+ const processRequest = async () => {
272
+ // Route: /hmr -> WebSocket for HMR
273
+ if (pathname === "/hmr" && hmrManager) {
274
+ if (req.headers.get("upgrade") !== "websocket") {
275
+ return new Response("Expected WebSocket", { status: 426 });
276
+ }
277
+ const { socket, response } = crossRuntime.runtime.http.upgradeWebSocket(req);
278
+ hmrManager.handleConnection(socket);
279
+ upgradeResponse = response;
280
+ return response;
281
+ }
282
+ // Rate limiting check
283
+ if (rateLimiter) {
284
+ // Keyed on the socket peer from runtime.http, not on client headers.
285
+ const rateLimitResponse = rateLimiter.check(req, pathname, info?.remoteAddr ?? null);
286
+ if (rateLimitResponse) {
287
+ return withSecurityHeaders(rateLimitResponse);
288
+ }
289
+ }
290
+ // GET /rsc renders the page its pathname parameter names. The path is
291
+ // normalized through a URL, so "/x/../admin" is "/admin" both for the
292
+ // proxies and for the render.
293
+ let rscPagePathname = null;
294
+ if (pathname === "/rsc") {
295
+ const pageUrl = new URL(url.origin);
296
+ pageUrl.pathname = url.searchParams.get("pathname") ?? "/";
297
+ rscPagePathname = pageUrl.pathname;
298
+ }
299
+ // Run middleware
300
+ if (middlewareDispatcher) {
301
+ // For /rsc the chain runs for the requested page, as it does for that
302
+ // page's document request, so route-scoped proxies cover its payload.
303
+ // The pathname is set on a copy of the origin, never resolved against
304
+ // it: resolving "//evil.com/x" would take the host from the client.
305
+ let proxyRequest = req;
306
+ if (rscPagePathname !== null) {
307
+ const proxyUrl = new URL(url.origin);
308
+ proxyUrl.pathname = rscPagePathname;
309
+ proxyRequest = new Request(proxyUrl, req);
310
+ }
311
+ const { result, finalPathname } = await middlewareDispatcher.runProxies(proxyRequest, rscPagePathname ?? pathname);
312
+ if (result.type === "response") {
313
+ return result.response;
314
+ }
315
+ if (result.type === "redirect") {
316
+ return Response.redirect(result.url, result.status ?? 302);
317
+ }
318
+ if (rscPagePathname !== null) {
319
+ rscPagePathname = finalPathname;
320
+ }
321
+ else {
322
+ pathname = finalPathname;
323
+ }
324
+ }
325
+ // Route: File-based API routes
326
+ if (apiHandler) {
327
+ const apiResponse = await apiHandler.handleRequest(req, pathname);
328
+ if (apiResponse) {
329
+ return apiResponse;
330
+ }
331
+ }
332
+ // Route: / -> HTML shell (with optional SSR)
333
+ if (pathname === "/" || pathname === "/index.html") {
334
+ return await handlePageRequest(req, "/", deps);
335
+ }
336
+ // Route: /_rsc POST with RSC-Action header -> Server Action (React 19 native)
337
+ if (pathname === "/_rsc" && req.method === "POST") {
338
+ const actionId = req.headers.get("RSC-Action");
339
+ if (actionId) {
340
+ rscLogger.debug(`RSC Server Action invoked: ${actionId}`);
341
+ // Defense in depth against cross-site request forgery: a browser
342
+ // page of another origin cannot run an action.
343
+ if (!actionGuard.isSameOriginRequest(req)) {
344
+ await rscLogger
345
+ .with({ actionId })
346
+ .warn("run server action: refused a cross-site request; answered 403");
347
+ return jsonResponse({ error: "Cross-site action request" }, 403);
348
+ }
349
+ try {
350
+ // Parse action ID: "path/to/file#exportName"
351
+ const [modulePath, exportName] = actionId.split("#");
352
+ if (!modulePath || !exportName) {
353
+ return jsonResponse({ error: "Invalid action ID format" }, 400);
354
+ }
355
+ // Only modules the build lists in actions-manifest.json are
356
+ // action modules. The id comes from a request header, so it is
357
+ // checked against that list before any module is imported.
358
+ const serverDir = crossRuntime.runtime.path.resolve(config.distDir, "server");
359
+ const manifest = await getActionManifest(serverDir, getBuildId());
360
+ if (!actionGuard.isListedActionModule(manifest, modulePath)) {
361
+ // The id goes into a log attribute; the response does not
362
+ // echo it.
363
+ await rscLogger
364
+ .with({ actionId })
365
+ .warn("run server action: the module is not in the actions manifest; answered 404");
366
+ return jsonResponse({ error: "Action not found" }, 404);
367
+ }
368
+ // Actions are in dist/server/<modulePath>.js, and the resolved
369
+ // file must stay inside that directory: an id with ../ or an
370
+ // absolute path is rejected.
371
+ const actionModulePath = pathContainment.resolveWithin(serverDir, `${modulePath}.js`);
372
+ if (actionModulePath === null) {
373
+ rscLogger.warn(`RSC action path outside server dir: ${actionId}`);
374
+ return jsonResponse({ error: "Invalid action ID" }, 400);
375
+ }
376
+ // The body is read with a size limit before it is parsed.
377
+ let bodyBytes;
378
+ try {
379
+ bodyBytes = await actionGuard.readBoundedBody(req);
380
+ }
381
+ catch (error) {
382
+ if (error instanceof actionGuard.ActionBodyTooLargeError) {
383
+ return jsonResponse({
384
+ error: `Action request body is over the ${error.limitBytes}-byte limit`,
385
+ }, 413);
386
+ }
387
+ throw error;
388
+ }
389
+ // Parse args based on content type
390
+ const contentType = req.headers.get("Content-Type") ?? "";
391
+ let args;
392
+ if (contentType.includes("multipart/form-data")) {
393
+ // FormData - pass as first arg
394
+ args = [
395
+ await new Response(bodyBytes, {
396
+ headers: { "Content-Type": contentType },
397
+ }).formData(),
398
+ ];
399
+ }
400
+ else {
401
+ // JSON args: the client sends the argument list as an array. A
402
+ // body that is not JSON gets the same 400 as one that is not an
403
+ // array.
404
+ let body = null;
405
+ try {
406
+ body = JSON.parse(new TextDecoder().decode(bodyBytes));
407
+ }
408
+ catch {
409
+ body = null;
410
+ }
411
+ if (!Array.isArray(body)) {
412
+ return jsonResponse({
413
+ error: "Action arguments must be a JSON array or multipart form data",
414
+ }, 400);
415
+ }
416
+ args = body;
417
+ }
418
+ rscLogger.debug(`Loading action module: ${actionModulePath}`);
419
+ const actionModule = await import(__rewriteRelativeImportExtension(buildModule.toBuildModuleUrl(actionModulePath, getBuildId())));
420
+ // Only exports the build marked as React server references are
421
+ // actions; other exports of the module cannot be called.
422
+ const actionFn = actionModule[exportName];
423
+ if (!actionGuard.isServerAction(actionFn, actionId)) {
424
+ await rscLogger
425
+ .with({ actionId })
426
+ .warn("run server action: the module has no server action with this id; answered 404");
427
+ return jsonResponse({ error: "Action not found" }, 404);
428
+ }
429
+ // The module map is loaded before the action runs, so a bundle
430
+ // that cannot load fails the request before any side effect.
431
+ const bundle = await bundler.getBundle();
432
+ // Call the action
433
+ const result = await actionFn(...args);
434
+ rscLogger.debug(`Action ${actionId} completed successfully`);
435
+ // The result is encoded as RSC, so Dates, Maps, Sets, BigInts,
436
+ // undefined and React elements reach the client as themselves.
437
+ return react.streamToResponse(react.renderValueToReadableStream(result, bundle.moduleMap));
438
+ }
439
+ catch (error) {
440
+ // Handled here: logged once with the action id, and the client
441
+ // receives a fixed message.
442
+ await rscLogger
443
+ .with({ actionId, error })
444
+ .error("run server action: the request or the action failed; answered 500");
445
+ return jsonResponse({ error: "Server action failed" }, 500);
446
+ }
447
+ }
448
+ }
449
+ // Route: /rsc -> React Server Components payload
450
+ if (pathname === "/rsc") {
451
+ rscLogger.debug("Rendering RSC payload...");
452
+ const bundle = await bundler.getBundle();
453
+ const requestPathname = rscPagePathname ?? "/";
454
+ const { Layout, Page, params } = await getApp(requestPathname);
455
+ // Request data travels with this render only, as the request prop
456
+ // of the page and the layout. The client forwards the page URL's
457
+ // locale parameter to /rsc.
458
+ return await react.renderRSCResponse(config, react.renderApp(Layout, Page, {
459
+ pathname: requestPathname,
460
+ params,
461
+ requestContext: {
462
+ cookieHeader: req.headers.get("cookie"),
463
+ host: req.headers.get("host"),
464
+ localeParam: url.searchParams.get("locale"),
465
+ },
466
+ }), bundle.moduleMap);
467
+ }
468
+ // Route: Runtime bundle endpoint
469
+ if (pathname === config.internal.runtimeBundleEndpoint) {
470
+ const bundle = await bundler.getBundle();
471
+ if (bundle.clientCode !== null) {
472
+ serverLogger.debug("Serving current bundle...");
473
+ return new Response(bundle.clientCode, {
474
+ headers: {
475
+ "Content-Type": "application/javascript; charset=utf-8",
476
+ "Cache-Control": CACHE_CONTROL_DYNAMIC,
477
+ },
478
+ });
479
+ }
480
+ return new Response("Not Found", { status: 404 });
481
+ }
482
+ // Route: Runtime module map endpoint
483
+ if (pathname === config.internal.runtimeModuleMapEndpoint) {
484
+ const bundle = await bundler.getBundle();
485
+ if (bundle.clientCode !== null) {
486
+ return new Response(JSON.stringify(bundle.moduleMap, null, 2), {
487
+ headers: {
488
+ "Content-Type": "application/json; charset=utf-8",
489
+ "Cache-Control": CACHE_CONTROL_DYNAMIC,
490
+ },
491
+ });
492
+ }
493
+ return new Response("Not Found", { status: 404 });
494
+ }
495
+ // Note: Old /action endpoint removed - use /_rsc with RSC-Action header instead
496
+ // This is React 19's native server actions mechanism
497
+ // Route: /dist/* -> Static assets
498
+ if (pathname.startsWith("/dist/")) {
499
+ const staticResponse = await serveStatic(config, pathname);
500
+ if (staticResponse) {
501
+ return staticResponse;
502
+ }
503
+ }
504
+ // Route: Clean URLs for client assets
505
+ if (pathname.startsWith("/fonts/") ||
506
+ pathname.startsWith("/chunk-") ||
507
+ pathname.startsWith("/_bundle_src/") ||
508
+ pathname === "/styles.css" ||
509
+ pathname === "/styles.deferred.css" ||
510
+ pathname === "/client.js" ||
511
+ pathname === "/client.js.map" ||
512
+ pathname.endsWith(".js.map")) {
513
+ const clientAssetPath = `/dist/client${pathname}`;
514
+ const staticResponse = await serveStatic(config, clientAssetPath);
515
+ if (staticResponse) {
516
+ return staticResponse;
517
+ }
518
+ }
519
+ // Route: Public assets
520
+ if (pathname !== "/" &&
521
+ !pathname.startsWith("/dist/") &&
522
+ !pathname.startsWith("/rsc") &&
523
+ !pathname.startsWith("/action")) {
524
+ const distResponse = await serveStatic(config, `/dist${pathname}`);
525
+ if (distResponse) {
526
+ return distResponse;
527
+ }
528
+ const publicResponse = await servePublicAsset(config, pathname);
529
+ if (publicResponse) {
530
+ return publicResponse;
531
+ }
532
+ }
533
+ // Route: /health -> Health check
534
+ if (pathname === "/health") {
535
+ return new Response(JSON.stringify({ status: "ok", timestamp: Date.now() }), {
536
+ headers: { "Content-Type": "application/json" },
537
+ });
538
+ }
539
+ // Fallback: Serve HTML shell for all other routes
540
+ return await handlePageRequest(req, pathname, deps);
541
+ };
542
+ try {
543
+ const response = await processRequest();
544
+ if (response === upgradeResponse) {
545
+ return response;
546
+ }
547
+ return withSecurityHeaders(response);
548
+ }
549
+ catch (error) {
550
+ serverLogger
551
+ .with({ error, method: req.method, pathname })
552
+ .error("handle request; answering 500");
553
+ // Don't expose error details to client - only log server-side
554
+ return withSecurityHeaders(new Response(JSON.stringify({
555
+ error: "Internal Server Error",
556
+ }), {
557
+ status: 500,
558
+ headers: { "Content-Type": "application/json" },
559
+ }));
560
+ }
561
+ };
562
+ }
563
+ /**
564
+ * Handle page request with SSR
565
+ */
566
+ async function handlePageRequest(req, pathname, deps) {
567
+ const { config, bundler, getApp } = deps;
568
+ const bundle = await bundler.getBundle();
569
+ // The manifest is read from disk for each request, so its build id is the
570
+ // current one, also after a dev rebuild.
571
+ const manifest = bundle.chunkManifest;
572
+ manifest.logLevel = config.logLevel;
573
+ // Load optimized font data
574
+ let fontPreloads;
575
+ let fontCSS;
576
+ try {
577
+ const fontPreloadsPath = crossRuntime.runtime.path.resolve(config.distDir, "client", "font-preloads.json");
578
+ const fontCssPath = crossRuntime.runtime.path.resolve(config.distDir, "client", "fonts.css");
579
+ const fontPreloadsContent = await crossRuntime.runtime.fs.readTextFile(fontPreloadsPath);
580
+ fontPreloads = JSON.parse(fontPreloadsContent);
581
+ fontCSS = await crossRuntime.runtime.fs.readTextFile(fontCssPath);
582
+ }
583
+ catch {
584
+ serverLogger.debug("Font optimization data not found, using fallback");
585
+ }
586
+ // Load critical CSS
587
+ let criticalPageCSS;
588
+ let criticalUniversalCSS;
589
+ let deferredCSSPath;
590
+ try {
591
+ const criticalCssPath = crossRuntime.runtime.path.resolve(config.distDir, "client", "styles.critical.css");
592
+ criticalPageCSS =
593
+ await crossRuntime.runtime.fs.readTextFile(criticalCssPath);
594
+ deferredCSSPath = "/styles.deferred.css";
595
+ }
596
+ catch {
597
+ serverLogger.debug("Critical page CSS not found, using defaults");
598
+ }
599
+ try {
600
+ const universalCssPath = crossRuntime.runtime.path.resolve(config.distDir, "client", "styles.universal.css");
601
+ criticalUniversalCSS =
602
+ await crossRuntime.runtime.fs.readTextFile(universalCssPath);
603
+ }
604
+ catch {
605
+ serverLogger.debug("Critical universal CSS not found, using defaults");
606
+ }
607
+ // Check if SSR is enabled
608
+ const ssrMode = config.ssr?.mode ?? "disabled";
609
+ const ssrEnabled = ssrMode !== "disabled" &&
610
+ (ssrMode === "always" ||
611
+ (ssrMode === "production-only" && !config.mode.isWatch));
612
+ let ssrContent;
613
+ let rscPayload;
614
+ let clientModules;
615
+ if (ssrEnabled) {
616
+ try {
617
+ serverLogger.debug(`SSR rendering page: ${pathname}`);
618
+ const { Layout, Page, params } = await getApp(pathname);
619
+ // Request data travels with this render only, as the request prop of
620
+ // the page and the layout.
621
+ const rscComponent = react.renderApp(Layout, Page, {
622
+ pathname,
623
+ params,
624
+ requestContext: {
625
+ cookieHeader: req.headers.get("cookie"),
626
+ host: req.headers.get("host"),
627
+ localeParam: new URL(req.url).searchParams.get("locale"),
628
+ },
629
+ });
630
+ const streamMode = config.ssr?.streamMode ?? "streaming-optimal";
631
+ if (streamMode === "streaming-optimal") {
632
+ serverLogger.debug(`Using streaming-optimal mode for SSR: ${pathname}`);
633
+ return createStreamingOptimalResponse({
634
+ element: rscComponent,
635
+ moduleMap: bundle.moduleMap,
636
+ shellOptions: {
637
+ chunkManifest: manifest,
638
+ entrypoint: bundle.entrypoint,
639
+ fontPreloads,
640
+ fontCSS,
641
+ criticalPageCSS,
642
+ criticalUniversalCSS,
643
+ deferredCSSPath,
644
+ clientModules: [],
645
+ },
646
+ });
647
+ }
648
+ const ssrResult = await react.renderSSR(rscComponent, bundle.moduleMap, {
649
+ streamMode,
650
+ });
651
+ ssrContent = ssrResult.html;
652
+ if (streamMode === "await-all") {
653
+ rscPayload = react.serializeRSCPayload(ssrResult.rscPayload);
654
+ }
655
+ clientModules = ssrResult.clientModules;
656
+ serverLogger.debug(`SSR complete for ${pathname}: ${ssrContent.length} bytes HTML`);
657
+ }
658
+ catch (error) {
659
+ serverLogger
660
+ .with({ error })
661
+ .error(`render SSR for ${pathname}; falling back to CSR`);
662
+ ssrContent = undefined;
663
+ rscPayload = undefined;
664
+ clientModules = undefined;
665
+ }
666
+ }
667
+ const html = htmlShell.createHtmlShell({
668
+ chunkManifest: manifest,
669
+ entrypoint: bundle.entrypoint,
670
+ fontPreloads,
671
+ fontCSS,
672
+ criticalPageCSS,
673
+ criticalUniversalCSS,
674
+ deferredCSSPath,
675
+ ssrContent,
676
+ rscPayload,
677
+ clientModules,
678
+ });
679
+ return new Response(html, {
680
+ headers: {
681
+ "Content-Type": "text/html; charset=utf-8",
682
+ },
683
+ });
684
+ }
685
+ /**
686
+ * Start the HTTP server on `config.server.host` and `config.server.port`.
687
+ * The host is passed explicitly because runtime.http binds to 127.0.0.1 when
688
+ * none is given. Resolves once the server listens.
689
+ */
690
+ export async function startHTTPServer(deps, options = {}) {
691
+ const { config } = deps;
692
+ const handler = createHandler(deps, { signal: options.signal });
693
+ return await crossRuntime.runtime.http.serve({
694
+ port: config.server.port,
695
+ hostname: config.server.host,
696
+ onListen: options.onListen,
697
+ signal: options.signal,
698
+ }, handler);
699
+ }