forked from codinit-dev/codinit-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.github-template.ts
More file actions
430 lines (348 loc) · 13.3 KB
/
Copy pathapi.github-template.ts
File metadata and controls
430 lines (348 loc) · 13.3 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import { json } from '@remix-run/cloudflare';
import JSZip from 'jszip';
// Helper function to decode base64 content (works in both Node.js and browser)
function decodeBase64Content(content: string): string {
// Check if Buffer is available (Node.js environment)
if (typeof Buffer !== 'undefined') {
return Buffer.from(content, 'base64').toString('utf-8');
}
// Fallback to atob for browser environments
return atob(content);
}
// Function to detect if we're running in Cloudflare
function isCloudflareEnvironment(context: any): boolean {
// Check if we're in production AND have Cloudflare Pages specific env vars
const isProduction = process.env.NODE_ENV === 'production';
const hasCfPagesVars = !!(
context?.cloudflare?.env?.CF_PAGES ||
context?.cloudflare?.env?.CF_PAGES_URL ||
context?.cloudflare?.env?.CF_PAGES_COMMIT_SHA
);
return isProduction && hasCfPagesVars;
}
// Cloudflare-compatible method using GitHub Contents API
async function fetchRepoContentsCloudflare(repo: string, githubToken?: string) {
const baseUrl = 'https://api.github.com';
const failedFiles: Array<{ path: string; error: string }> = [];
// Get repository info to find default branch
const repoResponse = await fetch(`${baseUrl}/repos/${repo}`, {
headers: {
Accept: 'application/vnd.github.v3+json',
'User-Agent': 'codinit.dev-app',
...(githubToken ? { Authorization: `Bearer ${githubToken}` } : {}),
},
});
if (!repoResponse.ok) {
throw new Error(`Repository not found: ${repo}`);
}
const repoData = (await repoResponse.json()) as any;
const defaultBranch = repoData.default_branch;
// Get the tree recursively
const treeResponse = await fetch(`${baseUrl}/repos/${repo}/git/trees/${defaultBranch}?recursive=1`, {
headers: {
Accept: 'application/vnd.github.v3+json',
'User-Agent': 'codinit.dev-app',
...(githubToken ? { Authorization: `Bearer ${githubToken}` } : {}),
},
});
if (!treeResponse.ok) {
throw new Error(`Failed to fetch repository tree: ${treeResponse.status}`);
}
const treeData = (await treeResponse.json()) as any;
// Filter for files only (not directories) and limit size
const files = treeData.tree.filter((item: any) => {
if (item.type !== 'blob') {
return false;
}
if (item.path.startsWith('.git/')) {
return false;
}
// Allow lock files even if they're large
const isLockFile =
item.path.endsWith('package-lock.json') ||
item.path.endsWith('yarn.lock') ||
item.path.endsWith('pnpm-lock.yaml');
// For non-lock files, limit size to 100KB
if (!isLockFile && item.size >= 100000) {
return false;
}
return true;
});
// Fetch file contents in batches to avoid overwhelming the API
const batchSize = 10;
const fileContents = [];
for (let i = 0; i < files.length; i += batchSize) {
const batch = files.slice(i, i + batchSize);
const batchPromises = batch.map(async (file: any) => {
// Try to fetch file with one immediate retry
let lastError: Error | null = null;
for (let attempt = 0; attempt < 2; attempt++) {
try {
const contentResponse = await fetch(`${baseUrl}/repos/${repo}/contents/${file.path}`, {
headers: {
Accept: 'application/vnd.github.v3+json',
'User-Agent': 'codinit.dev-app',
...(githubToken ? { Authorization: `Bearer ${githubToken}` } : {}),
},
});
if (!contentResponse.ok) {
throw new Error(`HTTP ${contentResponse.status}: ${contentResponse.statusText}`);
}
const contentData = (await contentResponse.json()) as any;
const content = decodeBase64Content(contentData.content.replace(/\s/g, ''));
return {
name: file.path.split('/').pop() || '',
path: file.path,
content,
};
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
if (attempt === 0) {
// First attempt failed, will retry immediately
continue;
}
}
}
// Both attempts failed
if (lastError) {
console.warn(`Failed to fetch ${file.path} after retry:`, lastError.message);
failedFiles.push({ path: file.path, error: lastError.message });
}
return null;
});
const batchResults = await Promise.all(batchPromises);
fileContents.push(...batchResults.filter(Boolean));
// Add a small delay between batches to be respectful to the API
if (i + batchSize < files.length) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
return {
files: fileContents,
failedFiles: failedFiles.length > 0 ? failedFiles : undefined,
};
}
// Your existing method for non-Cloudflare environments
async function fetchRepoContentsZip(repo: string, githubToken?: string) {
const baseUrl = 'https://api.github.com';
try {
// Try to get the latest release
const releaseResponse = await fetch(`${baseUrl}/repos/${repo}/releases/latest`, {
headers: {
Accept: 'application/vnd.github.v3+json',
'User-Agent': 'codinit.dev-app',
...(githubToken ? { Authorization: `Bearer ${githubToken}` } : {}),
},
});
if (!releaseResponse.ok) {
// If 404, it means no releases, so fall back to fetching from default branch
if (releaseResponse.status === 404) {
console.warn(`No releases found for ${repo}, falling back to default branch content.`);
return await fetchRepoContentsFromDefaultBranch(repo, githubToken);
}
throw new Error(`GitHub API error: ${releaseResponse.status} - ${releaseResponse.statusText}`);
}
const releaseData = (await releaseResponse.json()) as any;
const zipballUrl = releaseData.zipball_url;
// Fetch the zipball
const zipResponse = await fetch(zipballUrl, {
headers: {
...(githubToken ? { Authorization: `Bearer ${githubToken}` } : {}),
},
});
if (!zipResponse.ok) {
throw new Error(`Failed to fetch release zipball: ${zipResponse.status}`);
}
// Get the zip content as ArrayBuffer
const zipArrayBuffer = await zipResponse.arrayBuffer();
// Use JSZip to extract the contents
const zip = await JSZip.loadAsync(zipArrayBuffer);
// Find the root folder name
let rootFolderName = '';
zip.forEach((relativePath) => {
if (!rootFolderName && relativePath.includes('/')) {
rootFolderName = relativePath.split('/')[0];
}
});
// Extract all files
const promises = Object.keys(zip.files).map(async (filename) => {
const zipEntry = zip.files[filename];
// Skip directories
if (zipEntry.dir) {
return null;
}
// Skip the root folder itself
if (filename === rootFolderName) {
return null;
}
// Remove the root folder from the path
let normalizedPath = filename;
if (rootFolderName && filename.startsWith(rootFolderName + '/')) {
normalizedPath = filename.substring(rootFolderName.length + 1);
}
// Get the file content
const content = await zipEntry.async('string');
return {
name: normalizedPath.split('/').pop() || '',
path: normalizedPath,
content,
};
});
const results = await Promise.all(promises);
return {
files: results.filter(Boolean),
failedFiles: undefined,
};
} catch (error) {
console.error('Error in fetchRepoContentsZip:', error);
// If it's not a 404 from releases/latest, re-throw the error
if (error instanceof Error && !error.message.includes('404')) {
throw error;
}
/**
* If it's a 404 from releases/latest, it should have been handled by the fallback.
* This catch block is for other errors during zip processing or if the fallback also fails.
*/
console.warn(`Falling back to default branch content due to an error in zip processing for ${repo}.`);
return await fetchRepoContentsFromDefaultBranch(repo, githubToken);
}
}
/**
* New function to fetch repository contents from the default branch
*/
async function fetchRepoContentsFromDefaultBranch(repo: string, githubToken?: string) {
const baseUrl = 'https://api.github.com';
const failedFiles: Array<{ path: string; error: string }> = [];
// Get repository info to find default branch
const repoResponse = await fetch(`${baseUrl}/repos/${repo}`, {
headers: {
Accept: 'application/vnd.github.v3+json',
'User-Agent': 'codinit.dev-app',
...(githubToken ? { Authorization: `Bearer ${githubToken}` } : {}),
},
});
if (!repoResponse.ok) {
throw new Error(`Repository not found or accessible: ${repo}`);
}
const repoData = (await repoResponse.json()) as any;
const defaultBranch = repoData.default_branch;
// Get the tree recursively
const treeResponse = await fetch(`${baseUrl}/repos/${repo}/git/trees/${defaultBranch}?recursive=1`, {
headers: {
Accept: 'application/vnd.github.v3+json',
'User-Agent': 'codinit.dev-app',
...(githubToken ? { Authorization: `Bearer ${githubToken}` } : {}),
},
});
if (!treeResponse.ok) {
throw new Error(`Failed to fetch repository tree from default branch: ${treeResponse.status}`);
}
const treeData = (await treeResponse.json()) as any;
// Filter for files only (not directories) and limit size
const files = treeData.tree.filter((item: any) => {
if (item.type !== 'blob') {
return false;
}
if (item.path.startsWith('.git/')) {
return false;
}
// Allow lock files even if they're large
const isLockFile =
item.path.endsWith('package-lock.json') ||
item.path.endsWith('yarn.lock') ||
item.path.endsWith('pnpm-lock.yaml');
// For non-lock files, limit size to 100KB
if (!isLockFile && item.size >= 100000) {
return false;
}
return true;
});
// Fetch file contents in batches to avoid overwhelming the API
const batchSize = 10;
const fileContents = [];
for (let i = 0; i < files.length; i += batchSize) {
const batch = files.slice(i, i + batchSize);
const batchPromises = batch.map(async (file: any) => {
// Try to fetch file with one immediate retry
let lastError: Error | null = null;
for (let attempt = 0; attempt < 2; attempt++) {
try {
const contentResponse = await fetch(`${baseUrl}/repos/${repo}/contents/${file.path}`, {
headers: {
Accept: 'application/vnd.github.v3+json',
'User-Agent': 'codinit.dev-app',
...(githubToken ? { Authorization: `Bearer ${githubToken}` } : {}),
},
});
if (!contentResponse.ok) {
throw new Error(`HTTP ${contentResponse.status}: ${contentResponse.statusText}`);
}
const contentData = (await contentResponse.json()) as any;
const content = decodeBase64Content(contentData.content.replace(/\s/g, ''));
return {
name: file.path.split('/').pop() || '',
path: file.path,
content,
};
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
if (attempt === 0) {
// First attempt failed, will retry immediately
continue;
}
}
}
// Both attempts failed
if (lastError) {
console.warn(`Failed to fetch ${file.path} after retry:`, lastError.message);
failedFiles.push({ path: file.path, error: lastError.message });
}
return null;
});
const batchResults = await Promise.all(batchPromises);
fileContents.push(...batchResults.filter(Boolean));
// Add a small delay between batches to be respectful to the API
if (i + batchSize < files.length) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
return {
files: fileContents,
failedFiles: failedFiles.length > 0 ? failedFiles : undefined,
};
}
export async function loader({ request, context }: { request: Request; context: any }) {
const url = new URL(request.url);
const repo = url.searchParams.get('repo');
if (!repo) {
return json({ error: 'Repository name is required' }, { status: 400 });
}
try {
// Access environment variables from Cloudflare context or process.env
const githubToken =
context?.cloudflare?.env?.GITHUB_TOKEN || process.env.GITHUB_TOKEN || process.env.VITE_GITHUB_ACCESS_TOKEN;
let fileList;
if (isCloudflareEnvironment(context)) {
fileList = await fetchRepoContentsCloudflare(repo, githubToken);
} else {
fileList = await fetchRepoContentsZip(repo, githubToken);
}
// Filter out .git files for both methods
const filteredFiles = fileList.files.filter((file: any) => !file.path.startsWith('.git'));
return json({
files: filteredFiles,
failedFiles: fileList.failedFiles,
});
} catch (error) {
console.error('Error processing GitHub template:', error);
console.error('Repository:', repo);
console.error('Error details:', error instanceof Error ? error.message : String(error));
return json(
{
error: 'Failed to fetch template files',
details: error instanceof Error ? error.message : String(error),
},
{ status: 500 },
);
}
}