-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.ts
425 lines (358 loc) · 9.61 KB
/
main.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
import xss from 'xss';
import { Marked } from 'marked';
import { load } from 'std/dotenv/mod.ts';
import { resolve } from 'std/path/mod.ts';
import { walk } from 'std/fs/mod.ts';
import { Router } from './router.ts';
import { Paste, storage } from './storage.ts';
import {
deletePage,
editPage,
errorPage,
guidePage,
homePage,
pastePage,
} from './templates.ts';
interface TocItem {
level: number;
text: string;
anchor: string;
subitems: TocItem[];
}
await load({ export: true });
const SERVER_PORT = Deno.env.get('SERVER_PORT') ?? 8000;
const STATIC_ROOT = resolve('./static');
const FILES = new Map<string, string>();
const MIMES: Record<string, string> = {
'js': 'text/javascript',
'css': 'text/css',
'ico': 'image/vnd.microsoft.icon',
};
const XSS_OPTIONS = {
whiteList: {
...xss.whiteList,
// allow heading elements to have `id=` attributes
h1: ['id'],
h2: ['id'],
h3: ['id'],
h4: ['id'],
h5: ['id'],
h6: ['id'],
input: ['disabled', 'type', 'checked']
},
};
for await (const file of walk(STATIC_ROOT)) {
if (file.isFile) {
FILES.set('/' + file.name.normalize(), file.path);
}
}
const generateId = uid();
const app = new Router();
app.get('*', async (req) => {
const url = new URL(req.url);
const filepath = FILES.get(url.pathname);
if (filepath) {
const [ext] = filepath.split('.').slice(-1);
const contentType = MIMES[ext] ?? 'text/plain';
const file = await Deno.open(filepath, { read: true });
const readableStream = file.readable;
return new Response(readableStream, {
status: 200,
headers: {
'content-type': contentType,
},
});
}
});
app.get('/', () => {
return new Response(homePage(), {
status: 200,
headers: { 'content-type': 'text/html' },
});
});
app.get('/guide', async () => {
const guideMd = await Deno.readTextFile('./guide.md');
const parse = createParser();
const { html, title } = parse(guideMd, { toc: false });
return new Response(guidePage({ html, title }), {
status: 200,
headers: { 'content-type': 'text/html' },
});
});
app.get('/:id', async (_req, params) => {
let contents = '';
let status = 200;
const id = params.id as string ?? '';
const res = await storage.get(id);
if (res.value !== null) {
const parse = createParser();
const { paste } = res.value;
let { html, title } = parse(paste);
html = xss(html, XSS_OPTIONS);
if (!title) title = id;
contents = pastePage({ id, html, title });
status = 200;
} else {
contents = errorPage();
status = 404;
}
return new Response(contents, {
status,
headers: {
'content-type': 'text/html',
},
});
});
app.get('/:id/edit', async (_req, params) => {
let contents = '';
let status = 200;
const id = params.id as string ?? '';
const res = await storage.get(id);
if (res.value !== null) {
const { editCode, paste } = res.value;
const hasEditCode = Boolean(editCode);
contents = editPage({ id, paste, hasEditCode });
status = 200;
} else {
contents = errorPage();
status = 404;
}
return new Response(contents, {
status,
headers: {
'content-type': 'text/html',
},
});
});
app.get('/:id/delete', async (_req, params) => {
let contents = '';
let status = 200;
const id = params.id as string ?? '';
const res = await storage.get(id);
if (res.value !== null) {
const { editCode } = res.value;
const hasEditCode = Boolean(editCode);
contents = deletePage({ id, hasEditCode });
} else {
contents = errorPage();
status = 404;
}
return new Response(contents, {
status,
headers: {
'content-type': 'text/html',
},
});
});
app.get('/:id/raw', async (_req, params) => {
let contents = '';
let status = 200;
const id = params.id as string ?? '';
const res = await storage.get(id);
if (res.value !== null) {
const { paste } = res.value;
contents = paste;
status = 200;
} else {
contents = errorPage();
status = 404;
}
return new Response(contents, {
status,
headers: {
'content-type': 'text/plain',
},
});
});
app.post('/save', async (req) => {
let status = 302;
let contents = '';
const headers = new Headers({
'content-type': 'text/html',
});
const form = await req.formData();
const customUrl = form.get('url') as string;
const paste = form.get('paste') as string;
const slug = createSlug(customUrl);
let editCode: string | undefined = form.get('editcode') as string;
if (typeof editCode === 'string') {
editCode = editCode.trim() || undefined;
}
if (slug.length > 0) {
const res = await storage.get(slug);
if (slug === 'guide' || res.value !== null) {
status = 422;
contents = homePage({
paste,
url: customUrl,
errors: { url: `url unavailable: ${customUrl}` },
});
} else {
await storage.set(slug, { paste, editCode });
status = 302;
headers.set('location', '/' + slug.trim());
}
} else {
let id = '';
let exists = true;
for (; exists;) {
id = generateId();
exists = await storage.get(id).then(
(r) => r.value !== null,
);
}
await storage.set(id, { paste, editCode });
status = 302;
headers.set('location', '/' + id.trim());
}
return new Response(contents, {
status,
headers,
});
});
app.post('/:id/save', async (req, params) => {
let contents = '302';
let status = 302;
const id = params.id as string ?? '';
const form = await req.formData();
const paste = form.get('paste') as string;
let editCode: string | undefined = form.get('editcode') as string;
if (typeof editCode === 'string') {
editCode = editCode.trim() || undefined;
}
const headers = new Headers({
'content-type': 'text/html',
});
if (id.trim().length === 0) {
headers.set('location', '/');
} else {
const res = await storage.get(id);
const existing = res.value as Paste;
const hasEditCode = Boolean(existing.editCode);
if (
hasEditCode &&
existing.editCode !== editCode
) {
// editCode mismatch
status = 400;
contents = editPage({
id,
paste,
hasEditCode,
errors: { editCode: 'invalid edit code' },
});
} else {
await storage.set(id, { ...existing, paste });
headers.set('location', '/' + id);
}
}
return new Response(contents, {
status,
headers,
});
});
app.post('/:id/delete', async (req, params) => {
let contents = '302';
let status = 302;
const headers = new Headers({
'content-type': 'text/html',
});
const id = params.id as string ?? '';
const form = await req.formData();
let editCode: string | undefined = form.get('editcode') as string;
if (typeof editCode === 'string') {
editCode = editCode.trim() || undefined;
}
if (id.trim().length === 0) {
headers.set('location', '/');
} else {
const res = await storage.get(id);
const existing = res.value as Paste;
const hasEditCode = Boolean(existing.editCode);
if (
hasEditCode &&
existing.editCode !== editCode
) {
// editCode mismatch
status = 400;
contents = deletePage({
id,
hasEditCode,
errors: { editCode: 'invalid edit code' },
});
} else {
await storage.delete(id);
headers.set('location', '/');
}
}
return new Response(contents, {
status,
headers,
});
});
Deno.serve({ port: Number(SERVER_PORT) }, app.handler.bind(app));
function createParser() {
const tocItems: TocItem[] = [];
const renderer = {
heading(text: string, level: number) {
const anchor = createSlug(text);
const newItem = { level, text, anchor, subitems: [] };
tocItems.push(newItem);
return `<h${level} id="${anchor}"><a href="#${anchor}">${text}</a></h${level}>`;
},
};
const marked = new Marked({ renderer, breaks: true });
const parse = (markdown: string, { toc = true } = {}) => {
let html = marked.parse(markdown) as string;
const title = tocItems[0] ? tocItems[0].text : '';
if (toc) {
const tocHtml = buildToc(tocItems);
if (tocHtml) html = html.replace(/\[\[\[TOC\]\]\]/g, tocHtml);
}
return { title, html };
};
return parse;
}
function createSlug(text = '') {
const lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
const slug = lines[i].toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
if (slug.length > 0) return slug;
}
return '';
}
function uid() {
// https://github.com/lukeed/uid
// MIT License
// Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)
let IDX = 36, HEX = '';
while (IDX--) HEX += IDX.toString(36);
return () => {
let str = '', num = 6;
while (num--) str += HEX[Math.random() * 36 | 0];
return str;
};
}
function buildToc(items: TocItem[] = []) {
let html = '';
while (items.length > 0) {
html += buildNestedList(items, 1);
}
return html ? `<div class="toc">${html}</div>` : html;
}
function buildNestedList(items: TocItem[] = [], level: number) {
let html = '<ul>';
while (items.length > 0 && items[0].level === level) {
const item = items.shift();
if (item) html += `<li><a href="#${item.anchor}">${item.text}</a></li>`;
}
while (items.length > 0 && items[0].level > level) {
html += buildNestedList(items, level + 1);
}
return html + '</ul>';
}