(config)
| 539 | // ───────────────────────────────────────────────────────────────────────────── |
| 540 | |
| 541 | export function startStaticServer(config) { |
| 542 | const route = createRouter(config.routes); |
| 543 | const proxy = createProxyHandlers({ label: `static:${config.port}` }); |
| 544 | const dirAbs = resolve(config.dir); |
| 545 | const injectionOpts = { |
| 546 | sessionApiKey: config.sessionApiKey || null, |
| 547 | authRequired: config.authRequired || false, |
| 548 | runtimeServicesInfo: config.runtimeServicesInfo || null, |
| 549 | lockToCloud: config.lockToCloud || null, |
| 550 | basePath: normalizeBasePath(config.basePath), |
| 551 | }; |
| 552 | const basePath = injectionOpts.basePath; |
| 553 | const rejectPrefixes = config.rejectPrefixes ?? []; |
| 554 | const staticMiddleware = createStaticMiddleware(dirAbs); |
| 555 | |
| 556 | const uninstallDiagnostics = proxy.installDiagnostics(); |
| 557 | |
| 558 | const server = createServer((req, res) => { |
| 559 | const backend = route(req.url ?? "/"); |
| 560 | if (backend) { |
| 561 | proxy.proxyHttp(req, res, backend); |
| 562 | return; |
| 563 | } |
| 564 | handleStatic( |
| 565 | req, |
| 566 | res, |
| 567 | dirAbs, |
| 568 | staticMiddleware, |
| 569 | injectionOpts, |
| 570 | rejectPrefixes, |
| 571 | basePath, |
| 572 | ).catch((err) => { |
| 573 | console.error(`Static handler error for ${req.url}:`, err); |
| 574 | if (!res.headersSent) { |
| 575 | res.writeHead(500); |
| 576 | res.end("Internal Server Error"); |
| 577 | } |
| 578 | }); |
| 579 | }); |
| 580 | |
| 581 | server.on("upgrade", (req, socket, head) => { |
| 582 | const backend = route(req.url ?? "/"); |
| 583 | if (backend) { |
| 584 | proxy.proxyWebSocket(req, socket, head, backend); |
| 585 | return; |
| 586 | } |
| 587 | socket.destroy(); |
| 588 | }); |
| 589 | server.on("close", uninstallDiagnostics); |
| 590 | |
| 591 | return new Promise((resolveListen) => { |
| 592 | server.listen(config.port, config.host, () => { |
| 593 | const displayPath = basePath === "/" ? "/" : `${basePath}/`; |
| 594 | console.log(""); |
| 595 | console.log( |
| 596 | `Static-server + proxy listening on http://${config.host}:${config.port}${displayPath}`, |
| 597 | ); |
| 598 | console.log(` Static dir: ${dirAbs}`); |
no test coverage detected