-
Notifications
You must be signed in to change notification settings - Fork 3
/
docuraptor.ts
454 lines (398 loc) · 10.4 KB
/
docuraptor.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
import assets from "./assets.ts";
import {
assert,
argsParse,
pathJoin,
serve,
ServerRequest,
unreachable,
} from "./deps.ts";
import { generateStatic } from "./generator.ts";
import { DocRenderer } from "./renderer.ts";
import { htmlEscape } from "./utility.ts";
const decoder = new TextDecoder();
/*
* Request handling
*/
const doc_prefix = "/doc/";
async function handleDoc(req: ServerRequest): Promise<void> {
assert(req.url.startsWith(doc_prefix));
const args = req.url.substr(doc_prefix.length);
const search_index = args.indexOf("?");
const doc_url = decodeURIComponent(
search_index === -1 ? args : args.slice(0, search_index),
);
const search = new URLSearchParams(
search_index === -1 ? "" : args.slice(search_index),
);
let doc;
try {
doc = await new DocRenderer({
private: !!search.get("private"),
link_module: (mod) => `/doc/${encodeURIComponent(mod)}`,
}).render(
doc_url.length > 0 ? doc_url : undefined,
);
} catch (err) {
if (err.stderr !== undefined) {
handleFail(req, 500, htmlEscape(err.stderr));
} else {
handleFail(req, 500, "Documentation generation failed");
}
return;
}
await req.respond({
status: 200,
headers: new Headers({
"Content-Type": "text/html",
}),
body: doc,
});
}
async function handleFail(
req: ServerRequest,
status: number,
message: string,
): Promise<void> {
const rend = new DocRenderer();
await req.respond({
status,
headers: new Headers({
"Content-Type": "text/html",
}),
body: `<!DOCTYPE html>
<html>
<head>
${rend.renderHead("Docuraptor Error")}
</head>
<body>
${rend.renderHeader("An error occured")}
<main>
<pre>
${htmlEscape(message)}
</pre>
</main>
</body>
</html>`,
});
}
const file_url = new URL("file:/");
let deps_url: URL | undefined = undefined;
async function handleIndex(req: ServerRequest): Promise<void> {
const known_documentation = [];
if (deps_url !== undefined) {
for await (const protocol of Deno.readDir(deps_url.pathname)) {
if (!protocol.isDirectory) {
continue;
}
const path_url = new URL(protocol.name + "/", deps_url);
for await (const host of Deno.readDir(path_url.pathname)) {
if (!host.isDirectory) {
continue;
}
const host_url = new URL(host.name + "/", path_url);
for await (const resource of Deno.readDir(host_url.pathname)) {
if (!resource.isFile || !resource.name.endsWith(".metadata.json")) {
continue;
}
const resource_url = new URL(resource.name, host_url);
const metadata_string = await Deno.readTextFile(
resource_url.pathname,
);
const metadata: { headers: { [_: string]: string }; url: string } =
JSON.parse(metadata_string);
known_documentation.push(metadata.url);
}
}
}
} else {
console.warn("Failed to determine cache directory");
}
const rend = new DocRenderer();
await req.respond({
status: 200,
headers: new Headers({
"Content-Type": "text/html",
}),
body: `<html>
<head>
${rend.renderHead("Docuraptor Index")}
</head>
<body>
${rend.renderHeader("Docuraptor Index – Locally available modules")}
<main>
<ul>
<li class=link><a href="/doc/">Deno Builtin</a></li>
${
known_documentation.sort().map(
(url) =>
`<li class=link><a href="/doc/${encodeURIComponent(url)}">${
htmlEscape(url)
}</a></li>`,
).join("")
}
</ul>
</main>
</body>
</html>`,
});
}
const form_prefix = "/form/";
async function handleForm(req: ServerRequest): Promise<void> {
assert(req.url.startsWith(form_prefix));
const args = req.url.substr(form_prefix.length);
const search_index = args.indexOf("?");
const form_action = args.slice(0, search_index);
const search = new URLSearchParams(
search_index === -1 ? "" : args.slice(search_index),
);
switch (form_action) {
case "open": {
if (!search.has("url")) {
await handleFail(req, 400, "Received invalid request");
return;
}
await req.respond({
status: 301,
headers: new Headers({
"Location": `/doc/${search.get("url")!}`,
}),
});
break;
}
default:
await handleFail(
req,
400,
`Invalid form action ${htmlEscape(form_action)}`,
);
}
}
const static_prefix = "/static/";
async function handleStatic(req: ServerRequest): Promise<void> {
assert(req.url.startsWith(static_prefix));
const resource = req.url.substr(static_prefix.length);
const asset = assets[resource];
if (asset === undefined) {
handleFail(req, 404, "Resource not found");
} else {
await req.respond({
status: 200,
headers: new Headers({
"Content-Type": asset.mimetype ?? "application/octet-stream",
}),
body: asset.content,
});
}
}
async function handler(req: ServerRequest): Promise<void> {
try {
if (!["HEAD", "GET"].includes(req.method)) {
handleFail(req, 404, "Invalid method");
}
if (req.url.startsWith(static_prefix)) {
await handleStatic(req);
} else if (req.url.startsWith(doc_prefix)) {
await handleDoc(req);
} else if (req.url.startsWith(form_prefix)) {
await handleForm(req);
} else if (req.url === "/") {
await handleIndex(req);
} else {
await handleFail(req, 404, "Malformed path");
}
} finally {
req.finalize();
req.conn.close();
}
}
/*
* Main
*/
function argCheck(
rest: Record<string, unknown>,
specifier_rest: (string | number)[],
): void {
if (Object.keys(rest).length > 0 || specifier_rest.length > 0) {
console.error(
`Superfluous arguments: ${[Object.keys(rest), specifier_rest].flat()}`,
);
Deno.exit(1);
}
}
function open(s: string): void {
let run = Deno.run({
cmd: Deno.build.os === "windows"
? ["start", "", s]
: Deno.build.os === "darwin"
? ["open", s]
: Deno.build.os === "linux"
? ["xdg-open", s]
: unreachable(),
stdin: "null",
stdout: "null",
stderr: "null",
});
run.status().finally(() => run.close());
}
async function initialize() {
let p;
try {
p = Deno.run({
cmd: ["deno", "info", "--json", "--unstable"],
stdin: "null",
stdout: "piped",
stderr: "null",
});
const info: { modulesCache: string } = JSON.parse(
decoder.decode(await p.output()),
);
if ((await p.status()).success) {
deps_url = new URL(info.modulesCache + "/", file_url);
}
} finally {
p?.close();
}
}
async function mainGenerate() {
const {
builtin,
dependencies,
generate,
index,
out,
private: priv,
"_": specifiers,
...rest
} = argsParse(
Deno.args,
{
boolean: [/*"builtin",*/ "dependencies", "generate", "private"],
string: ["index", "out"],
},
);
argCheck(rest, []);
await generateStatic(specifiers.map((v) => v.toString()), {
builtin,
index_filename: index,
output_directory: out,
private: priv,
recursive: dependencies,
});
}
async function mainServer() {
const {
builtin,
hostname,
port,
private: priv,
"skip-browser": skip,
"_": specifier,
...rest
} = argsParse(Deno.args, {
default: {
hostname: "127.0.0.1",
port: 8709,
},
boolean: ["builtin", "private", "skip-browser"],
string: ["hostname"],
});
argCheck(rest, specifier.slice(1));
if (typeof port !== "number") {
console.error("Port must be a number");
Deno.exit(1);
}
if (builtin && specifier.length > 0) {
console.error("--builtin and <url> are mutually exclusive");
Deno.exit(1);
}
if (priv && specifier.length === 0) {
console.error("Must provide a specifier with --private");
Deno.exit(1);
}
let url = `http://${hostname}:${port}/`;
if (builtin) {
url += "doc/";
} else if (specifier.length > 0) {
url += `doc/${encodeURIComponent(specifier[0])}`;
}
if (priv) {
url += "?private=1";
}
console.info("Starting server...", url);
if (!skip) {
try {
const browser = Deno.env.get("DOCURAPTOR_BROWSER") ??
Deno.env.get("BROWSER");
if (browser === undefined) {
throw null;
}
let run = Deno.run({
cmd: [browser, url],
});
run.status().finally(() => run.close());
} catch {
open(url);
}
}
for await (const req of serve({ hostname, port })) {
await handler(req);
}
}
if (import.meta.main) {
const usage_string = `%cDocuraptor%c (${import.meta.url})
%cStart documentation server:%c
$ docuraptor [--port=<port>] [--hostname=<hostname>]
[--skip-browser] [--private] [--builtin | <url>]
Opens the selected module or,
if the module specifier is omitted, the documentation index,
in the system browser.
Listens on 127.0.0.1:8709 by default.
%cAdditionally requires network access for hostname:port.%c
%cGenerate HTML documentation:%c
$ docuraptor --generate [--out=<output dir>] [--index=<index file>]
[--dependencies] [--private] <url>...
Writes the documentation of the selected modules
to the output directory, defaulting to the
current working directory.
With the dependencies flag set documentation is also
generated for all modules dependet upon.
Writes an index of all generated documentation
to the index file, defaulting to %cindex.html%c.
%cAdditionally requires write access to the output directory.%c
%cAll functions require allow-run and read access to the Deno cache.%c
The system browser can be overwritten with the
DOCURAPTOR_BROWSER and BROWSER environment variables.
%cRequires allow-env.%c`;
const usage_css = [
"font-weight: bold",
"",
"text-decoration: underline;",
"",
"font-style: italic;",
"",
"text-decoration: underline;",
"",
"font-style: italic;",
"",
"font-style: italic;",
"",
"font-style: italic;",
"",
"font-style: italic;",
"",
];
const { help, generate } = argsParse(Deno.args, {
boolean: ["help", "generate"],
});
if (help) {
console.log(usage_string, ...usage_css);
Deno.exit(0);
}
await initialize();
if (generate) {
mainGenerate();
} else {
mainServer();
}
}