@docusaurus/core 2.0.0-beta.12faed89d → 2.0.0-beta.14

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 (111) hide show
  1. package/bin/beforeCli.js +46 -22
  2. package/bin/docusaurus.js +42 -44
  3. package/lib/babel/preset.d.ts +6 -0
  4. package/lib/babel/preset.js +3 -3
  5. package/lib/choosePort.js +19 -20
  6. package/lib/client/.eslintrc.js +0 -1
  7. package/lib/client/App.js +12 -22
  8. package/lib/client/LinksCollector.d.ts +2 -2
  9. package/lib/client/LinksCollector.js +4 -8
  10. package/lib/client/PendingNavigation.d.ts +24 -1
  11. package/lib/client/PendingNavigation.js +1 -1
  12. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.d.ts +5 -0
  13. package/lib/client/client-lifecycles-dispatcher.d.ts +2 -2
  14. package/lib/client/client-lifecycles-dispatcher.js +0 -2
  15. package/lib/client/docusaurus.d.ts +6 -0
  16. package/lib/client/docusaurus.js +11 -19
  17. package/lib/client/exports/BrowserOnly.js +5 -3
  18. package/lib/client/exports/ErrorBoundary.d.ts +18 -0
  19. package/lib/client/exports/ErrorBoundary.js +35 -0
  20. package/lib/client/exports/Interpolate.js +12 -15
  21. package/lib/client/exports/Link.js +9 -9
  22. package/lib/client/exports/Translate.d.ts +2 -2
  23. package/lib/client/exports/Translate.js +13 -9
  24. package/lib/client/exports/browserContext.d.ts +11 -0
  25. package/lib/client/exports/browserContext.js +21 -0
  26. package/lib/client/exports/constants.js +1 -11
  27. package/lib/client/exports/{context.d.ts → docusaurusContext.d.ts} +5 -3
  28. package/lib/client/exports/docusaurusContext.js +25 -0
  29. package/lib/client/exports/useBaseUrl.js +2 -4
  30. package/lib/client/exports/useDocusaurusContext.js +2 -7
  31. package/lib/client/exports/useGlobalData.js +1 -5
  32. package/lib/client/exports/{context.js → useIsBrowser.d.ts} +1 -2
  33. package/lib/{webpack/sharedModuleAliases.d.ts → client/exports/useIsBrowser.js} +5 -4
  34. package/lib/client/flat.d.ts +2 -1
  35. package/lib/client/flat.js +7 -9
  36. package/lib/client/normalizeLocation.d.ts +1 -3
  37. package/lib/client/prefetch.js +0 -1
  38. package/lib/client/serverEntry.js +20 -42
  39. package/lib/client/theme-fallback/Error/index.js +47 -0
  40. package/lib/client/theme-fallback/Layout/index.js +1 -1
  41. package/lib/client/theme-fallback/Loading/index.js +2 -2
  42. package/lib/client/theme-fallback/Root/index.js +1 -3
  43. package/lib/commands/build.js +39 -44
  44. package/lib/commands/clear.d.ts +6 -0
  45. package/lib/commands/clear.js +17 -18
  46. package/lib/commands/commandUtils.d.ts +6 -0
  47. package/lib/commands/commandUtils.js +7 -7
  48. package/lib/commands/deploy.d.ts +3 -0
  49. package/lib/commands/deploy.js +99 -64
  50. package/lib/commands/external.js +4 -4
  51. package/lib/commands/serve.js +12 -18
  52. package/lib/commands/start.js +98 -86
  53. package/lib/commands/swizzle.js +42 -51
  54. package/lib/commands/writeHeadingIds.d.ts +9 -6
  55. package/lib/commands/writeHeadingIds.js +33 -34
  56. package/lib/commands/writeTranslations.js +31 -11
  57. package/lib/server/brokenLinks.js +13 -17
  58. package/lib/server/client-modules/index.js +1 -3
  59. package/lib/server/config.js +4 -4
  60. package/lib/server/configValidation.d.ts +1 -1
  61. package/lib/server/configValidation.js +14 -7
  62. package/lib/server/duplicateRoutes.js +8 -2
  63. package/lib/server/html-tags/htmlTags.js +5 -6
  64. package/lib/server/html-tags/index.js +2 -2
  65. package/lib/server/i18n.js +16 -16
  66. package/lib/server/index.js +132 -59
  67. package/lib/server/loadSetup.js +3 -3
  68. package/lib/server/moduleShorthand.d.ts +9 -0
  69. package/lib/server/moduleShorthand.js +42 -0
  70. package/lib/server/plugins/applyRouteTrailingSlash.js +1 -1
  71. package/lib/server/plugins/index.d.ts +1 -1
  72. package/lib/server/plugins/index.js +25 -21
  73. package/lib/server/plugins/init.js +9 -12
  74. package/lib/server/plugins/pluginIds.js +6 -4
  75. package/lib/server/presets/index.js +12 -12
  76. package/lib/server/routes.js +9 -11
  77. package/lib/server/themes/alias.d.ts +1 -0
  78. package/lib/server/themes/alias.js +21 -12
  79. package/lib/server/themes/index.d.ts +1 -1
  80. package/lib/server/themes/index.js +22 -23
  81. package/lib/server/translations/translations.d.ts +6 -0
  82. package/lib/server/translations/translations.js +19 -26
  83. package/lib/server/translations/translationsExtractor.d.ts +7 -1
  84. package/lib/server/translations/translationsExtractor.js +66 -59
  85. package/lib/server/utils.d.ts +8 -2
  86. package/lib/server/utils.js +8 -10
  87. package/lib/server/versions/__fixtures__/dummy-plugin.d.ts +0 -0
  88. package/lib/server/versions/__tests/index.test.js +5 -5
  89. package/lib/server/versions/index.js +6 -6
  90. package/lib/webpack/base.js +14 -16
  91. package/lib/webpack/client.js +9 -18
  92. package/lib/webpack/plugins/CleanWebpackPlugin.js +4 -11
  93. package/lib/webpack/plugins/LogPlugin.js +5 -6
  94. package/lib/webpack/plugins/WaitPlugin.js +4 -4
  95. package/lib/webpack/server.js +9 -9
  96. package/lib/webpack/utils.d.ts +0 -22
  97. package/lib/webpack/utils.js +37 -134
  98. package/package.json +55 -50
  99. package/lib/.tsbuildinfo +0 -1
  100. package/lib/client/.tsbuildinfo +0 -1
  101. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  102. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  103. package/lib/constants.d.ts +0 -18
  104. package/lib/constants.js +0 -23
  105. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  106. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  107. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  108. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  109. package/lib/webpack/sharedModuleAliases.js +0 -18
  110. package/tsconfig.client.json +0 -13
  111. package/tsconfig.json +0 -13
@@ -8,33 +8,28 @@
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");
12
- const chokidar_1 = tslib_1.__importDefault(require("chokidar"));
13
- const express_1 = tslib_1.__importDefault(require("express"));
14
- const html_webpack_plugin_1 = tslib_1.__importDefault(require("html-webpack-plugin"));
15
- const path_1 = tslib_1.__importDefault(require("path"));
11
+ const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
12
+ const chokidar_1 = (0, tslib_1.__importDefault)(require("chokidar"));
13
+ const html_webpack_plugin_1 = (0, tslib_1.__importDefault)(require("html-webpack-plugin"));
14
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
16
15
  const lodash_1 = require("lodash");
17
- const openBrowser_1 = tslib_1.__importDefault(require("react-dev-utils/openBrowser"));
16
+ const openBrowser_1 = (0, 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"));
22
- const webpack_1 = tslib_1.__importDefault(require("webpack"));
23
- const webpack_dev_server_1 = tslib_1.__importDefault(require("webpack-dev-server"));
24
- const webpack_merge_1 = tslib_1.__importDefault(require("webpack-merge"));
25
- const HotModuleReplacementPlugin_1 = tslib_1.__importDefault(require("webpack/lib/HotModuleReplacementPlugin"));
18
+ const evalSourceMapMiddleware_1 = (0, tslib_1.__importDefault)(require("react-dev-utils/evalSourceMapMiddleware"));
19
+ const webpack_1 = (0, tslib_1.__importDefault)(require("webpack"));
20
+ const webpack_dev_server_1 = (0, tslib_1.__importDefault)(require("webpack-dev-server"));
21
+ const webpack_merge_1 = (0, tslib_1.__importDefault)(require("webpack-merge"));
26
22
  const server_1 = require("../server");
27
- const constants_1 = require("../constants");
28
- const client_1 = tslib_1.__importDefault(require("../webpack/client"));
23
+ const client_1 = (0, tslib_1.__importDefault)(require("../webpack/client"));
29
24
  const utils_2 = require("../webpack/utils");
30
25
  const commandUtils_1 = require("./commandUtils");
31
26
  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,34 +38,34 @@ 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 = (0, lodash_1.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
@@ -80,21 +75,29 @@ async function start(siteDir, cliOptions) {
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 = (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)((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({
@@ -107,8 +110,6 @@ 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.
@@ -116,75 +117,86 @@ async function start(siteDir, cliOptions) {
116
117
  var _a;
117
118
  const { configureWebpack, configurePostCss } = plugin;
118
119
  if (configurePostCss) {
119
- config = utils_2.applyConfigurePostCss(configurePostCss, config);
120
+ config = (0, utils_2.applyConfigurePostCss)(configurePostCss, config);
120
121
  }
121
122
  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 = (0, utils_2.applyConfigureWebpack)(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`. // TODO remove this implicit api: inject in callback instead
123
124
  config, false, (_a = props.siteConfig.webpack) === null || _a === void 0 ? void 0 : _a.jsLoader, plugin.content);
124
125
  }
125
126
  });
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);
127
+ const compiler = (0, webpack_1.default)(config);
166
128
  if (process.env.E2E_TEST) {
167
129
  compiler.hooks.done.tap('done', (stats) => {
168
130
  if (stats.hasErrors()) {
169
- console.log('E2E_TEST: Project has compiler errors.');
131
+ logger_1.default.error('E2E_TEST: Project has compiler errors.');
170
132
  process.exit(1);
171
133
  }
172
- console.log('E2E_TEST: Project can compile.');
134
+ logger_1.default.success('E2E_TEST: Project can compile.');
173
135
  process.exit(0);
174
136
  });
175
137
  }
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
- }
138
+ // https://webpack.js.org/configuration/dev-server
139
+ const defaultDevServerConfig = {
140
+ hot: cliOptions.hotOnly ? 'only' : true,
141
+ liveReload: false,
142
+ client: {
143
+ progress: true,
144
+ overlay: {
145
+ warnings: false,
146
+ errors: true,
147
+ },
148
+ },
149
+ headers: {
150
+ 'access-control-allow-origin': '*',
151
+ },
152
+ devMiddleware: {
153
+ publicPath: baseUrl,
154
+ // Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
155
+ stats: 'summary',
156
+ },
157
+ static: siteConfig.staticDirectories.map((dir) => ({
158
+ publicPath: baseUrl,
159
+ directory: path_1.default.resolve(siteDir, dir),
160
+ watch: {
161
+ // Useful options for our own monorepo using symlinks!
162
+ // See https://github.com/webpack/webpack/issues/11612#issuecomment-879259806
163
+ followSymlinks: true,
164
+ ignored: /node_modules\/(?!@docusaurus)/,
165
+ ...{ pollingOptions },
166
+ },
167
+ })),
168
+ ...(httpsConfig && {
169
+ server: typeof httpsConfig === 'object'
170
+ ? {
171
+ type: 'https',
172
+ options: httpsConfig,
173
+ }
174
+ : 'https',
175
+ }),
176
+ historyApiFallback: {
177
+ rewrites: [{ from: /\/*/, to: baseUrl }],
178
+ },
179
+ allowedHosts: 'all',
180
+ host,
181
+ port,
182
+ onBeforeSetupMiddleware: (devServer) => {
183
+ // This lets us fetch source contents from webpack for the error overlay.
184
+ devServer.app.use((0, evalSourceMapMiddleware_1.default)(
185
+ // @ts-expect-error: bad types
186
+ devServer));
187
+ },
188
+ };
189
+ // Allow plugin authors to customize/override devServer config
190
+ const devServerConfig = (0, webpack_merge_1.default)([defaultDevServerConfig, config.devServer].filter(Boolean));
191
+ const devServer = new webpack_dev_server_1.default(devServerConfig, compiler);
192
+ devServer.startCallback(() => {
181
193
  if (cliOptions.open) {
182
- openBrowser_1.default(openUrl);
194
+ (0, openBrowser_1.default)(openUrl);
183
195
  }
184
196
  });
185
197
  ['SIGINT', 'SIGTERM'].forEach((sig) => {
186
198
  process.on(sig, () => {
187
- devServer.close();
199
+ devServer.stop();
188
200
  process.exit();
189
201
  });
190
202
  });
@@ -8,15 +8,15 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.getPluginNames = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const chalk = require("chalk");
12
- const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
13
- const import_fresh_1 = tslib_1.__importDefault(require("import-fresh"));
14
- const path_1 = tslib_1.__importDefault(require("path"));
15
- const leven_1 = tslib_1.__importDefault(require("leven"));
11
+ const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
12
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
13
+ const import_fresh_1 = (0, tslib_1.__importDefault)(require("import-fresh"));
14
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
15
+ const leven_1 = (0, tslib_1.__importDefault)(require("leven"));
16
16
  const lodash_1 = require("lodash");
17
- const constants_1 = require("../constants");
17
+ const utils_1 = require("@docusaurus/utils");
18
18
  const server_1 = require("../server");
19
- const init_1 = tslib_1.__importDefault(require("../server/plugins/init"));
19
+ const init_1 = (0, tslib_1.__importDefault)(require("../server/plugins/init"));
20
20
  const utils_validation_1 = require("@docusaurus/utils-validation");
21
21
  function getPluginNames(plugins) {
22
22
  return plugins
@@ -37,7 +37,7 @@ function getPluginNames(plugins) {
37
37
  if (packagePath === '.') {
38
38
  return pluginPath;
39
39
  }
40
- return import_fresh_1.default(path_1.default.join(packagePath, 'package.json')).name;
40
+ return (0, import_fresh_1.default)(path_1.default.join(packagePath, 'package.json')).name;
41
41
  }
42
42
  return '';
43
43
  })
@@ -45,8 +45,8 @@ function getPluginNames(plugins) {
45
45
  }
46
46
  exports.getPluginNames = getPluginNames;
47
47
  const formatComponentName = (componentName) => componentName
48
- .replace(/(\/|\\)index.(js|tsx|ts|jsx)/, '')
49
- .replace(/.(js|tsx|ts|jsx)/, '');
48
+ .replace(/(\/|\\)index\.(js|tsx|ts|jsx)/, '')
49
+ .replace(/\.(js|tsx|ts|jsx)/, '');
50
50
  function readComponent(themePath) {
51
51
  function walk(dir) {
52
52
  let results = [];
@@ -82,20 +82,16 @@ function getComponentName(themePath, plugin, danger) {
82
82
  function themeComponents(themePath, plugin) {
83
83
  const components = colorCode(themePath, plugin);
84
84
  if (components.length === 0) {
85
- return `${chalk.red('No component to swizzle.')}`;
85
+ return 'No component to swizzle.';
86
86
  }
87
- return `
88
- ${chalk.cyan('Theme components available for swizzle.')}
87
+ return `Theme components available for swizzle.
89
88
 
90
- ${chalk.green('green =>')} safe: lower breaking change risk
91
- ${chalk.red('red =>')} unsafe: higher breaking change risk
89
+ ${logger_1.default.green(logger_1.default.bold('green =>'))} safe: lower breaking change risk
90
+ ${logger_1.default.red(logger_1.default.bold('red =>'))} unsafe: higher breaking change risk
92
91
 
93
92
  ${components.join('\n')}
94
93
  `;
95
94
  }
96
- function formattedThemeNames(themeNames) {
97
- return `Themes available for swizzle:\n- ${themeNames.join('\n- ')}`;
98
- }
99
95
  function colorCode(themePath, plugin) {
100
96
  var _a, _b;
101
97
  // support both commonjs and ES style exports
@@ -104,18 +100,18 @@ function colorCode(themePath, plugin) {
104
100
  const allowedComponent = getSwizzleComponentList
105
101
  ? getSwizzleComponentList()
106
102
  : [];
107
- const [greenComponents, redComponents] = lodash_1.partition(components, (comp) => allowedComponent.includes(comp));
103
+ const [greenComponents, redComponents] = (0, lodash_1.partition)(components, (comp) => allowedComponent.includes(comp));
108
104
  return [
109
- ...greenComponents.map((component) => chalk.green(`safe: ${component}`)),
110
- ...redComponents.map((component) => chalk.red(`unsafe: ${component}`)),
105
+ ...greenComponents.map((component) => `${logger_1.default.green(logger_1.default.bold('safe:'))} ${component}`),
106
+ ...redComponents.map((component) => `${logger_1.default.red(logger_1.default.bold('unsafe:'))} ${component}`),
111
107
  ];
112
108
  }
113
109
  async function swizzle(siteDir, themeName, componentName, typescript, danger) {
114
110
  var _a, _b, _c, _d, _e;
115
- const context = await server_1.loadContext(siteDir);
116
- const pluginConfigs = server_1.loadPluginConfigs(context);
111
+ const context = await (0, server_1.loadContext)(siteDir);
112
+ const pluginConfigs = (0, server_1.loadPluginConfigs)(context);
117
113
  const pluginNames = getPluginNames(pluginConfigs);
118
- const plugins = init_1.default({
114
+ const plugins = (0, init_1.default)({
119
115
  pluginConfigs,
120
116
  context,
121
117
  });
@@ -123,23 +119,23 @@ async function swizzle(siteDir, themeName, componentName, typescript, danger) {
123
119
  ? plugins[index].getTypeScriptThemePath
124
120
  : plugins[index].getThemePath);
125
121
  if (!themeName) {
126
- console.log(formattedThemeNames(themeNames));
127
- process.exit(1);
122
+ logger_1.default.info `Themes available for swizzle: name=${themeNames}`;
123
+ return;
128
124
  }
129
125
  let pluginModule;
130
126
  try {
131
- pluginModule = import_fresh_1.default(themeName);
127
+ pluginModule = (0, import_fresh_1.default)(themeName);
132
128
  }
133
129
  catch {
134
130
  let suggestion;
135
131
  themeNames.forEach((name) => {
136
- if (leven_1.default(name, themeName) < 4) {
132
+ if ((0, leven_1.default)(name, themeName) < 4) {
137
133
  suggestion = name;
138
134
  }
139
135
  });
140
- chalk.red(`Theme ${themeName} not found. ${suggestion
141
- ? `Did you mean "${suggestion}" ?`
142
- : formattedThemeNames(themeNames)}`);
136
+ logger_1.default.error `Theme name=${themeName} not found. ${suggestion
137
+ ? logger_1.default.interpolate `Did you mean name=${suggestion}?`
138
+ : logger_1.default.interpolate `Themes available for swizzle: ${themeNames}`}`;
143
139
  process.exit(1);
144
140
  }
145
141
  let pluginOptions = {};
@@ -171,14 +167,14 @@ async function swizzle(siteDir, themeName, componentName, typescript, danger) {
171
167
  ? (_d = pluginInstance.getTypeScriptThemePath) === null || _d === void 0 ? void 0 : _d.call(pluginInstance)
172
168
  : (_e = pluginInstance.getThemePath) === null || _e === void 0 ? void 0 : _e.call(pluginInstance);
173
169
  if (!themePath) {
174
- console.warn(chalk.yellow(typescript
175
- ? `${themeName} does not provide TypeScript theme code via "getTypeScriptThemePath()".`
176
- : `${themeName} does not provide any theme code.`));
170
+ logger_1.default.warn(typescript
171
+ ? logger_1.default.interpolate `name=${themeName} does not provide TypeScript theme code via ${'getTypeScriptThemePath()'}.`
172
+ : logger_1.default.interpolate `name=${themeName} does not provide any theme code.`);
177
173
  process.exit(1);
178
174
  }
179
175
  if (!componentName) {
180
- console.warn(themeComponents(themePath, pluginModule));
181
- process.exit(1);
176
+ logger_1.default.info(themeComponents(themePath, pluginModule));
177
+ return;
182
178
  }
183
179
  const components = getComponentName(themePath, pluginModule, Boolean(danger));
184
180
  const formattedComponentName = formatComponentName(componentName);
@@ -190,7 +186,7 @@ async function swizzle(siteDir, themeName, componentName, typescript, danger) {
190
186
  components.forEach((component) => {
191
187
  if (component.toLowerCase() === formattedComponentName.toLowerCase()) {
192
188
  // may be components with same lowercase key, try to match closest component
193
- const currentScore = leven_1.default(formattedComponentName, component);
189
+ const currentScore = (0, leven_1.default)(formattedComponentName, component);
194
190
  if (currentScore < score) {
195
191
  score = currentScore;
196
192
  mostSuitableMatch = component;
@@ -199,11 +195,12 @@ async function swizzle(siteDir, themeName, componentName, typescript, danger) {
199
195
  });
200
196
  if (mostSuitableMatch !== componentName) {
201
197
  mostSuitableComponent = mostSuitableMatch;
202
- console.log(chalk.red(`Component "${componentName}" doesn't exist.`), chalk.yellow(`"${mostSuitableComponent}" is swizzled instead of "${componentName}".`));
198
+ logger_1.default.error `Component name=${componentName} doesn't exist.`;
199
+ logger_1.default.info `name=${mostSuitableComponent} is swizzled instead of name=${componentName}.`;
203
200
  }
204
201
  }
205
202
  let fromPath = path_1.default.join(themePath, mostSuitableComponent);
206
- let toPath = path_1.default.resolve(siteDir, constants_1.THEME_PATH, mostSuitableComponent);
203
+ let toPath = path_1.default.resolve(siteDir, utils_1.THEME_PATH, mostSuitableComponent);
207
204
  // Handle single TypeScript/JavaScript file only.
208
205
  // E.g: if <fromPath> does not exist, we try to swizzle <fromPath>.(ts|tsx|js) instead
209
206
  if (!fs_extra_1.default.existsSync(fromPath)) {
@@ -219,27 +216,21 @@ async function swizzle(siteDir, themeName, componentName, typescript, danger) {
219
216
  else {
220
217
  let suggestion;
221
218
  components.forEach((name) => {
222
- if (leven_1.default(name, mostSuitableComponent) < 3) {
219
+ if ((0, leven_1.default)(name, mostSuitableComponent) < 3) {
223
220
  suggestion = name;
224
221
  }
225
222
  });
226
- console.warn(chalk.red(`Component ${mostSuitableComponent} not found.`));
227
- console.warn(suggestion
228
- ? `Did you mean "${suggestion}"?`
229
- : `${themeComponents(themePath, pluginModule)}`);
223
+ logger_1.default.error `Component name=${mostSuitableComponent} not found. ${suggestion
224
+ ? logger_1.default.interpolate `Did you mean name=${suggestion} ?`
225
+ : themeComponents(themePath, pluginModule)}`;
230
226
  process.exit(1);
231
227
  }
232
228
  }
233
229
  if (!components.includes(mostSuitableComponent) && !danger) {
234
- console.warn(chalk.red(`${mostSuitableComponent} is an internal component and has a higher breaking change probability. If you want to swizzle it, use the "--danger" flag.`));
230
+ logger_1.default.error `name=${mostSuitableComponent} is an internal component and has a higher breaking change probability. If you want to swizzle it, use the code=${'--danger'} flag.`;
235
231
  process.exit(1);
236
232
  }
237
233
  await fs_extra_1.default.copy(fromPath, toPath);
238
- const relativeDir = path_1.default.relative(process.cwd(), toPath);
239
- const fromMsg = chalk.blue(mostSuitableComponent
240
- ? `${themeName} ${chalk.yellow(mostSuitableComponent)}`
241
- : themeName);
242
- const toMsg = chalk.cyan(relativeDir);
243
- console.log(`\n${chalk.green('Success!')} Copied ${fromMsg} to ${toMsg}.\n`);
234
+ logger_1.default.success `Copied code=${mostSuitableComponent ? `${themeName} ${mostSuitableComponent}` : themeName} to path=${path_1.default.relative(process.cwd(), toPath)}.`;
244
235
  }
245
236
  exports.default = swizzle;
@@ -4,9 +4,12 @@
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 GithubSlugger from 'github-slugger';
8
- export declare function unwrapMarkdownLinks(line: string): string;
9
- export declare function transformMarkdownHeadingLine(line: string, slugger: GithubSlugger): string;
10
- export declare function transformMarkdownLine(line: string, slugger: GithubSlugger): string;
11
- export declare function transformMarkdownContent(content: string): string;
12
- export default function writeHeadingIds(siteDir: string): Promise<void>;
7
+ import { Slugger } from '@docusaurus/utils';
8
+ declare type Options = {
9
+ maintainCase?: boolean;
10
+ overwrite?: boolean;
11
+ };
12
+ export declare function transformMarkdownHeadingLine(line: string, slugger: Slugger, options?: Options): string;
13
+ export declare function transformMarkdownContent(content: string, options?: Options): string;
14
+ export default function writeHeadingIds(siteDir: string, files?: string, options?: Options): Promise<void>;
15
+ export {};
@@ -6,55 +6,55 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.transformMarkdownContent = exports.transformMarkdownLine = exports.transformMarkdownHeadingLine = exports.unwrapMarkdownLinks = void 0;
9
+ exports.transformMarkdownContent = exports.transformMarkdownHeadingLine = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
- const github_slugger_1 = tslib_1.__importDefault(require("github-slugger"));
13
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
11
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
12
+ const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
14
13
  const server_1 = require("../server");
15
- const init_1 = tslib_1.__importDefault(require("../server/plugins/init"));
16
- const lodash_1 = require("lodash");
14
+ const init_1 = (0, tslib_1.__importDefault)(require("../server/plugins/init"));
17
15
  const utils_1 = require("@docusaurus/utils");
18
16
  const utils_2 = require("../server/utils");
19
17
  function unwrapMarkdownLinks(line) {
20
18
  return line.replace(/\[([^\]]+)\]\([^)]+\)/g, (match, p1) => p1);
21
19
  }
22
- exports.unwrapMarkdownLinks = unwrapMarkdownLinks;
23
- function addHeadingId(line, slugger) {
20
+ function addHeadingId(line, slugger, maintainCase) {
24
21
  let headingLevel = 0;
25
22
  while (line.charAt(headingLevel) === '#') {
26
23
  headingLevel += 1;
27
24
  }
28
25
  const headingText = line.slice(headingLevel).trimEnd();
29
26
  const headingHashes = line.slice(0, headingLevel);
30
- const slug = slugger.slug(unwrapMarkdownLinks(headingText));
27
+ const slug = slugger
28
+ .slug(unwrapMarkdownLinks(headingText).trim(), { maintainCase })
29
+ .replace(/^-+/, '')
30
+ .replace(/-+$/, '');
31
31
  return `${headingHashes}${headingText} {#${slug}}`;
32
32
  }
33
- function transformMarkdownHeadingLine(line, slugger) {
33
+ function transformMarkdownHeadingLine(line, slugger, options = { maintainCase: false, overwrite: false }) {
34
+ const { maintainCase = false, overwrite = false } = options;
34
35
  if (!line.startsWith('#')) {
35
36
  throw new Error(`Line is not a Markdown heading: ${line}.`);
36
37
  }
37
- const parsedHeading = utils_1.parseMarkdownHeadingId(line);
38
- // Do not process if id is already therer
39
- if (parsedHeading.id) {
38
+ const parsedHeading = (0, utils_1.parseMarkdownHeadingId)(line);
39
+ // Do not process if id is already there
40
+ if (parsedHeading.id && !overwrite) {
40
41
  return line;
41
42
  }
42
- return addHeadingId(line, slugger);
43
+ return addHeadingId(parsedHeading.text, slugger, maintainCase);
43
44
  }
44
45
  exports.transformMarkdownHeadingLine = transformMarkdownHeadingLine;
45
- function transformMarkdownLine(line, slugger) {
46
+ function transformMarkdownLine(line, slugger, options) {
46
47
  // Ignore h1 headings on purpose, as we don't create anchor links for those
47
48
  if (line.startsWith('##')) {
48
- return transformMarkdownHeadingLine(line, slugger);
49
+ return transformMarkdownHeadingLine(line, slugger, options);
49
50
  }
50
51
  else {
51
52
  return line;
52
53
  }
53
54
  }
54
- exports.transformMarkdownLine = transformMarkdownLine;
55
- function transformMarkdownLines(lines) {
55
+ function transformMarkdownLines(lines, options) {
56
56
  let inCode = false;
57
- const slugger = new github_slugger_1.default();
57
+ const slugger = (0, utils_1.createSlugger)();
58
58
  return lines.map((line) => {
59
59
  if (line.startsWith('```')) {
60
60
  inCode = !inCode;
@@ -64,17 +64,17 @@ function transformMarkdownLines(lines) {
64
64
  if (inCode) {
65
65
  return line;
66
66
  }
67
- return transformMarkdownLine(line, slugger);
67
+ return transformMarkdownLine(line, slugger, options);
68
68
  }
69
69
  });
70
70
  }
71
- function transformMarkdownContent(content) {
72
- return transformMarkdownLines(content.split('\n')).join('\n');
71
+ function transformMarkdownContent(content, options) {
72
+ return transformMarkdownLines(content.split('\n'), options).join('\n');
73
73
  }
74
74
  exports.transformMarkdownContent = transformMarkdownContent;
75
- async function transformMarkdownFile(filepath) {
75
+ async function transformMarkdownFile(filepath, options) {
76
76
  const content = await fs_extra_1.default.readFile(filepath, 'utf8');
77
- const updatedContent = transformMarkdownLines(content.split('\n')).join('\n');
77
+ const updatedContent = transformMarkdownLines(content.split('\n'), options).join('\n');
78
78
  if (content !== updatedContent) {
79
79
  await fs_extra_1.default.writeFile(filepath, updatedContent);
80
80
  return filepath;
@@ -85,26 +85,25 @@ async function transformMarkdownFile(filepath) {
85
85
  // Also we don't want to transform the site md docs that do not belong to a content plugin
86
86
  // For example ./README.md should not be transformed
87
87
  async function getPathsToWatch(siteDir) {
88
- const context = await server_1.loadContext(siteDir);
89
- const pluginConfigs = server_1.loadPluginConfigs(context);
90
- const plugins = await init_1.default({
88
+ const context = await (0, server_1.loadContext)(siteDir);
89
+ const pluginConfigs = (0, server_1.loadPluginConfigs)(context);
90
+ const plugins = (0, init_1.default)({
91
91
  pluginConfigs,
92
92
  context,
93
93
  });
94
- return lodash_1.flatten(plugins.map((plugin) => { var _a, _b; return (_b = (_a = plugin === null || plugin === void 0 ? void 0 : plugin.getPathsToWatch) === null || _a === void 0 ? void 0 : _a.call(plugin)) !== null && _b !== void 0 ? _b : []; }));
94
+ return plugins.flatMap((plugin) => { var _a, _b; return (_b = (_a = plugin === null || plugin === void 0 ? void 0 : plugin.getPathsToWatch) === null || _a === void 0 ? void 0 : _a.call(plugin)) !== null && _b !== void 0 ? _b : []; });
95
95
  }
96
- async function writeHeadingIds(siteDir) {
97
- const markdownFiles = await utils_2.safeGlobby(await getPathsToWatch(siteDir), {
96
+ async function writeHeadingIds(siteDir, files, options) {
97
+ const markdownFiles = await (0, utils_2.safeGlobby)(files ? [files] : await getPathsToWatch(siteDir), {
98
98
  expandDirectories: ['**/*.{md,mdx}'],
99
99
  });
100
- const result = await Promise.all(markdownFiles.map(transformMarkdownFile));
100
+ const result = await Promise.all(markdownFiles.map((p) => transformMarkdownFile(p, options)));
101
101
  const pathsModified = result.filter(Boolean);
102
102
  if (pathsModified.length) {
103
- console.log(chalk_1.default.green(`Heading ids added to Markdown files (${pathsModified.length}/${markdownFiles.length} files):
104
- - ${pathsModified.join('\n- ')}`));
103
+ logger_1.default.success `Heading ids added to Markdown files (number=${`${pathsModified.length}/${markdownFiles.length}`} files): ${pathsModified}`;
105
104
  }
106
105
  else {
107
- console.log(chalk_1.default.yellow(`${markdownFiles.length} Markdown files already have explicit heading ids.`));
106
+ logger_1.default.warn `number=${markdownFiles.length} Markdown files already have explicit heading IDs. If you intend to overwrite the existing heading IDs, use the code=${'--overwrite'} option.`;
108
107
  }
109
108
  }
110
109
  exports.default = writeHeadingIds;