-
-
Notifications
You must be signed in to change notification settings - Fork 679
Expand file tree
/
Copy pathvalidate-jsdoc-codeblocks.js
More file actions
307 lines (252 loc) · 9.33 KB
/
validate-jsdoc-codeblocks.js
File metadata and controls
307 lines (252 loc) · 9.33 KB
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import path from 'node:path';
import ts from 'typescript';
import {createFSBackedSystem, createVirtualTypeScriptEnvironment} from '@typescript/vfs';
const CODEBLOCK_REGEX = /(?<openingFence>```(?:ts|typescript)?\n)(?<code>[\s\S]*?)```/g;
const FILENAME = 'example-codeblock.ts';
const TWOSLASH_COMMENT = '//=>';
const compilerOptions = {
lib: ['lib.es2023.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
target: ts.ScriptTarget.ESNext,
module: ts.ModuleKind.Node20,
moduleResolution: ts.ModuleResolutionKind.Node16,
strict: true,
noImplicitReturns: true,
noImplicitOverride: true,
noUnusedLocals: false, // This is intentionally disabled
noUnusedParameters: true,
noFallthroughCasesInSwitch: true,
noUncheckedIndexedAccess: true,
noPropertyAccessFromIndexSignature: true,
noUncheckedSideEffectImports: true,
useDefineForClassFields: true,
exactOptionalPropertyTypes: true,
};
const virtualFsMap = new Map();
virtualFsMap.set(FILENAME, '// Can\'t be empty');
const rootDir = path.join(import.meta.dirname, '..');
const system = createFSBackedSystem(virtualFsMap, rootDir, ts);
const defaultEnv = createVirtualTypeScriptEnvironment(system, [FILENAME], ts, compilerOptions);
function parseCompilerOptions(code) {
const options = {};
const lines = code.split('\n');
for (const line of lines) {
if (!line.trim()) {
// Skip empty lines
continue;
}
const match = line.match(/^\s*\/\/ @(\w+): (.*)$/);
if (!match) {
// Stop parsing at the first non-matching line
return options;
}
const [, key, value] = match;
const trimmedValue = value.trim();
try {
options[key] = JSON.parse(trimmedValue);
} catch {
options[key] = trimmedValue;
}
}
return options;
}
function getJSDocNode(sourceCode, node) {
let previousToken = sourceCode.getTokenBefore(node, {includeComments: true});
// Skip over any line comments immediately before the node
while (previousToken && previousToken.type === 'Line') {
previousToken = sourceCode.getTokenBefore(previousToken, {includeComments: true});
}
if (previousToken && previousToken.type === 'Block' && previousToken.value.startsWith('*')) {
return previousToken;
}
return undefined;
}
export const validateJSDocCodeblocksRule = /** @type {const} */ ({
meta: {
type: 'suggestion',
docs: {
description: 'Ensures JSDoc example codeblocks don\'t have errors',
},
fixable: 'code',
messages: {
invalidCodeblock: '{{errorMessage}}',
typeMismatch: 'Expected twoslash comment to be: {{expectedComment}}, but found: {{actualComment}}',
},
schema: [],
},
defaultOptions: [],
create(context) {
const filename = context.filename.replaceAll('\\', '/');
// Skip internal files
if (filename.includes('/internal/')) {
return {};
}
try {
defaultEnv.updateFile(context.filename, context.sourceCode.getText());
} catch {
// Ignore
}
return {
TSTypeAliasDeclaration(node) {
const {parent} = node;
// Skip if type is not exported or starts with an underscore (private/internal)
if (parent.type !== 'ExportNamedDeclaration' || node.id.name.startsWith('_')) {
return;
}
const previousNodes = [];
const jsdocForExport = getJSDocNode(context.sourceCode, parent);
if (jsdocForExport) {
previousNodes.push(jsdocForExport);
}
// Handle JSDoc blocks for options
if (node.id.name.endsWith('Options') && node.typeAnnotation.type === 'TSTypeLiteral') {
for (const member of node.typeAnnotation.members) {
const jsdocForMember = getJSDocNode(context.sourceCode, member);
if (jsdocForMember) {
previousNodes.push(jsdocForMember);
}
}
}
for (const previousNode of previousNodes) {
const comment = previousNode.value;
for (const match of comment.matchAll(CODEBLOCK_REGEX)) {
const {code, openingFence} = match.groups ?? {};
// Skip empty code blocks
if (!code || !openingFence) {
continue;
}
const matchOffset = match.index + openingFence.length + 2; // Add `2` because `comment` doesn't include the starting `/*`
const codeStartIndex = previousNode.range[0] + matchOffset;
const overrides = parseCompilerOptions(code);
let env = defaultEnv;
if (Object.keys(overrides).length > 0) {
const {options, errors} = ts.convertCompilerOptionsFromJson(overrides, rootDir);
if (errors.length === 0) {
// Create a new environment with overridden options
env = createVirtualTypeScriptEnvironment(system, [FILENAME], ts, {...compilerOptions, ...options});
}
}
env.updateFile(FILENAME, code);
const syntacticDiagnostics = env.languageService.getSyntacticDiagnostics(FILENAME);
const semanticDiagnostics = env.languageService.getSemanticDiagnostics(FILENAME);
const diagnostics = syntacticDiagnostics.length > 0 ? syntacticDiagnostics : semanticDiagnostics; // Show semantic errors only if there are no syntactic errors
for (const diagnostic of diagnostics) {
// If diagnostic location is not available, report on the entire code block
const diagnosticStart = codeStartIndex + (diagnostic.start ?? 0);
const diagnosticEnd = diagnosticStart + (diagnostic.length ?? code.length);
context.report({
loc: {
start: context.sourceCode.getLocFromIndex(diagnosticStart),
end: context.sourceCode.getLocFromIndex(diagnosticEnd),
},
messageId: 'invalidCodeblock',
data: {
errorMessage: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
},
});
}
if (diagnostics.length === 0) {
validateTwoslashTypes(context, env, code, codeStartIndex);
}
}
}
},
};
},
});
function validateTwoslashTypes(context, env, code, codeStartIndex) {
const sourceFile = env.languageService.getProgram().getSourceFile(FILENAME);
const lines = code.split('\n');
for (const [index, line] of lines.entries()) {
const dedentedLine = line.trimStart();
if (!dedentedLine.startsWith(TWOSLASH_COMMENT)) {
continue;
}
const previousLineIndex = index - 1;
if (previousLineIndex < 0) {
continue;
}
let actualComment = dedentedLine;
let actualCommentEndLine = index;
for (let i = index + 1; i < lines.length; i++) {
const dedentedNextLine = lines[i].trimStart();
if (!dedentedNextLine.startsWith('//') || dedentedNextLine.startsWith(TWOSLASH_COMMENT)) {
break;
}
actualComment += '\n' + dedentedNextLine;
actualCommentEndLine = i;
}
const previousLine = lines[previousLineIndex];
const previousLineOffset = sourceFile.getPositionOfLineAndCharacter(previousLineIndex, 0);
for (let i = 0; i < previousLine.length; i++) {
const quickInfo = env.languageService.getQuickInfoAtPosition(FILENAME, previousLineOffset + i);
if (quickInfo?.displayParts) {
let depth = 0;
const separatorIndex = quickInfo.displayParts.findIndex(part => {
if (part.kind === 'punctuation') {
if (['(', '{', '<'].includes(part.text)) {
depth++;
} else if ([')', '}', '>'].includes(part.text)) {
depth--;
} else if (part.text === ':' && depth === 0) {
return true;
}
} else if (part.kind === 'operator' && part.text === '=' && depth === 0) {
return true;
}
return false;
});
let partsToUse = quickInfo.displayParts;
if (separatorIndex !== -1) {
partsToUse = quickInfo.displayParts.slice(separatorIndex + 1);
}
let expectedType = partsToUse.map((part, index) => {
const {kind, text} = part;
// Replace spaces used for indentation with tabs
const previousPart = partsToUse[index - 1];
if (kind === 'space' && (index === 0 || previousPart?.kind === 'lineBreak')) {
return text.replaceAll(' ', '\t');
}
// Replace double-quoted string literals with single-quoted ones
if (kind === 'stringLiteral' && text.startsWith('"') && text.endsWith('"')) {
return `'${text.slice(1, -1).replaceAll(String.raw`\"`, '"').replaceAll('\'', String.raw`\'`)}'`;
}
return text;
}).join('').trim();
if (expectedType.length < 80) {
expectedType = expectedType
.replaceAll(/\r?\n\s*/g, ' ') // Collapse into single line
.replaceAll(/{\s+/g, '{') // Remove spaces after `{`
.replaceAll(/\s+}/g, '}') // Remove spaces before `}`
.replaceAll(/;(?=})/g, ''); // Remove semicolons before `}`
}
const expectedComment = TWOSLASH_COMMENT + ' ' + expectedType.replaceAll('\n', '\n// ');
if (actualComment !== expectedComment) {
const actualCommentIndex = line.indexOf(TWOSLASH_COMMENT);
const actualCommentStartOffset = sourceFile.getPositionOfLineAndCharacter(index, actualCommentIndex);
const actualCommentEndOffset = sourceFile.getPositionOfLineAndCharacter(actualCommentEndLine, lines[actualCommentEndLine].length);
const start = codeStartIndex + actualCommentStartOffset;
const end = codeStartIndex + actualCommentEndOffset;
context.report({
loc: {
start: context.sourceCode.getLocFromIndex(start),
end: context.sourceCode.getLocFromIndex(end),
},
messageId: 'typeMismatch',
data: {
expectedComment,
actualComment,
},
fix(fixer) {
const indent = line.slice(0, actualCommentIndex);
return fixer.replaceTextRange(
[start, end],
expectedComment.replaceAll('\n', `\n${indent}`),
);
},
});
}
break;
}
}
}
}