Skip to content

base configuration option #194

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 17 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,27 @@ export interface TableOfContents {

export interface Config {
title?: string;
base?: string;
pages?: (Page | Section)[]; // TODO rename to sidebar?
toc?: TableOfContents;
}

export async function readConfig(root: string): Promise<Config | undefined> {
for (const ext of [".js", ".ts"]) {
let config;
try {
const configPath = join(process.cwd(), root, ".observablehq", "config" + ext);
const configStat = await stat(configPath);
// By using the modification time of the config, we ensure that we pick up
// any changes to the config on reload. TODO It would be better to either
// restart the preview server when the config changes, or for the preview
// server to watch the config file and hot-reload it automatically.
return (await import(`${configPath}?${configStat.mtimeMs}`)).default;
config = (await import(`${configPath}?${configStat.mtimeMs}`)).default;
} catch {
continue;
}
if (typeof config?.base === "string" && !config.base.match(/^[/]\w+[/]$/))
throw new Error(`invalid base: ${config.base}`);
return config;
}
}
11 changes: 11 additions & 0 deletions src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,17 @@ class Server {
try {
const url = new URL(req.url!, "http://localhost");
let {pathname} = url;
const config = await readConfig(this.root);
const {base = "/"} = config ?? {};
if (!base || !pathname.startsWith(base)) {
if (pathname === "/") {
res.writeHead(302, {Location: base});
res.end();
return;
}
throw new HttpError("Not found", 404);
}
pathname = pathname.slice(base.length - 1);
if (pathname === "/_observablehq/runtime.js") {
send(req, "/@observablehq/runtime/dist/runtime.js", {root: "./node_modules"}).pipe(res);
} else if (pathname.startsWith("/_observablehq/")) {
Expand Down