| 8 | import { importReactDom } from './import-react-dom'; |
| 9 | |
| 10 | export const render = async ( |
| 11 | element: React.ReactElement, |
| 12 | options?: Options, |
| 13 | ) => { |
| 14 | const reactDOMServer = await importReactDom().then((m) => { |
| 15 | if ('default' in m) { |
| 16 | return m.default; |
| 17 | } |
| 18 | |
| 19 | return m; |
| 20 | }); |
| 21 | |
| 22 | const html = await new Promise<string>((resolve, reject) => { |
| 23 | const ErrorBoundary = createErrorBoundary(reject); |
| 24 | reactDOMServer |
| 25 | .renderToReadableStream( |
| 26 | <ErrorBoundary> |
| 27 | <Suspense>{element}</Suspense> |
| 28 | </ErrorBoundary>, |
| 29 | { |
| 30 | onError(error: unknown) { |
| 31 | reject(error); |
| 32 | }, |
| 33 | progressiveChunkSize: Number.POSITIVE_INFINITY, |
| 34 | }, |
| 35 | ) |
| 36 | .then(async (stream) => { |
| 37 | await stream.allReady; |
| 38 | return readStream(stream); |
| 39 | }) |
| 40 | .then((result) => resolve(stripImagePreloadLinks(result))) |
| 41 | .catch(reject); |
| 42 | }); |
| 43 | |
| 44 | if (options?.plainText) { |
| 45 | return toPlainText(html, options.htmlToTextOptions); |
| 46 | } |
| 47 | |
| 48 | const doctype = |
| 49 | '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'; |
| 50 | |
| 51 | const document = `${doctype}${html.replace(/<!DOCTYPE.*?>/, '')}`; |
| 52 | |
| 53 | if (options?.pretty) { |
| 54 | return pretty(document); |
| 55 | } |
| 56 | |
| 57 | return document; |
| 58 | }; |