@docusaurus/core 3.10.2 → 4.0.0-canary-6808

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/bin/beforeCli.mjs +9 -11
  2. package/lib/client/exports/ComponentCreator.js +0 -2
  3. package/lib/client/exports/Link.d.ts +3 -3
  4. package/lib/client/exports/Link.js +17 -17
  5. package/lib/client/exports/isInternalUrl.js +1 -1
  6. package/lib/client/preload.js +1 -3
  7. package/lib/client/serverEntry.js +1 -6
  8. package/lib/client/serverHelmetUtils.js +0 -1
  9. package/lib/commands/build/buildLocale.d.ts +1 -1
  10. package/lib/commands/build/buildLocale.js +0 -4
  11. package/lib/commands/build/buildUtils.d.ts +1 -1
  12. package/lib/commands/cli.js +3 -15
  13. package/lib/commands/deploy.js +39 -56
  14. package/lib/commands/serve.js +1 -1
  15. package/lib/commands/start/start.d.ts +3 -0
  16. package/lib/commands/start/webpack.js +18 -8
  17. package/lib/commands/swizzle/actions.js +5 -0
  18. package/lib/commands/utils/openBrowser/openBrowser.js +3 -3
  19. package/lib/commands/writeHeadingIds.js +3 -3
  20. package/lib/server/codegen/codegenRoutes.js +0 -1
  21. package/lib/server/config.js +1 -1
  22. package/lib/server/configValidation.js +10 -16
  23. package/lib/server/htmlTags.js +2 -3
  24. package/lib/server/i18n.js +2 -6
  25. package/lib/server/plugins/plugins.js +1 -9
  26. package/lib/server/site.js +1 -1
  27. package/lib/server/siteMetadata.d.ts +6 -1
  28. package/lib/server/siteMetadata.js +15 -12
  29. package/lib/server/translations/translations.js +1 -1
  30. package/lib/ssg/ssgEnv.js +2 -3
  31. package/lib/ssg/ssgExecutor.js +22 -5
  32. package/lib/ssg/ssgGlobalResult.js +1 -10
  33. package/lib/ssg/ssgParams.d.ts +0 -1
  34. package/lib/ssg/ssgParams.js +0 -1
  35. package/lib/ssg/ssgRenderer.js +1 -5
  36. package/lib/ssg/ssgTemplate.js +4 -6
  37. package/lib/ssg/ssgWorkerThread.js +0 -1
  38. package/lib/webpack/base.js +12 -22
  39. package/lib/webpack/server.js +1 -1
  40. package/lib/webpack/utils/getHttpsConfig.js +2 -2
  41. package/package.json +40 -39
package/bin/beforeCli.mjs CHANGED
@@ -10,14 +10,14 @@
10
10
  import fs from 'fs-extra';
11
11
  import path from 'path';
12
12
  import {createRequire} from 'module';
13
- import execa from 'execa';
13
+ import {execa} from 'execa';
14
14
  import {logger} from '@docusaurus/logger';
15
15
  import semver from 'semver';
16
16
  import updateNotifier from 'update-notifier';
17
17
  import boxen from 'boxen';
18
18
  import {DOCUSAURUS_VERSION} from '@docusaurus/utils';
19
19
 
20
- const packageJson = /** @type {import("../package.json")} */ (
20
+ const packageJson = /** @type {typeof import("../package.json")} */ (
21
21
  createRequire(import.meta.url)('../package.json')
22
22
  );
23
23
  /** @type {Record<string, any>} */
@@ -111,15 +111,13 @@ export default async function beforeCli() {
111
111
  return undefined;
112
112
  }
113
113
 
114
- const yarnVersionResult = await execa.command('yarn --version');
115
- if (yarnVersionResult.exitCode === 0) {
116
- const majorVersion = parseInt(
117
- yarnVersionResult.stdout?.trim().split('.')[0] ?? '',
118
- 10,
119
- );
120
- if (!Number.isNaN(majorVersion)) {
121
- return majorVersion;
122
- }
114
+ const yarnVersionResult = await execa`yarn --version`;
115
+ const majorVersion = parseInt(
116
+ yarnVersionResult.stdout?.trim().split('.')[0] ?? '',
117
+ 10,
118
+ );
119
+ if (!Number.isNaN(majorVersion)) {
120
+ return majorVersion;
123
121
  }
124
122
 
125
123
  return undefined;
@@ -94,14 +94,12 @@ export default function ComponentCreator(path, hash) {
94
94
  });
95
95
  val[keyPaths[keyPaths.length - 1]] = chunk;
96
96
  });
97
- /* eslint-disable no-underscore-dangle */
98
97
  const Component = loadedModules.__comp;
99
98
  delete loadedModules.__comp;
100
99
  const routeContext = loadedModules.__context;
101
100
  delete loadedModules.__context;
102
101
  const routeProps = loadedModules.__props;
103
102
  delete loadedModules.__props;
104
- /* eslint-enable no-underscore-dangle */
105
103
  // Is there any way to put this RouteContextProvider upper in the tree?
106
104
  return (<RouteContextProvider value={routeContext}>
107
105
  <Component {...loadedModules} {...routeProps} {...props}/>
@@ -4,7 +4,7 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import React from 'react';
7
+ import { type ReactNode } from 'react';
8
8
  import type { Props } from '@docusaurus/Link';
9
- declare const _default: React.ForwardRefExoticComponent<Omit<Props, "ref"> & React.RefAttributes<HTMLAnchorElement>>;
10
- export default _default;
9
+ declare function Link({ isNavLink, to, href, activeClassName, isActive, 'data-noBrokenLinkCheck': noBrokenLinkCheck, autoAddBaseUrl, ...props }: Props): ReactNode;
10
+ export default Link;
@@ -4,7 +4,7 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import React, { useEffect, useImperativeHandle, useRef, } from 'react';
7
+ import React, { useCallback, useEffect, useImperativeHandle, useRef, } from 'react';
8
8
  import { NavLink, Link as RRLink } from 'react-router-dom';
9
9
  import { applyTrailingSlash } from '@docusaurus/utils-common';
10
10
  import useDocusaurusContext from './useDocusaurusContext';
@@ -18,14 +18,14 @@ import { useBaseUrlUtils } from './useBaseUrl';
18
18
  // this is because useBaseUrl() actually transforms relative links
19
19
  // like "introduction" to "/baseUrl/introduction" => bad behavior to fix
20
20
  const shouldAddBaseUrlAutomatically = (to) => to.startsWith('/');
21
- function Link({ isNavLink, to, href, activeClassName, isActive, 'data-noBrokenLinkCheck': noBrokenLinkCheck, autoAddBaseUrl = true, ...props }, forwardedRef) {
21
+ function Link({ isNavLink, to, href, activeClassName, isActive, 'data-noBrokenLinkCheck': noBrokenLinkCheck, autoAddBaseUrl = true, ...props }) {
22
22
  const { siteConfig } = useDocusaurusContext();
23
23
  const { trailingSlash, baseUrl } = siteConfig;
24
24
  const router = siteConfig.future.experimental_router;
25
25
  const { withBaseUrl } = useBaseUrlUtils();
26
26
  const brokenLinks = useBrokenLinks();
27
27
  const innerRef = useRef(null);
28
- useImperativeHandle(forwardedRef, () => innerRef.current);
28
+ useImperativeHandle(props.ref, () => innerRef.current);
29
29
  // IMPORTANT: using to or href should not change anything
30
30
  // For example, MDX links will ALWAYS give us the href props
31
31
  // Using one prop or the other should not be used to distinguish
@@ -64,18 +64,23 @@ function Link({ isNavLink, to, href, activeClassName, isActive, 'data-noBrokenLi
64
64
  const LinkComponent = (isNavLink ? NavLink : RRLink);
65
65
  const IOSupported = ExecutionEnvironment.canUseIntersectionObserver;
66
66
  const ioRef = useRef(undefined);
67
- const handleRef = (el) => {
67
+ const handleRef = useCallback((el) => {
68
68
  innerRef.current = el;
69
+ ioRef.current?.disconnect();
70
+ ioRef.current = undefined;
69
71
  if (IOSupported && el && isInternal) {
70
72
  // If IO supported and element reference found, set up Observer.
71
- ioRef.current = new window.IntersectionObserver((entries) => {
73
+ const observer = new window.IntersectionObserver((entries) => {
72
74
  entries.forEach((entry) => {
73
75
  if (el === entry.target) {
74
76
  // If element is in viewport, stop observing and run callback.
75
77
  // https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
76
78
  if (entry.isIntersecting || entry.intersectionRatio > 0) {
77
- ioRef.current.unobserve(el);
78
- ioRef.current.disconnect();
79
+ observer.unobserve(el);
80
+ observer.disconnect();
81
+ if (ioRef.current === observer) {
82
+ ioRef.current = undefined;
83
+ }
79
84
  if (targetLink != null) {
80
85
  window.docusaurus.prefetch(targetLink);
81
86
  }
@@ -84,9 +89,10 @@ function Link({ isNavLink, to, href, activeClassName, isActive, 'data-noBrokenLi
84
89
  });
85
90
  });
86
91
  // Add element to the observer.
87
- ioRef.current.observe(el);
92
+ ioRef.current = observer;
93
+ observer.observe(el);
88
94
  }
89
- };
95
+ }, [IOSupported, isInternal, targetLink]);
90
96
  const onInteractionEnter = () => {
91
97
  if (!preloaded.current && targetLink != null) {
92
98
  window.docusaurus.preload(targetLink);
@@ -100,13 +106,7 @@ function Link({ isNavLink, to, href, activeClassName, isActive, 'data-noBrokenLi
100
106
  window.docusaurus.prefetch(targetLink);
101
107
  }
102
108
  }
103
- // When unmounting, stop intersection observer from watching.
104
- return () => {
105
- if (IOSupported && ioRef.current) {
106
- ioRef.current.disconnect();
107
- }
108
- };
109
- }, [ioRef, targetLink, IOSupported, isInternal]);
109
+ }, [targetLink, IOSupported, isInternal]);
110
110
  // It is simple local anchor link targeting current page?
111
111
  const isAnchorLink = targetLink?.startsWith('#') ?? false;
112
112
  // See also RR logic:
@@ -139,4 +139,4 @@ function Link({ isNavLink, to, href, activeClassName, isActive, 'data-noBrokenLi
139
139
  // element"
140
140
  {...(isNavLink && { isActive, activeClassName })} {...testOnlyProps}/>);
141
141
  }
142
- export default React.forwardRef(Link);
142
+ export default Link;
@@ -8,7 +8,7 @@
8
8
  // Spec: https://datatracker.ietf.org/doc/html/rfc3986#section-3.1
9
9
  // In particular: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
10
10
  export function hasProtocol(url) {
11
- return /^(?:[A-Za-z][A-Za-z\d+.-]*:|\/\/)/.test(url);
11
+ return /^(?:[A-Z][A-Z\d+.-]*:|\/\/)/i.test(url);
12
12
  }
13
13
  export default function isInternalUrl(url) {
14
14
  return typeof url !== 'undefined' && !hasProtocol(url);
@@ -15,8 +15,6 @@ import { matchRoutes } from 'react-router-config';
15
15
  * @returns Promise object represents whether pathname has been preloaded
16
16
  */
17
17
  export default function preload(pathname) {
18
- const matches = Array.from(new Set([pathname, decodeURI(pathname)]))
19
- .map((p) => matchRoutes(routes, p))
20
- .flat();
18
+ const matches = Array.from(new Set([pathname, decodeURI(pathname)])).flatMap((p) => matchRoutes(routes, p));
21
19
  return Promise.all(matches.map((match) => match.route.component.preload?.()));
22
20
  }
@@ -13,7 +13,7 @@ import preload from './preload';
13
13
  import App from './App';
14
14
  import { createStatefulBrokenLinks, BrokenLinksProvider, } from './BrokenLinksContext';
15
15
  import { toPageCollectedMetadataInternal } from './serverHelmetUtils';
16
- const render = async ({ pathname, v4RemoveLegacyPostBuildHeadAttribute, }) => {
16
+ const render = async ({ pathname }) => {
17
17
  await preload(pathname);
18
18
  const modules = new Set();
19
19
  const routerContext = {};
@@ -33,11 +33,6 @@ const render = async ({ pathname, v4RemoveLegacyPostBuildHeadAttribute, }) => {
33
33
  const html = await renderToHtml(app);
34
34
  const { helmet } = helmetContext;
35
35
  const metadata = toPageCollectedMetadataInternal({ helmet });
36
- // TODO Docusaurus v4 remove with deprecated postBuild({head}) API
37
- // the returned collectedData must be serializable to run in workers
38
- if (v4RemoveLegacyPostBuildHeadAttribute) {
39
- metadata.helmet = null;
40
- }
41
36
  const collectedData = {
42
37
  metadata,
43
38
  anchors: statefulBrokenLinks.getCollectedAnchors(),
@@ -23,7 +23,6 @@ export function toPageCollectedMetadataInternal({ helmet, }) {
23
23
  const tags = getBuildMetaTags(helmet);
24
24
  const noIndex = tags.some(isNoIndexTag);
25
25
  return {
26
- helmet, // TODO Docusaurus v4 remove
27
26
  public: {
28
27
  noIndex,
29
28
  },
@@ -4,7 +4,7 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import { BuildCLIOptions } from './build';
7
+ import type { BuildCLIOptions } from './build';
8
8
  export type BuildLocaleParams = {
9
9
  siteDir: string;
10
10
  locale: string;
@@ -99,9 +99,6 @@ async function buildLocale({ siteDir, locale, cliOptions, }) {
99
99
  logger_1.default.success `Generated static files in path=${path_1.default.relative(process.cwd(), outDir)}.`;
100
100
  }
101
101
  async function executePluginsPostBuild({ plugins, props, collectedData, }) {
102
- const head = props.siteConfig.future.v4.removeLegacyPostBuildHeadAttribute
103
- ? {}
104
- : lodash_1.default.mapValues(collectedData, (d) => d.metadata.helmet);
105
102
  const routesBuildMetadata = lodash_1.default.mapValues(collectedData, (d) => d.metadata.public);
106
103
  await Promise.all(plugins.map(async (plugin) => {
107
104
  if (!plugin.postBuild) {
@@ -109,7 +106,6 @@ async function executePluginsPostBuild({ plugins, props, collectedData, }) {
109
106
  }
110
107
  await plugin.postBuild({
111
108
  ...props,
112
- head,
113
109
  routesBuildMetadata,
114
110
  content: plugin.content,
115
111
  });
@@ -4,7 +4,7 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import { BuildCLIOptions } from './build';
7
+ import type { BuildCLIOptions } from './build';
8
8
  /**
9
9
  * We disable locale path localization if CLI has a single "--locale" option
10
10
  * yarn build --locale fr => baseUrl=/ instead of baseUrl=/fr/
@@ -109,21 +109,9 @@ async function createCLIProgram({ cli, cliArgs, siteDir, config, }) {
109
109
  .option('--no-open', 'do not open page in the browser (default: false)')
110
110
  .option('--poll [interval]', 'use polling rather than watching for reload (default: false). Can specify a poll interval in milliseconds', normalizePollValue)
111
111
  .option('--no-minify', 'build website without minimizing JS bundles (default: false)')
112
- /*
113
- TODO
114
- .option(
115
- '--https',
116
- 'serve the dev site over HTTPS using a self-signed cert (default: false). Preferred over the HTTPS=true env var. Implied when both --ssl-cert and --ssl-key are provided.',
117
- )
118
- .option(
119
- '--ssl-cert <path>',
120
- 'path to a TLS certificate file (implies HTTPS). Preferred over the SSL_CRT_FILE env var; CLI takes precedence if both are set.',
121
- )
122
- .option(
123
- '--ssl-key <path>',
124
- 'path to a TLS private key file (implies HTTPS). Preferred over the SSL_KEY_FILE env var; CLI takes precedence if both are set.',
125
- )
126
- */
112
+ .option('--https', 'serve the dev site over HTTPS using a self-signed cert (default: false). Preferred over the HTTPS=true env var. Implied when both --ssl-cert and --ssl-key are provided.')
113
+ .option('--ssl-cert <path>', 'path to a TLS certificate file (implies HTTPS). Preferred over the SSL_CRT_FILE env var; CLI takes precedence if both are set.')
114
+ .option('--ssl-key <path>', 'path to a TLS private key file (implies HTTPS). Preferred over the SSL_KEY_FILE env var; CLI takes precedence if both are set.')
127
115
  .action(start_1.start);
128
116
  cli
129
117
  .command('serve [siteDir]')
@@ -12,7 +12,7 @@ const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
12
  const path_1 = tslib_1.__importDefault(require("path"));
13
13
  const os_1 = tslib_1.__importDefault(require("os"));
14
14
  const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
15
- const execa_1 = tslib_1.__importDefault(require("execa"));
15
+ const execa_1 = require("execa");
16
16
  const utils_1 = require("@docusaurus/utils");
17
17
  const site_1 = require("../server/site");
18
18
  const build_1 = require("./build/build");
@@ -24,14 +24,12 @@ function obfuscateGitPass(str) {
24
24
  const debugMode = !!process.env.DOCUSAURUS_DEPLOY_DEBUG;
25
25
  // Log executed commands so that user can figure out mistakes on his own
26
26
  // for example: https://github.com/facebook/docusaurus/issues/3875
27
- function exec(cmd, options) {
27
+ async function exec(file, args, options) {
28
28
  const log = options?.log ?? true;
29
- const failfast = options?.failfast ?? false;
29
+ const failfast = options?.failfast ?? true;
30
+ const cmd = [file, ...args].join(' ');
30
31
  try {
31
- // TODO migrate to execa(file,[...args]) instead
32
- // Use async/await everything
33
- // Avoid execa.command: the args need to be escaped manually
34
- const result = execa_1.default.commandSync(cmd);
32
+ const result = await (0, execa_1.execa)(file, args, { reject: false });
35
33
  if (log || debugMode) {
36
34
  logger_1.default.info `code=${obfuscateGitPass(cmd)} subdue=${`code: ${result.exitCode}`}`;
37
35
  }
@@ -39,7 +37,8 @@ function exec(cmd, options) {
39
37
  console.log(result);
40
38
  }
41
39
  if (failfast && result.exitCode !== 0) {
42
- throw new Error(`Command returned unexpected exitCode ${result.exitCode}`);
40
+ throw new Error(`Command returned unexpected exitCode ${result.exitCode}
41
+ ${result.stderr}`);
43
42
  }
44
43
  return result;
45
44
  }
@@ -48,13 +47,8 @@ function exec(cmd, options) {
48
47
  In CWD code=${process.cwd()}`, { cause: err });
49
48
  }
50
49
  }
51
- // Execa escape args and add necessary quotes automatically
52
- // When using Execa.command, the args containing spaces must be escaped manually
53
- function escapeArg(arg) {
54
- return arg.replaceAll(' ', '\\ ');
55
- }
56
- function hasGit() {
57
- return exec('git --version').exitCode === 0;
50
+ async function hasGit() {
51
+ return (await exec('git', ['--version'], { failfast: false })).exitCode === 0;
58
52
  }
59
53
  async function deploy(siteDirParam = '.', cliOptions = {}) {
60
54
  const siteDir = await fs_extra_1.default.realpath(siteDirParam);
@@ -70,23 +64,16 @@ This behavior can have SEO impacts and create relative link issues.
70
64
  `);
71
65
  }
72
66
  logger_1.default.info('Deploy command invoked...');
73
- if (!hasGit()) {
67
+ if (!(await hasGit())) {
74
68
  throw new Error('Git not installed or not added to PATH!');
75
69
  }
76
70
  // Source repo is the repo from where the command is invoked
77
- const { stdout } = exec('git remote get-url origin', {
71
+ const sourceRepoUrl = (await exec('git', ['remote', 'get-url', 'origin'], {
78
72
  log: false,
79
- failfast: true,
80
- });
81
- const sourceRepoUrl = stdout.trim();
73
+ })).stdout.trim();
82
74
  // The source branch; defaults to the currently checked out branch
83
75
  const sourceBranch = process.env.CURRENT_BRANCH ??
84
- exec('git rev-parse --abbrev-ref HEAD', {
85
- log: false,
86
- failfast: true,
87
- })
88
- ?.stdout?.toString()
89
- .trim();
76
+ (await exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { log: false })).stdout.trim();
90
77
  const gitUser = process.env.GIT_USER;
91
78
  let useSSH = process.env.USE_SSH !== undefined &&
92
79
  process.env.USE_SSH.toLowerCase() === 'true';
@@ -116,10 +103,7 @@ This behavior can have SEO impacts and create relative link issues.
116
103
  // We never deploy on pull request.
117
104
  const isPullRequest = process.env.CI_PULL_REQUEST ?? process.env.CIRCLE_PULL_REQUEST;
118
105
  if (isPullRequest) {
119
- exec('echo "Skipping deploy on a pull request."', {
120
- log: false,
121
- failfast: true,
122
- });
106
+ logger_1.default.info('Skipping deploy on a pull request.');
123
107
  process.exit(0);
124
108
  }
125
109
  // github.io indicates organization repos that deploy via default branch. All
@@ -158,7 +142,7 @@ You can also set the deploymentBranch property in docusaurus.config.js .`);
158
142
  }
159
143
  // Save the commit hash that triggers publish-gh-pages before checking
160
144
  // out to deployment branch.
161
- const currentCommit = exec('git rev-parse HEAD')?.stdout?.toString().trim();
145
+ const currentCommit = (await exec('git', ['rev-parse', 'HEAD'])).stdout.trim();
162
146
  const runDeploy = async (outputDirectory) => {
163
147
  const targetDirectory = cliOptions.targetDir ?? '.';
164
148
  const fromPath = outputDirectory;
@@ -167,43 +151,47 @@ You can also set the deploymentBranch property in docusaurus.config.js .`);
167
151
  // Clones the repo into the temp folder and checks out the target branch.
168
152
  // If the branch doesn't exist, it creates a new one based on the
169
153
  // repository default branch.
170
- if (exec(`git clone --depth 1 --branch ${deploymentBranch} ${deploymentRepoURL} ${escapeArg(toPath)}`).exitCode !== 0) {
171
- exec(`git clone --depth 1 ${deploymentRepoURL} ${escapeArg(toPath)}`);
172
- exec(`git checkout -b ${deploymentBranch}`);
154
+ const cloneResult = await exec('git', [
155
+ 'clone',
156
+ '--depth',
157
+ '1',
158
+ '--branch',
159
+ deploymentBranch,
160
+ deploymentRepoURL,
161
+ toPath,
162
+ ], { failfast: false });
163
+ if (cloneResult.exitCode !== 0) {
164
+ await exec('git', ['clone', '--depth', '1', deploymentRepoURL, toPath]);
165
+ await exec('git', ['checkout', '-b', deploymentBranch]);
173
166
  }
174
167
  // Clear out any existing contents in the target directory
175
- exec(`git rm -rf ${escapeArg(targetDirectory)}`, {
176
- log: false,
177
- failfast: true,
178
- });
168
+ await exec('git', ['rm', '-rf', targetDirectory], { log: false });
179
169
  const targetPath = path_1.default.join(toPath, targetDirectory);
180
170
  try {
181
171
  await fs_extra_1.default.copy(fromPath, targetPath);
182
172
  }
183
173
  catch (err) {
184
- logger_1.default.error `Copying build assets from path=${fromPath} to path=${targetPath} failed.`;
185
- throw err;
174
+ throw new Error(`Failed to copy build assets from path=${fromPath} to path=${targetPath}.`, { cause: err });
186
175
  }
187
- exec('git add --all', { failfast: true });
176
+ await exec('git', ['add', '--all']);
188
177
  const gitUserName = process.env.GIT_USER_NAME;
189
178
  if (gitUserName) {
190
- exec(`git config user.name ${escapeArg(gitUserName)}`, { failfast: true });
179
+ await exec('git', ['config', 'user.name', gitUserName]);
191
180
  }
192
181
  const gitUserEmail = process.env.GIT_USER_EMAIL;
193
182
  if (gitUserEmail) {
194
- exec(`git config user.email ${escapeArg(gitUserEmail)}`, {
195
- failfast: true,
196
- });
183
+ await exec('git', ['config', 'user.email', gitUserEmail]);
197
184
  }
198
185
  const commitMessage = process.env.CUSTOM_COMMIT_MESSAGE ??
199
186
  `Deploy website - based on ${currentCommit}`;
200
- const commitResults = exec(`git commit -m ${escapeArg(commitMessage)} --allow-empty`);
201
- if (exec(`git push --force origin ${deploymentBranch}`).exitCode !== 0) {
187
+ // The commit might return a non-zero value when site is up to date.
188
+ const commitResults = await exec('git', ['commit', '-m', commitMessage, '--allow-empty'], { failfast: false });
189
+ const pushResult = await exec('git', ['push', '--force', 'origin', deploymentBranch], { failfast: false });
190
+ if (pushResult.exitCode !== 0) {
202
191
  throw new Error('Running "git push" command failed. Does the GitHub user account you are using have push access to the repository?');
203
192
  }
204
193
  else if (commitResults.exitCode === 0) {
205
- // The commit might return a non-zero value when site is up to date.
206
- let websiteURL = '';
194
+ let websiteURL;
207
195
  if (githubHost === 'github.com') {
208
196
  websiteURL = projectName.includes('.github.io')
209
197
  ? `https://${organizationName}.github.io/`
@@ -213,13 +201,8 @@ You can also set the deploymentBranch property in docusaurus.config.js .`);
213
201
  // GitHub enterprise hosting.
214
202
  websiteURL = `https://${githubHost}/pages/${organizationName}/${projectName}/`;
215
203
  }
216
- try {
217
- exec(`echo "Website is live at ${websiteURL}."`, { failfast: true });
218
- process.exit(0);
219
- }
220
- catch (err) {
221
- throw new Error(`Failed to execute command: ${err}`);
222
- }
204
+ logger_1.default.success `Website is live at url=${websiteURL}.`;
205
+ process.exit(0);
223
206
  }
224
207
  };
225
208
  if (!cliOptions.skipBuild) {
@@ -57,7 +57,7 @@ async function serve(siteDirParam = '.', cliOptions = {}) {
57
57
  if (baseUrl !== '/') {
58
58
  // Not super robust, but should be good enough for our use case
59
59
  // See https://github.com/facebook/docusaurus/pull/10090
60
- const looksLikeAsset = !!req.url.match(/\.[a-zA-Z\d]{1,4}$/);
60
+ const looksLikeAsset = !!req.url.match(/\.[a-z\d]{1,4}$/i);
61
61
  if (!looksLikeAsset) {
62
62
  const normalizedUrl = (0, utils_common_1.applyTrailingSlash)(req.url, {
63
63
  trailingSlash,
@@ -11,5 +11,8 @@ export type StartCLIOptions = HostPortOptions & Pick<LoadContextParams, 'locale'
11
11
  open?: boolean;
12
12
  poll?: boolean | number;
13
13
  minify?: boolean;
14
+ https?: true;
15
+ sslCert?: string;
16
+ sslKey?: string;
14
17
  };
15
18
  export declare function start(siteDirParam?: string, cliOptions?: Partial<StartCLIOptions>): Promise<void>;
@@ -42,13 +42,9 @@ async function createDevServerConfig({ cliOptions, props, host, port, }) {
42
42
  const { baseUrl, siteDir, siteConfig } = props;
43
43
  const pollingOptions = (0, watcher_1.createPollingOptions)(cliOptions);
44
44
  const httpsConfig = await (0, getHttpsConfig_1.default)({
45
- /*
46
- TODO Docusaurus v4: wire new CLI parameters
47
- https: cliOptions.https,
48
- sslCert: cliOptions.sslCert,
49
- sslKey: cliOptions.sslKey,
50
-
51
- */
45
+ https: cliOptions.https,
46
+ sslCert: cliOptions.sslCert,
47
+ sslKey: cliOptions.sslKey,
52
48
  });
53
49
  // https://webpack.js.org/configuration/dev-server
54
50
  return {
@@ -142,5 +138,19 @@ async function createWebpackDevServer({ props, cliOptions, openUrlContext, }) {
142
138
  });
143
139
  // Allow plugin authors to customize/override devServer config
144
140
  const devServerConfig = (0, webpack_merge_1.default)([defaultDevServerConfig, config.devServer].filter(Boolean));
145
- return new webpack_dev_server_1.default(devServerConfig, compiler);
141
+ return createDevServer({
142
+ devServerConfig,
143
+ compiler,
144
+ currentBundler: props.currentBundler,
145
+ });
146
+ }
147
+ async function createDevServer({ devServerConfig, compiler, currentBundler, }) {
148
+ if (currentBundler.name === 'webpack') {
149
+ return new webpack_dev_server_1.default(devServerConfig, compiler);
150
+ }
151
+ else {
152
+ const RspackDevServer = await (0, bundler_1.importRspackDevServer)();
153
+ // @ts-expect-error: different types
154
+ return new RspackDevServer(devServerConfig, compiler);
155
+ }
146
156
  }
@@ -39,6 +39,11 @@ async function eject({ siteDir, themePath, componentName, typescript, }) {
39
39
  : `${fromPath}.*`;
40
40
  const globPatternPosix = (0, utils_1.posixPath)(globPattern);
41
41
  const filesToCopy = await (0, utils_1.Globby)(globPatternPosix, {
42
+ // Workaround for Tinyglobby bug?
43
+ // We glob absolute from the theme root path, not from cwd
44
+ // See https://github.com/SuperchupuDev/tinyglobby/issues/186
45
+ cwd: themePath,
46
+ absolute: true,
42
47
  ignore: lodash_1.default.compact([
43
48
  '**/*.{story,stories,test,tests}.{js,jsx,ts,tsx}',
44
49
  // When ejecting JS components, we want to avoid emitting TS files
@@ -15,7 +15,7 @@ const tslib_1 = require("tslib");
15
15
  /* eslint-disable */
16
16
  const child_process_1 = require("child_process");
17
17
  const util_1 = require("util");
18
- const open_1 = tslib_1.__importDefault(require("open"));
18
+ const open_1 = tslib_1.__importStar(require("open"));
19
19
  const logger_1 = require("@docusaurus/logger");
20
20
  const execPromise = (0, util_1.promisify)(child_process_1.exec);
21
21
  // Not sure if we need this, but let's keep a secret escape hatch
@@ -101,9 +101,9 @@ function toOpenApp(params) {
101
101
  return undefined;
102
102
  }
103
103
  // Handles "cross-platform" shortcuts like "chrome", "firefox", "edge"
104
- if (open_1.default.apps[params.browser]) {
104
+ if (open_1.apps[params.browser]) {
105
105
  return {
106
- name: open_1.default.apps[params.browser],
106
+ name: open_1.apps[params.browser],
107
107
  arguments: params.browserArgs,
108
108
  };
109
109
  }
@@ -63,9 +63,9 @@ async function writeHeadingIds(siteDirParam = '.', files = [], options = {}) {
63
63
  validateOptions(options);
64
64
  const siteDir = await fs_extra_1.default.realpath(siteDirParam);
65
65
  const patterns = files.length ? files : await getPathsToWatch(siteDir);
66
- const markdownFiles = await (0, utils_1.safeGlobby)(patterns, {
67
- expandDirectories: ['**/*.{md,mdx}'],
68
- });
66
+ const markdownFiles = (await (0, utils_1.safeGlobby)(patterns, {
67
+ expandDirectories: true,
68
+ })).filter((file) => file.endsWith('.md') || file.endsWith('.mdx'));
69
69
  if (markdownFiles.length === 0) {
70
70
  logger_1.default.warn `No markdown files found in siteDir path=${siteDir} for patterns: ${patterns}`;
71
71
  return;
@@ -85,7 +85,6 @@ ${indent(parts.join(',\n'))}
85
85
  }
86
86
  const isModule = (value) => typeof value === 'string' ||
87
87
  (typeof value === 'object' &&
88
- // eslint-disable-next-line no-underscore-dangle
89
88
  !!value?.__import);
90
89
  /**
91
90
  * Takes a {@link Module} (which is nothing more than a path plus some metadata
@@ -33,7 +33,7 @@ async function loadSiteConfig({ siteDir, customConfigFilePath, }) {
33
33
  if (!(await fs_extra_1.default.pathExists(siteConfigPath))) {
34
34
  throw new Error(`Config file at "${siteConfigPath}" not found.`);
35
35
  }
36
- const importedConfig = await (0, utils_1.loadFreshModule)(siteConfigPath);
36
+ const importedConfig = await (0, utils_1.loadFreshModule)(siteConfigPath, { default: true });
37
37
  const loadedConfig = typeof importedConfig === 'function'
38
38
  ? await importedConfig()
39
39
  : await importedConfig;
@@ -16,15 +16,14 @@ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
16
16
  const DEFAULT_I18N_LOCALE = 'en';
17
17
  const SiteUrlSchema = utils_validation_1.Joi.string()
18
18
  .custom((value, helpers) => {
19
- try {
20
- const { pathname } = new URL(value);
21
- if (pathname !== '/') {
22
- return helpers.error('docusaurus.subPathError', { pathname });
23
- }
24
- }
25
- catch {
19
+ const url = URL.parse(value);
20
+ if (url === null) {
26
21
  return helpers.error('any.invalid');
27
22
  }
23
+ const { pathname } = url;
24
+ if (pathname !== '/') {
25
+ return helpers.error('docusaurus.subPathError', { pathname });
26
+ }
28
27
  return (0, utils_common_1.removeTrailingSlash)(value);
29
28
  })
30
29
  .messages({
@@ -70,7 +69,6 @@ exports.DEFAULT_FASTER_CONFIG_TRUE = {
70
69
  gitEagerVcs: true,
71
70
  };
72
71
  exports.DEFAULT_FUTURE_V4_CONFIG = {
73
- removeLegacyPostBuildHeadAttribute: false,
74
72
  useCssCascadeLayers: false,
75
73
  siteStorageNamespacing: false,
76
74
  fasterByDefault: false,
@@ -78,7 +76,6 @@ exports.DEFAULT_FUTURE_V4_CONFIG = {
78
76
  };
79
77
  // When using the "v4: true" shortcut
80
78
  exports.DEFAULT_FUTURE_V4_CONFIG_TRUE = {
81
- removeLegacyPostBuildHeadAttribute: true,
82
79
  useCssCascadeLayers: true,
83
80
  siteStorageNamespacing: true,
84
81
  fasterByDefault: true,
@@ -93,6 +90,7 @@ exports.DEFAULT_FUTURE_CONFIG = {
93
90
  exports.DEFAULT_MARKDOWN_HOOKS = {
94
91
  onBrokenMarkdownLinks: 'warn',
95
92
  onBrokenMarkdownImages: 'throw',
93
+ onUnusedMarkdownDirectives: 'warn',
96
94
  };
97
95
  exports.DEFAULT_MARKDOWN_MDX1COMPAT = {
98
96
  comments: true,
@@ -227,7 +225,6 @@ const FASTER_CONFIG_SCHEMA = utils_validation_1.Joi.alternatives()
227
225
  .optional();
228
226
  const FUTURE_V4_SCHEMA = utils_validation_1.Joi.alternatives()
229
227
  .try(utils_validation_1.Joi.object({
230
- removeLegacyPostBuildHeadAttribute: utils_validation_1.Joi.boolean().default(exports.DEFAULT_FUTURE_V4_CONFIG.removeLegacyPostBuildHeadAttribute),
231
228
  useCssCascadeLayers: utils_validation_1.Joi.boolean().default(exports.DEFAULT_FUTURE_V4_CONFIG.useCssCascadeLayers),
232
229
  siteStorageNamespacing: utils_validation_1.Joi.boolean().default(exports.DEFAULT_FUTURE_V4_CONFIG.siteStorageNamespacing),
233
230
  fasterByDefault: utils_validation_1.Joi.boolean().default(exports.DEFAULT_FUTURE_V4_CONFIG.fasterByDefault),
@@ -415,6 +412,9 @@ exports.ConfigSchema = utils_validation_1.Joi.object({
415
412
  onBrokenMarkdownImages: utils_validation_1.Joi.alternatives()
416
413
  .try(utils_validation_1.Joi.string().equal('ignore', 'log', 'warn', 'throw'), utils_validation_1.Joi.function())
417
414
  .default(exports.DEFAULT_CONFIG.markdown.hooks.onBrokenMarkdownImages),
415
+ onUnusedMarkdownDirectives: utils_validation_1.Joi.alternatives()
416
+ .try(utils_validation_1.Joi.string().equal('ignore', 'log', 'warn', 'throw'), utils_validation_1.Joi.function())
417
+ .default(exports.DEFAULT_CONFIG.markdown.hooks.onUnusedMarkdownDirectives),
418
418
  }).default(exports.DEFAULT_CONFIG.markdown.hooks),
419
419
  }).default({
420
420
  ...exports.DEFAULT_CONFIG.markdown,
@@ -470,12 +470,6 @@ Please migrate and move this option to code=${'siteConfig.markdown.hooks.onBroke
470
470
  : (0, utils_1.getVcsPreset)('disabled');
471
471
  config.future.experimental_vcs = vcsConfig;
472
472
  }
473
- if (config.future.faster.ssgWorkerThreads &&
474
- !config.future.v4.removeLegacyPostBuildHeadAttribute) {
475
- throw new Error(`Docusaurus config ${logger_1.default.code('future.faster.ssgWorkerThreads')} requires the future flag ${logger_1.default.code('future.v4.removeLegacyPostBuildHeadAttribute')} to be turned on.
476
- If you use Docusaurus Faster, we recommend that you also activate Docusaurus v4 future flags: ${logger_1.default.code('{future: {v4: true}}')}
477
- All the v4 future flags are documented here: https://docusaurus.io/docs/api/docusaurus-config#future`);
478
- }
479
473
  if (config.future.faster.rspackPersistentCache &&
480
474
  !config.future.faster.rspackBundler) {
481
475
  throw new Error(`Docusaurus config flag ${logger_1.default.code('future.faster.rspackPersistentCache')} requires the flag ${logger_1.default.code('future.faster.rspackBundler')} to be turned on.`);
@@ -9,8 +9,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.loadHtmlTags = loadHtmlTags;
10
10
  const tslib_1 = require("tslib");
11
11
  const lodash_1 = tslib_1.__importDefault(require("lodash"));
12
- const html_tags_1 = tslib_1.__importDefault(require("html-tags"));
13
- const void_1 = tslib_1.__importDefault(require("html-tags/void"));
12
+ const html_tags_1 = tslib_1.__importStar(require("html-tags"));
14
13
  const escape_html_1 = tslib_1.__importDefault(require("escape-html"));
15
14
  // TODO this should be done at config validation time, not here
16
15
  function assertIsHtmlTagObject(val) {
@@ -34,7 +33,7 @@ function hashRouterAbsoluteToRelativeTagAttribute(name, value) {
34
33
  }
35
34
  function htmlTagObjectToString({ tag, router, }) {
36
35
  assertIsHtmlTagObject(tag);
37
- const isVoidTag = void_1.default.includes(tag.tagName);
36
+ const isVoidTag = html_tags_1.voidHtmlTags.includes(tag.tagName);
38
37
  const tagAttributes = tag.attributes ?? {};
39
38
  const attributes = Object.keys(tagAttributes)
40
39
  .map((attr) => {
@@ -23,7 +23,7 @@ function inferLanguageDisplayName(locale) {
23
23
  fallback: 'code',
24
24
  }).of(l);
25
25
  }
26
- catch (e) {
26
+ catch {
27
27
  // This is to compensate "of()" that is a bit strict
28
28
  // Looks like starting Node 22, this locale throws: "en-US-u-ca-buddhist"
29
29
  // RangeError: invalid_argument
@@ -64,11 +64,7 @@ function getDefaultDirection(localeStr) {
64
64
  const locale = new Intl.Locale(localeStr);
65
65
  // see https://github.com/tc39/proposal-intl-locale-info
66
66
  // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getTextInfo
67
- // Node 18.0 implements a former version of the getTextInfo() proposal
68
- // TODO Docusaurus v4: remove the fallback to locale.textInfo
69
- // @ts-expect-error: The TC39 proposal was updated
70
- const textInto = locale.getTextInfo?.() ?? locale.textInfo;
71
- return textInto.direction ?? 'ltr';
67
+ return locale.getTextInfo().direction ?? 'ltr';
72
68
  }
73
69
  function getDefaultLocaleConfig(
74
70
  // Locale "key/identifier"
@@ -169,15 +169,7 @@ async function reloadPlugin({ pluginIdentifier, plugins: previousPlugins, contex
169
169
  plugin: previousPlugin,
170
170
  context,
171
171
  });
172
- /*
173
- // TODO Docusaurus v4 - upgrade to Node 20, use array.with()
174
- const plugins = previousPlugins.with(
175
- previousPlugins.indexOf(previousPlugin),
176
- plugin,
177
- );
178
- */
179
- const plugins = [...previousPlugins];
180
- plugins[previousPlugins.indexOf(previousPlugin)] = plugin;
172
+ const plugins = previousPlugins.with(previousPlugins.indexOf(previousPlugin), plugin);
181
173
  const allContentLoadedResult = await executeAllPluginsAllContentLoaded({
182
174
  plugins,
183
175
  context,
@@ -37,7 +37,7 @@ async function loadContext(params) {
37
37
  const { siteDir, outDir: baseOutDir = utils_1.DEFAULT_BUILD_DIR_NAME, locale, config: customConfigFilePath, automaticBaseUrlLocalizationDisabled, } = params;
38
38
  const generatedFilesDir = path_1.default.resolve(siteDir, utils_1.GENERATED_FILES_DIR_NAME);
39
39
  const { siteVersion, loadSiteConfig: { siteConfig: initialSiteConfig, siteConfigPath }, } = await (0, combine_promises_1.default)({
40
- siteVersion: (0, siteMetadata_1.loadSiteVersion)(siteDir),
40
+ siteVersion: (0, siteMetadata_1.tryLoadSitePackageJson)(siteDir).then((pkg) => pkg?.version),
41
41
  loadSiteConfig: (0, config_1.loadSiteConfig)({
42
42
  siteDir,
43
43
  customConfigFilePath,
@@ -5,9 +5,14 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  import type { LoadedPlugin, PluginVersionInformation, SiteMetadata } from '@docusaurus/types';
8
- export declare function loadSiteVersion(siteDir: string): Promise<string | undefined>;
8
+ type PackageJson = {
9
+ name?: string;
10
+ version?: string;
11
+ };
12
+ export declare function tryLoadSitePackageJson(siteDir: string): Promise<PackageJson | undefined>;
9
13
  export declare function loadPluginVersion(pluginPath: string, siteDir: string): Promise<PluginVersionInformation>;
10
14
  export declare function createSiteMetadata({ siteVersion, plugins, }: {
11
15
  siteVersion: string | undefined;
12
16
  plugins: LoadedPlugin[];
13
17
  }): SiteMetadata;
18
+ export {};
@@ -6,26 +6,28 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.loadSiteVersion = loadSiteVersion;
9
+ exports.tryLoadSitePackageJson = tryLoadSitePackageJson;
10
10
  exports.loadPluginVersion = loadPluginVersion;
11
11
  exports.createSiteMetadata = createSiteMetadata;
12
12
  const tslib_1 = require("tslib");
13
13
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
14
14
  const path_1 = tslib_1.__importDefault(require("path"));
15
15
  const utils_1 = require("@docusaurus/utils");
16
- async function loadPackageJsonVersion(packageJsonPath) {
16
+ async function tryLoadPackageJson(packageJsonPath) {
17
17
  if (await fs_extra_1.default.pathExists(packageJsonPath)) {
18
- // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-dynamic-require, global-require
19
- return require(packageJsonPath).version;
18
+ try {
19
+ return (await fs_extra_1.default.readJSON(packageJsonPath));
20
+ }
21
+ catch (error) {
22
+ throw new Error(`Couldn't load package.json file at ${packageJsonPath}`, {
23
+ cause: error,
24
+ });
25
+ }
20
26
  }
21
27
  return undefined;
22
28
  }
23
- async function loadPackageJsonName(packageJsonPath) {
24
- // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-dynamic-require, global-require
25
- return require(packageJsonPath).name;
26
- }
27
- async function loadSiteVersion(siteDir) {
28
- return loadPackageJsonVersion(path_1.default.join(siteDir, 'package.json'));
29
+ async function tryLoadSitePackageJson(siteDir) {
30
+ return tryLoadPackageJson(path_1.default.join(siteDir, 'package.json'));
29
31
  }
30
32
  async function loadPluginVersion(pluginPath, siteDir) {
31
33
  let potentialPluginPackageJsonDirectory = path_1.default.dirname(pluginPath);
@@ -38,10 +40,11 @@ async function loadPluginVersion(pluginPath, siteDir) {
38
40
  // as local plugin.
39
41
  return { type: 'project' };
40
42
  }
43
+ const packageJson = await tryLoadPackageJson(packageJsonPath);
41
44
  return {
42
45
  type: 'package',
43
- name: await loadPackageJsonName(packageJsonPath),
44
- version: await loadPackageJsonVersion(packageJsonPath),
46
+ name: packageJson?.name,
47
+ version: packageJson?.version,
45
48
  };
46
49
  }
47
50
  potentialPluginPackageJsonDirectory = path_1.default.dirname(potentialPluginPackageJsonDirectory);
@@ -62,7 +62,7 @@ function mergeTranslationFileContent({ existingContent = {}, newContent, options
62
62
  // If messages already exist, we don't override them (unless requested)
63
63
  message: options.override
64
64
  ? message
65
- : existingContent[key]?.message ?? message,
65
+ : (existingContent[key]?.message ?? message),
66
66
  description,
67
67
  };
68
68
  });
package/lib/ssg/ssgEnv.js CHANGED
@@ -9,9 +9,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.SSGWorkerThreadRecyclerMaxMemory = exports.SSGWorkerThreadTaskSize = exports.SSGWorkerThreadCount = exports.SSGConcurrency = void 0;
10
10
  // Secret way to set SSR plugin async concurrency option
11
11
  // Waiting for feedback before documenting this officially?
12
- // TODO Docusaurus v4, rename SSR => SSG
13
- exports.SSGConcurrency = process.env.DOCUSAURUS_SSR_CONCURRENCY
14
- ? parseInt(process.env.DOCUSAURUS_SSR_CONCURRENCY, 10)
12
+ exports.SSGConcurrency = process.env.DOCUSAURUS_SSG_CONCURRENCY
13
+ ? parseInt(process.env.DOCUSAURUS_SSG_CONCURRENCY, 10)
15
14
  : // Not easy to define a reasonable option default
16
15
  // Will still be better than Infinity
17
16
  // See also https://github.com/sindresorhus/p-map/issues/24
@@ -51,11 +51,7 @@ function getNumberOfThreads(pathnames) {
51
51
  return ssgEnv_1.SSGWorkerThreadCount;
52
52
  }
53
53
  // See also https://github.com/tinylibs/tinypool/pull/108
54
- const cpuCount =
55
- // TODO Docusaurus v4: bump node, availableParallelism() now always exists
56
- typeof os_1.default.availableParallelism === 'function'
57
- ? os_1.default.availableParallelism()
58
- : os_1.default.cpus().length;
54
+ const cpuCount = os_1.default.availableParallelism();
59
55
  return inferNumberOfThreads({
60
56
  pageCount: pathnames.length,
61
57
  cpuCount,
@@ -64,6 +60,21 @@ function getNumberOfThreads(pathnames) {
64
60
  minPagesPerCpu: 100,
65
61
  });
66
62
  }
63
+ // Workaround for Node styleText() limitation
64
+ // See https://github.com/nodejs/node/issues/65766
65
+ function getWorkerColorEnv() {
66
+ // Preserve an explicit user choice
67
+ if (process.env.FORCE_COLOR !== undefined) {
68
+ return {};
69
+ }
70
+ const depth = process.stdout.isTTY
71
+ ? (process.stdout.getColorDepth?.() ?? 0)
72
+ : 0;
73
+ if (depth > 2) {
74
+ return { FORCE_COLOR: depth >= 24 ? '3' : depth >= 8 ? '2' : '1' };
75
+ }
76
+ return {};
77
+ }
67
78
  const createPooledSSGExecutor = async ({ params, pathnames, }) => {
68
79
  const numberOfThreads = getNumberOfThreads(pathnames);
69
80
  // When the inferred or provided number of threads is just 1
@@ -84,6 +95,12 @@ const createPooledSSGExecutor = async ({ params, pathnames, }) => {
84
95
  runtime: 'worker_threads',
85
96
  isolateWorkers: false,
86
97
  workerData: { params },
98
+ env: {
99
+ // Cast is safe
100
+ // See https://github.com/tinylibs/tinypool/issues/136
101
+ ...process.env,
102
+ ...getWorkerColorEnv(),
103
+ },
87
104
  // WORKER MEMORY MANAGEMENT
88
105
  // Allows containing SSG memory leaks with a thread recycling workaround
89
106
  // See https://github.com/facebook/docusaurus/pull/11166
@@ -17,20 +17,11 @@ function printSSGWarnings(results) {
17
17
  if (process.env.DOCUSAURUS_IGNORE_SSG_WARNINGS === 'true') {
18
18
  return;
19
19
  }
20
- const ignoredWarnings = [
21
- // TODO Docusaurus v4: remove with React 19 upgrade
22
- // React 18 emit NULL chars, and minifier detects it
23
- // see https://github.com/facebook/docusaurus/issues/9985
24
- 'Unexpected null character',
25
- ];
26
- const keepWarning = (warning) => {
27
- return !ignoredWarnings.some((iw) => warning.includes(iw));
28
- };
29
20
  const resultsWithWarnings = results
30
21
  .map((success) => {
31
22
  return {
32
23
  ...success,
33
- warnings: success.result.warnings.filter(keepWarning),
24
+ warnings: success.result.warnings,
34
25
  };
35
26
  })
36
27
  .filter((result) => result.warnings.length > 0);
@@ -20,7 +20,6 @@ export type SSGParams = {
20
20
  htmlMinifierType: HtmlMinifierType;
21
21
  serverBundlePath: string;
22
22
  ssgTemplateContent: string;
23
- v4RemoveLegacyPostBuildHeadAttribute: boolean;
24
23
  };
25
24
  export declare function createSSGParams({ props, serverBundlePath, clientManifestPath, }: {
26
25
  props: Props;
@@ -29,7 +29,6 @@ async function createSSGParams({ props, serverBundlePath, clientManifestPath, })
29
29
  htmlMinifierType: props.siteConfig.future.faster.swcHtmlMinimizer
30
30
  ? 'swc'
31
31
  : 'terser',
32
- v4RemoveLegacyPostBuildHeadAttribute: props.siteConfig.future.v4.removeLegacyPostBuildHeadAttribute,
33
32
  };
34
33
  // Useless but ensures that SSG params remain serializable
35
34
  return structuredClone(params);
@@ -86,7 +86,6 @@ function reduceCollectedData(pageCollectedData) {
86
86
  anchors: pageCollectedData.anchors,
87
87
  metadata: {
88
88
  public: pageCollectedData.metadata.public,
89
- helmet: pageCollectedData.metadata.helmet,
90
89
  },
91
90
  links: pageCollectedData.links,
92
91
  };
@@ -94,10 +93,7 @@ function reduceCollectedData(pageCollectedData) {
94
93
  async function generateStaticFile({ pathname, appRenderer, params, htmlMinifier, ssgTemplate, }) {
95
94
  try {
96
95
  // This only renders the app HTML
97
- const appRenderResult = await appRenderer.render({
98
- pathname,
99
- v4RemoveLegacyPostBuildHeadAttribute: params.v4RemoveLegacyPostBuildHeadAttribute,
100
- });
96
+ const appRenderResult = await appRenderer.render({ pathname });
101
97
  // This renders the full page HTML, including head tags...
102
98
  const fullPageHtml = (0, ssgTemplate_1.renderSSGTemplate)({
103
99
  params,
@@ -9,15 +9,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.compileSSGTemplate = compileSSGTemplate;
10
10
  exports.renderSSGTemplate = renderSSGTemplate;
11
11
  exports.renderHashRouterTemplate = renderHashRouterTemplate;
12
- const tslib_1 = require("tslib");
13
- const eta = tslib_1.__importStar(require("eta"));
12
+ const eta_1 = require("eta");
14
13
  const react_loadable_ssr_addon_v5_slorber_1 = require("react-loadable-ssr-addon-v5-slorber");
15
14
  const logger_1 = require("@docusaurus/logger");
16
15
  async function compileSSGTemplate(template) {
17
- const compiledTemplate = eta.compile(template.trim(), {
18
- rmWhitespace: true,
19
- });
20
- return (data) => compiledTemplate(data, eta.defaultConfig);
16
+ const eta = new eta_1.Eta({ rmWhitespace: true });
17
+ const compiledTemplate = eta.compile(template.trim());
18
+ return (data) => eta.render(compiledTemplate, data);
21
19
  }
22
20
  /**
23
21
  * Given a list of modules that were SSR an d
@@ -11,7 +11,6 @@ const tslib_1 = require("tslib");
11
11
  const node_worker_threads_1 = require("node:worker_threads");
12
12
  const logger_1 = tslib_1.__importStar(require("@docusaurus/logger"));
13
13
  const ssgRenderer_js_1 = require("./ssgRenderer.js");
14
- // eslint-disable-next-line no-underscore-dangle
15
14
  const workerId = process?.__tinypool_state__?.workerId;
16
15
  if (!workerId) {
17
16
  throw new Error('SSG Worker Thread not executing in Tinypool context?');
@@ -87,9 +87,14 @@ async function createBaseConfig({ props, isServer, minify, faster, configureWebp
87
87
  }
88
88
  if (props.currentBundler.name === 'rspack') {
89
89
  if (props.siteConfig.future.faster.rspackPersistentCache) {
90
- // Use cache: true + experiments.cache.type: "persistent"
91
- // See https://rspack.dev/config/experiments#persistent-cache
92
- return true;
90
+ return {
91
+ type: 'persistent',
92
+ // Rspack doesn't have "cache.name" like Webpack
93
+ // This is not ideal but work around is to merge name/version
94
+ // See https://github.com/web-infra-dev/rspack/pull/8920#issuecomment-2658938695
95
+ version: `${getCacheName()}-${getCacheVersion()}`,
96
+ buildDependencies: getCacheBuildDependencies(),
97
+ };
93
98
  }
94
99
  else {
95
100
  return disabledPersistentCacheValue;
@@ -104,29 +109,10 @@ async function createBaseConfig({ props, isServer, minify, faster, configureWebp
104
109
  },
105
110
  };
106
111
  }
107
- function getExperiments() {
108
- if (props.currentBundler.name === 'rspack') {
109
- // TODO find a way to type this
110
- const experiments = {};
111
- if (!process.env.DOCUSAURUS_NO_PERSISTENT_CACHE) {
112
- experiments.cache = {
113
- type: 'persistent',
114
- // Rspack doesn't have "cache.name" like Webpack
115
- // This is not ideal but work around is to merge name/version
116
- // See https://github.com/web-infra-dev/rspack/pull/8920#issuecomment-2658938695
117
- version: `${getCacheName()}-${getCacheVersion()}`,
118
- buildDependencies: getCacheBuildDependencies(),
119
- };
120
- }
121
- return experiments;
122
- }
123
- return undefined;
124
- }
125
112
  return {
126
113
  mode,
127
114
  name,
128
115
  cache: getCache(),
129
- experiments: getExperiments(),
130
116
  output: {
131
117
  pathinfo: false,
132
118
  path: outDir,
@@ -251,6 +237,10 @@ async function createBaseConfig({ props, isServer, minify, faster, configureWebp
251
237
  // See https://github.com/facebook/docusaurus/pull/10423
252
238
  localIdentName: `[local]_[contenthash:base64:4]`,
253
239
  exportOnlyLocals: isServer,
240
+ // Export CSS module class names compatible with css-loader v6
241
+ // export ".themedComponent--dark" instead of .themedComponentDark
242
+ // See https://github.com/webpack/css-loader/releases/tag/v7.0.0
243
+ exportLocalsConvention: 'as-is',
254
244
  },
255
245
  importLoaders: 1,
256
246
  sourceMap: !isProd,
@@ -35,7 +35,7 @@ async function createServerConfig({ props, configureWebpackUtils, }) {
35
35
  output: {
36
36
  path: outputDir,
37
37
  filename: outputFilename,
38
- libraryTarget: 'commonjs2',
38
+ library: { type: 'commonjs2' },
39
39
  },
40
40
  plugins: [
41
41
  new ProgressBarPlugin({
@@ -40,10 +40,10 @@ function validateKeyAndCerts({ cert, key }) {
40
40
  function getExplicitHttps(options) {
41
41
  return (options.https ??
42
42
  (typeof process.env.DOCUSAURUS_HTTPS !== 'undefined'
43
- ? process.env.DOCUSAURUS_HTTPS === 'true'
43
+ ? process.env.DOCUSAURUS_HTTPS == 'true'
44
44
  : undefined) ??
45
45
  (typeof process.env.HTTPS !== 'undefined'
46
- ? process.env.HTTPS === 'true'
46
+ ? process.env.HTTPS == 'true'
47
47
  : undefined));
48
48
  }
49
49
  async function readCryptoFile(filepath, source) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@docusaurus/core",
3
3
  "description": "Easy to Maintain Open Source Documentation Websites",
4
- "version": "3.10.2",
4
+ "version": "4.0.0-canary-6808",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
7
7
  "access": "public"
@@ -33,31 +33,30 @@
33
33
  "url": "https://github.com/facebook/docusaurus/issues"
34
34
  },
35
35
  "dependencies": {
36
- "@docusaurus/babel": "3.10.2",
37
- "@docusaurus/bundler": "3.10.2",
38
- "@docusaurus/logger": "3.10.2",
39
- "@docusaurus/mdx-loader": "3.10.2",
40
- "@docusaurus/utils": "3.10.2",
41
- "@docusaurus/utils-common": "3.10.2",
42
- "@docusaurus/utils-validation": "3.10.2",
36
+ "@docusaurus/babel": "4.0.0-canary-6808",
37
+ "@docusaurus/bundler": "4.0.0-canary-6808",
38
+ "@docusaurus/logger": "4.0.0-canary-6808",
39
+ "@docusaurus/mdx-loader": "4.0.0-canary-6808",
40
+ "@docusaurus/utils": "4.0.0-canary-6808",
41
+ "@docusaurus/utils-common": "4.0.0-canary-6808",
42
+ "@docusaurus/utils-validation": "4.0.0-canary-6808",
43
43
  "boxen": "^6.2.1",
44
- "chalk": "^4.1.2",
45
- "chokidar": "^3.5.3",
46
- "cli-table3": "^0.6.3",
47
- "combine-promises": "^1.1.0",
44
+ "chokidar": "^3.6.0",
45
+ "cli-table3": "^0.6.5",
46
+ "combine-promises": "^1.2.0",
48
47
  "commander": "^5.1.0",
49
- "core-js": "^3.31.1",
48
+ "core-js": "^3.50.0",
50
49
  "detect-port": "^2.1.0",
51
50
  "escape-html": "^1.0.3",
52
- "eta": "^2.2.0",
51
+ "eta": "^4.6.0",
53
52
  "eval": "^0.1.8",
54
- "execa": "^5.1.1",
55
- "fs-extra": "^11.1.1",
56
- "html-tags": "^3.3.1",
57
- "html-webpack-plugin": "^5.6.0",
53
+ "execa": "^10.0.1",
54
+ "fs-extra": "^11.4.0",
55
+ "html-tags": "^5.1.0",
56
+ "html-webpack-plugin": "^5.6.8",
58
57
  "leven": "^3.1.0",
59
- "lodash": "^4.17.21",
60
- "open": "^8.4.0",
58
+ "lodash": "^4.18.1",
59
+ "open": "^11.0.2",
61
60
  "p-map": "^4.0.0",
62
61
  "prompts": "^2.4.2",
63
62
  "react-helmet-async": "npm:@slorber/react-helmet-async@1.3.0",
@@ -66,34 +65,36 @@
66
65
  "react-router": "^5.3.4",
67
66
  "react-router-config": "^5.1.1",
68
67
  "react-router-dom": "^5.3.4",
69
- "semver": "^7.5.4",
68
+ "semver": "^7.8.5",
70
69
  "serve-handler": "^6.1.7",
71
- "tinypool": "^1.0.2",
72
- "tslib": "^2.6.0",
70
+ "tinypool": "^2.1.2",
71
+ "tslib": "^2.8.1",
73
72
  "update-notifier": "^6.0.2",
74
- "webpack": "^5.95.0",
75
- "webpack-bundle-analyzer": "^4.10.2",
76
- "webpack-dev-server": "^5.2.2",
73
+ "webpack": "^5.110.3",
74
+ "webpack-bundle-analyzer": "^5.3.2",
75
+ "webpack-dev-server": "^6.0.0",
77
76
  "webpack-merge": "^6.0.1"
78
77
  },
79
78
  "devDependencies": {
80
- "@docusaurus/module-type-aliases": "3.10.2",
81
- "@docusaurus/types": "3.10.2",
79
+ "@docusaurus/module-type-aliases": "4.0.0-canary-6808",
80
+ "@docusaurus/types": "4.0.0-canary-6808",
82
81
  "@total-typescript/shoehorn": "^0.1.2",
83
- "@types/react-dom": "^19.2.3",
84
- "@types/react-router-config": "^5.0.7",
82
+ "@types/escape-html": "^1.0.4",
83
+ "@types/history": "^4.7.11",
84
+ "@types/react-dom": "^19.3.0",
85
+ "@types/react-router-config": "^5.0.11",
86
+ "@types/react-router-dom": "^5.3.3",
85
87
  "@types/serve-handler": "^6.1.4",
86
- "@types/update-notifier": "^6.0.4",
88
+ "@types/update-notifier": "^6.0.8",
87
89
  "@types/webpack-bundle-analyzer": "^4.7.0",
88
90
  "@types/webpack-env": "^1.18.8",
89
- "tmp-promise": "^3.0.3",
90
- "tree-node-cli": "^1.6.0"
91
+ "tree-node-cli": "^3.0.0"
91
92
  },
92
93
  "peerDependencies": {
93
- "@docusaurus/faster": "*",
94
- "@mdx-js/react": "^3.0.0",
95
- "react": "^18.0.0 || ^19.0.0",
96
- "react-dom": "^18.0.0 || ^19.0.0"
94
+ "@docusaurus/faster": "4.0.0-canary-6808",
95
+ "@mdx-js/react": "^3.1.1",
96
+ "react": "^19.3.0",
97
+ "react-dom": "^19.3.0"
97
98
  },
98
99
  "peerDependenciesMeta": {
99
100
  "@docusaurus/faster": {
@@ -101,7 +102,7 @@
101
102
  }
102
103
  },
103
104
  "engines": {
104
- "node": ">=20.0"
105
+ "node": ">=24.14"
105
106
  },
106
- "gitHead": "f37f9035584917a97a260b91fc2842cba4f8b94f"
107
+ "gitHead": "91e445730a91fbe20dd5fefae560303a0c655aa7"
107
108
  }