-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.ts
More file actions
169 lines (146 loc) · 4.87 KB
/
Copy pathgithub.ts
File metadata and controls
169 lines (146 loc) · 4.87 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
import { GitHubError, NotFoundError, RateLimitError } from "./errors.js";
const META_OWNER = "TMHSDigital";
const META_REPO = "Developer-Tools-Directory";
const CACHE_TTL_MS = 5 * 60 * 1000;
interface CacheEntry<T> {
data: T;
expiresAt: number;
}
const cache = new Map<string, CacheEntry<unknown>>();
function cached<T>(key: string): T | undefined {
const entry = cache.get(key);
if (entry && Date.now() < entry.expiresAt) return entry.data as T;
return undefined;
}
function store<T>(key: string, data: T): void {
cache.set(key, { data, expiresAt: Date.now() + CACHE_TTL_MS });
}
function buildHeaders(): Record<string, string> {
const token = process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN;
const headers: Record<string, string> = {
Accept: "application/vnd.github+json",
"User-Agent": "devtools-mcp/0.1.0",
"X-GitHub-Api-Version": "2022-11-28",
};
if (token) headers["Authorization"] = `Bearer ${token}`;
return headers;
}
export async function githubFetch<T>(path: string): Promise<T> {
const hit = cached<T>(`api:${path}`);
if (hit !== undefined) return hit;
const url = `https://api.github.com${path}`;
const res = await fetch(url, { headers: buildHeaders() });
if (res.status === 404) throw new NotFoundError(path);
if (res.status === 403 || res.status === 429) throw new RateLimitError();
if (!res.ok) {
throw new GitHubError(`GitHub API ${res.status} for ${path}`, res.status, path);
}
const data = (await res.json()) as T;
store(`api:${path}`, data);
return data;
}
export async function rawFetch(
owner: string,
repo: string,
filePath: string,
ref = "main",
): Promise<string> {
const key = `raw:${owner}/${repo}/${ref}/${filePath}`;
const hit = cached<string>(key);
if (hit !== undefined) return hit;
// Local mode: if DEVTOOLS_META_ROOT is set and this is the meta-repo, read from disk.
const metaRoot = process.env.DEVTOOLS_META_ROOT;
if (metaRoot && owner === META_OWNER && repo === META_REPO) {
const { readFile } = await import("fs/promises");
const { join } = await import("path");
const text = await readFile(join(metaRoot, filePath), "utf-8");
store(key, text);
return text;
}
const url = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${filePath}`;
const res = await fetch(url, { headers: buildHeaders() });
if (res.status === 404) throw new NotFoundError(`${owner}/${repo}/${filePath}`);
if (res.status === 403 || res.status === 429) throw new RateLimitError();
if (!res.ok) {
throw new GitHubError(
`Raw fetch ${res.status} for ${owner}/${repo}/${filePath}`,
res.status,
);
}
const text = await res.text();
store(key, text);
return text;
}
export function errorResponse(error: unknown): {
content: Array<{ type: "text"; text: string }>;
isError: true;
} {
const message =
error instanceof Error ? error.message : "An unknown error occurred.";
return { content: [{ type: "text", text: message }], isError: true };
}
export function extractStandardsVersion(content: string): string | null {
const match = content.match(/<!--\s*standards-version:\s*([\d.]+)\s*-->/);
return match?.[1] ?? null;
}
export type RegistryEntry = {
name: string;
repo: string;
slug: string;
description: string;
type: "cursor-plugin" | "mcp-server";
homepage: string;
skills: number;
rules: number;
mcpTools: number;
extras: Record<string, unknown>;
topics: string[];
status: string;
version: string;
language: string;
license: string;
pagesType: string;
hasCI: boolean;
npm?: string;
};
export async function fetchRegistry(): Promise<RegistryEntry[]> {
const raw = await rawFetch(META_OWNER, META_REPO, "registry.json");
return JSON.parse(raw) as RegistryEntry[];
}
export async function fetchStandardsVersion(): Promise<string> {
const raw = await rawFetch(META_OWNER, META_REPO, "STANDARDS_VERSION");
return raw.trim();
}
export async function githubWrite<T>(
path: string,
method: "POST" | "PUT" | "PATCH" | "DELETE",
body?: unknown,
): Promise<T> {
const token = process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN;
if (!token) {
throw new GitHubError(
"GH_TOKEN or GITHUB_TOKEN is required for write operations",
401,
path,
);
}
const url = `https://api.github.com${path}`;
const opts: RequestInit = {
method,
headers: { ...buildHeaders(), "Content-Type": "application/json" },
};
if (body !== undefined) opts.body = JSON.stringify(body);
const res = await fetch(url, opts);
if (res.status === 404) throw new NotFoundError(path);
if (res.status === 403 || res.status === 429) throw new RateLimitError();
if (res.status === 204) return {} as T;
if (!res.ok) {
const errText = await res.text().catch(() => "");
throw new GitHubError(
`GitHub ${method} ${res.status} for ${path}: ${errText}`,
res.status,
path,
);
}
return res.json() as Promise<T>;
}