-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfetch-data.ts
More file actions
1017 lines (917 loc) · 32.1 KB
/
fetch-data.ts
File metadata and controls
1017 lines (917 loc) · 32.1 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'fs';
import path from 'path';
import { GraphQLClient, gql } from 'graphql-request';
import ellipsize from 'ellipsize';
import MarkdownIt from 'markdown-it';
import markdownItTaskLists from 'markdown-it-task-lists';
import markdownItFootnote from 'markdown-it-footnote';
import markdownItGitHubAlerts from 'markdown-it-github-alerts';
import { full as markdownItEmoji } from 'markdown-it-emoji';
import { Octokit } from '@octokit/rest';
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
// Concurrent execution helper with limit
async function pMap<T, R>(
items: T[],
mapper: (item: T, index: number) => Promise<R>,
concurrency: number = 5
): Promise<R[]> {
const results: R[] = [];
const executing: Promise<void>[] = [];
for (let i = 0; i < items.length; i++) {
const item = items[i];
const promise = Promise.resolve().then(() => mapper(item, i)).then(result => {
results[i] = result;
});
const executing_promise = promise.then(() => {
executing.splice(executing.indexOf(executing_promise), 1);
});
executing.push(executing_promise);
if (executing.length >= concurrency) {
await Promise.race(executing);
}
}
await Promise.all(executing);
return results;
}
// Type definitions
type ReleaseAsset = {
name: string;
contentType: string;
downloadUrl: string;
downloadCount: number;
size: number;
};
type GraphQlRelease = {
name: string;
url: string;
immutable: boolean;
isDraft: boolean;
description: string;
descriptionHTML: string;
createdAt: string;
publishedAt: string;
updatedAt: string;
tagName: string;
isPrerelease: boolean;
isLatest: boolean;
releaseAssets: {
edges: Array<{ node: ReleaseAsset }>;
};
};
type GraphQlRepository = {
name: string;
description: string;
url: string;
homepageUrl?: string;
collaborators: {
edges: Array<{
node: {
login: string;
name?: string;
};
}>;
};
readme?: { text: string };
moduleJson?: { text: string };
latestRelease?: GraphQlRelease;
releases: {
edges: Array<{ node: GraphQlRelease }>;
};
updatedAt: string;
createdAt: string;
stargazerCount: number;
};
type GraphQlRepositoryWrapped = {
node: GraphQlRepository;
cursor: string;
};
type ModuleRelease = {
name: string;
url: string;
descriptionHTML: string;
createdAt: string;
publishedAt: string;
updatedAt: string;
tagName: string;
isPrerelease: boolean;
releaseAssets: ReleaseAsset[];
version: string;
versionCode: string;
};
type ModuleJson = {
moduleId: string;
moduleName: string;
url: string;
homepageUrl: string | null;
authors: Array<{ name: string; link: string }>;
latestRelease: string | null;
latestReleaseTime: string;
latestBetaReleaseTime: string;
latestSnapshotReleaseTime: string;
releases: ModuleRelease[];
readme: string | null;
readmeHTML: string | null;
summary: string | null;
sourceUrl: string | null;
updatedAt: string;
createdAt: string;
stargazerCount: number;
metamodule: boolean;
};
const md = new MarkdownIt({
html: true,
linkify: true,
typographer: true
})
.use(markdownItTaskLists, { enabled: true, label: true, labelAfter: true })
.use(markdownItFootnote)
.use(markdownItGitHubAlerts)
.use(markdownItEmoji);
// Skip reason types for detailed error reporting
enum SkipReason {
INVALID_NAME = 'INVALID_NAME',
NO_DESCRIPTION = 'NO_DESCRIPTION',
NO_VALID_RELEASES = 'NO_VALID_RELEASES',
RESERVED_NAME = 'RESERVED_NAME',
NO_ZIP_ASSET = 'NO_ZIP_ASSET',
MODULE_ID_MISMATCH = 'MODULE_ID_MISMATCH',
MISSING_VERSION = 'MISSING_VERSION',
MISSING_MODULE_PROP = 'MISSING_MODULE_PROP',
}
type SkipInfo = {
reason: SkipReason;
message: string;
details?: Record<string, any>;
shouldNotify: boolean; // Only notify when latest release has issues
tagName?: string; // The release tag that has issues (for commenting)
};
type ConvertResult =
| { success: true; module: ModuleJson }
| { success: false; skipInfo: SkipInfo };
const SKIP_REASON_MESSAGES: Record<SkipReason, { title: string; body: string }> = {
[SkipReason.INVALID_NAME]: {
title: 'Invalid module name format',
body: 'Repository name must start with a letter and can only contain letters, numbers, dots (.), underscores (_), and hyphens (-).\n\nPlease rename the repository to match the required format: `^[a-zA-Z][a-zA-Z0-9._-]+$`',
},
[SkipReason.NO_DESCRIPTION]: {
title: 'Missing repository description',
body: 'The repository is missing a description. Please add a description in the repository settings.\n\nThe description will be displayed as the module name in the module list.',
},
[SkipReason.NO_VALID_RELEASES]: {
title: 'No valid releases found',
body: 'The repository has no releases that meet the requirements.\n\nA valid release must:\n- Not be a draft\n- Be immutable (locked)\n- Contain a `.zip` attachment\n\nPlease create a proper release and upload the module zip file.',
},
[SkipReason.RESERVED_NAME]: {
title: 'Repository name is reserved',
body: 'This repository name is reserved for system use and will not be included as a module.',
},
[SkipReason.NO_ZIP_ASSET]: {
title: 'Release missing ZIP attachment',
body: 'No `.zip` attachment was found in the release.\n\nPlease ensure you upload the module zip file to the release.',
},
[SkipReason.MODULE_ID_MISMATCH]: {
title: 'module.prop id does not match repository name',
body: 'The `id` field in `module.prop` inside the zip file must exactly match the repository name.\n\n**Current status:**\n- Repository name: `{repoName}`\n- module.prop id: `{moduleId}`\n\nPlease update the `id` field in `module.prop` or rename the repository.',
},
[SkipReason.MISSING_VERSION]: {
title: 'module.prop missing version information',
body: 'The `module.prop` in the zip file is missing required version fields.\n\n**Current status:**\n- version: `{version}`\n- versionCode: `{versionCode}`\n\nPlease ensure `module.prop` contains valid `version` and `versionCode` fields.',
},
[SkipReason.MISSING_MODULE_PROP]: {
title: 'ZIP file missing module.prop',
body: 'No `module.prop` file was found in the release zip file.\n\nThis is a required file for KernelSU modules. Please ensure the zip package root directory contains a valid `module.prop`.',
},
};
const PAGINATION = 10;
const GRAPHQL_TOKEN = process.env.GRAPHQL_TOKEN;
const GITHUB_ORG = 'KernelSU-Modules-Repo';
// Initialize Octokit client
const octokit = new Octokit({
auth: GRAPHQL_TOKEN,
});
// GitHub Actions bot usernames
const GITHUB_BOTS = ['github-actions[bot]', 'dependabot[bot]', 'renovate[bot]'];
// Comment on a release tag for validation errors (incremental build only)
// No duplicate check needed - immutable releases cannot be republished
async function commentOnRelease(repoName: string, tagName: string, skipInfo: SkipInfo): Promise<void> {
const template = SKIP_REASON_MESSAGES[skipInfo.reason];
try {
// Get release author
const { data: release } = await octokit.repos.getReleaseByTag({
owner: GITHUB_ORG,
repo: repoName,
tag: tagName,
});
const author = release.author?.login;
let mentions = '';
if (author && !GITHUB_BOTS.includes(author)) {
// @ the release author
mentions = `@${author}`;
} else {
// Release was created by bot, @ all collaborators
try {
const { data: collaborators } = await octokit.repos.listCollaborators({
owner: GITHUB_ORG,
repo: repoName,
affiliation: 'direct',
});
const collaboratorMentions = collaborators
.filter(c => !GITHUB_BOTS.includes(c.login))
.map(c => `@${c.login}`);
if (collaboratorMentions.length > 0) {
mentions = collaboratorMentions.join(' ');
}
} catch {
// Failed to get collaborators, continue without mentions
}
}
let body = mentions ? `${mentions}\n\n` : '';
body += `## ⚠️ ${template.title}\n\n${template.body}`;
// Replace placeholders with actual values
if (skipInfo.details) {
for (const [key, value] of Object.entries(skipInfo.details)) {
body = body.replace(new RegExp(`\\{${key}\\}`, 'g'), String(value ?? 'N/A'));
}
}
body += `\n\n---\n*This comment was automatically created by the build system.*\n*Please fix the issue and create a new release.*`;
// Get the commit SHA for this tag
const { data: refData } = await octokit.git.getRef({
owner: GITHUB_ORG,
repo: repoName,
ref: `tags/${tagName}`,
});
let commitSha = refData.object.sha;
// If it's an annotated tag, get the actual commit
if (refData.object.type === 'tag') {
try {
const { data: tagData } = await octokit.git.getTag({
owner: GITHUB_ORG,
repo: repoName,
tag_sha: commitSha,
});
commitSha = tagData.object.sha;
} catch {
// Not an annotated tag, use the SHA directly
}
}
// Create comment on the commit
await octokit.repos.createCommitComment({
owner: GITHUB_ORG,
repo: repoName,
commit_sha: commitSha,
body,
});
console.log(`Commented on ${repoName}@${tagName}: ${template.title} (notified: ${mentions || 'none'})`);
} catch (err: any) {
console.error(`Failed to comment on ${repoName}@${tagName}: ${err.message}`);
}
}
if (!GRAPHQL_TOKEN) {
console.error('Error: GRAPHQL_TOKEN environment variable is not set.');
process.exit(1);
}
const client = new GraphQLClient('https://api.github.com/graphql', {
headers: {
authorization: `Bearer ${GRAPHQL_TOKEN}`,
},
});
// Cache for sourceUrl stars to avoid duplicate queries
const sourceStarsCache = new Map<string, number>();
const makeRepositoryQuery = (name: string) => gql`
{
repository(owner: "KernelSU-Modules-Repo", name: "${name}") {
name
description
url
homepageUrl
collaborators(affiliation: DIRECT, first: 100) {
edges {
node {
login
name
}
}
}
readme: object(expression: "HEAD:README.md") {
... on Blob {
text
}
}
moduleJson: object(expression: "HEAD:module.json") {
... on Blob {
text
}
}
latestRelease {
name
url
immutable
isDraft
description
descriptionHTML
createdAt
publishedAt
updatedAt
tagName
isPrerelease
releaseAssets(first: 50) {
edges {
node {
name
contentType
downloadUrl
downloadCount
size
}
}
}
}
releases(first: 20) {
edges {
node {
name
url
immutable
isDraft
description
descriptionHTML
createdAt
publishedAt
updatedAt
tagName
isPrerelease
isLatest
releaseAssets(first: 50) {
edges {
node {
name
contentType
downloadUrl
downloadCount
size
}
}
}
}
}
}
updatedAt
createdAt
stargazerCount
}
}
`;
// Generic repository query for arbitrary owner/name
const makeAnyRepositoryQuery = (owner: string, name: string) => gql`
{
repository(owner: "${owner}", name: "${name}") {
stargazerCount
}
}
`;
function parseGitHubRepoFromUrl(sourceUrl: string): { owner: string; name: string } | null {
try {
const u = new URL(sourceUrl);
if (u.hostname !== 'github.com') return null;
const parts = u.pathname.split('/').filter(Boolean);
if (parts.length < 2) return null;
const owner = parts[0];
let name = parts[1];
if (name.endsWith('.git')) name = name.slice(0, -4);
return { owner, name };
} catch {
return null;
}
}
async function getStarsFromSourceUrl(sourceUrl: string): Promise<number | null> {
const parsed = parseGitHubRepoFromUrl(sourceUrl);
if (!parsed) return null;
const key = `${parsed.owner}/${parsed.name}`;
if (sourceStarsCache.has(key)) return sourceStarsCache.get(key)!;
try {
const result: any = await client.request(makeAnyRepositoryQuery(parsed.owner, parsed.name));
const stars: number | null = result?.repository?.stargazerCount ?? null;
if (typeof stars === 'number') {
sourceStarsCache.set(key, stars);
return stars;
}
return null;
} catch {
return null;
}
}
const makeRepositoriesQuery = (cursor: string | null) => {
const arg = cursor ? `, after: "${cursor}"` : '';
return gql`
{
organization(login: "KernelSU-Modules-Repo") {
repositories(first: ${PAGINATION}${arg}, orderBy: {field: UPDATED_AT, direction: DESC}, privacy: PUBLIC) {
edges {
node {
name
description
url
homepageUrl
collaborators(affiliation: DIRECT, first: 100) {
edges {
node {
login
name
}
}
}
readme: object(expression: "HEAD:README.md") {
... on Blob {
text
}
}
moduleJson: object(expression: "HEAD:module.json") {
... on Blob {
text
}
}
latestRelease {
name
url
immutable
isDraft
description
descriptionHTML
createdAt
publishedAt
updatedAt
tagName
isPrerelease
releaseAssets(first: 50) {
edges {
node {
name
contentType
downloadUrl
downloadCount
size
}
}
}
}
releases(first: 20) {
edges {
node {
name
url
immutable
isDraft
description
descriptionHTML
createdAt
publishedAt
updatedAt
tagName
isPrerelease
isLatest
releaseAssets(first: 50) {
edges {
node {
name
contentType
downloadUrl
downloadCount
size
}
}
}
}
}
}
updatedAt
createdAt
stargazerCount
}
cursor
}
pageInfo {
hasNextPage
endCursor
}
totalCount
}
}
}`;
};
const REGEX_PUBLIC_IMAGES = /https:\/\/github\.com\/[a-zA-Z0-9-]+\/[\w\-.]+\/assets\/\d+\/([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})/g;
function replacePrivateImage(markdown: string, html: string): string {
if (!markdown) return html;
const publicMatches = new Map<string, string>();
for (const match of markdown.matchAll(REGEX_PUBLIC_IMAGES)) {
publicMatches.set(match[0], match[1]);
}
for (const [url, id] of publicMatches) {
const regexPrivateImages = new RegExp(`https:\\/\\/private-user-images\\.githubusercontent\\.com\\/\\d+\\/\\d+-${id}\\..*?(?=")`, 'g');
html = html.replaceAll(regexPrivateImages, url);
}
return html;
}
async function extractModulePropsFromZip(downloadUrl: string): Promise<Record<string, string>> {
const maxRetries = 3;
let lastError: any;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
// Extract module.prop content from zip URL (internal network, stable)
const { stdout: modulePropContent } = await execAsync(`runzip -p "${downloadUrl}" module.prop`, {
encoding: 'utf8',
maxBuffer: 64 * 1024 // 64KB buffer
});
// Check if content is empty or only whitespace - treat as failure and retry
if (!modulePropContent || !modulePropContent.trim()) {
throw new Error(`Empty content returned from runzip for URL: ${downloadUrl}`);
}
// Parse module.prop content
const props: Record<string, string> = {};
const lines = modulePropContent.split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eqIndex = trimmed.indexOf('=');
if (eqIndex > 0) {
const key = trimmed.substring(0, eqIndex).trim();
const value = trimmed.substring(eqIndex + 1).trim();
props[key] = value;
}
}
return props;
} catch (err: any) {
lastError = err;
if (attempt < maxRetries) {
console.warn(`Failed to extract props from ${downloadUrl} (attempt ${attempt}/${maxRetries}): ${err.message}, retrying...`);
// Add exponential backoff delay (1s, 2s) before retrying to handle transient issues
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
} else {
console.error(`Failed to extract props from ${downloadUrl} after ${maxRetries} attempts: ${err.message}`);
}
}
}
return {};
}
const RESERVED_NAMES = ['.github', 'submission', 'developers', 'modules', 'org.kernelsu.example', "module_release"];
async function convert2json(repo: GraphQlRepository): Promise<ConvertResult> {
// Check reserved names first
if (RESERVED_NAMES.includes(repo.name)) {
const msg = `Skipped ${repo.name}: reserved name`;
console.log(msg);
return {
success: false,
skipInfo: {
reason: SkipReason.RESERVED_NAME,
message: msg,
shouldNotify: true, // Module-level error, always notify
},
};
}
// Check name format
if (!repo.name.match(/^[a-zA-Z][a-zA-Z0-9._-]+$/)) {
const msg = `Skipped ${repo.name}: invalid name format (must match ^[a-zA-Z][a-zA-Z0-9._-]+$)`;
console.log(msg);
return {
success: false,
skipInfo: {
reason: SkipReason.INVALID_NAME,
message: msg,
details: { repoName: repo.name },
shouldNotify: true, // Module-level error, always notify
},
};
}
// Check description
if (!repo.description) {
const msg = `Skipped ${repo.name}: missing repository description`;
console.log(msg);
return {
success: false,
skipInfo: {
reason: SkipReason.NO_DESCRIPTION,
message: msg,
shouldNotify: true, // Module-level error, always notify
},
};
}
// Merge latestRelease into releases if not present
if (repo.latestRelease && !repo.releases.edges.find(r => r.node.tagName === repo.latestRelease?.tagName)) {
repo.releases.edges.push({ node: repo.latestRelease });
}
// Supported zip content types
const ZIP_CONTENT_TYPES = ['application/zip', 'application/x-zip-compressed'];
const isZipAsset = (contentType: string) => ZIP_CONTENT_TYPES.includes(contentType);
// Filter releases first
const filteredReleases = repo.releases.edges.filter(({ node }) =>
!node.isDraft &&
node.immutable &&
node.releaseAssets?.edges.some(({ node: asset }) => isZipAsset(asset.contentType))
);
// Track release-level skip reasons for reporting
const releaseSkipReasons: Array<{ tagName: string; reason: SkipReason; details?: Record<string, any> }> = [];
// Transform releases and extract version info from zip files concurrently
const startTime = Date.now();
const releasesResults = await pMap(
filteredReleases,
async ({ node }) => {
const zipAsset = node.releaseAssets.edges.find(({ node: asset }) => isZipAsset(asset.contentType));
if (!zipAsset) {
console.log(`Skipped release ${node.tagName} (${repo.name}): no zip asset found`);
releaseSkipReasons.push({ tagName: node.tagName, reason: SkipReason.NO_ZIP_ASSET });
return null;
}
const moduleProps = await extractModulePropsFromZip(zipAsset.node.downloadUrl);
// Check if module.prop exists (empty props means extraction failed)
if (Object.keys(moduleProps).length === 0) {
console.log(`Skipped release ${node.tagName} (${repo.name}): failed to read module.prop`);
releaseSkipReasons.push({ tagName: node.tagName, reason: SkipReason.MISSING_MODULE_PROP });
return null;
}
// Skip release if id doesn't match repository name
if (moduleProps.id !== repo.name) {
console.log(`Skipped release ${node.tagName} (${repo.name}): module.prop id (${moduleProps.id}) does not match repo name`);
releaseSkipReasons.push({
tagName: node.tagName,
reason: SkipReason.MODULE_ID_MISMATCH,
details: { repoName: repo.name, moduleId: moduleProps.id },
});
return null;
}
// Skip release if version or versionCode is missing
if (!moduleProps.version || !moduleProps.versionCode) {
console.log(`Skipped release ${node.tagName} (${repo.name}): missing version (${moduleProps.version}) or versionCode (${moduleProps.versionCode})`);
releaseSkipReasons.push({
tagName: node.tagName,
reason: SkipReason.MISSING_VERSION,
details: { version: moduleProps.version, versionCode: moduleProps.versionCode },
});
return null;
}
return {
name: node.name,
url: node.url,
descriptionHTML: replacePrivateImage(node.description, node.descriptionHTML),
createdAt: node.createdAt,
publishedAt: node.publishedAt,
updatedAt: node.updatedAt,
tagName: node.tagName,
isPrerelease: node.isPrerelease,
releaseAssets: node.releaseAssets.edges.map(({ node: asset }) => ({
name: asset.name,
contentType: asset.contentType,
downloadUrl: asset.downloadUrl,
downloadCount: asset.downloadCount,
size: asset.size,
})),
version: moduleProps.version,
versionCode: moduleProps.versionCode,
};
},
100 // 100 concurrent downloads per repository
);
const elapsed = ((Date.now() - startTime) / 1000).toFixed(2);
if (filteredReleases.length > 0) {
console.log(`Processed ${filteredReleases.length} releases for ${repo.name} in ${elapsed}s`);
}
// Filter out null results
const releases = releasesResults.filter((r): r is ModuleRelease => r !== null);
// Check if we have any valid releases
if (releases.length === 0) {
// Determine the most relevant skip reason
let skipInfo: SkipInfo;
if (filteredReleases.length === 0) {
// No releases passed initial filter (draft/immutable/zip check)
const msg = `Skipped ${repo.name}: no valid releases (requires non-draft, immutable, with zip asset)`;
console.log(msg);
skipInfo = {
reason: SkipReason.NO_VALID_RELEASES,
message: msg,
shouldNotify: true, // No releases at all, notify
};
} else if (releaseSkipReasons.length > 0) {
// Only notify if the latest release has issues
const latestReleaseTag = repo.latestRelease?.tagName;
const latestSkip = latestReleaseTag
? releaseSkipReasons.find(r => r.tagName === latestReleaseTag)
: null;
if (latestSkip) {
// Latest release has issues - notify with specific reason
const msg = `Skipped ${repo.name}: ${latestSkip.reason} (latest release: ${latestSkip.tagName})`;
console.log(msg);
skipInfo = {
reason: latestSkip.reason,
message: msg,
details: latestSkip.details,
shouldNotify: true, // Latest release has issues, notify
tagName: latestSkip.tagName, // For commenting on the release
};
} else {
// Latest release is not the problematic one - only older releases have issues
const msg = `Skipped ${repo.name}: no valid releases (older releases have issues)`;
console.log(msg);
skipInfo = {
reason: SkipReason.NO_VALID_RELEASES,
message: msg,
shouldNotify: false, // Don't notify - only older releases have issues
};
}
} else {
const msg = `Skipped ${repo.name}: no valid releases`;
console.log(msg);
skipInfo = {
reason: SkipReason.NO_VALID_RELEASES,
message: msg,
shouldNotify: true, // No releases, notify
};
}
return { success: false, skipInfo };
}
console.log(`Found module ${repo.name}`);
// Find latest releases by type
const latestRelease = releases.find(v => !v.isPrerelease);
const latestBetaRelease = releases.find(v => v.isPrerelease && !v.name.match(/^(snapshot|nightly).*/i)) || latestRelease;
const latestSnapshotRelease = releases.find(v => v.isPrerelease && v.name.match(/^(snapshot|nightly).*/i)) || latestBetaRelease;
// Generate README HTML
const readmeText = repo.readme?.text?.trim() || null;
const readmeHTML = readmeText ? md.render(readmeText) : null;
// Parse module.json for additional metadata
let summary: string | null = null;
let sourceUrl: string | null = null;
let additionalAuthors: Array<{ type?: string; name: string; link?: string }> = [];
let metamodule = false;
if (repo.moduleJson) {
try {
const moduleData = JSON.parse(repo.moduleJson.text);
if (moduleData.summary && typeof moduleData.summary === 'string') {
summary = ellipsize(moduleData.summary.trim(), 512).trim();
}
if (moduleData.sourceUrl && typeof moduleData.sourceUrl === 'string') {
sourceUrl = moduleData.sourceUrl.replace(/[\r\n]/g, '').trim();
}
if (moduleData.additionalAuthors instanceof Array) {
additionalAuthors = moduleData.additionalAuthors.filter((a: any) => a && typeof a === 'object');
}
if (moduleData.metamodule === true) {
metamodule = true;
}
} catch (e: any) {
console.log(`Failed to parse module.json for ${repo.name}: ${e.message}`);
}
}
// Build authors list
const collaborators = repo.collaborators.edges.map(({ node }) => ({
name: node.name || node.login,
login: node.login,
}));
const authorsToRemove = new Set(
additionalAuthors.filter(a => a.type === 'remove').map(a => a.name)
);
let authors = collaborators
.filter(c => !authorsToRemove.has(c.name) && !authorsToRemove.has(c.login))
.map(c => ({ name: c.name, link: `https://github.com/${c.login}` }));
const existingNames = new Set(authors.map(a => a.name));
for (const author of additionalAuthors.filter(a => a.type === 'add' || !a.type)) {
if (!existingNames.has(author.name)) {
authors.push({ name: author.name, link: author.link || '' });
existingNames.add(author.name);
}
}
return {
success: true,
module: {
moduleId: repo.name,
moduleName: repo.description,
url: repo.url,
homepageUrl: repo.homepageUrl || null,
authors,
latestRelease: latestRelease?.name || null,
latestReleaseTime: latestRelease?.publishedAt || '1970-01-01T00:00:00Z',
latestBetaReleaseTime: latestBetaRelease?.publishedAt || '1970-01-01T00:00:00Z',
latestSnapshotReleaseTime: latestSnapshotRelease?.publishedAt || '1970-01-01T00:00:00Z',
releases,
readme: readmeText,
readmeHTML,
summary,
sourceUrl,
updatedAt: repo.updatedAt,
createdAt: repo.createdAt,
stargazerCount: await (async () => {
if (sourceUrl) {
const sourceStars = await getStarsFromSourceUrl(sourceUrl);
if (typeof sourceStars === 'number') {
return Math.max(repo.stargazerCount, sourceStars);
}
}
return repo.stargazerCount;
})(),
metamodule,
},
};
}
async function main() {
const cacheDir = path.resolve('.data-cache');
const graphqlCachePath = path.join(cacheDir, 'graphql.json');
const modulesCachePath = path.join(cacheDir, 'modules.json');
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir, { recursive: true });
}
const modulePackage = process.env.REPO
? process.env.REPO.includes('/') ? process.env.REPO.split('/')[1] : process.env.REPO
: null;
let mergedRepositories: GraphQlRepositoryWrapped[] = [];
if (modulePackage && fs.existsSync(modulesCachePath)) {
// Incremental update: fetch single module
console.log(`Querying GitHub API for module ${modulePackage}`);
const result: any = await client.request(makeRepositoryQuery(modulePackage));
if (!result.repository) {
console.error('Repository not found');
return;
}
const convertResult = await convert2json(result.repository);
if (!convertResult.success) {
// Comment on the release tag for validation error (only if shouldNotify is true and has tagName)
if (convertResult.skipInfo.shouldNotify && convertResult.skipInfo.tagName) {
console.log(`Module validation failed, commenting on release ${convertResult.skipInfo.tagName}...`);
await commentOnRelease(modulePackage, convertResult.skipInfo.tagName, convertResult.skipInfo);
} else if (convertResult.skipInfo.shouldNotify) {
console.log(`Module validation failed (module-level error, no specific release to comment on)`);
} else {
console.log(`Module validation failed, but not notifying (older releases have issues, not latest)`);
}
console.error(`Incremental build failed: ${convertResult.skipInfo.message}`);
process.exit(1);
}
// Load existing modules and update
let modules: ModuleJson[] = JSON.parse(fs.readFileSync(modulesCachePath, 'utf-8'));
modules = modules.filter(m => m.moduleId !== modulePackage);
modules.unshift(convertResult.module);
// Sort by latest release time
modules.sort((a, b) => {
const aTime = Math.max(
Date.parse(a.latestReleaseTime),
Date.parse(a.latestBetaReleaseTime),
Date.parse(a.latestSnapshotReleaseTime)
);
const bTime = Math.max(
Date.parse(b.latestReleaseTime),
Date.parse(b.latestBetaReleaseTime),
Date.parse(b.latestSnapshotReleaseTime)
);
return bTime - aTime;
});
fs.writeFileSync(modulesCachePath, JSON.stringify(modules));
console.log(`Updated module ${modulePackage}`);
} else {
// Full fetch: get all repositories
let cursor: string | null = null;
let page = 1;
let total = 0;
while (true) {
console.log(`Querying GitHub API, page ${page}, total ${Math.ceil(total / PAGINATION) || 'unknown'}, cursor: ${cursor}`);
const result: any = await client.request(makeRepositoriesQuery(cursor));
mergedRepositories = mergedRepositories.concat(result.organization.repositories.edges);
if (!result.organization.repositories.pageInfo.hasNextPage) break;
cursor = result.organization.repositories.pageInfo.endCursor;
total = result.organization.repositories.totalCount;
page++;
}
// Save raw GraphQL response for incremental updates
fs.writeFileSync(graphqlCachePath, JSON.stringify({ repositories: mergedRepositories }, null, 2));
// Convert to modules with concurrency control
console.log(`Processing ${mergedRepositories.length} repositories...`);
const overallStartTime = Date.now();
const modulesResults = await pMap(
mergedRepositories,
async ({ node }, index) => {
console.log(`[${index + 1}/${mergedRepositories.length}] Processing ${node.name}...`);
return await convert2json(node);
},
20 // 20 concurrent repositories
);
const totalElapsed = ((Date.now() - overallStartTime) / 1000).toFixed(2);
console.log(`Completed processing all repositories in ${totalElapsed}s`);
// Filter successful results and extract modules
const modules = modulesResults
.filter((r): r is { success: true; module: ModuleJson } => r.success)
.map(r => r.module);
// Sort by latest release time
modules.sort((a, b) => {
const aTime = Math.max(
Date.parse(a.latestReleaseTime),