@docusaurus/core 2.0.0-beta.15d451942 → 2.0.0-beta.18

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 (200) hide show
  1. package/bin/beforeCli.mjs +133 -0
  2. package/bin/docusaurus.mjs +279 -0
  3. package/lib/babel/preset.d.ts +8 -3
  4. package/lib/babel/preset.js +8 -7
  5. package/lib/choosePort.js +31 -43
  6. package/lib/client/.eslintrc.js +0 -1
  7. package/lib/client/App.d.ts +1 -2
  8. package/lib/client/App.js +23 -24
  9. package/lib/client/LinksCollector.d.ts +3 -3
  10. package/lib/client/LinksCollector.js +7 -11
  11. package/lib/client/PendingNavigation.d.ts +24 -1
  12. package/lib/client/PendingNavigation.js +5 -7
  13. package/lib/{webpack/sharedModuleAliases.d.ts → client/SiteMetadataDefaults.d.ts} +2 -4
  14. package/lib/client/SiteMetadataDefaults.js +19 -0
  15. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.d.ts +13 -0
  16. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.js +15 -10
  17. package/lib/client/browserContext.d.ts +11 -0
  18. package/lib/client/browserContext.js +22 -0
  19. package/lib/client/client-lifecycles-dispatcher.d.ts +2 -5
  20. package/lib/client/client-lifecycles-dispatcher.js +6 -10
  21. package/lib/client/clientEntry.js +13 -7
  22. package/lib/client/docusaurus.d.ts +6 -0
  23. package/lib/client/docusaurus.js +16 -25
  24. package/lib/client/docusaurusContext.d.ts +12 -0
  25. package/lib/client/docusaurusContext.js +25 -0
  26. package/lib/client/exports/BrowserOnly.d.ts +2 -3
  27. package/lib/client/exports/BrowserOnly.js +14 -7
  28. package/lib/client/exports/ComponentCreator.d.ts +1 -2
  29. package/lib/client/exports/ComponentCreator.js +40 -19
  30. package/lib/client/exports/ErrorBoundary.d.ts +18 -0
  31. package/lib/client/exports/ErrorBoundary.js +35 -0
  32. package/lib/client/exports/Head.d.ts +2 -3
  33. package/lib/client/exports/Head.js +3 -4
  34. package/lib/client/exports/Interpolate.d.ts +2 -2
  35. package/lib/client/exports/Interpolate.js +20 -26
  36. package/lib/client/exports/Link.d.ts +11 -5
  37. package/lib/client/exports/Link.js +31 -20
  38. package/lib/client/exports/Translate.d.ts +1 -1
  39. package/lib/client/exports/Translate.js +14 -9
  40. package/lib/client/exports/constants.js +1 -11
  41. package/lib/client/exports/isInternalUrl.js +1 -1
  42. package/lib/client/exports/renderRoutes.d.ts +1 -2
  43. package/lib/client/exports/renderRoutes.js +1 -2
  44. package/lib/client/exports/router.d.ts +1 -1
  45. package/lib/client/exports/router.js +1 -1
  46. package/lib/client/exports/useBaseUrl.js +8 -5
  47. package/lib/client/exports/useDocusaurusContext.d.ts +2 -3
  48. package/lib/client/exports/useDocusaurusContext.js +3 -9
  49. package/lib/client/exports/useGlobalData.d.ts +4 -3
  50. package/lib/client/exports/useGlobalData.js +4 -8
  51. package/lib/{server/versions/__tests/index.test.d.ts → client/exports/useIsBrowser.d.ts} +1 -1
  52. package/lib/client/exports/useIsBrowser.js +11 -0
  53. package/lib/{server/loadSetup.d.ts → client/exports/useRouteContext.d.ts} +2 -3
  54. package/lib/client/exports/useRouteContext.js +15 -0
  55. package/lib/client/flat.d.ts +4 -2
  56. package/lib/client/flat.js +9 -13
  57. package/lib/client/normalizeLocation.d.ts +2 -5
  58. package/lib/client/normalizeLocation.js +2 -7
  59. package/lib/client/nprogress.css +2 -2
  60. package/lib/client/prefetch.d.ts +1 -2
  61. package/lib/client/prefetch.js +4 -6
  62. package/lib/client/preload.d.ts +3 -2
  63. package/lib/client/preload.js +5 -10
  64. package/lib/client/routeContext.d.ts +13 -0
  65. package/lib/client/routeContext.js +31 -0
  66. package/lib/client/serverEntry.d.ts +10 -0
  67. package/lib/client/serverEntry.js +90 -142
  68. package/lib/client/theme-fallback/Error/index.d.ts +10 -0
  69. package/lib/client/theme-fallback/Error/index.js +43 -0
  70. package/lib/client/theme-fallback/Layout/index.d.ts +10 -0
  71. package/lib/client/theme-fallback/Layout/index.js +2 -26
  72. package/lib/client/theme-fallback/Loading/index.d.ts +9 -0
  73. package/lib/client/theme-fallback/Loading/index.js +47 -115
  74. package/lib/client/{exports/context.js → theme-fallback/NotFound/index.d.ts} +2 -2
  75. package/lib/client/theme-fallback/NotFound/index.js +17 -18
  76. package/lib/client/theme-fallback/Root/index.d.ts +10 -0
  77. package/lib/client/theme-fallback/Root/index.js +2 -6
  78. package/lib/client/theme-fallback/SiteMetadata/index.d.ts +8 -0
  79. package/lib/client/theme-fallback/SiteMetadata/index.js +10 -0
  80. package/lib/commands/build.d.ts +1 -1
  81. package/lib/commands/build.js +50 -54
  82. package/lib/commands/clear.d.ts +6 -0
  83. package/lib/commands/clear.js +30 -19
  84. package/lib/commands/commandUtils.d.ts +7 -1
  85. package/lib/commands/commandUtils.js +7 -7
  86. package/lib/commands/deploy.d.ts +1 -1
  87. package/lib/commands/deploy.js +83 -66
  88. package/lib/commands/external.d.ts +2 -2
  89. package/lib/commands/external.js +4 -8
  90. package/lib/commands/serve.d.ts +1 -1
  91. package/lib/commands/serve.js +25 -12
  92. package/lib/commands/start.d.ts +1 -1
  93. package/lib/commands/start.js +96 -87
  94. package/lib/commands/swizzle/actions.d.ts +23 -0
  95. package/lib/commands/swizzle/actions.js +101 -0
  96. package/lib/commands/swizzle/common.d.ts +33 -0
  97. package/lib/commands/swizzle/common.js +56 -0
  98. package/lib/commands/swizzle/components.d.ts +29 -0
  99. package/lib/commands/swizzle/components.js +162 -0
  100. package/lib/commands/swizzle/config.d.ts +10 -0
  101. package/lib/commands/swizzle/config.js +80 -0
  102. package/lib/commands/swizzle/context.d.ts +8 -0
  103. package/lib/commands/swizzle/context.js +28 -0
  104. package/lib/commands/swizzle/index.d.ts +8 -0
  105. package/lib/commands/swizzle/index.js +115 -0
  106. package/lib/commands/swizzle/prompts.d.ts +12 -0
  107. package/lib/commands/swizzle/prompts.js +110 -0
  108. package/lib/{client/exports/context.d.ts → commands/swizzle/tables.d.ts} +3 -4
  109. package/lib/commands/swizzle/tables.js +113 -0
  110. package/lib/commands/swizzle/themes.d.ts +20 -0
  111. package/lib/commands/swizzle/themes.js +106 -0
  112. package/lib/commands/writeHeadingIds.d.ts +2 -6
  113. package/lib/commands/writeHeadingIds.js +19 -76
  114. package/lib/commands/writeTranslations.d.ts +2 -2
  115. package/lib/commands/writeTranslations.js +37 -17
  116. package/lib/index.d.ts +10 -9
  117. package/lib/index.js +20 -19
  118. package/lib/server/brokenLinks.d.ts +4 -17
  119. package/lib/server/brokenLinks.js +64 -52
  120. package/lib/server/client-modules/index.d.ts +2 -2
  121. package/lib/server/client-modules/index.js +4 -3
  122. package/lib/server/config.d.ts +2 -2
  123. package/lib/server/config.js +8 -5
  124. package/lib/server/configValidation.d.ts +4 -2
  125. package/lib/server/configValidation.js +93 -37
  126. package/lib/server/duplicateRoutes.d.ts +1 -3
  127. package/lib/server/duplicateRoutes.js +17 -13
  128. package/lib/server/html-tags/htmlTags.js +7 -8
  129. package/lib/server/html-tags/index.d.ts +2 -3
  130. package/lib/server/html-tags/index.js +3 -4
  131. package/lib/server/i18n.d.ts +2 -3
  132. package/lib/server/i18n.js +27 -48
  133. package/lib/server/index.d.ts +9 -2
  134. package/lib/server/index.js +175 -96
  135. package/lib/server/moduleShorthand.d.ts +9 -0
  136. package/lib/server/moduleShorthand.js +46 -0
  137. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +9 -0
  138. package/lib/server/plugins/applyRouteTrailingSlash.js +19 -0
  139. package/lib/server/plugins/index.d.ts +4 -5
  140. package/lib/server/plugins/index.js +69 -45
  141. package/lib/server/plugins/init.d.ts +15 -5
  142. package/lib/server/plugins/init.js +68 -81
  143. package/lib/server/plugins/pluginIds.d.ts +2 -2
  144. package/lib/server/plugins/pluginIds.js +8 -5
  145. package/lib/server/presets/index.d.ts +3 -3
  146. package/lib/server/presets/index.js +16 -23
  147. package/lib/server/routes.d.ts +3 -5
  148. package/lib/server/routes.js +68 -36
  149. package/lib/server/themes/alias.d.ts +3 -2
  150. package/lib/server/themes/alias.js +24 -13
  151. package/lib/server/themes/index.d.ts +6 -2
  152. package/lib/server/themes/index.js +36 -24
  153. package/lib/server/translations/translations.d.ts +21 -17
  154. package/lib/server/translations/translations.js +33 -54
  155. package/lib/server/translations/translationsExtractor.d.ts +12 -5
  156. package/lib/server/translations/translationsExtractor.js +159 -121
  157. package/lib/server/utils.d.ts +9 -3
  158. package/lib/server/utils.js +7 -9
  159. package/lib/server/versions/index.d.ts +3 -4
  160. package/lib/server/versions/index.js +22 -24
  161. package/lib/webpack/base.d.ts +6 -4
  162. package/lib/webpack/base.js +51 -36
  163. package/lib/webpack/client.d.ts +3 -3
  164. package/lib/webpack/client.js +12 -19
  165. package/lib/webpack/plugins/ChunkAssetPlugin.d.ts +13 -3
  166. package/lib/webpack/plugins/ChunkAssetPlugin.js +24 -17
  167. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +6 -6
  168. package/lib/webpack/plugins/CleanWebpackPlugin.js +10 -16
  169. package/lib/webpack/plugins/LogPlugin.d.ts +1 -1
  170. package/lib/webpack/plugins/LogPlugin.js +4 -5
  171. package/lib/webpack/plugins/WaitPlugin.d.ts +1 -1
  172. package/lib/webpack/plugins/WaitPlugin.js +1 -1
  173. package/lib/webpack/server.d.ts +3 -3
  174. package/lib/webpack/server.js +14 -7
  175. package/lib/{client → webpack}/templates/index.html.template.ejs +0 -0
  176. package/lib/webpack/templates/ssr.html.template.d.ts +8 -0
  177. package/lib/{client → webpack}/templates/ssr.html.template.js +5 -4
  178. package/lib/webpack/utils.d.ts +15 -30
  179. package/lib/webpack/utils.js +57 -175
  180. package/package.json +77 -70
  181. package/bin/docusaurus.js +0 -326
  182. package/lib/.tsbuildinfo +0 -5732
  183. package/lib/client/.tsbuildinfo +0 -4171
  184. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  185. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  186. package/lib/commands/swizzle.d.ts +0 -9
  187. package/lib/commands/swizzle.js +0 -245
  188. package/lib/constants.d.ts +0 -18
  189. package/lib/constants.js +0 -23
  190. package/lib/server/loadSetup.js +0 -25
  191. package/lib/server/versions/__fixtures__/dummy-plugin.js +0 -0
  192. package/lib/server/versions/__fixtures__/package.json +0 -3
  193. package/lib/server/versions/__tests/index.test.js +0 -25
  194. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  195. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  196. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  197. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  198. package/lib/webpack/sharedModuleAliases.js +0 -18
  199. package/tsconfig.client.json +0 -13
  200. package/tsconfig.json +0 -13
@@ -9,12 +9,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  const tslib_1 = require("tslib");
10
10
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
11
11
  const shelljs_1 = tslib_1.__importDefault(require("shelljs"));
12
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
12
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
13
+ const utils_1 = require("@docusaurus/utils");
13
14
  const server_1 = require("../server");
14
15
  const build_1 = tslib_1.__importDefault(require("./build"));
15
16
  const path_1 = tslib_1.__importDefault(require("path"));
16
17
  const os_1 = tslib_1.__importDefault(require("os"));
17
- const buildRemoteBranchUrl_1 = require("./buildRemoteBranchUrl");
18
18
  // GIT_PASS env variable should not appear in logs
19
19
  function obfuscateGitPass(str) {
20
20
  const gitPass = process.env.GIT_PASS;
@@ -25,72 +25,99 @@ function obfuscateGitPass(str) {
25
25
  function shellExecLog(cmd) {
26
26
  try {
27
27
  const result = shelljs_1.default.exec(cmd);
28
- console.log(`${chalk_1.default.cyan('CMD:')} ${obfuscateGitPass(cmd)} ${chalk_1.default.cyan(`(code=${result.code})`)}`);
28
+ logger_1.default.info `code=${obfuscateGitPass(cmd)} subdue=${`code: ${result.code}`}`;
29
29
  return result;
30
30
  }
31
- catch (e) {
32
- console.log(`${chalk_1.default.red('CMD:')} ${obfuscateGitPass(cmd)}`);
33
- throw e;
31
+ catch (err) {
32
+ logger_1.default.error `code=${obfuscateGitPass(cmd)}`;
33
+ throw err;
34
34
  }
35
35
  }
36
36
  async function deploy(siteDir, cliOptions = {}) {
37
- const { outDir, siteConfig, siteConfigPath } = await server_1.loadContext(siteDir, {
37
+ const { outDir, siteConfig, siteConfigPath } = await (0, server_1.loadContext)(siteDir, {
38
38
  customConfigFilePath: cliOptions.config,
39
39
  customOutDir: cliOptions.outDir,
40
40
  });
41
- console.log('Deploy command invoked ...');
41
+ if (typeof siteConfig.trailingSlash === 'undefined') {
42
+ logger_1.default.warn(`When deploying to GitHub Pages, it is better to use an explicit "trailingSlash" site config.
43
+ Otherwise, GitHub Pages will add an extra trailing slash to your site urls only on direct-access (not when navigation) with a server redirect.
44
+ This behavior can have SEO impacts and create relative link issues.
45
+ `);
46
+ }
47
+ logger_1.default.info('Deploy command invoked...');
42
48
  if (!shelljs_1.default.which('git')) {
43
49
  throw new Error('Git not installed or on the PATH!');
44
50
  }
51
+ // Source repo is the repo from where the command is invoked
52
+ const sourceRepoUrl = shelljs_1.default
53
+ .exec('git config --get remote.origin.url', { silent: true })
54
+ .stdout.trim();
55
+ // The source branch; defaults to the currently checked out branch
56
+ const sourceBranch = process.env.CURRENT_BRANCH ||
57
+ shelljs_1.default.exec('git rev-parse --abbrev-ref HEAD', { silent: true }).stdout.trim();
45
58
  const gitUser = process.env.GIT_USER;
46
- if (!gitUser) {
47
- throw new Error('Please set the GIT_USER environment variable!');
59
+ let useSSH = process.env.USE_SSH !== undefined &&
60
+ process.env.USE_SSH.toLowerCase() === 'true';
61
+ if (!gitUser && !useSSH) {
62
+ // If USE_SSH is unspecified: try inferring from repo URL
63
+ if (process.env.USE_SSH === undefined && (0, utils_1.hasSSHProtocol)(sourceRepoUrl)) {
64
+ useSSH = true;
65
+ }
66
+ else {
67
+ throw new Error('Please set the GIT_USER environment variable, or explicitly specify USE_SSH instead!');
68
+ }
48
69
  }
49
- // The branch that contains the latest docs changes that will be deployed.
50
- const currentBranch = process.env.CURRENT_BRANCH ||
51
- shelljs_1.default.exec('git rev-parse --abbrev-ref HEAD').stdout.trim();
52
70
  const organizationName = process.env.ORGANIZATION_NAME ||
53
71
  process.env.CIRCLE_PROJECT_USERNAME ||
54
72
  siteConfig.organizationName;
55
73
  if (!organizationName) {
56
- throw new Error(`Missing project organization name. Did you forget to define 'organizationName' in ${siteConfigPath}? You may also export it via the ORGANIZATION_NAME environment variable.`);
74
+ throw new Error(`Missing project organization name. Did you forget to define "organizationName" in ${siteConfigPath}? You may also export it via the ORGANIZATION_NAME environment variable.`);
57
75
  }
58
- console.log(`${chalk_1.default.cyan('organizationName:')} ${organizationName}`);
76
+ logger_1.default.info `organizationName: name=${organizationName}`;
59
77
  const projectName = process.env.PROJECT_NAME ||
60
78
  process.env.CIRCLE_PROJECT_REPONAME ||
61
79
  siteConfig.projectName;
62
80
  if (!projectName) {
63
- throw new Error(`Missing project name. Did you forget to define 'projectName' in ${siteConfigPath}? You may also export it via the PROJECT_NAME environment variable.`);
81
+ throw new Error(`Missing project name. Did you forget to define "projectName" in ${siteConfigPath}? You may also export it via the PROJECT_NAME environment variable.`);
64
82
  }
65
- console.log(`${chalk_1.default.cyan('projectName:')} ${projectName}`);
83
+ logger_1.default.info `projectName: name=${projectName}`;
66
84
  // We never deploy on pull request.
67
85
  const isPullRequest = process.env.CI_PULL_REQUEST || process.env.CIRCLE_PULL_REQUEST;
68
86
  if (isPullRequest) {
69
- shelljs_1.default.echo('Skipping deploy on a pull request');
87
+ shelljs_1.default.echo('Skipping deploy on a pull request.');
70
88
  shelljs_1.default.exit(0);
71
89
  }
72
- // github.io indicates organization repos that deploy via master. All others use gh-pages.
73
- const deploymentBranch = process.env.DEPLOYMENT_BRANCH ||
74
- (projectName.indexOf('.github.io') !== -1 ? 'master' : 'gh-pages');
75
- console.log(`${chalk_1.default.cyan('deploymentBranch:')} ${deploymentBranch}`);
90
+ // github.io indicates organization repos that deploy via default branch.
91
+ // All others use gh-pages. Organization deploys looks like:
92
+ // - Git repo: https://github.com/<organization>/<organization>.github.io
93
+ // - Site url: https://<organization>.github.io
94
+ const isGitHubPagesOrganizationDeploy = projectName.includes('.github.io');
95
+ if (isGitHubPagesOrganizationDeploy &&
96
+ !process.env.DEPLOYMENT_BRANCH &&
97
+ !siteConfig.deploymentBranch) {
98
+ throw new Error(`For GitHub pages organization deployments, 'docusaurus deploy' does not assume anymore that 'master' is your default Git branch.
99
+ Please provide the branch name to deploy to as an environment variable, for example DEPLOYMENT_BRANCH=main or DEPLOYMENT_BRANCH=master .
100
+ You can also set the deploymentBranch property in docusaurus.config.js .`);
101
+ }
102
+ const deploymentBranch = process.env.DEPLOYMENT_BRANCH || siteConfig.deploymentBranch || 'gh-pages';
103
+ logger_1.default.info `deploymentBranch: name=${deploymentBranch}`;
76
104
  const githubHost = process.env.GITHUB_HOST || siteConfig.githubHost || 'github.com';
77
105
  const githubPort = process.env.GITHUB_PORT || siteConfig.githubPort;
78
- const gitPass = process.env.GIT_PASS;
79
- let gitCredentials = `${gitUser}`;
80
- if (gitPass) {
81
- gitCredentials = `${gitCredentials}:${gitPass}`;
106
+ let deploymentRepoURL;
107
+ if (useSSH) {
108
+ deploymentRepoURL = (0, utils_1.buildSshUrl)(githubHost, organizationName, projectName, githubPort);
109
+ }
110
+ else {
111
+ const gitPass = process.env.GIT_PASS;
112
+ const gitCredentials = gitPass ? `${gitUser}:${gitPass}` : gitUser;
113
+ deploymentRepoURL = (0, utils_1.buildHttpsUrl)(gitCredentials, githubHost, organizationName, projectName, githubPort);
82
114
  }
83
- const useSSH = process.env.USE_SSH;
84
- const remoteBranch = buildRemoteBranchUrl_1.buildUrl(githubHost, githubPort, gitCredentials, organizationName, projectName, useSSH !== undefined && useSSH.toLowerCase() === 'true');
85
- console.log(`${chalk_1.default.cyan('Remote branch:')} ${obfuscateGitPass(remoteBranch)}`);
115
+ logger_1.default.info `Remote repo URL: name=${obfuscateGitPass(deploymentRepoURL)}`;
86
116
  // Check if this is a cross-repo publish.
87
- const currentRepoUrl = shelljs_1.default
88
- .exec('git config --get remote.origin.url')
89
- .stdout.trim();
90
- const crossRepoPublish = !currentRepoUrl.endsWith(`${organizationName}/${projectName}.git`);
117
+ const crossRepoPublish = !sourceRepoUrl.endsWith(`${organizationName}/${projectName}.git`);
91
118
  // We don't allow deploying to the same branch unless it's a cross publish.
92
- if (currentBranch === deploymentBranch && !crossRepoPublish) {
93
- throw new Error(`You cannot deploy from this branch (${currentBranch}).` +
119
+ if (sourceBranch === deploymentBranch && !crossRepoPublish) {
120
+ throw new Error(`You cannot deploy from this branch (${sourceBranch}).` +
94
121
  '\nYou will need to checkout to a different branch!');
95
122
  }
96
123
  // Save the commit hash that triggers publish-gh-pages before checking
@@ -99,42 +126,32 @@ async function deploy(siteDir, cliOptions = {}) {
99
126
  const runDeploy = async (outputDirectory) => {
100
127
  const fromPath = outputDirectory;
101
128
  const toPath = await fs_extra_1.default.mkdtemp(path_1.default.join(os_1.default.tmpdir(), `${projectName}-${deploymentBranch}`));
102
- if (shellExecLog(`git clone ${remoteBranch} ${toPath}`).code !== 0) {
103
- throw new Error(`Error: git clone failed in ${toPath}`);
104
- }
105
129
  shelljs_1.default.cd(toPath);
106
- // If the default branch is the one we're deploying to, then we'll fail
107
- // to create it. This is the case of a cross-repo publish, where we clone
108
- // a github.io repo with a default master branch.
109
- const defaultBranch = shelljs_1.default
110
- .exec('git rev-parse --abbrev-ref HEAD')
111
- .stdout.trim();
112
- if (defaultBranch !== deploymentBranch) {
113
- if (shellExecLog(`git checkout origin/${deploymentBranch}`).code !== 0) {
114
- if (shellExecLog(`git checkout --orphan ${deploymentBranch}`).code !== 0) {
115
- throw new Error(`Error: Git checkout ${deploymentBranch} failed`);
116
- }
117
- }
118
- else if (shellExecLog(`git checkout -b ${deploymentBranch}`).code +
119
- shellExecLog(`git branch --set-upstream-to=origin/${deploymentBranch}`).code !==
120
- 0) {
121
- throw new Error(`Error: Git checkout ${deploymentBranch} failed`);
122
- }
130
+ // Check out deployment branch when cloning repository, and then remove all
131
+ // the files in the directory. If the 'clone' command fails, assume that
132
+ // the deployment branch doesn't exist, and initialize git in an empty
133
+ // directory, check out a clean deployment branch and add remote.
134
+ if (shellExecLog(`git clone --depth 1 --branch ${deploymentBranch} ${deploymentRepoURL} "${toPath}"`).code === 0) {
135
+ shellExecLog('git rm -rf .');
136
+ }
137
+ else {
138
+ shellExecLog('git init');
139
+ shellExecLog(`git checkout -b ${deploymentBranch}`);
140
+ shellExecLog(`git remote add origin ${deploymentRepoURL}`);
123
141
  }
124
- shellExecLog('git rm -rf .');
125
142
  try {
126
143
  await fs_extra_1.default.copy(fromPath, toPath);
127
144
  }
128
- catch (error) {
129
- throw new Error(`Error: Copying build assets from "${fromPath}" to "${toPath}" failed with error '${error}'`);
145
+ catch (err) {
146
+ logger_1.default.error `Copying build assets from path=${fromPath} to path=${toPath} failed.`;
147
+ throw err;
130
148
  }
131
- shelljs_1.default.cd(toPath);
132
149
  shellExecLog('git add --all');
133
150
  const commitMessage = process.env.CUSTOM_COMMIT_MESSAGE ||
134
151
  `Deploy website - based on ${currentCommit}`;
135
152
  const commitResults = shellExecLog(`git commit -m "${commitMessage}"`);
136
153
  if (shellExecLog(`git push --force origin ${deploymentBranch}`).code !== 0) {
137
- throw new Error('Error: Git push failed');
154
+ throw new Error('Running "git push" command failed. Does the GitHub user account you are using have push access to the repository?');
138
155
  }
139
156
  else if (commitResults.code === 0) {
140
157
  // The commit might return a non-zero value when site is up to date.
@@ -148,18 +165,18 @@ async function deploy(siteDir, cliOptions = {}) {
148
165
  // GitHub enterprise hosting.
149
166
  websiteURL = `https://${githubHost}/pages/${organizationName}/${projectName}/`;
150
167
  }
151
- shelljs_1.default.echo(`Website is live at ${websiteURL}`);
168
+ shelljs_1.default.echo(`Website is live at "${websiteURL}".`);
152
169
  shelljs_1.default.exit(0);
153
170
  }
154
171
  };
155
172
  if (!cliOptions.skipBuild) {
156
- // Build static html files, then push to deploymentBranch branch of specified repo.
173
+ // Build site, then push to deploymentBranch branch of specified repo.
157
174
  try {
158
- await runDeploy(await build_1.default(siteDir, cliOptions, false));
175
+ await runDeploy(await (0, build_1.default)(siteDir, cliOptions, false));
159
176
  }
160
- catch (buildError) {
161
- console.error(buildError);
162
- process.exit(1);
177
+ catch (err) {
178
+ logger_1.default.error('Deployment of the build output failed.');
179
+ throw err;
163
180
  }
164
181
  }
165
182
  else {
@@ -4,5 +4,5 @@
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 { Command } from 'commander';
8
- export default function externalCommand(cli: Command, siteDir: string): Promise<void>;
7
+ import type { CommanderStatic } from 'commander';
8
+ export default function externalCommand(cli: CommanderStatic, siteDir: string): Promise<void>;
@@ -10,16 +10,12 @@ const tslib_1 = require("tslib");
10
10
  const server_1 = require("../server");
11
11
  const init_1 = tslib_1.__importDefault(require("../server/plugins/init"));
12
12
  async function externalCommand(cli, siteDir) {
13
- const context = await server_1.loadContext(siteDir);
14
- const pluginConfigs = server_1.loadPluginConfigs(context);
15
- const plugins = init_1.default({ pluginConfigs, context });
13
+ const context = await (0, server_1.loadContext)(siteDir);
14
+ const pluginConfigs = await (0, server_1.loadPluginConfigs)(context);
15
+ const plugins = await (0, init_1.default)({ pluginConfigs, context });
16
16
  // Plugin Lifecycle - extendCli.
17
17
  plugins.forEach((plugin) => {
18
- const { extendCli } = plugin;
19
- if (!extendCli) {
20
- return;
21
- }
22
- extendCli(cli);
18
+ plugin.extendCli?.(cli);
23
19
  });
24
20
  }
25
21
  exports.default = externalCommand;
@@ -4,5 +4,5 @@
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 { ServeCLIOptions } from '@docusaurus/types';
7
+ import type { ServeCLIOptions } from '@docusaurus/types';
8
8
  export default function serve(siteDir: string, cliOptions: ServeCLIOptions): Promise<void>;
@@ -9,9 +9,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  const tslib_1 = require("tslib");
10
10
  const http_1 = tslib_1.__importDefault(require("http"));
11
11
  const serve_handler_1 = tslib_1.__importDefault(require("serve-handler"));
12
- const boxen_1 = tslib_1.__importDefault(require("boxen"));
13
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
12
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
14
13
  const path_1 = tslib_1.__importDefault(require("path"));
14
+ const server_1 = require("../server");
15
15
  const build_1 = tslib_1.__importDefault(require("./build"));
16
16
  const commandUtils_1 = require("./commandUtils");
17
17
  async function serve(siteDir, cliOptions) {
@@ -19,28 +19,41 @@ async function serve(siteDir, cliOptions) {
19
19
  ? cliOptions.dir
20
20
  : path_1.default.join(siteDir, cliOptions.dir);
21
21
  if (cliOptions.build) {
22
- dir = await build_1.default(siteDir, {
22
+ dir = await (0, build_1.default)(siteDir, {
23
23
  config: cliOptions.config,
24
24
  outDir: dir,
25
25
  }, false);
26
26
  }
27
- const host = commandUtils_1.getCLIOptionHost(cliOptions.host);
28
- const port = await commandUtils_1.getCLIOptionPort(cliOptions.port, host);
27
+ const host = (0, commandUtils_1.getCLIOptionHost)(cliOptions.host);
28
+ const port = await (0, commandUtils_1.getCLIOptionPort)(cliOptions.port, host);
29
29
  if (port === null) {
30
30
  process.exit();
31
31
  }
32
+ const { siteConfig: { baseUrl, trailingSlash }, } = await (0, server_1.loadSiteConfig)({
33
+ siteDir,
34
+ customConfigFilePath: cliOptions.config,
35
+ });
36
+ const servingUrl = `http://${host}:${port}`;
32
37
  const server = http_1.default.createServer((req, res) => {
33
- serve_handler_1.default(req, res, {
38
+ // Automatically redirect requests to /baseUrl/
39
+ if (!req.url?.startsWith(baseUrl)) {
40
+ res.writeHead(302, {
41
+ Location: baseUrl,
42
+ });
43
+ res.end();
44
+ return;
45
+ }
46
+ // Remove baseUrl before calling serveHandler, because /baseUrl/ should
47
+ // serve /build/index.html, not /build/baseUrl/index.html (does not exist)
48
+ req.url = req.url?.replace(baseUrl, '/');
49
+ (0, serve_handler_1.default)(req, res, {
34
50
  cleanUrls: true,
35
51
  public: dir,
52
+ trailingSlash,
53
+ directoryListing: false,
36
54
  });
37
55
  });
38
- console.log(boxen_1.default(`${chalk_1.default.green(`Serving ${cliOptions.dir}!`)}\n\n- Local: http://${cliOptions.host}:${port}`, {
39
- borderColor: 'green',
40
- padding: 1,
41
- margin: 1,
42
- align: 'center',
43
- }));
56
+ logger_1.default.success `Serving path=${cliOptions.dir} directory at path=${servingUrl + baseUrl}.`;
44
57
  server.listen(port);
45
58
  }
46
59
  exports.default = serve;
@@ -4,5 +4,5 @@
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 { StartCLIOptions } from '@docusaurus/types';
7
+ import type { StartCLIOptions } from '@docusaurus/types';
8
8
  export default function start(siteDir: string, cliOptions: Partial<StartCLIOptions>): Promise<void>;
@@ -8,23 +8,18 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  const tslib_1 = require("tslib");
10
10
  const utils_1 = require("@docusaurus/utils");
11
- const chalk = require("chalk");
11
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
12
  const chokidar_1 = tslib_1.__importDefault(require("chokidar"));
13
- const express_1 = tslib_1.__importDefault(require("express"));
14
13
  const html_webpack_plugin_1 = tslib_1.__importDefault(require("html-webpack-plugin"));
15
14
  const path_1 = tslib_1.__importDefault(require("path"));
16
- const lodash_1 = require("lodash");
15
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
17
16
  const openBrowser_1 = tslib_1.__importDefault(require("react-dev-utils/openBrowser"));
18
17
  const WebpackDevServerUtils_1 = require("react-dev-utils/WebpackDevServerUtils");
19
- const errorOverlayMiddleware_1 = tslib_1.__importDefault(require("react-dev-utils/errorOverlayMiddleware"));
20
- // import evalSourceMapMiddleware from 'react-dev-utils/evalSourceMapMiddleware';
21
- const evalSourceMapMiddleware_1 = tslib_1.__importDefault(require("../webpack/react-dev-utils-webpack5/evalSourceMapMiddleware"));
18
+ const evalSourceMapMiddleware_1 = tslib_1.__importDefault(require("react-dev-utils/evalSourceMapMiddleware"));
22
19
  const webpack_1 = tslib_1.__importDefault(require("webpack"));
23
20
  const webpack_dev_server_1 = tslib_1.__importDefault(require("webpack-dev-server"));
24
21
  const webpack_merge_1 = tslib_1.__importDefault(require("webpack-merge"));
25
- const HotModuleReplacementPlugin_1 = tslib_1.__importDefault(require("webpack/lib/HotModuleReplacementPlugin"));
26
22
  const server_1 = require("../server");
27
- const constants_1 = require("../constants");
28
23
  const client_1 = tslib_1.__importDefault(require("../webpack/client"));
29
24
  const utils_2 = require("../webpack/utils");
30
25
  const commandUtils_1 = require("./commandUtils");
@@ -32,9 +27,9 @@ const translations_1 = require("../server/translations/translations");
32
27
  async function start(siteDir, cliOptions) {
33
28
  process.env.NODE_ENV = 'development';
34
29
  process.env.BABEL_ENV = 'development';
35
- console.log(chalk.blue('Starting the development server...'));
30
+ logger_1.default.info('Starting the development server...');
36
31
  function loadSite() {
37
- return server_1.load(siteDir, {
32
+ return (0, server_1.load)(siteDir, {
38
33
  customConfigFilePath: cliOptions.config,
39
34
  locale: cliOptions.locale,
40
35
  localizePath: undefined, // should this be configurable?
@@ -43,62 +38,69 @@ async function start(siteDir, cliOptions) {
43
38
  // Process all related files as a prop.
44
39
  const props = await loadSite();
45
40
  const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
46
- const host = commandUtils_1.getCLIOptionHost(cliOptions.host);
47
- const port = await commandUtils_1.getCLIOptionPort(cliOptions.port, host);
41
+ const host = (0, commandUtils_1.getCLIOptionHost)(cliOptions.host);
42
+ const port = await (0, commandUtils_1.getCLIOptionPort)(cliOptions.port, host);
48
43
  if (port === null) {
49
44
  process.exit();
50
45
  }
51
46
  const { baseUrl, headTags, preBodyTags, postBodyTags } = props;
52
- const urls = WebpackDevServerUtils_1.prepareUrls(protocol, host, port);
53
- const openUrl = utils_1.normalizeUrl([urls.localUrlForBrowser, baseUrl]);
54
- console.log(chalk.cyanBright(`Docusaurus website is running at: ${openUrl}`));
47
+ const urls = (0, WebpackDevServerUtils_1.prepareUrls)(protocol, host, port);
48
+ const openUrl = (0, utils_1.normalizeUrl)([urls.localUrlForBrowser, baseUrl]);
49
+ logger_1.default.success `Docusaurus website is running at path=${openUrl}.`;
55
50
  // Reload files processing.
56
- const reload = lodash_1.debounce(() => {
51
+ const reload = lodash_1.default.debounce(() => {
57
52
  loadSite()
58
53
  .then(({ baseUrl: newBaseUrl }) => {
59
- const newOpenUrl = utils_1.normalizeUrl([urls.localUrlForBrowser, newBaseUrl]);
54
+ const newOpenUrl = (0, utils_1.normalizeUrl)([urls.localUrlForBrowser, newBaseUrl]);
60
55
  if (newOpenUrl !== openUrl) {
61
- console.log(chalk.cyanBright(`Docusaurus website is running at: ${newOpenUrl}`));
56
+ logger_1.default.success `Docusaurus website is running at path=${newOpenUrl}.`;
62
57
  }
63
58
  })
64
59
  .catch((err) => {
65
- console.error(chalk.red(err.stack));
60
+ logger_1.default.error(err.stack);
66
61
  });
67
62
  }, 500);
68
- const { siteConfig, plugins = [] } = props;
63
+ const { siteConfig, plugins } = props;
69
64
  const normalizeToSiteDir = (filepath) => {
70
65
  if (filepath && path_1.default.isAbsolute(filepath)) {
71
- return utils_1.posixPath(path_1.default.relative(siteDir, filepath));
66
+ return (0, utils_1.posixPath)(path_1.default.relative(siteDir, filepath));
72
67
  }
73
- return utils_1.posixPath(filepath);
68
+ return (0, utils_1.posixPath)(filepath);
74
69
  };
75
- const pluginPaths = []
76
- .concat(...plugins
77
- .map((plugin) => { var _a, _b; return (_b = (_a = plugin.getPathsToWatch) === null || _a === void 0 ? void 0 : _a.call(plugin)) !== null && _b !== void 0 ? _b : []; })
78
- .filter(Boolean))
70
+ const pluginPaths = plugins
71
+ .flatMap((plugin) => plugin.getPathsToWatch?.() ?? [])
72
+ .filter(Boolean)
79
73
  .map(normalizeToSiteDir);
80
74
  const pathsToWatch = [
81
75
  ...pluginPaths,
82
76
  props.siteConfigPath,
83
- translations_1.getTranslationsLocaleDirPath({
77
+ (0, translations_1.getTranslationsLocaleDirPath)({
84
78
  siteDir,
85
79
  locale: props.i18n.currentLocale,
86
80
  }),
87
81
  ];
88
- const fsWatcher = chokidar_1.default.watch(pathsToWatch, {
89
- cwd: siteDir,
90
- ignoreInitial: true,
82
+ const pollingOptions = {
91
83
  usePolling: !!cliOptions.poll,
92
84
  interval: Number.isInteger(cliOptions.poll)
93
85
  ? cliOptions.poll
94
86
  : undefined,
87
+ };
88
+ const httpsConfig = await (0, utils_2.getHttpsConfig)();
89
+ const fsWatcher = chokidar_1.default.watch(pathsToWatch, {
90
+ cwd: siteDir,
91
+ ignoreInitial: true,
92
+ ...{ pollingOptions },
95
93
  });
96
94
  ['add', 'change', 'unlink', 'addDir', 'unlinkDir'].forEach((event) => fsWatcher.on(event, reload));
97
- let config = webpack_merge_1.default(client_1.default(props), {
95
+ let config = (0, webpack_merge_1.default)(await (0, client_1.default)(props), {
96
+ infrastructureLogging: {
97
+ // Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
98
+ level: 'warn',
99
+ },
98
100
  plugins: [
99
101
  // Generates an `index.html` file with the <script> injected.
100
102
  new html_webpack_plugin_1.default({
101
- template: path_1.default.resolve(__dirname, '../client/templates/index.html.template.ejs'),
103
+ template: path_1.default.join(__dirname, '../webpack/templates/index.html.template.ejs'),
102
104
  // So we can define the position where the scripts are injected.
103
105
  inject: false,
104
106
  filename: 'index.html',
@@ -107,84 +109,91 @@ async function start(siteDir, cliOptions) {
107
109
  preBodyTags,
108
110
  postBodyTags,
109
111
  }),
110
- // This is necessary to emit hot updates for webpack-dev-server.
111
- new HotModuleReplacementPlugin_1.default(),
112
112
  ],
113
113
  });
114
114
  // Plugin Lifecycle - configureWebpack and configurePostCss.
115
115
  plugins.forEach((plugin) => {
116
- var _a;
117
116
  const { configureWebpack, configurePostCss } = plugin;
118
117
  if (configurePostCss) {
119
- config = utils_2.applyConfigurePostCss(configurePostCss, config);
118
+ config = (0, utils_2.applyConfigurePostCss)(configurePostCss.bind(plugin), config);
120
119
  }
121
120
  if (configureWebpack) {
122
- config = utils_2.applyConfigureWebpack(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`.
123
- config, false, (_a = props.siteConfig.webpack) === null || _a === void 0 ? void 0 : _a.jsLoader);
121
+ config = (0, utils_2.applyConfigureWebpack)(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`.
122
+ config, false, props.siteConfig.webpack?.jsLoader, plugin.content);
124
123
  }
125
124
  });
126
- // https://webpack.js.org/configuration/dev-server
127
- const devServerConfig = {
128
- ...{
129
- compress: true,
130
- clientLogLevel: 'error',
131
- hot: true,
132
- hotOnly: cliOptions.hotOnly,
133
- // Use 'ws' instead of 'sockjs-node' on server since we're using native
134
- // websockets in `webpackHotDevClient`.
135
- transportMode: 'ws',
136
- // Prevent a WS client from getting injected as we're already including
137
- // `webpackHotDevClient`.
138
- injectClient: false,
139
- quiet: true,
140
- https: utils_2.getHttpsConfig(),
141
- headers: {
142
- 'access-control-allow-origin': '*',
143
- },
144
- publicPath: baseUrl,
145
- watchOptions: {
146
- ignored: /node_modules/,
147
- poll: cliOptions.poll,
148
- },
149
- historyApiFallback: {
150
- rewrites: [{ from: /\/*/, to: baseUrl }],
151
- },
152
- disableHostCheck: true,
153
- // Disable overlay on browser since we use CRA's overlay error reporting.
154
- overlay: false,
155
- host,
156
- before: (app, server) => {
157
- app.use(baseUrl, express_1.default.static(path_1.default.resolve(siteDir, constants_1.STATIC_DIR_NAME)));
158
- // This lets us fetch source contents from webpack for the error overlay.
159
- app.use(evalSourceMapMiddleware_1.default(server));
160
- // This lets us open files from the runtime error overlay.
161
- app.use(errorOverlayMiddleware_1.default());
162
- },
163
- },
164
- };
165
- const compiler = webpack_1.default(config);
125
+ const compiler = (0, webpack_1.default)(config);
166
126
  if (process.env.E2E_TEST) {
167
127
  compiler.hooks.done.tap('done', (stats) => {
168
128
  if (stats.hasErrors()) {
169
- console.log('E2E_TEST: Project has compiler errors.');
129
+ logger_1.default.error('E2E_TEST: Project has compiler errors.');
170
130
  process.exit(1);
171
131
  }
172
- console.log('E2E_TEST: Project can compile.');
132
+ logger_1.default.success('E2E_TEST: Project can compile.');
173
133
  process.exit(0);
174
134
  });
175
135
  }
176
- const devServer = new webpack_dev_server_1.default(compiler, devServerConfig);
177
- devServer.listen(port, host, (err) => {
178
- if (err) {
179
- console.log(err);
180
- }
136
+ // https://webpack.js.org/configuration/dev-server
137
+ const defaultDevServerConfig = {
138
+ hot: cliOptions.hotOnly ? 'only' : true,
139
+ liveReload: false,
140
+ client: {
141
+ progress: true,
142
+ overlay: {
143
+ warnings: false,
144
+ errors: true,
145
+ },
146
+ },
147
+ headers: {
148
+ 'access-control-allow-origin': '*',
149
+ },
150
+ devMiddleware: {
151
+ publicPath: baseUrl,
152
+ // Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
153
+ stats: 'summary',
154
+ },
155
+ static: siteConfig.staticDirectories.map((dir) => ({
156
+ publicPath: baseUrl,
157
+ directory: path_1.default.resolve(siteDir, dir),
158
+ watch: {
159
+ // Useful options for our own monorepo using symlinks!
160
+ // See https://github.com/webpack/webpack/issues/11612#issuecomment-879259806
161
+ followSymlinks: true,
162
+ ignored: /node_modules\/(?!@docusaurus)/,
163
+ ...{ pollingOptions },
164
+ },
165
+ })),
166
+ ...(httpsConfig && {
167
+ server: typeof httpsConfig === 'object'
168
+ ? {
169
+ type: 'https',
170
+ options: httpsConfig,
171
+ }
172
+ : 'https',
173
+ }),
174
+ historyApiFallback: {
175
+ rewrites: [{ from: /\/*/, to: baseUrl }],
176
+ },
177
+ allowedHosts: 'all',
178
+ host,
179
+ port,
180
+ setupMiddlewares: (middlewares, devServer) => {
181
+ // This lets us fetch source contents from webpack for the error overlay.
182
+ middlewares.unshift((0, evalSourceMapMiddleware_1.default)(devServer));
183
+ return middlewares;
184
+ },
185
+ };
186
+ // Allow plugin authors to customize/override devServer config
187
+ const devServerConfig = (0, webpack_merge_1.default)([defaultDevServerConfig, config.devServer].filter(Boolean));
188
+ const devServer = new webpack_dev_server_1.default(devServerConfig, compiler);
189
+ devServer.startCallback(() => {
181
190
  if (cliOptions.open) {
182
- openBrowser_1.default(openUrl);
191
+ (0, openBrowser_1.default)(openUrl);
183
192
  }
184
193
  });
185
194
  ['SIGINT', 'SIGTERM'].forEach((sig) => {
186
195
  process.on(sig, () => {
187
- devServer.close();
196
+ devServer.stop();
188
197
  process.exit();
189
198
  });
190
199
  });
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import type { SwizzleAction, SwizzleComponentConfig } from '@docusaurus/types';
8
+ import type { SwizzleOptions } from './common';
9
+ export declare const SwizzleActions: SwizzleAction[];
10
+ export declare function getAction(componentConfig: SwizzleComponentConfig, options: Pick<SwizzleOptions, 'wrap' | 'eject'>): Promise<SwizzleAction>;
11
+ export declare type ActionParams = {
12
+ siteDir: string;
13
+ themePath: string;
14
+ componentName: string;
15
+ };
16
+ export declare type ActionResult = {
17
+ createdFiles: string[];
18
+ };
19
+ export declare function eject({ siteDir, themePath, componentName, }: ActionParams): Promise<ActionResult>;
20
+ export declare function wrap({ siteDir, themePath, componentName: themeComponentName, typescript, importType, }: ActionParams & {
21
+ typescript: boolean;
22
+ importType?: 'original' | 'init';
23
+ }): Promise<ActionResult>;