@docusaurus/core 2.0.0-beta.15 → 2.0.0-beta.16

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 (131) hide show
  1. package/bin/beforeCli.mjs +136 -0
  2. package/bin/{docusaurus.js → docusaurus.mjs} +62 -40
  3. package/lib/babel/preset.d.ts +1 -2
  4. package/lib/babel/preset.js +5 -4
  5. package/lib/choosePort.js +22 -30
  6. package/lib/client/App.d.ts +1 -2
  7. package/lib/client/App.js +13 -8
  8. package/lib/client/LinksCollector.js +1 -1
  9. package/lib/client/PendingNavigation.d.ts +4 -4
  10. package/lib/client/PendingNavigation.js +4 -6
  11. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.d.ts +8 -0
  12. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.js +15 -10
  13. package/lib/client/client-lifecycles-dispatcher.d.ts +2 -5
  14. package/lib/client/client-lifecycles-dispatcher.js +5 -7
  15. package/lib/client/clientEntry.js +11 -5
  16. package/lib/client/docusaurus.js +6 -4
  17. package/lib/client/exports/BrowserOnly.d.ts +1 -2
  18. package/lib/client/exports/BrowserOnly.js +2 -3
  19. package/lib/client/exports/ComponentCreator.d.ts +1 -2
  20. package/lib/client/exports/ComponentCreator.js +7 -6
  21. package/lib/client/exports/ErrorBoundary.d.ts +2 -2
  22. package/lib/client/exports/ErrorBoundary.js +1 -2
  23. package/lib/client/exports/Head.d.ts +2 -3
  24. package/lib/client/exports/Head.js +3 -4
  25. package/lib/client/exports/Interpolate.js +9 -12
  26. package/lib/client/exports/Link.d.ts +11 -5
  27. package/lib/client/exports/Link.js +13 -7
  28. package/lib/client/exports/Translate.js +2 -1
  29. package/lib/client/exports/browserContext.js +3 -2
  30. package/lib/client/exports/docusaurusContext.js +1 -1
  31. package/lib/client/exports/isInternalUrl.js +1 -1
  32. package/lib/client/exports/renderRoutes.d.ts +1 -2
  33. package/lib/client/exports/renderRoutes.js +1 -2
  34. package/lib/client/exports/router.d.ts +1 -1
  35. package/lib/client/exports/router.js +1 -1
  36. package/lib/client/exports/useDocusaurusContext.d.ts +1 -2
  37. package/lib/client/exports/useDocusaurusContext.js +1 -2
  38. package/lib/client/flat.d.ts +1 -2
  39. package/lib/client/flat.js +1 -2
  40. package/lib/client/normalizeLocation.d.ts +2 -3
  41. package/lib/client/normalizeLocation.js +1 -2
  42. package/lib/client/prefetch.d.ts +1 -2
  43. package/lib/client/prefetch.js +1 -2
  44. package/lib/client/preload.d.ts +2 -1
  45. package/lib/client/preload.js +2 -1
  46. package/lib/client/serverEntry.js +23 -19
  47. package/lib/client/theme-fallback/Error/index.d.ts +10 -0
  48. package/lib/client/theme-fallback/Error/index.js +21 -29
  49. package/lib/client/theme-fallback/Layout/index.d.ts +10 -0
  50. package/lib/client/theme-fallback/Layout/index.js +10 -19
  51. package/lib/client/theme-fallback/Loading/index.d.ts +9 -0
  52. package/lib/client/theme-fallback/Loading/index.js +46 -114
  53. package/lib/{server/versions/__tests/index.test.d.ts → client/theme-fallback/NotFound/index.d.ts} +2 -1
  54. package/lib/client/theme-fallback/NotFound/index.js +9 -16
  55. package/lib/client/theme-fallback/Root/index.d.ts +10 -0
  56. package/lib/client/theme-fallback/Root/index.js +2 -5
  57. package/lib/commands/build.js +33 -34
  58. package/lib/commands/clear.js +23 -11
  59. package/lib/commands/deploy.js +12 -11
  60. package/lib/commands/external.d.ts +2 -2
  61. package/lib/commands/external.js +1 -1
  62. package/lib/commands/serve.js +3 -2
  63. package/lib/commands/start.js +4 -4
  64. package/lib/commands/swizzle/actions.d.ts +23 -0
  65. package/lib/commands/swizzle/actions.js +102 -0
  66. package/lib/commands/swizzle/common.d.ts +33 -0
  67. package/lib/commands/swizzle/common.js +57 -0
  68. package/lib/commands/swizzle/components.d.ts +29 -0
  69. package/lib/commands/swizzle/components.js +165 -0
  70. package/lib/commands/swizzle/config.d.ts +10 -0
  71. package/lib/commands/swizzle/config.js +77 -0
  72. package/lib/commands/swizzle/context.d.ts +8 -0
  73. package/lib/commands/swizzle/context.js +30 -0
  74. package/lib/commands/swizzle/index.d.ts +8 -0
  75. package/lib/commands/swizzle/index.js +115 -0
  76. package/lib/commands/swizzle/prompts.d.ts +12 -0
  77. package/lib/commands/swizzle/prompts.js +110 -0
  78. package/lib/commands/swizzle/tables.d.ts +9 -0
  79. package/lib/commands/swizzle/tables.js +116 -0
  80. package/lib/commands/swizzle/themes.d.ts +20 -0
  81. package/lib/commands/swizzle/themes.js +105 -0
  82. package/lib/commands/writeHeadingIds.d.ts +1 -1
  83. package/lib/commands/writeHeadingIds.js +13 -14
  84. package/lib/commands/writeTranslations.js +10 -7
  85. package/lib/index.d.ts +10 -9
  86. package/lib/index.js +20 -19
  87. package/lib/server/brokenLinks.js +30 -20
  88. package/lib/server/config.js +1 -1
  89. package/lib/server/configValidation.d.ts +1 -1
  90. package/lib/server/configValidation.js +32 -23
  91. package/lib/server/duplicateRoutes.js +2 -4
  92. package/lib/server/html-tags/htmlTags.js +1 -2
  93. package/lib/server/i18n.d.ts +0 -1
  94. package/lib/server/i18n.js +16 -26
  95. package/lib/server/index.d.ts +1 -1
  96. package/lib/server/index.js +17 -15
  97. package/lib/server/loadSetup.d.ts +1 -2
  98. package/lib/server/loadSetup.js +2 -2
  99. package/lib/server/moduleShorthand.js +1 -1
  100. package/lib/server/plugins/index.js +9 -9
  101. package/lib/server/plugins/init.d.ts +11 -1
  102. package/lib/server/plugins/init.js +23 -28
  103. package/lib/server/plugins/pluginIds.js +4 -3
  104. package/lib/server/presets/index.d.ts +2 -2
  105. package/lib/server/presets/index.js +3 -3
  106. package/lib/server/routes.js +13 -7
  107. package/lib/server/themes/alias.d.ts +1 -1
  108. package/lib/server/themes/alias.js +5 -6
  109. package/lib/server/themes/index.d.ts +2 -2
  110. package/lib/server/themes/index.js +10 -9
  111. package/lib/server/translations/translations.js +10 -11
  112. package/lib/server/translations/translationsExtractor.js +20 -19
  113. package/lib/server/versions/index.d.ts +2 -3
  114. package/lib/server/versions/index.js +22 -21
  115. package/lib/webpack/base.d.ts +2 -2
  116. package/lib/webpack/base.js +30 -22
  117. package/lib/webpack/client.d.ts +1 -1
  118. package/lib/webpack/client.js +7 -4
  119. package/lib/webpack/plugins/ChunkAssetPlugin.d.ts +12 -2
  120. package/lib/webpack/plugins/ChunkAssetPlugin.js +17 -10
  121. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +5 -5
  122. package/lib/webpack/plugins/CleanWebpackPlugin.js +5 -4
  123. package/lib/webpack/server.d.ts +1 -1
  124. package/lib/webpack/server.js +6 -5
  125. package/lib/webpack/utils.d.ts +3 -3
  126. package/lib/webpack/utils.js +17 -37
  127. package/package.json +56 -56
  128. package/bin/beforeCli.js +0 -124
  129. package/lib/commands/swizzle.d.ts +0 -9
  130. package/lib/commands/swizzle.js +0 -236
  131. package/lib/server/versions/__tests/index.test.js +0 -26
@@ -0,0 +1,136 @@
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
+
8
+ // @ts-check
9
+
10
+ import logger from '@docusaurus/logger';
11
+ import fs from 'fs-extra';
12
+ import semver from 'semver';
13
+ import path from 'path';
14
+ import updateNotifier from 'update-notifier';
15
+ import boxen from 'boxen';
16
+ import {createRequire} from 'module';
17
+
18
+ const packageJson = createRequire(import.meta.url)('../package.json');
19
+ const sitePkg = createRequire(path.join(process.cwd(), 'package.json'))(
20
+ './package.json',
21
+ );
22
+
23
+ const {
24
+ name,
25
+ version,
26
+ engines: {node: requiredVersion},
27
+ } = packageJson;
28
+
29
+ /**
30
+ * Notify user if `@docusaurus` packages are outdated
31
+ *
32
+ * Note: this is a 2-step process to avoid delaying cli usage by awaiting a
33
+ * response:
34
+ * - 1st run: trigger background job to check releases + store result
35
+ * - 2nd run: display potential update to users
36
+ *
37
+ * cache data is stored in `~/.config/configstore/update-notifier-@docusaurus`
38
+ */
39
+ export default async function beforeCli() {
40
+ const notifier = updateNotifier({
41
+ pkg: {
42
+ name,
43
+ version,
44
+ },
45
+ // Check is in background so it's fine to use a small value like 1h
46
+ // Use 0 for debugging
47
+ updateCheckInterval: 1000 * 60 * 60,
48
+ // updateCheckInterval: 0
49
+ });
50
+
51
+ // Hacky way to ensure we check for updates on first run
52
+ // Note: the notification will only happen in the 2nd run
53
+ // See https://github.com/yeoman/update-notifier/issues/209
54
+ try {
55
+ if (
56
+ notifier.config &&
57
+ // @ts-expect-error: this is an internal API
58
+ !notifier.disabled &&
59
+ Date.now() - notifier.config.get('lastUpdateCheck') < 50
60
+ ) {
61
+ notifier.config.set('lastUpdateCheck', 0);
62
+ notifier.check();
63
+ }
64
+ } catch (err) {
65
+ // Do not stop cli if this fails, see https://github.com/facebook/docusaurus/issues/5400
66
+ logger.error(err);
67
+ }
68
+
69
+ /**
70
+ * We don't want to display update message for canary releases.
71
+ * See https://github.com/facebook/docusaurus/issues/5378
72
+ * @param {import('update-notifier').UpdateInfo} update
73
+ */
74
+ function ignoreUpdate(update) {
75
+ const isCanaryRelease =
76
+ update && update.current && update.current.startsWith('0.0.0');
77
+ return isCanaryRelease;
78
+ }
79
+
80
+ if (
81
+ notifier.config &&
82
+ notifier.update &&
83
+ semver.lt(notifier.update.current, notifier.update.latest)
84
+ ) {
85
+ // Because notifier clears cached data after reading it, leading to notifier
86
+ // not consistently displaying the update.
87
+ // See https://github.com/yeoman/update-notifier/issues/209
88
+ notifier.config.set('update', notifier.update);
89
+
90
+ if (ignoreUpdate(notifier.update)) {
91
+ return;
92
+ }
93
+
94
+ const siteDocusaurusPackagesForUpdate = Object.keys({
95
+ ...sitePkg.dependencies,
96
+ ...sitePkg.devDependencies,
97
+ })
98
+ .filter((p) => p.startsWith('@docusaurus'))
99
+ .map((p) => p.concat('@latest'))
100
+ .join(' ');
101
+ const isYarnUsed = await fs.pathExists(
102
+ path.resolve(process.cwd(), 'yarn.lock'),
103
+ );
104
+ const upgradeCommand = isYarnUsed
105
+ ? `yarn upgrade ${siteDocusaurusPackagesForUpdate}`
106
+ : `npm i ${siteDocusaurusPackagesForUpdate}`;
107
+
108
+ /** @type {import('boxen').Options} */
109
+ const boxenOptions = {
110
+ padding: 1,
111
+ margin: 1,
112
+ align: 'center',
113
+ borderColor: 'yellow',
114
+ borderStyle: 'round',
115
+ };
116
+
117
+ const docusaurusUpdateMessage = boxen(
118
+ `Update available ${logger.dim(
119
+ `${notifier.update.current}`,
120
+ )} → ${logger.green(`${notifier.update.latest}`)}
121
+
122
+ To upgrade Docusaurus packages with the latest version, run the following command:
123
+ ${logger.code(upgradeCommand)}`,
124
+ boxenOptions,
125
+ );
126
+
127
+ console.log(docusaurusUpdateMessage);
128
+ }
129
+
130
+ // notify user if node version needs to be updated
131
+ if (!semver.satisfies(process.version, requiredVersion)) {
132
+ logger.error('Minimum Node.js version not met :(');
133
+ logger.info`You are using Node.js number=${process.version}, Requirement: Node.js number=${requiredVersion}.`;
134
+ process.exit(1);
135
+ }
136
+ }
@@ -8,10 +8,11 @@
8
8
 
9
9
  // @ts-check
10
10
 
11
- const logger = require('@docusaurus/logger').default;
12
- const fs = require('fs');
13
- const cli = require('commander');
14
- const {
11
+ import logger from '@docusaurus/logger';
12
+ import fs from 'fs-extra';
13
+ import cli from 'commander';
14
+ import {createRequire} from 'module';
15
+ import {
15
16
  build,
16
17
  swizzle,
17
18
  deploy,
@@ -21,13 +22,16 @@ const {
21
22
  clear,
22
23
  writeTranslations,
23
24
  writeHeadingIds,
24
- } = require('../lib');
25
+ } from '../lib/index.js';
26
+ import beforeCli from './beforeCli.mjs';
25
27
 
26
- require('./beforeCli');
28
+ await beforeCli();
27
29
 
28
- const resolveDir = (dir = '.') => fs.realpathSync(dir);
30
+ const resolveDir = (dir = '.') => fs.realpath(dir);
29
31
 
30
- cli.version(require('../package.json').version).usage('<command> [options]');
32
+ cli
33
+ .version(createRequire(import.meta.url)('../package.json').version)
34
+ .usage('<command> [options]');
31
35
 
32
36
  cli
33
37
  .command('build [siteDir]')
@@ -52,8 +56,8 @@ cli
52
56
  '--no-minify',
53
57
  'build website without minimizing JS bundles (default: false)',
54
58
  )
55
- .action((siteDir, {bundleAnalyzer, config, outDir, locale, minify}) => {
56
- build(resolveDir(siteDir), {
59
+ .action(async (siteDir, {bundleAnalyzer, config, outDir, locale, minify}) => {
60
+ build(await resolveDir(siteDir), {
57
61
  bundleAnalyzer,
58
62
  outDir,
59
63
  config,
@@ -64,14 +68,28 @@ cli
64
68
 
65
69
  cli
66
70
  .command('swizzle [themeName] [componentName] [siteDir]')
67
- .description('Copy the theme files into website folder for customization.')
71
+ .description(
72
+ 'Wraps or ejects the original theme files into website folder for customization.',
73
+ )
74
+ .option(
75
+ '-w, --wrap',
76
+ 'Creates a wrapper around the original theme component.\nAllows rendering other components before/after the original theme component.',
77
+ )
78
+ .option(
79
+ '-e, --eject',
80
+ 'Ejects the full source code of the original theme component.\nAllows overriding the original component entirely with your own UI and logic.',
81
+ )
68
82
  .option(
69
- '--typescript',
83
+ '-l, --list',
84
+ 'only list the available themes/components without further prompting (default: false)',
85
+ )
86
+ .option(
87
+ '-t, --typescript',
70
88
  'copy TypeScript theme files when possible (default: false)',
71
89
  )
72
- .option('--danger', 'enable swizzle for internal component of themes')
73
- .action((themeName, componentName, siteDir, {typescript, danger}) => {
74
- swizzle(resolveDir(siteDir), themeName, componentName, typescript, danger);
90
+ .option('--danger', 'enable swizzle for unsafe component of themes')
91
+ .action(async (themeName, componentName, siteDir, options) => {
92
+ swizzle(await resolveDir(siteDir), themeName, componentName, options);
75
93
  });
76
94
 
77
95
  cli
@@ -93,8 +111,8 @@ cli
93
111
  '--skip-build',
94
112
  'skip building website before deploy it (default: false)',
95
113
  )
96
- .action((siteDir, {outDir, skipBuild, config}) => {
97
- deploy(resolveDir(siteDir), {
114
+ .action(async (siteDir, {outDir, skipBuild, config}) => {
115
+ deploy(await resolveDir(siteDir), {
98
116
  outDir,
99
117
  config,
100
118
  skipBuild,
@@ -120,17 +138,19 @@ cli
120
138
  '--poll [interval]',
121
139
  'use polling rather than watching for reload (default: false). Can specify a poll interval in milliseconds',
122
140
  )
123
- .action((siteDir, {port, host, locale, config, hotOnly, open, poll}) => {
124
- start(resolveDir(siteDir), {
125
- port,
126
- host,
127
- locale,
128
- config,
129
- hotOnly,
130
- open,
131
- poll,
132
- });
133
- });
141
+ .action(
142
+ async (siteDir, {port, host, locale, config, hotOnly, open, poll}) => {
143
+ start(await resolveDir(siteDir), {
144
+ port,
145
+ host,
146
+ locale,
147
+ config,
148
+ hotOnly,
149
+ open,
150
+ poll,
151
+ });
152
+ },
153
+ );
134
154
 
135
155
  cli
136
156
  .command('serve [siteDir]')
@@ -147,7 +167,7 @@ cli
147
167
  .option('--build', 'build website before serving (default: false)')
148
168
  .option('-h, --host <host>', 'use specified host (default: localhost)')
149
169
  .action(
150
- (
170
+ async (
151
171
  siteDir,
152
172
  {
153
173
  dir = 'build',
@@ -157,7 +177,7 @@ cli
157
177
  config,
158
178
  },
159
179
  ) => {
160
- serve(resolveDir(siteDir), {
180
+ serve(await resolveDir(siteDir), {
161
181
  dir,
162
182
  port,
163
183
  build: buildSite,
@@ -170,8 +190,8 @@ cli
170
190
  cli
171
191
  .command('clear [siteDir]')
172
192
  .description('Remove build artifacts.')
173
- .action((siteDir) => {
174
- clear(resolveDir(siteDir));
193
+ .action(async (siteDir) => {
194
+ clear(await resolveDir(siteDir));
175
195
  });
176
196
 
177
197
  cli
@@ -194,11 +214,11 @@ cli
194
214
  'allows to init new written messages with a given prefix. This might help you to highlight untranslated message to make them stand out in the UI',
195
215
  )
196
216
  .action(
197
- (
217
+ async (
198
218
  siteDir,
199
219
  {locale = undefined, override = false, messagePrefix = '', config},
200
220
  ) => {
201
- writeTranslations(resolveDir(siteDir), {
221
+ writeTranslations(await resolveDir(siteDir), {
202
222
  locale,
203
223
  override,
204
224
  config,
@@ -208,15 +228,15 @@ cli
208
228
  );
209
229
 
210
230
  cli
211
- .command('write-heading-ids [contentDir] [files]')
231
+ .command('write-heading-ids [siteDir] [files...]')
212
232
  .description('Generate heading ids in Markdown content.')
213
233
  .option(
214
234
  '--maintain-case',
215
235
  "keep the headings' casing, otherwise make all lowercase (default: false)",
216
236
  )
217
237
  .option('--overwrite', 'overwrite existing heading IDs (default: false)')
218
- .action((siteDir, files, options) =>
219
- writeHeadingIds(resolveDir(siteDir), files, options),
238
+ .action(async (siteDir, files, options) =>
239
+ writeHeadingIds(await resolveDir(siteDir), files, options),
220
240
  );
221
241
 
222
242
  cli.arguments('<command>').action((cmd) => {
@@ -224,6 +244,9 @@ cli.arguments('<command>').action((cmd) => {
224
244
  logger.error` Unknown command name=${cmd}.`;
225
245
  });
226
246
 
247
+ /**
248
+ * @param {string} command
249
+ */
227
250
  function isInternalCommand(command) {
228
251
  return [
229
252
  'start',
@@ -239,8 +262,7 @@ function isInternalCommand(command) {
239
262
 
240
263
  async function run() {
241
264
  if (!isInternalCommand(process.argv.slice(2)[0])) {
242
- // @ts-expect-error: Hmmm
243
- await externalCommand(cli, resolveDir('.'));
265
+ await externalCommand(cli, await resolveDir('.'));
244
266
  }
245
267
 
246
268
  cli.parse(process.argv);
@@ -253,6 +275,6 @@ async function run() {
253
275
  run();
254
276
 
255
277
  process.on('unhandledRejection', (err) => {
256
- logger.error(err.stack);
278
+ logger.error(err);
257
279
  process.exit(1);
258
280
  });
@@ -5,5 +5,4 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  import type { ConfigAPI, TransformOptions } from '@babel/core';
8
- declare function babelPresets(api: ConfigAPI): TransformOptions;
9
- export default babelPresets;
8
+ export default function babelPresets(api: ConfigAPI): TransformOptions;
@@ -11,7 +11,8 @@ const path_1 = (0, tslib_1.__importDefault)(require("path"));
11
11
  function getTransformOptions(isServer) {
12
12
  const absoluteRuntimePath = path_1.default.dirname(require.resolve(`@babel/runtime/package.json`));
13
13
  return {
14
- // All optional newlines and whitespace will be omitted when generating code in compact mode
14
+ // All optional newlines and whitespace will be omitted when generating code
15
+ // in compact mode
15
16
  compact: true,
16
17
  presets: [
17
18
  isServer
@@ -46,9 +47,9 @@ function getTransformOptions(isServer) {
46
47
  {
47
48
  corejs: false,
48
49
  helpers: true,
49
- // By default, it assumes @babel/runtime@7.0.0. Since we use >7.0.0, better to
50
- // explicitly specify the version so that it can reuse the helper better
51
- // See https://github.com/babel/babel/issues/10261
50
+ // By default, it assumes @babel/runtime@7.0.0. Since we use >7.0.0,
51
+ // better to explicitly specify the version so that it can reuse the
52
+ // helper better. See https://github.com/babel/babel/issues/10261
52
53
  // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require
53
54
  version: require('@babel/runtime/package.json').version,
54
55
  regenerator: true,
package/lib/choosePort.js CHANGED
@@ -55,7 +55,7 @@ function getProcessForPort(port) {
55
55
  const command = getProcessCommand(processId);
56
56
  return logger_1.default.interpolate `code=${command} subdue=${`(pid ${processId})`} in path=${directory}`;
57
57
  }
58
- catch (e) {
58
+ catch {
59
59
  return null;
60
60
  }
61
61
  }
@@ -64,41 +64,33 @@ function getProcessForPort(port) {
64
64
  * to choose another if port is already being used
65
65
  */
66
66
  async function choosePort(host, defaultPort) {
67
- return (0, detect_port_1.default)({ port: defaultPort, hostname: host }).then((port) => new Promise((resolve) => {
67
+ try {
68
+ const port = await (0, detect_port_1.default)({ port: defaultPort, hostname: host });
68
69
  if (port === defaultPort) {
69
- resolve(port);
70
- return;
70
+ return port;
71
71
  }
72
72
  const message = process.platform !== 'win32' && defaultPort < 1024 && !(0, is_root_1.default)()
73
73
  ? `Admin permissions are required to run a server on a port below 1024.`
74
74
  : `Something is already running on port ${defaultPort}.`;
75
- if (isInteractive) {
76
- clearConsole();
77
- const existingProcess = getProcessForPort(defaultPort);
78
- const question = {
79
- type: 'confirm',
80
- name: 'shouldChangePort',
81
- message: logger_1.default.yellow(`${logger_1.default.bold('[WARNING]')} ${message}${existingProcess ? ` Probably:\n ${existingProcess}` : ''}
82
-
83
- Would you like to run the app on another port instead?`),
84
- initial: true,
85
- };
86
- (0, prompts_1.default)(question).then((answer) => {
87
- if (answer.shouldChangePort === true) {
88
- resolve(port);
89
- }
90
- else {
91
- resolve(null);
92
- }
93
- });
94
- }
95
- else {
75
+ if (!isInteractive) {
96
76
  logger_1.default.error(message);
97
- resolve(null);
77
+ return null;
98
78
  }
99
- }), (err) => {
100
- throw new Error(`Could not find an open port at ${host}.
101
- ${`Network error message: "${err.message || err}".`}`);
102
- });
79
+ clearConsole();
80
+ const existingProcess = getProcessForPort(defaultPort);
81
+ const { shouldChangePort } = await (0, prompts_1.default)({
82
+ type: 'confirm',
83
+ name: 'shouldChangePort',
84
+ message: logger_1.default.yellow(`${logger_1.default.bold('[WARNING]')} ${message}${existingProcess ? ` Probably:\n ${existingProcess}` : ''}
85
+
86
+ Would you like to run the app on another port instead?`),
87
+ initial: true,
88
+ });
89
+ return shouldChangePort ? port : null;
90
+ }
91
+ catch (err) {
92
+ logger_1.default.error `Could not find an open port at ${host}.`;
93
+ throw err;
94
+ }
103
95
  }
104
96
  exports.default = choosePort;
@@ -6,5 +6,4 @@
6
6
  */
7
7
  /// <reference types="react" />
8
8
  import './client-lifecycles-dispatcher';
9
- declare function App(): JSX.Element;
10
- export default App;
9
+ export default function App(): JSX.Element;
package/lib/client/App.js CHANGED
@@ -16,12 +16,17 @@ import './client-lifecycles-dispatcher';
16
16
  // TODO, quick fix for CSS insertion order
17
17
  import ErrorBoundary from '@docusaurus/ErrorBoundary';
18
18
  import Error from '@theme/Error';
19
- function App() {
20
- return (React.createElement(ErrorBoundary, { fallback: Error },
21
- React.createElement(DocusaurusContextProvider, null,
22
- React.createElement(BrowserContextProvider, null,
23
- React.createElement(Root, null,
24
- React.createElement(BaseUrlIssueBanner, null),
25
- React.createElement(PendingNavigation, { routes: routes, delay: 1000 }, renderRoutes(routes)))))));
19
+ export default function App() {
20
+ return (<ErrorBoundary fallback={Error}>
21
+ <DocusaurusContextProvider>
22
+ <BrowserContextProvider>
23
+ <Root>
24
+ <BaseUrlIssueBanner />
25
+ <PendingNavigation routes={routes} delay={1000}>
26
+ {renderRoutes(routes)}
27
+ </PendingNavigation>
28
+ </Root>
29
+ </BrowserContextProvider>
30
+ </DocusaurusContextProvider>
31
+ </ErrorBoundary>);
26
32
  }
27
- export default App;
@@ -23,5 +23,5 @@ const Context = createContext({
23
23
  });
24
24
  export const useLinksCollector = () => useContext(Context);
25
25
  export function ProvideLinksCollector({ children, linksCollector, }) {
26
- return React.createElement(Context.Provider, { value: linksCollector }, children);
26
+ return <Context.Provider value={linksCollector}>{children}</Context.Provider>;
27
27
  }
@@ -8,7 +8,7 @@
8
8
  import React from 'react';
9
9
  import { type RouteComponentProps } from 'react-router-dom';
10
10
  import type { RouteConfig } from 'react-router-config';
11
- import type { Location } from '@docusaurus/history';
11
+ import type { Location } from 'history';
12
12
  import './nprogress.css';
13
13
  interface Props extends RouteComponentProps {
14
14
  readonly routes: RouteConfig[];
@@ -23,9 +23,9 @@ declare class PendingNavigation extends React.Component<Props, State> {
23
23
  progressBarTimeout: NodeJS.Timeout | null;
24
24
  constructor(props: Props);
25
25
  shouldComponentUpdate(nextProps: Props, nextState: State): boolean;
26
- clearProgressBarTimeout(): void;
27
- startProgressBar(delay: number): void;
28
- stopProgressBar(): void;
26
+ private clearProgressBarTimeout;
27
+ private startProgressBar;
28
+ private stopProgressBar;
29
29
  render(): JSX.Element;
30
30
  }
31
31
  declare const _default: React.ComponentClass<Pick<Props, "routes" | "delay">, any> & import("react-router").WithRouterStatics<typeof PendingNavigation>;
@@ -27,8 +27,8 @@ class PendingNavigation extends React.Component {
27
27
  shouldComponentUpdate(nextProps, nextState) {
28
28
  const routeDidChange = nextProps.location !== this.props.location;
29
29
  const { routes, delay } = this.props;
30
- // If `routeDidChange` is true, means the router is trying to navigate to a new
31
- // route. We will preload the new route.
30
+ // If `routeDidChange` is true, means the router is trying to navigate to a
31
+ // new route. We will preload the new route.
32
32
  if (routeDidChange) {
33
33
  const nextLocation = normalizeLocation(nextProps.location);
34
34
  this.startProgressBar(delay);
@@ -46,9 +46,7 @@ class PendingNavigation extends React.Component {
46
46
  });
47
47
  // Route has loaded, we can reset previousLocation.
48
48
  this.previousLocation = null;
49
- this.setState({
50
- nextRouteHasLoaded: true,
51
- }, this.stopProgressBar);
49
+ this.setState({ nextRouteHasLoaded: true }, this.stopProgressBar);
52
50
  const { hash } = nextLocation;
53
51
  if (!hash) {
54
52
  window.scrollTo(0, 0);
@@ -92,7 +90,7 @@ class PendingNavigation extends React.Component {
92
90
  }
93
91
  render() {
94
92
  const { children, location } = this.props;
95
- return (React.createElement(Route, { location: normalizeLocation(location), render: () => children }));
93
+ return (<Route location={normalizeLocation(location)} render={() => children}/>);
96
94
  }
97
95
  }
98
96
  export default withRouter(PendingNavigation);
@@ -11,4 +11,12 @@ declare global {
11
11
  __DOCUSAURUS_INSERT_BASEURL_BANNER: boolean;
12
12
  }
13
13
  }
14
+ /**
15
+ * We want to help the users with a bad baseUrl configuration (very common
16
+ * error) Help message is inlined, and hidden if JS or CSS is able to load
17
+ * Note: it might create false positives (ie network failures): not a big deal
18
+ * Note: we only inline this for the homepage to avoid polluting all the site's
19
+ * pages
20
+ * @see https://github.com/facebook/docusaurus/pull/3621
21
+ */
14
22
  export default function BaseUrlIssueBanner(): JSX.Element | null;
@@ -67,21 +67,26 @@ function BaseUrlIssueBannerEnabled() {
67
67
  useLayoutEffect(() => {
68
68
  window[InsertBannerWindowAttribute] = false;
69
69
  }, []);
70
- return (React.createElement(React.Fragment, null,
71
- !ExecutionEnvironment.canUseDOM && (React.createElement(Head, null,
72
- React.createElement("script", null, createInlineScript(baseUrl)))),
73
- React.createElement("div", { id: BannerContainerId })));
70
+ return (<>
71
+ {!ExecutionEnvironment.canUseDOM && (<Head>
72
+ <script>{createInlineScript(baseUrl)}</script>
73
+ </Head>)}
74
+ <div id={BannerContainerId}/>
75
+ </>);
74
76
  }
75
- // We want to help the users with a bad baseUrl configuration (very common error)
76
- // Help message is inlined, and hidden if JS or CSS is able to load
77
- // Note: it might create false positives (ie network failures): not a big deal
78
- // Note: we only inline this for the homepage to avoid polluting all the site's pages
79
- // See https://github.com/facebook/docusaurus/pull/3621
77
+ /**
78
+ * We want to help the users with a bad baseUrl configuration (very common
79
+ * error) Help message is inlined, and hidden if JS or CSS is able to load
80
+ * Note: it might create false positives (ie network failures): not a big deal
81
+ * Note: we only inline this for the homepage to avoid polluting all the site's
82
+ * pages
83
+ * @see https://github.com/facebook/docusaurus/pull/3621
84
+ */
80
85
  export default function BaseUrlIssueBanner() {
81
86
  const { siteConfig: { baseUrl, baseUrlIssueBanner }, } = useDocusaurusContext();
82
87
  const { pathname } = useLocation();
83
88
  // returns true for the homepage during SRR
84
89
  const isHomePage = pathname === baseUrl;
85
90
  const enabled = baseUrlIssueBanner && isHomePage;
86
- return enabled ? React.createElement(BaseUrlIssueBannerEnabled, null) : null;
91
+ return enabled ? <BaseUrlIssueBannerEnabled /> : null;
87
92
  }
@@ -4,9 +4,6 @@
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
- interface Dispatchers {
8
- onRouteUpdate: (...args: unknown[]) => void;
9
- onRouteUpdateDelayed: (...args: unknown[]) => void;
10
- }
11
- declare const clientLifecyclesDispatchers: Dispatchers;
7
+ import type { ClientModule } from '@docusaurus/types';
8
+ declare const clientLifecyclesDispatchers: Required<ClientModule>;
12
9
  export default clientLifecyclesDispatchers;
@@ -5,21 +5,19 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  import clientModules from '@generated/client-modules';
8
- function dispatchLifecycleAction(lifecycleAction, ...args) {
8
+ function dispatchLifecycleAction(lifecycleAction, args) {
9
9
  clientModules.forEach((clientModule) => {
10
10
  var _a, _b;
11
- const lifecycleFunction = (_b = (_a = clientModule === null || clientModule === void 0 ? void 0 : clientModule.default) === null || _a === void 0 ? void 0 : _a[lifecycleAction]) !== null && _b !== void 0 ? _b : clientModule[lifecycleAction];
12
- if (lifecycleFunction) {
13
- lifecycleFunction(...args);
14
- }
11
+ const lifecycleFunction = ((_b = (_a = clientModule === null || clientModule === void 0 ? void 0 : clientModule.default) === null || _a === void 0 ? void 0 : _a[lifecycleAction]) !== null && _b !== void 0 ? _b : clientModule[lifecycleAction]);
12
+ lifecycleFunction === null || lifecycleFunction === void 0 ? void 0 : lifecycleFunction(...args);
15
13
  });
16
14
  }
17
15
  const clientLifecyclesDispatchers = {
18
16
  onRouteUpdate(...args) {
19
- dispatchLifecycleAction('onRouteUpdate', ...args);
17
+ dispatchLifecycleAction('onRouteUpdate', args);
20
18
  },
21
19
  onRouteUpdateDelayed(...args) {
22
- dispatchLifecycleAction('onRouteUpdateDelayed', ...args);
20
+ dispatchLifecycleAction('onRouteUpdateDelayed', args);
23
21
  },
24
22
  };
25
23
  export default clientLifecyclesDispatchers;