-
-
Notifications
You must be signed in to change notification settings - Fork 32k
/
buildApiUtils.ts
244 lines (219 loc) · 7.16 KB
/
buildApiUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import fs from 'fs';
import path from 'path';
import * as ts from 'typescript';
import * as prettier from 'prettier';
import kebabCase from 'lodash/kebabCase';
import { getLineFeed } from '@mui/internal-docs-utils';
import { replaceComponentLinks } from './utils/replaceUrl';
import { TypeScriptProject } from './utils/createTypeScriptProject';
/**
* TODO: this should really be fixed in findPagesMarkdown().
* Plus replaceComponentLinks() shouldn't exist in the first place,
* the markdown folder location should match the URLs.
*/
export function fixPathname(pathname: string): string {
let fixedPathname;
if (pathname.startsWith('/material')) {
fixedPathname = replaceComponentLinks(`${pathname.replace(/^\/material/, '')}/`);
} else if (pathname.startsWith('/joy')) {
fixedPathname = replaceComponentLinks(`${pathname.replace(/^\/joy/, '')}/`).replace(
'material-ui',
'joy-ui',
);
} else if (pathname.startsWith('/base')) {
fixedPathname = `${pathname
.replace('/base/', '/base-ui/')
.replace('/components/', '/react-')}/`;
} else {
fixedPathname = `${pathname.replace('/components/', '/react-')}/`;
}
return fixedPathname;
}
const DEFAULT_PRETTIER_CONFIG_PATH = path.join(process.cwd(), 'prettier.config.js');
export async function writePrettifiedFile(
filename: string,
data: string,
prettierConfigPath: string = DEFAULT_PRETTIER_CONFIG_PATH,
options: object = {},
) {
const prettierConfig = await prettier.resolveConfig(filename, {
config: prettierConfigPath,
});
if (prettierConfig === null) {
throw new Error(
`Could not resolve config for '${filename}' using prettier config path '${prettierConfigPath}'.`,
);
}
const formatted = await prettier.format(data, { ...prettierConfig, filepath: filename });
fs.writeFileSync(filename, formatted, {
encoding: 'utf8',
...options,
});
}
let systemComponents: string[] | undefined;
// making the resolution lazy to avoid issues when importing something irrelevant from this file (i.e. `getSymbolDescription`)
// the eager resolution results in errors when consuming externally (i.e. `mui-x`)
export function getSystemComponents() {
if (!systemComponents) {
systemComponents = fs
.readdirSync(path.resolve('packages', 'mui-system', 'src'))
// Normalization, the Unstable_ prefix doesn't count.
.map((pathname) => pathname.replace('Unstable_', ''))
.filter((pathname) => pathname.match(/^[A-Z][a-zA-Z]+$/));
}
return systemComponents;
}
export function getMuiName(name: string) {
return `Mui${name.replace('Styled', '')}`;
}
export function extractPackageFile(filePath: string) {
filePath = filePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/');
const match = filePath.match(
/.*\/packages.*\/(?<packagePath>[^/]+)\/src\/(.*\/)?(?<name>[^/]+)\.(js|tsx|ts|d\.ts)/,
);
const result = {
packagePath: match ? match.groups?.packagePath! : null,
name: match ? match.groups?.name! : null,
};
return {
...result,
muiPackage: result.packagePath?.replace('x-', 'mui-'),
};
}
export function parseFile(filename: string) {
const src = fs.readFileSync(filename, 'utf8');
return {
src,
shouldSkip:
filename.indexOf('internal') !== -1 ||
!!src.match(/@ignore - internal component\./) ||
!!src.match(/@ignore - internal hook\./) ||
!!src.match(/@ignore - do not document\./),
spread: !src.match(/ = exactProp\(/),
EOL: getLineFeed(src),
inheritedComponent: src.match(/\/\/ @inheritedComponent (.*)/)?.[1],
};
}
export type ComponentInfo = {
/**
* Full path to the source file.
*/
filename: string;
/**
* Component name as imported in the docs, in the global MUI namespace.
*/
name: string;
/**
* Component name with `Mui` prefix, in the global HTML page namespace.
*/
muiName: string;
/**
* The name of the slots interface. By default we consider `${componentName}Slots`.
*/
slotInterfaceName?: string;
apiPathname: string;
readFile: () => {
src: string;
spread: boolean;
shouldSkip: boolean;
EOL: string;
inheritedComponent?: string;
};
getInheritance: (inheritedComponent?: string) => null | {
/**
* Component name
*/
name: string;
/**
* API pathname
*/
apiPathname: string;
};
getDemos: () => Array<{ demoPageTitle: string; demoPathname: string }>;
apiPagesDirectory: string;
/**
* The path to import specific layout config of the page if needed.
*/
layoutConfigPath?: string;
skipApiGeneration?: boolean;
/**
* If `true`, the component's name match one of the MUI System components.
*/
isSystemComponent?: boolean;
};
export type HookInfo = {
/**
* Full path to the source file.
*/
filename: string;
/**
* Hook name as imported in the docs, in the global MUI namespace.
*/
name: string;
apiPathname: string;
readFile: ComponentInfo['readFile'];
getDemos: ComponentInfo['getDemos'];
apiPagesDirectory: string;
skipApiGeneration?: boolean;
};
export function getApiPath(
demos: Array<{ demoPageTitle: string; demoPathname: string }>,
name: string,
) {
let apiPath = null;
if (demos && demos.length > 0) {
// remove the hash from the demoPathname, for e.g. "#hooks"
const cleanedDemosPathname = demos[0].demoPathname.split('#')[0];
apiPath = `${cleanedDemosPathname}${
name.startsWith('use') ? 'hooks-api' : 'components-api'
}/#${kebabCase(name)}`;
}
return apiPath;
}
export async function formatType(rawType: string) {
if (!rawType) {
return '';
}
const prefix = 'type FakeType = ';
const signatureWithTypeName = `${prefix}${rawType}`;
const prettifiedSignatureWithTypeName = await prettier.format(signatureWithTypeName, {
printWidth: 999,
singleQuote: true,
semi: false,
trailingComma: 'none',
parser: 'typescript',
});
return prettifiedSignatureWithTypeName.slice(prefix.length).replace(/\n$/, '');
}
export function getSymbolDescription(symbol: ts.Symbol, project: TypeScriptProject) {
return symbol
.getDocumentationComment(project.checker)
.flatMap((comment) => comment.text.split('\n'))
.filter((line) => !line.startsWith('TODO'))
.join('\n');
}
export function getSymbolJSDocTags(symbol: ts.Symbol) {
return Object.fromEntries(symbol.getJsDocTags().map((tag) => [tag.name, tag]));
}
export async function stringifySymbol(symbol: ts.Symbol, project: TypeScriptProject) {
let rawType: string;
const declaration = symbol.declarations?.[0];
if (declaration && ts.isPropertySignature(declaration)) {
rawType = declaration.type?.getText() ?? '';
} else {
rawType = project.checker.typeToString(
project.checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration!),
symbol.valueDeclaration,
ts.TypeFormatFlags.NoTruncation,
);
}
return formatType(rawType);
}
/**
* @param filepath - absolute path
* @example toGitHubPath('/home/user/material-ui/packages/Accordion') === '/packages/Accordion'
* @example toGitHubPath('C:\\Development\\material-ui\\packages\\Accordion') === '/packages/Accordion'
*/
export function toGitHubPath(filepath: string): string {
return `/${path.relative(process.cwd(), filepath).replace(/\\/g, '/')}`;
}