1 | import { SyntaxMap } from "./mapping/markdown-syntax-map";
|
2 | import { ASTNodeTypes, TxtNode } from "@textlint/ast-node-types";
|
3 | import traverse from "traverse";
|
4 | import debug0 from "debug";
|
5 | import { parseMarkdown } from "./parse-markdown";
|
6 |
|
7 | const debug = debug0("@textlint/markdown-to-ast");
|
8 |
|
9 | export { ASTNodeTypes as Syntax };
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | export function parse<T extends TxtNode>(text: string): T {
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | const hasBOM = text.charCodeAt(0) === 0xfeff;
|
24 | const textWithoutBOM = hasBOM ? text.slice(1) : text;
|
25 | const ast = parseMarkdown(textWithoutBOM);
|
26 | traverse(ast).forEach(function (node: TxtNode) {
|
27 |
|
28 | if (this.notLeaf) {
|
29 | if (node.type) {
|
30 | const replacedType = SyntaxMap[node.type as keyof typeof SyntaxMap];
|
31 | if (!replacedType) {
|
32 | debug(`replacedType : ${replacedType} , node.type: ${node.type}`);
|
33 | } else {
|
34 | node.type = replacedType;
|
35 | }
|
36 | }
|
37 |
|
38 | if (node.position) {
|
39 | const position = node.position;
|
40 | const positionCompensated = {
|
41 | start: { line: position.start.line, column: Math.max(position.start.column - 1, 0) },
|
42 | end: { line: position.end.line, column: Math.max(position.end.column - 1, 0) }
|
43 | };
|
44 | const range = [position.start.offset, position.end.offset] as [number, number];
|
45 | node.loc = positionCompensated;
|
46 | node.range = range;
|
47 | node.raw = textWithoutBOM.slice(range[0], range[1]);
|
48 |
|
49 | Object.defineProperty(node, "position", {
|
50 | enumerable: false,
|
51 | configurable: false,
|
52 | writable: false,
|
53 | value: position
|
54 | });
|
55 | }
|
56 | }
|
57 | });
|
58 | return ast as T;
|
59 | }
|