|
| 1 | +#!/usr/bin/env bun |
| 2 | +/** |
| 3 | + * Generate API Schema Index from Sentry's OpenAPI Specification |
| 4 | + * |
| 5 | + * Fetches the dereferenced OpenAPI spec from the sentry-api-schema repository |
| 6 | + * and extracts a lightweight JSON index of all API endpoints. This index is |
| 7 | + * bundled into the CLI for runtime introspection via `sentry schema`. |
| 8 | + * |
| 9 | + * Data source: https://github.com/getsentry/sentry-api-schema |
| 10 | + * - openapi-derefed.json — full dereferenced OpenAPI 3.0 spec |
| 11 | + * |
| 12 | + * Also reads SDK function names from the installed @sentry/api package to |
| 13 | + * map operationIds to their TypeScript SDK function names. |
| 14 | + * |
| 15 | + * Usage: |
| 16 | + * bun run script/generate-api-schema.ts |
| 17 | + * |
| 18 | + * Output: |
| 19 | + * src/generated/api-schema.json |
| 20 | + */ |
| 21 | + |
| 22 | +import { resolve } from "node:path"; |
| 23 | + |
| 24 | +const OUTPUT_PATH = "src/generated/api-schema.json"; |
| 25 | + |
| 26 | +/** |
| 27 | + * Build the OpenAPI spec URL from the installed @sentry/api version. |
| 28 | + * The sentry-api-schema repo tags match the @sentry/api npm version. |
| 29 | + */ |
| 30 | +function getOpenApiUrl(): string { |
| 31 | + const pkgPath = require.resolve("@sentry/api/package.json"); |
| 32 | + const pkg = require(pkgPath) as { version: string }; |
| 33 | + return `https://raw.githubusercontent.com/getsentry/sentry-api-schema/${pkg.version}/openapi-derefed.json`; |
| 34 | +} |
| 35 | + |
| 36 | +/** Regex to extract path parameters from URL templates */ |
| 37 | +const PATH_PARAM_PATTERN = /\{(\w+)\}/g; |
| 38 | + |
| 39 | +/** Parsed endpoint data — exported to make this file a module for top-level await */ |
| 40 | +export type ApiEndpoint = { |
| 41 | + /** SDK function name (empty string if not found in @sentry/api) */ |
| 42 | + fn: string; |
| 43 | + /** HTTP method */ |
| 44 | + method: string; |
| 45 | + /** URL template with {param} placeholders */ |
| 46 | + path: string; |
| 47 | + /** Human-readable description from OpenAPI spec */ |
| 48 | + description: string; |
| 49 | + /** Path parameter names extracted from URL template */ |
| 50 | + pathParams: string[]; |
| 51 | + /** Query parameter names from OpenAPI spec */ |
| 52 | + queryParams: string[]; |
| 53 | + /** Whether the endpoint is deprecated */ |
| 54 | + deprecated: boolean; |
| 55 | + /** Resource category derived from URL path */ |
| 56 | + resource: string; |
| 57 | + /** Operation ID from OpenAPI spec (human-readable) */ |
| 58 | + operationId: string; |
| 59 | +}; |
| 60 | + |
| 61 | +// --------------------------------------------------------------------------- |
| 62 | +// OpenAPI Types (minimal subset we need) |
| 63 | +// --------------------------------------------------------------------------- |
| 64 | + |
| 65 | +type OpenApiSpec = { |
| 66 | + paths: Record<string, Record<string, OpenApiOperation>>; |
| 67 | +}; |
| 68 | + |
| 69 | +type OpenApiOperation = { |
| 70 | + operationId?: string; |
| 71 | + description?: string; |
| 72 | + deprecated?: boolean; |
| 73 | + parameters?: OpenApiParameter[]; |
| 74 | +}; |
| 75 | + |
| 76 | +type OpenApiParameter = { |
| 77 | + in: "path" | "query" | "header" | "cookie"; |
| 78 | + name: string; |
| 79 | + required?: boolean; |
| 80 | + description?: string; |
| 81 | + schema?: { type?: string }; |
| 82 | +}; |
| 83 | + |
| 84 | +// --------------------------------------------------------------------------- |
| 85 | +// SDK Function Name Mapping |
| 86 | +// --------------------------------------------------------------------------- |
| 87 | + |
| 88 | +/** |
| 89 | + * Build a map from URL+method to SDK function name by parsing |
| 90 | + * the @sentry/api index.js bundle. |
| 91 | + */ |
| 92 | +async function buildSdkFunctionMap(): Promise<Map<string, string>> { |
| 93 | + const pkgDir = resolve( |
| 94 | + require.resolve("@sentry/api/package.json"), |
| 95 | + "..", |
| 96 | + "dist" |
| 97 | + ); |
| 98 | + const js = await Bun.file(`${pkgDir}/index.js`).text(); |
| 99 | + const results = new Map<string, string>(); |
| 100 | + |
| 101 | + // Match: var NAME = (options...) => (options...client ?? client).METHOD({ |
| 102 | + const funcPattern = |
| 103 | + /var (\w+) = \(options\S*\) => \(options\S*client \?\? client\)\.(\w+)\(/g; |
| 104 | + // Match: url: "..." |
| 105 | + const urlPattern = /url: "([^"]+)"/g; |
| 106 | + |
| 107 | + // Extract all function declarations with their positions |
| 108 | + const funcs: { name: string; method: string; index: number }[] = []; |
| 109 | + let match = funcPattern.exec(js); |
| 110 | + while (match !== null) { |
| 111 | + funcs.push({ |
| 112 | + name: match[1], |
| 113 | + method: match[2].toUpperCase(), |
| 114 | + index: match.index, |
| 115 | + }); |
| 116 | + match = funcPattern.exec(js); |
| 117 | + } |
| 118 | + |
| 119 | + // Extract all URLs with their positions |
| 120 | + const urls: { url: string; index: number }[] = []; |
| 121 | + match = urlPattern.exec(js); |
| 122 | + while (match !== null) { |
| 123 | + urls.push({ url: match[1], index: match.index }); |
| 124 | + match = urlPattern.exec(js); |
| 125 | + } |
| 126 | + |
| 127 | + // Match each function to its nearest following URL |
| 128 | + for (const func of funcs) { |
| 129 | + const nextUrl = urls.find((u) => u.index > func.index); |
| 130 | + if (nextUrl) { |
| 131 | + const key = `${func.method}:${nextUrl.url}`; |
| 132 | + results.set(key, func.name); |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + return results; |
| 137 | +} |
| 138 | + |
| 139 | +// --------------------------------------------------------------------------- |
| 140 | +// Resource Derivation |
| 141 | +// --------------------------------------------------------------------------- |
| 142 | + |
| 143 | +/** |
| 144 | + * Derive the resource name from a URL template. |
| 145 | + * Uses the last non-parameter path segment. |
| 146 | + * |
| 147 | + * @example "/api/0/organizations/{org}/issues/" → "issues" |
| 148 | + * @example "/api/0/issues/{issue_id}/" → "issues" |
| 149 | + */ |
| 150 | +function deriveResource(url: string): string { |
| 151 | + const segments = url |
| 152 | + .split("/") |
| 153 | + .filter((s) => s.length > 0 && !s.startsWith("{")); |
| 154 | + const meaningful = segments.filter((s) => s !== "api" && s !== "0"); |
| 155 | + return meaningful.at(-1) ?? "unknown"; |
| 156 | +} |
| 157 | + |
| 158 | +/** |
| 159 | + * Extract path parameter names from a URL template. |
| 160 | + */ |
| 161 | +function extractPathParams(url: string): string[] { |
| 162 | + const params: string[] = []; |
| 163 | + const pattern = new RegExp( |
| 164 | + PATH_PARAM_PATTERN.source, |
| 165 | + PATH_PARAM_PATTERN.flags |
| 166 | + ); |
| 167 | + let match = pattern.exec(url); |
| 168 | + while (match !== null) { |
| 169 | + params.push(match[1]); |
| 170 | + match = pattern.exec(url); |
| 171 | + } |
| 172 | + return params; |
| 173 | +} |
| 174 | + |
| 175 | +// --------------------------------------------------------------------------- |
| 176 | +// Main |
| 177 | +// --------------------------------------------------------------------------- |
| 178 | + |
| 179 | +const openApiUrl = getOpenApiUrl(); |
| 180 | +console.log(`Fetching OpenAPI spec from ${openApiUrl}...`); |
| 181 | +const response = await fetch(openApiUrl); |
| 182 | +if (!response.ok) { |
| 183 | + throw new Error( |
| 184 | + `Failed to fetch OpenAPI spec: ${response.status} ${response.statusText}` |
| 185 | + ); |
| 186 | +} |
| 187 | +const spec = (await response.json()) as OpenApiSpec; |
| 188 | + |
| 189 | +console.log("Building SDK function name map from @sentry/api..."); |
| 190 | +const sdkMap = await buildSdkFunctionMap(); |
| 191 | + |
| 192 | +const endpoints: ApiEndpoint[] = []; |
| 193 | +const HTTP_METHODS = ["get", "post", "put", "delete", "patch"]; |
| 194 | + |
| 195 | +for (const [urlPath, pathItem] of Object.entries(spec.paths)) { |
| 196 | + for (const method of HTTP_METHODS) { |
| 197 | + const operation = pathItem[method] as OpenApiOperation | undefined; |
| 198 | + if (!operation) { |
| 199 | + continue; |
| 200 | + } |
| 201 | + |
| 202 | + const methodUpper = method.toUpperCase(); |
| 203 | + const sdkKey = `${methodUpper}:${urlPath}`; |
| 204 | + const fn = sdkMap.get(sdkKey) ?? ""; |
| 205 | + |
| 206 | + const queryParams = (operation.parameters ?? []) |
| 207 | + .filter((p) => p.in === "query") |
| 208 | + .map((p) => p.name); |
| 209 | + |
| 210 | + endpoints.push({ |
| 211 | + fn, |
| 212 | + method: methodUpper, |
| 213 | + path: urlPath, |
| 214 | + description: (operation.description ?? "").trim(), |
| 215 | + pathParams: extractPathParams(urlPath), |
| 216 | + queryParams, |
| 217 | + deprecated: operation.deprecated ?? false, |
| 218 | + resource: deriveResource(urlPath), |
| 219 | + operationId: operation.operationId ?? "", |
| 220 | + }); |
| 221 | + } |
| 222 | +} |
| 223 | + |
| 224 | +// Sort by resource, then method for stable output |
| 225 | +endpoints.sort((a, b) => { |
| 226 | + const resourceCmp = a.resource.localeCompare(b.resource); |
| 227 | + if (resourceCmp !== 0) { |
| 228 | + return resourceCmp; |
| 229 | + } |
| 230 | + return a.operationId.localeCompare(b.operationId); |
| 231 | +}); |
| 232 | + |
| 233 | +await Bun.write(OUTPUT_PATH, JSON.stringify(endpoints, null, 2)); |
| 234 | + |
| 235 | +console.log( |
| 236 | + `Generated ${OUTPUT_PATH} (${endpoints.length} endpoints, ${Math.round(JSON.stringify(endpoints).length / 1024)}KB)` |
| 237 | +); |
0 commit comments