git / tests / serve.mjsmain at 517348b
// tests/serve.mjs — THE APP ON THIS MACHINE, to try a change before a push:
//
// node tests/serve.mjs then open http://git.localhost:4173 (PORT=… for another)
// VISITOR=anyone node tests/serve.mjs as someone who is no member
//
// It serves COPIES of the repos cloned beside this one, made in a temporary folder that goes when
// the server stops: a merge here writes a commit to a copy, never to your clone. The copy of this
// repo has a branch of its own, `a-proposal`, to open a pull from.
//
// The mind is local-mind.mjs. What a member's page writes goes to it too: this server answers the
// page's /mind.js with a module of its own (below), in the place of the one that dials the mind.
// Git itself is served by git's own http-backend over the same copies (git-http.mjs), in the place
// of Cloudflare Artifacts: a clone, and the push of a branch that a member's page makes of an edit.
import "@repos/stdlib/testing/mind-loader.mjs";
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { mergePull } from "../pulls.ts";
import { gitBackend } from "./git-http.mjs";
import { localMind } from "./local-mind.mjs";
const { gitApp } = await import("../app.ts");
// The folder that holds every repo, side by side.
const workspace = new URL("../../", import.meta.url).pathname;
const copies = mkdtempSync(join(tmpdir(), "git-app-serve-"));
process.on("exit", () => rmSync(copies, { recursive: true, force: true }));
process.on("SIGINT", () => process.exit());
process.on("SIGTERM", () => process.exit());
const folders = {};
for (const name of ["kernel", "stdlib", "dash", "tasks", "git", "config"]) {
// a workspace need not hold every repo
if (!existsSync(join(workspace, name))) continue;
folders[`/repos/${name}`] = join(copies, name);
execFileSync("git", ["clone", "--quiet", "--branch", "main", join(workspace, name), folders[`/repos/${name}`]]);
}
// A branch to open a pull from: two commits on the copy of this repo.
{
const folder = folders["/repos/git"];
const git = (...args) => execFileSync("git", ["-C", folder, "-c", "user.name=Ada Author", "-c", "user.email=ada@example.com", ...args]);
git("checkout", "--quiet", "-b", "a-proposal");
writeFileSync(join(folder, "README.md"), "# git\n\nThe mind's repos, to read, to clone and to propose a change to.\n");
git("commit", "--quiet", "--all", "--message", "Say what the app is for in one line\n\nThe README opened with how, not what.");
writeFileSync(join(folder, "NOTES.md"), "A note that the proposal adds.\n");
git("add", "NOTES.md");
git("commit", "--quiet", "--message", "Add a note");
git("checkout", "--quiet", "main");
}
const visitor = process.env.VISITOR === "anyone" ? null : "ada@example.com";
const mind = localMind({ folders, member: visitor });
const git = gitApp({
public: Object.keys(folders).filter((repo) => repo !== "/repos/config"),
icon: () =>
new Response("<svg xmlns='http://www.w3.org/2000/svg'/>", {
headers: { "content-type": "image/svg+xml" },
}),
});
/** THE PAGE'S itx HERE: the two things a member's page does, sent to this server, which does
* them on the local mind as that member. */
const MIND_MODULE = `
const ask = async (path, body) => {
const answer = await fetch(path, { method: "POST", body: JSON.stringify(body) });
if (!answer.ok) throw new Error(await answer.text());
return answer.json();
};
export const itx = {
cd: (path) => ({ append: (event) => ask("/local-mind/append", { path, event }) }),
repos: { get: (repo) => ({ commitFiles: (input) => ask("/local-mind/commit", { repo, input }) }) },
config: { pullMerge: (repo, number) => ask("/local-mind/merge", { repo, number }) },
};
`;
const written = async (path, body) => {
if (path === "/local-mind/append") return mind.as(visitor).cd(body.path).append(body.event);
if (path === "/local-mind/commit")
return mind.getItx().repos.get(body.repo).commitFiles({ author: { name: visitor, email: visitor }, ...body.input });
if (path === "/local-mind/merge") return mergePull(mind.getItx(), body.repo, body.number);
};
const port = Number(process.env.PORT) || 4173;
createServer(async (request, response) => {
const { pathname } = new URL(request.url, "http://localhost");
if (pathname === "/mind.js") {
response.writeHead(200, { "content-type": "text/javascript; charset=utf-8" }).end(MIND_MODULE);
return;
}
// The page's own files as they are on disk now: the app holds them as they were when this
// server started, so an edit to public/ shows on the next load with no restart.
const file = new URL(`../public${pathname}`, import.meta.url);
if (/^\/[a-z-]+\.(js|css)$/.test(pathname) && existsSync(file)) {
const type = pathname.endsWith(".css") ? "text/css" : "text/javascript";
response.writeHead(200, { "content-type": `${type}; charset=utf-8` }).end(readFileSync(file));
return;
}
if (pathname.startsWith("/local-mind/")) {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
try {
const answer = await written(pathname, JSON.parse(Buffer.concat(chunks).toString()));
response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(answer));
} catch (error) {
response.writeHead(400).end(error instanceof Error ? error.message : String(error));
}
return;
}
const wire = /^(\/repos\/[^/]+)\/(info\/refs|git-upload-pack|git-receive-pack)$/.exec(pathname);
if (wire && folders[wire[1]]) {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const { search } = new URL(request.url, "http://localhost");
const sent = { folder: folders[wire[1]], verb: wire[2], search, method: request.method, headers: request.headers, body: Buffer.concat(chunks) };
const answered = await gitBackend(sent);
response.writeHead(answered.status, answered.headers).end(answered.body);
return;
}
const answer = await git.fetch(new Request(`http://${request.headers.host}${request.url}`), mind);
response.writeHead(answer.status, Object.fromEntries(answer.headers));
response.end(Buffer.from(await answer.arrayBuffer()));
}).listen(port, () => console.log(`http://git.localhost:${port}`));