@stats-organization/github-readme-stats-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 (140) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/build/api/gist.d.ts +19 -0
  4. package/build/api/gist.d.ts.map +1 -0
  5. package/build/api/gist.js +77 -0
  6. package/build/api/index.d.ts +37 -0
  7. package/build/api/index.d.ts.map +1 -0
  8. package/build/api/index.js +115 -0
  9. package/build/api/pin.d.ts +27 -0
  10. package/build/api/pin.d.ts.map +1 -0
  11. package/build/api/pin.js +104 -0
  12. package/build/api/top-langs.d.ts +31 -0
  13. package/build/api/top-langs.d.ts.map +1 -0
  14. package/build/api/top-langs.js +121 -0
  15. package/build/api/wakatime.d.ts +28 -0
  16. package/build/api/wakatime.d.ts.map +1 -0
  17. package/build/api/wakatime.js +85 -0
  18. package/build/calculateRank.d.ts +28 -0
  19. package/build/calculateRank.d.ts.map +1 -0
  20. package/build/calculateRank.js +63 -0
  21. package/build/cards/gist.d.ts +21 -0
  22. package/build/cards/gist.d.ts.map +1 -0
  23. package/build/cards/gist.js +124 -0
  24. package/build/cards/repo.d.ts +21 -0
  25. package/build/cards/repo.d.ts.map +1 -0
  26. package/build/cards/repo.js +264 -0
  27. package/build/cards/stats.d.ts +49 -0
  28. package/build/cards/stats.d.ts.map +1 -0
  29. package/build/cards/stats.js +527 -0
  30. package/build/cards/top-languages.d.ts +143 -0
  31. package/build/cards/top-languages.d.ts.map +1 -0
  32. package/build/cards/top-languages.js +795 -0
  33. package/build/cards/wakatime.d.ts +16 -0
  34. package/build/cards/wakatime.d.ts.map +1 -0
  35. package/build/cards/wakatime.js +387 -0
  36. package/build/common/Card.d.ts +109 -0
  37. package/build/common/Card.d.ts.map +1 -0
  38. package/build/common/Card.js +241 -0
  39. package/build/common/I18n.d.ts +26 -0
  40. package/build/common/I18n.d.ts.map +1 -0
  41. package/build/common/I18n.js +34 -0
  42. package/build/common/color.d.ts +53 -0
  43. package/build/common/color.d.ts.map +1 -0
  44. package/build/common/color.js +92 -0
  45. package/build/common/config.d.ts +3 -0
  46. package/build/common/config.d.ts.map +1 -0
  47. package/build/common/config.js +69 -0
  48. package/build/common/constants.d.ts +6 -0
  49. package/build/common/constants.d.ts.map +1 -0
  50. package/build/common/constants.js +7 -0
  51. package/build/common/error.d.ts +53 -0
  52. package/build/common/error.d.ts.map +1 -0
  53. package/build/common/error.js +72 -0
  54. package/build/common/fmt.d.ts +27 -0
  55. package/build/common/fmt.d.ts.map +1 -0
  56. package/build/common/fmt.js +66 -0
  57. package/build/common/html.d.ts +10 -0
  58. package/build/common/html.d.ts.map +1 -0
  59. package/build/common/html.js +18 -0
  60. package/build/common/http.d.ts +9 -0
  61. package/build/common/http.d.ts.map +1 -0
  62. package/build/common/http.js +18 -0
  63. package/build/common/icons.d.ts +26 -0
  64. package/build/common/icons.d.ts.map +1 -0
  65. package/build/common/icons.js +77 -0
  66. package/build/common/languageColors.json +667 -0
  67. package/build/common/log.d.ts +9 -0
  68. package/build/common/log.d.ts.map +1 -0
  69. package/build/common/log.js +8 -0
  70. package/build/common/ops.d.ts +65 -0
  71. package/build/common/ops.d.ts.map +1 -0
  72. package/build/common/ops.js +137 -0
  73. package/build/common/render.d.ts +155 -0
  74. package/build/common/render.d.ts.map +1 -0
  75. package/build/common/render.js +361 -0
  76. package/build/common/retryer.d.ts +22 -0
  77. package/build/common/retryer.d.ts.map +1 -0
  78. package/build/common/retryer.js +86 -0
  79. package/build/fetchers/gist.d.ts +26 -0
  80. package/build/fetchers/gist.d.ts.map +1 -0
  81. package/build/fetchers/gist.js +99 -0
  82. package/build/fetchers/repo.d.ts +16 -0
  83. package/build/fetchers/repo.d.ts.map +1 -0
  84. package/build/fetchers/repo.js +116 -0
  85. package/build/fetchers/stats.d.ts +22 -0
  86. package/build/fetchers/stats.d.ts.map +1 -0
  87. package/build/fetchers/stats.js +339 -0
  88. package/build/fetchers/top-languages.d.ts +20 -0
  89. package/build/fetchers/top-languages.d.ts.map +1 -0
  90. package/build/fetchers/top-languages.js +139 -0
  91. package/build/fetchers/wakatime.d.ts +11 -0
  92. package/build/fetchers/wakatime.d.ts.map +1 -0
  93. package/build/fetchers/wakatime.js +25 -0
  94. package/build/index.d.ts +20 -0
  95. package/build/index.d.ts.map +1 -0
  96. package/build/index.js +19 -0
  97. package/build/themes/index.d.ts +469 -0
  98. package/build/themes/index.d.ts.map +1 -0
  99. package/build/themes/index.js +468 -0
  100. package/build/translations.d.ts +533 -0
  101. package/build/translations.d.ts.map +1 -0
  102. package/build/translations.js +1140 -0
  103. package/package.json +94 -0
  104. package/src/api/gist.js +99 -0
  105. package/src/api/index.js +185 -0
  106. package/src/api/pin.js +146 -0
  107. package/src/api/top-langs.js +168 -0
  108. package/src/api/wakatime.js +113 -0
  109. package/src/calculateRank.js +86 -0
  110. package/src/cards/gist.js +187 -0
  111. package/src/cards/repo.js +365 -0
  112. package/src/cards/stats.js +673 -0
  113. package/src/cards/top-languages.js +1023 -0
  114. package/src/cards/types.d.ts +78 -0
  115. package/src/cards/wakatime.js +471 -0
  116. package/src/common/Card.js +275 -0
  117. package/src/common/I18n.js +42 -0
  118. package/src/common/color.js +145 -0
  119. package/src/common/config.js +78 -0
  120. package/src/common/constants.js +9 -0
  121. package/src/common/error.js +90 -0
  122. package/src/common/fmt.js +80 -0
  123. package/src/common/html.js +22 -0
  124. package/src/common/http.js +21 -0
  125. package/src/common/icons.js +81 -0
  126. package/src/common/languageColors.json +667 -0
  127. package/src/common/log.ts +12 -0
  128. package/src/common/ops.js +172 -0
  129. package/src/common/render.js +442 -0
  130. package/src/common/retryer.js +104 -0
  131. package/src/fetchers/gist.js +114 -0
  132. package/src/fetchers/repo.js +165 -0
  133. package/src/fetchers/stats.js +478 -0
  134. package/src/fetchers/top-languages.js +177 -0
  135. package/src/fetchers/types.d.ts +128 -0
  136. package/src/fetchers/wakatime.js +37 -0
  137. package/src/index.ts +25 -0
  138. package/src/themes/README.md +229 -0
  139. package/src/themes/index.ts +476 -0
  140. package/src/translations.js +1156 -0
@@ -0,0 +1,361 @@
1
+ // @ts-check
2
+ import { getCardColors } from "./color.js";
3
+ import { SECONDARY_ERROR_MESSAGES, TRY_AGAIN_LATER } from "./error.js";
4
+ import { encodeHTML } from "./html.js";
5
+ import { clampValue } from "./ops.js";
6
+ /**
7
+ * Auto layout utility, allows us to layout things vertically or horizontally with
8
+ * proper gaping.
9
+ *
10
+ * @param {object} props Function properties.
11
+ * @param {string[]} props.items Array of items to layout.
12
+ * @param {number} props.gap Gap between items.
13
+ * @param {"column" | "row"=} props.direction Direction to layout items.
14
+ * @param {number[]=} props.sizes Array of sizes for each item.
15
+ * @returns {string[]} Array of items with proper layout.
16
+ */
17
+ const flexLayout = ({ items, gap, direction, sizes = [] }) => {
18
+ let lastSize = 0;
19
+ // filter() for filtering out empty strings
20
+ return items.filter(Boolean).map((item, i) => {
21
+ const size = sizes[i] || 0;
22
+ let transform = `translate(${lastSize}, 0)`;
23
+ if (direction === "column") {
24
+ transform = `translate(0, ${lastSize})`;
25
+ }
26
+ lastSize += size + gap;
27
+ return `<g transform="${transform}">${item}</g>`;
28
+ });
29
+ };
30
+ /**
31
+ * Creates a node to display the primary programming language of the repository/gist.
32
+ *
33
+ * @param {string} langName Language name.
34
+ * @param {string} langColor Language color.
35
+ * @returns {string} Language display SVG object.
36
+ */
37
+ const createLanguageNode = (langName, langColor) => {
38
+ return `
39
+ <g data-testid="primary-lang">
40
+ <circle data-testid="lang-color" cx="0" cy="-5" r="6" fill="${langColor}" />
41
+ <text data-testid="lang-name" class="gray" x="15">${langName}</text>
42
+ </g>
43
+ `;
44
+ };
45
+ /**
46
+ * Create a node to indicate progress in percentage along a horizontal line.
47
+ *
48
+ * @param {Object} params Object that contains the createProgressNode parameters.
49
+ * @param {number} params.x X-axis position.
50
+ * @param {number} params.y Y-axis position.
51
+ * @param {number} params.width Width of progress bar.
52
+ * @param {string} params.color Progress color.
53
+ * @param {number} params.progress Progress value.
54
+ * @param {string} params.progressBarBackgroundColor Progress bar bg color.
55
+ * @param {number} params.delay Delay before animation starts.
56
+ * @returns {string} Progress node.
57
+ */
58
+ const createProgressNode = ({ x, y, width, color, progress, progressBarBackgroundColor, delay, }) => {
59
+ const progressPercentage = clampValue(progress, 2, 100);
60
+ return `
61
+ <svg width="${width}" x="${x}" y="${y}">
62
+ <rect data-testid="progress-background" rx="5" ry="5" x="0" y="0" width="${width}" height="8" fill="${progressBarBackgroundColor}"></rect>
63
+ <svg data-testid="lang-progress" width="${progressPercentage}%">
64
+ <rect
65
+ height="8"
66
+ fill="${color}"
67
+ rx="5" ry="5" x="0" y="0"
68
+ class="lang-progress"
69
+ style="animation-delay: ${delay}ms;"
70
+ />
71
+ </svg>
72
+ </svg>
73
+ `;
74
+ };
75
+ /**
76
+ * Renders multi-line text via a `foreignObject` so the browser performs
77
+ * native, font-aware wrapping. Content overflowing `lineCount` lines is
78
+ * clipped (with an ellipsis on the last visible line) by CSS line-clamp.
79
+ *
80
+ * @param {object} props Function properties.
81
+ * @param {string} props.text Text to render (will be HTML-encoded).
82
+ * @param {number} props.x X position of the foreignObject.
83
+ * @param {number} props.y Y position of the foreignObject.
84
+ * @param {number} props.width Width of the wrap box.
85
+ * @param {number} props.height Height of the wrap box.
86
+ * @param {number} props.lineCount Maximum number of lines to display.
87
+ * @param {string} props.className CSS class applied to the inner element.
88
+ * @param {string=} props.testId Optional test id for the inner element.
89
+ * @returns {string} foreignObject SVG node.
90
+ */
91
+ const wrappedTextNode = ({ text, x, y, width, height, lineCount, className, testId, }) => {
92
+ const testIdAttr = testId ? ` data-testid="${testId}"` : "";
93
+ return `
94
+ <foreignObject x="${x}" y="${y}" width="${width}" height="${height}">
95
+ <div xmlns="http://www.w3.org/1999/xhtml" class="${className}" style="--lines: ${lineCount};"${testIdAttr}>${encodeHTML(text)}</div>
96
+ </foreignObject>
97
+ `;
98
+ };
99
+ /**
100
+ * CSS rules used to render multi-line text inside a `foreignObject`. Apply this
101
+ * to a CSS class (e.g. `.description`) shared with `wrappedTextNode` so the
102
+ * browser handles wrapping and the line count is taken from the `--lines`
103
+ * custom property set on the element.
104
+ *
105
+ * @param {string} color Text color (CSS `color` property).
106
+ * @returns {string} CSS rules block (without the surrounding selector).
107
+ */
108
+ const wrappedTextStyles = (color) => `
109
+ color: ${color};
110
+ margin: 0;
111
+ line-height: 1.2;
112
+ overflow-wrap: anywhere;
113
+ word-break: break-word;
114
+ display: -webkit-box;
115
+ -webkit-box-orient: vertical;
116
+ -webkit-line-clamp: var(--lines);
117
+ line-clamp: var(--lines);
118
+ overflow: hidden;
119
+ text-overflow: ellipsis;
120
+ padding-bottom: 0.15em;
121
+ `;
122
+ /**
123
+ * Creates an icon with label to display repository/gist stats like forks, stars, etc.
124
+ *
125
+ * @param {string} icon The icon to display.
126
+ * @param {number|string} label The label to display.
127
+ * @param {string} testid The testid to assign to the label.
128
+ * @param {number} iconSize The size of the icon.
129
+ * @returns {string} Icon with label SVG object.
130
+ */
131
+ const iconWithLabel = (icon, label, testid, iconSize) => {
132
+ if (typeof label === "number" && label <= 0) {
133
+ return "";
134
+ }
135
+ const iconSvg = `
136
+ <svg
137
+ class="icon"
138
+ y="-12"
139
+ viewBox="0 0 16 16"
140
+ version="1.1"
141
+ width="${iconSize}"
142
+ height="${iconSize}"
143
+ >
144
+ ${icon}
145
+ </svg>
146
+ `;
147
+ const text = `<text data-testid="${testid}" class="gray">${label}</text>`;
148
+ return flexLayout({ items: [iconSvg, text], gap: 20 }).join("");
149
+ };
150
+ // Script parameters.
151
+ const ERROR_CARD_LENGTH = 576.5;
152
+ const UPSTREAM_API_ERRORS = [
153
+ TRY_AGAIN_LATER,
154
+ SECONDARY_ERROR_MESSAGES.MAX_RETRY,
155
+ ];
156
+ /**
157
+ * Renders error message on the card.
158
+ *
159
+ * @param {object} args Function arguments.
160
+ * @param {string} args.message Main error message.
161
+ * @param {string} [args.secondaryMessage=""] The secondary error message.
162
+ * @param {object} [args.renderOptions={}] Render options.
163
+ * @param {string=} args.renderOptions.title_color Card title color.
164
+ * @param {string=} args.renderOptions.text_color Card text color.
165
+ * @param {string=} args.renderOptions.bg_color Card background color.
166
+ * @param {string=} args.renderOptions.border_color Card border color.
167
+ * @param {Parameters<typeof getCardColors>[0]["theme"]=} args.renderOptions.theme Card theme.
168
+ * @param {boolean=} args.renderOptions.show_repo_link Whether to show repo link or not.
169
+ * @returns {string} The SVG markup.
170
+ */
171
+ const renderError = ({ message, secondaryMessage = "", renderOptions = {}, }) => {
172
+ const { title_color, text_color, bg_color, border_color, theme = "default", show_repo_link = true, } = renderOptions;
173
+ // returns theme based colors with proper overrides and defaults
174
+ const { titleColor, textColor, bgColor, borderColor } = getCardColors({
175
+ title_color,
176
+ text_color,
177
+ icon_color: "",
178
+ bg_color,
179
+ border_color,
180
+ ring_color: "",
181
+ theme,
182
+ });
183
+ return `
184
+ <svg width="${ERROR_CARD_LENGTH}" height="120" viewBox="0 0 ${ERROR_CARD_LENGTH} 120" fill="${bgColor}" xmlns="http://www.w3.org/2000/svg">
185
+ <style>
186
+ .text { font: 600 16px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${titleColor} }
187
+ .small { font: 600 12px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} }
188
+ .gray { fill: #858585 }
189
+ </style>
190
+ <rect x="0.5" y="0.5" width="${ERROR_CARD_LENGTH - 1}" height="99%" rx="4.5" fill="${bgColor}" stroke="${borderColor}"/>
191
+ <text x="25" y="45" class="text">Something went wrong!${UPSTREAM_API_ERRORS.includes(secondaryMessage) || !show_repo_link
192
+ ? ""
193
+ : " file an issue at https://tinyurl.com/github-stats"}</text>
194
+ <text data-testid="message" x="25" y="55" class="text small">
195
+ <tspan x="25" dy="18">${encodeHTML(message)}</tspan>
196
+ <tspan x="25" dy="18" class="gray">${secondaryMessage}</tspan>
197
+ </text>
198
+ </svg>
199
+ `;
200
+ };
201
+ /**
202
+ * Retrieve text length based on Segoe UI font.
203
+ *
204
+ * @see https://stackoverflow.com/a/48172630/10629172
205
+ * @param {string} str String to measure.
206
+ * @param {number} fontSize Font size.
207
+ * @returns {number} Text length.
208
+ */
209
+ const measureText = (str, fontSize = 10) => {
210
+ // prettier-ignore
211
+ const widths = [
212
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
213
+ 0, 0, 0, 0, 0, 0, 0, 0.2733333110809326, 0.28499999046325686,
214
+ 0.39166667461395266, 0.5900000095367431, 0.5383333206176758,
215
+ 0.8183333396911621, 0.8, 0.22999999523162842, 0.30166666507720946,
216
+ 0.30166666507720946, 0.41666665077209475, 0.6833333492279052,
217
+ 0.21666667461395264, 0.4, 0.21666667461395264, 0.3900000095367432,
218
+ 0.5383333206176758, 0.5383333206176758, 0.5383333206176758,
219
+ 0.5383333206176758, 0.5383333206176758, 0.5383333206176758,
220
+ 0.5383333206176758, 0.5383333206176758, 0.5383333206176758,
221
+ 0.5383333206176758, 0.21666667461395264, 0.21666667461395264,
222
+ 0.6833333492279052, 0.6833333492279052, 0.6833333492279052,
223
+ 0.4483333110809326, 0.9550000190734863, 0.6449999809265137,
224
+ 0.5733333110809327, 0.6183333396911621, 0.7016666889190674,
225
+ 0.5066666603088379, 0.48833332061767576, 0.6866666793823242,
226
+ 0.7099999904632568, 0.26666667461395266, 0.35666666030883787,
227
+ 0.5800000190734863, 0.4699999809265137, 0.8983333587646485,
228
+ 0.7483333110809326, 0.753333330154419, 0.5599999904632569,
229
+ 0.753333330154419, 0.5983333110809326, 0.5316666603088379,
230
+ 0.5233333110809326, 0.6866666793823242, 0.621666669845581,
231
+ 0.9333333015441895, 0.5900000095367431, 0.553333330154419,
232
+ 0.5699999809265137, 0.30166666507720946, 0.37833333015441895,
233
+ 0.30166666507720946, 0.6833333492279052, 0.41500000953674315,
234
+ 0.26833333969116213, 0.5083333492279053, 0.5883333206176757,
235
+ 0.4616666793823242, 0.5883333206176757, 0.5233333110809326,
236
+ 0.3133333444595337, 0.5883333206176757, 0.5666666507720948,
237
+ 0.24166667461395264, 0.24166667461395264, 0.49666666984558105,
238
+ 0.24166667461395264, 0.8616666793823242, 0.5666666507720948,
239
+ 0.5866666793823242, 0.5883333206176757, 0.5883333206176757,
240
+ 0.3483333349227905, 0.425, 0.33833334445953367, 0.5666666507720948,
241
+ 0.4783333301544189, 0.7233333110809326, 0.45833334922790525,
242
+ 0.4833333492279053, 0.45166668891906736, 0.30166666507720946,
243
+ 0.24000000953674316, 0.30166666507720946, 0.6833333492279052,
244
+ ];
245
+ const avg = 0.5131403493881227;
246
+ // CJK character range: U+3000–U+9FFF (CJK Symbols/Punctuation, Hiragana,
247
+ // Katakana, CJK Unified Ideographs incl. Extension A) plus U+FF00–U+FFEF
248
+ // (Halfwidth/Fullwidth Forms — fullwidth ASCII, fullwidth punctuation).
249
+ const cjkRange = /[\u3000-\u9FFF\uFF00-\uFFEF]/;
250
+ return (str
251
+ .split("")
252
+ .map((c) => {
253
+ if (cjkRange.test(c) || c === "\u3000") {
254
+ // CJK glyphs and U+3000 IDEOGRAPHIC SPACE are full-width by default;
255
+ return 1;
256
+ }
257
+ if (c.charCodeAt(0) < widths.length) {
258
+ return widths[c.charCodeAt(0)];
259
+ }
260
+ else {
261
+ return avg;
262
+ }
263
+ })
264
+ .reduce((cur, acc) => acc + cur) * fontSize);
265
+ };
266
+ /**
267
+ * Split text into the lines it would wrap to when laid out greedily at the
268
+ * given font size inside a box of width `maxWidth`. Uses `measureText` so the
269
+ * estimate reflects actual font metrics rather than a fixed character count.
270
+ * The browser still does the real wrap inside the foreignObject; this is only
271
+ * used to size the SVG.
272
+ *
273
+ * @param {string} text Text to split.
274
+ * @param {number} fontSize Font size in px (matches `measureText`).
275
+ * @param {number} maxWidth Available wrap width in px.
276
+ * @returns {string[]} Estimated wrapped lines.
277
+ */
278
+ const splitWrappedText = (text, fontSize, maxWidth) => {
279
+ if (!text) {
280
+ return [];
281
+ }
282
+ // Tokenize the text into atoms representing line-break opportunities:
283
+ // - ASCII whitespace runs (collapsed/dropped at line edges per CSS rules);
284
+ // - non-ASCII whitespaces
285
+ // - a single CJK codepoint (browsers break between any two CJK chars,
286
+ // punctuation or not, so each one is its own atom and ~1 em wide);
287
+ // - a run of non-whitespace non-CJK characters (a "word" that can only
288
+ // break at its boundaries, like Latin script).
289
+ // Korean Hangul (U+AC00–U+D7AF) is intentionally NOT in the CJK range
290
+ // because Korean wraps at word boundaries by default in HTML.
291
+ // ASCII whitespace is collapsed to a single space per CSS `white-space: normal;`
292
+ text = text.replace(/[\t\n\r ]+/g, " ");
293
+ const tokens = text.match(/\s|[\u3000-\u9FFF\uFF00-\uFFEF]|[^\s\u3000-\u9FFF\uFF00-\uFFEF]+/g);
294
+ if (!tokens) {
295
+ return [];
296
+ }
297
+ const takeFittingSegment = (token, availableWidth) => {
298
+ const characters = token.split("");
299
+ let segment = "";
300
+ let width = 0;
301
+ for (const character of characters) {
302
+ const characterWidth = measureText(character, fontSize);
303
+ if (segment && width + characterWidth > availableWidth) {
304
+ break;
305
+ }
306
+ segment += character;
307
+ width += characterWidth;
308
+ }
309
+ return {
310
+ segment,
311
+ width,
312
+ };
313
+ };
314
+ const lines = [""];
315
+ let currentWidth = 0;
316
+ for (const token of tokens) {
317
+ if (token === " ") {
318
+ // Whitespace at the start of a line is dropped by browsers.
319
+ if (currentWidth === 0) {
320
+ continue;
321
+ }
322
+ lines[lines.length - 1] += token;
323
+ currentWidth += measureText(token, fontSize);
324
+ continue;
325
+ }
326
+ let remaining = token;
327
+ while (remaining) {
328
+ const w = measureText(remaining, fontSize);
329
+ if (currentWidth + w <= maxWidth) {
330
+ lines[lines.length - 1] += remaining;
331
+ currentWidth += w;
332
+ break;
333
+ }
334
+ if (currentWidth > 0) {
335
+ lines.push("");
336
+ currentWidth = 0;
337
+ continue;
338
+ }
339
+ // An atom wider than the box wraps mid-glyph (overflow-wrap: anywhere).
340
+ const { segment, width } = takeFittingSegment(remaining, maxWidth);
341
+ lines[lines.length - 1] += segment;
342
+ currentWidth = width;
343
+ remaining = remaining.slice(segment.length);
344
+ }
345
+ }
346
+ return lines.map((line) => line.replace(/[\t\n\r ]+$/, ""));
347
+ };
348
+ /**
349
+ * Estimate how many lines a string will wrap to when laid out greedily at the
350
+ * given font size inside a box of width `maxWidth`, capped at `maxLines`.
351
+ *
352
+ * @param {string} text Text to estimate.
353
+ * @param {number} fontSize Font size in px (matches `measureText`).
354
+ * @param {number} maxWidth Available wrap width in px.
355
+ * @param {number} maxLines Cap on the returned line count.
356
+ * @returns {number} Estimated line count, at least 1, at most `maxLines`.
357
+ */
358
+ const countWrappedLines = (text, fontSize, maxWidth, maxLines) => {
359
+ return Math.min(Math.max(1, splitWrappedText(text, fontSize, maxWidth).length), maxLines);
360
+ };
361
+ export { renderError, createLanguageNode, createProgressNode, iconWithLabel, flexLayout, measureText, splitWrappedText, countWrappedLines, wrappedTextNode, wrappedTextStyles, };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Axios response.
3
+ */
4
+ export type AxiosResponse = import("axios").AxiosResponse;
5
+ /**
6
+ * Fetcher function.
7
+ */
8
+ export type FetcherFunction = (variables: any, token: string, retriesForTests?: number) => Promise<AxiosResponse>;
9
+ /**
10
+ * @typedef {import("axios").AxiosResponse} AxiosResponse Axios response.
11
+ * @typedef {(variables: any, token: string, retriesForTests?: number) => Promise<AxiosResponse>} FetcherFunction Fetcher function.
12
+ */
13
+ /**
14
+ * Try to execute the fetcher function until it succeeds or the max number of retries is reached.
15
+ *
16
+ * @param {FetcherFunction} fetcher The fetcher function.
17
+ * @param {any} variables Object with arguments to pass to the fetcher function.
18
+ * @param {string | null} pat Optional PAT override.
19
+ * @returns {Promise<any>} The response from the fetcher function.
20
+ */
21
+ export function retryer(fetcher: FetcherFunction, variables: any, pat?: string | null): Promise<any>;
22
+ //# sourceMappingURL=retryer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retryer.d.ts","sourceRoot":"","sources":["../../src/common/retryer.js"],"names":[],"mappings":";;;4BAqBa,OAAO,OAAO,EAAE,aAAa;;;;8BAC7B,CAAC,SAAS,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,aAAa,CAAC;AAFhG;;;GAGG;AAEH;;;;;;;GAOG;AACH,iCALW,eAAe,aACf,GAAG,QACH,MAAM,GAAG,IAAI,GACX,OAAO,CAAC,GAAG,CAAC,CAsExB"}
@@ -0,0 +1,86 @@
1
+ // @ts-check
2
+ import { getConfig } from "./config.js";
3
+ import { CustomError } from "./error.js";
4
+ import { logger } from "./log.js";
5
+ /**
6
+ * Returns a random integer from 0 (inclusive) to `max` (exclusive).
7
+ *
8
+ * The value is generated using `Math.random()` and uniformly distributed
9
+ * across the range.
10
+ *
11
+ * @param {number} max The upper bound (exclusive). Must be a positive number.
12
+ *
13
+ * @returns {number} A random integer `n` such that `0 <= n < max`.
14
+ */
15
+ function getRandomInt(max) {
16
+ return Math.floor(Math.random() * max);
17
+ }
18
+ /**
19
+ * @typedef {import("axios").AxiosResponse} AxiosResponse Axios response.
20
+ * @typedef {(variables: any, token: string, retriesForTests?: number) => Promise<AxiosResponse>} FetcherFunction Fetcher function.
21
+ */
22
+ /**
23
+ * Try to execute the fetcher function until it succeeds or the max number of retries is reached.
24
+ *
25
+ * @param {FetcherFunction} fetcher The fetcher function.
26
+ * @param {any} variables Object with arguments to pass to the fetcher function.
27
+ * @param {string | null} pat Optional PAT override.
28
+ * @returns {Promise<any>} The response from the fetcher function.
29
+ */
30
+ const retryer = async (fetcher, variables, pat = null) => {
31
+ let PATs;
32
+ if (pat) {
33
+ PATs = [{ name: "user PAT from database", value: pat }];
34
+ }
35
+ else {
36
+ PATs = getConfig().pats;
37
+ }
38
+ if (!PATs.length) {
39
+ throw new CustomError("No GitHub API tokens found", CustomError.NO_TOKENS);
40
+ }
41
+ const startPAT = getRandomInt(PATs.length);
42
+ for (let retries = 0; retries < PATs.length; retries++) {
43
+ const currentPAT = PATs[(startPAT + retries) % PATs.length];
44
+ try {
45
+ let response = await fetcher(variables,
46
+ // @ts-ignore
47
+ currentPAT.value,
48
+ // used in tests for faking rate limit
49
+ retries);
50
+ // react on both type and message-based rate-limit signals.
51
+ // https://github.com/anuraghazra/github-readme-stats/issues/4425
52
+ const errors = response?.data?.errors;
53
+ const errorType = errors?.[0]?.type;
54
+ const errorMsg = errors?.[0]?.message || "";
55
+ const isRateLimited = (errors && errorType === "RATE_LIMITED") ||
56
+ /rate limit/i.test(errorMsg);
57
+ if (isRateLimited) {
58
+ logger.log(`${currentPAT.name} Failed due to rate limiting`);
59
+ }
60
+ else {
61
+ return response;
62
+ }
63
+ }
64
+ catch (err) {
65
+ /** @type {any} */
66
+ const e = err;
67
+ // network/unexpected error → let caller treat as failure
68
+ if (!e?.response) {
69
+ throw e;
70
+ }
71
+ // prettier-ignore
72
+ // also checking for bad credentials if any tokens gets invalidated
73
+ const isBadCredential = e?.response?.data?.message === "Bad credentials";
74
+ const isAccountSuspended = e?.response?.data?.message === "Sorry. Your account was suspended.";
75
+ if (isBadCredential || isAccountSuspended) {
76
+ logger.log(`${currentPAT.name} Failed due to bad credentials`);
77
+ }
78
+ else {
79
+ // HTTP error with a response → return it for caller-side handling
80
+ return e.response;
81
+ }
82
+ }
83
+ }
84
+ throw new CustomError("Downtime due to GitHub API rate limiting", CustomError.MAX_RETRY);
85
+ };
86
+ export { retryer };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Gist file.
3
+ */
4
+ export type GistFile = {
5
+ name: string;
6
+ language: {
7
+ name: string;
8
+ };
9
+ size: number;
10
+ };
11
+ /**
12
+ * Gist data.
13
+ */
14
+ export type GistData = any;
15
+ /**
16
+ * @typedef {import('./types').GistData} GistData Gist data.
17
+ */
18
+ /**
19
+ * Fetch GitHub gist information by given username and ID.
20
+ *
21
+ * @param {string} id GitHub gist ID.
22
+ * @param {string | null} pat Optional PAT override.
23
+ * @returns {Promise<GistData>} Gist data.
24
+ */
25
+ export function fetchGist(id: string, pat?: string | null): Promise<GistData>;
26
+ //# sourceMappingURL=gist.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gist.d.ts","sourceRoot":"","sources":["../../src/fetchers/gist.js"],"names":[],"mappings":";;;uBA6Ca;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;KAAE,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE;;;;;AAiCxE;;GAEG;AAEH;;;;;;GAMG;AACH,8BAJW,MAAM,QACN,MAAM,GAAG,IAAI,GACX,OAAO,CAAC,QAAQ,CAAC,CAwB7B"}
@@ -0,0 +1,99 @@
1
+ // @ts-check
2
+ import { MissingParamError } from "../common/error.js";
3
+ import { request } from "../common/http.js";
4
+ import { retryer } from "../common/retryer.js";
5
+ const QUERY = `
6
+ query gistInfo($gistName: String!) {
7
+ viewer {
8
+ gist(name: $gistName) {
9
+ description
10
+ owner {
11
+ login
12
+ }
13
+ stargazerCount
14
+ forks {
15
+ totalCount
16
+ }
17
+ files {
18
+ name
19
+ language {
20
+ name
21
+ }
22
+ size
23
+ }
24
+ }
25
+ }
26
+ }
27
+ `;
28
+ /**
29
+ * Gist data fetcher.
30
+ *
31
+ * @param {object} variables Fetcher variables.
32
+ * @param {string} token GitHub token.
33
+ * @returns {Promise<import('axios').AxiosResponse>} The response.
34
+ */
35
+ const fetcher = async (variables, token) => {
36
+ return await request({ query: QUERY, variables }, { Authorization: `token ${token}` });
37
+ };
38
+ /**
39
+ * @typedef {{ name: string; language: { name: string; }, size: number }} GistFile Gist file.
40
+ */
41
+ /**
42
+ * This function calculates the primary language of a gist by files size.
43
+ *
44
+ * @param {GistFile[]} files Files.
45
+ * @returns {string} Primary language.
46
+ */
47
+ const calculatePrimaryLanguage = (files) => {
48
+ /** @type {Record<string, number>} */
49
+ const languages = {};
50
+ for (const file of files) {
51
+ if (file.language) {
52
+ if (languages[file.language.name]) {
53
+ languages[file.language.name] += file.size;
54
+ }
55
+ else {
56
+ languages[file.language.name] = file.size;
57
+ }
58
+ }
59
+ }
60
+ let primaryLanguage = Object.keys(languages)[0];
61
+ for (const language in languages) {
62
+ if (languages[language] > languages[primaryLanguage]) {
63
+ primaryLanguage = language;
64
+ }
65
+ }
66
+ return primaryLanguage;
67
+ };
68
+ /**
69
+ * @typedef {import('./types').GistData} GistData Gist data.
70
+ */
71
+ /**
72
+ * Fetch GitHub gist information by given username and ID.
73
+ *
74
+ * @param {string} id GitHub gist ID.
75
+ * @param {string | null} pat Optional PAT override.
76
+ * @returns {Promise<GistData>} Gist data.
77
+ */
78
+ const fetchGist = async (id, pat = null) => {
79
+ if (!id) {
80
+ throw new MissingParamError(["id"], "/api/gist?id=GIST_ID");
81
+ }
82
+ const res = await retryer(fetcher, { gistName: id }, pat);
83
+ if (res.data.errors) {
84
+ throw new Error(res.data.errors[0].message);
85
+ }
86
+ if (!res.data.data.viewer.gist) {
87
+ throw new Error("Gist not found");
88
+ }
89
+ const data = res.data.data.viewer.gist;
90
+ return {
91
+ name: data.files[Object.keys(data.files)[0]].name,
92
+ nameWithOwner: `${data.owner.login}/${data.files[Object.keys(data.files)[0]].name}`,
93
+ description: data.description,
94
+ language: calculatePrimaryLanguage(data.files),
95
+ starsCount: data.stargazerCount,
96
+ forksCount: data.forks.totalCount,
97
+ };
98
+ };
99
+ export { fetchGist };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Repository data.
3
+ */
4
+ export type RepositoryData = any;
5
+ /**
6
+ * @typedef {import("./types").RepositoryData} RepositoryData Repository data.
7
+ */
8
+ /**
9
+ * Fetch repository data.
10
+ *
11
+ * @param {string} username GitHub username.
12
+ * @param {string} reponame GitHub repository name.
13
+ * @returns {Promise<RepositoryData>} Repository data.
14
+ */
15
+ export function fetchRepo(username: string, reponame: string, include_prs_authored?: boolean, include_prs_commented?: boolean, include_prs_reviewed?: boolean, include_issues_authored?: boolean, include_issues_commented?: boolean, pat?: null): Promise<RepositoryData>;
16
+ //# sourceMappingURL=repo.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repo.d.ts","sourceRoot":"","sources":["../../src/fetchers/repo.js"],"names":[],"mappings":";;;;AA2DA;;GAEG;AAEH;;;;;;GAMG;AACH,oCAJW,MAAM,YACN,MAAM,uLACJ,OAAO,CAAC,cAAc,CAAC,CA8FnC"}