forked from wundergraph/wundergraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearchPlugin.mjs
156 lines (133 loc) · 3.85 KB
/
searchPlugin.mjs
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
import Markdoc from '@markdoc/markdoc';
import { readFile } from 'fs/promises';
import { globby } from 'globby';
import yaml from 'js-yaml';
import { default as webpack } from 'webpack';
const sources = webpack.sources;
const pluginName = 'SearchPlugin';
const isDev = process.env.NODE_ENV !== 'production';
function generateID(children, attributes) {
if (attributes.id && typeof attributes.id === 'string') {
return attributes.id;
}
return children
.filter((child) => typeof child === 'string')
.join(' ')
.replace(/[?]/g, '')
.replace(/\s+/g, '-')
.toLowerCase();
}
function getTitle(children) {
return children.filter((child) => typeof child === 'string').join(' ');
}
async function parseDocs() {
const allDocs = [];
const allFilesOps = [];
const paths = await globby(['src/pages/docs/**/*.md']);
for (const path of paths) {
allFilesOps.push(await readFile(path, 'utf8'));
}
const allFiles = await Promise.all(allFilesOps);
for (let i = 0; i < allFiles.length; i++) {
const filePath = paths[i];
const ast = Markdoc.parse(allFiles[i]);
const frontmatter = ast.attributes.frontmatter ? yaml.load(ast.attributes.frontmatter) : {};
const transformedContent = Markdoc.transform(ast, {
variables: {
variables: {
markdoc: {
frontmatter,
},
},
},
});
let route = filePath.replace(/^src\/pages\/docs\//, '/docs/').replace(/\.md$/, '');
if (route.endsWith('/index')) {
const indexPosition = route.lastIndexOf('/index');
if (indexPosition !== -1) {
route = route.substring(0, indexPosition);
}
}
const structuredContent = {};
let prevHeadingNode;
let textContent = '';
function extract(children) {
children.forEach((node) => {
if (typeof node === 'string') {
textContent += node;
} else if (node.name === 'h2' || node.name === 'h1') {
textContent = textContent
.trim()
.split('\n')
.map((line) => line.trim())
.join('\n');
let key = '';
if (prevHeadingNode) {
const { children, attributes } = prevHeadingNode;
key = generateID(children, attributes) + '#' + getTitle(children);
}
structuredContent[key] = textContent;
prevHeadingNode = node;
textContent = '';
} else if (node.children != undefined && node.name !== 'pre') {
extract(node.children);
}
});
}
extract([
...transformedContent.children,
{
name: 'h1',
attributes: {},
children: [`${frontmatter.title}`],
},
]);
const doc = {
title: `${frontmatter.title}`,
route,
data: structuredContent,
};
allDocs.push(doc);
}
return allDocs;
}
export class SearchPlugin {
apply(compiler) {
compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
compilation.hooks.processAssets.tapAsync(
{
name: pluginName,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
},
async (_, callback) => {
const indexFiles = {};
const allDocs = await parseDocs();
allDocs.forEach((doc, index) => {
const { title, data, route } = doc;
const indexFilename = `search-data.json`;
if (indexFiles[indexFilename] === undefined) {
indexFiles[indexFilename] = '{';
}
if (indexFiles[indexFilename] !== '{') {
indexFiles[indexFilename] += ',';
}
indexFiles[indexFilename] += `${JSON.stringify(route)}:{"title":${JSON.stringify(
title
)},"data":${JSON.stringify(data)}}`;
});
for (const [file, content] of Object.entries(indexFiles)) {
const filename = (isDev ? '../static/chunks/' : '../../static/chunks/') + file;
const source = new sources.RawSource(content + '}');
const existingAsset = compilation.getAsset(filename);
if (existingAsset) {
compilation.updateAsset(filename, source);
} else {
compilation.emitAsset(filename, source);
}
}
callback();
}
);
});
}
}