@docusaurus/core 0.0.0-4799 → 0.0.0-4800

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 (50) hide show
  1. package/lib/commands/build.js +4 -2
  2. package/lib/commands/commandUtils.js +2 -3
  3. package/lib/commands/deploy.js +2 -1
  4. package/lib/commands/external.js +1 -1
  5. package/lib/commands/serve.js +2 -2
  6. package/lib/commands/start.js +2 -1
  7. package/lib/commands/swizzle/common.d.ts +1 -2
  8. package/lib/commands/swizzle/context.js +2 -3
  9. package/lib/commands/writeHeadingIds.js +1 -1
  10. package/lib/commands/writeTranslations.js +2 -1
  11. package/lib/server/choosePort.d.ts +12 -0
  12. package/lib/{choosePort.js → server/choosePort.js} +8 -10
  13. package/lib/server/clientModules.d.ts +5 -1
  14. package/lib/server/clientModules.js +4 -0
  15. package/lib/server/config.d.ts +5 -2
  16. package/lib/server/config.js +11 -7
  17. package/lib/server/htmlTags.d.ts +6 -2
  18. package/lib/server/htmlTags.js +4 -0
  19. package/lib/server/i18n.d.ts +2 -3
  20. package/lib/server/index.d.ts +26 -10
  21. package/lib/server/index.js +34 -37
  22. package/lib/server/plugins/configs.d.ts +8 -2
  23. package/lib/server/plugins/configs.js +64 -5
  24. package/lib/server/plugins/index.d.ts +4 -0
  25. package/lib/server/plugins/index.js +20 -21
  26. package/lib/server/plugins/init.d.ts +5 -15
  27. package/lib/server/plugins/init.js +8 -61
  28. package/lib/server/{moduleShorthand.d.ts → plugins/moduleShorthand.d.ts} +0 -0
  29. package/lib/server/{moduleShorthand.js → plugins/moduleShorthand.js} +0 -0
  30. package/lib/server/plugins/pluginIds.d.ts +4 -0
  31. package/lib/server/plugins/pluginIds.js +4 -2
  32. package/lib/server/plugins/presets.d.ts +6 -5
  33. package/lib/server/plugins/presets.js +7 -3
  34. package/lib/server/routes.d.ts +3 -2
  35. package/lib/server/routes.js +49 -24
  36. package/lib/server/siteMetadata.d.ts +2 -2
  37. package/lib/server/siteMetadata.js +2 -1
  38. package/lib/server/translations/translations.js +1 -4
  39. package/lib/webpack/aliases/index.d.ts +29 -0
  40. package/lib/webpack/aliases/index.js +106 -0
  41. package/lib/webpack/base.d.ts +0 -3
  42. package/lib/webpack/base.js +4 -21
  43. package/package.json +10 -11
  44. package/lib/choosePort.d.ts +0 -11
  45. package/lib/server/duplicateRoutes.d.ts +0 -8
  46. package/lib/server/duplicateRoutes.js +0 -42
  47. package/lib/server/themes/alias.d.ts +0 -9
  48. package/lib/server/themes/alias.js +0 -50
  49. package/lib/server/themes/index.d.ts +0 -12
  50. package/lib/server/themes/index.js +0 -47
@@ -17,6 +17,10 @@ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
17
17
  const lodash_1 = tslib_1.__importDefault(require("lodash"));
18
18
  const translations_1 = require("../translations/translations");
19
19
  const routeConfig_1 = require("./routeConfig");
20
+ /**
21
+ * Initializes the plugins, runs `loadContent`, `translateContent`,
22
+ * `contentLoaded`, and `translateThemeConfig`.
23
+ */
20
24
  async function loadPlugins(context) {
21
25
  // 1. Plugin Lifecycle - Initialization/Constructor.
22
26
  const plugins = await (0, init_1.initPlugins)(context);
@@ -29,18 +33,18 @@ async function loadPlugins(context) {
29
33
  const content = await plugin.loadContent?.();
30
34
  return { ...plugin, content };
31
35
  }));
32
- const contentLoadedTranslatedPlugins = await Promise.all(loadedPlugins.map(async (contentLoadedPlugin) => {
33
- const translationFiles = (await contentLoadedPlugin?.getTranslationFiles?.({
34
- content: contentLoadedPlugin.content,
36
+ const contentLoadedTranslatedPlugins = await Promise.all(loadedPlugins.map(async (plugin) => {
37
+ const translationFiles = (await plugin?.getTranslationFiles?.({
38
+ content: plugin.content,
35
39
  })) ?? [];
36
40
  const localizedTranslationFiles = await Promise.all(translationFiles.map((translationFile) => (0, translations_1.localizePluginTranslationFile)({
37
41
  locale: context.i18n.currentLocale,
38
42
  siteDir: context.siteDir,
39
43
  translationFile,
40
- plugin: contentLoadedPlugin,
44
+ plugin,
41
45
  })));
42
46
  return {
43
- ...contentLoadedPlugin,
47
+ ...plugin,
44
48
  translationFiles: localizedTranslationFiles,
45
49
  };
46
50
  }));
@@ -109,9 +113,6 @@ async function loadPlugins(context) {
109
113
  });
110
114
  }));
111
115
  // 4. Plugin Lifecycle - routesLoaded.
112
- // Currently plugins run lifecycle methods in parallel and are not
113
- // order-dependent. We could change this in future if there are plugins which
114
- // need to run in certain order or depend on others for data.
115
116
  await Promise.all(contentLoadedTranslatedPlugins.map(async (plugin) => {
116
117
  if (!plugin.routesLoaded) {
117
118
  return;
@@ -126,23 +127,21 @@ async function loadPlugins(context) {
126
127
  // routes are always placed last.
127
128
  (0, routeConfig_1.sortConfig)(pluginsRouteConfigs, context.siteConfig.baseUrl);
128
129
  // Apply each plugin one after the other to translate the theme config
129
- function translateThemeConfig(untranslatedThemeConfig) {
130
- return contentLoadedTranslatedPlugins.reduce((currentThemeConfig, plugin) => {
131
- const translatedThemeConfigSlice = plugin.translateThemeConfig?.({
132
- themeConfig: currentThemeConfig,
133
- translationFiles: plugin.translationFiles,
134
- });
135
- return {
136
- ...currentThemeConfig,
137
- ...translatedThemeConfigSlice,
138
- };
139
- }, untranslatedThemeConfig);
140
- }
130
+ const themeConfigTranslated = contentLoadedTranslatedPlugins.reduce((currentThemeConfig, plugin) => {
131
+ const translatedThemeConfigSlice = plugin.translateThemeConfig?.({
132
+ themeConfig: currentThemeConfig,
133
+ translationFiles: plugin.translationFiles,
134
+ });
135
+ return {
136
+ ...currentThemeConfig,
137
+ ...translatedThemeConfigSlice,
138
+ };
139
+ }, context.siteConfig.themeConfig);
141
140
  return {
142
141
  plugins: loadedPlugins,
143
142
  pluginsRouteConfigs,
144
143
  globalData,
145
- themeConfigTranslated: translateThemeConfig(context.siteConfig.themeConfig),
144
+ themeConfigTranslated,
146
145
  };
147
146
  }
148
147
  exports.loadPlugins = loadPlugins;
@@ -4,19 +4,9 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import type { ImportedPluginModule, LoadContext, PluginModule, PluginConfig, PluginOptions, InitializedPlugin } from '@docusaurus/types';
8
- export declare type NormalizedPluginConfig = {
9
- plugin: PluginModule;
10
- options: PluginOptions;
11
- pluginModule?: {
12
- path: string;
13
- module: ImportedPluginModule;
14
- };
15
- /**
16
- * Different from pluginModule.path, this one is always an absolute path used
17
- * to resolve relative paths returned from lifecycles
18
- */
19
- entryPath: string;
20
- };
21
- export declare function normalizePluginConfigs(pluginConfigs: PluginConfig[], configPath: string): Promise<NormalizedPluginConfig[]>;
7
+ import type { LoadContext, InitializedPlugin } from '@docusaurus/types';
8
+ /**
9
+ * Runs the plugin constructors and returns their return values. It would load
10
+ * plugin configs from `plugins`, `themes`, and `presets`.
11
+ */
22
12
  export declare function initPlugins(context: LoadContext): Promise<InitializedPlugin[]>;
@@ -6,71 +6,15 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.initPlugins = exports.normalizePluginConfigs = void 0;
9
+ exports.initPlugins = void 0;
10
10
  const tslib_1 = require("tslib");
11
11
  const module_1 = require("module");
12
12
  const path_1 = tslib_1.__importDefault(require("path"));
13
- const import_fresh_1 = tslib_1.__importDefault(require("import-fresh"));
14
13
  const utils_1 = require("@docusaurus/utils");
15
14
  const siteMetadata_1 = require("../siteMetadata");
16
15
  const pluginIds_1 = require("./pluginIds");
17
16
  const utils_validation_1 = require("@docusaurus/utils-validation");
18
17
  const configs_1 = require("./configs");
19
- async function normalizePluginConfig(pluginConfig, configPath) {
20
- const pluginRequire = (0, module_1.createRequire)(configPath);
21
- // plugins: ['./plugin']
22
- if (typeof pluginConfig === 'string') {
23
- const pluginModuleImport = pluginConfig;
24
- const pluginPath = pluginRequire.resolve(pluginModuleImport);
25
- const pluginModule = (0, import_fresh_1.default)(pluginPath);
26
- return {
27
- plugin: pluginModule?.default ?? pluginModule,
28
- options: {},
29
- pluginModule: {
30
- path: pluginModuleImport,
31
- module: pluginModule,
32
- },
33
- entryPath: pluginPath,
34
- };
35
- }
36
- // plugins: [function plugin() { }]
37
- if (typeof pluginConfig === 'function') {
38
- return {
39
- plugin: pluginConfig,
40
- options: {},
41
- entryPath: configPath,
42
- };
43
- }
44
- // plugins: [
45
- // ['./plugin',options],
46
- // ]
47
- if (typeof pluginConfig[0] === 'string') {
48
- const pluginModuleImport = pluginConfig[0];
49
- const pluginPath = pluginRequire.resolve(pluginModuleImport);
50
- const pluginModule = (0, import_fresh_1.default)(pluginPath);
51
- return {
52
- plugin: pluginModule?.default ?? pluginModule,
53
- options: pluginConfig[1],
54
- pluginModule: {
55
- path: pluginModuleImport,
56
- module: pluginModule,
57
- },
58
- entryPath: pluginPath,
59
- };
60
- }
61
- // plugins: [
62
- // [function plugin() { },options],
63
- // ]
64
- return {
65
- plugin: pluginConfig[0],
66
- options: pluginConfig[1],
67
- entryPath: configPath,
68
- };
69
- }
70
- async function normalizePluginConfigs(pluginConfigs, configPath) {
71
- return Promise.all(pluginConfigs.map((pluginConfig) => normalizePluginConfig(pluginConfig, configPath)));
72
- }
73
- exports.normalizePluginConfigs = normalizePluginConfigs;
74
18
  function getOptionValidationFunction(normalizedPluginConfig) {
75
19
  if (normalizedPluginConfig.pluginModule) {
76
20
  // support both commonjs and ES modules
@@ -87,12 +31,15 @@ function getThemeValidationFunction(normalizedPluginConfig) {
87
31
  }
88
32
  return normalizedPluginConfig.plugin.validateThemeConfig;
89
33
  }
34
+ /**
35
+ * Runs the plugin constructors and returns their return values. It would load
36
+ * plugin configs from `plugins`, `themes`, and `presets`.
37
+ */
90
38
  async function initPlugins(context) {
91
- // We need to resolve plugins from the perspective of the siteDir, since the
92
- // siteDir's package.json declares the dependency on these plugins.
39
+ // We need to resolve plugins from the perspective of the site config, as if
40
+ // we are using `require.resolve` on those module names.
93
41
  const pluginRequire = (0, module_1.createRequire)(context.siteConfigPath);
94
42
  const pluginConfigs = await (0, configs_1.loadPluginConfigs)(context);
95
- const pluginConfigsNormalized = await normalizePluginConfigs(pluginConfigs, context.siteConfigPath);
96
43
  async function doGetPluginVersion(normalizedPluginConfig) {
97
44
  // get plugin version
98
45
  if (normalizedPluginConfig.pluginModule?.path) {
@@ -142,7 +89,7 @@ async function initPlugins(context) {
142
89
  path: path_1.default.dirname(normalizedPluginConfig.entryPath),
143
90
  };
144
91
  }
145
- const plugins = await Promise.all(pluginConfigsNormalized.map(initializePlugin));
92
+ const plugins = await Promise.all(pluginConfigs.map(initializePlugin));
146
93
  (0, pluginIds_1.ensureUniquePluginInstanceIds)(plugins);
147
94
  return plugins;
148
95
  }
@@ -5,4 +5,8 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  import type { InitializedPlugin } from '@docusaurus/types';
8
+ /**
9
+ * It is forbidden to have 2 plugins of the same name sharing the same ID.
10
+ * This is required to support multi-instance plugins without conflict.
11
+ */
8
12
  export declare function ensureUniquePluginInstanceIds(plugins: InitializedPlugin[]): void;
@@ -10,8 +10,10 @@ exports.ensureUniquePluginInstanceIds = void 0;
10
10
  const tslib_1 = require("tslib");
11
11
  const lodash_1 = tslib_1.__importDefault(require("lodash"));
12
12
  const utils_1 = require("@docusaurus/utils");
13
- // It is forbidden to have 2 plugins of the same name sharing the same id
14
- // this is required to support multi-instance plugins without conflict
13
+ /**
14
+ * It is forbidden to have 2 plugins of the same name sharing the same ID.
15
+ * This is required to support multi-instance plugins without conflict.
16
+ */
15
17
  function ensureUniquePluginInstanceIds(plugins) {
16
18
  const pluginsByName = lodash_1.default.groupBy(plugins, (p) => p.name);
17
19
  Object.entries(pluginsByName).forEach(([pluginName, pluginInstances]) => {
@@ -4,8 +4,9 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import type { LoadContext, PluginConfig } from '@docusaurus/types';
8
- export declare function loadPresets(context: LoadContext): Promise<{
9
- plugins: PluginConfig[];
10
- themes: PluginConfig[];
11
- }>;
7
+ import type { LoadContext, DocusaurusConfig } from '@docusaurus/types';
8
+ /**
9
+ * Calls preset functions, aggregates each of their return values, and returns
10
+ * the plugin and theme configs.
11
+ */
12
+ export declare function loadPresets(context: LoadContext): Promise<Pick<DocusaurusConfig, 'plugins' | 'themes'>>;
@@ -10,10 +10,14 @@ exports.loadPresets = void 0;
10
10
  const tslib_1 = require("tslib");
11
11
  const module_1 = require("module");
12
12
  const import_fresh_1 = tslib_1.__importDefault(require("import-fresh"));
13
- const moduleShorthand_1 = require("../moduleShorthand");
13
+ const moduleShorthand_1 = require("./moduleShorthand");
14
+ /**
15
+ * Calls preset functions, aggregates each of their return values, and returns
16
+ * the plugin and theme configs.
17
+ */
14
18
  async function loadPresets(context) {
15
- // We need to resolve presets from the perspective of the siteDir, since the
16
- // siteDir's package.json declares the dependency on these presets.
19
+ // We need to resolve plugins from the perspective of the site config, as if
20
+ // we are using `require.resolve` on those module names.
17
21
  const presetRequire = (0, module_1.createRequire)(context.siteConfigPath);
18
22
  const { presets } = context.siteConfig;
19
23
  const plugins = [];
@@ -4,8 +4,9 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import type { ChunkRegistry, RouteConfig, ChunkNames } from '@docusaurus/types';
8
- export declare function loadRoutes(pluginsRouteConfigs: RouteConfig[], baseUrl: string): Promise<{
7
+ import type { ChunkRegistry, RouteConfig, ChunkNames, ReportingSeverity } from '@docusaurus/types';
8
+ export declare function handleDuplicateRoutes(pluginsRouteConfigs: RouteConfig[], onDuplicateRoutes: ReportingSeverity): void;
9
+ export declare function loadRoutes(pluginsRouteConfigs: RouteConfig[], baseUrl: string, onDuplicateRoutes: ReportingSeverity): Promise<{
9
10
  registry: {
10
11
  [chunkName: string]: ChunkRegistry;
11
12
  };
@@ -6,9 +6,10 @@
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 = void 0;
9
+ exports.loadRoutes = exports.handleDuplicateRoutes = void 0;
10
10
  const utils_1 = require("@docusaurus/utils");
11
11
  const querystring_1 = require("querystring");
12
+ const utils_2 = require("./utils");
12
13
  function indent(str) {
13
14
  const spaces = ' ';
14
15
  return `${spaces}${str.replace(/\n/g, `\n${spaces}`)}`;
@@ -78,7 +79,53 @@ function getModulePath(target) {
78
79
  const queryStr = target.query ? `?${(0, querystring_1.stringify)(target.query)}` : '';
79
80
  return `${target.path}${queryStr}`;
80
81
  }
81
- async function loadRoutes(pluginsRouteConfigs, baseUrl) {
82
+ function genRouteChunkNames(
83
+ // TODO instead of passing a mutating the registry, return a registry slice?
84
+ registry, value, prefix, name) {
85
+ if (!value) {
86
+ return null;
87
+ }
88
+ if (Array.isArray(value)) {
89
+ return value.map((val, index) => genRouteChunkNames(registry, val, `${index}`, name));
90
+ }
91
+ if (isModule(value)) {
92
+ const modulePath = getModulePath(value);
93
+ const chunkName = (0, utils_1.genChunkName)(modulePath, prefix, name);
94
+ const loader = `() => import(/* webpackChunkName: '${chunkName}' */ '${(0, utils_1.escapePath)(modulePath)}')`;
95
+ registry[chunkName] = { loader, modulePath };
96
+ return chunkName;
97
+ }
98
+ const newValue = {};
99
+ Object.entries(value).forEach(([key, v]) => {
100
+ newValue[key] = genRouteChunkNames(registry, v, key, name);
101
+ });
102
+ return newValue;
103
+ }
104
+ function handleDuplicateRoutes(pluginsRouteConfigs, onDuplicateRoutes) {
105
+ if (onDuplicateRoutes === 'ignore') {
106
+ return;
107
+ }
108
+ const allRoutes = (0, utils_2.getAllFinalRoutes)(pluginsRouteConfigs).map((routeConfig) => routeConfig.path);
109
+ const seenRoutes = new Set();
110
+ const duplicatePaths = allRoutes.filter((route) => {
111
+ if (seenRoutes.has(route)) {
112
+ return true;
113
+ }
114
+ seenRoutes.add(route);
115
+ return false;
116
+ });
117
+ if (duplicatePaths.length > 0) {
118
+ const finalMessage = `Duplicate routes found!
119
+ ${duplicatePaths
120
+ .map((duplicateRoute) => `- Attempting to create page at ${duplicateRoute}, but a page already exists at this route.`)
121
+ .join('\n')}
122
+ This could lead to non-deterministic routing behavior.`;
123
+ (0, utils_1.reportMessage)(finalMessage, onDuplicateRoutes);
124
+ }
125
+ }
126
+ exports.handleDuplicateRoutes = handleDuplicateRoutes;
127
+ async function loadRoutes(pluginsRouteConfigs, baseUrl, onDuplicateRoutes) {
128
+ handleDuplicateRoutes(pluginsRouteConfigs, onDuplicateRoutes);
82
129
  const registry = {};
83
130
  const routesPaths = [(0, utils_1.normalizeUrl)([baseUrl, '404.html'])];
84
131
  const routesChunkNames = {};
@@ -129,25 +176,3 @@ ${indent(NotFoundRouteCode)}
129
176
  };
130
177
  }
131
178
  exports.loadRoutes = loadRoutes;
132
- function genRouteChunkNames(
133
- // TODO instead of passing a mutating the registry, return a registry slice?
134
- registry, value, prefix, name) {
135
- if (!value) {
136
- return null;
137
- }
138
- if (Array.isArray(value)) {
139
- return value.map((val, index) => genRouteChunkNames(registry, val, `${index}`, name));
140
- }
141
- if (isModule(value)) {
142
- const modulePath = getModulePath(value);
143
- const chunkName = (0, utils_1.genChunkName)(modulePath, prefix, name);
144
- const loader = `() => import(/* webpackChunkName: '${chunkName}' */ '${(0, utils_1.escapePath)(modulePath)}')`;
145
- registry[chunkName] = { loader, modulePath };
146
- return chunkName;
147
- }
148
- const newValue = {};
149
- Object.entries(value).forEach(([key, v]) => {
150
- newValue[key] = genRouteChunkNames(registry, v, key, name);
151
- });
152
- return newValue;
153
- }
@@ -4,9 +4,9 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import type { LoadedPlugin, PluginVersionInformation, DocusaurusSiteMetadata } from '@docusaurus/types';
7
+ import type { LoadedPlugin, PluginVersionInformation, SiteMetadata } from '@docusaurus/types';
8
8
  export declare function getPluginVersion(pluginPath: string, siteDir: string): Promise<PluginVersionInformation>;
9
9
  export declare function loadSiteMetadata({ plugins, siteDir, }: {
10
10
  plugins: LoadedPlugin[];
11
11
  siteDir: string;
12
- }): Promise<DocusaurusSiteMetadata>;
12
+ }): Promise<SiteMetadata>;
@@ -42,7 +42,8 @@ async function getPluginVersion(pluginPath, siteDir) {
42
42
  potentialPluginPackageJsonDirectory = path_1.default.dirname(potentialPluginPackageJsonDirectory);
43
43
  }
44
44
  // In the case where a plugin is a path where no parent directory contains
45
- // package.json (e.g. inline plugin), we can only classify it as local.
45
+ // package.json, we can only classify it as local. Could happen if one puts a
46
+ // script in the parent directory of the site.
46
47
  return { type: 'local' };
47
48
  }
48
49
  exports.getPluginVersion = getPluginVersion;
@@ -80,11 +80,8 @@ Maybe you should remove them? ${unknownKeys}`;
80
80
  }
81
81
  }
82
82
  // should we make this configurable?
83
- function getTranslationsDirPath(context) {
84
- return path_1.default.join(context.siteDir, utils_1.I18N_DIR_NAME);
85
- }
86
83
  function getTranslationsLocaleDirPath(context) {
87
- return path_1.default.join(getTranslationsDirPath(context), context.locale);
84
+ return path_1.default.join(context.siteDir, utils_1.I18N_DIR_NAME, context.locale);
88
85
  }
89
86
  exports.getTranslationsLocaleDirPath = getTranslationsLocaleDirPath;
90
87
  function getCodeTranslationsFilePath(context) {
@@ -0,0 +1,29 @@
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 { ThemeAliases, LoadedPlugin } from '@docusaurus/types';
8
+ /**
9
+ * Order of Webpack aliases is important because one alias can shadow another.
10
+ * This ensures `@theme/NavbarItem` alias is after
11
+ * `@theme/NavbarItem/LocaleDropdown`.
12
+ *
13
+ * @see https://github.com/facebook/docusaurus/pull/3922
14
+ * @see https://github.com/facebook/docusaurus/issues/5382
15
+ */
16
+ export declare function sortAliases(aliases: ThemeAliases): ThemeAliases;
17
+ export declare function createAliasesForTheme(themePath: string, addOriginalAlias: boolean): Promise<ThemeAliases>;
18
+ export declare function loadThemeAliases({ siteDir, plugins, }: {
19
+ siteDir: string;
20
+ plugins: LoadedPlugin[];
21
+ }): Promise<ThemeAliases>;
22
+ /**
23
+ * Note: a `@docusaurus` alias would also catch `@docusaurus/theme-common`, so
24
+ * instead of naively aliasing this to `client/exports`, we use fine-grained
25
+ * aliases instead.
26
+ */
27
+ export declare function loadDocusaurusAliases(): Promise<{
28
+ [aliasName: string]: string;
29
+ }>;
@@ -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 utils_1 = require("@docusaurus/utils");
14
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
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;
@@ -8,7 +8,4 @@ import type { Configuration } from 'webpack';
8
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(): Promise<{
12
- [aliasName: string]: string;
13
- }>;
14
11
  export declare function createBaseConfig(props: Props, isServer: boolean, minify?: boolean): Promise<Configuration>;
@@ -6,13 +6,13 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.createBaseConfig = exports.getDocusaurusAliases = exports.excludeJS = exports.clientDir = void 0;
9
+ exports.createBaseConfig = exports.excludeJS = exports.clientDir = void 0;
10
10
  const tslib_1 = require("tslib");
11
11
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
12
  const mini_css_extract_plugin_1 = tslib_1.__importDefault(require("mini-css-extract-plugin"));
13
13
  const path_1 = tslib_1.__importDefault(require("path"));
14
14
  const utils_1 = require("./utils");
15
- const themes_1 = require("../server/themes");
15
+ const aliases_1 = require("./aliases");
16
16
  const utils_2 = require("@docusaurus/utils");
17
17
  const CSS_REGEX = /\.css$/i;
18
18
  const CSS_MODULE_REGEX = /\.module\.css$/i;
@@ -32,20 +32,6 @@ function excludeJS(modulePath) {
32
32
  !LibrariesToTranspileRegex.test(modulePath));
33
33
  }
34
34
  exports.excludeJS = excludeJS;
35
- async function getDocusaurusAliases() {
36
- const dirPath = path_1.default.resolve(__dirname, '../client/exports');
37
- const extensions = ['.js', '.ts', '.tsx'];
38
- const aliases = {};
39
- (await fs_extra_1.default.readdir(dirPath))
40
- .filter((fileName) => extensions.includes(path_1.default.extname(fileName)))
41
- .forEach((fileName) => {
42
- const fileNameWithoutExtension = path_1.default.basename(fileName, path_1.default.extname(fileName));
43
- const aliasName = `@docusaurus/${fileNameWithoutExtension}`;
44
- aliases[aliasName] = path_1.default.resolve(dirPath, fileName);
45
- });
46
- return aliases;
47
- }
48
- exports.getDocusaurusAliases = getDocusaurusAliases;
49
35
  async function createBaseConfig(props, isServer, minify = true) {
50
36
  const { outDir, siteDir, siteConfig, siteConfigPath, baseUrl, generatedFilesDir, routesPaths, siteMetadata, plugins, } = props;
51
37
  const totalPages = routesPaths.length;
@@ -55,7 +41,7 @@ async function createBaseConfig(props, isServer, minify = true) {
55
41
  const fileLoaderUtils = (0, utils_2.getFileLoaderUtils)();
56
42
  const name = isServer ? 'server' : 'client';
57
43
  const mode = isProd ? 'production' : 'development';
58
- const themeAliases = await (0, themes_1.loadPluginsThemeAliases)({ siteDir, plugins });
44
+ const themeAliases = await (0, aliases_1.loadThemeAliases)({ siteDir, plugins });
59
45
  return {
60
46
  mode,
61
47
  name,
@@ -116,10 +102,7 @@ async function createBaseConfig(props, isServer, minify = true) {
116
102
  alias: {
117
103
  '@site': siteDir,
118
104
  '@generated': generatedFilesDir,
119
- // Note: a @docusaurus alias would also catch @docusaurus/theme-common,
120
- // so we use fine-grained aliases instead
121
- // '@docusaurus': path.resolve(__dirname, '../client/exports'),
122
- ...(await getDocusaurusAliases()),
105
+ ...(await (0, aliases_1.loadDocusaurusAliases)()),
123
106
  ...themeAliases,
124
107
  },
125
108
  // This allows you to set a fallback for where Webpack should look for