/
index.ts
444 lines (402 loc) · 12.2 KB
/
index.ts
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/**
* 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 chalk from 'chalk';
import path from 'path';
import {createHash} from 'crypto';
import {camelCase, mapValues} from 'lodash';
import escapeStringRegexp from 'escape-string-regexp';
import fs from 'fs-extra';
import {URL} from 'url';
import {
ReportingSeverity,
TranslationFileContent,
TranslationFile,
} from '@docusaurus/types';
import resolvePathnameUnsafe from 'resolve-pathname';
import {posixPath as posixPathImport} from './posixPath';
import {simpleHash, docuHash} from './hashUtils';
import {normalizeUrl} from './normalizeUrl';
export * from './mdxUtils';
export * from './normalizeUrl';
export * from './tags';
export const posixPath = posixPathImport;
export * from './codeTranslationsUtils';
export * from './markdownParser';
export * from './markdownLinks';
export * from './escapePath';
export {md5Hash, simpleHash, docuHash} from './hashUtils';
export {
Globby,
GlobExcludeDefault,
createMatcher,
createAbsoluteFilePathMatcher,
} from './globUtils';
const fileHash = new Map();
export async function generate(
generatedFilesDir: string,
file: string,
content: string,
skipCache: boolean = process.env.NODE_ENV === 'production',
): Promise<void> {
const filepath = path.join(generatedFilesDir, file);
if (skipCache) {
await fs.ensureDir(path.dirname(filepath));
await fs.writeFile(filepath, content);
return;
}
let lastHash = fileHash.get(filepath);
// If file already exists but its not in runtime cache yet,
// we try to calculate the content hash and then compare
// This is to avoid unnecessary overwriting and we can reuse old file.
if (!lastHash && fs.existsSync(filepath)) {
const lastContent = await fs.readFile(filepath, 'utf8');
lastHash = createHash('md5').update(lastContent).digest('hex');
fileHash.set(filepath, lastHash);
}
const currentHash = createHash('md5').update(content).digest('hex');
if (lastHash !== currentHash) {
await fs.ensureDir(path.dirname(filepath));
await fs.writeFile(filepath, content);
fileHash.set(filepath, currentHash);
}
}
export function objectWithKeySorted<T>(
obj: Record<string, T>,
): Record<string, T> {
// https://github.com/lodash/lodash/issues/1459#issuecomment-460941233
return Object.keys(obj)
.sort()
.reduce((acc: Record<string, T>, key: string) => {
acc[key] = obj[key];
return acc;
}, {});
}
const indexRE = /(^|.*\/)index\.(md|mdx|js|jsx|ts|tsx)$/i;
const extRE = /\.(md|mdx|js|jsx|ts|tsx)$/;
/**
* Convert filepath to url path.
* Example: 'index.md' -> '/', 'foo/bar.js' -> '/foo/bar',
*/
export function fileToPath(file: string): string {
if (indexRE.test(file)) {
return file.replace(indexRE, '/$1');
}
return `/${file.replace(extRE, '').replace(/\\/g, '/')}`;
}
export function encodePath(userpath: string): string {
return userpath
.split('/')
.map((item) => encodeURIComponent(item))
.join('/');
}
/**
* Convert first string character to the upper case.
* E.g: docusaurus -> Docusaurus
*/
export function upperFirst(str: string): string {
return str ? str.charAt(0).toUpperCase() + str.slice(1) : '';
}
/**
* Generate unique React Component Name.
* E.g: /foo-bar -> FooBar096
*/
export function genComponentName(pagePath: string): string {
if (pagePath === '/') {
return 'index';
}
const pageHash = docuHash(pagePath);
return upperFirst(camelCase(pageHash));
}
// When you want to display a path in a message/warning/error,
// it's more convenient to:
// - make it relative to cwd()
// - convert to posix (ie not using windows \ path separator)
// This way, Jest tests can run more reliably on any computer/CI
// on both Unix/Windows
// For Windows users this is not perfect (as they see / instead of \) but it's probably good enough
export function toMessageRelativeFilePath(filePath: string): string {
return posixPath(path.relative(process.cwd(), filePath));
}
const chunkNameCache = new Map();
/**
* Generate unique chunk name given a module path.
*/
export function genChunkName(
modulePath: string,
prefix?: string,
preferredName?: string,
shortId: boolean = process.env.NODE_ENV === 'production',
): string {
let chunkName: string | undefined = chunkNameCache.get(modulePath);
if (!chunkName) {
if (shortId) {
chunkName = simpleHash(modulePath, 8);
} else {
let str = modulePath;
if (preferredName) {
const shortHash = simpleHash(modulePath, 3);
str = `${preferredName}${shortHash}`;
}
const name = str === '/' ? 'index' : docuHash(str);
chunkName = prefix ? `${prefix}---${name}` : name;
}
chunkNameCache.set(modulePath, chunkName);
}
return chunkName;
}
// Too dynamic
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
export function idx(target: any, keyPaths?: string | (string | number)[]): any {
return (
target &&
keyPaths &&
(Array.isArray(keyPaths)
? keyPaths.reduce((obj, key) => obj && obj[key], target)
: target[keyPaths])
);
}
/**
* Given a filepath and dirpath, get the first directory.
*/
export function getSubFolder(file: string, refDir: string): string | null {
const separator = escapeStringRegexp(path.sep);
const baseDir = escapeStringRegexp(path.basename(refDir));
const regexSubFolder = new RegExp(
`${baseDir}${separator}(.*?)${separator}.*`,
);
const match = regexSubFolder.exec(file);
return match && match[1];
}
/**
* Alias filepath relative to site directory, very useful so that we
* don't expose user's site structure.
* Example: some/path/to/website/docs/foo.md -> @site/docs/foo.md
*/
export function aliasedSitePath(filePath: string, siteDir: string): string {
const relativePath = posixPath(path.relative(siteDir, filePath));
// Cannot use path.join() as it resolves '../' and removes
// the '@site'. Let webpack loader resolve it.
return `@site/${relativePath}`;
}
export function getEditUrl(
fileRelativePath: string,
editUrl?: string,
): string | undefined {
return editUrl
? normalizeUrl([editUrl, posixPath(fileRelativePath)])
: undefined;
}
export function isValidPathname(str: string): boolean {
if (!str.startsWith('/')) {
return false;
}
try {
// weird, but is there a better way?
const parsedPathname = new URL(str, 'https://domain.com').pathname;
return parsedPathname === str || parsedPathname === encodeURI(str);
} catch (e) {
return false;
}
}
// resolve pathname and fail fast if resolution fails
export function resolvePathname(to: string, from?: string): string {
return resolvePathnameUnsafe(to, from);
}
export function addLeadingSlash(str: string): string {
return str.startsWith('/') ? str : `/${str}`;
}
export function addTrailingPathSeparator(str: string): string {
return str.endsWith(path.sep) ? str : `${str}${path.sep}`;
}
// TODO deduplicate: also present in @docusaurus/utils-common
export function addTrailingSlash(str: string): string {
return str.endsWith('/') ? str : `${str}/`;
}
export function removeTrailingSlash(str: string): string {
return removeSuffix(str, '/');
}
export function removeSuffix(str: string, suffix: string): string {
if (suffix === '') {
return str; // always returns "" otherwise!
}
return str.endsWith(suffix) ? str.slice(0, -suffix.length) : str;
}
export function removePrefix(str: string, prefix: string): string {
return str.startsWith(prefix) ? str.slice(prefix.length) : str;
}
export function getElementsAround<T extends unknown>(
array: T[],
aroundIndex: number,
): {
next: T | undefined;
previous: T | undefined;
} {
const min = 0;
const max = array.length - 1;
if (aroundIndex < min || aroundIndex > max) {
throw new Error(
`Valid "aroundIndex" for array (of size ${array.length}) are between ${min} and ${max}, but you provided ${aroundIndex}.`,
);
}
const previous = aroundIndex === min ? undefined : array[aroundIndex - 1];
const next = aroundIndex === max ? undefined : array[aroundIndex + 1];
return {previous, next};
}
export function getPluginI18nPath({
siteDir,
locale,
pluginName,
pluginId = 'default', // TODO duplicated constant
subPaths = [],
}: {
siteDir: string;
locale: string;
pluginName: string;
pluginId?: string | undefined;
subPaths?: string[];
}): string {
return path.join(
siteDir,
'i18n',
// namespace first by locale: convenient to work in a single folder for a translator
locale,
// Make it convenient to use for single-instance
// ie: return "docs", not "docs-default" nor "docs/default"
`${pluginName}${
// TODO duplicate constant :(
pluginId === 'default' ? '' : `-${pluginId}`
}`,
...subPaths,
);
}
export async function mapAsyncSequencial<T extends unknown, R extends unknown>(
array: T[],
action: (t: T) => Promise<R>,
): Promise<R[]> {
const results: R[] = [];
// eslint-disable-next-line no-restricted-syntax
for (const t of array) {
// eslint-disable-next-line no-await-in-loop
const result = await action(t);
results.push(result);
}
return results;
}
export async function findAsyncSequential<T>(
array: T[],
predicate: (t: T) => Promise<boolean>,
): Promise<T | undefined> {
// eslint-disable-next-line no-restricted-syntax
for (const t of array) {
// eslint-disable-next-line no-await-in-loop
if (await predicate(t)) {
return t;
}
}
return undefined;
}
// return the first folder path in which the file exists in
export async function findFolderContainingFile(
folderPaths: string[],
relativeFilePath: string,
): Promise<string | undefined> {
return findAsyncSequential(folderPaths, (folderPath) =>
fs.pathExists(path.join(folderPath, relativeFilePath)),
);
}
export async function getFolderContainingFile(
folderPaths: string[],
relativeFilePath: string,
): Promise<string> {
const maybeFolderPath = await findFolderContainingFile(
folderPaths,
relativeFilePath,
);
// should never happen, as the source was read from the FS anyway...
if (!maybeFolderPath) {
throw new Error(
`File "${relativeFilePath}" does not exist in any of these folders:\n- ${folderPaths.join(
'\n- ',
)}]`,
);
}
return maybeFolderPath;
}
export function reportMessage(
message: string,
reportingSeverity: ReportingSeverity,
): void {
switch (reportingSeverity) {
case 'ignore':
break;
case 'log':
console.log(chalk.bold.blue('info ') + chalk.blue(message));
break;
case 'warn':
console.warn(chalk.bold.yellow('warn ') + chalk.yellow(message));
break;
case 'error':
console.error(chalk.bold.red('error ') + chalk.red(message));
break;
case 'throw':
throw new Error(message);
default:
throw new Error(
`Unexpected "reportingSeverity" value: ${reportingSeverity}.`,
);
}
}
export function mergeTranslations(
contents: TranslationFileContent[],
): TranslationFileContent {
return contents.reduce((acc, content) => {
return {...acc, ...content};
}, {});
}
export function getSwizzledComponent(
componentPath: string,
): string | undefined {
const swizzledComponentPath = path.resolve(
process.cwd(),
'src',
componentPath,
);
return fs.existsSync(swizzledComponentPath)
? swizzledComponentPath
: undefined;
}
// Useful to update all the messages of a translation file
// Used in tests to simulate translations
export function updateTranslationFileMessages(
translationFile: TranslationFile,
updateMessage: (message: string) => string,
): TranslationFile {
return {
...translationFile,
content: mapValues(translationFile.content, (translation) => ({
...translation,
message: updateMessage(translation.message),
})),
};
}
// Input: ## Some heading {#some-heading}
// Output: {text: "## Some heading", id: "some-heading"}
export function parseMarkdownHeadingId(heading: string): {
text: string;
id?: string;
} {
const customHeadingIdRegex = /^(.*?)\s*\{#([\w-]+)\}$/;
const matches = customHeadingIdRegex.exec(heading);
if (matches) {
return {
text: matches[1],
id: matches[2],
};
} else {
return {text: heading, id: undefined};
}
}