-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathserver.mjs
More file actions
70 lines (59 loc) · 2.46 KB
/
Copy pathserver.mjs
File metadata and controls
70 lines (59 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Docs web service: serves docs/dist via sirv and applies redirects.config.js
// redirects in middleware. Render sets PORT.
import { createServer } from "node:http";
import { readFileSync, existsSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import sirv from "sirv";
import { redirects } from "./redirects.config.js";
const PORT = Number(process.env.PORT) || 10000;
const DIR = join(fileURLToPath(new URL(".", import.meta.url)), "docs", "dist");
const EXACT = new Map(redirects.map((r) => [r.from, r.to]));
const PREFIX = [["/magic-account", "/smart-accounts/chain-abstraction/overview"]];
const SPA_FALLBACK = ["/sdk", "/meta-infra", "/recovery-flow", "/blog", "/react", "/smart-wallet"];
const assets = sirv(DIR, {
etag: true,
gzip: true,
brotli: true,
// Vocs writes its search index to docs/dist/.vocs/search-index-<hash>.json and
// the client fetches it from /.vocs/...; sirv skips dot-directories unless this
// is set, which 404'd the index and broke site search.
dotfiles: true,
setHeaders(res, pathname) {
if (pathname.startsWith("/assets/")) {
res.setHeader("cache-control", "public, max-age=31536000, immutable");
}
},
});
const shell = sirv(DIR, { etag: true, single: true }); // serves index.html on miss
const notFound = existsSync(join(DIR, "404.html")) ? readFileSync(join(DIR, "404.html")) : null;
function redirectTo(pathname) {
const clean = pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname;
return (
EXACT.get(pathname) ??
EXACT.get(clean) ??
PREFIX.find(([p]) => clean === p || clean.startsWith(p + "/"))?.[1] ??
null
);
}
const isSpaFallback = (pathname) => {
const clean = pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname;
return SPA_FALLBACK.some((p) => clean === p || clean.startsWith(p + "/"));
};
createServer((req, res) => {
const { pathname, search } = new URL(req.url, "http://localhost");
const to = redirectTo(pathname);
if (to) {
res.writeHead(301, { location: to + search });
return res.end();
}
assets(req, res, () => {
if (isSpaFallback(pathname)) return shell(req, res, () => res.end());
if (notFound) {
res.writeHead(404, { "content-type": "text/html; charset=utf-8" });
return res.end(notFound);
}
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
res.end("Not Found");
});
}).listen(PORT, "0.0.0.0", () => console.log(`docs server listening on :${PORT}`));