|
| 1 | +import { createServer as createHttpServer } from 'node:http'; |
| 2 | +import { readFileSync } from 'node:fs'; |
| 3 | +import { fileURLToPath } from 'node:url'; |
| 4 | +import path from 'node:path'; |
| 5 | + |
| 6 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 7 | +const isProduction = process.env.NODE_ENV === 'production'; |
| 8 | +const port = process.env.PORT || 3000; |
| 9 | + |
| 10 | +function getClientEntry() { |
| 11 | + if (!isProduction) return '/src/entry-client.tsx'; |
| 12 | + const manifest = JSON.parse( |
| 13 | + readFileSync(path.resolve(__dirname, 'dist/client/.vite/manifest.json'), 'utf-8'), |
| 14 | + ); |
| 15 | + const entry = manifest['src/entry-client.tsx']; |
| 16 | + return '/' + entry.file; |
| 17 | +} |
| 18 | + |
| 19 | +function readBody(req) { |
| 20 | + return new Promise((resolve, reject) => { |
| 21 | + const chunks = []; |
| 22 | + req.on('data', (chunk) => chunks.push(chunk)); |
| 23 | + req.on('end', () => resolve(Buffer.concat(chunks))); |
| 24 | + req.on('error', reject); |
| 25 | + }); |
| 26 | +} |
| 27 | + |
| 28 | +async function start() { |
| 29 | + let vite; |
| 30 | + let devHeadInjection = ''; |
| 31 | + |
| 32 | + const loadEntryServer = () => |
| 33 | + isProduction |
| 34 | + ? import('./dist/server/entry-server.js') |
| 35 | + : vite.ssrLoadModule('/src/entry-server.tsx'); |
| 36 | + |
| 37 | + const server = createHttpServer(async (req, res) => { |
| 38 | + const url = req.url || '/'; |
| 39 | + |
| 40 | + try { |
| 41 | + // Server function endpoint: adapt the node request to a web Request and |
| 42 | + // hand it to the runtime's handler inside the SSR module graph (so it |
| 43 | + // shares the registry with the rendered app). |
| 44 | + if (url.startsWith('/_server')) { |
| 45 | + const { handleServerFunction } = await loadEntryServer(); |
| 46 | + const body = await readBody(req); |
| 47 | + const request = new Request(`http://localhost:${port}${url}`, { |
| 48 | + method: req.method, |
| 49 | + headers: req.headers, |
| 50 | + body: req.method === 'GET' || req.method === 'HEAD' ? undefined : body, |
| 51 | + }); |
| 52 | + const response = await handleServerFunction(request); |
| 53 | + res.statusCode = response.status; |
| 54 | + response.headers.forEach((value, key) => res.setHeader(key, value)); |
| 55 | + res.end(await response.text()); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + if (!isProduction) { |
| 60 | + const handled = await new Promise((resolve) => { |
| 61 | + vite.middlewares(req, res, () => resolve(false)); |
| 62 | + }); |
| 63 | + if (handled !== false) return; |
| 64 | + if (!req.headers.accept?.includes('text/html')) { |
| 65 | + if (!res.headersSent) { |
| 66 | + res.statusCode = 404; |
| 67 | + res.end(); |
| 68 | + } |
| 69 | + return; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + if (isProduction && url !== '/') { |
| 74 | + const filePath = path.resolve(__dirname, 'dist/client' + url); |
| 75 | + try { |
| 76 | + const content = readFileSync(filePath); |
| 77 | + const ext = path.extname(url); |
| 78 | + const types = { |
| 79 | + '.js': 'application/javascript', |
| 80 | + '.css': 'text/css', |
| 81 | + '.html': 'text/html', |
| 82 | + '.json': 'application/json', |
| 83 | + }; |
| 84 | + res.setHeader('Content-Type', types[ext] || 'application/octet-stream'); |
| 85 | + res.end(content); |
| 86 | + return; |
| 87 | + } catch { |
| 88 | + // Fall through to SSR |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + const { render } = await loadEntryServer(); |
| 93 | + const stream = render(); |
| 94 | + const clientEntry = getClientEntry(); |
| 95 | + |
| 96 | + res.setHeader('Content-Type', 'text/html'); |
| 97 | + res.write('<!DOCTYPE html>'); |
| 98 | + |
| 99 | + stream.pipe({ |
| 100 | + write(chunk) { |
| 101 | + let html = chunk; |
| 102 | + if (!isProduction && html.includes('</head>')) { |
| 103 | + html = html.replace('</head>', devHeadInjection + '</head>'); |
| 104 | + } |
| 105 | + if (isProduction && html.includes('/src/entry-client.tsx')) { |
| 106 | + html = html.replace('/src/entry-client.tsx', clientEntry); |
| 107 | + } |
| 108 | + return res.write(html); |
| 109 | + }, |
| 110 | + end() { |
| 111 | + res.end(); |
| 112 | + }, |
| 113 | + }); |
| 114 | + } catch (e) { |
| 115 | + if (!isProduction) vite.ssrFixStacktrace(e); |
| 116 | + console.error(e); |
| 117 | + res.statusCode = 500; |
| 118 | + res.end(e.message); |
| 119 | + } |
| 120 | + }); |
| 121 | + |
| 122 | + if (!isProduction) { |
| 123 | + const { createServer } = await import('vite'); |
| 124 | + vite = await createServer({ |
| 125 | + server: { middlewareMode: true, hmr: { server } }, |
| 126 | + appType: 'custom', |
| 127 | + }); |
| 128 | + const { devStylePatch } = await import('vite-plugin-solid'); |
| 129 | + devHeadInjection = |
| 130 | + `<script>${devStylePatch}</script>` + |
| 131 | + '<script type="module" src="/@vite/client"></script>'; |
| 132 | + } |
| 133 | + |
| 134 | + server.listen(port, () => { |
| 135 | + console.log(`Server running at http://localhost:${port}`); |
| 136 | + }); |
| 137 | +} |
| 138 | + |
| 139 | +start(); |
0 commit comments