import { renderToString } from "https://esm.sh/react-dom@18.3.1/server";
import * as React from "https://esm.sh/react@18.3.1";
export { React };
const createScript = (module: string) => `
import App from "${module}";
import { hydrateRoot } from "https://esm.sh/react-dom@18.3.1/client";
import { jsx } from "https://esm.sh/react@18.3.1/jsx-runtime";
const root = document.getElementById("root");
hydrateRoot(root, jsx(App, {}));
`;
const App = ({ Component, module, simple }: {
Component: any;
module: string;
simple?: boolean;
}) => {
const script = (
<script
type="module"
dangerouslySetInnerHTML={{ __html: createScript(module) }}
/>
);
if (simple) {
return (
<>
<head></head>
<body id="root">
<Component />
{script}
</body>
</>
);
}
return <Component script={script} />;
};
interface Options {
root?: boolean;
}
export default function resrv(Component, module: string, opts: Options = {}) {
return function<T extends object>(args: Request | T): Response | any {
if (args instanceof Request) {
const body = renderToString(<App Component={Component} module={module} simple={!opts.root} />);
const html = `<!DOCTYPE html>
<html lang="en" ${opts.root ? "id='root'" : ""}>
${body}
</html>`;
return new Response(html, {
headers: {
"Content-Type": "text/html",
},
});
}
return <App Component={Component} module={module} />;
};
}