@stats-organization/github-readme-stats-core 2.1.5 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/build/api/gist.d.ts +2 -7
  2. package/build/api/gist.d.ts.map +1 -1
  3. package/build/api/gist.js +9 -41
  4. package/build/api/index.d.ts +3 -8
  5. package/build/api/index.d.ts.map +1 -1
  6. package/build/api/index.js +23 -45
  7. package/build/api/pin.d.ts +2 -7
  8. package/build/api/pin.d.ts.map +1 -1
  9. package/build/api/pin.js +9 -41
  10. package/build/api/top-langs.d.ts +2 -7
  11. package/build/api/top-langs.d.ts.map +1 -1
  12. package/build/api/top-langs.js +11 -55
  13. package/build/api/wakatime.d.ts +2 -7
  14. package/build/api/wakatime.d.ts.map +1 -1
  15. package/build/api/wakatime.js +9 -41
  16. package/build/cards/common-options.d.ts +13 -0
  17. package/build/cards/common-options.d.ts.map +1 -0
  18. package/build/cards/common-options.js +1 -0
  19. package/build/cards/gist.d.ts +11 -16
  20. package/build/cards/gist.d.ts.map +1 -1
  21. package/build/cards/gist.js +26 -31
  22. package/build/cards/repo.d.ts +19 -16
  23. package/build/cards/repo.d.ts.map +1 -1
  24. package/build/cards/repo.js +58 -60
  25. package/build/cards/stats.d.ts +29 -46
  26. package/build/cards/stats.d.ts.map +1 -1
  27. package/build/cards/stats.js +113 -181
  28. package/build/cards/top-languages.d.ts +81 -77
  29. package/build/cards/top-languages.d.ts.map +1 -1
  30. package/build/cards/top-languages.js +174 -200
  31. package/build/cards/wakatime.d.ts +21 -11
  32. package/build/cards/wakatime.d.ts.map +1 -1
  33. package/build/cards/wakatime.js +73 -111
  34. package/build/common/Card.d.ts +34 -13
  35. package/build/common/Card.d.ts.map +1 -1
  36. package/build/common/Card.js +73 -40
  37. package/build/common/I18n.d.ts +4 -2
  38. package/build/common/I18n.d.ts.map +1 -1
  39. package/build/common/color.d.ts +60 -18
  40. package/build/common/color.d.ts.map +1 -1
  41. package/build/common/color.js +102 -5
  42. package/build/common/config.d.ts +2 -1
  43. package/build/common/config.d.ts.map +1 -1
  44. package/build/common/config.js +16 -26
  45. package/build/common/constants.d.ts +2 -1
  46. package/build/common/constants.d.ts.map +1 -1
  47. package/build/common/date.d.ts +37 -0
  48. package/build/common/date.d.ts.map +1 -0
  49. package/build/common/date.js +31 -0
  50. package/build/common/http.d.ts +25 -2
  51. package/build/common/http.d.ts.map +1 -1
  52. package/build/common/http.js +26 -3
  53. package/build/common/icons.d.ts +1 -0
  54. package/build/common/icons.d.ts.map +1 -1
  55. package/build/common/icons.js +1 -0
  56. package/build/common/languageColors.d.ts +11 -0
  57. package/build/common/languageColors.d.ts.map +1 -0
  58. package/build/common/languageColors.js +15 -0
  59. package/build/common/languageColors.json +1 -0
  60. package/build/common/ops.d.ts +3 -10
  61. package/build/common/ops.d.ts.map +1 -1
  62. package/build/common/ops.js +3 -15
  63. package/build/common/render.d.ts +43 -6
  64. package/build/common/render.d.ts.map +1 -1
  65. package/build/common/render.js +77 -11
  66. package/build/common/retryer.d.ts +3 -2
  67. package/build/common/retryer.d.ts.map +1 -1
  68. package/build/common/retryer.js +1 -0
  69. package/build/fetchers/gist.d.ts.map +1 -1
  70. package/build/fetchers/gist.js +8 -39
  71. package/build/fetchers/repo.d.ts +12 -11
  72. package/build/fetchers/repo.d.ts.map +1 -1
  73. package/build/fetchers/repo.js +26 -67
  74. package/build/fetchers/stats.d.ts +24 -17
  75. package/build/fetchers/stats.d.ts.map +1 -1
  76. package/build/fetchers/stats.js +302 -183
  77. package/build/fetchers/top-languages.d.ts +10 -15
  78. package/build/fetchers/top-languages.d.ts.map +1 -1
  79. package/build/fetchers/top-languages.js +52 -103
  80. package/build/fetchers/types.d.ts +24 -20
  81. package/build/fetchers/types.d.ts.map +1 -1
  82. package/build/fetchers/wakatime.d.ts +9 -5
  83. package/build/fetchers/wakatime.d.ts.map +1 -1
  84. package/build/fetchers/wakatime.js +8 -4
  85. package/build/graphql/contributionsDocument.d.ts +18 -0
  86. package/build/graphql/contributionsDocument.d.ts.map +1 -0
  87. package/build/graphql/contributionsDocument.js +30 -0
  88. package/build/graphql/generated/common.d.ts +42 -0
  89. package/build/graphql/generated/common.d.ts.map +1 -0
  90. package/build/graphql/generated/common.js +2 -0
  91. package/build/graphql/generated/gist.d.ts +44 -0
  92. package/build/graphql/generated/gist.d.ts.map +1 -0
  93. package/build/graphql/generated/gist.js +27 -0
  94. package/build/graphql/generated/repo.d.ts +67 -0
  95. package/build/graphql/generated/repo.d.ts.map +1 -0
  96. package/build/graphql/generated/repo.js +30 -0
  97. package/build/graphql/generated/stats.d.ts +150 -0
  98. package/build/graphql/generated/stats.d.ts.map +1 -0
  99. package/build/graphql/generated/stats.js +95 -0
  100. package/build/graphql/generated/top-languages.d.ts +54 -0
  101. package/build/graphql/generated/top-languages.d.ts.map +1 -0
  102. package/build/graphql/generated/top-languages.js +27 -0
  103. package/build/graphql/graphqlDocument.d.ts +22 -0
  104. package/build/graphql/graphqlDocument.d.ts.map +1 -0
  105. package/build/graphql/graphqlDocument.js +8 -0
  106. package/build/graphql/reposContributedToDocument.d.ts +27 -0
  107. package/build/graphql/reposContributedToDocument.d.ts.map +1 -0
  108. package/build/graphql/reposContributedToDocument.js +59 -0
  109. package/build/index.d.ts +3 -1
  110. package/build/index.d.ts.map +1 -1
  111. package/build/index.js +2 -1
  112. package/build/themes/index.d.ts +32 -0
  113. package/build/themes/index.d.ts.map +1 -1
  114. package/build/themes/index.js +28 -0
  115. package/build/translations.d.ts +17 -0
  116. package/build/translations.d.ts.map +1 -1
  117. package/build/translations.js +17 -0
  118. package/package.json +13 -7
  119. package/src/_github-username-regex.d.ts +4 -0
  120. package/src/api/gist.js +10 -46
  121. package/src/api/index.js +30 -51
  122. package/src/api/pin.js +10 -46
  123. package/src/api/top-langs.js +13 -60
  124. package/src/api/wakatime.js +10 -46
  125. package/src/cards/common-options.ts +13 -0
  126. package/src/cards/{gist.js → gist.ts} +37 -37
  127. package/src/cards/{repo.js → repo.ts} +86 -68
  128. package/src/cards/{stats.js → stats.ts} +168 -219
  129. package/src/cards/{top-languages.js → top-languages.ts} +309 -265
  130. package/src/cards/{wakatime.js → wakatime.ts} +136 -130
  131. package/src/common/Card.ts +94 -49
  132. package/src/common/I18n.ts +6 -2
  133. package/src/common/color.ts +163 -14
  134. package/src/common/config.ts +22 -29
  135. package/src/common/constants.ts +3 -1
  136. package/src/common/date.ts +45 -0
  137. package/src/common/http.ts +43 -3
  138. package/src/common/icons.ts +1 -0
  139. package/src/common/languageColors.json +1 -0
  140. package/src/common/languageColors.ts +19 -0
  141. package/src/common/ops.ts +8 -18
  142. package/src/common/render.ts +114 -14
  143. package/src/common/retryer.ts +6 -5
  144. package/src/fetchers/gist.ts +15 -72
  145. package/src/fetchers/repo.ts +114 -0
  146. package/src/fetchers/stats.ts +743 -0
  147. package/src/fetchers/top-languages.ts +135 -0
  148. package/src/fetchers/types.ts +28 -20
  149. package/src/fetchers/{wakatime.js → wakatime.ts} +19 -5
  150. package/src/graphql/contributionsDocument.ts +44 -0
  151. package/src/graphql/generated/common.ts +26 -0
  152. package/src/graphql/generated/gist.ts +59 -0
  153. package/src/graphql/generated/repo.ts +90 -0
  154. package/src/graphql/generated/stats.ts +194 -0
  155. package/src/graphql/generated/top-languages.ts +75 -0
  156. package/src/graphql/graphqlDocument.ts +25 -0
  157. package/src/graphql/queries/gist.graphql +25 -0
  158. package/src/graphql/queries/repo.graphql +28 -0
  159. package/src/graphql/queries/stats.graphql +120 -0
  160. package/src/graphql/queries/top-languages.graphql +34 -0
  161. package/src/graphql/reposContributedToDocument.ts +86 -0
  162. package/src/index.ts +3 -1
  163. package/src/themes/index.ts +33 -0
  164. package/src/translations.ts +17 -0
  165. package/src/cards/types.d.ts +0 -78
  166. package/src/fetchers/repo.js +0 -161
  167. package/src/fetchers/stats.js +0 -473
  168. package/src/fetchers/top-languages.js +0 -175
  169. package/src/themes/README.md +0 -229
@@ -0,0 +1,743 @@
1
+ import axios from "axios";
2
+ import type { AxiosResponse } from "axios";
3
+ import githubUsernameRegex from "github-username-regex";
4
+
5
+ import { calculateRank } from "../calculateRank.js";
6
+ import { getConfig } from "../common/config.js";
7
+ import { getGitHubYearRange, toGitHubDateTime } from "../common/date.js";
8
+ import { CustomError, MissingParamError } from "../common/error.js";
9
+ import { wrapTextMultiline } from "../common/fmt.js";
10
+ import { createGraphQLFetcher } from "../common/http.js";
11
+ import type { GraphQLResponse } from "../common/http.js";
12
+ import { logger } from "../common/log.js";
13
+ import { buildSearchFilter, parseOwnerAffiliations } from "../common/ops.js";
14
+ import { retryer } from "../common/retryer.js";
15
+ import { buildContributionsDocument } from "../graphql/contributionsDocument.js";
16
+ import {
17
+ UserInfoDocument,
18
+ UserReposDocument,
19
+ } from "../graphql/generated/stats.js";
20
+ import type {
21
+ RepoNodeFragment,
22
+ UserInfoQuery,
23
+ UserInfoQueryVariables,
24
+ } from "../graphql/generated/stats.js";
25
+ import {
26
+ MAX_REPOSITORIES_LIMIT,
27
+ buildReposContributedToDocument,
28
+ } from "../graphql/reposContributedToDocument.js";
29
+
30
+ import type { RepoUserStats, StatsData } from "./types.js";
31
+
32
+ /** The subset of the stats response `statsFetcher` returns and threads on. */
33
+ type StatsFetcherResponse = Pick<
34
+ GraphQLResponse<UserInfoQuery>,
35
+ "data" | "statusText"
36
+ >;
37
+
38
+ const fetcher = createGraphQLFetcher(UserInfoDocument, "bearer");
39
+ /** Fetcher for the pages after the first, which only need `repositories`. */
40
+ const reposFetcher = createGraphQLFetcher(UserReposDocument, "bearer");
41
+
42
+ /**
43
+ * Fetch stats information for a given username.
44
+ *
45
+ * @param variables Fetcher variables.
46
+ * @param variables.username GitHub username.
47
+ * @param variables.includeMergedPullRequests Include merged pull requests.
48
+ * @param variables.includeDiscussions Include discussions.
49
+ * @param variables.includeDiscussionsAnswers Include discussions answers.
50
+ * @param variables.startTime Time to start the count of total commits.
51
+ * @param variables.ownerAffiliations The owner affiliations to filter by. Default: OWNER.
52
+ * @param variables.includeUserRepositories Whether to include the user's own repositories in the repos contributed to.
53
+ * @param variables.pat PAT override or null.
54
+ * @returns The stats response, with every fetched page's repos merged in.
55
+ *
56
+ * @description Supports multi-page fetching when the `FETCH_MULTI_PAGE_STARS`
57
+ * env variable is `true` or a fetch limit.
58
+ */
59
+ const statsFetcher = async ({
60
+ username,
61
+ includeMergedPullRequests,
62
+ includeDiscussions,
63
+ includeDiscussionsAnswers,
64
+ startTime,
65
+ ownerAffiliations,
66
+ includeUserRepositories,
67
+ pat,
68
+ }: {
69
+ username: string;
70
+ includeMergedPullRequests: boolean;
71
+ includeDiscussions: boolean;
72
+ includeDiscussionsAnswers: boolean;
73
+ startTime: string | undefined;
74
+ ownerAffiliations: UserInfoQueryVariables["ownerAffiliations"];
75
+ includeUserRepositories: boolean;
76
+ pat: string | null;
77
+ }): Promise<StatsFetcherResponse> => {
78
+ // only the first request carries the stats themselves
79
+ let stats: StatsFetcherResponse = await retryer(
80
+ fetcher,
81
+ {
82
+ login: username,
83
+ after: null,
84
+ includeMergedPullRequests,
85
+ includeDiscussions,
86
+ includeDiscussionsAnswers,
87
+ startTime,
88
+ ownerAffiliations,
89
+ includeUserRepositories,
90
+ },
91
+ pat,
92
+ );
93
+ if (stats.data.errors) {
94
+ return stats;
95
+ }
96
+
97
+ const pageLimit = getConfig().fetchMultiPageStars;
98
+
99
+ const extraRepoNodes: Array<RepoNodeFragment | null> = [];
100
+ let pageRepositories = stats.data.data.user?.repositories;
101
+ let previousCursor: string | null = null;
102
+ let fetchedPages = 1;
103
+ while (
104
+ fetchedPages < pageLimit &&
105
+ // an unstarred repo on the page means the starred ones are exhausted
106
+ !pageRepositories?.nodes?.some((node) => node?.stargazerCount === 0) &&
107
+ pageRepositories?.pageInfo.hasNextPage
108
+ ) {
109
+ const after = pageRepositories.pageInfo.endCursor;
110
+ // a null or non-advancing cursor would refetch the same page forever
111
+ if (after === null || after === previousCursor) {
112
+ break;
113
+ }
114
+ previousCursor = after;
115
+
116
+ const page = await retryer(
117
+ reposFetcher,
118
+ { login: username, after, ownerAffiliations },
119
+ pat,
120
+ );
121
+ if (page.data.errors) {
122
+ return {
123
+ data: { ...stats.data, errors: page.data.errors },
124
+ statusText: page.statusText,
125
+ };
126
+ }
127
+
128
+ pageRepositories = page.data.data.user?.repositories;
129
+ extraRepoNodes.push(...(pageRepositories?.nodes ?? []));
130
+ fetchedPages++;
131
+ }
132
+
133
+ if (extraRepoNodes.length > 0) {
134
+ // deep copy to avoid mutating the response cached by the frontend
135
+ stats = structuredClone({
136
+ data: stats.data,
137
+ statusText: stats.statusText,
138
+ });
139
+ stats.data.data.user?.repositories.nodes?.push(...extraRepoNodes);
140
+ }
141
+
142
+ return stats;
143
+ };
144
+
145
+ /**
146
+ * Fetch total items count using the REST search API.
147
+ *
148
+ * @param variables Fetcher variables.
149
+ * @param token GitHub token.
150
+ * @returns Axios response.
151
+ *
152
+ * @see https://developer.github.com/v3/search/#search-commits
153
+ */
154
+ const fetchTotalItems = (
155
+ variables: Record<string, unknown>,
156
+ token: string,
157
+ ): Promise<AxiosResponse> => {
158
+ const type = String(variables["type"]);
159
+ const filter = String(variables["filter"]);
160
+ const repo = variables["repo"] as Array<string> | string;
161
+ const owner = variables["owner"] as Array<string> | string;
162
+ return axios({
163
+ method: "get",
164
+ url:
165
+ `https://api.github.com/search/${type}?per_page=1&q=` +
166
+ buildSearchFilter(repo, owner).replaceAll(" ", "+") +
167
+ filter,
168
+ headers: {
169
+ "Content-Type": "application/json",
170
+ Accept: "application/vnd.github.cloak-preview",
171
+ Authorization: `token ${token}`,
172
+ },
173
+ });
174
+ };
175
+
176
+ /**
177
+ * Fetch a total count for a given username via the REST search API.
178
+ *
179
+ * @param username GitHub username.
180
+ * @returns Total count.
181
+ *
182
+ * The GraphQL API can't return this.
183
+ * @see https://github.com/anuraghazra/github-readme-stats/issues/92#issuecomment-661026467
184
+ * @see https://github.com/anuraghazra/github-readme-stats/pull/211
185
+ */
186
+ const totalItemsFetcher = async (
187
+ username: string,
188
+ repo: Array<string>,
189
+ owner: Array<string>,
190
+ type: string,
191
+ filter: string,
192
+ pat: string | null,
193
+ ): Promise<number> => {
194
+ if (!githubUsernameRegex.test(username)) {
195
+ logger.log("Invalid username provided.");
196
+ throw new Error("Invalid username provided.");
197
+ }
198
+
199
+ let res: AxiosResponse<{ total_count?: number }>;
200
+ try {
201
+ res = await retryer<{ total_count?: number }>(
202
+ fetchTotalItems,
203
+ { login: username, repo, owner, type, filter },
204
+ pat,
205
+ );
206
+ } catch (err) {
207
+ logger.log(err);
208
+ throw err;
209
+ }
210
+
211
+ const totalCount = res.data.total_count;
212
+ if (totalCount === undefined || isNaN(totalCount)) {
213
+ logger.error("GitHub error: " + JSON.stringify(res.data));
214
+ throw new CustomError(
215
+ "Could not fetch data from GitHub REST API.",
216
+ CustomError.GITHUB_REST_API_ERROR,
217
+ );
218
+ }
219
+ return totalCount;
220
+ };
221
+
222
+ const fetchRepoUserStats = async (
223
+ username: string,
224
+ repo: Array<string>,
225
+ owner: Array<string>,
226
+ include_prs_authored: boolean,
227
+ include_prs_commented: boolean,
228
+ include_prs_reviewed: boolean,
229
+ include_issues_authored: boolean,
230
+ include_issues_commented: boolean,
231
+ pat: string | null,
232
+ ): Promise<RepoUserStats> => {
233
+ const stats: RepoUserStats = {};
234
+ if (include_prs_authored) {
235
+ stats.totalPRsAuthored = await totalItemsFetcher(
236
+ username,
237
+ repo,
238
+ owner,
239
+ "issues",
240
+ `author:${username}+type:pr`,
241
+ pat,
242
+ );
243
+ }
244
+ if (include_prs_commented) {
245
+ stats.totalPRsCommented = await totalItemsFetcher(
246
+ username,
247
+ repo,
248
+ owner,
249
+ "issues",
250
+ `commenter:${username}+-author:${username}+type:pr`,
251
+ pat,
252
+ );
253
+ }
254
+ if (include_prs_reviewed) {
255
+ stats.totalPRsReviewed = await totalItemsFetcher(
256
+ username,
257
+ repo,
258
+ owner,
259
+ "issues",
260
+ `reviewed-by:${username}+-author:${username}+type:pr`,
261
+ pat,
262
+ );
263
+ }
264
+ if (include_issues_authored) {
265
+ stats.totalIssuesAuthored = await totalItemsFetcher(
266
+ username,
267
+ repo,
268
+ owner,
269
+ "issues",
270
+ `author:${username}+type:issue`,
271
+ pat,
272
+ );
273
+ }
274
+ if (include_issues_commented) {
275
+ stats.totalIssuesCommented = await totalItemsFetcher(
276
+ username,
277
+ repo,
278
+ owner,
279
+ "issues",
280
+ `commenter:${username}+-author:${username}+type:issue`,
281
+ pat,
282
+ );
283
+ }
284
+ return stats;
285
+ };
286
+
287
+ /**
288
+ * Turn a GraphQL `errors` payload into the error to throw.
289
+ *
290
+ * @param errors Errors from the response envelope.
291
+ * @param statusText HTTP status text, used as the error type when GitHub gave a message.
292
+ * @param fallback Message when GitHub gave none.
293
+ */
294
+ const graphqlError = (
295
+ errors: NonNullable<GraphQLResponse<unknown>["data"]["errors"]>,
296
+ statusText: string,
297
+ fallback: string,
298
+ ): CustomError => {
299
+ logger.error(errors);
300
+ const message = errors[0]?.message;
301
+ return message
302
+ ? new CustomError(wrapTextMultiline(message, 525, 12)[0] ?? "", statusText)
303
+ : new CustomError(fallback, CustomError.GRAPHQL_ERROR);
304
+ };
305
+
306
+ /**
307
+ * Fetch all-time contributions by building a single GraphQL query
308
+ * for all the given years.
309
+ *
310
+ * Whether private contributions are included depends on the user's profile settings:
311
+ * https://docs.github.com/en/account-and-profile/how-tos/contribution-settings/manage-visibility-settings-for-private-contributions-and-achievements#changing-the-visibility-of-your-private-contributions
312
+ */
313
+ const fetchTotalContributions = async (
314
+ username: string,
315
+ years: Array<number>,
316
+ pat: string | null = null,
317
+ ): Promise<number> => {
318
+ if (years.length === 0) {
319
+ return 0;
320
+ }
321
+
322
+ const contributionsFetcher = createGraphQLFetcher(
323
+ buildContributionsDocument(years),
324
+ "bearer",
325
+ );
326
+
327
+ const contribRes = await retryer(
328
+ contributionsFetcher,
329
+ { login: username },
330
+ pat,
331
+ );
332
+
333
+ if (contribRes.data.errors) {
334
+ throw graphqlError(
335
+ contribRes.data.errors,
336
+ contribRes.statusText,
337
+ "Something went wrong while trying to retrieve the contributions data using the GraphQL API.",
338
+ );
339
+ }
340
+
341
+ const user = contribRes.data.data.user;
342
+ if (!user) {
343
+ return 0;
344
+ }
345
+
346
+ let total = 0;
347
+ for (const year of years) {
348
+ const yearBlock = user[`year_${year}`];
349
+ if (yearBlock?.contributionCalendar.totalContributions) {
350
+ total += yearBlock.contributionCalendar.totalContributions;
351
+ }
352
+ }
353
+ return total;
354
+ };
355
+
356
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
357
+
358
+ /**
359
+ * Ranges per request.
360
+ * Each costs roughly `4 * MAX_REPOSITORIES_LIMIT` nodes,
361
+ * so an unchunked request for a heavily split account would breach GitHub's 500k node ceiling.
362
+ * GitHub can still reject a request of this size, in which case the chunk size is halved
363
+ * and the request retried; it is increased back up to this maximum after every success.
364
+ */
365
+ const MAX_RANGES_PER_REQUEST = 400;
366
+
367
+ const REPOS_CONTRIBUTED_TO_ERROR =
368
+ "Something went wrong while trying to retrieve the repository contributions data using the GraphQL API.";
369
+
370
+ /** GraphQL error type GitHub returns when a query exceeds its node/complexity budget. */
371
+ const RESOURCE_LIMITS_EXCEEDED = "RESOURCE_LIMITS_EXCEEDED";
372
+
373
+ /**
374
+ * Whether GitHub rejected the query for returning too many results.
375
+ *
376
+ * @see https://docs.github.com/en/graphql/overview/rate-limits-and-query-limits-for-the-graphql-api#other-resource-limits
377
+ *
378
+ * @param errors Errors from the response envelope.
379
+ * @returns True if the query has to be retried with fewer ranges.
380
+ */
381
+ const isResourceLimitsExceeded = (
382
+ errors: NonNullable<GraphQLResponse<unknown>["data"]["errors"]>,
383
+ ): boolean => errors.some((error) => error.type === RESOURCE_LIMITS_EXCEEDED);
384
+
385
+ /**
386
+ * Count the repositories a user contributed to across every contribution year.
387
+ *
388
+ * `repositoriesContributedTo` spans at most one year,
389
+ * so every year is fetched as an aliased `contributionsCollection(from, to)` in one request and the repos de-duplicated.
390
+ * Ranges are worked off a queue, multiple ranges at a time.
391
+ * A range returning `MAX_REPOSITORIES_LIMIT` results may have more,
392
+ * so it is halved and both halves are queued again.
393
+ * When GitHub rejects a request with `RESOURCE_LIMITS_EXCEEDED` or a timeout,
394
+ * it is retried with half as many ranges.
395
+ * When GitHub rejects a request with an empty response, it is retried up to 3 times.
396
+ *
397
+ * Whether private contributions are included depends on the used PAT.
398
+ *
399
+ * @param canonicalUsername Username as GitHub reports it; `nameWithOwner` uses its
400
+ * casing, which the raw query-string username need not match.
401
+ * @param years Contribution years to walk.
402
+ * @param includeOwnRepos Whether to count the user's own repositories.
403
+ * @param pat Optional PAT override.
404
+ * @returns Count of repositories.
405
+ */
406
+ const fetchAllTimeReposContributedTo = async (
407
+ canonicalUsername: string,
408
+ years: Array<number>,
409
+ includeOwnRepos: boolean,
410
+ pat: string | null,
411
+ ): Promise<number> => {
412
+ const repos = new Set<string>();
413
+ const pending = years.map(getGitHubYearRange);
414
+ // halved when GitHub rejects a request for exceeding its resource limits, increases on success
415
+ let rangesPerRequest = MAX_RANGES_PER_REQUEST;
416
+ let emptyResponseRetries = 0;
417
+ const MAX_EMPTY_RESPONSE_RETRIES = 3;
418
+
419
+ while (pending.length > 0) {
420
+ const chunk = pending.slice(0, rangesPerRequest);
421
+ const fetcher = createGraphQLFetcher(
422
+ buildReposContributedToDocument(chunk, includeOwnRepos),
423
+ "bearer",
424
+ );
425
+ const res = await retryer(
426
+ fetcher,
427
+ { login: canonicalUsername, maxRepositories: MAX_REPOSITORIES_LIMIT },
428
+ pat,
429
+ );
430
+ if (res.status === 502 || res.status === 504) {
431
+ if (chunk.length > 1) {
432
+ rangesPerRequest = Math.floor(chunk.length / 2);
433
+ logger.log(
434
+ `Gateway timeout (${res.status}), retrying with ${rangesPerRequest} range(s) per request...`,
435
+ );
436
+ continue;
437
+ }
438
+ throw new CustomError(
439
+ REPOS_CONTRIBUTED_TO_ERROR,
440
+ CustomError.GRAPHQL_ERROR,
441
+ );
442
+ }
443
+ if (res.data.errors) {
444
+ if (isResourceLimitsExceeded(res.data.errors) && chunk.length > 1) {
445
+ rangesPerRequest = Math.floor(chunk.length / 2);
446
+ logger.log(
447
+ `Resource limits exceeded, retrying with ${rangesPerRequest} range(s) per request...`,
448
+ );
449
+ continue;
450
+ }
451
+ throw graphqlError(
452
+ res.data.errors,
453
+ res.statusText,
454
+ REPOS_CONTRIBUTED_TO_ERROR,
455
+ );
456
+ }
457
+ if (typeof res.data !== "object") {
458
+ if (emptyResponseRetries < MAX_EMPTY_RESPONSE_RETRIES) {
459
+ emptyResponseRetries++;
460
+ logger.log(
461
+ `Empty response from GitHub, retrying (${emptyResponseRetries}/${MAX_EMPTY_RESPONSE_RETRIES})...`,
462
+ );
463
+ continue;
464
+ }
465
+ throw new CustomError(
466
+ REPOS_CONTRIBUTED_TO_ERROR,
467
+ CustomError.GRAPHQL_ERROR,
468
+ );
469
+ }
470
+ emptyResponseRetries = 0;
471
+ const user = res.data.data.user;
472
+ if (!user) {
473
+ throw new CustomError(
474
+ REPOS_CONTRIBUTED_TO_ERROR,
475
+ CustomError.GRAPHQL_ERROR,
476
+ );
477
+ }
478
+
479
+ pending.splice(0, chunk.length);
480
+ rangesPerRequest = Math.min(
481
+ MAX_RANGES_PER_REQUEST,
482
+ Math.ceil(rangesPerRequest * 1.25),
483
+ );
484
+
485
+ for (const [index, range] of chunk.entries()) {
486
+ const rangeResponse = user[`range_${index}`];
487
+ if (!rangeResponse) {
488
+ throw new CustomError(
489
+ REPOS_CONTRIBUTED_TO_ERROR,
490
+ CustomError.GRAPHQL_ERROR,
491
+ );
492
+ }
493
+
494
+ const lists = [
495
+ rangeResponse.commitContributionsByRepository,
496
+ rangeResponse.issueContributionsByRepository,
497
+ rangeResponse.pullRequestContributionsByRepository,
498
+ (rangeResponse.repositoryContributions?.nodes ?? []).filter(
499
+ (node) => node !== null,
500
+ ),
501
+ ];
502
+ const isSaturated = lists.some(
503
+ (list) => list.length >= MAX_REPOSITORIES_LIMIT,
504
+ );
505
+
506
+ const rangeDays = Math.round(
507
+ (range.to.getTime() - range.from.getTime()) / MS_PER_DAY,
508
+ );
509
+ if (isSaturated && rangeDays >= 2) {
510
+ const mid = new Date(
511
+ range.from.getTime() + Math.floor(rangeDays / 2) * MS_PER_DAY,
512
+ );
513
+ logger.log(
514
+ `Range ${range.from.toISOString()} - ${range.to.toISOString()} is saturated, splitting and retrying...`,
515
+ );
516
+ // GitHub only reads the date portion,
517
+ // so the first half ends 1 second before `mid` to keep the halves from sharing a day
518
+ pending.push(
519
+ { from: range.from, to: new Date(mid.getTime() - 1000) },
520
+ { from: mid, to: range.to },
521
+ );
522
+ continue;
523
+ }
524
+ if (isSaturated) {
525
+ logger.log(
526
+ `Range ${range.from.toISOString()} - ${range.to.toISOString()} is saturated but cannot be split further.`,
527
+ );
528
+ }
529
+
530
+ for (const { repository } of lists.flat()) {
531
+ const name = repository.nameWithOwner;
532
+ if (includeOwnRepos || !name.startsWith(`${canonicalUsername}/`)) {
533
+ repos.add(name);
534
+ }
535
+ }
536
+ }
537
+ }
538
+
539
+ return repos.size;
540
+ };
541
+
542
+ /**
543
+ * Fetch stats for a given username.
544
+ *
545
+ * @param username GitHub username.
546
+ * @param include_all_commits Include all commits.
547
+ * @param exclude_repo Repositories to exclude.
548
+ * @param include_merged_pull_requests Include merged pull requests.
549
+ * @param include_discussions Include discussions.
550
+ * @param include_discussions_answers Include discussions answers.
551
+ * @param commits_year Year to count total commits.
552
+ * @param repo Repositories to scope the REST search to.
553
+ * @param owner Owners to scope the REST search to.
554
+ * @param include_prs_authored Include count of PRs authored.
555
+ * @param include_prs_commented Include count of PRs commented.
556
+ * @param include_prs_reviewed Include count of PRs reviewed.
557
+ * @param include_issues_authored Include count of issues authored.
558
+ * @param include_issues_commented Include count of issues commented.
559
+ * @param ownerAffiliations Owner affiliations. Default: OWNER.
560
+ * @param include_contributions Include all-time contributions.
561
+ * @param include_all_time_contribs Include all-time count of repos contributed to.
562
+ * @param contribs_include_own_repos Include user-owned repos in contributed-to counts.
563
+ * @param pat Optional PAT override.
564
+ * @returns Stats data.
565
+ */
566
+ const fetchStats = async (
567
+ username: string,
568
+ include_all_commits = false,
569
+ exclude_repo: Array<string> = [],
570
+ include_merged_pull_requests = false,
571
+ include_discussions = false,
572
+ include_discussions_answers = false,
573
+ commits_year?: number,
574
+ repo: Array<string> = [],
575
+ owner: Array<string> = [],
576
+ include_prs_authored = false,
577
+ include_prs_commented = false,
578
+ include_prs_reviewed = false,
579
+ include_issues_authored = false,
580
+ include_issues_commented = false,
581
+ ownerAffiliations: Array<string> = [],
582
+ include_contributions = false,
583
+ include_all_time_contribs = false,
584
+ contribs_include_own_repos = false,
585
+ pat: string | null = null,
586
+ ): Promise<StatsData> => {
587
+ if (!username) {
588
+ throw new MissingParamError(["username"]);
589
+ }
590
+
591
+ const stats: StatsData = {
592
+ name: "",
593
+ totalPRs: 0,
594
+ totalPRsMerged: 0,
595
+ mergedPRsPercentage: 0,
596
+ totalReviews: 0,
597
+ totalCommits: 0,
598
+ totalIssues: 0,
599
+ totalStars: 0,
600
+ totalDiscussionsStarted: 0,
601
+ totalDiscussionsAnswered: 0,
602
+ contributedTo: 0,
603
+ allTimeContributedTo: 0,
604
+ totalPRsAuthored: 0,
605
+ totalPRsCommented: 0,
606
+ totalPRsReviewed: 0,
607
+ totalIssuesAuthored: 0,
608
+ totalIssuesCommented: 0,
609
+ totalContributions: 0,
610
+ rank: { level: "C", percentile: 100 },
611
+ };
612
+ const affiliations = parseOwnerAffiliations(ownerAffiliations);
613
+
614
+ const res = await statsFetcher({
615
+ username,
616
+ includeMergedPullRequests: include_merged_pull_requests,
617
+ includeDiscussions: include_discussions,
618
+ includeDiscussionsAnswers: include_discussions_answers,
619
+ startTime:
620
+ commits_year === undefined
621
+ ? undefined
622
+ : toGitHubDateTime(getGitHubYearRange(commits_year).from),
623
+ ownerAffiliations: affiliations,
624
+ includeUserRepositories: contribs_include_own_repos,
625
+ pat,
626
+ });
627
+
628
+ // Catch GraphQL errors.
629
+ if (res.data.errors) {
630
+ logger.error(res.data.errors);
631
+ const firstError = res.data.errors[0];
632
+ if (firstError?.type === "NOT_FOUND") {
633
+ throw new CustomError(
634
+ firstError.message || "Could not fetch user.",
635
+ CustomError.USER_NOT_FOUND,
636
+ );
637
+ }
638
+ if (firstError?.message) {
639
+ throw new CustomError(
640
+ wrapTextMultiline(firstError.message, 525, 12)[0] ?? "",
641
+ res.statusText,
642
+ );
643
+ }
644
+ throw new CustomError(
645
+ "Something went wrong while trying to retrieve the stats data using the GraphQL API.",
646
+ CustomError.GRAPHQL_ERROR,
647
+ );
648
+ }
649
+
650
+ const user = res.data.data.user;
651
+ if (!user) {
652
+ throw new CustomError("Could not fetch user.", CustomError.USER_NOT_FOUND);
653
+ }
654
+
655
+ stats.name = user.name || user.login;
656
+
657
+ // if include_all_commits, fetch all commits using the REST API.
658
+ if (include_all_commits) {
659
+ stats.totalCommits = await totalItemsFetcher(
660
+ username,
661
+ repo,
662
+ owner,
663
+ "commits",
664
+ `author:${username}`,
665
+ pat,
666
+ );
667
+ } else {
668
+ stats.totalCommits = user.commits.totalCommitContributions;
669
+ }
670
+ const repoUserStats = await fetchRepoUserStats(
671
+ username,
672
+ repo,
673
+ owner,
674
+ include_prs_authored,
675
+ include_prs_commented,
676
+ include_prs_reviewed,
677
+ include_issues_authored,
678
+ include_issues_commented,
679
+ pat,
680
+ );
681
+ Object.assign(stats, repoUserStats);
682
+
683
+ stats.totalPRs = user.pullRequests.totalCount;
684
+ if (include_merged_pull_requests) {
685
+ const mergedCount = user.mergedPullRequests?.totalCount ?? 0;
686
+ stats.totalPRsMerged = mergedCount;
687
+ stats.mergedPRsPercentage =
688
+ (mergedCount / user.pullRequests.totalCount) * 100 || 0;
689
+ }
690
+ stats.totalReviews = user.reviews.totalPullRequestReviewContributions;
691
+ stats.totalIssues = user.openIssues.totalCount + user.closedIssues.totalCount;
692
+ if (include_discussions) {
693
+ stats.totalDiscussionsStarted = user.repositoryDiscussions?.totalCount ?? 0;
694
+ }
695
+ if (include_discussions_answers) {
696
+ stats.totalDiscussionsAnswered =
697
+ user.repositoryDiscussionComments?.totalCount ?? 0;
698
+ }
699
+ stats.contributedTo = user.repositoriesContributedTo.totalCount;
700
+
701
+ if (include_contributions) {
702
+ stats.totalContributions = await fetchTotalContributions(
703
+ username,
704
+ user.contributionsCollection.contributionYears,
705
+ pat,
706
+ );
707
+ }
708
+
709
+ if (include_all_time_contribs) {
710
+ stats.allTimeContributedTo = await fetchAllTimeReposContributedTo(
711
+ user.login,
712
+ user.contributionsCollection.contributionYears,
713
+ contribs_include_own_repos,
714
+ pat,
715
+ );
716
+ }
717
+
718
+ // Retrieve stars while filtering out repositories to be hidden.
719
+ const allExcludedRepos = [
720
+ ...exclude_repo,
721
+ ...getConfig().excludeRepositories,
722
+ ];
723
+ const repoToHide = new Set(allExcludedRepos);
724
+
725
+ stats.totalStars = (user.repositories.nodes ?? [])
726
+ .filter((data) => !!data && !repoToHide.has(data.name))
727
+ .reduce((prev, curr) => prev + (curr?.stargazerCount ?? 0), 0);
728
+
729
+ stats.rank = calculateRank({
730
+ all_commits: include_all_commits,
731
+ commits: stats.totalCommits,
732
+ prs: stats.totalPRs,
733
+ reviews: stats.totalReviews,
734
+ issues: stats.totalIssues,
735
+ repos: user.repositories.totalCount,
736
+ stars: stats.totalStars,
737
+ followers: user.followers.totalCount,
738
+ });
739
+
740
+ return stats;
741
+ };
742
+
743
+ export { fetchStats, fetchRepoUserStats };