forked from facebook/docusaurus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
290 lines (261 loc) · 8.74 KB
/
Copy pathindex.ts
File metadata and controls
290 lines (261 loc) · 8.74 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
289
290
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import path from 'path';
import fs from 'fs-extra';
import {
normalizeUrl,
docuHash,
aliasedSitePath,
getContentPathList,
posixPath,
addTrailingPathSeparator,
createAbsoluteFilePathMatcher,
resolveMarkdownLinkPathname,
DEFAULT_PLUGIN_ID,
} from '@docusaurus/utils';
import {getTagsFilePathsToWatch} from '@docusaurus/utils-validation';
import {createMDXLoaderRule} from '@docusaurus/mdx-loader';
import {resolveSidebarPathOption} from './sidebars';
import {CategoryMetadataFilenamePattern} from './sidebars/generator';
import {type DocEnv} from './docs';
import {
getVersionFromSourceFilePath,
readVersionsMetadata,
toFullVersion,
} from './versions/version';
import cliDocs from './cli';
import {VERSIONS_JSON_FILE} from './constants';
import {toGlobalDataVersion} from './globalData';
import {
translateLoadedContent,
getLoadedContentTranslationFiles,
} from './translations';
import {createAllRoutes} from './routes';
import {createContentHelpers} from './contentHelpers';
import {loadVersion} from './versions/loadVersion';
import type {
PluginOptions,
VersionMetadata,
DocFrontMatter,
LoadedContent,
} from '@docusaurus/plugin-content-docs';
import type {LoadContext, Plugin} from '@docusaurus/types';
import type {FullVersion} from './types';
import type {RuleSetRule} from 'webpack';
// MDX loader is not 100% deterministic, leading to cache invalidation issue
// This permits to invalidate the MDX loader cache entries when content changes
// Problem documented here: https://github.com/facebook/docusaurus/pull/10934
// TODO this is not a perfect solution, find better?
async function createMdxLoaderDependencyFile({
dataDir,
options,
versionsMetadata,
}: {
dataDir: string;
options: PluginOptions;
versionsMetadata: VersionMetadata[];
}): Promise<string | undefined> {
// Disabled for unit tests, the side effect produces infinite watch loops
// TODO find a better way :/
if (process.env.NODE_ENV === 'test') {
return undefined;
}
const filePath = path.join(dataDir, '__mdx-loader-dependency.json');
// the cache is invalidated whenever this file content changes
const fileContent = {
options,
versionsMetadata,
};
await fs.ensureDir(dataDir);
await fs.writeFile(filePath, JSON.stringify(fileContent));
return filePath;
}
export default async function pluginContentDocs(
context: LoadContext,
options: PluginOptions,
): Promise<Plugin<LoadedContent>> {
const {siteDir, generatedFilesDir, baseUrl, siteConfig} = context;
// Mutate options to resolve sidebar path according to siteDir
options.sidebarPath = resolveSidebarPathOption(siteDir, options.sidebarPath);
const versionsMetadata = await readVersionsMetadata({context, options});
const pluginId = options.id;
const pluginDataDirRoot = path.join(
generatedFilesDir,
'docusaurus-plugin-content-docs',
);
const dataDir = path.join(pluginDataDirRoot, pluginId);
// TODO Docusaurus v4 breaking change
// module aliasing should be automatic
// we should never find local absolute FS paths in the codegen registry
const aliasedSource = (source: string) =>
`~docs/${posixPath(path.relative(pluginDataDirRoot, source))}`;
// TODO env should be injected into all plugins
const env = process.env.NODE_ENV as DocEnv;
const contentHelpers = createContentHelpers();
async function createDocsMDXLoaderRule(): Promise<RuleSetRule> {
const {
rehypePlugins,
remarkPlugins,
recmaPlugins,
beforeDefaultRehypePlugins,
beforeDefaultRemarkPlugins,
} = options;
const contentDirs = versionsMetadata
.flatMap(getContentPathList)
// Trailing slash is important, see https://github.com/facebook/docusaurus/pull/3970
.map(addTrailingPathSeparator);
return createMDXLoaderRule({
include: contentDirs,
options: {
dependencies: [
await createMdxLoaderDependencyFile({
dataDir,
options,
versionsMetadata,
}),
].filter((d): d is string => typeof d === 'string'),
useCrossCompilerCache: siteConfig.future.faster.mdxCrossCompilerCache,
admonitions: options.admonitions,
remarkPlugins,
rehypePlugins,
recmaPlugins,
beforeDefaultRehypePlugins,
beforeDefaultRemarkPlugins,
staticDirs: siteConfig.staticDirectories.map((dir) =>
path.resolve(siteDir, dir),
),
siteDir,
isMDXPartial: createAbsoluteFilePathMatcher(
options.exclude,
contentDirs,
),
metadataPath: (mdxPath: string) => {
// Note that metadataPath must be the same/in-sync as
// the path from createData for each MDX.
const aliasedPath = aliasedSitePath(mdxPath, siteDir);
const metadataSource = contentHelpers.getMetadataSource(aliasedPath);
return path.join(dataDir, `${docuHash(metadataSource)}.json`);
},
// createAssets converts relative paths to require() calls
createAssets: ({frontMatter}: {frontMatter: DocFrontMatter}) => ({
image: frontMatter.image,
}),
markdownConfig: siteConfig.markdown,
resolveMarkdownLink: ({linkPathname, sourceFilePath}) => {
const version = getVersionFromSourceFilePath(
sourceFilePath,
versionsMetadata,
);
return resolveMarkdownLinkPathname(linkPathname, {
sourceFilePath,
sourceToPermalink: contentHelpers.sourceToPermalink,
siteDir,
contentPaths: version,
});
},
},
});
}
const docsMDXLoaderRule = await createDocsMDXLoaderRule();
return {
name: 'docusaurus-plugin-content-docs',
extendCli(cli) {
const isDefaultPluginId = pluginId === DEFAULT_PLUGIN_ID;
// Need to create one distinct command per plugin instance
// otherwise 2 instances would try to execute the command!
const command = isDefaultPluginId
? 'docs:version'
: `docs:version:${pluginId}`;
const commandDescription = isDefaultPluginId
? 'Tag a new docs version'
: `Tag a new docs version (${pluginId})`;
cli
.command(command)
.arguments('<version>')
.description(commandDescription)
.action((version: unknown) =>
cliDocs.cliDocsVersionCommand(version, options, context),
);
},
getTranslationFiles({content}) {
return getLoadedContentTranslationFiles(content);
},
getPathsToWatch() {
function getVersionPathsToWatch(version: VersionMetadata): string[] {
const result = [
...options.include.flatMap((pattern) =>
getContentPathList(version).map(
(docsDirPath) => `${docsDirPath}/${pattern}`,
),
),
...getTagsFilePathsToWatch({
contentPaths: version,
tags: options.tags,
}),
`${version.contentPath}/**/${CategoryMetadataFilenamePattern}`,
];
if (typeof version.sidebarFilePath === 'string') {
result.unshift(version.sidebarFilePath);
}
return result;
}
return versionsMetadata.flatMap(getVersionPathsToWatch);
},
async loadContent() {
return {
loadedVersions: await Promise.all(
versionsMetadata.map((versionMetadata) =>
loadVersion({
context,
options,
env,
versionMetadata,
}),
),
),
};
},
translateContent({content, translationFiles}) {
return translateLoadedContent(content, translationFiles);
},
async contentLoaded({content, actions}) {
contentHelpers.updateContent(content);
const versions: FullVersion[] = content.loadedVersions.map(toFullVersion);
await createAllRoutes({
baseUrl,
versions,
options,
actions,
aliasedSource,
});
actions.setGlobalData({
path: normalizeUrl([baseUrl, options.routeBasePath]),
versions: versions.map(toGlobalDataVersion),
breadcrumbs: options.breadcrumbs,
});
},
configureWebpack() {
return {
ignoreWarnings: [
// Suppress warnings about non-existing of versions file.
(e) =>
e.message.includes("Can't resolve") &&
e.message.includes(VERSIONS_JSON_FILE),
],
resolve: {
alias: {
'~docs': pluginDataDirRoot,
},
},
module: {
rules: [docsMDXLoaderRule],
},
};
},
};
}
export {validateOptions} from './options';