@rspress/plugin-typedoc 1.37.2 → 1.37.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rspress/plugin-typedoc",
3
- "version": "1.37.2",
3
+ "version": "1.37.4",
4
4
  "description": "A plugin for rspress to integrate typedoc",
5
5
  "bugs": "https://github.com/web-infra-dev/rspress/issues",
6
6
  "repository": {
@@ -17,16 +17,18 @@
17
17
  "node": ">=14.17.6"
18
18
  },
19
19
  "devDependencies": {
20
- "@modern-js/tsconfig": "2.62.0",
20
+ "@microsoft/api-extractor": "^7.48.0",
21
+ "@modern-js/tsconfig": "2.63.0",
22
+ "@rslib/core": "0.1.2",
21
23
  "@types/node": "^18.11.17",
22
24
  "@types/react": "^18.3.12",
23
25
  "@types/react-dom": "^18.3.1",
24
26
  "react": "^18.3.1",
25
27
  "typescript": "^5.5.3",
26
- "vitest": "2.1.5"
28
+ "vitest": "2.1.8"
27
29
  },
28
30
  "peerDependencies": {
29
- "rspress": "^1.37.2"
31
+ "rspress": "^1.37.4"
30
32
  },
31
33
  "sideEffects": [
32
34
  "*.css",
@@ -46,11 +48,11 @@
46
48
  "dependencies": {
47
49
  "typedoc": "0.24.8",
48
50
  "typedoc-plugin-markdown": "3.17.1",
49
- "@rspress/shared": "1.37.2"
51
+ "@rspress/shared": "1.37.4"
50
52
  },
51
53
  "scripts": {
52
- "dev": "modern build -w",
53
- "build": "modern build",
54
+ "dev": "rslib build -w",
55
+ "build": "rslib build",
54
56
  "reset": "rimraf ./**/node_modules",
55
57
  "test": "vitest run --passWithNoTests"
56
58
  }
package/src/constants.ts CHANGED
@@ -1,2 +1 @@
1
1
  export const API_DIR = 'api';
2
- export const ROUTE_PREFIX = `/${API_DIR}`;
package/src/index.ts CHANGED
@@ -1,12 +1,9 @@
1
1
  import path from 'node:path';
2
2
  import { Application, TSConfigReader } from 'typedoc';
3
- import type { RspressPlugin } from '@rspress/shared';
3
+ import type { NavItem, RspressPlugin } from '@rspress/shared';
4
4
  import { load } from 'typedoc-plugin-markdown';
5
5
  import { API_DIR } from './constants';
6
- import {
7
- resolveSidebarForMultiEntry,
8
- resolveSidebarForSingleEntry,
9
- } from './sidebar';
6
+ import { patchGeneratedApiDocs } from './patch';
10
7
 
11
8
  export interface PluginTypeDocOptions {
12
9
  /**
@@ -24,12 +21,13 @@ export interface PluginTypeDocOptions {
24
21
  export function pluginTypeDoc(options: PluginTypeDocOptions): RspressPlugin {
25
22
  let docRoot: string | undefined;
26
23
  const { entryPoints = [], outDir = API_DIR } = options;
24
+ const apiPageRoute = `/${outDir.replace(/(^\/)|(\/$)/, '')}/`; // e.g: /api/
27
25
  return {
28
26
  name: '@rspress/plugin-typedoc',
29
27
  async addPages() {
30
28
  return [
31
29
  {
32
- routePath: `${outDir.replace(/\/$/, '')}/`,
30
+ routePath: apiPageRoute,
33
31
  filepath: path.join(docRoot!, outDir, 'README.md'),
34
32
  },
35
33
  ];
@@ -56,41 +54,49 @@ export function pluginTypeDoc(options: PluginTypeDocOptions): RspressPlugin {
56
54
  const project = app.convert();
57
55
 
58
56
  if (project) {
59
- // 1. Generate module doc by typedoc
60
- const absoluteOutputdir = path.join(docRoot!, outDir);
61
- await app.generateDocs(project, absoluteOutputdir);
62
- const jsonDir = path.join(absoluteOutputdir, 'documentation.json');
63
- await app.generateJson(project, jsonDir);
64
- // 2. Generate sidebar
57
+ // 1. Generate doc/api, doc/api/_meta.json by typedoc
58
+ const absoluteApiDir = path.join(docRoot!, outDir);
59
+ await app.generateDocs(project, absoluteApiDir);
60
+ await patchGeneratedApiDocs(absoluteApiDir);
61
+
62
+ // 2. Generate "api" nav bar
65
63
  config.themeConfig = config.themeConfig || {};
66
64
  config.themeConfig.nav = config.themeConfig.nav || [];
67
- const apiIndexLink = `/${outDir.replace(/(^\/)|(\/$)/, '')}/`;
68
65
  const { nav } = config.themeConfig;
66
+
67
+ // avoid that user config "api" in doc/_meta.json
68
+ function isApiAlreadyInNav(navList: NavItem[]) {
69
+ return navList.some(item => {
70
+ if (
71
+ 'link' in item &&
72
+ typeof item.link === 'string' &&
73
+ item.link.startsWith(
74
+ apiPageRoute.slice(0, apiPageRoute.length - 1), // /api
75
+ )
76
+ ) {
77
+ return true;
78
+ }
79
+ return false;
80
+ });
81
+ }
82
+
69
83
  // Note: TypeDoc does not support i18n
70
84
  if (Array.isArray(nav)) {
71
- nav.push({
72
- text: 'API',
73
- link: apiIndexLink,
74
- });
85
+ if (!isApiAlreadyInNav(nav)) {
86
+ nav.push({
87
+ text: 'API',
88
+ link: apiPageRoute,
89
+ });
90
+ }
75
91
  } else if ('default' in nav) {
76
- nav.default.push({
77
- text: 'API',
78
- link: apiIndexLink,
79
- });
92
+ if (!isApiAlreadyInNav(nav.default)) {
93
+ nav.default.push({
94
+ text: 'API',
95
+ link: apiPageRoute,
96
+ });
97
+ }
80
98
  }
81
-
82
- config.themeConfig.sidebar = config.themeConfig.sidebar || {};
83
- config.themeConfig.sidebar[apiIndexLink] =
84
- entryPoints.length > 1
85
- ? await resolveSidebarForMultiEntry(jsonDir)
86
- : await resolveSidebarForSingleEntry(jsonDir);
87
- config.themeConfig.sidebar[apiIndexLink].unshift({
88
- text: 'Overview',
89
- link: `${apiIndexLink}README`,
90
- });
91
99
  }
92
- config.route = config.route || {};
93
- config.route.exclude = config.route.exclude || [];
94
100
  return config;
95
101
  },
96
102
  };
package/src/patch.ts ADDED
@@ -0,0 +1,72 @@
1
+ import fs from '@rspress/shared/fs-extra';
2
+ import path from 'node:path';
3
+
4
+ async function patchLinks(outputDir: string) {
5
+ // Patch links in markdown files
6
+ // Scan all the markdown files in the output directory
7
+ // replace
8
+ // 1. [foo](bar) -> [foo](./bar)
9
+ // 2. [foo](./bar) -> [foo](./bar) no change
10
+ const normlizeLinksInFile = async (filePath: string) => {
11
+ const content = await fs.readFile(filePath, 'utf-8');
12
+ // 1. [foo](bar) -> [foo](./bar)
13
+ const newContent = content.replace(
14
+ /\[([^\]]+)\]\(([^)]+)\)/g,
15
+ (_match, p1, p2) => {
16
+ // 2. [foo](./bar) -> [foo](./bar) no change
17
+ if (['/', '.'].includes(p2[0])) {
18
+ return `[${p1}](${p2})`;
19
+ }
20
+ return `[${p1}](./${p2})`;
21
+ },
22
+ );
23
+ await fs.writeFile(filePath, newContent);
24
+ };
25
+
26
+ const traverse = async (dir: string) => {
27
+ const files = await fs.readdir(dir);
28
+ const filePaths = files.map(file => path.join(dir, file));
29
+ const stats = await Promise.all(filePaths.map(fp => fs.stat(fp)));
30
+
31
+ await Promise.all(
32
+ stats.map((stat, index) => {
33
+ const file = files[index];
34
+ const filePath = filePaths[index];
35
+ if (stat.isDirectory()) {
36
+ return traverse(filePath);
37
+ }
38
+ if (stat.isFile() && /\.mdx?/.test(file)) {
39
+ return normlizeLinksInFile(filePath);
40
+ }
41
+ }),
42
+ );
43
+ };
44
+ await traverse(outputDir);
45
+ }
46
+
47
+ async function generateMetaJson(absoluteApiDir: string) {
48
+ const metaJsonPath = path.join(absoluteApiDir, '_meta.json');
49
+
50
+ const files = await fs.readdir(absoluteApiDir);
51
+ const filePaths = files.map(file => path.join(absoluteApiDir, file));
52
+ const stats = await Promise.all(filePaths.map(fp => fs.stat(fp)));
53
+ const dirs = stats
54
+ .map((stat, index) => (stat.isDirectory() ? files[index] : null))
55
+ .filter(Boolean) as string[];
56
+
57
+ const meta = dirs.map(dir => ({
58
+ type: 'dir',
59
+ label: dir.slice(0, 1).toUpperCase() + dir.slice(1),
60
+ name: dir,
61
+ }));
62
+ await fs.writeFile(metaJsonPath, JSON.stringify(['index', ...meta]));
63
+ }
64
+
65
+ export async function patchGeneratedApiDocs(absoluteApiDir: string) {
66
+ await patchLinks(absoluteApiDir);
67
+ await fs.rename(
68
+ path.join(absoluteApiDir, 'README.md'),
69
+ path.join(absoluteApiDir, 'index.md'),
70
+ );
71
+ await generateMetaJson(absoluteApiDir);
72
+ }
@@ -1,17 +0,0 @@
1
- import { RspressPlugin } from '@rspress/shared';
2
-
3
- interface PluginTypeDocOptions {
4
- /**
5
- * The entry points of modules.
6
- * @default []
7
- */
8
- entryPoints: string[];
9
- /**
10
- * The output directory.
11
- * @default 'api'
12
- */
13
- outDir?: string;
14
- }
15
- declare function pluginTypeDoc(options: PluginTypeDocOptions): RspressPlugin;
16
-
17
- export { type PluginTypeDocOptions, pluginTypeDoc };
package/dist/es/index.js DELETED
@@ -1,253 +0,0 @@
1
- var __async = (__this, __arguments, generator) => {
2
- return new Promise((resolve, reject) => {
3
- var fulfilled = (value) => {
4
- try {
5
- step(generator.next(value));
6
- } catch (e) {
7
- reject(e);
8
- }
9
- };
10
- var rejected = (value) => {
11
- try {
12
- step(generator.throw(value));
13
- } catch (e) {
14
- reject(e);
15
- }
16
- };
17
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
- step((generator = generator.apply(__this, __arguments)).next());
19
- });
20
- };
21
-
22
- // src/index.ts
23
- import path2 from "path";
24
- import { Application, TSConfigReader } from "typedoc";
25
- import { load } from "typedoc-plugin-markdown";
26
-
27
- // src/constants.ts
28
- var API_DIR = "api";
29
- var ROUTE_PREFIX = `/${API_DIR}`;
30
-
31
- // src/sidebar.ts
32
- import path from "path";
33
- import fs from "@rspress/shared/fs-extra";
34
-
35
- // src/utils.ts
36
- function transformModuleName(name) {
37
- return name.replace(/\//g, "_").replace(/-/g, "_");
38
- }
39
-
40
- // src/sidebar.ts
41
- function patchLinks(outputDir) {
42
- return __async(this, null, function* () {
43
- const normlizeLinksInFile = (filePath) => __async(this, null, function* () {
44
- const content = yield fs.readFile(filePath, "utf-8");
45
- const newContent = content.replace(
46
- /\[([^\]]+)\]\(([^)]+)\)/g,
47
- (_match, p1, p2) => {
48
- return `[${p1}](./${p2})`;
49
- }
50
- );
51
- yield fs.writeFile(filePath, newContent);
52
- });
53
- const traverse = (dir) => __async(this, null, function* () {
54
- const files = yield fs.readdir(dir);
55
- for (const file of files) {
56
- const filePath = path.join(dir, file);
57
- const stat = yield fs.stat(filePath);
58
- if (stat.isDirectory()) {
59
- yield traverse(filePath);
60
- } else if (stat.isFile() && /\.mdx?/.test(file)) {
61
- yield normlizeLinksInFile(filePath);
62
- }
63
- }
64
- });
65
- yield traverse(outputDir);
66
- });
67
- }
68
- function resolveSidebarForSingleEntry(jsonFile) {
69
- return __async(this, null, function* () {
70
- const result = [];
71
- const data = JSON.parse(yield fs.readFile(jsonFile, "utf-8"));
72
- if (!data.children || data.children.length <= 0) {
73
- return [];
74
- }
75
- const symbolMap = /* @__PURE__ */ new Map();
76
- data.groups.forEach((group) => {
77
- const groupItem = {
78
- text: group.title,
79
- items: []
80
- };
81
- group.children.forEach((id) => {
82
- const dataItem = data.children.find((item) => item.id === id);
83
- if (dataItem) {
84
- let fileName = dataItem.name;
85
- if (symbolMap.has(dataItem.name)) {
86
- const count = symbolMap.get(dataItem.name) + 1;
87
- symbolMap.set(dataItem.name, count);
88
- fileName = `${dataItem.name}-${count}`;
89
- } else {
90
- symbolMap.set(dataItem.name.toLocaleLowerCase(), 0);
91
- }
92
- groupItem.items.push({
93
- text: dataItem.name,
94
- link: `${ROUTE_PREFIX}/${group.title.toLocaleLowerCase()}/${fileName}`
95
- });
96
- }
97
- });
98
- result.push(groupItem);
99
- });
100
- yield patchLinks(path.dirname(jsonFile));
101
- return result;
102
- });
103
- }
104
- function resolveSidebarForMultiEntry(jsonFile) {
105
- return __async(this, null, function* () {
106
- const result = [];
107
- const data = JSON.parse(yield fs.readFile(jsonFile, "utf-8"));
108
- if (!data.children || data.children.length <= 0) {
109
- return result;
110
- }
111
- function getModulePath(name) {
112
- return path.join(`${ROUTE_PREFIX}/modules`, `${transformModuleName(name)}`).replace(/\\/g, "/");
113
- }
114
- function getClassPath(moduleName, className) {
115
- return path.join(
116
- `${ROUTE_PREFIX}/classes`,
117
- `${transformModuleName(moduleName)}.${className}`
118
- ).replace(/\\/g, "/");
119
- }
120
- function getInterfacePath(moduleName, interfaceName) {
121
- return path.join(
122
- `${ROUTE_PREFIX}/interfaces`,
123
- `${transformModuleName(moduleName)}.${interfaceName}`
124
- ).replace(/\\/g, "/");
125
- }
126
- function getFunctionPath(moduleName, functionName) {
127
- return path.join(
128
- `${ROUTE_PREFIX}/functions`,
129
- `${transformModuleName(moduleName)}.${functionName}`
130
- ).replace(/\\/g, "/");
131
- }
132
- data.children.forEach((module) => {
133
- const moduleNames = module.name.split("/");
134
- const name = moduleNames[moduleNames.length - 1];
135
- const moduleConfig = {
136
- text: `Module:${name}`,
137
- items: [{ text: "Overview", link: getModulePath(module.name) }]
138
- };
139
- if (!module.children || module.children.length <= 0) {
140
- return;
141
- }
142
- module.children.forEach((sub) => {
143
- var _a;
144
- const kindString = (_a = module.groups.find((item) => item.children.includes(sub.id))) == null ? void 0 : _a.title.slice(0, -1);
145
- if (!kindString) {
146
- return;
147
- }
148
- switch (kindString) {
149
- case "Class":
150
- moduleConfig.items.push({
151
- text: `Class:${sub.name}`,
152
- link: getClassPath(module.name, sub.name)
153
- });
154
- break;
155
- case "Interface":
156
- moduleConfig.items.push({
157
- text: `Interface:${sub.name}`,
158
- link: getInterfacePath(module.name, sub.name)
159
- });
160
- break;
161
- case "Function":
162
- moduleConfig.items.push({
163
- text: `Function:${sub.name}`,
164
- link: getFunctionPath(module.name, sub.name)
165
- });
166
- break;
167
- default:
168
- break;
169
- }
170
- });
171
- result.push(moduleConfig);
172
- });
173
- yield patchLinks(path.dirname(jsonFile));
174
- return result;
175
- });
176
- }
177
-
178
- // src/index.ts
179
- function pluginTypeDoc(options) {
180
- let docRoot;
181
- const { entryPoints = [], outDir = API_DIR } = options;
182
- return {
183
- name: "@rspress/plugin-typedoc",
184
- addPages() {
185
- return __async(this, null, function* () {
186
- return [
187
- {
188
- routePath: `${outDir.replace(/\/$/, "")}/`,
189
- filepath: path2.join(docRoot, outDir, "README.md")
190
- }
191
- ];
192
- });
193
- },
194
- config(config) {
195
- return __async(this, null, function* () {
196
- const app = new Application();
197
- docRoot = config.root;
198
- app.options.addReader(new TSConfigReader());
199
- load(app);
200
- app.bootstrap({
201
- name: config.title,
202
- entryPoints,
203
- theme: "markdown",
204
- disableSources: true,
205
- readme: "none",
206
- githubPages: false,
207
- requiredToBeDocumented: ["Class", "Function", "Interface"],
208
- plugin: ["typedoc-plugin-markdown"],
209
- // @ts-expect-error MarkdownTheme has no export
210
- hideBreadcrumbs: true,
211
- hideMembersSymbol: true,
212
- allReflectionsHaveOwnDocument: true
213
- });
214
- const project = app.convert();
215
- if (project) {
216
- const absoluteOutputdir = path2.join(docRoot, outDir);
217
- yield app.generateDocs(project, absoluteOutputdir);
218
- const jsonDir = path2.join(absoluteOutputdir, "documentation.json");
219
- yield app.generateJson(project, jsonDir);
220
- config.themeConfig = config.themeConfig || {};
221
- config.themeConfig.nav = config.themeConfig.nav || [];
222
- const apiIndexLink = `/${outDir.replace(/(^\/)|(\/$)/, "")}/`;
223
- const { nav } = config.themeConfig;
224
- if (Array.isArray(nav)) {
225
- nav.push({
226
- text: "API",
227
- link: apiIndexLink
228
- });
229
- } else if ("default" in nav) {
230
- nav.default.push({
231
- text: "API",
232
- link: apiIndexLink
233
- });
234
- }
235
- config.themeConfig.sidebar = config.themeConfig.sidebar || {};
236
- config.themeConfig.sidebar[apiIndexLink] = entryPoints.length > 1 ? yield resolveSidebarForMultiEntry(jsonDir) : yield resolveSidebarForSingleEntry(jsonDir);
237
- config.themeConfig.sidebar[apiIndexLink].unshift({
238
- text: "Overview",
239
- link: `${apiIndexLink}README`
240
- });
241
- }
242
- config.route = config.route || {};
243
- config.route.exclude = config.route.exclude || [];
244
- return config;
245
- });
246
- }
247
- };
248
- }
249
- export {
250
- pluginTypeDoc
251
- };
252
-
253
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,WAAU;AACjB,SAAS,aAAa,sBAAsB;AAE5C,SAAS,YAAY;;;ACH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C,iBAAO,cAAc,OAAO,eAAe,CAAC;AAC5C,iBAAO,YAAY,MAAM,OAAO,YAAY,OAAO,CAAC;AACpD,gBAAM,eAAe,IAAI,OAAO,QAAQ,eAAe,EAAE,CAAC;AAC1D,gBAAM,EAAE,IAAI,IAAI,OAAO;AAEvB,cAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,gBAAI,KAAK;AAAA,cACP,MAAM;AAAA,cACN,MAAM;AAAA,YACR,CAAC;AAAA,UACH,WAAW,aAAa,KAAK;AAC3B,gBAAI,QAAQ,KAAK;AAAA,cACf,MAAM;AAAA,cACN,MAAM;AAAA,YACR,CAAC;AAAA,UACH;AAEA,iBAAO,YAAY,UAAU,OAAO,YAAY,WAAW,CAAC;AAC5D,iBAAO,YAAY,QAAQ,YAAY,IACrC,YAAY,SAAS,IACjB,MAAM,4BAA4B,OAAO,IACzC,MAAM,6BAA6B,OAAO;AAChD,iBAAO,YAAY,QAAQ,YAAY,EAAE,QAAQ;AAAA,YAC/C,MAAM;AAAA,YACN,MAAM,GAAG,YAAY;AAAA,UACvB,CAAC;AAAA,QACH;AACA,eAAO,QAAQ,OAAO,SAAS,CAAC;AAChC,eAAO,MAAM,UAAU,OAAO,MAAM,WAAW,CAAC;AAChD,eAAO;AAAA,MACT;AAAA;AAAA,EACF;AACF","names":["path"],"ignoreList":[],"sources":["../../src/index.ts","../../src/constants.ts","../../src/sidebar.ts","../../src/utils.ts"],"sourcesContent":["import path from 'node:path';\nimport { Application, TSConfigReader } from 'typedoc';\nimport type { RspressPlugin } from '@rspress/shared';\nimport { load } from 'typedoc-plugin-markdown';\nimport { API_DIR } from './constants';\nimport {\n resolveSidebarForMultiEntry,\n resolveSidebarForSingleEntry,\n} from './sidebar';\n\nexport interface PluginTypeDocOptions {\n /**\n * The entry points of modules.\n * @default []\n */\n entryPoints: string[];\n /**\n * The output directory.\n * @default 'api'\n */\n outDir?: string;\n}\n\nexport function pluginTypeDoc(options: PluginTypeDocOptions): RspressPlugin {\n let docRoot: string | undefined;\n const { entryPoints = [], outDir = API_DIR } = options;\n return {\n name: '@rspress/plugin-typedoc',\n async addPages() {\n return [\n {\n routePath: `${outDir.replace(/\\/$/, '')}/`,\n filepath: path.join(docRoot!, outDir, 'README.md'),\n },\n ];\n },\n async config(config) {\n const app = new Application();\n docRoot = config.root;\n app.options.addReader(new TSConfigReader());\n load(app);\n app.bootstrap({\n name: config.title,\n entryPoints,\n theme: 'markdown',\n disableSources: true,\n readme: 'none',\n githubPages: false,\n requiredToBeDocumented: ['Class', 'Function', 'Interface'],\n plugin: ['typedoc-plugin-markdown'],\n // @ts-expect-error MarkdownTheme has no export\n hideBreadcrumbs: true,\n hideMembersSymbol: true,\n allReflectionsHaveOwnDocument: true,\n });\n const project = app.convert();\n\n if (project) {\n // 1. Generate module doc by typedoc\n const absoluteOutputdir = path.join(docRoot!, outDir);\n await app.generateDocs(project, absoluteOutputdir);\n const jsonDir = path.join(absoluteOutputdir, 'documentation.json');\n await app.generateJson(project, jsonDir);\n // 2. Generate sidebar\n config.themeConfig = config.themeConfig || {};\n config.themeConfig.nav = config.themeConfig.nav || [];\n const apiIndexLink = `/${outDir.replace(/(^\\/)|(\\/$)/, '')}/`;\n const { nav } = config.themeConfig;\n // Note: TypeDoc does not support i18n\n if (Array.isArray(nav)) {\n nav.push({\n text: 'API',\n link: apiIndexLink,\n });\n } else if ('default' in nav) {\n nav.default.push({\n text: 'API',\n link: apiIndexLink,\n });\n }\n\n config.themeConfig.sidebar = config.themeConfig.sidebar || {};\n config.themeConfig.sidebar[apiIndexLink] =\n entryPoints.length > 1\n ? await resolveSidebarForMultiEntry(jsonDir)\n : await resolveSidebarForSingleEntry(jsonDir);\n config.themeConfig.sidebar[apiIndexLink].unshift({\n text: 'Overview',\n link: `${apiIndexLink}README`,\n });\n }\n config.route = config.route || {};\n config.route.exclude = config.route.exclude || [];\n return config;\n },\n };\n}\n","export const API_DIR = 'api';\nexport const ROUTE_PREFIX = `/${API_DIR}`;\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport type { SidebarGroup } from '@rspress/shared';\nimport { transformModuleName } from './utils';\nimport { ROUTE_PREFIX } from './constants';\n\ninterface ModuleItem {\n id: number;\n name: string;\n children: {\n id: number;\n name: string;\n }[];\n groups: {\n title: string;\n children: number[];\n }[];\n}\n\nasync function patchLinks(outputDir: string) {\n // Patch links in markdown files\n // Scan all the markdown files in the output directory\n // replace [foo](bar) -> [foo](./bar)\n const normlizeLinksInFile = async (filePath: string) => {\n const content = await fs.readFile(filePath, 'utf-8');\n // replace: [foo](bar) -> [foo](./bar)\n const newContent = content.replace(\n /\\[([^\\]]+)\\]\\(([^)]+)\\)/g,\n (_match, p1, p2) => {\n return `[${p1}](./${p2})`;\n },\n );\n await fs.writeFile(filePath, newContent);\n };\n\n const traverse = async (dir: string) => {\n const files = await fs.readdir(dir);\n for (const file of files) {\n const filePath = path.join(dir, file);\n const stat = await fs.stat(filePath);\n if (stat.isDirectory()) {\n await traverse(filePath);\n } else if (stat.isFile() && /\\.mdx?/.test(file)) {\n await normlizeLinksInFile(filePath);\n }\n }\n };\n await traverse(outputDir);\n}\n\nexport async function resolveSidebarForSingleEntry(\n jsonFile: string,\n): Promise<SidebarGroup[]> {\n const result: SidebarGroup[] = [];\n const data = JSON.parse(await fs.readFile(jsonFile, 'utf-8'));\n if (!data.children || data.children.length <= 0) {\n return [];\n }\n const symbolMap = new Map<string, number>();\n data.groups.forEach((group: { title: string; children: number[] }) => {\n const groupItem: SidebarGroup = {\n text: group.title,\n items: [],\n };\n group.children.forEach((id: number) => {\n const dataItem = data.children.find((item: ModuleItem) => item.id === id);\n if (dataItem) {\n // Note: we should handle the case that classes and interfaces have the same name\n // Such as class `Env` and variable `env`\n // The final output file name should be `classes/Env.md` and `variables/env-1.md`\n let fileName = dataItem.name;\n if (symbolMap.has(dataItem.name)) {\n const count = symbolMap.get(dataItem.name)! + 1;\n symbolMap.set(dataItem.name, count);\n fileName = `${dataItem.name}-${count}`;\n } else {\n symbolMap.set(dataItem.name.toLocaleLowerCase(), 0);\n }\n groupItem.items.push({\n text: dataItem.name,\n link: `${ROUTE_PREFIX}/${group.title.toLocaleLowerCase()}/${fileName}`,\n });\n }\n });\n result.push(groupItem);\n });\n\n await patchLinks(path.dirname(jsonFile));\n\n return result;\n}\n\nexport async function resolveSidebarForMultiEntry(\n jsonFile: string,\n): Promise<SidebarGroup[]> {\n const result: SidebarGroup[] = [];\n const data = JSON.parse(await fs.readFile(jsonFile, 'utf-8'));\n if (!data.children || data.children.length <= 0) {\n return result;\n }\n\n function getModulePath(name: string) {\n return path\n .join(`${ROUTE_PREFIX}/modules`, `${transformModuleName(name)}`)\n .replace(/\\\\/g, '/');\n }\n\n function getClassPath(moduleName: string, className: string) {\n return path\n .join(\n `${ROUTE_PREFIX}/classes`,\n `${transformModuleName(moduleName)}.${className}`,\n )\n .replace(/\\\\/g, '/');\n }\n\n function getInterfacePath(moduleName: string, interfaceName: string) {\n return path\n .join(\n `${ROUTE_PREFIX}/interfaces`,\n `${transformModuleName(moduleName)}.${interfaceName}`,\n )\n .replace(/\\\\/g, '/');\n }\n\n function getFunctionPath(moduleName: string, functionName: string) {\n return path\n .join(\n `${ROUTE_PREFIX}/functions`,\n `${transformModuleName(moduleName)}.${functionName}`,\n )\n .replace(/\\\\/g, '/');\n }\n\n data.children.forEach((module: ModuleItem) => {\n const moduleNames = module.name.split('/');\n const name = moduleNames[moduleNames.length - 1];\n const moduleConfig = {\n text: `Module:${name}`,\n items: [{ text: 'Overview', link: getModulePath(module.name) }],\n };\n if (!module.children || module.children.length <= 0) {\n return;\n }\n module.children.forEach(sub => {\n const kindString = module.groups\n .find(item => item.children.includes(sub.id))\n ?.title.slice(0, -1);\n if (!kindString) {\n return;\n }\n switch (kindString) {\n case 'Class':\n moduleConfig.items.push({\n text: `Class:${sub.name}`,\n link: getClassPath(module.name, sub.name),\n });\n break;\n case 'Interface':\n moduleConfig.items.push({\n text: `Interface:${sub.name}`,\n link: getInterfacePath(module.name, sub.name),\n });\n break;\n case 'Function':\n moduleConfig.items.push({\n text: `Function:${sub.name}`,\n link: getFunctionPath(module.name, sub.name),\n });\n break;\n default:\n break;\n }\n });\n result.push(moduleConfig);\n });\n await patchLinks(path.dirname(jsonFile));\n return result;\n}\n","export function transformModuleName(name: string) {\n return name.replace(/\\//g, '_').replace(/-/g, '_');\n}\n"]}
@@ -1,17 +0,0 @@
1
- import { RspressPlugin } from '@rspress/shared';
2
-
3
- interface PluginTypeDocOptions {
4
- /**
5
- * The entry points of modules.
6
- * @default []
7
- */
8
- entryPoints: string[];
9
- /**
10
- * The output directory.
11
- * @default 'api'
12
- */
13
- outDir?: string;
14
- }
15
- declare function pluginTypeDoc(options: PluginTypeDocOptions): RspressPlugin;
16
-
17
- export { type PluginTypeDocOptions, pluginTypeDoc };
@@ -1 +0,0 @@
1
- {"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,oBAAiB;AACjB,qBAA4C;AAE5C,qCAAqB;;;ACHd,IAAM,UAAU;AAChB,IAAM,eAAe,IAAI,OAAO;;;ACDvC,uBAAiB;AACjB,sBAAe;;;ACDR,SAAS,oBAAoB,MAAc;AAChD,SAAO,KAAK,QAAQ,OAAO,GAAG,EAAE,QAAQ,MAAM,GAAG;AACnD;;;ADiBA,SAAe,WAAW,WAAmB;AAAA;AAI3C,UAAM,sBAAsB,CAAO,aAAqB;AACtD,YAAM,UAAU,MAAM,gBAAAC,QAAG,SAAS,UAAU,OAAO;AAEnD,YAAM,aAAa,QAAQ;AAAA,QACzB;AAAA,QACA,CAAC,QAAQ,IAAI,OAAO;AAClB,iBAAO,IAAI,EAAE,OAAO,EAAE;AAAA,QACxB;AAAA,MACF;AACA,YAAM,gBAAAA,QAAG,UAAU,UAAU,UAAU;AAAA,IACzC;AAEA,UAAM,WAAW,CAAO,QAAgB;AACtC,YAAM,QAAQ,M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AAAA,UACH;AAEA,iBAAO,YAAY,UAAU,OAAO,YAAY,WAAW,CAAC;AAC5D,iBAAO,YAAY,QAAQ,YAAY,IACrC,YAAY,SAAS,IACjB,MAAM,4BAA4B,OAAO,IACzC,MAAM,6BAA6B,OAAO;AAChD,iBAAO,YAAY,QAAQ,YAAY,EAAE,QAAQ;AAAA,YAC/C,MAAM;AAAA,YACN,MAAM,GAAG,YAAY;AAAA,UACvB,CAAC;AAAA,QACH;AACA,eAAO,QAAQ,OAAO,SAAS,CAAC;AAChC,eAAO,MAAM,UAAU,OAAO,MAAM,WAAW,CAAC;AAChD,eAAO;AAAA,MACT;AAAA;AAAA,EACF;AACF","names":["import_node_path","fs","path","module"],"ignoreList":[],"sources":["../../src/index.ts","../../src/constants.ts","../../src/sidebar.ts","../../src/utils.ts"],"sourcesContent":["import path from 'node:path';\nimport { Application, TSConfigReader } from 'typedoc';\nimport type { RspressPlugin } from '@rspress/shared';\nimport { load } from 'typedoc-plugin-markdown';\nimport { API_DIR } from './constants';\nimport {\n resolveSidebarForMultiEntry,\n resolveSidebarForSingleEntry,\n} from './sidebar';\n\nexport interface PluginTypeDocOptions {\n /**\n * The entry points of modules.\n * @default []\n */\n entryPoints: string[];\n /**\n * The output directory.\n * @default 'api'\n */\n outDir?: string;\n}\n\nexport function pluginTypeDoc(options: PluginTypeDocOptions): RspressPlugin {\n let docRoot: string | undefined;\n const { entryPoints = [], outDir = API_DIR } = options;\n return {\n name: '@rspress/plugin-typedoc',\n async addPages() {\n return [\n {\n routePath: `${outDir.replace(/\\/$/, '')}/`,\n filepath: path.join(docRoot!, outDir, 'README.md'),\n },\n ];\n },\n async config(config) {\n const app = new Application();\n docRoot = config.root;\n app.options.addReader(new TSConfigReader());\n load(app);\n app.bootstrap({\n name: config.title,\n entryPoints,\n theme: 'markdown',\n disableSources: true,\n readme: 'none',\n githubPages: false,\n requiredToBeDocumented: ['Class', 'Function', 'Interface'],\n plugin: ['typedoc-plugin-markdown'],\n // @ts-expect-error MarkdownTheme has no export\n hideBreadcrumbs: true,\n hideMembersSymbol: true,\n allReflectionsHaveOwnDocument: true,\n });\n const project = app.convert();\n\n if (project) {\n // 1. Generate module doc by typedoc\n const absoluteOutputdir = path.join(docRoot!, outDir);\n await app.generateDocs(project, absoluteOutputdir);\n const jsonDir = path.join(absoluteOutputdir, 'documentation.json');\n await app.generateJson(project, jsonDir);\n // 2. Generate sidebar\n config.themeConfig = config.themeConfig || {};\n config.themeConfig.nav = config.themeConfig.nav || [];\n const apiIndexLink = `/${outDir.replace(/(^\\/)|(\\/$)/, '')}/`;\n const { nav } = config.themeConfig;\n // Note: TypeDoc does not support i18n\n if (Array.isArray(nav)) {\n nav.push({\n text: 'API',\n link: apiIndexLink,\n });\n } else if ('default' in nav) {\n nav.default.push({\n text: 'API',\n link: apiIndexLink,\n });\n }\n\n config.themeConfig.sidebar = config.themeConfig.sidebar || {};\n config.themeConfig.sidebar[apiIndexLink] =\n entryPoints.length > 1\n ? await resolveSidebarForMultiEntry(jsonDir)\n : await resolveSidebarForSingleEntry(jsonDir);\n config.themeConfig.sidebar[apiIndexLink].unshift({\n text: 'Overview',\n link: `${apiIndexLink}README`,\n });\n }\n config.route = config.route || {};\n config.route.exclude = config.route.exclude || [];\n return config;\n },\n };\n}\n","export const API_DIR = 'api';\nexport const ROUTE_PREFIX = `/${API_DIR}`;\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport type { SidebarGroup } from '@rspress/shared';\nimport { transformModuleName } from './utils';\nimport { ROUTE_PREFIX } from './constants';\n\ninterface ModuleItem {\n id: number;\n name: string;\n children: {\n id: number;\n name: string;\n }[];\n groups: {\n title: string;\n children: number[];\n }[];\n}\n\nasync function patchLinks(outputDir: string) {\n // Patch links in markdown files\n // Scan all the markdown files in the output directory\n // replace [foo](bar) -> [foo](./bar)\n const normlizeLinksInFile = async (filePath: string) => {\n const content = await fs.readFile(filePath, 'utf-8');\n // replace: [foo](bar) -> [foo](./bar)\n const newContent = content.replace(\n /\\[([^\\]]+)\\]\\(([^)]+)\\)/g,\n (_match, p1, p2) => {\n return `[${p1}](./${p2})`;\n },\n );\n await fs.writeFile(filePath, newContent);\n };\n\n const traverse = async (dir: string) => {\n const files = await fs.readdir(dir);\n for (const file of files) {\n const filePath = path.join(dir, file);\n const stat = await fs.stat(filePath);\n if (stat.isDirectory()) {\n await traverse(filePath);\n } else if (stat.isFile() && /\\.mdx?/.test(file)) {\n await normlizeLinksInFile(filePath);\n }\n }\n };\n await traverse(outputDir);\n}\n\nexport async function resolveSidebarForSingleEntry(\n jsonFile: string,\n): Promise<SidebarGroup[]> {\n const result: SidebarGroup[] = [];\n const data = JSON.parse(await fs.readFile(jsonFile, 'utf-8'));\n if (!data.children || data.children.length <= 0) {\n return [];\n }\n const symbolMap = new Map<string, number>();\n data.groups.forEach((group: { title: string; children: number[] }) => {\n const groupItem: SidebarGroup = {\n text: group.title,\n items: [],\n };\n group.children.forEach((id: number) => {\n const dataItem = data.children.find((item: ModuleItem) => item.id === id);\n if (dataItem) {\n // Note: we should handle the case that classes and interfaces have the same name\n // Such as class `Env` and variable `env`\n // The final output file name should be `classes/Env.md` and `variables/env-1.md`\n let fileName = dataItem.name;\n if (symbolMap.has(dataItem.name)) {\n const count = symbolMap.get(dataItem.name)! + 1;\n symbolMap.set(dataItem.name, count);\n fileName = `${dataItem.name}-${count}`;\n } else {\n symbolMap.set(dataItem.name.toLocaleLowerCase(), 0);\n }\n groupItem.items.push({\n text: dataItem.name,\n link: `${ROUTE_PREFIX}/${group.title.toLocaleLowerCase()}/${fileName}`,\n });\n }\n });\n result.push(groupItem);\n });\n\n await patchLinks(path.dirname(jsonFile));\n\n return result;\n}\n\nexport async function resolveSidebarForMultiEntry(\n jsonFile: string,\n): Promise<SidebarGroup[]> {\n const result: SidebarGroup[] = [];\n const data = JSON.parse(await fs.readFile(jsonFile, 'utf-8'));\n if (!data.children || data.children.length <= 0) {\n return result;\n }\n\n function getModulePath(name: string) {\n return path\n .join(`${ROUTE_PREFIX}/modules`, `${transformModuleName(name)}`)\n .replace(/\\\\/g, '/');\n }\n\n function getClassPath(moduleName: string, className: string) {\n return path\n .join(\n `${ROUTE_PREFIX}/classes`,\n `${transformModuleName(moduleName)}.${className}`,\n )\n .replace(/\\\\/g, '/');\n }\n\n function getInterfacePath(moduleName: string, interfaceName: string) {\n return path\n .join(\n `${ROUTE_PREFIX}/interfaces`,\n `${transformModuleName(moduleName)}.${interfaceName}`,\n )\n .replace(/\\\\/g, '/');\n }\n\n function getFunctionPath(moduleName: string, functionName: string) {\n return path\n .join(\n `${ROUTE_PREFIX}/functions`,\n `${transformModuleName(moduleName)}.${functionName}`,\n )\n .replace(/\\\\/g, '/');\n }\n\n data.children.forEach((module: ModuleItem) => {\n const moduleNames = module.name.split('/');\n const name = moduleNames[moduleNames.length - 1];\n const moduleConfig = {\n text: `Module:${name}`,\n items: [{ text: 'Overview', link: getModulePath(module.name) }],\n };\n if (!module.children || module.children.length <= 0) {\n return;\n }\n module.children.forEach(sub => {\n const kindString = module.groups\n .find(item => item.children.includes(sub.id))\n ?.title.slice(0, -1);\n if (!kindString) {\n return;\n }\n switch (kindString) {\n case 'Class':\n moduleConfig.items.push({\n text: `Class:${sub.name}`,\n link: getClassPath(module.name, sub.name),\n });\n break;\n case 'Interface':\n moduleConfig.items.push({\n text: `Interface:${sub.name}`,\n link: getInterfacePath(module.name, sub.name),\n });\n break;\n case 'Function':\n moduleConfig.items.push({\n text: `Function:${sub.name}`,\n link: getFunctionPath(module.name, sub.name),\n });\n break;\n default:\n break;\n }\n });\n result.push(moduleConfig);\n });\n await patchLinks(path.dirname(jsonFile));\n return result;\n}\n","export function transformModuleName(name: string) {\n return name.replace(/\\//g, '_').replace(/-/g, '_');\n}\n"]}