@docusaurus/plugin-content-docs 0.0.0-4848 → 0.0.0-4851

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.
package/lib/cli.d.ts CHANGED
@@ -6,4 +6,4 @@
6
6
  */
7
7
  import type { PluginOptions } from '@docusaurus/plugin-content-docs';
8
8
  import type { LoadContext } from '@docusaurus/types';
9
- export declare function cliDocsVersionCommand(version: string | null | undefined, { id: pluginId, path: docsPath, sidebarPath }: PluginOptions, { siteDir, i18n }: LoadContext): Promise<void>;
9
+ export declare function cliDocsVersionCommand(version: string, { id: pluginId, path: docsPath, sidebarPath }: PluginOptions, { siteDir, i18n }: LoadContext): Promise<void>;
package/lib/cli.js CHANGED
@@ -8,7 +8,8 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.cliDocsVersionCommand = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const versions_1 = require("./versions");
11
+ const files_1 = require("./versions/files");
12
+ const validation_1 = require("./versions/validation");
12
13
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
13
14
  const path_1 = tslib_1.__importDefault(require("path"));
14
15
  const sidebars_1 = require("./sidebars");
@@ -25,9 +26,7 @@ async function createVersionedSidebarFile({ siteDir, pluginId, sidebarPath, vers
25
26
  // or sidebars are disabled/false)
26
27
  const shouldCreateVersionedSidebarFile = Object.keys(sidebars).length > 0;
27
28
  if (shouldCreateVersionedSidebarFile) {
28
- const versionedSidebarsDir = (0, versions_1.getVersionedSidebarsDirPath)(siteDir, pluginId);
29
- const newSidebarFile = path_1.default.join(versionedSidebarsDir, `version-${version}-sidebars.json`);
30
- await fs_extra_1.default.outputFile(newSidebarFile, `${JSON.stringify(sidebars, null, 2)}\n`, 'utf8');
29
+ await fs_extra_1.default.outputFile((0, files_1.getVersionSidebarsPath)(siteDir, pluginId, version), `${JSON.stringify(sidebars, null, 2)}\n`, 'utf8');
31
30
  }
32
31
  }
33
32
  // Tests depend on non-default export for mocking.
@@ -35,29 +34,18 @@ async function cliDocsVersionCommand(version, { id: pluginId, path: docsPath, si
35
34
  // It wouldn't be very user-friendly to show a [default] log prefix,
36
35
  // so we use [docs] instead of [default]
37
36
  const pluginIdLogPrefix = pluginId === utils_1.DEFAULT_PLUGIN_ID ? '[docs]' : `[${pluginId}]`;
38
- if (!version) {
39
- throw new Error(`${pluginIdLogPrefix}: no version tag specified! Pass the version you wish to create as an argument, for example: 1.0.0.`);
37
+ try {
38
+ (0, validation_1.validateVersionName)(version);
40
39
  }
41
- if (version.includes('/') || version.includes('\\')) {
42
- throw new Error(`${pluginIdLogPrefix}: invalid version tag specified! Do not include slash (/) or backslash (\\). Try something like: 1.0.0.`);
43
- }
44
- if (version.length > 32) {
45
- throw new Error(`${pluginIdLogPrefix}: invalid version tag specified! Length cannot exceed 32 characters. Try something like: 1.0.0.`);
46
- }
47
- // Since we are going to create `version-${version}` folder, we need to make
48
- // sure it's a valid pathname.
49
- // eslint-disable-next-line no-control-regex
50
- if (/[<>:"|?*\x00-\x1F]/.test(version)) {
51
- throw new Error(`${pluginIdLogPrefix}: invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0.`);
52
- }
53
- if (/^\.\.?$/.test(version)) {
54
- throw new Error(`${pluginIdLogPrefix}: invalid version tag specified! Do not name your version "." or "..". Try something like: 1.0.0.`);
40
+ catch (e) {
41
+ logger_1.default.info `${pluginIdLogPrefix}: Invalid version name provided. Try something like: 1.0.0`;
42
+ throw e;
55
43
  }
56
44
  // Load existing versions.
57
45
  let versions = [];
58
- const versionsJSONFile = (0, versions_1.getVersionsFilePath)(siteDir, pluginId);
46
+ const versionsJSONFile = (0, files_1.getVersionsFilePath)(siteDir, pluginId);
59
47
  if (await fs_extra_1.default.pathExists(versionsJSONFile)) {
60
- versions = JSON.parse(await fs_extra_1.default.readFile(versionsJSONFile, 'utf8'));
48
+ versions = await fs_extra_1.default.readJSON(versionsJSONFile);
61
49
  }
62
50
  // Check if version already exists.
63
51
  if (versions.includes(version)) {
@@ -70,7 +58,7 @@ async function cliDocsVersionCommand(version, { id: pluginId, path: docsPath, si
70
58
  // Copy docs files.
71
59
  const docsDir = locale === i18n.defaultLocale
72
60
  ? path_1.default.resolve(siteDir, docsPath)
73
- : (0, versions_1.getDocsDirPathLocalized)({
61
+ : (0, files_1.getDocsDirPathLocalized)({
74
62
  siteDir,
75
63
  locale,
76
64
  pluginId,
@@ -87,8 +75,8 @@ async function cliDocsVersionCommand(version, { id: pluginId, path: docsPath, si
87
75
  }
88
76
  }
89
77
  const newVersionDir = locale === i18n.defaultLocale
90
- ? path_1.default.join((0, versions_1.getVersionedDocsDirPath)(siteDir, pluginId), `version-${version}`)
91
- : (0, versions_1.getDocsDirPathLocalized)({
78
+ ? (0, files_1.getVersionDocsDirPath)(siteDir, pluginId, version)
79
+ : (0, files_1.getDocsDirPathLocalized)({
92
80
  siteDir,
93
81
  locale,
94
82
  pluginId,
@@ -100,7 +88,7 @@ async function cliDocsVersionCommand(version, { id: pluginId, path: docsPath, si
100
88
  siteDir,
101
89
  pluginId,
102
90
  version,
103
- sidebarPath: (0, sidebars_1.resolveSidebarPathOption)(siteDir, sidebarPath),
91
+ sidebarPath,
104
92
  });
105
93
  // Update versions.json file.
106
94
  versions.unshift(version);
@@ -4,7 +4,11 @@
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
+ /** The name of the version that's actively worked on (e.g. `website/docs`) */
7
8
  export declare const CURRENT_VERSION_NAME = "current";
9
+ /** All doc versions are stored here by version names */
8
10
  export declare const VERSIONED_DOCS_DIR = "versioned_docs";
11
+ /** All doc versioned sidebars are stored here by version names */
9
12
  export declare const VERSIONED_SIDEBARS_DIR = "versioned_sidebars";
13
+ /** The version names. Should 1-1 map to the content of versioned docs dir. */
10
14
  export declare const VERSIONS_JSON_FILE = "versions.json";
package/lib/constants.js CHANGED
@@ -7,8 +7,11 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.VERSIONS_JSON_FILE = exports.VERSIONED_SIDEBARS_DIR = exports.VERSIONED_DOCS_DIR = exports.CURRENT_VERSION_NAME = void 0;
10
- // The name of the version at the root of your site (website/docs)
10
+ /** The name of the version that's actively worked on (e.g. `website/docs`) */
11
11
  exports.CURRENT_VERSION_NAME = 'current';
12
+ /** All doc versions are stored here by version names */
12
13
  exports.VERSIONED_DOCS_DIR = 'versioned_docs';
14
+ /** All doc versioned sidebars are stored here by version names */
13
15
  exports.VERSIONED_SIDEBARS_DIR = 'versioned_sidebars';
16
+ /** The version names. Should 1-1 map to the content of versioned docs dir. */
14
17
  exports.VERSIONS_JSON_FILE = 'versions.json';
package/lib/index.js CHANGED
@@ -26,6 +26,8 @@ const utils_2 = require("./sidebars/utils");
26
26
  const categoryGeneratedIndex_1 = require("./categoryGeneratedIndex");
27
27
  async function pluginContentDocs(context, options) {
28
28
  const { siteDir, generatedFilesDir, baseUrl, siteConfig } = context;
29
+ // Mutate options to resolve sidebar path according to siteDir
30
+ options.sidebarPath = (0, sidebars_1.resolveSidebarPathOption)(siteDir, options.sidebarPath);
29
31
  const versionsMetadata = await (0, versions_1.readVersionsMetadata)({ context, options });
30
32
  const pluginId = options.id;
31
33
  const pluginDataDirRoot = path_1.default.join(generatedFilesDir, 'docusaurus-plugin-content-docs');
@@ -5,4 +5,5 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  export { CURRENT_VERSION_NAME, VERSIONED_DOCS_DIR, VERSIONED_SIDEBARS_DIR, VERSIONS_JSON_FILE, } from './constants';
8
- export { filterVersions, getDefaultVersionBanner, getVersionBadge, getVersionBanner, getVersionsFilePath, readVersionsFile, readVersionNames, } from './versions';
8
+ export { filterVersions, getDefaultVersionBanner, getVersionBadge, getVersionBanner, } from './versions';
9
+ export { readVersionNames } from './versions/files';
@@ -6,7 +6,7 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.readVersionNames = exports.readVersionsFile = exports.getVersionsFilePath = exports.getVersionBanner = exports.getVersionBadge = exports.getDefaultVersionBanner = exports.filterVersions = exports.VERSIONS_JSON_FILE = exports.VERSIONED_SIDEBARS_DIR = exports.VERSIONED_DOCS_DIR = exports.CURRENT_VERSION_NAME = void 0;
9
+ exports.readVersionNames = exports.getVersionBanner = exports.getVersionBadge = exports.getDefaultVersionBanner = exports.filterVersions = exports.VERSIONS_JSON_FILE = exports.VERSIONED_SIDEBARS_DIR = exports.VERSIONED_DOCS_DIR = exports.CURRENT_VERSION_NAME = void 0;
10
10
  // APIs available to Node.js
11
11
  var constants_1 = require("./constants");
12
12
  Object.defineProperty(exports, "CURRENT_VERSION_NAME", { enumerable: true, get: function () { return constants_1.CURRENT_VERSION_NAME; } });
@@ -18,6 +18,5 @@ Object.defineProperty(exports, "filterVersions", { enumerable: true, get: functi
18
18
  Object.defineProperty(exports, "getDefaultVersionBanner", { enumerable: true, get: function () { return versions_1.getDefaultVersionBanner; } });
19
19
  Object.defineProperty(exports, "getVersionBadge", { enumerable: true, get: function () { return versions_1.getVersionBadge; } });
20
20
  Object.defineProperty(exports, "getVersionBanner", { enumerable: true, get: function () { return versions_1.getVersionBanner; } });
21
- Object.defineProperty(exports, "getVersionsFilePath", { enumerable: true, get: function () { return versions_1.getVersionsFilePath; } });
22
- Object.defineProperty(exports, "readVersionsFile", { enumerable: true, get: function () { return versions_1.readVersionsFile; } });
23
- Object.defineProperty(exports, "readVersionNames", { enumerable: true, get: function () { return versions_1.readVersionNames; } });
21
+ var files_1 = require("./versions/files");
22
+ Object.defineProperty(exports, "readVersionNames", { enumerable: true, get: function () { return files_1.readVersionNames; } });
@@ -30,7 +30,6 @@ exports.DefaultSidebars = {
30
30
  };
31
31
  exports.DisabledSidebars = {};
32
32
  // If a path is provided, make it absolute
33
- // use this before loadSidebars()
34
33
  function resolveSidebarPathOption(siteDir, sidebarPathOption) {
35
34
  return sidebarPathOption
36
35
  ? path_1.default.resolve(siteDir, sidebarPathOption)
@@ -76,7 +75,6 @@ async function loadSidebarsFileUnsafe(sidebarFilePath) {
76
75
  return (0, import_fresh_1.default)(sidebarFilePath);
77
76
  }
78
77
  exports.loadSidebarsFileUnsafe = loadSidebarsFileUnsafe;
79
- // Note: sidebarFilePath must be absolute, use resolveSidebarPathOption
80
78
  async function loadSidebars(sidebarFilePath, options) {
81
79
  try {
82
80
  const sidebarsConfig = await loadSidebarsFileUnsafe(sidebarFilePath);
@@ -0,0 +1,44 @@
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 { PluginOptions, VersionMetadata } from '@docusaurus/plugin-content-docs';
8
+ import type { VersionContext } from './index';
9
+ /** `[siteDir]/community_versioned_docs/version-1.0.0` */
10
+ export declare function getVersionDocsDirPath(siteDir: string, pluginId: string, versionName: string): string;
11
+ /** `[siteDir]/community_versioned_sidebars/version-1.0.0-sidebars.json` */
12
+ export declare function getVersionSidebarsPath(siteDir: string, pluginId: string, versionName: string): string;
13
+ export declare function getDocsDirPathLocalized({ siteDir, locale, pluginId, versionName, }: {
14
+ siteDir: string;
15
+ locale: string;
16
+ pluginId: string;
17
+ versionName: string;
18
+ }): string;
19
+ /** `community` => `[siteDir]/community_versions.json` */
20
+ export declare function getVersionsFilePath(siteDir: string, pluginId: string): string;
21
+ /**
22
+ * Reads the `versions.json` file, and returns an ordered list of version names.
23
+ *
24
+ * - If `disableVersioning` is turned on, it will return `["current"]` (requires
25
+ * `includeCurrentVersion` to be true);
26
+ * - If `includeCurrentVersion` is turned on, "current" will be inserted at the
27
+ * beginning, if not already there.
28
+ *
29
+ * You need to use {@link filterVersions} after this.
30
+ *
31
+ * @throws Throws an error if `disableVersioning: true` but `versions.json`
32
+ * doesn't exist (i.e. site is not versioned)
33
+ * @throws Throws an error if versions list is empty (empty `versions.json` or
34
+ * `disableVersioning` is true, and not including current version)
35
+ */
36
+ export declare function readVersionNames(siteDir: string, options: PluginOptions): Promise<string[]>;
37
+ /**
38
+ * Gets the path-related version metadata.
39
+ *
40
+ * @throws Throws if the resolved docs folder or sidebars file doesn't exist.
41
+ * Does not throw if a versioned sidebar is missing (since we don't create empty
42
+ * files).
43
+ */
44
+ export declare function getVersionMetadataPaths({ versionName, context, options, }: VersionContext): Promise<Pick<VersionMetadata, 'contentPath' | 'contentPathLocalized' | 'sidebarFilePath'>>;
@@ -0,0 +1,142 @@
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.getVersionMetadataPaths = exports.readVersionNames = exports.getVersionsFilePath = exports.getDocsDirPathLocalized = exports.getVersionSidebarsPath = exports.getVersionDocsDirPath = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const path_1 = tslib_1.__importDefault(require("path"));
12
+ const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
13
+ const constants_1 = require("../constants");
14
+ const validation_1 = require("./validation");
15
+ const utils_1 = require("@docusaurus/utils");
16
+ /** Add a prefix like `community_version-1.0.0`. No-op for default instance. */
17
+ function addPluginIdPrefix(fileOrDir, pluginId) {
18
+ return pluginId === utils_1.DEFAULT_PLUGIN_ID
19
+ ? fileOrDir
20
+ : `${pluginId}_${fileOrDir}`;
21
+ }
22
+ /** `[siteDir]/community_versioned_docs/version-1.0.0` */
23
+ function getVersionDocsDirPath(siteDir, pluginId, versionName) {
24
+ return path_1.default.join(siteDir, addPluginIdPrefix(constants_1.VERSIONED_DOCS_DIR, pluginId), `version-${versionName}`);
25
+ }
26
+ exports.getVersionDocsDirPath = getVersionDocsDirPath;
27
+ /** `[siteDir]/community_versioned_sidebars/version-1.0.0-sidebars.json` */
28
+ function getVersionSidebarsPath(siteDir, pluginId, versionName) {
29
+ return path_1.default.join(siteDir, addPluginIdPrefix(constants_1.VERSIONED_SIDEBARS_DIR, pluginId), `version-${versionName}-sidebars.json`);
30
+ }
31
+ exports.getVersionSidebarsPath = getVersionSidebarsPath;
32
+ function getDocsDirPathLocalized({ siteDir, locale, pluginId, versionName, }) {
33
+ return (0, utils_1.getPluginI18nPath)({
34
+ siteDir,
35
+ locale,
36
+ pluginName: 'docusaurus-plugin-content-docs',
37
+ pluginId,
38
+ subPaths: [
39
+ versionName === constants_1.CURRENT_VERSION_NAME
40
+ ? constants_1.CURRENT_VERSION_NAME
41
+ : `version-${versionName}`,
42
+ ],
43
+ });
44
+ }
45
+ exports.getDocsDirPathLocalized = getDocsDirPathLocalized;
46
+ /** `community` => `[siteDir]/community_versions.json` */
47
+ function getVersionsFilePath(siteDir, pluginId) {
48
+ return path_1.default.join(siteDir, addPluginIdPrefix(constants_1.VERSIONS_JSON_FILE, pluginId));
49
+ }
50
+ exports.getVersionsFilePath = getVersionsFilePath;
51
+ /**
52
+ * Reads the plugin's respective `versions.json` file, and returns its content.
53
+ *
54
+ * @throws Throws if validation fails, i.e. `versions.json` doesn't contain an
55
+ * array of valid version names.
56
+ */
57
+ async function readVersionsFile(siteDir, pluginId) {
58
+ const versionsFilePath = getVersionsFilePath(siteDir, pluginId);
59
+ if (await fs_extra_1.default.pathExists(versionsFilePath)) {
60
+ const content = await fs_extra_1.default.readJSON(versionsFilePath);
61
+ (0, validation_1.validateVersionNames)(content);
62
+ return content;
63
+ }
64
+ return null;
65
+ }
66
+ /**
67
+ * Reads the `versions.json` file, and returns an ordered list of version names.
68
+ *
69
+ * - If `disableVersioning` is turned on, it will return `["current"]` (requires
70
+ * `includeCurrentVersion` to be true);
71
+ * - If `includeCurrentVersion` is turned on, "current" will be inserted at the
72
+ * beginning, if not already there.
73
+ *
74
+ * You need to use {@link filterVersions} after this.
75
+ *
76
+ * @throws Throws an error if `disableVersioning: true` but `versions.json`
77
+ * doesn't exist (i.e. site is not versioned)
78
+ * @throws Throws an error if versions list is empty (empty `versions.json` or
79
+ * `disableVersioning` is true, and not including current version)
80
+ */
81
+ async function readVersionNames(siteDir, options) {
82
+ const versionFileContent = await readVersionsFile(siteDir, options.id);
83
+ if (!versionFileContent && options.disableVersioning) {
84
+ throw new Error(`Docs: using "disableVersioning: true" option on a non-versioned site does not make sense.`);
85
+ }
86
+ const versions = options.disableVersioning ? [] : versionFileContent ?? [];
87
+ // We add the current version at the beginning, unless:
88
+ // - user don't want to; or
89
+ // - it's already been explicitly added to versions.json
90
+ if (options.includeCurrentVersion &&
91
+ !versions.includes(constants_1.CURRENT_VERSION_NAME)) {
92
+ versions.unshift(constants_1.CURRENT_VERSION_NAME);
93
+ }
94
+ if (versions.length === 0) {
95
+ throw new Error(`It is not possible to use docs without any version. No version is included because you have requested to not include ${path_1.default.resolve(options.path)} through "includeCurrentVersion: false", while ${options.disableVersioning
96
+ ? 'versioning is disabled with "disableVersioning: true"'
97
+ : `the versions file is empty/non-existent`}.`);
98
+ }
99
+ return versions;
100
+ }
101
+ exports.readVersionNames = readVersionNames;
102
+ /**
103
+ * Gets the path-related version metadata.
104
+ *
105
+ * @throws Throws if the resolved docs folder or sidebars file doesn't exist.
106
+ * Does not throw if a versioned sidebar is missing (since we don't create empty
107
+ * files).
108
+ */
109
+ async function getVersionMetadataPaths({ versionName, context, options, }) {
110
+ const isCurrent = versionName === constants_1.CURRENT_VERSION_NAME;
111
+ const contentPathLocalized = getDocsDirPathLocalized({
112
+ siteDir: context.siteDir,
113
+ locale: context.i18n.currentLocale,
114
+ pluginId: options.id,
115
+ versionName,
116
+ });
117
+ const contentPath = isCurrent
118
+ ? path_1.default.resolve(context.siteDir, options.path)
119
+ : getVersionDocsDirPath(context.siteDir, options.id, versionName);
120
+ const sidebarFilePath = isCurrent
121
+ ? options.sidebarPath
122
+ : getVersionSidebarsPath(context.siteDir, options.id, versionName);
123
+ if (!(await fs_extra_1.default.pathExists(contentPath))) {
124
+ throw new Error(`The docs folder does not exist for version "${versionName}". A docs folder is expected to be found at ${path_1.default.relative(context.siteDir, contentPath)}.`);
125
+ }
126
+ // If the current version defines a path to a sidebar file that does not
127
+ // exist, we throw! Note: for versioned sidebars, the file may not exist (as
128
+ // we prefer to not create it rather than to create an empty file)
129
+ // See https://github.com/facebook/docusaurus/issues/3366
130
+ // See https://github.com/facebook/docusaurus/pull/4775
131
+ if (versionName === constants_1.CURRENT_VERSION_NAME &&
132
+ typeof sidebarFilePath === 'string' &&
133
+ !(await fs_extra_1.default.pathExists(sidebarFilePath))) {
134
+ throw new Error(`The path to the sidebar file does not exist at "${path_1.default.relative(context.siteDir, sidebarFilePath)}".
135
+ Please set the docs "sidebarPath" field in your config file to:
136
+ - a sidebars path that exists
137
+ - false: to disable the sidebar
138
+ - undefined: for Docusaurus to generate it automatically`);
139
+ }
140
+ return { contentPath, contentPathLocalized, sidebarFilePath };
141
+ }
142
+ exports.getVersionMetadataPaths = getVersionMetadataPaths;
@@ -0,0 +1,36 @@
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 { PluginOptions, VersionBanner, VersionMetadata } from '@docusaurus/plugin-content-docs';
8
+ import type { LoadContext } from '@docusaurus/types';
9
+ export declare type VersionContext = {
10
+ /** The version name to get banner of. */
11
+ versionName: string;
12
+ /** All versions, ordered from newest to oldest. */
13
+ versionNames: string[];
14
+ lastVersionName: string;
15
+ context: LoadContext;
16
+ options: PluginOptions;
17
+ };
18
+ /**
19
+ * The default version banner depends on the version's relative position to the
20
+ * latest version. More recent ones are "unreleased", and older ones are
21
+ * "unmaintained".
22
+ */
23
+ export declare function getDefaultVersionBanner({ versionName, versionNames, lastVersionName, }: VersionContext): VersionBanner | null;
24
+ export declare function getVersionBanner(context: VersionContext): VersionMetadata['banner'];
25
+ export declare function getVersionBadge({ versionName, versionNames, options, }: VersionContext): VersionMetadata['badge'];
26
+ /**
27
+ * Filter versions according to provided options (i.e. `onlyIncludeVersions`).
28
+ *
29
+ * Note: we preserve the order in which versions are provided; the order of the
30
+ * `onlyIncludeVersions` array does not matter
31
+ */
32
+ export declare function filterVersions(versionNamesUnfiltered: string[], options: PluginOptions): string[];
33
+ export declare function readVersionsMetadata({ context, options, }: {
34
+ context: LoadContext;
35
+ options: PluginOptions;
36
+ }): Promise<VersionMetadata[]>;
@@ -0,0 +1,155 @@
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.readVersionsMetadata = exports.filterVersions = exports.getVersionBadge = exports.getVersionBanner = exports.getDefaultVersionBanner = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const path_1 = tslib_1.__importDefault(require("path"));
12
+ const constants_1 = require("../constants");
13
+ const utils_1 = require("@docusaurus/utils");
14
+ const validation_1 = require("./validation");
15
+ const files_1 = require("./files");
16
+ function getVersionEditUrls({ contentPath, contentPathLocalized, context, options, }) {
17
+ // If the user is using the functional form of editUrl,
18
+ // she has total freedom and we can't compute a "version edit url"
19
+ if (!options.editUrl || typeof options.editUrl === 'function') {
20
+ return { editUrl: undefined, editUrlLocalized: undefined };
21
+ }
22
+ const editDirPath = options.editCurrentVersion ? options.path : contentPath;
23
+ const editDirPathLocalized = options.editCurrentVersion
24
+ ? (0, files_1.getDocsDirPathLocalized)({
25
+ siteDir: context.siteDir,
26
+ locale: context.i18n.currentLocale,
27
+ versionName: constants_1.CURRENT_VERSION_NAME,
28
+ pluginId: options.id,
29
+ })
30
+ : contentPathLocalized;
31
+ const versionPathSegment = (0, utils_1.posixPath)(path_1.default.relative(context.siteDir, path_1.default.resolve(context.siteDir, editDirPath)));
32
+ const versionPathSegmentLocalized = (0, utils_1.posixPath)(path_1.default.relative(context.siteDir, path_1.default.resolve(context.siteDir, editDirPathLocalized)));
33
+ const editUrl = (0, utils_1.normalizeUrl)([options.editUrl, versionPathSegment]);
34
+ const editUrlLocalized = (0, utils_1.normalizeUrl)([
35
+ options.editUrl,
36
+ versionPathSegmentLocalized,
37
+ ]);
38
+ return { editUrl, editUrlLocalized };
39
+ }
40
+ /**
41
+ * The default version banner depends on the version's relative position to the
42
+ * latest version. More recent ones are "unreleased", and older ones are
43
+ * "unmaintained".
44
+ */
45
+ function getDefaultVersionBanner({ versionName, versionNames, lastVersionName, }) {
46
+ // Current version: good, no banner
47
+ if (versionName === lastVersionName) {
48
+ return null;
49
+ }
50
+ // Upcoming versions: unreleased banner
51
+ if (versionNames.indexOf(versionName) < versionNames.indexOf(lastVersionName)) {
52
+ return 'unreleased';
53
+ }
54
+ // Older versions: display unmaintained banner
55
+ return 'unmaintained';
56
+ }
57
+ exports.getDefaultVersionBanner = getDefaultVersionBanner;
58
+ function getVersionBanner(context) {
59
+ const { versionName, options } = context;
60
+ const versionBannerOption = options.versions[versionName]?.banner;
61
+ if (versionBannerOption) {
62
+ return versionBannerOption === 'none' ? null : versionBannerOption;
63
+ }
64
+ return getDefaultVersionBanner(context);
65
+ }
66
+ exports.getVersionBanner = getVersionBanner;
67
+ function getVersionBadge({ versionName, versionNames, options, }) {
68
+ // If site is not versioned or only one version is included
69
+ // we don't show the version badge by default
70
+ // See https://github.com/facebook/docusaurus/issues/3362
71
+ const defaultVersionBadge = versionNames.length !== 1;
72
+ return options.versions[versionName]?.badge ?? defaultVersionBadge;
73
+ }
74
+ exports.getVersionBadge = getVersionBadge;
75
+ function getVersionClassName({ versionName, options, }) {
76
+ const defaultVersionClassName = `docs-version-${versionName}`;
77
+ return options.versions[versionName]?.className ?? defaultVersionClassName;
78
+ }
79
+ function getVersionLabel({ versionName, options, }) {
80
+ const defaultVersionLabel = versionName === constants_1.CURRENT_VERSION_NAME ? 'Next' : versionName;
81
+ return options.versions[versionName]?.label ?? defaultVersionLabel;
82
+ }
83
+ function getVersionPathPart({ versionName, options, lastVersionName, }) {
84
+ function getDefaultVersionPathPart() {
85
+ if (versionName === lastVersionName) {
86
+ return '';
87
+ }
88
+ return versionName === constants_1.CURRENT_VERSION_NAME ? 'next' : versionName;
89
+ }
90
+ return options.versions[versionName]?.path ?? getDefaultVersionPathPart();
91
+ }
92
+ async function createVersionMetadata(context) {
93
+ const { versionName, lastVersionName, options, context: loadContext } = context;
94
+ const { sidebarFilePath, contentPath, contentPathLocalized } = await (0, files_1.getVersionMetadataPaths)(context);
95
+ const versionPathPart = getVersionPathPart(context);
96
+ const routePath = (0, utils_1.normalizeUrl)([
97
+ loadContext.baseUrl,
98
+ options.routeBasePath,
99
+ versionPathPart,
100
+ ]);
101
+ const versionEditUrls = getVersionEditUrls({
102
+ contentPath,
103
+ contentPathLocalized,
104
+ context: loadContext,
105
+ options,
106
+ });
107
+ return {
108
+ versionName,
109
+ label: getVersionLabel(context),
110
+ banner: getVersionBanner(context),
111
+ badge: getVersionBadge(context),
112
+ className: getVersionClassName(context),
113
+ path: routePath,
114
+ tagsPath: (0, utils_1.normalizeUrl)([routePath, options.tagsBasePath]),
115
+ ...versionEditUrls,
116
+ isLast: versionName === lastVersionName,
117
+ routePriority: versionPathPart === '' ? -1 : undefined,
118
+ sidebarFilePath,
119
+ contentPath,
120
+ contentPathLocalized,
121
+ };
122
+ }
123
+ /**
124
+ * Filter versions according to provided options (i.e. `onlyIncludeVersions`).
125
+ *
126
+ * Note: we preserve the order in which versions are provided; the order of the
127
+ * `onlyIncludeVersions` array does not matter
128
+ */
129
+ function filterVersions(versionNamesUnfiltered, options) {
130
+ if (options.onlyIncludeVersions) {
131
+ return versionNamesUnfiltered.filter((name) => options.onlyIncludeVersions.includes(name));
132
+ }
133
+ return versionNamesUnfiltered;
134
+ }
135
+ exports.filterVersions = filterVersions;
136
+ function getLastVersionName({ versionNames, options, }) {
137
+ return (options.lastVersion ??
138
+ versionNames.find((name) => name !== constants_1.CURRENT_VERSION_NAME) ??
139
+ constants_1.CURRENT_VERSION_NAME);
140
+ }
141
+ async function readVersionsMetadata({ context, options, }) {
142
+ const allVersionNames = await (0, files_1.readVersionNames)(context.siteDir, options);
143
+ (0, validation_1.validateVersionsOptions)(allVersionNames, options);
144
+ const versionNames = filterVersions(allVersionNames, options);
145
+ const lastVersionName = getLastVersionName({ versionNames, options });
146
+ const versionsMetadata = await Promise.all(versionNames.map((versionName) => createVersionMetadata({
147
+ versionName,
148
+ versionNames,
149
+ lastVersionName,
150
+ context,
151
+ options,
152
+ })));
153
+ return versionsMetadata;
154
+ }
155
+ exports.readVersionsMetadata = readVersionsMetadata;
@@ -0,0 +1,17 @@
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 { VersionsOptions } from '@docusaurus/plugin-content-docs';
8
+ export declare function validateVersionName(name: unknown): asserts name is string;
9
+ export declare function validateVersionNames(names: unknown): asserts names is string[];
10
+ /**
11
+ * @throws Throws for one of the following invalid options:
12
+ * - `lastVersion` is non-existent
13
+ * - `versions` includes unknown keys
14
+ * - `onlyIncludeVersions` is empty, contains unknown names, or doesn't include
15
+ * `latestVersion` (if provided)
16
+ */
17
+ export declare function validateVersionsOptions(availableVersionNames: string[], options: VersionsOptions): void;
@@ -0,0 +1,71 @@
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.validateVersionsOptions = exports.validateVersionNames = exports.validateVersionName = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
12
+ function validateVersionName(name) {
13
+ if (typeof name !== 'string') {
14
+ throw new Error(`Versions should be strings. Found type "${typeof name}" for version "${name}".`);
15
+ }
16
+ if (!name.trim()) {
17
+ throw new Error(`Invalid version name "${name}": version name must contain at least one non-whitespace character.`);
18
+ }
19
+ const errors = [
20
+ [/[/\\]/, 'should not include slash (/) or backslash (\\)'],
21
+ [/.{33,}/, 'cannot be longer than 32 characters'],
22
+ // eslint-disable-next-line no-control-regex
23
+ [/[<>:"|?*\x00-\x1F]/, 'should be a valid file path'],
24
+ [/^\.\.?$/, 'should not be "." or ".."'],
25
+ ];
26
+ errors.forEach(([pattern, message]) => {
27
+ if (pattern.test(name)) {
28
+ throw new Error(`Invalid version name "${name}": version name ${message}.`);
29
+ }
30
+ });
31
+ }
32
+ exports.validateVersionName = validateVersionName;
33
+ function validateVersionNames(names) {
34
+ if (!Array.isArray(names)) {
35
+ throw new Error(`The versions file should contain an array of version names! Found content: ${JSON.stringify(names)}`);
36
+ }
37
+ names.forEach(validateVersionName);
38
+ }
39
+ exports.validateVersionNames = validateVersionNames;
40
+ /**
41
+ * @throws Throws for one of the following invalid options:
42
+ * - `lastVersion` is non-existent
43
+ * - `versions` includes unknown keys
44
+ * - `onlyIncludeVersions` is empty, contains unknown names, or doesn't include
45
+ * `latestVersion` (if provided)
46
+ */
47
+ function validateVersionsOptions(availableVersionNames, options) {
48
+ const availableVersionNamesMsg = `Available version names are: ${availableVersionNames.join(', ')}`;
49
+ if (options.lastVersion &&
50
+ !availableVersionNames.includes(options.lastVersion)) {
51
+ throw new Error(`Docs option lastVersion: ${options.lastVersion} is invalid. ${availableVersionNamesMsg}`);
52
+ }
53
+ const unknownVersionConfigNames = lodash_1.default.difference(Object.keys(options.versions), availableVersionNames);
54
+ if (unknownVersionConfigNames.length > 0) {
55
+ throw new Error(`Invalid docs option "versions": unknown versions (${unknownVersionConfigNames.join(',')}) found. ${availableVersionNamesMsg}`);
56
+ }
57
+ if (options.onlyIncludeVersions) {
58
+ if (options.onlyIncludeVersions.length === 0) {
59
+ throw new Error(`Invalid docs option "onlyIncludeVersions": an empty array is not allowed, at least one version is needed.`);
60
+ }
61
+ const unknownOnlyIncludeVersionNames = lodash_1.default.difference(options.onlyIncludeVersions, availableVersionNames);
62
+ if (unknownOnlyIncludeVersionNames.length > 0) {
63
+ throw new Error(`Invalid docs option "onlyIncludeVersions": unknown versions (${unknownOnlyIncludeVersionNames.join(',')}) found. ${availableVersionNamesMsg}`);
64
+ }
65
+ if (options.lastVersion &&
66
+ !options.onlyIncludeVersions.includes(options.lastVersion)) {
67
+ throw new Error(`Invalid docs option "lastVersion": if you use both the "onlyIncludeVersions" and "lastVersion" options, then "lastVersion" must be present in the provided "onlyIncludeVersions" array.`);
68
+ }
69
+ }
70
+ }
71
+ exports.validateVersionsOptions = validateVersionsOptions;