fumadocs-typescript 4.0.14 → 5.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.
package/dist/index.js CHANGED
@@ -1,522 +1,375 @@
1
- import {
2
- __async,
3
- __objRest,
4
- __spreadProps,
5
- __spreadValues,
6
- parseTags,
7
- renderMarkdownToHast,
8
- renderTypeToHast
9
- } from "./chunk-REUDVA2G.js";
10
-
11
- // src/lib/base.ts
12
- import {
13
- Project as Project2,
14
- ts as ts2
15
- } from "ts-morph";
1
+ import { a as _asyncToGenerator, i as renderTypeToHast, n as parseTags, o as _objectWithoutProperties, r as renderMarkdownToHast, t as _objectSpread2 } from "./objectSpread2-BbbttTvx.js";
2
+ import * as ts$1 from "ts-morph";
3
+ import { Project, ts } from "ts-morph";
4
+ import * as fs$1 from "node:fs/promises";
5
+ import fs from "node:fs/promises";
6
+ import path, { join } from "node:path";
7
+ import { valueToEstree } from "estree-util-value-to-estree";
8
+ import { visit } from "unist-util-visit";
9
+ import { toEstree } from "hast-util-to-estree";
10
+ import { createHash } from "node:crypto";
16
11
 
17
- // src/create-project.ts
18
- import { Project } from "ts-morph";
12
+ //#region src/create-project.ts
19
13
  function createProject(options = {}) {
20
- var _a;
21
- return new Project({
22
- tsConfigFilePath: (_a = options.tsconfigPath) != null ? _a : "./tsconfig.json",
23
- skipAddingFilesFromTsConfig: true
24
- });
14
+ var _options$tsconfigPath;
15
+ return new Project({
16
+ tsConfigFilePath: (_options$tsconfigPath = options.tsconfigPath) !== null && _options$tsconfigPath !== void 0 ? _options$tsconfigPath : "./tsconfig.json",
17
+ skipAddingFilesFromTsConfig: true
18
+ });
25
19
  }
26
20
 
27
- // src/lib/base.ts
28
- import fs3 from "fs";
29
-
30
- // src/lib/type-table.ts
31
- import * as fs from "fs/promises";
32
- import { join } from "path";
33
- function getTypeTableOutput(gen, _a, options) {
34
- return __async(this, null, function* () {
35
- var _b = _a, { name, type } = _b, props = __objRest(_b, ["name", "type"]);
36
- const file = props.path && (options == null ? void 0 : options.basePath) ? join(options.basePath, props.path) : props.path;
37
- let typeName = name;
38
- let content = "";
39
- if (file) {
40
- content = (yield fs.readFile(file)).toString();
41
- }
42
- if (type && type.split("\n").length > 1) {
43
- content += `
44
- ${type}`;
45
- } else if (type) {
46
- typeName != null ? typeName : typeName = "$Fumadocs";
47
- content += `
48
- export type ${typeName} = ${type}`;
49
- }
50
- const output = gen.generateDocumentation(
51
- { path: file != null ? file : "temp.ts", content },
52
- typeName,
53
- options
54
- );
55
- if (name && output.length === 0)
56
- throw new Error(`${name} in ${file != null ? file : "empty file"} doesn't exist`);
57
- return output;
58
- });
21
+ //#endregion
22
+ //#region src/lib/type-table.ts
23
+ const _excluded = ["name", "type"];
24
+ function getTypeTableOutput(_x, _x2, _x3) {
25
+ return _getTypeTableOutput.apply(this, arguments);
59
26
  }
60
-
61
- // src/lib/cache.ts
62
- import fs2 from "fs";
63
- import { createHash } from "crypto";
64
- import path from "path";
65
- function createCache() {
66
- const dir = path.join(process.cwd(), ".next/fumadocs-typescript");
67
- try {
68
- fs2.mkdirSync(dir, { recursive: true });
69
- } catch (e) {
70
- }
71
- return {
72
- write(input, data) {
73
- const hash = createHash("SHA256").update(input).digest("hex").slice(0, 12);
74
- fs2.writeFileSync(path.join(dir, `${hash}.json`), JSON.stringify(data));
75
- },
76
- read(input) {
77
- const hash = createHash("SHA256").update(input).digest("hex").slice(0, 12);
78
- try {
79
- return JSON.parse(
80
- fs2.readFileSync(path.join(dir, `${hash}.json`)).toString()
81
- );
82
- } catch (e) {
83
- return;
84
- }
85
- }
86
- };
27
+ function _getTypeTableOutput() {
28
+ _getTypeTableOutput = _asyncToGenerator(function* (gen, _ref, options) {
29
+ let { name, type } = _ref, props = _objectWithoutProperties(_ref, _excluded);
30
+ const file = props.path && (options === null || options === void 0 ? void 0 : options.basePath) ? join(options.basePath, props.path) : props.path;
31
+ let typeName = name;
32
+ let content = "";
33
+ if (file) content = (yield fs$1.readFile(file)).toString();
34
+ if (type && type.split("\n").length > 1) content += `\n${type}`;
35
+ else if (type) {
36
+ var _typeName;
37
+ (_typeName = typeName) !== null && _typeName !== void 0 || (typeName = "$Fumadocs");
38
+ content += `\nexport type ${typeName} = ${type}`;
39
+ }
40
+ const output = yield gen.generateDocumentation({
41
+ path: file !== null && file !== void 0 ? file : "temp.ts",
42
+ content
43
+ }, typeName, options);
44
+ if (name && output.length === 0) throw new Error(`${name} in ${file !== null && file !== void 0 ? file : "empty file"} doesn't exist`);
45
+ return output;
46
+ });
47
+ return _getTypeTableOutput.apply(this, arguments);
87
48
  }
88
49
 
89
- // src/lib/base.ts
90
- import path2 from "path";
91
-
92
- // src/lib/get-simple-form.ts
93
- import * as ts from "ts-morph";
50
+ //#endregion
51
+ //#region src/lib/get-simple-form.ts
94
52
  function getSimpleForm(type, checker, noUndefined = false, location) {
95
- if (type.isUndefined() && noUndefined) return "";
96
- const alias = type.getAliasSymbol();
97
- if (alias) {
98
- const args = type.getAliasTypeArguments();
99
- if (args.length === 0) return alias.getName();
100
- return `${alias.getName()}<${args.map((arg) => getSimpleForm(arg, checker)).join(", ")}>`;
101
- }
102
- if (type.isUnion()) {
103
- const types = [];
104
- for (const t of type.getUnionTypes()) {
105
- const str = getSimpleForm(t, checker, noUndefined);
106
- if (str.length > 0 && str !== "never") types.unshift(str);
107
- }
108
- return types.length > 0 ? (
109
- // boolean | null will become true | false | null, need to ensure it's still returned as boolean
110
- dedupe(types).join(" | ").replace("true | false", "boolean")
111
- ) : "never";
112
- }
113
- if (type.isIntersection()) {
114
- const types = [];
115
- for (const t of type.getIntersectionTypes()) {
116
- const str = getSimpleForm(t, checker, noUndefined);
117
- if (str.length > 0 && str !== "never") types.unshift(str);
118
- }
119
- return dedupe(types).join(" & ");
120
- }
121
- if (type.isTuple()) {
122
- const elements = type.getTupleElements().map((t) => getSimpleForm(t, checker)).join(", ");
123
- return `[${elements}]`;
124
- }
125
- if (type.isArray() || type.isReadonlyArray()) {
126
- return "array";
127
- }
128
- if (type.getCallSignatures().length > 0) {
129
- return "function";
130
- }
131
- if (type.isClassOrInterface() || type.isObject()) {
132
- return "object";
133
- }
134
- return type.getText(
135
- location,
136
- ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope
137
- );
53
+ if (type.isUndefined() && noUndefined) return "";
54
+ const alias = type.getAliasSymbol();
55
+ if (alias) {
56
+ const args = type.getAliasTypeArguments();
57
+ if (args.length === 0) return alias.getName();
58
+ return `${alias.getName()}<${args.map((arg) => getSimpleForm(arg, checker)).join(", ")}>`;
59
+ }
60
+ if (type.isUnion()) {
61
+ const types = [];
62
+ for (const t of type.getUnionTypes()) {
63
+ const str = getSimpleForm(t, checker, noUndefined);
64
+ if (str.length > 0 && str !== "never") types.unshift(str);
65
+ }
66
+ return types.length > 0 ? dedupe(types).join(" | ").replace("true | false", "boolean") : "never";
67
+ }
68
+ if (type.isIntersection()) {
69
+ const types = [];
70
+ for (const t of type.getIntersectionTypes()) {
71
+ const str = getSimpleForm(t, checker, noUndefined);
72
+ if (str.length > 0 && str !== "never") types.unshift(str);
73
+ }
74
+ return dedupe(types).join(" & ");
75
+ }
76
+ if (type.isTuple()) return `[${type.getTupleElements().map((t) => getSimpleForm(t, checker)).join(", ")}]`;
77
+ if (type.isArray() || type.isReadonlyArray()) return "array";
78
+ if (type.getCallSignatures().length > 0) return "function";
79
+ if (type.isClassOrInterface() || type.isObject()) return "object";
80
+ return type.getText(location, ts$1.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope);
138
81
  }
139
82
  function dedupe(arr) {
140
- const dedupe2 = /* @__PURE__ */ new Set();
141
- const out = [];
142
- for (const item of arr) {
143
- if (!dedupe2.has(item)) {
144
- out.push(item);
145
- dedupe2.add(item);
146
- }
147
- }
148
- return out;
83
+ const dedupe$1 = /* @__PURE__ */ new Set();
84
+ const out = [];
85
+ for (const item of arr) if (!dedupe$1.has(item)) {
86
+ out.push(item);
87
+ dedupe$1.add(item);
88
+ }
89
+ return out;
149
90
  }
150
91
 
151
- // src/lib/base.ts
92
+ //#endregion
93
+ //#region src/lib/base.ts
152
94
  function createGenerator(config) {
153
- var _a;
154
- const options = config instanceof Project2 ? {
155
- project: config
156
- } : config;
157
- const cacheType = (_a = options == null ? void 0 : options.cache) != null ? _a : process.env.NODE_ENV !== "development" ? "fs" : false;
158
- const cache = cacheType === "fs" ? createCache() : null;
159
- let instance;
160
- function getProject() {
161
- var _a2;
162
- instance != null ? instance : instance = (_a2 = options == null ? void 0 : options.project) != null ? _a2 : createProject(options);
163
- return instance;
164
- }
165
- return {
166
- generateDocumentation(file, name, options2) {
167
- var _a2;
168
- const content = (_a2 = file.content) != null ? _a2 : fs3.readFileSync(path2.resolve(file.path)).toString();
169
- const cacheKey = `${file.path}:${name}:${content}`;
170
- if (cache) {
171
- const cached = cache.read(cacheKey);
172
- if (cached) return cached;
173
- }
174
- const sourceFile = getProject().createSourceFile(file.path, content, {
175
- overwrite: true
176
- });
177
- const out = [];
178
- for (const [k, d] of sourceFile.getExportedDeclarations()) {
179
- if (name && name !== k) continue;
180
- if (d.length > 1)
181
- console.warn(
182
- `export ${k} should not have more than one type declaration.`
183
- );
184
- out.push(generate(getProject(), k, d[0], options2));
185
- }
186
- cache == null ? void 0 : cache.write(cacheKey, out);
187
- return out;
188
- },
189
- generateTypeTable(props, options2) {
190
- return getTypeTableOutput(this, props, options2);
191
- }
192
- };
193
- }
194
- function generateDocumentation(file, name, content, options = {}) {
195
- var _a;
196
- const gen = createGenerator((_a = options.project) != null ? _a : options.config);
197
- return gen.generateDocumentation({ path: file, content }, name, options);
95
+ const options = config instanceof Project ? { project: config } : config;
96
+ const cache = (options === null || options === void 0 ? void 0 : options.cache) ? options.cache : null;
97
+ let instance;
98
+ function getProject() {
99
+ var _instance, _options$project;
100
+ (_instance = instance) !== null && _instance !== void 0 || (instance = (_options$project = options === null || options === void 0 ? void 0 : options.project) !== null && _options$project !== void 0 ? _options$project : createProject(options));
101
+ return instance;
102
+ }
103
+ return {
104
+ generateDocumentation(file, name, options$1) {
105
+ return _asyncToGenerator(function* () {
106
+ var _file$content;
107
+ const content = (_file$content = file.content) !== null && _file$content !== void 0 ? _file$content : (yield fs.readFile(path.resolve(file.path))).toString();
108
+ const cacheKey = `${file.path}:${name}:${content}`;
109
+ if (cache) {
110
+ const cached = yield cache.read(cacheKey);
111
+ if (cached) return cached;
112
+ }
113
+ const sourceFile = getProject().createSourceFile(file.path, content, { overwrite: true });
114
+ const out = [];
115
+ for (const [k, d] of sourceFile.getExportedDeclarations()) {
116
+ if (name && name !== k) continue;
117
+ if (d.length > 1) console.warn(`export ${k} should not have more than one type declaration.`);
118
+ out.push(generate(getProject(), k, d[0], options$1));
119
+ }
120
+ cache === null || cache === void 0 || cache.write(cacheKey, out);
121
+ return out;
122
+ })();
123
+ },
124
+ generateTypeTable(props, options$1) {
125
+ return getTypeTableOutput(this, props, options$1);
126
+ }
127
+ };
198
128
  }
199
129
  function generate(program, name, declaration, { allowInternal = false, transform } = {}) {
200
- var _a;
201
- const entryContext = {
202
- transform,
203
- program,
204
- type: declaration.getType(),
205
- declaration
206
- };
207
- const comment = (_a = declaration.getSymbol()) == null ? void 0 : _a.compilerSymbol.getDocumentationComment(
208
- program.getTypeChecker().compilerObject
209
- );
210
- return {
211
- name,
212
- description: comment ? ts2.displayPartsToString(comment) : "",
213
- entries: declaration.getType().getProperties().map((prop) => getDocEntry(prop, entryContext)).filter(
214
- (entry) => entry && (allowInternal || !("internal" in entry.tags))
215
- )
216
- };
130
+ var _declaration$getSymbo;
131
+ const entryContext = {
132
+ transform,
133
+ program,
134
+ type: declaration.getType(),
135
+ declaration
136
+ };
137
+ const comment = (_declaration$getSymbo = declaration.getSymbol()) === null || _declaration$getSymbo === void 0 ? void 0 : _declaration$getSymbo.compilerSymbol.getDocumentationComment(program.getTypeChecker().compilerObject);
138
+ return {
139
+ name,
140
+ description: comment ? ts.displayPartsToString(comment) : "",
141
+ entries: declaration.getType().getProperties().map((prop) => getDocEntry(prop, entryContext)).filter((entry) => entry && (allowInternal || !("internal" in entry.tags)))
142
+ };
217
143
  }
218
144
  function getDocEntry(prop, context) {
219
- var _a, _b;
220
- const { transform, program } = context;
221
- if (context.type.isClass() && prop.getName().startsWith("#")) {
222
- return;
223
- }
224
- const subType = prop.getTypeAtLocation(context.declaration);
225
- const isOptional = prop.isOptional();
226
- const tags = prop.getJsDocTags().map(
227
- (tag) => ({
228
- name: tag.getName(),
229
- text: ts2.displayPartsToString(tag.getText())
230
- })
231
- );
232
- let type = subType.getText(
233
- context.declaration,
234
- ts2.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope | ts2.TypeFormatFlags.NoTruncation
235
- );
236
- let simplifiedType = getSimpleForm(
237
- subType,
238
- program.getTypeChecker(),
239
- isOptional,
240
- context.declaration
241
- );
242
- for (const tag of tags) {
243
- if (tag.name === "fumadocsType") {
244
- const match = (_a = new RegExp("`(?<name>.+)`$").exec(tag.text)) == null ? void 0 : _a[1];
245
- if (match) type = match;
246
- continue;
247
- }
248
- if (tag.name === "remarks") {
249
- const match = (_b = new RegExp("^`(?<name>.+)`").exec(tag.text)) == null ? void 0 : _b[1];
250
- if (match) simplifiedType = match;
251
- }
252
- }
253
- const entry = {
254
- name: prop.getName(),
255
- description: ts2.displayPartsToString(
256
- prop.compilerSymbol.getDocumentationComment(
257
- program.getTypeChecker().compilerObject
258
- )
259
- ),
260
- tags,
261
- type,
262
- simplifiedType,
263
- required: !isOptional,
264
- deprecated: tags.some((tag) => tag.name === "deprecated")
265
- };
266
- transform == null ? void 0 : transform.call(context, entry, subType, prop);
267
- return entry;
145
+ const { transform, program } = context;
146
+ if (context.type.isClass() && prop.getName().startsWith("#")) return;
147
+ const subType = prop.getTypeAtLocation(context.declaration);
148
+ const isOptional = prop.isOptional();
149
+ const tags = prop.getJsDocTags().map((tag) => ({
150
+ name: tag.getName(),
151
+ text: ts.displayPartsToString(tag.getText())
152
+ }));
153
+ let type = subType.getText(context.declaration, ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope | ts.TypeFormatFlags.NoTruncation);
154
+ let simplifiedType = getSimpleForm(subType, program.getTypeChecker(), isOptional, context.declaration);
155
+ for (const tag of tags) {
156
+ if (tag.name === "fumadocsType") {
157
+ var _exec;
158
+ const match = (_exec = new RegExp("`(?<name>.+)`$", "").exec(tag.text)) === null || _exec === void 0 ? void 0 : _exec[1];
159
+ if (match) type = match;
160
+ continue;
161
+ }
162
+ if (tag.name === "remarks") {
163
+ var _exec2;
164
+ const match = (_exec2 = new RegExp("^`(?<name>.+)`", "").exec(tag.text)) === null || _exec2 === void 0 ? void 0 : _exec2[1];
165
+ if (match) simplifiedType = match;
166
+ }
167
+ }
168
+ const entry = {
169
+ name: prop.getName(),
170
+ description: ts.displayPartsToString(prop.compilerSymbol.getDocumentationComment(program.getTypeChecker().compilerObject)),
171
+ tags,
172
+ type,
173
+ simplifiedType,
174
+ required: !isOptional,
175
+ deprecated: tags.some((tag) => tag.name === "deprecated")
176
+ };
177
+ transform === null || transform === void 0 || transform.call(context, entry, subType, prop);
178
+ return entry;
268
179
  }
269
180
 
270
- // src/lib/mdx.ts
271
- import * as path3 from "path";
272
- var regex = new RegExp("^---type-table---\\r?\\n(?<file>.+?)(?:#(?<name>.+))?\\r?\\n---end---$", "gm");
273
- var defaultTemplates = {
274
- block: (doc, c) => `### ${doc.name}
275
-
276
- ${doc.description}
277
-
278
- <div className='*:border-b [&>*:last-child]:border-b-0'>${c}</div>`,
279
- property: (c) => `<div className='text-sm text-fd-muted-foreground py-4'>
280
-
281
- <div className="flex flex-row items-center gap-4">
282
- <code className="text-sm">${c.name}</code>
283
- <code className="text-fd-muted-foreground">{${JSON.stringify(c.simplifiedType)}}</code>
284
- </div>
285
-
286
- Full Type: <code className="text-fd-muted-foreground">{${JSON.stringify(c.type)}}</code>
287
-
288
- ${c.description || "No Description"}
289
-
290
- ${c.tags.map((tag) => `- ${tag.name}:
291
- ${replaceJsDocLinks(tag.text)}`).join("\n")}
292
-
293
- </div>`
294
- };
295
- function generateMDX(generator, source, _a = {}) {
296
- var _b = _a, { basePath = "./", templates: overrides } = _b, rest = __objRest(_b, ["basePath", "templates"]);
297
- const templates = __spreadValues(__spreadValues({}, defaultTemplates), overrides);
298
- return source.replace(regex, (...args) => {
299
- const groups = args[args.length - 1];
300
- const file = path3.resolve(basePath, groups.file);
301
- const docs = generator.generateDocumentation(
302
- { path: file },
303
- groups.name,
304
- rest
305
- );
306
- return docs.map(
307
- (doc) => templates.block(doc, doc.entries.map(templates.property).join("\n"))
308
- ).join("\n\n");
309
- });
181
+ //#endregion
182
+ //#region src/lib/remark-auto-type-table.ts
183
+ function objectBuilder() {
184
+ const out = {
185
+ type: "ObjectExpression",
186
+ properties: []
187
+ };
188
+ return {
189
+ addExpressionNode(key, expression) {
190
+ out.properties.push({
191
+ type: "Property",
192
+ method: false,
193
+ shorthand: false,
194
+ computed: false,
195
+ key: {
196
+ type: "Identifier",
197
+ name: key
198
+ },
199
+ kind: "init",
200
+ value: expression
201
+ });
202
+ },
203
+ addJsxProperty(key, hast) {
204
+ const estree = toEstree(hast, { elementAttributeNameCase: "react" }).body[0];
205
+ this.addExpressionNode(key, estree.expression);
206
+ },
207
+ build() {
208
+ return out;
209
+ }
210
+ };
310
211
  }
311
- function replaceJsDocLinks(md) {
312
- return md.replace(new RegExp("{@link (?<link>[^}]*)}", "g"), "$1");
212
+ function buildTypeProp(_x4, _x5) {
213
+ return _buildTypeProp.apply(this, arguments);
313
214
  }
314
-
315
- // src/lib/file.ts
316
- import * as path4 from "path";
317
- import { mkdir, writeFile, readFile as readFile2 } from "fs/promises";
318
- import { glob } from "tinyglobby";
319
- function generateFiles(generator, options) {
320
- return __async(this, null, function* () {
321
- const files = yield glob(options.input, options.globOptions);
322
- const produce = files.map((file) => __async(null, null, function* () {
323
- const absolutePath = path4.resolve(file);
324
- const outputPath = typeof options.output === "function" ? options.output(file) : path4.resolve(
325
- options.output,
326
- `${path4.basename(file, path4.extname(file))}.mdx`
327
- );
328
- const content = (yield readFile2(absolutePath)).toString();
329
- let result = generateMDX(generator, content, __spreadValues({
330
- basePath: path4.dirname(absolutePath)
331
- }, options.options));
332
- if (options.transformOutput) {
333
- result = options.transformOutput(outputPath, result);
334
- }
335
- yield write(outputPath, result);
336
- console.log(`Generated: ${outputPath}`);
337
- }));
338
- yield Promise.all(produce);
339
- });
215
+ function _buildTypeProp() {
216
+ _buildTypeProp = _asyncToGenerator(function* (entries, { renderMarkdown = renderMarkdownToHast, renderType = renderTypeToHast }) {
217
+ function onItem(_x) {
218
+ return _onItem.apply(this, arguments);
219
+ }
220
+ function _onItem() {
221
+ _onItem = _asyncToGenerator(function* (entry) {
222
+ const node = objectBuilder();
223
+ const tags = parseTags(entry.tags);
224
+ node.addJsxProperty("type", yield renderType(entry.simplifiedType));
225
+ node.addJsxProperty("typeDescription", yield renderType(entry.type));
226
+ node.addExpressionNode("required", valueToEstree(entry.required));
227
+ if (tags.default) node.addJsxProperty("default", yield renderType(tags.default));
228
+ if (tags.returns) node.addJsxProperty("returns", yield renderMarkdown(tags.returns));
229
+ if (tags.params) node.addExpressionNode("parameters", {
230
+ type: "ArrayExpression",
231
+ elements: yield Promise.all(tags.params.map(onParam))
232
+ });
233
+ if (entry.description) node.addJsxProperty("description", yield renderMarkdown(entry.description));
234
+ return node.build();
235
+ });
236
+ return _onItem.apply(this, arguments);
237
+ }
238
+ function onParam(_x2) {
239
+ return _onParam.apply(this, arguments);
240
+ }
241
+ function _onParam() {
242
+ _onParam = _asyncToGenerator(function* (param) {
243
+ const node = objectBuilder();
244
+ node.addExpressionNode("name", valueToEstree(param.name));
245
+ if (param.description) node.addJsxProperty("description", yield renderMarkdown(param.description));
246
+ return node.build();
247
+ });
248
+ return _onParam.apply(this, arguments);
249
+ }
250
+ const prop = objectBuilder();
251
+ const output = yield Promise.all(entries.map(function() {
252
+ var _ref = _asyncToGenerator(function* (entry) {
253
+ return {
254
+ name: entry.name,
255
+ node: yield onItem(entry)
256
+ };
257
+ });
258
+ return function(_x3) {
259
+ return _ref.apply(this, arguments);
260
+ };
261
+ }()));
262
+ for (const node of output) prop.addExpressionNode(node.name, node.node);
263
+ return prop.build();
264
+ });
265
+ return _buildTypeProp.apply(this, arguments);
340
266
  }
341
- function write(file, content) {
342
- return __async(this, null, function* () {
343
- yield mkdir(path4.dirname(file), { recursive: true });
344
- yield writeFile(file, content);
345
- });
267
+ /**
268
+ * Compile `auto-type-table` into Fumadocs UI compatible TypeTable
269
+ *
270
+ * MDX is required to use this plugin.
271
+ */
272
+ function remarkAutoTypeTable(config = {}) {
273
+ const { name = "auto-type-table", outputName = "TypeTable", options: generateOptions = {}, remarkStringify = true, generator = createGenerator() } = config;
274
+ return function() {
275
+ var _ref3 = _asyncToGenerator(function* (tree, file) {
276
+ const queue = [];
277
+ function run(_x7, _x8) {
278
+ return _run.apply(this, arguments);
279
+ }
280
+ function _run() {
281
+ _run = _asyncToGenerator(function* (node, props) {
282
+ let basePath = props.cwd ? file.cwd : generateOptions.basePath;
283
+ if (file.dirname) {
284
+ var _basePath;
285
+ (_basePath = basePath) !== null && _basePath !== void 0 || (basePath = file.dirname);
286
+ }
287
+ const rendered = (yield generator.generateTypeTable(props, _objectSpread2(_objectSpread2({}, generateOptions), {}, { basePath }))).map(function() {
288
+ var _ref2 = _asyncToGenerator(function* (doc) {
289
+ return {
290
+ type: "mdxJsxFlowElement",
291
+ name: outputName,
292
+ attributes: [{
293
+ type: "mdxJsxAttribute",
294
+ name: "type",
295
+ value: {
296
+ type: "mdxJsxAttributeValueExpression",
297
+ value: remarkStringify ? JSON.stringify(doc, null, 2) : "",
298
+ data: { estree: {
299
+ type: "Program",
300
+ sourceType: "module",
301
+ body: [{
302
+ type: "ExpressionStatement",
303
+ expression: yield buildTypeProp(doc.entries, config)
304
+ }]
305
+ } }
306
+ }
307
+ }],
308
+ children: []
309
+ };
310
+ });
311
+ return function(_x6) {
312
+ return _ref2.apply(this, arguments);
313
+ };
314
+ }());
315
+ Object.assign(node, {
316
+ type: "root",
317
+ attributes: [],
318
+ children: yield Promise.all(rendered)
319
+ });
320
+ });
321
+ return _run.apply(this, arguments);
322
+ }
323
+ visit(tree, "mdxJsxFlowElement", (node) => {
324
+ if (node.name !== name) return;
325
+ const props = {};
326
+ const onError = (message, cause) => {
327
+ const location = node.position ? `${file.path}:${node.position.start.line}:${node.position.start.column}` : file.path;
328
+ throw new Error(`${location} from <auto-type-table>: ${message}`, { cause });
329
+ };
330
+ for (const attr of node.attributes) if (attr.type !== "mdxJsxAttribute") onError("only named attributes are allowed.");
331
+ else if (typeof attr.value === "string") props[attr.name] = attr.value;
332
+ else if (attr.value === null) props[attr.name] = true;
333
+ else onError("only string & boolean attributes are allowed.");
334
+ queue.push(run(node, props).catch((err) => {
335
+ onError("failed to generate type table", err);
336
+ }));
337
+ return "skip";
338
+ });
339
+ yield Promise.all(queue);
340
+ });
341
+ return function(_x9, _x10) {
342
+ return _ref3.apply(this, arguments);
343
+ };
344
+ }();
346
345
  }
347
346
 
348
- // src/lib/remark-auto-type-table.ts
349
- import { valueToEstree } from "estree-util-value-to-estree";
350
- import { visit } from "unist-util-visit";
351
- import { toEstree } from "hast-util-to-estree";
352
- import { dirname as dirname2 } from "path";
353
- function objectBuilder() {
354
- const out = {
355
- type: "ObjectExpression",
356
- properties: []
357
- };
358
- return {
359
- addExpressionNode(key, expression) {
360
- out.properties.push({
361
- type: "Property",
362
- method: false,
363
- shorthand: false,
364
- computed: false,
365
- key: {
366
- type: "Identifier",
367
- name: key
368
- },
369
- kind: "init",
370
- value: expression
371
- });
372
- },
373
- addJsxProperty(key, hast) {
374
- const estree = toEstree(hast, {
375
- elementAttributeNameCase: "react"
376
- }).body[0];
377
- this.addExpressionNode(key, estree.expression);
378
- },
379
- build() {
380
- return out;
381
- }
382
- };
383
- }
384
- function buildTypeProp(_0, _1) {
385
- return __async(this, arguments, function* (entries, {
386
- renderMarkdown = renderMarkdownToHast,
387
- renderType = renderTypeToHast
388
- }) {
389
- function onItem(entry) {
390
- return __async(this, null, function* () {
391
- const node = objectBuilder();
392
- node.addJsxProperty("type", yield renderType(entry.simplifiedType));
393
- node.addJsxProperty("typeDescription", yield renderType(entry.type));
394
- node.addExpressionNode("required", valueToEstree(entry.required));
395
- const tags = parseTags(entry.tags);
396
- if (tags.default)
397
- node.addJsxProperty("default", yield renderType(tags.default));
398
- if (tags.returns)
399
- node.addJsxProperty("returns", yield renderMarkdown(tags.returns));
400
- if (tags.params) {
401
- node.addExpressionNode("parameters", {
402
- type: "ArrayExpression",
403
- elements: yield Promise.all(tags.params.map(onParam))
404
- });
405
- }
406
- if (entry.description) {
407
- node.addJsxProperty(
408
- "description",
409
- yield renderMarkdown(entry.description)
410
- );
411
- }
412
- return node.build();
413
- });
414
- }
415
- function onParam(param) {
416
- return __async(this, null, function* () {
417
- const node = objectBuilder();
418
- node.addExpressionNode("name", valueToEstree(param.name));
419
- if (param.description)
420
- node.addJsxProperty(
421
- "description",
422
- yield renderMarkdown(param.description)
423
- );
424
- return node.build();
425
- });
426
- }
427
- const prop = objectBuilder();
428
- const output = yield Promise.all(
429
- entries.map((entry) => __async(null, null, function* () {
430
- return {
431
- name: entry.name,
432
- node: yield onItem(entry)
433
- };
434
- }))
435
- );
436
- for (const node of output) {
437
- prop.addExpressionNode(node.name, node.node);
438
- }
439
- return prop.build();
440
- });
347
+ //#endregion
348
+ //#region src/cache/fs-cache.ts
349
+ function createFileSystemGeneratorCache(dir) {
350
+ dir = path.resolve(dir);
351
+ const initDirPromise = fs.mkdir(dir, { recursive: true }).catch(() => {});
352
+ return {
353
+ write(input, data) {
354
+ return _asyncToGenerator(function* () {
355
+ const hash = createHash("SHA256").update(input).digest("hex").slice(0, 12);
356
+ yield initDirPromise;
357
+ yield fs.writeFile(path.join(dir, `${hash}.json`), JSON.stringify(data));
358
+ })();
359
+ },
360
+ read(input) {
361
+ return _asyncToGenerator(function* () {
362
+ const hash = createHash("SHA256").update(input).digest("hex").slice(0, 12);
363
+ try {
364
+ return JSON.parse((yield fs.readFile(path.join(dir, `${hash}.json`))).toString());
365
+ } catch (_unused) {
366
+ return;
367
+ }
368
+ })();
369
+ }
370
+ };
441
371
  }
442
- function remarkAutoTypeTable(config = {}) {
443
- const {
444
- name = "auto-type-table",
445
- outputName = "TypeTable",
446
- options: generateOptions = {},
447
- remarkStringify = true,
448
- generator = createGenerator()
449
- } = config;
450
- return (tree, file) => __async(null, null, function* () {
451
- const queue = [];
452
- const defaultBasePath = file.path ? dirname2(file.path) : void 0;
453
- visit(tree, "mdxJsxFlowElement", (node) => {
454
- if (node.name !== name) return;
455
- const props = {};
456
- for (const attr of node.attributes) {
457
- if (attr.type !== "mdxJsxAttribute" || typeof attr.value !== "string")
458
- throw new Error(
459
- "`auto-type-table` does not support non-string attributes"
460
- );
461
- props[attr.name] = attr.value;
462
- }
463
- function run() {
464
- return __async(this, null, function* () {
465
- var _a;
466
- const output = yield generator.generateTypeTable(
467
- props,
468
- __spreadProps(__spreadValues({}, generateOptions), {
469
- basePath: (_a = generateOptions.basePath) != null ? _a : defaultBasePath
470
- })
471
- );
472
- const rendered = output.map((doc) => __async(null, null, function* () {
473
- return {
474
- type: "mdxJsxFlowElement",
475
- name: outputName,
476
- attributes: [
477
- {
478
- type: "mdxJsxAttribute",
479
- name: "type",
480
- value: {
481
- type: "mdxJsxAttributeValueExpression",
482
- value: remarkStringify ? JSON.stringify(doc, null, 2) : "",
483
- data: {
484
- estree: {
485
- type: "Program",
486
- sourceType: "module",
487
- body: [
488
- {
489
- type: "ExpressionStatement",
490
- expression: yield buildTypeProp(doc.entries, config)
491
- }
492
- ]
493
- }
494
- }
495
- }
496
- }
497
- ],
498
- children: []
499
- };
500
- }));
501
- Object.assign(node, {
502
- type: "root",
503
- attributes: [],
504
- children: yield Promise.all(rendered)
505
- });
506
- });
507
- }
508
- queue.push(run());
509
- return "skip";
510
- });
511
- yield Promise.all(queue);
512
- });
513
- }
514
- export {
515
- createGenerator,
516
- createProject,
517
- generateDocumentation,
518
- generateFiles,
519
- generateMDX,
520
- remarkAutoTypeTable,
521
- renderMarkdownToHast
522
- };
372
+
373
+ //#endregion
374
+ export { createFileSystemGeneratorCache, createGenerator, createProject, remarkAutoTypeTable, renderMarkdownToHast };
375
+ //# sourceMappingURL=index.js.map