forked from duddud11/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent-loading.ts
More file actions
288 lines (256 loc) · 10.9 KB
/
content-loading.ts
File metadata and controls
288 lines (256 loc) · 10.9 KB
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
import { promises as fs } from 'fs';
import { fromHtmlIsomorphic } from 'hast-util-from-html-isomorphic'
import { hasProperty } from 'hast-util-has-property';
import { headingRank } from 'hast-util-heading-rank';
import { isElement } from 'hast-util-is-element';
import { toString } from 'hast-util-to-string';
import path from 'path';
import { serialize } from 'next-mdx-remote/serialize';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import rehypeHighlight from 'rehype-highlight';
import rehypeSlug from 'rehype-slug';
import remarkCodeExtra from 'remark-code-extra';
import { MDASTCode } from 'remark-code-extra/types';
import remarkGfm from 'remark-gfm';
import { visit } from 'unist-util-visit';
import type { Root } from 'mdast';
import type { Node } from 'unist';
import { lowlight } from 'lowlight/lib/core.js';
import http from 'highlight.js/lib/languages/http';
import linkIcon from '../node_modules/@tabler/icons/icons/link.svg';
import {
canonicalContentPath,
Content,
Frontmatter,
GraphQL,
Heading,
REST,
TableOfContents,
TableOfContentsPage,
} from './content';
async function* walk(dir: string): AsyncGenerator<string> {
for await (const d of await fs.opendir(dir)) {
const entry = path.join(dir, d.name);
if (d.isDirectory()) yield* walk(entry);
else if (d.isFile()) yield entry;
}
}
interface ParsedHttpCodeBlock {
method: string;
url: string;
headers: Headers;
body?: string;
}
function parseHttpMarkdownCode(code: string): ParsedHttpCodeBlock {
const normalized = code.replace(/\r\n/g, '\n');
const firstLineEnd = normalized.includes('\n') ? normalized.indexOf('\n') : normalized.length;
const [method, url] = normalized
.slice(0, firstLineEnd)
.split(' ')
.map((s) => s.trim());
let body = undefined;
const headers = new Headers();
const lines = normalized.slice(firstLineEnd + 1).split('\n');
for (let i = 0; i < lines.length; ++i) {
const line = lines[i];
if (!line.trim()) {
body = lines
.slice(i + 1)
.join('\n')
.trim();
break;
}
const [key, value] = line.split(':').map((s) => s.trim());
headers.append(key, value);
}
return {
method,
url,
headers,
body,
};
}
let cachedContent: Map<string, Content> | undefined = undefined;
// Returns a map where each key is a path, such as "/" or "/fusion-feed".
export async function getAllContent(): Promise<Map<string, Content>> {
// This function can be expensive, so memoize it in production.
if (process.env.NODE_ENV === 'production' && cachedContent) {
return cachedContent;
}
const ret = new Map();
for await (const p of walk('./content')) {
if (!p.endsWith('.mdx')) {
continue;
}
const body = await fs.readFile(p, 'utf8');
let contentPath = p.slice(8, p.length - 4);
let isIndex = false;
if (contentPath.endsWith('/index') || contentPath === 'index') {
contentPath = contentPath.slice(0, contentPath.length - 5);
isIndex = true;
}
contentPath = canonicalContentPath(contentPath);
const contentPathBase = isIndex ? contentPath : contentPath.slice(0, contentPath.lastIndexOf('/'));
const graphql: GraphQL[] = [];
const links = new Set<string>();
lowlight.registerLanguage('http', http);
const rest: REST[] = [];
const markdownLinkPlugin = () => {
return (tree: Root) => {
visit(tree, (node) => {
if (node.type === 'link') {
// make relative content links absolute
if (node.url.indexOf('://') < 0 && node.url[0] !== '/' && !node.url.startsWith('mailto:')) {
node.url = canonicalContentPath(contentPathBase + '/' + node.url);
}
links.add(node.url);
}
});
};
};
const headings: Heading[] = [];
const headingPlugin = () => {
return (tree: Root) => {
visit(tree, (node: Node) => {
if (isElement(node)) {
const rank = headingRank(node);
if (rank && node.properties && hasProperty(node, 'id') && typeof node.properties.id === 'string') {
headings.push({
id: node.properties.id,
text: toString(node),
rank,
});
}
}
});
};
};
const source = await serialize(body, {
mdxOptions: {
remarkPlugins: [
remarkGfm,
[
remarkCodeExtra,
{
transform: (node: MDASTCode) => {
if (node.lang === 'gql' || node.lang === 'graphql') {
if (node.meta !== 'v1' && node.meta !== 'v2') {
throw new Error('GraphQL code must be marked as V1 or V2.');
}
const version = node.meta;
const document = node.value;
graphql.push({
document,
version,
});
return {
transform: (node: any) => {
node.type = 'mdxJsxFlowElement';
node.name = `GraphQLExample`;
node.attributes = [{
type: 'mdxJsxAttribute',
name: 'document',
value: document,
}, {
type: 'mdxJsxAttribute',
name: 'version',
value: version,
}];
node.children = [];
},
};
} else if (node.lang === 'http' || node.lang === 'https') {
const { method, url, headers, body } = parseHttpMarkdownCode(node.value);
const [path, params] = url.split('?');
if (path === '/v1/graphql' || path === '/v2/graphql') {
// This is actually a GraphQL request.
const version = path === '/v1/graphql' ? 'v1' : 'v2';
if (method === 'GET') {
graphql.push({
document: new URLSearchParams(params).get('query') || '',
version,
});
} else if (headers.get('Content-Type') === 'application/json') {
graphql.push({
document: JSON.parse(body || '').query || '',
version,
});
} else if (headers.get('Content-Type') === 'application/graphql') {
graphql.push({
document: body || '',
version,
});
} else {
throw new Error('Invalid HTTP request for GraphQL v2.');
}
return null;
}
if (method !== 'GET' && method !== 'POST') {
throw new Error('Only GET and POST requests are supported.');
}
rest.push({
method,
url,
body: body,
});
}
return null;
},
},
],
markdownLinkPlugin,
],
rehypePlugins: [
rehypeHighlight,
rehypeSlug,
[rehypeAutolinkHeadings, {
properties: {
className: 'heading-anchor',
},
content: fromHtmlIsomorphic(`<img src="${linkIcon.src}" />`, {fragment: true}).children
}],
headingPlugin,
],
},
parseFrontmatter: true,
});
ret.set(contentPath, {
frontmatter: source.frontmatter as unknown as Frontmatter,
graphql,
headings,
rest,
links,
source,
path: contentPath,
filePath: p,
});
}
cachedContent = ret;
return ret;
}
function tocPagesForContent(allContent: Map<string, Content>, content: Content): TableOfContentsPage[] {
return (content.frontmatter.children || []).map((c) => {
const childPath = canonicalContentPath(content.path + '/' + c);
const childContent = allContent.get(childPath);
if (!childContent) {
throw new Error(`path for child does not exist: ${childPath}`);
}
return {
children: tocPagesForContent(allContent, childContent),
path: childPath,
title: childContent.frontmatter.title,
};
});
}
export async function getProductTableOfContents(path: string): Promise<TableOfContents | null> {
const allContent = await getAllContent();
const content = allContent.get(canonicalContentPath(path));
if (!content) {
return null;
}
return {
title: content.frontmatter.title,
pages: tocPagesForContent(allContent, content),
path: canonicalContentPath(path),
};
}