@stats-forge/github-stats-forge-core 0.0.2 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +0 -10
  2. package/build/api/api-result.d.ts +6 -7
  3. package/build/api/api-result.d.ts.map +1 -1
  4. package/build/api/api-result.js +4 -5
  5. package/build/api/gist.d.ts +3 -10
  6. package/build/api/gist.d.ts.map +1 -1
  7. package/build/api/gist.js +4 -11
  8. package/build/api/index.d.ts +12 -12
  9. package/build/api/params.d.ts +11 -8
  10. package/build/api/params.d.ts.map +1 -1
  11. package/build/api/params.js +16 -14
  12. package/build/api/pin.d.ts +3 -19
  13. package/build/api/pin.d.ts.map +1 -1
  14. package/build/api/pin.js +6 -22
  15. package/build/api/stats.d.ts +10 -4
  16. package/build/api/stats.d.ts.map +1 -1
  17. package/build/api/stats.js +6 -32
  18. package/build/api/top-langs.d.ts +12 -6
  19. package/build/api/top-langs.d.ts.map +1 -1
  20. package/build/api/top-langs.js +6 -26
  21. package/build/api/wakatime.d.ts +13 -5
  22. package/build/api/wakatime.d.ts.map +1 -1
  23. package/build/api/wakatime.js +4 -21
  24. package/build/calculateRank.d.ts +0 -9
  25. package/build/calculateRank.d.ts.map +1 -1
  26. package/build/calculateRank.js +12 -17
  27. package/build/cards/gist.d.ts +2 -4
  28. package/build/cards/gist.d.ts.map +1 -1
  29. package/build/cards/gist.js +27 -36
  30. package/build/cards/options.d.ts +1 -1
  31. package/build/cards/repo.d.ts +2 -4
  32. package/build/cards/repo.d.ts.map +1 -1
  33. package/build/cards/repo.js +61 -93
  34. package/build/cards/stats.d.ts +3 -8
  35. package/build/cards/stats.d.ts.map +1 -1
  36. package/build/cards/stats.js +119 -165
  37. package/build/cards/top-languages.d.ts +5 -31
  38. package/build/cards/top-languages.d.ts.map +1 -1
  39. package/build/cards/top-languages.js +176 -384
  40. package/build/cards/wakatime.d.ts +4 -6
  41. package/build/cards/wakatime.d.ts.map +1 -1
  42. package/build/cards/wakatime.js +118 -185
  43. package/build/common/Card.d.ts +14 -62
  44. package/build/common/Card.d.ts.map +1 -1
  45. package/build/common/Card.js +97 -199
  46. package/build/common/I18n.d.ts +0 -6
  47. package/build/common/I18n.d.ts.map +1 -1
  48. package/build/common/I18n.js +3 -6
  49. package/build/common/color.d.ts +4 -17
  50. package/build/common/color.d.ts.map +1 -1
  51. package/build/common/color.js +67 -49
  52. package/build/common/config.d.ts +4 -14
  53. package/build/common/config.d.ts.map +1 -1
  54. package/build/common/config.js +3 -16
  55. package/build/common/constants.d.ts +4 -2
  56. package/build/common/constants.d.ts.map +1 -1
  57. package/build/common/constants.js +3 -1
  58. package/build/common/date.d.ts +0 -2
  59. package/build/common/date.d.ts.map +1 -1
  60. package/build/common/date.js +0 -2
  61. package/build/common/emojiMap.d.ts +8 -0
  62. package/build/common/emojiMap.d.ts.map +1 -0
  63. package/build/common/emojiMap.js +10 -0
  64. package/build/common/emojiMap.json +1915 -0
  65. package/build/common/error.d.ts +1 -10
  66. package/build/common/error.d.ts.map +1 -1
  67. package/build/common/error.js +1 -10
  68. package/build/common/fmt.d.ts +3 -15
  69. package/build/common/fmt.d.ts.map +1 -1
  70. package/build/common/fmt.js +7 -35
  71. package/build/common/http.d.ts +2 -7
  72. package/build/common/http.d.ts.map +1 -1
  73. package/build/common/http.js +8 -17
  74. package/build/common/icons.d.ts +18 -20
  75. package/build/common/icons.d.ts.map +1 -1
  76. package/build/common/icons.js +103 -67
  77. package/build/common/languageColors.d.ts +0 -1
  78. package/build/common/languageColors.d.ts.map +1 -1
  79. package/build/common/languageColors.js +1 -4
  80. package/build/common/languageColors.json +18 -2
  81. package/build/common/ops.d.ts +3 -14
  82. package/build/common/ops.d.ts.map +1 -1
  83. package/build/common/ops.js +19 -30
  84. package/build/common/render.d.ts +28 -82
  85. package/build/common/render.d.ts.map +1 -1
  86. package/build/common/render.js +175 -211
  87. package/build/common/retryer.d.ts +2 -7
  88. package/build/common/retryer.d.ts.map +1 -1
  89. package/build/common/retryer.js +4 -11
  90. package/build/fetchers/gist.d.ts +2 -5
  91. package/build/fetchers/gist.d.ts.map +1 -1
  92. package/build/fetchers/gist.js +1 -5
  93. package/build/fetchers/index.d.ts +12 -12
  94. package/build/fetchers/repo.d.ts +2 -11
  95. package/build/fetchers/repo.d.ts.map +1 -1
  96. package/build/fetchers/repo.js +20 -33
  97. package/build/fetchers/stats.d.ts +2 -32
  98. package/build/fetchers/stats.d.ts.map +1 -1
  99. package/build/fetchers/stats.js +27 -86
  100. package/build/fetchers/top-languages.d.ts +2 -9
  101. package/build/fetchers/top-languages.d.ts.map +1 -1
  102. package/build/fetchers/top-languages.js +15 -31
  103. package/build/fetchers/types.d.ts +1 -1
  104. package/build/fetchers/wakatime.d.ts +2 -6
  105. package/build/fetchers/wakatime.d.ts.map +1 -1
  106. package/build/fetchers/wakatime.js +1 -5
  107. package/build/graphql/contributionsDocument.d.ts +3 -3
  108. package/build/graphql/contributionsDocument.d.ts.map +1 -1
  109. package/build/graphql/contributionsDocument.js +0 -1
  110. package/build/graphql/generated/gist.d.ts +1 -1
  111. package/build/graphql/generated/repo.d.ts +1 -1
  112. package/build/graphql/generated/stats.d.ts +3 -3
  113. package/build/graphql/generated/top-languages.d.ts +2 -2
  114. package/build/graphql/graphqlDocument.d.ts +0 -1
  115. package/build/graphql/graphqlDocument.d.ts.map +1 -1
  116. package/build/graphql/graphqlDocument.js +0 -1
  117. package/build/graphql/reposContributedToDocument.d.ts +4 -5
  118. package/build/graphql/reposContributedToDocument.d.ts.map +1 -1
  119. package/build/graphql/reposContributedToDocument.js +0 -2
  120. package/build/markup/css.d.ts +35 -0
  121. package/build/markup/css.d.ts.map +1 -0
  122. package/build/markup/css.js +64 -0
  123. package/build/markup/element.d.ts +41 -0
  124. package/build/markup/element.d.ts.map +1 -0
  125. package/build/markup/element.js +127 -0
  126. package/build/markup/html.d.ts +13 -0
  127. package/build/markup/html.d.ts.map +1 -0
  128. package/build/markup/html.js +27 -0
  129. package/build/markup/index.d.ts +9 -0
  130. package/build/markup/index.d.ts.map +1 -0
  131. package/build/markup/index.js +6 -0
  132. package/build/markup/serialize.d.ts +16 -0
  133. package/build/markup/serialize.d.ts.map +1 -0
  134. package/build/markup/serialize.js +17 -0
  135. package/build/themes/index.d.ts +332 -333
  136. package/build/themes/index.d.ts.map +1 -1
  137. package/build/themes/index.js +1 -1
  138. package/build/translations.d.ts +2 -6
  139. package/build/translations.d.ts.map +1 -1
  140. package/build/translations.js +621 -628
  141. package/package.json +17 -26
  142. package/src/api/api-result.ts +10 -9
  143. package/src/api/gist.ts +11 -18
  144. package/src/api/index.ts +12 -12
  145. package/src/api/params.ts +27 -21
  146. package/src/api/pin.ts +13 -28
  147. package/src/api/stats.ts +13 -39
  148. package/src/api/top-langs.ts +13 -33
  149. package/src/api/wakatime.ts +11 -28
  150. package/src/calculateRank.ts +12 -23
  151. package/src/cards/gist.ts +40 -43
  152. package/src/cards/options.ts +1 -1
  153. package/src/cards/repo.ts +97 -107
  154. package/src/cards/stats.ts +165 -184
  155. package/src/cards/top-languages.ts +297 -413
  156. package/src/cards/wakatime.ts +193 -221
  157. package/src/common/Card.ts +165 -217
  158. package/src/common/I18n.ts +3 -6
  159. package/src/common/color.ts +80 -57
  160. package/src/common/config.ts +5 -18
  161. package/src/common/constants.ts +5 -2
  162. package/src/common/date.ts +0 -2
  163. package/src/common/emojiMap.json +1915 -0
  164. package/src/common/emojiMap.ts +13 -0
  165. package/src/common/error.ts +2 -11
  166. package/src/common/fmt.ts +7 -44
  167. package/src/common/http.ts +9 -15
  168. package/src/common/icons.ts +117 -42
  169. package/src/common/languageColors.json +18 -2
  170. package/src/common/languageColors.ts +1 -4
  171. package/src/common/ops.ts +26 -34
  172. package/src/common/render.ts +279 -232
  173. package/src/common/retryer.ts +8 -15
  174. package/src/fetchers/gist.ts +8 -12
  175. package/src/fetchers/index.ts +12 -12
  176. package/src/fetchers/repo.ts +27 -40
  177. package/src/fetchers/stats.ts +44 -102
  178. package/src/fetchers/top-languages.ts +26 -40
  179. package/src/fetchers/types.ts +1 -1
  180. package/src/fetchers/wakatime.ts +5 -9
  181. package/src/graphql/contributionsDocument.ts +7 -5
  182. package/src/graphql/generated/gist.ts +1 -1
  183. package/src/graphql/generated/repo.ts +1 -1
  184. package/src/graphql/generated/stats.ts +2 -2
  185. package/src/graphql/generated/top-languages.ts +2 -2
  186. package/src/graphql/graphqlDocument.ts +0 -1
  187. package/src/graphql/reposContributedToDocument.ts +6 -7
  188. package/src/markup/css.ts +118 -0
  189. package/src/markup/element.ts +246 -0
  190. package/src/markup/html.ts +34 -0
  191. package/src/markup/index.ts +9 -0
  192. package/src/markup/serialize.ts +27 -0
  193. package/src/themes/index.ts +1 -1
  194. package/src/translations.ts +622 -629
  195. package/build/cards/index.d.ts +0 -11
  196. package/build/cards/index.d.ts.map +0 -1
  197. package/build/cards/index.js +0 -7
  198. package/build/common/html.d.ts +0 -8
  199. package/build/common/html.d.ts.map +0 -1
  200. package/build/common/html.js +0 -14
  201. package/build/index.d.ts +0 -15
  202. package/build/index.d.ts.map +0 -1
  203. package/build/index.js +0 -10
  204. package/src/_emoji-name-map.d.ts +0 -10
  205. package/src/_github-username-regex.d.ts +0 -4
  206. package/src/cards/index.ts +0 -21
  207. package/src/common/html.ts +0 -17
  208. package/src/index.ts +0 -18
@@ -1,66 +1,50 @@
1
+ import { el, renderMarkup, rule, style } from '../markup/index.js';
1
2
  import { getCardColors, isPrefixedHexColor } from './color.js';
2
3
  import { SECONDARY_ERROR_MESSAGES, TRY_AGAIN_LATER } from './error.js';
3
4
  import { kFormatter } from './fmt.js';
4
- import { encodeHTML } from './html.js';
5
5
  import { clampValue } from './ops.js';
6
6
  /**
7
7
  * Auto layout utility, allows us to layout things vertically or horizontally with
8
8
  * proper gaping.
9
9
  *
10
- * The caller must ensure that the passed `items` are properly sanitized!
11
- *
12
- * @param props Function properties.
13
- * @param props.items Array of sanitized items to layout.
14
- * @param props.gap Gap between items.
15
- * @param props.direction Direction to layout items.
16
- * @param props.sizes Array of sizes for each item.
17
- * @returns Array of items with proper layout.
10
+ * @returns The items, each in the group that positions it.
18
11
  */
19
12
  const flexLayout = ({ items, gap, direction, sizes = [], }) => {
20
13
  if (sizes.some((size) => !Number.isFinite(size))) {
21
14
  throw new Error('flexLayout: `sizes` must contain only numbers');
22
15
  }
16
+ const laidOut = items.filter(Boolean);
17
+ // A lone item is already where it belongs, so it needs no group to move it.
18
+ if (laidOut.length === 1) {
19
+ return laidOut;
20
+ }
23
21
  let lastSize = 0;
24
- // filter() for filtering out empty strings
25
- return items.filter(Boolean).map((item, i) => {
26
- const size = sizes[i] || 0;
27
- let transform = `translate(${lastSize}, 0)`;
28
- if (direction === 'column') {
29
- transform = `translate(0, ${lastSize})`;
30
- }
31
- lastSize += size + gap;
32
- return `<g transform="${transform}">${item}</g>`;
22
+ return laidOut.map((item, i) => {
23
+ const offset = lastSize;
24
+ lastSize += (sizes[i] ?? 0) + gap;
25
+ // The first item never moves, so it gets no transform to carry.
26
+ const transform = offset === 0
27
+ ? undefined
28
+ : direction === 'column'
29
+ ? `translate(0, ${offset})`
30
+ : `translate(${offset}, 0)`;
31
+ return el('g', { transform }, item);
33
32
  });
34
33
  };
35
34
  /**
36
35
  * Creates a node to display the primary programming language of the repository/gist.
37
36
  *
38
- * @param langName Language name.
39
- * @param langColor Language color.
40
37
  * @returns Language display SVG object.
41
38
  */
42
39
  const createLanguageNode = (langName, langColor) => {
43
40
  if (!isPrefixedHexColor(langColor)) {
44
41
  throw new Error(`Invalid language color: "${langColor}"`);
45
42
  }
46
- return `
47
- <g data-testid="primary-lang">
48
- <circle data-testid="lang-color" cx="0" cy="-5" r="6" fill="${langColor}" />
49
- <text data-testid="lang-name" class="gray" x="15">${encodeHTML(langName)}</text>
50
- </g>
51
- `;
43
+ return el('g', { 'data-testid': 'primary-lang' }, el('circle', { 'data-testid': 'lang-color', cx: 0, cy: -5, r: 6, fill: langColor }), el('text', { 'data-testid': 'lang-name', class: 'gray', x: 15 }, langName));
52
44
  };
53
45
  /**
54
46
  * Create a node to indicate progress in percentage along a horizontal line.
55
47
  *
56
- * @param params Object that contains the createProgressNode parameters.
57
- * @param params.x X-axis position.
58
- * @param params.y Y-axis position.
59
- * @param params.width Width of progress bar.
60
- * @param params.color Optional foreground color as an inline fill fallback.
61
- * When omitted, the color must be set via a `.lang-progress` CSS rule.
62
- * @param params.progress Progress value.
63
- * @param params.delay Delay before animation starts.
64
48
  * @returns Progress node.
65
49
  */
66
50
  const createProgressNode = ({ x, y, width, color, progress, delay, }) => {
@@ -68,71 +52,67 @@ const createProgressNode = ({ x, y, width, color, progress, delay, }) => {
68
52
  throw new Error(`Invalid progress color: "${color}"`);
69
53
  }
70
54
  if (!Number.isFinite(width)) {
71
- throw new Error(`Invalid width: "${width}"`);
55
+ throw new TypeError(`Invalid width: "${width}"`);
72
56
  }
73
57
  if (!Number.isFinite(x)) {
74
- throw new Error(`Invalid x: "${x}"`);
58
+ throw new TypeError(`Invalid x: "${x}"`);
75
59
  }
76
60
  if (!Number.isFinite(y)) {
77
- throw new Error(`Invalid y: "${y}"`);
61
+ throw new TypeError(`Invalid y: "${y}"`);
78
62
  }
79
63
  if (!Number.isFinite(delay)) {
80
- throw new Error(`Invalid delay: "${delay}"`);
64
+ throw new TypeError(`Invalid delay: "${delay}"`);
81
65
  }
82
66
  const progressPercentage = clampValue(progress, 2, 100);
83
- return `
84
- <svg width="${width}" x="${x}" y="${y}">
85
- <rect data-testid="progress-background" class="progress-background" rx="5" ry="5" x="0" y="0" width="${width}" height="8"></rect>
86
- <svg data-testid="lang-progress" width="${progressPercentage}%">
87
- <rect
88
- height="8"
89
- ${color === undefined ? '' : `fill="${color}"`}
90
- rx="5" ry="5" x="0" y="0"
91
- class="lang-progress"
92
- style="animation-delay: ${delay}ms;"
93
- />
94
- </svg>
95
- </svg>
96
- `;
67
+ return el('svg', { width, x, y }, el('rect', {
68
+ 'data-testid': 'progress-background',
69
+ class: 'progress-background',
70
+ rx: 5,
71
+ ry: 5,
72
+ x: 0,
73
+ y: 0,
74
+ width,
75
+ height: 8,
76
+ }), el('svg', { 'data-testid': 'lang-progress', width: `${progressPercentage}%` }, el('rect', {
77
+ height: 8,
78
+ fill: color,
79
+ rx: 5,
80
+ ry: 5,
81
+ x: 0,
82
+ y: 0,
83
+ class: 'lang-progress',
84
+ style: `animation-delay: ${delay}ms;`,
85
+ })));
97
86
  };
98
87
  /**
99
88
  * Renders multi-line text via a `foreignObject` so the browser performs
100
89
  * native, font-aware wrapping. Content overflowing `lineCount` lines is
101
90
  * clipped (with an ellipsis on the last visible line) by CSS line-clamp.
102
91
  *
103
- * @param props Function properties.
104
- * @param props.text Text to render (will be HTML-encoded).
105
- * @param props.x X position of the foreignObject.
106
- * @param props.y Y position of the foreignObject.
107
- * @param props.width Width of the wrap box.
108
- * @param props.height Height of the wrap box.
109
- * @param props.lineCount Maximum number of lines to display.
110
- * @param props.className CSS class applied to the inner element.
111
- * @param props.testId Optional test id for the inner element.
112
92
  * @returns foreignObject SVG node.
113
93
  */
114
94
  const wrappedTextNode = ({ text, x, y, width, height, lineCount, className, testId, }) => {
115
95
  if (!Number.isFinite(x)) {
116
- throw new Error(`Invalid x: "${x}"`);
96
+ throw new TypeError(`Invalid x: "${x}"`);
117
97
  }
118
98
  if (!Number.isFinite(y)) {
119
- throw new Error(`Invalid y: "${y}"`);
99
+ throw new TypeError(`Invalid y: "${y}"`);
120
100
  }
121
101
  if (!Number.isFinite(width)) {
122
- throw new Error(`Invalid width: "${width}"`);
102
+ throw new TypeError(`Invalid width: "${width}"`);
123
103
  }
124
104
  if (!Number.isFinite(height)) {
125
- throw new Error(`Invalid height: "${height}"`);
105
+ throw new TypeError(`Invalid height: "${height}"`);
126
106
  }
127
107
  if (!Number.isFinite(lineCount)) {
128
- throw new Error(`Invalid lineCount: "${lineCount}"`);
108
+ throw new TypeError(`Invalid lineCount: "${lineCount}"`);
129
109
  }
130
- const testIdAttr = testId ? ` data-testid="${encodeHTML(testId)}"` : '';
131
- return `
132
- <foreignObject x="${x}" y="${y}" width="${width}" height="${height}">
133
- <div xmlns="http://www.w3.org/1999/xhtml" class="${encodeHTML(className)}" style="--lines: ${lineCount};"${testIdAttr}>${encodeHTML(text)}</div>
134
- </foreignObject>
135
- `;
110
+ return el('foreignObject', { x, y, width, height }, el('div', {
111
+ xmlns: 'http://www.w3.org/1999/xhtml',
112
+ class: className,
113
+ style: `--lines: ${lineCount};`,
114
+ 'data-testid': testId,
115
+ }, text));
136
116
  };
137
117
  /**
138
118
  * CSS rules used to render multi-line text inside a `foreignObject`. Apply this
@@ -140,93 +120,76 @@ const wrappedTextNode = ({ text, x, y, width, height, lineCount, className, test
140
120
  * browser handles wrapping and the line count is taken from the `--lines`
141
121
  * custom property set on the element.
142
122
  *
143
- * @param color Text color (CSS `color` property).
144
- * @returns CSS rules block (without the surrounding selector).
123
+ * @returns The declarations, to merge into the class's own rule.
145
124
  */
146
125
  const wrappedTextStyles = (color) => {
147
126
  if (!isPrefixedHexColor(color)) {
148
127
  throw new Error(`Invalid text color: "${color}"`);
149
128
  }
150
- return `
151
- color: ${color};
152
- margin: 0;
153
- line-height: 1.2;
154
- overflow-wrap: anywhere;
155
- word-break: break-word;
156
- display: -webkit-box;
157
- -webkit-box-orient: vertical;
158
- -webkit-line-clamp: var(--lines);
159
- line-clamp: var(--lines);
160
- overflow: hidden;
161
- text-overflow: ellipsis;
162
- padding-bottom: 0.15em;
163
- `;
129
+ return {
130
+ color,
131
+ margin: 0,
132
+ 'line-height': 1.2,
133
+ 'overflow-wrap': 'anywhere',
134
+ 'word-break': 'break-word',
135
+ display: '-webkit-box',
136
+ '-webkit-box-orient': 'vertical',
137
+ '-webkit-line-clamp': 'var(--lines)',
138
+ 'line-clamp': 'var(--lines)',
139
+ overflow: 'hidden',
140
+ 'text-overflow': 'ellipsis',
141
+ 'padding-bottom': '0.15em',
142
+ };
164
143
  };
165
144
  /**
166
145
  * Creates an icon with label to display repository/gist stats like forks, stars, etc.
146
+ * Draws nothing when the label is not positive.
167
147
  *
168
- * The caller must ensure that the passed `icon` is properly sanitized!
169
- *
170
- * @param icon The sanitized icon to display.
171
- * @param label The label to display.
172
- * @param testid The testid to assign to the label.
173
- * @param iconSize The size of the icon.
174
- * @returns Icon with label SVG object.
148
+ * @returns Icon with label SVG object, or nothing when the label is not positive.
175
149
  */
176
150
  const iconWithLabel = (icon, label, testid, iconSize) => {
177
151
  if (typeof label === 'number' && label <= 0) {
178
- return '';
152
+ return undefined;
179
153
  }
180
154
  if (!Number.isFinite(iconSize)) {
181
- throw new Error(`Invalid iconSize: "${iconSize}"`);
155
+ throw new TypeError(`Invalid iconSize: "${iconSize}"`);
182
156
  }
183
- const iconSvg = `
184
- <svg
185
- class="icon"
186
- y="-12"
187
- viewBox="0 0 16 16"
188
- version="1.1"
189
- width="${iconSize}"
190
- height="${iconSize}"
191
- >
192
- ${icon}
193
- </svg>
194
- `;
195
- const text = `<text data-testid="${encodeHTML(testid)}" class="gray">${encodeHTML(String(label))}</text>`;
196
- return flexLayout({ items: [iconSvg, text], gap: 20 }).join('');
157
+ return flexLayout({
158
+ items: [
159
+ el('svg', {
160
+ class: 'icon',
161
+ y: -12,
162
+ viewBox: '0 0 16 16',
163
+ version: '1.1',
164
+ width: iconSize,
165
+ height: iconSize,
166
+ }, icon),
167
+ el('text', { 'data-testid': testid, class: 'gray' }, String(label)),
168
+ ],
169
+ gap: 20,
170
+ });
197
171
  };
198
172
  /**
199
173
  * Create a labelled stat text item
200
174
  * (a label and its value, optionally with an icon and link).
201
175
  * Shared by the stats and repo cards.
202
176
  *
203
- * The caller must ensure that the passed `icon` and `link` are properly sanitized!
177
+ * The caller must ensure that the passed `link` is properly sanitized!
204
178
  *
205
- * @param params Object that contains the createTextNode parameters.
206
- * @param params.icon The sanitized icon to display.
207
- * @param params.label The label to display.
208
- * @param params.value The value to display.
209
- * @param params.id The id of the stat.
210
- * @param params.unitSymbol The unit symbol of the stat.
211
- * @param params.index The index of the stat.
212
- * @param params.showIcons Whether to show icons.
213
- * @param params.shiftValuePos Number of pixels the value has to be shifted to the right.
214
- * @param params.bold Whether to bold the label.
215
- * @param params.numberFormat The format of numbers on card.
216
- * @param params.numberPrecision The precision of numbers on card.
217
- * @param params.link Sanitized url to link to.
218
- * @param params.labelXOffset horizontal offset for label.
219
179
  * @returns The stats card text item SVG object.
220
180
  */
221
- const createTextNode = ({ icon, label, value, id, unitSymbol, index, showIcons, shiftValuePos, bold, numberFormat, numberPrecision, link, labelXOffset = 25, }) => {
181
+ const createTextNode = ({ icon, label, value, id, unitSymbol, index, showIcons, shiftValuePos, valueAnchorX, bold, labelBold = bold, numberFormat, numberPrecision, link, labelXOffset = 25, }) => {
222
182
  if (!Number.isFinite(labelXOffset)) {
223
- throw new Error(`Invalid labelXOffset: "${labelXOffset}"`);
183
+ throw new TypeError(`Invalid labelXOffset: "${labelXOffset}"`);
224
184
  }
225
185
  if (!Number.isFinite(shiftValuePos)) {
226
- throw new Error(`Invalid shiftValuePos: "${shiftValuePos}"`);
186
+ throw new TypeError(`Invalid shiftValuePos: "${shiftValuePos}"`);
227
187
  }
228
188
  if (!Number.isFinite(index)) {
229
- throw new Error(`Invalid index: "${index}"`);
189
+ throw new TypeError(`Invalid index: "${index}"`);
190
+ }
191
+ if (valueAnchorX !== undefined && !Number.isFinite(valueAnchorX)) {
192
+ throw new Error(`Invalid valueAnchorX: "${valueAnchorX}"`);
230
193
  }
231
194
  const precision = numberPrecision !== undefined && Number.isFinite(numberPrecision)
232
195
  ? clampValue(numberPrecision, 0, 2)
@@ -235,49 +198,41 @@ const createTextNode = ({ icon, label, value, id, unitSymbol, index, showIcons,
235
198
  // (always a number here) is abbreviated via kFormatter.
236
199
  const rawValue = numberFormat.toLowerCase() === 'long' || id === 'prs_merged_percentage';
237
200
  const kValue = rawValue || typeof value !== 'number' ? value : kFormatter(value, precision);
238
- const staggerDelay = (index + 3) * 150;
239
- const boldClass = bold ? ' bold' : 'not_bold';
201
+ const staggerDelay = 120 + index * 40;
202
+ const boldClass = bold ? 'bold' : 'not_bold';
203
+ const labelBoldClass = labelBold ? 'bold' : 'not_bold';
240
204
  const valueX = (showIcons ? 140 : 120) + (bold ? 5 : 0) + shiftValuePos;
241
205
  const unit = unitSymbol ? ` ${unitSymbol}` : '';
242
- const labelOffset = showIcons ? `x="${labelXOffset}"` : '';
243
- const iconSvg = showIcons
244
- ? `
245
- <svg data-testid="icon" class="icon" viewBox="0 0 16 16" version="1.1" width="16" height="16">
246
- ${icon}
247
- </svg>
248
- `
249
- : '';
250
- const content = `
251
- ${iconSvg}
252
- <text class="stat ${boldClass}" ${labelOffset} y="12.5">${encodeHTML(label)}:</text>
253
- <text
254
- class="stat ${boldClass}"
255
- x="${valueX}"
256
- y="12.5"
257
- data-testid="${id}"
258
- >${kValue}${unit}</text>`;
259
- const inner = link ? `<a href="${link}">${content}</a>` : content;
260
- return `
261
- <g class="stagger" style="animation-delay: ${staggerDelay}ms" transform="translate(25, 0)">${inner}
262
- </g>
263
- `;
206
+ const content = [
207
+ showIcons &&
208
+ el('svg', {
209
+ 'data-testid': 'icon',
210
+ class: 'icon',
211
+ viewBox: '0 0 16 16',
212
+ version: '1.1',
213
+ width: 16,
214
+ height: 16,
215
+ }, icon),
216
+ el('text', { class: `stat ${labelBoldClass}`, x: showIcons ? labelXOffset : undefined, y: 12.5 }, `${label}:`),
217
+ el('text', {
218
+ class: `stat ${boldClass}`,
219
+ x: valueAnchorX ?? valueX,
220
+ 'text-anchor': valueAnchorX === undefined ? undefined : 'end',
221
+ y: 12.5,
222
+ 'data-testid': id,
223
+ }, `${String(kValue)}${unit}`),
224
+ ];
225
+ return el('g', {
226
+ class: 'stagger',
227
+ style: `animation-delay: ${staggerDelay}ms`,
228
+ transform: 'translate(25, 0)',
229
+ }, link ? el('a', { href: link }, content) : content);
264
230
  };
265
- // Script parameters.
266
231
  const ERROR_CARD_LENGTH = 576.5;
267
- const UPSTREAM_API_ERRORS = [TRY_AGAIN_LATER, SECONDARY_ERROR_MESSAGES.rate_limited];
232
+ const UPSTREAM_API_ERRORS = new Set([TRY_AGAIN_LATER, SECONDARY_ERROR_MESSAGES.rate_limited]);
268
233
  /**
269
234
  * Renders error message on the card.
270
235
  *
271
- * @param args Function arguments.
272
- * @param args.message Main error message.
273
- * @param args.secondaryMessage The secondary error message.
274
- * @param args.renderOptions Render options.
275
- * @param args.renderOptions.title_color Card title color.
276
- * @param args.renderOptions.text_color Card text color.
277
- * @param args.renderOptions.bg_color Card background color.
278
- * @param args.renderOptions.border_color Card border color.
279
- * @param args.renderOptions.theme Card theme.
280
- * @param args.renderOptions.show_repo_link Whether to show repo link or not.
281
236
  * @returns The SVG markup.
282
237
  */
283
238
  const renderError = ({ message, secondaryMessage = '', renderOptions = {}, }) => {
@@ -291,32 +246,32 @@ const renderError = ({ message, secondaryMessage = '', renderOptions = {}, }) =>
291
246
  ring_color: '',
292
247
  theme,
293
248
  });
294
- return `
295
- <svg width="${ERROR_CARD_LENGTH}" height="120" viewBox="0 0 ${ERROR_CARD_LENGTH} 120" fill="${String(bgColor)}" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="titleId descId">
296
- <title id="titleId">${encodeHTML(message)}</title>
297
- <desc id="descId">${encodeHTML(secondaryMessage)}</desc>
298
- <style>
299
- .text { font: 600 16px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${titleColor} }
300
- .small { font: 600 12px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} }
301
- .gray { fill: #858585 }
302
- </style>
303
- <rect x="0.5" y="0.5" width="${ERROR_CARD_LENGTH - 1}" height="99%" rx="4.5" fill="${String(bgColor)}" stroke="${borderColor}"/>
304
- <text x="25" y="45" class="text">Something went wrong!${UPSTREAM_API_ERRORS.includes(secondaryMessage) || !show_repo_link
249
+ const hint = UPSTREAM_API_ERRORS.has(secondaryMessage) || !show_repo_link
305
250
  ? ''
306
- : ' file an issue at https://tinyurl.com/github-stats'}</text>
307
- <text data-testid="message" x="25" y="55" class="text small">
308
- <tspan x="25" dy="18">${encodeHTML(message)}</tspan>
309
- <tspan x="25" dy="18" class="gray">${encodeHTML(secondaryMessage)}</tspan>
310
- </text>
311
- </svg>
312
- `;
251
+ : ' file an issue at https://tinyurl.com/github-stats';
252
+ return renderMarkup(el('svg', {
253
+ width: ERROR_CARD_LENGTH,
254
+ height: 120,
255
+ viewBox: `0 0 ${ERROR_CARD_LENGTH} 120`,
256
+ fill: String(bgColor),
257
+ xmlns: 'http://www.w3.org/2000/svg',
258
+ role: 'img',
259
+ 'aria-labelledby': 'titleId descId',
260
+ }, el('title', { id: 'titleId' }, message), el('desc', { id: 'descId' }, secondaryMessage), style(rule('.text', { font: "600 16px 'Segoe UI', Ubuntu, Sans-Serif", fill: titleColor }), rule('.small', { font: "600 12px 'Segoe UI', Ubuntu, Sans-Serif", fill: textColor }), rule('.gray', { fill: '#858585' })), el('rect', {
261
+ x: 0.5,
262
+ y: 0.5,
263
+ width: ERROR_CARD_LENGTH - 1,
264
+ height: '99%',
265
+ rx: 8,
266
+ fill: String(bgColor),
267
+ stroke: borderColor,
268
+ }), el('text', { x: 25, y: 45, class: 'text' }, `Something went wrong!${hint}`), el('text', { 'data-testid': 'message', x: 25, y: 55, class: 'text small' }, el('tspan', { x: 25, dy: 18 }, message), el('tspan', { x: 25, dy: 18, class: 'gray' }, secondaryMessage))));
313
269
  };
314
270
  /**
315
271
  * Retrieve text length based on Segoe UI font.
316
272
  *
317
273
  * @see https://stackoverflow.com/a/48172630/10629172
318
- * @param str String to measure.
319
- * @param fontSize Font size.
274
+ *
320
275
  * @returns Text length.
321
276
  */
322
277
  const measureText = (str, fontSize = 10) => {
@@ -360,19 +315,17 @@ const measureText = (str, fontSize = 10) => {
360
315
  // Katakana, CJK Unified Ideographs incl. Extension A) plus U+FF00–U+FFEF
361
316
  // (Halfwidth/Fullwidth Forms — fullwidth ASCII, fullwidth punctuation).
362
317
  const cjkRange = /[\u3000-\u9FFF\uFF00-\uFFEF]/;
363
- return (str
364
- .split('')
365
- .map((c) => {
366
- if (cjkRange.test(c) || c === '\u3000') {
318
+ return ([...str]
319
+ .map((char) => {
320
+ if (cjkRange.test(char) || char === '\u3000') {
367
321
  // CJK glyphs and U+3000 IDEOGRAPHIC SPACE are full-width by default;
368
322
  return 1;
369
323
  }
370
- if (c.charCodeAt(0) < widths.length) {
371
- return widths[c.charCodeAt(0)] ?? avg;
372
- }
373
- else {
374
- return avg;
324
+ const code = char.codePointAt(0) ?? 0;
325
+ if (code < widths.length) {
326
+ return widths[code] ?? avg;
375
327
  }
328
+ return avg;
376
329
  })
377
330
  .reduce((cur, acc) => acc + cur) * fontSize);
378
331
  };
@@ -383,9 +336,6 @@ const measureText = (str, fontSize = 10) => {
383
336
  * The browser still does the real wrap inside the foreignObject; this is only
384
337
  * used to size the SVG.
385
338
  *
386
- * @param text Text to split.
387
- * @param fontSize Font size in px (matches `measureText`).
388
- * @param maxWidth Available wrap width in px.
389
339
  * @returns Estimated wrapped lines.
390
340
  */
391
341
  const splitWrappedText = (text, fontSize, maxWidth) => {
@@ -402,13 +352,13 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
402
352
  // Korean Hangul (U+AC00–U+D7AF) is intentionally NOT in the CJK range
403
353
  // because Korean wraps at word boundaries by default in HTML.
404
354
  // ASCII whitespace is collapsed to a single space per CSS `white-space: normal;`
405
- const normalizedText = text.replace(/[\t\n\r ]+/g, ' ');
355
+ const normalizedText = text.replaceAll(/[\t\n\r ]+/g, ' ');
406
356
  const tokens = normalizedText.match(/\s|[\u3000-\u9FFF\uFF00-\uFFEF]|[^\s\u3000-\u9FFF\uFF00-\uFFEF]+/g);
407
357
  if (!tokens) {
408
358
  return [];
409
359
  }
410
360
  const takeFittingSegment = (token, availableWidth) => {
411
- const characters = token.split('');
361
+ const characters = [...token];
412
362
  let segment = '';
413
363
  let width = 0;
414
364
  for (const character of characters) {
@@ -432,7 +382,7 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
432
382
  if (currentWidth === 0) {
433
383
  continue;
434
384
  }
435
- lines[lines.length - 1] = (lines[lines.length - 1] ?? '') + token;
385
+ lines[lines.length - 1] = (lines.at(-1) ?? '') + token;
436
386
  currentWidth += measureText(token, fontSize);
437
387
  continue;
438
388
  }
@@ -440,7 +390,7 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
440
390
  while (remaining) {
441
391
  const w = measureText(remaining, fontSize);
442
392
  if (currentWidth + w <= maxWidth) {
443
- lines[lines.length - 1] = (lines[lines.length - 1] ?? '') + remaining;
393
+ lines[lines.length - 1] = (lines.at(-1) ?? '') + remaining;
444
394
  currentWidth += w;
445
395
  break;
446
396
  }
@@ -451,24 +401,38 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
451
401
  }
452
402
  // An atom wider than the box wraps mid-glyph (overflow-wrap: anywhere).
453
403
  const { segment, width } = takeFittingSegment(remaining, maxWidth);
454
- lines[lines.length - 1] = (lines[lines.length - 1] ?? '') + segment;
404
+ lines[lines.length - 1] = (lines.at(-1) ?? '') + segment;
455
405
  currentWidth = width;
456
406
  remaining = remaining.slice(segment.length);
457
407
  }
458
408
  }
459
409
  return lines.map((line) => line.replace(/[\t\n\r ]+$/, ''));
460
410
  };
411
+ /**
412
+ * Split text over multiple lines based on the card width.
413
+ *
414
+ * @returns Array of lines.
415
+ */
416
+ const wrapTextMultiline = (text, width, fontSize, maxLines = 3) => {
417
+ const wrapped = splitWrappedText(text, fontSize, width);
418
+ const lines = wrapped.map((line) => line.trim()).slice(0, maxLines); // Only consider maxLines lines
419
+ // Add "..." to the last line if the text exceeds maxLines
420
+ if (wrapped.length > maxLines) {
421
+ const lastIndex = maxLines - 1;
422
+ const lastLine = lines[lastIndex];
423
+ if (lastLine !== undefined) {
424
+ lines[lastIndex] = `${lastLine}...`;
425
+ }
426
+ }
427
+ // Remove empty lines if text fits in less than maxLines lines
428
+ const multiLineText = lines.filter(Boolean);
429
+ return multiLineText;
430
+ };
461
431
  /**
462
432
  * Estimate how many lines a string will wrap to when laid out greedily at the
463
433
  * given font size inside a box of width `maxWidth`, capped at `maxLines`.
464
434
  *
465
- * @param text Text to estimate.
466
- * @param fontSize Font size in px (matches `measureText`).
467
- * @param maxWidth Available wrap width in px.
468
- * @param maxLines Cap on the returned line count.
469
435
  * @returns Estimated line count, at least 1, at most `maxLines`.
470
436
  */
471
- const countWrappedLines = (text, fontSize, maxWidth, maxLines) => {
472
- return Math.min(Math.max(1, splitWrappedText(text, fontSize, maxWidth).length), maxLines);
473
- };
474
- export { renderError, createLanguageNode, createProgressNode, createTextNode, iconWithLabel, flexLayout, measureText, splitWrappedText, countWrappedLines, wrappedTextNode, wrappedTextStyles, };
437
+ const countWrappedLines = (text, fontSize, maxWidth, maxLines) => Math.min(Math.max(1, splitWrappedText(text, fontSize, maxWidth).length), maxLines);
438
+ export { renderError, createLanguageNode, createProgressNode, createTextNode, iconWithLabel, flexLayout, measureText, splitWrappedText, wrapTextMultiline, countWrappedLines, wrappedTextNode, wrappedTextStyles, };
@@ -1,5 +1,5 @@
1
- import type { CardConfig } from './config.js';
2
- import type { FetcherContext, HttpResponse } from './http.js';
1
+ import type { CardConfig } from './config.ts';
2
+ import type { FetcherContext, HttpResponse } from './http.ts';
3
3
  /**
4
4
  * Error-detection fields the retryer inspects to detect rate-limiting and credential failures.
5
5
  * Every fetcher's payload is intersected with
@@ -23,11 +23,6 @@ type FetcherFunction<TData = unknown, TVariables = Record<string, unknown>> = (v
23
23
  /**
24
24
  * Try to execute the fetcher function until it succeeds or the max number of retries is reached.
25
25
  *
26
- * @template TData Shape of `response.data` returned by the fetcher.
27
- * @template TVariables Variables the fetcher accepts.
28
- * @param fetcher The fetcher function.
29
- * @param variables Object with arguments to pass to the fetcher function.
30
- * @param config Deployment config supplying the PAT pool and the transport.
31
26
  * @returns The response from the fetcher function.
32
27
  */
33
28
  declare const retryer: <TData = unknown, TVariables = Record<string, unknown>>(fetcher: FetcherFunction<TData, TVariables>, variables: TVariables, config: CardConfig) => Promise<FetcherResponse<TData>>;
@@ -1 +1 @@
1
- {"version":3,"file":"retryer.d.ts","sourceRoot":"","sources":["../../src/common/retryer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9C,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAG9D;;;;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,YAAY,CAAC,KAAK,GAAG,cAAc,CAAC,CAAC;AAE7E,KAAK,eAAe,CAAC,KAAK,GAAG,OAAO,EAAE,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,CAC5E,SAAS,EAAE,UAAU,EACrB,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,cAAc,KACpB,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;AAErC;;;;;;;;;GASG;AACH,QAAA,MAAM,OAAO,GAAU,KAAK,GAAG,OAAO,EAAE,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC1E,SAAS,eAAe,CAAC,KAAK,EAAE,UAAU,CAAC,EAC3C,WAAW,UAAU,EACrB,QAAQ,UAAU,KACjB,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,CAkDhC,CAAC;AAEF,OAAO,EAAE,OAAO,EAAE,CAAC;AACnB,YAAY,EAAE,eAAe,EAAE,CAAC"}
1
+ {"version":3,"file":"retryer.d.ts","sourceRoot":"","sources":["../../src/common/retryer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9C,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAG9D;;;;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;AAcD;;;;;GAKG;AACH,KAAK,eAAe,CAAC,KAAK,GAAG,OAAO,IAAI,YAAY,CAAC,KAAK,GAAG,cAAc,CAAC,CAAC;AAE7E,KAAK,eAAe,CAAC,KAAK,GAAG,OAAO,EAAE,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,CAC5E,SAAS,EAAE,UAAU,EACrB,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,cAAc,KACpB,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;AAErC;;;;GAIG;AACH,QAAA,MAAM,OAAO,GAAU,KAAK,GAAG,OAAO,EAAE,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,WACjE,eAAe,CAAC,KAAK,EAAE,UAAU,CAAC,aAChC,UAAU,UACb,UAAU,KACjB,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,CAkDhC,CAAC;AAEF,OAAO,EAAE,OAAO,EAAE,CAAC;AACnB,YAAY,EAAE,eAAe,EAAE,CAAC"}
@@ -6,8 +6,6 @@ import { logger } from './log.js';
6
6
  * The value is generated using `Math.random()` and uniformly distributed
7
7
  * across the range.
8
8
  *
9
- * @param max The upper bound (exclusive). Must be a positive number.
10
- *
11
9
  * @returns A random integer `n` such that `0 <= n < max`.
12
10
  */
13
11
  function getRandomInt(max) {
@@ -16,20 +14,15 @@ function getRandomInt(max) {
16
14
  /**
17
15
  * Try to execute the fetcher function until it succeeds or the max number of retries is reached.
18
16
  *
19
- * @template TData Shape of `response.data` returned by the fetcher.
20
- * @template TVariables Variables the fetcher accepts.
21
- * @param fetcher The fetcher function.
22
- * @param variables Object with arguments to pass to the fetcher function.
23
- * @param config Deployment config supplying the PAT pool and the transport.
24
17
  * @returns The response from the fetcher function.
25
18
  */
26
19
  const retryer = async (fetcher, variables, config) => {
27
20
  const PATs = config.pats;
28
- if (!PATs.length) {
21
+ if (PATs.length === 0) {
29
22
  throw new CardError('No GitHub API tokens found', { code: 'no_tokens' });
30
23
  }
31
24
  const startPAT = getRandomInt(PATs.length);
32
- for (let retries = 0; retries < PATs.length; retries++) {
25
+ for (let retries = 0; retries < PATs.length; retries += 1) {
33
26
  const currentPAT = PATs[(startPAT + retries) % PATs.length];
34
27
  if (!currentPAT) {
35
28
  continue;
@@ -41,7 +34,7 @@ const retryer = async (fetcher, variables, config) => {
41
34
  });
42
35
  // react on both type and message-based rate-limit signals.
43
36
  // https://github.com/anuraghazra/github-readme-stats/issues/4425
44
- const errors = response.data.errors;
37
+ const { errors } = response.data;
45
38
  const errorType = errors?.[0]?.type;
46
39
  const errorMsg = errors?.[0]?.message ?? '';
47
40
  const isRateLimited = (!!errors && errorType === 'RATE_LIMITED') || /rate limit/i.test(errorMsg);
@@ -50,7 +43,7 @@ const retryer = async (fetcher, variables, config) => {
50
43
  continue;
51
44
  }
52
45
  // also checking for bad credentials if any tokens gets invalidated
53
- const message = response.data.message;
46
+ const { message } = response.data;
54
47
  const isBadCredential = message === 'Bad credentials';
55
48
  const isAccountSuspended = message === 'Sorry. Your account was suspended.';
56
49
  if (isBadCredential || isAccountSuspended) {