fumadocs-mdx 13.0.0 → 13.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/bin.cjs +272 -240
  2. package/dist/{build-mdx-CzrQDBRZ.d.ts → build-mdx-CCNr86q6.d.ts} +1 -1
  3. package/dist/{build-mdx-BHG-_uxo.d.cts → build-mdx-D-r3_eQL.d.cts} +1 -1
  4. package/dist/bun/index.cjs +114 -34
  5. package/dist/bun/index.d.cts +8 -3
  6. package/dist/bun/index.d.ts +8 -3
  7. package/dist/bun/index.js +20 -10
  8. package/dist/{chunk-6Y5JDZHD.js → chunk-CXA4JO4Z.js} +1 -21
  9. package/dist/chunk-EELYB2XC.js +207 -0
  10. package/dist/{chunk-CEA6MYJU.js → chunk-XQ5O7IPO.js} +29 -27
  11. package/dist/chunk-XZY2AWJI.js +81 -0
  12. package/dist/{chunk-XV5Z4BFL.js → chunk-YVCR6FUH.js} +1 -1
  13. package/dist/config/index.d.cts +2 -2
  14. package/dist/config/index.d.ts +2 -2
  15. package/dist/{define-BCNh3n4O.d.cts → core-B6j6Fxse.d.cts} +101 -38
  16. package/dist/{define-bck_EB4t.d.ts → core-B6j6Fxse.d.ts} +101 -38
  17. package/dist/index.d.cts +7 -2
  18. package/dist/index.d.ts +7 -2
  19. package/dist/next/index.cjs +195 -163
  20. package/dist/next/index.js +79 -71
  21. package/dist/node/loader.cjs +120 -35
  22. package/dist/node/loader.js +10 -5
  23. package/dist/plugins/json-schema.cjs +103 -2
  24. package/dist/plugins/json-schema.d.cts +12 -4
  25. package/dist/plugins/json-schema.d.ts +12 -4
  26. package/dist/plugins/json-schema.js +40 -2
  27. package/dist/runtime/next/async.d.cts +4 -4
  28. package/dist/runtime/next/async.d.ts +4 -4
  29. package/dist/runtime/next/async.js +3 -3
  30. package/dist/runtime/next/index.d.cts +5 -5
  31. package/dist/runtime/next/index.d.ts +5 -5
  32. package/dist/runtime/vite/browser.d.cts +3 -3
  33. package/dist/runtime/vite/browser.d.ts +3 -3
  34. package/dist/runtime/vite/server.d.cts +3 -3
  35. package/dist/runtime/vite/server.d.ts +3 -3
  36. package/dist/{types-1cCFEzWt.d.ts → types-AGzTfBmf.d.ts} +1 -1
  37. package/dist/{types-D5NhXTJY.d.cts → types-DKGMoay5.d.cts} +1 -1
  38. package/dist/vite/index.cjs +123 -91
  39. package/dist/vite/index.js +30 -27
  40. package/dist/{loader-mdx.cjs → webpack/index.cjs} +151 -58
  41. package/dist/webpack/index.js +44 -0
  42. package/loader-mdx.cjs +1 -1
  43. package/package.json +4 -3
  44. package/dist/chunk-4MAYA5QX.js +0 -44
  45. package/dist/chunk-HI62EXSB.js +0 -127
  46. package/dist/loader-mdx.js +0 -39
  47. package/dist/plugins/index.cjs +0 -78
  48. package/dist/plugins/index.d.cts +0 -7
  49. package/dist/plugins/index.d.ts +0 -7
  50. package/dist/plugins/index.js +0 -6
  51. package/dist/remark-postprocess-K233ZVBK.d.cts +0 -22
  52. package/dist/remark-postprocess-K233ZVBK.d.ts +0 -22
  53. package/dist/watcher-WXJDWRZY.js +0 -22
  54. /package/dist/{loader-mdx.d.cts → webpack/index.d.cts} +0 -0
  55. /package/dist/{loader-mdx.d.ts → webpack/index.d.ts} +0 -0
@@ -1,25 +1,24 @@
1
- import {
2
- getGlobPatterns,
3
- getImportCode,
4
- isFileSupported,
5
- toImportPath
6
- } from "../chunk-6Y5JDZHD.js";
7
1
  import {
8
2
  loadConfig
9
3
  } from "../chunk-JVZFH6ND.js";
4
+ import {
5
+ getImportCode,
6
+ toImportPath
7
+ } from "../chunk-CXA4JO4Z.js";
10
8
  import "../chunk-U4MQ44TS.js";
11
9
  import {
12
10
  ValidationError,
11
+ createCore,
13
12
  findConfigFile,
14
13
  getGitTimestamp,
15
14
  validate
16
- } from "../chunk-HI62EXSB.js";
15
+ } from "../chunk-EELYB2XC.js";
17
16
  import {
18
17
  fumaMatter
19
18
  } from "../chunk-VWJKRQZR.js";
20
19
  import {
21
- createPluginHandler
22
- } from "../chunk-4MAYA5QX.js";
20
+ getCollectionFiles
21
+ } from "../chunk-XZY2AWJI.js";
23
22
 
24
23
  // src/next/index.ts
25
24
  import * as path3 from "path";
@@ -52,13 +51,29 @@ function removeFileCache(file) {
52
51
  // src/plugins/next.ts
53
52
  import * as path2 from "path";
54
53
  import { createHash } from "crypto";
55
- import { glob } from "tinyglobby";
56
54
  import { load } from "js-yaml";
57
55
  function next() {
58
56
  let config;
57
+ let shouldEmitOnChange = false;
59
58
  return {
59
+ name: "next",
60
60
  config(v) {
61
61
  config = v;
62
+ shouldEmitOnChange = false;
63
+ for (const collection of config.collections.values()) {
64
+ if (collection.type === "doc" && collection.async || collection.type === "docs" && collection.docs.async) {
65
+ shouldEmitOnChange = true;
66
+ }
67
+ }
68
+ },
69
+ configureServer(server) {
70
+ if (!server.watcher) return;
71
+ server.watcher.on("all", async () => {
72
+ if (!shouldEmitOnChange) return;
73
+ await this.core.emitAndWrite({
74
+ filterPlugin: (plugin) => plugin.name === "next"
75
+ });
76
+ });
62
77
  },
63
78
  async emit() {
64
79
  return [
@@ -201,27 +216,6 @@ async function indexFile(configPath, config, importPath, configHash = false) {
201
216
  ...resolvedDeclares
202
217
  ].join("\n");
203
218
  }
204
- async function getCollectionFiles(collection) {
205
- const files = /* @__PURE__ */ new Map();
206
- const dirs = Array.isArray(collection.dir) ? collection.dir : [collection.dir];
207
- const patterns = getGlobPatterns(collection);
208
- await Promise.all(
209
- dirs.map(async (dir) => {
210
- const result = await glob(patterns, {
211
- cwd: path2.resolve(dir)
212
- });
213
- for (const item of result) {
214
- if (!isFileSupported(item, collection)) continue;
215
- const fullPath = path2.join(dir, item);
216
- files.set(fullPath, {
217
- path: item,
218
- fullPath
219
- });
220
- }
221
- })
222
- );
223
- return Array.from(files.values());
224
- }
225
219
  function parseMetaEntry(file, content) {
226
220
  const extname2 = path2.extname(file);
227
221
  try {
@@ -289,63 +283,63 @@ function createMDX(createOptions = {}) {
289
283
  };
290
284
  }
291
285
  async function init(dev, options) {
292
- const pluginHandler = createNextPluginHandler(options);
293
- let config;
294
- async function updateConfig() {
295
- config = await pluginHandler.init(
296
- await loadConfig(options.configPath, options.outDir, true)
297
- );
286
+ const core = createNextCore(options);
287
+ async function initOrReload() {
288
+ await core.init({
289
+ config: loadConfig(options.configPath, options.outDir, true)
290
+ });
291
+ await core.emitAndWrite();
298
292
  }
299
- async function emitFiles() {
300
- const start = performance.now();
301
- try {
302
- await pluginHandler.emitAndWrite();
303
- } catch (err) {
304
- if (err instanceof ValidationError) {
305
- console.error(err.toStringFormatted());
293
+ async function devServer() {
294
+ const { FSWatcher } = await import("chokidar");
295
+ const watcher = new FSWatcher({
296
+ ignoreInitial: true,
297
+ persistent: true,
298
+ ignored: [options.outDir]
299
+ });
300
+ watcher.add(options.configPath);
301
+ for (const collection of core.getConfig().collections.values()) {
302
+ if (collection.type === "docs") {
303
+ watcher.add(collection.docs.dir);
304
+ watcher.add(collection.meta.dir);
306
305
  } else {
307
- console.error(err);
306
+ watcher.add(collection.dir);
308
307
  }
309
308
  }
310
- console.log(`[MDX] updated map file in ${performance.now() - start}ms`);
311
- }
312
- async function devServer() {
313
- const { watcher } = await import("../watcher-WXJDWRZY.js");
314
- const instance = watcher(options.configPath, config, [options.outDir]);
315
- async function onUpdate(event, file) {
309
+ watcher.on("ready", () => {
310
+ console.log("[MDX] started dev server");
311
+ });
312
+ watcher.on("all", async (event, file) => {
316
313
  const absolutePath = path3.resolve(file);
317
314
  if (event === "change") removeFileCache(absolutePath);
318
315
  if (absolutePath === path3.resolve(options.configPath)) {
319
- await updateConfig();
316
+ watcher.removeAllListeners();
317
+ await watcher.close();
318
+ await initOrReload();
320
319
  console.log("[MDX] restarting dev server");
321
- await instance.close();
322
- void devServer();
320
+ await devServer();
323
321
  }
324
- await emitFiles();
325
- }
326
- instance.on("ready", () => {
327
- console.log("[MDX] started dev server");
328
- });
329
- instance.on("all", (event, file) => {
330
- void onUpdate(event, file);
331
322
  });
332
323
  process.on("exit", () => {
324
+ if (watcher.closed) return;
333
325
  console.log("[MDX] closing dev server");
334
- void instance.close();
326
+ void watcher.close();
335
327
  });
328
+ await core.initServer({ watcher });
329
+ }
330
+ await initOrReload();
331
+ if (dev) {
332
+ await devServer();
336
333
  }
337
- await updateConfig();
338
- await emitFiles();
339
- if (dev) void devServer();
340
334
  }
341
335
  async function postInstall(configPath = findConfigFile(), outDir = ".source") {
342
- const pluginHandler = createNextPluginHandler({
336
+ const core = await createNextCore({
343
337
  outDir,
344
338
  configPath
339
+ }).init({
340
+ config: loadConfig(configPath, outDir, true)
345
341
  });
346
- await pluginHandler.init(await loadConfig(configPath, outDir, true));
347
- await pluginHandler.emitAndWrite();
348
- console.log("[MDX] types generated");
342
+ await core.emitAndWrite();
349
343
  }
350
344
  function applyDefaults(options) {
351
345
  return {
@@ -353,11 +347,11 @@ function applyDefaults(options) {
353
347
  configPath: options.configPath ?? findConfigFile()
354
348
  };
355
349
  }
356
- function createNextPluginHandler({
350
+ function createNextCore({
357
351
  outDir,
358
352
  configPath
359
353
  }) {
360
- return createPluginHandler(
354
+ const core = createCore(
361
355
  {
362
356
  environment: "next",
363
357
  outDir,
@@ -365,6 +359,20 @@ function createNextPluginHandler({
365
359
  },
366
360
  [next()]
367
361
  );
362
+ return {
363
+ ...core,
364
+ async emitAndWrite(...args) {
365
+ try {
366
+ await core.emitAndWrite(...args);
367
+ } catch (err) {
368
+ if (err instanceof ValidationError) {
369
+ console.error(err.toStringFormatted());
370
+ } else {
371
+ console.error(err);
372
+ }
373
+ }
374
+ }
375
+ };
368
376
  }
369
377
  export {
370
378
  createMDX,
@@ -230,18 +230,24 @@ function findConfigFile() {
230
230
  return import_node_path.default.resolve("source.config.ts");
231
231
  }
232
232
  function staticConfig({
233
- outDir,
234
- configPath,
233
+ core: core2,
235
234
  buildConfig: buildConfig2
236
235
  }) {
237
236
  let cached;
237
+ async function newConfig() {
238
+ const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_load(), load_exports));
239
+ await core2.init({
240
+ config: loadConfig2(
241
+ core2._options.configPath,
242
+ core2._options.outDir,
243
+ buildConfig2
244
+ )
245
+ });
246
+ return core2.getConfig();
247
+ }
238
248
  return {
239
249
  async getConfig() {
240
- if (cached) return cached;
241
- cached = Promise.resolve().then(() => (init_load(), load_exports)).then(
242
- (mod) => mod.loadConfig(configPath, outDir, buildConfig2)
243
- );
244
- return cached;
250
+ return cached ??= newConfig();
245
251
  }
246
252
  };
247
253
  }
@@ -690,14 +696,6 @@ var cacheEntry = import_zod.z.object({
690
696
  map: import_zod.z.any().optional(),
691
697
  hash: import_zod.z.string().optional()
692
698
  });
693
- var hashes = /* @__PURE__ */ new WeakMap();
694
- function getConfigHash(config) {
695
- let hash = hashes.get(config);
696
- if (hash) return hash;
697
- hash = Date.now().toString();
698
- hashes.set(config, hash);
699
- return hash;
700
- }
701
699
  function createMdxLoader(configLoader) {
702
700
  return async ({
703
701
  source: value,
@@ -708,14 +706,25 @@ function createMdxLoader(configLoader) {
708
706
  }) => {
709
707
  const matter = fumaMatter(value);
710
708
  const parsed = querySchema.parse(query);
711
- const loaded = await configLoader.getConfig();
712
- const cacheDir = isDevelopment ? void 0 : loaded.global.experimentalBuildCache;
713
- const cacheKey = `${parsed.hash}_${parsed.collection ?? "global"}_${generateCacheHash(filePath)}`;
714
- if (cacheDir) {
709
+ const config = await configLoader.getConfig();
710
+ let after;
711
+ if (!isDevelopment && config.global.experimentalBuildCache) {
712
+ const cacheDir = config.global.experimentalBuildCache;
713
+ const cacheKey = `${parsed.hash}_${parsed.collection ?? "global"}_${generateCacheHash(filePath)}`;
715
714
  const cached = await import_promises2.default.readFile(import_node_path3.default.join(cacheDir, cacheKey)).then((content) => cacheEntry.parse(JSON.parse(content.toString()))).catch(() => null);
716
715
  if (cached && cached.hash === generateCacheHash(value)) return cached;
716
+ after = async () => {
717
+ await import_promises2.default.mkdir(cacheDir, { recursive: true });
718
+ await import_promises2.default.writeFile(
719
+ import_node_path3.default.join(cacheDir, cacheKey),
720
+ JSON.stringify({
721
+ ...out,
722
+ hash: generateCacheHash(value)
723
+ })
724
+ );
725
+ };
717
726
  }
718
- const collection = parsed.collection ? loaded.collections.get(parsed.collection) : void 0;
727
+ const collection = parsed.collection ? config.collections.get(parsed.collection) : void 0;
719
728
  let docCollection;
720
729
  switch (collection?.type) {
721
730
  case "doc":
@@ -743,16 +752,16 @@ function createMdxLoader(configLoader) {
743
752
  };
744
753
  }
745
754
  const data = {};
746
- if (loaded.global.lastModifiedTime === "git") {
755
+ if (config.global.lastModifiedTime === "git") {
747
756
  data.lastModified = (await getGitTimestamp(filePath))?.getTime();
748
757
  }
749
758
  const lineOffset = isDevelopment ? countLines(matter.matter) : 0;
750
759
  const compiled = await buildMDX(
751
- `${getConfigHash(loaded)}:${parsed.collection ?? "global"}`,
760
+ `${getConfigHash(config)}:${parsed.collection ?? "global"}`,
752
761
  "\n".repeat(lineOffset) + matter.content,
753
762
  {
754
763
  development: isDevelopment,
755
- ...docCollection?.mdxOptions ?? await loaded.getDefaultMDXOptions(),
764
+ ...docCollection?.mdxOptions ?? await config.getDefaultMDXOptions(),
756
765
  postprocess: docCollection?.postprocess,
757
766
  data,
758
767
  filePath,
@@ -764,19 +773,18 @@ function createMdxLoader(configLoader) {
764
773
  code: String(compiled.value),
765
774
  map: compiled.map
766
775
  };
767
- if (cacheDir) {
768
- await import_promises2.default.mkdir(cacheDir, { recursive: true });
769
- await import_promises2.default.writeFile(
770
- import_node_path3.default.join(cacheDir, cacheKey),
771
- JSON.stringify({
772
- ...out,
773
- hash: generateCacheHash(value)
774
- })
775
- );
776
- }
776
+ await after?.();
777
777
  return out;
778
778
  };
779
779
  }
780
+ var hashes = /* @__PURE__ */ new WeakMap();
781
+ function getConfigHash(config) {
782
+ let hash = hashes.get(config);
783
+ if (hash) return hash;
784
+ hash = Date.now().toString();
785
+ hashes.set(config, hash);
786
+ return hash;
787
+ }
780
788
  function generateCacheHash(input) {
781
789
  return (0, import_node_crypto.createHash)("md5").update(input).digest("hex");
782
790
  }
@@ -820,12 +828,89 @@ function toNode(loader, filterByPath) {
820
828
  };
821
829
  }
822
830
 
831
+ // src/core.ts
832
+ var import_node_path5 = __toESM(require("path"), 1);
833
+ var import_promises4 = __toESM(require("fs/promises"), 1);
834
+ function createCore(options, defaultPlugins = []) {
835
+ let config;
836
+ let plugins2;
837
+ return {
838
+ _options: options,
839
+ getPluginContext() {
840
+ return {
841
+ core: this,
842
+ ...options
843
+ };
844
+ },
845
+ /**
846
+ * Convenient cache store, reset when config changes
847
+ */
848
+ cache: /* @__PURE__ */ new Map(),
849
+ async init({ config: newConfig }) {
850
+ config = await newConfig;
851
+ this.cache.clear();
852
+ plugins2 = [];
853
+ for await (const option of [
854
+ ...defaultPlugins,
855
+ ...config.global.plugins ?? []
856
+ ]) {
857
+ if (!option) continue;
858
+ if (Array.isArray(option)) plugins2.push(...option);
859
+ else plugins2.push(option);
860
+ }
861
+ for (const plugin of plugins2) {
862
+ const out = await plugin.config?.call(this.getPluginContext(), config);
863
+ if (out) config = out;
864
+ }
865
+ return this;
866
+ },
867
+ getConfig() {
868
+ return config;
869
+ },
870
+ creatConfigLoader() {
871
+ return {
872
+ getConfig() {
873
+ return config;
874
+ }
875
+ };
876
+ },
877
+ async initServer(server) {
878
+ for (const plugin of plugins2) {
879
+ await plugin.configureServer?.call(this.getPluginContext(), server);
880
+ }
881
+ },
882
+ async emitAndWrite({
883
+ filterPlugin = () => true
884
+ } = {}) {
885
+ const start = performance.now();
886
+ const out = await Promise.all(
887
+ plugins2.map((plugin) => {
888
+ if (!filterPlugin(plugin) || !plugin.emit) return [];
889
+ return plugin.emit.call(this.getPluginContext());
890
+ })
891
+ );
892
+ await Promise.all(
893
+ out.flat().map(async (entry) => {
894
+ const file = import_node_path5.default.join(options.outDir, entry.path);
895
+ await import_promises4.default.mkdir(import_node_path5.default.dirname(file), { recursive: true });
896
+ await import_promises4.default.writeFile(file, entry.content);
897
+ })
898
+ );
899
+ console.log(`[MDX] generated files in ${performance.now() - start}ms`);
900
+ }
901
+ };
902
+ }
903
+
823
904
  // src/node/loader.ts
905
+ var core = createCore({
906
+ environment: "node",
907
+ configPath: findConfigFile(),
908
+ outDir: ".source"
909
+ });
824
910
  var load2 = toNode(
825
911
  createMdxLoader(
826
912
  staticConfig({
827
- configPath: findConfigFile(),
828
- outDir: ".source",
913
+ core,
829
914
  buildConfig: true
830
915
  })
831
916
  ),
@@ -1,23 +1,28 @@
1
1
  import {
2
2
  toNode
3
- } from "../chunk-XV5Z4BFL.js";
3
+ } from "../chunk-YVCR6FUH.js";
4
4
  import {
5
5
  createMdxLoader
6
- } from "../chunk-CEA6MYJU.js";
6
+ } from "../chunk-XQ5O7IPO.js";
7
7
  import "../chunk-3J3WL7WN.js";
8
8
  import "../chunk-K5ZLPEIQ.js";
9
9
  import {
10
+ createCore,
10
11
  findConfigFile,
11
12
  staticConfig
12
- } from "../chunk-HI62EXSB.js";
13
+ } from "../chunk-EELYB2XC.js";
13
14
  import "../chunk-VWJKRQZR.js";
14
15
 
15
16
  // src/node/loader.ts
17
+ var core = createCore({
18
+ environment: "node",
19
+ configPath: findConfigFile(),
20
+ outDir: ".source"
21
+ });
16
22
  var load = toNode(
17
23
  createMdxLoader(
18
24
  staticConfig({
19
- configPath: findConfigFile(),
20
- outDir: ".source",
25
+ core,
21
26
  buildConfig: true
22
27
  })
23
28
  ),
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/plugins/json-schema.ts
@@ -24,17 +34,108 @@ __export(json_schema_exports, {
24
34
  });
25
35
  module.exports = __toCommonJS(json_schema_exports);
26
36
  var import_zod = require("zod");
27
- function jsonSchema() {
37
+
38
+ // src/utils/collections.ts
39
+ var import_picomatch = __toESM(require("picomatch"), 1);
40
+ var import_tinyglobby = require("tinyglobby");
41
+ var import_node_path = __toESM(require("path"), 1);
42
+ var SupportedFormats = {
43
+ doc: ["mdx", "md"],
44
+ meta: ["json", "yaml"]
45
+ };
46
+ function getGlobPatterns(collection) {
47
+ if (collection.files) return collection.files;
48
+ return [`**/*.{${SupportedFormats[collection.type].join(",")}}`];
49
+ }
50
+ function isFileSupported(filePath, collection) {
51
+ return SupportedFormats[collection.type].some(
52
+ (format) => filePath.endsWith(`.${format}`)
53
+ );
54
+ }
55
+ function createCollectionMatcher(core) {
56
+ const CacheKey = "collection-matcher";
57
+ return {
58
+ scan(config) {
59
+ const scanned = [];
60
+ function scan(name, collection) {
61
+ const patterns = getGlobPatterns(collection);
62
+ for (const dir of Array.isArray(collection.dir) ? collection.dir : [collection.dir]) {
63
+ scanned.push({
64
+ name,
65
+ collection,
66
+ matcher: (0, import_picomatch.default)(patterns, {
67
+ cwd: dir
68
+ })
69
+ });
70
+ }
71
+ }
72
+ for (const [name, collection] of config.collections) {
73
+ if (collection.type === "docs") {
74
+ scan(name, collection.meta);
75
+ scan(name, collection.docs);
76
+ } else {
77
+ scan(name, collection);
78
+ }
79
+ }
80
+ return scanned;
81
+ },
82
+ getFileCollection(file) {
83
+ const scanned = core.cache.get(CacheKey) ?? this.scan(core.getConfig());
84
+ core.cache.set(CacheKey, scanned);
85
+ for (const item of scanned) {
86
+ if (isFileSupported(file, item.collection) && item.matcher(file))
87
+ return { name: item.name, collection: item.collection };
88
+ }
89
+ }
90
+ };
91
+ }
92
+
93
+ // src/plugins/json-schema.ts
94
+ var import_promises = __toESM(require("fs/promises"), 1);
95
+ var import_node_path2 = __toESM(require("path"), 1);
96
+ function jsonSchema({
97
+ insert = false
98
+ } = {}) {
28
99
  let config;
100
+ function getSchemaPath(name) {
101
+ return `json-schema/${name}.json`;
102
+ }
29
103
  return {
30
104
  config(v) {
31
105
  config = v;
32
106
  },
107
+ configureServer(server) {
108
+ if (!server.watcher || !insert) return;
109
+ const matcher = createCollectionMatcher(this.core);
110
+ server.watcher.on("add", async (file) => {
111
+ const match = matcher.getFileCollection(file);
112
+ if (!match || match.collection.type !== "meta") return;
113
+ const { name } = match;
114
+ const parent = config.collections.get(name);
115
+ let obj;
116
+ try {
117
+ const content = (await import_promises.default.readFile(file)).toString();
118
+ obj = content.length > 0 ? JSON.parse(content) : {};
119
+ } catch {
120
+ return;
121
+ }
122
+ if ("$schema" in obj) return;
123
+ const schemaPath = import_node_path2.default.join(
124
+ this.outDir,
125
+ getSchemaPath(parent?.type === "docs" ? `${name}.meta` : name)
126
+ );
127
+ const updated = {
128
+ $schema: import_node_path2.default.relative(import_node_path2.default.dirname(file), schemaPath),
129
+ ...obj
130
+ };
131
+ await import_promises.default.writeFile(file, JSON.stringify(updated, null, 2));
132
+ });
133
+ },
33
134
  emit() {
34
135
  const files = [];
35
136
  function onSchema(name, schema) {
36
137
  files.push({
37
- path: `json-schema/${name}.json`,
138
+ path: getSchemaPath(name),
38
139
  content: JSON.stringify(
39
140
  import_zod.z.toJSONSchema(schema, {
40
141
  io: "input",
@@ -1,16 +1,24 @@
1
- import { P as Plugin } from '../define-BCNh3n4O.cjs';
1
+ import { i as Plugin } from '../core-B6j6Fxse.cjs';
2
2
  import '@standard-schema/spec';
3
3
  import 'fumadocs-core/mdx-plugins';
4
4
  import '@mdx-js/mdx';
5
5
  import 'unified';
6
6
  import 'zod';
7
- import '../remark-postprocess-K233ZVBK.cjs';
7
+ import 'chokidar';
8
8
 
9
+ interface JSONSchemaOptions {
10
+ /**
11
+ * insert `$schema` field to JSON files on creation.
12
+ *
13
+ * @defaultValue false
14
+ */
15
+ insert?: boolean;
16
+ }
9
17
  /**
10
18
  * Generate JSON schemas locally for collection schemas
11
19
  *
12
20
  * note: **it only works with Zod**
13
21
  */
14
- declare function jsonSchema(): Plugin;
22
+ declare function jsonSchema({ insert, }?: JSONSchemaOptions): Plugin;
15
23
 
16
- export { jsonSchema as default };
24
+ export { type JSONSchemaOptions, jsonSchema as default };
@@ -1,16 +1,24 @@
1
- import { P as Plugin } from '../define-bck_EB4t.js';
1
+ import { i as Plugin } from '../core-B6j6Fxse.js';
2
2
  import '@standard-schema/spec';
3
3
  import 'fumadocs-core/mdx-plugins';
4
4
  import '@mdx-js/mdx';
5
5
  import 'unified';
6
6
  import 'zod';
7
- import '../remark-postprocess-K233ZVBK.js';
7
+ import 'chokidar';
8
8
 
9
+ interface JSONSchemaOptions {
10
+ /**
11
+ * insert `$schema` field to JSON files on creation.
12
+ *
13
+ * @defaultValue false
14
+ */
15
+ insert?: boolean;
16
+ }
9
17
  /**
10
18
  * Generate JSON schemas locally for collection schemas
11
19
  *
12
20
  * note: **it only works with Zod**
13
21
  */
14
- declare function jsonSchema(): Plugin;
22
+ declare function jsonSchema({ insert, }?: JSONSchemaOptions): Plugin;
15
23
 
16
- export { jsonSchema as default };
24
+ export { type JSONSchemaOptions, jsonSchema as default };