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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/bin/beforeCli.mjs +136 -0
  2. package/bin/docusaurus.mjs +280 -0
  3. package/lib/babel/preset.d.ts +8 -3
  4. package/lib/babel/preset.js +8 -7
  5. package/lib/choosePort.js +32 -41
  6. package/lib/client/.eslintrc.js +0 -1
  7. package/lib/client/App.d.ts +1 -2
  8. package/lib/client/App.js +19 -24
  9. package/lib/client/LinksCollector.d.ts +3 -3
  10. package/lib/client/LinksCollector.js +5 -9
  11. package/lib/client/PendingNavigation.d.ts +24 -1
  12. package/lib/client/PendingNavigation.js +5 -7
  13. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.d.ts +13 -0
  14. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.js +15 -10
  15. package/lib/client/client-lifecycles-dispatcher.d.ts +2 -5
  16. package/lib/client/client-lifecycles-dispatcher.js +5 -9
  17. package/lib/client/clientEntry.js +11 -5
  18. package/lib/client/docusaurus.d.ts +6 -0
  19. package/lib/client/docusaurus.js +17 -23
  20. package/lib/client/exports/BrowserOnly.d.ts +2 -3
  21. package/lib/client/exports/BrowserOnly.js +14 -7
  22. package/lib/client/exports/ComponentCreator.d.ts +1 -2
  23. package/lib/client/exports/ComponentCreator.js +7 -6
  24. package/lib/client/exports/ErrorBoundary.d.ts +18 -0
  25. package/lib/client/exports/ErrorBoundary.js +36 -0
  26. package/lib/client/exports/Head.d.ts +2 -3
  27. package/lib/client/exports/Head.js +3 -4
  28. package/lib/client/exports/Interpolate.d.ts +1 -1
  29. package/lib/client/exports/Interpolate.js +15 -21
  30. package/lib/client/exports/Link.d.ts +11 -5
  31. package/lib/client/exports/Link.js +29 -17
  32. package/lib/client/exports/Translate.d.ts +3 -3
  33. package/lib/client/exports/Translate.js +15 -10
  34. package/lib/client/exports/browserContext.d.ts +11 -0
  35. package/lib/client/exports/browserContext.js +22 -0
  36. package/lib/client/exports/constants.js +1 -11
  37. package/lib/client/exports/docusaurusContext.d.ts +12 -0
  38. package/lib/client/exports/docusaurusContext.js +25 -0
  39. package/lib/client/exports/isInternalUrl.js +1 -1
  40. package/lib/client/exports/renderRoutes.d.ts +1 -2
  41. package/lib/client/exports/renderRoutes.js +1 -2
  42. package/lib/client/exports/router.d.ts +1 -1
  43. package/lib/client/exports/router.js +1 -1
  44. package/lib/client/exports/useBaseUrl.js +3 -5
  45. package/lib/client/exports/useDocusaurusContext.d.ts +2 -3
  46. package/lib/client/exports/useDocusaurusContext.js +3 -9
  47. package/lib/client/exports/useGlobalData.js +4 -8
  48. package/lib/{server/versions/__tests/index.test.d.ts → client/exports/useIsBrowser.d.ts} +1 -1
  49. package/lib/client/exports/useIsBrowser.js +11 -0
  50. package/lib/client/flat.d.ts +2 -2
  51. package/lib/client/flat.js +8 -11
  52. package/lib/client/normalizeLocation.d.ts +2 -5
  53. package/lib/client/normalizeLocation.js +1 -2
  54. package/lib/client/nprogress.css +2 -2
  55. package/lib/client/prefetch.d.ts +1 -2
  56. package/lib/client/prefetch.js +1 -3
  57. package/lib/client/preload.d.ts +3 -2
  58. package/lib/client/preload.js +2 -1
  59. package/lib/client/serverEntry.d.ts +10 -0
  60. package/lib/client/serverEntry.js +90 -142
  61. package/lib/client/theme-fallback/Error/index.d.ts +10 -0
  62. package/lib/client/theme-fallback/Error/index.js +39 -0
  63. package/lib/client/theme-fallback/Layout/index.d.ts +10 -0
  64. package/lib/client/theme-fallback/Layout/index.js +10 -19
  65. package/lib/client/theme-fallback/Loading/index.d.ts +9 -0
  66. package/lib/client/theme-fallback/Loading/index.js +47 -115
  67. package/lib/client/{exports/context.js → theme-fallback/NotFound/index.d.ts} +2 -2
  68. package/lib/client/theme-fallback/NotFound/index.js +9 -16
  69. package/lib/{webpack/sharedModuleAliases.d.ts → client/theme-fallback/Root/index.d.ts} +4 -4
  70. package/lib/client/theme-fallback/Root/index.js +2 -7
  71. package/lib/commands/build.d.ts +1 -1
  72. package/lib/commands/build.js +59 -61
  73. package/lib/commands/clear.d.ts +6 -0
  74. package/lib/commands/clear.js +32 -21
  75. package/lib/commands/commandUtils.d.ts +7 -1
  76. package/lib/commands/commandUtils.js +7 -7
  77. package/lib/commands/deploy.d.ts +4 -1
  78. package/lib/commands/deploy.js +115 -71
  79. package/lib/commands/external.d.ts +2 -2
  80. package/lib/commands/external.js +4 -4
  81. package/lib/commands/serve.d.ts +1 -1
  82. package/lib/commands/serve.js +30 -16
  83. package/lib/commands/start.d.ts +1 -1
  84. package/lib/commands/start.js +100 -89
  85. package/lib/commands/swizzle/actions.d.ts +23 -0
  86. package/lib/commands/swizzle/actions.js +102 -0
  87. package/lib/commands/swizzle/common.d.ts +33 -0
  88. package/lib/commands/swizzle/common.js +57 -0
  89. package/lib/commands/swizzle/components.d.ts +29 -0
  90. package/lib/commands/swizzle/components.js +165 -0
  91. package/lib/commands/swizzle/config.d.ts +10 -0
  92. package/lib/commands/swizzle/config.js +77 -0
  93. package/lib/{client/exports → commands/swizzle}/context.d.ts +2 -4
  94. package/lib/commands/swizzle/context.js +30 -0
  95. package/lib/commands/swizzle/index.d.ts +8 -0
  96. package/lib/commands/swizzle/index.js +115 -0
  97. package/lib/commands/swizzle/prompts.d.ts +12 -0
  98. package/lib/commands/swizzle/prompts.js +110 -0
  99. package/lib/commands/swizzle/tables.d.ts +9 -0
  100. package/lib/commands/swizzle/tables.js +116 -0
  101. package/lib/commands/swizzle/themes.d.ts +20 -0
  102. package/lib/commands/swizzle/themes.js +105 -0
  103. package/lib/commands/writeHeadingIds.d.ts +9 -6
  104. package/lib/commands/writeHeadingIds.js +44 -46
  105. package/lib/commands/writeTranslations.d.ts +2 -2
  106. package/lib/commands/writeTranslations.js +36 -14
  107. package/lib/index.d.ts +10 -9
  108. package/lib/index.js +20 -19
  109. package/lib/server/brokenLinks.d.ts +1 -1
  110. package/lib/server/brokenLinks.js +38 -33
  111. package/lib/server/client-modules/index.d.ts +1 -1
  112. package/lib/server/client-modules/index.js +1 -3
  113. package/lib/server/config.d.ts +2 -2
  114. package/lib/server/config.js +10 -7
  115. package/lib/server/configValidation.d.ts +4 -2
  116. package/lib/server/configValidation.js +63 -32
  117. package/lib/server/duplicateRoutes.d.ts +1 -1
  118. package/lib/server/duplicateRoutes.js +10 -6
  119. package/lib/server/html-tags/htmlTags.js +8 -9
  120. package/lib/server/html-tags/index.d.ts +2 -2
  121. package/lib/server/html-tags/index.js +3 -3
  122. package/lib/server/i18n.d.ts +1 -2
  123. package/lib/server/i18n.js +31 -46
  124. package/lib/server/index.d.ts +9 -2
  125. package/lib/server/index.js +165 -87
  126. package/lib/server/loadSetup.d.ts +2 -3
  127. package/lib/server/loadSetup.js +5 -5
  128. package/lib/server/moduleShorthand.d.ts +9 -0
  129. package/lib/server/moduleShorthand.js +46 -0
  130. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +9 -0
  131. package/lib/server/plugins/applyRouteTrailingSlash.js +19 -0
  132. package/lib/server/plugins/index.d.ts +3 -4
  133. package/lib/server/plugins/index.js +53 -37
  134. package/lib/server/plugins/init.d.ts +11 -5
  135. package/lib/server/plugins/init.js +40 -47
  136. package/lib/server/plugins/pluginIds.d.ts +2 -2
  137. package/lib/server/plugins/pluginIds.js +8 -5
  138. package/lib/server/presets/index.d.ts +3 -3
  139. package/lib/server/presets/index.js +14 -14
  140. package/lib/server/routes.d.ts +1 -1
  141. package/lib/server/routes.js +51 -28
  142. package/lib/server/themes/alias.d.ts +3 -2
  143. package/lib/server/themes/alias.js +24 -15
  144. package/lib/server/themes/index.d.ts +6 -2
  145. package/lib/server/themes/index.js +36 -24
  146. package/lib/server/translations/translations.d.ts +10 -5
  147. package/lib/server/translations/translations.js +27 -35
  148. package/lib/server/translations/translationsExtractor.d.ts +9 -4
  149. package/lib/server/translations/translationsExtractor.js +160 -119
  150. package/lib/server/utils.d.ts +9 -3
  151. package/lib/server/utils.js +8 -10
  152. package/lib/server/versions/__fixtures__/dummy-plugin.d.ts +0 -0
  153. package/lib/server/versions/index.d.ts +3 -4
  154. package/lib/server/versions/index.js +22 -21
  155. package/lib/webpack/base.d.ts +4 -4
  156. package/lib/webpack/base.js +54 -38
  157. package/lib/webpack/client.d.ts +3 -3
  158. package/lib/webpack/client.js +15 -21
  159. package/lib/webpack/plugins/ChunkAssetPlugin.d.ts +13 -3
  160. package/lib/webpack/plugins/ChunkAssetPlugin.js +17 -10
  161. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +6 -6
  162. package/lib/webpack/plugins/CleanWebpackPlugin.js +10 -16
  163. package/lib/webpack/plugins/LogPlugin.d.ts +1 -1
  164. package/lib/webpack/plugins/LogPlugin.js +5 -6
  165. package/lib/webpack/plugins/WaitPlugin.d.ts +1 -1
  166. package/lib/webpack/plugins/WaitPlugin.js +4 -4
  167. package/lib/webpack/server.d.ts +3 -3
  168. package/lib/webpack/server.js +18 -11
  169. package/lib/{client → webpack}/templates/index.html.template.ejs +0 -0
  170. package/lib/webpack/templates/ssr.html.template.d.ts +8 -0
  171. package/lib/{client → webpack}/templates/ssr.html.template.js +5 -4
  172. package/lib/webpack/utils.d.ts +9 -30
  173. package/lib/webpack/utils.js +58 -171
  174. package/package.json +76 -69
  175. package/bin/docusaurus.js +0 -326
  176. package/lib/.tsbuildinfo +0 -5732
  177. package/lib/client/.tsbuildinfo +0 -4171
  178. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  179. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  180. package/lib/commands/swizzle.d.ts +0 -9
  181. package/lib/commands/swizzle.js +0 -245
  182. package/lib/constants.d.ts +0 -18
  183. package/lib/constants.js +0 -23
  184. package/lib/server/versions/__tests/index.test.js +0 -25
  185. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  186. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  187. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  188. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  189. package/lib/webpack/sharedModuleAliases.js +0 -18
  190. package/tsconfig.client.json +0 -13
  191. package/tsconfig.json +0 -13
@@ -0,0 +1,165 @@
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.getComponentName = exports.getThemeComponents = exports.listComponentNames = exports.readComponentNames = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
12
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
13
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
14
+ const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
15
+ const utils_1 = require("@docusaurus/utils");
16
+ const prompts_1 = require("./prompts");
17
+ const common_1 = require("./common");
18
+ const tables_1 = require("./tables");
19
+ const actions_1 = require("./actions");
20
+ const formatComponentName = (componentName) => componentName.replace(/[/\\]index\.[jt]sx?/, '').replace(/\.[jt]sx?/, '');
21
+ const skipReadDirNames = ['__test__', '__tests__', '__mocks__', '__fixtures__'];
22
+ async function readComponentNames(themePath) {
23
+ if (!(await fs_extra_1.default.pathExists(themePath))) {
24
+ return [];
25
+ }
26
+ async function walk(dir) {
27
+ const files = await Promise.all((await fs_extra_1.default.readdir(dir)).flatMap(async (file) => {
28
+ const fullPath = path_1.default.join(dir, file);
29
+ const stat = await fs_extra_1.default.stat(fullPath);
30
+ const isDir = stat.isDirectory();
31
+ return { file, fullPath, isDir };
32
+ }));
33
+ return (await Promise.all(files.map(async (file) => {
34
+ if (file.isDir) {
35
+ if (skipReadDirNames.includes(file.file)) {
36
+ return [];
37
+ }
38
+ return walk(file.fullPath);
39
+ }
40
+ else if (
41
+ // TODO can probably be refactored
42
+ /(?<!\.d)\.[jt]sx?$/.test(file.fullPath) &&
43
+ !/(?<!\.d)\.(?:test|tests|story|stories)\.[jt]sx?$/.test(file.fullPath)) {
44
+ const componentName = formatComponentName((0, utils_1.posixPath)(path_1.default.relative(themePath, file.fullPath)));
45
+ return [{ ...file, componentName }];
46
+ }
47
+ return [];
48
+ }))).flat();
49
+ }
50
+ const componentFiles = await walk(themePath);
51
+ const componentFilesOrdered = lodash_1.default.orderBy(componentFiles, [(f) => f.componentName], ['asc']);
52
+ return componentFilesOrdered.map((f) => f.componentName);
53
+ }
54
+ exports.readComponentNames = readComponentNames;
55
+ function listComponentNames(themeComponents) {
56
+ if (themeComponents.all.length === 0) {
57
+ return 'No component to swizzle.';
58
+ }
59
+ return `${(0, tables_1.themeComponentsTable)(themeComponents)}
60
+
61
+ ${(0, tables_1.helpTables)()}
62
+ `;
63
+ }
64
+ exports.listComponentNames = listComponentNames;
65
+ async function getThemeComponents({ themeName, themePath, swizzleConfig, }) {
66
+ const FallbackSwizzleActionStatus = 'unsafe';
67
+ const FallbackSwizzleComponentDescription = 'N/A';
68
+ const FallbackSwizzleComponentConfig = {
69
+ actions: {
70
+ wrap: FallbackSwizzleActionStatus,
71
+ eject: FallbackSwizzleActionStatus,
72
+ },
73
+ description: FallbackSwizzleComponentDescription,
74
+ };
75
+ const allComponents = await readComponentNames(themePath);
76
+ function getConfig(component) {
77
+ var _a;
78
+ if (!allComponents.includes(component)) {
79
+ throw new Error(`Can't get component config: component doesn't exist: ${component}`);
80
+ }
81
+ return ((_a = swizzleConfig.components[component]) !== null && _a !== void 0 ? _a : FallbackSwizzleComponentConfig);
82
+ }
83
+ function getDescription(component) {
84
+ var _a;
85
+ return ((_a = getConfig(component).description) !== null && _a !== void 0 ? _a : FallbackSwizzleComponentDescription);
86
+ }
87
+ function getActionStatus(component, action) {
88
+ var _a;
89
+ return (_a = getConfig(component).actions[action]) !== null && _a !== void 0 ? _a : FallbackSwizzleActionStatus;
90
+ }
91
+ function isSafeAction(component, action) {
92
+ return getActionStatus(component, action) === 'safe';
93
+ }
94
+ function hasAllSafeAction(component) {
95
+ return actions_1.SwizzleActions.every((action) => isSafeAction(component, action));
96
+ }
97
+ function hasAnySafeAction(component) {
98
+ return actions_1.SwizzleActions.some((action) => isSafeAction(component, action));
99
+ }
100
+ // Present the safest components first
101
+ const orderedComponents = lodash_1.default.orderBy(allComponents, [
102
+ hasAllSafeAction,
103
+ (component) => isSafeAction(component, 'wrap'),
104
+ (component) => isSafeAction(component, 'eject'),
105
+ (component) => component,
106
+ ], ['desc', 'desc', 'desc', 'asc']);
107
+ return {
108
+ themeName,
109
+ all: orderedComponents,
110
+ getConfig,
111
+ getDescription,
112
+ getActionStatus,
113
+ isSafeAction,
114
+ hasAnySafeAction,
115
+ hasAllSafeAction,
116
+ };
117
+ }
118
+ exports.getThemeComponents = getThemeComponents;
119
+ // Returns a valid value if recovering is possible
120
+ function handleInvalidComponentNameParam({ componentNameParam, themeComponents, }) {
121
+ // Trying to recover invalid value
122
+ // We look for potential matches that only differ in casing.
123
+ const differentCaseMatch = (0, common_1.findStringIgnoringCase)(componentNameParam, themeComponents.all);
124
+ if (differentCaseMatch) {
125
+ logger_1.default.warn `Component name=${componentNameParam} doesn't exist.`;
126
+ logger_1.default.info `name=${differentCaseMatch} will be used instead of name=${componentNameParam}.`;
127
+ return differentCaseMatch;
128
+ }
129
+ // No recovery value is possible: print error
130
+ logger_1.default.error `Component name=${componentNameParam} not found.`;
131
+ const suggestion = (0, common_1.findClosestValue)(componentNameParam, themeComponents.all);
132
+ if (suggestion) {
133
+ logger_1.default.info `Did you mean name=${suggestion}? ${themeComponents.hasAnySafeAction(suggestion)
134
+ ? `Note: this component is an unsafe internal component and can only be swizzled with code=${'--danger'} or explicit confirmation.`
135
+ : ''}`;
136
+ }
137
+ else {
138
+ logger_1.default.info(listComponentNames(themeComponents));
139
+ }
140
+ return process.exit(1);
141
+ }
142
+ async function handleComponentNameParam({ componentNameParam, themeComponents, }) {
143
+ const isValidName = themeComponents.all.includes(componentNameParam);
144
+ if (!isValidName) {
145
+ return handleInvalidComponentNameParam({
146
+ componentNameParam,
147
+ themeComponents,
148
+ });
149
+ }
150
+ return componentNameParam;
151
+ }
152
+ async function getComponentName({ componentNameParam, themeComponents, list, }) {
153
+ if (list) {
154
+ logger_1.default.info(listComponentNames(themeComponents));
155
+ return process.exit(0);
156
+ }
157
+ const componentName = componentNameParam
158
+ ? await handleComponentNameParam({
159
+ componentNameParam,
160
+ themeComponents,
161
+ })
162
+ : await (0, prompts_1.askComponentName)(themeComponents);
163
+ return componentName;
164
+ }
165
+ exports.getComponentName = getComponentName;
@@ -0,0 +1,10 @@
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 { SwizzleConfig } from '@docusaurus/types';
8
+ import type { SwizzlePlugin } from './common';
9
+ export declare function normalizeSwizzleConfig(unsafeSwizzleConfig: unknown): SwizzleConfig;
10
+ export declare function getThemeSwizzleConfig(themeName: string, plugins: SwizzlePlugin[]): SwizzleConfig;
@@ -0,0 +1,77 @@
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.getThemeSwizzleConfig = exports.normalizeSwizzleConfig = void 0;
10
+ const utils_validation_1 = require("@docusaurus/utils-validation");
11
+ const common_1 = require("./common");
12
+ const themes_1 = require("./themes");
13
+ function getModuleSwizzleConfig(swizzlePlugin) {
14
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
15
+ const getSwizzleConfig = (_d = (_b = (_a = swizzlePlugin.plugin.plugin) === null || _a === void 0 ? void 0 : _a.getSwizzleConfig) !== null && _b !== void 0 ? _b : (_c = swizzlePlugin.plugin.pluginModule) === null || _c === void 0 ? void 0 : _c.module.getSwizzleConfig) !== null && _d !== void 0 ? _d : (_f = (_e = swizzlePlugin.plugin.pluginModule) === null || _e === void 0 ? void 0 : _e.module) === null || _f === void 0 ? void 0 : _f.getSwizzleConfig;
16
+ if (getSwizzleConfig) {
17
+ return getSwizzleConfig();
18
+ }
19
+ // TODO deprecate getSwizzleComponentList later
20
+ const getSwizzleComponentList = (_k = (_h = (_g = swizzlePlugin.plugin.plugin) === null || _g === void 0 ? void 0 : _g.getSwizzleComponentList) !== null && _h !== void 0 ? _h : (_j = swizzlePlugin.plugin.pluginModule) === null || _j === void 0 ? void 0 : _j.module.getSwizzleComponentList) !== null && _k !== void 0 ? _k : (_m = (_l = swizzlePlugin.plugin.pluginModule) === null || _l === void 0 ? void 0 : _l.module) === null || _m === void 0 ? void 0 : _m.getSwizzleComponentList;
21
+ if (getSwizzleComponentList) {
22
+ const safeComponents = (_o = getSwizzleComponentList()) !== null && _o !== void 0 ? _o : [];
23
+ const safeComponentConfig = {
24
+ actions: {
25
+ eject: 'safe',
26
+ wrap: 'safe',
27
+ },
28
+ description: undefined,
29
+ };
30
+ return {
31
+ components: Object.fromEntries(safeComponents.map((comp) => [comp, safeComponentConfig])),
32
+ };
33
+ }
34
+ return undefined;
35
+ }
36
+ function normalizeSwizzleConfig(unsafeSwizzleConfig) {
37
+ const schema = utils_validation_1.Joi.object({
38
+ components: utils_validation_1.Joi.object()
39
+ .pattern(utils_validation_1.Joi.string(), utils_validation_1.Joi.object({
40
+ actions: utils_validation_1.Joi.object().pattern(utils_validation_1.Joi.string().valid(...common_1.SwizzleActions), utils_validation_1.Joi.string().valid(...common_1.SwizzleActionsStatuses)),
41
+ description: utils_validation_1.Joi.string(),
42
+ }))
43
+ .required(),
44
+ });
45
+ const result = schema.validate(unsafeSwizzleConfig);
46
+ if (result.error) {
47
+ throw new Error(`Swizzle config does not match expected schema: ${result.error.message}`);
48
+ }
49
+ const swizzleConfig = result.value;
50
+ // Ensure all components always declare all actions
51
+ Object.values(swizzleConfig.components).forEach((componentConfig) => {
52
+ common_1.SwizzleActions.forEach((action) => {
53
+ if (!componentConfig.actions[action]) {
54
+ componentConfig.actions[action] = 'unsafe';
55
+ }
56
+ });
57
+ });
58
+ return swizzleConfig;
59
+ }
60
+ exports.normalizeSwizzleConfig = normalizeSwizzleConfig;
61
+ const FallbackSwizzleConfig = {
62
+ components: {},
63
+ };
64
+ function getThemeSwizzleConfig(themeName, plugins) {
65
+ const plugin = (0, themes_1.getPluginByThemeName)(plugins, themeName);
66
+ const config = getModuleSwizzleConfig(plugin);
67
+ if (config) {
68
+ try {
69
+ return normalizeSwizzleConfig(config);
70
+ }
71
+ catch (e) {
72
+ throw new Error(`Invalid Swizzle config for theme ${themeName}.\n${e.message}`);
73
+ }
74
+ }
75
+ return FallbackSwizzleConfig;
76
+ }
77
+ exports.getThemeSwizzleConfig = getThemeSwizzleConfig;
@@ -4,7 +4,5 @@
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 React from 'react';
8
- import { DocusaurusContext } from '@docusaurus/types';
9
- declare const _default: React.Context<DocusaurusContext | null>;
10
- export default _default;
7
+ import type { SwizzleContext } from './common';
8
+ export declare function initSwizzleContext(siteDir: string): Promise<SwizzleContext>;
@@ -0,0 +1,30 @@
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.initSwizzleContext = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const module_1 = require("module");
12
+ const server_1 = require("../../server");
13
+ const init_1 = (0, tslib_1.__importStar)(require("../../server/plugins/init"));
14
+ async function initSwizzleContext(siteDir) {
15
+ const context = await (0, server_1.loadContext)(siteDir);
16
+ const pluginRequire = (0, module_1.createRequire)(context.siteConfigPath);
17
+ const pluginConfigs = await (0, server_1.loadPluginConfigs)(context);
18
+ const plugins = await (0, init_1.default)({
19
+ pluginConfigs,
20
+ context,
21
+ });
22
+ const pluginsNormalized = await (0, init_1.normalizePluginConfigs)(pluginConfigs, pluginRequire);
23
+ return {
24
+ plugins: plugins.map((plugin, pluginIndex) => ({
25
+ plugin: pluginsNormalized[pluginIndex],
26
+ instance: plugin,
27
+ })),
28
+ };
29
+ }
30
+ exports.initSwizzleContext = initSwizzleContext;
@@ -0,0 +1,8 @@
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 { SwizzleOptions } from './common';
8
+ export default function swizzle(siteDir: string, themeNameParam: string | undefined, componentNameParam: string | undefined, optionsParam: Partial<SwizzleOptions>): Promise<void>;
@@ -0,0 +1,115 @@
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
+ const tslib_1 = require("tslib");
10
+ const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
11
+ const themes_1 = require("./themes");
12
+ const components_1 = require("./components");
13
+ const tables_1 = require("./tables");
14
+ const common_1 = require("./common");
15
+ const actions_1 = require("./actions");
16
+ const config_1 = require("./config");
17
+ const prompts_1 = require("./prompts");
18
+ const context_1 = require("./context");
19
+ async function listAllThemeComponents({ themeNames, plugins, typescript, }) {
20
+ const themeComponentsTables = (await Promise.all(themeNames.map(async (themeName) => {
21
+ const themePath = (0, themes_1.getThemePath)({ themeName, plugins, typescript });
22
+ const swizzleConfig = (0, config_1.getThemeSwizzleConfig)(themeName, plugins);
23
+ const themeComponents = await (0, components_1.getThemeComponents)({
24
+ themeName,
25
+ themePath,
26
+ swizzleConfig,
27
+ });
28
+ return (0, tables_1.themeComponentsTable)(themeComponents);
29
+ }))).join('\n\n');
30
+ logger_1.default.info(`All theme components available to swizzle:
31
+
32
+ ${themeComponentsTables}
33
+
34
+ ${(0, tables_1.helpTables)()}
35
+ `);
36
+ return process.exit(0);
37
+ }
38
+ async function ensureActionSafety({ componentName, componentConfig, action, danger, }) {
39
+ const actionStatus = componentConfig.actions[action];
40
+ if (actionStatus === 'forbidden') {
41
+ logger_1.default.error `
42
+ Swizzle action name=${action} is forbidden for component name=${componentName}
43
+ `;
44
+ return process.exit(1);
45
+ }
46
+ if (actionStatus === 'unsafe' && !danger) {
47
+ logger_1.default.warn `
48
+ Swizzle action name=${action} is unsafe to perform on name=${componentName}.
49
+ It is more likely to be affected by breaking changes in the future
50
+ If you want to swizzle it, use the code=${'--danger'} flag, or confirm that you understand the risks.
51
+ `;
52
+ const swizzleDangerousComponent = await (0, prompts_1.askSwizzleDangerousComponent)();
53
+ if (!swizzleDangerousComponent) {
54
+ return process.exit(1);
55
+ }
56
+ }
57
+ return undefined;
58
+ }
59
+ async function swizzle(siteDir, themeNameParam, componentNameParam, optionsParam) {
60
+ const options = (0, common_1.normalizeOptions)(optionsParam);
61
+ const { list, danger, typescript } = options;
62
+ const { plugins } = await (0, context_1.initSwizzleContext)(siteDir);
63
+ const themeNames = (0, themes_1.getThemeNames)(plugins);
64
+ if (list && !themeNameParam) {
65
+ await listAllThemeComponents({ themeNames, plugins, typescript });
66
+ }
67
+ const themeName = await (0, themes_1.getThemeName)({ themeNameParam, themeNames, list });
68
+ const themePath = (0, themes_1.getThemePath)({ themeName, plugins, typescript });
69
+ const swizzleConfig = (0, config_1.getThemeSwizzleConfig)(themeName, plugins);
70
+ const themeComponents = await (0, components_1.getThemeComponents)({
71
+ themeName,
72
+ themePath,
73
+ swizzleConfig,
74
+ });
75
+ const componentName = await (0, components_1.getComponentName)({
76
+ componentNameParam,
77
+ themeComponents,
78
+ list,
79
+ });
80
+ const componentConfig = themeComponents.getConfig(componentName);
81
+ const action = await (0, actions_1.getAction)(componentConfig, options);
82
+ await ensureActionSafety({ componentName, componentConfig, action, danger });
83
+ async function executeAction() {
84
+ switch (action) {
85
+ case 'wrap': {
86
+ const result = await (0, actions_1.wrap)({
87
+ siteDir,
88
+ themePath,
89
+ componentName,
90
+ typescript,
91
+ });
92
+ logger_1.default.success `
93
+ Created wrapper of name=${componentName} from name=${themeName} in path=${result.createdFiles}.
94
+ `;
95
+ return result;
96
+ }
97
+ case 'eject': {
98
+ const result = await (0, actions_1.eject)({
99
+ siteDir,
100
+ themePath,
101
+ componentName,
102
+ });
103
+ logger_1.default.success `
104
+ Ejected name=${componentName} from name=${themeName} to path=${result.createdFiles}.
105
+ `;
106
+ return result;
107
+ }
108
+ default:
109
+ throw new Error(`Unexpected action ${action}`);
110
+ }
111
+ }
112
+ await executeAction();
113
+ return process.exit(0);
114
+ }
115
+ exports.default = swizzle;
@@ -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 { ThemeComponents } from './components';
8
+ import type { SwizzleAction, SwizzleComponentConfig } from '@docusaurus/types';
9
+ export declare function askThemeName(themeNames: string[]): Promise<string>;
10
+ export declare function askComponentName(themeComponents: ThemeComponents): Promise<string>;
11
+ export declare function askSwizzleDangerousComponent(): Promise<boolean>;
12
+ export declare function askSwizzleAction(componentConfig: SwizzleComponentConfig): Promise<SwizzleAction>;
@@ -0,0 +1,110 @@
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.askSwizzleAction = exports.askSwizzleDangerousComponent = exports.askComponentName = exports.askThemeName = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
12
+ const prompts_1 = (0, tslib_1.__importDefault)(require("prompts"));
13
+ const common_1 = require("./common");
14
+ const ExitTitle = logger_1.default.yellow('[Exit]');
15
+ async function askThemeName(themeNames) {
16
+ const { themeName } = await (0, prompts_1.default)({
17
+ type: 'select',
18
+ name: 'themeName',
19
+ message: 'Select a theme to swizzle:',
20
+ choices: themeNames
21
+ .map((theme) => ({ title: theme, value: theme }))
22
+ .concat({ title: ExitTitle, value: '[Exit]' }),
23
+ });
24
+ if (!themeName || themeName === '[Exit]') {
25
+ process.exit(0);
26
+ }
27
+ return themeName;
28
+ }
29
+ exports.askThemeName = askThemeName;
30
+ async function askComponentName(themeComponents) {
31
+ function formatComponentName(componentName) {
32
+ const anySafe = themeComponents.hasAnySafeAction(componentName);
33
+ const allSafe = themeComponents.hasAllSafeAction(componentName);
34
+ const safestStatus = anySafe ? 'safe' : 'unsafe'; // Not 100% accurate but good enough for now.
35
+ const partiallySafe = anySafe && !allSafe;
36
+ return `${componentName}${(0, common_1.actionStatusSuffix)(safestStatus, {
37
+ partiallySafe,
38
+ })}`;
39
+ }
40
+ const { componentName } = await (0, prompts_1.default)({
41
+ type: 'autocomplete',
42
+ name: 'componentName',
43
+ message: `
44
+ Select or type the component to swizzle.
45
+ ${common_1.PartiallySafeHint} = not safe for all swizzle actions
46
+ `,
47
+ // This doesn't work well in small-height terminals (like IDE)
48
+ // limit: 30,
49
+ // This does not work well and messes up with terminal scroll position
50
+ // limit: Number.POSITIVE_INFINITY,
51
+ choices: themeComponents.all
52
+ .map((compName) => ({
53
+ title: formatComponentName(compName),
54
+ value: compName,
55
+ }))
56
+ .concat({ title: ExitTitle, value: '[Exit]' }),
57
+ async suggest(input, choices) {
58
+ return choices.filter((choice) => choice.title.toLowerCase().includes(input.toLowerCase()));
59
+ },
60
+ });
61
+ logger_1.default.newLine();
62
+ if (!componentName || componentName === '[Exit]') {
63
+ return process.exit(0);
64
+ }
65
+ return componentName;
66
+ }
67
+ exports.askComponentName = askComponentName;
68
+ async function askSwizzleDangerousComponent() {
69
+ const { switchToDanger } = await (0, prompts_1.default)({
70
+ type: 'select',
71
+ name: 'switchToDanger',
72
+ message: `Do you really want to swizzle this unsafe internal component?`,
73
+ choices: [
74
+ { title: logger_1.default.green('NO: cancel and stay safe'), value: false },
75
+ {
76
+ title: logger_1.default.red('YES: I know what I am doing!'),
77
+ value: true,
78
+ },
79
+ { title: ExitTitle, value: '[Exit]' },
80
+ ],
81
+ });
82
+ if (typeof switchToDanger === 'undefined' || switchToDanger === '[Exit]') {
83
+ return process.exit(0);
84
+ }
85
+ return !!switchToDanger;
86
+ }
87
+ exports.askSwizzleDangerousComponent = askSwizzleDangerousComponent;
88
+ async function askSwizzleAction(componentConfig) {
89
+ const { action } = await (0, prompts_1.default)({
90
+ type: 'select',
91
+ name: 'action',
92
+ message: `Which swizzle action do you want to do?`,
93
+ choices: [
94
+ {
95
+ title: `${logger_1.default.bold('Wrap')}${(0, common_1.actionStatusSuffix)(componentConfig.actions.wrap)}`,
96
+ value: 'wrap',
97
+ },
98
+ {
99
+ title: `${logger_1.default.bold('Eject')}${(0, common_1.actionStatusSuffix)(componentConfig.actions.eject)}`,
100
+ value: 'eject',
101
+ },
102
+ { title: ExitTitle, value: '[Exit]' },
103
+ ],
104
+ });
105
+ if (typeof action === 'undefined' || action === '[Exit]') {
106
+ return process.exit(0);
107
+ }
108
+ return action;
109
+ }
110
+ exports.askSwizzleAction = askSwizzleAction;
@@ -0,0 +1,9 @@
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 { ThemeComponents } from './components';
8
+ export declare function helpTables(): string;
9
+ export declare function themeComponentsTable(themeComponents: ThemeComponents): string;
@@ -0,0 +1,116 @@
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.themeComponentsTable = exports.helpTables = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
12
+ const cli_table3_1 = (0, tslib_1.__importDefault)(require("cli-table3"));
13
+ const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
14
+ const actions_1 = require("./actions");
15
+ const common_1 = require("./common");
16
+ function tableStatusLabel(status) {
17
+ return (0, common_1.actionStatusColor)(status, (0, common_1.actionStatusLabel)(status));
18
+ }
19
+ function getStatusLabel(status) {
20
+ return (0, common_1.actionStatusColor)(status, (0, common_1.actionStatusLabel)(status));
21
+ }
22
+ function statusTable() {
23
+ const table = new cli_table3_1.default({
24
+ head: ['Status', 'CLI option', 'Description'],
25
+ });
26
+ table.push({
27
+ [tableStatusLabel('safe')]: [
28
+ '',
29
+ `
30
+ This component is safe to swizzle and was designed for this purpose.
31
+ The swizzled component is retro-compatible with minor version upgrades.
32
+ `,
33
+ ],
34
+ });
35
+ table.push({
36
+ [tableStatusLabel('unsafe')]: [
37
+ logger_1.default.code('--danger'),
38
+ `
39
+ This component is unsafe to swizzle, but you can still do it!
40
+ Warning: we may release breaking changes within minor version upgrades.
41
+ You will have to upgrade your component manually and maintain it over time.
42
+
43
+ ${logger_1.default.green('Tip')}: your customization can't be done in a ${tableStatusLabel('safe')} way?
44
+ Report it here: https://github.com/facebook/docusaurus/discussions/5468
45
+ `,
46
+ ],
47
+ });
48
+ table.push({
49
+ [tableStatusLabel('forbidden')]: [
50
+ '',
51
+ `
52
+ This component should not meant to be swizzled.
53
+ `,
54
+ ],
55
+ });
56
+ return table.toString();
57
+ }
58
+ function actionsTable() {
59
+ const table = new cli_table3_1.default({
60
+ head: ['Actions', 'CLI option', 'Description'],
61
+ });
62
+ table.push({
63
+ [logger_1.default.bold('Wrap')]: [
64
+ logger_1.default.code('--wrap'),
65
+ `
66
+ Creates a wrapper around the original theme component.
67
+ Allows rendering other components before/after the original theme component.
68
+
69
+ ${logger_1.default.green('Tip')}: prefer ${logger_1.default.code('--wrap')} whenever possible to reduces the amount of code to maintain.
70
+ `,
71
+ ],
72
+ });
73
+ table.push({
74
+ [logger_1.default.bold('Eject')]: [
75
+ logger_1.default.code('--eject'),
76
+ `
77
+ Ejects the full source code of the original theme component.
78
+ Allows overriding the original component entirely with your own UI and logic.
79
+
80
+ ${logger_1.default.green('Tip')}: ${logger_1.default.code('--eject')} can be useful to completely redesign a component.
81
+ `,
82
+ ],
83
+ });
84
+ return table.toString();
85
+ }
86
+ function helpTables() {
87
+ return `${logger_1.default.bold('Swizzle actions')}:
88
+ ${actionsTable()}
89
+
90
+ ${logger_1.default.bold('Swizzle safety statuses')}:
91
+ ${statusTable()}
92
+
93
+ ${logger_1.default.bold('Swizzle guide')}: https://docusaurus.io/docs/swizzling`;
94
+ }
95
+ exports.helpTables = helpTables;
96
+ function themeComponentsTable(themeComponents) {
97
+ const table = new cli_table3_1.default({
98
+ head: [
99
+ 'Component name',
100
+ ...actions_1.SwizzleActions.map((action) => lodash_1.default.capitalize(action)),
101
+ 'Description',
102
+ ],
103
+ });
104
+ themeComponents.all.forEach((component) => {
105
+ table.push({
106
+ [component]: [
107
+ ...actions_1.SwizzleActions.map((action) => getStatusLabel(themeComponents.getActionStatus(component, action))),
108
+ themeComponents.getDescription(component),
109
+ ],
110
+ });
111
+ });
112
+ return `${logger_1.default.bold(`Components available for swizzle in ${logger_1.default.name(themeComponents.themeName)}`)}:
113
+ ${table.toString()}
114
+ `;
115
+ }
116
+ exports.themeComponentsTable = themeComponentsTable;