From 3cb0972b79dd43571502f4ed782aa4bd6d1db247 Mon Sep 17 00:00:00 2001 From: Joshua Chen Date: Mon, 17 Jan 2022 08:57:06 +0800 Subject: [PATCH] refactor: use findAsyncSequential in a few places (#6377) * refactor: use findAsyncSequential in a few places * fixes * fix --- .../src/remark/transformImage/index.ts | 27 ++++++++-------- .../src/remark/transformLinks/index.ts | 13 ++++---- .../src/sidebars/generator.ts | 31 ++++++++++--------- .../src/__tests__/index.test.ts | 10 +++--- .../docusaurus/src/server/moduleShorthand.ts | 18 ++++++----- 5 files changed, 53 insertions(+), 46 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts index 6d172fddef..526a026920 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts @@ -10,6 +10,7 @@ import { posixPath, escapePath, getFileLoaderUtils, + findAsyncSequential, } from '@docusaurus/utils'; import visit from 'unist-util-visit'; import path from 'path'; @@ -76,20 +77,20 @@ async function getImageAbsolutePath( } else if (path.isAbsolute(imagePath)) { // absolute paths are expected to exist in the static folder const possiblePaths = staticDirs.map((dir) => path.join(dir, imagePath)); - // eslint-disable-next-line no-restricted-syntax - for (const possiblePath of possiblePaths) { - const imageFilePath = possiblePath; - if (await fs.pathExists(imageFilePath)) { - return imageFilePath; - } - } - throw new Error( - `Image ${possiblePaths - .map((p) => toMessageRelativeFilePath(p)) - .join(' or ')} used in ${toMessageRelativeFilePath( - filePath, - )} not found.`, + const imageFilePath = await findAsyncSequential( + possiblePaths, + fs.pathExists, ); + if (!imageFilePath) { + throw new Error( + `Image ${possiblePaths + .map((p) => toMessageRelativeFilePath(p)) + .join(' or ')} used in ${toMessageRelativeFilePath( + filePath, + )} not found.`, + ); + } + return imageFilePath; } // We try to convert image urls without protocol to images with require calls // going through webpack ensures that image assets exist at build time diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts index b337185b81..8d4a9dc386 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts @@ -10,6 +10,7 @@ import { posixPath, escapePath, getFileLoaderUtils, + findAsyncSequential, } from '@docusaurus/utils'; import visit from 'unist-util-visit'; import path from 'path'; @@ -79,12 +80,12 @@ async function getAssetAbsolutePath( await ensureAssetFileExist(assetFilePath, filePath); return assetFilePath; } else if (path.isAbsolute(assetPath)) { - // eslint-disable-next-line no-restricted-syntax - for (const staticDir of staticDirs) { - const assetFilePath = path.join(staticDir, assetPath); - if (await fs.pathExists(assetFilePath)) { - return assetFilePath; - } + const assetFilePath = await findAsyncSequential( + staticDirs.map((dir) => path.join(dir, assetPath)), + fs.pathExists, + ); + if (assetFilePath) { + return assetFilePath; } } else { const assetFilePath = path.join(path.dirname(filePath), assetPath); diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars/generator.ts b/packages/docusaurus-plugin-content-docs/src/sidebars/generator.ts index e06e1d752b..acd534a993 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars/generator.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars/generator.ts @@ -15,7 +15,11 @@ import type { SidebarItemCategoryLinkConfig, } from './types'; import {sortBy, last} from 'lodash'; -import {addTrailingSlash, posixPath} from '@docusaurus/utils'; +import { + addTrailingSlash, + posixPath, + findAsyncSequential, +} from '@docusaurus/utils'; import logger from '@docusaurus/logger'; import path from 'path'; import fs from 'fs-extra'; @@ -76,17 +80,15 @@ async function readCategoryMetadataFile( throw e; } } - // eslint-disable-next-line no-restricted-syntax - for (const ext of ['.json', '.yml', '.yaml']) { - // Simpler to use only posix paths for mocking file metadata in tests - const filePath = posixPath( - path.join(categoryDirPath, `${CategoryMetadataFilenameBase}${ext}`), - ); - if (await fs.pathExists(filePath)) { - return tryReadFile(filePath); - } - } - return null; + const filePath = await findAsyncSequential( + ['.json', '.yml', '.yaml'].map((ext) => + posixPath( + path.join(categoryDirPath, `${CategoryMetadataFilenameBase}${ext}`), + ), + ), + fs.pathExists, + ); + return filePath ? tryReadFile(filePath) : null; } // Comment for this feature: https://github.com/facebook/docusaurus/issues/3464#issuecomment-818670449 @@ -154,13 +156,12 @@ export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async ({ docs.forEach((doc) => { const breadcrumb = getRelativeBreadcrumb(doc); let currentDir = treeRoot; // We walk down the file's path to generate the fs structure - // eslint-disable-next-line no-restricted-syntax - for (const dir of breadcrumb) { + breadcrumb.forEach((dir) => { if (typeof currentDir[dir] === 'undefined') { currentDir[dir] = {}; // Create new folder. } currentDir = currentDir[dir]!; // Go into the subdirectory. - } + }); currentDir[`${docIdPrefix}${doc.id}`] = null; // We've walked through the file path. Register the file in this directory. }); return treeRoot; diff --git a/packages/docusaurus-utils/src/__tests__/index.test.ts b/packages/docusaurus-utils/src/__tests__/index.test.ts index f78e5aa72a..93edef9640 100644 --- a/packages/docusaurus-utils/src/__tests__/index.test.ts +++ b/packages/docusaurus-utils/src/__tests__/index.test.ts @@ -321,11 +321,11 @@ describe('mapAsyncSequential', () => { const timeTotal = timeAfter - timeBefore; const totalTimeouts = sum(Object.values(itemToTimeout)); - expect(timeTotal).toBeGreaterThanOrEqual(totalTimeouts); + expect(timeTotal).toBeGreaterThanOrEqual(totalTimeouts - 5); expect(itemMapStartsAt['1']).toBeGreaterThanOrEqual(0); - expect(itemMapStartsAt['2']).toBeGreaterThanOrEqual(itemMapEndsAt['1']); - expect(itemMapStartsAt['3']).toBeGreaterThanOrEqual(itemMapEndsAt['2']); + expect(itemMapStartsAt['2']).toBeGreaterThanOrEqual(itemMapEndsAt['1'] - 5); + expect(itemMapStartsAt['3']).toBeGreaterThanOrEqual(itemMapEndsAt['2'] - 5); }); }); @@ -353,8 +353,8 @@ describe('findAsyncSequential', () => { expect(findFn).toHaveBeenNthCalledWith(2, '2'); const timeTotal = timeAfter - timeBefore; - expect(timeTotal).toBeGreaterThanOrEqual(100); - expect(timeTotal).toBeLessThan(150); + expect(timeTotal).toBeGreaterThanOrEqual(95); + expect(timeTotal).toBeLessThan(105); }); }); diff --git a/packages/docusaurus/src/server/moduleShorthand.ts b/packages/docusaurus/src/server/moduleShorthand.ts index fce11f32b8..37a50e5027 100644 --- a/packages/docusaurus/src/server/moduleShorthand.ts +++ b/packages/docusaurus/src/server/moduleShorthand.ts @@ -33,13 +33,17 @@ export function resolveModuleName( moduleType: 'preset' | 'theme' | 'plugin', ): string { const modulePatterns = getNamePatterns(moduleName, moduleType); - // eslint-disable-next-line no-restricted-syntax - for (const module of modulePatterns) { + const module = modulePatterns.find((m) => { try { - moduleRequire.resolve(module); - return module; - } catch (e) {} + moduleRequire.resolve(m); + return true; + } catch { + return false; + } + }); + if (!module) { + throw new Error(`Docusaurus was unable to resolve the "${moduleName}" ${moduleType}. Make sure one of the following packages are installed: +${modulePatterns.map((m) => `- ${m}`).join('\n')}`); } - throw new Error(`Docusaurus was unable to resolve the "${moduleName}" ${moduleType}. Make sure one of the following packages are installed: -${modulePatterns.map((module) => `- ${module}`).join('\n')}`); + return module; }