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
@@ -1,1687 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
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/utils/fuma-matter.ts
226
- function fumaMatter(input) {
227
- const output = { matter: "", data: {}, content: input };
228
- const match = regex.exec(input);
229
- if (!match) {
230
- return output;
231
- }
232
- output.matter = match[0];
233
- output.content = input.slice(match[0].length);
234
- const loaded = (0, import_js_yaml.load)(match[1]);
235
- output.data = loaded ?? {};
236
- return output;
237
- }
238
- var import_js_yaml, regex;
239
- var init_fuma_matter = __esm({
240
- "src/utils/fuma-matter.ts"() {
241
- "use strict";
242
- import_js_yaml = require("js-yaml");
243
- regex = /^---\r?\n(.+?)\r?\n---\r?\n/s;
244
- }
245
- });
246
-
247
- // src/loaders/mdx/remark-unravel.ts
248
- function remarkMarkAndUnravel() {
249
- return (tree) => {
250
- (0, import_unist_util_visit.visit)(tree, function(node, index, parent) {
251
- let offset = -1;
252
- let all = true;
253
- let oneOrMore = false;
254
- if (parent && typeof index === "number" && node.type === "paragraph") {
255
- const children = node.children;
256
- while (++offset < children.length) {
257
- const child = children[offset];
258
- if (child.type === "mdxJsxTextElement" || child.type === "mdxTextExpression") {
259
- oneOrMore = true;
260
- } else if (child.type === "text" && child.value.trim().length === 0) {
261
- } else {
262
- all = false;
263
- break;
264
- }
265
- }
266
- if (all && oneOrMore) {
267
- offset = -1;
268
- const newChildren = [];
269
- while (++offset < children.length) {
270
- const child = children[offset];
271
- if (child.type === "mdxJsxTextElement") {
272
- child.type = "mdxJsxFlowElement";
273
- }
274
- if (child.type === "mdxTextExpression") {
275
- child.type = "mdxFlowExpression";
276
- }
277
- if (child.type === "text" && /^[\t\r\n ]+$/.test(String(child.value))) {
278
- } else {
279
- newChildren.push(child);
280
- }
281
- }
282
- parent.children.splice(index, 1, ...newChildren);
283
- return index;
284
- }
285
- }
286
- });
287
- };
288
- }
289
- var import_unist_util_visit;
290
- var init_remark_unravel = __esm({
291
- "src/loaders/mdx/remark-unravel.ts"() {
292
- "use strict";
293
- import_unist_util_visit = require("unist-util-visit");
294
- }
295
- });
296
-
297
- // src/loaders/mdx/mdast-utils.ts
298
- function flattenNode(node) {
299
- if ("children" in node)
300
- return node.children.map((child) => flattenNode(child)).join("");
301
- if ("value" in node) return node.value;
302
- return "";
303
- }
304
- var init_mdast_utils = __esm({
305
- "src/loaders/mdx/mdast-utils.ts"() {
306
- "use strict";
307
- }
308
- });
309
-
310
- // src/loaders/mdx/remark-include.ts
311
- function isElementLike(node) {
312
- return ElementLikeTypes.includes(node.type);
313
- }
314
- function parseElementAttributes(element) {
315
- if (Array.isArray(element.attributes)) {
316
- const attributes = {};
317
- for (const attr of element.attributes) {
318
- if (attr.type === "mdxJsxAttribute" && (typeof attr.value === "string" || attr.value === null)) {
319
- attributes[attr.name] = attr.value;
320
- }
321
- }
322
- return attributes;
323
- }
324
- return element.attributes ?? {};
325
- }
326
- function parseSpecifier(specifier) {
327
- const idx = specifier.lastIndexOf("#");
328
- if (idx === -1) return { file: specifier };
329
- return {
330
- file: specifier.slice(0, idx),
331
- section: specifier.slice(idx + 1)
332
- };
333
- }
334
- function extractSection(root, section) {
335
- let nodes;
336
- let capturingHeadingContent = false;
337
- (0, import_unist_util_visit2.visit)(root, (node) => {
338
- if (node.type === "heading") {
339
- if (capturingHeadingContent) {
340
- return false;
341
- }
342
- if (node.data?.hProperties?.id === section) {
343
- capturingHeadingContent = true;
344
- nodes = [node];
345
- return "skip";
346
- }
347
- return;
348
- }
349
- if (capturingHeadingContent) {
350
- nodes?.push(node);
351
- return "skip";
352
- }
353
- if (isElementLike(node) && node.name === "section") {
354
- const attributes = parseElementAttributes(node);
355
- if (attributes.id === section) {
356
- nodes = node.children;
357
- return false;
358
- }
359
- }
360
- });
361
- if (nodes)
362
- return {
363
- type: "root",
364
- children: nodes
365
- };
366
- }
367
- function remarkInclude() {
368
- const TagName = "include";
369
- const embedContent = async (file, heading, params, data) => {
370
- let content;
371
- try {
372
- content = (await fs.readFile(file)).toString();
373
- } catch (e) {
374
- throw new Error(
375
- `failed to read file ${file}
376
- ${e instanceof Error ? e.message : String(e)}`,
377
- { cause: e }
378
- );
379
- }
380
- const ext = path.extname(file);
381
- data._compiler?.addDependency(file);
382
- if (params.lang || ext !== ".md" && ext !== ".mdx") {
383
- const lang = params.lang ?? ext.slice(1);
384
- return {
385
- type: "code",
386
- lang,
387
- meta: params.meta,
388
- value: content,
389
- data: {}
390
- };
391
- }
392
- const parser = data._getProcessor ? data._getProcessor(ext === ".mdx" ? "mdx" : "md") : this;
393
- const parsed = fumaMatter(content);
394
- let mdast = parser.parse({
395
- path: file,
396
- value: parsed.content,
397
- data: { frontmatter: parsed.data }
398
- });
399
- const baseProcessor = (0, import_unified.unified)().use(remarkMarkAndUnravel);
400
- if (heading) {
401
- const extracted = extractSection(
402
- await baseProcessor.use(import_mdx_plugins.remarkHeading).run(mdast),
403
- heading
404
- );
405
- if (!extracted)
406
- throw new Error(
407
- `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.`
408
- );
409
- mdast = extracted;
410
- } else {
411
- mdast = await baseProcessor.run(mdast);
412
- }
413
- await update(mdast, path.dirname(file), data);
414
- return mdast;
415
- };
416
- async function update(tree, directory, data) {
417
- const queue = [];
418
- (0, import_unist_util_visit2.visit)(tree, ElementLikeTypes, (_node, _, parent) => {
419
- const node = _node;
420
- if (node.name !== TagName) return;
421
- const specifier = flattenNode(node);
422
- if (specifier.length === 0) return "skip";
423
- const attributes = parseElementAttributes(node);
424
- const { file: relativePath, section } = parseSpecifier(specifier);
425
- const file = path.resolve(
426
- "cwd" in attributes ? process.cwd() : directory,
427
- relativePath
428
- );
429
- queue.push(
430
- embedContent(file, section, attributes, data).then((replace) => {
431
- Object.assign(
432
- parent && parent.type === "paragraph" ? parent : node,
433
- replace
434
- );
435
- })
436
- );
437
- return "skip";
438
- });
439
- await Promise.all(queue);
440
- }
441
- return async (tree, file) => {
442
- await update(tree, path.dirname(file.path), file.data);
443
- };
444
- }
445
- var import_unified, import_unist_util_visit2, path, fs, import_mdx_plugins, ElementLikeTypes;
446
- var init_remark_include = __esm({
447
- "src/loaders/mdx/remark-include.ts"() {
448
- "use strict";
449
- import_unified = require("unified");
450
- import_unist_util_visit2 = require("unist-util-visit");
451
- path = __toESM(require("path"), 1);
452
- fs = __toESM(require("fs/promises"), 1);
453
- init_fuma_matter();
454
- import_mdx_plugins = require("fumadocs-core/mdx-plugins");
455
- init_remark_unravel();
456
- init_mdast_utils();
457
- ElementLikeTypes = [
458
- "mdxJsxFlowElement",
459
- "mdxJsxTextElement",
460
- "containerDirective",
461
- "textDirective",
462
- "leafDirective"
463
- ];
464
- }
465
- });
466
-
467
- // src/loaders/mdx/remark-postprocess.ts
468
- function remarkPostprocess({
469
- _format,
470
- includeProcessedMarkdown = false,
471
- includeMDAST = false,
472
- extractLinkReferences = false,
473
- valueToExport = []
474
- }) {
475
- let _stringifyProcessor;
476
- const getStringifyProcessor = () => {
477
- return _stringifyProcessor ??= _format === "mdx" ? this : (
478
- // force Markdown processor to stringify MDX nodes
479
- this().use(import_remark_mdx.default).freeze()
480
- );
481
- };
482
- return (tree, file) => {
483
- const frontmatter = file.data.frontmatter ??= {};
484
- if (!frontmatter.title) {
485
- (0, import_unist_util_visit3.visit)(tree, "heading", (node) => {
486
- if (node.depth === 1) {
487
- frontmatter.title = flattenNode(node);
488
- return false;
489
- }
490
- });
491
- }
492
- file.data["mdx-export"] ??= [];
493
- if (extractLinkReferences) {
494
- const urls = [];
495
- (0, import_unist_util_visit3.visit)(tree, "link", (node) => {
496
- urls.push({
497
- href: node.url
498
- });
499
- return "skip";
500
- });
501
- file.data["mdx-export"].push({
502
- name: "extractedReferences",
503
- value: urls
504
- });
505
- }
506
- if (includeProcessedMarkdown) {
507
- const processor = getStringifyProcessor();
508
- const markdown = (0, import_mdast_util_to_markdown.toMarkdown)(tree, {
509
- ...processor.data("settings"),
510
- // from https://github.com/remarkjs/remark/blob/main/packages/remark-stringify/lib/index.js
511
- extensions: processor.data("toMarkdownExtensions") || []
512
- });
513
- file.data["mdx-export"].push({
514
- name: "_markdown",
515
- value: markdown
516
- });
517
- }
518
- if (includeMDAST) {
519
- const options = includeMDAST === true ? {} : includeMDAST;
520
- const mdast = JSON.stringify(
521
- options.removePosition ? (0, import_unist_util_remove_position.removePosition)(structuredClone(tree)) : tree
522
- );
523
- file.data["mdx-export"].push({
524
- name: "_mdast",
525
- value: mdast
526
- });
527
- }
528
- for (const { name, value } of file.data["mdx-export"]) {
529
- tree.children.unshift(getMdastExport(name, value));
530
- }
531
- file.data["mdx-export"] = [];
532
- for (const name of valueToExport) {
533
- if (!(name in file.data)) continue;
534
- tree.children.unshift(getMdastExport(name, file.data[name]));
535
- }
536
- };
537
- }
538
- function getMdastExport(name, value) {
539
- return {
540
- type: "mdxjsEsm",
541
- value: "",
542
- data: {
543
- estree: {
544
- type: "Program",
545
- sourceType: "module",
546
- body: [
547
- {
548
- type: "ExportNamedDeclaration",
549
- attributes: [],
550
- specifiers: [],
551
- source: null,
552
- declaration: {
553
- type: "VariableDeclaration",
554
- kind: "let",
555
- declarations: [
556
- {
557
- type: "VariableDeclarator",
558
- id: {
559
- type: "Identifier",
560
- name
561
- },
562
- init: (0, import_estree_util_value_to_estree.valueToEstree)(value)
563
- }
564
- ]
565
- }
566
- }
567
- ]
568
- }
569
- }
570
- };
571
- }
572
- var import_unist_util_visit3, import_mdast_util_to_markdown, import_estree_util_value_to_estree, import_unist_util_remove_position, import_remark_mdx;
573
- var init_remark_postprocess = __esm({
574
- "src/loaders/mdx/remark-postprocess.ts"() {
575
- "use strict";
576
- import_unist_util_visit3 = require("unist-util-visit");
577
- import_mdast_util_to_markdown = require("mdast-util-to-markdown");
578
- import_estree_util_value_to_estree = require("estree-util-value-to-estree");
579
- import_unist_util_remove_position = require("unist-util-remove-position");
580
- import_remark_mdx = __toESM(require("remark-mdx"), 1);
581
- init_mdast_utils();
582
- }
583
- });
584
-
585
- // src/loaders/mdx/build-mdx.ts
586
- var build_mdx_exports = {};
587
- __export(build_mdx_exports, {
588
- buildMDX: () => buildMDX
589
- });
590
- async function buildMDX(core, collection, {
591
- filePath,
592
- frontmatter,
593
- source,
594
- _compiler,
595
- environment,
596
- isDevelopment
597
- }) {
598
- const mdxOptions = await core.getConfig().getMDXOptions(collection, environment);
599
- function getProcessor(format) {
600
- const cache = core.cache;
601
- const key = `build-mdx:${collection?.name ?? "global"}:${format}`;
602
- let processor = cache.get(key);
603
- if (!processor) {
604
- const postprocessOptions = {
605
- _format: format,
606
- ...collection?.postprocess,
607
- valueToExport: [
608
- ...collection?.postprocess?.valueToExport ?? [],
609
- "structuredData",
610
- "frontmatter"
611
- ]
612
- };
613
- processor = (0, import_mdx.createProcessor)({
614
- outputFormat: "program",
615
- development: isDevelopment,
616
- ...mdxOptions,
617
- remarkPlugins: [
618
- remarkInclude,
619
- ...mdxOptions.remarkPlugins ?? [],
620
- [remarkPostprocess, postprocessOptions]
621
- ],
622
- format
623
- });
624
- cache.set(key, processor);
625
- }
626
- return processor;
627
- }
628
- let vfile = new import_vfile.VFile({
629
- value: source,
630
- path: filePath,
631
- data: { frontmatter, _compiler, _getProcessor: getProcessor }
632
- });
633
- if (collection) {
634
- vfile = await core.transformVFile({ collection, filePath, source }, vfile);
635
- }
636
- return getProcessor(filePath.endsWith(".mdx") ? "mdx" : "md").process(vfile);
637
- }
638
- var import_mdx, import_vfile;
639
- var init_build_mdx = __esm({
640
- "src/loaders/mdx/build-mdx.ts"() {
641
- "use strict";
642
- import_mdx = require("@mdx-js/mdx");
643
- import_vfile = require("vfile");
644
- init_remark_include();
645
- init_remark_postprocess();
646
- }
647
- });
648
-
649
- // src/config/load-from-file.ts
650
- var load_from_file_exports = {};
651
- __export(load_from_file_exports, {
652
- loadConfig: () => loadConfig
653
- });
654
- async function compileConfig(core) {
655
- const { build } = await import("esbuild");
656
- const { configPath, outDir } = core.getOptions();
657
- const transformed = await build({
658
- entryPoints: [{ in: configPath, out: "source.config" }],
659
- bundle: true,
660
- outdir: outDir,
661
- target: "node20",
662
- write: true,
663
- platform: "node",
664
- format: "esm",
665
- packages: "external",
666
- outExtension: {
667
- ".js": ".mjs"
668
- },
669
- allowOverwrite: true
670
- });
671
- if (transformed.errors.length > 0) {
672
- throw new Error("failed to compile configuration file");
673
- }
674
- }
675
- async function loadConfig(core, build = false) {
676
- if (build) await compileConfig(core);
677
- const url = (0, import_node_url2.pathToFileURL)(core.getCompiledConfigPath());
678
- url.searchParams.set("hash", Date.now().toString());
679
- const config = import(url.href).then(
680
- (loaded) => buildConfig(loaded)
681
- );
682
- return await config;
683
- }
684
- var import_node_url2;
685
- var init_load_from_file = __esm({
686
- "src/config/load-from-file.ts"() {
687
- "use strict";
688
- import_node_url2 = require("url");
689
- init_build();
690
- }
691
- });
692
-
693
- // src/vite/index.ts
694
- var vite_exports = {};
695
- __export(vite_exports, {
696
- default: () => mdx,
697
- postInstall: () => postInstall
698
- });
699
- module.exports = __toCommonJS(vite_exports);
700
- var import_vite = require("vite");
701
- init_build();
702
-
703
- // src/utils/validation.ts
704
- var ValidationError = class extends Error {
705
- constructor(message, issues) {
706
- super(
707
- `${message}:
708
- ${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`
709
- );
710
- this.title = message;
711
- this.issues = issues;
712
- }
713
- async toStringFormatted() {
714
- const picocolors = await import("picocolors");
715
- return [
716
- picocolors.bold(`[MDX] ${this.title}:`),
717
- ...this.issues.map(
718
- (issue) => picocolors.redBright(
719
- `- ${picocolors.bold(issue.path?.join(".") ?? "*")}: ${issue.message}`
720
- )
721
- )
722
- ].join("\n");
723
- }
724
- };
725
- async function validate(schema, data, context, errorMessage) {
726
- if (typeof schema === "function" && !("~standard" in schema)) {
727
- schema = schema(context);
728
- }
729
- if ("~standard" in schema) {
730
- const result = await schema["~standard"].validate(
731
- data
732
- );
733
- if (result.issues) {
734
- throw new ValidationError(errorMessage, result.issues);
735
- }
736
- return result.value;
737
- }
738
- return data;
739
- }
740
-
741
- // src/loaders/mdx/index.ts
742
- init_fuma_matter();
743
- var import_zod = require("zod");
744
- var import_promises = __toESM(require("fs/promises"), 1);
745
- var import_node_path = __toESM(require("path"), 1);
746
- var import_node_crypto = require("crypto");
747
-
748
- // src/loaders/index.ts
749
- var metaLoaderGlob = /\.(json|yaml)(\?.+?)?$/;
750
- var mdxLoaderGlob = /\.mdx?(\?.+?)?$/;
751
-
752
- // src/loaders/mdx/index.ts
753
- var querySchema = import_zod.z.object({
754
- only: import_zod.z.literal(["frontmatter", "all"]).default("all"),
755
- collection: import_zod.z.string().optional()
756
- }).loose();
757
- var cacheEntry = import_zod.z.object({
758
- code: import_zod.z.string(),
759
- map: import_zod.z.any().optional(),
760
- hash: import_zod.z.string().optional()
761
- });
762
- function createMdxLoader(configLoader) {
763
- return {
764
- test: mdxLoaderGlob,
765
- async load({
766
- getSource,
767
- development: isDevelopment,
768
- query,
769
- compiler,
770
- filePath
771
- }) {
772
- const config = await configLoader.getConfig();
773
- const value = await getSource();
774
- const matter = fumaMatter(value);
775
- const parsed = querySchema.parse(query);
776
- let after;
777
- if (!isDevelopment && config.global.experimentalBuildCache) {
778
- const cacheDir = config.global.experimentalBuildCache;
779
- const cacheKey = `${parsed.hash}_${parsed.collection ?? "global"}_${generateCacheHash(filePath)}`;
780
- const cached = await import_promises.default.readFile(import_node_path.default.join(cacheDir, cacheKey)).then((content) => cacheEntry.parse(JSON.parse(content.toString()))).catch(() => null);
781
- if (cached && cached.hash === generateCacheHash(value)) return cached;
782
- after = async () => {
783
- await import_promises.default.mkdir(cacheDir, { recursive: true });
784
- await import_promises.default.writeFile(
785
- import_node_path.default.join(cacheDir, cacheKey),
786
- JSON.stringify({
787
- ...out,
788
- hash: generateCacheHash(value)
789
- })
790
- );
791
- };
792
- }
793
- const collection = parsed.collection ? config.getCollection(parsed.collection) : void 0;
794
- let docCollection;
795
- switch (collection?.type) {
796
- case "doc":
797
- docCollection = collection;
798
- break;
799
- case "docs":
800
- docCollection = collection.docs;
801
- break;
802
- }
803
- if (docCollection) {
804
- matter.data = await configLoader.core.transformFrontmatter(
805
- { collection: docCollection, filePath, source: value },
806
- matter.data
807
- );
808
- }
809
- if (parsed.only === "frontmatter") {
810
- return {
811
- code: `export const frontmatter = ${JSON.stringify(matter.data)}`,
812
- map: null
813
- };
814
- }
815
- const lineOffset = isDevelopment ? countLines(matter.matter) : 0;
816
- const { buildMDX: buildMDX2 } = await Promise.resolve().then(() => (init_build_mdx(), build_mdx_exports));
817
- const compiled = await buildMDX2(configLoader.core, docCollection, {
818
- isDevelopment,
819
- source: "\n".repeat(lineOffset) + matter.content,
820
- filePath,
821
- frontmatter: matter.data,
822
- _compiler: compiler,
823
- environment: "bundler"
824
- });
825
- const out = {
826
- code: String(compiled.value),
827
- map: compiled.map
828
- };
829
- await after?.();
830
- return out;
831
- }
832
- };
833
- }
834
- function generateCacheHash(input) {
835
- return (0, import_node_crypto.createHash)("md5").update(input).digest("hex");
836
- }
837
- function countLines(s) {
838
- let num = 0;
839
- for (const c of s) {
840
- if (c === "\n") num++;
841
- }
842
- return num;
843
- }
844
-
845
- // src/loaders/adapter.ts
846
- var import_node_url = require("url");
847
- var import_promises2 = __toESM(require("fs/promises"), 1);
848
- var import_node_querystring = require("querystring");
849
- var import_node_path2 = __toESM(require("path"), 1);
850
- var import_node_fs = require("fs");
851
- function toVite(loader) {
852
- return {
853
- filter(id) {
854
- return !loader.test || loader.test.test(id);
855
- },
856
- async transform(value, id) {
857
- const [file, query = ""] = id.split("?", 2);
858
- const result = await loader.load({
859
- filePath: file,
860
- query: (0, import_node_querystring.parse)(query),
861
- getSource() {
862
- return value;
863
- },
864
- development: this.environment.mode === "dev",
865
- compiler: {
866
- addDependency: (file2) => {
867
- this.addWatchFile(file2);
868
- }
869
- }
870
- });
871
- if (result === null) return null;
872
- return {
873
- code: result.code,
874
- map: result.map
875
- };
876
- }
877
- };
878
- }
879
-
880
- // src/core.ts
881
- var import_node_path4 = __toESM(require("path"), 1);
882
- var import_promises3 = __toESM(require("fs/promises"), 1);
883
-
884
- // src/utils/codegen.ts
885
- var import_node_path3 = __toESM(require("path"), 1);
886
- var import_tinyglobby = require("tinyglobby");
887
- function createCodegen({
888
- target = "default",
889
- outDir = "",
890
- jsExtension = false,
891
- globCache = /* @__PURE__ */ new Map()
892
- }) {
893
- let eagerImportId = 0;
894
- const banner = ["// @ts-nocheck"];
895
- if (target === "vite") {
896
- banner.push('/// <reference types="vite/client" />');
897
- }
898
- return {
899
- options: {
900
- target,
901
- outDir
902
- },
903
- lines: [],
904
- addImport(statement) {
905
- this.lines.unshift(statement);
906
- },
907
- async pushAsync(insert) {
908
- for (const line of await Promise.all(insert)) {
909
- if (line === void 0) continue;
910
- this.lines.push(line);
911
- }
912
- },
913
- async generateGlobImport(patterns, options) {
914
- if (target === "vite") {
915
- return this.generateViteGlobImport(patterns, options);
916
- }
917
- return this.generateNodeGlobImport(patterns, options);
918
- },
919
- generateViteGlobImport(patterns, { base, ...rest }) {
920
- patterns = (typeof patterns === "string" ? [patterns] : patterns).map(
921
- normalizeViteGlobPath
922
- );
923
- return `import.meta.glob(${JSON.stringify(patterns)}, ${JSON.stringify(
924
- {
925
- base: normalizeViteGlobPath(import_node_path3.default.relative(outDir, base)),
926
- ...rest
927
- },
928
- null,
929
- 2
930
- )})`;
931
- },
932
- async generateNodeGlobImport(patterns, {
933
- base,
934
- eager = false,
935
- query = {},
936
- import: importName
937
- }) {
938
- const cacheKey = JSON.stringify({ patterns, base });
939
- let files = globCache.get(cacheKey);
940
- if (!files) {
941
- files = (0, import_tinyglobby.glob)(patterns, {
942
- cwd: base
943
- });
944
- globCache.set(cacheKey, files);
945
- }
946
- let code = "{";
947
- for (const item of await files) {
948
- const fullPath = import_node_path3.default.join(base, item);
949
- const searchParams = new URLSearchParams();
950
- for (const [k, v] of Object.entries(query)) {
951
- searchParams.set(k, v);
952
- }
953
- const importPath = this.formatImportPath(fullPath) + "?" + searchParams.toString();
954
- if (eager) {
955
- const name = `__fd_glob_${eagerImportId++}`;
956
- this.lines.unshift(
957
- importName ? `import { ${importName} as ${name} } from ${JSON.stringify(importPath)}` : `import * as ${name} from ${JSON.stringify(importPath)}`
958
- );
959
- code += `${JSON.stringify(item)}: ${name}, `;
960
- } else {
961
- let line = `${JSON.stringify(item)}: () => import(${JSON.stringify(importPath)})`;
962
- if (importName) {
963
- line += `.then(mod => mod.${importName})`;
964
- }
965
- code += `${line}, `;
966
- }
967
- }
968
- code += "}";
969
- return code;
970
- },
971
- formatImportPath(file) {
972
- const ext = import_node_path3.default.extname(file);
973
- let filename;
974
- if (ext === ".ts" && jsExtension) {
975
- filename = file.substring(0, file.length - ext.length) + ".js";
976
- } else if (ext === ".ts") {
977
- filename = file.substring(0, file.length - ext.length);
978
- } else {
979
- filename = file;
980
- }
981
- const importPath = slash(import_node_path3.default.relative(outDir, filename));
982
- return importPath.startsWith(".") ? importPath : `./${importPath}`;
983
- },
984
- toString() {
985
- return [...banner, ...this.lines].join("\n");
986
- }
987
- };
988
- }
989
- function normalizeViteGlobPath(file) {
990
- file = slash(file);
991
- if (file.startsWith("./")) return file;
992
- if (file.startsWith("/")) return `.${file}`;
993
- return `./${file}`;
994
- }
995
- function slash(path8) {
996
- const isExtendedLengthPath = path8.startsWith("\\\\?\\");
997
- if (isExtendedLengthPath) {
998
- return path8;
999
- }
1000
- return path8.replaceAll("\\", "/");
1001
- }
1002
- function ident(code, tab = 1) {
1003
- return code.split("\n").map((v) => " ".repeat(tab) + v).join("\n");
1004
- }
1005
-
1006
- // src/core.ts
1007
- var _Defaults = {
1008
- configPath: "source.config.ts",
1009
- outDir: ".source"
1010
- };
1011
- async function getPlugins(pluginOptions) {
1012
- const plugins = [];
1013
- for await (const option of pluginOptions) {
1014
- if (!option) continue;
1015
- if (Array.isArray(option)) plugins.push(...await getPlugins(option));
1016
- else plugins.push(option);
1017
- }
1018
- return plugins;
1019
- }
1020
- function createCore(options, defaultPlugins = []) {
1021
- let config;
1022
- let plugins;
1023
- async function transformMetadata({
1024
- collection,
1025
- filePath,
1026
- source
1027
- }, data) {
1028
- if (collection.schema) {
1029
- data = await validate(
1030
- collection.schema,
1031
- data,
1032
- { path: filePath, source },
1033
- collection.type === "doc" ? `invalid frontmatter in ${filePath}` : `invalid data in ${filePath}`
1034
- );
1035
- }
1036
- return data;
1037
- }
1038
- const core = {
1039
- /**
1040
- * Convenient cache store, reset when config changes
1041
- */
1042
- cache: /* @__PURE__ */ new Map(),
1043
- async init({ config: newConfig }) {
1044
- config = await newConfig;
1045
- this.cache.clear();
1046
- plugins = await getPlugins([
1047
- postprocessPlugin(),
1048
- ...defaultPlugins,
1049
- ...config.global.plugins ?? []
1050
- ]);
1051
- for (const plugin of plugins) {
1052
- const out = await plugin.config?.call(pluginContext, config);
1053
- if (out) config = out;
1054
- }
1055
- },
1056
- getOptions() {
1057
- return options;
1058
- },
1059
- getConfig() {
1060
- return config;
1061
- },
1062
- /**
1063
- * The file path of compiled config file, the file may not exist (e.g. on Vite, or still compiling)
1064
- */
1065
- getCompiledConfigPath() {
1066
- return import_node_path4.default.join(options.outDir, "source.config.mjs");
1067
- },
1068
- getPlugins() {
1069
- return plugins;
1070
- },
1071
- getPluginContext() {
1072
- return pluginContext;
1073
- },
1074
- async initServer(server) {
1075
- for (const plugin of plugins) {
1076
- await plugin.configureServer?.call(pluginContext, server);
1077
- }
1078
- },
1079
- async emit({ filterPlugin = () => true } = {}) {
1080
- return (await Promise.all(
1081
- plugins.map((plugin) => {
1082
- if (!filterPlugin(plugin) || !plugin.emit) return [];
1083
- return plugin.emit.call(pluginContext);
1084
- })
1085
- )).flat();
1086
- },
1087
- async emitAndWrite(emitOptions) {
1088
- const start = performance.now();
1089
- const out = await this.emit(emitOptions);
1090
- await Promise.all(
1091
- out.map(async (entry) => {
1092
- const file = import_node_path4.default.join(options.outDir, entry.path);
1093
- await import_promises3.default.mkdir(import_node_path4.default.dirname(file), { recursive: true });
1094
- await import_promises3.default.writeFile(file, entry.content);
1095
- })
1096
- );
1097
- console.log(`[MDX] generated files in ${performance.now() - start}ms`);
1098
- },
1099
- async transformMeta(options2, data) {
1100
- const ctx = {
1101
- ...pluginContext,
1102
- ...options2
1103
- };
1104
- data = await transformMetadata(options2, data);
1105
- for (const plugin of plugins) {
1106
- if (plugin.meta?.transform)
1107
- data = await plugin.meta.transform.call(ctx, data) ?? data;
1108
- }
1109
- return data;
1110
- },
1111
- async transformFrontmatter(options2, data) {
1112
- const ctx = {
1113
- ...pluginContext,
1114
- ...options2
1115
- };
1116
- data = await transformMetadata(options2, data);
1117
- for (const plugin of plugins) {
1118
- if (plugin.doc?.frontmatter)
1119
- data = await plugin.doc.frontmatter.call(ctx, data) ?? data;
1120
- }
1121
- return data;
1122
- },
1123
- async transformVFile(options2, file) {
1124
- const ctx = {
1125
- ...pluginContext,
1126
- ...options2
1127
- };
1128
- for (const plugin of plugins) {
1129
- if (plugin.doc?.vfile)
1130
- file = await plugin.doc.vfile.call(ctx, file) ?? file;
1131
- }
1132
- return file;
1133
- }
1134
- };
1135
- const pluginContext = {
1136
- core,
1137
- ...options
1138
- };
1139
- return core;
1140
- }
1141
- function postprocessPlugin() {
1142
- const LinkReferenceTypes = `{
1143
- /**
1144
- * extracted references (e.g. hrefs, paths), useful for analyzing relationships between pages.
1145
- */
1146
- extractedReferences?: import('fumadocs-mdx').ExtractedReference[];
1147
- }`;
1148
- return {
1149
- "index-file": {
1150
- generateTypeConfig() {
1151
- const lines = [];
1152
- lines.push("{");
1153
- lines.push(" DocData: {");
1154
- for (const collection of this.core.getConfig().collectionList) {
1155
- let postprocessOptions;
1156
- switch (collection.type) {
1157
- case "doc":
1158
- postprocessOptions = collection.postprocess;
1159
- break;
1160
- case "docs":
1161
- postprocessOptions = collection.docs.postprocess;
1162
- break;
1163
- }
1164
- if (postprocessOptions?.extractLinkReferences) {
1165
- lines.push(ident(`${collection.name}: ${LinkReferenceTypes},`, 2));
1166
- }
1167
- }
1168
- lines.push(" }");
1169
- lines.push("}");
1170
- return lines.join("\n");
1171
- },
1172
- serverOptions(options) {
1173
- options.doc ??= {};
1174
- options.doc.passthroughs ??= [];
1175
- options.doc.passthroughs.push("extractedReferences");
1176
- }
1177
- }
1178
- };
1179
- }
1180
-
1181
- // src/loaders/config.ts
1182
- var import_promises4 = __toESM(require("fs/promises"), 1);
1183
- function createIntegratedConfigLoader(core) {
1184
- return {
1185
- core,
1186
- getConfig() {
1187
- return core.getConfig();
1188
- }
1189
- };
1190
- }
1191
-
1192
- // src/loaders/meta.ts
1193
- var import_js_yaml2 = require("js-yaml");
1194
- var import_zod2 = require("zod");
1195
- var querySchema2 = import_zod2.z.object({
1196
- collection: import_zod2.z.string().optional()
1197
- }).loose();
1198
- function createMetaLoader(configLoader, resolve2 = {}) {
1199
- const { json: resolveJson = "js", yaml: resolveYaml = "js" } = resolve2;
1200
- function parse2(filePath, source) {
1201
- try {
1202
- if (filePath.endsWith(".json")) return JSON.parse(source);
1203
- if (filePath.endsWith(".yaml")) return (0, import_js_yaml2.load)(source);
1204
- } catch (e) {
1205
- throw new Error(`invalid data in ${filePath}`, { cause: e });
1206
- }
1207
- throw new Error("Unknown file type " + filePath);
1208
- }
1209
- function onMeta(source, { filePath, query }) {
1210
- const parsed = querySchema2.safeParse(query);
1211
- if (!parsed.success || !parsed.data.collection) return null;
1212
- const collectionName = parsed.data.collection;
1213
- return async () => {
1214
- const config = await configLoader.getConfig();
1215
- const collection = config.getCollection(collectionName);
1216
- let metaCollection;
1217
- switch (collection?.type) {
1218
- case "meta":
1219
- metaCollection = collection;
1220
- break;
1221
- case "docs":
1222
- metaCollection = collection.meta;
1223
- break;
1224
- }
1225
- const data = parse2(filePath, source);
1226
- if (!metaCollection) return data;
1227
- return configLoader.core.transformMeta(
1228
- {
1229
- collection: metaCollection,
1230
- filePath,
1231
- source
1232
- },
1233
- data
1234
- );
1235
- };
1236
- }
1237
- return {
1238
- test: metaLoaderGlob,
1239
- async load(input) {
1240
- const result = onMeta(await input.getSource(), input);
1241
- if (result === null) return null;
1242
- const data = await result();
1243
- if (input.filePath.endsWith(".json")) {
1244
- return {
1245
- code: resolveJson === "json" ? JSON.stringify(data) : `export default ${JSON.stringify(data)}`
1246
- };
1247
- } else {
1248
- return {
1249
- code: resolveYaml === "yaml" ? (0, import_js_yaml2.dump)(data) : `export default ${JSON.stringify(data)}`
1250
- };
1251
- }
1252
- },
1253
- bun: {
1254
- load(source, input) {
1255
- const result = onMeta(source, input);
1256
- if (result === null)
1257
- return {
1258
- loader: "object",
1259
- exports: parse2(input.filePath, source)
1260
- };
1261
- return result().then((data) => ({
1262
- loader: "object",
1263
- exports: { default: data }
1264
- }));
1265
- }
1266
- }
1267
- };
1268
- }
1269
-
1270
- // src/plugins/index-file.ts
1271
- var import_path = __toESM(require("path"), 1);
1272
- var import_tinyglobby2 = require("tinyglobby");
1273
-
1274
- // src/utils/fs-cache.ts
1275
- var import_lru_cache = require("lru-cache");
1276
- var import_promises5 = __toESM(require("fs/promises"), 1);
1277
- var import_node_path5 = __toESM(require("path"), 1);
1278
- var map = new import_lru_cache.LRUCache({
1279
- max: 100
1280
- });
1281
- function toFullPath(file) {
1282
- if (import_node_path5.default.isAbsolute(file)) {
1283
- return import_node_path5.default.relative(process.cwd(), file);
1284
- }
1285
- return file;
1286
- }
1287
- function readFileWithCache(file) {
1288
- const fullPath = toFullPath(file);
1289
- const cached = map.get(fullPath);
1290
- if (cached) return cached;
1291
- const read = import_promises5.default.readFile(fullPath).then((s) => s.toString());
1292
- map.set(fullPath, read);
1293
- return read;
1294
- }
1295
- function removeFileCache(file) {
1296
- map.delete(toFullPath(file));
1297
- }
1298
-
1299
- // src/plugins/index-file.ts
1300
- var import_crypto = require("crypto");
1301
- init_fuma_matter();
1302
- function indexFile(options = {}) {
1303
- const {
1304
- target = "default",
1305
- addJsExtension,
1306
- browser = true,
1307
- dynamic = true
1308
- } = options;
1309
- let config;
1310
- let dynamicCollections;
1311
- function isDynamic(collection) {
1312
- return collection.type === "docs" && collection.docs.dynamic || collection.type === "doc" && collection.dynamic;
1313
- }
1314
- function generateConfigs(core) {
1315
- const serverOptions = {};
1316
- const typeConfigs = [];
1317
- const ctx = core.getPluginContext();
1318
- for (const plugin of core.getPlugins()) {
1319
- const indexFilePlugin = plugin["index-file"];
1320
- if (!indexFilePlugin) continue;
1321
- indexFilePlugin.serverOptions?.call(ctx, serverOptions);
1322
- const config2 = indexFilePlugin.generateTypeConfig?.call(ctx);
1323
- if (config2) typeConfigs.push(config2);
1324
- }
1325
- if (typeConfigs.length === 0) {
1326
- typeConfigs.push("{ DocData: {} }");
1327
- }
1328
- return {
1329
- serverOptions,
1330
- tc: typeConfigs.join(" & ")
1331
- };
1332
- }
1333
- return {
1334
- name: "index-file",
1335
- config(v) {
1336
- config = v;
1337
- dynamicCollections = config.collectionList.filter(isDynamic);
1338
- },
1339
- configureServer(server) {
1340
- if (!server.watcher) return;
1341
- server.watcher.on("all", async (event, file) => {
1342
- removeFileCache(file);
1343
- if (dynamicCollections.length === 0) {
1344
- if (target === "vite") return;
1345
- if (target === "default" && event === "change") return;
1346
- }
1347
- const updatedCollection = config.collectionList.find(
1348
- (collection) => collection.hasFile(file)
1349
- );
1350
- if (!updatedCollection) return;
1351
- if (!isDynamic(updatedCollection)) {
1352
- if (target === "vite") return;
1353
- if (target === "default" && event === "change") return;
1354
- }
1355
- await this.core.emitAndWrite({
1356
- filterPlugin: (plugin) => plugin.name === "index-file"
1357
- });
1358
- });
1359
- },
1360
- async emit() {
1361
- const globCache = /* @__PURE__ */ new Map();
1362
- const { serverOptions, tc } = generateConfigs(this.core);
1363
- const toEmitEntry = async (path8, content) => {
1364
- const codegen = createCodegen({
1365
- target,
1366
- outDir: this.outDir,
1367
- jsExtension: addJsExtension,
1368
- globCache
1369
- });
1370
- await content({
1371
- core: this.core,
1372
- codegen,
1373
- serverOptions,
1374
- tc
1375
- });
1376
- return {
1377
- path: path8,
1378
- content: codegen.toString()
1379
- };
1380
- };
1381
- const out = [
1382
- toEmitEntry("server.ts", generateServerIndexFile)
1383
- ];
1384
- if (dynamic)
1385
- out.push(toEmitEntry("dynamic.ts", generateDynamicIndexFile));
1386
- if (browser)
1387
- out.push(toEmitEntry("browser.ts", generateBrowserIndexFile));
1388
- return await Promise.all(out);
1389
- }
1390
- };
1391
- }
1392
- async function generateServerIndexFile({
1393
- core,
1394
- codegen,
1395
- serverOptions,
1396
- tc
1397
- }) {
1398
- codegen.lines.push(
1399
- `import { server } from 'fumadocs-mdx/runtime/server';`,
1400
- `import type * as Config from '${codegen.formatImportPath(core.getOptions().configPath)}';`,
1401
- "",
1402
- `const create = server<typeof Config, ${tc}>(${JSON.stringify(serverOptions)});`
1403
- );
1404
- async function generateCollectionObject(collection) {
1405
- switch (collection.type) {
1406
- case "docs": {
1407
- if (collection.docs.dynamic) return;
1408
- if (collection.docs.async) {
1409
- const [metaGlob2, headGlob, bodyGlob] = await Promise.all([
1410
- generateMetaCollectionGlob(codegen, collection.meta, true),
1411
- generateDocCollectionFrontmatterGlob(
1412
- codegen,
1413
- collection.docs,
1414
- true
1415
- ),
1416
- generateDocCollectionGlob(codegen, collection.docs)
1417
- ]);
1418
- return `await create.docsLazy("${collection.name}", "${collection.dir}", ${metaGlob2}, ${headGlob}, ${bodyGlob})`;
1419
- }
1420
- const [metaGlob, docGlob] = await Promise.all([
1421
- generateMetaCollectionGlob(codegen, collection.meta, true),
1422
- generateDocCollectionGlob(codegen, collection.docs, true)
1423
- ]);
1424
- return `await create.docs("${collection.name}", "${collection.dir}", ${metaGlob}, ${docGlob})`;
1425
- }
1426
- case "doc":
1427
- if (collection.dynamic) return;
1428
- if (collection.async) {
1429
- const [headGlob, bodyGlob] = await Promise.all([
1430
- generateDocCollectionFrontmatterGlob(codegen, collection, true),
1431
- generateDocCollectionGlob(codegen, collection)
1432
- ]);
1433
- return `await create.docLazy("${collection.name}", "${collection.dir}", ${headGlob}, ${bodyGlob})`;
1434
- }
1435
- return `await create.doc("${collection.name}", "${collection.dir}", ${await generateDocCollectionGlob(
1436
- codegen,
1437
- collection,
1438
- true
1439
- )})`;
1440
- case "meta":
1441
- return `await create.meta("${collection.name}", "${collection.dir}", ${await generateMetaCollectionGlob(
1442
- codegen,
1443
- collection,
1444
- true
1445
- )})`;
1446
- }
1447
- }
1448
- await codegen.pushAsync(
1449
- core.getConfig().collectionList.map(async (collection) => {
1450
- const obj = await generateCollectionObject(collection);
1451
- if (!obj) return;
1452
- return `
1453
- export const ${collection.name} = ${obj};`;
1454
- })
1455
- );
1456
- }
1457
- async function generateDynamicIndexFile({
1458
- core,
1459
- codegen,
1460
- serverOptions,
1461
- tc
1462
- }) {
1463
- const { configPath } = core.getOptions();
1464
- codegen.lines.push(
1465
- `import { dynamic } from 'fumadocs-mdx/runtime/dynamic';`,
1466
- `import * as Config from '${codegen.formatImportPath(configPath)}';`,
1467
- "",
1468
- `const create = await dynamic<typeof Config, ${tc}>(Config, ${JSON.stringify(core.getOptions())}, ${JSON.stringify(serverOptions)});`
1469
- );
1470
- async function generateCollectionObjectEntry(collection, file) {
1471
- const fullPath = import_path.default.join(collection.dir, file);
1472
- const content = await readFileWithCache(fullPath).catch(() => "");
1473
- const parsed = fumaMatter(content);
1474
- const data = await core.transformFrontmatter(
1475
- {
1476
- collection,
1477
- filePath: fullPath,
1478
- source: content
1479
- },
1480
- parsed.data
1481
- );
1482
- const hash = (0, import_crypto.createHash)("md5").update(content).digest("hex");
1483
- const infoStr = [
1484
- // make sure it's included in vercel/nft
1485
- `absolutePath: path.resolve(${JSON.stringify(fullPath)})`
1486
- ];
1487
- for (const [k, v] of Object.entries({
1488
- info: {
1489
- fullPath,
1490
- path: file
1491
- },
1492
- data,
1493
- hash
1494
- })) {
1495
- infoStr.push(`${k}: ${JSON.stringify(v)}`);
1496
- }
1497
- return `{ ${infoStr.join(", ")} }`;
1498
- }
1499
- async function generateCollectionObject(parent) {
1500
- let collection;
1501
- if (parent.type === "doc") collection = parent;
1502
- else if (parent.type === "docs") collection = parent.docs;
1503
- if (!collection || !collection.dynamic) return;
1504
- const files = await (0, import_tinyglobby2.glob)(collection.patterns, {
1505
- cwd: collection.dir
1506
- });
1507
- const entries = await Promise.all(
1508
- files.map((file) => generateCollectionObjectEntry(collection, file))
1509
- );
1510
- switch (parent.type) {
1511
- case "docs": {
1512
- const metaGlob = await generateMetaCollectionGlob(
1513
- codegen,
1514
- parent.meta,
1515
- true
1516
- );
1517
- return `await create.docs("${parent.name}", "${parent.dir}", ${metaGlob}, ${entries.join(", ")})`;
1518
- }
1519
- case "doc":
1520
- return `await create.doc("${collection.name}", "${collection.dir}", ${entries.join(", ")})`;
1521
- }
1522
- }
1523
- await codegen.pushAsync(
1524
- core.getConfig().collectionList.map(async (collection) => {
1525
- const obj = await generateCollectionObject(collection);
1526
- if (!obj) return;
1527
- return `
1528
- export const ${collection.name} = ${obj};`;
1529
- })
1530
- );
1531
- }
1532
- async function generateBrowserIndexFile({ core, codegen, tc }) {
1533
- codegen.lines.push(
1534
- `import { browser } from 'fumadocs-mdx/runtime/browser';`,
1535
- `import type * as Config from '${codegen.formatImportPath(core.getOptions().configPath)}';`,
1536
- "",
1537
- `const create = browser<typeof Config, ${tc}>();`
1538
- );
1539
- async function generateCollectionObject(collection) {
1540
- switch (collection.type) {
1541
- case "docs": {
1542
- if (collection.docs.dynamic) return;
1543
- return generateCollectionObject(collection.docs);
1544
- }
1545
- case "doc":
1546
- if (collection.dynamic) return;
1547
- return `create.doc("${collection.name}", ${await generateDocCollectionGlob(codegen, collection)})`;
1548
- }
1549
- }
1550
- codegen.lines.push("const browserCollections = {");
1551
- await codegen.pushAsync(
1552
- core.getConfig().collectionList.map(async (collection) => {
1553
- const obj = await generateCollectionObject(collection);
1554
- if (!obj) return;
1555
- return ident(`${collection.name}: ${obj},`);
1556
- })
1557
- );
1558
- codegen.lines.push("};", "export default browserCollections;");
1559
- }
1560
- function generateDocCollectionFrontmatterGlob(codegen, collection, eager = false) {
1561
- return codegen.generateGlobImport(collection.patterns, {
1562
- query: {
1563
- collection: collection.name,
1564
- only: "frontmatter"
1565
- },
1566
- import: "frontmatter",
1567
- base: collection.dir,
1568
- eager
1569
- });
1570
- }
1571
- function generateDocCollectionGlob(codegen, collection, eager = false) {
1572
- return codegen.generateGlobImport(collection.patterns, {
1573
- query: {
1574
- collection: collection.name
1575
- },
1576
- base: collection.dir,
1577
- eager
1578
- });
1579
- }
1580
- function generateMetaCollectionGlob(codegen, collection, eager = false) {
1581
- return codegen.generateGlobImport(collection.patterns, {
1582
- query: {
1583
- collection: collection.name
1584
- },
1585
- import: "default",
1586
- base: collection.dir,
1587
- eager
1588
- });
1589
- }
1590
-
1591
- // src/vite/index.ts
1592
- var FumadocsDeps = ["fumadocs-core", "fumadocs-ui", "fumadocs-openapi"];
1593
- async function mdx(config, pluginOptions = {}) {
1594
- const options = applyDefaults(pluginOptions);
1595
- const core = createViteCore(options);
1596
- await core.init({
1597
- config: buildConfig(config)
1598
- });
1599
- const configLoader = createIntegratedConfigLoader(core);
1600
- const mdxLoader = toVite(createMdxLoader(configLoader));
1601
- const metaLoader = toVite(
1602
- createMetaLoader(configLoader, {
1603
- // vite has built-in plugin for JSON files
1604
- json: "json"
1605
- })
1606
- );
1607
- return {
1608
- name: "fumadocs-mdx",
1609
- // needed, otherwise other plugins will be executed before our `transform`.
1610
- enforce: "pre",
1611
- config(config2) {
1612
- if (!options.updateViteConfig) return config2;
1613
- return (0, import_vite.mergeConfig)(config2, {
1614
- optimizeDeps: {
1615
- exclude: FumadocsDeps
1616
- },
1617
- resolve: {
1618
- noExternal: FumadocsDeps,
1619
- dedupe: FumadocsDeps
1620
- }
1621
- });
1622
- },
1623
- async buildStart() {
1624
- await core.emitAndWrite();
1625
- },
1626
- async configureServer(server) {
1627
- await core.initServer({
1628
- watcher: server.watcher
1629
- });
1630
- },
1631
- async transform(value, id) {
1632
- try {
1633
- if (metaLoader.filter(id)) {
1634
- return await metaLoader.transform.call(this, value, id);
1635
- }
1636
- if (mdxLoader.filter(id)) {
1637
- return await mdxLoader.transform.call(this, value, id);
1638
- }
1639
- } catch (e) {
1640
- if (e instanceof ValidationError) {
1641
- throw new Error(await e.toStringFormatted());
1642
- }
1643
- throw e;
1644
- }
1645
- }
1646
- };
1647
- }
1648
- async function postInstall(pluginOptions = {}) {
1649
- const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_load_from_file(), load_from_file_exports));
1650
- const core = createViteCore(applyDefaults(pluginOptions));
1651
- await core.init({
1652
- config: loadConfig2(core, true)
1653
- });
1654
- await core.emitAndWrite();
1655
- }
1656
- function createViteCore({
1657
- index,
1658
- configPath,
1659
- outDir
1660
- }) {
1661
- if (index === true) index = {};
1662
- return createCore(
1663
- {
1664
- environment: "vite",
1665
- configPath,
1666
- outDir
1667
- },
1668
- [
1669
- index && indexFile({
1670
- ...index,
1671
- target: index.target ?? "vite"
1672
- })
1673
- ]
1674
- );
1675
- }
1676
- function applyDefaults(options) {
1677
- return {
1678
- updateViteConfig: options.updateViteConfig ?? true,
1679
- index: options.index ?? true,
1680
- configPath: options.configPath ?? _Defaults.configPath,
1681
- outDir: options.outDir ?? _Defaults.outDir
1682
- };
1683
- }
1684
- // Annotate the CommonJS export names for ESM import in node:
1685
- 0 && (module.exports = {
1686
- postInstall
1687
- });