Repository navigation
Expand file tree
/
Copy pathauto-detect-newman.html
More file actions
1023 lines (909 loc) · 31.9 KB
/
Copy pathauto-detect-newman.html
File metadata and controls
1023 lines (909 loc) · 31.9 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enhanced Swagger Coverage Report</title>
<!-- Basic Material-like style + dark theme classes -->
<style>
:root {
--md-bg-color: #fafafa;
--md-text-color: #212121;
--md-surface-color: #ffffff;
--md-table-header-bg: #f5f5f5;
--md-table-hover: #eee;
--md-subtable-bg: #e0f2e9; /* soft green for sub-tables */
--md-primary-color: #6200ee; /* example, can adapt */
--md-border-color: #ccc;
}
.dark-theme {
--md-bg-color: #121212;
--md-text-color: #eeeeee;
--md-surface-color: #1e1e1e;
--md-table-header-bg: #2a2a2a;
--md-table-hover: #333333;
--md-subtable-bg: #224f3b; /* darker green for sub-table in dark theme */
--md-border-color: #666;
}
body {
margin: 0;
font-family: "Roboto", sans-serif;
background-color: var(--md-bg-color);
color: var(--md-text-color);
}
header {
padding: 16px;
background-color: var(--md-surface-color);
position: relative;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
h1 {
margin: 0 0 8px 0;
font-size: 1.6rem;
}
.meta-info {
font-size: 0.9em;
opacity: 0.8;
}
.theme-toggle {
position: absolute;
top: 16px;
right: 16px;
background: none;
border: none;
cursor: pointer;
font-size: 1.4rem;
opacity: 0.7;
transition: opacity 0.3s;
}
.theme-toggle:hover {
opacity: 1;
}
.top-buttons {
padding: 8px 16px;
display: flex;
justify-content: flex-end;
gap: 10px;
}
button {
cursor: pointer;
border: none;
border-radius: 20px;
padding: 8px 16px;
background-color: var(--md-primary-color);
color: #fff;
font-weight: 500;
font-size: 0.9rem;
letter-spacing: 0.5px;
}
button:hover {
background-color: #3700b3;
}
.coverage-section {
display: flex;
flex-wrap: wrap;
justify-content: center; /* Center containers horizontally */
gap: 20px;
padding: 16px;
}
.chart-container {
width: 300px;
max-width: 50%;
position: relative;
height: 400px; /* Fixed height for chart */
margin-bottom: 30px; /* Add bottom margin */
}
/* Special styling for tag chart container */
.chart-container:nth-child(3) {
width: 750px; /* 300px * 2.5 = 750px */
max-width: 100%; /* Allow full width */
}
/* При большом количестве тегов увеличиваем высоту */
@media (min-height: 1000px) {
.chart-container {
height: 600px; /* Increase height for many tags */
}
}
.chart-title {
text-align: center;
margin: 0.5rem 0;
font-size: 0.9rem;
opacity: 0.8;
}
.coverage-text {
min-width: 180px;
}
.trend-chart-container {
width: 300px;
max-width: 50%;
position: relative;
}
.filter-container {
padding: 0 16px 16px 16px;
display: flex;
align-items: center;
gap: 16px;
}
.search-container {
position: relative;
flex: 1;
max-width: 300px;
}
.search-input {
width: 100%;
padding: 8px 16px;
border: 1px solid var(--md-primary-color);
border-radius: 20px;
outline: none;
background: var(--md-surface-color);
color: var(--md-text-color);
font-size: 0.9rem;
transition: border-color 0.3s, box-shadow 0.3s;
}
.search-input:focus {
border-color: var(--md-primary-color);
box-shadow: 0 0 0 2px rgba(98, 0, 238, 0.2);
}
.search-input::placeholder {
color: rgba(0, 0, 0, 0.5);
}
.dark-theme .search-input::placeholder {
color: rgba(255, 255, 255, 0.5);
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 40px;
}
th, td {
border: 1px solid var(--md-border-color);
padding: 8px;
}
th {
background-color: var(--md-table-header-bg);
text-align: left;
cursor: pointer;
}
tr:hover {
background-color: var(--md-table-hover);
}
tr.unmatched-spec > td.spec-cell {
background-color: rgba(255,229,229, 0.7); /* light red */
}
tr.spec-row.matched {
cursor: pointer;
}
.matched-requests-row {
display: none;
}
.postman-table {
border: 1px solid var(--md-border-color);
margin-top: 5px;
width: 100%;
background-color: var(--md-subtable-bg);
}
.postman-table th {
background-color: rgba(255,255,255,0.2);
}
/* Smart Mapping Badges */
.primary-match-badge {
background-color: #4caf50;
color: white;
padding: 2px 6px;
border-radius: 10px;
font-size: 10px;
margin-left: 5px;
font-weight: bold;
}
.confidence-badge {
background-color: #2196f3;
color: white;
padding: 2px 6px;
border-radius: 10px;
font-size: 10px;
margin-left: 5px;
font-weight: bold;
}
/* Nested JS Code Table */
.js-code-row {
display: none;
}
.js-code-table {
width: 100%;
border-collapse: collapse;
margin-top: 5px;
background-color: #f0f0f0; /* Light grey for code table */
}
.js-code-table th, .js-code-table td {
border: 1px solid #ddd;
padding: 8px;
}
.js-code-table th {
background-color: #e0e0e0;
text-align: left;
}
/* Footer */
footer {
text-align: center;
font-size: 0.9em;
opacity: 0.6;
margin: 16px;
}
/* Highlight.js Styles */
/* Выберите тему по вашему усмотрению на https://highlightjs.org/static/demo/ */
.hljs {
background: none;
color: inherit;
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-literal,
.hljs-section,
.hljs-link {
color: #d73a49;
font-weight: bold;
}
.hljs-string,
.hljs-title,
.hljs-name,
.hljs-type,
.hljs-attr,
.hljs-number,
.hljs-selector-id,
.hljs-selector-class {
color: #005cc5;
}
.hljs-comment,
.hljs-quote {
color: #6a737d;
font-style: italic;
}
.hljs-doctag,
.hljs-meta,
.hljs-tag .hljs-attr {
color: #22863a;
font-weight: bold;
}
.hljs-title.class_,
.hljs-title.class_.inherited__,
.hljs-title.function_,
.hljs-title.function_.inherited__ {
color: #6f42c1;
}
.badge {
display: inline-block;
padding: 2px 6px;
margin: 1px;
border-radius: 4px;
font-size: 0.85em;
}
.badge-green { background: #c8e6c9; color: #2e7d32; }
.badge-yellow { background: #fff9c4; color: #f57f17; }
.badge-red { background: #ffcdd2; color: #c62828; }
.eye-btn {
background: none;
border: none;
cursor: pointer;
font-size: 1.2em;
opacity: 0.7;
transition: opacity 0.2s;
}
.eye-btn:hover { opacity: 1; }
/* Tooltip styles */
[data-tooltip] {
position: relative;
cursor: help;
}
[data-tooltip]:hover:after {
content: attr(data-tooltip);
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
padding: 4px 8px;
background: rgba(0, 0, 0, 0.8);
color: white;
border-radius: 4px;
font-size: 12px;
white-space: nowrap;
z-index: 100;
margin-bottom: 4px;
}
/* Ensure tooltips are visible even in dark theme */
.dark-theme [data-tooltip]:hover:after {
background: rgba(255, 255, 255, 0.9);
color: black;
}
.recommendation-icon {
display: inline-block;
width: 24px;
height: 24px;
line-height: 24px;
text-align: center;
background-color: #ffd700;
color: #000;
border-radius: 50%;
cursor: pointer;
font-weight: bold;
}
.recommendation-text {
display: none;
}
.recommendation-text.visible {
display: block;
}
/* Update the code-toggle style to remove background color */
.code-toggle {
display: inline-block;
color: #ffd700;
cursor: pointer;
font-family: monospace;
font-weight: bold;
font-size: 14px;
transition: opacity 0.2s;
}
.code-toggle:hover {
opacity: 0.8;
}
</style>
</head>
<body>
<header>
<h1>Swagger Coverage Report</h1>
<button class="theme-toggle" id="themeToggleBtn" onclick="toggleTheme()">
🔆 <!-- flashlight icon -->
</button>
<div class="meta-info">
<p><strong>Timestamp:</strong> 10/9/2025, 11:28:33 AM</p>
<p><strong>API Spec:</strong> Test API</p>
<p><strong>Postman Collection:</strong> Test Newman Collection</p>
<p><strong>Coverage:</strong> 40.00%</p>
<p>Covered: 40.00%<br/>
Not Covered: 60.00%</p>
</div>
</header>
<div class="top-buttons">
<!-- Button to export to PDF -->
<button onclick="exportToPDF()">Export PDF</button>
</div>
<section class="coverage-section">
<!-- Coverage Pie Chart -->
<div class="chart-container">
<canvas id="coverageChart"></canvas>
<div class="chart-title">Overall Coverage</div>
</div>
<!-- Trend chart container -->
<div class="trend-chart-container">
<canvas id="trendChart"></canvas>
<div class="chart-title">Coverage Trend Over Time</div>
</div>
<!-- Tag coverage chart container -->
<div class="chart-container">
<canvas id="tagChart"></canvas>
<div class="chart-title">Coverage by Tag</div>
</div>
</section>
<div class="filter-container">
<button class="filter-button" id="filterBtn" onclick="cycleFilterMode()">
Show: All
</button>
<div class="search-container">
<input type="text"
class="search-input"
id="searchInput"
placeholder="Search..."
oninput="filterTable()">
</div>
</div>
<table id="specTable">
<thead>
<tr>
<th onclick="sortTableBy('protocol')">Protocol</th>
<th onclick="sortTableBy('method')">Method</th>
<th onclick="sortTableBy('path')">Path</th>
<th onclick="sortTableBy('name')">Name</th>
<th onclick="sortTableBy('statusCode')">StatusCode</th>
</tr>
</thead>
<tbody id="specTbody">
<!-- Rows rendered by JS -->
</tbody>
</table>
</div>
<footer>
<p>Generated by swagger-coverage-cli</p>
</footer>
<!-- Chart.js from a CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- Highlight.js for code formatting -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script>
// Initialize Highlight.js
hljs.highlightAll();
// coverageData from server
let coverageData = [{"method":"GET","path":"/users","name":"getUsers","statusCode":"200","tags":[],"expectedStatusCodes":["200"],"apiName":"Test API","sourceFile":"test-api.yaml","protocol":"rest","unmatched":false,"matchedRequests":[{"name":"Get Users","rawUrl":"https://api.example.com/users","method":"GET","testedStatusCodes":["200"],"testScripts":"// Status code is 200","confidence":0.8999999999999999}],"isPrimaryMatch":true,"matchConfidence":0.8999999999999999},{"method":"POST","path":"/users","name":"createUser","statusCode":"201","tags":[],"expectedStatusCodes":["201","400"],"apiName":"Test API","sourceFile":"test-api.yaml","protocol":"rest","unmatched":false,"matchedRequests":[{"name":"Create User","rawUrl":"https://api.example.com/users","method":"POST","testedStatusCodes":["201"],"testScripts":"// Status code is 201","confidence":0.8999999999999999}],"isPrimaryMatch":true,"matchConfidence":0.8999999999999999},{"method":"POST","path":"/users","name":"createUser","statusCode":"400","tags":[],"expectedStatusCodes":["201","400"],"apiName":"Test API","sourceFile":"test-api.yaml","protocol":"rest","unmatched":true,"matchedRequests":[],"isPrimaryMatch":false,"matchConfidence":0},{"method":"GET","path":"/users/{id}","name":"getUserById","statusCode":"200","tags":[],"expectedStatusCodes":["200","404"],"apiName":"Test API","sourceFile":"test-api.yaml","protocol":"rest","unmatched":true,"matchedRequests":[],"isPrimaryMatch":false,"matchConfidence":0},{"method":"GET","path":"/users/{id}","name":"getUserById","statusCode":"404","tags":[],"expectedStatusCodes":["200","404"],"apiName":"Test API","sourceFile":"test-api.yaml","protocol":"rest","unmatched":true,"matchedRequests":[],"isPrimaryMatch":false,"matchConfidence":0}];
let apiCount = 1;
// Merge duplicates for display only
function unifyByMethodAndPath(items) {
const result = {};
items.forEach(item => {
// Include API name in the key for multiple APIs to keep them separate
const key = apiCount > 1 ?
(item.method + item.path + (item.apiName || '')).toLowerCase() :
(item.method + item.path).toLowerCase();
if (!result[key]) {
result[key] = { ...item, matchedRequests: [...item.matchedRequests] };
} else {
// Merge matchedRequests
result[key].matchedRequests.push(...item.matchedRequests);
// Merge tags if needed
result[key].tags = Array.from(new Set([...result[key].tags, ...item.tags]));
// Merge expectedStatusCodes
result[key].expectedStatusCodes = Array.from(
new Set([...result[key].expectedStatusCodes, ...item.expectedStatusCodes])
);
// If any item is matched, set unmatched = false
if (!item.unmatched) result[key].unmatched = false;
}
});
return Object.values(result);
}
// Sort direction
let sortAsc = true;
// Filter mode: "all", "matched", "unmatched"
let filterMode = "all";
// Method priority for custom sorting
const methodPriority = ["get","post","put","patch","delete","head","options","trace"];
// The "darkTheme" toggle
let darkTheme = false;
// On load
window.onload = function() {
coverageData = unifyByMethodAndPath(coverageData);
// Save coverage in localStorage to build a trend
updateCoverageHistory(40.00);
renderCoverageChart(40.00);
renderTrendChart();
renderTagChart();
renderTable();
};
// Render Trend Chart from localStorage coverageHistory
function renderTrendChart() {
let hist = localStorage.getItem('coverageHistory');
let arr = hist ? JSON.parse(hist) : [];
const labels = arr.map(e => new Date(e.timestamp).toLocaleDateString() + " " + new Date(e.timestamp).toLocaleTimeString());
const dataPoints = arr.map(e => e.coverage);
const ctx = document.getElementById('trendChart').getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
labels,
datasets: [{
label: 'Coverage Trend (%)',
data: dataPoints,
borderColor: '#6200ee',
backgroundColor: 'rgba(98, 0, 238, 0.1)',
fill: true,
tension: 0.2,
}]
},
options: {
responsive: true,
plugins: {
legend: { position: 'bottom' }
},
scales: {
y: {
beginAtZero: true,
max: 100
}
}
}
});
}
// Render Tag coverage chart
function renderTagChart() {
// Получаем все уникальные теги из спецификации
let allTags = new Set();
// Сначала собираем все теги из операций
coverageData.forEach(item => {
(item.tags || []).forEach(tag => allTags.add(tag));
});
// Инициализируем статистику для всех тегов
let tagStats = {};
allTags.forEach(tag => {
tagStats[tag] = { total: 0, matched: 0 };
});
// Теперь подсчитываем статистику
coverageData.forEach(item => {
let tags = item.tags || [];
tags.forEach(tag => {
tagStats[tag].total += 1;
if(!item.unmatched) {
tagStats[tag].matched += 1;
}
});
});
// Сортируем теги по алфавиту для лучшей читаемости
let labels = Object.keys(tagStats).sort();
let coverageVals = labels.map(t => {
// Если total === 0, возвращаем 0 чтобы избежать деления на ноль
return tagStats[t].total === 0 ? 0 : (tagStats[t].matched / tagStats[t].total) * 100;
});
const ctx = document.getElementById('tagChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels,
datasets: [
{
label: 'Tag Coverage (%)',
data: coverageVals,
backgroundColor: '#03dac6'
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { position: 'bottom' }
},
scales: {
y: {
beginAtZero: true,
max: 100
},
x: {
ticks: {
autoSkip: false, // Disable auto-skip
maxRotation: 45, // Rotate labels for better readability
minRotation: 45
}
}
}
}
});
}
// Render coverage pie chart
function renderCoverageChart(cov) {
const ctx = document.getElementById('coverageChart').getContext('2d');
new Chart(ctx, {
type: 'pie',
data: {
labels: ['Covered', 'Not Covered'],
datasets: [{
data: [cov, 100 - cov],
backgroundColor: ['#4caf50','#f44336']
}]
},
options: {
responsive: true,
plugins: {
legend: { position: 'bottom' }
}
}
});
}
// Export PDF via window.print() approach
function exportToPDF() {
window.print();
}
// Update localStorage coverage history
function updateCoverageHistory(current) {
let hist = localStorage.getItem('coverageHistory');
let arr = hist ? JSON.parse(hist) : [];
// Limit to 10 entries to avoid unbounded growth
if (arr.length >= 10) {
arr.shift();
}
arr.push({ timestamp: Date.now(), coverage: current });
localStorage.setItem('coverageHistory', JSON.stringify(arr));
}
// Toggle theme
function toggleTheme() {
darkTheme = !darkTheme;
document.body.classList.toggle('dark-theme', darkTheme);
const btn = document.getElementById('themeToggleBtn');
btn.innerHTML = darkTheme ? '☼' : '🔆';
// e.g., sun (☀) vs flashlight (🔦)
}
// Cycle the filter mode: all -> matched -> unmatched -> all ...
function cycleFilterMode() {
if (filterMode === 'all') {
filterMode = 'matched';
} else if (filterMode === 'matched') {
filterMode = 'unmatched';
} else {
filterMode = 'all';
}
const filterBtn = document.getElementById('filterBtn');
filterBtn.textContent = 'Show: ' + (filterMode.charAt(0).toUpperCase() + filterMode.slice(1));
filterTable();
}
// Add helper function for color-coded status code badges
function buildStatusBadges(specCodes, testedCodes) {
const specSet = new Set(specCodes || []);
const testSet = new Set(testedCodes || []);
let result = '';
// Check if all spec codes were found in tests
const allFound = Array.from(specSet).every(code => testSet.has(code));
// For spec codes, use green if found in tests, red if not
specSet.forEach(code => {
const badgeClass = testSet.has(code) ? 'badge-green' : 'badge-red';
const tooltip = testSet.has(code)
? 'Documented and verified'
: 'Documented but not verified';
result += '<span class="badge ' + badgeClass + '" data-tooltip="' + tooltip + '">' + code + '</span> ';
});
// For extra tested codes not in spec, use yellow
testSet.forEach(code => {
if (!specSet.has(code)) {
const tooltip = 'Not documented';
result += '<span class="badge badge-yellow" data-tooltip="' + tooltip + '">' + code + '</span> ';
}
});
return result.trim();
}
// Render the main table
function renderTable() {
const tbody = document.getElementById('specTbody');
tbody.innerHTML = '';
const filtered = coverageData.filter(item => {
if(filterMode === 'matched') return !item.unmatched;
if(filterMode === 'unmatched') return item.unmatched;
return true; // 'all'
});
filtered.forEach((item, idx) => {
const rowClass = item.unmatched ? "unmatched-spec" : "";
const hasMatches = item.matchedRequests && item.matchedRequests.length > 0;
const tr = document.createElement('tr');
tr.className = "spec-row " + rowClass;
// Only matched items get the onclick
if (hasMatches) {
tr.classList.add("matched");
const rowId = "match-row-" + idx;
tr.onclick = () => toggleMatchedRow(rowId);
}
// Columns
// Add API name column if multiple APIs
if (apiCount > 1) {
const tdApi = document.createElement('td');
tdApi.className = "spec-cell";
tdApi.textContent = item.apiName || '';
tr.appendChild(tdApi);
}
// Add protocol column
const tdProtocol = document.createElement('td');
tdProtocol.className = "spec-cell protocol-cell";
const protocol = item.protocol || 'rest';
tdProtocol.textContent = protocol.toUpperCase();
// Add styling based on protocol
if (protocol === 'grpc') {
tdProtocol.style.color = '#4caf50';
tdProtocol.style.fontWeight = 'bold';
} else if (protocol === 'graphql') {
tdProtocol.style.color = '#e91e63';
tdProtocol.style.fontWeight = 'bold';
} else {
tdProtocol.style.color = '#2196f3';
}
tr.appendChild(tdProtocol);
const tdMethod = document.createElement('td');
tdMethod.className = "spec-cell";
tdMethod.textContent = (item.method || "").toUpperCase();
const tdPath = document.createElement('td');
tdPath.className = "spec-cell";
tdPath.textContent = item.path || "";
const tdName = document.createElement('td');
tdName.className = "spec-cell";
let nameContent = item.name || item.summary || item.operationId || '(No operationId in spec)';
// Add smart mapping indicators
if (item.isPrimaryMatch) {
nameContent += ' <span class="primary-match-badge" title="Primary Match">Primary</span>';
}
if (item.matchConfidence && item.matchConfidence < 1.0) {
const confidence = Math.round(item.matchConfidence * 100);
nameContent += ' <span class="confidence-badge" title="Match Confidence: ' + confidence + '%">' + confidence + '%</span>';
}
tdName.innerHTML = nameContent;
const tdStatus = document.createElement('td');
tdStatus.className = "spec-cell";
tdStatus.innerHTML = buildStatusBadges(
item.expectedStatusCodes,
item.matchedRequests.flatMap(req => req.testedStatusCodes || [])
);
tr.appendChild(tdMethod);
tr.appendChild(tdPath);
tr.appendChild(tdName);
tr.appendChild(tdStatus);
tbody.appendChild(tr);
// If matched, add a hidden sub-row with the postman requests
if(hasMatches) {
const subTr = document.createElement('tr');
subTr.id = "match-row-" + idx;
subTr.className = "matched-requests-row";
const subTd = document.createElement('td');
subTd.colSpan = apiCount > 1 ? 6 : 5;
const pmTable = document.createElement('table');
pmTable.className = "postman-table";
// Update column header from "Codes (Spec vs. Tested)" to "Recommendation"
const pmThead = document.createElement('thead');
pmThead.innerHTML = '<tr><th>Postman Request Name</th><th>Method</th><th>URL</th><th>Recommendation</th><th>Test Scripts</th></tr>';
pmTable.appendChild(pmThead);
const pmTbody = document.createElement('tbody');
item.matchedRequests.forEach(pmReq => {
const pmRow = document.createElement('tr');
const pmName = document.createElement('td');
pmName.textContent = pmReq.name || "";
pmRow.appendChild(pmName);
const pmMethod = document.createElement('td');
pmMethod.textContent = (pmReq.method || "").toUpperCase();
pmRow.appendChild(pmMethod);
const pmUrl = document.createElement('td');
pmUrl.textContent = pmReq.rawUrl || "";
pmRow.appendChild(pmUrl);
// Replace status code badges with recommendations
const pmCodes = document.createElement('td');
const recommendations = generateRecommendations(pmReq, item);
if (recommendations.length > 0) {
const icon = document.createElement('div');
icon.className = 'recommendation-icon';
icon.textContent = '!';
icon.onclick = function(e) {
e.stopPropagation(); // Prevent row expansion
this.style.display = 'none';
text.classList.add('visible');
};
const text = document.createElement('div');
text.className = 'recommendation-text';
text.innerHTML = '<ul style="margin: 0; padding-left: 20px; color: var(--md-text-color);">' +
recommendations.map(r => '<li>' + r + '</li>').join('') + '</ul>';
text.onclick = function(e) {
e.stopPropagation(); // Prevent row expansion
this.classList.remove('visible');
icon.style.display = 'inline-block';
};
pmCodes.appendChild(icon);
pmCodes.appendChild(text);
} else {
pmCodes.innerHTML = '<span style="color: var(--md-text-color);">All recommended tests are present</span>';
}
pmRow.appendChild(pmCodes);
// Update the Test Scripts cell generation code
const pmScripts = document.createElement('td');
if(pmReq.testScripts) {
if(pmReq.testScripts.length > 100) {
const id = 'script_' + idx + '_' + Math.random().toString(36).substr(2,9);
const codeToggle = document.createElement('div');
codeToggle.className = 'code-toggle';
codeToggle.textContent = '</>';
codeToggle.style.display = 'inline-block';
codeToggle.id = 'toggle_' + id;
codeToggle.onclick = function(e) {
e.stopPropagation();
this.style.display = 'none';
codeBlock.style.display = 'block';
};
const codeBlock = document.createElement('div');
codeBlock.id = id;
codeBlock.style.display = 'none'; // Initially hidden
codeBlock.innerHTML = '<pre><code class="javascript">' + pmReq.testScripts + '</code></pre>';
codeBlock.onclick = function(e) {
e.stopPropagation();
this.style.display = 'none';
codeToggle.style.display = 'block';
};
pmScripts.appendChild(codeToggle);
pmScripts.appendChild(codeBlock);
} else {
const pre = document.createElement('pre');
const code = document.createElement('code');
code.className = 'javascript';
code.textContent = pmReq.testScripts;
pre.appendChild(code);
pmScripts.appendChild(pre);
}
} else {
pmScripts.textContent = 'No scripts found';
}
pmRow.appendChild(pmScripts);
pmTbody.appendChild(pmRow);
});
pmTable.appendChild(pmTbody);
subTd.appendChild(pmTable);
subTr.appendChild(subTd);
tbody.appendChild(subTr);
}
});
// Re-initialize Highlight.js for new code blocks
hljs.highlightAll();
filterTable();
}
// Toggle the matched requests sub-row
function toggleMatchedRow(rowId) {
const row = document.getElementById(rowId);
if(!row) return;
row.style.display = (row.style.display === 'none' || row.style.display === '') ? 'table-row' : 'none';
}
// Sort coverageData
function sortTableBy(columnKey) {
coverageData.sort((a, b) => {
let valA = a[columnKey] || "";
let valB = b[columnKey] || "";
if(columnKey === "method") {
const mA = valA.toLowerCase();
const mB = valB.toLowerCase();
const iA = methodPriority.indexOf(mA);
const iB = methodPriority.indexOf(mB);
if(iA !== -1 && iB !== -1) {
return sortAsc ? iA - iB : iB - iA;
}
if(iA !== -1 && iB === -1) {
return sortAsc ? -1 : 1;
}
if(iB !== -1 && iA === -1) {
return sortAsc ? 1 : -1;
}
}
// Fallback to standard string compare
valA = valA.toString().toLowerCase();
valB = valB.toString().toLowerCase();
if(valA < valB) return sortAsc ? -1 : 1;
if(valA > valB) return sortAsc ? 1 : -1;
return 0;
});
sortAsc = !sortAsc;
renderTable();
}
// Update the generateRecommendations function to return array instead of HTML
function generateRecommendations(pmReq, item) {
const recommendations = [];
const testScripts = pmReq.testScripts || '';
const method = (pmReq.method || '').toUpperCase();
const hasResponseTimeTest = /pm.response.responseTime|pm.expect([^)]*responseTime[^)]*)|pm.response.time/i.test(testScripts);
if (!hasResponseTimeTest) {
recommendations.push('Missing response time validation');
}
const hasSchemaValidation = /pm.response.json().*schema|tv4.validate|ajv.validate|expect(.*).to.match.schema/i.test(testScripts);
if (!hasSchemaValidation && !(method === 'DELETE' && pmReq.testedStatusCodes.includes('204'))) {
recommendations.push('Missing JSON schema validation');
}
if (method !== 'DELETE' && item.requestBodyContent) {
recommendations.push('Consider testing boundary values');
}
const hasPaginationTerms = /page|per[_-]?page|perPage|perpage|Page|limit|offset|size|from|to|&[^=]*(?:page|perPage|per_page|limit|offset|size)[^&]*/i.test(testScripts);
if (!hasPaginationTerms && method !== 'DELETE') {
recommendations.push('Consider testing pagination if applicable');
}
if (method === 'PATCH') {
recommendations.push('Verify all partial update scenarios');
}
return recommendations;
}
// Add new function for table filtering by search
function filterTable() {
const searchText = document.getElementById('searchInput').value.toLowerCase();
const rows = document.querySelectorAll('#specTable tbody tr.spec-row');
rows.forEach(row => {
// Column indices adjust based on whether we have API column and protocol column
let colIndex = 1;
if (false) colIndex++; // API column
colIndex++; // Protocol column