|
| 1 | +import { renderToStaticMarkup } from "react-dom/server"; |
| 2 | +// @ts-ignore |
| 3 | +import * as ReactServerDom from "react-server-dom-webpack/server.node"; |
| 4 | +// @ts-ignore |
| 5 | +import * as ReactClient from "react-server-dom-webpack/client.node"; |
| 6 | + |
| 7 | +import { ElementType, useContext } from "react"; |
| 8 | +import type { Context, RouteModule } from "@impalajs/core"; |
| 9 | +import { Writable, WritableOptions } from "node:stream"; |
| 10 | +import { HeadContext } from "./head-context"; |
| 11 | +import { promises as fs } from "node:fs"; |
| 12 | + |
| 13 | +class StringResponse extends Writable { |
| 14 | + private buffer: string; |
| 15 | + private responseData: Promise<string>; |
| 16 | + constructor(options?: WritableOptions) { |
| 17 | + super(options); |
| 18 | + this.buffer = ""; |
| 19 | + this.responseData = new Promise((resolve, reject) => { |
| 20 | + this.on("finish", () => resolve(this.buffer)); |
| 21 | + this.on("error", reject); |
| 22 | + }); |
| 23 | + } |
| 24 | + |
| 25 | + _write( |
| 26 | + chunk: any, |
| 27 | + encoding: BufferEncoding, |
| 28 | + callback: (error?: Error | null) => void |
| 29 | + ): void { |
| 30 | + console.log("chunk", chunk); |
| 31 | + this.buffer += chunk; |
| 32 | + callback(); |
| 33 | + } |
| 34 | + |
| 35 | + getData(): Promise<string> { |
| 36 | + return this.responseData; |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +function HeadContent() { |
| 41 | + const headProvider = useContext(HeadContext); |
| 42 | + return <>{...headProvider.getHead()}</>; |
| 43 | +} |
| 44 | + |
| 45 | +export async function render( |
| 46 | + context: Context, |
| 47 | + mod: () => Promise<RouteModule<ElementType>>, |
| 48 | + bootstrapModules?: Array<string> |
| 49 | +) { |
| 50 | + // @ts-ignore |
| 51 | + const { default: bundleMapPath } = await import("virtual:client-bundle-map"); |
| 52 | + console.log(bundleMapPath); |
| 53 | + const bundleMap = JSON.parse(await fs.readFile(bundleMapPath, "utf-8")); |
| 54 | + console.log(bundleMap); |
| 55 | + const { default: Page } = await mod(); |
| 56 | + |
| 57 | + const response = new StringResponse(); |
| 58 | + |
| 59 | + const stream = ReactServerDom.renderToPipeableStream( |
| 60 | + <Page {...context} />, |
| 61 | + { |
| 62 | + bootstrapModules, |
| 63 | + bootstrapScriptContent: `window.___CONTEXT=${JSON.stringify(context)};`, |
| 64 | + }, |
| 65 | + bundleMap |
| 66 | + ); |
| 67 | + |
| 68 | + console.log(stream); |
| 69 | + |
| 70 | + const something = ReactClient.createFromNodeStream(stream, bundleMap); |
| 71 | + console.log(something); |
| 72 | + const body = await response.getData(); |
| 73 | + |
| 74 | + const head = renderToStaticMarkup(<HeadContent />); |
| 75 | + |
| 76 | + return { body, head }; |
| 77 | +} |
0 commit comments