diff --git a/__tests__/validate-package-json.test.ts b/__tests__/validate-package-json.test.ts index ef18176ecd92..b8dd9b78771e 100644 --- a/__tests__/validate-package-json.test.ts +++ b/__tests__/validate-package-json.test.ts @@ -70,17 +70,15 @@ describe('packages', () => { packageJsonFile.content.name?.startsWith('@'), ) .forEach((packageJsonFile) => { - if (packageJsonFile) { - // Unfortunately jest custom message do not exist in loops, - // so using an exception instead to show failing package file - // (see https://github.com/facebook/jest/issues/3293) - // expect(packageJsonFile.content.publishConfig?.access) - // .toEqual('public'); - if (packageJsonFile.content.publishConfig?.access !== 'public') { - throw new Error( - `Package ${packageJsonFile.file} does not have publishConfig.access: 'public'`, - ); - } + // Unfortunately jest custom message do not exist in loops, + // so using an exception instead to show failing package file + // (see https://github.com/facebook/jest/issues/3293) + // expect(packageJsonFile.content.publishConfig?.access) + // .toEqual('public'); + if (packageJsonFile.content.publishConfig?.access !== 'public') { + throw new Error( + `Package ${packageJsonFile.file} does not have publishConfig.access: 'public'`, + ); } }); }); diff --git a/admin/new.docusaurus.io/functions/codesandbox.ts b/admin/new.docusaurus.io/functions/codesandbox.ts index 650c45727e6b..6f7b8327decf 100644 --- a/admin/new.docusaurus.io/functions/codesandbox.ts +++ b/admin/new.docusaurus.io/functions/codesandbox.ts @@ -8,6 +8,5 @@ import {createPlaygroundResponse} from '../functionUtils/playgroundUtils'; import type {Handler} from '@netlify/functions'; -export const handler: Handler = async function handler() { - return createPlaygroundResponse('codesandbox'); -}; +export const handler: Handler = () => + Promise.resolve(createPlaygroundResponse('codesandbox')); diff --git a/admin/new.docusaurus.io/functions/stackblitz.ts b/admin/new.docusaurus.io/functions/stackblitz.ts index bc6a84d31f5a..6e69c2ade829 100644 --- a/admin/new.docusaurus.io/functions/stackblitz.ts +++ b/admin/new.docusaurus.io/functions/stackblitz.ts @@ -8,6 +8,5 @@ import {createPlaygroundResponse} from '../functionUtils/playgroundUtils'; import type {Handler} from '@netlify/functions'; -export const handler: Handler = async function handler() { - return createPlaygroundResponse('stackblitz'); -}; +export const handler: Handler = () => + Promise.resolve(createPlaygroundResponse('stackblitz')); diff --git a/packages/create-docusaurus/src/index.ts b/packages/create-docusaurus/src/index.ts index c1f592cefcd1..6523b9291766 100755 --- a/packages/create-docusaurus/src/index.ts +++ b/packages/create-docusaurus/src/index.ts @@ -65,20 +65,22 @@ async function askForPackageManagerChoice(): Promise { .map((p) => ({title: p, value: p})); return ( - (await prompts( - { - type: 'select', - name: 'packageManager', - message: 'Select a package manager...', - choices, - }, - { - onCancel() { - logger.info`Falling back to name=${defaultPackageManager}`; + ( + (await prompts( + { + type: 'select', + name: 'packageManager', + message: 'Select a package manager...', + choices, }, - }, - )) as {packageManager: PackageManager} - ).packageManager; + { + onCancel() { + logger.info`Falling back to name=${defaultPackageManager}`; + }, + }, + )) as {packageManager: PackageManager} + ).packageManager ?? defaultPackageManager + ); } async function getPackageManager( @@ -101,8 +103,7 @@ async function getPackageManager( (await findPackageManagerFromLockFile('.')) ?? findPackageManagerFromUserAgent() ?? // This only happens if the user has a global installation in PATH - (skipInstall ? defaultPackageManager : askForPackageManagerChoice()) ?? - defaultPackageManager + (skipInstall ? defaultPackageManager : askForPackageManagerChoice()) ); } @@ -215,7 +216,7 @@ async function getGitCommand(gitStrategy: GitStrategy): Promise { logger.info`Falling back to code=${'git clone'}`; }, }, - )) as {command: string}; + )) as {command?: string}; return command ?? 'git clone'; } case 'deep': @@ -362,7 +363,7 @@ async function getSource( )) as {gitRepoUrl: string}; let strategy = cliOptions.gitStrategy; if (!strategy) { - ({strategy} = await prompts( + ({strategy} = (await prompts( { type: 'select', name: 'strategy', @@ -385,7 +386,7 @@ async function getSource( logger.info`Falling back to name=${'deep'}`; }, }, - )); + )) as {strategy?: GitStrategy}); } return { type: 'git', @@ -426,13 +427,13 @@ async function getSource( } let useTS = cliOptions.typescript; if (!useTS && template.tsVariantPath) { - ({useTS} = await prompts({ + ({useTS} = (await prompts({ type: 'confirm', name: 'useTS', message: 'This template is available in TypeScript. Do you want to use the TS variant?', initial: false, - })); + })) as {useTS?: boolean}); } return { type: 'template', diff --git a/packages/docusaurus-logger/src/index.ts b/packages/docusaurus-logger/src/index.ts index 6db95cdd1531..768cb8f9a0c2 100644 --- a/packages/docusaurus-logger/src/index.ts +++ b/packages/docusaurus-logger/src/index.ts @@ -9,10 +9,10 @@ import chalk from 'chalk'; type InterpolatableValue = string | number | (string | number)[]; -const path = (msg: unknown): string => chalk.cyan.underline(`"${msg}"`); +const path = (msg: unknown): string => chalk.cyan.underline(`"${String(msg)}"`); const url = (msg: unknown): string => chalk.cyan.underline(msg); const name = (msg: unknown): string => chalk.blue.bold(msg); -const code = (msg: unknown): string => chalk.cyan(`\`${msg}\``); +const code = (msg: unknown): string => chalk.cyan(`\`${String(msg)}\``); const subdue = (msg: unknown): string => chalk.gray(msg); const num = (msg: unknown): string => chalk.yellow(msg); diff --git a/packages/docusaurus-mdx-loader/src/index.ts b/packages/docusaurus-mdx-loader/src/index.ts index ad7887dcc77c..1b7f2be72344 100644 --- a/packages/docusaurus-mdx-loader/src/index.ts +++ b/packages/docusaurus-mdx-loader/src/index.ts @@ -21,7 +21,7 @@ export type LoadedMDXContent = { /** As provided by the content plugin. */ readonly metadata: Metadata; /** A list of TOC items (headings). */ - readonly toc: readonly TOCItem[]; + readonly toc?: readonly TOCItem[]; /** First h1 title before any content. */ readonly contentTitle: string | undefined; /** diff --git a/packages/docusaurus-mdx-loader/src/loader.ts b/packages/docusaurus-mdx-loader/src/loader.ts index 88fa1ecd5bdc..638a62566724 100644 --- a/packages/docusaurus-mdx-loader/src/loader.ts +++ b/packages/docusaurus-mdx-loader/src/loader.ts @@ -55,7 +55,7 @@ export type MDXOptions = { beforeDefaultRehypePlugins: MDXPlugin[]; }; -export type Options = MDXOptions & { +export type Options = Partial & { staticDirs: string[]; siteDir: string; isMDXPartial?: (filePath: string) => boolean; @@ -138,7 +138,7 @@ export async function mdxLoader( ): Promise { const callback = this.async(); const filePath = this.resourcePath; - const reqOptions = this.getOptions() ?? {}; + const reqOptions = this.getOptions(); const {frontMatter, content: contentWithTitle} = parseFrontMatter(fileString); diff --git a/packages/docusaurus-mdx-loader/src/remark/headings/index.ts b/packages/docusaurus-mdx-loader/src/remark/headings/index.ts index 51b0cb6c7bbd..98aaa37f7552 100644 --- a/packages/docusaurus-mdx-loader/src/remark/headings/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/headings/index.ts @@ -17,7 +17,7 @@ export default function plugin(): Transformer { return (root) => { const slugs = createSlugger(); visit(root, 'heading', (headingNode: Heading) => { - const data = headingNode.data || (headingNode.data = {}); + const data = headingNode.data ?? (headingNode.data = {}); const properties = (data.hProperties || (data.hProperties = {})) as { id: string; }; @@ -36,7 +36,7 @@ export default function plugin(): Transformer { // Support explicit heading IDs const parsedHeading = parseMarkdownHeadingId(heading); - id = parsedHeading.id || slugs.slug(heading); + id = parsedHeading.id ?? slugs.slug(heading); if (parsedHeading.id) { // When there's an id, it is always in the last child node diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts index 9c9f2004ba7d..59e1b4117bf5 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts @@ -110,8 +110,9 @@ async function processLinkNode(node: Link, context: Context) { if (!node.url) { // Try to improve error feedback // see https://github.com/facebook/docusaurus/issues/3309#issuecomment-690371675 - const title = node.title || (node.children[0] as Literal)?.value || '?'; - const line = node?.position?.start?.line || '?'; + const title = + node.title ?? (node.children[0] as Literal | undefined)?.value ?? '?'; + const line = node.position?.start.line ?? '?'; throw new Error( `Markdown link URL is mandatory in "${toMessageRelativeFilePath( context.filePath, diff --git a/packages/docusaurus-mdx-loader/src/remark/utils/index.ts b/packages/docusaurus-mdx-loader/src/remark/utils/index.ts index b0314d7a2349..3bf275085bf5 100644 --- a/packages/docusaurus-mdx-loader/src/remark/utils/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/utils/index.ts @@ -15,7 +15,7 @@ export function stringifyContent(node: Parent): string { } export function toValue(node: PhrasingContent | Heading): string { - switch (node?.type) { + switch (node.type) { case 'text': return escapeHtml(node.value); case 'heading': diff --git a/packages/docusaurus-migrate/src/__tests__/index.test.ts b/packages/docusaurus-migrate/src/__tests__/index.test.ts index 8eea0cd15849..306f7e394a12 100644 --- a/packages/docusaurus-migrate/src/__tests__/index.test.ts +++ b/packages/docusaurus-migrate/src/__tests__/index.test.ts @@ -19,22 +19,22 @@ async function testMigration(siteDir: string, newDir: string) { await migrateDocusaurusProject(siteDir, newDir, true, true); expect( writeMock.mock.calls.sort((a, b) => - posixPath(a[0] as string).localeCompare(posixPath(b[0] as string)), + posixPath(a[0]).localeCompare(posixPath(b[0])), ), ).toMatchSnapshot('write'); expect( mkdirpMock.mock.calls.sort((a, b) => - posixPath(a[0] as string).localeCompare(posixPath(b[0] as string)), + posixPath(a[0]).localeCompare(posixPath(b[0])), ), ).toMatchSnapshot('mkdirp'); expect( mkdirsMock.mock.calls.sort((a, b) => - posixPath(a[0] as string).localeCompare(posixPath(b[0] as string)), + posixPath(a[0]).localeCompare(posixPath(b[0])), ), ).toMatchSnapshot('mkdirs'); expect( copyMock.mock.calls.sort((a, b) => - posixPath(a[0] as string).localeCompare(posixPath(b[0] as string)), + posixPath(a[0]).localeCompare(posixPath(b[0])), ), ).toMatchSnapshot('copy'); writeMock.mockRestore(); diff --git a/packages/docusaurus-migrate/src/frontMatter.ts b/packages/docusaurus-migrate/src/frontMatter.ts index 2d03fb0e40e5..6ec040296d74 100644 --- a/packages/docusaurus-migrate/src/frontMatter.ts +++ b/packages/docusaurus-migrate/src/frontMatter.ts @@ -40,12 +40,7 @@ export default function extractMetadata(content: string): Data { lines.slice(0, -1).forEach((line) => { const keyValue = line.split(':') as [string, ...string[]]; const key = keyValue[0].trim(); - let value = keyValue.slice(1).join(':').trim(); - try { - value = JSON.parse(value); - } catch (err) { - // Ignore the error as it means it's not a JSON value. - } + const value = keyValue.slice(1).join(':').trim(); metadata[key] = value; }); return {metadata, rawContent: both.content}; diff --git a/packages/docusaurus-migrate/src/index.ts b/packages/docusaurus-migrate/src/index.ts index 81f31e6b874c..165c7c2fd32f 100644 --- a/packages/docusaurus-migrate/src/index.ts +++ b/packages/docusaurus-migrate/src/index.ts @@ -474,7 +474,7 @@ async function migrateVersionedDocs( versions.reverse().map(async (version, index) => { if (index === 0) { await fs.copy( - path.join(siteDir, '..', context.v1Config.customDocsPath || 'docs'), + path.join(siteDir, '..', context.v1Config.customDocsPath ?? 'docs'), path.join(newDir, 'versioned_docs', `version-${version}`), ); await fs.copy( @@ -551,7 +551,9 @@ async function migrateVersionedSidebar( const newSidebar = Object.entries(sidebarEntries).reduce( (topLevel: SidebarEntries, value) => { const key = value[0].replace(versionRegex, ''); - topLevel[key] = Object.entries(value[1]).reduce((acc, val) => { + topLevel[key] = Object.entries(value[1]).reduce<{ + [key: string]: Array; + }>((acc, val) => { acc[val[0].replace(versionRegex, '')] = ( val[1] as SidebarEntry[] ).map((item) => { @@ -565,7 +567,7 @@ async function migrateVersionedSidebar( }; }); return acc; - }, {} as {[key: string]: Array}); + }, {}); return topLevel; }, {}, @@ -574,33 +576,32 @@ async function migrateVersionedSidebar( } await Promise.all( sidebars.map(async (sidebar) => { - const newSidebar = Object.entries(sidebar.entries).reduce( - (acc, val) => { - const key = `version-${sidebar.version}/${val[0]}`; - acc[key] = Object.entries(val[1]).map((value) => ({ - type: 'category', - label: value[0], - items: (value[1] as SidebarEntry[]).map((sidebarItem) => { - if (typeof sidebarItem === 'string') { - return { - type: 'doc', - id: `version-${sidebar.version}/${sidebarItem}`, - }; - } + const newSidebar = Object.entries( + sidebar.entries, + ).reduce((acc, val) => { + const key = `version-${sidebar.version}/${val[0]}`; + acc[key] = Object.entries(val[1]).map((value) => ({ + type: 'category', + label: value[0], + items: (value[1] as SidebarEntry[]).map((sidebarItem) => { + if (typeof sidebarItem === 'string') { return { - type: 'category', - label: sidebarItem.label, - items: sidebarItem.ids.map((id) => ({ - type: 'doc', - id: `version-${sidebar.version}/${id}`, - })), + type: 'doc', + id: `version-${sidebar.version}/${sidebarItem}`, }; - }), - })); - return acc; - }, - {} as SidebarEntries, - ); + } + return { + type: 'category', + label: sidebarItem.label, + items: sidebarItem.ids.map((id) => ({ + type: 'doc', + id: `version-${sidebar.version}/${id}`, + })), + }; + }), + })); + return acc; + }, {}); await fs.outputFile( path.join( newDir, @@ -702,12 +703,12 @@ async function migrateLatestDocs(context: MigrationContext) { async function migratePackageFile(context: MigrationContext): Promise { const {deps, siteDir, newDir} = context; - const packageFile = importFresh(`${siteDir}/package.json`) as { + const packageFile = importFresh<{ scripts?: {[key: string]: string}; dependencies?: {[key: string]: string}; devDependencies?: {[key: string]: string}; [otherKey: string]: unknown; - }; + }>(`${siteDir}/package.json`); packageFile.scripts = { ...packageFile.scripts, start: 'docusaurus start', diff --git a/packages/docusaurus-migrate/src/sanitizeMD.ts b/packages/docusaurus-migrate/src/sanitizeMD.ts index 55bd803aea51..61e3904cb0aa 100644 --- a/packages/docusaurus-migrate/src/sanitizeMD.ts +++ b/packages/docusaurus-migrate/src/sanitizeMD.ts @@ -37,7 +37,7 @@ export default function sanitizeMD(code: string): string { const htmlTree = unified().use(parse).parse(markdownString); visit(htmlTree, 'element', (node: Element) => { - if (!tags[node.tagName as string]) { + if (!tags[node.tagName]) { (node as Element | Text).type = 'text'; (node as Element & Partial>).value = node.tagName + toText(node); diff --git a/packages/docusaurus-module-type-aliases/src/index.d.ts b/packages/docusaurus-module-type-aliases/src/index.d.ts index ccb4bf5706fc..cd6bf0d1c910 100644 --- a/packages/docusaurus-module-type-aliases/src/index.d.ts +++ b/packages/docusaurus-module-type-aliases/src/index.d.ts @@ -8,7 +8,7 @@ declare module '@generated/client-modules' { import type {ClientModule} from '@docusaurus/types'; - const clientModules: readonly (ClientModule & {default: ClientModule})[]; + const clientModules: readonly (ClientModule & {default?: ClientModule})[]; export default clientModules; } diff --git a/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts b/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts index 739c2f6a99b5..2ed5d2f1a1b1 100644 --- a/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts +++ b/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts @@ -17,7 +17,7 @@ import writeRedirectFiles, { // - https://github.com/facebook/docusaurus/issues/3886 // - https://github.com/facebook/docusaurus/issues/3925 describe('createToUrl', () => { - it('creates appropriate redirect urls', async () => { + it('creates appropriate redirect urls', () => { expect(createToUrl('/', '/docs/something/else')).toBe( '/docs/something/else', ); @@ -29,7 +29,7 @@ describe('createToUrl', () => { ); }); - it('creates appropriate redirect urls with baseUrl', async () => { + it('creates appropriate redirect urls with baseUrl', () => { expect(createToUrl('/baseUrl/', '/docs/something/else')).toBe( '/baseUrl/docs/something/else', ); @@ -43,7 +43,7 @@ describe('createToUrl', () => { }); describe('toRedirectFilesMetadata', () => { - it('creates appropriate metadata trailingSlash=undefined', async () => { + it('creates appropriate metadata trailingSlash=undefined', () => { const pluginContext = { outDir: '/tmp/someFixedOutDir', baseUrl: 'https://docusaurus.io', @@ -70,7 +70,7 @@ describe('toRedirectFilesMetadata', () => { ); }); - it('creates appropriate metadata trailingSlash=true', async () => { + it('creates appropriate metadata trailingSlash=true', () => { const pluginContext = { outDir: '/tmp/someFixedOutDir', baseUrl: 'https://docusaurus.io', @@ -97,7 +97,7 @@ describe('toRedirectFilesMetadata', () => { ); }); - it('creates appropriate metadata trailingSlash=false', async () => { + it('creates appropriate metadata trailingSlash=false', () => { const pluginContext = { outDir: '/tmp/someFixedOutDir', baseUrl: 'https://docusaurus.io', @@ -127,7 +127,7 @@ describe('toRedirectFilesMetadata', () => { ); }); - it('creates appropriate metadata for root baseUrl', async () => { + it('creates appropriate metadata for root baseUrl', () => { const pluginContext = { outDir: '/tmp/someFixedOutDir', baseUrl: '/', @@ -142,7 +142,7 @@ describe('toRedirectFilesMetadata', () => { ); }); - it('creates appropriate metadata for empty baseUrl', async () => { + it('creates appropriate metadata for empty baseUrl', () => { const pluginContext = { outDir: '/tmp/someFixedOutDir', baseUrl: '', diff --git a/packages/docusaurus-plugin-client-redirects/src/index.ts b/packages/docusaurus-plugin-client-redirects/src/index.ts index 78d117c7ca28..237f3f099e9e 100644 --- a/packages/docusaurus-plugin-client-redirects/src/index.ts +++ b/packages/docusaurus-plugin-client-redirects/src/index.ts @@ -18,7 +18,7 @@ import type {PluginOptions, Options} from './options'; export default function pluginClientRedirectsPages( context: LoadContext, options: PluginOptions, -): Plugin { +): Plugin { const {trailingSlash} = context.siteConfig; return { diff --git a/packages/docusaurus-plugin-content-blog/src/__tests__/feed.test.ts b/packages/docusaurus-plugin-content-blog/src/__tests__/feed.test.ts index 48c3395f728b..7b7981985443 100644 --- a/packages/docusaurus-plugin-content-blog/src/__tests__/feed.test.ts +++ b/packages/docusaurus-plugin-content-blog/src/__tests__/feed.test.ts @@ -89,6 +89,7 @@ describe.each(['atom', 'rss', 'json'])('%s', (feedType) => { }, readingTime: ({content, defaultReadingTime}) => defaultReadingTime({content}), + truncateMarker: //, } as PluginOptions, ); @@ -128,6 +129,7 @@ describe.each(['atom', 'rss', 'json'])('%s', (feedType) => { }, readingTime: ({content, defaultReadingTime}) => defaultReadingTime({content}), + truncateMarker: //, } as PluginOptions, ); diff --git a/packages/docusaurus-plugin-content-blog/src/__tests__/index.test.ts b/packages/docusaurus-plugin-content-blog/src/__tests__/index.test.ts index 11b33cd2a183..384b7014c7ea 100644 --- a/packages/docusaurus-plugin-content-blog/src/__tests__/index.test.ts +++ b/packages/docusaurus-plugin-content-blog/src/__tests__/index.test.ts @@ -76,7 +76,7 @@ const getPlugin = async ( editUrl: BaseEditUrl, ...pluginOptions, }, - }) as PluginOptions, + }), ); }; diff --git a/packages/docusaurus-plugin-content-blog/src/__tests__/translations.test.ts b/packages/docusaurus-plugin-content-blog/src/__tests__/translations.test.ts index 62442bbf8151..a29ae6e3acb7 100644 --- a/packages/docusaurus-plugin-content-blog/src/__tests__/translations.test.ts +++ b/packages/docusaurus-plugin-content-blog/src/__tests__/translations.test.ts @@ -74,7 +74,7 @@ function getSampleTranslationFilesTranslated() { } describe('getContentTranslationFiles', () => { - it('returns translation files matching snapshot', async () => { + it('returns translation files matching snapshot', () => { expect(getSampleTranslationFiles()).toMatchSnapshot(); }); }); diff --git a/packages/docusaurus-plugin-content-blog/src/authors.ts b/packages/docusaurus-plugin-content-blog/src/authors.ts index cf3bbe5c8522..4d8f7b90b3fb 100644 --- a/packages/docusaurus-plugin-content-blog/src/authors.ts +++ b/packages/docusaurus-plugin-content-blog/src/authors.ts @@ -44,7 +44,11 @@ const AuthorsMapSchema = Joi.object() }); export function validateAuthorsMap(content: unknown): AuthorsMap { - return Joi.attempt(content, AuthorsMapSchema); + const {error, value} = AuthorsMapSchema.validate(content); + if (error) { + throw error; + } + return value; } export async function getAuthorsMap(params: { diff --git a/packages/docusaurus-plugin-content-blog/src/blogUtils.ts b/packages/docusaurus-plugin-content-blog/src/blogUtils.ts index 370ddeb50aa3..ee6742c7bff5 100644 --- a/packages/docusaurus-plugin-content-blog/src/blogUtils.ts +++ b/packages/docusaurus-plugin-content-blog/src/blogUtils.ts @@ -264,7 +264,7 @@ async function processBlogSourceFile( const title = frontMatter.title ?? contentTitle ?? parsedBlogFileName.text; const description = frontMatter.description ?? excerpt ?? ''; - const slug = frontMatter.slug || parsedBlogFileName.slug; + const slug = frontMatter.slug ?? parsedBlogFileName.slug; const permalink = normalizeUrl([baseUrl, routeBasePath, slug]); @@ -323,7 +323,7 @@ async function processBlogSourceFile( defaultReadingTime, }) : undefined, - truncated: truncateMarker?.test(content) || false, + truncated: truncateMarker.test(content), authors, frontMatter, }, diff --git a/packages/docusaurus-plugin-content-blog/src/index.ts b/packages/docusaurus-plugin-content-blog/src/index.ts index a3dddc2404f5..2b0355a0f3f1 100644 --- a/packages/docusaurus-plugin-content-blog/src/index.ts +++ b/packages/docusaurus-plugin-content-blog/src/index.ts @@ -176,10 +176,6 @@ export default async function pluginContentBlog( }, async contentLoaded({content: blogContents, actions}) { - if (!blogContents) { - return; - } - const { blogListComponent, blogPostComponent, @@ -500,11 +496,7 @@ export default async function pluginContentBlog( }, injectHtmlTags({content}) { - if (!content.blogPosts.length) { - return {}; - } - - if (!options.feedOptions?.type) { + if (!content.blogPosts.length || !options.feedOptions.type) { return {}; } diff --git a/packages/docusaurus-plugin-content-blog/src/markdownLoader.ts b/packages/docusaurus-plugin-content-blog/src/markdownLoader.ts index a5f3d4929889..add3e16682c2 100644 --- a/packages/docusaurus-plugin-content-blog/src/markdownLoader.ts +++ b/packages/docusaurus-plugin-content-blog/src/markdownLoader.ts @@ -34,5 +34,5 @@ export default function markdownLoader( finalContent = truncate(finalContent, markdownLoaderOptions.truncateMarker); } - return callback?.(null, finalContent); + return callback(null, finalContent); } diff --git a/packages/docusaurus-plugin-content-blog/src/options.ts b/packages/docusaurus-plugin-content-blog/src/options.ts index f6fa74e726bc..ff06c867dc9d 100644 --- a/packages/docusaurus-plugin-content-blog/src/options.ts +++ b/packages/docusaurus-plugin-content-blog/src/options.ts @@ -136,9 +136,6 @@ export function validateOptions({ validate, options, }: OptionValidationContext): PluginOptions { - const validatedOptions = validate( - PluginOptionSchema, - options, - ) as PluginOptions; + const validatedOptions = validate(PluginOptionSchema, options); return validatedOptions; } diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/translations.test.ts.snap b/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/translations.test.ts.snap index a67e0081748c..b952835b06d0 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/translations.test.ts.snap +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/translations.test.ts.snap @@ -90,13 +90,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc1 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc1 title", + }, "id": "doc1", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc1 title", "slug": "any", "source": "any", "title": "doc1 title", @@ -106,13 +108,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc2 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc2 title", + }, "id": "doc2", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc2 title", "slug": "any", "source": "any", "title": "doc2 title", @@ -122,13 +126,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc3 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc3 title", + }, "id": "doc3", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc3 title", "slug": "any", "source": "any", "title": "doc3 title", @@ -138,13 +144,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc4 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc4 title", + }, "id": "doc4", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc4 title", "slug": "any", "source": "any", "title": "doc4 title", @@ -154,13 +162,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc5 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc5 title", + }, "id": "doc5", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc5 title", "slug": "any", "source": "any", "title": "doc5 title", @@ -232,13 +242,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc1 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc1 title", + }, "id": "doc1", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc1 title", "slug": "any", "source": "any", "title": "doc1 title", @@ -248,13 +260,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc2 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc2 title", + }, "id": "doc2", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc2 title", "slug": "any", "source": "any", "title": "doc2 title", @@ -264,13 +278,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc3 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc3 title", + }, "id": "doc3", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc3 title", "slug": "any", "source": "any", "title": "doc3 title", @@ -280,13 +296,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc4 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc4 title", + }, "id": "doc4", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc4 title", "slug": "any", "source": "any", "title": "doc4 title", @@ -296,13 +314,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc5 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc5 title", + }, "id": "doc5", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc5 title", "slug": "any", "source": "any", "title": "doc5 title", @@ -374,13 +394,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc1 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc1 title", + }, "id": "doc1", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc1 title", "slug": "any", "source": "any", "title": "doc1 title", @@ -390,13 +412,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc2 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc2 title", + }, "id": "doc2", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc2 title", "slug": "any", "source": "any", "title": "doc2 title", @@ -406,13 +430,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc3 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc3 title", + }, "id": "doc3", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc3 title", "slug": "any", "source": "any", "title": "doc3 title", @@ -422,13 +448,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc4 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc4 title", + }, "id": "doc4", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc4 title", "slug": "any", "source": "any", "title": "doc4 title", @@ -438,13 +466,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = ` { "description": "doc5 description", "editUrl": "any", + "frontMatter": { + "sidebar_label": "doc5 title", + }, "id": "doc5", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, - "sidebar_label": "doc5 title", "slug": "any", "source": "any", "title": "doc5 title", diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts index bb1f1c70a071..55c50ab0cddf 100644 Binary files a/packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts and b/packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts differ diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/docs.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/docs.test.ts index 3e0f09010925..9a338c5bf9d2 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/docs.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/docs.test.ts @@ -119,7 +119,7 @@ function createTestUtils({ async function testSlug(docFileSource: string, expectedPermalink: string) { const docFile = await readDoc(docFileSource); - const metadata = await processDocMetadata({ + const metadata = processDocMetadata({ docFile, versionMetadata, context, diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts index 0d54d4bc1308..fd25cc85eef9 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts @@ -54,9 +54,9 @@ const createFakeActions = (contentDir: string) => { addRoute: (config: RouteConfig) => { routeConfigs.push(config); }, - createData: async (name: string, content: unknown) => { + createData: (name: string, content: unknown) => { dataContainer[name] = content; - return path.join(contentDir, name); + return Promise.resolve(path.join(contentDir, name)); }, setGlobalData: (data: unknown) => { globalDataContainer.pluginName = {pluginId: data}; diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/options.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/options.test.ts index bcbaccfe1144..a3ddd11f843d 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/options.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/options.test.ts @@ -31,11 +31,11 @@ const defaultOptions = { }; describe('normalizeDocsPluginOptions', () => { - it('returns default options for undefined user options', async () => { + it('returns default options for undefined user options', () => { expect(testValidate({})).toEqual(defaultOptions); }); - it('accepts correctly defined user options', async () => { + it('accepts correctly defined user options', () => { const userOptions = { path: 'my-docs', // Path to data on filesystem, relative to site dir. routeBasePath: 'my-docs', // URL Route. @@ -83,7 +83,7 @@ describe('normalizeDocsPluginOptions', () => { }); }); - it('accepts correctly defined remark and rehype plugin options', async () => { + it('accepts correctly defined remark and rehype plugin options', () => { const userOptions = { beforeDefaultRemarkPlugins: [], beforeDefaultRehypePlugins: [markdownPluginsFunctionStub], @@ -100,7 +100,7 @@ describe('normalizeDocsPluginOptions', () => { }); }); - it('accepts admonitions false', async () => { + it('accepts admonitions false', () => { const admonitionsFalse = { admonitions: false, }; @@ -110,7 +110,7 @@ describe('normalizeDocsPluginOptions', () => { }); }); - it('rejects admonitions true', async () => { + it('rejects admonitions true', () => { const admonitionsTrue = { admonitions: true, }; diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/translations.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/translations.test.ts index 5d098e355fb7..a79409ba8d84 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/translations.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/translations.test.ts @@ -30,7 +30,9 @@ function createSampleDoc(doc: Pick): DocMetadata { unversionedId: 'any', version: 'any', title: `${doc.id} title`, - sidebar_label: `${doc.id} title`, + frontMatter: { + sidebar_label: `${doc.id} title`, + }, description: `${doc.id} description`, ...doc, }; @@ -136,7 +138,7 @@ function getSampleTranslationFilesTranslated() { } describe('getLoadedContentTranslationFiles', () => { - it('returns translation files', async () => { + it('returns translation files', () => { expect(getSampleTranslationFiles()).toMatchSnapshot(); }); }); diff --git a/packages/docusaurus-plugin-content-docs/src/client/docsClientUtils.ts b/packages/docusaurus-plugin-content-docs/src/client/docsClientUtils.ts index 752a53d91edc..f3229ac46522 100644 --- a/packages/docusaurus-plugin-content-docs/src/client/docsClientUtils.ts +++ b/packages/docusaurus-plugin-content-docs/src/client/docsClientUtils.ts @@ -126,6 +126,6 @@ export function getDocVersionSuggestions( const latestVersion = getLatestVersion(data); const activeDocContext = getActiveDocContext(data, pathname); const latestDocSuggestion: GlobalDoc | undefined = - activeDocContext?.alternateDocVersions[latestVersion.name]; + activeDocContext.alternateDocVersions[latestVersion.name]; return {latestDocSuggestion, latestVersionSuggestion: latestVersion}; } diff --git a/packages/docusaurus-plugin-content-docs/src/client/index.ts b/packages/docusaurus-plugin-content-docs/src/client/index.ts index 298ed4dcd9c9..bfc2bfd78cb0 100644 --- a/packages/docusaurus-plugin-content-docs/src/client/index.ts +++ b/packages/docusaurus-plugin-content-docs/src/client/index.ts @@ -34,9 +34,11 @@ const StableEmptyObject = {}; // In blog-only mode, docs hooks are still used by the theme. We need a fail- // safe fallback when the docs plugin is not in use export const useAllDocsData = (): {[pluginId: string]: GlobalPluginData} => - (useAllPluginInstancesData('docusaurus-plugin-content-docs') as { - [pluginId: string]: GlobalPluginData; - }) ?? StableEmptyObject; + (useAllPluginInstancesData('docusaurus-plugin-content-docs') as + | { + [pluginId: string]: GlobalPluginData; + } + | undefined) ?? StableEmptyObject; export const useDocsData = (pluginId: string | undefined): GlobalPluginData => usePluginData('docusaurus-plugin-content-docs', pluginId, { diff --git a/packages/docusaurus-plugin-content-docs/src/index.ts b/packages/docusaurus-plugin-content-docs/src/index.ts index 982895957382..afbb809fb718 100644 --- a/packages/docusaurus-plugin-content-docs/src/index.ts +++ b/packages/docusaurus-plugin-content-docs/src/index.ts @@ -143,7 +143,7 @@ export default async function pluginContentDocs( )}".`, ); } - async function processVersionDoc(docFile: DocFile) { + function processVersionDoc(docFile: DocFile) { return processDocMetadata({ docFile, versionMetadata, diff --git a/packages/docusaurus-plugin-content-docs/src/markdown/index.ts b/packages/docusaurus-plugin-content-docs/src/markdown/index.ts index 5de4aae87f4d..9d846ef8d5c5 100644 --- a/packages/docusaurus-plugin-content-docs/src/markdown/index.ts +++ b/packages/docusaurus-plugin-content-docs/src/markdown/index.ts @@ -16,5 +16,5 @@ export default function markdownLoader( const fileString = source; const callback = this.async(); const options = this.getOptions(); - return callback?.(null, linkify(fileString, this.resourcePath, options)); + return callback(null, linkify(fileString, this.resourcePath, options)); } diff --git a/packages/docusaurus-plugin-content-docs/src/options.ts b/packages/docusaurus-plugin-content-docs/src/options.ts index 27b9118a718f..bd1cd5d70732 100644 --- a/packages/docusaurus-plugin-content-docs/src/options.ts +++ b/packages/docusaurus-plugin-content-docs/src/options.ts @@ -165,7 +165,7 @@ export function validateOptions({ } } - const normalizedOptions = validate(OptionsSchema, options) as PluginOptions; + const normalizedOptions = validate(OptionsSchema, options); if (normalizedOptions.admonitions) { normalizedOptions.remarkPlugins = normalizedOptions.remarkPlugins.concat([ diff --git a/packages/docusaurus-plugin-content-docs/src/props.ts b/packages/docusaurus-plugin-content-docs/src/props.ts index 8505d5de2cd2..7d27cebaa9b4 100644 --- a/packages/docusaurus-plugin-content-docs/src/props.ts +++ b/packages/docusaurus-plugin-content-docs/src/props.ts @@ -51,7 +51,7 @@ Available document ids are: } = docMetadata; return { type: 'link', - label: sidebarLabel || item.label || title, + label: sidebarLabel ?? item.label ?? title, href: permalink, className: item.className, customProps: diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/generator.test.ts b/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/generator.test.ts index 671c12cfe256..9f01f06347b7 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/generator.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/generator.test.ts @@ -463,7 +463,7 @@ describe('DefaultSidebarItemsGenerator', () => { expect(sidebarSlice).toMatchSnapshot(); }); - it('throws for unknown index link', async () => { + it('throws for unknown index link', () => { const generateSidebar = () => DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, @@ -499,7 +499,7 @@ describe('DefaultSidebarItemsGenerator', () => { }, }); - await expect(generateSidebar).rejects.toThrowErrorMatchingInlineSnapshot(` + expect(() => generateSidebar()).toThrowErrorMatchingInlineSnapshot(` "Can't find any doc with ID foo. Available doc IDs: - intro" diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/processor.test.ts b/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/processor.test.ts index d0a530bbd7f2..7dc7111dbe0a 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/processor.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/processor.test.ts @@ -26,7 +26,7 @@ describe('processSidebars', () => { function createStaticSidebarItemGenerator( sidebarSlice: SidebarItem[], ): SidebarItemsGenerator { - return jest.fn(async () => sidebarSlice); + return jest.fn(() => sidebarSlice); } const StaticGeneratedSidebarSlice: NormalizedSidebar = [ @@ -40,7 +40,7 @@ describe('processSidebars', () => { // @ts-expect-error: good enough for this test const version: VersionMetadata = { versionName: '1.0.0', - versionPath: '/docs/1.0.0', + path: '/docs/1.0.0', }; const params: SidebarProcessorParams = { diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/utils.test.ts b/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/utils.test.ts index 7c2d4428c642..4085c9931dc7 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/utils.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/utils.test.ts @@ -134,11 +134,11 @@ describe('createSidebarsUtils', () => { getFirstLink, } = createSidebarsUtils(sidebars); - it('getFirstDocIdOfFirstSidebar', async () => { + it('getFirstDocIdOfFirstSidebar', () => { expect(getFirstDocIdOfFirstSidebar()).toBe('doc1'); }); - it('getSidebarNameByDocId', async () => { + it('getSidebarNameByDocId', () => { expect(getSidebarNameByDocId('doc1')).toBe('sidebar1'); expect(getSidebarNameByDocId('doc2')).toBe('sidebar1'); expect(getSidebarNameByDocId('doc3')).toBe('sidebar2'); @@ -149,7 +149,7 @@ describe('createSidebarsUtils', () => { expect(getSidebarNameByDocId('unknown_id')).toBeUndefined(); }); - it('getDocNavigation', async () => { + it('getDocNavigation', () => { expect(getDocNavigation('doc1', 'doc1', undefined)).toEqual({ sidebarName: 'sidebar1', previous: undefined, @@ -229,7 +229,7 @@ describe('createSidebarsUtils', () => { }); }); - it('getCategoryGeneratedIndexNavigation', async () => { + it('getCategoryGeneratedIndexNavigation', () => { expect( getCategoryGeneratedIndexNavigation('/s3-subcategory-index-permalink'), ).toMatchObject({ @@ -259,7 +259,7 @@ describe('createSidebarsUtils', () => { }); }); - it('getCategoryGeneratedIndexList', async () => { + it('getCategoryGeneratedIndexList', () => { expect(getCategoryGeneratedIndexList()).toMatchObject([ { type: 'category', @@ -301,7 +301,7 @@ describe('createSidebarsUtils', () => { }); describe('collectSidebarDocItems', () => { - it('can collect docs', async () => { + it('can collect docs', () => { const sidebar: Sidebar = [ { type: 'category', @@ -357,7 +357,7 @@ describe('collectSidebarDocItems', () => { }); describe('collectSidebarCategories', () => { - it('can collect categories', async () => { + it('can collect categories', () => { const sidebar: Sidebar = [ { type: 'category', @@ -415,7 +415,7 @@ describe('collectSidebarCategories', () => { }); describe('collectSidebarLinks', () => { - it('can collect links', async () => { + it('can collect links', () => { const sidebar: Sidebar = [ { type: 'category', @@ -453,7 +453,7 @@ describe('collectSidebarLinks', () => { }); describe('collectSidebarsDocIds', () => { - it('can collect sidebars doc items', async () => { + it('can collect sidebars doc items', () => { const sidebar1: Sidebar = [ { type: 'category', @@ -499,7 +499,7 @@ describe('collectSidebarsDocIds', () => { }); describe('transformSidebarItems', () => { - it('can transform sidebar items', async () => { + it('can transform sidebar items', () => { const sidebar: Sidebar = [ { type: 'category', diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/validation.test.ts b/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/validation.test.ts index d8f5fcab0d9e..8186601285a0 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/validation.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/validation.test.ts @@ -9,7 +9,7 @@ import {validateSidebars, validateCategoryMetadataFile} from '../validation'; import type {SidebarsConfig, CategoryMetadataFile} from '../types'; describe('validateSidebars', () => { - it('throw for bad value', async () => { + it('throw for bad value', () => { expect(() => validateSidebars({sidebar: [{type: 42}]})) .toThrowErrorMatchingInlineSnapshot(` "{ @@ -21,12 +21,12 @@ describe('validateSidebars', () => { `); }); - it('accept empty object', async () => { + it('accept empty object', () => { const sidebars: SidebarsConfig = {}; validateSidebars(sidebars); }); - it('accept valid values', async () => { + it('accept valid values', () => { const sidebars: SidebarsConfig = { sidebar1: [ {type: 'doc', id: 'doc1'}, @@ -207,7 +207,7 @@ describe('validateSidebars', () => { ).toThrowErrorMatchingInlineSnapshot(`"sidebar.forEach is not a function"`); }); - it('sidebars item doc but id is not a string', async () => { + it('sidebars item doc but id is not a string', () => { expect(() => validateSidebars({ docs: [ @@ -267,18 +267,18 @@ describe('validateSidebars', () => { describe('validateCategoryMetadataFile', () => { // TODO add more tests - it('throw for bad value', async () => { + it('throw for bad value', () => { expect(() => validateCategoryMetadataFile(42), ).toThrowErrorMatchingInlineSnapshot(`""value" must be of type object"`); }); - it('accept empty object', async () => { + it('accept empty object', () => { const content: CategoryMetadataFile = {}; expect(validateCategoryMetadataFile(content)).toEqual(content); }); - it('accept valid values', async () => { + it('accept valid values', () => { const content: CategoryMetadataFile = { className: 'className', label: 'Category Label', @@ -295,7 +295,7 @@ describe('validateCategoryMetadataFile', () => { expect(validateCategoryMetadataFile(content)).toEqual(content); }); - it('rejects permalink', async () => { + it('rejects permalink', () => { const content: CategoryMetadataFile = { className: 'className', label: 'Category Label', diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars/generator.ts b/packages/docusaurus-plugin-content-docs/src/sidebars/generator.ts index 56e0025a81af..7dc6ece7bedc 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars/generator.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars/generator.ts @@ -46,7 +46,7 @@ type Dir = { }; // Comment for this feature: https://github.com/facebook/docusaurus/issues/3464#issuecomment-818670449 -export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async ({ +export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = ({ numberPrefixParser, isCategoryIndex, docs: allDocs, diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars/postProcessor.ts b/packages/docusaurus-plugin-content-docs/src/sidebars/postProcessor.ts index 307ed9de8675..58c69912d704 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars/postProcessor.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars/postProcessor.ts @@ -84,7 +84,7 @@ function postProcessSidebarItem( }; } // A non-collapsible category can't be collapsed! - if (category.collapsible === false) { + if (!category.collapsible) { category.collapsed = false; } return category; diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars/types.ts b/packages/docusaurus-plugin-content-docs/src/sidebars/types.ts index 8284f09048ee..8d038f417537 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars/types.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars/types.ts @@ -251,7 +251,7 @@ export type SidebarItemsGeneratorArgs = { }; export type SidebarItemsGenerator = ( generatorArgs: SidebarItemsGeneratorArgs, -) => Promise; +) => NormalizedSidebar | Promise; export type SidebarItemsGeneratorOption = ( generatorArgs: { @@ -262,7 +262,7 @@ export type SidebarItemsGeneratorOption = ( */ defaultSidebarItemsGenerator: SidebarItemsGenerator; } & SidebarItemsGeneratorArgs, -) => Promise; +) => NormalizedSidebar | Promise; export type SidebarProcessorParams = { sidebarItemsGenerator: SidebarItemsGeneratorOption; diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars/utils.ts b/packages/docusaurus-plugin-content-docs/src/sidebars/utils.ts index a213b2e7dedc..0c743f42d537 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars/utils.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars/utils.ts @@ -257,7 +257,7 @@ export function createSidebarsUtils(sidebars: Sidebars): SidebarsUtils { ): boolean { return ( item.type === 'category' && - item.link?.type === 'generated-index' && + item.link.type === 'generated-index' && item.link.permalink === categoryGeneratedIndexPermalink ); } diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars/validation.ts b/packages/docusaurus-plugin-content-docs/src/sidebars/validation.ts index 22ddcfbf77ce..b9b1bfae007e 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars/validation.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars/validation.ts @@ -144,7 +144,7 @@ function validateSidebarItem( // manually Joi.assert(item, sidebarItemSchema); - if ((item as NormalizedSidebarItemCategory).type === 'category') { + if ((item as NormalizedSidebarItem).type === 'category') { (item as NormalizedSidebarItemCategory).items.forEach(validateSidebarItem); } } @@ -170,5 +170,9 @@ const categoryMetadataFileSchema = Joi.object({ export function validateCategoryMetadataFile( unsafeContent: unknown, ): CategoryMetadataFile { - return Joi.attempt(unsafeContent, categoryMetadataFileSchema); + const {error, value} = categoryMetadataFileSchema.validate(unsafeContent); + if (error) { + throw error; + } + return value; } diff --git a/packages/docusaurus-plugin-content-docs/src/slug.ts b/packages/docusaurus-plugin-content-docs/src/slug.ts index 4815e210b01d..130c7a63b1f5 100644 --- a/packages/docusaurus-plugin-content-docs/src/slug.ts +++ b/packages/docusaurus-plugin-content-docs/src/slug.ts @@ -58,7 +58,7 @@ export default function getSlug({ ) { return dirNameSlug; } - const baseSlug = frontMatterSlug || baseID; + const baseSlug = frontMatterSlug ?? baseID; return resolvePathname(baseSlug, getDirNameSlug()); } diff --git a/packages/docusaurus-plugin-content-docs/src/versions/__tests__/index.test.ts b/packages/docusaurus-plugin-content-docs/src/versions/__tests__/index.test.ts index 4a3448460a24..773643ba8441 100644 --- a/packages/docusaurus-plugin-content-docs/src/versions/__tests__/index.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/versions/__tests__/index.test.ts @@ -604,7 +604,7 @@ describe('readVersionsMetadata', () => { context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Versions should be strings. Found type "number" for version "1.1"."`, + `"Versions should be strings. Found type "number" for version 1.1."`, ); jsonMock.mockImplementationOnce(() => [' ']); diff --git a/packages/docusaurus-plugin-content-docs/src/versions/validation.ts b/packages/docusaurus-plugin-content-docs/src/versions/validation.ts index 422d58f713d3..c2f1505275a0 100644 --- a/packages/docusaurus-plugin-content-docs/src/versions/validation.ts +++ b/packages/docusaurus-plugin-content-docs/src/versions/validation.ts @@ -11,7 +11,9 @@ import type {VersionsOptions} from '@docusaurus/plugin-content-docs'; export function validateVersionName(name: unknown): asserts name is string { if (typeof name !== 'string') { throw new Error( - `Versions should be strings. Found type "${typeof name}" for version "${name}".`, + `Versions should be strings. Found type "${typeof name}" for version ${JSON.stringify( + name, + )}.`, ); } if (!name.trim()) { diff --git a/packages/docusaurus-plugin-content-pages/src/__tests__/index.test.ts b/packages/docusaurus-plugin-content-pages/src/__tests__/index.test.ts index f3b94d2df5f4..31706d3a4cd4 100644 --- a/packages/docusaurus-plugin-content-pages/src/__tests__/index.test.ts +++ b/packages/docusaurus-plugin-content-pages/src/__tests__/index.test.ts @@ -16,7 +16,7 @@ describe('docusaurus-plugin-content-pages', () => { it('loads simple pages', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const context = await loadContext({siteDir}); - const plugin = await pluginContentPages( + const plugin = pluginContentPages( context, validateOptions({ validate: normalizePluginOptions, @@ -33,7 +33,7 @@ describe('docusaurus-plugin-content-pages', () => { it('loads simple pages with french translations', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const context = await loadContext({siteDir}); - const plugin = await pluginContentPages( + const plugin = pluginContentPages( { ...context, i18n: { diff --git a/packages/docusaurus-plugin-content-pages/src/index.ts b/packages/docusaurus-plugin-content-pages/src/index.ts index 66bcb0d15712..a9051e4545e6 100644 --- a/packages/docusaurus-plugin-content-pages/src/index.ts +++ b/packages/docusaurus-plugin-content-pages/src/index.ts @@ -39,10 +39,10 @@ export function getContentPathList(contentPaths: PagesContentPaths): string[] { const isMarkdownSource = (source: string) => source.endsWith('.md') || source.endsWith('.mdx'); -export default async function pluginContentPages( +export default function pluginContentPages( context: LoadContext, options: PluginOptions, -): Promise> { +): Plugin { if (options.admonitions) { options.remarkPlugins = options.remarkPlugins.concat([ [admonitions, options.admonitions], diff --git a/packages/docusaurus-plugin-content-pages/src/markdownLoader.ts b/packages/docusaurus-plugin-content-pages/src/markdownLoader.ts index e8ca79a21681..e5c91b7bf797 100644 --- a/packages/docusaurus-plugin-content-pages/src/markdownLoader.ts +++ b/packages/docusaurus-plugin-content-pages/src/markdownLoader.ts @@ -18,5 +18,5 @@ export default function markdownLoader( // TODO provide additional md processing here? like interlinking pages? // fileString = linkify(fileString) - return callback?.(null, fileString); + return callback(null, fileString); } diff --git a/packages/docusaurus-plugin-content-pages/src/options.ts b/packages/docusaurus-plugin-content-pages/src/options.ts index 475ed8311060..2c1f38201c30 100644 --- a/packages/docusaurus-plugin-content-pages/src/options.ts +++ b/packages/docusaurus-plugin-content-pages/src/options.ts @@ -28,7 +28,7 @@ export const DEFAULT_OPTIONS: PluginOptions = { admonitions: {}, }; -const PluginOptionSchema = Joi.object({ +const PluginOptionSchema = Joi.object({ path: Joi.string().default(DEFAULT_OPTIONS.path), routeBasePath: Joi.string().default(DEFAULT_OPTIONS.routeBasePath), include: Joi.array().items(Joi.string()).default(DEFAULT_OPTIONS.include), diff --git a/packages/docusaurus-plugin-debug/src/theme/DebugSiteMetadata/index.tsx b/packages/docusaurus-plugin-debug/src/theme/DebugSiteMetadata/index.tsx index 64d3954842c5..c366475762f8 100644 --- a/packages/docusaurus-plugin-debug/src/theme/DebugSiteMetadata/index.tsx +++ b/packages/docusaurus-plugin-debug/src/theme/DebugSiteMetadata/index.tsx @@ -20,7 +20,7 @@ export default function DebugMetadata(): JSX.Element {
Site Version:{' '} - {siteMetadata.siteVersion || 'No version specified'} + {siteMetadata.siteVersion ?? 'No version specified'}

Plugins and themes

    diff --git a/packages/docusaurus-plugin-google-gtag/src/index.ts b/packages/docusaurus-plugin-google-gtag/src/index.ts index 7724c9676683..2e278094e105 100644 --- a/packages/docusaurus-plugin-google-gtag/src/index.ts +++ b/packages/docusaurus-plugin-google-gtag/src/index.ts @@ -25,7 +25,7 @@ export default function pluginGoogleGtag( return { name: 'docusaurus-plugin-google-gtag', - async contentLoaded({actions}) { + contentLoaded({actions}) { actions.setGlobalData(options); }, diff --git a/packages/docusaurus-plugin-ideal-image/src/index.ts b/packages/docusaurus-plugin-ideal-image/src/index.ts index d650e33b1006..4b8862171859 100644 --- a/packages/docusaurus-plugin-ideal-image/src/index.ts +++ b/packages/docusaurus-plugin-ideal-image/src/index.ts @@ -80,7 +80,7 @@ export function validateOptions({ validate, options, }: OptionValidationContext): PluginOptions { - const pluginOptionsSchema = Joi.object({ + const pluginOptionsSchema = Joi.object({ disableInDev: Joi.boolean().default(true), }).unknown(); return validate(pluginOptionsSchema, options); diff --git a/packages/docusaurus-plugin-ideal-image/src/theme/IdealImage/index.tsx b/packages/docusaurus-plugin-ideal-image/src/theme/IdealImage/index.tsx index ff8ea85f6f2b..fbf2d3278a9b 100644 --- a/packages/docusaurus-plugin-ideal-image/src/theme/IdealImage/index.tsx +++ b/packages/docusaurus-plugin-ideal-image/src/theme/IdealImage/index.tsx @@ -22,9 +22,9 @@ function bytesToSize(bytes: number) { } const scale = Math.floor(Math.log(bytes) / Math.log(1024)); if (scale === 0) { - return `${bytes} ${sizes[scale]}`; + return `${bytes} ${sizes[scale]!}`; } - return `${(bytes / 1024 ** scale).toFixed(1)} ${sizes[scale]}`; + return `${(bytes / 1024 ** scale).toFixed(1)} ${sizes[scale]!}`; } // Adopted from https://github.com/endiliey/react-ideal-image/blob/master/src/components/IdealImage/index.js#L43-L75 @@ -100,8 +100,8 @@ export default function IdealImage(props: Props): JSX.Element { {...props} alt={alt} className={className} - height={img.src.height || 100} - width={img.src.width || 100} + height={img.src.height ?? 100} + width={img.src.width ?? 100} placeholder={{lqip: img.preSrc}} src={img.src.src} srcSet={img.src.images.map((image) => ({ diff --git a/packages/docusaurus-plugin-pwa/src/index.ts b/packages/docusaurus-plugin-pwa/src/index.ts index 7ec58b25f439..448e7d2f9917 100644 --- a/packages/docusaurus-plugin-pwa/src/index.ts +++ b/packages/docusaurus-plugin-pwa/src/index.ts @@ -89,7 +89,7 @@ export default function pluginPWA( new webpack.EnvironmentPlugin({ PWA_DEBUG: debug, PWA_SERVICE_WORKER_URL: path.posix.resolve( - `${config.output?.publicPath || '/'}`, + `${(config.output?.publicPath as string) || '/'}`, 'sw.js', ), PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES: @@ -102,7 +102,7 @@ export default function pluginPWA( injectHtmlTags() { const headTags: HtmlTags = []; - if (isProd && pwaHead) { + if (isProd) { pwaHead.forEach(({tagName, ...attributes}) => { (['href', 'content'] as const).forEach((attribute) => { const attributeValue = attributes[attribute]; @@ -160,7 +160,7 @@ export default function pluginPWA( plugins: [ new webpack.EnvironmentPlugin({ // Fallback value required with Webpack 5 - PWA_SW_CUSTOM: swCustom || '', + PWA_SW_CUSTOM: swCustom ?? '', }), new LogPlugin({ name: 'Service Worker', @@ -189,7 +189,7 @@ export default function pluginPWA( '**/*.{png,jpg,jpeg,gif,svg,ico}', '**/*.{woff,woff2,eot,ttf,otf}', // @ts-expect-error: internal API? - ...(injectManifest.globPatterns ?? []), + ...((injectManifest.globPatterns as string[] | undefined) ?? []), ], // Those attributes are not overrideable swDest, diff --git a/packages/docusaurus-plugin-pwa/src/options.ts b/packages/docusaurus-plugin-pwa/src/options.ts index e96405756ad1..8517028f9f20 100644 --- a/packages/docusaurus-plugin-pwa/src/options.ts +++ b/packages/docusaurus-plugin-pwa/src/options.ts @@ -23,7 +23,7 @@ const DEFAULT_OPTIONS = { reloadPopup: '@theme/PwaReloadPopup', }; -const Schema = Joi.object({ +const optionsSchema = Joi.object({ debug: Joi.bool().default(DEFAULT_OPTIONS.debug), offlineModeActivationStrategies: Joi.array() .items( @@ -58,5 +58,5 @@ export function validateOptions({ validate, options, }: OptionValidationContext): PluginOptions { - return validate(Schema, options); + return validate(optionsSchema, options); } diff --git a/packages/docusaurus-plugin-pwa/src/registerSw.ts b/packages/docusaurus-plugin-pwa/src/registerSw.ts index 2bb7a92eb06b..d48e7b29b2f7 100644 --- a/packages/docusaurus-plugin-pwa/src/registerSw.ts +++ b/packages/docusaurus-plugin-pwa/src/registerSw.ts @@ -9,7 +9,7 @@ import {createStorageSlot} from '@docusaurus/theme-common'; // First: read the env variables (provided by Webpack) /* eslint-disable prefer-destructuring */ -const PWA_SERVICE_WORKER_URL = process.env.PWA_SERVICE_WORKER_URL; +const PWA_SERVICE_WORKER_URL = process.env.PWA_SERVICE_WORKER_URL!; const PWA_RELOAD_POPUP = process.env.PWA_RELOAD_POPUP; const PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES = process.env .PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES as unknown as (keyof typeof OfflineModeActivationStrategiesImplementations)[]; @@ -34,7 +34,7 @@ async function clearRegistrations() { } await Promise.all( registrations.map(async (registration) => { - const result = await registration?.unregister(); + const result = await registration.unregister(); if (debug) { console.log( `[Docusaurus-PWA][registerSw]: unregister() service worker registration`, @@ -69,7 +69,7 @@ async function isAppInstalledEventFired() { declare global { interface Navigator { getInstalledRelatedApps: () => Promise<{platform: string}[]>; - connection: {effectiveType: string; saveData: boolean}; + connection?: {effectiveType: string; saveData: boolean}; } } diff --git a/packages/docusaurus-plugin-sitemap/src/options.ts b/packages/docusaurus-plugin-sitemap/src/options.ts index 5a8302424e83..365f60156eaf 100644 --- a/packages/docusaurus-plugin-sitemap/src/options.ts +++ b/packages/docusaurus-plugin-sitemap/src/options.ts @@ -29,7 +29,8 @@ export const DEFAULT_OPTIONS: PluginOptions = { ignorePatterns: [], }; -const PluginOptionSchema = Joi.object({ +const PluginOptionSchema = Joi.object({ + // @ts-expect-error: forbidden cacheTime: Joi.forbidden().messages({ 'any.unknown': 'Option `cacheTime` in sitemap config is deprecated. Please remove it.', diff --git a/packages/docusaurus-remark-plugin-npm2yarn/src/index.ts b/packages/docusaurus-remark-plugin-npm2yarn/src/index.ts index 28b4c7e89150..39236a1537b4 100644 --- a/packages/docusaurus-remark-plugin-npm2yarn/src/index.ts +++ b/packages/docusaurus-remark-plugin-npm2yarn/src/index.ts @@ -62,8 +62,8 @@ const nodeForImport: Literal = { const plugin: Plugin<[PluginOptions?]> = (options = {}) => { const {sync = false} = options; return (root) => { - let transformed = false; - let alreadyImported = false; + let transformed = false as boolean; + let alreadyImported = false as boolean; visit(root, (node: Node) => { if (isImport(node) && node.value.includes('@theme/Tabs')) { alreadyImported = true; diff --git a/packages/docusaurus-theme-classic/src/index.ts b/packages/docusaurus-theme-classic/src/index.ts index a0cb4629cb58..c87fef7f4b7e 100644 --- a/packages/docusaurus-theme-classic/src/index.ts +++ b/packages/docusaurus-theme-classic/src/index.ts @@ -177,7 +177,7 @@ export default function themeClassic( const plugin: PostCssPlugin = { postcssPlugin: 'RtlCssPlugin', prepare: (result) => { - const file = result.root?.source?.input?.file; + const file = result.root.source?.input.file; // Skip Infima as we are using the its RTL version. if (file === resolvedInfimaFile) { return {}; diff --git a/packages/docusaurus-theme-classic/src/theme-classic.d.ts b/packages/docusaurus-theme-classic/src/theme-classic.d.ts index ef8c33023fd2..4aa679bd4946 100644 --- a/packages/docusaurus-theme-classic/src/theme-classic.d.ts +++ b/packages/docusaurus-theme-classic/src/theme-classic.d.ts @@ -21,12 +21,14 @@ // in their tsconfig. declare module '@docusaurus/theme-classic' { - import type {LoadContext, Plugin} from '@docusaurus/types'; + import type {LoadContext, Plugin, PluginModule} from '@docusaurus/types'; export type Options = { customCss?: string | string[]; }; + export const getSwizzleConfig: PluginModule['getSwizzleConfig']; + export default function themeClassic( context: LoadContext, options: Options, diff --git a/packages/docusaurus-theme-classic/src/theme/CodeBlock/Content/String.tsx b/packages/docusaurus-theme-classic/src/theme/CodeBlock/Content/String.tsx index 5a9384f7b638..9947164ddbef 100644 --- a/packages/docusaurus-theme-classic/src/theme/CodeBlock/Content/String.tsx +++ b/packages/docusaurus-theme-classic/src/theme/CodeBlock/Content/String.tsx @@ -52,7 +52,7 @@ export default function CodeBlockString({ magicComments, }); const showLineNumbers = - showLineNumbersProp || containsLineNumbers(metastring); + showLineNumbersProp ?? containsLineNumbers(metastring); return ( ) : ( -
  • +
  • ); diff --git a/packages/docusaurus-theme-common/src/components/Collapsible/index.tsx b/packages/docusaurus-theme-common/src/components/Collapsible/index.tsx index b6210a2b3660..39c6ce63fdf1 100644 --- a/packages/docusaurus-theme-common/src/components/Collapsible/index.tsx +++ b/packages/docusaurus-theme-common/src/components/Collapsible/index.tsx @@ -27,7 +27,7 @@ export function useCollapsible({ initialState, }: { /** The initial state. Will be non-collapsed by default. */ - initialState: boolean | (() => boolean); + initialState?: boolean | (() => boolean); }): { collapsed: boolean; setCollapsed: Dispatch>; diff --git a/packages/docusaurus-theme-common/src/hooks/useSkipToContent.ts b/packages/docusaurus-theme-common/src/hooks/useSkipToContent.ts index 54e6a42f3a85..bdcac465d487 100644 --- a/packages/docusaurus-theme-common/src/hooks/useSkipToContent.ts +++ b/packages/docusaurus-theme-common/src/hooks/useSkipToContent.ts @@ -40,7 +40,7 @@ export function useSkipToContent(): { e.preventDefault(); const targetElement: HTMLElement | null = - document.querySelector('main:first-of-type') || + document.querySelector('main:first-of-type') ?? document.querySelector(`.${ThemeClassNames.wrapper.main}`); if (targetElement) { diff --git a/packages/docusaurus-theme-common/src/hooks/useTOCHighlight.ts b/packages/docusaurus-theme-common/src/hooks/useTOCHighlight.ts index fca0174fe644..924ede9e09c3 100644 --- a/packages/docusaurus-theme-common/src/hooks/useTOCHighlight.ts +++ b/packages/docusaurus-theme-common/src/hooks/useTOCHighlight.ts @@ -38,15 +38,12 @@ function getAnchors({ }: { minHeadingLevel: number; maxHeadingLevel: number; -}) { +}): HTMLElement[] { const selectors = []; for (let i = minHeadingLevel; i <= maxHeadingLevel; i += 1) { selectors.push(`h${i}.anchor`); } - - return Array.from( - document.querySelectorAll(selectors.join()), - ) as HTMLElement[]; + return Array.from(document.querySelectorAll(selectors.join())); } function getActiveAnchor( diff --git a/packages/docusaurus-theme-common/src/utils/codeBlockUtils.ts b/packages/docusaurus-theme-common/src/utils/codeBlockUtils.ts index 97c9056eb297..a0d3163df88e 100644 --- a/packages/docusaurus-theme-common/src/utils/codeBlockUtils.ts +++ b/packages/docusaurus-theme-common/src/utils/codeBlockUtils.ts @@ -171,7 +171,7 @@ export function parseLines( const metastringRangeClassName = magicComments[0]!.className; const lines = rangeParser(linesRange) .filter((n) => n > 0) - .map((n) => [n - 1, [metastringRangeClassName]]); + .map((n) => [n - 1, [metastringRangeClassName]] as [number, string[]]); return {lineClassNames: Object.fromEntries(lines), code}; } if (language === undefined) { @@ -189,7 +189,7 @@ export function parseLines( const lineToClassName: {[comment: string]: string} = Object.fromEntries( magicComments .filter((d) => d.line) - .map(({className, line}) => [line, className]), + .map(({className, line}) => [line!, className] as [string, string]), ); const blockStartToClassName: {[comment: string]: string} = Object.fromEntries( magicComments diff --git a/packages/docusaurus-theme-common/src/utils/reactUtils.tsx b/packages/docusaurus-theme-common/src/utils/reactUtils.tsx index 09cb1b7b52e7..4a7410e3fb6d 100644 --- a/packages/docusaurus-theme-common/src/utils/reactUtils.tsx +++ b/packages/docusaurus-theme-common/src/utils/reactUtils.tsx @@ -70,7 +70,7 @@ export class ReactContextError extends Error { this.name = 'ReactContextError'; this.message = `Hook ${ this.stack?.split('\n')[1]?.match(/at (?:\w+\.)?(?\w+)/)?.groups! - .name + .name ?? '' } is called outside the <${providerName}>. ${additionalInfo || ''}`; } } diff --git a/packages/docusaurus-theme-common/src/utils/routesUtils.ts b/packages/docusaurus-theme-common/src/utils/routesUtils.ts index 4faa24b675a0..b662ab4bf23d 100644 --- a/packages/docusaurus-theme-common/src/utils/routesUtils.ts +++ b/packages/docusaurus-theme-common/src/utils/routesUtils.ts @@ -18,7 +18,7 @@ export function isSamePath( path2: string | undefined, ): boolean { const normalize = (pathname: string | undefined) => - (!pathname || pathname?.endsWith('/') + (!pathname || pathname.endsWith('/') ? pathname : `${pathname}/` )?.toLowerCase(); diff --git a/packages/docusaurus-theme-common/src/utils/scrollUtils.tsx b/packages/docusaurus-theme-common/src/utils/scrollUtils.tsx index 32095c3feac3..514222d18ac0 100644 --- a/packages/docusaurus-theme-common/src/utils/scrollUtils.tsx +++ b/packages/docusaurus-theme-common/src/utils/scrollUtils.tsx @@ -112,11 +112,7 @@ export function useScrollPosition( return; } const currentPosition = getScrollPosition()!; - - if (dynamicEffect) { - dynamicEffect(currentPosition, lastPositionRef.current); - } - + dynamicEffect(currentPosition, lastPositionRef.current); lastPositionRef.current = currentPosition; }; diff --git a/packages/docusaurus-theme-common/src/utils/searchUtils.ts b/packages/docusaurus-theme-common/src/utils/searchUtils.ts index 7f6fe91e48f0..082f0fb7085c 100644 --- a/packages/docusaurus-theme-common/src/utils/searchUtils.ts +++ b/packages/docusaurus-theme-common/src/utils/searchUtils.ts @@ -39,7 +39,7 @@ export function useContextualSearchFilters(): {locale: string; tags: string[]} { // plugin instances. function getDocPluginTags(pluginId: string) { const activeVersion = - activePluginAndVersion?.activePlugin?.pluginId === pluginId + activePluginAndVersion?.activePlugin.pluginId === pluginId ? activePluginAndVersion.activeVersion : undefined; diff --git a/packages/docusaurus-theme-common/src/utils/tocUtils.ts b/packages/docusaurus-theme-common/src/utils/tocUtils.ts index 8f12d780719d..64be4cb51191 100644 --- a/packages/docusaurus-theme-common/src/utils/tocUtils.ts +++ b/packages/docusaurus-theme-common/src/utils/tocUtils.ts @@ -27,7 +27,7 @@ function treeifyTOC(flatTOC: readonly TOCItem[]): TOCTreeNode[] { // level . We will modify these indices as we iterate through all headings. // e.g. if an ### H3 was last seen at index 2, then prevIndexForLevel[3] === 2 // indices 0 and 1 will remain unused. - const prevIndexForLevel = Array(7).fill(-1); + const prevIndexForLevel = Array(7).fill(-1); headings.forEach((curr, currIndex) => { // Take the last seen index for each ancestor level. the highest index will diff --git a/packages/docusaurus-theme-common/src/utils/usePluralForm.ts b/packages/docusaurus-theme-common/src/utils/usePluralForm.ts index cc5ce45317bf..726d406db2d7 100644 --- a/packages/docusaurus-theme-common/src/utils/usePluralForm.ts +++ b/packages/docusaurus-theme-common/src/utils/usePluralForm.ts @@ -95,7 +95,11 @@ function selectPluralMessage( } if (parts.length > localePluralForms.pluralForms.length) { console.error( - `For locale=${localePluralForms.locale}, a maximum of ${localePluralForms.pluralForms.length} plural forms are expected (${localePluralForms.pluralForms}), but the message contains ${parts.length}: ${pluralMessages}`, + `For locale=${localePluralForms.locale}, a maximum of ${ + localePluralForms.pluralForms.length + } plural forms are expected (${localePluralForms.pluralForms.join( + ',', + )}), but the message contains ${parts.length}: ${pluralMessages}`, ); } const pluralForm = localePluralForms.select(count); diff --git a/packages/docusaurus-theme-live-codeblock/src/validateThemeConfig.ts b/packages/docusaurus-theme-live-codeblock/src/validateThemeConfig.ts index 4b9fb583be03..d642214987de 100644 --- a/packages/docusaurus-theme-live-codeblock/src/validateThemeConfig.ts +++ b/packages/docusaurus-theme-live-codeblock/src/validateThemeConfig.ts @@ -15,7 +15,7 @@ export const DEFAULT_CONFIG = { playgroundPosition: 'bottom', }; -export const Schema = Joi.object({ +export const Schema = Joi.object({ liveCodeBlock: Joi.object({ playgroundPosition: Joi.string() .equal('top', 'bottom') diff --git a/packages/docusaurus-theme-search-algolia/src/index.ts b/packages/docusaurus-theme-search-algolia/src/index.ts index dbd2a58db30c..af54aafba33f 100644 --- a/packages/docusaurus-theme-search-algolia/src/index.ts +++ b/packages/docusaurus-theme-search-algolia/src/index.ts @@ -60,7 +60,7 @@ export default function themeSearchAlgolia(context: LoadContext): Plugin { }); }, - async contentLoaded({actions: {addRoute}}) { + contentLoaded({actions: {addRoute}}) { if (searchPagePath) { addRoute({ path: normalizeUrl([baseUrl, searchPagePath]), diff --git a/packages/docusaurus-theme-search-algolia/src/validateThemeConfig.ts b/packages/docusaurus-theme-search-algolia/src/validateThemeConfig.ts index 68bd60d163a1..a2a2ccd7869e 100644 --- a/packages/docusaurus-theme-search-algolia/src/validateThemeConfig.ts +++ b/packages/docusaurus-theme-search-algolia/src/validateThemeConfig.ts @@ -20,7 +20,7 @@ export const DEFAULT_CONFIG = { searchPagePath: 'search', }; -export const Schema = Joi.object({ +export const Schema = Joi.object({ algolia: Joi.object({ // Docusaurus attributes contextualSearch: Joi.boolean().default(DEFAULT_CONFIG.contextualSearch), diff --git a/packages/docusaurus-theme-translations/src/index.ts b/packages/docusaurus-theme-translations/src/index.ts index f6b7e7303e19..8b9afb841d90 100644 --- a/packages/docusaurus-theme-translations/src/index.ts +++ b/packages/docusaurus-theme-translations/src/index.ts @@ -25,9 +25,9 @@ export function codeTranslationLocalesToTry(locale: string): string[] { // unresolved except for simply locales locale, // "zh-CN" / "pt-BR" - `${maximizedLocale.language}-${maximizedLocale.region}`, + `${maximizedLocale.language!}-${maximizedLocale.region!}`, // "zh-Hans" / "pt-Latn" - `${maximizedLocale.language}-${maximizedLocale.script}`, + `${maximizedLocale.language!}-${maximizedLocale.script!}`, // "zh" / "pt" maximizedLocale.language!, ]; diff --git a/packages/docusaurus-utils-validation/src/JoiFrontMatter.ts b/packages/docusaurus-utils-validation/src/JoiFrontMatter.ts index b09f528ec14d..5de48285cc38 100644 --- a/packages/docusaurus-utils-validation/src/JoiFrontMatter.ts +++ b/packages/docusaurus-utils-validation/src/JoiFrontMatter.ts @@ -28,4 +28,4 @@ const JoiFrontMatterString: Joi.Extension = { * @see https://github.com/facebook/docusaurus/issues/4642 * @see https://github.com/sideway/joi/issues/1442#issuecomment-823997884 */ -export const JoiFrontMatter: typeof Joi = Joi.extend(JoiFrontMatterString); +export const JoiFrontMatter = Joi.extend(JoiFrontMatterString) as typeof Joi; diff --git a/packages/docusaurus-utils/src/pathUtils.ts b/packages/docusaurus-utils/src/pathUtils.ts index a9fbb0bd98f7..35b8bd2656e8 100644 --- a/packages/docusaurus-utils/src/pathUtils.ts +++ b/packages/docusaurus-utils/src/pathUtils.ts @@ -56,7 +56,7 @@ export function shortName(str: string): string { * Adopted from https://github.com/sindresorhus/slash/blob/main/index.js */ export function posixPath(str: string): string { - const isExtendedLengthPath = /^\\\\\?\\/.test(str); + const isExtendedLengthPath = str.startsWith('\\\\?\\'); // Forward slashes are only valid Windows paths when they don't contain non- // ascii characters. diff --git a/packages/docusaurus-utils/src/urlUtils.ts b/packages/docusaurus-utils/src/urlUtils.ts index 708d50dbfe57..06694a00bd09 100644 --- a/packages/docusaurus-utils/src/urlUtils.ts +++ b/packages/docusaurus-utils/src/urlUtils.ts @@ -72,11 +72,11 @@ export function normalizeUrl(rawUrls: string[]): string { /^\/+/, // Special case where the first element of rawUrls is empty // ["", "/hello"] => /hello - component[0] === '/' && !hasStartingSlash ? '/' : '', + component.startsWith('/') && !hasStartingSlash ? '/' : '', ); } - hasEndingSlash = component[component.length - 1] === '/'; + hasEndingSlash = component.endsWith('/'); // Removing the ending slashes for each component but the last. For the // last component we will combine multiple slashes to a single one. component = component.replace(/\/+$/, i < urls.length - 1 ? '' : '/'); @@ -95,7 +95,7 @@ export function normalizeUrl(rawUrls: string[]): string { // Replace ? in parameters with &. const parts = str.split('?'); - str = parts.shift() + (parts.length > 0 ? '?' : '') + parts.join('&'); + str = parts.shift()! + (parts.length > 0 ? '?' : '') + parts.join('&'); // Dedupe forward slashes in the entire path, avoiding protocol slashes. str = str.replace(/(?[^:/]\/)\/+/g, '$1'); diff --git a/packages/docusaurus/src/client/docusaurus.ts b/packages/docusaurus/src/client/docusaurus.ts index 80fa879e30cb..987f931ede0a 100644 --- a/packages/docusaurus/src/client/docusaurus.ts +++ b/packages/docusaurus/src/client/docusaurus.ts @@ -19,7 +19,7 @@ declare global { // eslint-disable-next-line camelcase, no-underscore-dangle const __webpack_require__: {gca: (name: string) => string}; interface Navigator { - connection: {effectiveType: string; saveData: boolean}; + connection?: {effectiveType: string; saveData: boolean}; } } diff --git a/packages/docusaurus/src/client/exports/useBaseUrl.ts b/packages/docusaurus/src/client/exports/useBaseUrl.ts index 174ea539c1b7..c5481e57670f 100644 --- a/packages/docusaurus/src/client/exports/useBaseUrl.ts +++ b/packages/docusaurus/src/client/exports/useBaseUrl.ts @@ -10,7 +10,7 @@ import {hasProtocol} from './isInternalUrl'; import type {BaseUrlOptions, BaseUrlUtils} from '@docusaurus/useBaseUrl'; function addBaseUrl( - siteUrl: string | undefined, + siteUrl: string, baseUrl: string, url: string, {forcePrependBaseUrl = false, absolute = false}: BaseUrlOptions = {}, diff --git a/packages/docusaurus/src/commands/serve.ts b/packages/docusaurus/src/commands/serve.ts index da94dc86678d..64845cb5ced4 100644 --- a/packages/docusaurus/src/commands/serve.ts +++ b/packages/docusaurus/src/commands/serve.ts @@ -66,7 +66,7 @@ export async function serve( // Remove baseUrl before calling serveHandler, because /baseUrl/ should // serve /build/index.html, not /build/baseUrl/index.html (does not exist) - req.url = req.url?.replace(baseUrl, '/'); + req.url = req.url.replace(baseUrl, '/'); serveHandler(req, res, { cleanUrls: true, diff --git a/packages/docusaurus/src/commands/swizzle/__tests__/config.test.ts b/packages/docusaurus/src/commands/swizzle/__tests__/config.test.ts index cb924a626ffc..8042d3d51dae 100644 --- a/packages/docusaurus/src/commands/swizzle/__tests__/config.test.ts +++ b/packages/docusaurus/src/commands/swizzle/__tests__/config.test.ts @@ -9,14 +9,14 @@ import {normalizeSwizzleConfig} from '../config'; import type {SwizzleConfig} from '@docusaurus/types'; describe('normalizeSwizzleConfig', () => { - it(`validate no components config`, async () => { + it(`validate no components config`, () => { const config: SwizzleConfig = { components: {}, }; expect(normalizeSwizzleConfig(config)).toEqual(config); }); - it(`validate complete config`, async () => { + it(`validate complete config`, () => { const config: SwizzleConfig = { components: { SomeComponent: { @@ -38,7 +38,7 @@ describe('normalizeSwizzleConfig', () => { expect(normalizeSwizzleConfig(config)).toEqual(config); }); - it(`normalize partial config`, async () => { + it(`normalize partial config`, () => { const config: SwizzleConfig = { components: { SomeComponent: { @@ -59,7 +59,7 @@ describe('normalizeSwizzleConfig', () => { expect(normalizeSwizzleConfig(config)).toMatchSnapshot(); }); - it(`reject missing components`, async () => { + it(`reject missing components`, () => { // @ts-expect-error: incomplete actions map const config: SwizzleConfig = {}; @@ -70,7 +70,7 @@ describe('normalizeSwizzleConfig', () => { ); }); - it(`reject invalid action name`, async () => { + it(`reject invalid action name`, () => { const config: SwizzleConfig = { components: { MyComponent: { @@ -91,7 +91,7 @@ describe('normalizeSwizzleConfig', () => { ); }); - it(`reject invalid action status`, async () => { + it(`reject invalid action status`, () => { const config: SwizzleConfig = { components: { MyComponent: { diff --git a/packages/docusaurus/src/commands/swizzle/actions.ts b/packages/docusaurus/src/commands/swizzle/actions.ts index e295f8c2bd2d..44aba75cca13 100644 --- a/packages/docusaurus/src/commands/swizzle/actions.ts +++ b/packages/docusaurus/src/commands/swizzle/actions.ts @@ -109,7 +109,7 @@ export async function wrap({ const isDirectory = await isDir(path.join(themePath, themeComponentName)); // Top/Parent/ComponentName => ComponentName - const componentName = _.last(themeComponentName.split('/')); + const componentName = _.last(themeComponentName.split('/'))!; const wrapperComponentName = `${componentName}Wrapper`; const wrapperFileName = `${themeComponentName}${isDirectory ? '/index' : ''}${ diff --git a/packages/docusaurus/src/commands/swizzle/config.ts b/packages/docusaurus/src/commands/swizzle/config.ts index 83f0bbe75101..b72f30cc60c9 100644 --- a/packages/docusaurus/src/commands/swizzle/config.ts +++ b/packages/docusaurus/src/commands/swizzle/config.ts @@ -16,9 +16,8 @@ function getModuleSwizzleConfig( swizzlePlugin: SwizzlePlugin, ): SwizzleConfig | undefined { const getSwizzleConfig = - swizzlePlugin.plugin.plugin?.getSwizzleConfig ?? - swizzlePlugin.plugin.pluginModule?.module.getSwizzleConfig ?? - swizzlePlugin.plugin.pluginModule?.module?.getSwizzleConfig; + swizzlePlugin.plugin.plugin.getSwizzleConfig ?? + swizzlePlugin.plugin.pluginModule?.module.getSwizzleConfig; if (getSwizzleConfig) { return getSwizzleConfig(); @@ -26,9 +25,8 @@ function getModuleSwizzleConfig( // TODO deprecate getSwizzleComponentList later const getSwizzleComponentList = - swizzlePlugin.plugin.plugin?.getSwizzleComponentList ?? - swizzlePlugin.plugin.pluginModule?.module.getSwizzleComponentList ?? - swizzlePlugin.plugin.pluginModule?.module?.getSwizzleComponentList; + swizzlePlugin.plugin.plugin.getSwizzleComponentList ?? + swizzlePlugin.plugin.pluginModule?.module.getSwizzleComponentList; if (getSwizzleComponentList) { const safeComponents = getSwizzleComponentList() ?? []; diff --git a/packages/docusaurus/src/commands/swizzle/themes.ts b/packages/docusaurus/src/commands/swizzle/themes.ts index c31b0f28dd8b..84961dd9716c 100644 --- a/packages/docusaurus/src/commands/swizzle/themes.ts +++ b/packages/docusaurus/src/commands/swizzle/themes.ts @@ -15,7 +15,7 @@ import {findStringIgnoringCase, type SwizzlePlugin} from './common'; export function pluginToThemeName(plugin: SwizzlePlugin): string | undefined { if (plugin.instance.getThemePath) { return ( - (plugin.instance.version as {name: string}).name ?? plugin.instance.name + (plugin.instance.version as {name?: string}).name ?? plugin.instance.name ); } return undefined; @@ -76,9 +76,7 @@ function handleInvalidThemeName({ // TODO recover from short theme-names here: "classic" => "@docusaurus/theme-classic" // No recovery value is possible: print error - const suggestion = themeNames.find( - (name) => leven(name, themeNameParam!) < 4, - ); + const suggestion = themeNames.find((name) => leven(name, themeNameParam) < 4); logger.error`Theme name=${themeNameParam} not found. ${ suggestion ? logger.interpolate`Did you mean name=${suggestion}?` @@ -87,13 +85,13 @@ function handleInvalidThemeName({ return process.exit(1); } -async function validateThemeName({ +function validateThemeName({ themeNameParam, themeNames, }: { themeNameParam: string; themeNames: string[]; -}): Promise { +}): string { const isValidName = themeNames.includes(themeNameParam); if (!isValidName) { return handleInvalidThemeName({ diff --git a/packages/docusaurus/src/commands/writeHeadingIds.ts b/packages/docusaurus/src/commands/writeHeadingIds.ts index fe15c0b1f3ef..73bc699c25b3 100644 --- a/packages/docusaurus/src/commands/writeHeadingIds.ts +++ b/packages/docusaurus/src/commands/writeHeadingIds.ts @@ -37,12 +37,12 @@ async function transformMarkdownFile( async function getPathsToWatch(siteDir: string): Promise { const context = await loadContext({siteDir}); const plugins = await initPlugins(context); - return plugins.flatMap((plugin) => plugin?.getPathsToWatch?.() ?? []); + return plugins.flatMap((plugin) => plugin.getPathsToWatch?.() ?? []); } export async function writeHeadingIds( siteDir: string, - files: string[], + files: string[] | undefined, options: WriteHeadingIDOptions, ): Promise { const markdownFiles = await safeGlobby( diff --git a/packages/docusaurus/src/deps.d.ts b/packages/docusaurus/src/deps.d.ts index 06f478ca6330..57de485ea0ce 100644 --- a/packages/docusaurus/src/deps.d.ts +++ b/packages/docusaurus/src/deps.d.ts @@ -20,13 +20,13 @@ declare module 'react-loadable-ssr-addon-v5-slorber' { export type Manifest = { entrypoints: string[]; origins: {[key: string]: number[]}; - assets: Array<{[key: string]: Asset[]}>; + assets: {[key: string]: Asset[]}[]; }; export function getBundles( manifest: Manifest, modulesToBeLoaded: string[], - ): {js: Asset[]; css: Asset[]}; + ): {js?: Asset[]; css?: Asset[]}; export default class ReactLoadableSSRAddon implements WebpackPluginInstance { constructor(props: {filename: string}); diff --git a/packages/docusaurus/src/server/plugins/configs.ts b/packages/docusaurus/src/server/plugins/configs.ts index b7b7bbf6ccd4..eb2898e5d312 100644 --- a/packages/docusaurus/src/server/plugins/configs.ts +++ b/packages/docusaurus/src/server/plugins/configs.ts @@ -63,7 +63,7 @@ async function normalizePluginConfig( const pluginPath = pluginRequire.resolve(pluginModuleImport); const pluginModule = importFresh(pluginPath); return { - plugin: pluginModule?.default ?? pluginModule, + plugin: pluginModule.default ?? pluginModule, options: {}, pluginModule: { path: pluginModuleImport, @@ -90,7 +90,7 @@ async function normalizePluginConfig( const pluginPath = pluginRequire.resolve(pluginModuleImport); const pluginModule = importFresh(pluginPath); return { - plugin: pluginModule?.default ?? pluginModule, + plugin: pluginModule.default ?? pluginModule, options: pluginConfig[1], pluginModule: { path: pluginModuleImport, diff --git a/packages/docusaurus/src/server/plugins/index.ts b/packages/docusaurus/src/server/plugins/index.ts index 812ea7b2e80e..5a8dbb98d095 100644 --- a/packages/docusaurus/src/server/plugins/index.ts +++ b/packages/docusaurus/src/server/plugins/index.ts @@ -52,7 +52,7 @@ export async function loadPlugins(context: LoadContext): Promise<{ plugins.map(async (plugin) => { const content = await plugin.loadContent?.(); const rawTranslationFiles = - (await plugin?.getTranslationFiles?.({content})) ?? []; + (await plugin.getTranslationFiles?.({content})) ?? []; const translationFiles = await Promise.all( rawTranslationFiles.map((translationFile) => localizePluginTranslationFile({ diff --git a/packages/docusaurus/src/server/plugins/init.ts b/packages/docusaurus/src/server/plugins/init.ts index 771a407cccb5..c19f82d15b80 100644 --- a/packages/docusaurus/src/server/plugins/init.ts +++ b/packages/docusaurus/src/server/plugins/init.ts @@ -29,8 +29,8 @@ function getOptionValidationFunction( if (normalizedPluginConfig.pluginModule) { // Support both CommonJS and ES modules return ( - normalizedPluginConfig.pluginModule.module?.default?.validateOptions ?? - normalizedPluginConfig.pluginModule.module?.validateOptions + normalizedPluginConfig.pluginModule.module.default?.validateOptions ?? + normalizedPluginConfig.pluginModule.module.validateOptions ); } return normalizedPluginConfig.plugin.validateOptions; @@ -66,7 +66,7 @@ export async function initPlugins( ): Promise { if (normalizedPluginConfig.pluginModule?.path) { const pluginPath = pluginRequire.resolve( - normalizedPluginConfig.pluginModule?.path, + normalizedPluginConfig.pluginModule.path, ); return getPluginVersion(pluginPath, context.siteDir); } diff --git a/packages/docusaurus/src/server/plugins/moduleShorthand.ts b/packages/docusaurus/src/server/plugins/moduleShorthand.ts index df0ab5570d43..5a106e88fe30 100644 --- a/packages/docusaurus/src/server/plugins/moduleShorthand.ts +++ b/packages/docusaurus/src/server/plugins/moduleShorthand.ts @@ -14,7 +14,10 @@ export function getNamePatterns( if (!moduleName.includes('/')) { return [`${moduleName}/docusaurus-${moduleType}`]; } - const [scope, packageName] = moduleName.split(/\/(?.*)/); + const [scope, packageName] = moduleName.split(/\/(?.*)/) as [ + string, + string, + ]; return [ `${scope}/${packageName}`, `${scope}/docusaurus-${moduleType}-${packageName}`, diff --git a/packages/docusaurus/src/server/plugins/routeConfig.ts b/packages/docusaurus/src/server/plugins/routeConfig.ts index e9b7c589408f..3731eb993d74 100644 --- a/packages/docusaurus/src/server/plugins/routeConfig.ts +++ b/packages/docusaurus/src/server/plugins/routeConfig.ts @@ -50,8 +50,8 @@ export function sortConfig( } // Higher priority get placed first. if (a.priority || b.priority) { - const priorityA = a.priority || 0; - const priorityB = b.priority || 0; + const priorityA = a.priority ?? 0; + const priorityB = b.priority ?? 0; const score = priorityB - priorityA; if (score !== 0) { diff --git a/packages/docusaurus/src/server/plugins/synthetic.ts b/packages/docusaurus/src/server/plugins/synthetic.ts index 67e297ffe5f5..5d4fe38b4d01 100644 --- a/packages/docusaurus/src/server/plugins/synthetic.ts +++ b/packages/docusaurus/src/server/plugins/synthetic.ts @@ -89,7 +89,7 @@ export function createMDXFallbackPlugin({ // processed by content plugins mdx loaders. This works, but a bit // hacky... Not sure there's a way to handle that differently in webpack function getMDXFallbackExcludedPaths(): string[] { - const rules: RuleSetRule[] = config?.module?.rules as RuleSetRule[]; + const rules: RuleSetRule[] = config.module?.rules as RuleSetRule[]; return rules.flatMap((rule) => { const isMDXRule = rule.test instanceof RegExp && rule.test.test('x.mdx'); diff --git a/packages/docusaurus/src/server/routes.ts b/packages/docusaurus/src/server/routes.ts index ab97b1a7b9d7..b13c8cd9b11a 100644 --- a/packages/docusaurus/src/server/routes.ts +++ b/packages/docusaurus/src/server/routes.ts @@ -152,7 +152,7 @@ const isModule = (value: unknown): value is Module => typeof value === 'string' || (typeof value === 'object' && // eslint-disable-next-line no-underscore-dangle - !!(value as {[key: string]: unknown})?.__import); + !!(value as {[key: string]: unknown} | null)?.__import); /** * Takes a {@link Module} (which is nothing more than a path plus some metadata diff --git a/packages/docusaurus/src/server/translations/translationsExtractor.ts b/packages/docusaurus/src/server/translations/translationsExtractor.ts index 6113b23ba933..83be6bcd7503 100644 --- a/packages/docusaurus/src/server/translations/translationsExtractor.ts +++ b/packages/docusaurus/src/server/translations/translationsExtractor.ts @@ -160,7 +160,7 @@ export async function extractSourceCodeFileTranslations( filename: sourceCodeFilePath, }) as Node; - const translations = await extractSourceCodeAstTranslations( + const translations = extractSourceCodeAstTranslations( ast, sourceCodeFilePath, ); @@ -243,9 +243,7 @@ Full code: ${generate(node).code}`; .find( (attr) => attr.isJSXAttribute() && - (attr as NodePath) - .get('name') - .isJSXIdentifier({name: propName}), + attr.get('name').isJSXIdentifier({name: propName}), ); if (attributePath) { diff --git a/packages/docusaurus/src/webpack/base.ts b/packages/docusaurus/src/webpack/base.ts index 4e00fecefaf1..0b66a8d539be 100644 --- a/packages/docusaurus/src/webpack/base.ts +++ b/packages/docusaurus/src/webpack/base.ts @@ -38,7 +38,7 @@ export function excludeJS(modulePath: string): boolean { } // Don't transpile node_modules except any docusaurus npm package return ( - /node_modules/.test(modulePath) && + modulePath.includes('node_modules') && !/docusaurus(?:(?!node_modules).)*\.jsx?$/.test(modulePath) && !LibrariesToTranspileRegex.test(modulePath) ); diff --git a/packages/docusaurus/src/webpack/plugins/CleanWebpackPlugin.ts b/packages/docusaurus/src/webpack/plugins/CleanWebpackPlugin.ts index 5a8f4770102a..a87d2dcfda05 100644 --- a/packages/docusaurus/src/webpack/plugins/CleanWebpackPlugin.ts +++ b/packages/docusaurus/src/webpack/plugins/CleanWebpackPlugin.ts @@ -116,7 +116,7 @@ export default class CleanWebpackPlugin { } apply(compiler: Compiler): void { - if (!compiler.options.output || !compiler.options.output.path) { + if (!compiler.options.output.path) { console.warn( 'clean-webpack-plugin: options.output.path not defined. Plugin disabled...', ); @@ -185,7 +185,7 @@ export default class CleanWebpackPlugin { * (relies on del's cwd: outputPath option) */ const staleFiles = this.currentAssets.filter( - (previousAsset) => assets.includes(previousAsset) === false, + (previousAsset) => !assets.includes(previousAsset), ); /** @@ -198,7 +198,7 @@ export default class CleanWebpackPlugin { /** * Remove unused webpack assets */ - if (this.cleanStaleWebpackAssets === true && staleFiles.length !== 0) { + if (this.cleanStaleWebpackAssets && staleFiles.length !== 0) { removePatterns.push(...staleFiles); } @@ -234,10 +234,9 @@ export default class CleanWebpackPlugin { }); } } catch (err) { - const needsForce = - /Cannot delete files\/folders outside the current working directory\./.test( - (err as Error).message, - ); + const needsForce = (err as Error).message.includes( + 'Cannot delete files/folders outside the current working directory.', + ); if (needsForce) { const message = diff --git a/packages/docusaurus/src/webpack/utils.ts b/packages/docusaurus/src/webpack/utils.ts index 79362887679e..8a7d0aef6120 100644 --- a/packages/docusaurus/src/webpack/utils.ts +++ b/packages/docusaurus/src/webpack/utils.ts @@ -185,13 +185,11 @@ export function applyConfigureWebpack( if (typeof configureWebpack === 'function') { const {mergeStrategy, ...res} = configureWebpack(config, isServer, utils, content) ?? {}; - if (res && typeof res === 'object') { - const customizeRules = mergeStrategy ?? {}; - return mergeWithCustomize({ - customizeArray: customizeArray(customizeRules), - customizeObject: customizeObject(customizeRules), - })(config, res); - } + const customizeRules = mergeStrategy ?? {}; + return mergeWithCustomize({ + customizeArray: customizeArray(customizeRules), + customizeObject: customizeObject(customizeRules), + })(config, res); } return config; } @@ -243,7 +241,7 @@ export function compile(config: Configuration[]): Promise { const compiler = webpack(config); compiler.run((err, stats) => { if (err) { - logger.error(err.stack || err); + logger.error(err.stack ?? err); if (err.details) { logger.error(err.details); } diff --git a/packages/lqip-loader/src/index.ts b/packages/lqip-loader/src/index.ts index 6bb0eb526240..5dd78269439c 100644 --- a/packages/lqip-loader/src/index.ts +++ b/packages/lqip-loader/src/index.ts @@ -17,9 +17,7 @@ export default async function lqipLoader( this: LoaderContext, contentBuffer: Buffer, ): Promise { - if (this.cacheable) { - this.cacheable(); - } + this.cacheable(); const callback = this.async(); const imgPath = this.resourcePath; let content = contentBuffer.toString('utf8'); diff --git a/packages/stylelint-copyright/src/index.ts b/packages/stylelint-copyright/src/index.ts index a620d184d0a0..0b591561ea0e 100644 --- a/packages/stylelint-copyright/src/index.ts +++ b/packages/stylelint-copyright/src/index.ts @@ -27,7 +27,8 @@ const plugin = stylelint.createPlugin( }, { actual: secondaryOption, - possible: (v) => typeof (v as SecondaryOption)?.header === 'string', + possible: (v) => + typeof (v as SecondaryOption | undefined)?.header === 'string', }, ); @@ -42,7 +43,7 @@ const plugin = stylelint.createPlugin( } } if (context.fix) { - root.first?.before(`/*${secondaryOption.header}\n */`); + root.first?.before(`/*${secondaryOption.header!}\n */`); return; } diff --git a/website/_dogfooding/docs-tests-sidebars.js b/website/_dogfooding/docs-tests-sidebars.js index 6b8b8f9c4365..e7ebb55ce1a5 100644 --- a/website/_dogfooding/docs-tests-sidebars.js +++ b/website/_dogfooding/docs-tests-sidebars.js @@ -5,7 +5,12 @@ * LICENSE file in the root directory of this source tree. */ -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ +/** + * @typedef {import('@docusaurus/plugin-content-docs').SidebarsConfig} SidebarsConfig + * @typedef {import('@docusaurus/plugin-content-docs/lib/sidebars/types').SidebarItemConfig} SidebarItemConfig + */ + +/** @type {SidebarsConfig} */ const sidebars = { sidebar: [ { @@ -119,6 +124,11 @@ function generateHugeSidebarItems() { const linksCount = 8; const categoriesCount = 8; + /** + * @param {number} maxLevel + * @param {number} currentLevel + * @returns {SidebarItemConfig[]} + */ function generateRecursive(maxLevel, currentLevel = 0) { if (currentLevel === maxLevel) { return [ @@ -130,17 +140,19 @@ function generateHugeSidebarItems() { ]; } - const linkItems = [...Array(linksCount).keys()].map((index) => ({ + const linkItems = Array.from(Array(linksCount).keys()).map((index) => ({ type: 'link', href: '/', label: `Link ${index} (level ${currentLevel + 1})`, })); - const categoryItems = [...Array(categoriesCount).keys()].map((index) => ({ - type: 'category', - label: `Category ${index} (level ${currentLevel + 1})`, - items: generateRecursive(maxLevel, currentLevel + 1), - })); + const categoryItems = Array.from(Array(categoriesCount).keys()).map( + (index) => ({ + type: 'category', + label: `Category ${index} (level ${currentLevel + 1})`, + items: generateRecursive(maxLevel, currentLevel + 1), + }), + ); return [...linkItems, ...categoryItems]; } diff --git a/website/_dogfooding/testSwizzleThemeClassic.mjs b/website/_dogfooding/testSwizzleThemeClassic.mjs index ab75a7d1dafb..6f635bea5718 100644 --- a/website/_dogfooding/testSwizzleThemeClassic.mjs +++ b/website/_dogfooding/testSwizzleThemeClassic.mjs @@ -10,15 +10,16 @@ import fs from 'fs-extra'; import {fileURLToPath} from 'url'; import logger from '@docusaurus/logger'; -import ClassicTheme from '@docusaurus/theme-classic'; +import classicTheme from '@docusaurus/theme-classic'; // Unsafe imports import {readComponentNames} from '@docusaurus/core/lib/commands/swizzle/components.js'; import {normalizeSwizzleConfig} from '@docusaurus/core/lib/commands/swizzle/config.js'; import {wrap, eject} from '@docusaurus/core/lib/commands/swizzle/actions.js'; -const swizzleConfig = normalizeSwizzleConfig(ClassicTheme.getSwizzleConfig()); +const swizzleConfig = normalizeSwizzleConfig(classicTheme.getSwizzleConfig()); +/** @type {"eject" | "wrap"} */ const action = process.env.SWIZZLE_ACTION ?? 'eject'; const typescript = process.env.SWIZZLE_TYPESCRIPT === 'true'; @@ -81,14 +82,12 @@ if (action === 'wrap') { }); } +/** + * @param {string} componentName + */ function getActionStatus(componentName) { const actionStatus = swizzleConfig.components[componentName]?.actions[action] ?? 'unsafe'; - if (!actionStatus) { - throw new Error( - `Unexpected: missing action ${action} for ${componentName}`, - ); - } return actionStatus; } diff --git a/website/delayCrowdin.mjs b/website/delayCrowdin.mjs index d212e0e7c9a0..2fbb232c2f47 100644 --- a/website/delayCrowdin.mjs +++ b/website/delayCrowdin.mjs @@ -13,6 +13,9 @@ And then both try to dl the translations at the same time, and then we have a Used in conjunction with waitForCrowdin.js (which is not enough) */ +/** + * @param {number} ms + */ async function delay(ms) { return new Promise((resolve) => { setTimeout(resolve, ms); diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js index 4fe18ec4dfb3..6885a87f8667 100644 --- a/website/docusaurus.config.js +++ b/website/docusaurus.config.js @@ -49,7 +49,7 @@ const isDeployPreview = // Used to debug production build issues faster const isBuildFast = !!process.env.BUILD_FAST; -const baseUrl = process.env.BASE_URL || '/'; +const baseUrl = process.env.BASE_URL ?? '/'; // Special deployment for staging locales until they get enough translations // https://app.netlify.com/sites/docusaurus-i18n-staging diff --git a/website/src/components/APITable/index.tsx b/website/src/components/APITable/index.tsx index fb2e69366fde..b6a73d2862cf 100644 --- a/website/src/components/APITable/index.tsx +++ b/website/src/components/APITable/index.tsx @@ -68,8 +68,8 @@ const APITableRowComp = React.forwardRef(APITableRow); */ export default function APITable({children, name}: Props): JSX.Element { const [thead, tbody] = React.Children.toArray(children.props.children) as [ - ReactElement, - ReactElement, + ReactElement<{children: ReactElement[]}>, + ReactElement<{children: ReactElement[]}>, ]; const highlightedRow = useRef(null); useEffect(() => { diff --git a/website/src/components/ColorGenerator/index.tsx b/website/src/components/ColorGenerator/index.tsx index 87e68c528682..7fbcdfa03b60 100644 --- a/website/src/components/ColorGenerator/index.tsx +++ b/website/src/components/ColorGenerator/index.tsx @@ -59,7 +59,9 @@ export default function ColorGenerator(): JSX.Element { // Switch modes -> update state by stored values useEffect(() => { - const storedValues: ColorState = JSON.parse(storage.get() ?? '{}'); + const storedValues = JSON.parse( + storage.get() ?? '{}', + ) as Partial; setInputColor(storedValues.baseColor ?? DEFAULT_PRIMARY_COLOR); setBaseColor(storedValues.baseColor ?? DEFAULT_PRIMARY_COLOR); setBackground(storedValues.background ?? DEFAULT_BACKGROUND_COLOR); diff --git a/website/src/components/TeamProfileCards/index.tsx b/website/src/components/TeamProfileCards/index.tsx index 92b6858df745..d1b3d506291b 100644 --- a/website/src/components/TeamProfileCards/index.tsx +++ b/website/src/components/TeamProfileCards/index.tsx @@ -12,7 +12,7 @@ import Link from '@docusaurus/Link'; function WebsiteLink({to, children}: {to: string; children?: ReactNode}) { return ( - {children || ( + {children ?? ( website )} @@ -23,7 +23,7 @@ type ProfileProps = { className?: string; name: string; children: ReactNode; - githubUrl?: string; + githubUrl: string; twitterUrl?: string; }; diff --git a/website/src/pages/index.tsx b/website/src/pages/index.tsx index 6937b6da4ed2..00903c3c7b60 100644 --- a/website/src/pages/index.tsx +++ b/website/src/pages/index.tsx @@ -99,7 +99,7 @@ function MigrationAnnouncement() { } function TweetsSection() { - const tweetColumns: Array> = [[], [], []]; + const tweetColumns: TweetItem[][] = [[], [], []]; Tweets.filter((tweet) => tweet.showOnHomepage).forEach((tweet, i) => tweetColumns[i % 3]!.push(tweet), ); diff --git a/website/src/pages/showcase/_components/ShowcaseFilterToggle/index.tsx b/website/src/pages/showcase/_components/ShowcaseFilterToggle/index.tsx index acb4516d111f..aaada5d7618f 100644 --- a/website/src/pages/showcase/_components/ShowcaseFilterToggle/index.tsx +++ b/website/src/pages/showcase/_components/ShowcaseFilterToggle/index.tsx @@ -35,7 +35,7 @@ export default function ShowcaseFilterToggle(): JSX.Element { const searchParams = new URLSearchParams(location.search); searchParams.delete(OperatorQueryKey); if (!operator) { - searchParams.append(OperatorQueryKey, operator ? 'OR' : 'AND'); + searchParams.append(OperatorQueryKey, 'AND'); } history.push({ ...location, diff --git a/website/src/pages/showcase/_components/ShowcaseTooltip/index.tsx b/website/src/pages/showcase/_components/ShowcaseTooltip/index.tsx index bcbf5b4709b8..7087fa0e5d2d 100644 --- a/website/src/pages/showcase/_components/ShowcaseTooltip/index.tsx +++ b/website/src/pages/showcase/_components/ShowcaseTooltip/index.tsx @@ -14,7 +14,6 @@ interface Props { anchorEl?: HTMLElement | string; id: string; text: string; - delay?: number; children: React.ReactElement; } @@ -23,7 +22,6 @@ export default function Tooltip({ id, anchorEl, text, - delay, }: Props): JSX.Element { const [open, setOpen] = useState(false); const [referenceElement, setReferenceElement] = useState( @@ -84,7 +82,7 @@ export default function Tooltip({ timeout.current = window.setTimeout(() => { setOpen(true); - }, delay || 400); + }, 400); }; const handleClose = () => { @@ -113,7 +111,7 @@ export default function Tooltip({ }); } }; - }, [referenceElement, text, delay]); + }, [referenceElement, text]); return ( <> diff --git a/website/src/pages/versions.tsx b/website/src/pages/versions.tsx index 9db0ec5d10ee..4a65419b8837 100644 --- a/website/src/pages/versions.tsx +++ b/website/src/pages/versions.tsx @@ -58,38 +58,35 @@ export default function Version(): JSX.Element { - {latestVersion && ( -
    - - - Current version (Stable) - - -

    - - Here you can find the documentation for current released - version. - -

    - - - - - - - - -
    {latestVersion.label} - - - - - - - -
    -
    - )} +
    + + + Current version (Stable) + + +

    + + Here you can find the documentation for current released version. + +

    + + + + + + + + +
    {latestVersion.label} + + + + + + + +
    +
    {currentVersion !== latestVersion && (
    diff --git a/website/src/theme/ColorModeToggle.tsx b/website/src/theme/ColorModeToggle.tsx index 44f81a00ff66..85e886bc75b8 100644 --- a/website/src/theme/ColorModeToggle.tsx +++ b/website/src/theme/ColorModeToggle.tsx @@ -32,7 +32,9 @@ export default function ColorModeToggle(props: Props): JSX.Element { props.onChange(colorMode); const isDarkMode = colorMode === 'dark'; const storage = isDarkMode ? darkStorage : lightStorage; - const colorState: ColorState = JSON.parse(storage.get() ?? 'null') ?? { + const colorState = (JSON.parse( + storage.get() ?? 'null', + ) as ColorState | null) ?? { baseColor: isDarkMode ? DARK_PRIMARY_COLOR : LIGHT_PRIMARY_COLOR, background: isDarkMode ? DARK_BACKGROUND_COLOR diff --git a/website/testCSSOrder.mjs b/website/testCSSOrder.mjs index 9594c9ab3286..62422e3d4ea8 100644 --- a/website/testCSSOrder.mjs +++ b/website/testCSSOrder.mjs @@ -84,9 +84,14 @@ if (missingCSSMarkers.length > 0) { } // https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_sortby-and-_orderby -const sortBy = (key) => (a, b) => - // eslint-disable-next-line no-nested-ternary - a[key] > b[key] ? 1 : b[key] > a[key] ? -1 : 0; +const sortBy = + (/** @type {string} */ key) => + ( + /** @type {Record} */ a, + /** @type {Record} */ b, + ) => + // eslint-disable-next-line no-nested-ternary + a[key] > b[key] ? 1 : b[key] > a[key] ? -1 : 0; const sortedCSSMarkers = [...cssMarkersWithPositions] .sort(sortBy('position')) diff --git a/website/waitForCrowdin.mjs b/website/waitForCrowdin.mjs index d8e2823b5008..7a02bf0a4ed6 100644 --- a/website/waitForCrowdin.mjs +++ b/website/waitForCrowdin.mjs @@ -28,6 +28,9 @@ const token = process.env.CROWDIN_PERSONAL_TOKEN; // Set on Netlify const translations = new Translations({token}); +/** + * @param {number} ms + */ async function delay(ms) { return new Promise((resolve) => { setTimeout(resolve, ms);