UNPKG

3.06 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.parse = exports.Syntax = void 0;
7const markdown_syntax_map_1 = require("./mapping/markdown-syntax-map");
8const ast_node_types_1 = require("@textlint/ast-node-types");
9Object.defineProperty(exports, "Syntax", { enumerable: true, get: function () { return ast_node_types_1.ASTNodeTypes; } });
10const traverse_1 = __importDefault(require("traverse"));
11const debug_1 = __importDefault(require("debug"));
12const parse_markdown_1 = require("./parse-markdown");
13const debug = debug_1.default("@textlint/markdown-to-ast");
14/**
15 * parse markdown text and return ast mapped location info.
16 * @param {string} text
17 * @returns {TxtNode}
18 */
19function parse(text) {
20 // remark-parse's AST does not consider BOM
21 // AST's position does not +1 by BOM
22 // So, just trim BOM and parse it for `raw` property
23 // textlint's SourceCode also take same approach - trim BOM and check the position
24 // This means that the loading side need to consider BOM position - for example fs.readFile and text slice script.
25 // https://github.com/micromark/micromark/blob/0f19c1ac25964872a160d8b536878b125ddfe393/lib/preprocess.mjs#L29-L31
26 const hasBOM = text.charCodeAt(0) === 0xfeff;
27 const textWithoutBOM = hasBOM ? text.slice(1) : text;
28 const ast = parse_markdown_1.parseMarkdown(textWithoutBOM);
29 traverse_1.default(ast).forEach(function (node) {
30 // eslint-disable-next-line no-invalid-this
31 if (this.notLeaf) {
32 if (node.type) {
33 const replacedType = markdown_syntax_map_1.SyntaxMap[node.type];
34 if (!replacedType) {
35 debug(`replacedType : ${replacedType} , node.type: ${node.type}`);
36 }
37 else {
38 node.type = replacedType;
39 }
40 }
41 // map `range`, `loc` and `raw` to node
42 if (node.position) {
43 const position = node.position;
44 const positionCompensated = {
45 start: { line: position.start.line, column: Math.max(position.start.column - 1, 0) },
46 end: { line: position.end.line, column: Math.max(position.end.column - 1, 0) }
47 };
48 const range = [position.start.offset, position.end.offset];
49 node.loc = positionCompensated;
50 node.range = range;
51 node.raw = textWithoutBOM.slice(range[0], range[1]);
52 // Compatible for https://github.com/syntax-tree/unist, but it is hidden
53 Object.defineProperty(node, "position", {
54 enumerable: false,
55 configurable: false,
56 writable: false,
57 value: position
58 });
59 }
60 }
61 });
62 return ast;
63}
64exports.parse = parse;
65//# sourceMappingURL=index.js.map
\No newline at end of file