@docusaurus/plugin-client-redirects 2.0.0-beta.1decd6f80 → 2.0.0-beta.20

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 (39) hide show
  1. package/lib/collectRedirects.d.ts +2 -2
  2. package/lib/collectRedirects.js +43 -33
  3. package/lib/createRedirectPageContent.d.ts +2 -4
  4. package/lib/createRedirectPageContent.js +2 -4
  5. package/lib/extensionRedirects.d.ts +1 -1
  6. package/lib/extensionRedirects.js +16 -12
  7. package/lib/index.d.ts +5 -3
  8. package/lib/index.js +9 -7
  9. package/lib/options.d.ts +31 -0
  10. package/lib/options.js +36 -0
  11. package/lib/redirectValidation.d.ts +1 -1
  12. package/lib/types.d.ts +12 -14
  13. package/lib/writeRedirectFiles.d.ts +2 -2
  14. package/lib/writeRedirectFiles.js +36 -11
  15. package/package.json +16 -13
  16. package/src/collectRedirects.ts +56 -44
  17. package/src/createRedirectPageContent.ts +8 -10
  18. package/src/extensionRedirects.ts +21 -15
  19. package/src/index.ts +16 -9
  20. package/src/options.ts +71 -0
  21. package/src/redirectValidation.ts +1 -1
  22. package/src/types.ts +14 -28
  23. package/src/writeRedirectFiles.ts +43 -14
  24. package/lib/.tsbuildinfo +0 -1970
  25. package/lib/normalizePluginOptions.d.ts +0 -9
  26. package/lib/normalizePluginOptions.js +0 -44
  27. package/src/__tests__/__snapshots__/collectRedirects.test.ts.snap +0 -27
  28. package/src/__tests__/__snapshots__/createRedirectPageContent.test.ts.snap +0 -29
  29. package/src/__tests__/__snapshots__/normalizePluginOptions.test.ts.snap +0 -35
  30. package/src/__tests__/__snapshots__/redirectValidation.test.ts.snap +0 -11
  31. package/src/__tests__/__snapshots__/writeRedirectFiles.test.ts.snap +0 -71
  32. package/src/__tests__/collectRedirects.test.ts +0 -255
  33. package/src/__tests__/createRedirectPageContent.test.ts +0 -26
  34. package/src/__tests__/extensionRedirects.test.ts +0 -109
  35. package/src/__tests__/normalizePluginOptions.test.ts +0 -76
  36. package/src/__tests__/redirectValidation.test.ts +0 -66
  37. package/src/__tests__/writeRedirectFiles.test.ts +0 -146
  38. package/src/normalizePluginOptions.ts +0 -55
  39. package/tsconfig.json +0 -10
@@ -5,40 +5,64 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- import {flatten, uniqBy, difference, groupBy} from 'lodash';
9
- import {
10
- PluginContext,
11
- RedirectMetadata,
12
- PluginOptions,
13
- RedirectOption,
14
- } from './types';
8
+ import _ from 'lodash';
9
+ import type {PluginOptions, RedirectOption} from './options';
10
+ import type {PluginContext, RedirectMetadata} from './types';
15
11
  import {
16
12
  createFromExtensionsRedirects,
17
13
  createToExtensionsRedirects,
18
14
  } from './extensionRedirects';
19
15
  import {validateRedirect} from './redirectValidation';
16
+ import {
17
+ applyTrailingSlash,
18
+ type ApplyTrailingSlashParams,
19
+ } from '@docusaurus/utils-common';
20
20
 
21
- import chalk from 'chalk';
21
+ import logger from '@docusaurus/logger';
22
22
 
23
23
  export default function collectRedirects(
24
24
  pluginContext: PluginContext,
25
+ trailingSlash: boolean | undefined,
25
26
  ): RedirectMetadata[] {
26
- const redirects = doCollectRedirects(pluginContext);
27
+ let redirects = doCollectRedirects(pluginContext);
28
+
29
+ redirects = applyRedirectsTrailingSlash(redirects, {
30
+ trailingSlash,
31
+ baseUrl: pluginContext.baseUrl,
32
+ });
33
+
27
34
  validateCollectedRedirects(redirects, pluginContext);
28
35
  return filterUnwantedRedirects(redirects, pluginContext);
29
36
  }
30
37
 
38
+ // If users wants to redirect to=/abc and they enable trailingSlash=true then
39
+ // => we don't want to reject the to=/abc (as only /abc/ is an existing/valid
40
+ // path now)
41
+ // => we want to redirect to=/abc/ without the user having to change all its
42
+ // redirect plugin options
43
+ // It should be easy to toggle siteConfig.trailingSlash option without having to
44
+ // change other configs
45
+ function applyRedirectsTrailingSlash(
46
+ redirects: RedirectMetadata[],
47
+ params: ApplyTrailingSlashParams,
48
+ ) {
49
+ return redirects.map((redirect) => ({
50
+ ...redirect,
51
+ to: applyTrailingSlash(redirect.to, params),
52
+ }));
53
+ }
54
+
31
55
  function validateCollectedRedirects(
32
56
  redirects: RedirectMetadata[],
33
57
  pluginContext: PluginContext,
34
58
  ) {
35
- const redirectValidationErrors: string[] = redirects
59
+ const redirectValidationErrors = redirects
36
60
  .map((redirect) => {
37
61
  try {
38
62
  validateRedirect(redirect);
39
63
  return undefined;
40
- } catch (e) {
41
- return e.message;
64
+ } catch (err) {
65
+ return (err as Error).message;
42
66
  }
43
67
  })
44
68
  .filter(Boolean);
@@ -52,7 +76,7 @@ function validateCollectedRedirects(
52
76
 
53
77
  const allowedToPaths = pluginContext.relativeRoutesPaths;
54
78
  const toPaths = redirects.map((redirect) => redirect.to);
55
- const illegalToPaths = difference(toPaths, allowedToPaths);
79
+ const illegalToPaths = _.difference(toPaths, allowedToPaths);
56
80
  if (illegalToPaths.length > 0) {
57
81
  throw new Error(
58
82
  `You are trying to create client-side redirections to paths that do not exist:
@@ -69,36 +93,28 @@ function filterUnwantedRedirects(
69
93
  redirects: RedirectMetadata[],
70
94
  pluginContext: PluginContext,
71
95
  ): RedirectMetadata[] {
72
- // we don't want to create twice the same redirect
73
- // that would lead to writing twice the same html redirection file
74
- Object.entries(groupBy(redirects, (redirect) => redirect.from)).forEach(
96
+ // We don't want to create the same redirect twice, since that would lead to
97
+ // writing the same html redirection file twice.
98
+ Object.entries(_.groupBy(redirects, (redirect) => redirect.from)).forEach(
75
99
  ([from, groupedFromRedirects]) => {
76
100
  if (groupedFromRedirects.length > 1) {
77
- console.error(
78
- chalk.red(
79
- `@docusaurus/plugin-client-redirects: multiple redirects are created with the same "from" pathname=${from}
80
- It is not possible to redirect the same pathname to multiple destinations:
81
- - ${groupedFromRedirects.map((r) => JSON.stringify(r)).join('\n- ')}
82
- `,
83
- ),
84
- );
101
+ logger.error`name=${'@docusaurus/plugin-client-redirects'}: multiple redirects are created with the same "from" pathname: path=${from}
102
+ It is not possible to redirect the same pathname to multiple destinations: ${groupedFromRedirects.map(
103
+ (r) => JSON.stringify(r),
104
+ )}`;
85
105
  }
86
106
  },
87
107
  );
88
- const collectedRedirects = uniqBy(redirects, (redirect) => redirect.from);
108
+ const collectedRedirects = _.uniqBy(redirects, (redirect) => redirect.from);
89
109
 
90
110
  // We don't want to override an already existing route with a redirect file!
91
111
  const redirectsOverridingExistingPath = collectedRedirects.filter(
92
112
  (redirect) => pluginContext.relativeRoutesPaths.includes(redirect.from),
93
113
  );
94
114
  if (redirectsOverridingExistingPath.length > 0) {
95
- console.error(
96
- chalk.red(
97
- `@docusaurus/plugin-client-redirects: some redirects would override existing paths, and will be ignored:
98
- - ${redirectsOverridingExistingPath.map((r) => JSON.stringify(r)).join('\n- ')}
99
- `,
100
- ),
101
- );
115
+ logger.error`name=${'@docusaurus/plugin-client-redirects'}: some redirects would override existing paths, and will be ignored: ${redirectsOverridingExistingPath.map(
116
+ (r) => JSON.stringify(r),
117
+ )}`;
102
118
  }
103
119
  return collectedRedirects.filter(
104
120
  (redirect) => !pluginContext.relativeRoutesPaths.includes(redirect.from),
@@ -127,7 +143,7 @@ function doCollectRedirects(pluginContext: PluginContext): RedirectMetadata[] {
127
143
  function createRedirectsOptionRedirects(
128
144
  redirectsOption: PluginOptions['redirects'],
129
145
  ): RedirectMetadata[] {
130
- // For conveniency, user can use a string or a string[]
146
+ // For convenience, user can use a string or a string[]
131
147
  function optionToRedirects(option: RedirectOption): RedirectMetadata[] {
132
148
  if (typeof option.from === 'string') {
133
149
  return [{from: option.from, to: option.to}];
@@ -138,7 +154,7 @@ function createRedirectsOptionRedirects(
138
154
  }));
139
155
  }
140
156
 
141
- return flatten(redirectsOption.map(optionToRedirects));
157
+ return redirectsOption.flatMap(optionToRedirects);
142
158
  }
143
159
 
144
160
  // Create redirects from the "createRedirects" fn provided by the user
@@ -147,20 +163,16 @@ function createCreateRedirectsOptionRedirects(
147
163
  createRedirects: PluginOptions['createRedirects'],
148
164
  ): RedirectMetadata[] {
149
165
  function createPathRedirects(path: string): RedirectMetadata[] {
150
- const fromsMixed: string | string[] = createRedirects
151
- ? createRedirects(path) || []
152
- : [];
166
+ const fromsMixed: string | string[] = createRedirects?.(path) ?? [];
153
167
 
154
168
  const froms: string[] =
155
169
  typeof fromsMixed === 'string' ? [fromsMixed] : fromsMixed;
156
170
 
157
- return froms.map((from) => {
158
- return {
159
- from,
160
- to: path,
161
- };
162
- });
171
+ return froms.map((from) => ({
172
+ from,
173
+ to: path,
174
+ }));
163
175
  }
164
176
 
165
- return flatten(paths.map(createPathRedirects));
177
+ return paths.flatMap(createPathRedirects);
166
178
  }
@@ -7,24 +7,22 @@
7
7
 
8
8
  import * as eta from 'eta';
9
9
  import redirectPageTemplate from './templates/redirectPage.template.html';
10
- import {memoize} from 'lodash';
10
+ import _ from 'lodash';
11
11
 
12
- type CreateRedirectPageOptions = {
13
- toUrl: string;
14
- };
15
-
16
- const getCompiledRedirectPageTemplate = memoize(() => {
17
- return eta.compile(redirectPageTemplate.trim());
18
- });
12
+ const getCompiledRedirectPageTemplate = _.memoize(() =>
13
+ eta.compile(redirectPageTemplate.trim()),
14
+ );
19
15
 
20
- function renderRedirectPageTemplate(data: Record<string, unknown>) {
16
+ function renderRedirectPageTemplate(data: {toUrl: string}) {
21
17
  const compiled = getCompiledRedirectPageTemplate();
22
18
  return compiled(data, eta.defaultConfig);
23
19
  }
24
20
 
25
21
  export default function createRedirectPageContent({
26
22
  toUrl,
27
- }: CreateRedirectPageOptions): string {
23
+ }: {
24
+ toUrl: string;
25
+ }): string {
28
26
  return renderRedirectPageTemplate({
29
27
  toUrl: encodeURI(toUrl),
30
28
  });
@@ -5,34 +5,35 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- import {flatten} from 'lodash';
9
- import {removeSuffix} from '@docusaurus/utils';
10
- import {RedirectMetadata} from './types';
8
+ import {
9
+ addTrailingSlash,
10
+ removeSuffix,
11
+ removeTrailingSlash,
12
+ } from '@docusaurus/utils';
13
+ import type {RedirectMetadata} from './types';
11
14
 
12
15
  const ExtensionAdditionalMessage =
13
- "If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the 'createRedirects' plugin option.";
16
+ 'If the redirect extension system is not good enough for your use case, you can create redirects yourself with the "createRedirects" plugin option.';
14
17
 
15
18
  const validateExtension = (ext: string) => {
16
19
  if (!ext) {
17
20
  throw new Error(
18
- `Extension=['${String(
19
- ext,
20
- )}'] is not allowed. ${ExtensionAdditionalMessage}`,
21
+ `Extension "${ext}" is not allowed.\n${ExtensionAdditionalMessage}`,
21
22
  );
22
23
  }
23
24
  if (ext.includes('.')) {
24
25
  throw new Error(
25
- `Extension=['${ext}'] contains a . (dot) and is not allowed. ${ExtensionAdditionalMessage}`,
26
+ `Extension "${ext}" contains a "." (dot) which is not allowed.\n${ExtensionAdditionalMessage}`,
26
27
  );
27
28
  }
28
29
  if (ext.includes('/')) {
29
30
  throw new Error(
30
- `Extension=['${ext}'] contains a / and is not allowed. ${ExtensionAdditionalMessage}`,
31
+ `Extension "${ext}" contains a "/" (slash) which is not allowed.\n${ExtensionAdditionalMessage}`,
31
32
  );
32
33
  }
33
34
  if (encodeURIComponent(ext) !== ext) {
34
35
  throw new Error(
35
- `Extension=['${ext}'] contains invalid uri characters. ${ExtensionAdditionalMessage}`,
36
+ `Extension "${ext}" contains invalid URI characters.\n${ExtensionAdditionalMessage}`,
36
37
  );
37
38
  }
38
39
  };
@@ -60,10 +61,11 @@ export function createToExtensionsRedirects(
60
61
  return [];
61
62
  };
62
63
 
63
- return flatten(paths.map(createPathRedirects));
64
+ return paths.flatMap(createPathRedirects);
64
65
  }
65
66
 
66
- // Create new /path.html that redirects to existing an /path
67
+ // Create new /path.html/index.html that redirects to existing an /path
68
+ // The filename pattern might look weird but it's on purpose (see https://github.com/facebook/docusaurus/issues/5055)
67
69
  export function createFromExtensionsRedirects(
68
70
  paths: string[],
69
71
  extensions: string[],
@@ -76,14 +78,18 @@ export function createFromExtensionsRedirects(
76
78
  dottedExtensions.some((ext) => str.endsWith(ext));
77
79
 
78
80
  const createPathRedirects = (path: string): RedirectMetadata[] => {
79
- if (path === '' || path.endsWith('/') || alreadyEndsWithAnExtension(path)) {
81
+ if (path === '' || path === '/' || alreadyEndsWithAnExtension(path)) {
80
82
  return [];
81
83
  }
82
84
  return extensions.map((ext) => ({
83
- from: `${path}.${ext}`,
85
+ // /path => /path.html
86
+ // /path/ => /path.html/
87
+ from: path.endsWith('/')
88
+ ? addTrailingSlash(`${removeTrailingSlash(path)}.${ext}`)
89
+ : `${path}.${ext}`,
84
90
  to: path,
85
91
  }));
86
92
  };
87
93
 
88
- return flatten(paths.map(createPathRedirects));
94
+ return paths.flatMap(createPathRedirects);
89
95
  }
package/src/index.ts CHANGED
@@ -5,26 +5,26 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- import {LoadContext, Plugin, Props} from '@docusaurus/types';
9
- import {UserPluginOptions, PluginContext, RedirectMetadata} from './types';
8
+ import type {LoadContext, Plugin} from '@docusaurus/types';
9
+ import type {PluginContext, RedirectMetadata} from './types';
10
+ import type {PluginOptions, Options} from './options';
10
11
 
11
- import normalizePluginOptions from './normalizePluginOptions';
12
12
  import collectRedirects from './collectRedirects';
13
13
  import writeRedirectFiles, {
14
14
  toRedirectFilesMetadata,
15
- RedirectFileMetadata,
15
+ type RedirectFileMetadata,
16
16
  } from './writeRedirectFiles';
17
17
  import {removePrefix, addLeadingSlash} from '@docusaurus/utils';
18
18
 
19
19
  export default function pluginClientRedirectsPages(
20
- _context: LoadContext,
21
- opts: UserPluginOptions,
20
+ context: LoadContext,
21
+ options: PluginOptions,
22
22
  ): Plugin<unknown> {
23
- const options = normalizePluginOptions(opts);
23
+ const {trailingSlash} = context.siteConfig;
24
24
 
25
25
  return {
26
26
  name: 'docusaurus-plugin-client-redirects',
27
- async postBuild(props: Props) {
27
+ async postBuild(props) {
28
28
  const pluginContext: PluginContext = {
29
29
  relativeRoutesPaths: props.routesPaths.map(
30
30
  (path) => `${addLeadingSlash(removePrefix(path, props.baseUrl))}`,
@@ -34,11 +34,15 @@ export default function pluginClientRedirectsPages(
34
34
  options,
35
35
  };
36
36
 
37
- const redirects: RedirectMetadata[] = collectRedirects(pluginContext);
37
+ const redirects: RedirectMetadata[] = collectRedirects(
38
+ pluginContext,
39
+ trailingSlash,
40
+ );
38
41
 
39
42
  const redirectFiles: RedirectFileMetadata[] = toRedirectFilesMetadata(
40
43
  redirects,
41
44
  pluginContext,
45
+ trailingSlash,
42
46
  );
43
47
 
44
48
  // Write files only at the end: make code more easy to test without IO
@@ -46,3 +50,6 @@ export default function pluginClientRedirectsPages(
46
50
  },
47
51
  };
48
52
  }
53
+
54
+ export {validateOptions} from './options';
55
+ export type {PluginOptions, Options};
package/src/options.ts ADDED
@@ -0,0 +1,71 @@
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
+
8
+ import type {OptionValidationContext} from '@docusaurus/types';
9
+ import {Joi, PathnameSchema} from '@docusaurus/utils-validation';
10
+
11
+ export type RedirectOption = {
12
+ to: string;
13
+ from: string | string[];
14
+ };
15
+
16
+ export type PluginOptions = {
17
+ /** Plugin ID. */
18
+ id: string;
19
+ /** The extensions to be removed from the route after redirecting. */
20
+ fromExtensions: string[];
21
+ /** The extensions to be appended to the route after redirecting. */
22
+ toExtensions: string[];
23
+ /** The list of redirect rules, each one with multiple `from`s → one `to`. */
24
+ redirects: RedirectOption[];
25
+ /**
26
+ * A callback to create a redirect rule.
27
+ * @returns All the paths from which we should redirect to `path`
28
+ */
29
+ createRedirects?: (
30
+ /** An existing Docusaurus route path */
31
+ path: string,
32
+ ) => string[] | string | null | undefined;
33
+ };
34
+
35
+ export type Options = Partial<PluginOptions>;
36
+
37
+ export const DEFAULT_OPTIONS: Partial<PluginOptions> = {
38
+ fromExtensions: [],
39
+ toExtensions: [],
40
+ redirects: [],
41
+ };
42
+
43
+ const RedirectPluginOptionValidation = Joi.object<RedirectOption>({
44
+ to: PathnameSchema.required(),
45
+ from: Joi.alternatives().try(
46
+ PathnameSchema.required(),
47
+ Joi.array().items(PathnameSchema.required()),
48
+ ),
49
+ });
50
+
51
+ const isString = Joi.string().required().not(null);
52
+
53
+ const UserOptionsSchema = Joi.object<PluginOptions>({
54
+ fromExtensions: Joi.array()
55
+ .items(isString)
56
+ .default(DEFAULT_OPTIONS.fromExtensions),
57
+ toExtensions: Joi.array()
58
+ .items(isString)
59
+ .default(DEFAULT_OPTIONS.toExtensions),
60
+ redirects: Joi.array()
61
+ .items(RedirectPluginOptionValidation)
62
+ .default(DEFAULT_OPTIONS.redirects),
63
+ createRedirects: Joi.function().maxArity(1),
64
+ }).default(DEFAULT_OPTIONS);
65
+
66
+ export function validateOptions({
67
+ validate,
68
+ options: userOptions,
69
+ }: OptionValidationContext<Options, PluginOptions>): PluginOptions {
70
+ return validate(UserOptionsSchema, userOptions);
71
+ }
@@ -5,7 +5,7 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- import {RedirectMetadata} from './types';
8
+ import type {RedirectMetadata} from './types';
9
9
  import {Joi, PathnameSchema} from '@docusaurus/utils-validation';
10
10
 
11
11
  const RedirectSchema = Joi.object<RedirectMetadata>({
package/src/types.ts CHANGED
@@ -5,39 +5,25 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- import {Props} from '@docusaurus/types';
8
+ import type {Props} from '@docusaurus/types';
9
+ import type {PluginOptions} from './options';
9
10
 
10
- export type PluginOptions = {
11
- id: string;
12
- fromExtensions: string[];
13
- toExtensions: string[];
14
- redirects: RedirectOption[];
15
- createRedirects?: CreateRedirectsFnOption;
16
- };
17
-
18
- // For a given existing route path,
19
- // return all the paths from which we should redirect from
20
- export type CreateRedirectsFnOption = (
21
- path: string,
22
- ) => string[] | string | null | undefined;
23
-
24
- export type RedirectOption = {
25
- to: string;
26
- from: string | string[];
27
- };
28
-
29
- export type UserPluginOptions = Partial<PluginOptions>;
30
-
31
- // The minimal infos the plugin needs to work
11
+ /**
12
+ * The minimal infos the plugin needs to work
13
+ */
32
14
  export type PluginContext = Pick<Props, 'outDir' | 'baseUrl'> & {
33
15
  options: PluginOptions;
34
16
  relativeRoutesPaths: string[];
35
17
  };
36
18
 
37
- // In-memory representation of redirects we want: easier to test
38
- // /!\ easy to be confused: "from" is the new page we should create,
39
- // that redirects to "to": the existing Docusaurus page
19
+ /**
20
+ * In-memory representation of redirects we want: easier to test
21
+ * /!\ easy to be confused: "from" is the new page we should create,
22
+ * that redirects to "to": the existing Docusaurus page
23
+ */
40
24
  export type RedirectMetadata = {
41
- from: string; // pathname
42
- to: string; // pathname
25
+ /** Pathname of the new page we should create */
26
+ from: string;
27
+ /** Pathname of an existing Docusaurus page */
28
+ to: string;
43
29
  };
@@ -7,11 +7,11 @@
7
7
 
8
8
  import fs from 'fs-extra';
9
9
  import path from 'path';
10
- import {memoize} from 'lodash';
10
+ import _ from 'lodash';
11
11
 
12
- import {PluginContext, RedirectMetadata} from './types';
12
+ import type {PluginContext, RedirectMetadata} from './types';
13
13
  import createRedirectPageContent from './createRedirectPageContent';
14
- import {getFilePathForRoutePath, normalizeUrl} from '@docusaurus/utils';
14
+ import {normalizeUrl} from '@docusaurus/utils';
15
15
 
16
16
  export type WriteFilesPluginContext = Pick<PluginContext, 'baseUrl' | 'outDir'>;
17
17
 
@@ -24,22 +24,52 @@ export function createToUrl(baseUrl: string, to: string): string {
24
24
  return normalizeUrl([baseUrl, to]);
25
25
  }
26
26
 
27
+ // Create redirect file path
28
+ // Make sure this path has lower precedence over the original file path when
29
+ // served by host providers!
30
+ // Otherwise it can produce infinite redirect loops!
31
+ //
32
+ // See https://github.com/facebook/docusaurus/issues/5055
33
+ // See https://github.com/facebook/docusaurus/pull/5085
34
+ // See https://github.com/facebook/docusaurus/pull/5102
35
+ function getRedirectFilePath(
36
+ fromPath: string,
37
+ trailingSlash: boolean | undefined, // Now unused, on purpose
38
+ ): string {
39
+ const fileName = path.basename(fromPath);
40
+ const filePath = path.dirname(fromPath);
41
+ // Edge case for https://github.com/facebook/docusaurus/pull/5102
42
+ // If the redirect source path is /xyz, with file /xyz.html
43
+ // We can't write the redirect file at /xyz.html/index.html because for Unix
44
+ // FS, a file/folder can't have the same name "xyz.html"
45
+ // The only possible solution for a redirect file is thus /xyz.html.html (I
46
+ // know, looks suspicious)
47
+ if (trailingSlash === false && fileName.endsWith('.html')) {
48
+ return path.join(filePath, `${fileName}.html`);
49
+ }
50
+ // If the target path is /xyz, with file /xyz/index.html, we don't want the
51
+ // redirect file to be /xyz.html, otherwise it would be picked in priority and
52
+ // the redirect file would redirect to itself. We prefer the redirect file to
53
+ // be /xyz.html/index.html, served with lower priority for most static hosting
54
+ // tools
55
+ return path.join(filePath, `${fileName}/index.html`);
56
+ }
57
+
27
58
  export function toRedirectFilesMetadata(
28
59
  redirects: RedirectMetadata[],
29
60
  pluginContext: WriteFilesPluginContext,
61
+ trailingSlash: boolean | undefined,
30
62
  ): RedirectFileMetadata[] {
31
63
  // Perf: avoid rendering the template twice with the exact same "props"
32
64
  // We might create multiple redirect pages for the same destination url
33
65
  // note: the first fn arg is the cache key!
34
- const createPageContentMemoized = memoize((toUrl: string) => {
35
- return createRedirectPageContent({toUrl});
36
- });
66
+ const createPageContentMemoized = _.memoize((toUrl: string) =>
67
+ createRedirectPageContent({toUrl}),
68
+ );
37
69
 
38
70
  const createFileMetadata = (redirect: RedirectMetadata) => {
39
- const fileAbsolutePath = path.join(
40
- pluginContext.outDir,
41
- getFilePathForRoutePath(redirect.from),
42
- );
71
+ const fileRelativePath = getRedirectFilePath(redirect.from, trailingSlash);
72
+ const fileAbsolutePath = path.join(pluginContext.outDir, fileRelativePath);
43
73
  const toUrl = createToUrl(pluginContext.baseUrl, redirect.to);
44
74
  const fileContent = createPageContentMemoized(toUrl);
45
75
  return {
@@ -59,11 +89,10 @@ export async function writeRedirectFile(
59
89
  // User-friendly security to prevent file overrides
60
90
  if (await fs.pathExists(file.fileAbsolutePath)) {
61
91
  throw new Error(
62
- 'The redirect plugin is not supposed to override existing files',
92
+ 'The redirect plugin is not supposed to override existing files.',
63
93
  );
64
94
  }
65
- await fs.ensureDir(path.dirname(file.fileAbsolutePath));
66
- await fs.writeFile(
95
+ await fs.outputFile(
67
96
  file.fileAbsolutePath,
68
97
  file.fileContent,
69
98
  // Hard security to prevent file overrides
@@ -72,7 +101,7 @@ export async function writeRedirectFile(
72
101
  );
73
102
  } catch (err) {
74
103
  throw new Error(
75
- `Redirect file creation error for path=${file.fileAbsolutePath}: ${err}`,
104
+ `Redirect file creation error for "${file.fileAbsolutePath}" path: ${err}.`,
76
105
  );
77
106
  }
78
107
  }