UNPKG

2.12 kBJavaScriptView Raw
1'use strict'
2module.exports = mos
3
4const remark = require('@zkochan/remark')
5const remarkToc = require('@zkochan/remark-toc')
6const remarkMos = require('remark-mos')
7const visit = require('async-unist-util-visit')
8const getMarkdownMeta = require('./get-markdown-meta')
9const createMDScope = require('./create-md-scope')
10
11const defaultPlugins = [
12 require('../plugins/mos-plugin-package-json'),
13 require('../plugins/mos-plugin-installation'),
14 require('../plugins/mos-plugin-license'),
15 require('mos-plugin-shields'),
16 require('mos-plugin-example'),
17 require('mos-plugin-dependencies'),
18 require('mos-plugin-snippet'),
19]
20
21const defaultRemarkPlugins = [[remarkToc]]
22
23function mos () {
24 let mosPlugins = defaultPlugins
25 const remarkPlugins = defaultRemarkPlugins
26
27 const remarkSettings = {
28 listItemIndent: '1',
29 }
30
31 const processor = {
32 use (plugins) {
33 mosPlugins = mosPlugins.concat(plugins)
34 return processor
35 },
36 useRemarkPlugin () {
37 remarkPlugins.push(arguments)
38 return processor
39 },
40 process (md, opts) {
41 return createRemark(opts)
42 .then(remarkProcessor => {
43 if (typeof md === 'object') {
44 return visit(md, 'markdownScript', node =>
45 remarkProcessor
46 .createParser()
47 .generateMarkdown(node.code)
48 .then(children => {
49 node.children = children
50 })
51 )
52 .then(() => remarkProcessor.process(md, remarkSettings))
53 }
54 return remarkProcessor.process(md, remarkSettings)
55 })
56 .then(res => res.result)
57 },
58 }
59
60 function createRemark (opts) {
61 opts = opts || {}
62 if (!opts.filePath) throw new Error('opts.filePath is required')
63
64 return getMarkdownMeta(opts.filePath)
65 .then(markdown => createMDScope(mosPlugins, markdown))
66 .then(scope => {
67 const remarkProcessor = remark().use(remarkMos, {scope})
68
69 remarkPlugins.forEach(useArgs => remarkProcessor.use.apply(remarkProcessor, useArgs))
70
71 return remarkProcessor
72 })
73 }
74
75 return processor
76}