-
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathadd-examples-to-dts.ts
More file actions
153 lines (128 loc) · 4.94 KB
/
add-examples-to-dts.ts
File metadata and controls
153 lines (128 loc) · 4.94 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
/* eslint-disable n/prefer-global/process, unicorn/no-process-exit */
import {readFileSync, writeFileSync} from 'node:fs';
import {execSync} from 'node:child_process';
// Import index.ts to populate the test data via side effect
// eslint-disable-next-line import-x/no-unassigned-import
import './index.ts';
import {getTests} from './collector.ts';
// Read the generated .d.ts file
const dtsPath = './distribution/index.d.ts';
const dtsContent = readFileSync(dtsPath, 'utf8');
// Check if script has already been run
const marker = '/* Examples added by add-examples-to-dts.ts */';
if (dtsContent.includes(marker)) {
console.error('❌ Error: Examples have already been added to this file');
process.exit(1);
}
// Process each exported function
const lines = dtsContent.split('\n');
const outputLines: string[] = [];
let examplesAdded = 0;
for (const line of lines) {
// Check if this is a function declaration
const match = /^export declare const (\w+):/.exec(line);
if (match) {
const functionName = match[1];
// Get the tests/examples for this function
const examples = getTests(functionName);
// Only add examples if they exist and aren't the special 'combinedTestOnly' marker
if (examples && examples.length > 0 && examples[0] !== 'combinedTestOnly') {
// Filter to only include actual URLs (not references to other functions)
const urlExamples = examples.filter((url: string) => url.startsWith('http'));
if (urlExamples.length > 0) {
// Check if there's an existing JSDoc block immediately before this line
let jsDocumentEndIndex = -1;
let jsDocumentStartIndex = -1;
let isSingleLineJsDocument = false;
// Look backwards from outputLines to find JSDoc
for (let index = outputLines.length - 1; index >= 0; index--) {
const previousLine = outputLines[index];
const trimmed = previousLine.trim();
if (trimmed === '') {
continue; // Skip empty lines
}
// Check for single-line JSDoc: /** ... */
if (trimmed.startsWith('/**') && trimmed.endsWith('*/') && trimmed.length > 5) {
jsDocumentStartIndex = index;
jsDocumentEndIndex = index;
isSingleLineJsDocument = true;
break;
}
// Check for multi-line JSDoc ending
if (trimmed === '*/') {
jsDocumentEndIndex = index;
// Now find the start of this JSDoc
for (let k = index - 1; k >= 0; k--) {
if (outputLines[k].trim().startsWith('/**')) {
jsDocumentStartIndex = k;
break;
}
}
break;
}
// If we hit a non-JSDoc line, there's no JSDoc block
break;
}
if (jsDocumentStartIndex >= 0 && jsDocumentEndIndex >= 0) {
// Extend existing JSDoc block
if (isSingleLineJsDocument) {
// Convert single-line to multi-line and add examples
const singleLineContent = outputLines[jsDocumentStartIndex];
// Extract the comment text without /** and */
const commentText = singleLineContent.trim().slice(3, -2).trim();
// Replace the single line with multi-line format
outputLines[jsDocumentStartIndex] = '/**';
if (commentText) {
outputLines.splice(jsDocumentStartIndex + 1, 0, ` * ${commentText}`);
}
// Add examples after the existing content
const insertIndex = jsDocumentStartIndex + (commentText ? 2 : 1);
for (const url of urlExamples) {
outputLines.splice(insertIndex + urlExamples.indexOf(url), 0, ` * @example ${url}`);
}
outputLines.splice(insertIndex + urlExamples.length, 0, ' */');
examplesAdded += urlExamples.length;
} else {
// Insert @example lines before the closing */
for (const url of urlExamples) {
outputLines.splice(jsDocumentEndIndex, 0, ` * @example ${url}`);
}
examplesAdded += urlExamples.length;
}
} else {
// Add new JSDoc comment with examples before the declaration
outputLines.push('/**');
for (const url of urlExamples) {
outputLines.push(` * @example ${url}`);
}
outputLines.push(' */');
examplesAdded += urlExamples.length;
}
}
}
}
outputLines.push(line);
}
// Add marker at the beginning
const finalContent = `${marker}\n${outputLines.join('\n')}`;
// Validate that we added some examples
if (examplesAdded === 0) {
console.error('❌ Error: No examples were added. This likely indicates a problem with the script.');
process.exit(1);
}
// Write the modified content back
writeFileSync(dtsPath, finalContent, 'utf8');
console.log(`✓ Added ${examplesAdded} example URLs to index.d.ts`);
// Validate with TypeScript
try {
execSync('npx tsc --noEmit distribution/index.d.ts', {
cwd: process.cwd(),
stdio: 'pipe',
});
console.log('✓ TypeScript validation passed');
} catch (error: unknown) {
console.error('❌ TypeScript validation failed:');
const execError = error as {stdout?: Uint8Array; stderr?: Uint8Array; message?: string};
console.error(execError.stdout?.toString() ?? execError.stderr?.toString() ?? execError.message);
process.exit(1);
}