generated from kawarimidoll/deno-dev-template
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmod.ts
274 lines (229 loc) Β· 7.1 KB
/
mod.ts
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import { log, lookupMimeType, parseYaml, sortBy } from "./deps.ts";
import { Marked } from "./marked.ts";
import { genResponseArgs, getH1, toTitle } from "./utils.ts";
import { renderPage } from "./render.ts";
export const defaultConfig = {
sourceDir: "docs",
rootFile: "index",
lang: "en",
siteName: "Built by Diplodocus",
description: "This site is built by Diplodocus",
favicon:
"https://cdn.jsdelivr.net/gh/twitter/[email protected]/assets/72x72/1f995.png",
image:
"https://cdn.jsdelivr.net/gh/twitter/[email protected]/assets/72x72/1f995.png",
twitter: "",
navLinks: [] as Array<NavLink>,
listPages: [] as Array<PageLink>,
tocLevels: [2, 3],
removeDefaultStyles: false,
bottomHead: "",
bottomBody: "",
};
export type Config = typeof defaultConfig;
export type UserConfig = Partial<Config>;
export type NavLink = {
title: string;
path?: string;
items?: Array<NavLink>;
};
export type ListPage = {
title: string;
path: string;
items: Array<PageLink>;
};
export type PageLink = {
title: string;
path: string;
};
export type PageMeta = {
prev?: PageLink;
next?: PageLink;
date?: string;
tag?: Array<string>;
title?: string;
tocLevels?: Array<number>;
lang?: string;
description?: string;
favicon?: string;
image?: string;
removeDefaultStyles?: boolean;
bottomHead?: string;
bottomBody?: string;
};
export class Diplodocus {
private storedPages: Record<string, string> = {};
private storedMeta: Record<string, PageMeta> = {};
private siteMeta: Config;
private constructor(userConfig: UserConfig = {}) {
this.siteMeta = { ...defaultConfig, ...userConfig };
}
static async load() {
try {
let userConfig: UserConfig = {};
const files: string[] = [];
for await (const file of Deno.readDir(Deno.cwd())) {
if (!file.isFile || !/^diplodocus\.\w{2,4}$/.test(file.name)) {
continue;
}
files.push(file.name);
}
log.debug({ files });
for (const ext of ["yaml", "yml", "json"]) {
const configFile = `diplodocus.${ext}`;
if (files.includes(configFile)) {
userConfig = parseYaml(
await Deno.readTextFile(configFile),
) as UserConfig;
break;
}
}
const instance = new Diplodocus(userConfig);
await instance.processStoredData();
return instance;
} catch (error) {
log.error("Diplodocus load failed");
throw error;
}
}
private async collectList(
listPath: string,
sortKey: "path" | "title" = "path",
) {
const listDir = `${this.siteMeta.sourceDir}${listPath}`;
log.debug({ listDir });
const pages: Array<PageLink> = [];
for await (const page of Deno.readDir(listDir)) {
if (!page.isFile || !/\.md$/.test(page.name)) {
continue;
}
const { name } = page;
const basename = name.replace(/\.md$/, "");
const md = await Deno.readTextFile(`${listDir}/${name}`);
const { content, meta } = Marked.parse(md);
const title = meta.title || getH1(content) || toTitle(basename);
pages.push({ title, path: `${listPath}/${basename}` });
}
// TODO: configure sortKey
return sortBy(pages, (page) => page[sortKey]);
}
private async processStoredData() {
this.storedPages = {};
this.storedMeta = {};
const { listPages, sourceDir } = this.siteMeta;
for (let { title, path } of listPages) {
if (!path) {
log.error("path of listPages is required");
continue;
}
if (!/^\/.*/.test(path)) {
path = "/" + path;
}
if (!title) {
title = toTitle(path);
}
const filePath = `${sourceDir}${path}.md`;
this.storedMeta[filePath] ||= {};
const pages = await this.collectList(path);
log.debug({ pages });
// generate list pages
this.storedPages[filePath] = [
`# ${title}`,
...pages.map(({ title, path }) => `- [${title}](${path})`),
].join("\n");
this.storedMeta[filePath].tocLevels = [];
// generate prev/next links
pages.forEach(({ path }, idx) => {
const itemFilePath = `${sourceDir}${path}.md`;
this.storedMeta[itemFilePath] ||= {};
if (pages[idx - 1]) {
this.storedMeta[itemFilePath].prev = pages[idx - 1];
}
if (pages[idx + 1]) {
this.storedMeta[itemFilePath].next = pages[idx + 1];
}
});
}
log.debug({
listPages,
storedPages: this.storedPages,
storedMeta: this.storedMeta,
});
}
private async readData(
filePath: string,
pageUrl: string,
tryParse = false,
): Promise<BodyInit> {
log.debug({ filePath, tryParse });
const siteMeta = this.siteMeta;
const storedPage = this.storedPages[filePath];
if (storedPage) {
const { content, meta } = Marked.parse(storedPage);
const storedMeta = this.storedMeta[filePath] || {};
const pageMeta = { ...storedMeta, ...meta };
log.debug({ meta, pageMeta });
return renderPage({ content, pageMeta, siteMeta, pageUrl });
}
try {
const data = await Deno.readFile(filePath);
if (filePath.endsWith(".md") && tryParse) {
const md = new TextDecoder().decode(data);
const storedMeta = this.storedMeta[filePath] || {};
const { content, meta } = Marked.parse(md);
const pageMeta = { ...storedMeta, ...meta };
log.debug({ meta, pageMeta });
return renderPage({ content, pageMeta, siteMeta, pageUrl });
}
return data;
} catch (error) {
const subject = `${error}`.split(":")[0];
if (subject === "NotFound" && filePath.endsWith(".html")) {
return this.readData(filePath.replace(/html$/, "md"), pageUrl, true);
}
// in other cases, throw error transparency
throw error;
}
}
async handler(request: Request) {
const url = new URL(request.url);
const { href, origin, host, hash, search } = url;
let { pathname } = url;
log.debug({ href, origin, host, pathname, hash, search });
if (pathname === "/") {
pathname += this.siteMeta.rootFile;
} else if (pathname.endsWith("/")) {
return new Response(
...genResponseArgs(302, {
headers: { location: pathname.slice(0, -1) },
}),
);
}
const tailPath = pathname.split("/").at(-1) || "";
let ext = tailPath.includes(".") ? tailPath.split(".").at(-1) : "";
if (!ext) {
pathname += ".html";
ext = "html";
}
const mimeType = lookupMimeType(ext);
const filePath = `${this.siteMeta.sourceDir}${pathname}`;
log.debug({ pathname, ext, mimeType, filePath });
if (!mimeType) {
return new Response(...genResponseArgs(400));
}
try {
log.info(`accessed: ${href}`);
const data = await this.readData(filePath, href);
return new Response(data, {
headers: { "content-type": mimeType },
});
} catch (error) {
log.error(error);
const subject = `${error}`.split(":")[0];
if (subject === "NotFound") {
return new Response(...genResponseArgs(404));
}
return new Response(...genResponseArgs(500));
}
}
}