fumadocs-mdx 11.7.0 → 11.7.3

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.
@@ -168,7 +168,7 @@ module.exports = __toCommonJS(vite_exports);
168
168
  // src/config/build.ts
169
169
  function buildConfig(config) {
170
170
  const collections = /* @__PURE__ */ new Map();
171
- let globalConfig;
171
+ let globalConfig = {};
172
172
  for (const [k, v] of Object.entries(config)) {
173
173
  if (!v) {
174
174
  continue;
@@ -183,34 +183,30 @@ function buildConfig(config) {
183
183
  continue;
184
184
  }
185
185
  }
186
- if (k === "default") {
186
+ if (k === "default" && v) {
187
187
  globalConfig = v;
188
188
  continue;
189
189
  }
190
- return [
191
- `Unknown export "${k}", you can only export collections from source configuration file.`,
192
- null
193
- ];
190
+ throw new Error(
191
+ `Unknown export "${k}", you can only export collections from source configuration file.`
192
+ );
194
193
  }
195
194
  let cachedMdxOptions;
196
- return [
197
- null,
198
- {
199
- global: globalConfig,
200
- collections,
201
- async getDefaultMDXOptions() {
202
- if (cachedMdxOptions) return cachedMdxOptions;
203
- const input = this.global?.mdxOptions;
204
- async function uncached() {
205
- const options = typeof input === "function" ? await input() : input;
206
- const { getDefaultMDXOptions: getDefaultMDXOptions2 } = await Promise.resolve().then(() => (init_mdx_options(), mdx_options_exports));
207
- if (options?.preset === "minimal") return options;
208
- return getDefaultMDXOptions2(options ?? {});
209
- }
210
- return cachedMdxOptions = uncached();
195
+ return {
196
+ global: globalConfig,
197
+ collections,
198
+ async getDefaultMDXOptions() {
199
+ if (cachedMdxOptions) return cachedMdxOptions;
200
+ const input = this.global.mdxOptions;
201
+ async function uncached() {
202
+ const options = typeof input === "function" ? await input() : input;
203
+ const { getDefaultMDXOptions: getDefaultMDXOptions2 } = await Promise.resolve().then(() => (init_mdx_options(), mdx_options_exports));
204
+ if (options?.preset === "minimal") return options;
205
+ return getDefaultMDXOptions2(options ?? {});
211
206
  }
207
+ return cachedMdxOptions = uncached();
212
208
  }
213
- ];
209
+ };
214
210
  }
215
211
 
216
212
  // src/utils/build-mdx.ts
@@ -425,18 +421,184 @@ function toImportPath(file, config) {
425
421
  }
426
422
  return importPath.replaceAll(import_node_path.default.sep, "/");
427
423
  }
424
+ function ident(code, tab = 1) {
425
+ return code.split("\n").map((v) => " ".repeat(tab) + v).join("\n");
426
+ }
428
427
 
429
428
  // src/vite/index.ts
430
- var import_promises = __toESM(require("fs/promises"), 1);
431
- var import_node_path2 = __toESM(require("path"), 1);
429
+ var fs2 = __toESM(require("fs/promises"), 1);
430
+ var path4 = __toESM(require("path"), 1);
432
431
  var import_js_yaml2 = require("js-yaml");
433
- var fileRegex = /\.(md|mdx)$/;
432
+
433
+ // src/utils/collections.ts
434
+ function getSupportedFormats(collection) {
435
+ return {
436
+ doc: ["mdx", "md"],
437
+ meta: ["json", "yaml"]
438
+ }[collection.type];
439
+ }
440
+ function getGlobPatterns(collection) {
441
+ if (collection.files) return collection.files;
442
+ return [`**/*.{${getSupportedFormats(collection).join(",")}}`];
443
+ }
444
+
445
+ // src/vite/generate-glob.ts
446
+ function generateGlob(name, collection) {
447
+ const patterns = mapGlobPatterns(getGlobPatterns(collection));
448
+ const options = {
449
+ query: {
450
+ collection: name
451
+ },
452
+ base: getGlobBase(collection)
453
+ };
454
+ if (collection.type === "meta") {
455
+ options.import = "default";
456
+ }
457
+ return `import.meta.glob(${JSON.stringify(patterns)}, ${JSON.stringify(options, null, 2)})`;
458
+ }
459
+ function mapGlobPatterns(patterns) {
460
+ return patterns.map((file) => {
461
+ if (file.startsWith("./")) return file;
462
+ if (file.startsWith("/")) return `.${file}`;
463
+ return `./${file}`;
464
+ });
465
+ }
466
+ function getGlobBase(collection) {
467
+ let dir = collection.dir;
468
+ if (Array.isArray(dir)) {
469
+ if (dir.length !== 1)
470
+ throw new Error(
471
+ `[Fumadocs MDX] Vite Plugin doesn't support multiple \`dir\` for a collection at the moment.`
472
+ );
473
+ dir = dir[0];
474
+ }
475
+ if (!dir.startsWith("./") && !dir.startsWith("/")) {
476
+ return "/" + dir;
477
+ }
478
+ return dir;
479
+ }
480
+
481
+ // src/utils/git-timestamp.ts
482
+ var import_node_path2 = __toESM(require("path"), 1);
483
+ var import_tinyexec = require("tinyexec");
484
+ var cache2 = /* @__PURE__ */ new Map();
485
+ async function getGitTimestamp(file) {
486
+ const cached = cache2.get(file);
487
+ if (cached) return cached;
488
+ try {
489
+ const out = await (0, import_tinyexec.x)(
490
+ "git",
491
+ ["log", "-1", '--pretty="%ai"', import_node_path2.default.relative(process.cwd(), file)],
492
+ {
493
+ throwOnError: true
494
+ }
495
+ );
496
+ const time = new Date(out.stdout);
497
+ cache2.set(file, time);
498
+ return time;
499
+ } catch {
500
+ return;
501
+ }
502
+ }
503
+
504
+ // src/vite/index.ts
434
505
  var onlySchema = import_zod2.z.literal(["frontmatter", "all"]);
435
506
  function mdx(config, options = {}) {
436
507
  const { generateIndexFile = true, configPath = "source.config.ts" } = options;
437
- const [err, loaded] = buildConfig(config);
438
- if (err || !loaded) {
439
- throw new Error(err);
508
+ const loaded = buildConfig(config);
509
+ async function transformMeta(path5, query, value) {
510
+ const isJson = path5.endsWith(".json");
511
+ const parsed = (0, import_node_querystring.parse)(query);
512
+ const collection = parsed.collection ? loaded.collections.get(parsed.collection) : void 0;
513
+ if (!collection) return null;
514
+ let schema;
515
+ switch (collection.type) {
516
+ case "meta":
517
+ schema = collection.schema;
518
+ break;
519
+ case "docs":
520
+ schema = collection.meta.schema;
521
+ break;
522
+ }
523
+ if (!schema) return null;
524
+ let data;
525
+ try {
526
+ data = isJson ? JSON.parse(value) : (0, import_js_yaml2.load)(value);
527
+ } catch {
528
+ return null;
529
+ }
530
+ const out = await validate(
531
+ schema,
532
+ data,
533
+ { path: path5, source: value },
534
+ `invalid data in ${path5}`
535
+ );
536
+ return {
537
+ code: isJson ? JSON.stringify(out) : `export default ${JSON.stringify(out)}`,
538
+ map: null
539
+ };
540
+ }
541
+ async function transformContent(file, query, value) {
542
+ const matter = fumaMatter(value);
543
+ const isDevelopment = this.environment.mode === "dev";
544
+ const parsed = (0, import_node_querystring.parse)(query);
545
+ const collection = parsed.collection ? loaded.collections.get(parsed.collection) : void 0;
546
+ const only = parsed.only ? onlySchema.parse(parsed.only) : "all";
547
+ let schema;
548
+ let mdxOptions;
549
+ switch (collection?.type) {
550
+ case "doc":
551
+ mdxOptions = collection.mdxOptions;
552
+ schema = collection.schema;
553
+ break;
554
+ case "docs":
555
+ mdxOptions = collection.docs.mdxOptions;
556
+ schema = collection.docs.schema;
557
+ break;
558
+ }
559
+ if (schema) {
560
+ matter.data = await validate(
561
+ schema,
562
+ matter.data,
563
+ {
564
+ source: value,
565
+ path: file
566
+ },
567
+ `invalid frontmatter in ${file}`
568
+ );
569
+ }
570
+ if (only === "frontmatter") {
571
+ return {
572
+ code: `export const frontmatter = ${JSON.stringify(matter.data)}`,
573
+ map: null
574
+ };
575
+ }
576
+ const data = {};
577
+ if (loaded.global.lastModifiedTime === "git") {
578
+ data.lastModified = (await getGitTimestamp(file))?.getTime();
579
+ }
580
+ mdxOptions ??= await loaded.getDefaultMDXOptions();
581
+ const lineOffset = isDevelopment ? countLines(matter.matter) : 0;
582
+ const compiled = await buildMDX(
583
+ parsed.collection ?? "global",
584
+ "\n".repeat(lineOffset) + matter.content,
585
+ {
586
+ development: isDevelopment,
587
+ ...mdxOptions,
588
+ data,
589
+ filePath: file,
590
+ frontmatter: matter.data,
591
+ _compiler: {
592
+ addDependency: (file2) => {
593
+ this.addWatchFile(file2);
594
+ }
595
+ }
596
+ }
597
+ );
598
+ return {
599
+ code: String(compiled.value),
600
+ map: compiled.map
601
+ };
440
602
  }
441
603
  return {
442
604
  name: "fumadocs-mdx",
@@ -448,6 +610,7 @@ function mdx(config, options = {}) {
448
610
  const outdir = process.cwd();
449
611
  const outFile = "source.generated.ts";
450
612
  const lines = [
613
+ '/// <reference types="vite/client" />',
451
614
  `import { fromConfig } from 'fumadocs-mdx/runtime/vite';`,
452
615
  `import type * as Config from '${toImportPath(configPath, {
453
616
  relativeTo: outdir
@@ -455,177 +618,47 @@ function mdx(config, options = {}) {
455
618
  "",
456
619
  `export const create = fromConfig<typeof Config>();`
457
620
  ];
458
- function filesToGlob(files) {
459
- return files.map((file) => {
460
- if (file.startsWith("./")) return file;
461
- if (file.startsWith("/")) return `.${file}`;
462
- return `./${file}`;
463
- });
464
- }
465
- function docs(name, dir, collection) {
466
- const docFiles = collection.docs.files ? filesToGlob(collection.docs.files) : ["./**/*.{mdx,md}"];
467
- const metaFiles = collection.meta.files ? filesToGlob(collection.meta.files) : ["./**/*.{yaml,json}"];
468
- return `export const ${name} = create.docs('${name}', {
469
- doc: import.meta.glob(${JSON.stringify(docFiles)}, {
470
- query: {
471
- collection: '${name}',
472
- },
473
- base: '${dir}',
474
- }),
475
- meta: import.meta.glob(${JSON.stringify(metaFiles)}, {
476
- query: {
477
- collection: '${name}',
478
- },
479
- base: '${dir}',
480
- import: 'default',
481
- }),
621
+ function docs(name, collection) {
622
+ const args = [
623
+ ident(`doc: ${generateGlob(name, collection.docs)}`),
624
+ ident(`meta: ${generateGlob(name, collection.meta)}`)
625
+ ].join(",\n");
626
+ return `export const ${name} = create.docs("${name}", {
627
+ ${args}
482
628
  });`;
483
629
  }
484
- function doc(name, dir, collection) {
485
- const files = collection.files ? filesToGlob(collection.files) : ["./**/*.{mdx,md}"];
486
- return `export const ${name} = create.doc(
487
- '${name}',
488
- import.meta.glob(${JSON.stringify(files)}, {
489
- query: {
490
- collection: '${name}',
491
- },
492
- base: '${dir}',
493
- }),
494
- );`;
630
+ function doc(name, collection) {
631
+ return `export const ${name} = create.doc("${name}", ${generateGlob(name, collection)});`;
495
632
  }
496
- function meta(name, dir, collection) {
497
- const files = collection.files ? filesToGlob(collection.files) : ["./**/*.{yaml,json}"];
498
- return `export const ${name} = create.meta(
499
- '${name}',
500
- import.meta.glob(${JSON.stringify(files)}, {
501
- query: {
502
- collection: '${name}',
503
- },
504
- base: '${dir}',
505
- import: 'default',
506
- }),
507
- );`;
633
+ function meta(name, collection) {
634
+ return `export const ${name} = create.meta("${name}", ${generateGlob(name, collection)});`;
508
635
  }
509
636
  for (const [name, collection] of loaded.collections.entries()) {
510
- let dir = collection.dir;
511
- if (Array.isArray(dir) && dir.length === 1) {
512
- dir = dir[0];
513
- } else if (Array.isArray(dir)) {
514
- throw new Error(
515
- `[Fumadocs MDX] Vite Plugin doesn't support multiple \`dir\` for a collection at the moment.`
516
- );
517
- }
518
- if (!dir.startsWith("./") && !dir.startsWith("/")) {
519
- dir = "/" + dir;
520
- }
521
637
  lines.push("");
522
638
  if (collection.type === "docs") {
523
- lines.push(docs(name, dir, collection));
639
+ lines.push(docs(name, collection));
524
640
  } else if (collection.type === "meta") {
525
- lines.push(meta(name, dir, collection));
641
+ lines.push(meta(name, collection));
526
642
  } else {
527
- lines.push(doc(name, dir, collection));
643
+ lines.push(doc(name, collection));
528
644
  }
529
645
  }
530
- await import_promises.default.writeFile(import_node_path2.default.join(outdir, outFile), lines.join("\n"));
646
+ await fs2.writeFile(path4.join(outdir, outFile), lines.join("\n"));
531
647
  },
532
648
  async transform(value, id) {
533
- const [path4, query = ""] = id.split("?");
534
- const isJson = path4.endsWith(".json");
535
- const isYaml = path4.endsWith(".yaml");
536
- if (isJson || isYaml) {
537
- const parsed2 = (0, import_node_querystring.parse)(query);
538
- const collection2 = parsed2.collection ? loaded.collections.get(parsed2.collection) : void 0;
539
- if (!collection2) return null;
540
- let schema2;
541
- switch (collection2.type) {
542
- case "meta":
543
- schema2 = collection2.schema;
544
- break;
545
- case "docs":
546
- schema2 = collection2.meta.schema;
547
- break;
548
- }
549
- if (!schema2) return null;
550
- let data;
551
- try {
552
- data = isJson ? JSON.parse(value) : (0, import_js_yaml2.load)(value);
553
- } catch {
554
- return null;
555
- }
556
- const out = await validate(
557
- schema2,
558
- data,
559
- { path: path4, source: value },
560
- `invalid data in ${path4}`
561
- );
562
- return {
563
- code: isJson ? JSON.stringify(out) : `export default ${JSON.stringify(out)}`,
564
- map: null
565
- };
566
- }
567
- if (!fileRegex.test(path4)) return;
568
- const matter = fumaMatter(value);
569
- const isDevelopment = this.environment.mode === "dev";
570
- const parsed = (0, import_node_querystring.parse)(query);
571
- const collection = parsed.collection ? loaded.collections.get(parsed.collection) : void 0;
572
- const only = parsed.only ? onlySchema.parse(parsed.only) : "all";
573
- let schema;
574
- let mdxOptions;
575
- switch (collection?.type) {
576
- case "doc":
577
- mdxOptions = collection.mdxOptions;
578
- schema = collection.schema;
579
- break;
580
- case "docs":
581
- mdxOptions = collection.docs.mdxOptions;
582
- schema = collection.docs.schema;
583
- break;
584
- }
585
- if (schema) {
586
- try {
587
- matter.data = await validate(
588
- schema,
589
- matter.data,
590
- {
591
- source: value,
592
- path: path4
593
- },
594
- `invalid frontmatter in ${path4}`
595
- );
596
- } catch (e) {
597
- if (e instanceof ValidationError) {
598
- throw new Error(e.toStringFormatted());
599
- }
600
- throw e;
649
+ const [file, query = ""] = id.split("?");
650
+ const ext = path4.extname(file);
651
+ try {
652
+ if ([".yaml", ".json"].includes(ext))
653
+ return await transformMeta(file, query, value);
654
+ if ([".md", ".mdx"].includes(ext))
655
+ return await transformContent.call(this, file, query, value);
656
+ } catch (e) {
657
+ if (e instanceof ValidationError) {
658
+ throw new Error(e.toStringFormatted());
601
659
  }
660
+ throw e;
602
661
  }
603
- if (only === "frontmatter") {
604
- return {
605
- code: `export const frontmatter = ${JSON.stringify(matter.data)}`
606
- };
607
- }
608
- mdxOptions ??= await loaded.getDefaultMDXOptions();
609
- const lineOffset = isDevelopment ? countLines(matter.matter) : 0;
610
- const file = await buildMDX(
611
- parsed.collection ?? "global",
612
- "\n".repeat(lineOffset) + matter.content,
613
- {
614
- development: isDevelopment,
615
- ...mdxOptions,
616
- filePath: path4,
617
- frontmatter: matter.data,
618
- _compiler: {
619
- addDependency: (file2) => {
620
- this.addWatchFile(file2);
621
- }
622
- }
623
- }
624
- );
625
- return {
626
- code: String(file.value),
627
- map: file.map
628
- };
629
662
  }
630
663
  };
631
664
  }