refactor: mark all functions that import external modules as async (#6521)

This commit is contained in:
Joshua Chen 2022-01-31 13:04:45 +08:00 committed by GitHub
parent aa446b7a9c
commit c56e6194b4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 125 additions and 112 deletions

8
.gitattributes vendored
View file

@ -28,8 +28,8 @@
*.swp binary *.swp binary
*.webp binary *.webp binary
# Make GitHub not index certain files in the languages overview and minify their diff # Make GitHub not index certain files in the languages overview and/or minify their diff
# See https://github.com/github/linguist/blob/master/docs/overrides.md # See https://github.com/github/linguist/blob/master/docs/overrides.md
__fixtures__ linguist-generated __fixtures__/** linguist-generated
website linguist-documentation website/** linguist-documentation
admin linguist-documentation admin/** linguist-documentation

View file

@ -78,7 +78,7 @@ export async function migrateDocusaurusProject(
shouldMigrateMdFiles: boolean = false, shouldMigrateMdFiles: boolean = false,
shouldMigratePages: boolean = false, shouldMigratePages: boolean = false,
): Promise<void> { ): Promise<void> {
function createMigrationContext(): MigrationContext { async function createMigrationContext(): Promise<MigrationContext> {
const v1Config = importFresh(`${siteDir}/siteConfig`) as VersionOneConfig; const v1Config = importFresh(`${siteDir}/siteConfig`) as VersionOneConfig;
logger.info('Starting migration from v1 to v2...'); logger.info('Starting migration from v1 to v2...');
const partialMigrationContext = { const partialMigrationContext = {
@ -95,7 +95,7 @@ export async function migrateDocusaurusProject(
}; };
} }
const migrationContext = createMigrationContext(); const migrationContext = await createMigrationContext();
// TODO need refactor legacy, we pass migrationContext to all methods // TODO need refactor legacy, we pass migrationContext to all methods
const siteConfig = migrationContext.v1Config; const siteConfig = migrationContext.v1Config;
@ -187,7 +187,7 @@ export async function migrateDocusaurusProject(
errorCount += 1; errorCount += 1;
} }
try { try {
migratePackageFile(siteDir, deps, newDir); await migratePackageFile(siteDir, deps, newDir);
} catch (e) { } catch (e) {
logger.error( logger.error(
`Error occurred while creating package.json file for project: ${e}`, `Error occurred while creating package.json file for project: ${e}`,
@ -715,11 +715,11 @@ function migrateLatestDocs(
} }
} }
function migratePackageFile( async function migratePackageFile(
siteDir: string, siteDir: string,
deps: {[key: string]: string}, deps: {[key: string]: string},
newDir: string, newDir: string,
): void { ): Promise<void> {
const packageFile = importFresh(`${siteDir}/package.json`) as { const packageFile = importFresh(`${siteDir}/package.json`) as {
scripts?: Record<string, string>; scripts?: Record<string, string>;
dependencies?: Record<string, string>; dependencies?: Record<string, string>;

View file

@ -32,159 +32,159 @@ describe('docsVersion', () => {
sidebarCollapsible: true, sidebarCollapsible: true,
}; };
test('no version tag provided', () => { test('no version tag provided', async () => {
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
null, null,
simpleSiteDir, simpleSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: no version tag specified! Pass the version you wish to create as an argument, for example: 1.0.0."`, `"[docs]: no version tag specified! Pass the version you wish to create as an argument, for example: 1.0.0."`,
); );
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
undefined, undefined,
simpleSiteDir, simpleSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: no version tag specified! Pass the version you wish to create as an argument, for example: 1.0.0."`, `"[docs]: no version tag specified! Pass the version you wish to create as an argument, for example: 1.0.0."`,
); );
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
'', '',
simpleSiteDir, simpleSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: no version tag specified! Pass the version you wish to create as an argument, for example: 1.0.0."`, `"[docs]: no version tag specified! Pass the version you wish to create as an argument, for example: 1.0.0."`,
); );
}); });
test('version tag should not have slash', () => { test('version tag should not have slash', async () => {
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
'foo/bar', 'foo/bar',
simpleSiteDir, simpleSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: invalid version tag specified! Do not include slash (/) or backslash (\\\\). Try something like: 1.0.0."`, `"[docs]: invalid version tag specified! Do not include slash (/) or backslash (\\\\). Try something like: 1.0.0."`,
); );
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
'foo\\bar', 'foo\\bar',
simpleSiteDir, simpleSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: invalid version tag specified! Do not include slash (/) or backslash (\\\\). Try something like: 1.0.0."`, `"[docs]: invalid version tag specified! Do not include slash (/) or backslash (\\\\). Try something like: 1.0.0."`,
); );
}); });
test('version tag should not be too long', () => { test('version tag should not be too long', async () => {
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
'a'.repeat(255), 'a'.repeat(255),
simpleSiteDir, simpleSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: invalid version tag specified! Length cannot exceed 32 characters. Try something like: 1.0.0."`, `"[docs]: invalid version tag specified! Length cannot exceed 32 characters. Try something like: 1.0.0."`,
); );
}); });
test('version tag should not be a dot or two dots', () => { test('version tag should not be a dot or two dots', async () => {
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
'..', '..',
simpleSiteDir, simpleSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: invalid version tag specified! Do not name your version \\".\\" or \\"..\\". Try something like: 1.0.0."`, `"[docs]: invalid version tag specified! Do not name your version \\".\\" or \\"..\\". Try something like: 1.0.0."`,
); );
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
'.', '.',
simpleSiteDir, simpleSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: invalid version tag specified! Do not name your version \\".\\" or \\"..\\". Try something like: 1.0.0."`, `"[docs]: invalid version tag specified! Do not name your version \\".\\" or \\"..\\". Try something like: 1.0.0."`,
); );
}); });
test('version tag should be a valid pathname', () => { test('version tag should be a valid pathname', async () => {
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
'<foo|bar>', '<foo|bar>',
simpleSiteDir, simpleSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0."`, `"[docs]: invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0."`,
); );
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
'foo\x00bar', 'foo\x00bar',
simpleSiteDir, simpleSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0."`, `"[docs]: invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0."`,
); );
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
'foo:bar', 'foo:bar',
simpleSiteDir, simpleSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0."`, `"[docs]: invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0."`,
); );
}); });
test('version tag already exist', () => { test('version tag already exist', async () => {
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
'1.0.0', '1.0.0',
versionedSiteDir, versionedSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: this version already exists! Use a version tag that does not already exist."`, `"[docs]: this version already exists! Use a version tag that does not already exist."`,
); );
}); });
test('no docs file to version', () => { test('no docs file to version', async () => {
const emptySiteDir = path.join(fixtureDir, 'empty-site'); const emptySiteDir = path.join(fixtureDir, 'empty-site');
expect(() => await expect(() =>
cliDocsVersionCommand( cliDocsVersionCommand(
'1.0.0', '1.0.0',
emptySiteDir, emptySiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
), ),
).toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"[docs]: there is no docs to version!"`, `"[docs]: there is no docs to version!"`,
); );
}); });
test('first time versioning', () => { test('first time versioning', async () => {
const copyMock = jest.spyOn(fs, 'copySync').mockImplementation(); const copyMock = jest.spyOn(fs, 'copySync').mockImplementation();
const ensureMock = jest.spyOn(fs, 'ensureDirSync').mockImplementation(); const ensureMock = jest.spyOn(fs, 'ensureDirSync').mockImplementation();
const writeMock = jest.spyOn(fs, 'writeFileSync'); const writeMock = jest.spyOn(fs, 'writeFileSync');
@ -205,7 +205,12 @@ describe('docsVersion', () => {
...DEFAULT_OPTIONS, ...DEFAULT_OPTIONS,
sidebarPath: path.join(simpleSiteDir, 'sidebars.json'), sidebarPath: path.join(simpleSiteDir, 'sidebars.json'),
}; };
cliDocsVersionCommand('1.0.0', simpleSiteDir, DEFAULT_PLUGIN_ID, options); await cliDocsVersionCommand(
'1.0.0',
simpleSiteDir,
DEFAULT_PLUGIN_ID,
options,
);
expect(copyMock).toHaveBeenCalledWith( expect(copyMock).toHaveBeenCalledWith(
path.join(simpleSiteDir, options.path), path.join(simpleSiteDir, options.path),
path.join( path.join(
@ -236,7 +241,7 @@ describe('docsVersion', () => {
ensureMock.mockRestore(); ensureMock.mockRestore();
}); });
test('not the first time versioning', () => { test('not the first time versioning', async () => {
const copyMock = jest.spyOn(fs, 'copySync').mockImplementation(); const copyMock = jest.spyOn(fs, 'copySync').mockImplementation();
const ensureMock = jest.spyOn(fs, 'ensureDirSync').mockImplementation(); const ensureMock = jest.spyOn(fs, 'ensureDirSync').mockImplementation();
const writeMock = jest.spyOn(fs, 'writeFileSync'); const writeMock = jest.spyOn(fs, 'writeFileSync');
@ -257,7 +262,7 @@ describe('docsVersion', () => {
...DEFAULT_OPTIONS, ...DEFAULT_OPTIONS,
sidebarPath: path.join(versionedSiteDir, 'sidebars.json'), sidebarPath: path.join(versionedSiteDir, 'sidebars.json'),
}; };
cliDocsVersionCommand( await cliDocsVersionCommand(
'2.0.0', '2.0.0',
versionedSiteDir, versionedSiteDir,
DEFAULT_PLUGIN_ID, DEFAULT_PLUGIN_ID,
@ -293,7 +298,7 @@ describe('docsVersion', () => {
ensureMock.mockRestore(); ensureMock.mockRestore();
}); });
test('second docs instance versioning', () => { test('second docs instance versioning', async () => {
const pluginId = 'community'; const pluginId = 'community';
const copyMock = jest.spyOn(fs, 'copySync').mockImplementation(); const copyMock = jest.spyOn(fs, 'copySync').mockImplementation();
@ -317,7 +322,7 @@ describe('docsVersion', () => {
path: 'community', path: 'community',
sidebarPath: path.join(versionedSiteDir, 'community_sidebars.json'), sidebarPath: path.join(versionedSiteDir, 'community_sidebars.json'),
}; };
cliDocsVersionCommand('2.0.0', versionedSiteDir, pluginId, options); await cliDocsVersionCommand('2.0.0', versionedSiteDir, pluginId, options);
expect(copyMock).toHaveBeenCalledWith( expect(copyMock).toHaveBeenCalledWith(
path.join(versionedSiteDir, options.path), path.join(versionedSiteDir, options.path),
path.join( path.join(

View file

@ -20,7 +20,7 @@ import {loadSidebarsFile, resolveSidebarPathOption} from './sidebars';
import {DEFAULT_PLUGIN_ID} from '@docusaurus/utils'; import {DEFAULT_PLUGIN_ID} from '@docusaurus/utils';
import logger from '@docusaurus/logger'; import logger from '@docusaurus/logger';
function createVersionedSidebarFile({ async function createVersionedSidebarFile({
siteDir, siteDir,
pluginId, pluginId,
sidebarPath, sidebarPath,
@ -34,7 +34,7 @@ function createVersionedSidebarFile({
// Load current sidebar and create a new versioned sidebars file (if needed). // Load current sidebar and create a new versioned sidebars file (if needed).
// Note: we don't need the sidebars file to be normalized: it's ok to let // Note: we don't need the sidebars file to be normalized: it's ok to let
// plugin option changes to impact older, versioned sidebars // plugin option changes to impact older, versioned sidebars
const sidebars = loadSidebarsFile(sidebarPath); const sidebars = await loadSidebarsFile(sidebarPath);
// Do not create a useless versioned sidebars file if sidebars file is empty // Do not create a useless versioned sidebars file if sidebars file is empty
// or sidebars are disabled/false) // or sidebars are disabled/false)
@ -56,12 +56,12 @@ function createVersionedSidebarFile({
} }
// Tests depend on non-default export for mocking. // Tests depend on non-default export for mocking.
export function cliDocsVersionCommand( export async function cliDocsVersionCommand(
version: string | null | undefined, version: string | null | undefined,
siteDir: string, siteDir: string,
pluginId: string, pluginId: string,
options: PathOptions & SidebarOptions, options: PathOptions & SidebarOptions,
): void { ): Promise<void> {
// It wouldn't be very user-friendly to show a [default] log prefix, // It wouldn't be very user-friendly to show a [default] log prefix,
// so we use [docs] instead of [default] // so we use [docs] instead of [default]
const pluginIdLogPrefix = const pluginIdLogPrefix =
@ -127,7 +127,7 @@ export function cliDocsVersionCommand(
throw new Error(`${pluginIdLogPrefix}: there is no docs to version!`); throw new Error(`${pluginIdLogPrefix}: there is no docs to version!`);
} }
createVersionedSidebarFile({ await createVersionedSidebarFile({
siteDir, siteDir,
pluginId, pluginId,
version, version,

View file

@ -25,13 +25,13 @@ describe('loadNormalizedSidebars', () => {
}; };
test('sidebars with known sidebar item type', async () => { test('sidebars with known sidebar item type', async () => {
const sidebarPath = path.join(fixtureDir, 'sidebars.json'); const sidebarPath = path.join(fixtureDir, 'sidebars.json');
const result = loadNormalizedSidebars(sidebarPath, options); const result = await loadNormalizedSidebars(sidebarPath, options);
expect(result).toMatchSnapshot(); expect(result).toMatchSnapshot();
}); });
test('sidebars with deep level of category', async () => { test('sidebars with deep level of category', async () => {
const sidebarPath = path.join(fixtureDir, 'sidebars-category.js'); const sidebarPath = path.join(fixtureDir, 'sidebars-category.js');
const result = loadNormalizedSidebars(sidebarPath, options); const result = await loadNormalizedSidebars(sidebarPath, options);
expect(result).toMatchSnapshot(); expect(result).toMatchSnapshot();
}); });
@ -41,8 +41,8 @@ describe('loadNormalizedSidebars', () => {
fixtureDir, fixtureDir,
'sidebars-category-shorthand.js', 'sidebars-category-shorthand.js',
); );
const sidebar1 = loadNormalizedSidebars(sidebarPath1, options); const sidebar1 = await loadNormalizedSidebars(sidebarPath1, options);
const sidebar2 = loadNormalizedSidebars(sidebarPath2, options); const sidebar2 = await loadNormalizedSidebars(sidebarPath2, options);
expect(sidebar1).toEqual(sidebar2); expect(sidebar1).toEqual(sidebar2);
}); });
@ -51,7 +51,7 @@ describe('loadNormalizedSidebars', () => {
fixtureDir, fixtureDir,
'sidebars-category-wrong-items.json', 'sidebars-category-wrong-items.json',
); );
expect(() => loadNormalizedSidebars(sidebarPath, options)) await expect(() => loadNormalizedSidebars(sidebarPath, options)).rejects
.toThrowErrorMatchingInlineSnapshot(` .toThrowErrorMatchingInlineSnapshot(`
"{ "{
\\"type\\": \\"category\\", \\"type\\": \\"category\\",
@ -68,7 +68,7 @@ describe('loadNormalizedSidebars', () => {
fixtureDir, fixtureDir,
'sidebars-category-wrong-label.json', 'sidebars-category-wrong-label.json',
); );
expect(() => loadNormalizedSidebars(sidebarPath, options)) await expect(() => loadNormalizedSidebars(sidebarPath, options)).rejects
.toThrowErrorMatchingInlineSnapshot(` .toThrowErrorMatchingInlineSnapshot(`
"{ "{
\\"type\\": \\"category\\", \\"type\\": \\"category\\",
@ -87,7 +87,7 @@ describe('loadNormalizedSidebars', () => {
fixtureDir, fixtureDir,
'sidebars-doc-id-not-string.json', 'sidebars-doc-id-not-string.json',
); );
expect(() => loadNormalizedSidebars(sidebarPath, options)) await expect(() => loadNormalizedSidebars(sidebarPath, options)).rejects
.toThrowErrorMatchingInlineSnapshot(` .toThrowErrorMatchingInlineSnapshot(`
"{ "{
\\"type\\": \\"doc\\", \\"type\\": \\"doc\\",
@ -105,19 +105,19 @@ describe('loadNormalizedSidebars', () => {
fixtureDir, fixtureDir,
'sidebars-first-level-not-category.js', 'sidebars-first-level-not-category.js',
); );
const result = loadNormalizedSidebars(sidebarPath, options); const result = await loadNormalizedSidebars(sidebarPath, options);
expect(result).toMatchSnapshot(); expect(result).toMatchSnapshot();
}); });
test('sidebars link', async () => { test('sidebars link', async () => {
const sidebarPath = path.join(fixtureDir, 'sidebars-link.json'); const sidebarPath = path.join(fixtureDir, 'sidebars-link.json');
const result = loadNormalizedSidebars(sidebarPath, options); const result = await loadNormalizedSidebars(sidebarPath, options);
expect(result).toMatchSnapshot(); expect(result).toMatchSnapshot();
}); });
test('sidebars link wrong label', async () => { test('sidebars link wrong label', async () => {
const sidebarPath = path.join(fixtureDir, 'sidebars-link-wrong-label.json'); const sidebarPath = path.join(fixtureDir, 'sidebars-link-wrong-label.json');
expect(() => loadNormalizedSidebars(sidebarPath, options)) await expect(() => loadNormalizedSidebars(sidebarPath, options)).rejects
.toThrowErrorMatchingInlineSnapshot(` .toThrowErrorMatchingInlineSnapshot(`
"{ "{
\\"type\\": \\"link\\", \\"type\\": \\"link\\",
@ -131,7 +131,7 @@ describe('loadNormalizedSidebars', () => {
test('sidebars link wrong href', async () => { test('sidebars link wrong href', async () => {
const sidebarPath = path.join(fixtureDir, 'sidebars-link-wrong-href.json'); const sidebarPath = path.join(fixtureDir, 'sidebars-link-wrong-href.json');
expect(() => loadNormalizedSidebars(sidebarPath, options)) await expect(() => loadNormalizedSidebars(sidebarPath, options)).rejects
.toThrowErrorMatchingInlineSnapshot(` .toThrowErrorMatchingInlineSnapshot(`
"{ "{
\\"type\\": \\"link\\", \\"type\\": \\"link\\",
@ -147,7 +147,7 @@ describe('loadNormalizedSidebars', () => {
test('sidebars with unknown sidebar item type', async () => { test('sidebars with unknown sidebar item type', async () => {
const sidebarPath = path.join(fixtureDir, 'sidebars-unknown-type.json'); const sidebarPath = path.join(fixtureDir, 'sidebars-unknown-type.json');
expect(() => loadNormalizedSidebars(sidebarPath, options)) await expect(() => loadNormalizedSidebars(sidebarPath, options)).rejects
.toThrowErrorMatchingInlineSnapshot(` .toThrowErrorMatchingInlineSnapshot(`
"{ "{
\\"type\\": \\"superman\\", \\"type\\": \\"superman\\",
@ -160,7 +160,7 @@ describe('loadNormalizedSidebars', () => {
test('sidebars with known sidebar item type but wrong field', async () => { test('sidebars with known sidebar item type but wrong field', async () => {
const sidebarPath = path.join(fixtureDir, 'sidebars-wrong-field.json'); const sidebarPath = path.join(fixtureDir, 'sidebars-wrong-field.json');
expect(() => loadNormalizedSidebars(sidebarPath, options)) await expect(() => loadNormalizedSidebars(sidebarPath, options)).rejects
.toThrowErrorMatchingInlineSnapshot(` .toThrowErrorMatchingInlineSnapshot(`
"{ "{
\\"type\\": \\"category\\", \\"type\\": \\"category\\",
@ -173,23 +173,27 @@ describe('loadNormalizedSidebars', () => {
`); `);
}); });
test('unexisting path', () => { test('unexisting path', async () => {
expect(loadNormalizedSidebars('badpath', options)).toEqual( await expect(loadNormalizedSidebars('badpath', options)).resolves.toEqual(
DisabledSidebars, DisabledSidebars,
); );
}); });
test('undefined path', () => { test('undefined path', async () => {
expect(loadNormalizedSidebars(undefined, options)).toEqual(DefaultSidebars); await expect(loadNormalizedSidebars(undefined, options)).resolves.toEqual(
DefaultSidebars,
);
}); });
test('literal false path', () => { test('literal false path', async () => {
expect(loadNormalizedSidebars(false, options)).toEqual(DisabledSidebars); await expect(loadNormalizedSidebars(false, options)).resolves.toEqual(
DisabledSidebars,
);
}); });
test('sidebars with category.collapsed property', async () => { test('sidebars with category.collapsed property', async () => {
const sidebarPath = path.join(fixtureDir, 'sidebars-collapsed.json'); const sidebarPath = path.join(fixtureDir, 'sidebars-collapsed.json');
const result = loadNormalizedSidebars(sidebarPath, options); const result = await loadNormalizedSidebars(sidebarPath, options);
expect(result).toMatchSnapshot(); expect(result).toMatchSnapshot();
}); });
@ -198,7 +202,7 @@ describe('loadNormalizedSidebars', () => {
fixtureDir, fixtureDir,
'sidebars-collapsed-first-level.json', 'sidebars-collapsed-first-level.json',
); );
const result = loadNormalizedSidebars(sidebarPath, options); const result = await loadNormalizedSidebars(sidebarPath, options);
expect(result).toMatchSnapshot(); expect(result).toMatchSnapshot();
}); });
}); });

View file

@ -38,9 +38,9 @@ export function resolveSidebarPathOption(
: sidebarPathOption; : sidebarPathOption;
} }
function loadSidebarsFileUnsafe( async function loadSidebarsFileUnsafe(
sidebarFilePath: string | false | undefined, sidebarFilePath: string | false | undefined,
): SidebarsConfig { ): Promise<SidebarsConfig> {
// false => no sidebars // false => no sidebars
if (sidebarFilePath === false) { if (sidebarFilePath === false) {
return DisabledSidebars; return DisabledSidebars;
@ -62,19 +62,19 @@ function loadSidebarsFileUnsafe(
return importFresh(sidebarFilePath); return importFresh(sidebarFilePath);
} }
export function loadSidebarsFile( export async function loadSidebarsFile(
sidebarFilePath: string | false | undefined, sidebarFilePath: string | false | undefined,
): SidebarsConfig { ): Promise<SidebarsConfig> {
const sidebarsConfig = loadSidebarsFileUnsafe(sidebarFilePath); const sidebarsConfig = await loadSidebarsFileUnsafe(sidebarFilePath);
validateSidebars(sidebarsConfig); validateSidebars(sidebarsConfig);
return sidebarsConfig; return sidebarsConfig;
} }
export function loadNormalizedSidebars( export async function loadNormalizedSidebars(
sidebarFilePath: string | false | undefined, sidebarFilePath: string | false | undefined,
params: NormalizeSidebarsParams, params: NormalizeSidebarsParams,
): NormalizedSidebars { ): Promise<NormalizedSidebars> {
return normalizeSidebars(loadSidebarsFile(sidebarFilePath), params); return normalizeSidebars(await loadSidebarsFile(sidebarFilePath), params);
} }
// Note: sidebarFilePath must be absolute, use resolveSidebarPathOption // Note: sidebarFilePath must be absolute, use resolveSidebarPathOption
@ -87,7 +87,7 @@ export async function loadSidebars(
version: options.version, version: options.version,
categoryLabelSlugger: createSlugger(), categoryLabelSlugger: createSlugger(),
}; };
const normalizedSidebars = loadNormalizedSidebars( const normalizedSidebars = await loadNormalizedSidebars(
sidebarFilePath, sidebarFilePath,
normalizeSidebarsParams, normalizeSidebarsParams,
); );

View file

@ -14,7 +14,7 @@ export default async function externalCommand(
siteDir: string, siteDir: string,
): Promise<void> { ): Promise<void> {
const context = await loadContext(siteDir); const context = await loadContext(siteDir);
const pluginConfigs = loadPluginConfigs(context); const pluginConfigs = await loadPluginConfigs(context);
const plugins = await initPlugins({pluginConfigs, context}); const plugins = await initPlugins({pluginConfigs, context});
// Plugin Lifecycle - extendCli. // Plugin Lifecycle - extendCli.

View file

@ -147,7 +147,7 @@ export default async function swizzle(
danger?: boolean, danger?: boolean,
): Promise<void> { ): Promise<void> {
const context = await loadContext(siteDir); const context = await loadContext(siteDir);
const pluginConfigs = loadPluginConfigs(context); const pluginConfigs = await loadPluginConfigs(context);
const pluginNames = getPluginNames(pluginConfigs); const pluginNames = getPluginNames(pluginConfigs);
const plugins = await initPlugins({ const plugins = await initPlugins({
pluginConfigs, pluginConfigs,

View file

@ -124,7 +124,7 @@ async function transformMarkdownFile(
*/ */
async function getPathsToWatch(siteDir: string): Promise<string[]> { async function getPathsToWatch(siteDir: string): Promise<string[]> {
const context = await loadContext(siteDir); const context = await loadContext(siteDir);
const pluginConfigs = loadPluginConfigs(context); const pluginConfigs = await loadPluginConfigs(context);
const plugins = await initPlugins({ const plugins = await initPlugins({
pluginConfigs, pluginConfigs,
context, context,

View file

@ -80,7 +80,7 @@ export default async function writeTranslations(
customConfigFilePath: options.config, customConfigFilePath: options.config,
locale: options.locale, locale: options.locale,
}); });
const pluginConfigs = loadPluginConfigs(context); const pluginConfigs = await loadPluginConfigs(context);
const plugins = await initPlugins({ const plugins = await initPlugins({
pluginConfigs, pluginConfigs,
context, context,

View file

@ -129,8 +129,12 @@ export async function loadContext(
}; };
} }
export function loadPluginConfigs(context: LoadContext): PluginConfig[] { export async function loadPluginConfigs(
let {plugins: presetPlugins, themes: presetThemes} = loadPresets(context); context: LoadContext,
): Promise<PluginConfig[]> {
let {plugins: presetPlugins, themes: presetThemes} = await loadPresets(
context,
);
const {siteConfig, siteConfigPath} = context; const {siteConfig, siteConfigPath} = context;
const require = createRequire(siteConfigPath); const require = createRequire(siteConfigPath);
function normalizeShorthand( function normalizeShorthand(
@ -298,7 +302,7 @@ export async function load(
codeTranslations, codeTranslations,
} = context; } = context;
// Plugins. // Plugins.
const pluginConfigs: PluginConfig[] = loadPluginConfigs(context); const pluginConfigs: PluginConfig[] = await loadPluginConfigs(context);
const {plugins, pluginsRouteConfigs, globalData, themeConfigTranslated} = const {plugins, pluginsRouteConfigs, globalData, themeConfigTranslated} =
await loadPlugins({pluginConfigs, context}); await loadPlugins({pluginConfigs, context});

View file

@ -20,7 +20,7 @@ describe('initPlugins', () => {
async function loadSite(options: LoadContextOptions = {}) { async function loadSite(options: LoadContextOptions = {}) {
const siteDir = path.join(__dirname, '__fixtures__', 'site-with-plugin'); const siteDir = path.join(__dirname, '__fixtures__', 'site-with-plugin');
const context = await loadContext(siteDir, options); const context = await loadContext(siteDir, options);
const pluginConfigs = loadPluginConfigs(context); const pluginConfigs = await loadPluginConfigs(context);
const plugins = await initPlugins({ const plugins = await initPlugins({
pluginConfigs, pluginConfigs,
context, context,

View file

@ -34,10 +34,10 @@ type NormalizedPluginConfig = {
}; };
}; };
function normalizePluginConfig( async function normalizePluginConfig(
pluginConfig: PluginConfig, pluginConfig: PluginConfig,
pluginRequire: NodeRequire, pluginRequire: NodeRequire,
): NormalizedPluginConfig { ): Promise<NormalizedPluginConfig> {
// plugins: ['./plugin'] // plugins: ['./plugin']
if (typeof pluginConfig === 'string') { if (typeof pluginConfig === 'string') {
const pluginModuleImport = pluginConfig; const pluginModuleImport = pluginConfig;
@ -182,7 +182,7 @@ export default async function initPlugins({
async function initializePlugin( async function initializePlugin(
pluginConfig: PluginConfig, pluginConfig: PluginConfig,
): Promise<InitializedPlugin> { ): Promise<InitializedPlugin> {
const normalizedPluginConfig = normalizePluginConfig( const normalizedPluginConfig = await normalizePluginConfig(
pluginConfig, pluginConfig,
pluginRequire, pluginRequire,
); );

View file

@ -11,12 +11,12 @@ import loadPresets from '../index';
import type {LoadContext} from '@docusaurus/types'; import type {LoadContext} from '@docusaurus/types';
describe('loadPresets', () => { describe('loadPresets', () => {
test('no presets', () => { test('no presets', async () => {
const context = { const context = {
siteConfigPath: __dirname, siteConfigPath: __dirname,
siteConfig: {}, siteConfig: {},
} as LoadContext; } as LoadContext;
const presets = loadPresets(context); const presets = await loadPresets(context);
expect(presets).toMatchInlineSnapshot(` expect(presets).toMatchInlineSnapshot(`
Object { Object {
"plugins": Array [], "plugins": Array [],
@ -25,14 +25,14 @@ describe('loadPresets', () => {
`); `);
}); });
test('string form', () => { test('string form', async () => {
const context = { const context = {
siteConfigPath: __dirname, siteConfigPath: __dirname,
siteConfig: { siteConfig: {
presets: [path.join(__dirname, '__fixtures__/preset-bar.js')], presets: [path.join(__dirname, '__fixtures__/preset-bar.js')],
}, },
} as LoadContext; } as LoadContext;
const presets = loadPresets(context); const presets = await loadPresets(context);
expect(presets).toMatchInlineSnapshot(` expect(presets).toMatchInlineSnapshot(`
Object { Object {
"plugins": Array [ "plugins": Array [
@ -50,7 +50,7 @@ describe('loadPresets', () => {
`); `);
}); });
test('string form composite', () => { test('string form composite', async () => {
const context = { const context = {
siteConfigPath: __dirname, siteConfigPath: __dirname,
siteConfig: { siteConfig: {
@ -60,7 +60,7 @@ describe('loadPresets', () => {
], ],
}, },
} as LoadContext; } as LoadContext;
const presets = loadPresets(context); const presets = await loadPresets(context);
expect(presets).toMatchInlineSnapshot(` expect(presets).toMatchInlineSnapshot(`
Object { Object {
"plugins": Array [ "plugins": Array [
@ -86,14 +86,14 @@ describe('loadPresets', () => {
`); `);
}); });
test('array form', () => { test('array form', async () => {
const context = { const context = {
siteConfigPath: __dirname, siteConfigPath: __dirname,
siteConfig: { siteConfig: {
presets: [[path.join(__dirname, '__fixtures__/preset-bar.js')]], presets: [[path.join(__dirname, '__fixtures__/preset-bar.js')]],
}, },
} as Partial<LoadContext>; } as Partial<LoadContext>;
const presets = loadPresets(context); const presets = await loadPresets(context);
expect(presets).toMatchInlineSnapshot(` expect(presets).toMatchInlineSnapshot(`
Object { Object {
"plugins": Array [ "plugins": Array [
@ -111,7 +111,7 @@ describe('loadPresets', () => {
`); `);
}); });
test('array form with options', () => { test('array form with options', async () => {
const context = { const context = {
siteConfigPath: __dirname, siteConfigPath: __dirname,
siteConfig: { siteConfig: {
@ -123,7 +123,7 @@ describe('loadPresets', () => {
], ],
}, },
} as Partial<LoadContext>; } as Partial<LoadContext>;
const presets = loadPresets(context); const presets = await loadPresets(context);
expect(presets).toMatchInlineSnapshot(` expect(presets).toMatchInlineSnapshot(`
Object { Object {
"plugins": Array [ "plugins": Array [
@ -143,7 +143,7 @@ describe('loadPresets', () => {
`); `);
}); });
test('array form composite', () => { test('array form composite', async () => {
const context = { const context = {
siteConfigPath: __dirname, siteConfigPath: __dirname,
siteConfig: { siteConfig: {
@ -159,7 +159,7 @@ describe('loadPresets', () => {
], ],
}, },
} as Partial<LoadContext>; } as Partial<LoadContext>;
const presets = loadPresets(context); const presets = await loadPresets(context);
expect(presets).toMatchInlineSnapshot(` expect(presets).toMatchInlineSnapshot(`
Object { Object {
"plugins": Array [ "plugins": Array [
@ -189,7 +189,7 @@ describe('loadPresets', () => {
`); `);
}); });
test('mixed form', () => { test('mixed form', async () => {
const context = { const context = {
siteConfigPath: __dirname, siteConfigPath: __dirname,
siteConfig: { siteConfig: {
@ -202,7 +202,7 @@ describe('loadPresets', () => {
], ],
}, },
} as LoadContext; } as LoadContext;
const presets = loadPresets(context); const presets = await loadPresets(context);
expect(presets).toMatchInlineSnapshot(` expect(presets).toMatchInlineSnapshot(`
Object { Object {
"plugins": Array [ "plugins": Array [
@ -230,7 +230,7 @@ describe('loadPresets', () => {
`); `);
}); });
test('mixed form with themes', () => { test('mixed form with themes', async () => {
const context = { const context = {
siteConfigPath: __dirname, siteConfigPath: __dirname,
siteConfig: { siteConfig: {
@ -244,7 +244,7 @@ describe('loadPresets', () => {
], ],
}, },
} as LoadContext; } as LoadContext;
const presets = loadPresets(context); const presets = await loadPresets(context);
expect(presets).toMatchInlineSnapshot(` expect(presets).toMatchInlineSnapshot(`
Object { Object {
"plugins": Array [ "plugins": Array [

View file

@ -15,10 +15,10 @@ import type {
} from '@docusaurus/types'; } from '@docusaurus/types';
import {resolveModuleName} from '../moduleShorthand'; import {resolveModuleName} from '../moduleShorthand';
export default function loadPresets(context: LoadContext): { export default async function loadPresets(context: LoadContext): Promise<{
plugins: PluginConfig[]; plugins: PluginConfig[];
themes: PluginConfig[]; themes: PluginConfig[];
} { }> {
// We need to resolve presets from the perspective of the siteDir, since the // We need to resolve presets from the perspective of the siteDir, since the
// siteDir's package.json declares the dependency on these presets. // siteDir's package.json declares the dependency on these presets.
const presetRequire = createRequire(context.siteConfigPath); const presetRequire = createRequire(context.siteConfigPath);