@stats-forge/github-stats-forge-core 0.0.1

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