fumadocs-mdx 13.0.8 → 14.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/bin.cjs +924 -901
  2. package/dist/bin.js +3 -3
  3. package/dist/build-mdx-6UAK5FF5.js +8 -0
  4. package/dist/bun/index.cjs +578 -471
  5. package/dist/bun/index.d.cts +3 -2
  6. package/dist/bun/index.d.ts +3 -2
  7. package/dist/bun/index.js +12 -12
  8. package/dist/chunk-4JSFLXXT.js +8 -0
  9. package/dist/chunk-5UMZCWKV.js +17 -0
  10. package/dist/chunk-5YXP7JLN.js +138 -0
  11. package/dist/{chunk-2E2JCOSO.js → chunk-6NISOLQ6.js} +16 -44
  12. package/dist/chunk-7L2KNF6B.js +180 -0
  13. package/dist/chunk-E5DJTSIM.js +86 -0
  14. package/dist/{chunk-K5ZLPEIQ.js → chunk-FBLMK4RS.js} +9 -6
  15. package/dist/{chunk-QXHN25N3.js → chunk-OXSRIWQW.js} +7 -8
  16. package/dist/chunk-PKI7ZDA5.js +29 -0
  17. package/dist/{chunk-3J3WL7WN.js → chunk-SLY7WXTX.js} +71 -58
  18. package/dist/{chunk-5FTSWCB4.js → chunk-SRSRFOVI.js} +8 -10
  19. package/dist/chunk-TYJDYTKH.js +85 -0
  20. package/dist/chunk-XHJCLBZ4.js +406 -0
  21. package/dist/{chunk-2HXTGJBI.js → chunk-ZY6UZ7NH.js} +22 -19
  22. package/dist/config/index.cjs +79 -71
  23. package/dist/config/index.d.cts +2 -1
  24. package/dist/config/index.d.ts +2 -1
  25. package/dist/config/index.js +5 -5
  26. package/dist/index-BlVBvy-z.d.ts +8 -0
  27. package/dist/{core-DB7TdlyC.d.cts → index-D7JdSMpp.d.cts} +99 -61
  28. package/dist/{core-DB7TdlyC.d.ts → index-D7JdSMpp.d.ts} +99 -61
  29. package/dist/index-P2NNUkHn.d.cts +8 -0
  30. package/dist/index.d.cts +3 -74
  31. package/dist/index.d.ts +3 -74
  32. package/dist/load-from-file-I3ALLIVB.js +8 -0
  33. package/dist/next/index.cjs +698 -476
  34. package/dist/next/index.d.cts +11 -1
  35. package/dist/next/index.d.ts +11 -1
  36. package/dist/next/index.js +78 -281
  37. package/dist/node/loader.cjs +704 -602
  38. package/dist/node/loader.js +10 -11
  39. package/dist/plugins/index-file.cjs +471 -0
  40. package/dist/plugins/index-file.d.cts +29 -0
  41. package/dist/plugins/index-file.d.ts +29 -0
  42. package/dist/plugins/index-file.js +8 -0
  43. package/dist/plugins/json-schema.d.cts +3 -2
  44. package/dist/plugins/json-schema.d.ts +3 -2
  45. package/dist/plugins/last-modified.cjs +75 -0
  46. package/dist/plugins/last-modified.d.cts +27 -0
  47. package/dist/plugins/last-modified.d.ts +27 -0
  48. package/dist/plugins/last-modified.js +44 -0
  49. package/dist/runtime/{vite/browser.cjs → browser.cjs} +40 -53
  50. package/dist/runtime/browser.d.cts +50 -0
  51. package/dist/runtime/browser.d.ts +50 -0
  52. package/dist/runtime/browser.js +68 -0
  53. package/dist/runtime/dynamic.cjs +985 -0
  54. package/dist/runtime/dynamic.d.cts +27 -0
  55. package/dist/runtime/dynamic.d.ts +27 -0
  56. package/dist/runtime/dynamic.js +78 -0
  57. package/dist/runtime/server.cjs +173 -0
  58. package/dist/runtime/server.d.cts +161 -0
  59. package/dist/runtime/server.d.ts +161 -0
  60. package/dist/runtime/server.js +8 -0
  61. package/dist/vite/index.cjs +934 -638
  62. package/dist/vite/index.d.cts +12 -22
  63. package/dist/vite/index.d.ts +12 -22
  64. package/dist/vite/index.js +30 -221
  65. package/dist/webpack/mdx.cjs +613 -515
  66. package/dist/webpack/mdx.d.cts +9 -1
  67. package/dist/webpack/mdx.d.ts +9 -1
  68. package/dist/webpack/mdx.js +12 -17
  69. package/dist/webpack/meta.cjs +327 -233
  70. package/dist/webpack/meta.d.cts +9 -1
  71. package/dist/webpack/meta.d.ts +9 -1
  72. package/dist/webpack/meta.js +13 -15
  73. package/package.json +15 -32
  74. package/dist/build-mdx-BjXOmv0b.d.cts +0 -53
  75. package/dist/build-mdx-CY5UldCO.d.ts +0 -53
  76. package/dist/chunk-2AQRQXSO.js +0 -119
  77. package/dist/chunk-CXA4JO4Z.js +0 -45
  78. package/dist/chunk-DMJ6I4C3.js +0 -76
  79. package/dist/chunk-FSZMKRVH.js +0 -80
  80. package/dist/chunk-II3H5ZVZ.js +0 -77
  81. package/dist/chunk-KILFIBVW.js +0 -75
  82. package/dist/chunk-NVRDCY6Z.js +0 -30
  83. package/dist/chunk-VUEZTR2H.js +0 -26
  84. package/dist/index-D7s7kCc2.d.cts +0 -7
  85. package/dist/index-D7s7kCc2.d.ts +0 -7
  86. package/dist/load-from-file-AVYOFOI7.js +0 -7
  87. package/dist/preset-ZMP6U62C.js +0 -6
  88. package/dist/runtime/next/async.cjs +0 -760
  89. package/dist/runtime/next/async.d.cts +0 -19
  90. package/dist/runtime/next/async.d.ts +0 -19
  91. package/dist/runtime/next/async.js +0 -86
  92. package/dist/runtime/next/index.cjs +0 -136
  93. package/dist/runtime/next/index.d.cts +0 -33
  94. package/dist/runtime/next/index.d.ts +0 -33
  95. package/dist/runtime/next/index.js +0 -11
  96. package/dist/runtime/vite/browser.d.cts +0 -59
  97. package/dist/runtime/vite/browser.d.ts +0 -59
  98. package/dist/runtime/vite/browser.js +0 -11
  99. package/dist/runtime/vite/server.cjs +0 -243
  100. package/dist/runtime/vite/server.d.cts +0 -30
  101. package/dist/runtime/vite/server.d.ts +0 -30
  102. package/dist/runtime/vite/server.js +0 -111
  103. package/dist/types-Bnh9n7mj.d.cts +0 -45
  104. package/dist/types-ey1AZqrg.d.ts +0 -45
@@ -0,0 +1,985 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/runtime/dynamic.ts
31
+ var dynamic_exports = {};
32
+ __export(dynamic_exports, {
33
+ fromConfigDynamic: () => fromConfigDynamic
34
+ });
35
+ module.exports = __toCommonJS(dynamic_exports);
36
+
37
+ // src/config/build.ts
38
+ var import_picomatch = __toESM(require("picomatch"), 1);
39
+
40
+ // src/config/preset.ts
41
+ function pluginOption(def, options = []) {
42
+ const list = def(Array.isArray(options) ? options : []).filter(
43
+ Boolean
44
+ );
45
+ if (typeof options === "function") {
46
+ return options(list);
47
+ }
48
+ return list;
49
+ }
50
+ function applyMdxPreset(options = {}) {
51
+ return async (environment = "bundler") => {
52
+ if (options.preset === "minimal") return options;
53
+ const plugins = await import("fumadocs-core/mdx-plugins");
54
+ const {
55
+ valueToExport = [],
56
+ rehypeCodeOptions,
57
+ remarkImageOptions,
58
+ remarkHeadingOptions,
59
+ remarkStructureOptions,
60
+ remarkCodeTabOptions,
61
+ remarkNpmOptions,
62
+ ...mdxOptions
63
+ } = options;
64
+ const remarkPlugins = pluginOption(
65
+ (v) => [
66
+ plugins.remarkGfm,
67
+ [
68
+ plugins.remarkHeading,
69
+ {
70
+ generateToc: false,
71
+ ...remarkHeadingOptions
72
+ }
73
+ ],
74
+ remarkImageOptions !== false && [
75
+ plugins.remarkImage,
76
+ {
77
+ ...remarkImageOptions,
78
+ useImport: remarkImageOptions?.useImport ?? environment === "bundler"
79
+ }
80
+ ],
81
+ "remarkCodeTab" in plugins && remarkCodeTabOptions !== false && [
82
+ plugins.remarkCodeTab,
83
+ remarkCodeTabOptions
84
+ ],
85
+ "remarkNpm" in plugins && remarkNpmOptions !== false && [plugins.remarkNpm, remarkNpmOptions],
86
+ ...v,
87
+ remarkStructureOptions !== false && [
88
+ plugins.remarkStructure,
89
+ remarkStructureOptions
90
+ ],
91
+ valueToExport.length > 0 && (() => {
92
+ return (_, file) => {
93
+ file.data["mdx-export"] ??= [];
94
+ for (const name of valueToExport) {
95
+ if (!(name in file.data)) continue;
96
+ file.data["mdx-export"].push({
97
+ name,
98
+ value: file.data[name]
99
+ });
100
+ }
101
+ };
102
+ })
103
+ ],
104
+ mdxOptions.remarkPlugins
105
+ );
106
+ const rehypePlugins = pluginOption(
107
+ (v) => [
108
+ rehypeCodeOptions !== false && [plugins.rehypeCode, rehypeCodeOptions],
109
+ ...v,
110
+ plugins.rehypeToc
111
+ ],
112
+ mdxOptions.rehypePlugins
113
+ );
114
+ return {
115
+ ...mdxOptions,
116
+ outputFormat: environment === "runtime" ? "function-body" : mdxOptions.outputFormat,
117
+ remarkPlugins,
118
+ rehypePlugins
119
+ };
120
+ };
121
+ }
122
+
123
+ // src/config/build.ts
124
+ var SupportedFormats = {
125
+ doc: ["mdx", "md"],
126
+ meta: ["json", "yaml"]
127
+ };
128
+ function buildCollection(name, config) {
129
+ if (config.type === "docs") {
130
+ return {
131
+ ...config,
132
+ name,
133
+ meta: buildPrimitiveCollection(name, config.meta),
134
+ docs: buildPrimitiveCollection(name, config.docs),
135
+ hasFile(filePath) {
136
+ return this.docs.hasFile(filePath) || this.meta.hasFile(filePath);
137
+ }
138
+ };
139
+ }
140
+ return buildPrimitiveCollection(name, config);
141
+ }
142
+ function buildPrimitiveCollection(name, { files, ...config }) {
143
+ const supportedFormats = SupportedFormats[config.type];
144
+ const patterns = files ?? [`**/*.{${supportedFormats.join(",")}}`];
145
+ let matchers;
146
+ return {
147
+ ...config,
148
+ name,
149
+ patterns,
150
+ isFileSupported(filePath) {
151
+ return supportedFormats.some((format) => filePath.endsWith(`.${format}`));
152
+ },
153
+ hasFile(filePath) {
154
+ matchers ??= (Array.isArray(config.dir) ? config.dir : [config.dir]).map(
155
+ (dir) => (0, import_picomatch.default)(patterns, {
156
+ cwd: dir
157
+ })
158
+ );
159
+ return this.isFileSupported(filePath) && matchers.some((matcher) => matcher(filePath));
160
+ }
161
+ };
162
+ }
163
+ function buildConfig(config) {
164
+ const collections = /* @__PURE__ */ new Map();
165
+ const loaded = {};
166
+ for (const [k, v] of Object.entries(config)) {
167
+ if (!v) {
168
+ continue;
169
+ }
170
+ if (typeof v === "object" && "type" in v) {
171
+ if (v.type === "docs") {
172
+ collections.set(k, buildCollection(k, v));
173
+ continue;
174
+ }
175
+ if (v.type === "doc" || v.type === "meta") {
176
+ collections.set(
177
+ k,
178
+ buildCollection(k, v)
179
+ );
180
+ continue;
181
+ }
182
+ }
183
+ if (k === "default" && v) {
184
+ Object.assign(loaded, v);
185
+ continue;
186
+ }
187
+ throw new Error(
188
+ `Unknown export "${k}", you can only export collections from source configuration file.`
189
+ );
190
+ }
191
+ const mdxOptionsCache = /* @__PURE__ */ new Map();
192
+ return {
193
+ global: loaded,
194
+ collectionList: Array.from(collections.values()),
195
+ getCollection(name) {
196
+ return collections.get(name);
197
+ },
198
+ getMDXOptions(collection, environment = "bundler") {
199
+ const key = collection ? `${environment}:${collection.name}` : environment;
200
+ const cached = mdxOptionsCache.get(key);
201
+ if (cached) return cached;
202
+ let result;
203
+ if (collection?.mdxOptions) {
204
+ const optionsFn = collection.mdxOptions;
205
+ result = typeof optionsFn === "function" ? optionsFn(environment) : optionsFn;
206
+ } else {
207
+ result = (async () => {
208
+ const optionsFn = this.global.mdxOptions;
209
+ const options = typeof optionsFn === "function" ? await optionsFn() : optionsFn;
210
+ return applyMdxPreset(options)(environment);
211
+ })();
212
+ }
213
+ mdxOptionsCache.set(key, result);
214
+ return result;
215
+ }
216
+ };
217
+ }
218
+
219
+ // src/loaders/mdx/build-mdx.ts
220
+ var import_mdx = require("@mdx-js/mdx");
221
+ var import_vfile = require("vfile");
222
+
223
+ // src/loaders/mdx/remark-include.ts
224
+ var import_unified = require("unified");
225
+ var import_unist_util_visit2 = require("unist-util-visit");
226
+ var path = __toESM(require("path"), 1);
227
+ var fs = __toESM(require("fs/promises"), 1);
228
+
229
+ // src/utils/fuma-matter.ts
230
+ var import_js_yaml = require("js-yaml");
231
+ var regex = /^---\r?\n(.+?)\r?\n---\r?\n/s;
232
+ function fumaMatter(input) {
233
+ const output = { matter: "", data: {}, content: input };
234
+ const match = regex.exec(input);
235
+ if (!match) {
236
+ return output;
237
+ }
238
+ output.matter = match[0];
239
+ output.content = input.slice(match[0].length);
240
+ const loaded = (0, import_js_yaml.load)(match[1]);
241
+ output.data = loaded ?? {};
242
+ return output;
243
+ }
244
+
245
+ // src/loaders/mdx/remark-include.ts
246
+ var import_mdx_plugins = require("fumadocs-core/mdx-plugins");
247
+
248
+ // src/loaders/mdx/remark-unravel.ts
249
+ var import_unist_util_visit = require("unist-util-visit");
250
+ function remarkMarkAndUnravel() {
251
+ return (tree) => {
252
+ (0, import_unist_util_visit.visit)(tree, function(node, index, parent) {
253
+ let offset = -1;
254
+ let all = true;
255
+ let oneOrMore = false;
256
+ if (parent && typeof index === "number" && node.type === "paragraph") {
257
+ const children = node.children;
258
+ while (++offset < children.length) {
259
+ const child = children[offset];
260
+ if (child.type === "mdxJsxTextElement" || child.type === "mdxTextExpression") {
261
+ oneOrMore = true;
262
+ } else if (child.type === "text" && child.value.trim().length === 0) {
263
+ } else {
264
+ all = false;
265
+ break;
266
+ }
267
+ }
268
+ if (all && oneOrMore) {
269
+ offset = -1;
270
+ const newChildren = [];
271
+ while (++offset < children.length) {
272
+ const child = children[offset];
273
+ if (child.type === "mdxJsxTextElement") {
274
+ child.type = "mdxJsxFlowElement";
275
+ }
276
+ if (child.type === "mdxTextExpression") {
277
+ child.type = "mdxFlowExpression";
278
+ }
279
+ if (child.type === "text" && /^[\t\r\n ]+$/.test(String(child.value))) {
280
+ } else {
281
+ newChildren.push(child);
282
+ }
283
+ }
284
+ parent.children.splice(index, 1, ...newChildren);
285
+ return index;
286
+ }
287
+ }
288
+ });
289
+ };
290
+ }
291
+
292
+ // src/loaders/mdx/mdast-utils.ts
293
+ function flattenNode(node) {
294
+ if ("children" in node)
295
+ return node.children.map((child) => flattenNode(child)).join("");
296
+ if ("value" in node) return node.value;
297
+ return "";
298
+ }
299
+
300
+ // src/loaders/mdx/remark-include.ts
301
+ var ElementLikeTypes = [
302
+ "mdxJsxFlowElement",
303
+ "mdxJsxTextElement",
304
+ "containerDirective",
305
+ "textDirective",
306
+ "leafDirective"
307
+ ];
308
+ function isElementLike(node) {
309
+ return ElementLikeTypes.includes(node.type);
310
+ }
311
+ function parseElementAttributes(element) {
312
+ if (Array.isArray(element.attributes)) {
313
+ const attributes = {};
314
+ for (const attr of element.attributes) {
315
+ if (attr.type === "mdxJsxAttribute" && (typeof attr.value === "string" || attr.value === null)) {
316
+ attributes[attr.name] = attr.value;
317
+ }
318
+ }
319
+ return attributes;
320
+ }
321
+ return element.attributes ?? {};
322
+ }
323
+ function parseSpecifier(specifier) {
324
+ const idx = specifier.lastIndexOf("#");
325
+ if (idx === -1) return { file: specifier };
326
+ return {
327
+ file: specifier.slice(0, idx),
328
+ section: specifier.slice(idx + 1)
329
+ };
330
+ }
331
+ function extractSection(root, section) {
332
+ let nodes;
333
+ let capturingHeadingContent = false;
334
+ (0, import_unist_util_visit2.visit)(root, (node) => {
335
+ if (node.type === "heading") {
336
+ if (capturingHeadingContent) {
337
+ return false;
338
+ }
339
+ if (node.data?.hProperties?.id === section) {
340
+ capturingHeadingContent = true;
341
+ nodes = [node];
342
+ return "skip";
343
+ }
344
+ return;
345
+ }
346
+ if (capturingHeadingContent) {
347
+ nodes?.push(node);
348
+ return "skip";
349
+ }
350
+ if (isElementLike(node) && node.name === "section") {
351
+ const attributes = parseElementAttributes(node);
352
+ if (attributes.id === section) {
353
+ nodes = node.children;
354
+ return false;
355
+ }
356
+ }
357
+ });
358
+ if (nodes)
359
+ return {
360
+ type: "root",
361
+ children: nodes
362
+ };
363
+ }
364
+ function remarkInclude() {
365
+ const TagName = "include";
366
+ const embedContent = async (file, heading, params, data) => {
367
+ let content;
368
+ try {
369
+ content = (await fs.readFile(file)).toString();
370
+ } catch (e) {
371
+ throw new Error(
372
+ `failed to read file ${file}
373
+ ${e instanceof Error ? e.message : String(e)}`,
374
+ { cause: e }
375
+ );
376
+ }
377
+ const ext = path.extname(file);
378
+ data._compiler?.addDependency(file);
379
+ if (params.lang || ext !== ".md" && ext !== ".mdx") {
380
+ const lang = params.lang ?? ext.slice(1);
381
+ return {
382
+ type: "code",
383
+ lang,
384
+ meta: params.meta,
385
+ value: content,
386
+ data: {}
387
+ };
388
+ }
389
+ const parser = data._getProcessor ? data._getProcessor(ext === ".mdx" ? "mdx" : "md") : this;
390
+ const parsed = fumaMatter(content);
391
+ let mdast = parser.parse({
392
+ path: file,
393
+ value: parsed.content,
394
+ data: { frontmatter: parsed.data }
395
+ });
396
+ const baseProcessor = (0, import_unified.unified)().use(remarkMarkAndUnravel);
397
+ if (heading) {
398
+ const extracted = extractSection(
399
+ await baseProcessor.use(import_mdx_plugins.remarkHeading).run(mdast),
400
+ heading
401
+ );
402
+ if (!extracted)
403
+ throw new Error(
404
+ `Cannot find section ${heading} in ${file}, make sure you have encapsulated the section in a <section id="${heading}"> tag, or a :::section directive with remark-directive configured.`
405
+ );
406
+ mdast = extracted;
407
+ } else {
408
+ mdast = await baseProcessor.run(mdast);
409
+ }
410
+ await update(mdast, path.dirname(file), data);
411
+ return mdast;
412
+ };
413
+ async function update(tree, directory, data) {
414
+ const queue = [];
415
+ (0, import_unist_util_visit2.visit)(tree, ElementLikeTypes, (_node, _, parent) => {
416
+ const node = _node;
417
+ if (node.name !== TagName) return;
418
+ const specifier = flattenNode(node);
419
+ if (specifier.length === 0) return "skip";
420
+ const attributes = parseElementAttributes(node);
421
+ const { file: relativePath, section } = parseSpecifier(specifier);
422
+ const file = path.resolve(
423
+ "cwd" in attributes ? process.cwd() : directory,
424
+ relativePath
425
+ );
426
+ queue.push(
427
+ embedContent(file, section, attributes, data).then((replace) => {
428
+ Object.assign(
429
+ parent && parent.type === "paragraph" ? parent : node,
430
+ replace
431
+ );
432
+ })
433
+ );
434
+ return "skip";
435
+ });
436
+ await Promise.all(queue);
437
+ }
438
+ return async (tree, file) => {
439
+ await update(tree, path.dirname(file.path), file.data);
440
+ };
441
+ }
442
+
443
+ // src/loaders/mdx/remark-postprocess.ts
444
+ var import_unist_util_visit3 = require("unist-util-visit");
445
+ var import_mdast_util_to_markdown = require("mdast-util-to-markdown");
446
+ var import_estree_util_value_to_estree = require("estree-util-value-to-estree");
447
+ var import_unist_util_remove_position = require("unist-util-remove-position");
448
+ var import_remark_mdx = __toESM(require("remark-mdx"), 1);
449
+ function remarkPostprocess({
450
+ _format,
451
+ includeProcessedMarkdown = false,
452
+ includeMDAST = false,
453
+ extractLinkReferences = false,
454
+ valueToExport = []
455
+ }) {
456
+ let _stringifyProcessor;
457
+ const getStringifyProcessor = () => {
458
+ return _stringifyProcessor ??= _format === "mdx" ? this : (
459
+ // force Markdown processor to stringify MDX nodes
460
+ this().use(import_remark_mdx.default).freeze()
461
+ );
462
+ };
463
+ return (tree, file) => {
464
+ const frontmatter = file.data.frontmatter ??= {};
465
+ if (!frontmatter.title) {
466
+ (0, import_unist_util_visit3.visit)(tree, "heading", (node) => {
467
+ if (node.depth === 1) {
468
+ frontmatter.title = flattenNode(node);
469
+ return false;
470
+ }
471
+ });
472
+ }
473
+ file.data["mdx-export"] ??= [];
474
+ if (extractLinkReferences) {
475
+ const urls = [];
476
+ (0, import_unist_util_visit3.visit)(tree, "link", (node) => {
477
+ urls.push({
478
+ href: node.url
479
+ });
480
+ return "skip";
481
+ });
482
+ file.data["mdx-export"].push({
483
+ name: "extractedReferences",
484
+ value: urls
485
+ });
486
+ }
487
+ if (includeProcessedMarkdown) {
488
+ const processor = getStringifyProcessor();
489
+ const markdown = (0, import_mdast_util_to_markdown.toMarkdown)(tree, {
490
+ ...processor.data("settings"),
491
+ // from https://github.com/remarkjs/remark/blob/main/packages/remark-stringify/lib/index.js
492
+ extensions: processor.data("toMarkdownExtensions") || []
493
+ });
494
+ file.data["mdx-export"].push({
495
+ name: "_markdown",
496
+ value: markdown
497
+ });
498
+ }
499
+ if (includeMDAST) {
500
+ const options = includeMDAST === true ? {} : includeMDAST;
501
+ const mdast = JSON.stringify(
502
+ options.removePosition ? (0, import_unist_util_remove_position.removePosition)(structuredClone(tree)) : tree
503
+ );
504
+ file.data["mdx-export"].push({
505
+ name: "_mdast",
506
+ value: mdast
507
+ });
508
+ }
509
+ for (const { name, value } of file.data["mdx-export"]) {
510
+ tree.children.unshift(getMdastExport(name, value));
511
+ }
512
+ file.data["mdx-export"] = [];
513
+ for (const name of valueToExport) {
514
+ if (!(name in file.data)) continue;
515
+ tree.children.unshift(getMdastExport(name, file.data[name]));
516
+ }
517
+ };
518
+ }
519
+ function getMdastExport(name, value) {
520
+ return {
521
+ type: "mdxjsEsm",
522
+ value: "",
523
+ data: {
524
+ estree: {
525
+ type: "Program",
526
+ sourceType: "module",
527
+ body: [
528
+ {
529
+ type: "ExportNamedDeclaration",
530
+ attributes: [],
531
+ specifiers: [],
532
+ source: null,
533
+ declaration: {
534
+ type: "VariableDeclaration",
535
+ kind: "let",
536
+ declarations: [
537
+ {
538
+ type: "VariableDeclarator",
539
+ id: {
540
+ type: "Identifier",
541
+ name
542
+ },
543
+ init: (0, import_estree_util_value_to_estree.valueToEstree)(value)
544
+ }
545
+ ]
546
+ }
547
+ }
548
+ ]
549
+ }
550
+ }
551
+ };
552
+ }
553
+
554
+ // src/loaders/mdx/build-mdx.ts
555
+ async function buildMDX(core, collection, {
556
+ filePath,
557
+ frontmatter,
558
+ source,
559
+ _compiler,
560
+ environment,
561
+ isDevelopment
562
+ }) {
563
+ const mdxOptions = await core.getConfig().getMDXOptions(collection, environment);
564
+ function getProcessor(format) {
565
+ const cache = core.cache;
566
+ const key = `build-mdx:${collection?.name ?? "global"}:${format}`;
567
+ let processor = cache.get(key);
568
+ if (!processor) {
569
+ const postprocessOptions = {
570
+ _format: format,
571
+ ...collection?.postprocess,
572
+ valueToExport: [
573
+ ...collection?.postprocess?.valueToExport ?? [],
574
+ "structuredData",
575
+ "frontmatter"
576
+ ]
577
+ };
578
+ processor = (0, import_mdx.createProcessor)({
579
+ outputFormat: "program",
580
+ development: isDevelopment,
581
+ ...mdxOptions,
582
+ remarkPlugins: [
583
+ remarkInclude,
584
+ ...mdxOptions.remarkPlugins ?? [],
585
+ [remarkPostprocess, postprocessOptions]
586
+ ],
587
+ format
588
+ });
589
+ cache.set(key, processor);
590
+ }
591
+ return processor;
592
+ }
593
+ let vfile = new import_vfile.VFile({
594
+ value: source,
595
+ path: filePath,
596
+ data: { frontmatter, _compiler, _getProcessor: getProcessor }
597
+ });
598
+ if (collection) {
599
+ vfile = await core.transformVFile({ collection, filePath, source }, vfile);
600
+ }
601
+ return getProcessor(filePath.endsWith(".mdx") ? "mdx" : "md").process(vfile);
602
+ }
603
+
604
+ // src/runtime/dynamic.ts
605
+ var import_client = require("@fumadocs/mdx-remote/client");
606
+ var import_node_url = require("url");
607
+ var import_promises3 = __toESM(require("fs/promises"), 1);
608
+
609
+ // src/runtime/server.ts
610
+ var path2 = __toESM(require("path"), 1);
611
+ function fromConfig() {
612
+ function fileInfo(file, base) {
613
+ if (file.startsWith("./")) {
614
+ file = file.slice(2);
615
+ }
616
+ return {
617
+ path: file,
618
+ fullPath: path2.join(base, file)
619
+ };
620
+ }
621
+ function mapDocData(entry) {
622
+ return {
623
+ body: entry.default,
624
+ toc: entry.toc,
625
+ extractedReferences: entry.extractedReferences,
626
+ structuredData: entry.structuredData,
627
+ lastModified: entry.lastModified,
628
+ _exports: entry
629
+ };
630
+ }
631
+ return {
632
+ async doc(_name, base, glob) {
633
+ const out = await Promise.all(
634
+ Object.entries(glob).map(async ([k, v]) => {
635
+ const data = typeof v === "function" ? await v() : v;
636
+ return {
637
+ ...mapDocData(data),
638
+ ...data.frontmatter,
639
+ ...createDocMethods(fileInfo(k, base), () => data)
640
+ };
641
+ })
642
+ );
643
+ return out;
644
+ },
645
+ async docLazy(_name, base, head, body) {
646
+ const out = await Promise.all(
647
+ Object.entries(head).map(async ([k, v]) => {
648
+ const data = typeof v === "function" ? await v() : v;
649
+ const content = body[k];
650
+ return {
651
+ ...data,
652
+ ...createDocMethods(fileInfo(k, base), content),
653
+ async load() {
654
+ return mapDocData(await content());
655
+ }
656
+ };
657
+ })
658
+ );
659
+ return out;
660
+ },
661
+ async meta(_name, base, glob) {
662
+ const out = await Promise.all(
663
+ Object.entries(glob).map(async ([k, v]) => {
664
+ const data = typeof v === "function" ? await v() : v;
665
+ return {
666
+ info: fileInfo(k, base),
667
+ ...data
668
+ };
669
+ })
670
+ );
671
+ return out;
672
+ },
673
+ async docs(name, base, metaGlob, docGlob) {
674
+ const entry = {
675
+ docs: await this.doc(name, base, docGlob),
676
+ meta: await this.meta(name, base, metaGlob),
677
+ toFumadocsSource() {
678
+ return toFumadocsSource(this.docs, this.meta);
679
+ }
680
+ };
681
+ return entry;
682
+ },
683
+ async docsLazy(name, base, metaGlob, docHeadGlob, docBodyGlob) {
684
+ const entry = {
685
+ docs: await this.docLazy(name, base, docHeadGlob, docBodyGlob),
686
+ meta: await this.meta(name, base, metaGlob),
687
+ toFumadocsSource() {
688
+ return toFumadocsSource(this.docs, this.meta);
689
+ }
690
+ };
691
+ return entry;
692
+ }
693
+ };
694
+ }
695
+ function toFumadocsSource(pages, metas) {
696
+ const files = [];
697
+ for (const entry of pages) {
698
+ files.push({
699
+ type: "page",
700
+ path: entry.info.path,
701
+ absolutePath: entry.info.fullPath,
702
+ data: entry
703
+ });
704
+ }
705
+ for (const entry of metas) {
706
+ files.push({
707
+ type: "meta",
708
+ path: entry.info.path,
709
+ absolutePath: entry.info.fullPath,
710
+ data: entry
711
+ });
712
+ }
713
+ return {
714
+ files
715
+ };
716
+ }
717
+ function createDocMethods(info, load2) {
718
+ return {
719
+ info,
720
+ async getText(type) {
721
+ if (type === "raw") {
722
+ const fs5 = await import("fs/promises");
723
+ return (await fs5.readFile(info.fullPath)).toString();
724
+ }
725
+ const data = await load2();
726
+ if (typeof data._markdown !== "string")
727
+ throw new Error(
728
+ "getText('processed') requires `includeProcessedMarkdown` to be enabled in your collection config."
729
+ );
730
+ return data._markdown;
731
+ },
732
+ async getMDAST() {
733
+ const data = await load2();
734
+ if (!data._mdast)
735
+ throw new Error(
736
+ "getMDAST() requires `includeMDAST` to be enabled in your collection config."
737
+ );
738
+ return JSON.parse(data._mdast);
739
+ }
740
+ };
741
+ }
742
+
743
+ // src/core.ts
744
+ var import_node_path2 = __toESM(require("path"), 1);
745
+ var import_promises2 = __toESM(require("fs/promises"), 1);
746
+
747
+ // src/utils/codegen/cache.ts
748
+ var import_lru_cache = require("lru-cache");
749
+ var import_promises = __toESM(require("fs/promises"), 1);
750
+ var import_node_path = __toESM(require("path"), 1);
751
+ var map = new import_lru_cache.LRUCache({
752
+ max: 100
753
+ });
754
+ function toFullPath(file) {
755
+ if (import_node_path.default.isAbsolute(file)) {
756
+ return import_node_path.default.relative(process.cwd(), file);
757
+ }
758
+ return file;
759
+ }
760
+ function removeFileCache(file) {
761
+ map.delete(toFullPath(file));
762
+ }
763
+
764
+ // src/utils/validation.ts
765
+ var ValidationError = class extends Error {
766
+ constructor(message, issues) {
767
+ super(
768
+ `${message}:
769
+ ${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`
770
+ );
771
+ this.title = message;
772
+ this.issues = issues;
773
+ }
774
+ async toStringFormatted() {
775
+ const picocolors = await import("picocolors");
776
+ return [
777
+ picocolors.bold(`[MDX] ${this.title}:`),
778
+ ...this.issues.map(
779
+ (issue) => picocolors.redBright(
780
+ `- ${picocolors.bold(issue.path?.join(".") ?? "*")}: ${issue.message}`
781
+ )
782
+ )
783
+ ].join("\n");
784
+ }
785
+ };
786
+ async function validate(schema, data, context, errorMessage) {
787
+ if (typeof schema === "function" && !("~standard" in schema)) {
788
+ schema = schema(context);
789
+ }
790
+ if ("~standard" in schema) {
791
+ const result = await schema["~standard"].validate(
792
+ data
793
+ );
794
+ if (result.issues) {
795
+ throw new ValidationError(errorMessage, result.issues);
796
+ }
797
+ return result.value;
798
+ }
799
+ return data;
800
+ }
801
+
802
+ // src/core.ts
803
+ async function getPlugins(pluginOptions) {
804
+ const plugins = [];
805
+ for await (const option of pluginOptions) {
806
+ if (!option) continue;
807
+ if (Array.isArray(option)) plugins.push(...await getPlugins(option));
808
+ else plugins.push(option);
809
+ }
810
+ return plugins;
811
+ }
812
+ function createCore(options, defaultPlugins = []) {
813
+ let config;
814
+ let plugins;
815
+ async function transformMetadata({
816
+ collection,
817
+ filePath,
818
+ source
819
+ }, data) {
820
+ if (collection.schema) {
821
+ data = await validate(
822
+ collection.schema,
823
+ data,
824
+ { path: filePath, source },
825
+ collection.type === "doc" ? `invalid frontmatter in ${filePath}` : `invalid data in ${filePath}`
826
+ );
827
+ }
828
+ return data;
829
+ }
830
+ const core = {
831
+ _options: options,
832
+ /**
833
+ * Convenient cache store, reset when config changes
834
+ */
835
+ cache: /* @__PURE__ */ new Map(),
836
+ async init({ config: newConfig }) {
837
+ config = await newConfig;
838
+ this.cache.clear();
839
+ plugins = await getPlugins([
840
+ ...defaultPlugins,
841
+ ...config.global.plugins ?? []
842
+ ]);
843
+ for (const plugin of plugins) {
844
+ const out = await plugin.config?.call(pluginContext, config);
845
+ if (out) config = out;
846
+ }
847
+ return this;
848
+ },
849
+ getConfig() {
850
+ return config;
851
+ },
852
+ /**
853
+ * The file path of compiled config file, the file may not exist (e.g. on Vite, or still compiling)
854
+ */
855
+ getCompiledConfigPath() {
856
+ return import_node_path2.default.join(options.outDir, "source.config.mjs");
857
+ },
858
+ async initServer(server) {
859
+ server.watcher?.on("all", async (event, file) => {
860
+ if (event === "change") removeFileCache(file);
861
+ });
862
+ for (const plugin of plugins) {
863
+ await plugin.configureServer?.call(pluginContext, server);
864
+ }
865
+ },
866
+ async emit({ filterPlugin = () => true } = {}) {
867
+ return (await Promise.all(
868
+ plugins.map((plugin) => {
869
+ if (!filterPlugin(plugin) || !plugin.emit) return [];
870
+ return plugin.emit.call(pluginContext);
871
+ })
872
+ )).flat();
873
+ },
874
+ async emitAndWrite(emitOptions) {
875
+ const start = performance.now();
876
+ const out = await this.emit(emitOptions);
877
+ await Promise.all(
878
+ out.map(async (entry) => {
879
+ const file = import_node_path2.default.join(options.outDir, entry.path);
880
+ await import_promises2.default.mkdir(import_node_path2.default.dirname(file), { recursive: true });
881
+ await import_promises2.default.writeFile(file, entry.content);
882
+ })
883
+ );
884
+ console.log(`[MDX] generated files in ${performance.now() - start}ms`);
885
+ },
886
+ async transformMeta(options2, data) {
887
+ const ctx = {
888
+ ...pluginContext,
889
+ ...options2
890
+ };
891
+ data = await transformMetadata(options2, data);
892
+ for (const plugin of plugins) {
893
+ if (plugin.meta?.transform)
894
+ data = await plugin.meta.transform.call(ctx, data) ?? data;
895
+ }
896
+ return data;
897
+ },
898
+ async transformFrontmatter(options2, data) {
899
+ const ctx = {
900
+ ...pluginContext,
901
+ ...options2
902
+ };
903
+ data = await transformMetadata(options2, data);
904
+ for (const plugin of plugins) {
905
+ if (plugin.doc?.frontmatter)
906
+ data = await plugin.doc.frontmatter.call(ctx, data) ?? data;
907
+ }
908
+ return data;
909
+ },
910
+ async transformVFile(options2, file) {
911
+ const ctx = {
912
+ ...pluginContext,
913
+ ...options2
914
+ };
915
+ for (const plugin of plugins) {
916
+ if (plugin.doc?.vfile)
917
+ file = await plugin.doc.vfile.call(ctx, file) ?? file;
918
+ }
919
+ return file;
920
+ }
921
+ };
922
+ const pluginContext = {
923
+ core,
924
+ ...options
925
+ };
926
+ return core;
927
+ }
928
+
929
+ // src/runtime/dynamic.ts
930
+ async function fromConfigDynamic(configExports, coreOptions) {
931
+ const core = await createCore(coreOptions).init({
932
+ config: buildConfig(configExports)
933
+ });
934
+ const create = fromConfig();
935
+ function getDocCollection(name) {
936
+ const collection = core.getConfig().getCollection(name);
937
+ if (!collection) return;
938
+ if (collection.type === "docs") return collection.docs;
939
+ else if (collection.type === "doc") return collection;
940
+ }
941
+ function convertLazyEntries(collection, entries) {
942
+ const head = {};
943
+ const body = {};
944
+ async function compile({ info, data }) {
945
+ let content = (await import_promises3.default.readFile(info.fullPath)).toString();
946
+ content = fumaMatter(content).content;
947
+ const compiled = await buildMDX(core, collection, {
948
+ filePath: info.fullPath,
949
+ source: content,
950
+ frontmatter: data,
951
+ isDevelopment: false,
952
+ environment: "runtime"
953
+ });
954
+ return await (0, import_client.executeMdx)(String(compiled.value), {
955
+ baseUrl: (0, import_node_url.pathToFileURL)(info.fullPath)
956
+ });
957
+ }
958
+ for (const entry of entries) {
959
+ head[entry.info.path] = () => entry.data;
960
+ let cachedResult;
961
+ body[entry.info.path] = () => cachedResult ??= compile(entry);
962
+ }
963
+ return { head, body };
964
+ }
965
+ return {
966
+ async doc(name, base, entries) {
967
+ const collection = getDocCollection(name);
968
+ if (!collection)
969
+ throw new Error(`the doc collection ${name} doesn't exist.`);
970
+ const { head, body } = convertLazyEntries(collection, entries);
971
+ return create.docLazy(name, base, head, body);
972
+ },
973
+ async docs(name, base, meta, entries) {
974
+ const collection = getDocCollection(name);
975
+ if (!collection)
976
+ throw new Error(`the doc collection ${name} doesn't exist.`);
977
+ const docs = convertLazyEntries(collection, entries);
978
+ return create.docsLazy(name, base, meta, docs.head, docs.body);
979
+ }
980
+ };
981
+ }
982
+ // Annotate the CommonJS export names for ESM import in node:
983
+ 0 && (module.exports = {
984
+ fromConfigDynamic
985
+ });