@docusaurus/core 2.0.0-beta.2 → 2.0.0-beta.22

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 (223) hide show
  1. package/README.md +1 -0
  2. package/bin/beforeCli.mjs +140 -0
  3. package/bin/docusaurus.mjs +221 -0
  4. package/lib/babel/preset.d.ts +8 -3
  5. package/lib/babel/preset.js +10 -8
  6. package/lib/client/App.d.ts +2 -3
  7. package/lib/client/App.js +31 -28
  8. package/lib/client/BaseUrlIssueBanner/index.d.ts +27 -0
  9. package/lib/client/{baseUrlIssueBanner/BaseUrlIssueBanner.js → BaseUrlIssueBanner/index.js} +25 -14
  10. package/lib/client/{baseUrlIssueBanner → BaseUrlIssueBanner}/styles.module.css +0 -0
  11. package/lib/client/ClientLifecyclesDispatcher.d.ts +16 -0
  12. package/lib/client/ClientLifecyclesDispatcher.js +39 -0
  13. package/lib/client/LinksCollector.d.ts +3 -3
  14. package/lib/client/LinksCollector.js +8 -13
  15. package/lib/client/PendingNavigation.d.ts +17 -3
  16. package/lib/client/PendingNavigation.js +47 -72
  17. package/lib/client/{baseUrlIssueBanner/BaseUrlIssueBanner.d.ts → SiteMetadataDefaults.d.ts} +1 -2
  18. package/lib/client/SiteMetadataDefaults.js +21 -0
  19. package/lib/{choosePort.d.ts → client/browserContext.d.ts} +5 -5
  20. package/lib/client/browserContext.js +22 -0
  21. package/lib/client/clientEntry.js +14 -9
  22. package/lib/client/docusaurus.d.ts +12 -6
  23. package/lib/client/docusaurus.js +30 -43
  24. package/lib/client/docusaurusContext.d.ts +12 -0
  25. package/lib/client/docusaurusContext.js +25 -0
  26. package/lib/client/exports/BrowserOnly.d.ts +3 -5
  27. package/lib/client/exports/BrowserOnly.js +14 -8
  28. package/lib/client/exports/ComponentCreator.d.ts +6 -2
  29. package/lib/client/exports/ComponentCreator.js +75 -42
  30. package/lib/client/exports/ErrorBoundary.d.ts +18 -0
  31. package/lib/client/exports/ErrorBoundary.js +37 -0
  32. package/lib/client/exports/Head.d.ts +2 -3
  33. package/lib/client/exports/Head.js +3 -4
  34. package/lib/client/exports/Interpolate.d.ts +2 -2
  35. package/lib/client/exports/Interpolate.js +20 -49
  36. package/lib/client/exports/Link.d.ts +4 -10
  37. package/lib/client/exports/Link.js +40 -40
  38. package/lib/client/exports/Translate.d.ts +1 -1
  39. package/lib/client/exports/Translate.js +14 -9
  40. package/lib/client/exports/constants.js +1 -11
  41. package/lib/client/exports/isInternalUrl.js +1 -1
  42. package/lib/client/exports/renderRoutes.d.ts +1 -2
  43. package/lib/client/exports/renderRoutes.js +1 -2
  44. package/lib/client/exports/router.d.ts +1 -1
  45. package/lib/client/exports/router.js +1 -1
  46. package/lib/client/exports/useBaseUrl.js +11 -14
  47. package/lib/client/exports/useDocusaurusContext.d.ts +2 -3
  48. package/lib/client/exports/useDocusaurusContext.js +3 -9
  49. package/lib/client/exports/useGlobalData.d.ts +4 -3
  50. package/lib/client/exports/useGlobalData.js +6 -13
  51. package/lib/{server/versions/__tests/index.test.d.ts → client/exports/useIsBrowser.d.ts} +1 -1
  52. package/lib/client/exports/useIsBrowser.js +11 -0
  53. package/lib/client/exports/useRouteContext.d.ts +8 -0
  54. package/lib/client/exports/useRouteContext.js +15 -0
  55. package/lib/client/flat.d.ts +12 -2
  56. package/lib/client/flat.js +19 -15
  57. package/lib/client/normalizeLocation.d.ts +2 -5
  58. package/lib/client/normalizeLocation.js +14 -10
  59. package/lib/client/prefetch.d.ts +1 -2
  60. package/lib/client/prefetch.js +12 -32
  61. package/lib/client/preload.d.ts +3 -4
  62. package/lib/client/preload.js +5 -12
  63. package/lib/client/routeContext.d.ts +13 -0
  64. package/lib/client/routeContext.js +31 -0
  65. package/lib/client/serverEntry.d.ts +10 -0
  66. package/lib/client/serverEntry.js +108 -146
  67. package/lib/client/theme-fallback/Error/index.d.ts +10 -0
  68. package/lib/client/theme-fallback/Error/index.js +45 -0
  69. package/lib/client/theme-fallback/Layout/index.d.ts +10 -0
  70. package/lib/client/theme-fallback/Layout/index.js +2 -26
  71. package/lib/client/theme-fallback/Loading/index.d.ts +9 -0
  72. package/lib/client/theme-fallback/Loading/index.js +50 -116
  73. package/lib/client/{exports/context.js → theme-fallback/NotFound/index.d.ts} +2 -2
  74. package/lib/client/theme-fallback/NotFound/index.js +19 -18
  75. package/lib/client/theme-fallback/Root/index.d.ts +10 -0
  76. package/lib/client/theme-fallback/Root/index.js +2 -6
  77. package/lib/{server/html-tags/htmlTags.d.ts → client/theme-fallback/SiteMetadata/index.d.ts} +2 -1
  78. package/lib/client/theme-fallback/SiteMetadata/index.js +10 -0
  79. package/lib/commands/build.d.ts +6 -2
  80. package/lib/commands/build.js +81 -64
  81. package/lib/commands/clear.d.ts +7 -1
  82. package/lib/commands/clear.js +34 -21
  83. package/lib/commands/deploy.d.ts +5 -2
  84. package/lib/commands/deploy.js +104 -81
  85. package/lib/commands/external.d.ts +2 -2
  86. package/lib/commands/external.js +9 -11
  87. package/lib/commands/serve.d.ts +8 -2
  88. package/lib/commands/serve.js +29 -28
  89. package/lib/commands/start.d.ts +9 -2
  90. package/lib/commands/start.js +109 -101
  91. package/lib/commands/swizzle/actions.d.ts +23 -0
  92. package/lib/commands/swizzle/actions.js +101 -0
  93. package/lib/commands/swizzle/common.d.ts +33 -0
  94. package/lib/commands/swizzle/common.js +56 -0
  95. package/lib/commands/swizzle/components.d.ts +29 -0
  96. package/lib/commands/swizzle/components.js +200 -0
  97. package/lib/commands/swizzle/config.d.ts +10 -0
  98. package/lib/commands/swizzle/config.js +84 -0
  99. package/lib/{server/client-modules/index.d.ts → commands/swizzle/context.d.ts} +2 -2
  100. package/lib/commands/swizzle/context.js +24 -0
  101. package/lib/commands/swizzle/index.d.ts +8 -0
  102. package/lib/commands/swizzle/index.js +118 -0
  103. package/lib/commands/swizzle/prompts.d.ts +12 -0
  104. package/lib/commands/swizzle/prompts.js +110 -0
  105. package/lib/{client/exports/context.d.ts → commands/swizzle/tables.d.ts} +3 -4
  106. package/lib/commands/swizzle/tables.js +113 -0
  107. package/lib/commands/swizzle/themes.d.ts +20 -0
  108. package/lib/commands/swizzle/themes.js +106 -0
  109. package/lib/commands/writeHeadingIds.d.ts +2 -6
  110. package/lib/commands/writeHeadingIds.js +22 -81
  111. package/lib/commands/writeTranslations.d.ts +4 -5
  112. package/lib/commands/writeTranslations.js +46 -25
  113. package/lib/index.d.ts +9 -9
  114. package/lib/index.js +14 -14
  115. package/lib/server/brokenLinks.d.ts +4 -17
  116. package/lib/server/brokenLinks.js +67 -56
  117. package/lib/server/clientModules.d.ts +12 -0
  118. package/lib/server/clientModules.js +20 -0
  119. package/lib/server/config.d.ts +5 -2
  120. package/lib/server/config.js +29 -6
  121. package/lib/server/configValidation.d.ts +4 -4
  122. package/lib/server/configValidation.js +86 -41
  123. package/lib/server/getHostPort.d.ts +14 -0
  124. package/lib/server/getHostPort.js +79 -0
  125. package/lib/server/htmlTags.d.ts +12 -0
  126. package/lib/server/htmlTags.js +62 -0
  127. package/lib/server/i18n.d.ts +3 -13
  128. package/lib/server/i18n.js +21 -55
  129. package/lib/server/index.d.ts +28 -13
  130. package/lib/server/index.js +83 -165
  131. package/lib/server/plugins/configs.d.ts +51 -0
  132. package/lib/server/plugins/configs.js +101 -0
  133. package/lib/server/plugins/index.d.ts +9 -8
  134. package/lib/server/plugins/index.js +73 -134
  135. package/lib/server/plugins/init.d.ts +6 -5
  136. package/lib/server/plugins/init.js +44 -109
  137. package/lib/server/plugins/moduleShorthand.d.ts +9 -0
  138. package/lib/server/plugins/moduleShorthand.js +46 -0
  139. package/lib/server/plugins/pluginIds.d.ts +5 -1
  140. package/lib/server/plugins/pluginIds.js +12 -7
  141. package/lib/server/plugins/presets.d.ts +12 -0
  142. package/lib/server/plugins/presets.js +49 -0
  143. package/lib/server/plugins/routeConfig.d.ts +11 -0
  144. package/lib/server/plugins/routeConfig.js +54 -0
  145. package/lib/server/plugins/synthetic.d.ts +20 -0
  146. package/lib/server/plugins/synthetic.js +111 -0
  147. package/lib/server/routes.d.ts +39 -7
  148. package/lib/server/routes.js +182 -95
  149. package/lib/server/siteMetadata.d.ts +12 -0
  150. package/lib/server/siteMetadata.js +81 -0
  151. package/lib/server/translations/translations.d.ts +14 -19
  152. package/lib/server/translations/translations.js +40 -72
  153. package/lib/server/translations/translationsExtractor.d.ts +10 -4
  154. package/lib/server/translations/translationsExtractor.js +158 -122
  155. package/lib/server/utils.d.ts +9 -3
  156. package/lib/server/utils.js +7 -9
  157. package/lib/webpack/aliases/index.d.ts +34 -0
  158. package/lib/webpack/aliases/index.js +106 -0
  159. package/lib/webpack/base.d.ts +3 -4
  160. package/lib/webpack/base.js +45 -57
  161. package/lib/webpack/client.d.ts +3 -3
  162. package/lib/webpack/client.js +12 -19
  163. package/lib/webpack/plugins/ChunkAssetPlugin.d.ts +13 -3
  164. package/lib/webpack/plugins/ChunkAssetPlugin.js +24 -17
  165. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +6 -25
  166. package/lib/webpack/plugins/CleanWebpackPlugin.js +33 -17
  167. package/lib/webpack/plugins/LogPlugin.d.ts +1 -1
  168. package/lib/webpack/plugins/LogPlugin.js +4 -5
  169. package/lib/webpack/plugins/WaitPlugin.d.ts +3 -3
  170. package/lib/webpack/plugins/WaitPlugin.js +1 -1
  171. package/lib/webpack/server.d.ts +5 -5
  172. package/lib/webpack/server.js +22 -9
  173. package/lib/{client → webpack}/templates/index.html.template.ejs +0 -0
  174. package/lib/webpack/templates/ssr.html.template.d.ts +8 -0
  175. package/lib/{client → webpack}/templates/ssr.html.template.js +3 -2
  176. package/lib/webpack/utils.d.ts +15 -31
  177. package/lib/webpack/utils.js +61 -182
  178. package/package.json +81 -77
  179. package/bin/docusaurus.js +0 -325
  180. package/lib/.tsbuildinfo +0 -1
  181. package/lib/choosePort.js +0 -105
  182. package/lib/client/.eslintrc.js +0 -29
  183. package/lib/client/.tsbuildinfo +0 -1
  184. package/lib/client/client-lifecycles-dispatcher.d.ts +0 -12
  185. package/lib/client/client-lifecycles-dispatcher.js +0 -27
  186. package/lib/client/nprogress.css +0 -36
  187. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  188. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  189. package/lib/commands/commandUtils.d.ts +0 -3
  190. package/lib/commands/commandUtils.js +0 -21
  191. package/lib/commands/swizzle.d.ts +0 -9
  192. package/lib/commands/swizzle.js +0 -245
  193. package/lib/constants.d.ts +0 -18
  194. package/lib/constants.js +0 -23
  195. package/lib/server/client-modules/index.js +0 -14
  196. package/lib/server/duplicateRoutes.d.ts +0 -10
  197. package/lib/server/duplicateRoutes.js +0 -38
  198. package/lib/server/html-tags/htmlTags.js +0 -40
  199. package/lib/server/html-tags/index.d.ts +0 -9
  200. package/lib/server/html-tags/index.js +0 -43
  201. package/lib/server/loadSetup.d.ts +0 -9
  202. package/lib/server/loadSetup.js +0 -25
  203. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +0 -8
  204. package/lib/server/plugins/applyRouteTrailingSlash.js +0 -19
  205. package/lib/server/presets/index.d.ts +0 -11
  206. package/lib/server/presets/index.js +0 -48
  207. package/lib/server/themes/alias.d.ts +0 -8
  208. package/lib/server/themes/alias.js +0 -40
  209. package/lib/server/themes/index.d.ts +0 -12
  210. package/lib/server/themes/index.js +0 -47
  211. package/lib/server/versions/__fixtures__/dummy-plugin.js +0 -0
  212. package/lib/server/versions/__fixtures__/package.json +0 -3
  213. package/lib/server/versions/__tests/index.test.js +0 -25
  214. package/lib/server/versions/index.d.ts +0 -10
  215. package/lib/server/versions/index.js +0 -50
  216. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  217. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  218. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  219. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  220. package/lib/webpack/sharedModuleAliases.d.ts +0 -10
  221. package/lib/webpack/sharedModuleAliases.js +0 -18
  222. package/tsconfig.client.json +0 -13
  223. package/tsconfig.json +0 -13
@@ -1,22 +1,21 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractSourceCodeFileTranslations = exports.extractAllSourceCodeFileTranslations = exports.extractSiteSourceCodeTranslations = exports.globSourceCodeFilePaths = void 0;
4
- const tslib_1 = require("tslib");
5
2
  /**
6
3
  * Copyright (c) Facebook, Inc. and its affiliates.
7
4
  *
8
5
  * This source code is licensed under the MIT license found in the
9
6
  * LICENSE file in the root directory of this source tree.
10
7
  */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.extractSourceCodeFileTranslations = exports.extractAllSourceCodeFileTranslations = exports.extractSiteSourceCodeTranslations = exports.globSourceCodeFilePaths = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const path_1 = tslib_1.__importDefault(require("path"));
11
12
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
13
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
14
  const traverse_1 = tslib_1.__importDefault(require("@babel/traverse"));
13
15
  const generator_1 = tslib_1.__importDefault(require("@babel/generator"));
14
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
15
16
  const core_1 = require("@babel/core");
16
- const lodash_1 = require("lodash");
17
- const path_1 = tslib_1.__importDefault(require("path"));
18
- const constants_1 = require("../../constants");
19
- const utils_1 = require("../utils");
17
+ const utils_1 = require("@docusaurus/utils");
18
+ const utils_2 = require("../utils");
20
19
  // We only support extracting source code translations from these kind of files
21
20
  const TranslatableSourceCodeExtension = new Set([
22
21
  '.js',
@@ -24,7 +23,7 @@ const TranslatableSourceCodeExtension = new Set([
24
23
  '.ts',
25
24
  '.tsx',
26
25
  // TODO support md/mdx too? (may be overkill)
27
- // need to compile the MDX to JSX first and remove frontmatter
26
+ // need to compile the MDX to JSX first and remove front matter
28
27
  // '.md',
29
28
  // '.mdx',
30
29
  ]);
@@ -32,44 +31,48 @@ function isTranslatableSourceCodePath(filePath) {
32
31
  return TranslatableSourceCodeExtension.has(path_1.default.extname(filePath));
33
32
  }
34
33
  function getSiteSourceCodeFilePaths(siteDir) {
35
- return [path_1.default.join(siteDir, constants_1.SRC_DIR_NAME)];
34
+ return [path_1.default.join(siteDir, utils_1.SRC_DIR_NAME)];
36
35
  }
37
36
  function getPluginSourceCodeFilePaths(plugin) {
38
- var _a, _b, _c;
39
37
  // The getPathsToWatch() generally returns the js/jsx/ts/tsx/md/mdx file paths
40
- // We can use this method as well to know which folders we should try to extract translations from
41
- // Hacky/implicit, but do we want to introduce a new lifecycle method just for that???
42
- const codePaths = (_b = (_a = plugin.getPathsToWatch) === null || _a === void 0 ? void 0 : _a.call(plugin)) !== null && _b !== void 0 ? _b : [];
38
+ // We can use this method as well to know which folders we should try to
39
+ // extract translations from. Hacky/implicit, but do we want to introduce a
40
+ // new lifecycle method just for that???
41
+ const codePaths = plugin.getPathsToWatch?.() ?? [];
43
42
  // We also include theme code
44
- const themePath = (_c = plugin.getThemePath) === null || _c === void 0 ? void 0 : _c.call(plugin);
43
+ const themePath = plugin.getThemePath?.();
45
44
  if (themePath) {
46
45
  codePaths.push(themePath);
47
46
  }
48
- return codePaths;
47
+ return codePaths.map((p) => path_1.default.resolve(plugin.path, p));
49
48
  }
50
49
  async function globSourceCodeFilePaths(dirPaths) {
51
- const filePaths = await utils_1.safeGlobby(dirPaths);
50
+ const filePaths = await (0, utils_2.safeGlobby)(dirPaths);
52
51
  return filePaths.filter(isTranslatableSourceCodePath);
53
52
  }
54
53
  exports.globSourceCodeFilePaths = globSourceCodeFilePaths;
55
54
  async function getSourceCodeFilePaths(siteDir, plugins) {
56
55
  const sitePaths = getSiteSourceCodeFilePaths(siteDir);
57
56
  // The getPathsToWatch() generally returns the js/jsx/ts/tsx/md/mdx file paths
58
- // We can use this method as well to know which folders we should try to extract translations from
59
- // Hacky/implicit, but do we want to introduce a new lifecycle method for that???
60
- const pluginsPaths = lodash_1.flatten(plugins.map(getPluginSourceCodeFilePaths));
57
+ // We can use this method as well to know which folders we should try to
58
+ // extract translations from. Hacky/implicit, but do we want to introduce a
59
+ // new lifecycle method for that???
60
+ const pluginsPaths = plugins.flatMap(getPluginSourceCodeFilePaths);
61
61
  const allPaths = [...sitePaths, ...pluginsPaths];
62
62
  return globSourceCodeFilePaths(allPaths);
63
63
  }
64
- async function extractSiteSourceCodeTranslations(siteDir, plugins, babelOptions) {
65
- // Should we warn here if the same translation "key" is found in multiple source code files?
64
+ async function extractSiteSourceCodeTranslations(siteDir, plugins, babelOptions, extraSourceCodeFilePaths = []) {
65
+ // Should we warn here if the same translation "key" is found in multiple
66
+ // source code files?
66
67
  function toTranslationFileContent(sourceCodeFileTranslations) {
67
- return sourceCodeFileTranslations.reduce((acc, item) => {
68
- return { ...acc, ...item.translations };
69
- }, {});
68
+ return sourceCodeFileTranslations.reduce((acc, item) => ({ ...acc, ...item.translations }), {});
70
69
  }
71
70
  const sourceCodeFilePaths = await getSourceCodeFilePaths(siteDir, plugins);
72
- const sourceCodeFilesTranslations = await extractAllSourceCodeFileTranslations(sourceCodeFilePaths, babelOptions);
71
+ const allSourceCodeFilePaths = [
72
+ ...sourceCodeFilePaths,
73
+ ...extraSourceCodeFilePaths,
74
+ ];
75
+ const sourceCodeFilesTranslations = await extractAllSourceCodeFileTranslations(allSourceCodeFilePaths, babelOptions);
73
76
  logSourceCodeFileTranslationsWarnings(sourceCodeFilesTranslations);
74
77
  return toTranslationFileContent(sourceCodeFilesTranslations);
75
78
  }
@@ -77,29 +80,31 @@ exports.extractSiteSourceCodeTranslations = extractSiteSourceCodeTranslations;
77
80
  function logSourceCodeFileTranslationsWarnings(sourceCodeFilesTranslations) {
78
81
  sourceCodeFilesTranslations.forEach(({ sourceCodeFilePath, warnings }) => {
79
82
  if (warnings.length > 0) {
80
- console.warn(`Translation extraction warnings for file path=${sourceCodeFilePath}:\n- ${chalk_1.default.yellow(warnings.join('\n\n- '))}`);
83
+ logger_1.default.warn `Translation extraction warnings for file path=${sourceCodeFilePath}: ${warnings}`;
81
84
  }
82
85
  });
83
86
  }
84
87
  async function extractAllSourceCodeFileTranslations(sourceCodeFilePaths, babelOptions) {
85
- return lodash_1.flatten(await Promise.all(sourceCodeFilePaths.map((sourceFilePath) => extractSourceCodeFileTranslations(sourceFilePath, babelOptions))));
88
+ return Promise.all(sourceCodeFilePaths.flatMap((sourceFilePath) => extractSourceCodeFileTranslations(sourceFilePath, babelOptions)));
86
89
  }
87
90
  exports.extractAllSourceCodeFileTranslations = extractAllSourceCodeFileTranslations;
88
91
  async function extractSourceCodeFileTranslations(sourceCodeFilePath, babelOptions) {
89
92
  try {
90
93
  const code = await fs_extra_1.default.readFile(sourceCodeFilePath, 'utf8');
91
- const ast = core_1.parse(code, {
94
+ const ast = (0, core_1.parse)(code, {
92
95
  ...babelOptions,
93
96
  ast: true,
94
- // filename is important, because babel does not process the same files according to their js/ts extensions
95
- // see see https://twitter.com/NicoloRibaudo/status/1321130735605002243
97
+ // filename is important, because babel does not process the same files
98
+ // according to their js/ts extensions.
99
+ // See https://twitter.com/NicoloRibaudo/status/1321130735605002243
96
100
  filename: sourceCodeFilePath,
97
101
  });
98
- return await extractSourceCodeAstTranslations(ast, sourceCodeFilePath);
102
+ const translations = extractSourceCodeAstTranslations(ast, sourceCodeFilePath);
103
+ return translations;
99
104
  }
100
- catch (e) {
101
- e.message = `Error while attempting to extract Docusaurus translations from source code file at path=${sourceCodeFilePath}\n${e.message}`;
102
- throw e;
105
+ catch (err) {
106
+ logger_1.default.error `Error while attempting to extract Docusaurus translations from source code file at path=${sourceCodeFilePath}.`;
107
+ throw err;
103
108
  }
104
109
  }
105
110
  exports.extractSourceCodeFileTranslations = extractSourceCodeFileTranslations;
@@ -112,108 +117,139 @@ https://github.com/formatjs/formatjs/blob/main/packages/babel-plugin-formatjs/in
112
117
  https://github.com/pugjs/babel-walk
113
118
  */
114
119
  function extractSourceCodeAstTranslations(ast, sourceCodeFilePath) {
115
- function staticTranslateJSXWarningPart() {
116
- return 'Translate content could not be extracted.\nIt has to be a static string and use optional but static props, like <Translate id="my-id" description="my-description">text</Translate>.';
117
- }
118
- function sourceFileWarningPart(node) {
119
- var _a;
120
- return `File=${sourceCodeFilePath} at line=${(_a = node.loc) === null || _a === void 0 ? void 0 : _a.start.line}`;
121
- }
122
- function generateCode(node) {
123
- return generator_1.default(node).code;
120
+ function sourceWarningPart(node) {
121
+ return `File: ${sourceCodeFilePath} at line ${node.loc?.start.line ?? '?'}
122
+ Full code: ${(0, generator_1.default)(node).code}`;
124
123
  }
125
124
  const translations = {};
126
125
  const warnings = [];
127
- // TODO we should check the presence of the correct @docusaurus imports here!
128
- traverse_1.default(ast, {
129
- JSXElement(path) {
130
- if (!path
131
- .get('openingElement')
132
- .get('name')
133
- .isJSXIdentifier({ name: 'Translate' })) {
126
+ let translateComponentName;
127
+ let translateFunctionName;
128
+ // First pass: find import declarations of Translate / translate.
129
+ // If not found, don't process the rest to avoid false positives
130
+ (0, traverse_1.default)(ast, {
131
+ ImportDeclaration(path) {
132
+ if (path.node.importKind === 'type' ||
133
+ path.get('source').node.value !== '@docusaurus/Translate') {
134
134
  return;
135
135
  }
136
- function evaluateJSXProp(propName) {
137
- const attributePath = path
138
- .get('openingElement.attributes')
139
- .find((attr) => attr.isJSXAttribute() &&
140
- attr
141
- .get('name')
142
- .isJSXIdentifier({ name: propName }));
143
- if (attributePath) {
144
- const attributeValue = attributePath.get('value');
145
- const attributeValueEvaluated = attributeValue.isJSXExpressionContainer()
146
- ? attributeValue.get('expression').evaluate()
147
- : attributeValue.evaluate();
148
- if (attributeValueEvaluated.confident &&
149
- typeof attributeValueEvaluated.value === 'string') {
150
- return attributeValueEvaluated.value;
151
- }
152
- else {
153
- warnings.push(`<Translate> prop=${propName} should be a statically evaluable object.\nExample: <Translate id="optional.id" description="optional description">Message</Translate>\nDynamically constructed values are not allowed, because they prevent translations to be extracted.\n${sourceFileWarningPart(path.node)}\n${generateCode(path.node)}`);
136
+ const importSpecifiers = path.get('specifiers');
137
+ const defaultImport = importSpecifiers.find((specifier) => specifier.node.type === 'ImportDefaultSpecifier');
138
+ const callbackImport = importSpecifiers.find((specifier) => specifier.node.type === 'ImportSpecifier' &&
139
+ (specifier.get('imported')
140
+ .node.name === 'translate' ||
141
+ specifier.get('imported')
142
+ .node.value === 'translate'));
143
+ translateComponentName = defaultImport?.get('local').node.name;
144
+ translateFunctionName = callbackImport?.get('local').node.name;
145
+ },
146
+ });
147
+ (0, traverse_1.default)(ast, {
148
+ ...(translateComponentName && {
149
+ JSXElement(path) {
150
+ if (!path
151
+ .get('openingElement')
152
+ .get('name')
153
+ .isJSXIdentifier({ name: translateComponentName })) {
154
+ return;
155
+ }
156
+ function evaluateJSXProp(propName) {
157
+ const attributePath = path
158
+ .get('openingElement.attributes')
159
+ .find((attr) => attr.isJSXAttribute() &&
160
+ attr.get('name').isJSXIdentifier({ name: propName }));
161
+ if (attributePath) {
162
+ const attributeValue = attributePath.get('value');
163
+ const attributeValueEvaluated = attributeValue.isJSXExpressionContainer()
164
+ ? attributeValue.get('expression').evaluate()
165
+ : attributeValue.evaluate();
166
+ if (attributeValueEvaluated.confident &&
167
+ typeof attributeValueEvaluated.value === 'string') {
168
+ return attributeValueEvaluated.value;
169
+ }
170
+ warnings.push(`<Translate> prop=${propName} should be a statically evaluable object.
171
+ Example: <Translate id="optional id" description="optional description">Message</Translate>
172
+ Dynamically constructed values are not allowed, because they prevent translations to be extracted.
173
+ ${sourceWarningPart(path.node)}`);
154
174
  }
175
+ return undefined;
155
176
  }
156
- return undefined;
157
- }
158
- // We only handle the optimistic case where we have a single non-empty content
159
- const singleChildren = path
160
- .get('children')
161
- // Remove empty/useless text nodes that might be around our translation!
162
- // Makes the translation system more reliable to JSX formatting issues
163
- .filter((childrenPath) => !(childrenPath.isJSXText() &&
164
- childrenPath.node.value.replace('\n', '').trim() === ''))
165
- .pop();
166
- if (singleChildren && singleChildren.isJSXText()) {
167
- const message = singleChildren.node.value.trim().replace(/\s+/g, ' ');
168
- const id = evaluateJSXProp('id');
169
- const description = evaluateJSXProp('description');
170
- translations[id !== null && id !== void 0 ? id : message] = {
171
- message,
172
- ...(description && { description }),
173
- };
174
- }
175
- else if (singleChildren &&
176
- singleChildren.isJSXExpressionContainer() &&
177
- singleChildren.get('expression').evaluate().confident) {
178
- const message = singleChildren.get('expression').evaluate().value;
179
177
  const id = evaluateJSXProp('id');
180
178
  const description = evaluateJSXProp('description');
181
- translations[id !== null && id !== void 0 ? id : message] = {
182
- message,
183
- ...(description && { description }),
184
- };
185
- }
186
- else {
187
- warnings.push(`${staticTranslateJSXWarningPart()}\n${sourceFileWarningPart(path.node)}\n${generateCode(path.node)}`);
188
- }
189
- },
190
- CallExpression(path) {
191
- if (!path.get('callee').isIdentifier({ name: 'translate' })) {
192
- return;
193
- }
194
- // console.log('CallExpression', path.node);
195
- const args = path.get('arguments');
196
- if (args.length === 1 || args.length === 2) {
197
- const firstArgPath = args[0];
198
- // evaluation allows translate("x" + "y"); to be considered as translate("xy");
199
- const firstArgEvaluated = firstArgPath.evaluate();
200
- // console.log('firstArgEvaluated', firstArgEvaluated);
201
- if (firstArgEvaluated.confident &&
202
- typeof firstArgEvaluated.value === 'object') {
203
- const { message, id, description } = firstArgEvaluated.value;
204
- translations[id !== null && id !== void 0 ? id : message] = {
179
+ let message;
180
+ const childrenPath = path.get('children');
181
+ // Handle empty content
182
+ if (!childrenPath.length) {
183
+ if (!id) {
184
+ warnings.push(`<Translate> without children must have id prop.
185
+ Example: <Translate id="my-id" />
186
+ ${sourceWarningPart(path.node)}`);
187
+ }
188
+ else {
189
+ translations[id] = {
190
+ message: id,
191
+ ...(description && { description }),
192
+ };
193
+ }
194
+ return;
195
+ }
196
+ // Handle single non-empty content
197
+ const singleChildren = childrenPath
198
+ // Remove empty/useless text nodes that might be around our
199
+ // translation! Makes the translation system more reliable to JSX
200
+ // formatting issues
201
+ .filter((children) => !(children.isJSXText() &&
202
+ children.node.value.replace('\n', '').trim() === ''))
203
+ .pop();
204
+ const isJSXText = singleChildren?.isJSXText();
205
+ const isJSXExpressionContainer = singleChildren?.isJSXExpressionContainer() &&
206
+ singleChildren.get('expression').evaluate().confident;
207
+ if (isJSXText || isJSXExpressionContainer) {
208
+ message = isJSXText
209
+ ? singleChildren.node.value.trim().replace(/\s+/g, ' ')
210
+ : String(singleChildren.get('expression').evaluate().value);
211
+ translations[id ?? message] = {
205
212
  message,
206
213
  ...(description && { description }),
207
214
  };
208
215
  }
209
216
  else {
210
- warnings.push(`translate() first arg should be a statically evaluable object.\nExample: translate({message: "text",id: "optional.id",description: "optional description"}\nDynamically constructed values are not allowed, because they prevent translations to be extracted.\n${sourceFileWarningPart(path.node)}\n${generateCode(path.node)}`);
217
+ warnings.push(`Translate content could not be extracted. It has to be a static string and use optional but static props, like <Translate id="my-id" description="my-description">text</Translate>.
218
+ ${sourceWarningPart(path.node)}`);
211
219
  }
212
- }
213
- else {
214
- warnings.push(`translate() function only takes 1 or 2 args\n${sourceFileWarningPart(path.node)}\n${generateCode(path.node)}`);
215
- }
216
- },
220
+ },
221
+ }),
222
+ ...(translateFunctionName && {
223
+ CallExpression(path) {
224
+ if (!path.get('callee').isIdentifier({ name: translateFunctionName })) {
225
+ return;
226
+ }
227
+ const args = path.get('arguments');
228
+ if (args.length === 1 || args.length === 2) {
229
+ const firstArgPath = args[0];
230
+ // translate("x" + "y"); => translate("xy");
231
+ const firstArgEvaluated = firstArgPath.evaluate();
232
+ if (firstArgEvaluated.confident &&
233
+ typeof firstArgEvaluated.value === 'object') {
234
+ const { message, id, description } = firstArgEvaluated.value;
235
+ translations[String(id ?? message)] = {
236
+ message: String(message ?? id),
237
+ ...(Boolean(description) && { description: String(description) }),
238
+ };
239
+ }
240
+ else {
241
+ warnings.push(`translate() first arg should be a statically evaluable object.
242
+ Example: translate({message: "text",id: "optional.id",description: "optional description"}
243
+ Dynamically constructed values are not allowed, because they prevent translations to be extracted.
244
+ ${sourceWarningPart(path.node)}`);
245
+ }
246
+ }
247
+ else {
248
+ warnings.push(`translate() function only takes 1 or 2 args
249
+ ${sourceWarningPart(path.node)}`);
250
+ }
251
+ },
252
+ }),
217
253
  });
218
254
  return { sourceCodeFilePath, translations, warnings };
219
255
  }
@@ -1,4 +1,10 @@
1
- import { RouteConfig } from '@docusaurus/types';
2
- import globby from 'globby';
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 { Globby } from '@docusaurus/utils';
8
+ import type { RouteConfig } from '@docusaurus/types';
3
9
  export declare function getAllFinalRoutes(routeConfig: RouteConfig[]): RouteConfig[];
4
- export declare function safeGlobby(patterns: string[], options?: globby.GlobbyOptions): Promise<string[]>;
10
+ export declare function safeGlobby(patterns: string[], options?: Globby.GlobbyOptions): Promise<string[]>;
@@ -1,23 +1,21 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.safeGlobby = exports.getAllFinalRoutes = void 0;
4
- const tslib_1 = require("tslib");
5
2
  /**
6
3
  * Copyright (c) Facebook, Inc. and its affiliates.
7
4
  *
8
5
  * This source code is licensed under the MIT license found in the
9
6
  * LICENSE file in the root directory of this source tree.
10
7
  */
11
- const lodash_1 = require("lodash");
12
- const globby_1 = tslib_1.__importDefault(require("globby"));
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.safeGlobby = exports.getAllFinalRoutes = void 0;
10
+ const tslib_1 = require("tslib");
13
11
  const path_1 = tslib_1.__importDefault(require("path"));
14
12
  const utils_1 = require("@docusaurus/utils");
15
13
  // Recursively get the final routes (routes with no subroutes)
16
14
  function getAllFinalRoutes(routeConfig) {
17
15
  function getFinalRoutes(route) {
18
- return route.routes ? lodash_1.flatMap(route.routes, getFinalRoutes) : [route];
16
+ return route.routes ? route.routes.flatMap(getFinalRoutes) : [route];
19
17
  }
20
- return lodash_1.flatMap(routeConfig, getFinalRoutes);
18
+ return routeConfig.flatMap(getFinalRoutes);
21
19
  }
22
20
  exports.getAllFinalRoutes = getAllFinalRoutes;
23
21
  // Globby that fix Windows path patterns
@@ -25,7 +23,7 @@ exports.getAllFinalRoutes = getAllFinalRoutes;
25
23
  async function safeGlobby(patterns, options) {
26
24
  // Required for Windows support, as paths using \ should not be used by globby
27
25
  // (also using the windows hard drive prefix like c: is not a good idea)
28
- const globPaths = patterns.map((dirPath) => utils_1.posixPath(path_1.default.relative(process.cwd(), dirPath)));
29
- return globby_1.default(globPaths, options);
26
+ const globPaths = patterns.map((dirPath) => (0, utils_1.posixPath)(path_1.default.relative(process.cwd(), dirPath)));
27
+ return (0, utils_1.Globby)(globPaths, options);
30
28
  }
31
29
  exports.safeGlobby = safeGlobby;
@@ -0,0 +1,34 @@
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 } from '@docusaurus/types';
8
+ /**
9
+ * Aliases used for Webpack resolution (useful for implementing swizzling)
10
+ */
11
+ declare type ThemeAliases = {
12
+ [alias: string]: string;
13
+ };
14
+ /**
15
+ * Order of Webpack aliases is important because one alias can shadow another.
16
+ * This ensures `@theme/NavbarItem` alias is after
17
+ * `@theme/NavbarItem/LocaleDropdown`.
18
+ *
19
+ * @see https://github.com/facebook/docusaurus/pull/3922
20
+ * @see https://github.com/facebook/docusaurus/issues/5382
21
+ */
22
+ export declare function sortAliases(aliases: ThemeAliases): ThemeAliases;
23
+ export declare function createAliasesForTheme(themePath: string, addOriginalAlias: boolean): Promise<ThemeAliases>;
24
+ export declare function loadThemeAliases({ siteDir, plugins, }: {
25
+ siteDir: string;
26
+ plugins: LoadedPlugin[];
27
+ }): Promise<ThemeAliases>;
28
+ /**
29
+ * Note: a `@docusaurus` alias would also catch `@docusaurus/theme-common`, so
30
+ * instead of naively aliasing this to `client/exports`, we use fine-grained
31
+ * aliases instead.
32
+ */
33
+ export declare function loadDocusaurusAliases(): Promise<ThemeAliases>;
34
+ export {};
@@ -0,0 +1,106 @@
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.loadDocusaurusAliases = exports.loadThemeAliases = exports.createAliasesForTheme = exports.sortAliases = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
+ const path_1 = tslib_1.__importDefault(require("path"));
13
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
14
+ const utils_1 = require("@docusaurus/utils");
15
+ const ThemeFallbackDir = path_1.default.join(__dirname, '../../client/theme-fallback');
16
+ /**
17
+ * Order of Webpack aliases is important because one alias can shadow another.
18
+ * This ensures `@theme/NavbarItem` alias is after
19
+ * `@theme/NavbarItem/LocaleDropdown`.
20
+ *
21
+ * @see https://github.com/facebook/docusaurus/pull/3922
22
+ * @see https://github.com/facebook/docusaurus/issues/5382
23
+ */
24
+ function sortAliases(aliases) {
25
+ // Alphabetical order by default
26
+ const entries = lodash_1.default.sortBy(Object.entries(aliases), ([alias]) => alias);
27
+ // @theme/NavbarItem should be after @theme/NavbarItem/LocaleDropdown
28
+ entries.sort(([alias1], [alias2]) =>
29
+ // eslint-disable-next-line no-nested-ternary
30
+ alias1.includes(`${alias2}/`) ? -1 : alias2.includes(`${alias1}/`) ? 1 : 0);
31
+ return Object.fromEntries(entries);
32
+ }
33
+ exports.sortAliases = sortAliases;
34
+ async function createAliasesForTheme(themePath, addOriginalAlias) {
35
+ if (!(await fs_extra_1.default.pathExists(themePath))) {
36
+ return {};
37
+ }
38
+ const themeComponentFiles = await (0, utils_1.Globby)(['**/*.{js,jsx,ts,tsx}'], {
39
+ cwd: themePath,
40
+ });
41
+ const aliases = {};
42
+ themeComponentFiles.forEach((relativeSource) => {
43
+ const filePath = path_1.default.join(themePath, relativeSource);
44
+ const fileName = (0, utils_1.fileToPath)(relativeSource);
45
+ const aliasName = (0, utils_1.posixPath)((0, utils_1.normalizeUrl)(['@theme', fileName]).replace(/\/$/, ''));
46
+ aliases[aliasName] = filePath;
47
+ if (addOriginalAlias) {
48
+ // For swizzled components to access the original.
49
+ const originalAliasName = (0, utils_1.posixPath)((0, utils_1.normalizeUrl)(['@theme-original', fileName]).replace(/\/$/, ''));
50
+ aliases[originalAliasName] = filePath;
51
+ }
52
+ });
53
+ return sortAliases(aliases);
54
+ }
55
+ exports.createAliasesForTheme = createAliasesForTheme;
56
+ async function createThemeAliases(themePaths, userThemePaths) {
57
+ const aliases = {};
58
+ for (const themePath of themePaths) {
59
+ const themeAliases = await createAliasesForTheme(themePath, true);
60
+ Object.entries(themeAliases).forEach(([aliasKey, alias]) => {
61
+ // If this alias shadows a previous one, use @theme-init to preserve the
62
+ // initial one. @theme-init is only applied once: to the initial theme
63
+ // that provided this component
64
+ if (aliasKey in aliases) {
65
+ const componentName = aliasKey.substring(aliasKey.indexOf('/') + 1);
66
+ const initAlias = `@theme-init/${componentName}`;
67
+ if (!(initAlias in aliases)) {
68
+ aliases[initAlias] = aliases[aliasKey];
69
+ }
70
+ }
71
+ aliases[aliasKey] = alias;
72
+ });
73
+ }
74
+ for (const themePath of userThemePaths) {
75
+ const userThemeAliases = await createAliasesForTheme(themePath, false);
76
+ Object.assign(aliases, userThemeAliases);
77
+ }
78
+ return sortAliases(aliases);
79
+ }
80
+ function loadThemeAliases({ siteDir, plugins, }) {
81
+ const pluginThemes = plugins
82
+ .map((plugin) => plugin.getThemePath && path_1.default.resolve(plugin.path, plugin.getThemePath()))
83
+ .filter((x) => Boolean(x));
84
+ const userTheme = path_1.default.resolve(siteDir, utils_1.THEME_PATH);
85
+ return createThemeAliases([ThemeFallbackDir, ...pluginThemes], [userTheme]);
86
+ }
87
+ exports.loadThemeAliases = loadThemeAliases;
88
+ /**
89
+ * Note: a `@docusaurus` alias would also catch `@docusaurus/theme-common`, so
90
+ * instead of naively aliasing this to `client/exports`, we use fine-grained
91
+ * aliases instead.
92
+ */
93
+ async function loadDocusaurusAliases() {
94
+ const dirPath = path_1.default.resolve(__dirname, '../../client/exports');
95
+ const extensions = ['.js', '.ts', '.tsx'];
96
+ const aliases = {};
97
+ (await fs_extra_1.default.readdir(dirPath))
98
+ .filter((fileName) => extensions.includes(path_1.default.extname(fileName)))
99
+ .forEach((fileName) => {
100
+ const fileNameWithoutExtension = path_1.default.basename(fileName, path_1.default.extname(fileName));
101
+ const aliasName = `@docusaurus/${fileNameWithoutExtension}`;
102
+ aliases[aliasName] = path_1.default.resolve(dirPath, fileName);
103
+ });
104
+ return aliases;
105
+ }
106
+ exports.loadDocusaurusAliases = loadDocusaurusAliases;
@@ -4,9 +4,8 @@
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 { Configuration } from 'webpack';
8
- import { Props } from '@docusaurus/types';
7
+ import type { Configuration } from 'webpack';
8
+ import type { Props } from '@docusaurus/types';
9
9
  export declare const clientDir: string;
10
10
  export declare function excludeJS(modulePath: string): boolean;
11
- export declare function getDocusaurusAliases(): Record<string, string>;
12
- export declare function createBaseConfig(props: Props, isServer: boolean, minify?: boolean): Configuration;
11
+ export declare function createBaseConfig(props: Props, isServer: boolean, minify?: boolean): Promise<Configuration>;