@docusaurus/core 0.0.0-4811 → 0.0.0-4814

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.
@@ -16,66 +16,86 @@ export default function ComponentCreator(path, hash) {
16
16
  if (path === '*') {
17
17
  return Loadable({
18
18
  loading: Loading,
19
- loader: async () => {
20
- const NotFound = (await import('@theme/NotFound')).default;
21
- return (props) => (
22
- // Is there a better API for this?
23
- <RouteContextProvider value={{ plugin: { name: 'native', id: 'default' } }}>
19
+ loader: () => import('@theme/NotFound').then(({ default: NotFound }) => (props) => (<RouteContextProvider
20
+ // Do we want a better name than native-default?
21
+ value={{ plugin: { name: 'native', id: 'default' } }}>
24
22
  <NotFound {...props}/>
25
- </RouteContextProvider>);
26
- },
23
+ </RouteContextProvider>)),
27
24
  });
28
25
  }
29
26
  const chunkNames = routesChunkNames[`${path}-${hash}`];
30
27
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
- const optsLoader = {};
32
- const optsModules = [];
28
+ const loader = {};
29
+ const modules = [];
33
30
  const optsWebpack = [];
31
+ // A map from prop names to chunk names.
32
+ // e.g. Suppose the plugin added this as route:
33
+ // { __comp: "...", prop: { foo: "..." }, items: ["...", "..."] }
34
+ // It will become:
35
+ // { __comp: "...", "prop.foo": "...", "items.0": "...", "items.1": ... }
36
+ // Loadable.Map will _map_ over `loader` and load each key.
34
37
  const flatChunkNames = flat(chunkNames);
35
- Object.entries(flatChunkNames).forEach(([key, chunkName]) => {
38
+ Object.entries(flatChunkNames).forEach(([keyPath, chunkName]) => {
36
39
  const chunkRegistry = registry[chunkName];
37
40
  if (chunkRegistry) {
38
41
  // eslint-disable-next-line prefer-destructuring
39
- optsLoader[key] = chunkRegistry[0];
40
- optsModules.push(chunkRegistry[1]);
42
+ loader[keyPath] = chunkRegistry[0];
43
+ modules.push(chunkRegistry[1]);
41
44
  optsWebpack.push(chunkRegistry[2]);
42
45
  }
43
46
  });
44
47
  return Loadable.Map({
45
48
  loading: Loading,
46
- loader: optsLoader,
47
- modules: optsModules,
49
+ loader,
50
+ modules,
48
51
  webpack: () => optsWebpack,
49
52
  render: (loaded, props) => {
50
- // Clone the original object since we don't want to alter the original.
53
+ // `loaded` will be a map from key path (as returned from the flattened
54
+ // chunk names) to the modules loaded from the loaders. We now have to
55
+ // restore the chunk names' previous shape from this flat record.
56
+ // We do so by taking advantage of the existing `chunkNames` and replacing
57
+ // each chunk name with its loaded module, so we don't create another
58
+ // object from scratch.
51
59
  const loadedModules = JSON.parse(JSON.stringify(chunkNames));
52
- Object.keys(loaded).forEach((key) => {
53
- const newComp = loaded[key].default;
54
- if (!newComp) {
60
+ Object.entries(loaded).forEach(([keyPath, loadedModule]) => {
61
+ // JSON modules are also loaded as `{ default: ... }` (`import()`
62
+ // semantics) but we just want to pass the actual value to props.
63
+ const chunk = loadedModule.default;
64
+ // One loaded chunk can only be one of two things: a module (props) or a
65
+ // component. Modules are always JSON, so `default` always exists. This
66
+ // could only happen with a user-defined component.
67
+ if (!chunk) {
55
68
  throw new Error(`The page component at ${path} doesn't have a default export. This makes it impossible to render anything. Consider default-exporting a React component.`);
56
69
  }
57
- if (typeof newComp === 'object' || typeof newComp === 'function') {
58
- Object.keys(loaded[key])
70
+ // A module can be a primitive, for example, if the user stored a string
71
+ // as a prop. However, there seems to be a bug with swc-loader's CJS
72
+ // logic, in that it would load a JSON module with content "foo" as
73
+ // `{ default: "foo", 0: "f", 1: "o", 2: "o" }`. Just to be safe, we
74
+ // first make sure that the chunk is non-primitive.
75
+ if (typeof chunk === 'object' || typeof chunk === 'function') {
76
+ Object.keys(loadedModule)
59
77
  .filter((k) => k !== 'default')
60
78
  .forEach((nonDefaultKey) => {
61
- newComp[nonDefaultKey] = loaded[key][nonDefaultKey];
79
+ chunk[nonDefaultKey] = loadedModule[nonDefaultKey];
62
80
  });
63
81
  }
82
+ // We now have this chunk prepared. Go down the key path and replace the
83
+ // chunk name with the actual chunk.
64
84
  let val = loadedModules;
65
- const keyPath = key.split('.');
66
- keyPath.slice(0, -1).forEach((k) => {
85
+ const keyPaths = keyPath.split('.');
86
+ keyPaths.slice(0, -1).forEach((k) => {
67
87
  val = val[k];
68
88
  });
69
- val[keyPath[keyPath.length - 1]] = newComp;
89
+ val[keyPaths[keyPaths.length - 1]] = chunk;
70
90
  });
71
- const Component = loadedModules.component;
72
- delete loadedModules.component;
73
91
  /* eslint-disable no-underscore-dangle */
74
- const routeContextModule = loadedModules.__routeContextModule;
75
- delete loadedModules.__routeContextModule;
92
+ const Component = loadedModules.__comp;
93
+ delete loadedModules.__comp;
94
+ const routeContext = loadedModules.__context;
95
+ delete loadedModules.__context;
76
96
  /* eslint-enable no-underscore-dangle */
77
97
  // Is there any way to put this RouteContextProvider upper in the tree?
78
- return (<RouteContextProvider value={routeContextModule}>
98
+ return (<RouteContextProvider value={routeContext}>
79
99
  <Component {...loadedModules} {...props}/>
80
100
  </RouteContextProvider>);
81
101
  },
@@ -4,20 +4,14 @@
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
- function support(feature) {
8
- if (typeof document === 'undefined') {
9
- return false;
10
- }
11
- const fakeLink = document.createElement('link');
7
+ function supports(feature) {
12
8
  try {
13
- if (fakeLink.relList && typeof fakeLink.relList.supports === 'function') {
14
- return fakeLink.relList.supports(feature);
15
- }
9
+ const fakeLink = document.createElement('link');
10
+ return fakeLink.relList?.supports?.(feature);
16
11
  }
17
12
  catch (err) {
18
13
  return false;
19
14
  }
20
- return false;
21
15
  }
22
16
  function linkPrefetchStrategy(url) {
23
17
  return new Promise((resolve, reject) => {
@@ -51,7 +45,7 @@ function xhrPrefetchStrategy(url) {
51
45
  req.send(null);
52
46
  });
53
47
  }
54
- const supportedPrefetchStrategy = support('prefetch')
48
+ const supportedPrefetchStrategy = supports('prefetch')
55
49
  ? linkPrefetchStrategy
56
50
  : xhrPrefetchStrategy;
57
51
  const preFetched = {};
@@ -51,12 +51,12 @@ async function doRender(locals) {
51
51
  const location = routesLocation[locals.path];
52
52
  await preload(routes, location);
53
53
  const modules = new Set();
54
- const context = {};
54
+ const routerContext = {};
55
55
  const helmetContext = {};
56
56
  const linksCollector = createStatefulLinksCollector();
57
57
  const appHtml = ReactDOMServer.renderToString(<Loadable.Capture report={(moduleName) => modules.add(moduleName)}>
58
58
  <HelmetProvider context={helmetContext}>
59
- <StaticRouter location={location} context={context}>
59
+ <StaticRouter location={location} context={routerContext}>
60
60
  <LinksCollectorProvider linksCollector={linksCollector}>
61
61
  <App />
62
62
  </LinksCollectorProvider>
@@ -76,9 +76,7 @@ async function load(options) {
76
76
  const { siteDir } = options;
77
77
  const context = await loadContext(options);
78
78
  const { generatedFilesDir, siteConfig, siteConfigPath, outDir, baseUrl, i18n, ssrTemplate, codeTranslations: siteCodeTranslations, } = context;
79
- const { plugins, pluginsRouteConfigs, globalData, themeConfigTranslated } = await (0, plugins_1.loadPlugins)(context);
80
- // Side-effect to replace the untranslated themeConfig by the translated one
81
- context.siteConfig.themeConfig = themeConfigTranslated;
79
+ const { plugins, pluginsRouteConfigs, globalData } = await (0, plugins_1.loadPlugins)(context);
82
80
  const clientModules = (0, clientModules_1.loadClientModules)(plugins);
83
81
  const { headTags, preBodyTags, postBodyTags } = (0, htmlTags_1.loadHtmlTags)(plugins);
84
82
  const { registry, routesChunkNames, routesConfig, routesPaths } = await (0, routes_1.loadRoutes)(pluginsRouteConfigs, baseUrl, siteConfig.onDuplicateRoutes);
@@ -4,15 +4,15 @@
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, RouteConfig, GlobalData, ThemeConfig, LoadedPlugin } from '@docusaurus/types';
7
+ import type { LoadContext, RouteConfig, GlobalData, LoadedPlugin } from '@docusaurus/types';
8
8
  /**
9
9
  * Initializes the plugins, runs `loadContent`, `translateContent`,
10
10
  * `contentLoaded`, and `translateThemeConfig`. Because `contentLoaded` is
11
- * side-effect-ful (it generates temp files), so is this function.
11
+ * side-effect-ful (it generates temp files), so is this function. This function
12
+ * would also mutate `context.siteConfig.themeConfig` to translate it.
12
13
  */
13
14
  export declare function loadPlugins(context: LoadContext): Promise<{
14
15
  plugins: LoadedPlugin[];
15
16
  pluginsRouteConfigs: RouteConfig[];
16
17
  globalData: GlobalData;
17
- themeConfigTranslated: ThemeConfig;
18
18
  }>;
@@ -19,7 +19,8 @@ const routeConfig_1 = require("./routeConfig");
19
19
  /**
20
20
  * Initializes the plugins, runs `loadContent`, `translateContent`,
21
21
  * `contentLoaded`, and `translateThemeConfig`. Because `contentLoaded` is
22
- * side-effect-ful (it generates temp files), so is this function.
22
+ * side-effect-ful (it generates temp files), so is this function. This function
23
+ * would also mutate `context.siteConfig.themeConfig` to translate it.
23
24
  */
24
25
  async function loadPlugins(context) {
25
26
  // 1. Plugin Lifecycle - Initialization/Constructor.
@@ -29,24 +30,27 @@ async function loadPlugins(context) {
29
30
  // Currently plugins run lifecycle methods in parallel and are not
30
31
  // order-dependent. We could change this in future if there are plugins which
31
32
  // need to run in certain order or depend on others for data.
33
+ // This would also translate theme config and content upfront, given the
34
+ // translation files that the plugin declares.
32
35
  const loadedPlugins = await Promise.all(plugins.map(async (plugin) => {
33
36
  const content = await plugin.loadContent?.();
34
- return { ...plugin, content };
35
- }));
36
- const contentLoadedTranslatedPlugins = await Promise.all(loadedPlugins.map(async (plugin) => {
37
- const translationFiles = (await plugin?.getTranslationFiles?.({
38
- content: plugin.content,
39
- })) ?? [];
40
- const localizedTranslationFiles = await Promise.all(translationFiles.map((translationFile) => (0, translations_1.localizePluginTranslationFile)({
37
+ const rawTranslationFiles = (await plugin?.getTranslationFiles?.({ content })) ?? [];
38
+ const translationFiles = await Promise.all(rawTranslationFiles.map((translationFile) => (0, translations_1.localizePluginTranslationFile)({
41
39
  locale: context.i18n.currentLocale,
42
40
  siteDir: context.siteDir,
43
41
  translationFile,
44
42
  plugin,
45
43
  })));
46
- return {
47
- ...plugin,
48
- translationFiles: localizedTranslationFiles,
49
- };
44
+ const translatedContent = plugin.translateContent?.({ content, translationFiles }) ?? content;
45
+ const translatedThemeConfigSlice = plugin.translateThemeConfig?.({
46
+ themeConfig: context.siteConfig.themeConfig,
47
+ translationFiles,
48
+ });
49
+ // Side-effect to merge theme config translations. A plugin should only
50
+ // translate its own slice of theme config and should make no assumptions
51
+ // about other plugins' keys, so this is safe to run in parallel.
52
+ Object.assign(context.siteConfig.themeConfig, translatedThemeConfigSlice);
53
+ return { ...plugin, content: translatedContent };
50
54
  }));
51
55
  const allContent = lodash_1.default.chain(loadedPlugins)
52
56
  .groupBy((item) => item.name)
@@ -58,7 +62,7 @@ async function loadPlugins(context) {
58
62
  // 3. Plugin Lifecycle - contentLoaded.
59
63
  const pluginsRouteConfigs = [];
60
64
  const globalData = {};
61
- await Promise.all(contentLoadedTranslatedPlugins.map(async ({ content, translationFiles, ...plugin }) => {
65
+ await Promise.all(loadedPlugins.map(async ({ content, ...plugin }) => {
62
66
  if (!plugin.contentLoaded) {
63
67
  return;
64
68
  }
@@ -81,7 +85,7 @@ async function loadPlugins(context) {
81
85
  ...finalRouteConfig,
82
86
  modules: {
83
87
  ...finalRouteConfig.modules,
84
- __routeContextModule: pluginRouteContextModulePath,
88
+ __context: pluginRouteContextModulePath,
85
89
  },
86
90
  });
87
91
  },
@@ -96,43 +100,21 @@ async function loadPlugins(context) {
96
100
  globalData[plugin.name][pluginId] = data;
97
101
  },
98
102
  };
99
- const translatedContent = plugin.translateContent?.({ content, translationFiles }) ?? content;
100
- await plugin.contentLoaded({
101
- content: translatedContent,
102
- actions,
103
- allContent,
104
- });
103
+ await plugin.contentLoaded({ content, actions, allContent });
105
104
  }));
106
105
  // 4. Plugin Lifecycle - routesLoaded.
107
- await Promise.all(contentLoadedTranslatedPlugins.map(async (plugin) => {
106
+ await Promise.all(loadedPlugins.map(async (plugin) => {
108
107
  if (!plugin.routesLoaded) {
109
108
  return;
110
109
  }
111
- // TODO remove this deprecated lifecycle soon
112
- // deprecated since alpha-60
113
- // TODO, 1 user reported usage of this lifecycle! https://github.com/facebook/docusaurus/issues/3918
110
+ // TODO alpha-60: remove this deprecated lifecycle soon
111
+ // 1 user reported usage of this lifecycle: https://github.com/facebook/docusaurus/issues/3918
114
112
  logger_1.default.error `Plugin code=${'routesLoaded'} lifecycle is deprecated. If you think we should keep this lifecycle, please report here: url=${'https://github.com/facebook/docusaurus/issues/3918'}`;
115
113
  await plugin.routesLoaded(pluginsRouteConfigs);
116
114
  }));
117
115
  // Sort the route config. This ensures that route with nested
118
116
  // routes are always placed last.
119
117
  (0, routeConfig_1.sortConfig)(pluginsRouteConfigs, context.siteConfig.baseUrl);
120
- // Apply each plugin one after the other to translate the theme config
121
- const themeConfigTranslated = contentLoadedTranslatedPlugins.reduce((currentThemeConfig, plugin) => {
122
- const translatedThemeConfigSlice = plugin.translateThemeConfig?.({
123
- themeConfig: currentThemeConfig,
124
- translationFiles: plugin.translationFiles,
125
- });
126
- return {
127
- ...currentThemeConfig,
128
- ...translatedThemeConfigSlice,
129
- };
130
- }, context.siteConfig.themeConfig);
131
- return {
132
- plugins: loadedPlugins,
133
- pluginsRouteConfigs,
134
- globalData,
135
- themeConfigTranslated,
136
- };
118
+ return { plugins: loadedPlugins, pluginsRouteConfigs, globalData };
137
119
  }
138
120
  exports.loadPlugins = loadPlugins;
@@ -95,7 +95,10 @@ const isModule = (value) => typeof value === 'string' ||
95
95
  (typeof value === 'object' &&
96
96
  // eslint-disable-next-line no-underscore-dangle
97
97
  !!value?.__import);
98
- /** Takes a {@link Module} and returns the string path it represents. */
98
+ /**
99
+ * Takes a {@link Module} (which is nothing more than a path plus some metadata
100
+ * like query) and returns the string path it represents.
101
+ */
99
102
  function getModulePath(target) {
100
103
  if (typeof target === 'string') {
101
104
  return target;
@@ -144,7 +147,7 @@ This could lead to non-deterministic routing behavior.`;
144
147
  exports.handleDuplicateRoutes = handleDuplicateRoutes;
145
148
  /**
146
149
  * This is the higher level overview of route code generation. For each route
147
- * config node, it return the node's serialized form, and mutate `registry`,
150
+ * config node, it returns the node's serialized form, and mutates `registry`,
148
151
  * `routesPaths`, and `routesChunkNames` accordingly.
149
152
  */
150
153
  function genRouteCode(routeConfig, res) {
@@ -158,7 +161,8 @@ ${JSON.stringify(routeConfig)}`);
158
161
  }
159
162
  const routeHash = (0, utils_1.simpleHash)(JSON.stringify(routeConfig), 3);
160
163
  res.routesChunkNames[`${routePath}-${routeHash}`] = {
161
- ...genChunkNames({ component }, 'component', component, res),
164
+ // Avoid clash with a prop called "component"
165
+ ...genChunkNames({ __comp: component }, 'component', component, res),
162
166
  ...genChunkNames(modules, 'module', routePath, res),
163
167
  };
164
168
  return serializeRouteConfig({
@@ -181,7 +185,7 @@ ${JSON.stringify(routeConfig)}`);
181
185
  async function loadRoutes(routeConfigs, baseUrl, onDuplicateRoutes) {
182
186
  handleDuplicateRoutes(routeConfigs, onDuplicateRoutes);
183
187
  const res = {
184
- // To be written
188
+ // To be written by `genRouteCode`
185
189
  routesConfig: '',
186
190
  routesChunkNames: {},
187
191
  registry: {},
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@docusaurus/core",
3
3
  "description": "Easy to Maintain Open Source Documentation Websites",
4
- "version": "0.0.0-4811",
4
+ "version": "0.0.0-4814",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
7
7
  "access": "public"
@@ -41,13 +41,13 @@
41
41
  "@babel/runtime": "^7.17.8",
42
42
  "@babel/runtime-corejs3": "^7.17.8",
43
43
  "@babel/traverse": "^7.17.3",
44
- "@docusaurus/cssnano-preset": "0.0.0-4811",
45
- "@docusaurus/logger": "0.0.0-4811",
46
- "@docusaurus/mdx-loader": "0.0.0-4811",
44
+ "@docusaurus/cssnano-preset": "0.0.0-4814",
45
+ "@docusaurus/logger": "0.0.0-4814",
46
+ "@docusaurus/mdx-loader": "0.0.0-4814",
47
47
  "@docusaurus/react-loadable": "5.5.2",
48
- "@docusaurus/utils": "0.0.0-4811",
49
- "@docusaurus/utils-common": "0.0.0-4811",
50
- "@docusaurus/utils-validation": "0.0.0-4811",
48
+ "@docusaurus/utils": "0.0.0-4814",
49
+ "@docusaurus/utils-common": "0.0.0-4814",
50
+ "@docusaurus/utils-validation": "0.0.0-4814",
51
51
  "@slorber/static-site-generator-webpack-plugin": "^4.0.4",
52
52
  "@svgr/webpack": "^6.2.1",
53
53
  "autoprefixer": "^10.4.4",
@@ -105,8 +105,8 @@
105
105
  "webpackbar": "^5.0.2"
106
106
  },
107
107
  "devDependencies": {
108
- "@docusaurus/module-type-aliases": "0.0.0-4811",
109
- "@docusaurus/types": "0.0.0-4811",
108
+ "@docusaurus/module-type-aliases": "0.0.0-4814",
109
+ "@docusaurus/types": "0.0.0-4814",
110
110
  "@types/detect-port": "^1.3.2",
111
111
  "@types/nprogress": "^0.2.0",
112
112
  "@types/react-dom": "^17.0.14",
@@ -127,5 +127,5 @@
127
127
  "engines": {
128
128
  "node": ">=14"
129
129
  },
130
- "gitHead": "f174c77967abd972ab9685ba682119b38c6ac55b"
130
+ "gitHead": "a9bcbaa758fc3daf0923d8b3c3bf0aa944c75d33"
131
131
  }