-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.ts
More file actions
1347 lines (1177 loc) · 49.4 KB
/
Copy pathlib.ts
File metadata and controls
1347 lines (1177 loc) · 49.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// Pure/testable functions extracted from app.ts
// ============================================================================
// These functions contain no DOM dependencies and can be unit tested directly.
// ============================================================================
// Type Definitions
// ============================================================================
export interface GitHubUser {
login?: string;
}
export interface PullRequest {
id: number;
number: number;
title: string | null;
state: 'open' | 'closed';
merged_at: string | null;
created_at: string;
user: GitHubUser | null;
html_url: string | null;
}
export interface PRsByDate {
[date: string]: {
merged: number;
closed: number;
open: number;
};
}
export interface StatusConfig {
class: string;
icon: string;
text: string;
}
export interface StatusConfigMap {
merged: StatusConfig;
closed: StatusConfig;
open: StatusConfig;
}
export interface RateLimitInfo {
limit: number;
remaining: number;
reset: number;
used: number;
}
export interface AllPRCounts {
total: number;
merged: number;
closed: number;
open: number;
}
export interface CacheEntry {
data: PullRequest[];
timestamp: number;
rateLimitInfo: RateLimitInfo | null;
allPRCounts?: AllPRCounts;
allMergedPRs?: PullRequest[];
}
export interface SearchResponse {
total_count: number;
incomplete_results: boolean;
items: SearchIssueItem[];
}
export interface SearchIssueItem {
id: number;
number: number;
title: string | null;
state: 'open' | 'closed';
created_at: string;
user: GitHubUser | null;
html_url: string | null;
pull_request?: {
merged_at: string | null;
};
}
// ============================================================================
// GraphQL Types
// ============================================================================
export interface GraphQLResponse<T> {
data?: T;
errors?: Array<{ message: string; type?: string; path?: string[] }>;
}
export interface GraphQLRateLimit {
limit: number;
remaining: number;
resetAt: string;
cost: number;
used: number;
}
export interface GraphQLSearchResult {
issueCount: number;
pageInfo: {
hasNextPage: boolean;
endCursor: string | null;
};
nodes: GraphQLPullRequest[];
}
export interface GraphQLPullRequest {
databaseId: number;
number: number;
title: string | null;
state: 'OPEN' | 'CLOSED' | 'MERGED';
createdAt: string;
mergedAt: string | null;
url: string;
author: { login: string } | null;
}
export interface CombinedQueryData {
copilotPRs: GraphQLSearchResult;
allMergedPRs: GraphQLSearchResult;
totalCount: { issueCount: number };
mergedCount: { issueCount: number };
openCount: { issueCount: number };
rateLimit: GraphQLRateLimit;
}
export interface SingleSearchQueryData {
search: GraphQLSearchResult;
rateLimit: GraphQLRateLimit;
}
// ============================================================================
// Constants
// ============================================================================
export const ITEMS_PER_PAGE = 10;
export const CACHE_KEY_PREFIX = 'copilot_pr_cache_';
export const CACHE_VERSION = 'v3';
export const CACHE_DURATION_MS = 5 * 60 * 1000; // 5 minutes
export const CACHE_CLEANUP_INTERVAL_MS = 60 * 1000; // 1 minute
// ============================================================================
// GraphQL Utilities
// ============================================================================
/**
* Converts GraphQL PullRequest nodes to internal PullRequest format.
* GraphQL state MERGED/CLOSED both map to state:'closed'; merged_at distinguishes them.
*/
export function convertGraphQLPRs(nodes: GraphQLPullRequest[]): PullRequest[] {
return nodes.map(pr => ({
id: pr.databaseId,
number: pr.number,
title: pr.title,
state: pr.state === 'OPEN' ? 'open' as const : 'closed' as const,
merged_at: pr.mergedAt,
created_at: pr.createdAt,
user: pr.author ? { login: pr.author.login } : null,
html_url: pr.url,
}));
}
/**
* Converts a GraphQL rate limit object to our internal RateLimitInfo format.
*/
export function convertGraphQLRateLimit(rl: GraphQLRateLimit): RateLimitInfo {
return {
limit: rl.limit,
remaining: rl.remaining,
reset: Math.floor(new Date(rl.resetAt).getTime() / 1000),
used: rl.used,
};
}
// ============================================================================
// GraphQL Query Constants
// ============================================================================
/** Inline PR fields for use inside search query nodes (union type requires type condition) */
const GRAPHQL_PR_INLINE_FIELDS = `... on PullRequest {
databaseId
number
title
state
createdAt
mergedAt
url
author { login }
}`;
/**
* Combined query: fetches Copilot PRs + all PR counts in a single request.
* Uses aliases to run multiple search queries simultaneously.
*/
export const GRAPHQL_COMBINED_QUERY = `
query CopilotDashboard($copilotQuery: String!, $mergedAllQuery: String!, $totalQuery: String!, $mergedQuery: String!, $openQuery: String!, $first: Int!, $after: String) {
copilotPRs: search(query: $copilotQuery, type: ISSUE, first: $first, after: $after) {
issueCount
pageInfo { hasNextPage endCursor }
nodes { ${GRAPHQL_PR_INLINE_FIELDS} }
}
# Note: allMergedPRs is hardcoded to first 100 items without $after pagination.
# Additional pages are fetched separately via fetchMergedPRsWithPagination().
allMergedPRs: search(query: $mergedAllQuery, type: ISSUE, first: 100) {
issueCount
pageInfo { hasNextPage endCursor }
nodes { ${GRAPHQL_PR_INLINE_FIELDS} }
}
totalCount: search(query: $totalQuery, type: ISSUE, first: 1) { issueCount }
mergedCount: search(query: $mergedQuery, type: ISSUE, first: 1) { issueCount }
openCount: search(query: $openQuery, type: ISSUE, first: 1) { issueCount }
rateLimit { limit remaining resetAt cost used }
}
`;
/**
* Simple search query for pagination and single-purpose fetches.
*/
export const GRAPHQL_SEARCH_QUERY = `
query SearchQuery($query: String!, $first: Int!, $after: String) {
search(query: $query, type: ISSUE, first: $first, after: $after) {
issueCount
pageInfo { hasNextPage endCursor }
nodes { ${GRAPHQL_PR_INLINE_FIELDS} }
}
rateLimit { limit remaining resetAt cost used }
}
`;
// ============================================================================
// HTML Escaping & Sanitization
// ============================================================================
/**
* Escapes HTML special characters to prevent XSS attacks.
*/
export function escapeHtml(text: string | null | undefined): string {
if (text == null) return '';
return String(text)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/**
* Sanitizes a URL to prevent XSS attacks.
* Only allows HTTPS URLs from github.com.
*/
export function sanitizeUrl(url: string | null | undefined): string {
if (url == null) return '#';
try {
const parsedUrl = new URL(String(url).trim());
if (parsedUrl.protocol === 'https:' && parsedUrl.hostname === 'github.com') {
return parsedUrl.href;
}
} catch {
// Invalid URL
}
return '#';
}
// ============================================================================
// Input Validation
// ============================================================================
/**
* Validates GitHub owner/repo segments using a conservative allowlist.
* Rejects "." and ".." and only allows letters, numbers, hyphens, underscores, and periods.
*/
export function isValidGitHubName(name: string): boolean {
if (!name || name === '.' || name === '..') {
return false;
}
const validPattern = /^[A-Za-z0-9_.-]+$/;
return validPattern.test(name);
}
/**
* Parses and validates the repository input string.
* Returns { owner, repo } on success, or an error message string on failure.
*/
export function parseRepoInput(repoInput: string): { owner: string; repo: string } | string {
const trimmed = repoInput.trim();
const [owner, repo, ...rest] = trimmed.split('/');
if (!owner || !repo || rest.length > 0) {
return 'Please enter repository in "owner/repo" format';
}
if (!isValidGitHubName(owner) || !isValidGitHubName(repo)) {
return 'Invalid repository name. Names can only contain letters, numbers, hyphens, underscores, and periods.';
}
return { owner, repo };
}
/**
* Validates that date strings parse to valid dates and that fromDate is not after toDate.
*/
export function validateDateRange(fromDate: string, toDate: string): string | null {
const from = new Date(fromDate);
const to = new Date(toDate);
if (isNaN(from.getTime()) || isNaN(to.getTime())) {
return 'Invalid date format';
}
if (from > to) {
return 'Start date must be before end date';
}
return null;
}
// ============================================================================
// Date Range Splitting
// ============================================================================
/**
* Splits a date range into non-overlapping segments.
* Used to overcome GitHub Search API's 1,000 result limit per query.
* Each segment covers a contiguous portion of the date range with no overlap.
*/
export function splitDateRange(fromDate: string, toDate: string, segments: number): Array<{ from: string; to: string }> {
const dayMs = 24 * 60 * 60 * 1000;
const start = new Date(fromDate + 'T00:00:00Z');
const end = new Date(toDate + 'T00:00:00Z');
const totalDays = Math.round((end.getTime() - start.getTime()) / dayMs) + 1;
const actualSegments = Math.min(Math.max(1, segments), totalDays);
if (actualSegments <= 1) {
return [{ from: fromDate, to: toDate }];
}
const ranges: Array<{ from: string; to: string }> = [];
let currentDay = 0;
for (let i = 0; i < actualSegments; i++) {
const remainingSegments = actualSegments - i;
const remainingDays = totalDays - currentDay;
const daysInSegment = Math.ceil(remainingDays / remainingSegments);
const segStart = new Date(start.getTime() + currentDay * dayMs);
const segEnd = i === actualSegments - 1
? end
: new Date(start.getTime() + (currentDay + daysInSegment - 1) * dayMs);
ranges.push({
from: segStart.toISOString().split('T')[0],
to: segEnd.toISOString().split('T')[0],
});
currentDay += daysInSegment;
}
return ranges;
}
// ============================================================================
// Cache Functions
// ============================================================================
export function getCacheKey(owner: string, repo: string, fromDate: string, toDate: string, hasToken: boolean): string {
const authSuffix = hasToken ? '_auth' : '_noauth';
const paramsKey = JSON.stringify({ owner, repo, fromDate, toDate });
return `${CACHE_KEY_PREFIX}${CACHE_VERSION}_${paramsKey}${authSuffix}`;
}
function isValidAllPRCounts(value: unknown): value is AllPRCounts {
if (typeof value !== 'object' || value === null) return false;
const obj = value as Record<string, unknown>;
return (
typeof obj.total === 'number' &&
typeof obj.merged === 'number' &&
typeof obj.closed === 'number' &&
typeof obj.open === 'number'
);
}
function isValidRateLimitInfo(value: unknown): value is RateLimitInfo | null {
if (value === null) return true;
if (typeof value !== 'object') return false;
const obj = value as Record<string, unknown>;
return (
typeof obj.limit === 'number' &&
typeof obj.remaining === 'number' &&
typeof obj.reset === 'number' &&
typeof obj.used === 'number'
);
}
/**
* Type guard that validates a parsed object conforms to the CacheEntry schema.
*/
export function isCacheEntry(value: unknown): value is CacheEntry {
if (typeof value !== 'object' || value === null) return false;
const obj = value as Record<string, unknown>;
if (!Array.isArray(obj.data)) return false;
if (typeof obj.timestamp !== 'number') return false;
if (!isValidRateLimitInfo(obj.rateLimitInfo)) return false;
// Optional comparison data validation
if (obj.allPRCounts !== undefined && !isValidAllPRCounts(obj.allPRCounts)) return false;
if (obj.allMergedPRs !== undefined && !Array.isArray(obj.allMergedPRs)) return false;
return true;
}
export function getFromCache(cacheKey: string, storage: Storage = localStorage): CacheEntry | null {
try {
const cached = storage.getItem(cacheKey);
if (!cached) return null;
const parsed: unknown = JSON.parse(cached);
if (!isCacheEntry(parsed)) {
storage.removeItem(cacheKey);
return null;
}
const now = Date.now();
if (now - parsed.timestamp > CACHE_DURATION_MS) {
storage.removeItem(cacheKey);
return null;
}
return parsed;
} catch {
return null;
}
}
export function saveToCache(cacheKey: string, data: PullRequest[], rateLimitInfo: RateLimitInfo | null, allPRCounts?: AllPRCounts, allMergedPRs?: PullRequest[], storage: Storage = localStorage): void {
try {
const entry: CacheEntry = {
data,
timestamp: Date.now(),
rateLimitInfo,
};
if (allPRCounts) entry.allPRCounts = allPRCounts;
if (allMergedPRs !== undefined) entry.allMergedPRs = allMergedPRs;
storage.setItem(cacheKey, JSON.stringify(entry));
} catch {
// Cache save failed (e.g., localStorage full), ignore
}
}
export function updateCacheWithComparison(cacheKey: string, allPRCounts: AllPRCounts, allMergedPRs: PullRequest[], rateLimitInfo: RateLimitInfo | null, storage: Storage = localStorage): void {
try {
const cached = storage.getItem(cacheKey);
if (!cached) return;
const parsed: unknown = JSON.parse(cached);
if (!isCacheEntry(parsed)) return;
parsed.allPRCounts = allPRCounts;
parsed.allMergedPRs = allMergedPRs;
if (rateLimitInfo) parsed.rateLimitInfo = rateLimitInfo;
storage.setItem(cacheKey, JSON.stringify(parsed));
} catch {
// ignore
}
}
let lastCacheCleanupTime = 0;
export function resetCacheCleanupTimer(): void {
lastCacheCleanupTime = 0;
}
export function clearOldCache(storage: Storage = localStorage): void {
const now = Date.now();
if (now - lastCacheCleanupTime < CACHE_CLEANUP_INTERVAL_MS) {
return; // Skip if cleaned recently
}
lastCacheCleanupTime = now;
try {
const keysToRemove: string[] = [];
const currentVersionPrefix = `${CACHE_KEY_PREFIX}${CACHE_VERSION}_`;
for (let i = 0; i < storage.length; i++) {
const key = storage.key(i);
if (key?.startsWith(CACHE_KEY_PREFIX)) {
if (!key.startsWith(currentVersionPrefix)) {
keysToRemove.push(key);
continue;
}
const cached = storage.getItem(key);
if (cached) {
try {
const entry: CacheEntry = JSON.parse(cached);
if (Date.now() - entry.timestamp > CACHE_DURATION_MS) {
keysToRemove.push(key);
}
} catch {
keysToRemove.push(key);
}
}
}
}
keysToRemove.forEach(key => storage.removeItem(key));
} catch {
// Ignore cache cleanup errors
}
}
// ============================================================================
// Rate Limit Functions
// ============================================================================
/**
* Extracts rate limit information from response headers.
* Accepts a Headers-like object (or a real Response for convenience).
*/
export function extractRateLimitInfo(headers: { get(name: string): string | null }): RateLimitInfo | null {
const limit = headers.get('X-RateLimit-Limit');
const remaining = headers.get('X-RateLimit-Remaining');
const reset = headers.get('X-RateLimit-Reset');
const usedHeader = headers.get('X-RateLimit-Used');
if (!limit || !remaining || !reset) {
return null;
}
const limitNum = parseInt(limit, 10);
const remainingNum = parseInt(remaining, 10);
const resetNum = parseInt(reset, 10);
if (Number.isNaN(limitNum) || Number.isNaN(remainingNum) || Number.isNaN(resetNum)) {
return null;
}
let usedNum: number;
if (usedHeader !== null) {
usedNum = parseInt(usedHeader, 10);
if (Number.isNaN(usedNum)) {
return null;
}
} else {
usedNum = limitNum - remainingNum;
if (Number.isNaN(usedNum)) {
return null;
}
}
return {
limit: limitNum,
remaining: remainingNum,
reset: resetNum,
used: usedNum
};
}
export function formatCountdown(resetTimestamp: number): string {
const now = Date.now();
const diffMs = resetTimestamp * 1000 - now;
const diffSecs = Math.max(0, Math.floor(diffMs / 1000));
const minutes = Math.floor(diffSecs / 60);
const seconds = diffSecs % 60;
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
/**
* Determines rate limit status based on remaining and limit.
*/
export function getRateLimitStatus(remaining: number, limit: number): { statusText: string; isAuthenticated: boolean } {
const isAuthenticated = limit > 10;
let statusText: string;
if (remaining > limit * 0.5) {
statusText = 'Good';
} else if (remaining > limit * 0.2) {
statusText = 'Warning';
} else {
statusText = 'Low';
}
return { statusText, isAuthenticated };
}
// ============================================================================
// Pagination
// ============================================================================
export function getPageNumbersToShow(current: number, total: number): (number | string)[] {
const pages: (number | string)[] = [];
const delta = 1;
if (total <= 7) {
for (let i = 1; i <= total; i++) {
pages.push(i);
}
} else {
pages.push(1);
if (current > delta + 2) {
pages.push('...');
}
const start = Math.max(2, current - delta);
const end = Math.min(total - 1, current + delta);
for (let i = start; i <= end; i++) {
pages.push(i);
}
if (current < total - delta - 1) {
pages.push('...');
}
pages.push(total);
}
return pages;
}
// ============================================================================
// PR Classification Logic
// ============================================================================
export interface PRCounts {
total: number;
merged: number;
closed: number;
open: number;
mergeRate: number;
}
/**
* Classifies PRs into merged, closed (not merged), and open categories.
*/
export function classifyPRs(prs: PullRequest[]): PRCounts {
const merged = prs.filter(pr => pr.merged_at !== null);
const closed = prs.filter(pr => pr.state === 'closed' && pr.merged_at === null);
const open = prs.filter(pr => pr.state === 'open' && pr.merged_at === null);
const mergeRate = prs.length > 0
? Math.round((merged.length / prs.length) * 100)
: 0;
return {
total: prs.length,
merged: merged.length,
closed: closed.length,
open: open.length,
mergeRate
};
}
export function calculateResponseTimes(prs: PullRequest[]): ResponseTimeMetrics | null {
const mergedPRs = prs.filter(pr => pr.merged_at !== null);
const hours = mergedPRs
.map(pr => {
const created = new Date(pr.created_at).getTime();
const merged = new Date(pr.merged_at!).getTime();
return (merged - created) / (1000 * 60 * 60);
})
.filter(h => Number.isFinite(h) && h >= 0);
if (hours.length === 0) return null;
const sorted = [...hours].sort((a, b) => a - b);
const average = sorted.reduce((sum, h) => sum + h, 0) / sorted.length;
const fastest = sorted[0];
const slowest = sorted[sorted.length - 1];
let median: number;
const mid = Math.floor(sorted.length / 2);
if (sorted.length % 2 === 0) {
median = (sorted[mid - 1] + sorted[mid]) / 2;
} else {
median = sorted[mid];
}
const bucketDefs: { label: string; min: number; max: number }[] = [
{ label: '<1h', min: 0, max: 1 },
{ label: '1-6h', min: 1, max: 6 },
{ label: '6-24h', min: 6, max: 24 },
{ label: '1-3d', min: 24, max: 72 },
{ label: '3-7d', min: 72, max: 168 },
{ label: '7d+', min: 168, max: Infinity },
];
const buckets = bucketDefs.map(def => ({
label: def.label,
count: hours.filter(h => h >= def.min && h < def.max).length,
}));
buckets[buckets.length - 1].count = hours.filter(h => h >= 168).length;
return {
average,
median,
fastest,
slowest,
buckets,
totalMerged: hours.length,
};
}
export function formatDuration(hours: number): string {
if (!Number.isFinite(hours)) return '0 min';
hours = Math.max(0, hours);
if (hours < 1) {
const mins = Math.round(hours * 60);
if (mins >= 60) return '1.0 hours';
return `${mins} min`;
}
if (hours < 24) {
const fixed = parseFloat(hours.toFixed(1));
if (fixed >= 24) return `${(fixed / 24).toFixed(1)} days`;
return `${hours.toFixed(1)} hours`;
}
return `${(hours / 24).toFixed(1)} days`;
}
export function generateResponseTimeStatsHtml(metrics: ResponseTimeMetrics, othersMetrics?: ResponseTimeMetrics | null): string {
const entries = [
{ label: 'Average Response Time', value: metrics.average, othersValue: othersMetrics?.average, description: 'The arithmetic mean of the time from PR creation to merge across all merged PRs.' },
{ label: 'Median Response Time', value: metrics.median, othersValue: othersMetrics?.median, description: 'The middle value of response times when sorted. Less affected by outliers than the average.' },
{ label: 'Fastest PR', value: metrics.fastest, othersValue: othersMetrics?.fastest, description: 'The shortest time from PR creation to merge among all merged PRs.' },
{ label: 'Slowest PR', value: metrics.slowest, othersValue: othersMetrics?.slowest, description: 'The longest time from PR creation to merge among all merged PRs.' },
];
const showComparison = othersMetrics !== undefined;
return entries.map(entry => {
const mainValue = formatDuration(entry.value);
const tooltipId = entry.label.toLowerCase().replace(/\s+/g, '-') + '-tooltip';
const valueHtml = showComparison
? `<div class="space-y-1.5">
<div class="flex items-center gap-2">
<span class="text-xs font-semibold px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300">Copilot</span>
<span class="text-xl font-bold text-slate-800 dark:text-slate-100">${mainValue}</span>
</div>
<div class="flex items-center gap-2">
<span class="text-xs font-semibold px-1.5 py-0.5 rounded bg-indigo-100 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300">Others</span>
<span class="text-xl font-bold text-slate-800 dark:text-slate-100">${entry.othersValue != null ? formatDuration(entry.othersValue) : '-'}</span>
</div>
</div>`
: `<p class="text-2xl font-bold text-slate-800 dark:text-slate-100">${mainValue}</p>`;
return `
<div class="glass-card rounded-2xl p-6 relative overflow-hidden">
<div class="absolute top-0 right-0 w-32 h-32 bg-linear-to-br from-amber-500/10 to-orange-500/10 rounded-full -translate-y-16 translate-x-16"></div>
<div class="relative">
<div class="flex items-center gap-2 mb-3">
<div class="p-2 rounded-lg bg-linear-to-br from-amber-500 to-orange-500">
<svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="10"></circle>
<polyline points="12 6 12 12 16 14"></polyline>
</svg>
</div>
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">${escapeHtml(entry.label)}</span>
<div class="relative group">
<button type="button" class="p-0.5 rounded-full text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:focus-visible:ring-offset-slate-900" aria-label="${escapeHtml(entry.label)} description" aria-describedby="${tooltipId}">
<span class="inline-flex items-center justify-center w-4 h-4 rounded-full border border-current text-[10px] font-bold leading-none" aria-hidden="true">?</span>
</button>
<div id="${tooltipId}" class="absolute left-1/2 -translate-x-1/2 top-full mt-2 w-56 p-3 rounded-xl bg-white dark:bg-slate-800 shadow-lg border border-slate-200 dark:border-slate-700 text-sm text-slate-600 dark:text-slate-300 opacity-0 invisible group-hover:opacity-100 group-hover:visible group-focus-within:opacity-100 group-focus-within:visible transition-all duration-200 z-50" role="tooltip">
<p>${escapeHtml(entry.description)}</p>
</div>
</div>
</div>
${valueHtml}
</div>
</div>
`;
}).join('');
}
// ============================================================================
// Chart Data Preparation
// ============================================================================
export interface ChartData {
dates: string[];
mergedData: number[];
closedData: number[];
openData: number[];
}
export interface ResponseTimeMetrics {
average: number; // 平均所要時間(hours)
median: number; // 中央値(hours)
fastest: number; // 最速(hours)
slowest: number; // 最遅(hours)
buckets: { label: string; count: number }[]; // ヒストグラム用バケット(6個)
totalMerged: number; // 対象マージ済みPR数
}
/**
* Groups PRs by date and generates chart data.
*/
export function prepareChartData(prs: PullRequest[], fromDate: string, toDate: string): ChartData {
const prsByDate: PRsByDate = {};
prs.forEach(pr => {
const date = new Date(pr.created_at).toISOString().split('T')[0];
if (!prsByDate[date]) {
prsByDate[date] = { merged: 0, closed: 0, open: 0 };
}
if (pr.merged_at) {
prsByDate[date].merged++;
} else if (pr.state === 'closed') {
prsByDate[date].closed++;
} else {
prsByDate[date].open++;
}
});
const dates: string[] = [];
if (fromDate && toDate) {
const startDate = new Date(fromDate);
const endDate = new Date(toDate);
const currentDate = new Date(startDate);
while (currentDate <= endDate) {
dates.push(currentDate.toISOString().split('T')[0]);
currentDate.setDate(currentDate.getDate() + 1);
}
} else {
dates.push(...Object.keys(prsByDate).sort());
}
const mergedData = dates.map(date => prsByDate[date]?.merged ?? 0);
const closedData = dates.map(date => prsByDate[date]?.closed ?? 0);
const openData = dates.map(date => prsByDate[date]?.open ?? 0);
return { dates, mergedData, closedData, openData };
}
// ============================================================================
// API Error Message Generation
// ============================================================================
/**
* Generates an appropriate error message based on HTTP status code and response.
*/
export function getApiErrorMessage(
status: number,
rateLimitInfo: RateLimitInfo | null,
responseBody?: { message?: string; errors?: Array<{ message?: string }> }
): string {
if (status === 404) {
return 'Repository not found';
}
if (status === 401) {
return 'Authentication failed. Please check that your GitHub token is valid.';
}
if (status === 403) {
const isRateLimit = rateLimitInfo?.remaining === 0;
if (isRateLimit) {
const resetTime = rateLimitInfo?.reset
? new Date(rateLimitInfo.reset * 1000).toLocaleString('en-US', { timeZoneName: 'short' })
: 'unknown';
return `API rate limit reached. Reset at: ${resetTime}. Try again later or use a different token.`;
} else {
return 'Access forbidden (HTTP 403). This may be due to insufficient permissions, SSO not being authorized, or temporary abuse protection on the GitHub API.';
}
}
if (status === 422) {
const detail = responseBody?.errors?.[0]?.message ?? '';
if (detail.toLowerCase().includes('cannot be searched')) {
return (
'Search query validation failed. The repository or author filter could not be resolved. ' +
'This may happen if the repository does not exist, you do not have permission to access it, ' +
'or the Copilot Coding Agent app is not installed on the repository. ' +
'Please verify the repository name and ensure your token has access.'
);
}
return `Search query validation failed. ${detail || 'Please check the repository name.'}`;
}
return `GitHub API Error: ${status}`;
}
// ============================================================================
// Search Result Processing
// ============================================================================
/**
* Converts search API items to PullRequest format.
*/
export function convertSearchItemsToPRs(items: SearchIssueItem[]): PullRequest[] {
return items.map(item => ({
id: item.id,
number: item.number,
title: item.title,
state: item.state,
merged_at: item.pull_request?.merged_at ?? null,
created_at: item.created_at,
user: item.user,
html_url: item.html_url
}));
}
/**
* Builds the search query string for copilot PRs.
*/
export function buildSearchQuery(owner: string, repo: string, fromDate: string, toDate: string): string {
return `repo:${owner}/${repo} is:pr author:app/copilot-swe-agent created:${fromDate}..${toDate}`;
}
/**
* Builds the search URL for GitHub API.
*/
export function buildSearchUrl(query: string, perPage: number, page: number): string {
return `https://api.github.com/search/issues?q=${encodeURIComponent(query)}&per_page=${perPage}&page=${page}&sort=created&order=desc`;
}
/**
* Builds request headers for GitHub API.
*/
export function buildApiHeaders(token: string): Record<string, string> {
const headers: Record<string, string> = {
'Accept': 'application/vnd.github.v3+json'
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
return headers;
}
/**
* Adjusts closed PR count by subtracting merged PRs.
* GitHub's "closed" state includes both merged and unmerged PRs.
*/
export function adjustClosedCount(
counts: AllPRCounts,
succeeded: Set<string>
): AllPRCounts {
const adjusted = { ...counts };
if (succeeded.has('closed') && succeeded.has('merged')) {
adjusted.closed = Math.max(0, adjusted.closed - adjusted.merged);
} else if (succeeded.has('closed') && !succeeded.has('merged')) {
adjusted.closed = 0;
}
return adjusted;
}
// ============================================================================
// PR Number Display
// ============================================================================
/**
* Formats PR number for display. Returns empty string for invalid numbers.
*/
export function formatPRNumber(num: number): string {
return Number.isSafeInteger(num) && num > 0 ? `#${num}` : '';
}
// ============================================================================
// Ratio Display
// ============================================================================
/**
* Creates HTML for ratio display (copilot count / total count).
*/
export function createRatioHtml(copilotCount: number, totalCount: number, colorClass: string): string {
if (totalCount > 0) {
return `<span class="text-4xl font-bold ${colorClass}">${copilotCount}</span><span class="text-lg text-slate-500 dark:text-slate-400 ml-1">/ ${totalCount}</span>`;
}
return `<span class="text-4xl font-bold ${colorClass}">${copilotCount}</span><span class="text-lg text-slate-500 dark:text-slate-400 ml-1">/ -</span>`;
}
// ============================================================================
// Sort Functions
// ============================================================================
/**
* Sorts PRs by created date (newest first).
*/
export function sortPRsByDate(prs: PullRequest[]): PullRequest[] {
return [...prs].sort((a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
);
}
/**
* Filter type for PR status: 'all' shows everything, others match the PR status.
*/
export type PRFilterStatus = 'all' | 'merged' | 'closed' | 'open';
/**
* Filters PRs by status and/or search text.
* Pure function with no DOM dependencies.
*/
export function filterPRs(
prs: PullRequest[],
statusFilter: PRFilterStatus,
searchText: string
): PullRequest[] {
let filtered = prs;
// Filter by status