forked from mswjs/mswjs.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
430 lines (371 loc) · 10.2 KB
/
gatsby-node.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
require('dotenv').config()
const path = require('path')
const { until } = require('@open-draft/until')
const { createApolloFetch } = require('apollo-fetch')
const { createFilePath } = require('gatsby-source-filesystem')
const { NODE_ENV, GITHUB_ACCESS_TOKEN } = process.env
const IS_DEV = NODE_ENV === 'development'
const REPO_URL = 'https://github.com/mswjs/mswjs.io'
const DOCS_BASE_PATH = 'docs'
const DOCS_PAGE_TEMPLATE = path.resolve(
__dirname,
'src/templates/docs/singlePage.tsx',
)
const DOCS_CATEGORY_TEMPLATE = path.resolve(
__dirname,
'src/templates/docs/categoryPage.tsx',
)
const fetchFromGitHub = createApolloFetch({
uri: 'https://api.github.com/graphql',
})
fetchFromGitHub.use(({ options }, next) => {
if (!options.headers) {
options.headers = {}
}
options.headers.authorization = `bearer ${GITHUB_ACCESS_TOKEN}`
next()
})
async function getContributors(pages) {
const pageObjects = pages.map(
({ node }, index) => `
page${index}: object(expression: "master") {
... on Commit {
history(path: "${node.fields.relativeFilePath}", first: 100) {
nodes {
author {
user {
id
avatarUrl(size: 100)
url
}
}
}
}
}
}
`,
)
const CONTRIBUTORS_QUERY = `
{
repository(name: "mswjs.io", owner: "mswjs") {
${pageObjects}
}
}
`
// Make a single query to the GitHub GraphQL API
// to fetch contributors to all documentation pages.
const [error, res] = await until(() =>
fetchFromGitHub({ query: CONTRIBUTORS_QUERY }),
)
if (error || res.errors || res.message) {
console.error(JSON.stringify(res, null, 2))
return []
}
const { data } = res
const contributors = Object.entries(data.repository || {}).reduce(
(acc, [verboseIndex, chunk]) => {
const pageIndex = Number(verboseIndex.replace('page', ''))
const page = pages[pageIndex]
const { nodes: allContributors } = chunk.history
const uniqueContributors = allContributors.reduce((acc, node) => {
const isUnique = acc.every(
(existingContributor) =>
existingContributor.id !== node.author.user.id,
)
if (!isUnique) {
return acc
}
return acc.concat(node.author.user)
}, [])
acc[page.node.id] = uniqueContributors
return acc
},
{},
)
console.log(
'Successfully retrieved GitHub contributors for %s pages!',
pages.length,
)
return contributors
}
exports.createPages = async ({ actions, graphql }) => {
const { errors, data } = await graphql(`
{
pages: allMdx(
filter: { frontmatter: { title: { ne: "" } } }
sort: { order: ASC, fields: [frontmatter___order] }
) {
edges {
node {
id
fileAbsolutePath
fields {
relativeFilePath
url
isHomepage
}
frontmatter {
title
displayName
description
}
wordCount {
paragraphs
}
}
}
}
}
`)
if (errors) {
console.log(errors)
return null
}
const { edges: allPages } = data.pages
const navTree = createNavTree(allPages)
// Do not fetch page contributors during development
// to prevent the GitHub access token reaching the rate limit.
const contributors = IS_DEV ? [] : await getContributors(allPages)
const [categories, pages] = allPages.reduce(
(acc, { node }) => {
const [prevCategories, prevPages] = acc
const isCategory = node.wordCount.paragraphs === null
if (isCategory) {
return [prevCategories.concat(node), prevPages]
}
return [prevCategories, prevPages.concat(node)]
},
[[], []],
)
pages.forEach((node) => {
actions.createPage({
path: node.fields.url,
component: DOCS_PAGE_TEMPLATE,
context: {
postId: node.id,
breadcrumbs: getDocumentBreadcrumbs(node, navTree),
navTree,
contributors: contributors[node.id],
},
})
})
// Populate each category node with its child nodes
// and build a hierarchical nav tree for each category.
const categoriesWithChildren = await Promise.all(
categories.map(async (node) => {
const regex = new RegExp(`^${node.fields.url}\/.+`).toString()
const { errors, data } = await graphql(`
{
allMdx(
filter: { fields: { url: { regex: "${regex}" } } }
sort: { order: ASC, fields: [frontmatter___order] }
) {
edges {
node {
fileAbsolutePath
fields {
url
}
frontmatter {
title
displayName
description
}
}
}
}
}
`)
if (errors) {
return null
}
const { edges: childPages } = data.allMdx
return [node, childPages, createNavTree(childPages)]
}),
)
categoriesWithChildren.forEach(([node, childPages, childNavTree]) => {
actions.createPage({
path: node.fields.url,
component: DOCS_CATEGORY_TEMPLATE,
context: {
categoryTitle: node.frontmatter.title,
categoryDescription: node.frontmatter.description,
childPages,
childNavTree,
breadcrumbs: getDocumentBreadcrumbs(node, navTree),
navTree,
contributors: contributors[node.id],
},
})
})
}
exports.onCreateNode = async ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (['mdx'].includes(node.internal.type.toLowerCase())) {
const postSlug = createFilePath({
node,
getNode,
basePath: DOCS_BASE_PATH,
trailingSlash: false,
})
const relativeFilePath = path.relative(__dirname, node.fileAbsolutePath)
createNodeField({
node,
name: 'relativeFilePath',
value: relativeFilePath,
})
// Reference the raw file on GitHub to allow edits
createNodeField({
node,
name: 'editUrl',
value: `${REPO_URL}/tree/master/${relativeFilePath}`,
})
createNodeField({
node,
name: 'url',
value: ['/', DOCS_BASE_PATH, '/', postSlug]
.filter(Boolean)
.join('')
.replace(/\/+/g, '/'),
})
createNodeField({
node,
name: 'isHomepage',
value: postSlug === '/',
})
}
}
//
// Utils
//
function unslugify(slug) {
return slug
.replace(/^(\d+?)-/g, '')
.replace(/^([a-z])/, (_, letter) => letter.toUpperCase())
.replace(/-([a-zA-Z])/g, (_, letter) => {
return ` ${letter.toUpperCase()}`
})
}
/**
* Returns a relative path based on the given absolute path.
*/
function getRelativePagePath(absolutePath) {
return path.relative(
path.resolve(process.cwd(), DOCS_BASE_PATH),
absolutePath,
)
}
/**
* Determines if the given filename is a root file.
*/
function isRootFile(filename) {
return /^(index|readme)\.mdx?$/i.test(filename)
}
/**
* Returns a breadcrumbs list for the given MDX node.
*/
function getDocumentBreadcrumbs(node, tree) {
let breadcrumbs = []
const { url } = node.fields
const traverseTree = (items) => {
items.forEach((chunk) => {
if (url.startsWith(chunk.url)) {
if (!chunk.isHomepage) {
breadcrumbs.push({
title: chunk.displayName || chunk.title,
url: chunk.url,
})
}
if (chunk.items) {
return traverseTree(chunk.items)
}
}
})
}
traverseTree(tree)
// If the current page is the only breadcrumb item,
// produce no breadcrumbs.
if (breadcrumbs.length == 1) {
breadcrumbs = []
}
return breadcrumbs
}
/**
* Creates a deep nested navigation tree from the given
* MDX documents list.
*/
function createNavTree(edges) {
const items = edges.map(({ node }) => ({
url: node.fields.url,
isHomepage: node.fields.isHomepage,
title: node.frontmatter.title,
displayName: node.frontmatter.displayName,
pathChunks: getRelativePagePath(node.fileAbsolutePath).split(path.sep),
filename: path.basename(node.fileAbsolutePath),
}))
function buildRecursiveTree(pages) {
return pages.reduce((tree, page) => {
let { pathChunks, filename, url, title, isHomepage } = page
const displayName = page.displayName || title
// Remove the last node in the path chunks for root pages
if (isRootFile(filename)) {
pathChunks = pathChunks.slice(0, -1)
}
if (pathChunks.length === 0) {
return tree.concat({
title,
displayName,
url,
isHomepage,
})
} else {
const targetItems = pathChunks.reduce((acc, pathSegment, index) => {
const isLastSegment = index === pathChunks.length - 1
const existingNode = acc.find((node) => {
return node.segment === pathSegment
})
if (!existingNode) {
acc.push(
Object.assign(
{},
{
title: pathSegment,
segment: pathSegment,
displayName: unslugify(pathSegment),
},
isLastSegment
? {
title,
displayName,
url,
}
: {
items: [],
},
),
)
} else if (isLastSegment) {
existingNode.url = url
return existingNode
} else if (!existingNode.items) {
existingNode.items = []
}
const nextAcc = existingNode
? existingNode.items
: acc[acc.length - 1].items
return nextAcc
}, tree)
if (targetItems && Array.isArray(targetItems)) {
targetItems.push({
title,
pathSegment,
displayName,
url,
})
}
}
return tree
}, [])
}
return buildRecursiveTree(items)
}