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

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 (77) hide show
  1. package/build/api/gist.d.ts.map +1 -1
  2. package/build/api/gist.js +34 -0
  3. package/build/api/index.d.ts.map +1 -1
  4. package/build/api/index.js +18 -0
  5. package/build/api/pin.d.ts.map +1 -1
  6. package/build/api/pin.js +17 -0
  7. package/build/api/top-langs.d.ts.map +1 -1
  8. package/build/api/top-langs.js +36 -4
  9. package/build/api/wakatime.d.ts.map +1 -1
  10. package/build/api/wakatime.js +34 -0
  11. package/build/calculateRank.d.ts +12 -11
  12. package/build/calculateRank.d.ts.map +1 -1
  13. package/build/calculateRank.js +18 -18
  14. package/build/cards/repo.d.ts.map +1 -1
  15. package/build/cards/repo.js +29 -20
  16. package/build/cards/stats.d.ts +4 -2
  17. package/build/cards/stats.d.ts.map +1 -1
  18. package/build/cards/stats.js +21 -8
  19. package/build/cards/top-languages.d.ts.map +1 -1
  20. package/build/cards/top-languages.js +39 -11
  21. package/build/cards/wakatime.d.ts.map +1 -1
  22. package/build/cards/wakatime.js +29 -8
  23. package/build/common/Card.d.ts +9 -3
  24. package/build/common/Card.d.ts.map +1 -1
  25. package/build/common/Card.js +47 -19
  26. package/build/common/color.d.ts +42 -8
  27. package/build/common/color.d.ts.map +1 -1
  28. package/build/common/color.js +62 -13
  29. package/build/common/html.js +1 -1
  30. package/build/common/http.d.ts +13 -4
  31. package/build/common/http.d.ts.map +1 -1
  32. package/build/common/http.js +3 -3
  33. package/build/common/languageColors.json +9 -1
  34. package/build/common/ops.d.ts +30 -29
  35. package/build/common/ops.d.ts.map +1 -1
  36. package/build/common/ops.js +32 -37
  37. package/build/common/render.d.ts +115 -111
  38. package/build/common/render.d.ts.map +1 -1
  39. package/build/common/render.js +138 -87
  40. package/build/common/retryer.d.ts +14 -6
  41. package/build/common/retryer.d.ts.map +1 -1
  42. package/build/common/retryer.js +1 -0
  43. package/build/fetchers/gist.d.ts +6 -21
  44. package/build/fetchers/gist.d.ts.map +1 -1
  45. package/build/fetchers/gist.js +30 -35
  46. package/build/fetchers/repo.js +1 -1
  47. package/build/fetchers/stats.d.ts.map +1 -1
  48. package/build/fetchers/stats.js +0 -1
  49. package/build/fetchers/types.d.ts +126 -0
  50. package/build/fetchers/types.d.ts.map +1 -0
  51. package/build/fetchers/types.js +1 -0
  52. package/package.json +4 -4
  53. package/src/_emoji-name-map.d.ts +10 -0
  54. package/src/api/gist.js +36 -0
  55. package/src/api/index.js +19 -0
  56. package/src/api/pin.js +18 -0
  57. package/src/api/top-langs.js +38 -4
  58. package/src/api/wakatime.js +36 -0
  59. package/src/{calculateRank.js → calculateRank.ts} +29 -19
  60. package/src/cards/repo.js +30 -20
  61. package/src/cards/stats.js +22 -8
  62. package/src/cards/top-languages.js +49 -11
  63. package/src/cards/wakatime.js +33 -8
  64. package/src/common/Card.ts +51 -16
  65. package/src/common/color.ts +85 -22
  66. package/src/common/html.ts +1 -1
  67. package/src/common/http.ts +31 -0
  68. package/src/common/languageColors.json +9 -1
  69. package/src/common/{ops.js → ops.ts} +48 -50
  70. package/src/common/{render.js → render.ts} +208 -96
  71. package/src/common/retryer.ts +18 -10
  72. package/src/fetchers/gist.ts +136 -0
  73. package/src/fetchers/repo.js +1 -1
  74. package/src/fetchers/stats.js +0 -1
  75. package/src/common/http.js +0 -19
  76. package/src/fetchers/gist.js +0 -112
  77. /package/src/fetchers/{types.d.ts → types.ts} +0 -0
@@ -1,4 +1,4 @@
1
- import { getCardColors } from "./color.js";
1
+ import { getCardColors, isPrefixedHexColor } from "./color.js";
2
2
  import { SECONDARY_ERROR_MESSAGES, TRY_AGAIN_LATER } from "./error.js";
3
3
  import { encodeHTML } from "./html.js";
4
4
  import { clampValue } from "./ops.js";
@@ -6,14 +6,19 @@ import { clampValue } from "./ops.js";
6
6
  * Auto layout utility, allows us to layout things vertically or horizontally with
7
7
  * proper gaping.
8
8
  *
9
- * @param {object} props Function properties.
10
- * @param {string[]} props.items Array of items to layout.
11
- * @param {number} props.gap Gap between items.
12
- * @param {"column" | "row"=} props.direction Direction to layout items.
13
- * @param {number[]=} props.sizes Array of sizes for each item.
14
- * @returns {string[]} Array of items with proper layout.
9
+ * The caller must ensure that the passed `items` are properly sanitized!
10
+ *
11
+ * @param props Function properties.
12
+ * @param props.items Array of sanitized items to layout.
13
+ * @param props.gap Gap between items.
14
+ * @param props.direction Direction to layout items.
15
+ * @param props.sizes Array of sizes for each item.
16
+ * @returns Array of items with proper layout.
15
17
  */
16
- const flexLayout = ({ items, gap, direction, sizes = [] }) => {
18
+ const flexLayout = ({ items, gap, direction, sizes = [], }) => {
19
+ if (sizes.some((size) => !Number.isFinite(size))) {
20
+ throw new Error("flexLayout: `sizes` must contain only numbers");
21
+ }
17
22
  let lastSize = 0;
18
23
  // filter() for filtering out empty strings
19
24
  return items.filter(Boolean).map((item, i) => {
@@ -29,32 +34,53 @@ const flexLayout = ({ items, gap, direction, sizes = [] }) => {
29
34
  /**
30
35
  * Creates a node to display the primary programming language of the repository/gist.
31
36
  *
32
- * @param {string} langName Language name.
33
- * @param {string} langColor Language color.
34
- * @returns {string} Language display SVG object.
37
+ * @param langName Language name.
38
+ * @param langColor Language color.
39
+ * @returns Language display SVG object.
35
40
  */
36
41
  const createLanguageNode = (langName, langColor) => {
42
+ if (!isPrefixedHexColor(langColor)) {
43
+ throw new Error(`Invalid language color: "${langColor}"`);
44
+ }
37
45
  return `
38
46
  <g data-testid="primary-lang">
39
47
  <circle data-testid="lang-color" cx="0" cy="-5" r="6" fill="${langColor}" />
40
- <text data-testid="lang-name" class="gray" x="15">${langName}</text>
48
+ <text data-testid="lang-name" class="gray" x="15">${encodeHTML(langName)}</text>
41
49
  </g>
42
50
  `;
43
51
  };
44
52
  /**
45
53
  * Create a node to indicate progress in percentage along a horizontal line.
46
54
  *
47
- * @param {Object} params Object that contains the createProgressNode parameters.
48
- * @param {number} params.x X-axis position.
49
- * @param {number} params.y Y-axis position.
50
- * @param {number} params.width Width of progress bar.
51
- * @param {string} params.color Progress color.
52
- * @param {number} params.progress Progress value.
53
- * @param {string} params.progressBarBackgroundColor Progress bar bg color.
54
- * @param {number} params.delay Delay before animation starts.
55
- * @returns {string} Progress node.
55
+ * @param params Object that contains the createProgressNode parameters.
56
+ * @param params.x X-axis position.
57
+ * @param params.y Y-axis position.
58
+ * @param params.width Width of progress bar.
59
+ * @param params.color Progress color.
60
+ * @param params.progress Progress value.
61
+ * @param params.progressBarBackgroundColor Progress bar bg color.
62
+ * @param params.delay Delay before animation starts.
63
+ * @returns Progress node.
56
64
  */
57
65
  const createProgressNode = ({ x, y, width, color, progress, progressBarBackgroundColor, delay, }) => {
66
+ if (!isPrefixedHexColor(color)) {
67
+ throw new Error(`Invalid progress color: "${color}"`);
68
+ }
69
+ if (!isPrefixedHexColor(progressBarBackgroundColor)) {
70
+ throw new Error(`Invalid progress bar background color: "${progressBarBackgroundColor}"`);
71
+ }
72
+ if (!Number.isFinite(width)) {
73
+ throw new Error(`Invalid width: "${width}"`);
74
+ }
75
+ if (!Number.isFinite(x)) {
76
+ throw new Error(`Invalid x: "${x}"`);
77
+ }
78
+ if (!Number.isFinite(y)) {
79
+ throw new Error(`Invalid y: "${y}"`);
80
+ }
81
+ if (!Number.isFinite(delay)) {
82
+ throw new Error(`Invalid delay: "${delay}"`);
83
+ }
58
84
  const progressPercentage = clampValue(progress, 2, 100);
59
85
  return `
60
86
  <svg width="${width}" x="${x}" y="${y}">
@@ -76,22 +102,37 @@ const createProgressNode = ({ x, y, width, color, progress, progressBarBackgroun
76
102
  * native, font-aware wrapping. Content overflowing `lineCount` lines is
77
103
  * clipped (with an ellipsis on the last visible line) by CSS line-clamp.
78
104
  *
79
- * @param {object} props Function properties.
80
- * @param {string} props.text Text to render (will be HTML-encoded).
81
- * @param {number} props.x X position of the foreignObject.
82
- * @param {number} props.y Y position of the foreignObject.
83
- * @param {number} props.width Width of the wrap box.
84
- * @param {number} props.height Height of the wrap box.
85
- * @param {number} props.lineCount Maximum number of lines to display.
86
- * @param {string} props.className CSS class applied to the inner element.
87
- * @param {string=} props.testId Optional test id for the inner element.
88
- * @returns {string} foreignObject SVG node.
105
+ * @param props Function properties.
106
+ * @param props.text Text to render (will be HTML-encoded).
107
+ * @param props.x X position of the foreignObject.
108
+ * @param props.y Y position of the foreignObject.
109
+ * @param props.width Width of the wrap box.
110
+ * @param props.height Height of the wrap box.
111
+ * @param props.lineCount Maximum number of lines to display.
112
+ * @param props.className CSS class applied to the inner element.
113
+ * @param props.testId Optional test id for the inner element.
114
+ * @returns foreignObject SVG node.
89
115
  */
90
116
  const wrappedTextNode = ({ text, x, y, width, height, lineCount, className, testId, }) => {
91
- const testIdAttr = testId ? ` data-testid="${testId}"` : "";
117
+ if (!Number.isFinite(x)) {
118
+ throw new Error(`Invalid x: "${x}"`);
119
+ }
120
+ if (!Number.isFinite(y)) {
121
+ throw new Error(`Invalid y: "${y}"`);
122
+ }
123
+ if (!Number.isFinite(width)) {
124
+ throw new Error(`Invalid width: "${width}"`);
125
+ }
126
+ if (!Number.isFinite(height)) {
127
+ throw new Error(`Invalid height: "${height}"`);
128
+ }
129
+ if (!Number.isFinite(lineCount)) {
130
+ throw new Error(`Invalid lineCount: "${lineCount}"`);
131
+ }
132
+ const testIdAttr = testId ? ` data-testid="${encodeHTML(testId)}"` : "";
92
133
  return `
93
134
  <foreignObject x="${x}" y="${y}" width="${width}" height="${height}">
94
- <div xmlns="http://www.w3.org/1999/xhtml" class="${className}" style="--lines: ${lineCount};"${testIdAttr}>${encodeHTML(text)}</div>
135
+ <div xmlns="http://www.w3.org/1999/xhtml" class="${encodeHTML(className)}" style="--lines: ${lineCount};"${testIdAttr}>${encodeHTML(text)}</div>
95
136
  </foreignObject>
96
137
  `;
97
138
  };
@@ -101,36 +142,46 @@ const wrappedTextNode = ({ text, x, y, width, height, lineCount, className, test
101
142
  * browser handles wrapping and the line count is taken from the `--lines`
102
143
  * custom property set on the element.
103
144
  *
104
- * @param {string} color Text color (CSS `color` property).
105
- * @returns {string} CSS rules block (without the surrounding selector).
145
+ * @param color Text color (CSS `color` property).
146
+ * @returns CSS rules block (without the surrounding selector).
106
147
  */
107
- const wrappedTextStyles = (color) => `
108
- color: ${color};
109
- margin: 0;
110
- line-height: 1.2;
111
- overflow-wrap: anywhere;
112
- word-break: break-word;
113
- display: -webkit-box;
114
- -webkit-box-orient: vertical;
115
- -webkit-line-clamp: var(--lines);
116
- line-clamp: var(--lines);
117
- overflow: hidden;
118
- text-overflow: ellipsis;
119
- padding-bottom: 0.15em;
120
- `;
148
+ const wrappedTextStyles = (color) => {
149
+ if (!isPrefixedHexColor(color)) {
150
+ throw new Error(`Invalid text color: "${color}"`);
151
+ }
152
+ return `
153
+ color: ${color};
154
+ margin: 0;
155
+ line-height: 1.2;
156
+ overflow-wrap: anywhere;
157
+ word-break: break-word;
158
+ display: -webkit-box;
159
+ -webkit-box-orient: vertical;
160
+ -webkit-line-clamp: var(--lines);
161
+ line-clamp: var(--lines);
162
+ overflow: hidden;
163
+ text-overflow: ellipsis;
164
+ padding-bottom: 0.15em;
165
+ `;
166
+ };
121
167
  /**
122
168
  * Creates an icon with label to display repository/gist stats like forks, stars, etc.
123
169
  *
124
- * @param {string} icon The icon to display.
125
- * @param {number|string} label The label to display.
126
- * @param {string} testid The testid to assign to the label.
127
- * @param {number} iconSize The size of the icon.
128
- * @returns {string} Icon with label SVG object.
170
+ * The caller must ensure that the passed `icon` is properly sanitized!
171
+ *
172
+ * @param icon The sanitized icon to display.
173
+ * @param label The label to display.
174
+ * @param testid The testid to assign to the label.
175
+ * @param iconSize The size of the icon.
176
+ * @returns Icon with label SVG object.
129
177
  */
130
178
  const iconWithLabel = (icon, label, testid, iconSize) => {
131
179
  if (typeof label === "number" && label <= 0) {
132
180
  return "";
133
181
  }
182
+ if (!Number.isFinite(iconSize)) {
183
+ throw new Error(`Invalid iconSize: "${iconSize}"`);
184
+ }
134
185
  const iconSvg = `
135
186
  <svg
136
187
  class="icon"
@@ -143,7 +194,7 @@ const iconWithLabel = (icon, label, testid, iconSize) => {
143
194
  ${icon}
144
195
  </svg>
145
196
  `;
146
- const text = `<text data-testid="${testid}" class="gray">${label}</text>`;
197
+ const text = `<text data-testid="${encodeHTML(testid)}" class="gray">${encodeHTML(String(label))}</text>`;
147
198
  return flexLayout({ items: [iconSvg, text], gap: 20 }).join("");
148
199
  };
149
200
  // Script parameters.
@@ -155,17 +206,17 @@ const UPSTREAM_API_ERRORS = [
155
206
  /**
156
207
  * Renders error message on the card.
157
208
  *
158
- * @param {object} args Function arguments.
159
- * @param {string} args.message Main error message.
160
- * @param {string} [args.secondaryMessage=""] The secondary error message.
161
- * @param {object} [args.renderOptions={}] Render options.
162
- * @param {string=} args.renderOptions.title_color Card title color.
163
- * @param {string=} args.renderOptions.text_color Card text color.
164
- * @param {string=} args.renderOptions.bg_color Card background color.
165
- * @param {string=} args.renderOptions.border_color Card border color.
166
- * @param {Parameters<typeof getCardColors>[0]["theme"]=} args.renderOptions.theme Card theme.
167
- * @param {boolean=} args.renderOptions.show_repo_link Whether to show repo link or not.
168
- * @returns {string} The SVG markup.
209
+ * @param args Function arguments.
210
+ * @param args.message Main error message.
211
+ * @param args.secondaryMessage The secondary error message.
212
+ * @param args.renderOptions Render options.
213
+ * @param args.renderOptions.title_color Card title color.
214
+ * @param args.renderOptions.text_color Card text color.
215
+ * @param args.renderOptions.bg_color Card background color.
216
+ * @param args.renderOptions.border_color Card border color.
217
+ * @param args.renderOptions.theme Card theme.
218
+ * @param args.renderOptions.show_repo_link Whether to show repo link or not.
219
+ * @returns The SVG markup.
169
220
  */
170
221
  const renderError = ({ message, secondaryMessage = "", renderOptions = {}, }) => {
171
222
  const { title_color, text_color, bg_color, border_color, theme = "default", show_repo_link = true, } = renderOptions;
@@ -180,19 +231,19 @@ const renderError = ({ message, secondaryMessage = "", renderOptions = {}, }) =>
180
231
  theme,
181
232
  });
182
233
  return `
183
- <svg width="${ERROR_CARD_LENGTH}" height="120" viewBox="0 0 ${ERROR_CARD_LENGTH} 120" fill="${bgColor}" xmlns="http://www.w3.org/2000/svg">
234
+ <svg width="${ERROR_CARD_LENGTH}" height="120" viewBox="0 0 ${ERROR_CARD_LENGTH} 120" fill="${String(bgColor)}" xmlns="http://www.w3.org/2000/svg">
184
235
  <style>
185
236
  .text { font: 600 16px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${titleColor} }
186
237
  .small { font: 600 12px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} }
187
238
  .gray { fill: #858585 }
188
239
  </style>
189
- <rect x="0.5" y="0.5" width="${ERROR_CARD_LENGTH - 1}" height="99%" rx="4.5" fill="${bgColor}" stroke="${borderColor}"/>
240
+ <rect x="0.5" y="0.5" width="${ERROR_CARD_LENGTH - 1}" height="99%" rx="4.5" fill="${String(bgColor)}" stroke="${borderColor}"/>
190
241
  <text x="25" y="45" class="text">Something went wrong!${UPSTREAM_API_ERRORS.includes(secondaryMessage) || !show_repo_link
191
242
  ? ""
192
243
  : " file an issue at https://tinyurl.com/github-stats"}</text>
193
244
  <text data-testid="message" x="25" y="55" class="text small">
194
245
  <tspan x="25" dy="18">${encodeHTML(message)}</tspan>
195
- <tspan x="25" dy="18" class="gray">${secondaryMessage}</tspan>
246
+ <tspan x="25" dy="18" class="gray">${encodeHTML(secondaryMessage)}</tspan>
196
247
  </text>
197
248
  </svg>
198
249
  `;
@@ -201,9 +252,9 @@ const renderError = ({ message, secondaryMessage = "", renderOptions = {}, }) =>
201
252
  * Retrieve text length based on Segoe UI font.
202
253
  *
203
254
  * @see https://stackoverflow.com/a/48172630/10629172
204
- * @param {string} str String to measure.
205
- * @param {number} fontSize Font size.
206
- * @returns {number} Text length.
255
+ * @param str String to measure.
256
+ * @param fontSize Font size.
257
+ * @returns Text length.
207
258
  */
208
259
  const measureText = (str, fontSize = 10) => {
209
260
  // prettier-ignore
@@ -254,7 +305,7 @@ const measureText = (str, fontSize = 10) => {
254
305
  return 1;
255
306
  }
256
307
  if (c.charCodeAt(0) < widths.length) {
257
- return widths[c.charCodeAt(0)];
308
+ return widths[c.charCodeAt(0)] ?? avg;
258
309
  }
259
310
  else {
260
311
  return avg;
@@ -269,10 +320,10 @@ const measureText = (str, fontSize = 10) => {
269
320
  * The browser still does the real wrap inside the foreignObject; this is only
270
321
  * used to size the SVG.
271
322
  *
272
- * @param {string} text Text to split.
273
- * @param {number} fontSize Font size in px (matches `measureText`).
274
- * @param {number} maxWidth Available wrap width in px.
275
- * @returns {string[]} Estimated wrapped lines.
323
+ * @param text Text to split.
324
+ * @param fontSize Font size in px (matches `measureText`).
325
+ * @param maxWidth Available wrap width in px.
326
+ * @returns Estimated wrapped lines.
276
327
  */
277
328
  const splitWrappedText = (text, fontSize, maxWidth) => {
278
329
  if (!text) {
@@ -288,8 +339,8 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
288
339
  // Korean Hangul (U+AC00–U+D7AF) is intentionally NOT in the CJK range
289
340
  // because Korean wraps at word boundaries by default in HTML.
290
341
  // ASCII whitespace is collapsed to a single space per CSS `white-space: normal;`
291
- text = text.replace(/[\t\n\r ]+/g, " ");
292
- const tokens = text.match(/\s|[\u3000-\u9FFF\uFF00-\uFFEF]|[^\s\u3000-\u9FFF\uFF00-\uFFEF]+/g);
342
+ const normalizedText = text.replace(/[\t\n\r ]+/g, " ");
343
+ const tokens = normalizedText.match(/\s|[\u3000-\u9FFF\uFF00-\uFFEF]|[^\s\u3000-\u9FFF\uFF00-\uFFEF]+/g);
293
344
  if (!tokens) {
294
345
  return [];
295
346
  }
@@ -318,7 +369,7 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
318
369
  if (currentWidth === 0) {
319
370
  continue;
320
371
  }
321
- lines[lines.length - 1] += token;
372
+ lines[lines.length - 1] = (lines[lines.length - 1] ?? "") + token;
322
373
  currentWidth += measureText(token, fontSize);
323
374
  continue;
324
375
  }
@@ -326,7 +377,7 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
326
377
  while (remaining) {
327
378
  const w = measureText(remaining, fontSize);
328
379
  if (currentWidth + w <= maxWidth) {
329
- lines[lines.length - 1] += remaining;
380
+ lines[lines.length - 1] = (lines[lines.length - 1] ?? "") + remaining;
330
381
  currentWidth += w;
331
382
  break;
332
383
  }
@@ -337,7 +388,7 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
337
388
  }
338
389
  // An atom wider than the box wraps mid-glyph (overflow-wrap: anywhere).
339
390
  const { segment, width } = takeFittingSegment(remaining, maxWidth);
340
- lines[lines.length - 1] += segment;
391
+ lines[lines.length - 1] = (lines[lines.length - 1] ?? "") + segment;
341
392
  currentWidth = width;
342
393
  remaining = remaining.slice(segment.length);
343
394
  }
@@ -348,11 +399,11 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
348
399
  * Estimate how many lines a string will wrap to when laid out greedily at the
349
400
  * given font size inside a box of width `maxWidth`, capped at `maxLines`.
350
401
  *
351
- * @param {string} text Text to estimate.
352
- * @param {number} fontSize Font size in px (matches `measureText`).
353
- * @param {number} maxWidth Available wrap width in px.
354
- * @param {number} maxLines Cap on the returned line count.
355
- * @returns {number} Estimated line count, at least 1, at most `maxLines`.
402
+ * @param text Text to estimate.
403
+ * @param fontSize Font size in px (matches `measureText`).
404
+ * @param maxWidth Available wrap width in px.
405
+ * @param maxLines Cap on the returned line count.
406
+ * @returns Estimated line count, at least 1, at most `maxLines`.
356
407
  */
357
408
  const countWrappedLines = (text, fontSize, maxWidth, maxLines) => {
358
409
  return Math.min(Math.max(1, splitWrappedText(text, fontSize, maxWidth).length), maxLines);
@@ -1,25 +1,33 @@
1
1
  import type { AxiosResponse } from "axios";
2
2
  /**
3
- * Subset of the response payload the retryer inspects to detect
4
- * rate-limiting and credential failures.
3
+ * Error-detection fields the retryer inspects to detect rate-limiting and credential failures.
4
+ * Every fetcher's payload is intersected with
5
+ * this, so the retryer can read `errors`/`message` regardless of the payload's own shape.
5
6
  */
6
- interface ResponseData {
7
+ interface ResponseErrors {
7
8
  errors?: Array<{
8
9
  type?: string;
9
10
  message?: string;
10
11
  }>;
11
12
  message?: string;
12
13
  }
13
- type FetcherResponse = AxiosResponse<ResponseData>;
14
- type FetcherFunction = (variables: Record<string, unknown>, token: string, retriesForTests?: number) => Promise<FetcherResponse>;
14
+ /**
15
+ * A fetcher's Axios response. `TData` is the shape of `response.data`,
16
+ * which is intersected with {@link ResponseErrors} so the retryer can inspect
17
+ * `errors`/`message`.
18
+ * Defaults to `unknown` (error fields only) for callers that don't care about the payload.
19
+ */
20
+ type FetcherResponse<TData = unknown> = AxiosResponse<TData & ResponseErrors>;
21
+ type FetcherFunction<TData = unknown> = (variables: Record<string, unknown>, token: string, retriesForTests?: number) => Promise<FetcherResponse<TData>>;
15
22
  /**
16
23
  * Try to execute the fetcher function until it succeeds or the max number of retries is reached.
17
24
  *
25
+ * @template TData Shape of `response.data` returned by the fetcher.
18
26
  * @param fetcher The fetcher function.
19
27
  * @param variables Object with arguments to pass to the fetcher function.
20
28
  * @param pat Optional PAT override.
21
29
  * @returns The response from the fetcher function.
22
30
  */
23
- declare const retryer: (fetcher: FetcherFunction, variables: Record<string, unknown>, pat?: string | null) => Promise<FetcherResponse>;
31
+ declare const retryer: <TData = unknown>(fetcher: FetcherFunction<TData>, variables: Record<string, unknown>, pat?: string | null) => Promise<FetcherResponse<TData>>;
24
32
  export { retryer };
25
33
  //# sourceMappingURL=retryer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"retryer.d.ts","sourceRoot":"","sources":["../../src/common/retryer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAM3C;;;GAGG;AACH,UAAU,YAAY;IACpB,MAAM,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACpD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAgBD,KAAK,eAAe,GAAG,aAAa,CAAC,YAAY,CAAC,CAAC;AAEnD,KAAK,eAAe,GAAG,CACrB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,KAAK,EAAE,MAAM,EACb,eAAe,CAAC,EAAE,MAAM,KACrB,OAAO,CAAC,eAAe,CAAC,CAAC;AAE9B;;;;;;;GAOG;AACH,QAAA,MAAM,OAAO,GACX,SAAS,eAAe,EACxB,WAAW,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,MAAK,MAAM,GAAG,IAAW,KACxB,OAAO,CAAC,eAAe,CAiEzB,CAAC;AAEF,OAAO,EAAE,OAAO,EAAE,CAAC"}
1
+ {"version":3,"file":"retryer.d.ts","sourceRoot":"","sources":["../../src/common/retryer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAM3C;;;;GAIG;AACH,UAAU,cAAc;IACtB,MAAM,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACpD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAgBD;;;;;GAKG;AACH,KAAK,eAAe,CAAC,KAAK,GAAG,OAAO,IAAI,aAAa,CAAC,KAAK,GAAG,cAAc,CAAC,CAAC;AAE9E,KAAK,eAAe,CAAC,KAAK,GAAG,OAAO,IAAI,CACtC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,KAAK,EAAE,MAAM,EACb,eAAe,CAAC,EAAE,MAAM,KACrB,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;AAErC;;;;;;;;GAQG;AACH,QAAA,MAAM,OAAO,GAAU,KAAK,GAAG,OAAO,EACpC,SAAS,eAAe,CAAC,KAAK,CAAC,EAC/B,WAAW,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,MAAK,MAAM,GAAG,IAAW,KACxB,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,CAiEhC,CAAC;AAEF,OAAO,EAAE,OAAO,EAAE,CAAC"}
@@ -17,6 +17,7 @@ function getRandomInt(max) {
17
17
  /**
18
18
  * Try to execute the fetcher function until it succeeds or the max number of retries is reached.
19
19
  *
20
+ * @template TData Shape of `response.data` returned by the fetcher.
20
21
  * @param fetcher The fetcher function.
21
22
  * @param variables Object with arguments to pass to the fetcher function.
22
23
  * @param pat Optional PAT override.
@@ -1,26 +1,11 @@
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
- */
1
+ import type { GistData } from "./types.js";
18
2
  /**
19
3
  * Fetch GitHub gist information by given username and ID.
20
4
  *
21
- * @param {string} id GitHub gist ID.
22
- * @param {string | null} pat Optional PAT override.
23
- * @returns {Promise<GistData>} Gist data.
5
+ * @param id GitHub gist ID.
6
+ * @param pat Optional PAT override.
7
+ * @returns Gist data.
24
8
  */
25
- export function fetchGist(id: string, pat?: string | null): Promise<GistData>;
9
+ declare const fetchGist: (id: string, pat?: string | null) => Promise<GistData>;
10
+ export { fetchGist };
26
11
  //# sourceMappingURL=gist.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"gist.d.ts","sourceRoot":"","sources":["../../src/fetchers/gist.js"],"names":[],"mappings":";;;uBA2Ca;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"}
1
+ {"version":3,"file":"gist.d.ts","sourceRoot":"","sources":["../../src/fetchers/gist.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AA6F3C;;;;;;GAMG;AACH,QAAA,MAAM,SAAS,GACb,IAAI,MAAM,EACV,MAAK,MAAM,GAAG,IAAW,KACxB,OAAO,CAAC,QAAQ,CAwBlB,CAAC;AAEF,OAAO,EAAE,SAAS,EAAE,CAAC"}
@@ -27,52 +27,43 @@ query gistInfo($gistName: String!) {
27
27
  /**
28
28
  * Gist data fetcher.
29
29
  *
30
- * @param {object} variables Fetcher variables.
31
- * @param {string} token GitHub token.
32
- * @returns {Promise<import('axios').AxiosResponse>} The response.
30
+ * @param variables Fetcher variables.
31
+ * @param token GitHub token.
32
+ * @returns The response.
33
33
  */
34
- const fetcher = async (variables, token) => {
35
- return await request({ query: QUERY, variables }, { Authorization: `token ${token}` });
34
+ const fetcher = (variables, token) => {
35
+ return request({ query: QUERY, variables }, { Authorization: `token ${token}` });
36
36
  };
37
- /**
38
- * @typedef {{ name: string; language: { name: string; }, size: number }} GistFile Gist file.
39
- */
40
37
  /**
41
38
  * This function calculates the primary language of a gist by files size.
42
39
  *
43
- * @param {GistFile[]} files Files.
44
- * @returns {string} Primary language.
40
+ * @param files Files.
41
+ * @returns Primary language, or `null` when no file has a language.
45
42
  */
46
43
  const calculatePrimaryLanguage = (files) => {
47
- /** @type {Record<string, number>} */
48
44
  const languages = {};
49
45
  for (const file of files) {
50
46
  if (file.language) {
51
- if (languages[file.language.name]) {
52
- languages[file.language.name] += file.size;
53
- }
54
- else {
55
- languages[file.language.name] = file.size;
56
- }
47
+ languages[file.language.name] =
48
+ (languages[file.language.name] ?? 0) + file.size;
57
49
  }
58
50
  }
59
- let primaryLanguage = Object.keys(languages)[0];
60
- for (const language in languages) {
61
- if (languages[language] > languages[primaryLanguage]) {
51
+ let primaryLanguage = null;
52
+ let maxSize = -1;
53
+ for (const [language, size] of Object.entries(languages)) {
54
+ if (size > maxSize) {
55
+ maxSize = size;
62
56
  primaryLanguage = language;
63
57
  }
64
58
  }
65
59
  return primaryLanguage;
66
60
  };
67
- /**
68
- * @typedef {import('./types').GistData} GistData Gist data.
69
- */
70
61
  /**
71
62
  * Fetch GitHub gist information by given username and ID.
72
63
  *
73
- * @param {string} id GitHub gist ID.
74
- * @param {string | null} pat Optional PAT override.
75
- * @returns {Promise<GistData>} Gist data.
64
+ * @param id GitHub gist ID.
65
+ * @param pat Optional PAT override.
66
+ * @returns Gist data.
76
67
  */
77
68
  const fetchGist = async (id, pat = null) => {
78
69
  if (!id) {
@@ -80,19 +71,23 @@ const fetchGist = async (id, pat = null) => {
80
71
  }
81
72
  const res = await retryer(fetcher, { gistName: id }, pat);
82
73
  if (res.data.errors) {
83
- throw new Error(res.data.errors[0].message);
74
+ throw new Error(res.data.errors[0]?.message);
84
75
  }
85
- if (!res.data.data.viewer.gist) {
76
+ const gist = res.data.data.viewer.gist;
77
+ if (!gist) {
86
78
  throw new Error("Gist not found");
87
79
  }
88
- const data = res.data.data.viewer.gist;
80
+ const firstFile = gist.files[0];
81
+ if (!firstFile) {
82
+ throw new Error("Gist has no files");
83
+ }
89
84
  return {
90
- name: data.files[Object.keys(data.files)[0]].name,
91
- nameWithOwner: `${data.owner.login}/${data.files[Object.keys(data.files)[0]].name}`,
92
- description: data.description,
93
- language: calculatePrimaryLanguage(data.files),
94
- starsCount: data.stargazerCount,
95
- forksCount: data.forks.totalCount,
85
+ name: firstFile.name,
86
+ nameWithOwner: `${gist.owner.login}/${firstFile.name}`,
87
+ description: gist.description,
88
+ language: calculatePrimaryLanguage(gist.files),
89
+ starsCount: gist.stargazerCount,
90
+ forksCount: gist.forks.totalCount,
96
91
  };
97
92
  };
98
93
  export { fetchGist };
@@ -45,7 +45,7 @@ const fetcher = (variables, token) => {
45
45
  Authorization: `token ${token}`,
46
46
  });
47
47
  };
48
- const urlExample = "/api/pin?username=USERNAME&amp;repo=REPO_NAME";
48
+ const urlExample = "/api/pin?username=USERNAME&repo=REPO_NAME";
49
49
  /**
50
50
  * @typedef {import("./types").RepositoryData} RepositoryData Repository data.
51
51
  */
@@ -1 +1 @@
1
- {"version":3,"file":"stats.d.ts","sourceRoot":"","sources":["../../src/fetchers/stats.js"],"names":[],"mappings":"AAmTA;;;;;;;;;;;;GAYG;AACH,qCAVW,MAAM,uBACN,OAAO,4BACP,MAAM,EAAE,4CACR,OAAO,mCACP,OAAO,2CACP,OAAO,4BACP,MAAM,GAAC,SAAS,2NAChB,MAAM,EAAE,eACN,OAAO,CAAC,GAA2B,CAAC,CAyJhD;AArOD;;;;;;GA+DC"}
1
+ {"version":3,"file":"stats.d.ts","sourceRoot":"","sources":["../../src/fetchers/stats.js"],"names":[],"mappings":"AAkTA;;;;;;;;;;;;GAYG;AACH,qCAVW,MAAM,uBACN,OAAO,4BACP,MAAM,EAAE,4CACR,OAAO,mCACP,OAAO,2CACP,OAAO,4BACP,MAAM,GAAC,SAAS,2NAChB,MAAM,EAAE,eACN,OAAO,CAAC,GAA2B,CAAC,CAyJhD;AArOD;;;;;;GA+DC"}
@@ -134,7 +134,6 @@ const statsFetcher = async ({ username, includeMergedPullRequests, includeDiscus
134
134
  else {
135
135
  stats = res;
136
136
  }
137
- // Disable multi page fetching on public Vercel instance due to rate limits.
138
137
  fetchedPages++;
139
138
  const repoNodesWithStars = repoNodes.filter((node) => node.stargazerCount !== 0);
140
139
  hasNextPage =