-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathparse.ts
More file actions
81 lines (68 loc) · 2.06 KB
/
parse.ts
File metadata and controls
81 lines (68 loc) · 2.06 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
71
72
73
74
75
76
77
78
79
80
81
import mit from "markdown-it";
import type { Token } from "markdown-it/index.js";
import { sourceLocationOf, type SourceLocation } from "./sourceLocation.js";
export type ParsedLink = {
readonly target: string;
readonly content: string;
readonly sourceLocation: SourceLocation | null;
};
export type ParsedImage = {
readonly src: string;
readonly alt: string;
readonly sourceLocation: SourceLocation | null;
};
export type ParseResult = {
readonly links: readonly ParsedLink[];
readonly images: readonly ParsedImage[];
readonly trailingWhitespace: readonly SourceLocation[];
};
export const parse = (content: string): ParseResult => {
const trailingWhitespace: SourceLocation[] = [];
content.split(/\n/).forEach((line, index) => {
if (line.endsWith(" ")) {
trailingWhitespace.push({
line0: index,
column0: line.trimEnd().length,
});
}
});
const parser = mit();
const tokens = parser.parse(content, {});
const parsedLinks: ParsedLink[] = [];
const parsedImages: ParsedImage[] = [];
const scan = (tokens: Token[]) => {
tokens.forEach((token, index) => {
if (token.type === "link_open") {
const indexOfNextClose = tokens.findIndex(
(t2, i2) => i2 > index && t2.type === "link_close",
);
if (indexOfNextClose > index) {
const target = token.attrGet("href") as string;
parsedLinks.push({
target,
content: tokens
.slice(index + 1, indexOfNextClose)
.map((t) => t.content)
.join(""),
sourceLocation: sourceLocationOf(`(${target})`, content),
});
}
}
if (token.type === "image") {
const src = token.attrGet("src") as string;
parsedImages.push({
src,
alt: token.content,
sourceLocation: sourceLocationOf(`(${src})`, content),
});
}
if (token.children) scan(token.children);
});
};
scan(tokens);
return {
links: parsedLinks,
images: parsedImages,
trailingWhitespace,
};
};