@docusaurus/core 2.0.0-beta.18 → 2.0.0-beta.19

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 (130) hide show
  1. package/bin/beforeCli.mjs +12 -7
  2. package/bin/docusaurus.mjs +21 -72
  3. package/lib/client/.eslintrc.js +2 -3
  4. package/lib/client/App.d.ts +1 -1
  5. package/lib/client/App.js +9 -5
  6. package/lib/client/{baseUrlIssueBanner/BaseUrlIssueBanner.d.ts → BaseUrlIssueBanner/index.d.ts} +10 -5
  7. package/lib/client/{baseUrlIssueBanner/BaseUrlIssueBanner.js → BaseUrlIssueBanner/index.js} +14 -9
  8. package/lib/client/{baseUrlIssueBanner → BaseUrlIssueBanner}/styles.module.css +0 -0
  9. package/lib/client/ClientLifecyclesDispatcher.d.ts +16 -0
  10. package/lib/client/ClientLifecyclesDispatcher.js +34 -0
  11. package/lib/client/LinksCollector.js +1 -2
  12. package/lib/client/PendingNavigation.d.ts +8 -17
  13. package/lib/client/PendingNavigation.js +39 -70
  14. package/lib/client/clientEntry.js +1 -2
  15. package/lib/client/docusaurus.d.ts +5 -5
  16. package/lib/client/docusaurus.js +25 -29
  17. package/lib/client/exports/BrowserOnly.d.ts +3 -4
  18. package/lib/client/exports/BrowserOnly.js +1 -1
  19. package/lib/client/exports/ComponentCreator.js +51 -46
  20. package/lib/client/exports/ErrorBoundary.d.ts +2 -2
  21. package/lib/client/exports/Interpolate.js +16 -39
  22. package/lib/client/exports/Link.d.ts +3 -15
  23. package/lib/client/exports/Link.js +21 -26
  24. package/lib/client/exports/useBaseUrl.js +3 -9
  25. package/lib/client/exports/useGlobalData.d.ts +3 -3
  26. package/lib/client/exports/useGlobalData.js +5 -5
  27. package/lib/client/flat.d.ts +10 -2
  28. package/lib/client/flat.js +11 -3
  29. package/lib/client/normalizeLocation.js +14 -5
  30. package/lib/client/prefetch.js +7 -25
  31. package/lib/client/preload.d.ts +1 -3
  32. package/lib/client/preload.js +2 -2
  33. package/lib/client/routeContext.js +1 -1
  34. package/lib/client/serverEntry.js +12 -11
  35. package/lib/client/theme-fallback/Error/index.js +2 -0
  36. package/lib/client/theme-fallback/Loading/index.js +2 -0
  37. package/lib/client/theme-fallback/NotFound/index.js +2 -0
  38. package/lib/commands/build.d.ts +6 -2
  39. package/lib/commands/build.js +35 -15
  40. package/lib/commands/clear.d.ts +1 -1
  41. package/lib/commands/clear.js +3 -2
  42. package/lib/commands/deploy.d.ts +5 -2
  43. package/lib/commands/deploy.js +12 -9
  44. package/lib/commands/external.d.ts +1 -1
  45. package/lib/commands/external.js +5 -6
  46. package/lib/commands/serve.d.ts +7 -2
  47. package/lib/commands/serve.js +12 -12
  48. package/lib/commands/start.d.ts +8 -2
  49. package/lib/commands/start.js +14 -9
  50. package/lib/commands/swizzle/actions.d.ts +2 -2
  51. package/lib/commands/swizzle/actions.js +5 -4
  52. package/lib/commands/swizzle/common.d.ts +3 -3
  53. package/lib/commands/swizzle/components.js +41 -3
  54. package/lib/commands/swizzle/config.js +14 -11
  55. package/lib/commands/swizzle/context.js +6 -10
  56. package/lib/commands/swizzle/index.d.ts +2 -2
  57. package/lib/commands/swizzle/index.js +4 -3
  58. package/lib/commands/writeHeadingIds.d.ts +1 -1
  59. package/lib/commands/writeHeadingIds.js +5 -8
  60. package/lib/commands/writeTranslations.d.ts +3 -4
  61. package/lib/commands/writeTranslations.js +7 -9
  62. package/lib/index.d.ts +9 -10
  63. package/lib/index.js +18 -19
  64. package/lib/server/brokenLinks.js +1 -2
  65. package/lib/server/{client-modules/index.d.ts → clientModules.d.ts} +5 -1
  66. package/lib/server/{client-modules/index.js → clientModules.js} +6 -1
  67. package/lib/server/config.d.ts +5 -2
  68. package/lib/server/config.js +11 -6
  69. package/lib/server/configValidation.js +6 -5
  70. package/lib/server/getHostPort.d.ts +14 -0
  71. package/lib/{choosePort.js → server/getHostPort.js} +21 -35
  72. package/lib/server/htmlTags.d.ts +12 -0
  73. package/lib/server/htmlTags.js +62 -0
  74. package/lib/server/i18n.d.ts +2 -11
  75. package/lib/server/i18n.js +4 -19
  76. package/lib/server/index.d.ts +28 -13
  77. package/lib/server/index.js +42 -210
  78. package/lib/server/plugins/configs.d.ts +51 -0
  79. package/lib/server/plugins/configs.js +101 -0
  80. package/lib/server/plugins/index.d.ts +8 -7
  81. package/lib/server/plugins/index.js +59 -134
  82. package/lib/server/plugins/init.d.ts +6 -19
  83. package/lib/server/plugins/init.js +16 -68
  84. package/lib/server/{moduleShorthand.d.ts → plugins/moduleShorthand.d.ts} +0 -0
  85. package/lib/server/{moduleShorthand.js → plugins/moduleShorthand.js} +0 -0
  86. package/lib/server/plugins/pluginIds.d.ts +4 -0
  87. package/lib/server/plugins/pluginIds.js +4 -2
  88. package/lib/server/plugins/presets.d.ts +12 -0
  89. package/lib/server/{presets/index.js → plugins/presets.js} +14 -6
  90. package/lib/server/plugins/{applyRouteTrailingSlash.d.ts → routeConfig.d.ts} +3 -1
  91. package/lib/server/plugins/routeConfig.js +54 -0
  92. package/lib/server/plugins/synthetic.d.ts +20 -0
  93. package/lib/server/plugins/synthetic.js +112 -0
  94. package/lib/server/routes.d.ts +42 -8
  95. package/lib/server/routes.js +150 -92
  96. package/lib/server/{versions/index.d.ts → siteMetadata.d.ts} +5 -2
  97. package/lib/server/{versions/index.js → siteMetadata.js} +36 -3
  98. package/lib/server/translations/translations.d.ts +5 -13
  99. package/lib/server/translations/translations.js +5 -8
  100. package/lib/server/translations/translationsExtractor.d.ts +2 -4
  101. package/lib/webpack/aliases/index.d.ts +34 -0
  102. package/lib/webpack/aliases/index.js +106 -0
  103. package/lib/webpack/base.d.ts +0 -3
  104. package/lib/webpack/base.js +8 -25
  105. package/lib/webpack/client.js +1 -1
  106. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +2 -2
  107. package/lib/webpack/plugins/WaitPlugin.d.ts +2 -2
  108. package/lib/webpack/server.d.ts +2 -2
  109. package/lib/webpack/server.js +5 -3
  110. package/lib/webpack/utils.d.ts +3 -3
  111. package/lib/webpack/utils.js +3 -3
  112. package/package.json +33 -36
  113. package/lib/choosePort.d.ts +0 -11
  114. package/lib/client/client-lifecycles-dispatcher.d.ts +0 -9
  115. package/lib/client/client-lifecycles-dispatcher.js +0 -23
  116. package/lib/client/nprogress.css +0 -36
  117. package/lib/commands/commandUtils.d.ts +0 -9
  118. package/lib/commands/commandUtils.js +0 -21
  119. package/lib/server/duplicateRoutes.d.ts +0 -8
  120. package/lib/server/duplicateRoutes.js +0 -42
  121. package/lib/server/html-tags/htmlTags.d.ts +0 -7
  122. package/lib/server/html-tags/htmlTags.js +0 -38
  123. package/lib/server/html-tags/index.d.ts +0 -8
  124. package/lib/server/html-tags/index.js +0 -42
  125. package/lib/server/plugins/applyRouteTrailingSlash.js +0 -19
  126. package/lib/server/presets/index.d.ts +0 -11
  127. package/lib/server/themes/alias.d.ts +0 -9
  128. package/lib/server/themes/alias.js +0 -50
  129. package/lib/server/themes/index.d.ts +0 -12
  130. package/lib/server/themes/index.js +0 -47
@@ -0,0 +1,54 @@
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.sortConfig = exports.applyRouteTrailingSlash = void 0;
10
+ const utils_common_1 = require("@docusaurus/utils-common");
11
+ /** Recursively applies trailing slash config to all nested routes. */
12
+ function applyRouteTrailingSlash(route, params) {
13
+ return {
14
+ ...route,
15
+ path: (0, utils_common_1.applyTrailingSlash)(route.path, params),
16
+ ...(route.routes && {
17
+ routes: route.routes.map((subroute) => applyRouteTrailingSlash(subroute, params)),
18
+ }),
19
+ };
20
+ }
21
+ exports.applyRouteTrailingSlash = applyRouteTrailingSlash;
22
+ function sortConfig(routeConfigs, baseUrl = '/') {
23
+ // Sort the route config. This ensures that route with nested
24
+ // routes is always placed last.
25
+ routeConfigs.sort((a, b) => {
26
+ // Root route should get placed last.
27
+ if (a.path === baseUrl && b.path !== baseUrl) {
28
+ return 1;
29
+ }
30
+ if (a.path !== baseUrl && b.path === baseUrl) {
31
+ return -1;
32
+ }
33
+ if (a.routes && !b.routes) {
34
+ return 1;
35
+ }
36
+ if (!a.routes && b.routes) {
37
+ return -1;
38
+ }
39
+ // Higher priority get placed first.
40
+ if (a.priority || b.priority) {
41
+ const priorityA = a.priority || 0;
42
+ const priorityB = b.priority || 0;
43
+ const score = priorityB - priorityA;
44
+ if (score !== 0) {
45
+ return score;
46
+ }
47
+ }
48
+ return a.path.localeCompare(b.path);
49
+ });
50
+ routeConfigs.forEach((routeConfig) => {
51
+ routeConfig.routes?.sort((a, b) => a.path.localeCompare(b.path));
52
+ });
53
+ }
54
+ exports.sortConfig = sortConfig;
@@ -0,0 +1,20 @@
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 { LoadedPlugin, LoadContext } from '@docusaurus/types';
8
+ /**
9
+ * Make a synthetic plugin to:
10
+ * - Inject site client modules
11
+ * - Inject scripts/stylesheets
12
+ */
13
+ export declare function createBootstrapPlugin({ siteDir, siteConfig, }: LoadContext): LoadedPlugin;
14
+ /**
15
+ * Configure Webpack fallback mdx loader for md/mdx files out of content-plugin
16
+ * folders. Adds a "fallback" mdx loader for mdx files that are not processed by
17
+ * content plugins. This allows to do things such as importing repo/README.md as
18
+ * a partial from another doc. Not ideal solution, but good enough for now
19
+ */
20
+ export declare function createMDXFallbackPlugin({ siteDir, siteConfig, }: LoadContext): LoadedPlugin;
@@ -0,0 +1,112 @@
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.createMDXFallbackPlugin = exports.createBootstrapPlugin = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const path_1 = tslib_1.__importDefault(require("path"));
12
+ const remark_admonitions_1 = tslib_1.__importDefault(require("remark-admonitions"));
13
+ /**
14
+ * Make a synthetic plugin to:
15
+ * - Inject site client modules
16
+ * - Inject scripts/stylesheets
17
+ */
18
+ function createBootstrapPlugin({ siteDir, siteConfig, }) {
19
+ const { stylesheets, scripts, clientModules: siteConfigClientModules, } = siteConfig;
20
+ return {
21
+ name: 'docusaurus-bootstrap-plugin',
22
+ content: null,
23
+ options: {
24
+ id: 'default',
25
+ },
26
+ version: { type: 'synthetic' },
27
+ path: siteDir,
28
+ getClientModules() {
29
+ return siteConfigClientModules;
30
+ },
31
+ injectHtmlTags: () => {
32
+ const stylesheetsTags = stylesheets.map((source) => typeof source === 'string'
33
+ ? `<link rel="stylesheet" href="${source}">`
34
+ : {
35
+ tagName: 'link',
36
+ attributes: {
37
+ rel: 'stylesheet',
38
+ ...source,
39
+ },
40
+ });
41
+ const scriptsTags = scripts.map((source) => typeof source === 'string'
42
+ ? `<script src="${source}"></script>`
43
+ : {
44
+ tagName: 'script',
45
+ attributes: {
46
+ ...source,
47
+ },
48
+ });
49
+ return {
50
+ headTags: [...stylesheetsTags, ...scriptsTags],
51
+ };
52
+ },
53
+ };
54
+ }
55
+ exports.createBootstrapPlugin = createBootstrapPlugin;
56
+ /**
57
+ * Configure Webpack fallback mdx loader for md/mdx files out of content-plugin
58
+ * folders. Adds a "fallback" mdx loader for mdx files that are not processed by
59
+ * content plugins. This allows to do things such as importing repo/README.md as
60
+ * a partial from another doc. Not ideal solution, but good enough for now
61
+ */
62
+ function createMDXFallbackPlugin({ siteDir, siteConfig, }) {
63
+ return {
64
+ name: 'docusaurus-mdx-fallback-plugin',
65
+ content: null,
66
+ options: {
67
+ id: 'default',
68
+ },
69
+ version: { type: 'synthetic' },
70
+ // Synthetic, the path doesn't matter much
71
+ path: '.',
72
+ configureWebpack(config, isServer, { getJSLoader }) {
73
+ // We need the mdx fallback loader to exclude files that were already
74
+ // processed by content plugins mdx loaders. This works, but a bit
75
+ // hacky... Not sure there's a way to handle that differently in webpack
76
+ function getMDXFallbackExcludedPaths() {
77
+ const rules = config?.module?.rules;
78
+ return rules.flatMap((rule) => {
79
+ const isMDXRule = rule.test instanceof RegExp && rule.test.test('x.mdx');
80
+ return isMDXRule ? rule.include : [];
81
+ });
82
+ }
83
+ const mdxLoaderOptions = {
84
+ staticDirs: siteConfig.staticDirectories.map((dir) => path_1.default.resolve(siteDir, dir)),
85
+ siteDir,
86
+ // External MDX files are always meant to be imported as partials
87
+ isMDXPartial: () => true,
88
+ // External MDX files might have front matter, just disable the warning
89
+ isMDXPartialFrontMatterWarningDisabled: true,
90
+ remarkPlugins: [remark_admonitions_1.default],
91
+ };
92
+ return {
93
+ module: {
94
+ rules: [
95
+ {
96
+ test: /\.mdx?$/i,
97
+ exclude: getMDXFallbackExcludedPaths(),
98
+ use: [
99
+ getJSLoader({ isServer }),
100
+ {
101
+ loader: require.resolve('@docusaurus/mdx-loader'),
102
+ options: mdxLoaderOptions,
103
+ },
104
+ ],
105
+ },
106
+ ],
107
+ },
108
+ };
109
+ },
110
+ };
111
+ }
112
+ exports.createMDXFallbackPlugin = createMDXFallbackPlugin;
@@ -4,14 +4,48 @@
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 type { ChunkRegistry, RouteConfig, ChunkNames } from '@docusaurus/types';
8
- export default function loadRoutes(pluginsRouteConfigs: RouteConfig[], baseUrl: string): Promise<{
9
- registry: {
10
- [chunkName: string]: ChunkRegistry;
11
- };
7
+ import type { RouteConfig, RouteChunkNames, ReportingSeverity } from '@docusaurus/types';
8
+ declare type LoadedRoutes = {
9
+ /** Serialized routes config that can be directly emitted into temp file. */
12
10
  routesConfig: string;
13
- routesChunkNames: {
14
- [routePath: string]: ChunkNames;
11
+ /** @see {ChunkNames} */
12
+ routesChunkNames: RouteChunkNames;
13
+ /**
14
+ * A map from chunk name to module paths. Module paths would have backslash
15
+ * escaped already, so they can be directly printed.
16
+ */
17
+ registry: {
18
+ [chunkName: string]: string;
15
19
  };
20
+ /**
21
+ * Collect all page paths for injecting it later in the plugin lifecycle.
22
+ * This is useful for plugins like sitemaps, redirects etc... Only collects
23
+ * "actual" pages, i.e. those without subroutes, because if a route has
24
+ * subroutes, it is probably a wrapper.
25
+ */
16
26
  routesPaths: string[];
17
- }>;
27
+ };
28
+ /**
29
+ * Generates a unique chunk name that can be used in the chunk registry.
30
+ *
31
+ * @param modulePath A path to generate chunk name from. The actual value has no
32
+ * semantic significance.
33
+ * @param prefix A prefix to append to the chunk name, to avoid name clash.
34
+ * @param preferredName Chunk names default to `modulePath`, and this can supply
35
+ * a more human-readable name.
36
+ * @param shortId When `true`, the chunk name would only be a hash without any
37
+ * other characters. Useful for bundle size. Defaults to `true` in production.
38
+ */
39
+ export declare function genChunkName(modulePath: string, prefix?: string, preferredName?: string, shortId?: boolean): string;
40
+ export declare function handleDuplicateRoutes(pluginsRouteConfigs: RouteConfig[], onDuplicateRoutes: ReportingSeverity): void;
41
+ /**
42
+ * Routes are prepared into three temp files:
43
+ *
44
+ * - `routesConfig`, the route config passed to react-router. This file is kept
45
+ * minimal, because it can't be code-splitted.
46
+ * - `routesChunkNames`, a mapping from route paths (hashed) to code-splitted
47
+ * chunk names.
48
+ * - `registry`, a mapping from chunk names to options for react-loadable.
49
+ */
50
+ export declare function loadRoutes(routeConfigs: RouteConfig[], baseUrl: string, onDuplicateRoutes: ReportingSeverity): LoadedRoutes;
51
+ export {};
@@ -6,23 +6,64 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.loadRoutes = exports.handleDuplicateRoutes = exports.genChunkName = void 0;
10
+ const tslib_1 = require("tslib");
9
11
  const utils_1 = require("@docusaurus/utils");
10
- const querystring_1 = require("querystring");
12
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
13
+ const querystring_1 = tslib_1.__importDefault(require("querystring"));
14
+ const utils_2 = require("./utils");
15
+ /** Indents every line of `str` by one level. */
11
16
  function indent(str) {
12
- const spaces = ' ';
13
- return `${spaces}${str.replace(/\n/g, `\n${spaces}`)}`;
17
+ return ` ${str.replace(/\n/g, `\n `)}`;
14
18
  }
15
- function createRouteCodeString({ routePath, routeHash, exact, subroutesCodeStrings, props, }) {
19
+ const chunkNameCache = new Map();
20
+ /**
21
+ * Generates a unique chunk name that can be used in the chunk registry.
22
+ *
23
+ * @param modulePath A path to generate chunk name from. The actual value has no
24
+ * semantic significance.
25
+ * @param prefix A prefix to append to the chunk name, to avoid name clash.
26
+ * @param preferredName Chunk names default to `modulePath`, and this can supply
27
+ * a more human-readable name.
28
+ * @param shortId When `true`, the chunk name would only be a hash without any
29
+ * other characters. Useful for bundle size. Defaults to `true` in production.
30
+ */
31
+ function genChunkName(modulePath, prefix, preferredName, shortId = process.env.NODE_ENV === 'production') {
32
+ let chunkName = chunkNameCache.get(modulePath);
33
+ if (!chunkName) {
34
+ if (shortId) {
35
+ chunkName = (0, utils_1.simpleHash)(modulePath, 8);
36
+ }
37
+ else {
38
+ let str = modulePath;
39
+ if (preferredName) {
40
+ const shortHash = (0, utils_1.simpleHash)(modulePath, 3);
41
+ str = `${preferredName}${shortHash}`;
42
+ }
43
+ const name = str === '/' ? 'index' : (0, utils_1.docuHash)(str);
44
+ chunkName = prefix ? `${prefix}---${name}` : name;
45
+ }
46
+ chunkNameCache.set(modulePath, chunkName);
47
+ }
48
+ return chunkName;
49
+ }
50
+ exports.genChunkName = genChunkName;
51
+ /**
52
+ * Takes a piece of route config, and serializes it into raw JS code. The shape
53
+ * is the same as react-router's `RouteConfig`. Formatting is similar to
54
+ * `JSON.stringify` but without all the quotes.
55
+ */
56
+ function serializeRouteConfig({ routePath, routeHash, exact, subroutesCodeStrings, props, }) {
16
57
  const parts = [
17
58
  `path: '${routePath}'`,
18
- `component: ComponentCreator('${routePath}','${routeHash}')`,
59
+ `component: ComponentCreator('${routePath}', '${routeHash}')`,
19
60
  ];
20
61
  if (exact) {
21
62
  parts.push(`exact: true`);
22
63
  }
23
64
  if (subroutesCodeStrings) {
24
65
  parts.push(`routes: [
25
- ${indent((0, utils_1.removeSuffix)(subroutesCodeStrings.join(',\n'), ',\n'))}
66
+ ${indent(subroutesCodeStrings.join(',\n'))}
26
67
  ]`);
27
68
  }
28
69
  Object.entries(props).forEach(([propName, propValue]) => {
@@ -50,103 +91,120 @@ ${indent((0, utils_1.removeSuffix)(subroutesCodeStrings.join(',\n'), ',\n'))}
50
91
  ${indent(parts.join(',\n'))}
51
92
  }`;
52
93
  }
53
- const NotFoundRouteCode = `{
54
- path: '*',
55
- component: ComponentCreator('*')
56
- }`;
57
- const RoutesImportsCode = [
58
- `import React from 'react';`,
59
- `import ComponentCreator from '@docusaurus/ComponentCreator';`,
60
- ].join('\n');
61
- function isModule(value) {
62
- if (typeof value === 'string') {
63
- return true;
64
- }
65
- if (typeof value === 'object' &&
94
+ const isModule = (value) => typeof value === 'string' ||
95
+ (typeof value === 'object' &&
66
96
  // eslint-disable-next-line no-underscore-dangle
67
- value?.__import &&
68
- value?.path) {
69
- return true;
70
- }
71
- return false;
72
- }
97
+ !!value?.__import);
98
+ /**
99
+ * Takes a {@link Module} (which is nothing more than a path plus some metadata
100
+ * like query) and returns the string path it represents.
101
+ */
73
102
  function getModulePath(target) {
74
103
  if (typeof target === 'string') {
75
104
  return target;
76
105
  }
77
- const queryStr = target.query ? `?${(0, querystring_1.stringify)(target.query)}` : '';
106
+ const queryStr = target.query ? `?${querystring_1.default.stringify(target.query)}` : '';
78
107
  return `${target.path}${queryStr}`;
79
108
  }
80
- async function loadRoutes(pluginsRouteConfigs, baseUrl) {
81
- const registry = {};
82
- const routesPaths = [(0, utils_1.normalizeUrl)([baseUrl, '404.html'])];
83
- const routesChunkNames = {};
84
- // This is the higher level overview of route code generation.
85
- function generateRouteCode(routeConfig) {
86
- const { path: routePath, component, modules = {}, routes: subroutes, exact, priority, ...props } = routeConfig;
87
- if (typeof routePath !== 'string' || !component) {
88
- throw new Error(`Invalid route config: path must be a string and component is required.
89
- ${JSON.stringify(routeConfig)}`);
90
- }
91
- // Collect all page paths for injecting it later in the plugin lifecycle
92
- // This is useful for plugins like sitemaps, redirects etc...
93
- // If a route has subroutes, it is not necessarily a valid page path (more
94
- // likely to be a wrapper)
95
- if (!subroutes) {
96
- routesPaths.push(routePath);
97
- }
98
- // We hash the route to generate the key, because 2 routes can conflict with
99
- // each others if they have the same path, ex: parent=/docs, child=/docs
100
- // see https://github.com/facebook/docusaurus/issues/2917
101
- const routeHash = (0, utils_1.simpleHash)(JSON.stringify(routeConfig), 3);
102
- const chunkNamesKey = `${routePath}-${routeHash}`;
103
- routesChunkNames[chunkNamesKey] = {
104
- ...genRouteChunkNames(registry, { component }, 'component', component),
105
- ...genRouteChunkNames(registry, modules, 'module', routePath),
106
- };
107
- return createRouteCodeString({
108
- routePath: routeConfig.path.replace(/'/g, "\\'"),
109
- routeHash,
110
- exact,
111
- subroutesCodeStrings: subroutes?.map(generateRouteCode),
112
- props,
113
- });
109
+ function genChunkNames(routeModule, prefix, name, res) {
110
+ if (isModule(routeModule)) {
111
+ // This is a leaf node, no need to recurse
112
+ const modulePath = getModulePath(routeModule);
113
+ const chunkName = genChunkName(modulePath, prefix, name);
114
+ res.registry[chunkName] = (0, utils_1.escapePath)(modulePath);
115
+ return chunkName;
114
116
  }
115
- const routesConfig = `
116
- ${RoutesImportsCode}
117
-
118
- export default [
119
- ${indent(`${pluginsRouteConfigs.map(generateRouteCode).join(',\n')},`)}
120
- ${indent(NotFoundRouteCode)}
121
- ];
122
- `;
123
- return {
124
- registry,
125
- routesConfig,
126
- routesChunkNames,
127
- routesPaths,
128
- };
117
+ if (Array.isArray(routeModule)) {
118
+ return routeModule.map((val, index) => genChunkNames(val, `${index}`, name, res));
119
+ }
120
+ return lodash_1.default.mapValues(routeModule, (v, key) => genChunkNames(v, key, name, res));
129
121
  }
130
- exports.default = loadRoutes;
131
- function genRouteChunkNames(
132
- // TODO instead of passing a mutating the registry, return a registry slice?
133
- registry, value, prefix, name) {
134
- if (!value) {
135
- return null;
122
+ function handleDuplicateRoutes(pluginsRouteConfigs, onDuplicateRoutes) {
123
+ if (onDuplicateRoutes === 'ignore') {
124
+ return;
136
125
  }
137
- if (Array.isArray(value)) {
138
- return value.map((val, index) => genRouteChunkNames(registry, val, `${index}`, name));
126
+ const allRoutes = (0, utils_2.getAllFinalRoutes)(pluginsRouteConfigs).map((routeConfig) => routeConfig.path);
127
+ const seenRoutes = new Set();
128
+ const duplicatePaths = allRoutes.filter((route) => {
129
+ if (seenRoutes.has(route)) {
130
+ return true;
131
+ }
132
+ seenRoutes.add(route);
133
+ return false;
134
+ });
135
+ if (duplicatePaths.length > 0) {
136
+ const finalMessage = `Duplicate routes found!
137
+ ${duplicatePaths
138
+ .map((duplicateRoute) => `- Attempting to create page at ${duplicateRoute}, but a page already exists at this route.`)
139
+ .join('\n')}
140
+ This could lead to non-deterministic routing behavior.`;
141
+ (0, utils_1.reportMessage)(finalMessage, onDuplicateRoutes);
139
142
  }
140
- if (isModule(value)) {
141
- const modulePath = getModulePath(value);
142
- const chunkName = (0, utils_1.genChunkName)(modulePath, prefix, name);
143
- const loader = `() => import(/* webpackChunkName: '${chunkName}' */ '${(0, utils_1.escapePath)(modulePath)}')`;
144
- registry[chunkName] = { loader, modulePath };
145
- return chunkName;
143
+ }
144
+ exports.handleDuplicateRoutes = handleDuplicateRoutes;
145
+ /**
146
+ * This is the higher level overview of route code generation. For each route
147
+ * config node, it returns the node's serialized form, and mutates `registry`,
148
+ * `routesPaths`, and `routesChunkNames` accordingly.
149
+ */
150
+ function genRouteCode(routeConfig, res) {
151
+ const { path: routePath, component, modules = {}, context, routes: subroutes, priority, exact, ...props } = routeConfig;
152
+ if (typeof routePath !== 'string' || !component) {
153
+ throw new Error(`Invalid route config: path must be a string and component is required.
154
+ ${JSON.stringify(routeConfig)}`);
146
155
  }
147
- const newValue = {};
148
- Object.entries(value).forEach(([key, v]) => {
149
- newValue[key] = genRouteChunkNames(registry, v, key, name);
156
+ if (!subroutes) {
157
+ res.routesPaths.push(routePath);
158
+ }
159
+ const routeHash = (0, utils_1.simpleHash)(JSON.stringify(routeConfig), 3);
160
+ res.routesChunkNames[`${routePath}-${routeHash}`] = {
161
+ // Avoid clash with a prop called "component"
162
+ ...genChunkNames({ __comp: component }, 'component', component, res),
163
+ ...(context &&
164
+ genChunkNames({ __context: context }, 'context', routePath, res)),
165
+ ...genChunkNames(modules, 'module', routePath, res),
166
+ };
167
+ return serializeRouteConfig({
168
+ routePath: routePath.replace(/'/g, "\\'"),
169
+ routeHash,
170
+ subroutesCodeStrings: subroutes?.map((r) => genRouteCode(r, res)),
171
+ exact,
172
+ props,
150
173
  });
151
- return newValue;
152
174
  }
175
+ /**
176
+ * Routes are prepared into three temp files:
177
+ *
178
+ * - `routesConfig`, the route config passed to react-router. This file is kept
179
+ * minimal, because it can't be code-splitted.
180
+ * - `routesChunkNames`, a mapping from route paths (hashed) to code-splitted
181
+ * chunk names.
182
+ * - `registry`, a mapping from chunk names to options for react-loadable.
183
+ */
184
+ function loadRoutes(routeConfigs, baseUrl, onDuplicateRoutes) {
185
+ handleDuplicateRoutes(routeConfigs, onDuplicateRoutes);
186
+ const res = {
187
+ // To be written by `genRouteCode`
188
+ routesConfig: '',
189
+ routesChunkNames: {},
190
+ registry: {},
191
+ routesPaths: [(0, utils_1.normalizeUrl)([baseUrl, '404.html'])],
192
+ };
193
+ // `genRouteCode` would mutate `res`
194
+ const routeConfigSerialized = routeConfigs
195
+ .map((r) => genRouteCode(r, res))
196
+ .join(',\n');
197
+ res.routesConfig = `import React from 'react';
198
+ import ComponentCreator from '@docusaurus/ComponentCreator';
199
+
200
+ export default [
201
+ ${indent(routeConfigSerialized)},
202
+ {
203
+ path: '*',
204
+ component: ComponentCreator('*'),
205
+ },
206
+ ];
207
+ `;
208
+ return res;
209
+ }
210
+ exports.loadRoutes = loadRoutes;
@@ -4,6 +4,9 @@
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 type { PluginVersionInformation } from '@docusaurus/types';
8
- export declare function getPackageJsonVersion(packageJsonPath: string): Promise<string | undefined>;
7
+ import type { LoadedPlugin, PluginVersionInformation, SiteMetadata } from '@docusaurus/types';
9
8
  export declare function getPluginVersion(pluginPath: string, siteDir: string): Promise<PluginVersionInformation>;
9
+ export declare function loadSiteMetadata({ plugins, siteDir, }: {
10
+ plugins: LoadedPlugin[];
11
+ siteDir: string;
12
+ }): Promise<SiteMetadata>;
@@ -6,10 +6,12 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.getPluginVersion = exports.getPackageJsonVersion = void 0;
9
+ exports.loadSiteMetadata = exports.getPluginVersion = void 0;
10
10
  const tslib_1 = require("tslib");
11
+ const utils_1 = require("@docusaurus/utils");
11
12
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
13
  const path_1 = tslib_1.__importDefault(require("path"));
14
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
13
15
  async function getPackageJsonVersion(packageJsonPath) {
14
16
  if (await fs_extra_1.default.pathExists(packageJsonPath)) {
15
17
  // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-dynamic-require, global-require
@@ -17,7 +19,6 @@ async function getPackageJsonVersion(packageJsonPath) {
17
19
  }
18
20
  return undefined;
19
21
  }
20
- exports.getPackageJsonVersion = getPackageJsonVersion;
21
22
  async function getPackageJsonName(packageJsonPath) {
22
23
  // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-dynamic-require, global-require
23
24
  return require(packageJsonPath).name;
@@ -42,7 +43,39 @@ async function getPluginVersion(pluginPath, siteDir) {
42
43
  potentialPluginPackageJsonDirectory = path_1.default.dirname(potentialPluginPackageJsonDirectory);
43
44
  }
44
45
  // In the case where a plugin is a path where no parent directory contains
45
- // package.json (e.g. inline plugin), we can only classify it as local.
46
+ // package.json, we can only classify it as local. Could happen if one puts a
47
+ // script in the parent directory of the site.
46
48
  return { type: 'local' };
47
49
  }
48
50
  exports.getPluginVersion = getPluginVersion;
51
+ /**
52
+ * We want all `@docusaurus/*` packages to have the exact same version!
53
+ * @see https://github.com/facebook/docusaurus/issues/3371
54
+ * @see https://github.com/facebook/docusaurus/pull/3386
55
+ */
56
+ function checkDocusaurusPackagesVersion(siteMetadata) {
57
+ const { docusaurusVersion } = siteMetadata;
58
+ Object.entries(siteMetadata.pluginVersions).forEach(([plugin, versionInfo]) => {
59
+ if (versionInfo.type === 'package' &&
60
+ versionInfo.name?.startsWith('@docusaurus/') &&
61
+ versionInfo.version &&
62
+ versionInfo.version !== docusaurusVersion) {
63
+ // Should we throw instead? It still could work with different versions
64
+ logger_1.default.error `Invalid name=${plugin} version number=${versionInfo.version}.
65
+ All official @docusaurus/* packages should have the exact same version as @docusaurus/core (number=${docusaurusVersion}).
66
+ Maybe you want to check, or regenerate your yarn.lock or package-lock.json file?`;
67
+ }
68
+ });
69
+ }
70
+ async function loadSiteMetadata({ plugins, siteDir, }) {
71
+ const siteMetadata = {
72
+ docusaurusVersion: utils_1.DOCUSAURUS_VERSION,
73
+ siteVersion: await getPackageJsonVersion(path_1.default.join(siteDir, 'package.json')),
74
+ pluginVersions: Object.fromEntries(plugins
75
+ .filter(({ version: { type } }) => type !== 'synthetic')
76
+ .map(({ name, version }) => [name, version])),
77
+ };
78
+ checkDocusaurusPackagesVersion(siteMetadata);
79
+ return siteMetadata;
80
+ }
81
+ exports.loadSiteMetadata = loadSiteMetadata;
@@ -4,7 +4,7 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import type { TranslationFileContent, TranslationFile, TranslationMessage, InitializedPlugin } from '@docusaurus/types';
7
+ import type { TranslationFileContent, TranslationFile, CodeTranslations, InitializedPlugin } from '@docusaurus/types';
8
8
  export declare type WriteTranslationsOptions = {
9
9
  override?: boolean;
10
10
  messagePrefix?: string;
@@ -25,17 +25,9 @@ export declare function localizePluginTranslationFile({ siteDir, plugin, locale,
25
25
  plugin: InitializedPlugin;
26
26
  translationFile: TranslationFile;
27
27
  }): Promise<TranslationFile>;
28
- export declare function getPluginsDefaultCodeTranslationMessages(plugins: InitializedPlugin[]): Promise<{
29
- [msgId: string]: string;
30
- }>;
28
+ export declare function getPluginsDefaultCodeTranslationMessages(plugins: InitializedPlugin[]): Promise<CodeTranslations>;
31
29
  export declare function applyDefaultCodeTranslations({ extractedCodeTranslations, defaultCodeMessages, }: {
32
- extractedCodeTranslations: {
33
- [msgId: string]: TranslationMessage;
34
- };
35
- defaultCodeMessages: {
36
- [msgId: string]: string;
37
- };
38
- }): {
39
- [msgId: string]: TranslationMessage;
40
- };
30
+ extractedCodeTranslations: TranslationFileContent;
31
+ defaultCodeMessages: CodeTranslations;
32
+ }): TranslationFileContent;
41
33
  export {};