-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcheck-coverage.ts
More file actions
237 lines (199 loc) · 6.98 KB
/
check-coverage.ts
File metadata and controls
237 lines (199 loc) · 6.98 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
#!/usr/bin/env tsx
/**
* Coverage checker: compares the WorkOS OpenAPI spec against the emulator's
* registered routes to find missing or extra endpoints.
*
* Usage:
* pnpm check:coverage path/to/openapi.yaml
* pnpm check:coverage ~/Developer/workos/packages/api/open-api-spec.yaml
*
* Reports:
* - Spec endpoints missing from the emulator
* - Emulator endpoints not in the spec (custom/internal)
* - Coverage percentage
*/
import { readFileSync, existsSync, readdirSync } from 'node:fs';
import { resolve, extname, join } from 'node:path';
import YAML from 'yaml';
// ---------------------------------------------------------------------------
// Parse OpenAPI spec endpoints
// ---------------------------------------------------------------------------
interface SpecEndpoint {
method: string;
path: string;
operationId?: string;
summary?: string;
tags: string[];
}
function parseOpenApiEndpoints(specPath: string): SpecEndpoint[] {
const raw = readFileSync(specPath, 'utf-8');
const ext = extname(specPath).toLowerCase();
const spec = ext === '.yaml' || ext === '.yml' ? YAML.parse(raw) : JSON.parse(raw);
const endpoints: SpecEndpoint[] = [];
const methods = ['get', 'post', 'put', 'patch', 'delete'] as const;
for (const [path, item] of Object.entries(spec.paths ?? {}) as [string, any][]) {
for (const method of methods) {
const op = item[method];
if (!op) continue;
// Normalize OpenAPI path params {id} → :id
const normalizedPath = path.replace(/\{([^}]+)\}/g, ':$1');
endpoints.push({
method: method.toUpperCase(),
path: normalizedPath,
operationId: op.operationId,
summary: op.summary,
tags: op.tags ?? [],
});
}
}
return endpoints;
}
// ---------------------------------------------------------------------------
// Parse emulator registered routes from source files
// ---------------------------------------------------------------------------
interface EmulatorEndpoint {
method: string;
path: string;
file: string;
line: number;
}
function parseEmulatorEndpoints(): EmulatorEndpoint[] {
const routesDir = resolve('src/emulate/workos/routes');
const serverFile = resolve('src/emulate/core/server.ts');
const endpoints: EmulatorEndpoint[] = [];
const routePattern = /app\.(get|post|put|patch|delete)\('([^']+)'/g;
const filesToScan: string[] = [];
// Collect route files
if (existsSync(routesDir)) {
for (const file of readdirSync(routesDir)) {
if (file.endsWith('.ts') && !file.endsWith('.spec.ts')) {
filesToScan.push(join(routesDir, file));
}
}
}
// Also scan server.ts for JWKS and other direct routes
if (existsSync(serverFile)) {
filesToScan.push(serverFile);
}
for (const filePath of filesToScan) {
const content = readFileSync(filePath, 'utf-8');
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
routePattern.lastIndex = 0;
let match;
while ((match = routePattern.exec(lines[i])) !== null) {
endpoints.push({
method: match[1].toUpperCase(),
path: match[2],
file: filePath.replace(resolve('.') + '/', ''),
line: i + 1,
});
}
}
}
return endpoints;
}
// ---------------------------------------------------------------------------
// Normalize paths for comparison
// ---------------------------------------------------------------------------
/** Normalize path params to a canonical form for matching.
* e.g., :id, :orgId, :organization_id all become :param in the same position */
function normalizePath(path: string): string {
return path
.replace(/:[a-zA-Z_]+/g, ':param')
.replace(/\/+$/, '')
.toLowerCase();
}
function routeKey(method: string, path: string): string {
return `${method} ${normalizePath(path)}`;
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
function main(): void {
const specPath = process.argv[2];
if (!specPath) {
console.error('Usage: check-coverage <openapi-spec-path>');
console.error(' e.g.: pnpm check:coverage ~/Developer/workos/packages/api/open-api-spec.yaml');
process.exit(1);
}
const resolvedSpec = resolve(specPath);
if (!existsSync(resolvedSpec)) {
console.error(`Spec file not found: ${resolvedSpec}`);
process.exit(1);
}
const specEndpoints = parseOpenApiEndpoints(resolvedSpec);
const emulatorEndpoints = parseEmulatorEndpoints();
// Build lookup maps
const specMap = new Map<string, SpecEndpoint>();
for (const ep of specEndpoints) {
specMap.set(routeKey(ep.method, ep.path), ep);
}
const emulatorMap = new Map<string, EmulatorEndpoint>();
for (const ep of emulatorEndpoints) {
emulatorMap.set(routeKey(ep.method, ep.path), ep);
}
// Find gaps
const missing: SpecEndpoint[] = [];
const covered: SpecEndpoint[] = [];
for (const [key, ep] of specMap) {
if (emulatorMap.has(key)) {
covered.push(ep);
} else {
missing.push(ep);
}
}
const extra: EmulatorEndpoint[] = [];
for (const [key, ep] of emulatorMap) {
if (!specMap.has(key)) {
extra.push(ep);
}
}
// Group missing by tag
const missingByTag = new Map<string, SpecEndpoint[]>();
for (const ep of missing) {
const tag = ep.tags[0] ?? 'untagged';
if (!missingByTag.has(tag)) missingByTag.set(tag, []);
missingByTag.get(tag)!.push(ep);
}
// Report
const total = specEndpoints.length;
const coveredCount = covered.length;
const pct = total > 0 ? ((coveredCount / total) * 100).toFixed(1) : '0';
console.log('');
console.log('=== Emulator API Coverage Report ===');
console.log('');
console.log(` Spec endpoints: ${total}`);
console.log(` Emulator endpoints: ${emulatorEndpoints.length}`);
console.log(` Covered: ${coveredCount}/${total} (${pct}%)`);
console.log(` Missing: ${missing.length}`);
console.log(` Extra (emulator-only): ${extra.length}`);
console.log('');
if (missing.length > 0) {
console.log('--- Missing from emulator ---');
console.log('');
for (const [tag, eps] of [...missingByTag.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
console.log(` [${tag}]`);
for (const ep of eps) {
const desc = ep.summary ? ` — ${ep.summary}` : '';
console.log(` ${ep.method.padEnd(6)} ${ep.path}${desc}`);
}
console.log('');
}
}
if (extra.length > 0) {
console.log('--- Emulator-only (not in spec) ---');
console.log('');
for (const ep of extra.sort((a, b) => a.path.localeCompare(b.path))) {
console.log(` ${ep.method.padEnd(6)} ${ep.path} (${ep.file}:${ep.line})`);
}
console.log('');
}
if (missing.length === 0) {
console.log('Full coverage — all spec endpoints are implemented.');
console.log('');
}
// Exit 1 if there are missing endpoints (useful for CI later)
process.exit(missing.length > 0 ? 1 : 0);
}
main();