-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage (2).html
More file actions
1100 lines (984 loc) · 35.8 KB
/
page (2).html
File metadata and controls
1100 lines (984 loc) · 35.8 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>
<!--
© 2025 Bekono Beyas — Tous droits réservés.
Usage autorisé uniquement pour des tests légitimes et avec autorisation.
Contact: (beyasbekono@gmail.com)
-->
<html lang="fr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>API Pro - Swagger UI + Code Generator</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
@import url("https://fonts.googleapis.com/css2?family=Droid+Sans+Mono:wght@400;700&family=Open+Sans:wght@400;600;700&display=swap");
* {
font-family: "Open Sans", sans-serif;
}
.mono {
font-family: "Droid Sans Mono", monospace;
}
body {
background: #fafafa;
}
.swagger-header {
background: #fff;
border-bottom: 1px solid #e8e8e8;
padding: 15px 20px;
}
.swagger-title {
font-size: 36px;
font-weight: 700;
color: #3b3b3b;
}
.swagger-desc {
font-size: 13px;
color: #717171;
}
.method-tag {
display: inline-block;
padding: 6px 12px;
border-radius: 4px;
font-weight: 600;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.tag-GET {
background: #61affe;
color: white;
}
.tag-POST {
background: #49cc90;
color: white;
}
.tag-PUT {
background: #fca130;
color: white;
}
.tag-PATCH {
background: #50e3c2;
color: white;
}
.tag-DELETE {
background: #f93e3e;
color: white;
}
.endpoint-container {
background: white;
border: 1px solid #e8e8e8;
border-radius: 4px;
margin-bottom: 0;
}
.endpoint-header {
display: flex;
align-items: center;
padding: 16px 20px;
cursor: pointer;
border-bottom: 1px solid #e8e8e8;
transition: background 0.2s;
}
.endpoint-header:hover {
background: #fafafa;
}
.endpoint-path {
flex: 1;
margin-left: 15px;
font-family: "Droid Sans Mono", monospace;
font-size: 14px;
color: #3b3b3b;
font-weight: 600;
}
.endpoint-body {
padding: 20px;
background: #fafafa;
border-top: 1px solid #e8e8e8;
}
.section-title {
font-size: 14px;
font-weight: 600;
color: #3b3b3b;
margin-bottom: 10px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.param-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.param-table thead {
background: #f0f0f0;
border: 1px solid #e8e8e8;
}
.param-table th {
padding: 10px 15px;
text-align: left;
font-weight: 600;
color: #3b3b3b;
border-right: 1px solid #e8e8e8;
}
.param-table td {
padding: 10px 15px;
border: 1px solid #e8e8e8;
color: #717171;
}
.param-name {
color: #3b3b3b;
font-weight: 600;
font-family: "Droid Sans Mono", monospace;
}
.param-type {
background: #f0f0f0;
padding: 2px 6px;
border-radius: 3px;
font-size: 12px;
font-family: "Droid Sans Mono", monospace;
}
.code-block {
background: #263238;
color: #aed581;
padding: 15px;
border-radius: 4px;
overflow-x: auto;
font-family: "Droid Sans Mono", monospace;
font-size: 12px;
line-height: 1.5;
margin: 10px 0;
}
.sidebar {
background: white;
border-right: 1px solid #e8e8e8;
height: 100vh;
overflow-y: auto;
position: sticky;
top: 0;
}
.sidebar-item {
padding: 10px 15px;
border-left: 3px solid transparent;
cursor: pointer;
font-size: 13px;
color: #717171;
transition: all 0.2s;
}
.sidebar-item:hover {
background: #fafafa;
}
.sidebar-item.active {
border-left-color: #61affe;
background: #f0f6ff;
color: #61affe;
font-weight: 600;
}
.tag-group {
margin-bottom: 1px;
}
.group-header {
background: #f0f0f0;
padding: 10px 15px;
font-weight: 600;
font-size: 12px;
color: #3b3b3b;
text-transform: uppercase;
cursor: pointer;
}
.group-header:hover {
background: #e8e8e8;
}
.toggle-icon {
display: inline-block;
transition: transform 0.2s;
}
.toggle-icon.open {
transform: rotate(180deg);
}
.btn-try {
background: #61affe;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
font-weight: 600;
transition: background 0.2s;
margin-right: 8px;
}
.btn-try:hover {
background: #4a9fd8;
}
.btn-gen {
background: #49cc90;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
font-weight: 600;
transition: background 0.2s;
}
.btn-gen:hover {
background: #36a570;
}
.model-definition {
background: white;
border: 1px solid #e8e8e8;
border-radius: 4px;
margin-bottom: 20px;
overflow: hidden;
}
.model-header {
background: #58509c;
color: white;
padding: 12px 16px;
font-weight: 600;
cursor: pointer;
display: flex;
justify-content: space-between;
align-items: center;
}
.model-body {
padding: 20px;
background: #fafafa;
}
.response-box {
background: white;
border: 1px solid #e8e8e8;
border-radius: 4px;
padding: 15px;
margin-top: 15px;
}
.response-code {
display: inline-block;
background: #49cc90;
color: white;
padding: 4px 8px;
border-radius: 3px;
font-weight: 600;
font-size: 12px;
}
.tab-btn {
padding: 8px 16px;
margin-right: 8px;
background: #e8e8e8;
color: #3b3b3b;
border: none;
cursor: pointer;
border-radius: 4px;
font-weight: 600;
transition: all 0.2s;
}
.tab-btn.active {
background: #61affe;
color: white;
}
</style>
</head>
<body>
<div class="flex h-screen">
<!-- Sidebar -->
<div class="w-64 sidebar hidden md:block overflow-y-auto">
<div class="p-4 border-b border-gray-200">
<input
id="search"
type="text"
placeholder="Search..."
class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div id="sidebar-content"></div>
</div>
<!-- Main Content -->
<div class="flex-1 overflow-y-auto">
<!-- Header -->
<div class="swagger-header sticky top-0 z-10">
<div class="swagger-title">
Api exploit Pro - Swagger UI + Code Generator
</div>
<div class="swagger-desc">
v1 - Base URL:
<span id="baseUrlDisplay"></span>
</div>
<div class="p-2 mt-2 text-sm text-red-600 font-semibold">
Usage légal uniquement — Ne pas utiliser pour des activités non
autorisées.
</div>
</div>
<!-- Input Section -->
<div class="p-6 bg-white border-b border-gray-200">
<h3 class="font-bold mb-3">Pâte la documentation</h3>
<textarea
id="apiInput"
rows="8"
placeholder="Collez votre documentation Swagger ici..."
class="w-full p-3 border border-gray-300 rounded-lg font-mono text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
></textarea>
<div class="mt-3 flex gap-2">
<input
id="baseUrl"
type="text"
value=""
placeholder="URL de base"
class="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm"
/>
<button
onclick="analyzeAPI()"
class="bg-blue-600 text-white px-6 py-2 rounded-md hover:bg-blue-700 font-semibold"
>
⚡ ANALYSER
</button>
</div>
<p id="status" class="mt-3 text-sm font-semibold hidden"></p>
</div>
<!-- API Documentation -->
<div class="p-6 max-w-5xl">
<div class="mb-6 flex gap-3">
<button
onclick="generateFullAPI()"
class="bg-purple-600 text-white px-6 py-3 rounded-md hover:bg-purple-700 font-semibold"
>
🚀 Générer TOUTE l'API (DTOs + Services)
</button>
</div>
<div id="apiContainer" class="space-y-6">
<p class="text-center text-gray-500 py-8">
Collez et analysez la documentation pour voir les endpoints
</p>
</div>
</div>
<!-- Models Section -->
<div class="p-6 max-w-5xl border-t border-gray-200 mt-6">
<h2 class="text-2xl font-bold mb-6">Models</h2>
<div id="modelsContainer" class="space-y-4">
<p class="text-gray-500">Les modèles apparaîtront ici</p>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div
id="modal"
class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
onclick="if(event.target === this) closeModal()"
>
<div
class="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] overflow-hidden flex flex-col"
>
<div
class="p-4 border-b flex justify-between items-center sticky top-0 bg-gray-50"
>
<h3 id="modalTitle" class="font-bold text-lg"></h3>
<button onclick="closeModal()" class="text-2xl cursor-pointer">
✕
</button>
</div>
<div class="flex gap-2 px-4 pt-4 border-b overflow-x-auto">
<button class="tab-btn active" onclick="switchTab(this, 'code')">
💻 Code
</button>
<button class="tab-btn" onclick="switchTab(this, 'dto')">
📦 DTO
</button>
<button class="tab-btn" onclick="switchTab(this, 'service')">
🔌 Service
</button>
</div>
<div id="modalBody" class="p-6 overflow-y-auto flex-1"></div>
<div class="p-4 border-t bg-gray-50 flex gap-2 justify-end">
<button
onclick="copyActiveCode()"
class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 font-semibold"
>
📋 Copier
</button>
<button
onclick="downloadCode()"
class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700 font-semibold"
>
⬇️ Télécharger
</button>
</div>
</div>
</div>
<script>
let apiSpec = { endpoints: {}, models: {} };
let baseURL = "";
let currentCode = { code: "", dto: "", service: "" };
// ===================================
// Fonctions d'Analyse et de Rendu
// ===================================
function analyzeAPI() {
const input = document.getElementById("apiInput").value.trim();
baseURL = document.getElementById("baseUrl").value.trim() || "";
document.getElementById("baseUrlDisplay").textContent = baseURL;
if (!input || input.length < 50) {
showStatus("❌ Veuillez coller une documentation valide", "error");
return;
}
try {
parseSwaggerText(input);
renderUI();
showStatus("✅ API analysée avec succès!", "success");
} catch (e) {
showStatus("❌ Erreur lors de l'analyse : " + e.message, "error");
console.error(e);
}
}
function parseSwaggerText(text) {
apiSpec.endpoints = {};
apiSpec.models = {};
// 1. Parser les modèles EN PREMIER
parseModels(text);
// Détecter les tags d'endpoint de manière dynamique (commencent souvent par Majuscule ou sont des mots clés)
const allTags = new Set();
const tagLineRegex =
/^(auth|common|drivers|driver-profiles|match-requests|match-suggestions|shipments|travels|users|user-management|admin|config|api)\n/gim;
let tagMatch;
while ((tagMatch = tagLineRegex.exec(text)) !== null) {
allTags.add(tagMatch[1].toLowerCase());
}
const tags = Array.from(allTags);
const methods = ["POST", "GET", "PUT", "PATCH", "DELETE"];
tags.forEach((tag) => {
apiSpec.endpoints[tag] = [];
// Regex pour extraire la section du tag
const tagRegex = new RegExp(
`\\n${tag}\\n([\\s\\S]*?)(?=\\n(Models|Schemas|schemas|models${tags.join(
"|"
)})\\n|$)`,
"i"
);
const match = text.match(tagRegex);
if (match) {
const sectionText = match[1];
const lines = sectionText.split("\n");
for (let i = 0; i < lines.length; i++) {
const method = methods.find((m) => lines[i].trim() === m);
if (
method &&
i + 1 < lines.length &&
lines[i + 1].trim().startsWith("/")
) {
const path = lines[i + 1].trim();
const descLine = lines[i + 2]?.trim() || "";
let reqModel = null,
respModel = null;
// Chercher les modèles dans les 50 lignes suivantes
for (let j = i + 3; j < Math.min(i + 50, lines.length); j++) {
const line = lines[j];
const nextMethodCheck = methods.find(
(m) => lines[j].trim() === m
);
if (nextMethodCheck && j !== i + 3) break; // Arrêter si on atteint l'endpoint suivant
// Détection du modèle de requête (Body)
if (
(line.includes("(body)") || line.includes("data *")) &&
!reqModel
) {
for (let k = j; k < Math.min(j + 15, lines.length); k++) {
const modelMatch = lines[k].match(
/Model\s*\n?([A-Z][a-zA-Z]*)/
);
const directMatch = lines[k].match(
/([A-Z][a-zA-Z]*)(\s*\{|\s*\n)/
);
if (modelMatch) {
reqModel = modelMatch[1];
break;
}
if (directMatch && !lines[k].includes("Example")) {
reqModel = directMatch[1];
break;
}
}
}
// Détection du modèle de réponse (Responses)
if (line.includes("Responses") && !respModel) {
for (let k = j; k < Math.min(j + 20, lines.length); k++) {
const modelMatch = lines[k].match(
/Model\s*\n?([A-Z][a-zA-Z]*)/
);
const directMatch = lines[k].match(
/([A-Z][a-zA-Z]*)(\s*\{|\s*\n)/
);
if (modelMatch) {
respModel = modelMatch[1];
break;
}
if (directMatch && !lines[k].includes("Example")) {
respModel = directMatch[1];
break;
}
}
break;
}
}
apiSpec.endpoints[tag].push({
method,
path,
description: descLine || `${method} endpoint`,
tag,
requestModel:
reqModel && apiSpec.models[reqModel] ? reqModel : null,
responseModel:
respModel && apiSpec.models[respModel] ? respModel : null,
});
}
}
}
});
}
function parseModels(text) {
// Extraire la section Models ou Schemas
const modelsMatch = text.match(
/(Models|Schemas)\n([\s\S]*?)(?=\n[A-Z][a-zA-Z]*\n|$|Online validator)/i
);
if (!modelsMatch) return;
const modelsText = modelsMatch[2] || modelsMatch[1]; // Utiliser le groupe 2 si présent (le contenu)
const lines = modelsText.split("\n");
let currentModel = null;
let modelContent = "";
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Détecte un nouveau modèle (commence par majuscule)
// Assurez-vous qu'il ne s'agit pas d'un type simple comme 'string' ou 'integer'
const modelMatch = line.match(/^([A-Z][a-zA-Z0-9]*)\s*(\{|$)/);
if (modelMatch) {
// Sauvegarder le modèle précédent
if (currentModel) {
parseModelFields(currentModel, modelContent);
}
currentModel = modelMatch[1];
modelContent = line;
// Extraire les champs jusqu'à la fin du modèle
for (let j = i + 1; j < lines.length; j++) {
const contentLine = lines[j].trim();
modelContent += "\n" + contentLine;
// Si on trouve une nouvelle définition de modèle, arrêter
if (
contentLine.match(/^[A-Z][a-zA-Z0-9]*\s*(\{|$)/) &&
contentLine !== currentModel
) {
i = j - 1; // Revenir en arrière d'une ligne pour que la boucle principale le traite
break;
}
}
// Si la boucle se termine, on a le dernier modèle
if (i === lines.length - 1 && currentModel) {
parseModelFields(currentModel, modelContent);
currentModel = null;
}
}
}
// Sauvegarder le dernier modèle si non sauvegardé (cas où le match interne ne s'arrête pas par un nouveau modèle)
if (currentModel) {
parseModelFields(currentModel, modelContent);
}
}
function parseModelFields(modelName, modelContent) {
const fields = {};
// Extraire les champs (nom * type | nom type)
const fieldRegex =
/([a-z_]+)\*?\s+(string|integer|number|decimal|datetime|boolean|object|array|ID|[A-Z][a-zA-Z]*)/gi;
let match;
while ((match = fieldRegex.exec(modelContent)) !== null) {
const fieldName = match[1];
let fieldType = match[2];
// Mapper les types
if (fieldType === "ID") fieldType = "integer";
if (fieldType === "Postal") fieldType = "string";
// Vérifier si requis (avec *)
const isRequired = modelContent
.substring(Math.max(0, match.index - 50), match.index)
.includes("*");
fields[fieldName] = fieldType + (isRequired ? " (required)" : "");
}
if (Object.keys(fields).length > 0) {
apiSpec.models[modelName] = { fields };
}
}
// ===================================
// Génération de Code (DTOs & Service)
// ===================================
function generateFullAPI() {
const allDTOs = new Set();
const allModels = new Set();
const allEndpoints = [];
let modelMap = {};
// 1. Collecter tous les modèles et endpoints
for (const tag in apiSpec.endpoints) {
apiSpec.endpoints[tag].forEach((ep) => {
allEndpoints.push(ep);
if (ep.requestModel) allModels.add(ep.requestModel);
if (ep.responseModel) allModels.add(ep.responseModel);
});
}
// 2. Détecter les dépendances pour générer les DTOs dans le bon ordre
// (Pour cet exercice, on va juste utiliser la liste des modèles uniques)
allModels.forEach((modelName) => {
if (apiSpec.models[modelName]) {
modelMap[modelName] = apiSpec.models[modelName];
allDTOs.add({ name: modelName, model: apiSpec.models[modelName] });
}
});
// 3. Générer les DTOs
const dtoCode = generateDTOs(Array.from(allDTOs));
// 4. Générer le Service
let serviceCode = `// ===== Service API pour toute l'API =====\n\n`;
serviceCode += `// Importez vos DTOs si nécessaire (ex: from './dtos')\n`;
serviceCode += `// import { ${Array.from(allModels).join(
", "
)} } from './dtos';\n\n`;
serviceCode += `export class FullAPIService {\n`;
serviceCode += ` private baseUrl = "${baseURL}";\n\n`;
allEndpoints.forEach((ep) => {
serviceCode += generateServiceMethod(ep);
});
serviceCode += `}\n`;
// 5. Afficher dans la modale
const fullCode = dtoCode + serviceCode;
currentCode = { code: fullCode, dto: dtoCode, service: serviceCode };
showModal("Génération Complète (DTOs + Service)", fullCode);
}
function generateServiceMethod(ep) {
const methodName = ep.path
.replace(/\//g, "_")
.replace(/\{[^}]+\}/g, "id")
.replace(/^_|_$/g, "")
.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase()) // CamelCase après le tag
.replace(`${ep.tag}_`, ""); // Enlever le tag si présent au début (ex: auth_login)
const reqType = ep.requestModel || "any";
const respType = ep.responseModel || "any";
let code = ` // ${ep.description} - ${ep.method} ${ep.path}\n`;
code += ` async ${methodName}(`;
const params = [];
const bodyNeeded = ep.method !== "GET" && ep.method !== "DELETE";
if (ep.path.includes("{")) {
const pathParams = Array.from(ep.path.matchAll(/\{([^}]+)\}/g)).map(
(m) => m[1]
);
pathParams.forEach((param) =>
params.push(`${param}: string | number`)
);
}
if (bodyNeeded) {
params.push(`data: ${reqType}`);
}
code += params.join(", ");
code += `): Promise<${respType}> {\n`;
let urlVar = "url";
code += ` let ${urlVar} = \`\${this.baseUrl}${ep.path}\`;\n`;
// Remplacement des paramètres de chemin (path parameters)
if (ep.path.includes("{")) {
const pathParams = Array.from(ep.path.matchAll(/\{([^}]+)\}/g)).map(
(m) => m[1]
);
pathParams.forEach((param) => {
code += ` ${urlVar} = ${urlVar}.replace('{${param}}', String(${param}));\n`;
});
}
code += `\n const options: RequestInit = {\n`;
code += ` method: '${ep.method}',\n`;
code += ` headers: {\n`;
code += ` 'Content-Type': 'application/json',\n`;
code += ` // TODO: Remplacez 'YOUR_TOKEN' par votre jeton d'authentification réel\n`;
code += ` 'Authorization': 'Bearer YOUR_TOKEN'\n`;
code += ` }\n`;
if (bodyNeeded) {
code += `,\n body: JSON.stringify(data)\n`;
}
code += ` };\n\n`;
code += ` const response = await fetch(${urlVar}, options);\n`;
code += ` if (!response.ok) throw new Error(\`HTTP Error: \${response.status} - \${await response.text()}\`);\n`;
code += ` // Si la réponse est vide (ex: 204 No Content), ne pas essayer de la parser en JSON\n`;
code += ` if (response.status === 204) return {} as ${respType};\n`;
code += ` return response.json() as Promise<${respType}>;\n`;
code += ` }\n\n`;
return code;
}
function generateForEndpoint(tag, idx) {
const ep = apiSpec.endpoints[tag][idx];
const reqModel = ep.requestModel
? apiSpec.models[ep.requestModel]
: null;
const respModel = ep.responseModel
? apiSpec.models[ep.responseModel]
: null;
const curl = `curl -X ${ep.method} "${baseURL}${ep.path}" \\
-H "Authorization: Bearer YOUR_TOKEN" \\
-H "Content-Type: application/json"${reqModel ? " \\\n -d '{}'" : ""}`;
const modelsToGenerate = [];
if (reqModel)
modelsToGenerate.push({ name: ep.requestModel, model: reqModel });
if (respModel)
modelsToGenerate.push({ name: ep.responseModel, model: respModel });
const dtoCode = generateDTOs(modelsToGenerate);
const serviceCode = generateServiceMethod(ep);
const fullServiceCode = `// ===== Service API =====\nexport class APIService {\n${serviceCode}}\n`;
currentCode = { code: curl, dto: dtoCode, service: fullServiceCode };
showModal(`${ep.method} ${ep.path}`, curl);
}
function generateDTOs(modelsArray) {
let code = `// ===== DTOs / Modèles de Données (${modelsArray
.map((m) => m.name)
.join(", ")}) =====\n\n`;
modelsArray.forEach((item) => {
if (!item.name || !item.model || !item.model.fields) return;
code += `export interface ${item.name} {\n`;
const fields = item.model.fields;
for (const field in fields) {
const typeInfo = fields[field];
const type = mapToTS(typeInfo);
const required = typeInfo.includes("required") ? "" : "?";
code += ` ${field}${required}: ${type};\n`;
}
code += `}\n\n`;
});
return code;
}
function mapToTS(typeInfo) {
if (typeof typeInfo !== "string") return "any";
const type = typeInfo.toLowerCase().split(" ")[0].split("(")[0];
const mapping = {
string: "string",
integer: "number",
number: "number",
decimal: "number",
datetime: "string",
boolean: "boolean",
array: "any[]", // On pourrait améliorer en recherchant le type de l'array
object: "any",
id: "number",
};
// 1. Types de base
if (mapping[type]) return mapping[type];
// 2. Modèles de référence
const modelName = type.charAt(0).toUpperCase() + type.slice(1);
if (apiSpec.models[modelName]) return modelName;
// 3. Fallback
return "any";
}
// ===================================
// Fonctions d'Affichage
// ===================================
function renderUI() {
renderSidebar();
renderEndpoints();
renderModels();
}
function renderSidebar() {
const sidebar = document.getElementById("sidebar-content");
sidebar.innerHTML = "";
for (const tag in apiSpec.endpoints) {
if (apiSpec.endpoints[tag].length === 0) continue;
const group = document.createElement("div");
group.className = "tag-group";
const header = document.createElement("div");
header.className = "group-header";
header.innerHTML = `<span class="toggle-icon">▼</span> ${tag.toUpperCase()}`;
header.onclick = (e) => {
const items = group.querySelectorAll(".sidebar-item");
items.forEach((item) => item.classList.toggle("hidden"));
header.querySelector(".toggle-icon").classList.toggle("open");
};
group.appendChild(header);
apiSpec.endpoints[tag].forEach((ep) => {
const item = document.createElement("div");
item.className = "sidebar-item";
item.innerHTML = `<span class="method-tag tag-${ep.method}">${ep.method}</span> <span class="mono">${ep.path}</span>`;
item.onclick = () =>
scrollToEndpoint(
`${tag}-${ep.path.replace(/[^a-zA-Z0-9]/g, "-")}`
);
group.appendChild(item);
});
sidebar.appendChild(group);
}
}
function renderEndpoints() {
const parentContainer =
document.getElementById("apiContainer").parentElement;
let endpointsDiv = document.getElementById("endpointsContent");
if (endpointsDiv) {
endpointsDiv.innerHTML = "";
} else {
endpointsDiv = document.createElement("div");
endpointsDiv.className = "space-y-6";
endpointsDiv.id = "endpointsContent";
document.getElementById("apiContainer").remove();
parentContainer.appendChild(endpointsDiv);
}
for (const tag in apiSpec.endpoints) {
apiSpec.endpoints[tag].forEach((ep, idx) => {
const epId = `${tag}-${ep.path.replace(/[^a-zA-Z0-9]/g, "-")}`;
const div = document.createElement("div");
div.id = epId;
div.className = "endpoint-container";
div.innerHTML = `
<div class="endpoint-header" onclick="toggleElement('${epId}-body')">
<span class="method-tag tag-${ep.method}">${
ep.method
}</span>
<div class="endpoint-path mono">${ep.path}</div>
</div>
<div id="${epId}-body" class="endpoint-body hidden">
<p class="text-gray-700 mb-4">${ep.description}</p>
${
ep.requestModel
? `<p class="text-sm text-gray-600"><strong>Requête:</strong> <span class="mono">${ep.requestModel}</span></p>`
: ""
}
${
ep.responseModel
? `<p class="text-sm text-gray-600"><strong>Réponse:</strong> <span class="mono">${ep.responseModel}</span></p>`
: ""
}
<div class="mt-4 flex gap-2">
<button class="btn-try" onclick="generateForEndpoint('${tag}', ${idx})">cURL / Code</button>
<button class="btn-gen" onclick="generateForEndpoint('${tag}', ${idx})">📦 Générer DTO/Service</button>
</div>
</div>
`;
endpointsDiv.appendChild(div);
});
}
}
function renderModels() {
const container = document.getElementById("modelsContainer");
container.innerHTML = "";
const sortedModelNames = Object.keys(apiSpec.models).sort();
sortedModelNames.forEach((name) => {
const model = apiSpec.models[name];
const fields = model.fields;
const fieldRows = Object.keys(fields)
.map(
(f) =>
`<tr><td class="param-name">${f}</td><td><span class="param-type">${fields[f]}</span></td></tr>`
)
.join("");
const div = document.createElement("div");
div.className = "model-definition";
div.innerHTML = `
<div class="model-header" onclick="toggleElement('model-${name}')">
<span>${name}</span>
</div>
<div id="model-${name}" class="model-body hidden">
<table class="param-table">
<thead><tr><th>Field</th><th>Type</th></tr></thead>
<tbody>${fieldRows}</tbody>
</table>
</div>
`;
container.appendChild(div);
});
if (sortedModelNames.length === 0) {
container.innerHTML = `<p class="text-gray-500">Les modèles apparaîtront ici</p>`;
}
}
// ===================================
// Fonctions Utilitaires
// ===================================
function toggleElement(id) {
const el = document.getElementById(id);
if (el) el.classList.toggle("hidden");
}
function scrollToEndpoint(id) {
const el = document.getElementById(id);
if (el) {
el.scrollIntoView({ behavior: "smooth" });
document.getElementById(`${id}-body`)?.classList.remove("hidden");
}
}
function switchTab(btn, tab) {
document
.querySelectorAll(".tab-btn")