@rspress/core 2.0.0-beta.2 → 2.0.0-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/loader.js CHANGED
@@ -1,541 +1,46 @@
1
- import __rslib_shim_module__ from 'module';
1
+ import 'module';
2
2
  /*#__PURE__*/ import.meta.url;
3
- import * as __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__ from "node:fs/promises";
4
- import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
5
- import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
6
- import * as __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__ from "@mdx-js/mdx";
7
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__ from "@rspress/shared";
8
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__ from "@rspress/shared/logger";
9
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__ from "@rspress/shared/node-utils";
10
- import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
11
- import * as __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__ from "enhanced-resolve";
12
- import * as __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__ from "node:os";
13
- import * as __WEBPACK_EXTERNAL_MODULE_rehype_external_links_09bed11a__ from "rehype-external-links";
14
- import * as __WEBPACK_EXTERNAL_MODULE_remark_gfm_073acf21__ from "remark-gfm";
15
- import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__ from "unist-util-visit";
16
- import * as __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__ from "github-slugger";
17
- import * as __WEBPACK_EXTERNAL_MODULE_hast_util_heading_rank_cff646ba__ from "hast-util-heading-rank";
18
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__ from "@rspress/shared/constants";
19
- import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_children_71921007__ from "unist-util-visit-children";
20
- const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
21
- `{
22
- const saved = localStorage.getItem('${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.APPEARANCE_KEY}')
23
- const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
24
- const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
25
- document.documentElement.classList.toggle('dark', isDark)
26
- document.documentElement.classList.toggle('rp-dark', isDark)
27
- document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
28
- }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
29
- const dirname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(new URL(import.meta.url)));
30
- const PACKAGE_ROOT = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(dirname, '..');
31
- __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'index.html');
32
- __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
33
- __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
34
- __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
35
- const TEMP_DIR = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), 'node_modules', __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.RSPRESS_TEMP_DIR);
36
- var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
37
- RuntimeModuleID["GlobalStyles"] = "virtual-global-styles";
38
- RuntimeModuleID["GlobalComponents"] = "virtual-global-components";
39
- RuntimeModuleID["RouteForClient"] = "virtual-routes";
40
- RuntimeModuleID["RouteForSSR"] = "virtual-routes-ssr";
41
- RuntimeModuleID["SiteData"] = "virtual-site-data";
42
- RuntimeModuleID["SearchIndexHash"] = "virtual-search-index-hash";
43
- RuntimeModuleID["I18nText"] = "virtual-i18n-text";
44
- RuntimeModuleID["SearchHooks"] = "virtual-search-hooks";
45
- RuntimeModuleID["PrismLanguages"] = "virtual-prism-languages";
46
- return RuntimeModuleID;
47
- }({});
48
- let resolver;
49
- let startFlatten = false;
50
- const processor = (0, __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__.createProcessor)();
51
- const { CachedInputFileSystem, ResolverFactory } = __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__["default"];
52
- const fileSystem = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"];
53
- async function resolveDepPath(importPath, importer, alias) {
54
- if (!resolver) resolver = ResolverFactory.createResolver({
55
- fileSystem: new CachedInputFileSystem(fileSystem, 0),
56
- extensions: [
57
- '.mdx',
58
- '.md'
59
- ],
60
- alias
61
- });
62
- const resolveResult = await new Promise((resolve, reject)=>{
63
- resolver.resolve({
64
- importer
65
- }, importer, importPath, {}, (err, filePath)=>{
66
- if (err) return reject(err);
67
- if (!filePath) return reject(new Error(`Empty result when resolving ${importPath} from ${importer}`));
68
- return resolve(filePath);
69
- });
70
- });
71
- return resolveResult;
72
- }
73
- async function flattenMdxContent(content, basePath, alias) {
74
- const deps = [];
75
- const regex = new RegExp(importStatementRegex);
76
- if (!regex.test(content)) return {
77
- flattenContent: content,
78
- deps
79
- };
80
- if (!startFlatten) {
81
- resolver = ResolverFactory.createResolver({
82
- fileSystem: new CachedInputFileSystem(fileSystem, 0),
83
- extensions: [
84
- '.mdx',
85
- '.md',
86
- '.js'
87
- ],
88
- alias
89
- });
90
- startFlatten = true;
91
- }
92
- let ast;
93
- let result = content;
94
- try {
95
- ast = processor.parse(content);
96
- } catch (e) {
97
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug('flattenMdxContent parse failed: \n', e);
98
- return {
99
- flattenContent: content,
100
- deps
101
- };
102
- }
103
- const importNodes = ast.children.filter((node)=>'mdxjsEsm' === node.type).flatMap((node)=>node.data?.estree?.body || []).filter((node)=>'ImportDeclaration' === node.type);
104
- for (const importNode of importNodes){
105
- const id = importNode.specifiers[0].local.name;
106
- const importPath = importNode.source.value;
107
- let absoluteImportPath;
108
- try {
109
- absoluteImportPath = await resolveDepPath(importPath, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(basePath), alias);
110
- } catch (_e) {
111
- continue;
112
- }
113
- if (__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
114
- const importedContent = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(absoluteImportPath, 'utf-8');
115
- const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
116
- result = result.replace(new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`), '').replace(new RegExp(`<${id}\\s*/>`, 'g'), ()=>replacedValue);
117
- deps.push(...subDeps, absoluteImportPath);
118
- }
119
- }
120
- return {
121
- flattenContent: result,
122
- deps
123
- };
124
- }
125
- function applyReplaceRules(code = '', replaceRules = []) {
126
- let result = code;
127
- for (const rule of replaceRules)result = result.replace(rule.search, rule.replace);
128
- return result;
129
- }
130
- function escapeMarkdownHeadingIds(content) {
131
- const markdownHeadingRegexp = /(?:^|\n)#{1,6}(?!#).*/g;
132
- return content.replace(markdownHeadingRegexp, (substring)=>substring.replace('{#', '\\{#').replace('\\\\{#', '\\{#'));
133
- }
134
- const isWindows = 'win32' === __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__["default"].platform();
135
- function slash(p) {
136
- return p.replace(/\\/g, '/');
137
- }
138
- function normalizePath(id) {
139
- return __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.normalize(isWindows ? slash(id) : id);
140
- }
141
- const rehypePluginCodeMeta = ()=>(tree)=>{
142
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'element', (node)=>{
143
- if ('pre' === node.tagName && node.children[0]?.type === 'element' && 'code' === node.children[0].tagName) {
144
- const codeNode = node.children[0];
145
- codeNode.properties ??= {};
146
- codeNode.properties.meta = codeNode.data?.meta;
147
- }
148
- });
149
- };
150
- const rehypeHeaderAnchor = ()=>{
151
- const slugger = new __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__["default"]();
152
- return (tree)=>{
153
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'element', (node)=>{
154
- if (!(0, __WEBPACK_EXTERNAL_MODULE_hast_util_heading_rank_cff646ba__.headingRank)(node)) return;
155
- if (!node.properties?.id) {
156
- const [text, customId] = collectHeaderText(node);
157
- node.properties ??= {};
158
- node.properties.id = customId || slugger.slug(text);
159
- }
160
- node.children.unshift(create(node));
161
- });
162
- };
163
- };
164
- const collectHeaderText = (node)=>{
165
- let text = '';
166
- let id = '';
167
- node.children.forEach((child)=>{
168
- if ('text' === child.type) {
169
- const [textPart, idPart] = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(child.value);
170
- child.value = textPart;
171
- text += textPart;
172
- id = idPart;
173
- } else if ('element' === child.type) child.children.forEach((c)=>{
174
- if ('text' === c.type) text += c.value;
175
- });
176
- });
177
- return [
178
- text,
179
- id
180
- ];
181
- };
182
- function create(node) {
183
- return {
184
- type: 'element',
185
- tagName: 'a',
186
- properties: {
187
- class: 'header-anchor',
188
- ariaHidden: 'true',
189
- href: `#${node.properties.id}`
190
- },
191
- children: [
192
- {
193
- type: 'text',
194
- value: '#'
195
- }
196
- ]
197
- };
198
- }
199
- const getASTNodeImport = (name, from)=>({
200
- type: 'mdxjsEsm',
201
- value: `import ${name} from ${JSON.stringify(from)}`,
202
- data: {
203
- estree: {
204
- type: 'Program',
205
- sourceType: 'module',
206
- body: [
207
- {
208
- type: 'ImportDeclaration',
209
- specifiers: [
210
- {
211
- type: 'ImportDefaultSpecifier',
212
- local: {
213
- type: 'Identifier',
214
- name
215
- }
216
- }
217
- ],
218
- source: {
219
- type: 'Literal',
220
- value: from,
221
- raw: `${JSON.stringify(from)}`
222
- }
223
- }
224
- ]
225
- }
226
- }
227
- });
228
- const remarkBuiltin = ({ globalComponents })=>(tree)=>{
229
- const demos = globalComponents.map((componentPath)=>{
230
- const filename = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].parse(componentPath).name;
231
- const componentName = filename[0].toUpperCase() + filename.slice(1);
232
- return getASTNodeImport(componentName, componentPath);
233
- });
234
- tree.children.unshift(...demos);
235
- };
236
- const IGNORE_REGEXP = /^(https?|mailto|tel|#)/;
237
- function checkLinks(links, filepath, root, routeService) {
238
- const errorInfos = [];
239
- links.filter((link)=>!IGNORE_REGEXP.test(link)).map((link)=>normalizePath(link)).forEach((link)=>{
240
- const relativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, filepath);
241
- if (!routeService.isExistRoute((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.cleanUrl)(link))) errorInfos.push(`Internal link to "${link}" is dead, check it in "${relativePath}"`);
242
- });
243
- if (errorInfos.length > 0) {
244
- errorInfos?.forEach((err)=>{
245
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(err);
246
- });
247
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isProduction)()) throw new Error('Dead link found');
248
- }
249
- }
250
- const remarkCheckDeadLinks = (checkLink)=>{
251
- const { root, routeService } = checkLink;
252
- return (tree, vfile)=>{
253
- const internalLinks = new Set();
254
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'link', ({ url })=>{
255
- if (!url) return;
256
- if (internalLinks.has(url)) return;
257
- if (!url.startsWith('http://') && !url.startsWith('https://')) {
258
- const { routePath: normalizeUrl } = routeService.normalizeRoutePath(url.split(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].sep).join('/')?.split('#')[0]);
259
- internalLinks.add(normalizeUrl);
260
- }
261
- });
262
- checkLinks(Array.from(internalLinks), vfile.path, root, routeService);
263
- };
264
- };
265
- function normalizeLink(nodeUrl, routeService, relativePath, cleanUrls) {
266
- if (!nodeUrl) return '';
267
- if (nodeUrl.startsWith('#')) return `#${nodeUrl.slice(1)}`;
268
- let { url, hash } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.parseUrl)(nodeUrl);
269
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(url)) return url + (hash ? `#${hash}` : '');
270
- const extname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(url);
271
- if ((routeService?.extensions ?? __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__.DEFAULT_PAGE_EXTENSIONS).includes(extname)) url = url.replace(new RegExp(`\\${extname}$`), '');
272
- if (url.startsWith('.')) url = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.join((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.slash)(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(relativePath)), url);
273
- else if (routeService) {
274
- const [pathVersion, pathLang] = routeService.getRoutePathParts((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.slash)(relativePath));
275
- const [urlVersion, urlLang, urlPath] = routeService.getRoutePathParts(url);
276
- url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addLeadingSlash)(urlPath);
277
- if (pathLang && urlLang !== pathLang) url = `/${pathLang}${url}`;
278
- if (pathVersion && urlVersion !== pathVersion) url = `/${pathVersion}${url}`;
279
- }
280
- if ('boolean' == typeof cleanUrls) url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, cleanUrls);
281
- else {
282
- url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, false);
283
- url = url.replace(/\.html$/, cleanUrls);
284
- }
285
- if (hash) url += `#${hash}`;
286
- return url;
287
- }
288
- const normalizeImageUrl = (imageUrl)=>{
289
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(imageUrl) || imageUrl.startsWith('/')) return '';
290
- return imageUrl;
291
- };
292
- const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, file)=>{
293
- const images = [];
294
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'link', (node)=>{
295
- const { url: nodeUrl } = node;
296
- const relativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, file.path);
297
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
298
- });
299
- const getMdxSrcAttribute = (tempVar)=>({
300
- type: 'mdxJsxAttribute',
301
- name: 'src',
302
- value: {
303
- type: 'mdxJsxAttributeValueExpression',
304
- value: tempVar,
305
- data: {
306
- estree: {
307
- type: 'Program',
308
- sourceType: 'module',
309
- body: [
310
- {
311
- type: 'ExpressionStatement',
312
- expression: {
313
- type: 'Identifier',
314
- name: tempVar
315
- }
316
- }
317
- ]
318
- }
319
- }
320
- }
321
- });
322
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'image', (node)=>{
323
- const { alt, url } = node;
324
- if (!url) return;
325
- const imagePath = normalizeImageUrl(url);
326
- if (!imagePath) return;
327
- const tempVariableName = `image${images.length}`;
328
- Object.assign(node, {
329
- type: 'mdxJsxFlowElement',
330
- name: 'img',
331
- children: [],
332
- attributes: [
333
- alt && {
334
- type: 'mdxJsxAttribute',
335
- name: 'alt',
336
- value: alt
337
- },
338
- getMdxSrcAttribute(tempVariableName)
339
- ].filter(Boolean)
340
- });
341
- images.push(getASTNodeImport(tempVariableName, imagePath));
342
- });
343
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, (node)=>{
344
- if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
345
- const srcAttr = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.getNodeAttribute)(node, 'src', true);
346
- if ('string' != typeof srcAttr?.value) return;
347
- const imagePath = normalizeImageUrl(srcAttr.value);
348
- if (!imagePath) return;
349
- const tempVariableName = `image${images.length}`;
350
- Object.assign(srcAttr, getMdxSrcAttribute(tempVariableName));
351
- images.push(getASTNodeImport(tempVariableName, imagePath));
352
- });
353
- tree.children.unshift(...images);
354
- };
355
- const parseToc = (tree)=>{
356
- let title = '';
357
- const toc = [];
358
- const slugger = new __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__["default"]();
359
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_children_71921007__.visitChildren)((node)=>{
360
- if ('heading' !== node.type || !node.depth || !node.children) return;
361
- if (node.depth >= 1 && node.depth < 5) {
362
- let customId = '';
363
- const text = node.children.map((child)=>{
364
- if ('link' === child.type) return child.children?.map((item)=>item.value).join('');
365
- if ('strong' === child.type) return `**${child.children?.map((item)=>item.value).join('')}**`;
366
- if ('emphasis' === child.type) return `*${child.children?.map((item)=>item.value).join('')}*`;
367
- if ('delete' === child.type) return `~~${child.children?.map((item)=>item.value).join('')}~~`;
368
- if ('text' === child.type) {
369
- const [textPart, idPart] = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(child.value);
370
- customId = idPart;
371
- return textPart;
372
- }
373
- if ('inlineCode' === child.type) return `\`${child.value}\``;
374
- return '';
375
- }).join('');
376
- if (1 === node.depth) {
377
- if (!title) title = text;
378
- } else {
379
- const id = customId ? customId : slugger.slug(text);
380
- const { depth } = node;
381
- toc.push({
382
- id,
383
- text,
384
- depth
385
- });
386
- }
387
- }
388
- })(tree);
389
- return {
390
- title,
391
- toc
392
- };
393
- };
394
- const remarkPluginToc = function() {
395
- const data = this.data();
396
- return (tree)=>{
397
- const { toc, title } = parseToc(tree);
398
- data.pageMeta.toc = toc;
399
- if (title) data.pageMeta.title = title;
400
- };
401
- };
402
- async function createMDXOptions(docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver) {
403
- const cleanUrls = config?.route?.cleanUrls ?? false;
404
- const { remarkPlugins: remarkPluginsFromConfig = [], rehypePlugins: rehypePluginsFromConfig = [], globalComponents: globalComponentsFromConfig = [] } = config?.markdown || {};
405
- const rspressPlugins = pluginDriver.getPlugins();
406
- const remarkPluginsFromPlugins = rspressPlugins.flatMap((plugin)=>plugin.markdown?.remarkPlugins || []);
407
- const rehypePluginsFromPlugins = rspressPlugins.flatMap((plugin)=>plugin.markdown?.rehypePlugins || []);
408
- const globalComponents = [
409
- ...rspressPlugins.flatMap((plugin)=>plugin.markdown?.globalComponents || []),
410
- ...globalComponentsFromConfig
411
- ];
412
- return {
413
- providerImportSource: '@mdx-js/react',
414
- format: __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(filepath).slice(1),
415
- remarkPlugins: [
416
- __WEBPACK_EXTERNAL_MODULE_remark_gfm_073acf21__["default"],
417
- remarkPluginToc,
418
- [
419
- remarkPluginNormalizeLink,
420
- {
421
- cleanUrls,
422
- root: docDirectory,
423
- routeService
424
- }
425
- ],
426
- checkDeadLinks && [
427
- remarkCheckDeadLinks,
428
- {
429
- root: docDirectory,
430
- base: config?.base || '',
431
- routeService
432
- }
433
- ],
434
- globalComponents.length && [
435
- remarkBuiltin,
436
- {
437
- globalComponents
438
- }
439
- ],
440
- ...remarkPluginsFromConfig,
441
- ...remarkPluginsFromPlugins
442
- ].filter(Boolean),
443
- rehypePlugins: [
444
- rehypeHeaderAnchor,
445
- rehypePluginCodeMeta,
446
- [
447
- __WEBPACK_EXTERNAL_MODULE_rehype_external_links_09bed11a__["default"],
448
- {
449
- target: '_blank',
450
- rel: 'noopener noreferrer'
451
- }
452
- ],
453
- ...rehypePluginsFromConfig,
454
- ...rehypePluginsFromPlugins
455
- ]
456
- };
457
- }
458
- async function updateSiteDataRuntimeModule(modulePath, pageMeta) {
459
- const siteDataModulePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(TEMP_DIR, 'runtime', `${types_RuntimeModuleID.SiteData}.mjs`);
460
- const { default: siteData } = await import((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.pathToFileURL)(siteDataModulePath).href);
461
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].writeFile(siteDataModulePath, `export default ${JSON.stringify({
462
- ...siteData,
463
- timestamp: Date.now().toString(),
464
- pages: siteData.pages.map((page)=>page._filepath === modulePath ? {
465
- ...page,
466
- ...pageMeta
467
- } : page)
468
- }, null, 2)}`);
469
- }
470
- function createCheckPageMetaUpdateFn() {
471
- const pageMetaMap = new Map();
472
- return (modulePath, pageMeta)=>{
473
- const prevMeta = pageMetaMap.get(modulePath);
474
- const deserializedMeta = JSON.stringify(pageMeta);
475
- pageMetaMap.set(modulePath, deserializedMeta);
476
- if (!prevMeta) return;
477
- if (prevMeta !== deserializedMeta) setTimeout(async ()=>{
478
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info('Page metadata changed, page reloading...');
479
- await updateSiteDataRuntimeModule(modulePath, pageMeta);
480
- });
481
- };
482
- }
483
- const checkPageMetaUpdate = createCheckPageMetaUpdateFn();
3
+ import { logger } from "@rsbuild/core";
4
+ import { compile, compileWithCrossCompilerCache } from "./processor.js";
484
5
  async function mdxLoader(source) {
485
6
  this.cacheable(true);
486
7
  const callback = this.async();
487
8
  const options = this.getOptions();
488
9
  const filepath = this.resourcePath;
489
- const { alias } = this._compiler.options.resolve;
490
10
  const { config, docDirectory, checkDeadLinks, routeService, pluginDriver } = options;
491
- const { frontmatter, content } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.loadFrontMatter)(source, filepath, docDirectory, true);
492
- const { flattenContent, deps } = await flattenMdxContent(content, filepath, alias);
493
- deps.forEach((dep)=>this.addDependency(dep));
494
- const replacedContent = applyReplaceRules(flattenContent, config.replaceRules);
495
- const preprocessedContent = escapeMarkdownHeadingIds(replacedContent);
11
+ const crossCompilerCache = config?.markdown?.crossCompilerCache ?? true;
496
12
  try {
497
- let pageMeta = {
498
- title: '',
499
- toc: [],
500
- headingTitle: ''
501
- };
502
- const frontmatterTitle = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(frontmatter.title)[0];
503
- const mdxOptions = await createMDXOptions(docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver);
504
- const compiler = (0, __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__.createProcessor)(mdxOptions);
505
- compiler.data('pageMeta', {
506
- toc: [],
507
- title: ''
508
- });
509
- const vFile = await compiler.process({
510
- value: preprocessedContent,
511
- path: filepath
512
- });
513
- const compileResult = String(vFile);
514
- const compilationMeta = compiler.data('pageMeta');
515
- const headingTitle = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(compilationMeta.title)[0];
516
- pageMeta = {
517
- ...compilationMeta,
518
- title: frontmatterTitle || headingTitle,
519
- headingTitle,
520
- frontmatter
521
- };
522
- if (!(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isProduction)()) checkPageMetaUpdate(filepath, pageMeta);
523
- const result = `const frontmatter = ${JSON.stringify(frontmatter)};
524
- ${compileResult}
525
- MDXContent.__RSPRESS_PAGE_META = {};
526
-
527
- MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(normalizePath(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(docDirectory, filepath)))}"] = ${JSON.stringify(pageMeta)};
528
- `;
529
- callback(null, result);
13
+ if (crossCompilerCache && 'production' === process.env.NODE_ENV) {
14
+ const compileResult = await compileWithCrossCompilerCache({
15
+ source,
16
+ filepath,
17
+ docDirectory,
18
+ checkDeadLinks,
19
+ config,
20
+ pluginDriver,
21
+ routeService
22
+ });
23
+ callback(null, compileResult);
24
+ } else {
25
+ const compileResult = await compile({
26
+ source,
27
+ filepath,
28
+ docDirectory,
29
+ checkDeadLinks,
30
+ config,
31
+ pluginDriver,
32
+ routeService
33
+ });
34
+ callback(null, compileResult);
35
+ }
530
36
  } catch (e) {
531
37
  if (e instanceof Error) {
532
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`MDX compile error: ${e.message} in ${filepath}`);
533
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug(e);
38
+ logger.debug(e);
534
39
  callback({
535
- message: e.message,
40
+ message: `MDX compile error: ${e.message} in ${filepath}`,
536
41
  name: `${filepath} compile error`
537
42
  });
538
43
  }
539
44
  }
540
45
  }
541
- export { createCheckPageMetaUpdateFn, mdxLoader as default, updateSiteDataRuntimeModule };
46
+ export { mdxLoader as default };
@@ -0,0 +1,95 @@
1
+ import { AdditionalPage } from '@rspress/shared';
2
+ import { DefaultThemeConfig } from '@rspress/shared';
3
+ import type { PageIndexInfo } from '@rspress/shared';
4
+ import type { RouteMeta } from '@rspress/shared';
5
+ import type { RspressPlugin } from '@rspress/shared';
6
+ import type { UserConfig } from '@rspress/shared';
7
+
8
+ export declare function compile(options: CompileOptions): Promise<string>;
9
+
10
+ declare interface CompileOptions {
11
+ source: string;
12
+ filepath: string;
13
+ checkDeadLinks: boolean;
14
+ docDirectory: string;
15
+ config: UserConfig | null;
16
+ routeService: RouteService | null;
17
+ pluginDriver: PluginDriver | null;
18
+ }
19
+
20
+ export declare function compileWithCrossCompilerCache(options: CompileOptions): Promise<string>;
21
+
22
+ declare interface InitOptions {
23
+ scanDir: string;
24
+ config: UserConfig;
25
+ runtimeTempDir: string;
26
+ pluginDriver: PluginDriver;
27
+ }
28
+
29
+ declare class PluginDriver {
30
+ #private;
31
+ constructor(config: UserConfig, configFilePath: string, isProd: boolean);
32
+ getConfigFilePath(): string;
33
+ init(): Promise<void>;
34
+ addPlugin(plugin: RspressPlugin): void;
35
+ getPlugins(): RspressPlugin[];
36
+ clearPlugins(): void;
37
+ removePlugin(pluginName: string): void;
38
+ modifyConfig(): Promise<UserConfig<DefaultThemeConfig>>;
39
+ beforeBuild(): Promise<void[]>;
40
+ afterBuild(): Promise<void[]>;
41
+ modifySearchIndexData(pages: PageIndexInfo[]): Promise<void[]>;
42
+ extendPageData(pageData: PageIndexInfo): Promise<void[]>;
43
+ addPages(): Promise<AdditionalPage[]>;
44
+ routeGenerated(routes: RouteMeta[]): Promise<void[]>;
45
+ routeServiceGenerated(routeService: RouteService): Promise<void[]>;
46
+ addRuntimeModules(): Promise<Record<string, string>>;
47
+ addSSGRoutes(): Promise<({
48
+ path: string;
49
+ } | {
50
+ path: string;
51
+ })[]>;
52
+ globalUIComponents(): (string | [string, object])[];
53
+ globalStyles(): string[];
54
+ _runParallelAsyncHook<H extends RspressPluginHookKeys>(hookName: H, ...args: Parameters<Required<RspressPlugin>[H]>): Promise<Awaited<ReturnType<Required<RspressPlugin>[H]>>[]>;
55
+ _runSerialAsyncHook<H extends RspressPluginHookKeys>(hookName: H, ...args: Parameters<Required<RspressPlugin>[H]>): RspressPlugin;
56
+ }
57
+
58
+ declare class RoutePage {
59
+ #private;
60
+ routeMeta: RouteMeta;
61
+ static create(absolutePath: string, docsDir: string): RoutePage;
62
+ static createFromExternal(routePath: string, filepath: string, docDir: string): RoutePage;
63
+ private constructor();
64
+ static generateRouteMeta(routePath: string, filepath: string, docDir: string): RouteMeta;
65
+ }
66
+
67
+ declare class RouteService {
68
+ #private;
69
+ routeData: Map<string, RoutePage>;
70
+ static __instance__: RouteService | null;
71
+ static getInstance(): RouteService;
72
+ static create(options: InitOptions): Promise<RouteService>;
73
+ private constructor();
74
+ get extensions(): readonly string[];
75
+ addRoute(routePage: RoutePage): Promise<void>;
76
+ getRoutes(): RouteMeta[];
77
+ getRoutePages(): RoutePage[];
78
+ isExistRoute(routePath: string): boolean;
79
+ generateRoutesCode(): string;
80
+ generateRoutesCodeByRouteMeta(routeMeta: RouteMeta[]): string;
81
+ getRoutePathParts(relativePath: string): readonly [string, string, string];
82
+ normalizeRoutePath(relativePath: string): {
83
+ pureRoutePath: string;
84
+ routePath: string;
85
+ lang: string;
86
+ version: string;
87
+ };
88
+ absolutePathToRoutePath(absolutePath: string): string;
89
+ absolutePathToRelativePath(absolutePath: string): string;
90
+ getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
91
+ }
92
+
93
+ declare type RspressPluginHookKeys = 'beforeBuild' | 'config' | 'afterBuild' | 'addPages' | 'addRuntimeModules' | 'routeGenerated' | 'routeServiceGenerated' | 'addSSGRoutes' | 'extendPageData' | 'modifySearchIndexData';
94
+
95
+ export { }