@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,625 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Server-Side Rendering (SSR) Renderer
4
+ *
5
+ * This module renders React Server Components to HTML for initial page load.
6
+ * It generates both:
7
+ * 1. HTML markup for immediate display
8
+ * 2. RSC payload for client hydration
9
+ *
10
+ * Key concepts:
11
+ * - Server components are rendered to HTML directly
12
+ * - Client components render as placeholders with data attributes
13
+ * - RSC payload is embedded in the HTML for hydration without refetch
14
+ */
15
+ import * as errorChunk from "./error-chunk.js";
16
+ import * as scriptJson from "./script-json.js";
17
+ import * as React from "react";
18
+ import * as ReactDOMServer from "react-dom/server";
19
+ import * as protocol from "@eserstack/laroux-react/protocol";
20
+ import * as logging from "@eserstack/logging";
21
+ const ssrLogger = logging.logger.getLogger(["laroux-server", "react", "ssr"]);
22
+ /**
23
+ * Ensure all elements in an array have keys.
24
+ * Uses cloneElement to add explicit keys only to elements that need them.
25
+ *
26
+ * Performance optimizations:
27
+ * 1. Fast-path check: if all elements have keys, return original array (no allocation)
28
+ * 2. Early termination: stops checking once we find a keyless element
29
+ *
30
+ * Why we need this:
31
+ * When preprocessing creates new elements with createElement(), original keys
32
+ * are lost because React stores keys on the element object, not in props.
33
+ * Unlike react-server-dom-webpack which serializes to JSON and reconstructs
34
+ * elements with proper keys on the client, we need actual React elements for
35
+ * renderToReadableStream - hence we must ensure keys exist before rendering.
36
+ */
37
+ function ensureArrayKeys(arr) {
38
+ // Fast-path: check if any valid React element lacks a key
39
+ let needsProcessing = false;
40
+ for (let i = 0; i < arr.length; i++) {
41
+ const item = arr[i];
42
+ // Use isReactElement from protocol.ts for element type check
43
+ if (protocol.isReactElement(item)) {
44
+ // Check if key is missing
45
+ if (item.key === null || item.key === undefined || item.key === "") {
46
+ needsProcessing = true;
47
+ break; // Early termination - one keyless element is enough
48
+ }
49
+ }
50
+ }
51
+ // Fast-path: no changes needed, return original array (zero allocation)
52
+ if (!needsProcessing) {
53
+ return arr;
54
+ }
55
+ // Slow-path: create new array with keys added where needed
56
+ const result = new Array(arr.length);
57
+ for (let i = 0; i < arr.length; i++) {
58
+ const item = arr[i];
59
+ // Use isReactElement from protocol.ts for element type check
60
+ if (protocol.isReactElement(item)) {
61
+ // Only clone if key is missing
62
+ if (item.key === null || item.key === undefined || item.key === "") {
63
+ result[i] = React.cloneElement(item, { key: `.${i}` });
64
+ continue;
65
+ }
66
+ }
67
+ result[i] = item;
68
+ }
69
+ return result;
70
+ }
71
+ /**
72
+ * Name of a function component for logs and data attributes; anonymous
73
+ * functions have an empty name, so they get the fallback.
74
+ */
75
+ function componentName(type, fallback) {
76
+ const name = type.name;
77
+ return name !== undefined && name !== "" ? name : fallback;
78
+ }
79
+ /**
80
+ * Describe an element type for debug logs
81
+ */
82
+ function describeType(type) {
83
+ if (typeof type === "function")
84
+ return componentName(type, "anonymous");
85
+ if (typeof type === "string")
86
+ return type;
87
+ if (typeof type === "symbol")
88
+ return type.toString();
89
+ return "unknown";
90
+ }
91
+ /**
92
+ * Create a placeholder element for client components
93
+ * The placeholder includes data attributes for hydration
94
+ *
95
+ * @param moduleId - The module path (e.g., "./src/app/counter.tsx")
96
+ * @param exportName - The export name (e.g., "Counter" or "default")
97
+ * @param props - Component props (serializable ones only)
98
+ * @param children - Server-rendered children (if any)
99
+ * @param elementChunkId - RSC chunk ID for this element (for proper hydration)
100
+ */
101
+ function createClientPlaceholder(moduleId, exportName, props, children, elementChunkId) {
102
+ // Serialize props (excluding children and functions)
103
+ const serializableProps = {};
104
+ for (const [key, value] of Object.entries(props)) {
105
+ if (key === "children" || typeof value === "function")
106
+ continue;
107
+ serializableProps[key] = value;
108
+ }
109
+ // Ensure array children have keys
110
+ const safeChildren = Array.isArray(children)
111
+ ? ensureArrayKeys(children)
112
+ : children;
113
+ // Create a div placeholder with data attributes
114
+ // data-chunk-id links to RSC payload for proper prop/children resolution
115
+ return React.createElement("div", {
116
+ "data-client-component": moduleId,
117
+ "data-export-name": exportName,
118
+ "data-props": JSON.stringify(serializableProps),
119
+ "data-chunk-id": String(elementChunkId),
120
+ style: { display: "contents" }, // Don't affect layout
121
+ }, safeChildren);
122
+ }
123
+ /**
124
+ * Pre-process the React tree to handle client components
125
+ * Returns a new tree with client components replaced by placeholders
126
+ * and collects RSC chunks for the payload
127
+ */
128
+ async function preprocessTree(element, context) {
129
+ // Null/undefined
130
+ if (element === null || element === undefined) {
131
+ const id = context.nextId++;
132
+ context.chunks.push({ type: "J", id, value: null });
133
+ return { processedElement: null, chunkId: id };
134
+ }
135
+ // Primitives (string, number, boolean). The chunk escapes strings that
136
+ // start with "$", which the client would otherwise read as references.
137
+ if (typeof element !== "object") {
138
+ const id = context.nextId++;
139
+ context.chunks.push({
140
+ type: "J",
141
+ id,
142
+ value: protocol.encodeJsonValue(element) ?? null,
143
+ });
144
+ return { processedElement: element, chunkId: id };
145
+ }
146
+ // Arrays - use Children.toArray to ensure all elements have keys
147
+ if (Array.isArray(element)) {
148
+ const id = context.nextId++;
149
+ const processedItems = await Promise.all(element.map((item) => preprocessTree(item, context)));
150
+ // Use $-prefixed references for RSC protocol
151
+ const chunkRefs = processedItems.map((r) => `$${r.chunkId}`);
152
+ context.chunks.push({ type: "J", id, value: chunkRefs });
153
+ const rawElements = processedItems.map((r) => r.processedElement);
154
+ // Ensure all elements have keys
155
+ return {
156
+ processedElement: ensureArrayKeys(rawElements),
157
+ chunkId: id,
158
+ };
159
+ }
160
+ // Client component reference (the type itself is a reference)
161
+ if (protocol.isClientReference(element)) {
162
+ const id = context.nextId++;
163
+ const moduleId = element.$$id;
164
+ const exportName = element.name ?? "default";
165
+ // Look up in bundler config
166
+ const moduleRef = context.bundlerConfig[moduleId] ?? {
167
+ id: moduleId,
168
+ chunks: [],
169
+ name: exportName,
170
+ };
171
+ context.chunks.push({ type: "M", id, value: moduleRef });
172
+ context.clientModules.add(moduleId);
173
+ // Return a simple placeholder reference
174
+ return { processedElement: null, chunkId: id };
175
+ }
176
+ // React element (handle both standard and transitional symbols for React 19 RSC)
177
+ if (protocol.isReactElement(element)) {
178
+ // Extract key from element - React stores it on the element object, not in props
179
+ const { type, props, key: originalKey } = element;
180
+ // Debug: log what type we're processing
181
+ ssrLogger.debug(`Processing React element with type: ${typeof type}, name: ${describeType(type)}`);
182
+ // Client component element (type is a client reference)
183
+ if (protocol.isClientReference(type)) {
184
+ // Pre-allocate IDs so we can pass elementId to placeholder
185
+ const moduleChunkId = context.nextId++;
186
+ const propsChunkId = context.nextId++;
187
+ const elementChunkId = context.nextId++;
188
+ const moduleId = type.$$id;
189
+ const exportName = type.name ?? "default";
190
+ // Look up in bundler config
191
+ const moduleRef = context.bundlerConfig[moduleId] ?? {
192
+ id: moduleId,
193
+ chunks: [],
194
+ name: exportName,
195
+ };
196
+ context.chunks.push({ type: "M", id: moduleChunkId, value: moduleRef });
197
+ context.clientModules.add(moduleId);
198
+ // Process children (if any) - they might be server components
199
+ let processedChildren = null;
200
+ let childrenChunkId;
201
+ if (props?.children) {
202
+ const childResult = await preprocessTree(props.children, context);
203
+ processedChildren = childResult.processedElement;
204
+ childrenChunkId = childResult.chunkId;
205
+ }
206
+ // Create placeholder with processed children and element chunk ID
207
+ // The chunk ID allows client to look up this element in RSC payload
208
+ const placeholder = createClientPlaceholder(moduleId, exportName, props ?? {}, processedChildren, elementChunkId);
209
+ // Create RSC props chunk for hydration
210
+ const serializedProps = {};
211
+ if (props !== undefined) {
212
+ for (const [key, value] of Object.entries(props)) {
213
+ if (typeof value === "function")
214
+ continue;
215
+ if (key === "children" && childrenChunkId !== undefined) {
216
+ // Reference the processed children chunk
217
+ serializedProps[key] = `$${childrenChunkId}`;
218
+ }
219
+ else if (typeof value === "object" && value !== null) {
220
+ // Props are processed in order: preprocessTree takes chunk ids from
221
+ // the shared context counter, so the order fixes the ids.
222
+ // oxlint-disable-next-line no-await-in-loop
223
+ const valueResult = await preprocessTree(value, context);
224
+ serializedProps[key] = `$${valueResult.chunkId}`;
225
+ }
226
+ else {
227
+ serializedProps[key] = protocol.encodeJsonValue(value);
228
+ }
229
+ }
230
+ }
231
+ context.chunks.push({
232
+ type: "J",
233
+ id: propsChunkId,
234
+ value: serializedProps,
235
+ });
236
+ // Element chunk referencing the module and props
237
+ context.chunks.push({
238
+ type: "J",
239
+ id: elementChunkId,
240
+ value: {
241
+ $$typeof: "react.element",
242
+ type: `$M${moduleChunkId}`,
243
+ props: `$${propsChunkId}`,
244
+ },
245
+ });
246
+ return { processedElement: placeholder, chunkId: elementChunkId };
247
+ }
248
+ // ForwardRef component - unwrap and call render function
249
+ if (type !== null &&
250
+ typeof type === "object" &&
251
+ type.$$typeof === Symbol.for("react.forward_ref") &&
252
+ typeof type.render === "function") {
253
+ try {
254
+ ssrLogger.debug("Processing ForwardRef component");
255
+ const result = type.render(props, null);
256
+ return await preprocessTree(result, context);
257
+ }
258
+ catch (error) {
259
+ ssrLogger
260
+ .with({ error })
261
+ .error("render SSR: a forwardRef component threw; sent an error chunk in its place");
262
+ const errorId = context.nextId++;
263
+ context.chunks.push({
264
+ type: "E",
265
+ id: errorId,
266
+ value: errorChunk.toClientErrorValue(error),
267
+ });
268
+ return { processedElement: null, chunkId: errorId };
269
+ }
270
+ }
271
+ // Memo component - unwrap and render inner type
272
+ if (type !== null &&
273
+ typeof type === "object" &&
274
+ type.$$typeof === Symbol.for("react.memo")) {
275
+ ssrLogger.debug("Processing Memo component");
276
+ const innerType = type.type;
277
+ const innerElement = { ...element, type: innerType };
278
+ return await preprocessTree(innerElement, context);
279
+ }
280
+ // Server component (function type)
281
+ if (typeof type === "function") {
282
+ try {
283
+ ssrLogger.debug(`Executing server component: ${componentName(type, "anonymous")}`);
284
+ // Execute the server component
285
+ const result = type(props);
286
+ // Handle async components
287
+ if (result instanceof Promise) {
288
+ // In streaming mode, don't await AND don't track the promise
289
+ // This prevents duplicate execution - async components only run via /rsc
290
+ if (context.streamMode === "streaming-classic") {
291
+ ssrLogger.debug(`Async server component ${componentName(type, "anonymous")} skipped in SSR (streaming-classic mode) - client will fetch via /rsc`);
292
+ const id = context.nextId++;
293
+ // Return a placeholder that will be hydrated by /rsc endpoint
294
+ // Use the pre-processed Suspense fallback directly (no await needed)
295
+ const fallbackContent = context.suspenseFallback ?? "Loading...";
296
+ // Ensure array children have keys
297
+ const safeFallback = Array.isArray(fallbackContent)
298
+ ? ensureArrayKeys(fallbackContent)
299
+ : fallbackContent;
300
+ const placeholder = React.createElement("div", {
301
+ "data-async-boundary": id,
302
+ "data-component": componentName(type, "async"),
303
+ }, safeFallback);
304
+ // DON'T track the promise - prevents execution and allows GC
305
+ // The async function was already called above (type(props)), but by
306
+ // not awaiting or tracking it, we let it run once in SSR and let GC handle it.
307
+ // The client will execute it again via /rsc for the actual content.
308
+ // Mark chunk as pending - client knows to get this from /rsc stream
309
+ // This marker tells the client: "this chunk is async, wait for /rsc"
310
+ context.chunks.push({
311
+ type: "J",
312
+ id,
313
+ value: { __rsc_pending: true }, // Marker for pending async
314
+ });
315
+ return { processedElement: placeholder, chunkId: id };
316
+ }
317
+ // In await-all mode, wait for the async component
318
+ ssrLogger.debug("Awaiting async server component...");
319
+ const resolved = await result;
320
+ // Validate resolved result
321
+ if (resolved === undefined) {
322
+ ssrLogger.warn(`Async server component ${componentName(type, "anonymous")} returned undefined`);
323
+ }
324
+ return await preprocessTree(resolved, context);
325
+ }
326
+ // Validate sync result
327
+ if (result === undefined) {
328
+ ssrLogger.warn(`Server component ${componentName(type, "anonymous")} returned undefined`);
329
+ }
330
+ // Recursively process the result
331
+ return await preprocessTree(result, context);
332
+ }
333
+ catch (error) {
334
+ ssrLogger
335
+ .with({ error })
336
+ .error(`render SSR: server component ${componentName(type, "anonymous")} threw; sent an error chunk in its place`);
337
+ const errorId = context.nextId++;
338
+ context.chunks.push({
339
+ type: "E",
340
+ id: errorId,
341
+ value: errorChunk.toClientErrorValue(error),
342
+ });
343
+ return { processedElement: null, chunkId: errorId };
344
+ }
345
+ }
346
+ // Built-in element (string type like "div", "span")
347
+ if (typeof type === "string") {
348
+ // Process children
349
+ let processedChildren = props?.children;
350
+ let childrenChunkId;
351
+ if (props?.children !== undefined) {
352
+ const childResult = await preprocessTree(props.children, context);
353
+ processedChildren = childResult.processedElement;
354
+ childrenChunkId = childResult.chunkId;
355
+ }
356
+ // Create the processed element for React SSR
357
+ // Ensure array children have keys
358
+ const safeChildren = Array.isArray(processedChildren)
359
+ ? ensureArrayKeys(processedChildren)
360
+ : processedChildren;
361
+ // Preserve the original key if present
362
+ const processedProps = originalKey !== null && originalKey !== undefined
363
+ ? { ...props, key: originalKey, children: safeChildren }
364
+ : { ...props, children: safeChildren };
365
+ const processedElement = React.createElement(type, processedProps);
366
+ // Create RSC chunk for this element
367
+ const id = context.nextId++;
368
+ const chunkProps = {};
369
+ if (props !== undefined) {
370
+ for (const [key, value] of Object.entries(props)) {
371
+ if (typeof value === "function")
372
+ continue;
373
+ if (key === "children" && childrenChunkId !== undefined) {
374
+ chunkProps[key] = `$${childrenChunkId}`;
375
+ }
376
+ else {
377
+ chunkProps[key] = protocol.encodeJsonValue(value);
378
+ }
379
+ }
380
+ }
381
+ context.chunks.push({
382
+ type: "J",
383
+ id,
384
+ value: {
385
+ $$typeof: "react.element",
386
+ type,
387
+ props: chunkProps,
388
+ },
389
+ });
390
+ return { processedElement, chunkId: id };
391
+ }
392
+ // Suspense boundary - render children for SSR HTML and RSC payload
393
+ if (type === React.Suspense) {
394
+ ssrLogger.debug("Processing Suspense boundary");
395
+ // Save previous fallback for nested Suspense support
396
+ const previousFallback = context.suspenseFallback;
397
+ // Pre-process fallback ONCE here (before processing children)
398
+ // This way async components can use it directly without await
399
+ let processedFallback = null;
400
+ if (props?.fallback !== undefined) {
401
+ const fallbackResult = await preprocessTree(props.fallback, context);
402
+ processedFallback = fallbackResult.processedElement;
403
+ }
404
+ // Store PROCESSED fallback in context for async component placeholders
405
+ context.suspenseFallback = processedFallback;
406
+ // Process children (async components) for both SSR HTML and RSC payload
407
+ let processedChildren = null;
408
+ let childrenChunkId;
409
+ if (props?.children !== undefined) {
410
+ ssrLogger.debug("Processing Suspense children...");
411
+ const childResult = await preprocessTree(props.children, context);
412
+ processedChildren = childResult.processedElement;
413
+ childrenChunkId = childResult.chunkId;
414
+ ssrLogger.debug("Suspense children processed");
415
+ }
416
+ // Restore previous fallback after processing children
417
+ context.suspenseFallback = previousFallback;
418
+ // For SSR HTML, render the actual content (children if available, else fallback)
419
+ const content = processedChildren ?? processedFallback;
420
+ // Ensure array children have keys
421
+ const safeContent = Array.isArray(content)
422
+ ? ensureArrayKeys(content)
423
+ : content;
424
+ const processedElement = React.createElement(React.Fragment, null, safeContent);
425
+ const id = context.nextId++;
426
+ // Store reference to children chunk in RSC payload
427
+ context.chunks.push({
428
+ type: "J",
429
+ id,
430
+ value: childrenChunkId !== undefined ? `$${childrenChunkId}` : null,
431
+ });
432
+ return { processedElement, chunkId: id };
433
+ }
434
+ // React built-in types (Fragment, etc.)
435
+ if (typeof type === "symbol" || type === React.Fragment) {
436
+ // Process children
437
+ let processedChildren = props?.children;
438
+ let childrenChunkId;
439
+ if (props?.children !== undefined) {
440
+ const childResult = await preprocessTree(props.children, context);
441
+ processedChildren = childResult.processedElement;
442
+ childrenChunkId = childResult.chunkId;
443
+ }
444
+ // Ensure array children have keys
445
+ const safeChildren = Array.isArray(processedChildren)
446
+ ? ensureArrayKeys(processedChildren)
447
+ : processedChildren;
448
+ // Preserve the original key if present
449
+ const fragmentProps = originalKey !== null && originalKey !== undefined
450
+ ? { ...props, key: originalKey, children: safeChildren }
451
+ : { ...props, children: safeChildren };
452
+ const processedElement = React.createElement(type, fragmentProps);
453
+ const id = context.nextId++;
454
+ // Store reference to children chunk, not the actual elements
455
+ context.chunks.push({
456
+ type: "J",
457
+ id,
458
+ value: childrenChunkId !== undefined ? `$${childrenChunkId}` : null,
459
+ });
460
+ return { processedElement, chunkId: id };
461
+ }
462
+ // Unhandled React element type - log warning and return null
463
+ ssrLogger.warn(`Unhandled React element type: ${typeof type}`, {
464
+ typeSymbol: type?.$$typeof?.toString?.(),
465
+ typeName: type?.name,
466
+ typeValue: type,
467
+ });
468
+ const id = context.nextId++;
469
+ context.chunks.push({ type: "J", id, value: null });
470
+ return { processedElement: null, chunkId: id };
471
+ }
472
+ // Plain objects (props, etc.)
473
+ if (typeof element === "object" && element !== null) {
474
+ const id = context.nextId++;
475
+ const processedObj = {};
476
+ for (const [key, value] of Object.entries(element)) {
477
+ if (typeof value === "function")
478
+ continue;
479
+ if (typeof value === "object" && value !== null) {
480
+ // Entries are processed in order: preprocessTree takes chunk ids from
481
+ // the shared context counter, so the order fixes the ids.
482
+ // oxlint-disable-next-line no-await-in-loop
483
+ const valueResult = await preprocessTree(value, context);
484
+ processedObj[key] = valueResult.processedElement;
485
+ }
486
+ else {
487
+ processedObj[key] = value;
488
+ }
489
+ }
490
+ // The chunk gets an escaped copy; the HTML render keeps the values.
491
+ context.chunks.push({
492
+ type: "J",
493
+ id,
494
+ value: protocol.encodeJsonValue(processedObj),
495
+ });
496
+ return { processedElement: processedObj, chunkId: id };
497
+ }
498
+ // Fallback
499
+ const id = context.nextId++;
500
+ context.chunks.push({ type: "J", id, value: element });
501
+ return { processedElement: element, chunkId: id };
502
+ }
503
+ /**
504
+ * Render a React element tree to HTML with RSC payload
505
+ *
506
+ * @param element - The root React element to render
507
+ * @param bundlerConfig - Module map for client component resolution
508
+ * @param options - SSR rendering options
509
+ * @returns SSR result with HTML, RSC payload, and client modules
510
+ */
511
+ export async function renderSSR(
512
+ // Any value a server component tree can hold; the walk narrows it per node.
513
+ // oxlint-disable-next-line typescript/no-explicit-any
514
+ element, bundlerConfig, options = { streamMode: "await-all" }) {
515
+ ssrLogger.debug("Starting SSR render...");
516
+ // Debug: inspect incoming element
517
+ ssrLogger.debug(`Input element type: ${typeof element}`);
518
+ if (element !== null && typeof element === "object") {
519
+ ssrLogger.debug(`Element $$typeof: ${element.$$typeof?.toString?.()}`);
520
+ ssrLogger.debug(`Element type: ${describeType(element.type)}`);
521
+ }
522
+ // Create SSR context
523
+ // Start nextId at 1 to reserve ID 0 for the root reference
524
+ const context = {
525
+ bundlerConfig,
526
+ nextId: 1,
527
+ chunks: [],
528
+ clientModules: new Set(),
529
+ pendingPromises: [],
530
+ streamMode: options.streamMode,
531
+ asyncComponents: new Map(),
532
+ suspenseFallback: null,
533
+ };
534
+ try {
535
+ // Pre-process the tree to handle client components and collect RSC chunks
536
+ const { processedElement, chunkId: rootChunkId } = await preprocessTree(element, context);
537
+ // Add root chunk marker (chunk 0 is always the root reference)
538
+ // Since we reserved ID 0 (nextId starts at 1), we can safely add it
539
+ context.chunks.unshift({
540
+ type: "J",
541
+ id: 0,
542
+ value: `$${rootChunkId}`,
543
+ });
544
+ ssrLogger.debug(`Pre-processed tree, collected ${context.chunks.length} RSC chunks`);
545
+ // React reports every render error through onError: an error in the
546
+ // shell, which also rejects renderToReadableStream and is handled in the
547
+ // catch below, and errors inside Suspense boundaries, which React leaves
548
+ // for the client to render again. The latter are logged once the HTML is
549
+ // read, so each error is logged once.
550
+ const boundaryErrors = [];
551
+ // Render to HTML using React's renderToReadableStream
552
+ const stream = await ReactDOMServer.renderToReadableStream(processedElement, {
553
+ onError: (error) => {
554
+ boundaryErrors.push(error);
555
+ },
556
+ });
557
+ // Wait for all content if in await-all mode
558
+ if (options.streamMode === "await-all") {
559
+ await stream.allReady;
560
+ }
561
+ // Read the whole stream as UTF-8 text
562
+ const html = await new Response(stream).text();
563
+ await Promise.all(boundaryErrors.map((error) => ssrLogger
564
+ .with({ error })
565
+ .error("render page to HTML: a Suspense boundary failed; the client renders it again")));
566
+ ssrLogger.debug(`SSR complete, HTML length: ${html.length}`);
567
+ return {
568
+ html,
569
+ rscPayload: context.chunks,
570
+ clientModules: Array.from(context.clientModules),
571
+ };
572
+ }
573
+ catch (error) {
574
+ // Handled here: the error is logged once, under the id the visitor sees,
575
+ // and the response carries only that id and a fixed message.
576
+ const correlationId = crypto.randomUUID();
577
+ await ssrLogger
578
+ .with({ correlationId, error })
579
+ .error("render page to HTML: rendering failed; sent the error fallback with this correlationId");
580
+ return createSSRErrorFallback(correlationId);
581
+ }
582
+ }
583
+ /**
584
+ * What a visitor sees when the page cannot be rendered at all. The error
585
+ * stays in the server log, under the correlation id shown next to this text.
586
+ */
587
+ export const SSR_ERROR_MESSAGE = "This page could not be rendered. Reload it, or report this error id:";
588
+ /**
589
+ * Build the result renderSSR returns when rendering fails as a whole. It
590
+ * carries a fixed message and the correlation id, never the error's own
591
+ * message: that text can hold request data and internal detail, and
592
+ * runtime/server.ts writes this HTML into the page as it is.
593
+ *
594
+ * @param correlationId - Id of the server log entry that holds the error; a
595
+ * crypto.randomUUID() value, so it needs no HTML escaping
596
+ */
597
+ function createSSRErrorFallback(correlationId) {
598
+ const message = `${SSR_ERROR_MESSAGE} ${correlationId}`;
599
+ return {
600
+ html: `<div data-ssr-error="true" data-error-id="${correlationId}" role="alert">${message}</div>`,
601
+ rscPayload: [{ type: "E", id: 0, value: { message } }],
602
+ clientModules: [],
603
+ };
604
+ }
605
+ /**
606
+ * Serialize RSC payload for embedding in HTML
607
+ *
608
+ * @param chunks - RSC chunks to serialize
609
+ * @returns JSON string safe for embedding in script tag
610
+ */
611
+ export function serializeRSCPayload(chunks) {
612
+ return JSON.stringify(chunks);
613
+ }
614
+ /**
615
+ * Generate RSC payload script tag
616
+ *
617
+ * @param chunks - RSC chunks to embed
618
+ * @returns HTML script tag with serialized payload
619
+ */
620
+ export function generateRSCPayloadScript(chunks) {
621
+ const serialized = serializeRSCPayload(chunks);
622
+ // Escape for script context so no value can end the element
623
+ const escaped = scriptJson.escapeJsonForScript(serialized);
624
+ return `<script id="__RSC_PAYLOAD__" type="application/json">${escaped}</script>`;
625
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Entry point for the standalone `laroux` binary.
4
+ *
5
+ * The command tree is the module the `eser` CLI mounts at `eser laroux`,
6
+ * re-rooted. See runStandaloneModule for why both binaries exist and why this
7
+ * is not a second implementation.
8
+ *
9
+ * @module
10
+ */
11
+ import * as cliSupport from "@eserstack/codebase/cli-support";
12
+ import * as module from "./module.js";
13
+ import config from "./package.json" with { type: "json" };
14
+ if (import.meta.main) {
15
+ // Binary entry point: the process runs the CLI and exits when it settles.
16
+ // oxlint-disable-next-line node/no-top-level-await
17
+ await cliSupport.runStandaloneModule(module.moduleDef, "laroux", config.version);
18
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * laroux.js — standalone CLI entry point.
3
+ *
4
+ * Usage:
5
+ * node ./cli.ts <command> [options]
6
+ * npx laroux <command> [options] # the bin of the npm package `laroux`
7
+ *
8
+ * @module
9
+ */
10
+ import * as results from "@eserstack/primitives/results";
11
+ /**
12
+ * Run the `laroux` command line with the process arguments.
13
+ *
14
+ * @returns ok when the command succeeded; otherwise the message to print and
15
+ * the exit code to set
16
+ */
17
+ export declare const main: () => Promise<results.Result<void, {
18
+ message?: string;
19
+ exitCode: number;
20
+ }>>;
21
+ /**
22
+ * Run the `laroux` command line as a bin does: a failure prints its message to
23
+ * stderr and sets the process exit code. The `laroux` bin of the npm package
24
+ * `laroux` calls this, so the CLI and the app share one copy of this package.
25
+ */
26
+ export declare const run: () => Promise<void>;