fumadocs-mdx 14.0.1 → 14.0.2

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 (72) hide show
  1. package/dist/{build-mdx-6UAK5FF5.js → build-mdx-W3233QBZ.js} +1 -1
  2. package/dist/bun/index.d.ts +1 -1
  3. package/dist/bun/index.js +5 -5
  4. package/dist/{chunk-ZY6UZ7NH.js → chunk-6RPNS75C.js} +1 -1
  5. package/dist/{chunk-7UKSZSPY.js → chunk-ED3ON275.js} +3 -4
  6. package/dist/{chunk-BEBCWQC7.js → chunk-GB4W3YCZ.js} +1 -1
  7. package/dist/{chunk-SLY7WXTX.js → chunk-KOPLIEVQ.js} +5 -6
  8. package/dist/{chunk-MTTISKQJ.js → chunk-LPX7ZO66.js} +1 -1
  9. package/dist/{chunk-K6HCOGOX.js → chunk-OLL7FM7W.js} +2 -2
  10. package/dist/{chunk-IQGEFL2B.js → chunk-Q5OSGLJL.js} +1 -1
  11. package/dist/{chunk-E5DJTSIM.js → chunk-S7KOJHHO.js} +4 -1
  12. package/dist/{chunk-6NISOLQ6.js → chunk-USWQVJWR.js} +1 -1
  13. package/dist/config/index.d.ts +1 -1
  14. package/dist/config/index.js +1 -1
  15. package/dist/{core-B9ZoS6sA.d.ts → core-C3QZSdEx.d.ts} +1 -1
  16. package/dist/{index-CNOvhtOn.d.ts → index-RVIZxMZG.d.ts} +1 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/load-from-file-OZ5N7DXU.js +8 -0
  19. package/dist/next/index.cjs +8 -6
  20. package/dist/next/index.d.ts +1 -1
  21. package/dist/next/index.js +5 -5
  22. package/dist/node/loader.js +3 -3
  23. package/dist/plugins/index-file.d.ts +1 -1
  24. package/dist/plugins/index-file.js +1 -1
  25. package/dist/plugins/json-schema.d.ts +1 -1
  26. package/dist/plugins/last-modified.d.ts +5 -2
  27. package/dist/plugins/last-modified.js +10 -3
  28. package/dist/runtime/browser.d.ts +1 -1
  29. package/dist/runtime/dynamic.d.ts +1 -1
  30. package/dist/runtime/dynamic.js +4 -4
  31. package/dist/runtime/server.d.ts +1 -1
  32. package/dist/vite/index.d.ts +1 -1
  33. package/dist/vite/index.js +7 -7
  34. package/dist/webpack/mdx.d.ts +2 -2
  35. package/dist/webpack/mdx.js +4 -4
  36. package/dist/webpack/meta.d.ts +2 -2
  37. package/dist/webpack/meta.js +3 -3
  38. package/package.json +4 -6
  39. package/dist/bin.cjs +0 -1958
  40. package/dist/bin.d.cts +0 -1
  41. package/dist/bun/index.cjs +0 -1147
  42. package/dist/bun/index.d.cts +0 -25
  43. package/dist/config/index.cjs +0 -400
  44. package/dist/config/index.d.cts +0 -18
  45. package/dist/core-DTuP23zu.d.cts +0 -341
  46. package/dist/index-BD8Woo4m.d.cts +0 -8
  47. package/dist/index.cjs +0 -18
  48. package/dist/index.d.cts +0 -61
  49. package/dist/load-from-file-5HUQN36V.js +0 -8
  50. package/dist/next/index.d.cts +0 -33
  51. package/dist/node/loader.cjs +0 -1200
  52. package/dist/node/loader.d.cts +0 -5
  53. package/dist/plugins/index-file.cjs +0 -495
  54. package/dist/plugins/index-file.d.cts +0 -14
  55. package/dist/plugins/json-schema.cjs +0 -114
  56. package/dist/plugins/json-schema.d.cts +0 -31
  57. package/dist/plugins/last-modified.cjs +0 -110
  58. package/dist/plugins/last-modified.d.cts +0 -37
  59. package/dist/runtime/browser.cjs +0 -93
  60. package/dist/runtime/browser.d.cts +0 -53
  61. package/dist/runtime/dynamic.cjs +0 -1023
  62. package/dist/runtime/dynamic.d.cts +0 -27
  63. package/dist/runtime/server.cjs +0 -176
  64. package/dist/runtime/server.d.cts +0 -14
  65. package/dist/runtime/types.cjs +0 -18
  66. package/dist/runtime/types.d.cts +0 -61
  67. package/dist/vite/index.cjs +0 -1687
  68. package/dist/vite/index.d.cts +0 -44
  69. package/dist/webpack/mdx.cjs +0 -1124
  70. package/dist/webpack/mdx.d.cts +0 -20
  71. package/dist/webpack/meta.cjs +0 -684
  72. package/dist/webpack/meta.d.cts +0 -20
package/dist/bin.cjs DELETED
@@ -1,1958 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
- }
22
- return to;
23
- };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
- // If the importer is in node compatibility mode or this is not an ESM
26
- // file that has been converted to a CommonJS file using a Babel-
27
- // compatible transform (i.e. "__esModule" has not been set), then set
28
- // "default" to the CommonJS "module.exports" for node compatibility.
29
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
- mod
31
- ));
32
-
33
- // src/config/preset.ts
34
- function pluginOption(def, options = []) {
35
- const list = def(Array.isArray(options) ? options : []).filter(
36
- Boolean
37
- );
38
- if (typeof options === "function") {
39
- return options(list);
40
- }
41
- return list;
42
- }
43
- function applyMdxPreset(options = {}) {
44
- return async (environment = "bundler") => {
45
- if (options.preset === "minimal") return options;
46
- const plugins = await import("fumadocs-core/mdx-plugins");
47
- const {
48
- valueToExport = [],
49
- rehypeCodeOptions,
50
- remarkImageOptions,
51
- remarkHeadingOptions,
52
- remarkStructureOptions,
53
- remarkCodeTabOptions,
54
- remarkNpmOptions,
55
- ...mdxOptions
56
- } = options;
57
- const remarkPlugins = pluginOption(
58
- (v) => [
59
- plugins.remarkGfm,
60
- [
61
- plugins.remarkHeading,
62
- {
63
- generateToc: false,
64
- ...remarkHeadingOptions
65
- }
66
- ],
67
- remarkImageOptions !== false && [
68
- plugins.remarkImage,
69
- {
70
- ...remarkImageOptions,
71
- useImport: remarkImageOptions?.useImport ?? environment === "bundler"
72
- }
73
- ],
74
- "remarkCodeTab" in plugins && remarkCodeTabOptions !== false && [
75
- plugins.remarkCodeTab,
76
- remarkCodeTabOptions
77
- ],
78
- "remarkNpm" in plugins && remarkNpmOptions !== false && [plugins.remarkNpm, remarkNpmOptions],
79
- ...v,
80
- remarkStructureOptions !== false && [
81
- plugins.remarkStructure,
82
- remarkStructureOptions
83
- ],
84
- valueToExport.length > 0 && (() => {
85
- return (_, file) => {
86
- file.data["mdx-export"] ??= [];
87
- for (const name of valueToExport) {
88
- if (!(name in file.data)) continue;
89
- file.data["mdx-export"].push({
90
- name,
91
- value: file.data[name]
92
- });
93
- }
94
- };
95
- })
96
- ],
97
- mdxOptions.remarkPlugins
98
- );
99
- const rehypePlugins = pluginOption(
100
- (v) => [
101
- rehypeCodeOptions !== false && [plugins.rehypeCode, rehypeCodeOptions],
102
- ...v,
103
- plugins.rehypeToc
104
- ],
105
- mdxOptions.rehypePlugins
106
- );
107
- return {
108
- ...mdxOptions,
109
- outputFormat: environment === "runtime" ? "function-body" : mdxOptions.outputFormat,
110
- remarkPlugins,
111
- rehypePlugins
112
- };
113
- };
114
- }
115
- var init_preset = __esm({
116
- "src/config/preset.ts"() {
117
- "use strict";
118
- }
119
- });
120
-
121
- // src/config/build.ts
122
- function buildCollection(name, config) {
123
- if (config.type === "docs") {
124
- return {
125
- ...config,
126
- name,
127
- meta: buildPrimitiveCollection(name, config.meta),
128
- docs: buildPrimitiveCollection(name, config.docs),
129
- hasFile(filePath) {
130
- return this.docs.hasFile(filePath) || this.meta.hasFile(filePath);
131
- }
132
- };
133
- }
134
- return buildPrimitiveCollection(name, config);
135
- }
136
- function buildPrimitiveCollection(name, { files, ...config }) {
137
- const supportedFormats = SupportedFormats[config.type];
138
- const patterns = files ?? [`**/*.{${supportedFormats.join(",")}}`];
139
- let matchers;
140
- return {
141
- ...config,
142
- name,
143
- patterns,
144
- isFileSupported(filePath) {
145
- return supportedFormats.some((format) => filePath.endsWith(`.${format}`));
146
- },
147
- hasFile(filePath) {
148
- matchers ??= (Array.isArray(config.dir) ? config.dir : [config.dir]).map(
149
- (dir) => (0, import_picomatch.default)(patterns, {
150
- cwd: dir
151
- })
152
- );
153
- return this.isFileSupported(filePath) && matchers.some((matcher) => matcher(filePath));
154
- }
155
- };
156
- }
157
- function buildConfig(config) {
158
- const collections = /* @__PURE__ */ new Map();
159
- const loaded = {};
160
- for (const [k, v] of Object.entries(config)) {
161
- if (!v) {
162
- continue;
163
- }
164
- if (typeof v === "object" && "type" in v) {
165
- if (v.type === "docs") {
166
- collections.set(k, buildCollection(k, v));
167
- continue;
168
- }
169
- if (v.type === "doc" || v.type === "meta") {
170
- collections.set(
171
- k,
172
- buildCollection(k, v)
173
- );
174
- continue;
175
- }
176
- }
177
- if (k === "default" && v) {
178
- Object.assign(loaded, v);
179
- continue;
180
- }
181
- throw new Error(
182
- `Unknown export "${k}", you can only export collections from source configuration file.`
183
- );
184
- }
185
- const mdxOptionsCache = /* @__PURE__ */ new Map();
186
- return {
187
- global: loaded,
188
- collectionList: Array.from(collections.values()),
189
- getCollection(name) {
190
- return collections.get(name);
191
- },
192
- getMDXOptions(collection, environment = "bundler") {
193
- const key = collection ? `${environment}:${collection.name}` : environment;
194
- const cached = mdxOptionsCache.get(key);
195
- if (cached) return cached;
196
- let result;
197
- if (collection?.mdxOptions) {
198
- const optionsFn = collection.mdxOptions;
199
- result = typeof optionsFn === "function" ? optionsFn(environment) : optionsFn;
200
- } else {
201
- result = (async () => {
202
- const optionsFn = this.global.mdxOptions;
203
- const options = typeof optionsFn === "function" ? await optionsFn() : optionsFn;
204
- return applyMdxPreset(options)(environment);
205
- })();
206
- }
207
- mdxOptionsCache.set(key, 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
- init_preset();
218
- SupportedFormats = {
219
- doc: ["mdx", "md"],
220
- meta: ["json", "yaml"]
221
- };
222
- }
223
- });
224
-
225
- // src/config/load-from-file.ts
226
- var load_from_file_exports = {};
227
- __export(load_from_file_exports, {
228
- loadConfig: () => loadConfig
229
- });
230
- async function compileConfig(core) {
231
- const { build } = await import("esbuild");
232
- const { configPath, outDir } = core.getOptions();
233
- const transformed = await build({
234
- entryPoints: [{ in: configPath, out: "source.config" }],
235
- bundle: true,
236
- outdir: outDir,
237
- target: "node20",
238
- write: true,
239
- platform: "node",
240
- format: "esm",
241
- packages: "external",
242
- outExtension: {
243
- ".js": ".mjs"
244
- },
245
- allowOverwrite: true
246
- });
247
- if (transformed.errors.length > 0) {
248
- throw new Error("failed to compile configuration file");
249
- }
250
- }
251
- async function loadConfig(core, build = false) {
252
- if (build) await compileConfig(core);
253
- const url = (0, import_node_url.pathToFileURL)(core.getCompiledConfigPath());
254
- url.searchParams.set("hash", Date.now().toString());
255
- const config = import(url.href).then(
256
- (loaded) => buildConfig(loaded)
257
- );
258
- return await config;
259
- }
260
- var import_node_url;
261
- var init_load_from_file = __esm({
262
- "src/config/load-from-file.ts"() {
263
- "use strict";
264
- import_node_url = require("url");
265
- init_build();
266
- }
267
- });
268
-
269
- // src/utils/validation.ts
270
- async function validate(schema, data, context, errorMessage) {
271
- if (typeof schema === "function" && !("~standard" in schema)) {
272
- schema = schema(context);
273
- }
274
- if ("~standard" in schema) {
275
- const result = await schema["~standard"].validate(
276
- data
277
- );
278
- if (result.issues) {
279
- throw new ValidationError(errorMessage, result.issues);
280
- }
281
- return result.value;
282
- }
283
- return data;
284
- }
285
- var ValidationError;
286
- var init_validation = __esm({
287
- "src/utils/validation.ts"() {
288
- "use strict";
289
- ValidationError = class extends Error {
290
- constructor(message, issues) {
291
- super(
292
- `${message}:
293
- ${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`
294
- );
295
- this.title = message;
296
- this.issues = issues;
297
- }
298
- async toStringFormatted() {
299
- const picocolors = await import("picocolors");
300
- return [
301
- picocolors.bold(`[MDX] ${this.title}:`),
302
- ...this.issues.map(
303
- (issue) => picocolors.redBright(
304
- `- ${picocolors.bold(issue.path?.join(".") ?? "*")}: ${issue.message}`
305
- )
306
- )
307
- ].join("\n");
308
- }
309
- };
310
- }
311
- });
312
-
313
- // src/utils/codegen.ts
314
- function createCodegen({
315
- target = "default",
316
- outDir = "",
317
- jsExtension = false,
318
- globCache = /* @__PURE__ */ new Map()
319
- }) {
320
- let eagerImportId = 0;
321
- const banner = ["// @ts-nocheck"];
322
- if (target === "vite") {
323
- banner.push('/// <reference types="vite/client" />');
324
- }
325
- return {
326
- options: {
327
- target,
328
- outDir
329
- },
330
- lines: [],
331
- addImport(statement) {
332
- this.lines.unshift(statement);
333
- },
334
- async pushAsync(insert) {
335
- for (const line of await Promise.all(insert)) {
336
- if (line === void 0) continue;
337
- this.lines.push(line);
338
- }
339
- },
340
- async generateGlobImport(patterns, options) {
341
- if (target === "vite") {
342
- return this.generateViteGlobImport(patterns, options);
343
- }
344
- return this.generateNodeGlobImport(patterns, options);
345
- },
346
- generateViteGlobImport(patterns, { base, ...rest }) {
347
- patterns = (typeof patterns === "string" ? [patterns] : patterns).map(
348
- normalizeViteGlobPath
349
- );
350
- return `import.meta.glob(${JSON.stringify(patterns)}, ${JSON.stringify(
351
- {
352
- base: normalizeViteGlobPath(import_node_path.default.relative(outDir, base)),
353
- ...rest
354
- },
355
- null,
356
- 2
357
- )})`;
358
- },
359
- async generateNodeGlobImport(patterns, {
360
- base,
361
- eager = false,
362
- query = {},
363
- import: importName
364
- }) {
365
- const cacheKey = JSON.stringify({ patterns, base });
366
- let files = globCache.get(cacheKey);
367
- if (!files) {
368
- files = (0, import_tinyglobby.glob)(patterns, {
369
- cwd: base
370
- });
371
- globCache.set(cacheKey, files);
372
- }
373
- let code = "{";
374
- for (const item of await files) {
375
- const fullPath = import_node_path.default.join(base, item);
376
- const searchParams = new URLSearchParams();
377
- for (const [k, v] of Object.entries(query)) {
378
- searchParams.set(k, v);
379
- }
380
- const importPath = this.formatImportPath(fullPath) + "?" + searchParams.toString();
381
- if (eager) {
382
- const name = `__fd_glob_${eagerImportId++}`;
383
- this.lines.unshift(
384
- importName ? `import { ${importName} as ${name} } from ${JSON.stringify(importPath)}` : `import * as ${name} from ${JSON.stringify(importPath)}`
385
- );
386
- code += `${JSON.stringify(item)}: ${name}, `;
387
- } else {
388
- let line = `${JSON.stringify(item)}: () => import(${JSON.stringify(importPath)})`;
389
- if (importName) {
390
- line += `.then(mod => mod.${importName})`;
391
- }
392
- code += `${line}, `;
393
- }
394
- }
395
- code += "}";
396
- return code;
397
- },
398
- formatImportPath(file) {
399
- const ext = import_node_path.default.extname(file);
400
- let filename;
401
- if (ext === ".ts" && jsExtension) {
402
- filename = file.substring(0, file.length - ext.length) + ".js";
403
- } else if (ext === ".ts") {
404
- filename = file.substring(0, file.length - ext.length);
405
- } else {
406
- filename = file;
407
- }
408
- const importPath = slash(import_node_path.default.relative(outDir, filename));
409
- return importPath.startsWith(".") ? importPath : `./${importPath}`;
410
- },
411
- toString() {
412
- return [...banner, ...this.lines].join("\n");
413
- }
414
- };
415
- }
416
- function normalizeViteGlobPath(file) {
417
- file = slash(file);
418
- if (file.startsWith("./")) return file;
419
- if (file.startsWith("/")) return `.${file}`;
420
- return `./${file}`;
421
- }
422
- function slash(path9) {
423
- const isExtendedLengthPath = path9.startsWith("\\\\?\\");
424
- if (isExtendedLengthPath) {
425
- return path9;
426
- }
427
- return path9.replaceAll("\\", "/");
428
- }
429
- function ident(code, tab = 1) {
430
- return code.split("\n").map((v) => " ".repeat(tab) + v).join("\n");
431
- }
432
- var import_node_path, import_tinyglobby;
433
- var init_codegen = __esm({
434
- "src/utils/codegen.ts"() {
435
- "use strict";
436
- import_node_path = __toESM(require("path"), 1);
437
- import_tinyglobby = require("tinyglobby");
438
- }
439
- });
440
-
441
- // src/core.ts
442
- async function getPlugins(pluginOptions) {
443
- const plugins = [];
444
- for await (const option of pluginOptions) {
445
- if (!option) continue;
446
- if (Array.isArray(option)) plugins.push(...await getPlugins(option));
447
- else plugins.push(option);
448
- }
449
- return plugins;
450
- }
451
- function createCore(options, defaultPlugins = []) {
452
- let config;
453
- let plugins;
454
- async function transformMetadata({
455
- collection,
456
- filePath,
457
- source
458
- }, data) {
459
- if (collection.schema) {
460
- data = await validate(
461
- collection.schema,
462
- data,
463
- { path: filePath, source },
464
- collection.type === "doc" ? `invalid frontmatter in ${filePath}` : `invalid data in ${filePath}`
465
- );
466
- }
467
- return data;
468
- }
469
- const core = {
470
- /**
471
- * Convenient cache store, reset when config changes
472
- */
473
- cache: /* @__PURE__ */ new Map(),
474
- async init({ config: newConfig }) {
475
- config = await newConfig;
476
- this.cache.clear();
477
- plugins = await getPlugins([
478
- postprocessPlugin(),
479
- ...defaultPlugins,
480
- ...config.global.plugins ?? []
481
- ]);
482
- for (const plugin of plugins) {
483
- const out = await plugin.config?.call(pluginContext, config);
484
- if (out) config = out;
485
- }
486
- },
487
- getOptions() {
488
- return options;
489
- },
490
- getConfig() {
491
- return config;
492
- },
493
- /**
494
- * The file path of compiled config file, the file may not exist (e.g. on Vite, or still compiling)
495
- */
496
- getCompiledConfigPath() {
497
- return import_node_path2.default.join(options.outDir, "source.config.mjs");
498
- },
499
- getPlugins() {
500
- return plugins;
501
- },
502
- getPluginContext() {
503
- return pluginContext;
504
- },
505
- async initServer(server) {
506
- for (const plugin of plugins) {
507
- await plugin.configureServer?.call(pluginContext, server);
508
- }
509
- },
510
- async emit({ filterPlugin = () => true } = {}) {
511
- return (await Promise.all(
512
- plugins.map((plugin) => {
513
- if (!filterPlugin(plugin) || !plugin.emit) return [];
514
- return plugin.emit.call(pluginContext);
515
- })
516
- )).flat();
517
- },
518
- async emitAndWrite(emitOptions) {
519
- const start2 = performance.now();
520
- const out = await this.emit(emitOptions);
521
- await Promise.all(
522
- out.map(async (entry) => {
523
- const file = import_node_path2.default.join(options.outDir, entry.path);
524
- await import_promises.default.mkdir(import_node_path2.default.dirname(file), { recursive: true });
525
- await import_promises.default.writeFile(file, entry.content);
526
- })
527
- );
528
- console.log(`[MDX] generated files in ${performance.now() - start2}ms`);
529
- },
530
- async transformMeta(options2, data) {
531
- const ctx = {
532
- ...pluginContext,
533
- ...options2
534
- };
535
- data = await transformMetadata(options2, data);
536
- for (const plugin of plugins) {
537
- if (plugin.meta?.transform)
538
- data = await plugin.meta.transform.call(ctx, data) ?? data;
539
- }
540
- return data;
541
- },
542
- async transformFrontmatter(options2, data) {
543
- const ctx = {
544
- ...pluginContext,
545
- ...options2
546
- };
547
- data = await transformMetadata(options2, data);
548
- for (const plugin of plugins) {
549
- if (plugin.doc?.frontmatter)
550
- data = await plugin.doc.frontmatter.call(ctx, data) ?? data;
551
- }
552
- return data;
553
- },
554
- async transformVFile(options2, file) {
555
- const ctx = {
556
- ...pluginContext,
557
- ...options2
558
- };
559
- for (const plugin of plugins) {
560
- if (plugin.doc?.vfile)
561
- file = await plugin.doc.vfile.call(ctx, file) ?? file;
562
- }
563
- return file;
564
- }
565
- };
566
- const pluginContext = {
567
- core,
568
- ...options
569
- };
570
- return core;
571
- }
572
- function postprocessPlugin() {
573
- const LinkReferenceTypes = `{
574
- /**
575
- * extracted references (e.g. hrefs, paths), useful for analyzing relationships between pages.
576
- */
577
- extractedReferences?: import('fumadocs-mdx').ExtractedReference[];
578
- }`;
579
- return {
580
- "index-file": {
581
- generateTypeConfig() {
582
- const lines = [];
583
- lines.push("{");
584
- lines.push(" DocData: {");
585
- for (const collection of this.core.getConfig().collectionList) {
586
- let postprocessOptions;
587
- switch (collection.type) {
588
- case "doc":
589
- postprocessOptions = collection.postprocess;
590
- break;
591
- case "docs":
592
- postprocessOptions = collection.docs.postprocess;
593
- break;
594
- }
595
- if (postprocessOptions?.extractLinkReferences) {
596
- lines.push(ident(`${collection.name}: ${LinkReferenceTypes},`, 2));
597
- }
598
- }
599
- lines.push(" }");
600
- lines.push("}");
601
- return lines.join("\n");
602
- },
603
- serverOptions(options) {
604
- options.doc ??= {};
605
- options.doc.passthroughs ??= [];
606
- options.doc.passthroughs.push("extractedReferences");
607
- }
608
- }
609
- };
610
- }
611
- var import_node_path2, import_promises, _Defaults;
612
- var init_core = __esm({
613
- "src/core.ts"() {
614
- "use strict";
615
- import_node_path2 = __toESM(require("path"), 1);
616
- import_promises = __toESM(require("fs/promises"), 1);
617
- init_validation();
618
- init_codegen();
619
- _Defaults = {
620
- configPath: "source.config.ts",
621
- outDir: ".source"
622
- };
623
- }
624
- });
625
-
626
- // src/loaders/index.ts
627
- var metaLoaderGlob, mdxLoaderGlob;
628
- var init_loaders = __esm({
629
- "src/loaders/index.ts"() {
630
- "use strict";
631
- metaLoaderGlob = /\.(json|yaml)(\?.+?)?$/;
632
- mdxLoaderGlob = /\.mdx?(\?.+?)?$/;
633
- }
634
- });
635
-
636
- // src/utils/fs-cache.ts
637
- function toFullPath(file) {
638
- if (import_node_path3.default.isAbsolute(file)) {
639
- return import_node_path3.default.relative(process.cwd(), file);
640
- }
641
- return file;
642
- }
643
- function readFileWithCache(file) {
644
- const fullPath = toFullPath(file);
645
- const cached = map.get(fullPath);
646
- if (cached) return cached;
647
- const read = import_promises2.default.readFile(fullPath).then((s) => s.toString());
648
- map.set(fullPath, read);
649
- return read;
650
- }
651
- function removeFileCache(file) {
652
- map.delete(toFullPath(file));
653
- }
654
- var import_lru_cache, import_promises2, import_node_path3, map;
655
- var init_fs_cache = __esm({
656
- "src/utils/fs-cache.ts"() {
657
- "use strict";
658
- import_lru_cache = require("lru-cache");
659
- import_promises2 = __toESM(require("fs/promises"), 1);
660
- import_node_path3 = __toESM(require("path"), 1);
661
- map = new import_lru_cache.LRUCache({
662
- max: 100
663
- });
664
- }
665
- });
666
-
667
- // src/utils/fuma-matter.ts
668
- function fumaMatter(input) {
669
- const output = { matter: "", data: {}, content: input };
670
- const match = regex.exec(input);
671
- if (!match) {
672
- return output;
673
- }
674
- output.matter = match[0];
675
- output.content = input.slice(match[0].length);
676
- const loaded = (0, import_js_yaml.load)(match[1]);
677
- output.data = loaded ?? {};
678
- return output;
679
- }
680
- var import_js_yaml, regex;
681
- var init_fuma_matter = __esm({
682
- "src/utils/fuma-matter.ts"() {
683
- "use strict";
684
- import_js_yaml = require("js-yaml");
685
- regex = /^---\r?\n(.+?)\r?\n---\r?\n/s;
686
- }
687
- });
688
-
689
- // src/plugins/index-file.ts
690
- function indexFile(options = {}) {
691
- const {
692
- target = "default",
693
- addJsExtension,
694
- browser = true,
695
- dynamic = true
696
- } = options;
697
- let config;
698
- let dynamicCollections;
699
- function isDynamic(collection) {
700
- return collection.type === "docs" && collection.docs.dynamic || collection.type === "doc" && collection.dynamic;
701
- }
702
- function generateConfigs(core) {
703
- const serverOptions = {};
704
- const typeConfigs = [];
705
- const ctx = core.getPluginContext();
706
- for (const plugin of core.getPlugins()) {
707
- const indexFilePlugin = plugin["index-file"];
708
- if (!indexFilePlugin) continue;
709
- indexFilePlugin.serverOptions?.call(ctx, serverOptions);
710
- const config2 = indexFilePlugin.generateTypeConfig?.call(ctx);
711
- if (config2) typeConfigs.push(config2);
712
- }
713
- if (typeConfigs.length === 0) {
714
- typeConfigs.push("{ DocData: {} }");
715
- }
716
- return {
717
- serverOptions,
718
- tc: typeConfigs.join(" & ")
719
- };
720
- }
721
- return {
722
- name: "index-file",
723
- config(v) {
724
- config = v;
725
- dynamicCollections = config.collectionList.filter(isDynamic);
726
- },
727
- configureServer(server) {
728
- if (!server.watcher) return;
729
- server.watcher.on("all", async (event, file) => {
730
- removeFileCache(file);
731
- if (dynamicCollections.length === 0) {
732
- if (target === "vite") return;
733
- if (target === "default" && event === "change") return;
734
- }
735
- const updatedCollection = config.collectionList.find(
736
- (collection) => collection.hasFile(file)
737
- );
738
- if (!updatedCollection) return;
739
- if (!isDynamic(updatedCollection)) {
740
- if (target === "vite") return;
741
- if (target === "default" && event === "change") return;
742
- }
743
- await this.core.emitAndWrite({
744
- filterPlugin: (plugin) => plugin.name === "index-file"
745
- });
746
- });
747
- },
748
- async emit() {
749
- const globCache = /* @__PURE__ */ new Map();
750
- const { serverOptions, tc } = generateConfigs(this.core);
751
- const toEmitEntry = async (path9, content) => {
752
- const codegen = createCodegen({
753
- target,
754
- outDir: this.outDir,
755
- jsExtension: addJsExtension,
756
- globCache
757
- });
758
- await content({
759
- core: this.core,
760
- codegen,
761
- serverOptions,
762
- tc
763
- });
764
- return {
765
- path: path9,
766
- content: codegen.toString()
767
- };
768
- };
769
- const out = [
770
- toEmitEntry("server.ts", generateServerIndexFile)
771
- ];
772
- if (dynamic)
773
- out.push(toEmitEntry("dynamic.ts", generateDynamicIndexFile));
774
- if (browser)
775
- out.push(toEmitEntry("browser.ts", generateBrowserIndexFile));
776
- return await Promise.all(out);
777
- }
778
- };
779
- }
780
- async function generateServerIndexFile({
781
- core,
782
- codegen,
783
- serverOptions,
784
- tc
785
- }) {
786
- codegen.lines.push(
787
- `import { server } from 'fumadocs-mdx/runtime/server';`,
788
- `import type * as Config from '${codegen.formatImportPath(core.getOptions().configPath)}';`,
789
- "",
790
- `const create = server<typeof Config, ${tc}>(${JSON.stringify(serverOptions)});`
791
- );
792
- async function generateCollectionObject(collection) {
793
- switch (collection.type) {
794
- case "docs": {
795
- if (collection.docs.dynamic) return;
796
- if (collection.docs.async) {
797
- const [metaGlob2, headGlob, bodyGlob] = await Promise.all([
798
- generateMetaCollectionGlob(codegen, collection.meta, true),
799
- generateDocCollectionFrontmatterGlob(
800
- codegen,
801
- collection.docs,
802
- true
803
- ),
804
- generateDocCollectionGlob(codegen, collection.docs)
805
- ]);
806
- return `await create.docsLazy("${collection.name}", "${collection.dir}", ${metaGlob2}, ${headGlob}, ${bodyGlob})`;
807
- }
808
- const [metaGlob, docGlob] = await Promise.all([
809
- generateMetaCollectionGlob(codegen, collection.meta, true),
810
- generateDocCollectionGlob(codegen, collection.docs, true)
811
- ]);
812
- return `await create.docs("${collection.name}", "${collection.dir}", ${metaGlob}, ${docGlob})`;
813
- }
814
- case "doc":
815
- if (collection.dynamic) return;
816
- if (collection.async) {
817
- const [headGlob, bodyGlob] = await Promise.all([
818
- generateDocCollectionFrontmatterGlob(codegen, collection, true),
819
- generateDocCollectionGlob(codegen, collection)
820
- ]);
821
- return `await create.docLazy("${collection.name}", "${collection.dir}", ${headGlob}, ${bodyGlob})`;
822
- }
823
- return `await create.doc("${collection.name}", "${collection.dir}", ${await generateDocCollectionGlob(
824
- codegen,
825
- collection,
826
- true
827
- )})`;
828
- case "meta":
829
- return `await create.meta("${collection.name}", "${collection.dir}", ${await generateMetaCollectionGlob(
830
- codegen,
831
- collection,
832
- true
833
- )})`;
834
- }
835
- }
836
- await codegen.pushAsync(
837
- core.getConfig().collectionList.map(async (collection) => {
838
- const obj = await generateCollectionObject(collection);
839
- if (!obj) return;
840
- return `
841
- export const ${collection.name} = ${obj};`;
842
- })
843
- );
844
- }
845
- async function generateDynamicIndexFile({
846
- core,
847
- codegen,
848
- serverOptions,
849
- tc
850
- }) {
851
- const { configPath } = core.getOptions();
852
- codegen.lines.push(
853
- `import { dynamic } from 'fumadocs-mdx/runtime/dynamic';`,
854
- `import * as Config from '${codegen.formatImportPath(configPath)}';`,
855
- "",
856
- `const create = await dynamic<typeof Config, ${tc}>(Config, ${JSON.stringify(core.getOptions())}, ${JSON.stringify(serverOptions)});`
857
- );
858
- async function generateCollectionObjectEntry(collection, file) {
859
- const fullPath = import_path.default.join(collection.dir, file);
860
- const content = await readFileWithCache(fullPath).catch(() => "");
861
- const parsed = fumaMatter(content);
862
- const data = await core.transformFrontmatter(
863
- {
864
- collection,
865
- filePath: fullPath,
866
- source: content
867
- },
868
- parsed.data
869
- );
870
- const hash = (0, import_crypto.createHash)("md5").update(content).digest("hex");
871
- const infoStr = [
872
- // make sure it's included in vercel/nft
873
- `absolutePath: path.resolve(${JSON.stringify(fullPath)})`
874
- ];
875
- for (const [k, v] of Object.entries({
876
- info: {
877
- fullPath,
878
- path: file
879
- },
880
- data,
881
- hash
882
- })) {
883
- infoStr.push(`${k}: ${JSON.stringify(v)}`);
884
- }
885
- return `{ ${infoStr.join(", ")} }`;
886
- }
887
- async function generateCollectionObject(parent) {
888
- let collection;
889
- if (parent.type === "doc") collection = parent;
890
- else if (parent.type === "docs") collection = parent.docs;
891
- if (!collection || !collection.dynamic) return;
892
- const files = await (0, import_tinyglobby2.glob)(collection.patterns, {
893
- cwd: collection.dir
894
- });
895
- const entries = await Promise.all(
896
- files.map((file) => generateCollectionObjectEntry(collection, file))
897
- );
898
- switch (parent.type) {
899
- case "docs": {
900
- const metaGlob = await generateMetaCollectionGlob(
901
- codegen,
902
- parent.meta,
903
- true
904
- );
905
- return `await create.docs("${parent.name}", "${parent.dir}", ${metaGlob}, ${entries.join(", ")})`;
906
- }
907
- case "doc":
908
- return `await create.doc("${collection.name}", "${collection.dir}", ${entries.join(", ")})`;
909
- }
910
- }
911
- await codegen.pushAsync(
912
- core.getConfig().collectionList.map(async (collection) => {
913
- const obj = await generateCollectionObject(collection);
914
- if (!obj) return;
915
- return `
916
- export const ${collection.name} = ${obj};`;
917
- })
918
- );
919
- }
920
- async function generateBrowserIndexFile({ core, codegen, tc }) {
921
- codegen.lines.push(
922
- `import { browser } from 'fumadocs-mdx/runtime/browser';`,
923
- `import type * as Config from '${codegen.formatImportPath(core.getOptions().configPath)}';`,
924
- "",
925
- `const create = browser<typeof Config, ${tc}>();`
926
- );
927
- async function generateCollectionObject(collection) {
928
- switch (collection.type) {
929
- case "docs": {
930
- if (collection.docs.dynamic) return;
931
- return generateCollectionObject(collection.docs);
932
- }
933
- case "doc":
934
- if (collection.dynamic) return;
935
- return `create.doc("${collection.name}", ${await generateDocCollectionGlob(codegen, collection)})`;
936
- }
937
- }
938
- codegen.lines.push("const browserCollections = {");
939
- await codegen.pushAsync(
940
- core.getConfig().collectionList.map(async (collection) => {
941
- const obj = await generateCollectionObject(collection);
942
- if (!obj) return;
943
- return ident(`${collection.name}: ${obj},`);
944
- })
945
- );
946
- codegen.lines.push("};", "export default browserCollections;");
947
- }
948
- function generateDocCollectionFrontmatterGlob(codegen, collection, eager = false) {
949
- return codegen.generateGlobImport(collection.patterns, {
950
- query: {
951
- collection: collection.name,
952
- only: "frontmatter"
953
- },
954
- import: "frontmatter",
955
- base: collection.dir,
956
- eager
957
- });
958
- }
959
- function generateDocCollectionGlob(codegen, collection, eager = false) {
960
- return codegen.generateGlobImport(collection.patterns, {
961
- query: {
962
- collection: collection.name
963
- },
964
- base: collection.dir,
965
- eager
966
- });
967
- }
968
- function generateMetaCollectionGlob(codegen, collection, eager = false) {
969
- return codegen.generateGlobImport(collection.patterns, {
970
- query: {
971
- collection: collection.name
972
- },
973
- import: "default",
974
- base: collection.dir,
975
- eager
976
- });
977
- }
978
- var import_path, import_tinyglobby2, import_crypto;
979
- var init_index_file = __esm({
980
- "src/plugins/index-file.ts"() {
981
- "use strict";
982
- import_path = __toESM(require("path"), 1);
983
- init_codegen();
984
- import_tinyglobby2 = require("tinyglobby");
985
- init_fs_cache();
986
- import_crypto = require("crypto");
987
- init_fuma_matter();
988
- }
989
- });
990
-
991
- // src/next/index.ts
992
- var next_exports = {};
993
- __export(next_exports, {
994
- createMDX: () => createMDX,
995
- postInstall: () => postInstall
996
- });
997
- function createMDX(createOptions = {}) {
998
- const core = createNextCore(applyDefaults(createOptions));
999
- const isDev = process.env.NODE_ENV === "development";
1000
- if (process.env._FUMADOCS_MDX !== "1") {
1001
- process.env._FUMADOCS_MDX = "1";
1002
- void init(isDev, core);
1003
- }
1004
- return (nextConfig = {}) => {
1005
- const loaderOptions = {
1006
- ...core.getOptions(),
1007
- compiledConfigPath: core.getCompiledConfigPath(),
1008
- isDev
1009
- };
1010
- const turbopack = {
1011
- ...nextConfig.turbopack,
1012
- rules: {
1013
- ...nextConfig.turbopack?.rules,
1014
- "*.{md,mdx}": {
1015
- loaders: [
1016
- {
1017
- loader: "fumadocs-mdx/loader-mdx",
1018
- options: loaderOptions
1019
- }
1020
- ],
1021
- as: "*.js"
1022
- },
1023
- "*.json": {
1024
- loaders: [
1025
- {
1026
- loader: "fumadocs-mdx/loader-meta",
1027
- options: loaderOptions
1028
- }
1029
- ],
1030
- as: "*.json"
1031
- },
1032
- "*.yaml": {
1033
- loaders: [
1034
- {
1035
- loader: "fumadocs-mdx/loader-meta",
1036
- options: loaderOptions
1037
- }
1038
- ],
1039
- as: "*.js"
1040
- }
1041
- }
1042
- };
1043
- return {
1044
- ...nextConfig,
1045
- turbopack,
1046
- pageExtensions: nextConfig.pageExtensions ?? defaultPageExtensions,
1047
- webpack: (config, options) => {
1048
- config.resolve ||= {};
1049
- config.module ||= {};
1050
- config.module.rules ||= [];
1051
- config.module.rules.push(
1052
- {
1053
- test: mdxLoaderGlob,
1054
- use: [
1055
- options.defaultLoaders.babel,
1056
- {
1057
- loader: "fumadocs-mdx/loader-mdx",
1058
- options: loaderOptions
1059
- }
1060
- ]
1061
- },
1062
- {
1063
- test: metaLoaderGlob,
1064
- use: [
1065
- options.defaultLoaders.babel,
1066
- {
1067
- loader: "fumadocs-mdx/loader-meta",
1068
- options: loaderOptions
1069
- }
1070
- ]
1071
- }
1072
- );
1073
- config.plugins ||= [];
1074
- return nextConfig.webpack?.(config, options) ?? config;
1075
- }
1076
- };
1077
- };
1078
- }
1079
- async function init(dev, core) {
1080
- async function initOrReload() {
1081
- await core.init({
1082
- config: loadConfig(core, true)
1083
- });
1084
- await core.emitAndWrite();
1085
- }
1086
- async function devServer() {
1087
- const { FSWatcher } = await import("chokidar");
1088
- const { configPath, outDir } = core.getOptions();
1089
- const watcher = new FSWatcher({
1090
- ignoreInitial: true,
1091
- persistent: true,
1092
- ignored: [outDir]
1093
- });
1094
- watcher.add(configPath);
1095
- for (const collection of core.getConfig().collectionList) {
1096
- if (collection.type === "docs") {
1097
- watcher.add(collection.docs.dir);
1098
- watcher.add(collection.meta.dir);
1099
- } else {
1100
- watcher.add(collection.dir);
1101
- }
1102
- }
1103
- watcher.on("ready", () => {
1104
- console.log("[MDX] started dev server");
1105
- });
1106
- const absoluteConfigPath = path5.resolve(configPath);
1107
- watcher.on("all", async (_event, file) => {
1108
- if (path5.resolve(file) === absoluteConfigPath) {
1109
- watcher.removeAllListeners();
1110
- await watcher.close();
1111
- await initOrReload();
1112
- console.log("[MDX] restarting dev server");
1113
- await devServer();
1114
- }
1115
- });
1116
- process.on("exit", () => {
1117
- if (watcher.closed) return;
1118
- console.log("[MDX] closing dev server");
1119
- void watcher.close();
1120
- });
1121
- await core.initServer({ watcher });
1122
- }
1123
- await initOrReload();
1124
- if (dev) {
1125
- await devServer();
1126
- }
1127
- }
1128
- async function postInstall(options) {
1129
- const core = createNextCore(applyDefaults(options));
1130
- await core.init({
1131
- config: loadConfig(core, true)
1132
- });
1133
- await core.emitAndWrite();
1134
- }
1135
- function applyDefaults(options) {
1136
- return {
1137
- index: {},
1138
- outDir: options.outDir ?? _Defaults.outDir,
1139
- configPath: options.configPath ?? _Defaults.configPath
1140
- };
1141
- }
1142
- function createNextCore(options) {
1143
- const core = createCore(
1144
- {
1145
- environment: "next",
1146
- outDir: options.outDir,
1147
- configPath: options.configPath
1148
- },
1149
- [options.index && indexFile(options.index)]
1150
- );
1151
- return {
1152
- ...core,
1153
- async emitAndWrite(...args) {
1154
- try {
1155
- await core.emitAndWrite(...args);
1156
- } catch (err) {
1157
- if (err instanceof ValidationError) {
1158
- console.error(await err.toStringFormatted());
1159
- } else {
1160
- console.error(err);
1161
- }
1162
- }
1163
- }
1164
- };
1165
- }
1166
- var path5, defaultPageExtensions;
1167
- var init_next = __esm({
1168
- "src/next/index.ts"() {
1169
- "use strict";
1170
- path5 = __toESM(require("path"), 1);
1171
- init_load_from_file();
1172
- init_validation();
1173
- init_core();
1174
- init_loaders();
1175
- init_index_file();
1176
- defaultPageExtensions = ["mdx", "md", "jsx", "js", "tsx", "ts"];
1177
- }
1178
- });
1179
-
1180
- // src/loaders/mdx/remark-unravel.ts
1181
- function remarkMarkAndUnravel() {
1182
- return (tree) => {
1183
- (0, import_unist_util_visit.visit)(tree, function(node, index, parent) {
1184
- let offset = -1;
1185
- let all = true;
1186
- let oneOrMore = false;
1187
- if (parent && typeof index === "number" && node.type === "paragraph") {
1188
- const children = node.children;
1189
- while (++offset < children.length) {
1190
- const child = children[offset];
1191
- if (child.type === "mdxJsxTextElement" || child.type === "mdxTextExpression") {
1192
- oneOrMore = true;
1193
- } else if (child.type === "text" && child.value.trim().length === 0) {
1194
- } else {
1195
- all = false;
1196
- break;
1197
- }
1198
- }
1199
- if (all && oneOrMore) {
1200
- offset = -1;
1201
- const newChildren = [];
1202
- while (++offset < children.length) {
1203
- const child = children[offset];
1204
- if (child.type === "mdxJsxTextElement") {
1205
- child.type = "mdxJsxFlowElement";
1206
- }
1207
- if (child.type === "mdxTextExpression") {
1208
- child.type = "mdxFlowExpression";
1209
- }
1210
- if (child.type === "text" && /^[\t\r\n ]+$/.test(String(child.value))) {
1211
- } else {
1212
- newChildren.push(child);
1213
- }
1214
- }
1215
- parent.children.splice(index, 1, ...newChildren);
1216
- return index;
1217
- }
1218
- }
1219
- });
1220
- };
1221
- }
1222
- var import_unist_util_visit;
1223
- var init_remark_unravel = __esm({
1224
- "src/loaders/mdx/remark-unravel.ts"() {
1225
- "use strict";
1226
- import_unist_util_visit = require("unist-util-visit");
1227
- }
1228
- });
1229
-
1230
- // src/loaders/mdx/mdast-utils.ts
1231
- function flattenNode(node) {
1232
- if ("children" in node)
1233
- return node.children.map((child) => flattenNode(child)).join("");
1234
- if ("value" in node) return node.value;
1235
- return "";
1236
- }
1237
- var init_mdast_utils = __esm({
1238
- "src/loaders/mdx/mdast-utils.ts"() {
1239
- "use strict";
1240
- }
1241
- });
1242
-
1243
- // src/loaders/mdx/remark-include.ts
1244
- function isElementLike(node) {
1245
- return ElementLikeTypes.includes(node.type);
1246
- }
1247
- function parseElementAttributes(element) {
1248
- if (Array.isArray(element.attributes)) {
1249
- const attributes = {};
1250
- for (const attr of element.attributes) {
1251
- if (attr.type === "mdxJsxAttribute" && (typeof attr.value === "string" || attr.value === null)) {
1252
- attributes[attr.name] = attr.value;
1253
- }
1254
- }
1255
- return attributes;
1256
- }
1257
- return element.attributes ?? {};
1258
- }
1259
- function parseSpecifier(specifier) {
1260
- const idx = specifier.lastIndexOf("#");
1261
- if (idx === -1) return { file: specifier };
1262
- return {
1263
- file: specifier.slice(0, idx),
1264
- section: specifier.slice(idx + 1)
1265
- };
1266
- }
1267
- function extractSection(root, section) {
1268
- let nodes;
1269
- let capturingHeadingContent = false;
1270
- (0, import_unist_util_visit2.visit)(root, (node) => {
1271
- if (node.type === "heading") {
1272
- if (capturingHeadingContent) {
1273
- return false;
1274
- }
1275
- if (node.data?.hProperties?.id === section) {
1276
- capturingHeadingContent = true;
1277
- nodes = [node];
1278
- return "skip";
1279
- }
1280
- return;
1281
- }
1282
- if (capturingHeadingContent) {
1283
- nodes?.push(node);
1284
- return "skip";
1285
- }
1286
- if (isElementLike(node) && node.name === "section") {
1287
- const attributes = parseElementAttributes(node);
1288
- if (attributes.id === section) {
1289
- nodes = node.children;
1290
- return false;
1291
- }
1292
- }
1293
- });
1294
- if (nodes)
1295
- return {
1296
- type: "root",
1297
- children: nodes
1298
- };
1299
- }
1300
- function remarkInclude() {
1301
- const TagName = "include";
1302
- const embedContent = async (file, heading, params, data) => {
1303
- let content;
1304
- try {
1305
- content = (await fs3.readFile(file)).toString();
1306
- } catch (e) {
1307
- throw new Error(
1308
- `failed to read file ${file}
1309
- ${e instanceof Error ? e.message : String(e)}`,
1310
- { cause: e }
1311
- );
1312
- }
1313
- const ext = path6.extname(file);
1314
- data._compiler?.addDependency(file);
1315
- if (params.lang || ext !== ".md" && ext !== ".mdx") {
1316
- const lang = params.lang ?? ext.slice(1);
1317
- return {
1318
- type: "code",
1319
- lang,
1320
- meta: params.meta,
1321
- value: content,
1322
- data: {}
1323
- };
1324
- }
1325
- const parser = data._getProcessor ? data._getProcessor(ext === ".mdx" ? "mdx" : "md") : this;
1326
- const parsed = fumaMatter(content);
1327
- let mdast = parser.parse({
1328
- path: file,
1329
- value: parsed.content,
1330
- data: { frontmatter: parsed.data }
1331
- });
1332
- const baseProcessor = (0, import_unified.unified)().use(remarkMarkAndUnravel);
1333
- if (heading) {
1334
- const extracted = extractSection(
1335
- await baseProcessor.use(import_mdx_plugins.remarkHeading).run(mdast),
1336
- heading
1337
- );
1338
- if (!extracted)
1339
- throw new Error(
1340
- `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.`
1341
- );
1342
- mdast = extracted;
1343
- } else {
1344
- mdast = await baseProcessor.run(mdast);
1345
- }
1346
- await update(mdast, path6.dirname(file), data);
1347
- return mdast;
1348
- };
1349
- async function update(tree, directory, data) {
1350
- const queue = [];
1351
- (0, import_unist_util_visit2.visit)(tree, ElementLikeTypes, (_node, _, parent) => {
1352
- const node = _node;
1353
- if (node.name !== TagName) return;
1354
- const specifier = flattenNode(node);
1355
- if (specifier.length === 0) return "skip";
1356
- const attributes = parseElementAttributes(node);
1357
- const { file: relativePath, section } = parseSpecifier(specifier);
1358
- const file = path6.resolve(
1359
- "cwd" in attributes ? process.cwd() : directory,
1360
- relativePath
1361
- );
1362
- queue.push(
1363
- embedContent(file, section, attributes, data).then((replace) => {
1364
- Object.assign(
1365
- parent && parent.type === "paragraph" ? parent : node,
1366
- replace
1367
- );
1368
- })
1369
- );
1370
- return "skip";
1371
- });
1372
- await Promise.all(queue);
1373
- }
1374
- return async (tree, file) => {
1375
- await update(tree, path6.dirname(file.path), file.data);
1376
- };
1377
- }
1378
- var import_unified, import_unist_util_visit2, path6, fs3, import_mdx_plugins, ElementLikeTypes;
1379
- var init_remark_include = __esm({
1380
- "src/loaders/mdx/remark-include.ts"() {
1381
- "use strict";
1382
- import_unified = require("unified");
1383
- import_unist_util_visit2 = require("unist-util-visit");
1384
- path6 = __toESM(require("path"), 1);
1385
- fs3 = __toESM(require("fs/promises"), 1);
1386
- init_fuma_matter();
1387
- import_mdx_plugins = require("fumadocs-core/mdx-plugins");
1388
- init_remark_unravel();
1389
- init_mdast_utils();
1390
- ElementLikeTypes = [
1391
- "mdxJsxFlowElement",
1392
- "mdxJsxTextElement",
1393
- "containerDirective",
1394
- "textDirective",
1395
- "leafDirective"
1396
- ];
1397
- }
1398
- });
1399
-
1400
- // src/loaders/mdx/remark-postprocess.ts
1401
- function remarkPostprocess({
1402
- _format,
1403
- includeProcessedMarkdown = false,
1404
- includeMDAST = false,
1405
- extractLinkReferences = false,
1406
- valueToExport = []
1407
- }) {
1408
- let _stringifyProcessor;
1409
- const getStringifyProcessor = () => {
1410
- return _stringifyProcessor ??= _format === "mdx" ? this : (
1411
- // force Markdown processor to stringify MDX nodes
1412
- this().use(import_remark_mdx.default).freeze()
1413
- );
1414
- };
1415
- return (tree, file) => {
1416
- const frontmatter = file.data.frontmatter ??= {};
1417
- if (!frontmatter.title) {
1418
- (0, import_unist_util_visit3.visit)(tree, "heading", (node) => {
1419
- if (node.depth === 1) {
1420
- frontmatter.title = flattenNode(node);
1421
- return false;
1422
- }
1423
- });
1424
- }
1425
- file.data["mdx-export"] ??= [];
1426
- if (extractLinkReferences) {
1427
- const urls = [];
1428
- (0, import_unist_util_visit3.visit)(tree, "link", (node) => {
1429
- urls.push({
1430
- href: node.url
1431
- });
1432
- return "skip";
1433
- });
1434
- file.data["mdx-export"].push({
1435
- name: "extractedReferences",
1436
- value: urls
1437
- });
1438
- }
1439
- if (includeProcessedMarkdown) {
1440
- const processor = getStringifyProcessor();
1441
- const markdown = (0, import_mdast_util_to_markdown.toMarkdown)(tree, {
1442
- ...processor.data("settings"),
1443
- // from https://github.com/remarkjs/remark/blob/main/packages/remark-stringify/lib/index.js
1444
- extensions: processor.data("toMarkdownExtensions") || []
1445
- });
1446
- file.data["mdx-export"].push({
1447
- name: "_markdown",
1448
- value: markdown
1449
- });
1450
- }
1451
- if (includeMDAST) {
1452
- const options = includeMDAST === true ? {} : includeMDAST;
1453
- const mdast = JSON.stringify(
1454
- options.removePosition ? (0, import_unist_util_remove_position.removePosition)(structuredClone(tree)) : tree
1455
- );
1456
- file.data["mdx-export"].push({
1457
- name: "_mdast",
1458
- value: mdast
1459
- });
1460
- }
1461
- for (const { name, value } of file.data["mdx-export"]) {
1462
- tree.children.unshift(getMdastExport(name, value));
1463
- }
1464
- file.data["mdx-export"] = [];
1465
- for (const name of valueToExport) {
1466
- if (!(name in file.data)) continue;
1467
- tree.children.unshift(getMdastExport(name, file.data[name]));
1468
- }
1469
- };
1470
- }
1471
- function getMdastExport(name, value) {
1472
- return {
1473
- type: "mdxjsEsm",
1474
- value: "",
1475
- data: {
1476
- estree: {
1477
- type: "Program",
1478
- sourceType: "module",
1479
- body: [
1480
- {
1481
- type: "ExportNamedDeclaration",
1482
- attributes: [],
1483
- specifiers: [],
1484
- source: null,
1485
- declaration: {
1486
- type: "VariableDeclaration",
1487
- kind: "let",
1488
- declarations: [
1489
- {
1490
- type: "VariableDeclarator",
1491
- id: {
1492
- type: "Identifier",
1493
- name
1494
- },
1495
- init: (0, import_estree_util_value_to_estree.valueToEstree)(value)
1496
- }
1497
- ]
1498
- }
1499
- }
1500
- ]
1501
- }
1502
- }
1503
- };
1504
- }
1505
- var import_unist_util_visit3, import_mdast_util_to_markdown, import_estree_util_value_to_estree, import_unist_util_remove_position, import_remark_mdx;
1506
- var init_remark_postprocess = __esm({
1507
- "src/loaders/mdx/remark-postprocess.ts"() {
1508
- "use strict";
1509
- import_unist_util_visit3 = require("unist-util-visit");
1510
- import_mdast_util_to_markdown = require("mdast-util-to-markdown");
1511
- import_estree_util_value_to_estree = require("estree-util-value-to-estree");
1512
- import_unist_util_remove_position = require("unist-util-remove-position");
1513
- import_remark_mdx = __toESM(require("remark-mdx"), 1);
1514
- init_mdast_utils();
1515
- }
1516
- });
1517
-
1518
- // src/loaders/mdx/build-mdx.ts
1519
- var build_mdx_exports = {};
1520
- __export(build_mdx_exports, {
1521
- buildMDX: () => buildMDX
1522
- });
1523
- async function buildMDX(core, collection, {
1524
- filePath,
1525
- frontmatter,
1526
- source,
1527
- _compiler,
1528
- environment,
1529
- isDevelopment
1530
- }) {
1531
- const mdxOptions = await core.getConfig().getMDXOptions(collection, environment);
1532
- function getProcessor(format) {
1533
- const cache = core.cache;
1534
- const key = `build-mdx:${collection?.name ?? "global"}:${format}`;
1535
- let processor = cache.get(key);
1536
- if (!processor) {
1537
- const postprocessOptions = {
1538
- _format: format,
1539
- ...collection?.postprocess,
1540
- valueToExport: [
1541
- ...collection?.postprocess?.valueToExport ?? [],
1542
- "structuredData",
1543
- "frontmatter"
1544
- ]
1545
- };
1546
- processor = (0, import_mdx.createProcessor)({
1547
- outputFormat: "program",
1548
- development: isDevelopment,
1549
- ...mdxOptions,
1550
- remarkPlugins: [
1551
- remarkInclude,
1552
- ...mdxOptions.remarkPlugins ?? [],
1553
- [remarkPostprocess, postprocessOptions]
1554
- ],
1555
- format
1556
- });
1557
- cache.set(key, processor);
1558
- }
1559
- return processor;
1560
- }
1561
- let vfile = new import_vfile.VFile({
1562
- value: source,
1563
- path: filePath,
1564
- data: { frontmatter, _compiler, _getProcessor: getProcessor }
1565
- });
1566
- if (collection) {
1567
- vfile = await core.transformVFile({ collection, filePath, source }, vfile);
1568
- }
1569
- return getProcessor(filePath.endsWith(".mdx") ? "mdx" : "md").process(vfile);
1570
- }
1571
- var import_mdx, import_vfile;
1572
- var init_build_mdx = __esm({
1573
- "src/loaders/mdx/build-mdx.ts"() {
1574
- "use strict";
1575
- import_mdx = require("@mdx-js/mdx");
1576
- import_vfile = require("vfile");
1577
- init_remark_include();
1578
- init_remark_postprocess();
1579
- }
1580
- });
1581
-
1582
- // src/loaders/mdx/index.ts
1583
- function createMdxLoader(configLoader) {
1584
- return {
1585
- test: mdxLoaderGlob,
1586
- async load({
1587
- getSource,
1588
- development: isDevelopment,
1589
- query,
1590
- compiler,
1591
- filePath
1592
- }) {
1593
- const config = await configLoader.getConfig();
1594
- const value = await getSource();
1595
- const matter = fumaMatter(value);
1596
- const parsed = querySchema.parse(query);
1597
- let after;
1598
- if (!isDevelopment && config.global.experimentalBuildCache) {
1599
- const cacheDir = config.global.experimentalBuildCache;
1600
- const cacheKey = `${parsed.hash}_${parsed.collection ?? "global"}_${generateCacheHash(filePath)}`;
1601
- const cached = await import_promises3.default.readFile(import_node_path4.default.join(cacheDir, cacheKey)).then((content) => cacheEntry.parse(JSON.parse(content.toString()))).catch(() => null);
1602
- if (cached && cached.hash === generateCacheHash(value)) return cached;
1603
- after = async () => {
1604
- await import_promises3.default.mkdir(cacheDir, { recursive: true });
1605
- await import_promises3.default.writeFile(
1606
- import_node_path4.default.join(cacheDir, cacheKey),
1607
- JSON.stringify({
1608
- ...out,
1609
- hash: generateCacheHash(value)
1610
- })
1611
- );
1612
- };
1613
- }
1614
- const collection = parsed.collection ? config.getCollection(parsed.collection) : void 0;
1615
- let docCollection;
1616
- switch (collection?.type) {
1617
- case "doc":
1618
- docCollection = collection;
1619
- break;
1620
- case "docs":
1621
- docCollection = collection.docs;
1622
- break;
1623
- }
1624
- if (docCollection) {
1625
- matter.data = await configLoader.core.transformFrontmatter(
1626
- { collection: docCollection, filePath, source: value },
1627
- matter.data
1628
- );
1629
- }
1630
- if (parsed.only === "frontmatter") {
1631
- return {
1632
- code: `export const frontmatter = ${JSON.stringify(matter.data)}`,
1633
- map: null
1634
- };
1635
- }
1636
- const lineOffset = isDevelopment ? countLines(matter.matter) : 0;
1637
- const { buildMDX: buildMDX2 } = await Promise.resolve().then(() => (init_build_mdx(), build_mdx_exports));
1638
- const compiled = await buildMDX2(configLoader.core, docCollection, {
1639
- isDevelopment,
1640
- source: "\n".repeat(lineOffset) + matter.content,
1641
- filePath,
1642
- frontmatter: matter.data,
1643
- _compiler: compiler,
1644
- environment: "bundler"
1645
- });
1646
- const out = {
1647
- code: String(compiled.value),
1648
- map: compiled.map
1649
- };
1650
- await after?.();
1651
- return out;
1652
- }
1653
- };
1654
- }
1655
- function generateCacheHash(input) {
1656
- return (0, import_node_crypto.createHash)("md5").update(input).digest("hex");
1657
- }
1658
- function countLines(s) {
1659
- let num = 0;
1660
- for (const c of s) {
1661
- if (c === "\n") num++;
1662
- }
1663
- return num;
1664
- }
1665
- var import_zod, import_promises3, import_node_path4, import_node_crypto, querySchema, cacheEntry;
1666
- var init_mdx = __esm({
1667
- "src/loaders/mdx/index.ts"() {
1668
- "use strict";
1669
- init_fuma_matter();
1670
- import_zod = require("zod");
1671
- import_promises3 = __toESM(require("fs/promises"), 1);
1672
- import_node_path4 = __toESM(require("path"), 1);
1673
- import_node_crypto = require("crypto");
1674
- init_loaders();
1675
- querySchema = import_zod.z.object({
1676
- only: import_zod.z.literal(["frontmatter", "all"]).default("all"),
1677
- collection: import_zod.z.string().optional()
1678
- }).loose();
1679
- cacheEntry = import_zod.z.object({
1680
- code: import_zod.z.string(),
1681
- map: import_zod.z.any().optional(),
1682
- hash: import_zod.z.string().optional()
1683
- });
1684
- }
1685
- });
1686
-
1687
- // src/loaders/adapter.ts
1688
- function toVite(loader) {
1689
- return {
1690
- filter(id) {
1691
- return !loader.test || loader.test.test(id);
1692
- },
1693
- async transform(value, id) {
1694
- const [file, query = ""] = id.split("?", 2);
1695
- const result = await loader.load({
1696
- filePath: file,
1697
- query: (0, import_node_querystring.parse)(query),
1698
- getSource() {
1699
- return value;
1700
- },
1701
- development: this.environment.mode === "dev",
1702
- compiler: {
1703
- addDependency: (file2) => {
1704
- this.addWatchFile(file2);
1705
- }
1706
- }
1707
- });
1708
- if (result === null) return null;
1709
- return {
1710
- code: result.code,
1711
- map: result.map
1712
- };
1713
- }
1714
- };
1715
- }
1716
- var import_node_url2, import_promises4, import_node_querystring, import_node_path5, import_node_fs;
1717
- var init_adapter = __esm({
1718
- "src/loaders/adapter.ts"() {
1719
- "use strict";
1720
- import_node_url2 = require("url");
1721
- import_promises4 = __toESM(require("fs/promises"), 1);
1722
- import_node_querystring = require("querystring");
1723
- init_validation();
1724
- import_node_path5 = __toESM(require("path"), 1);
1725
- import_node_fs = require("fs");
1726
- }
1727
- });
1728
-
1729
- // src/loaders/config.ts
1730
- function createIntegratedConfigLoader(core) {
1731
- return {
1732
- core,
1733
- getConfig() {
1734
- return core.getConfig();
1735
- }
1736
- };
1737
- }
1738
- var import_promises5;
1739
- var init_config = __esm({
1740
- "src/loaders/config.ts"() {
1741
- "use strict";
1742
- import_promises5 = __toESM(require("fs/promises"), 1);
1743
- }
1744
- });
1745
-
1746
- // src/loaders/meta.ts
1747
- function createMetaLoader(configLoader, resolve3 = {}) {
1748
- const { json: resolveJson = "js", yaml: resolveYaml = "js" } = resolve3;
1749
- function parse2(filePath, source) {
1750
- try {
1751
- if (filePath.endsWith(".json")) return JSON.parse(source);
1752
- if (filePath.endsWith(".yaml")) return (0, import_js_yaml2.load)(source);
1753
- } catch (e) {
1754
- throw new Error(`invalid data in ${filePath}`, { cause: e });
1755
- }
1756
- throw new Error("Unknown file type " + filePath);
1757
- }
1758
- function onMeta(source, { filePath, query }) {
1759
- const parsed = querySchema2.safeParse(query);
1760
- if (!parsed.success || !parsed.data.collection) return null;
1761
- const collectionName = parsed.data.collection;
1762
- return async () => {
1763
- const config = await configLoader.getConfig();
1764
- const collection = config.getCollection(collectionName);
1765
- let metaCollection;
1766
- switch (collection?.type) {
1767
- case "meta":
1768
- metaCollection = collection;
1769
- break;
1770
- case "docs":
1771
- metaCollection = collection.meta;
1772
- break;
1773
- }
1774
- const data = parse2(filePath, source);
1775
- if (!metaCollection) return data;
1776
- return configLoader.core.transformMeta(
1777
- {
1778
- collection: metaCollection,
1779
- filePath,
1780
- source
1781
- },
1782
- data
1783
- );
1784
- };
1785
- }
1786
- return {
1787
- test: metaLoaderGlob,
1788
- async load(input) {
1789
- const result = onMeta(await input.getSource(), input);
1790
- if (result === null) return null;
1791
- const data = await result();
1792
- if (input.filePath.endsWith(".json")) {
1793
- return {
1794
- code: resolveJson === "json" ? JSON.stringify(data) : `export default ${JSON.stringify(data)}`
1795
- };
1796
- } else {
1797
- return {
1798
- code: resolveYaml === "yaml" ? (0, import_js_yaml2.dump)(data) : `export default ${JSON.stringify(data)}`
1799
- };
1800
- }
1801
- },
1802
- bun: {
1803
- load(source, input) {
1804
- const result = onMeta(source, input);
1805
- if (result === null)
1806
- return {
1807
- loader: "object",
1808
- exports: parse2(input.filePath, source)
1809
- };
1810
- return result().then((data) => ({
1811
- loader: "object",
1812
- exports: { default: data }
1813
- }));
1814
- }
1815
- }
1816
- };
1817
- }
1818
- var import_js_yaml2, import_zod2, querySchema2;
1819
- var init_meta = __esm({
1820
- "src/loaders/meta.ts"() {
1821
- "use strict";
1822
- import_js_yaml2 = require("js-yaml");
1823
- import_zod2 = require("zod");
1824
- init_loaders();
1825
- querySchema2 = import_zod2.z.object({
1826
- collection: import_zod2.z.string().optional()
1827
- }).loose();
1828
- }
1829
- });
1830
-
1831
- // src/vite/index.ts
1832
- var vite_exports = {};
1833
- __export(vite_exports, {
1834
- default: () => mdx,
1835
- postInstall: () => postInstall2
1836
- });
1837
- async function mdx(config, pluginOptions = {}) {
1838
- const options = applyDefaults2(pluginOptions);
1839
- const core = createViteCore(options);
1840
- await core.init({
1841
- config: buildConfig(config)
1842
- });
1843
- const configLoader = createIntegratedConfigLoader(core);
1844
- const mdxLoader = toVite(createMdxLoader(configLoader));
1845
- const metaLoader = toVite(
1846
- createMetaLoader(configLoader, {
1847
- // vite has built-in plugin for JSON files
1848
- json: "json"
1849
- })
1850
- );
1851
- return {
1852
- name: "fumadocs-mdx",
1853
- // needed, otherwise other plugins will be executed before our `transform`.
1854
- enforce: "pre",
1855
- config(config2) {
1856
- if (!options.updateViteConfig) return config2;
1857
- return (0, import_vite.mergeConfig)(config2, {
1858
- optimizeDeps: {
1859
- exclude: FumadocsDeps
1860
- },
1861
- resolve: {
1862
- noExternal: FumadocsDeps,
1863
- dedupe: FumadocsDeps
1864
- }
1865
- });
1866
- },
1867
- async buildStart() {
1868
- await core.emitAndWrite();
1869
- },
1870
- async configureServer(server) {
1871
- await core.initServer({
1872
- watcher: server.watcher
1873
- });
1874
- },
1875
- async transform(value, id) {
1876
- try {
1877
- if (metaLoader.filter(id)) {
1878
- return await metaLoader.transform.call(this, value, id);
1879
- }
1880
- if (mdxLoader.filter(id)) {
1881
- return await mdxLoader.transform.call(this, value, id);
1882
- }
1883
- } catch (e) {
1884
- if (e instanceof ValidationError) {
1885
- throw new Error(await e.toStringFormatted());
1886
- }
1887
- throw e;
1888
- }
1889
- }
1890
- };
1891
- }
1892
- async function postInstall2(pluginOptions = {}) {
1893
- const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_load_from_file(), load_from_file_exports));
1894
- const core = createViteCore(applyDefaults2(pluginOptions));
1895
- await core.init({
1896
- config: loadConfig2(core, true)
1897
- });
1898
- await core.emitAndWrite();
1899
- }
1900
- function createViteCore({
1901
- index,
1902
- configPath,
1903
- outDir
1904
- }) {
1905
- if (index === true) index = {};
1906
- return createCore(
1907
- {
1908
- environment: "vite",
1909
- configPath,
1910
- outDir
1911
- },
1912
- [
1913
- index && indexFile({
1914
- ...index,
1915
- target: index.target ?? "vite"
1916
- })
1917
- ]
1918
- );
1919
- }
1920
- function applyDefaults2(options) {
1921
- return {
1922
- updateViteConfig: options.updateViteConfig ?? true,
1923
- index: options.index ?? true,
1924
- configPath: options.configPath ?? _Defaults.configPath,
1925
- outDir: options.outDir ?? _Defaults.outDir
1926
- };
1927
- }
1928
- var import_vite, FumadocsDeps;
1929
- var init_vite = __esm({
1930
- "src/vite/index.ts"() {
1931
- "use strict";
1932
- import_vite = require("vite");
1933
- init_build();
1934
- init_validation();
1935
- init_mdx();
1936
- init_adapter();
1937
- init_core();
1938
- init_config();
1939
- init_meta();
1940
- init_index_file();
1941
- FumadocsDeps = ["fumadocs-core", "fumadocs-ui", "fumadocs-openapi"];
1942
- }
1943
- });
1944
-
1945
- // src/bin.ts
1946
- var import_node_fs2 = require("fs");
1947
- async function start() {
1948
- const [configPath, outDir] = process.argv.slice(2);
1949
- const isNext = (0, import_node_fs2.existsSync)("next.config.js") || (0, import_node_fs2.existsSync)("next.config.mjs") || (0, import_node_fs2.existsSync)("next.config.mts") || (0, import_node_fs2.existsSync)("next.config.ts");
1950
- if (isNext) {
1951
- const { postInstall: postInstall3 } = await Promise.resolve().then(() => (init_next(), next_exports));
1952
- await postInstall3({ configPath, outDir });
1953
- } else {
1954
- const { postInstall: postInstall3 } = await Promise.resolve().then(() => (init_vite(), vite_exports));
1955
- await postInstall3({ configPath, outDir });
1956
- }
1957
- }
1958
- void start();