58 lines
1.7 KiB
JavaScript
58 lines
1.7 KiB
JavaScript
|
|
import { createServer } from "node:http";
|
||
|
|
import { buildContext, workspaceRoot } from "./generate-local-context.mjs";
|
||
|
|
|
||
|
|
const host = process.env.LOCAL_CONTEXT_HOST || "127.0.0.1";
|
||
|
|
const port = Number(process.env.LOCAL_CONTEXT_PORT || 23873);
|
||
|
|
|
||
|
|
function sendJson(response, status, payload) {
|
||
|
|
response.writeHead(status, {
|
||
|
|
"Access-Control-Allow-Origin": "*",
|
||
|
|
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
||
|
|
"Access-Control-Allow-Headers": "Content-Type",
|
||
|
|
"Cache-Control": "no-store",
|
||
|
|
"Content-Type": "application/json; charset=utf-8"
|
||
|
|
});
|
||
|
|
response.end(`${JSON.stringify(payload, null, 2)}\n`);
|
||
|
|
}
|
||
|
|
|
||
|
|
const server = createServer((request, response) => {
|
||
|
|
if (request.method === "OPTIONS") {
|
||
|
|
response.writeHead(204, {
|
||
|
|
"Access-Control-Allow-Origin": "*",
|
||
|
|
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
||
|
|
"Access-Control-Allow-Headers": "Content-Type"
|
||
|
|
});
|
||
|
|
response.end();
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (request.method !== "GET") {
|
||
|
|
sendJson(response, 405, { error: "Method not allowed" });
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
const url = new URL(request.url || "/", `http://${host}:${port}`);
|
||
|
|
|
||
|
|
if (url.pathname === "/health") {
|
||
|
|
sendJson(response, 200, { ok: true, workspaceRoot });
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (url.pathname !== "/local-context.json") {
|
||
|
|
sendJson(response, 404, { error: "Not found" });
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
sendJson(response, 200, buildContext());
|
||
|
|
} catch (error) {
|
||
|
|
sendJson(response, 500, {
|
||
|
|
error: error instanceof Error ? error.message : "Could not build local context"
|
||
|
|
});
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
server.listen(port, host, () => {
|
||
|
|
console.log(`Serving live local context for ${workspaceRoot} at http://${host}:${port}/local-context.json`);
|
||
|
|
});
|