fumadocs-typescript 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Fuma
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # Fumadocs Typescript
2
+
3
+ Typescript Integration for Fumadocs.
@@ -0,0 +1,46 @@
1
+ import ts from 'typescript';
2
+
3
+ interface TypescriptConfig {
4
+ files?: string[];
5
+ tsconfigPath?: string;
6
+ /** A root directory to resolve relative path entries in the config file to. e.g. outDir */
7
+ basePath?: string;
8
+ }
9
+
10
+ interface GeneratedDoc {
11
+ name: string;
12
+ description: string;
13
+ entries: DocEntry[];
14
+ }
15
+ interface DocEntry {
16
+ name: string;
17
+ description: string;
18
+ type: string;
19
+ tags: Record<string, string>;
20
+ }
21
+ interface EntryContext {
22
+ program: ts.Program;
23
+ checker: ts.TypeChecker;
24
+ options: GenerateOptions;
25
+ type: ts.Type;
26
+ symbol: ts.Symbol;
27
+ }
28
+ interface GenerateOptions {
29
+ /**
30
+ * Modify output property entry
31
+ */
32
+ transform?: (this: EntryContext, entry: DocEntry, propertyType: ts.Type, propertySymbol: ts.Symbol) => void;
33
+ }
34
+ interface GenerateDocumentationOptions extends GenerateOptions {
35
+ /**
36
+ * Typescript configurations
37
+ */
38
+ config?: TypescriptConfig;
39
+ }
40
+ /**
41
+ * Generate documentation for properties in an exported type/interface
42
+ */
43
+ declare function generateDocumentation(file: string, name: string, options?: GenerateDocumentationOptions): GeneratedDoc | undefined;
44
+ declare function generate(program: ts.Program, symbol: ts.Symbol, options: GenerateOptions): GeneratedDoc;
45
+
46
+ export { type DocEntry as D, type GenerateOptions as G, type TypescriptConfig as T, type GeneratedDoc as a, type GenerateDocumentationOptions as b, generate as c, generateDocumentation as g };
@@ -0,0 +1,156 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
31
+ };
32
+ var __async = (__this, __arguments, generator) => {
33
+ return new Promise((resolve, reject) => {
34
+ var fulfilled = (value) => {
35
+ try {
36
+ step(generator.next(value));
37
+ } catch (e) {
38
+ reject(e);
39
+ }
40
+ };
41
+ var rejected = (value) => {
42
+ try {
43
+ step(generator.throw(value));
44
+ } catch (e) {
45
+ reject(e);
46
+ }
47
+ };
48
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
49
+ step((generator = generator.apply(__this, __arguments)).next());
50
+ });
51
+ };
52
+
53
+ // src/generate/base.ts
54
+ import ts2 from "typescript";
55
+
56
+ // src/program.ts
57
+ import ts from "typescript";
58
+ var cache = /* @__PURE__ */ new Map();
59
+ function getFileSymbol(file, program) {
60
+ const checker = program.getTypeChecker();
61
+ const sourceFile = program.getSourceFile(file);
62
+ if (!sourceFile)
63
+ return;
64
+ return checker.getSymbolAtLocation(sourceFile);
65
+ }
66
+ function getProgram(options = {}) {
67
+ var _a, _b, _c;
68
+ const key = JSON.stringify(options);
69
+ const cached = cache.get(key);
70
+ if (cached)
71
+ return cached;
72
+ const configFile = ts.readJsonConfigFile(
73
+ (_a = options.tsconfigPath) != null ? _a : "./tsconfig.json",
74
+ (path) => ts.sys.readFile(path)
75
+ );
76
+ const parsed = ts.parseJsonSourceFileConfigFileContent(
77
+ configFile,
78
+ ts.sys,
79
+ (_b = options.basePath) != null ? _b : "./"
80
+ );
81
+ const program = ts.createProgram({
82
+ rootNames: (_c = options.files) != null ? _c : parsed.fileNames,
83
+ options: __spreadProps(__spreadValues({}, parsed.options), {
84
+ incremental: false
85
+ })
86
+ });
87
+ cache.set(key, program);
88
+ return program;
89
+ }
90
+
91
+ // src/generate/base.ts
92
+ function generateDocumentation(file, name, options = {}) {
93
+ const program = getProgram(options.config);
94
+ const fileSymbol = getFileSymbol(file, program);
95
+ if (!fileSymbol)
96
+ return;
97
+ const symbol = program.getTypeChecker().getExportsOfModule(fileSymbol).find((e) => e.getEscapedName().toString() === name);
98
+ if (!symbol)
99
+ return;
100
+ return generate(program, symbol, options);
101
+ }
102
+ function generate(program, symbol, options) {
103
+ const checker = program.getTypeChecker();
104
+ const type = checker.getDeclaredTypeOfSymbol(symbol);
105
+ const entryContext = {
106
+ checker,
107
+ options,
108
+ program,
109
+ type,
110
+ symbol
111
+ };
112
+ return {
113
+ name: symbol.getEscapedName().toString(),
114
+ description: ts2.displayPartsToString(
115
+ symbol.getDocumentationComment(checker)
116
+ ),
117
+ entries: type.getProperties().map((prop) => getDocEntry(prop, entryContext))
118
+ };
119
+ }
120
+ function getDocEntry(prop, context) {
121
+ var _a, _b, _c;
122
+ const { checker, options } = context;
123
+ const subType = checker.getTypeOfSymbol(prop);
124
+ const tags = Object.fromEntries(
125
+ prop.getJsDocTags().map((tag) => [tag.name, ts2.displayPartsToString(tag.text)])
126
+ );
127
+ let typeName = checker.typeToString(
128
+ subType.getNonNullableType(),
129
+ void 0,
130
+ ts2.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope
131
+ );
132
+ if (subType.aliasSymbol && !subType.aliasTypeArguments) {
133
+ typeName = subType.aliasSymbol.escapedName.toString();
134
+ }
135
+ if (tags.remarks) {
136
+ typeName = (_b = (_a = new RegExp("^`(?<name>.+)`").exec(tags.remarks)) == null ? void 0 : _a[1]) != null ? _b : typeName;
137
+ }
138
+ const entry = {
139
+ name: prop.getName(),
140
+ description: ts2.displayPartsToString(prop.getDocumentationComment(checker)),
141
+ tags,
142
+ type: typeName
143
+ };
144
+ (_c = options.transform) == null ? void 0 : _c.call(context, entry, subType, prop);
145
+ return entry;
146
+ }
147
+
148
+ export {
149
+ __spreadValues,
150
+ __objRest,
151
+ __async,
152
+ getFileSymbol,
153
+ getProgram,
154
+ generateDocumentation,
155
+ generate
156
+ };
@@ -0,0 +1,35 @@
1
+ import { G as GenerateOptions, T as TypescriptConfig, a as GeneratedDoc, D as DocEntry } from './base-tTG4_ClF.js';
2
+ export { b as GenerateDocumentationOptions, c as generate, g as generateDocumentation } from './base-tTG4_ClF.js';
3
+ import fg from 'fast-glob';
4
+ import 'typescript';
5
+
6
+ interface Templates {
7
+ block: (doc: GeneratedDoc, children: string) => string;
8
+ property: (entry: DocEntry) => string;
9
+ }
10
+ interface GenerateMDXOptions extends GenerateOptions {
11
+ /**
12
+ * a root directory to resolve relative file paths
13
+ */
14
+ basePath?: string;
15
+ templates?: Partial<Templates>;
16
+ config?: TypescriptConfig;
17
+ }
18
+ declare function generateMDX(source: string, { basePath, templates: overrides, config: options, ...rest }?: GenerateMDXOptions): string;
19
+
20
+ interface GenerateFilesOptions {
21
+ input: string | string[];
22
+ /**
23
+ * Output directory, or a function that returns the output path
24
+ */
25
+ output: string | ((inputPath: string) => string);
26
+ globOptions?: fg.Options;
27
+ options?: GenerateMDXOptions;
28
+ /**
29
+ * @returns New content
30
+ */
31
+ transformOutput?: (path: string, content: string) => string;
32
+ }
33
+ declare function generateFiles(options: GenerateFilesOptions): Promise<void>;
34
+
35
+ export { DocEntry, type GenerateFilesOptions, type GenerateMDXOptions, GenerateOptions, GeneratedDoc, generateFiles, generateMDX };
package/dist/index.js ADDED
@@ -0,0 +1,107 @@
1
+ import {
2
+ __async,
3
+ __objRest,
4
+ __spreadValues,
5
+ generate,
6
+ generateDocumentation,
7
+ getFileSymbol,
8
+ getProgram
9
+ } from "./chunk-HQHQFSUJ.js";
10
+
11
+ // src/generate/mdx.ts
12
+ import * as path from "path";
13
+ var regex = new RegExp("^---type-table---\\r?\\n(?<file>.+?)(?:#(?<name>.+))?\\r?\\n---end---$", "gm");
14
+ var defaultTemplates = {
15
+ block: (doc, c) => `### ${doc.name}
16
+
17
+ ${doc.description}
18
+
19
+ <div className='*:border-b [&>*:last-child]:border-b-0'>${c}</div>`,
20
+ property: (c) => `<div className='text-sm text-muted-foreground py-4'>
21
+
22
+ <div className="flex flex-row items-center gap-4">
23
+ <code className="text-sm">${c.name}</code>
24
+ <code className="text-muted-foreground">{${JSON.stringify(c.type)}}</code>
25
+ </div>
26
+
27
+ ${c.description || "No Description"}
28
+
29
+ ${Object.entries(c.tags).map(([tag, value]) => `- ${tag}:
30
+ ${replaceJsDocLinks(value)}`).join("\n")}
31
+
32
+ </div>`
33
+ };
34
+ function generateMDX(source, _a = {}) {
35
+ var _b = _a, {
36
+ basePath = "./",
37
+ templates: overrides,
38
+ config: options
39
+ } = _b, rest = __objRest(_b, [
40
+ "basePath",
41
+ "templates",
42
+ "config"
43
+ ]);
44
+ const templates = __spreadValues(__spreadValues({}, defaultTemplates), overrides);
45
+ const program = getProgram(options);
46
+ return source.replace(regex, (...args) => {
47
+ const groups = args[args.length - 1];
48
+ const file = path.resolve(basePath, groups.file);
49
+ const fileSymbol = getFileSymbol(file, program);
50
+ if (!fileSymbol)
51
+ throw new Error(`${file} doesn't exist`);
52
+ let docs;
53
+ if (!groups.name) {
54
+ docs = program.getTypeChecker().getExportsOfModule(fileSymbol).map((symbol) => generate(program, symbol, rest));
55
+ } else {
56
+ const symbol = program.getTypeChecker().getExportsOfModule(fileSymbol).find((s) => s.getEscapedName().toString() === groups.name);
57
+ if (!symbol)
58
+ throw new Error(`Type ${groups.name} doesn't exist`);
59
+ docs = [generate(program, symbol, rest)];
60
+ }
61
+ return docs.map(
62
+ (doc) => templates.block(doc, doc.entries.map(templates.property).join("\n"))
63
+ ).join("\n\n");
64
+ });
65
+ }
66
+ function replaceJsDocLinks(md) {
67
+ return md.replace(new RegExp("{@link (?<link>[^}]*)}", "g"), "$1");
68
+ }
69
+
70
+ // src/generate/file.ts
71
+ import * as path2 from "path";
72
+ import { mkdir, writeFile, readFile } from "fs/promises";
73
+ import fg from "fast-glob";
74
+ function generateFiles(options) {
75
+ return __async(this, null, function* () {
76
+ const files = yield fg(options.input, options.globOptions);
77
+ const produce = files.map((file) => __async(this, null, function* () {
78
+ const absolutePath = path2.resolve(file);
79
+ const outputPath = typeof options.output === "function" ? options.output(file) : path2.resolve(
80
+ options.output,
81
+ `${path2.basename(file, path2.extname(file))}.mdx`
82
+ );
83
+ const content = (yield readFile(absolutePath)).toString();
84
+ let result = generateMDX(content, __spreadValues({
85
+ basePath: path2.dirname(absolutePath)
86
+ }, options.options));
87
+ if (options.transformOutput) {
88
+ result = options.transformOutput(outputPath, result);
89
+ }
90
+ yield write(outputPath, result);
91
+ console.log(`Generated: ${outputPath}`);
92
+ }));
93
+ yield Promise.all(produce);
94
+ });
95
+ }
96
+ function write(file, content) {
97
+ return __async(this, null, function* () {
98
+ yield mkdir(path2.dirname(file), { recursive: true });
99
+ yield writeFile(file, content);
100
+ });
101
+ }
102
+ export {
103
+ generate,
104
+ generateDocumentation,
105
+ generateFiles,
106
+ generateMDX
107
+ };
@@ -0,0 +1,15 @@
1
+ import { G as GenerateOptions } from '../base-tTG4_ClF.js';
2
+ import 'typescript';
3
+
4
+ /**
5
+ * **Server Component Only**
6
+ *
7
+ * Display properties in an exported interface via Type Table
8
+ */
9
+ declare function AutoTypeTable({ path, name, options, }: {
10
+ path: string;
11
+ name: string;
12
+ options?: GenerateOptions;
13
+ }): JSX.Element;
14
+
15
+ export { AutoTypeTable };
@@ -0,0 +1,58 @@
1
+ import {
2
+ generateDocumentation
3
+ } from "../chunk-HQHQFSUJ.js";
4
+
5
+ // src/ui/auto-type-table.tsx
6
+ import { TypeTable } from "fumadocs-ui/components/type-table";
7
+
8
+ // src/markdown.ts
9
+ import { fromMarkdown } from "mdast-util-from-markdown";
10
+ import { gfmFromMarkdown } from "mdast-util-gfm";
11
+ import { toHast } from "mdast-util-to-hast";
12
+ import {
13
+ toJsxRuntime
14
+ } from "hast-util-to-jsx-runtime";
15
+ import * as runtime from "react/jsx-runtime";
16
+ function renderMarkdown(md) {
17
+ const mdast = fromMarkdown(
18
+ md.replace(new RegExp("{@link (?<link>[^}]*)}", "g"), "$1"),
19
+ // replace jsdoc links
20
+ { mdastExtensions: [gfmFromMarkdown()] }
21
+ );
22
+ return toJsxRuntime(toHast(mdast), {
23
+ Fragment: runtime.Fragment,
24
+ jsx: runtime.jsx,
25
+ jsxs: runtime.jsxs
26
+ });
27
+ }
28
+
29
+ // src/ui/auto-type-table.tsx
30
+ import "server-only";
31
+ import { jsx as jsx2 } from "react/jsx-runtime";
32
+ function AutoTypeTable({
33
+ path,
34
+ name,
35
+ options
36
+ }) {
37
+ const output = generateDocumentation(path, name, options);
38
+ if (!output)
39
+ throw new Error(`${name} in ${path} doesn't exist`);
40
+ return /* @__PURE__ */ jsx2(
41
+ TypeTable,
42
+ {
43
+ type: Object.fromEntries(
44
+ output.entries.map((entry) => [
45
+ entry.name,
46
+ {
47
+ type: entry.type,
48
+ description: renderMarkdown(entry.description),
49
+ default: entry.tags.default || entry.tags.defaultValue
50
+ }
51
+ ])
52
+ )
53
+ }
54
+ );
55
+ }
56
+ export {
57
+ AutoTypeTable
58
+ };
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "fumadocs-typescript",
3
+ "version": "1.0.0",
4
+ "description": "Typescript Integration for Fumadocs",
5
+ "keywords": [
6
+ "NextJs",
7
+ "fumadocs",
8
+ "Docs"
9
+ ],
10
+ "homepage": "https://fumadocs.vercel.app",
11
+ "repository": "github:fuma-nama/fumadocs",
12
+ "license": "MIT",
13
+ "author": "Fuma Nama",
14
+ "type": "module",
15
+ "exports": {
16
+ ".": {
17
+ "import": "./dist/index.js",
18
+ "types": "./dist/index.d.ts"
19
+ },
20
+ "./ui": {
21
+ "import": "./dist/ui/index.js",
22
+ "types": "./dist/ui/index.d.ts"
23
+ }
24
+ },
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "typesVersions": {
28
+ "*": {
29
+ "ui": [
30
+ "./dist/ui/index.d.ts"
31
+ ]
32
+ }
33
+ },
34
+ "files": [
35
+ "dist/*"
36
+ ],
37
+ "dependencies": {
38
+ "fast-glob": "^3.3.1",
39
+ "hast-util-to-jsx-runtime": "^2.3.0",
40
+ "mdast-util-from-markdown": "^2.0.0",
41
+ "mdast-util-gfm": "^3.0.0",
42
+ "mdast-util-to-hast": "^13.1.0"
43
+ },
44
+ "devDependencies": {
45
+ "@types/hast": "^3.0.4",
46
+ "@types/mdast": "^4.0.3",
47
+ "@types/react": "18.2.0",
48
+ "@types/react-dom": "18.2.1",
49
+ "eslint-config-custom": "0.0.0",
50
+ "fumadocs-ui": "10.0.0",
51
+ "tsconfig": "0.0.0"
52
+ },
53
+ "peerDependencies": {
54
+ "typescript": "*"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public"
58
+ },
59
+ "scripts": {
60
+ "build": "tsup",
61
+ "clean": "rimraf dist",
62
+ "dev": "tsup --watch",
63
+ "lint": "eslint .",
64
+ "types:check": "tsc --noEmit"
65
+ }
66
+ }