-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.ts
More file actions
167 lines (142 loc) · 4.22 KB
/
Copy pathgithub.ts
File metadata and controls
167 lines (142 loc) · 4.22 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
export class PrivateRepoError extends Error {
constructor() {
super('Private repository — access token required.');
this.name = 'PrivateRepoError';
}
}
export class TokenExpiredError extends Error {
constructor() {
super('Access token is invalid or expired.');
this.name = 'TokenExpiredError';
}
}
export class RateLimitError extends Error {
constructor() {
super(
'API rate limit exceeded. Authenticated requests get a higher rate limit.'
);
this.name = 'RateLimitError';
}
}
export interface GitHubContext {
owner: string;
repo: string;
branch: string;
path: string;
}
export interface GitHubFile {
path: string;
url: string;
apiUrl?: string;
}
export const parseGitHubUrl = (url: string): GitHubContext | null => {
try {
const u = new URL(url);
if (u.hostname !== 'github.com') return null;
const parts = u.pathname.split('/').filter(Boolean);
if (parts.length < 2) return null;
const owner = parts[0];
const repo = parts[1];
if (parts.length === 2) {
return { owner, repo, branch: 'HEAD', path: '' };
}
if (parts[2] === 'tree' || parts[2] === 'blob') {
const branch = parts[3];
const path = parts.slice(4).join('/');
return { owner, repo, branch, path };
}
return null;
} catch {
return null;
}
};
export const getStoredToken = (): Promise<string | null> =>
new Promise((resolve) => {
chrome.storage.local.get('github_token', (result) => {
resolve(result.github_token || null);
});
});
export const fetchTree = async (
context: GitHubContext,
token?: string | null
): Promise<GitHubFile[]> => {
const { owner, repo, branch, path } = context;
const headers: Record<string, string> = {
Accept: 'application/vnd.github.v3+json',
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const res = await fetch(
`https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}?recursive=1`,
{
headers,
}
);
if (!res.ok) {
if (res.status === 404) {
throw new PrivateRepoError();
}
if (res.status === 401) {
throw new TokenExpiredError();
}
if (res.status === 403) {
throw new RateLimitError();
}
throw new Error(
`Failed to fetch repository tree (HTTP ${res.status}).`
);
}
const data = await res.json();
if (data.truncated) {
console.warn(
'Repository tree is very large and the result was truncated.'
);
}
const files: GitHubFile[] = [];
const prefix = path ? `${path}/` : '';
for (const item of data.tree) {
if (item.type !== 'blob') continue;
let matched = false;
let relativePath = item.path;
if (!path) {
matched = true;
} else if (item.path.startsWith(prefix)) {
matched = true;
relativePath = item.path.substring(prefix.length);
} else if (item.path === path) {
matched = true;
relativePath = item.path.split('/').pop() || item.path;
}
if (matched) {
files.push({
path: relativePath,
url: `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/${item.path}`,
apiUrl: `https://api.github.com/repos/${owner}/${repo}/contents/${item.path}?ref=${branch}`,
});
}
}
return files;
};
export const fetchFileWithToken = async (
file: GitHubFile,
token?: string | null
): Promise<Response> => {
if (!file.apiUrl) {
throw new Error(`Missing API URL for file: ${file.path}`);
}
const headers: Record<string, string> = {
Accept: 'application/vnd.github.raw+json',
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const res = await fetch(file.apiUrl, { headers });
if (res.status === 401) {
throw new TokenExpiredError();
}
if (res.status === 403) {
throw new RateLimitError();
}
return res;
};