forked from storyblok/storyblok-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docgen.js
265 lines (228 loc) · 9.26 KB
/
docgen.js
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
const watch = require('node-watch')
const frontmatter = require('front-matter')
const path = require('path')
const fs = require('fs-extra')
const glob = require('glob')
const config = require('./dg-config')
const marked = require('marked')
const prism = require('prismjs')
const loadTechnologies = require('prismjs/components/')
marked.setOptions({
highlight(code, lang) {
loadTechnologies([lang])
return prism.highlight(code, prism.languages[lang], lang)
}
})
const args = process.argv
.slice(2)
.map(arg => arg.split('='))
.reduce((args, [value, key]) => {
args[value] = key
return args
}, {})
const Docgen = {
sections: {},
init: () => {
Docgen.generateRoutes()
Docgen.coldstart()
if (!!args.watch) {
watch(config.contentInputFolder, { filter: /\.md$/, recursive: true }, Docgen.handleFileEvent)
watch(config.contentInputFolder, { filter: /\.json$/, recursive: false }, Docgen.handleMenuEvent)
}
},
/**
* Handles all node-watch file events (remove, update)
* @param {string} event - node-watch event type; eg. 'remove' || 'change'
* @param {string} contentFilePath - path to file that triggered that event
*/
handleFileEvent: (event, contentFilePath) => {
switch (event) {
case 'remove':
// contentFilePath = /my_absolute_file/content/content-delivery/en/topics/introduction.md
// contentPath = content-delivery/en/topics/introduction
const contentPath = contentFilePath.replace(config.contentInputFolder, '').replace(path.parse(contentFilePath).ext, '')
// [ content-delivery, en, topics, introduction ]
const contentPathParts = contentPath.replace(/\\/g, '/').split('/')
// content-delivery
const origin = contentPathParts.shift()
// en
const lang = contentPathParts.shift()
// topics/introduction
const relativePath = contentPathParts.join('/')
delete Docgen.sections[origin][lang][relativePath]
Docgen.generate(origin, lang)
break
default:
const section = Docgen.load(contentFilePath)
Docgen.generate(section.origin, section.lang)
break
}
},
/**
* Handles all node-watch file events (remove, update)
* @param {string} event - node-watch event type; eg. 'remove' || 'change'
* @param {string} contentFilePath - path to file that triggered that event
*/
handleMenuEvent: (event, contentFilePath) => {
switch (event) {
case 'remove':
// ignore
return
break
default:
// [ content-delivery, en, json ]
const contentPathParts = contentFilePath.replace(config.contentInputFolder, '').split('.')
// content-delivery
const origin = contentPathParts.shift()
// en
const lang = contentPathParts.shift()
Docgen.exportMenu(origin, lang)
break
}
},
/**
* Iterates through all markdown files, loads their content
* and generates section JSONs after preparation
*/
coldstart: () => {
glob(`${config.contentInputFolder}**/*.md`, (err, files) => {
if (err) throw err
files.forEach((contentFilePath) => {
Docgen.load(contentFilePath)
})
Docgen.generateAll()
})
},
/**
* Iterate through all origins and languages to trigger
* the generate for each content file.
*/
generateAll: () => {
// content-delivery, ...
Docgen.listFoldersInFolder(config.contentInputFolder).forEach((origin) => {
// en, ...
Docgen.listFoldersInFolder(config.contentInputFolder + origin).forEach((lang) => {
// generate sections json from one language and origin
Docgen.generate(origin, lang)
})
})
},
/**
* Generates sections JSON for one origin and language combination
* @param {string} origin - first level of content folder, eg.: content-delivery, managmenet
* @param {string} lang - second level of content folder, eg.: en, de, es, it, ...
*/
generate: (origin, lang) => {
// order sections for one language and origin
Docgen.exportSections(Docgen.sections[origin][lang], origin, lang)
// copies menu to static
Docgen.exportMenu(origin, lang)
},
/**
* Exports the generated menu as JSON depending on origin and language
* @param {string} origin - first level of content folder, eg.: content-delivery, managmenet
* @param {string} lang - second level of content folder, eg.: en, de, es, it, ...
*/
exportMenu: (origin, lang) => {
fs.copySync(config.menuInputFile.replace('{origin}', origin).replace('{lang}', lang), config.menuOutputFile.replace('{origin}', origin).replace('{lang}', lang))
},
/**
* Exports the sections as JSON depending on origin and language
* @param {Array} sections - Array of section objects
* @param {string} origin - first level of content folder, eg.: content-delivery, managmenet
* @param {string} lang - second level of content folder, eg.: en, de, es, it, ...
*/
exportSections: (sections, origin, lang) => {
return fs.writeFileSync(config.sectionsOutputFile.replace('{origin}', origin).replace('{lang}', lang), JSON.stringify(sections))
},
/**
* Loads one file into Docgen.sections
* @param {string} contentFilePath - Absolute path to Content Source File, will be a *.md file containing frontmatter.
* @returns {Object} section - Object containing parsed markdown and additional information
*/
load: (contentFilePath) => {
const content = fs.readFileSync(contentFilePath, { encoding: 'utf8' })
const frontmatterContent = frontmatter(content)
const title = marked(frontmatterContent.attributes.title || '').replace('<p>', '').replace('</p>\n', '')
const areas = frontmatterContent.body.split(config.splitString)
const methodContent = Docgen.prepareTemplate(marked(areas[0] || ''))
const methodExample = Docgen.prepareTemplate(marked(areas[1] || ''))
// contentFilePath = /my_absolute_file/content/content-delivery/en/topics/introduction.md
// contentPath = content-delivery/en/topics/introduction
const contentPath = contentFilePath.replace(config.contentInputFolder, '').replace(path.parse(contentFilePath).ext, '')
// [ content-delivery, en, topics, introduction ]
const contentPathParts = contentPath.replace(/\\/g, '/').split('/')
// content-delivery
const origin = contentPathParts.shift()
// en
const lang = contentPathParts.shift()
// topics/introduction
const relativePath = contentPathParts.join('/')
// prepare data for json
let section = {
contentPath: contentPath, // content-delivery/en/topics/introduction
path: relativePath, // topics/introduction
lang: lang, // en
origin: origin, // content-delivery
title: title, // title from frontmatter
attributes: frontmatterContent.attributes, // all attributes from frontmatter
content: methodContent, // Markdown Content for left part of method section already as HTML
example: methodExample // Markdown Content for right part of method section already as HTML
}
// check if origin already exists in sections object
if (typeof Docgen.sections[origin] === 'undefined') {
Docgen.sections[origin] = {}
}
// check if language already exists in section origin
if (typeof Docgen.sections[origin][lang] === 'undefined') {
Docgen.sections[origin][lang] = {}
}
// assign data to origin, lang and relativePath combination
Docgen.sections[origin][lang][relativePath] = section
return section
},
/**
* Generate and export a routes.json which will be used by Nuxt during "nuxt generate"
*/
generateRoutes: () => {
const routes = []
Docgen.listFoldersInFolder(config.contentInputFolder).forEach((origin) => {
Docgen.listFoldersInFolder(config.contentInputFolder + origin).forEach((lang) => {
if(lang == config.defaultLanguage) {
routes.push(`/docs/api/${origin}/`)
} else {
routes.push(`/docs/api/${origin}/${lang}/`)
}
})
})
fs.writeFile(config.availableRoutesFile, JSON.stringify(routes), (err) => {
if (err) throw err
})
},
/**
* Replaces all wrapper <p> for our RequestExample component with an empty string array
* as it otherwise would be an invalid HTML because RequestExample will be rendered to a Block Type
* Element which is not allowed to be nested inside a paragraph.
* Adds a wrapper div to each <table> so we can later add overflow-y container.
* @param {string} html - HTML content from Markdown file
* @returns {string} html
*/
prepareTemplate(html) {
html = html.replace(new RegExp('<p><RequestExample', 'g'), '<RequestExample')
html = html.replace(new RegExp('</RequestExample></p>', 'g'), '</RequestExample>')
html = html.replace(new RegExp('<table>', 'g'), '<div class="table"><table>')
html = html.replace(new RegExp('</table>', 'g'), '</table></div>')
return html
},
/**
* Returns all first level subfolder names as string Array
* @param {string} folder - Path to folder you want all first level subfolders.
* @returns {Array<string>} folders - Array of folder names as string
*/
listFoldersInFolder: (folder) => {
return fs.readdirSync(folder).filter((file) => {
return fs.statSync(path.join(folder, file)).isDirectory()
})
},
}
Docgen.init()