@rspress/core 2.0.0-beta.18 → 2.0.0-beta.19

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/dist/index.d.ts CHANGED
@@ -123,9 +123,10 @@ declare class PluginDriver {
123
123
  */
124
124
  export declare const remarkPluginNormalizeLink: Plugin_2<[
125
125
  {
126
- root: string;
127
126
  cleanUrls: boolean | string;
128
- routeService?: RouteService;
127
+ routeService: RouteService | null;
128
+ checkDeadLinks?: boolean;
129
+ __base?: string;
129
130
  }
130
131
  ], Root>;
131
132
 
@@ -159,9 +160,12 @@ declare type RootContent = RootContentMap[keyof RootContentMap];
159
160
  declare interface RootData extends Data {}
160
161
 
161
162
  declare class RoutePage {
163
+ #private;
162
164
  routeMeta: RouteMeta;
163
- static create(routeMeta: RouteMeta): RoutePage;
164
- constructor(routeMeta: RouteMeta);
165
+ static create(absolutePath: string, docsDir: string): RoutePage;
166
+ static createFromExternal(routePath: string, filepath: string, docDir: string): RoutePage;
167
+ private constructor();
168
+ static generateRouteMeta(routePath: string, filepath: string, docDir: string): RouteMeta;
165
169
  }
166
170
 
167
171
  export declare class RouteService {
@@ -170,21 +174,23 @@ export declare class RouteService {
170
174
  static __instance__: RouteService | null;
171
175
  static getInstance(): RouteService;
172
176
  static create(options: InitOptions): Promise<RouteService>;
173
- constructor(scanDir: string, userConfig: UserConfig, tempDir: string, pluginDriver: PluginDriver);
177
+ private constructor();
174
178
  get extensions(): readonly string[];
175
- addRoute(routeMeta: RouteMeta): Promise<void>;
176
- removeRoute(filePath: string): void;
179
+ addRoute(routePage: RoutePage): Promise<void>;
177
180
  getRoutes(): RouteMeta[];
178
181
  getRoutePages(): RoutePage[];
179
182
  isExistRoute(routePath: string): boolean;
180
183
  generateRoutesCode(): string;
181
184
  generateRoutesCodeByRouteMeta(routeMeta: RouteMeta[]): string;
182
- getRoutePathParts(routePath: string): readonly [string, string, string];
183
- normalizeRoutePath(routePath: string): {
185
+ getRoutePathParts(relativePath: string): readonly [string, string, string];
186
+ normalizeRoutePath(relativePath: string): {
187
+ pureRoutePath: string;
184
188
  routePath: string;
185
189
  lang: string;
186
190
  version: string;
187
191
  };
192
+ absolutePathToRoutePath(absolutePath: string): string;
193
+ absolutePathToRelativePath(absolutePath: string): string;
188
194
  getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
189
195
  }
190
196
 
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import __rslib_shim_module__ from 'module';
2
2
  const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(import.meta.url);
3
3
  import node_fs_promises, { mkdir, readFile, readdir, rm, stat as promises_stat, writeFile } from "node:fs/promises";
4
- import node_path, { dirname, extname as external_node_path_extname, join, relative } from "node:path";
4
+ import node_path, { dirname, extname, join, relative } from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
7
- import { APPEARANCE_KEY, MDX_OR_MD_REGEXP, RSPRESS_TEMP_DIR, SEARCH_INDEX_NAME, addLeadingSlash, addTrailingSlash, isDebugMode, isExternalUrl, isSCM, normalizeHref, normalizeSlash, parseUrl, removeLeadingSlash, removeTrailingSlash, slash } from "@rspress/shared";
7
+ import { APPEARANCE_KEY, MDX_OR_MD_REGEXP, RSPRESS_TEMP_DIR, SEARCH_INDEX_NAME, addLeadingSlash, addTrailingSlash, isDebugMode, isExternalUrl, isProduction, isSCM, normalizeHref, normalizeSlash, parseUrl, removeLeadingSlash, removeTrailingSlash, slash, withBase } from "@rspress/shared";
8
8
  import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
9
9
  import { logger } from "@rspress/shared/logger";
10
10
  import picocolors from "picocolors";
@@ -142,7 +142,7 @@ const pluginVirtualModule = (pluginOptions = {})=>({
142
142
  const TEMP_DIR = join(api.context.rootPath, 'node_modules', virtualFolderName);
143
143
  const virtualFileAbsolutePaths = Object.keys(virtualModules).map((i)=>{
144
144
  let absolutePath = join(TEMP_DIR, i);
145
- if (!external_node_path_extname(absolutePath)) absolutePath = `${absolutePath}.js`;
145
+ if (!extname(absolutePath)) absolutePath = `${absolutePath}.js`;
146
146
  return [
147
147
  i,
148
148
  absolutePath
@@ -239,9 +239,26 @@ function hintNavJsonChangeThenPanic(metaJson, metaJsonDir, docsDir) {
239
239
  process.exit(1);
240
240
  }
241
241
  }
242
- var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.18"}');
242
+ let isLogged = false;
243
+ function hintRelativeMarkdownLink() {
244
+ if (isLogged) return;
245
+ isLogged = true;
246
+ logger.info('[Rspress v2] Markdown links without "./" prefix are now relative links, e.g: [](guide/getting-started) is equal to [](./guide/getting-started). You can rewrite it to [](/guide/getting-started) to always use absolute links, or use [](./getting-started.md)');
247
+ }
248
+ function getPageKey(route) {
249
+ const cleanRoute = removeLeadingSlash(route);
250
+ return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
251
+ }
252
+ const isWindows = 'win32' === node_os.platform();
253
+ function normalizePath_slash(p) {
254
+ return p.replace(/\\/g, '/');
255
+ }
256
+ function normalizePath(id) {
257
+ return node_path.posix.normalize(isWindows ? normalizePath_slash(id) : id);
258
+ }
259
+ var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.19"}');
243
260
  const RSPRESS_VERSION = package_namespaceObject.i8;
244
- const isProduction = ()=>'production' === process.env.NODE_ENV;
261
+ const constants_isProduction = ()=>'production' === process.env.NODE_ENV;
245
262
  const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
246
263
  const inlineThemeScript = `{
247
264
  const saved = localStorage.getItem('${APPEARANCE_KEY}')
@@ -266,25 +283,12 @@ const PUBLIC_DIR = 'public';
266
283
  const constants_TEMP_DIR = node_path.join(process.cwd(), 'node_modules', RSPRESS_TEMP_DIR);
267
284
  const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
268
285
  const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
269
- function getPageKey(route) {
270
- const cleanRoute = removeLeadingSlash(route);
271
- return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
272
- }
273
- class RoutePage {
274
- routeMeta;
275
- static create(routeMeta) {
276
- return new RoutePage(routeMeta);
277
- }
278
- constructor(routeMeta){
279
- this.routeMeta = routeMeta;
280
- }
281
- }
282
- const getRoutePathParts = (routePath, lang, version, langs, versions)=>{
283
- const hasTrailSlash = routePath.endsWith('/');
286
+ const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
287
+ const hasTrailSlash = relativePath.endsWith('/');
284
288
  let versionPart = '';
285
289
  let langPart = '';
286
290
  let purePathPart = '';
287
- const parts = routePath.split('/').filter(Boolean);
291
+ const parts = relativePath.split('/').filter(Boolean);
288
292
  if (version) {
289
293
  const versionToMatch = parts[0];
290
294
  if (versions.includes(versionToMatch)) {
@@ -306,15 +310,22 @@ const getRoutePathParts = (routePath, lang, version, langs, versions)=>{
306
310
  hasTrailSlash ? addTrailingSlash(purePathPart) : purePathPart
307
311
  ];
308
312
  };
309
- const normalizeRoutePath = (routePath, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS)=>{
310
- const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
313
+ const normalizeRoutePath = (relativePath, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS)=>{
311
314
  const extensionsWithoutDot = extensions.map((i)=>i.slice(1));
312
315
  const cleanExtensionPattern = new RegExp(`\\.(${extensionsWithoutDot.join('|')})$`, 'i');
316
+ let routePath = relativePath.replace(cleanExtensionPattern, '').replace(/\.html$/, '');
317
+ const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
318
+ routePath = purePathPart.replace(/\/index$/, '/');
319
+ if ('index' === routePath) routePath = '';
313
320
  const normalizedRoutePath = addLeadingSlash([
314
- versionPart,
315
- langPart
316
- ].filter(Boolean).join('/') + addLeadingSlash(purePathPart)).replace(cleanExtensionPattern, '').replace(/\.html$/, '').replace(/\/index$/, '/');
321
+ ...[
322
+ versionPart,
323
+ langPart
324
+ ].filter(Boolean),
325
+ routePath
326
+ ].join('/'));
317
327
  return {
328
+ pureRoutePath: `/${routePath}`,
318
329
  routePath: normalizedRoutePath,
319
330
  lang: langPart || lang,
320
331
  version: versionPart || version
@@ -339,9 +350,9 @@ class RouteService {
339
350
  static async create(options) {
340
351
  const { scanDir, config, runtimeTempDir, pluginDriver } = options;
341
352
  const routeService = new RouteService(scanDir, config, runtimeTempDir, pluginDriver);
353
+ RouteService.__instance__ = routeService;
342
354
  await routeService.#init();
343
355
  await pluginDriver.routeServiceGenerated(routeService);
344
- RouteService.__instance__ = routeService;
345
356
  return routeService;
346
357
  }
347
358
  constructor(scanDir, userConfig, tempDir, pluginDriver){
@@ -380,46 +391,30 @@ class RouteService {
380
391
  ]
381
392
  })).sort();
382
393
  files.forEach((filePath)=>{
383
- const fileRelativePath = normalizePath(node_path.relative(this.#scanDir, filePath));
384
- const { routePath, lang, version } = this.normalizeRoutePath(fileRelativePath);
385
- const absolutePath = node_path.join(this.#scanDir, fileRelativePath);
386
- const routeMeta = {
387
- routePath,
388
- absolutePath: normalizePath(absolutePath),
389
- relativePath: fileRelativePath,
390
- pageName: getPageKey(fileRelativePath),
391
- lang,
392
- version
393
- };
394
- this.addRoute(routeMeta);
394
+ const routePage = RoutePage.create(filePath, this.#scanDir);
395
+ this.addRoute(routePage);
395
396
  });
396
397
  const externalPages = await this.#pluginDriver.addPages();
397
398
  await Promise.all(externalPages.map(async (route, index)=>{
398
399
  const { routePath, content, filepath } = route;
399
400
  if (filepath) {
400
- const routeMeta = this.#generateRouteMeta(routePath, filepath);
401
- this.addRoute(routeMeta);
401
+ const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
402
+ this.addRoute(routePage);
402
403
  return;
403
404
  }
404
405
  if (content) {
405
406
  const filepath = await this.#writeTempFile(index, content);
406
- const routeMeta = this.#generateRouteMeta(routePath, filepath);
407
- this.addRoute(routeMeta);
407
+ const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
408
+ this.addRoute(routePage);
408
409
  }
409
410
  }));
410
411
  await this.#pluginDriver.routeGenerated(this.getRoutes());
411
412
  }
412
- async addRoute(routeMeta) {
413
- const { routePath } = routeMeta;
413
+ async addRoute(routePage) {
414
+ const { routeMeta: { routePath } } = routePage;
414
415
  if (this.routeData.has(routePath)) throw new Error(`routePath ${routePath} has already been added`);
415
- const routePage = RoutePage.create(routeMeta);
416
416
  this.routeData.set(routePath, routePage);
417
417
  }
418
- removeRoute(filePath) {
419
- const fileRelativePath = node_path.relative(this.#scanDir, filePath);
420
- const { routePath } = this.normalizeRoutePath(fileRelativePath);
421
- this.routeData.delete(routePath);
422
- }
423
418
  getRoutes() {
424
419
  return Array.from(this.routeData.values()).map((i)=>i.routeMeta);
425
420
  }
@@ -427,8 +422,7 @@ class RouteService {
427
422
  return Array.from(this.routeData.values());
428
423
  }
429
424
  isExistRoute(routePath) {
430
- const { routePath: normalizedRoute } = this.normalizeRoutePath(routePath);
431
- return Boolean(this.routeData.get(normalizedRoute));
425
+ return this.routeData.has(routePath);
432
426
  }
433
427
  generateRoutesCode() {
434
428
  return this.generateRoutesCodeByRouteMeta(this.getRoutes());
@@ -450,43 +444,72 @@ ${routeMeta.map((route, index)=>{
450
444
  ];
451
445
  `;
452
446
  }
453
- getRoutePathParts(routePath) {
454
- return getRoutePathParts(routePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
447
+ getRoutePathParts(relativePath) {
448
+ return getRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
449
+ }
450
+ normalizeRoutePath(relativePath) {
451
+ return normalizeRoutePath(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
455
452
  }
456
- normalizeRoutePath(routePath) {
457
- return normalizeRoutePath(routePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
453
+ absolutePathToRoutePath(absolutePath) {
454
+ return absolutePathToRoutePath(absolutePath, this.#scanDir, this);
455
+ }
456
+ absolutePathToRelativePath(absolutePath) {
457
+ return absolutePathToRelativePath(absolutePath, this.#scanDir);
458
458
  }
459
459
  async #writeTempFile(index, content) {
460
460
  const tempFilePath = node_path.join(this.#tempDir, `temp-${index}.mdx`);
461
461
  await node_fs_promises.writeFile(tempFilePath, content);
462
462
  return tempFilePath;
463
463
  }
464
- #generateRouteMeta(routePath, filepath) {
465
- const { routePath: normalizedPath, lang, version } = this.normalizeRoutePath(routePath);
464
+ getRoutePageByRoutePath(routePath) {
465
+ return this.routeData.get(routePath);
466
+ }
467
+ }
468
+ class RoutePage {
469
+ routeMeta;
470
+ #docDir;
471
+ static create(absolutePath, docsDir) {
472
+ const routeMeta = absolutePathToRouteMeta(absolutePath, docsDir, RouteService.getInstance());
473
+ return new RoutePage(routeMeta, docsDir);
474
+ }
475
+ static createFromExternal(routePath, filepath, docDir) {
476
+ const routeMeta = RoutePage.generateRouteMeta(routePath, filepath, docDir);
477
+ return new RoutePage(routeMeta, node_path.dirname(filepath));
478
+ }
479
+ constructor(routeMeta, docDir){
480
+ this.routeMeta = routeMeta;
481
+ this.#docDir = docDir;
482
+ }
483
+ static generateRouteMeta(routePath, filepath, docDir) {
484
+ const routeService = RouteService.getInstance();
485
+ const { routePath: normalizedPath, lang, version } = routeService.normalizeRoutePath(routePath);
466
486
  return {
467
487
  routePath: normalizedPath,
468
488
  absolutePath: normalizePath(filepath),
469
- relativePath: normalizePath(node_path.relative(this.#scanDir, filepath)),
489
+ relativePath: absolutePathToRelativePath(filepath, docDir),
470
490
  pageName: getPageKey(routePath),
471
491
  lang,
472
492
  version
473
493
  };
474
494
  }
475
- getRoutePageByRoutePath(routePath) {
476
- return this.routeData.get(routePath);
477
- }
478
495
  }
479
- const isWindows = 'win32' === node_os.platform();
480
- function normalizePath_slash(p) {
481
- return p.replace(/\\/g, '/');
496
+ function absolutePathToRelativePath(absolutePath, docsDir) {
497
+ return normalizePath_slash(node_path.relative(docsDir, absolutePath));
482
498
  }
483
- function normalizePath(id) {
484
- return node_path.posix.normalize(isWindows ? normalizePath_slash(id) : id);
499
+ function absolutePathToRouteMeta(absolutePath, docsDir, routeService = RouteService.getInstance()) {
500
+ const relativePath = absolutePathToRelativePath(absolutePath, docsDir);
501
+ const { lang, routePath, version } = routeService.normalizeRoutePath(relativePath);
502
+ return {
503
+ pageName: getPageKey(relativePath),
504
+ absolutePath,
505
+ lang,
506
+ version,
507
+ routePath,
508
+ relativePath
509
+ };
485
510
  }
486
- function absolutePathToLink(absolutePath, docsDir) {
487
- const relativePath = normalizePath_slash(node_path.relative(docsDir, absolutePath.replace(node_path.extname(absolutePath), '')));
488
- const routeService = RouteService.getInstance();
489
- return routeService.normalizeRoutePath(relativePath).routePath;
511
+ function absolutePathToRoutePath(absolutePath, docsDir, routeService = RouteService.getInstance()) {
512
+ return absolutePathToRouteMeta(absolutePath, docsDir, routeService).routePath;
490
513
  }
491
514
  function absolutePathToRoutePrefix(absolutePath, docsDir) {
492
515
  const relativePath = normalizePath_slash(node_path.relative(docsDir, absolutePath.replace(node_path.extname(absolutePath), '')));
@@ -523,7 +546,7 @@ async function extractInfoFromFrontmatterWithAbsolutePath(absolutePath, rootDir)
523
546
  };
524
547
  }
525
548
  function getHmrFileKey(realPath, docsDir) {
526
- return realPath ? slash(relative(docsDir, realPath).replace(external_node_path_extname(realPath), '')) : '';
549
+ return realPath ? slash(relative(docsDir, realPath).replace(extname(realPath), '')) : '';
527
550
  }
528
551
  async function fsDirToMetaItems(workDir, extensions) {
529
552
  let subItems = await readdir(workDir);
@@ -586,7 +609,7 @@ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isF
586
609
  } catch (e) {
587
610
  logger.debug(e);
588
611
  const isIndexInMetaJsonIndex = dirMetaJson.find((i)=>{
589
- if ('string' == typeof i) return 'index' === i.replace(external_node_path_extname(i), '');
612
+ if ('string' == typeof i) return 'index' === i.replace(extname(i), '');
590
613
  return false;
591
614
  });
592
615
  const isIndexFileExists = await utils_pathExists(join(dirAbsolutePath, 'index.mdx')) || await utils_pathExists(join(dirAbsolutePath, 'index.md'));
@@ -623,7 +646,7 @@ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isF
623
646
  throw new Error(`Unknown meta item type: ${metaItem.type}, please check it in "${join(workDir, '_meta.json')}".`);
624
647
  }
625
648
  async function detectFilePath(absolutePath, extensions) {
626
- const ext = external_node_path_extname(absolutePath);
649
+ const ext = extname(absolutePath);
627
650
  if (ext && extensions.includes(ext)) return absolutePath;
628
651
  for (const extension of extensions){
629
652
  const realPath = absolutePath + extension;
@@ -646,7 +669,7 @@ async function metaFileItemToSidebarItem(metaItemRaw, workDir, docsDir, extensio
646
669
  } catch {
647
670
  throw new Error(`The file "${absolutePath}" does not exist, please check it in "${join(workDir, '_meta.json')}".`);
648
671
  }
649
- const link = absolutePathToLink(absolutePathWithExt, docsDir);
672
+ const link = absolutePathToRoutePath(absolutePathWithExt, docsDir);
650
673
  const info = await extractInfoFromFrontmatterWithAbsolutePath(absolutePathWithExt, docsDir);
651
674
  const title = label || info.title;
652
675
  return {
@@ -1188,7 +1211,7 @@ async function siteDataVMPlugin(context) {
1188
1211
  },
1189
1212
  pages: pages.map((page)=>{
1190
1213
  const { content, domain, _filepath, _html, _flattenContent, ...rest } = page;
1191
- return isProduction() ? rest : {
1214
+ return constants_isProduction() ? rest : {
1192
1215
  ...rest,
1193
1216
  _filepath
1194
1217
  };
@@ -1312,7 +1335,7 @@ async function writeSearchIndex(config) {
1312
1335
  await node_fs_promises.rename(source, target);
1313
1336
  scanning = true;
1314
1337
  }
1315
- if (isProduction() && isSCM() && config?.search?.mode === 'remote') {
1338
+ if (constants_isProduction() && isSCM() && config?.search?.mode === 'remote') {
1316
1339
  const { apiUrl, indexName } = config.search;
1317
1340
  try {
1318
1341
  await fetch(`${apiUrl}?index=${indexName}`, {
@@ -1730,7 +1753,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1730
1753
  const outDir = config?.outDir ?? OUTPUT_DIR;
1731
1754
  const DEFAULT_THEME = require.resolve('@rspress/theme-default');
1732
1755
  const base = config?.base ?? '';
1733
- const assetPrefix = isProduction() ? removeTrailingSlash(config?.builderConfig?.output?.assetPrefix ?? base) : '';
1756
+ const assetPrefix = constants_isProduction() ? removeTrailingSlash(config?.builderConfig?.output?.assetPrefix ?? base) : '';
1734
1757
  const reactVersion = await detectReactVersion();
1735
1758
  const normalizeIcon = (icon)=>{
1736
1759
  if (!icon) return;
@@ -1779,7 +1802,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1779
1802
  ] : []
1780
1803
  ],
1781
1804
  server: {
1782
- port: !isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
1805
+ port: !constants_isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
1783
1806
  publicDir: {
1784
1807
  name: node_path.join(userDocRoot, PUBLIC_DIR)
1785
1808
  },
@@ -1897,7 +1920,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1897
1920
  },
1898
1921
  source: {
1899
1922
  entry: {
1900
- index: enableSSG && isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
1923
+ index: enableSSG && constants_isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
1901
1924
  },
1902
1925
  preEntry: [
1903
1926
  node_path.join(DEFAULT_THEME, '../styles/index.js'),
@@ -2140,45 +2163,71 @@ const getASTNodeImport = (name, from)=>({
2140
2163
  }
2141
2164
  }
2142
2165
  });
2143
- function normalizeLink(nodeUrl, routeService, relativePath, cleanUrls) {
2166
+ function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
2167
+ const errorInfos = [];
2168
+ let possibleBreakingChange = false;
2169
+ [
2170
+ ...internalLinks.entries()
2171
+ ].forEach(([nodeUrl, link])=>{
2172
+ const cleanLinkPath = linkToRoutePath(link);
2173
+ if (!cleanLinkPath) return;
2174
+ if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
2175
+ if (!routeService.isExistRoute(removeTrailingSlash(cleanLinkPath)) && !routeService.isExistRoute(addTrailingSlash(cleanLinkPath))) errorInfos.push([
2176
+ nodeUrl,
2177
+ link
2178
+ ]);
2179
+ });
2180
+ if (errorInfos.length > 0) {
2181
+ if (possibleBreakingChange) hintRelativeMarkdownLink();
2182
+ logger.error(`Dead links found in ${picocolors.cyan(filePath)}:
2183
+ ${errorInfos.map(([nodeUrl, link])=>` ${picocolors.green(`"[..](${nodeUrl})"`)} ${picocolors.gray(link)}`).join('\n')}`);
2184
+ if (isProduction()) throw new Error('Dead link found');
2185
+ }
2186
+ }
2187
+ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks, __base) {
2144
2188
  if (!nodeUrl) return '';
2145
- if (nodeUrl.startsWith('#')) return `#${nodeUrl.slice(1)}`;
2189
+ if (nodeUrl.startsWith('#')) return nodeUrl;
2146
2190
  let { url, hash } = parseUrl(nodeUrl);
2147
2191
  if (isExternalUrl(url)) return url + (hash ? `#${hash}` : '');
2148
- const extname = node_path.extname(url);
2149
- if ((routeService?.extensions ?? DEFAULT_PAGE_EXTENSIONS).includes(extname)) url = url.replace(new RegExp(`\\${extname}$`), '');
2150
- if (url.startsWith('.')) url = node_path.posix.join(slash(node_path.dirname(relativePath)), url);
2151
- else if (routeService) {
2152
- const [pathVersion, pathLang] = routeService.getRoutePathParts(slash(relativePath));
2153
- const [urlVersion, urlLang, urlPath] = routeService.getRoutePathParts(url);
2154
- url = addLeadingSlash(urlPath);
2155
- if (pathLang && urlLang !== pathLang) url = `/${pathLang}${url}`;
2156
- if (pathVersion && urlVersion !== pathVersion) url = `/${pathVersion}${url}`;
2192
+ if (!routeService) return nodeUrl;
2193
+ if (url.startsWith('/')) {
2194
+ const { routePath } = routeService.normalizeRoutePath(url);
2195
+ url = routePath;
2196
+ } else {
2197
+ const anotherFileAbsolutePath = node_path.join(node_path.dirname(filePath), url);
2198
+ url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
2157
2199
  }
2158
2200
  if ('boolean' == typeof cleanUrls) url = normalizeHref(url, cleanUrls);
2159
2201
  else {
2160
2202
  url = normalizeHref(url, false);
2161
2203
  url = url.replace(/\.html$/, cleanUrls);
2162
2204
  }
2205
+ internalLinks.set(nodeUrl, url);
2163
2206
  if (hash) url += `#${hash}`;
2207
+ if (__base) url = withBase(url, __base);
2164
2208
  return url;
2165
2209
  }
2210
+ function linkToRoutePath(routePath) {
2211
+ return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
2212
+ }
2166
2213
  const normalizeImageUrl = (imageUrl)=>{
2167
2214
  if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) return '';
2168
2215
  return imageUrl;
2169
2216
  };
2170
- const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, file)=>{
2171
- const images = [];
2217
+ const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: shouldCheckDeadLinks = false, __base })=>(tree, file)=>{
2218
+ const internalLinks = new Map();
2172
2219
  visit(tree, 'link', (node)=>{
2173
2220
  const { url: nodeUrl } = node;
2174
- const relativePath = node_path.relative(root, file.path);
2175
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
2221
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
2222
+ node.url = link;
2176
2223
  });
2177
2224
  visit(tree, 'definition', (node)=>{
2178
2225
  const { url: nodeUrl } = node;
2179
- const relativePath = node_path.relative(root, file.path);
2180
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
2226
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
2227
+ node.url = link;
2181
2228
  });
2229
+ if (shouldCheckDeadLinks && routeService) normalizeLink_checkDeadLinks(internalLinks, file.path, routeService);
2230
+ const images = [];
2182
2231
  const getMdxSrcAttribute = (tempVar)=>({
2183
2232
  type: 'mdxJsxAttribute',
2184
2233
  name: 'src',
package/dist/loader.d.ts CHANGED
@@ -53,9 +53,12 @@ declare class PluginDriver {
53
53
  }
54
54
 
55
55
  declare class RoutePage {
56
+ #private;
56
57
  routeMeta: RouteMeta;
57
- static create(routeMeta: RouteMeta): RoutePage;
58
- constructor(routeMeta: RouteMeta);
58
+ static create(absolutePath: string, docsDir: string): RoutePage;
59
+ static createFromExternal(routePath: string, filepath: string, docDir: string): RoutePage;
60
+ private constructor();
61
+ static generateRouteMeta(routePath: string, filepath: string, docDir: string): RouteMeta;
59
62
  }
60
63
 
61
64
  declare class RouteService {
@@ -64,21 +67,23 @@ declare class RouteService {
64
67
  static __instance__: RouteService | null;
65
68
  static getInstance(): RouteService;
66
69
  static create(options: InitOptions): Promise<RouteService>;
67
- constructor(scanDir: string, userConfig: UserConfig, tempDir: string, pluginDriver: PluginDriver);
70
+ private constructor();
68
71
  get extensions(): readonly string[];
69
- addRoute(routeMeta: RouteMeta): Promise<void>;
70
- removeRoute(filePath: string): void;
72
+ addRoute(routePage: RoutePage): Promise<void>;
71
73
  getRoutes(): RouteMeta[];
72
74
  getRoutePages(): RoutePage[];
73
75
  isExistRoute(routePath: string): boolean;
74
76
  generateRoutesCode(): string;
75
77
  generateRoutesCodeByRouteMeta(routeMeta: RouteMeta[]): string;
76
- getRoutePathParts(routePath: string): readonly [string, string, string];
77
- normalizeRoutePath(routePath: string): {
78
+ getRoutePathParts(relativePath: string): readonly [string, string, string];
79
+ normalizeRoutePath(relativePath: string): {
80
+ pureRoutePath: string;
78
81
  routePath: string;
79
82
  lang: string;
80
83
  version: string;
81
84
  };
85
+ absolutePathToRoutePath(absolutePath: string): string;
86
+ absolutePathToRelativePath(absolutePath: string): string;
82
87
  getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
83
88
  }
84
89
 
@@ -55,9 +55,12 @@ declare class PluginDriver {
55
55
  }
56
56
 
57
57
  declare class RoutePage {
58
+ #private;
58
59
  routeMeta: RouteMeta;
59
- static create(routeMeta: RouteMeta): RoutePage;
60
- constructor(routeMeta: RouteMeta);
60
+ static create(absolutePath: string, docsDir: string): RoutePage;
61
+ static createFromExternal(routePath: string, filepath: string, docDir: string): RoutePage;
62
+ private constructor();
63
+ static generateRouteMeta(routePath: string, filepath: string, docDir: string): RouteMeta;
61
64
  }
62
65
 
63
66
  declare class RouteService {
@@ -66,21 +69,23 @@ declare class RouteService {
66
69
  static __instance__: RouteService | null;
67
70
  static getInstance(): RouteService;
68
71
  static create(options: InitOptions): Promise<RouteService>;
69
- constructor(scanDir: string, userConfig: UserConfig, tempDir: string, pluginDriver: PluginDriver);
72
+ private constructor();
70
73
  get extensions(): readonly string[];
71
- addRoute(routeMeta: RouteMeta): Promise<void>;
72
- removeRoute(filePath: string): void;
74
+ addRoute(routePage: RoutePage): Promise<void>;
73
75
  getRoutes(): RouteMeta[];
74
76
  getRoutePages(): RoutePage[];
75
77
  isExistRoute(routePath: string): boolean;
76
78
  generateRoutesCode(): string;
77
79
  generateRoutesCodeByRouteMeta(routeMeta: RouteMeta[]): string;
78
- getRoutePathParts(routePath: string): readonly [string, string, string];
79
- normalizeRoutePath(routePath: string): {
80
+ getRoutePathParts(relativePath: string): readonly [string, string, string];
81
+ normalizeRoutePath(relativePath: string): {
82
+ pureRoutePath: string;
80
83
  routePath: string;
81
84
  lang: string;
82
85
  version: string;
83
86
  };
87
+ absolutePathToRoutePath(absolutePath: string): string;
88
+ absolutePathToRelativePath(absolutePath: string): string;
84
89
  getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
85
90
  }
86
91
 
package/dist/processor.js CHANGED
@@ -10,9 +10,10 @@ import remark_gfm from "remark-gfm";
10
10
  import github_slugger from "github-slugger";
11
11
  import { headingRank } from "hast-util-heading-rank";
12
12
  import { visit } from "unist-util-visit";
13
- import { addLeadingSlash, cleanUrl, isExternalUrl, isProduction, normalizeHref, parseUrl, slash as shared_slash } from "@rspress/shared";
14
- import { logger } from "@rspress/shared/logger";
15
- import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
13
+ import { addTrailingSlash, isExternalUrl, isProduction, normalizeHref, parseUrl, removeTrailingSlash, withBase } from "@rspress/shared";
14
+ import { logger as logger_logger } from "@rspress/shared/logger";
15
+ import picocolors_0 from "picocolors";
16
+ import "node:fs/promises";
16
17
  import { visitChildren } from "unist-util-visit-children";
17
18
  import rehype from "@shikijs/rehype";
18
19
  import { createCssVariablesTheme } from "shiki";
@@ -118,74 +119,77 @@ const remarkBuiltin = ({ globalComponents })=>(tree)=>{
118
119
  });
119
120
  tree.children.unshift(...demos);
120
121
  };
121
- const IGNORE_REGEXP = /^(https?|mailto|tel|#)/;
122
- function checkLinks(links, filepath, root, routeService) {
122
+ let isLogged = false;
123
+ function hintRelativeMarkdownLink() {
124
+ if (isLogged) return;
125
+ isLogged = true;
126
+ logger_logger.info('[Rspress v2] Markdown links without "./" prefix are now relative links, e.g: [](guide/getting-started) is equal to [](./guide/getting-started). You can rewrite it to [](/guide/getting-started) to always use absolute links, or use [](./getting-started.md)');
127
+ }
128
+ function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
123
129
  const errorInfos = [];
124
- links.filter((link)=>!IGNORE_REGEXP.test(link)).map((link)=>normalizePath(link)).forEach((link)=>{
125
- const relativePath = node_path.relative(root, filepath);
126
- if (!routeService.isExistRoute(cleanUrl(link))) errorInfos.push(`Internal link to "${link}" is dead, check it in "${relativePath}"`);
130
+ let possibleBreakingChange = false;
131
+ [
132
+ ...internalLinks.entries()
133
+ ].forEach(([nodeUrl, link])=>{
134
+ const cleanLinkPath = linkToRoutePath(link);
135
+ if (!cleanLinkPath) return;
136
+ if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
137
+ if (!routeService.isExistRoute(removeTrailingSlash(cleanLinkPath)) && !routeService.isExistRoute(addTrailingSlash(cleanLinkPath))) errorInfos.push([
138
+ nodeUrl,
139
+ link
140
+ ]);
127
141
  });
128
142
  if (errorInfos.length > 0) {
129
- errorInfos?.forEach((err)=>{
130
- logger.error(err);
131
- });
143
+ if (possibleBreakingChange) hintRelativeMarkdownLink();
144
+ logger_logger.error(`Dead links found in ${picocolors_0.cyan(filePath)}:
145
+ ${errorInfos.map(([nodeUrl, link])=>` ${picocolors_0.green(`"[..](${nodeUrl})"`)} ${picocolors_0.gray(link)}`).join('\n')}`);
132
146
  if (isProduction()) throw new Error('Dead link found');
133
147
  }
134
148
  }
135
- const remarkCheckDeadLinks = (checkLink)=>{
136
- const { root, routeService } = checkLink;
137
- return (tree, vfile)=>{
138
- const internalLinks = new Set();
139
- visit(tree, 'link', ({ url })=>{
140
- if (!url) return;
141
- if (internalLinks.has(url)) return;
142
- if (!url.startsWith('http://') && !url.startsWith('https://')) {
143
- const { routePath: normalizeUrl } = routeService.normalizeRoutePath(url.split(node_path.sep).join('/')?.split('#')[0]);
144
- internalLinks.add(normalizeUrl);
145
- }
146
- });
147
- checkLinks(Array.from(internalLinks), vfile.path, root, routeService);
148
- };
149
- };
150
- function normalizeLink(nodeUrl, routeService, relativePath, cleanUrls) {
149
+ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks, __base) {
151
150
  if (!nodeUrl) return '';
152
- if (nodeUrl.startsWith('#')) return `#${nodeUrl.slice(1)}`;
151
+ if (nodeUrl.startsWith('#')) return nodeUrl;
153
152
  let { url, hash } = parseUrl(nodeUrl);
154
153
  if (isExternalUrl(url)) return url + (hash ? `#${hash}` : '');
155
- const extname = node_path.extname(url);
156
- if ((routeService?.extensions ?? DEFAULT_PAGE_EXTENSIONS).includes(extname)) url = url.replace(new RegExp(`\\${extname}$`), '');
157
- if (url.startsWith('.')) url = node_path.posix.join(shared_slash(node_path.dirname(relativePath)), url);
158
- else if (routeService) {
159
- const [pathVersion, pathLang] = routeService.getRoutePathParts(shared_slash(relativePath));
160
- const [urlVersion, urlLang, urlPath] = routeService.getRoutePathParts(url);
161
- url = addLeadingSlash(urlPath);
162
- if (pathLang && urlLang !== pathLang) url = `/${pathLang}${url}`;
163
- if (pathVersion && urlVersion !== pathVersion) url = `/${pathVersion}${url}`;
154
+ if (!routeService) return nodeUrl;
155
+ if (url.startsWith('/')) {
156
+ const { routePath } = routeService.normalizeRoutePath(url);
157
+ url = routePath;
158
+ } else {
159
+ const anotherFileAbsolutePath = node_path.join(node_path.dirname(filePath), url);
160
+ url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
164
161
  }
165
162
  if ('boolean' == typeof cleanUrls) url = normalizeHref(url, cleanUrls);
166
163
  else {
167
164
  url = normalizeHref(url, false);
168
165
  url = url.replace(/\.html$/, cleanUrls);
169
166
  }
167
+ internalLinks.set(nodeUrl, url);
170
168
  if (hash) url += `#${hash}`;
169
+ if (__base) url = withBase(url, __base);
171
170
  return url;
172
171
  }
172
+ function linkToRoutePath(routePath) {
173
+ return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
174
+ }
173
175
  const normalizeImageUrl = (imageUrl)=>{
174
176
  if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) return '';
175
177
  return imageUrl;
176
178
  };
177
- const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, file)=>{
178
- const images = [];
179
+ const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: shouldCheckDeadLinks = false, __base })=>(tree, file)=>{
180
+ const internalLinks = new Map();
179
181
  visit(tree, 'link', (node)=>{
180
182
  const { url: nodeUrl } = node;
181
- const relativePath = node_path.relative(root, file.path);
182
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
183
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
184
+ node.url = link;
183
185
  });
184
186
  visit(tree, 'definition', (node)=>{
185
187
  const { url: nodeUrl } = node;
186
- const relativePath = node_path.relative(root, file.path);
187
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
188
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
189
+ node.url = link;
188
190
  });
191
+ if (shouldCheckDeadLinks && routeService) normalizeLink_checkDeadLinks(internalLinks, file.path, routeService);
192
+ const images = [];
189
193
  const getMdxSrcAttribute = (tempVar)=>({
190
194
  type: 'mdxJsxAttribute',
191
195
  name: 'src',
@@ -582,15 +586,8 @@ async function createMDXOptions(options) {
582
586
  {
583
587
  cleanUrls,
584
588
  root: docDirectory,
585
- routeService
586
- }
587
- ],
588
- checkDeadLinks && routeService && [
589
- remarkCheckDeadLinks,
590
- {
591
- root: docDirectory,
592
- base: config?.base || '',
593
- routeService
589
+ routeService,
590
+ checkDeadLinks
594
591
  }
595
592
  ],
596
593
  globalComponents.length && [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rspress/core",
3
- "version": "2.0.0-beta.18",
3
+ "version": "2.0.0-beta.19",
4
4
  "description": "The Rspress Documentation Framework",
5
5
  "bugs": "https://github.com/web-infra-dev/rspress/issues",
6
6
  "repository": {
@@ -47,13 +47,13 @@
47
47
  "@mdx-js/loader": "^3.1.0",
48
48
  "@mdx-js/mdx": "^3.1.0",
49
49
  "@mdx-js/react": "^3.1.0",
50
- "@rsbuild/core": "~1.4.0",
50
+ "@rsbuild/core": "~1.4.2",
51
51
  "@rsbuild/plugin-react": "~1.3.2",
52
52
  "@rspress/mdx-rs": "0.6.6",
53
53
  "@shikijs/rehype": "^3.4.2",
54
54
  "@types/unist": "^3.0.3",
55
- "@unhead/react": "^2.0.10",
56
- "enhanced-resolve": "5.18.1",
55
+ "@unhead/react": "^2.0.11",
56
+ "enhanced-resolve": "5.18.2",
57
57
  "github-slugger": "^2.0.0",
58
58
  "hast-util-from-html": "^2.0.3",
59
59
  "hast-util-heading-rank": "^3.0.0",
@@ -75,15 +75,15 @@
75
75
  "unified": "^11.0.5",
76
76
  "unist-util-visit": "^5.0.0",
77
77
  "unist-util-visit-children": "^3.0.0",
78
- "@rspress/plugin-last-updated": "2.0.0-beta.18",
79
- "@rspress/plugin-medium-zoom": "2.0.0-beta.18",
80
- "@rspress/runtime": "2.0.0-beta.18",
81
- "@rspress/shared": "2.0.0-beta.18",
82
- "@rspress/theme-default": "2.0.0-beta.18"
78
+ "@rspress/plugin-last-updated": "2.0.0-beta.19",
79
+ "@rspress/shared": "2.0.0-beta.19",
80
+ "@rspress/plugin-medium-zoom": "2.0.0-beta.19",
81
+ "@rspress/runtime": "2.0.0-beta.19",
82
+ "@rspress/theme-default": "2.0.0-beta.19"
83
83
  },
84
84
  "devDependencies": {
85
85
  "@microsoft/api-extractor": "^7.52.8",
86
- "@rslib/core": "0.10.3",
86
+ "@rslib/core": "0.10.4",
87
87
  "@rspress-dev/plugin-preview": "link:../plugin-preview",
88
88
  "@types/hast": "^3.0.4",
89
89
  "@types/html-to-text": "^9.0.4",