@docusaurus/core 2.0.0-beta.15a2b59f9 → 2.0.0-beta.17

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 (189) hide show
  1. package/bin/beforeCli.mjs +136 -0
  2. package/bin/{docusaurus.js → docusaurus.mjs} +63 -108
  3. package/lib/babel/preset.d.ts +8 -3
  4. package/lib/babel/preset.js +8 -7
  5. package/lib/choosePort.js +29 -38
  6. package/lib/client/.eslintrc.js +0 -1
  7. package/lib/client/App.d.ts +1 -2
  8. package/lib/client/App.js +19 -24
  9. package/lib/client/LinksCollector.d.ts +3 -3
  10. package/lib/client/LinksCollector.js +5 -9
  11. package/lib/client/PendingNavigation.d.ts +24 -1
  12. package/lib/client/PendingNavigation.js +5 -7
  13. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.d.ts +13 -0
  14. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.js +15 -10
  15. package/lib/client/client-lifecycles-dispatcher.d.ts +2 -5
  16. package/lib/client/client-lifecycles-dispatcher.js +6 -10
  17. package/lib/client/clientEntry.js +11 -5
  18. package/lib/client/docusaurus.d.ts +6 -0
  19. package/lib/client/docusaurus.js +16 -25
  20. package/lib/client/exports/BrowserOnly.d.ts +2 -3
  21. package/lib/client/exports/BrowserOnly.js +13 -7
  22. package/lib/client/exports/ComponentCreator.d.ts +1 -2
  23. package/lib/client/exports/ComponentCreator.js +7 -6
  24. package/lib/client/exports/ErrorBoundary.d.ts +18 -0
  25. package/lib/client/exports/ErrorBoundary.js +35 -0
  26. package/lib/client/exports/Head.d.ts +2 -3
  27. package/lib/client/exports/Head.js +3 -4
  28. package/lib/client/exports/Interpolate.d.ts +1 -1
  29. package/lib/client/exports/Interpolate.js +16 -22
  30. package/lib/client/exports/Link.d.ts +11 -5
  31. package/lib/client/exports/Link.js +24 -19
  32. package/lib/client/exports/Translate.d.ts +3 -3
  33. package/lib/client/exports/Translate.js +14 -10
  34. package/lib/client/exports/browserContext.d.ts +11 -0
  35. package/lib/client/exports/browserContext.js +22 -0
  36. package/lib/client/exports/constants.js +1 -11
  37. package/lib/client/exports/docusaurusContext.d.ts +12 -0
  38. package/lib/client/exports/docusaurusContext.js +25 -0
  39. package/lib/client/exports/isInternalUrl.js +1 -1
  40. package/lib/client/exports/renderRoutes.d.ts +1 -2
  41. package/lib/client/exports/renderRoutes.js +1 -2
  42. package/lib/client/exports/router.d.ts +1 -1
  43. package/lib/client/exports/router.js +1 -1
  44. package/lib/client/exports/useBaseUrl.js +3 -5
  45. package/lib/client/exports/useDocusaurusContext.d.ts +2 -3
  46. package/lib/client/exports/useDocusaurusContext.js +3 -9
  47. package/lib/client/exports/useGlobalData.js +1 -5
  48. package/lib/{server/versions/__tests/index.test.d.ts → client/exports/useIsBrowser.d.ts} +1 -1
  49. package/lib/client/exports/useIsBrowser.js +11 -0
  50. package/lib/client/flat.d.ts +2 -2
  51. package/lib/client/flat.js +8 -11
  52. package/lib/client/normalizeLocation.d.ts +2 -5
  53. package/lib/client/normalizeLocation.js +1 -2
  54. package/lib/client/nprogress.css +2 -2
  55. package/lib/client/prefetch.d.ts +1 -2
  56. package/lib/client/prefetch.js +1 -3
  57. package/lib/client/preload.d.ts +3 -2
  58. package/lib/client/preload.js +2 -1
  59. package/lib/client/serverEntry.d.ts +10 -0
  60. package/lib/client/serverEntry.js +90 -142
  61. package/lib/client/theme-fallback/Error/index.d.ts +10 -0
  62. package/lib/client/theme-fallback/Error/index.js +39 -0
  63. package/lib/client/theme-fallback/Layout/index.d.ts +10 -0
  64. package/lib/client/theme-fallback/Layout/index.js +10 -19
  65. package/lib/client/theme-fallback/Loading/index.d.ts +9 -0
  66. package/lib/client/theme-fallback/Loading/index.js +47 -115
  67. package/lib/client/{exports/context.js → theme-fallback/NotFound/index.d.ts} +2 -2
  68. package/lib/client/theme-fallback/NotFound/index.js +9 -16
  69. package/lib/{webpack/sharedModuleAliases.d.ts → client/theme-fallback/Root/index.d.ts} +4 -4
  70. package/lib/client/theme-fallback/Root/index.js +2 -7
  71. package/lib/commands/build.d.ts +1 -1
  72. package/lib/commands/build.js +50 -54
  73. package/lib/commands/clear.d.ts +6 -0
  74. package/lib/commands/clear.js +30 -19
  75. package/lib/commands/commandUtils.d.ts +7 -1
  76. package/lib/commands/commandUtils.js +6 -6
  77. package/lib/commands/deploy.d.ts +4 -1
  78. package/lib/commands/deploy.js +102 -66
  79. package/lib/commands/external.d.ts +2 -2
  80. package/lib/commands/external.js +3 -3
  81. package/lib/commands/serve.d.ts +1 -1
  82. package/lib/commands/serve.js +13 -19
  83. package/lib/commands/start.d.ts +1 -1
  84. package/lib/commands/start.js +93 -83
  85. package/lib/commands/swizzle/actions.d.ts +23 -0
  86. package/lib/commands/swizzle/actions.js +102 -0
  87. package/lib/commands/swizzle/common.d.ts +33 -0
  88. package/lib/commands/swizzle/common.js +56 -0
  89. package/lib/commands/swizzle/components.d.ts +29 -0
  90. package/lib/commands/swizzle/components.js +162 -0
  91. package/lib/commands/swizzle/config.d.ts +10 -0
  92. package/lib/commands/swizzle/config.js +80 -0
  93. package/lib/{server/loadSetup.d.ts → commands/swizzle/context.d.ts} +2 -3
  94. package/lib/commands/swizzle/context.js +30 -0
  95. package/lib/commands/swizzle/index.d.ts +8 -0
  96. package/lib/commands/swizzle/index.js +115 -0
  97. package/lib/commands/swizzle/prompts.d.ts +12 -0
  98. package/lib/commands/swizzle/prompts.js +110 -0
  99. package/lib/{client/exports/context.d.ts → commands/swizzle/tables.d.ts} +3 -4
  100. package/lib/commands/swizzle/tables.js +116 -0
  101. package/lib/commands/swizzle/themes.d.ts +20 -0
  102. package/lib/commands/swizzle/themes.js +103 -0
  103. package/lib/commands/writeHeadingIds.d.ts +9 -6
  104. package/lib/commands/writeHeadingIds.js +41 -43
  105. package/lib/commands/writeTranslations.d.ts +2 -2
  106. package/lib/commands/writeTranslations.js +35 -14
  107. package/lib/index.d.ts +10 -9
  108. package/lib/index.js +20 -19
  109. package/lib/server/brokenLinks.d.ts +1 -1
  110. package/lib/server/brokenLinks.js +57 -38
  111. package/lib/server/client-modules/index.d.ts +1 -1
  112. package/lib/server/client-modules/index.js +1 -3
  113. package/lib/server/config.d.ts +2 -2
  114. package/lib/server/config.js +7 -4
  115. package/lib/server/configValidation.d.ts +2 -2
  116. package/lib/server/configValidation.js +43 -28
  117. package/lib/server/duplicateRoutes.d.ts +1 -1
  118. package/lib/server/duplicateRoutes.js +10 -6
  119. package/lib/server/html-tags/htmlTags.js +2 -4
  120. package/lib/server/html-tags/index.d.ts +1 -1
  121. package/lib/server/html-tags/index.js +1 -1
  122. package/lib/server/i18n.d.ts +1 -2
  123. package/lib/server/i18n.js +32 -46
  124. package/lib/server/index.d.ts +2 -2
  125. package/lib/server/index.js +147 -68
  126. package/lib/server/moduleShorthand.d.ts +9 -0
  127. package/lib/server/moduleShorthand.js +46 -0
  128. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +2 -2
  129. package/lib/server/plugins/applyRouteTrailingSlash.js +1 -1
  130. package/lib/server/plugins/index.d.ts +2 -2
  131. package/lib/server/plugins/index.js +34 -35
  132. package/lib/server/plugins/init.d.ts +12 -2
  133. package/lib/server/plugins/init.js +48 -58
  134. package/lib/server/plugins/pluginIds.d.ts +1 -1
  135. package/lib/server/plugins/pluginIds.js +8 -5
  136. package/lib/server/presets/index.d.ts +3 -3
  137. package/lib/server/presets/index.js +12 -13
  138. package/lib/server/routes.d.ts +1 -1
  139. package/lib/server/routes.js +50 -29
  140. package/lib/server/themes/alias.d.ts +3 -2
  141. package/lib/server/themes/alias.js +22 -14
  142. package/lib/server/themes/index.d.ts +3 -3
  143. package/lib/server/themes/index.js +26 -26
  144. package/lib/server/translations/translations.d.ts +7 -1
  145. package/lib/server/translations/translations.js +30 -45
  146. package/lib/server/translations/translationsExtractor.d.ts +9 -3
  147. package/lib/server/translations/translationsExtractor.js +159 -120
  148. package/lib/server/utils.d.ts +9 -3
  149. package/lib/server/utils.js +7 -9
  150. package/lib/server/versions/__fixtures__/dummy-plugin.d.ts +0 -0
  151. package/lib/server/versions/index.d.ts +3 -4
  152. package/lib/server/versions/index.js +22 -21
  153. package/lib/webpack/base.d.ts +4 -4
  154. package/lib/webpack/base.js +38 -33
  155. package/lib/webpack/client.d.ts +3 -3
  156. package/lib/webpack/client.js +12 -19
  157. package/lib/webpack/plugins/ChunkAssetPlugin.d.ts +13 -3
  158. package/lib/webpack/plugins/ChunkAssetPlugin.js +17 -10
  159. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +6 -6
  160. package/lib/webpack/plugins/CleanWebpackPlugin.js +8 -14
  161. package/lib/webpack/plugins/LogPlugin.d.ts +1 -1
  162. package/lib/webpack/plugins/LogPlugin.js +4 -5
  163. package/lib/webpack/plugins/WaitPlugin.d.ts +1 -1
  164. package/lib/webpack/plugins/WaitPlugin.js +1 -1
  165. package/lib/webpack/server.d.ts +3 -3
  166. package/lib/webpack/server.js +9 -8
  167. package/lib/{client → webpack}/templates/index.html.template.ejs +0 -0
  168. package/lib/webpack/templates/ssr.html.template.d.ts +8 -0
  169. package/lib/{client → webpack}/templates/ssr.html.template.js +3 -2
  170. package/lib/webpack/utils.d.ts +7 -29
  171. package/lib/webpack/utils.js +54 -171
  172. package/package.json +74 -69
  173. package/lib/.tsbuildinfo +0 -1
  174. package/lib/client/.tsbuildinfo +0 -1
  175. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  176. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  177. package/lib/commands/swizzle.d.ts +0 -9
  178. package/lib/commands/swizzle.js +0 -245
  179. package/lib/constants.d.ts +0 -18
  180. package/lib/constants.js +0 -23
  181. package/lib/server/loadSetup.js +0 -25
  182. package/lib/server/versions/__tests/index.test.js +0 -25
  183. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  184. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  185. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  186. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  187. package/lib/webpack/sharedModuleAliases.js +0 -18
  188. package/tsconfig.client.json +0 -13
  189. package/tsconfig.json +0 -13
@@ -9,8 +9,7 @@ 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"));
15
14
  const server_1 = require("../server");
16
15
  const build_1 = tslib_1.__importDefault(require("./build"));
@@ -20,46 +19,41 @@ async function serve(siteDir, cliOptions) {
20
19
  ? cliOptions.dir
21
20
  : path_1.default.join(siteDir, cliOptions.dir);
22
21
  if (cliOptions.build) {
23
- dir = await build_1.default(siteDir, {
22
+ dir = await (0, build_1.default)(siteDir, {
24
23
  config: cliOptions.config,
25
24
  outDir: dir,
26
25
  }, false);
27
26
  }
28
- const host = commandUtils_1.getCLIOptionHost(cliOptions.host);
29
- 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);
30
29
  if (port === null) {
31
30
  process.exit();
32
31
  }
33
- const { siteConfig: { baseUrl, trailingSlash }, } = await server_1.loadSiteConfig({
32
+ const { siteConfig: { baseUrl, trailingSlash }, } = await (0, server_1.loadSiteConfig)({
34
33
  siteDir,
35
34
  customConfigFilePath: cliOptions.config,
36
35
  });
37
- const servingUrl = `http://${cliOptions.host}:${cliOptions.port}`;
36
+ const servingUrl = `http://${host}:${port}`;
38
37
  const server = http_1.default.createServer((req, res) => {
39
- var _a, _b;
40
38
  // Automatically redirect requests to /baseUrl/
41
- if (!((_a = req.url) === null || _a === void 0 ? void 0 : _a.startsWith(baseUrl))) {
39
+ if (!req.url?.startsWith(baseUrl)) {
42
40
  res.writeHead(302, {
43
41
  Location: baseUrl,
44
42
  });
45
43
  res.end();
46
44
  return;
47
45
  }
48
- // Remove baseUrl before calling serveHandler
49
- // Reason: /baseUrl/ should serve /build/index.html, not /build/baseUrl/index.html (does not exist)
50
- req.url = (_b = req.url) === null || _b === void 0 ? void 0 : _b.replace(baseUrl, '/');
51
- serve_handler_1.default(req, res, {
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, {
52
50
  cleanUrls: true,
53
51
  public: dir,
54
52
  trailingSlash,
53
+ directoryListing: false,
55
54
  });
56
55
  });
57
- console.log(boxen_1.default(chalk_1.default.green(`Serving "${cliOptions.dir}" directory at "${servingUrl + baseUrl}".`), {
58
- borderColor: 'green',
59
- padding: 1,
60
- margin: 1,
61
- align: 'center',
62
- }));
56
+ logger_1.default.success `Serving path=${cliOptions.dir} directory at path=${servingUrl + baseUrl}.`;
63
57
  server.listen(port);
64
58
  }
65
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,70 @@ 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
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
70
  const pluginPaths = []
76
71
  .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 : []; })
72
+ .map((plugin) => plugin.getPathsToWatch?.() ?? [])
78
73
  .filter(Boolean))
79
74
  .map(normalizeToSiteDir);
80
75
  const pathsToWatch = [
81
76
  ...pluginPaths,
82
77
  props.siteConfigPath,
83
- translations_1.getTranslationsLocaleDirPath({
78
+ (0, translations_1.getTranslationsLocaleDirPath)({
84
79
  siteDir,
85
80
  locale: props.i18n.currentLocale,
86
81
  }),
87
82
  ];
88
- const fsWatcher = chokidar_1.default.watch(pathsToWatch, {
89
- cwd: siteDir,
90
- ignoreInitial: true,
83
+ const pollingOptions = {
91
84
  usePolling: !!cliOptions.poll,
92
85
  interval: Number.isInteger(cliOptions.poll)
93
86
  ? cliOptions.poll
94
87
  : undefined,
88
+ };
89
+ const httpsConfig = await (0, utils_2.getHttpsConfig)();
90
+ const fsWatcher = chokidar_1.default.watch(pathsToWatch, {
91
+ cwd: siteDir,
92
+ ignoreInitial: true,
93
+ ...{ pollingOptions },
95
94
  });
96
95
  ['add', 'change', 'unlink', 'addDir', 'unlinkDir'].forEach((event) => fsWatcher.on(event, reload));
97
- let config = webpack_merge_1.default(client_1.default(props), {
96
+ let config = (0, webpack_merge_1.default)(await (0, client_1.default)(props), {
97
+ infrastructureLogging: {
98
+ // Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
99
+ level: 'warn',
100
+ },
98
101
  plugins: [
99
102
  // Generates an `index.html` file with the <script> injected.
100
103
  new html_webpack_plugin_1.default({
101
- template: path_1.default.resolve(__dirname, '../client/templates/index.html.template.ejs'),
104
+ template: path_1.default.resolve(__dirname, '../webpack/templates/index.html.template.ejs'),
102
105
  // So we can define the position where the scripts are injected.
103
106
  inject: false,
104
107
  filename: 'index.html',
@@ -107,84 +110,91 @@ async function start(siteDir, cliOptions) {
107
110
  preBodyTags,
108
111
  postBodyTags,
109
112
  }),
110
- // This is necessary to emit hot updates for webpack-dev-server.
111
- new HotModuleReplacementPlugin_1.default(),
112
113
  ],
113
114
  });
114
115
  // Plugin Lifecycle - configureWebpack and configurePostCss.
115
116
  plugins.forEach((plugin) => {
116
- var _a;
117
117
  const { configureWebpack, configurePostCss } = plugin;
118
118
  if (configurePostCss) {
119
- config = utils_2.applyConfigurePostCss(configurePostCss, config);
119
+ config = (0, utils_2.applyConfigurePostCss)(configurePostCss, config);
120
120
  }
121
121
  if (configureWebpack) {
122
- config = utils_2.applyConfigureWebpack(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`. // TODO remove this implicit api: inject in callback instead
123
- config, false, (_a = props.siteConfig.webpack) === null || _a === void 0 ? void 0 : _a.jsLoader, plugin.content);
122
+ config = (0, utils_2.applyConfigureWebpack)(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`. // TODO remove this implicit api: inject in callback instead
123
+ config, false, props.siteConfig.webpack?.jsLoader, plugin.content);
124
124
  }
125
125
  });
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);
126
+ const compiler = (0, webpack_1.default)(config);
166
127
  if (process.env.E2E_TEST) {
167
128
  compiler.hooks.done.tap('done', (stats) => {
168
129
  if (stats.hasErrors()) {
169
- console.log('E2E_TEST: Project has compiler errors.');
130
+ logger_1.default.error('E2E_TEST: Project has compiler errors.');
170
131
  process.exit(1);
171
132
  }
172
- console.log('E2E_TEST: Project can compile.');
133
+ logger_1.default.success('E2E_TEST: Project can compile.');
173
134
  process.exit(0);
174
135
  });
175
136
  }
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
- }
137
+ // https://webpack.js.org/configuration/dev-server
138
+ const defaultDevServerConfig = {
139
+ hot: cliOptions.hotOnly ? 'only' : true,
140
+ liveReload: false,
141
+ client: {
142
+ progress: true,
143
+ overlay: {
144
+ warnings: false,
145
+ errors: true,
146
+ },
147
+ },
148
+ headers: {
149
+ 'access-control-allow-origin': '*',
150
+ },
151
+ devMiddleware: {
152
+ publicPath: baseUrl,
153
+ // Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
154
+ stats: 'summary',
155
+ },
156
+ static: siteConfig.staticDirectories.map((dir) => ({
157
+ publicPath: baseUrl,
158
+ directory: path_1.default.resolve(siteDir, dir),
159
+ watch: {
160
+ // Useful options for our own monorepo using symlinks!
161
+ // See https://github.com/webpack/webpack/issues/11612#issuecomment-879259806
162
+ followSymlinks: true,
163
+ ignored: /node_modules\/(?!@docusaurus)/,
164
+ ...{ pollingOptions },
165
+ },
166
+ })),
167
+ ...(httpsConfig && {
168
+ server: typeof httpsConfig === 'object'
169
+ ? {
170
+ type: 'https',
171
+ options: httpsConfig,
172
+ }
173
+ : 'https',
174
+ }),
175
+ historyApiFallback: {
176
+ rewrites: [{ from: /\/*/, to: baseUrl }],
177
+ },
178
+ allowedHosts: 'all',
179
+ host,
180
+ port,
181
+ setupMiddlewares: (middlewares, devServer) => {
182
+ // This lets us fetch source contents from webpack for the error overlay.
183
+ middlewares.unshift((0, evalSourceMapMiddleware_1.default)(devServer));
184
+ return middlewares;
185
+ },
186
+ };
187
+ // Allow plugin authors to customize/override devServer config
188
+ const devServerConfig = (0, webpack_merge_1.default)([defaultDevServerConfig, config.devServer].filter(Boolean));
189
+ const devServer = new webpack_dev_server_1.default(devServerConfig, compiler);
190
+ devServer.startCallback(() => {
181
191
  if (cliOptions.open) {
182
- openBrowser_1.default(openUrl);
192
+ (0, openBrowser_1.default)(openUrl);
183
193
  }
184
194
  });
185
195
  ['SIGINT', 'SIGTERM'].forEach((sig) => {
186
196
  process.on(sig, () => {
187
- devServer.close();
197
+ devServer.stop();
188
198
  process.exit();
189
199
  });
190
200
  });
@@ -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>;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.wrap = exports.eject = exports.getAction = exports.SwizzleActions = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
+ const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
13
+ const path_1 = tslib_1.__importDefault(require("path"));
14
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
15
+ const utils_1 = require("@docusaurus/utils");
16
+ const prompts_1 = require("./prompts");
17
+ exports.SwizzleActions = ['wrap', 'eject'];
18
+ async function getAction(componentConfig, options) {
19
+ if (options.wrap) {
20
+ return 'wrap';
21
+ }
22
+ if (options.eject) {
23
+ return 'eject';
24
+ }
25
+ return (0, prompts_1.askSwizzleAction)(componentConfig);
26
+ }
27
+ exports.getAction = getAction;
28
+ async function isDir(dirPath) {
29
+ return ((await fs_extra_1.default.pathExists(dirPath)) && (await fs_extra_1.default.stat(dirPath)).isDirectory());
30
+ }
31
+ async function eject({ siteDir, themePath, componentName, }) {
32
+ const fromPath = path_1.default.join(themePath, componentName);
33
+ const isDirectory = await isDir(fromPath);
34
+ const globPattern = isDirectory
35
+ ? // do we really want to copy all components?
36
+ path_1.default.join(fromPath, '*')
37
+ : `${fromPath}.*`;
38
+ const globPatternPosix = (0, utils_1.posixPath)(globPattern);
39
+ const filesToCopy = await (0, utils_1.Globby)(globPatternPosix, {
40
+ ignore: ['**/*.{story,stories,test,tests}.{js,jsx,ts,tsx}'],
41
+ });
42
+ if (filesToCopy.length === 0) {
43
+ // This should never happen
44
+ throw new Error(logger_1.default.interpolate `No files to copy from path=${fromPath} with glob code=${globPatternPosix}`);
45
+ }
46
+ const toPath = isDirectory
47
+ ? path_1.default.join(siteDir, utils_1.THEME_PATH, componentName)
48
+ : path_1.default.join(siteDir, utils_1.THEME_PATH);
49
+ await fs_extra_1.default.ensureDir(toPath);
50
+ const createdFiles = await Promise.all(filesToCopy.map(async (sourceFile) => {
51
+ const fileName = path_1.default.basename(sourceFile);
52
+ const targetFile = path_1.default.join(toPath, fileName);
53
+ try {
54
+ await fs_extra_1.default.copy(sourceFile, targetFile, { overwrite: true });
55
+ }
56
+ catch (err) {
57
+ throw new Error(logger_1.default.interpolate `Could not copy file from ${sourceFile} to ${targetFile}`);
58
+ }
59
+ return targetFile;
60
+ }));
61
+ return { createdFiles };
62
+ }
63
+ exports.eject = eject;
64
+ async function wrap({ siteDir, themePath, componentName: themeComponentName, typescript, importType = 'original', }) {
65
+ const isDirectory = await isDir(path_1.default.join(themePath, themeComponentName));
66
+ // Top/Parent/ComponentName => ComponentName
67
+ const componentName = lodash_1.default.last(themeComponentName.split('/'));
68
+ const wrapperComponentName = `${componentName}Wrapper`;
69
+ const wrapperFileName = `${themeComponentName}${isDirectory ? '/index' : ''}${typescript ? '.tsx' : '.js'}`;
70
+ await fs_extra_1.default.ensureDir(path_1.default.resolve(siteDir, utils_1.THEME_PATH));
71
+ const toPath = path_1.default.resolve(siteDir, utils_1.THEME_PATH, wrapperFileName);
72
+ const content = typescript
73
+ ? `import React, {ComponentProps} from 'react';
74
+ import type ${componentName}Type from '@theme/${themeComponentName}';
75
+ import ${componentName} from '@theme-${importType}/${themeComponentName}';
76
+
77
+ type Props = ComponentProps<typeof ${componentName}Type>
78
+
79
+ export default function ${wrapperComponentName}(props: Props): JSX.Element {
80
+ return (
81
+ <>
82
+ <${componentName} {...props} />
83
+ </>
84
+ );
85
+ }
86
+ `
87
+ : `import React from 'react';
88
+ import ${componentName} from '@theme-${importType}/${themeComponentName}';
89
+
90
+ export default function ${wrapperComponentName}(props) {
91
+ return (
92
+ <>
93
+ <${componentName} {...props} />
94
+ </>
95
+ );
96
+ }
97
+ `;
98
+ await fs_extra_1.default.ensureDir(path_1.default.dirname(toPath));
99
+ await fs_extra_1.default.writeFile(toPath, content);
100
+ return { createdFiles: [toPath] };
101
+ }
102
+ exports.wrap = wrap;
@@ -0,0 +1,33 @@
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 { InitializedPlugin, SwizzleAction, SwizzleActionStatus } from '@docusaurus/types';
8
+ import type { NormalizedPluginConfig } from '../../server/plugins/init';
9
+ export declare const SwizzleActions: SwizzleAction[];
10
+ export declare const SwizzleActionsStatuses: SwizzleActionStatus[];
11
+ export declare const PartiallySafeHint: string;
12
+ export declare function actionStatusLabel(status: SwizzleActionStatus): string;
13
+ export declare function actionStatusColor(status: SwizzleActionStatus, str: string): string;
14
+ export declare function actionStatusSuffix(status: SwizzleActionStatus, options?: {
15
+ partiallySafe?: boolean;
16
+ }): string;
17
+ export declare type SwizzlePlugin = {
18
+ instance: InitializedPlugin;
19
+ plugin: NormalizedPluginConfig;
20
+ };
21
+ export declare type SwizzleContext = {
22
+ plugins: SwizzlePlugin[];
23
+ };
24
+ export declare type SwizzleOptions = {
25
+ typescript: boolean;
26
+ danger: boolean;
27
+ list: boolean;
28
+ wrap: boolean;
29
+ eject: boolean;
30
+ };
31
+ export declare function normalizeOptions(options: Partial<SwizzleOptions>): SwizzleOptions;
32
+ export declare function findStringIgnoringCase(str: string, values: string[]): string | undefined;
33
+ export declare function findClosestValue(str: string, values: string[], maxLevenshtein?: number): string | undefined;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.findClosestValue = exports.findStringIgnoringCase = exports.normalizeOptions = exports.actionStatusSuffix = exports.actionStatusColor = exports.actionStatusLabel = exports.PartiallySafeHint = exports.SwizzleActionsStatuses = exports.SwizzleActions = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const leven_1 = tslib_1.__importDefault(require("leven"));
12
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
13
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
14
+ exports.SwizzleActions = ['wrap', 'eject'];
15
+ exports.SwizzleActionsStatuses = [
16
+ 'safe',
17
+ 'unsafe',
18
+ 'forbidden',
19
+ ];
20
+ exports.PartiallySafeHint = logger_1.default.red('*');
21
+ function actionStatusLabel(status) {
22
+ return lodash_1.default.capitalize(status);
23
+ }
24
+ exports.actionStatusLabel = actionStatusLabel;
25
+ const SwizzleActionStatusColors = {
26
+ safe: logger_1.default.green,
27
+ unsafe: logger_1.default.yellow,
28
+ forbidden: logger_1.default.red,
29
+ };
30
+ function actionStatusColor(status, str) {
31
+ const colorFn = SwizzleActionStatusColors[status];
32
+ return colorFn(str);
33
+ }
34
+ exports.actionStatusColor = actionStatusColor;
35
+ function actionStatusSuffix(status, options = {}) {
36
+ return ` (${actionStatusColor(status, actionStatusLabel(status))}${options.partiallySafe ? exports.PartiallySafeHint : ''})`;
37
+ }
38
+ exports.actionStatusSuffix = actionStatusSuffix;
39
+ function normalizeOptions(options) {
40
+ return {
41
+ typescript: options.typescript ?? false,
42
+ danger: options.danger ?? false,
43
+ list: options.list ?? false,
44
+ wrap: options.wrap ?? false,
45
+ eject: options.eject ?? false,
46
+ };
47
+ }
48
+ exports.normalizeOptions = normalizeOptions;
49
+ function findStringIgnoringCase(str, values) {
50
+ return values.find((v) => v.toLowerCase() === str.toLowerCase());
51
+ }
52
+ exports.findStringIgnoringCase = findStringIgnoringCase;
53
+ function findClosestValue(str, values, maxLevenshtein = 3) {
54
+ return values.find((v) => (0, leven_1.default)(v, str) <= maxLevenshtein);
55
+ }
56
+ exports.findClosestValue = findClosestValue;
@@ -0,0 +1,29 @@
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, SwizzleActionStatus, SwizzleComponentConfig, SwizzleConfig } from '@docusaurus/types';
8
+ export declare type ThemeComponents = {
9
+ themeName: string;
10
+ all: string[];
11
+ getConfig: (component: string) => SwizzleComponentConfig;
12
+ getDescription: (component: string) => string;
13
+ getActionStatus: (component: string, action: SwizzleAction) => SwizzleActionStatus;
14
+ isSafeAction: (component: string, action: SwizzleAction) => boolean;
15
+ hasAnySafeAction: (component: string) => boolean;
16
+ hasAllSafeAction: (component: string) => boolean;
17
+ };
18
+ export declare function readComponentNames(themePath: string): Promise<string[]>;
19
+ export declare function listComponentNames(themeComponents: ThemeComponents): string;
20
+ export declare function getThemeComponents({ themeName, themePath, swizzleConfig, }: {
21
+ themeName: string;
22
+ themePath: string;
23
+ swizzleConfig: SwizzleConfig;
24
+ }): Promise<ThemeComponents>;
25
+ export declare function getComponentName({ componentNameParam, themeComponents, list, }: {
26
+ componentNameParam: string | undefined;
27
+ themeComponents: ThemeComponents;
28
+ list: boolean | undefined;
29
+ }): Promise<string>;