fumadocs-mdx 13.0.8 → 14.0.1

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 (111) hide show
  1. package/dist/bin.cjs +985 -893
  2. package/dist/bin.js +3 -3
  3. package/dist/build-mdx-6UAK5FF5.js +8 -0
  4. package/dist/bun/index.cjs +613 -471
  5. package/dist/bun/index.d.cts +9 -2
  6. package/dist/bun/index.d.ts +9 -2
  7. package/dist/bun/index.js +15 -14
  8. package/dist/chunk-4JSFLXXT.js +8 -0
  9. package/dist/chunk-5OBUOALK.js +141 -0
  10. package/dist/{chunk-2E2JCOSO.js → chunk-6NISOLQ6.js} +16 -44
  11. package/dist/chunk-7UKSZSPY.js +331 -0
  12. package/dist/chunk-BEBCWQC7.js +224 -0
  13. package/dist/chunk-E5DJTSIM.js +86 -0
  14. package/dist/{chunk-K5ZLPEIQ.js → chunk-FBLMK4RS.js} +9 -6
  15. package/dist/chunk-IQGEFL2B.js +17 -0
  16. package/dist/{chunk-5FTSWCB4.js → chunk-K6HCOGOX.js} +9 -11
  17. package/dist/{chunk-QXHN25N3.js → chunk-MTTISKQJ.js} +6 -6
  18. package/dist/{chunk-3J3WL7WN.js → chunk-SLY7WXTX.js} +71 -58
  19. package/dist/chunk-TYJDYTKH.js +85 -0
  20. package/dist/chunk-WBIHDYMN.js +126 -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 +7 -1
  24. package/dist/config/index.d.ts +7 -1
  25. package/dist/config/index.js +5 -5
  26. package/dist/core-B9ZoS6sA.d.ts +341 -0
  27. package/dist/core-DTuP23zu.d.cts +341 -0
  28. package/dist/index-BD8Woo4m.d.cts +8 -0
  29. package/dist/index-CNOvhtOn.d.ts +8 -0
  30. package/dist/index.d.cts +38 -56
  31. package/dist/index.d.ts +38 -56
  32. package/dist/load-from-file-5HUQN36V.js +8 -0
  33. package/dist/next/index.cjs +763 -473
  34. package/dist/next/index.d.cts +16 -1
  35. package/dist/next/index.d.ts +16 -1
  36. package/dist/next/index.js +80 -281
  37. package/dist/node/loader.cjs +764 -627
  38. package/dist/node/loader.js +10 -11
  39. package/dist/plugins/index-file.cjs +495 -0
  40. package/dist/plugins/index-file.d.cts +14 -0
  41. package/dist/plugins/index-file.d.ts +14 -0
  42. package/dist/plugins/index-file.js +8 -0
  43. package/dist/plugins/json-schema.d.cts +9 -2
  44. package/dist/plugins/json-schema.d.ts +9 -2
  45. package/dist/plugins/last-modified.cjs +110 -0
  46. package/dist/plugins/last-modified.d.cts +37 -0
  47. package/dist/plugins/last-modified.d.ts +37 -0
  48. package/dist/plugins/last-modified.js +74 -0
  49. package/dist/runtime/browser.cjs +93 -0
  50. package/dist/runtime/browser.d.cts +53 -0
  51. package/dist/runtime/browser.d.ts +53 -0
  52. package/dist/runtime/browser.js +67 -0
  53. package/dist/runtime/dynamic.cjs +1023 -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 +79 -0
  57. package/dist/runtime/server.cjs +176 -0
  58. package/dist/runtime/server.d.cts +14 -0
  59. package/dist/runtime/server.d.ts +14 -0
  60. package/dist/runtime/server.js +8 -0
  61. package/dist/runtime/types.cjs +18 -0
  62. package/dist/runtime/types.d.cts +61 -0
  63. package/dist/runtime/types.d.ts +61 -0
  64. package/dist/runtime/types.js +0 -0
  65. package/dist/vite/index.cjs +984 -621
  66. package/dist/vite/index.d.cts +17 -22
  67. package/dist/vite/index.d.ts +17 -22
  68. package/dist/vite/index.js +32 -222
  69. package/dist/webpack/mdx.cjs +647 -514
  70. package/dist/webpack/mdx.d.cts +15 -1
  71. package/dist/webpack/mdx.d.ts +15 -1
  72. package/dist/webpack/mdx.js +12 -17
  73. package/dist/webpack/meta.cjs +360 -231
  74. package/dist/webpack/meta.d.cts +15 -1
  75. package/dist/webpack/meta.d.ts +15 -1
  76. package/dist/webpack/meta.js +13 -15
  77. package/package.json +15 -32
  78. package/dist/build-mdx-BjXOmv0b.d.cts +0 -53
  79. package/dist/build-mdx-CY5UldCO.d.ts +0 -53
  80. package/dist/chunk-2AQRQXSO.js +0 -119
  81. package/dist/chunk-CXA4JO4Z.js +0 -45
  82. package/dist/chunk-DMJ6I4C3.js +0 -76
  83. package/dist/chunk-FSZMKRVH.js +0 -80
  84. package/dist/chunk-II3H5ZVZ.js +0 -77
  85. package/dist/chunk-KILFIBVW.js +0 -75
  86. package/dist/chunk-NVRDCY6Z.js +0 -30
  87. package/dist/chunk-VUEZTR2H.js +0 -26
  88. package/dist/core-DB7TdlyC.d.cts +0 -234
  89. package/dist/core-DB7TdlyC.d.ts +0 -234
  90. package/dist/index-D7s7kCc2.d.cts +0 -7
  91. package/dist/index-D7s7kCc2.d.ts +0 -7
  92. package/dist/load-from-file-AVYOFOI7.js +0 -7
  93. package/dist/preset-ZMP6U62C.js +0 -6
  94. package/dist/runtime/next/async.cjs +0 -760
  95. package/dist/runtime/next/async.d.cts +0 -19
  96. package/dist/runtime/next/async.d.ts +0 -19
  97. package/dist/runtime/next/async.js +0 -86
  98. package/dist/runtime/next/index.cjs +0 -136
  99. package/dist/runtime/next/index.d.cts +0 -33
  100. package/dist/runtime/next/index.d.ts +0 -33
  101. package/dist/runtime/next/index.js +0 -11
  102. package/dist/runtime/vite/browser.cjs +0 -107
  103. package/dist/runtime/vite/browser.d.cts +0 -59
  104. package/dist/runtime/vite/browser.d.ts +0 -59
  105. package/dist/runtime/vite/browser.js +0 -11
  106. package/dist/runtime/vite/server.cjs +0 -243
  107. package/dist/runtime/vite/server.d.cts +0 -30
  108. package/dist/runtime/vite/server.d.ts +0 -30
  109. package/dist/runtime/vite/server.js +0 -111
  110. package/dist/types-Bnh9n7mj.d.cts +0 -45
  111. package/dist/types-ey1AZqrg.d.ts +0 -45
@@ -30,207 +30,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
- // src/loaders/mdx/preset.ts
34
- var preset_exports = {};
35
- __export(preset_exports, {
36
- getDefaultMDXOptions: () => getDefaultMDXOptions
37
- });
38
- function pluginOption(def, options = []) {
39
- const list = def(Array.isArray(options) ? options : []).filter(
40
- Boolean
41
- );
42
- if (typeof options === "function") {
43
- return options(list);
44
- }
45
- return list;
46
- }
47
- function getDefaultMDXOptions({
48
- valueToExport = [],
49
- rehypeCodeOptions,
50
- remarkImageOptions,
51
- remarkHeadingOptions,
52
- remarkStructureOptions,
53
- remarkCodeTabOptions,
54
- remarkNpmOptions,
55
- _withoutBundler = false,
56
- ...mdxOptions
57
- }) {
58
- const remarkPlugins = pluginOption(
59
- (v) => [
60
- plugins.remarkGfm,
61
- [
62
- plugins.remarkHeading,
63
- {
64
- generateToc: false,
65
- ...remarkHeadingOptions
66
- }
67
- ],
68
- remarkImageOptions !== false && [
69
- plugins.remarkImage,
70
- {
71
- ...remarkImageOptions,
72
- useImport: _withoutBundler ? false : remarkImageOptions?.useImport
73
- }
74
- ],
75
- "remarkCodeTab" in plugins && remarkCodeTabOptions !== false && [
76
- plugins.remarkCodeTab,
77
- remarkCodeTabOptions
78
- ],
79
- "remarkNpm" in plugins && remarkNpmOptions !== false && [plugins.remarkNpm, remarkNpmOptions],
80
- ...v,
81
- remarkStructureOptions !== false && [
82
- plugins.remarkStructure,
83
- remarkStructureOptions
84
- ],
85
- () => {
86
- return (_, file) => {
87
- file.data["mdx-export"] ??= [];
88
- for (const name of valueToExport) {
89
- if (name in file.data)
90
- file.data["mdx-export"].push({ name, value: file.data[name] });
91
- }
92
- };
93
- }
94
- ],
95
- mdxOptions.remarkPlugins
96
- );
97
- const rehypePlugins = pluginOption(
98
- (v) => [
99
- rehypeCodeOptions !== false && [plugins.rehypeCode, rehypeCodeOptions],
100
- ...v,
101
- plugins.rehypeToc
102
- ],
103
- mdxOptions.rehypePlugins
104
- );
105
- return {
106
- ...mdxOptions,
107
- outputFormat: _withoutBundler ? "function-body" : mdxOptions.outputFormat,
108
- remarkPlugins,
109
- rehypePlugins
110
- };
111
- }
112
- var plugins;
113
- var init_preset = __esm({
114
- "src/loaders/mdx/preset.ts"() {
115
- "use strict";
116
- plugins = __toESM(require("fumadocs-core/mdx-plugins"), 1);
117
- }
118
- });
119
-
120
- // src/config/build.ts
121
- function buildCollection(name, config) {
122
- if (config.type === "docs") {
123
- return {
124
- ...config,
125
- name,
126
- meta: buildPrimitiveCollection(name, config.meta),
127
- docs: buildPrimitiveCollection(name, config.docs)
128
- };
129
- }
130
- return buildPrimitiveCollection(name, config);
131
- }
132
- function buildPrimitiveCollection(name, { files, ...config }) {
133
- const supportedFormats = SupportedFormats[config.type];
134
- const patterns = files ?? [`**/*.{${supportedFormats.join(",")}}`];
135
- let matchers;
136
- return {
137
- ...config,
138
- name,
139
- patterns,
140
- isFileSupported(filePath) {
141
- return supportedFormats.some((format) => filePath.endsWith(`.${format}`));
142
- },
143
- hasFile(filePath) {
144
- matchers ??= (Array.isArray(config.dir) ? config.dir : [config.dir]).map(
145
- (dir) => (0, import_picomatch.default)(patterns, {
146
- cwd: dir
147
- })
148
- );
149
- return this.isFileSupported(filePath) && matchers.some((matcher) => matcher(filePath));
150
- }
151
- };
152
- }
153
- function buildConfig(config) {
154
- const collections = /* @__PURE__ */ new Map();
155
- const loaded = {};
156
- for (const [k, v] of Object.entries(config)) {
157
- if (!v) {
158
- continue;
159
- }
160
- if (typeof v === "object" && "type" in v) {
161
- if (v.type === "docs") {
162
- collections.set(k, buildCollection(k, v));
163
- continue;
164
- }
165
- if (v.type === "doc" || v.type === "meta") {
166
- collections.set(
167
- k,
168
- buildCollection(k, v)
169
- );
170
- continue;
171
- }
172
- }
173
- if (k === "default" && v) {
174
- Object.assign(loaded, v);
175
- continue;
176
- }
177
- throw new Error(
178
- `Unknown export "${k}", you can only export collections from source configuration file.`
179
- );
180
- }
181
- if (loaded.collections) {
182
- for (const [k, v] of Object.entries(loaded.collections)) {
183
- collections.set(k, buildCollection(k, v));
184
- }
185
- }
186
- const mdxOptionsCache = /* @__PURE__ */ new Map();
187
- return {
188
- global: loaded,
189
- collectionList: Array.from(collections.values()),
190
- getCollection(name) {
191
- return collections.get(name);
192
- },
193
- async getDefaultMDXOptions(mode = "default") {
194
- const cached = mdxOptionsCache.get(mode);
195
- if (cached) return cached;
196
- const input = this.global.mdxOptions;
197
- async function uncached() {
198
- const options = typeof input === "function" ? await input() : input;
199
- const { getDefaultMDXOptions: getDefaultMDXOptions2 } = await Promise.resolve().then(() => (init_preset(), preset_exports));
200
- if (options?.preset === "minimal") return options;
201
- return getDefaultMDXOptions2({
202
- ...options,
203
- _withoutBundler: mode === "remote"
204
- });
205
- }
206
- const result = uncached();
207
- mdxOptionsCache.set(mode, result);
208
- return result;
209
- }
210
- };
211
- }
212
- var import_picomatch, SupportedFormats;
213
- var init_build = __esm({
214
- "src/config/build.ts"() {
215
- "use strict";
216
- import_picomatch = __toESM(require("picomatch"), 1);
217
- SupportedFormats = {
218
- doc: ["mdx", "md"],
219
- meta: ["json", "yaml"]
220
- };
221
- }
222
- });
223
-
224
- // src/bun/index.ts
225
- var bun_exports = {};
226
- __export(bun_exports, {
227
- createMdxPlugin: () => createMdxPlugin
228
- });
229
- module.exports = __toCommonJS(bun_exports);
230
-
231
33
  // src/utils/fuma-matter.ts
232
- var import_js_yaml = require("js-yaml");
233
- var regex = /^---\r?\n(.+?)\r?\n---\r?\n/s;
234
34
  function fumaMatter(input) {
235
35
  const output = { matter: "", data: {}, content: input };
236
36
  const match = regex.exec(input);
@@ -243,80 +43,16 @@ function fumaMatter(input) {
243
43
  output.data = loaded ?? {};
244
44
  return output;
245
45
  }
246
-
247
- // src/utils/validation.ts
248
- var import_picocolors = __toESM(require("picocolors"), 1);
249
- var ValidationError = class extends Error {
250
- constructor(message, issues) {
251
- super(
252
- `${message}:
253
- ${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`
254
- );
255
- this.title = message;
256
- this.issues = issues;
257
- }
258
- toStringFormatted() {
259
- return [
260
- import_picocolors.default.bold(`[MDX] ${this.title}:`),
261
- ...this.issues.map(
262
- (issue) => import_picocolors.default.redBright(
263
- `- ${import_picocolors.default.bold(issue.path?.join(".") ?? "*")}: ${issue.message}`
264
- )
265
- )
266
- ].join("\n");
267
- }
268
- };
269
- async function validate(schema, data, context, errorMessage) {
270
- if (typeof schema === "function" && !("~standard" in schema)) {
271
- schema = schema(context);
272
- }
273
- if ("~standard" in schema) {
274
- const result = await schema["~standard"].validate(
275
- data
276
- );
277
- if (result.issues) {
278
- throw new ValidationError(errorMessage, result.issues);
279
- }
280
- return result.value;
281
- }
282
- return data;
283
- }
284
-
285
- // src/utils/git-timestamp.ts
286
- var import_node_path = __toESM(require("path"), 1);
287
- var import_tinyexec = require("tinyexec");
288
- var cache = /* @__PURE__ */ new Map();
289
- async function getGitTimestamp(file) {
290
- const cached = cache.get(file);
291
- if (cached) return cached;
292
- try {
293
- const out = await (0, import_tinyexec.x)(
294
- "git",
295
- ["log", "-1", '--pretty="%ai"', import_node_path.default.relative(process.cwd(), file)],
296
- {
297
- throwOnError: true
298
- }
299
- );
300
- const time = new Date(out.stdout);
301
- cache.set(file, time);
302
- return time;
303
- } catch {
304
- return;
46
+ var import_js_yaml, regex;
47
+ var init_fuma_matter = __esm({
48
+ "src/utils/fuma-matter.ts"() {
49
+ "use strict";
50
+ import_js_yaml = require("js-yaml");
51
+ regex = /^---\r?\n(.+?)\r?\n---\r?\n/s;
305
52
  }
306
- }
307
-
308
- // src/loaders/mdx/build-mdx.ts
309
- var import_mdx = require("@mdx-js/mdx");
310
-
311
- // src/loaders/mdx/remark-include.ts
312
- var import_unified = require("unified");
313
- var import_unist_util_visit2 = require("unist-util-visit");
314
- var path2 = __toESM(require("path"), 1);
315
- var fs = __toESM(require("fs/promises"), 1);
316
- var import_mdx_plugins = require("fumadocs-core/mdx-plugins");
53
+ });
317
54
 
318
55
  // src/loaders/mdx/remark-unravel.ts
319
- var import_unist_util_visit = require("unist-util-visit");
320
56
  function remarkMarkAndUnravel() {
321
57
  return (tree) => {
322
58
  (0, import_unist_util_visit.visit)(tree, function(node, index, parent) {
@@ -358,15 +94,28 @@ function remarkMarkAndUnravel() {
358
94
  });
359
95
  };
360
96
  }
97
+ var import_unist_util_visit;
98
+ var init_remark_unravel = __esm({
99
+ "src/loaders/mdx/remark-unravel.ts"() {
100
+ "use strict";
101
+ import_unist_util_visit = require("unist-util-visit");
102
+ }
103
+ });
104
+
105
+ // src/loaders/mdx/mdast-utils.ts
106
+ function flattenNode(node) {
107
+ if ("children" in node)
108
+ return node.children.map((child) => flattenNode(child)).join("");
109
+ if ("value" in node) return node.value;
110
+ return "";
111
+ }
112
+ var init_mdast_utils = __esm({
113
+ "src/loaders/mdx/mdast-utils.ts"() {
114
+ "use strict";
115
+ }
116
+ });
361
117
 
362
118
  // src/loaders/mdx/remark-include.ts
363
- var ElementLikeTypes = [
364
- "mdxJsxFlowElement",
365
- "mdxJsxTextElement",
366
- "containerDirective",
367
- "textDirective",
368
- "leafDirective"
369
- ];
370
119
  function isElementLike(node) {
371
120
  return ElementLikeTypes.includes(node.type);
372
121
  }
@@ -382,12 +131,6 @@ function parseElementAttributes(element) {
382
131
  }
383
132
  return element.attributes ?? {};
384
133
  }
385
- function flattenNode(node) {
386
- if ("children" in node)
387
- return node.children.map((child) => flattenNode(child)).join("");
388
- if ("value" in node) return node.value;
389
- return "";
390
- }
391
134
  function parseSpecifier(specifier) {
392
135
  const idx = specifier.lastIndexOf("#");
393
136
  if (idx === -1) return { file: specifier };
@@ -442,7 +185,7 @@ ${e instanceof Error ? e.message : String(e)}`,
442
185
  { cause: e }
443
186
  );
444
187
  }
445
- const ext = path2.extname(file);
188
+ const ext = path.extname(file);
446
189
  data._compiler?.addDependency(file);
447
190
  if (params.lang || ext !== ".md" && ext !== ".mdx") {
448
191
  const lang = params.lang ?? ext.slice(1);
@@ -475,7 +218,7 @@ ${e instanceof Error ? e.message : String(e)}`,
475
218
  } else {
476
219
  mdast = await baseProcessor.run(mdast);
477
220
  }
478
- await update(mdast, path2.dirname(file), data);
221
+ await update(mdast, path.dirname(file), data);
479
222
  return mdast;
480
223
  };
481
224
  async function update(tree, directory, data) {
@@ -487,7 +230,7 @@ ${e instanceof Error ? e.message : String(e)}`,
487
230
  if (specifier.length === 0) return "skip";
488
231
  const attributes = parseElementAttributes(node);
489
232
  const { file: relativePath, section } = parseSpecifier(specifier);
490
- const file = path2.resolve(
233
+ const file = path.resolve(
491
234
  "cwd" in attributes ? process.cwd() : directory,
492
235
  relativePath
493
236
  );
@@ -504,62 +247,96 @@ ${e instanceof Error ? e.message : String(e)}`,
504
247
  await Promise.all(queue);
505
248
  }
506
249
  return async (tree, file) => {
507
- await update(tree, path2.dirname(file.path), file.data);
250
+ await update(tree, path.dirname(file.path), file.data);
508
251
  };
509
252
  }
253
+ var import_unified, import_unist_util_visit2, path, fs, import_mdx_plugins, ElementLikeTypes;
254
+ var init_remark_include = __esm({
255
+ "src/loaders/mdx/remark-include.ts"() {
256
+ "use strict";
257
+ import_unified = require("unified");
258
+ import_unist_util_visit2 = require("unist-util-visit");
259
+ path = __toESM(require("path"), 1);
260
+ fs = __toESM(require("fs/promises"), 1);
261
+ init_fuma_matter();
262
+ import_mdx_plugins = require("fumadocs-core/mdx-plugins");
263
+ init_remark_unravel();
264
+ init_mdast_utils();
265
+ ElementLikeTypes = [
266
+ "mdxJsxFlowElement",
267
+ "mdxJsxTextElement",
268
+ "containerDirective",
269
+ "textDirective",
270
+ "leafDirective"
271
+ ];
272
+ }
273
+ });
510
274
 
511
275
  // src/loaders/mdx/remark-postprocess.ts
512
- var import_unist_util_visit3 = require("unist-util-visit");
513
- var import_mdast_util_to_markdown = require("mdast-util-to-markdown");
514
- var import_estree_util_value_to_estree = require("estree-util-value-to-estree");
515
- var import_unist_util_remove_position = require("unist-util-remove-position");
516
- var import_remark_mdx = __toESM(require("remark-mdx"), 1);
517
276
  function remarkPostprocess({
518
277
  _format,
519
278
  includeProcessedMarkdown = false,
520
279
  includeMDAST = false,
280
+ extractLinkReferences = false,
521
281
  valueToExport = []
522
282
  }) {
523
283
  let _stringifyProcessor;
524
284
  const getStringifyProcessor = () => {
525
- if (_format === "mdx") return this;
526
- return _stringifyProcessor ??= this().use(import_remark_mdx.default).freeze();
285
+ return _stringifyProcessor ??= _format === "mdx" ? this : (
286
+ // force Markdown processor to stringify MDX nodes
287
+ this().use(import_remark_mdx.default).freeze()
288
+ );
527
289
  };
528
290
  return (tree, file) => {
529
- let title;
530
- const urls = [];
531
- (0, import_unist_util_visit3.visit)(tree, ["heading", "link"], (node) => {
532
- if (node.type === "heading" && node.depth === 1) {
533
- title = flattenNode2(node);
534
- }
535
- if (node.type !== "link") return;
536
- urls.push({
537
- href: node.url
291
+ const frontmatter = file.data.frontmatter ??= {};
292
+ if (!frontmatter.title) {
293
+ (0, import_unist_util_visit3.visit)(tree, "heading", (node) => {
294
+ if (node.depth === 1) {
295
+ frontmatter.title = flattenNode(node);
296
+ return false;
297
+ }
298
+ });
299
+ }
300
+ file.data["mdx-export"] ??= [];
301
+ if (extractLinkReferences) {
302
+ const urls = [];
303
+ (0, import_unist_util_visit3.visit)(tree, "link", (node) => {
304
+ urls.push({
305
+ href: node.url
306
+ });
307
+ return "skip";
308
+ });
309
+ file.data["mdx-export"].push({
310
+ name: "extractedReferences",
311
+ value: urls
538
312
  });
539
- return "skip";
540
- });
541
- if (title) {
542
- file.data.frontmatter ??= {};
543
- if (!file.data.frontmatter.title) file.data.frontmatter.title = title;
544
313
  }
545
- file.data.extractedReferences = urls;
546
314
  if (includeProcessedMarkdown) {
547
315
  const processor = getStringifyProcessor();
548
- file.data._markdown = (0, import_mdast_util_to_markdown.toMarkdown)(tree, {
316
+ const markdown = (0, import_mdast_util_to_markdown.toMarkdown)(tree, {
549
317
  ...processor.data("settings"),
550
318
  // from https://github.com/remarkjs/remark/blob/main/packages/remark-stringify/lib/index.js
551
319
  extensions: processor.data("toMarkdownExtensions") || []
552
320
  });
321
+ file.data["mdx-export"].push({
322
+ name: "_markdown",
323
+ value: markdown
324
+ });
553
325
  }
554
326
  if (includeMDAST) {
555
327
  const options = includeMDAST === true ? {} : includeMDAST;
556
- file.data._mdast = JSON.stringify(
328
+ const mdast = JSON.stringify(
557
329
  options.removePosition ? (0, import_unist_util_remove_position.removePosition)(structuredClone(tree)) : tree
558
330
  );
331
+ file.data["mdx-export"].push({
332
+ name: "_mdast",
333
+ value: mdast
334
+ });
559
335
  }
560
- for (const { name, value } of file.data["mdx-export"] ?? []) {
336
+ for (const { name, value } of file.data["mdx-export"]) {
561
337
  tree.children.unshift(getMdastExport(name, value));
562
338
  }
339
+ file.data["mdx-export"] = [];
563
340
  for (const name of valueToExport) {
564
341
  if (!(name in file.data)) continue;
565
342
  tree.children.unshift(getMdastExport(name, file.data[name]));
@@ -600,68 +377,287 @@ function getMdastExport(name, value) {
600
377
  }
601
378
  };
602
379
  }
603
- function flattenNode2(node) {
604
- if ("children" in node)
605
- return node.children.map((child) => flattenNode2(child)).join("");
606
- if ("value" in node) return node.value;
607
- return "";
608
- }
380
+ var import_unist_util_visit3, import_mdast_util_to_markdown, import_estree_util_value_to_estree, import_unist_util_remove_position, import_remark_mdx;
381
+ var init_remark_postprocess = __esm({
382
+ "src/loaders/mdx/remark-postprocess.ts"() {
383
+ "use strict";
384
+ import_unist_util_visit3 = require("unist-util-visit");
385
+ import_mdast_util_to_markdown = require("mdast-util-to-markdown");
386
+ import_estree_util_value_to_estree = require("estree-util-value-to-estree");
387
+ import_unist_util_remove_position = require("unist-util-remove-position");
388
+ import_remark_mdx = __toESM(require("remark-mdx"), 1);
389
+ init_mdast_utils();
390
+ }
391
+ });
609
392
 
610
393
  // src/loaders/mdx/build-mdx.ts
611
- var cache2 = /* @__PURE__ */ new Map();
612
- async function buildMDX(cacheKey, source, options) {
613
- const { filePath, frontmatter, data, _compiler, ...rest } = options;
394
+ var build_mdx_exports = {};
395
+ __export(build_mdx_exports, {
396
+ buildMDX: () => buildMDX
397
+ });
398
+ async function buildMDX(core, collection, {
399
+ filePath,
400
+ frontmatter,
401
+ source,
402
+ _compiler,
403
+ environment,
404
+ isDevelopment
405
+ }) {
406
+ const mdxOptions = await core.getConfig().getMDXOptions(collection, environment);
614
407
  function getProcessor(format) {
615
- const key = `${cacheKey}:${format}`;
616
- let processor = cache2.get(key);
408
+ const cache = core.cache;
409
+ const key = `build-mdx:${collection?.name ?? "global"}:${format}`;
410
+ let processor = cache.get(key);
617
411
  if (!processor) {
412
+ const postprocessOptions = {
413
+ _format: format,
414
+ ...collection?.postprocess,
415
+ valueToExport: [
416
+ ...collection?.postprocess?.valueToExport ?? [],
417
+ "structuredData",
418
+ "frontmatter"
419
+ ]
420
+ };
618
421
  processor = (0, import_mdx.createProcessor)({
619
422
  outputFormat: "program",
620
- ...rest,
423
+ development: isDevelopment,
424
+ ...mdxOptions,
621
425
  remarkPlugins: [
622
426
  remarkInclude,
623
- ...rest.remarkPlugins ?? [],
624
- [
625
- remarkPostprocess,
626
- {
627
- _format: format,
628
- ...options.postprocess,
629
- valueToExport: [
630
- ...options.postprocess?.valueToExport ?? [],
631
- "structuredData",
632
- "extractedReferences",
633
- "frontmatter",
634
- "lastModified",
635
- "_markdown",
636
- "_mdast"
637
- ]
638
- }
639
- ]
427
+ ...mdxOptions.remarkPlugins ?? [],
428
+ [remarkPostprocess, postprocessOptions]
640
429
  ],
641
430
  format
642
431
  });
643
- cache2.set(key, processor);
432
+ cache.set(key, processor);
644
433
  }
645
434
  return processor;
646
435
  }
647
- return getProcessor(
648
- options.format ?? (filePath.endsWith(".mdx") ? "mdx" : "md")
649
- ).process({
436
+ let vfile = new import_vfile.VFile({
650
437
  value: source,
651
438
  path: filePath,
652
- data: {
653
- ...data,
654
- frontmatter,
655
- _compiler,
656
- _getProcessor: getProcessor
657
- }
439
+ data: { frontmatter, _compiler, _getProcessor: getProcessor }
658
440
  });
441
+ if (collection) {
442
+ vfile = await core.transformVFile({ collection, filePath, source }, vfile);
443
+ }
444
+ return getProcessor(filePath.endsWith(".mdx") ? "mdx" : "md").process(vfile);
445
+ }
446
+ var import_mdx, import_vfile;
447
+ var init_build_mdx = __esm({
448
+ "src/loaders/mdx/build-mdx.ts"() {
449
+ "use strict";
450
+ import_mdx = require("@mdx-js/mdx");
451
+ import_vfile = require("vfile");
452
+ init_remark_include();
453
+ init_remark_postprocess();
454
+ }
455
+ });
456
+
457
+ // src/config/preset.ts
458
+ function pluginOption(def, options = []) {
459
+ const list = def(Array.isArray(options) ? options : []).filter(
460
+ Boolean
461
+ );
462
+ if (typeof options === "function") {
463
+ return options(list);
464
+ }
465
+ return list;
466
+ }
467
+ function applyMdxPreset(options = {}) {
468
+ return async (environment = "bundler") => {
469
+ if (options.preset === "minimal") return options;
470
+ const plugins = await import("fumadocs-core/mdx-plugins");
471
+ const {
472
+ valueToExport = [],
473
+ rehypeCodeOptions,
474
+ remarkImageOptions,
475
+ remarkHeadingOptions,
476
+ remarkStructureOptions,
477
+ remarkCodeTabOptions,
478
+ remarkNpmOptions,
479
+ ...mdxOptions
480
+ } = options;
481
+ const remarkPlugins = pluginOption(
482
+ (v) => [
483
+ plugins.remarkGfm,
484
+ [
485
+ plugins.remarkHeading,
486
+ {
487
+ generateToc: false,
488
+ ...remarkHeadingOptions
489
+ }
490
+ ],
491
+ remarkImageOptions !== false && [
492
+ plugins.remarkImage,
493
+ {
494
+ ...remarkImageOptions,
495
+ useImport: remarkImageOptions?.useImport ?? environment === "bundler"
496
+ }
497
+ ],
498
+ "remarkCodeTab" in plugins && remarkCodeTabOptions !== false && [
499
+ plugins.remarkCodeTab,
500
+ remarkCodeTabOptions
501
+ ],
502
+ "remarkNpm" in plugins && remarkNpmOptions !== false && [plugins.remarkNpm, remarkNpmOptions],
503
+ ...v,
504
+ remarkStructureOptions !== false && [
505
+ plugins.remarkStructure,
506
+ remarkStructureOptions
507
+ ],
508
+ valueToExport.length > 0 && (() => {
509
+ return (_, file) => {
510
+ file.data["mdx-export"] ??= [];
511
+ for (const name of valueToExport) {
512
+ if (!(name in file.data)) continue;
513
+ file.data["mdx-export"].push({
514
+ name,
515
+ value: file.data[name]
516
+ });
517
+ }
518
+ };
519
+ })
520
+ ],
521
+ mdxOptions.remarkPlugins
522
+ );
523
+ const rehypePlugins = pluginOption(
524
+ (v) => [
525
+ rehypeCodeOptions !== false && [plugins.rehypeCode, rehypeCodeOptions],
526
+ ...v,
527
+ plugins.rehypeToc
528
+ ],
529
+ mdxOptions.rehypePlugins
530
+ );
531
+ return {
532
+ ...mdxOptions,
533
+ outputFormat: environment === "runtime" ? "function-body" : mdxOptions.outputFormat,
534
+ remarkPlugins,
535
+ rehypePlugins
536
+ };
537
+ };
659
538
  }
539
+ var init_preset = __esm({
540
+ "src/config/preset.ts"() {
541
+ "use strict";
542
+ }
543
+ });
544
+
545
+ // src/config/build.ts
546
+ function buildCollection(name, config) {
547
+ if (config.type === "docs") {
548
+ return {
549
+ ...config,
550
+ name,
551
+ meta: buildPrimitiveCollection(name, config.meta),
552
+ docs: buildPrimitiveCollection(name, config.docs),
553
+ hasFile(filePath) {
554
+ return this.docs.hasFile(filePath) || this.meta.hasFile(filePath);
555
+ }
556
+ };
557
+ }
558
+ return buildPrimitiveCollection(name, config);
559
+ }
560
+ function buildPrimitiveCollection(name, { files, ...config }) {
561
+ const supportedFormats = SupportedFormats[config.type];
562
+ const patterns = files ?? [`**/*.{${supportedFormats.join(",")}}`];
563
+ let matchers;
564
+ return {
565
+ ...config,
566
+ name,
567
+ patterns,
568
+ isFileSupported(filePath) {
569
+ return supportedFormats.some((format) => filePath.endsWith(`.${format}`));
570
+ },
571
+ hasFile(filePath) {
572
+ matchers ??= (Array.isArray(config.dir) ? config.dir : [config.dir]).map(
573
+ (dir) => (0, import_picomatch.default)(patterns, {
574
+ cwd: dir
575
+ })
576
+ );
577
+ return this.isFileSupported(filePath) && matchers.some((matcher) => matcher(filePath));
578
+ }
579
+ };
580
+ }
581
+ function buildConfig(config) {
582
+ const collections = /* @__PURE__ */ new Map();
583
+ const loaded = {};
584
+ for (const [k, v] of Object.entries(config)) {
585
+ if (!v) {
586
+ continue;
587
+ }
588
+ if (typeof v === "object" && "type" in v) {
589
+ if (v.type === "docs") {
590
+ collections.set(k, buildCollection(k, v));
591
+ continue;
592
+ }
593
+ if (v.type === "doc" || v.type === "meta") {
594
+ collections.set(
595
+ k,
596
+ buildCollection(k, v)
597
+ );
598
+ continue;
599
+ }
600
+ }
601
+ if (k === "default" && v) {
602
+ Object.assign(loaded, v);
603
+ continue;
604
+ }
605
+ throw new Error(
606
+ `Unknown export "${k}", you can only export collections from source configuration file.`
607
+ );
608
+ }
609
+ const mdxOptionsCache = /* @__PURE__ */ new Map();
610
+ return {
611
+ global: loaded,
612
+ collectionList: Array.from(collections.values()),
613
+ getCollection(name) {
614
+ return collections.get(name);
615
+ },
616
+ getMDXOptions(collection, environment = "bundler") {
617
+ const key = collection ? `${environment}:${collection.name}` : environment;
618
+ const cached = mdxOptionsCache.get(key);
619
+ if (cached) return cached;
620
+ let result;
621
+ if (collection?.mdxOptions) {
622
+ const optionsFn = collection.mdxOptions;
623
+ result = typeof optionsFn === "function" ? optionsFn(environment) : optionsFn;
624
+ } else {
625
+ result = (async () => {
626
+ const optionsFn = this.global.mdxOptions;
627
+ const options = typeof optionsFn === "function" ? await optionsFn() : optionsFn;
628
+ return applyMdxPreset(options)(environment);
629
+ })();
630
+ }
631
+ mdxOptionsCache.set(key, result);
632
+ return result;
633
+ }
634
+ };
635
+ }
636
+ var import_picomatch, SupportedFormats;
637
+ var init_build = __esm({
638
+ "src/config/build.ts"() {
639
+ "use strict";
640
+ import_picomatch = __toESM(require("picomatch"), 1);
641
+ init_preset();
642
+ SupportedFormats = {
643
+ doc: ["mdx", "md"],
644
+ meta: ["json", "yaml"]
645
+ };
646
+ }
647
+ });
648
+
649
+ // src/bun/index.ts
650
+ var bun_exports = {};
651
+ __export(bun_exports, {
652
+ createMdxPlugin: () => createMdxPlugin
653
+ });
654
+ module.exports = __toCommonJS(bun_exports);
660
655
 
661
656
  // src/loaders/mdx/index.ts
657
+ init_fuma_matter();
662
658
  var import_zod = require("zod");
663
659
  var import_promises = __toESM(require("fs/promises"), 1);
664
- var import_node_path2 = __toESM(require("path"), 1);
660
+ var import_node_path = __toESM(require("path"), 1);
665
661
  var import_node_crypto = require("crypto");
666
662
 
667
663
  // src/loaders/index.ts
@@ -688,20 +684,20 @@ function createMdxLoader(configLoader) {
688
684
  compiler,
689
685
  filePath
690
686
  }) {
687
+ const config = await configLoader.getConfig();
691
688
  const value = await getSource();
692
689
  const matter = fumaMatter(value);
693
690
  const parsed = querySchema.parse(query);
694
- const config = await configLoader.getConfig();
695
691
  let after;
696
692
  if (!isDevelopment && config.global.experimentalBuildCache) {
697
693
  const cacheDir = config.global.experimentalBuildCache;
698
694
  const cacheKey = `${parsed.hash}_${parsed.collection ?? "global"}_${generateCacheHash(filePath)}`;
699
- const cached = await import_promises.default.readFile(import_node_path2.default.join(cacheDir, cacheKey)).then((content) => cacheEntry.parse(JSON.parse(content.toString()))).catch(() => null);
695
+ const cached = await import_promises.default.readFile(import_node_path.default.join(cacheDir, cacheKey)).then((content) => cacheEntry.parse(JSON.parse(content.toString()))).catch(() => null);
700
696
  if (cached && cached.hash === generateCacheHash(value)) return cached;
701
697
  after = async () => {
702
698
  await import_promises.default.mkdir(cacheDir, { recursive: true });
703
699
  await import_promises.default.writeFile(
704
- import_node_path2.default.join(cacheDir, cacheKey),
700
+ import_node_path.default.join(cacheDir, cacheKey),
705
701
  JSON.stringify({
706
702
  ...out,
707
703
  hash: generateCacheHash(value)
@@ -719,15 +715,10 @@ function createMdxLoader(configLoader) {
719
715
  docCollection = collection.docs;
720
716
  break;
721
717
  }
722
- if (docCollection?.schema) {
723
- matter.data = await validate(
724
- docCollection.schema,
725
- matter.data,
726
- {
727
- source: value,
728
- path: filePath
729
- },
730
- `invalid frontmatter in ${filePath}`
718
+ if (docCollection) {
719
+ matter.data = await configLoader.core.transformFrontmatter(
720
+ { collection: docCollection, filePath, source: value },
721
+ matter.data
731
722
  );
732
723
  }
733
724
  if (parsed.only === "frontmatter") {
@@ -736,24 +727,16 @@ function createMdxLoader(configLoader) {
736
727
  map: null
737
728
  };
738
729
  }
739
- const data = {};
740
- if (config.global.lastModifiedTime === "git") {
741
- data.lastModified = (await getGitTimestamp(filePath))?.getTime();
742
- }
743
730
  const lineOffset = isDevelopment ? countLines(matter.matter) : 0;
744
- const compiled = await buildMDX(
745
- `${getConfigHash(config)}:${parsed.collection ?? "global"}`,
746
- "\n".repeat(lineOffset) + matter.content,
747
- {
748
- development: isDevelopment,
749
- ...docCollection?.mdxOptions ?? await config.getDefaultMDXOptions(),
750
- postprocess: docCollection?.postprocess,
751
- data,
752
- filePath,
753
- frontmatter: matter.data,
754
- _compiler: compiler
755
- }
756
- );
731
+ const { buildMDX: buildMDX2 } = await Promise.resolve().then(() => (init_build_mdx(), build_mdx_exports));
732
+ const compiled = await buildMDX2(configLoader.core, docCollection, {
733
+ isDevelopment,
734
+ source: "\n".repeat(lineOffset) + matter.content,
735
+ filePath,
736
+ frontmatter: matter.data,
737
+ _compiler: compiler,
738
+ environment: "bundler"
739
+ });
757
740
  const out = {
758
741
  code: String(compiled.value),
759
742
  map: compiled.map
@@ -763,14 +746,6 @@ function createMdxLoader(configLoader) {
763
746
  }
764
747
  };
765
748
  }
766
- var hashes = /* @__PURE__ */ new WeakMap();
767
- function getConfigHash(config) {
768
- let hash = hashes.get(config);
769
- if (hash) return hash;
770
- hash = Date.now().toString();
771
- hashes.set(config, hash);
772
- return hash;
773
- }
774
749
  function generateCacheHash(input) {
775
750
  return (0, import_node_crypto.createHash)("md5").update(input).digest("hex");
776
751
  }
@@ -789,20 +764,85 @@ var import_node_url2 = require("url");
789
764
  // src/core.ts
790
765
  var import_node_path3 = __toESM(require("path"), 1);
791
766
  var import_promises2 = __toESM(require("fs/promises"), 1);
792
- function findConfigFile() {
793
- return import_node_path3.default.resolve("source.config.ts");
767
+
768
+ // src/utils/validation.ts
769
+ var ValidationError = class extends Error {
770
+ constructor(message, issues) {
771
+ super(
772
+ `${message}:
773
+ ${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`
774
+ );
775
+ this.title = message;
776
+ this.issues = issues;
777
+ }
778
+ async toStringFormatted() {
779
+ const picocolors = await import("picocolors");
780
+ return [
781
+ picocolors.bold(`[MDX] ${this.title}:`),
782
+ ...this.issues.map(
783
+ (issue) => picocolors.redBright(
784
+ `- ${picocolors.bold(issue.path?.join(".") ?? "*")}: ${issue.message}`
785
+ )
786
+ )
787
+ ].join("\n");
788
+ }
789
+ };
790
+ async function validate(schema, data, context, errorMessage) {
791
+ if (typeof schema === "function" && !("~standard" in schema)) {
792
+ schema = schema(context);
793
+ }
794
+ if ("~standard" in schema) {
795
+ const result = await schema["~standard"].validate(
796
+ data
797
+ );
798
+ if (result.issues) {
799
+ throw new ValidationError(errorMessage, result.issues);
800
+ }
801
+ return result.value;
802
+ }
803
+ return data;
804
+ }
805
+
806
+ // src/utils/codegen.ts
807
+ var import_node_path2 = __toESM(require("path"), 1);
808
+ var import_tinyglobby = require("tinyglobby");
809
+ function ident(code, tab = 1) {
810
+ return code.split("\n").map((v) => " ".repeat(tab) + v).join("\n");
811
+ }
812
+
813
+ // src/core.ts
814
+ var _Defaults = {
815
+ configPath: "source.config.ts",
816
+ outDir: ".source"
817
+ };
818
+ async function getPlugins(pluginOptions) {
819
+ const plugins = [];
820
+ for await (const option of pluginOptions) {
821
+ if (!option) continue;
822
+ if (Array.isArray(option)) plugins.push(...await getPlugins(option));
823
+ else plugins.push(option);
824
+ }
825
+ return plugins;
794
826
  }
795
827
  function createCore(options, defaultPlugins = []) {
796
828
  let config;
797
- let plugins2;
798
- return {
799
- _options: options,
800
- getPluginContext() {
801
- return {
802
- core: this,
803
- ...options
804
- };
805
- },
829
+ let plugins;
830
+ async function transformMetadata({
831
+ collection,
832
+ filePath,
833
+ source
834
+ }, data) {
835
+ if (collection.schema) {
836
+ data = await validate(
837
+ collection.schema,
838
+ data,
839
+ { path: filePath, source },
840
+ collection.type === "doc" ? `invalid frontmatter in ${filePath}` : `invalid data in ${filePath}`
841
+ );
842
+ }
843
+ return data;
844
+ }
845
+ const core = {
806
846
  /**
807
847
  * Convenient cache store, reset when config changes
808
848
  */
@@ -810,47 +850,137 @@ function createCore(options, defaultPlugins = []) {
810
850
  async init({ config: newConfig }) {
811
851
  config = await newConfig;
812
852
  this.cache.clear();
813
- plugins2 = [];
814
- for await (const option of [
853
+ plugins = await getPlugins([
854
+ postprocessPlugin(),
815
855
  ...defaultPlugins,
816
856
  ...config.global.plugins ?? []
817
- ]) {
818
- if (!option) continue;
819
- if (Array.isArray(option)) plugins2.push(...option);
820
- else plugins2.push(option);
821
- }
822
- for (const plugin of plugins2) {
823
- const out = await plugin.config?.call(this.getPluginContext(), config);
857
+ ]);
858
+ for (const plugin of plugins) {
859
+ const out = await plugin.config?.call(pluginContext, config);
824
860
  if (out) config = out;
825
861
  }
826
- return this;
862
+ },
863
+ getOptions() {
864
+ return options;
827
865
  },
828
866
  getConfig() {
829
867
  return config;
830
868
  },
869
+ /**
870
+ * The file path of compiled config file, the file may not exist (e.g. on Vite, or still compiling)
871
+ */
872
+ getCompiledConfigPath() {
873
+ return import_node_path3.default.join(options.outDir, "source.config.mjs");
874
+ },
875
+ getPlugins() {
876
+ return plugins;
877
+ },
878
+ getPluginContext() {
879
+ return pluginContext;
880
+ },
831
881
  async initServer(server) {
832
- for (const plugin of plugins2) {
833
- await plugin.configureServer?.call(this.getPluginContext(), server);
882
+ for (const plugin of plugins) {
883
+ await plugin.configureServer?.call(pluginContext, server);
834
884
  }
835
885
  },
836
- async emitAndWrite({
837
- filterPlugin = () => true
838
- } = {}) {
839
- const start = performance.now();
840
- const out = await Promise.all(
841
- plugins2.map((plugin) => {
886
+ async emit({ filterPlugin = () => true } = {}) {
887
+ return (await Promise.all(
888
+ plugins.map((plugin) => {
842
889
  if (!filterPlugin(plugin) || !plugin.emit) return [];
843
- return plugin.emit.call(this.getPluginContext());
890
+ return plugin.emit.call(pluginContext);
844
891
  })
845
- );
892
+ )).flat();
893
+ },
894
+ async emitAndWrite(emitOptions) {
895
+ const start = performance.now();
896
+ const out = await this.emit(emitOptions);
846
897
  await Promise.all(
847
- out.flat().map(async (entry) => {
898
+ out.map(async (entry) => {
848
899
  const file = import_node_path3.default.join(options.outDir, entry.path);
849
900
  await import_promises2.default.mkdir(import_node_path3.default.dirname(file), { recursive: true });
850
901
  await import_promises2.default.writeFile(file, entry.content);
851
902
  })
852
903
  );
853
904
  console.log(`[MDX] generated files in ${performance.now() - start}ms`);
905
+ },
906
+ async transformMeta(options2, data) {
907
+ const ctx = {
908
+ ...pluginContext,
909
+ ...options2
910
+ };
911
+ data = await transformMetadata(options2, data);
912
+ for (const plugin of plugins) {
913
+ if (plugin.meta?.transform)
914
+ data = await plugin.meta.transform.call(ctx, data) ?? data;
915
+ }
916
+ return data;
917
+ },
918
+ async transformFrontmatter(options2, data) {
919
+ const ctx = {
920
+ ...pluginContext,
921
+ ...options2
922
+ };
923
+ data = await transformMetadata(options2, data);
924
+ for (const plugin of plugins) {
925
+ if (plugin.doc?.frontmatter)
926
+ data = await plugin.doc.frontmatter.call(ctx, data) ?? data;
927
+ }
928
+ return data;
929
+ },
930
+ async transformVFile(options2, file) {
931
+ const ctx = {
932
+ ...pluginContext,
933
+ ...options2
934
+ };
935
+ for (const plugin of plugins) {
936
+ if (plugin.doc?.vfile)
937
+ file = await plugin.doc.vfile.call(ctx, file) ?? file;
938
+ }
939
+ return file;
940
+ }
941
+ };
942
+ const pluginContext = {
943
+ core,
944
+ ...options
945
+ };
946
+ return core;
947
+ }
948
+ function postprocessPlugin() {
949
+ const LinkReferenceTypes = `{
950
+ /**
951
+ * extracted references (e.g. hrefs, paths), useful for analyzing relationships between pages.
952
+ */
953
+ extractedReferences?: import('fumadocs-mdx').ExtractedReference[];
954
+ }`;
955
+ return {
956
+ "index-file": {
957
+ generateTypeConfig() {
958
+ const lines = [];
959
+ lines.push("{");
960
+ lines.push(" DocData: {");
961
+ for (const collection of this.core.getConfig().collectionList) {
962
+ let postprocessOptions;
963
+ switch (collection.type) {
964
+ case "doc":
965
+ postprocessOptions = collection.postprocess;
966
+ break;
967
+ case "docs":
968
+ postprocessOptions = collection.docs.postprocess;
969
+ break;
970
+ }
971
+ if (postprocessOptions?.extractLinkReferences) {
972
+ lines.push(ident(`${collection.name}: ${LinkReferenceTypes},`, 2));
973
+ }
974
+ }
975
+ lines.push(" }");
976
+ lines.push("}");
977
+ return lines.join("\n");
978
+ },
979
+ serverOptions(options) {
980
+ options.doc ??= {};
981
+ options.doc.passthroughs ??= [];
982
+ options.doc.passthroughs.push("extractedReferences");
983
+ }
854
984
  }
855
985
  };
856
986
  }
@@ -859,6 +989,7 @@ function createCore(options, defaultPlugins = []) {
859
989
  var import_promises3 = __toESM(require("fs/promises"), 1);
860
990
  function createIntegratedConfigLoader(core) {
861
991
  return {
992
+ core,
862
993
  getConfig() {
863
994
  return core.getConfig();
864
995
  }
@@ -873,61 +1004,71 @@ var querySchema2 = import_zod2.z.object({
873
1004
  }).loose();
874
1005
  function createMetaLoader(configLoader, resolve2 = {}) {
875
1006
  const { json: resolveJson = "js", yaml: resolveYaml = "js" } = resolve2;
876
- function stringifyOutput(isJson, data) {
877
- if (isJson) {
878
- return resolveJson === "json" ? JSON.stringify(data) : `export default ${JSON.stringify(data)}`;
879
- } else {
880
- return resolveYaml === "yaml" ? (0, import_js_yaml2.dump)(data) : `export default ${JSON.stringify(data)}`;
1007
+ function parse2(filePath, source) {
1008
+ try {
1009
+ if (filePath.endsWith(".json")) return JSON.parse(source);
1010
+ if (filePath.endsWith(".yaml")) return (0, import_js_yaml2.load)(source);
1011
+ } catch (e) {
1012
+ throw new Error(`invalid data in ${filePath}`, { cause: e });
881
1013
  }
1014
+ throw new Error("Unknown file type " + filePath);
882
1015
  }
883
- return {
884
- test: metaLoaderGlob,
885
- async load({ filePath, query, getSource }) {
886
- const parsed = querySchema2.parse(query);
887
- const collection = parsed.collection ? (await configLoader.getConfig()).getCollection(parsed.collection) : void 0;
888
- if (!collection) return null;
889
- const isJson = filePath.endsWith(".json");
890
- const source = await getSource();
891
- let data;
892
- try {
893
- data = isJson ? JSON.parse(source) : (0, import_js_yaml2.load)(source);
894
- } catch (e) {
895
- throw new Error(`invalid data in ${filePath}`, { cause: e });
896
- }
897
- let schema;
1016
+ function onMeta(source, { filePath, query }) {
1017
+ const parsed = querySchema2.safeParse(query);
1018
+ if (!parsed.success || !parsed.data.collection) return null;
1019
+ const collectionName = parsed.data.collection;
1020
+ return async () => {
1021
+ const config = await configLoader.getConfig();
1022
+ const collection = config.getCollection(collectionName);
1023
+ let metaCollection;
898
1024
  switch (collection?.type) {
899
1025
  case "meta":
900
- schema = collection.schema;
1026
+ metaCollection = collection;
901
1027
  break;
902
1028
  case "docs":
903
- schema = collection.meta.schema;
1029
+ metaCollection = collection.meta;
904
1030
  break;
905
1031
  }
906
- if (schema) {
907
- data = await validate(
908
- schema,
909
- data,
910
- { path: filePath, source },
911
- `invalid data in ${filePath}`
912
- );
1032
+ const data = parse2(filePath, source);
1033
+ if (!metaCollection) return data;
1034
+ return configLoader.core.transformMeta(
1035
+ {
1036
+ collection: metaCollection,
1037
+ filePath,
1038
+ source
1039
+ },
1040
+ data
1041
+ );
1042
+ };
1043
+ }
1044
+ return {
1045
+ test: metaLoaderGlob,
1046
+ async load(input) {
1047
+ const result = onMeta(await input.getSource(), input);
1048
+ if (result === null) return null;
1049
+ const data = await result();
1050
+ if (input.filePath.endsWith(".json")) {
1051
+ return {
1052
+ code: resolveJson === "json" ? JSON.stringify(data) : `export default ${JSON.stringify(data)}`
1053
+ };
1054
+ } else {
1055
+ return {
1056
+ code: resolveYaml === "yaml" ? (0, import_js_yaml2.dump)(data) : `export default ${JSON.stringify(data)}`
1057
+ };
913
1058
  }
914
- return {
915
- code: stringifyOutput(isJson, data)
916
- };
917
1059
  },
918
1060
  bun: {
919
- loadSync(source, { filePath }) {
920
- const isJson = filePath.endsWith(".json");
921
- let data;
922
- try {
923
- data = isJson ? JSON.parse(source) : (0, import_js_yaml2.load)(source);
924
- } catch (e) {
925
- throw new Error(`invalid data in ${filePath}`, { cause: e });
926
- }
927
- return {
1061
+ load(source, input) {
1062
+ const result = onMeta(source, input);
1063
+ if (result === null)
1064
+ return {
1065
+ loader: "object",
1066
+ exports: parse2(input.filePath, source)
1067
+ };
1068
+ return result().then((data) => ({
928
1069
  loader: "object",
929
- exports: data
930
- };
1070
+ exports: { default: data }
1071
+ }));
931
1072
  }
932
1073
  }
933
1074
  };
@@ -962,8 +1103,8 @@ function toBun(loader) {
962
1103
  }
963
1104
  }
964
1105
  };
965
- if (loader.bun?.loadSync) {
966
- return loader.bun.loadSync((0, import_node_fs.readFileSync)(filePath).toString(), input);
1106
+ if (loader.bun?.load) {
1107
+ return loader.bun.load((0, import_node_fs.readFileSync)(filePath).toString(), input);
967
1108
  }
968
1109
  const result = loader.load(input);
969
1110
  if (result instanceof Promise) {
@@ -978,19 +1119,20 @@ function toBun(loader) {
978
1119
  function createMdxPlugin(options = {}) {
979
1120
  const {
980
1121
  environment = "bun",
981
- outDir = ".source",
982
- configPath = findConfigFile(),
1122
+ outDir = _Defaults.outDir,
1123
+ configPath = _Defaults.configPath,
983
1124
  disableMetaFile = false
984
1125
  } = options;
985
1126
  return {
986
1127
  name: "bun-plugin-fumadocs-mdx",
987
1128
  async setup(build) {
988
1129
  const importPath = (0, import_node_url2.pathToFileURL)(configPath).href;
989
- const core = await createCore({
1130
+ const core = createCore({
990
1131
  environment,
991
1132
  outDir,
992
1133
  configPath
993
- }).init({
1134
+ });
1135
+ await core.init({
994
1136
  config: buildConfig(await import(importPath))
995
1137
  });
996
1138
  const configLoader = createIntegratedConfigLoader(core);