-
Notifications
You must be signed in to change notification settings - Fork 20
/
block-parsers.ts
233 lines (209 loc) · 7.54 KB
/
block-parsers.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
import { expect } from 'chai';
import { Token } from 'markdown-it';
import {
parseHeadingTags,
headingsAndContent,
findNextList,
convertListToTypedKeys,
findContentAfterList,
safelyJoinTokens,
HeadingContent,
extractReturnType,
findContentAfterHeadingClose,
StripReturnTypeBehavior,
consumeTypedKeysList,
slugifyHeading,
} from './markdown-helpers.js';
import {
MethodDocumentationBlock,
PropertyDocumentationBlock,
EventDocumentationBlock,
} from './ParsedDocumentation.js';
type GuessedParam = {
name: string;
optional: boolean;
};
export const guessParametersFromSignature = (signature: string) => {
expect(signature).to.match(
/^\(([a-zA-Z,\[\] ]+|(\.\.\.[^\.])|([a-zA-Z][0-9]))+\)$/g,
'signature should be a bracket wrapped group of parameters',
);
const justParams = signature.slice(1, signature.length - 1);
let optionalDepth = 0;
const params: GuessedParam[] = [];
let currentParam = '';
let currentOptional = false;
const maybePushCurrent = () => {
const trimmed = currentParam.trim();
if (trimmed) {
params.push({
name: trimmed,
optional: currentOptional,
});
currentParam = '';
}
};
for (let i = 0; i < justParams.length; i++) {
const char = justParams[i];
switch (char) {
case '[':
optionalDepth++;
break;
case ']':
maybePushCurrent();
optionalDepth--;
expect(optionalDepth).to.be.gte(
0,
`optional depth should never be negative, you have too many "]" characters in your signature: "${signature}"`,
);
break;
case ',':
maybePushCurrent();
break;
default:
if (!currentParam.trim()) currentOptional = optionalDepth > 0;
currentParam += char;
}
}
maybePushCurrent();
expect(optionalDepth).to.equal(
0,
`optional depth should return to 0, you have mismateched [ and ] characters in your signature: "${signature}"`,
);
return params;
};
export const _headingToMethodBlock = (
heading: HeadingContent | null,
): MethodDocumentationBlock | null => {
if (!heading) return null;
const methodStringWithGenericRegexp = /`(?:.+\.)?(.+?)(<.+>)(\(.*?\))`((?: _[^_]+?_)*)/g;
const methodStringRegexp = /`(?:.+\.)?(.+?)(\(.*?\))`((?: _[^_]+?_)*)/g;
const methodStringWithGenericMatch = methodStringWithGenericRegexp.exec(heading.heading);
const methodStringMatch = methodStringRegexp.exec(heading.heading)!;
methodStringRegexp.lastIndex = -1;
methodStringWithGenericRegexp.lastIndex = -1;
expect(heading.heading).to.match(
methodStringRegexp,
'each method should have a code blocked method name',
);
let methodString: string;
let methodGenerics = '';
let methodSignature: string;
let headingTags: string;
if (methodStringWithGenericMatch) {
[, methodString, methodGenerics, methodSignature, headingTags] = methodStringWithGenericMatch;
} else {
[, methodString, methodSignature, headingTags] = methodStringMatch;
}
let parameters: MethodDocumentationBlock['parameters'] = [];
if (methodSignature !== '()') {
const guessedParams = guessParametersFromSignature(methodSignature);
// If we have parameters we need to find the list of typed keys
const list = findNextList(heading.content)!;
expect(list).to.not.equal(
null,
`Method ${heading.heading} has at least one parameter but no parameter type list`,
);
parameters = consumeTypedKeysList(convertListToTypedKeys(list)).map((typedKey) => ({
name: typedKey.key,
description: typedKey.description,
required: typedKey.required,
...typedKey.type,
}));
expect(parameters).to.have.lengthOf(
guessedParams.length,
`should have the same number of documented parameters as we have in the method signature: "${methodSignature}"`,
);
for (let i = 0; i < parameters.length; i++) {
expect(parameters[i].required).to.equal(
!guessedParams[i].optional,
`the optionality of a parameter in the signature should match the documented optionality in the parameter description: "${methodString}${methodSignature}", while parsing parameter: "${parameters[i].name}"`,
);
}
}
const returnTokens =
methodSignature === '()'
? findContentAfterHeadingClose(heading.content)
: findContentAfterList(heading.content, true);
const { parsedDescription, parsedReturnType } = extractReturnType(returnTokens);
return {
name: methodString,
signature: methodSignature,
description: parsedDescription,
rawGenerics: methodGenerics || undefined,
parameters,
returns: parsedReturnType,
additionalTags: parseHeadingTags(headingTags),
urlFragment: `#${slugifyHeading(heading.heading)}`,
};
};
export const _headingToPropertyBlock = (heading: HeadingContent): PropertyDocumentationBlock => {
const propertyStringRegexp = /`(?:.+\.)?(.+?)`((?: _[^_]+?_)*)/g;
const propertyStringMatch = propertyStringRegexp.exec(heading.heading)!;
propertyStringRegexp.lastIndex = -1;
expect(heading.heading).to.match(
propertyStringRegexp,
'each property should have a code blocked property name',
);
const [, propertyString, headingTags] = propertyStringMatch;
const { parsedDescription, parsedReturnType } = extractReturnType(
findContentAfterHeadingClose(heading.content),
StripReturnTypeBehavior.DO_NOT_STRIP,
'An?',
);
expect(parsedReturnType).to.not.equal(
null,
`Property ${heading.heading} should have a declared type but it does not`,
);
return {
name: propertyString,
description: parsedDescription,
required: !/\(optional\)/i.test(parsedDescription),
additionalTags: parseHeadingTags(headingTags),
urlFragment: `#${slugifyHeading(heading.heading)}`,
...parsedReturnType!,
};
};
export const _headingToEventBlock = (heading: HeadingContent): EventDocumentationBlock => {
const eventNameRegexp = /^Event: '(.+)'((?: _[^_]+?_)*)/g;
const eventNameMatch = eventNameRegexp.exec(heading.heading)!;
eventNameRegexp.lastIndex = -1;
expect(heading.heading).to.match(eventNameRegexp, 'each event should have a quoted event name');
const [, eventName, headingTags] = eventNameMatch;
expect(eventName).to.not.equal('', 'should have a non-zero-length event name');
const description = safelyJoinTokens(findContentAfterList(heading.content, true));
let parameters: EventDocumentationBlock['parameters'] = [];
if (
safelyJoinTokens(findContentAfterHeadingClose(heading.content)).trim().startsWith('Returns:')
) {
const list = findNextList(heading.content);
if (list) {
parameters = consumeTypedKeysList(convertListToTypedKeys(list)).map((typedKey) => ({
name: typedKey.key,
description: typedKey.description,
...typedKey.type,
additionalTags: typedKey.additionalTags,
required: true,
}));
}
}
return {
name: eventName,
description,
parameters,
additionalTags: parseHeadingTags(headingTags),
urlFragment: `#${slugifyHeading(heading.heading)}`,
};
};
export const parseMethodBlocks = (tokens: Token[] | null): MethodDocumentationBlock[] => {
if (!tokens) return [];
return headingsAndContent(tokens).map((heading) => _headingToMethodBlock(heading)!);
};
export const parsePropertyBlocks = (tokens: Token[] | null): PropertyDocumentationBlock[] => {
if (!tokens) return [];
return headingsAndContent(tokens).map(_headingToPropertyBlock);
};
export const parseEventBlocks = (tokens: Token[] | null): EventDocumentationBlock[] => {
if (!tokens) return [];
return headingsAndContent(tokens).map(_headingToEventBlock);
};