@docusaurus/core 2.0.0-beta.16 → 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 (171) hide show
  1. package/bin/beforeCli.mjs +14 -12
  2. package/bin/docusaurus.mjs +41 -93
  3. package/lib/babel/preset.js +2 -2
  4. package/lib/client/.eslintrc.js +2 -3
  5. package/lib/client/App.d.ts +1 -1
  6. package/lib/client/App.js +15 -7
  7. package/lib/client/{baseUrlIssueBanner/BaseUrlIssueBanner.d.ts → BaseUrlIssueBanner/index.d.ts} +10 -5
  8. package/lib/client/{baseUrlIssueBanner/BaseUrlIssueBanner.js → BaseUrlIssueBanner/index.js} +14 -9
  9. package/lib/client/{baseUrlIssueBanner → BaseUrlIssueBanner}/styles.module.css +0 -0
  10. package/lib/client/ClientLifecyclesDispatcher.d.ts +16 -0
  11. package/lib/client/ClientLifecyclesDispatcher.js +34 -0
  12. package/lib/client/LinksCollector.d.ts +1 -1
  13. package/lib/client/LinksCollector.js +4 -5
  14. package/lib/client/PendingNavigation.d.ts +8 -17
  15. package/lib/client/PendingNavigation.js +39 -70
  16. package/lib/{server/loadSetup.d.ts → client/SiteMetadataDefaults.d.ts} +2 -2
  17. package/lib/client/SiteMetadataDefaults.js +19 -0
  18. package/lib/client/{exports/browserContext.d.ts → browserContext.d.ts} +0 -0
  19. package/lib/client/{exports/browserContext.js → browserContext.js} +0 -0
  20. package/lib/client/clientEntry.js +3 -4
  21. package/lib/client/docusaurus.d.ts +5 -5
  22. package/lib/client/docusaurus.js +26 -33
  23. package/lib/client/{exports/docusaurusContext.d.ts → docusaurusContext.d.ts} +0 -0
  24. package/lib/client/{exports/docusaurusContext.js → docusaurusContext.js} +0 -0
  25. package/lib/client/exports/BrowserOnly.d.ts +3 -4
  26. package/lib/client/exports/BrowserOnly.js +2 -2
  27. package/lib/client/exports/ComponentCreator.js +65 -40
  28. package/lib/client/exports/ErrorBoundary.d.ts +2 -2
  29. package/lib/client/exports/ErrorBoundary.js +4 -5
  30. package/lib/client/exports/Interpolate.d.ts +1 -1
  31. package/lib/client/exports/Interpolate.js +18 -41
  32. package/lib/client/exports/Link.d.ts +3 -15
  33. package/lib/client/exports/Link.js +24 -30
  34. package/lib/client/exports/Translate.d.ts +2 -2
  35. package/lib/client/exports/Translate.js +3 -3
  36. package/lib/client/exports/useBaseUrl.js +8 -9
  37. package/lib/client/exports/useDocusaurusContext.js +1 -1
  38. package/lib/client/exports/useGlobalData.d.ts +4 -3
  39. package/lib/client/exports/useGlobalData.js +5 -5
  40. package/lib/client/exports/useIsBrowser.js +1 -1
  41. package/lib/{server/client-modules/index.d.ts → client/exports/useRouteContext.d.ts} +2 -2
  42. package/lib/client/exports/useRouteContext.js +15 -0
  43. package/lib/client/flat.d.ts +12 -2
  44. package/lib/client/flat.js +12 -5
  45. package/lib/client/normalizeLocation.js +13 -8
  46. package/lib/client/prefetch.js +10 -28
  47. package/lib/client/preload.d.ts +1 -3
  48. package/lib/client/preload.js +5 -11
  49. package/lib/client/routeContext.d.ts +13 -0
  50. package/lib/client/routeContext.js +31 -0
  51. package/lib/client/serverEntry.js +19 -18
  52. package/lib/client/theme-fallback/Error/index.js +7 -1
  53. package/lib/client/theme-fallback/Layout/index.d.ts +1 -1
  54. package/lib/client/theme-fallback/Layout/index.js +2 -17
  55. package/lib/client/theme-fallback/Loading/index.js +2 -0
  56. package/lib/client/theme-fallback/NotFound/index.js +13 -5
  57. package/lib/client/theme-fallback/Root/index.d.ts +4 -4
  58. package/lib/client/theme-fallback/Root/index.js +2 -1
  59. package/lib/{server/html-tags/htmlTags.d.ts → client/theme-fallback/SiteMetadata/index.d.ts} +2 -1
  60. package/lib/client/theme-fallback/SiteMetadata/index.js +10 -0
  61. package/lib/commands/build.d.ts +6 -2
  62. package/lib/commands/build.js +48 -30
  63. package/lib/commands/clear.d.ts +1 -1
  64. package/lib/commands/clear.js +6 -5
  65. package/lib/commands/deploy.d.ts +5 -5
  66. package/lib/commands/deploy.js +21 -45
  67. package/lib/commands/external.d.ts +1 -1
  68. package/lib/commands/external.js +6 -11
  69. package/lib/commands/serve.d.ts +7 -2
  70. package/lib/commands/serve.js +18 -19
  71. package/lib/commands/start.d.ts +8 -2
  72. package/lib/commands/start.js +33 -30
  73. package/lib/commands/swizzle/actions.d.ts +2 -2
  74. package/lib/commands/swizzle/actions.js +10 -10
  75. package/lib/commands/swizzle/common.d.ts +3 -3
  76. package/lib/commands/swizzle/common.js +8 -9
  77. package/lib/commands/swizzle/components.js +48 -13
  78. package/lib/commands/swizzle/config.js +21 -15
  79. package/lib/commands/swizzle/context.js +6 -12
  80. package/lib/commands/swizzle/index.d.ts +2 -2
  81. package/lib/commands/swizzle/index.js +5 -4
  82. package/lib/commands/swizzle/prompts.js +2 -2
  83. package/lib/commands/swizzle/tables.js +10 -13
  84. package/lib/commands/swizzle/themes.js +9 -8
  85. package/lib/commands/writeHeadingIds.d.ts +2 -9
  86. package/lib/commands/writeHeadingIds.js +11 -69
  87. package/lib/commands/writeTranslations.d.ts +3 -4
  88. package/lib/commands/writeTranslations.js +10 -14
  89. package/lib/index.d.ts +9 -10
  90. package/lib/index.js +18 -19
  91. package/lib/server/brokenLinks.d.ts +3 -16
  92. package/lib/server/brokenLinks.js +37 -31
  93. package/lib/server/clientModules.d.ts +12 -0
  94. package/lib/server/clientModules.js +20 -0
  95. package/lib/server/config.d.ts +5 -2
  96. package/lib/server/config.js +14 -9
  97. package/lib/server/configValidation.d.ts +1 -1
  98. package/lib/server/configValidation.js +39 -13
  99. package/lib/server/getHostPort.d.ts +14 -0
  100. package/lib/{choosePort.js → server/getHostPort.js} +24 -41
  101. package/lib/server/htmlTags.d.ts +12 -0
  102. package/lib/server/htmlTags.js +62 -0
  103. package/lib/server/i18n.d.ts +2 -11
  104. package/lib/server/i18n.js +7 -28
  105. package/lib/server/index.d.ts +28 -13
  106. package/lib/server/index.js +62 -229
  107. package/lib/server/plugins/configs.d.ts +51 -0
  108. package/lib/server/plugins/configs.js +101 -0
  109. package/lib/server/plugins/index.d.ts +9 -8
  110. package/lib/server/plugins/index.js +65 -132
  111. package/lib/server/plugins/init.d.ts +6 -15
  112. package/lib/server/plugins/init.js +25 -83
  113. package/lib/server/{moduleShorthand.d.ts → plugins/moduleShorthand.d.ts} +0 -0
  114. package/lib/server/{moduleShorthand.js → plugins/moduleShorthand.js} +0 -0
  115. package/lib/server/plugins/pluginIds.d.ts +4 -0
  116. package/lib/server/plugins/pluginIds.js +6 -4
  117. package/lib/server/plugins/presets.d.ts +12 -0
  118. package/lib/server/{presets/index.js → plugins/presets.js} +21 -20
  119. package/lib/server/plugins/{applyRouteTrailingSlash.d.ts → routeConfig.d.ts} +3 -1
  120. package/lib/server/plugins/routeConfig.js +54 -0
  121. package/lib/server/plugins/synthetic.d.ts +20 -0
  122. package/lib/server/plugins/synthetic.js +112 -0
  123. package/lib/server/routes.d.ts +39 -7
  124. package/lib/server/routes.js +169 -102
  125. package/lib/server/siteMetadata.d.ts +12 -0
  126. package/lib/server/siteMetadata.js +81 -0
  127. package/lib/server/translations/translations.d.ts +5 -14
  128. package/lib/server/translations/translations.js +23 -39
  129. package/lib/server/translations/translationsExtractor.d.ts +2 -2
  130. package/lib/server/translations/translationsExtractor.js +16 -19
  131. package/lib/server/utils.js +1 -1
  132. package/lib/webpack/aliases/index.d.ts +34 -0
  133. package/lib/webpack/aliases/index.js +106 -0
  134. package/lib/webpack/base.d.ts +0 -1
  135. package/lib/webpack/base.js +12 -30
  136. package/lib/webpack/client.js +7 -8
  137. package/lib/webpack/plugins/ChunkAssetPlugin.js +7 -7
  138. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +2 -2
  139. package/lib/webpack/plugins/CleanWebpackPlugin.js +2 -2
  140. package/lib/webpack/plugins/LogPlugin.js +2 -2
  141. package/lib/webpack/plugins/WaitPlugin.d.ts +2 -2
  142. package/lib/webpack/plugins/WaitPlugin.js +3 -3
  143. package/lib/webpack/server.d.ts +2 -2
  144. package/lib/webpack/server.js +10 -8
  145. package/lib/webpack/utils.d.ts +9 -3
  146. package/lib/webpack/utils.js +20 -25
  147. package/package.json +38 -41
  148. package/lib/choosePort.d.ts +0 -11
  149. package/lib/client/client-lifecycles-dispatcher.d.ts +0 -9
  150. package/lib/client/client-lifecycles-dispatcher.js +0 -23
  151. package/lib/client/nprogress.css +0 -36
  152. package/lib/commands/commandUtils.d.ts +0 -9
  153. package/lib/commands/commandUtils.js +0 -21
  154. package/lib/server/client-modules/index.js +0 -12
  155. package/lib/server/duplicateRoutes.d.ts +0 -10
  156. package/lib/server/duplicateRoutes.js +0 -42
  157. package/lib/server/html-tags/htmlTags.js +0 -38
  158. package/lib/server/html-tags/index.d.ts +0 -9
  159. package/lib/server/html-tags/index.js +0 -43
  160. package/lib/server/loadSetup.js +0 -25
  161. package/lib/server/plugins/applyRouteTrailingSlash.js +0 -19
  162. package/lib/server/presets/index.d.ts +0 -11
  163. package/lib/server/themes/alias.d.ts +0 -9
  164. package/lib/server/themes/alias.js +0 -48
  165. package/lib/server/themes/index.d.ts +0 -12
  166. package/lib/server/themes/index.js +0 -47
  167. package/lib/server/versions/__fixtures__/dummy-plugin.d.ts +0 -0
  168. package/lib/server/versions/__fixtures__/dummy-plugin.js +0 -0
  169. package/lib/server/versions/__fixtures__/package.json +0 -3
  170. package/lib/server/versions/index.d.ts +0 -9
  171. package/lib/server/versions/index.js +0 -51
@@ -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,16 +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';
7
+ import type { RouteConfig, RouteChunkNames, ReportingSeverity } from '@docusaurus/types';
8
8
  declare type LoadedRoutes = {
9
- registry: {
10
- [chunkName: string]: ChunkRegistry;
11
- };
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
  };
18
- export default function loadRoutes(pluginsRouteConfigs: RouteConfig[], baseUrl: string): Promise<LoadedRoutes>;
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;
19
51
  export {};
@@ -6,138 +6,205 @@
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
- const 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]) => {
29
- // Figure out how to "unquote" JS attributes that don't need to be quoted
30
- // Is this lib reliable? https://github.com/armanozak/should-quote
31
- const shouldQuote = true; // TODO
32
- const key = shouldQuote ? `'${propName}'` : propName;
70
+ // Inspired by https://github.com/armanozak/should-quote/blob/main/packages/should-quote/src/lib/should-quote.ts
71
+ const shouldQuote = ((key) => {
72
+ // Pre-sanitation to prevent injection
73
+ if (/[.,;:}/\s]/.test(key)) {
74
+ return true;
75
+ }
76
+ try {
77
+ // If this key can be used in an expression like ({a:0}).a
78
+ // eslint-disable-next-line no-eval
79
+ eval(`({${key}:0}).${key}`);
80
+ return false;
81
+ }
82
+ catch {
83
+ return true;
84
+ }
85
+ })(propName);
86
+ // Escape quotes as well
87
+ const key = shouldQuote ? JSON.stringify(propName) : propName;
33
88
  parts.push(`${key}: ${JSON.stringify(propValue)}`);
34
89
  });
35
90
  return `{
36
91
  ${indent(parts.join(',\n'))}
37
92
  }`;
38
- };
39
- const NotFoundRouteCode = `{
40
- path: '*',
41
- component: ComponentCreator('*')
42
- }`;
43
- const RoutesImportsCode = [
44
- `import React from 'react';`,
45
- `import ComponentCreator from '@docusaurus/ComponentCreator';`,
46
- ].join('\n');
47
- function isModule(value) {
48
- var _a, _b;
49
- if (typeof value === 'string') {
50
- return true;
51
- }
52
- if (typeof value === 'object' &&
53
- (
54
- // eslint-disable-next-line no-underscore-dangle
55
- (_a = value) === null || _a === void 0 ? void 0 : _a.__import) &&
56
- ((_b = value) === null || _b === void 0 ? void 0 : _b.path)) {
57
- return true;
58
- }
59
- return false;
60
93
  }
94
+ const isModule = (value) => typeof value === 'string' ||
95
+ (typeof value === 'object' &&
96
+ // eslint-disable-next-line no-underscore-dangle
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
+ */
61
102
  function getModulePath(target) {
62
103
  if (typeof target === 'string') {
63
104
  return target;
64
105
  }
65
- const queryStr = target.query ? `?${(0, querystring_1.stringify)(target.query)}` : '';
106
+ const queryStr = target.query ? `?${querystring_1.default.stringify(target.query)}` : '';
66
107
  return `${target.path}${queryStr}`;
67
108
  }
68
- async function loadRoutes(pluginsRouteConfigs, baseUrl) {
69
- const registry = {};
70
- const routesPaths = [(0, utils_1.normalizeUrl)([baseUrl, '404.html'])];
71
- const routesChunkNames = {};
72
- // This is the higher level overview of route code generation.
73
- function generateRouteCode(routeConfig) {
74
- const { path: routePath, component, modules = {}, routes: subroutes, exact, priority, ...props } = routeConfig;
75
- if (typeof routePath !== 'string' || !component) {
76
- throw new Error(`Invalid route config: path must be a string and component is required.
77
- ${JSON.stringify(routeConfig)}`);
78
- }
79
- // Collect all page paths for injecting it later in the plugin lifecycle
80
- // This is useful for plugins like sitemaps, redirects etc...
81
- // If a route has subroutes, it is not necessarily a valid page path (more
82
- // likely to be a wrapper)
83
- if (!subroutes) {
84
- routesPaths.push(routePath);
85
- }
86
- // We hash the route to generate the key, because 2 routes can conflict with
87
- // each others if they have the same path, ex: parent=/docs, child=/docs
88
- // see https://github.com/facebook/docusaurus/issues/2917
89
- const routeHash = (0, utils_1.simpleHash)(JSON.stringify(routeConfig), 3);
90
- const chunkNamesKey = `${routePath}-${routeHash}`;
91
- routesChunkNames[chunkNamesKey] = {
92
- ...genRouteChunkNames(registry, { component }, 'component', component),
93
- ...genRouteChunkNames(registry, modules, 'module', routePath),
94
- };
95
- return createRouteCodeString({
96
- routePath: routeConfig.path.replace(/'/g, "\\'"),
97
- routeHash,
98
- exact,
99
- subroutesCodeStrings: subroutes === null || subroutes === void 0 ? void 0 : subroutes.map(generateRouteCode),
100
- props,
101
- });
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;
102
116
  }
103
- const routesConfig = `
104
- ${RoutesImportsCode}
105
-
106
- export default [
107
- ${indent(`${pluginsRouteConfigs.map(generateRouteCode).join(',\n')},`)}
108
- ${indent(NotFoundRouteCode)}
109
- ];
110
- `;
111
- return {
112
- registry,
113
- routesConfig,
114
- routesChunkNames,
115
- routesPaths,
116
- };
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));
117
121
  }
118
- exports.default = loadRoutes;
119
- function genRouteChunkNames(
120
- // TODO instead of passing a mutating the registry, return a registry slice?
121
- registry, value, prefix, name) {
122
- if (!value) {
123
- return null;
122
+ function handleDuplicateRoutes(pluginsRouteConfigs, onDuplicateRoutes) {
123
+ if (onDuplicateRoutes === 'ignore') {
124
+ return;
124
125
  }
125
- if (Array.isArray(value)) {
126
- 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);
127
142
  }
128
- if (isModule(value)) {
129
- const modulePath = getModulePath(value);
130
- const chunkName = (0, utils_1.genChunkName)(modulePath, prefix, name);
131
- const loader = `() => import(/* webpackChunkName: '${chunkName}' */ '${(0, utils_1.escapePath)(modulePath)}')`;
132
- registry[chunkName] = {
133
- loader,
134
- modulePath,
135
- };
136
- 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)}`);
137
155
  }
138
- const newValue = {};
139
- Object.keys(value).forEach((key) => {
140
- newValue[key] = genRouteChunkNames(registry, value[key], 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,
141
173
  });
142
- return newValue;
143
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;
@@ -0,0 +1,12 @@
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, PluginVersionInformation, SiteMetadata } from '@docusaurus/types';
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>;
@@ -0,0 +1,81 @@
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.loadSiteMetadata = exports.getPluginVersion = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const utils_1 = require("@docusaurus/utils");
12
+ const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
13
+ const path_1 = tslib_1.__importDefault(require("path"));
14
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
15
+ async function getPackageJsonVersion(packageJsonPath) {
16
+ if (await fs_extra_1.default.pathExists(packageJsonPath)) {
17
+ // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-dynamic-require, global-require
18
+ return require(packageJsonPath).version;
19
+ }
20
+ return undefined;
21
+ }
22
+ async function getPackageJsonName(packageJsonPath) {
23
+ // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-dynamic-require, global-require
24
+ return require(packageJsonPath).name;
25
+ }
26
+ async function getPluginVersion(pluginPath, siteDir) {
27
+ let potentialPluginPackageJsonDirectory = path_1.default.dirname(pluginPath);
28
+ while (potentialPluginPackageJsonDirectory !== '/') {
29
+ const packageJsonPath = path_1.default.join(potentialPluginPackageJsonDirectory, 'package.json');
30
+ if ((await fs_extra_1.default.pathExists(packageJsonPath)) &&
31
+ (await fs_extra_1.default.lstat(packageJsonPath)).isFile()) {
32
+ if (potentialPluginPackageJsonDirectory === siteDir) {
33
+ // If the plugin belongs to the same docusaurus project, we classify it
34
+ // as local plugin.
35
+ return { type: 'project' };
36
+ }
37
+ return {
38
+ type: 'package',
39
+ name: await getPackageJsonName(packageJsonPath),
40
+ version: await getPackageJsonVersion(packageJsonPath),
41
+ };
42
+ }
43
+ potentialPluginPackageJsonDirectory = path_1.default.dirname(potentialPluginPackageJsonDirectory);
44
+ }
45
+ // In the case where a plugin is a path where no parent directory contains
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.
48
+ return { type: 'local' };
49
+ }
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;
@@ -13,16 +13,7 @@ declare type TranslationContext = {
13
13
  siteDir: string;
14
14
  locale: string;
15
15
  };
16
- export declare function ensureTranslationFileContent(content: unknown): asserts content is TranslationFileContent;
17
- export declare function readTranslationFileContent(filePath: string): Promise<TranslationFileContent | undefined>;
18
- export declare function writeTranslationFileContent({ filePath, content: newContent, options, }: {
19
- filePath: string;
20
- content: TranslationFileContent;
21
- options?: WriteTranslationsOptions;
22
- }): Promise<void>;
23
- export declare function getTranslationsDirPath(context: TranslationContext): string;
24
16
  export declare function getTranslationsLocaleDirPath(context: TranslationContext): string;
25
- export declare function getCodeTranslationsFilePath(context: TranslationContext): string;
26
17
  export declare function readCodeTranslationFileContent(context: TranslationContext): Promise<TranslationFileContent | undefined>;
27
18
  export declare function writeCodeTranslations(context: TranslationContext, content: TranslationFileContent, options: WriteTranslationsOptions): Promise<void>;
28
19
  export declare function writePluginTranslations({ siteDir, plugin, locale, translationFile, options, }: TranslationContext & {
@@ -34,9 +25,9 @@ export declare function localizePluginTranslationFile({ siteDir, plugin, locale,
34
25
  plugin: InitializedPlugin;
35
26
  translationFile: TranslationFile;
36
27
  }): Promise<TranslationFile>;
37
- export declare function getPluginsDefaultCodeTranslationMessages(plugins: InitializedPlugin[]): Promise<Record<string, string>>;
28
+ export declare function getPluginsDefaultCodeTranslationMessages(plugins: InitializedPlugin[]): Promise<CodeTranslations>;
38
29
  export declare function applyDefaultCodeTranslations({ extractedCodeTranslations, defaultCodeMessages, }: {
39
- extractedCodeTranslations: Record<string, TranslationMessage>;
40
- defaultCodeMessages: Record<string, string>;
41
- }): Record<string, TranslationMessage>;
30
+ extractedCodeTranslations: TranslationFileContent;
31
+ defaultCodeMessages: CodeTranslations;
32
+ }): TranslationFileContent;
42
33
  export {};