@t0.labs/daxta 0.4.7 → 0.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -287,6 +287,26 @@
287
287
  color: var(--white);
288
288
  box-shadow: none;
289
289
  }
290
+ .env-base-line {
291
+ margin-top: 8px;
292
+ padding: 8px 10px;
293
+ border-radius: 8px;
294
+ background: var(--inset);
295
+ font: 11px/1.4 var(--mono);
296
+ color: var(--charcoal);
297
+ word-break: break-all;
298
+ }
299
+ .env-base-line span { color: var(--stone); }
300
+ .env-quick {
301
+ display: flex;
302
+ flex-wrap: wrap;
303
+ gap: 6px;
304
+ margin-top: 8px;
305
+ }
306
+ .env-kv.base-url .env-cell[data-field="key"] {
307
+ opacity: 0.7;
308
+ pointer-events: none;
309
+ }
290
310
  .env-add {
291
311
  height: 32px;
292
312
  padding: 0 10px;
@@ -310,16 +330,72 @@
310
330
 
311
331
  .app {
312
332
  display: grid;
313
- grid-template-columns: 320px minmax(0, 1fr);
333
+ grid-template-columns: var(--sidebar-w, 320px) 6px minmax(0, 1fr);
314
334
  height: calc(100vh - 56px);
315
335
  }
336
+ .app.sidebar-collapsed {
337
+ grid-template-columns: 0 28px minmax(0, 1fr);
338
+ }
316
339
  .sidebar, .workbench { height: 100%; overflow: auto; }
317
340
  .sidebar {
341
+ position: relative;
342
+ min-width: 0;
318
343
  padding: 16px 12px 48px;
319
344
  background: var(--sidebar);
320
- border-right: 1px solid var(--line);
345
+ border-right: 0;
321
346
  font-size: 13px;
322
347
  }
348
+ .app.sidebar-collapsed .sidebar {
349
+ overflow: hidden;
350
+ padding: 0;
351
+ pointer-events: none;
352
+ opacity: 0;
353
+ }
354
+ .sidebar-resizer {
355
+ position: relative;
356
+ z-index: 5;
357
+ width: 6px;
358
+ margin: 0;
359
+ padding: 0;
360
+ border: 0;
361
+ background: var(--line);
362
+ cursor: col-resize;
363
+ touch-action: none;
364
+ }
365
+ .sidebar-resizer::after {
366
+ content: "";
367
+ position: absolute;
368
+ inset: 0 -4px;
369
+ }
370
+ .sidebar-resizer:hover,
371
+ body.sidebar-resizing .sidebar-resizer {
372
+ background: var(--obsidian);
373
+ }
374
+ .app.sidebar-collapsed .sidebar-resizer {
375
+ width: 28px;
376
+ cursor: pointer;
377
+ background: var(--sidebar);
378
+ border-right: 1px solid var(--line);
379
+ }
380
+ .app.sidebar-collapsed .sidebar-resizer::before {
381
+ content: "";
382
+ position: absolute;
383
+ top: 50%;
384
+ left: 50%;
385
+ width: 6px;
386
+ height: 6px;
387
+ border-right: 1.5px solid var(--charcoal);
388
+ border-bottom: 1.5px solid var(--charcoal);
389
+ transform: translate(-70%, -50%) rotate(-45deg);
390
+ }
391
+ body.sidebar-resizing {
392
+ cursor: col-resize;
393
+ user-select: none;
394
+ }
395
+ body.sidebar-resizing * {
396
+ cursor: col-resize !important;
397
+ user-select: none !important;
398
+ }
323
399
  .tree-root { display: flex; flex-direction: column; gap: 2px; }
324
400
  .tree-folder { display: flex; flex-direction: column; gap: 2px; }
325
401
  .tree-folder-toggle {
@@ -380,7 +456,8 @@
380
456
  display: flex;
381
457
  align-items: center;
382
458
  gap: 8px;
383
- width: 100%;
459
+ flex: 1;
460
+ min-width: 0;
384
461
  border: 0;
385
462
  background: transparent;
386
463
  text-align: left;
@@ -388,8 +465,80 @@
388
465
  border-radius: var(--radius);
389
466
  cursor: pointer;
390
467
  }
391
- .nav-item:hover { background: var(--white); }
392
- .nav-item.active { background: var(--white); box-shadow: var(--ring); }
468
+ .nav-item:hover { background: transparent; }
469
+ .nav-op {
470
+ display: flex;
471
+ flex-direction: column;
472
+ gap: 0;
473
+ border-radius: var(--radius);
474
+ }
475
+ .nav-op:hover { background: var(--white); }
476
+ .nav-op.active { background: var(--white); box-shadow: var(--ring); }
477
+ .nav-op-row {
478
+ display: flex;
479
+ align-items: center;
480
+ gap: 2px;
481
+ min-width: 0;
482
+ }
483
+ .nav-expand {
484
+ flex: none;
485
+ width: 28px;
486
+ height: 28px;
487
+ border: 0;
488
+ border-radius: 6px;
489
+ background: transparent;
490
+ color: var(--stone);
491
+ cursor: pointer;
492
+ display: inline-flex;
493
+ align-items: center;
494
+ justify-content: center;
495
+ padding: 0;
496
+ }
497
+ .nav-expand:hover { color: var(--obsidian); background: var(--inset); }
498
+ .nav-expand .chev {
499
+ width: 6px;
500
+ height: 6px;
501
+ border-right: 1.5px solid currentColor;
502
+ border-bottom: 1.5px solid currentColor;
503
+ transform: rotate(-45deg);
504
+ transition: transform 0.15s ease;
505
+ margin-top: -2px;
506
+ }
507
+ .nav-op.examples-open > .nav-op-row .nav-expand .chev {
508
+ transform: rotate(45deg);
509
+ margin-top: 0;
510
+ }
511
+ .nav-expand:disabled {
512
+ opacity: 0.25;
513
+ cursor: default;
514
+ }
515
+ .nav-examples {
516
+ display: none;
517
+ flex-direction: column;
518
+ gap: 1px;
519
+ margin: 0 4px 6px 18px;
520
+ padding-left: 10px;
521
+ border-left: 1px solid var(--hairline);
522
+ }
523
+ .nav-op.examples-open > .nav-examples { display: flex; }
524
+ .nav-example {
525
+ display: block;
526
+ width: 100%;
527
+ border: 0;
528
+ background: transparent;
529
+ text-align: left;
530
+ padding: 5px 8px;
531
+ border-radius: 6px;
532
+ cursor: pointer;
533
+ font-size: 11px;
534
+ line-height: 1.35;
535
+ color: var(--stone);
536
+ overflow: hidden;
537
+ text-overflow: ellipsis;
538
+ white-space: nowrap;
539
+ }
540
+ .nav-example:hover { background: var(--inset); color: var(--charcoal); }
541
+ .nav-example.on { color: var(--obsidian); background: var(--inset); }
393
542
  .nav-title {
394
543
  font-size: 12px;
395
544
  color: var(--charcoal);
@@ -398,7 +547,149 @@
398
547
  text-overflow: ellipsis;
399
548
  white-space: nowrap;
400
549
  }
401
- .nav-item.active .nav-title { color: var(--obsidian); }
550
+ .nav-op.active .nav-title { color: var(--obsidian); }
551
+
552
+ .export-backdrop {
553
+ display: none;
554
+ position: fixed;
555
+ inset: 0;
556
+ background: rgba(232, 232, 232, 0.72);
557
+ backdrop-filter: blur(2px);
558
+ z-index: 40;
559
+ align-items: center;
560
+ justify-content: center;
561
+ padding: 24px;
562
+ }
563
+ body.exporting .export-backdrop { display: flex; }
564
+ .export-modal {
565
+ width: min(560px, 100%);
566
+ max-height: min(720px, calc(100vh - 48px));
567
+ display: flex;
568
+ flex-direction: column;
569
+ background: var(--white);
570
+ border-radius: 12px;
571
+ box-shadow: 0 18px 48px rgba(0, 0, 0, 0.16), var(--ring);
572
+ overflow: hidden;
573
+ }
574
+ .export-head {
575
+ padding: 18px 20px 12px;
576
+ border-bottom: 1px solid var(--hairline);
577
+ }
578
+ .export-head h2 {
579
+ margin: 0;
580
+ font-size: 18px;
581
+ font-weight: 500;
582
+ letter-spacing: -0.02em;
583
+ }
584
+ .export-head p {
585
+ margin: 6px 0 0;
586
+ font-size: 13px;
587
+ color: var(--stone);
588
+ line-height: 1.4;
589
+ }
590
+ .export-options {
591
+ padding: 12px 20px;
592
+ border-bottom: 1px solid var(--hairline);
593
+ display: flex;
594
+ flex-direction: column;
595
+ gap: 10px;
596
+ background: var(--inset);
597
+ }
598
+ .export-check {
599
+ display: flex;
600
+ align-items: flex-start;
601
+ gap: 8px;
602
+ font-size: 13px;
603
+ color: var(--obsidian);
604
+ cursor: pointer;
605
+ line-height: 1.35;
606
+ }
607
+ .export-check input { margin-top: 2px; }
608
+ .export-tryit-meta {
609
+ margin: -4px 0 0 22px;
610
+ font-size: 12px;
611
+ color: var(--stone);
612
+ font-family: var(--mono);
613
+ }
614
+ .export-mode {
615
+ display: flex;
616
+ flex-direction: column;
617
+ gap: 6px;
618
+ margin-left: 22px;
619
+ }
620
+ .export-mode label {
621
+ display: flex;
622
+ align-items: flex-start;
623
+ gap: 8px;
624
+ font-size: 12px;
625
+ color: var(--charcoal);
626
+ cursor: pointer;
627
+ line-height: 1.35;
628
+ }
629
+ .export-mode.disabled { opacity: 0.45; pointer-events: none; }
630
+ .export-tip {
631
+ margin: 0 0 0 22px;
632
+ font-size: 11px;
633
+ color: var(--stone);
634
+ line-height: 1.4;
635
+ }
636
+ .export-toolbar {
637
+ display: flex;
638
+ flex-wrap: wrap;
639
+ gap: 8px;
640
+ padding: 10px 20px;
641
+ border-bottom: 1px solid var(--hairline);
642
+ }
643
+ .export-body {
644
+ flex: 1;
645
+ overflow: auto;
646
+ padding: 8px 12px 16px;
647
+ }
648
+ .export-op {
649
+ padding: 10px 8px;
650
+ border-bottom: 1px solid var(--hairline);
651
+ }
652
+ .export-op:last-child { border-bottom: 0; }
653
+ .export-op-title {
654
+ display: flex;
655
+ align-items: center;
656
+ gap: 8px;
657
+ margin-bottom: 8px;
658
+ font-size: 12px;
659
+ color: var(--obsidian);
660
+ }
661
+ .export-op-title .path {
662
+ font-family: var(--mono);
663
+ font-size: 11px;
664
+ color: var(--stone);
665
+ overflow: hidden;
666
+ text-overflow: ellipsis;
667
+ white-space: nowrap;
668
+ }
669
+ .export-ex {
670
+ display: flex;
671
+ align-items: flex-start;
672
+ gap: 8px;
673
+ padding: 4px 4px 4px 2px;
674
+ font-size: 12px;
675
+ color: var(--charcoal);
676
+ line-height: 1.35;
677
+ }
678
+ .export-ex input { margin-top: 2px; }
679
+ .export-ex label { cursor: pointer; min-width: 0; }
680
+ .export-empty {
681
+ padding: 28px 16px;
682
+ text-align: center;
683
+ color: var(--stone);
684
+ font-size: 13px;
685
+ }
686
+ .export-foot {
687
+ display: flex;
688
+ justify-content: flex-end;
689
+ gap: 8px;
690
+ padding: 12px 16px 16px;
691
+ border-top: 1px solid var(--hairline);
692
+ }
402
693
 
403
694
  .method {
404
695
  display: inline-flex;
@@ -699,20 +990,49 @@
699
990
  }
700
991
  .row {
701
992
  display: grid;
702
- grid-template-columns: 1.2fr 0.7fr 1fr;
993
+ grid-template-columns: minmax(0, 1.5fr) minmax(72px, 0.55fr) minmax(0, 0.95fr);
703
994
  gap: 12px;
995
+ align-items: start;
704
996
  padding: 8px 0;
705
997
  font-size: 13px;
706
998
  }
707
- .row .name { font-family: var(--mono); font-size: 12px; color: var(--obsidian); }
708
- .row .name.nested { color: var(--ink, var(--obsidian)); }
709
- .row .type { color: var(--stone); font-family: var(--mono); font-size: 12px; }
999
+ .row .name {
1000
+ font-family: var(--mono);
1001
+ font-size: 12px;
1002
+ color: var(--obsidian);
1003
+ min-width: 0;
1004
+ overflow-wrap: anywhere;
1005
+ word-break: break-word;
1006
+ }
1007
+ .row .name.nested {
1008
+ color: var(--charcoal);
1009
+ border-left: 2px solid var(--hairline);
1010
+ padding-left: 10px;
1011
+ margin-left: 2px;
1012
+ }
1013
+ .row .name.nested[data-depth="2"] { margin-left: 14px; }
1014
+ .row .name.nested[data-depth="3"] { margin-left: 26px; }
1015
+ .row .name.nested[data-depth="4"] { margin-left: 38px; }
1016
+ .row .loc,
1017
+ .row .type {
1018
+ color: var(--stone);
1019
+ font-family: var(--mono);
1020
+ font-size: 12px;
1021
+ min-width: 0;
1022
+ }
710
1023
  .flag { margin-top: 4px; font-size: 11px; color: var(--smoke); }
711
1024
  .flag.req { color: #8a2e2e; }
712
1025
 
713
1026
  @media (max-width: 960px) {
714
- .app { grid-template-columns: 1fr; height: auto; }
715
- .sidebar { max-height: 40vh; }
1027
+ .app {
1028
+ grid-template-columns: 1fr;
1029
+ height: auto;
1030
+ }
1031
+ .app.sidebar-collapsed {
1032
+ grid-template-columns: 1fr;
1033
+ }
1034
+ .sidebar { max-height: 40vh; opacity: 1 !important; pointer-events: auto !important; padding: 16px 12px 24px !important; }
1035
+ .sidebar-resizer { display: none; }
716
1036
  .pair { grid-template-columns: 1fr; }
717
1037
  .search-wrap { width: min(280px, 70vw); }
718
1038
  }
@@ -739,8 +1059,49 @@
739
1059
  </div>
740
1060
  </header>
741
1061
  <div class="search-backdrop" id="search-backdrop"></div>
742
- <div class="app">
1062
+ <div class="export-backdrop" id="export-backdrop" role="dialog" aria-modal="true" aria-labelledby="export-title">
1063
+ <div class="export-modal" id="export-modal">
1064
+ <div class="export-head">
1065
+ <h2 id="export-title">Export OpenAPI</h2>
1066
+ <p>Choose examples to include. Optionally bake Try-it env/headers so Postman can auto-fill on import.</p>
1067
+ </div>
1068
+ <div class="export-options">
1069
+ <label class="export-check">
1070
+ <input type="checkbox" id="export-include-tryit" checked />
1071
+ <span>Include active Try-it env + header group</span>
1072
+ </label>
1073
+ <div class="export-tryit-meta" id="export-tryit-meta">—</div>
1074
+ <div class="export-mode" id="export-mode-wrap">
1075
+ <label>
1076
+ <input type="radio" name="export-fill" value="resolved" checked />
1077
+ <span>Resolved values in OpenAPI <span style="color:var(--stone)">(headers/server filled literally)</span></span>
1078
+ </label>
1079
+ <label>
1080
+ <input type="radio" name="export-fill" value="variables" />
1081
+ <span>Postman <code>{{variables}}</code> + download environment file</span>
1082
+ </label>
1083
+ </div>
1084
+ <p class="export-tip">Postman names saved examples from OpenAPI <em>response description</em> (“Created”), so also download a Collection with the real scenario titles. Import → advanced → parameter generation = <strong>Example</strong>.</p>
1085
+ <label class="export-check">
1086
+ <input type="checkbox" id="export-postman-collection" checked />
1087
+ <span>Also download Postman Collection <span style="color:var(--stone)">(named examples)</span></span>
1088
+ </label>
1089
+ </div>
1090
+ <div class="export-toolbar">
1091
+ <button type="button" class="btn sm" id="export-all">All</button>
1092
+ <button type="button" class="btn sm" id="export-none">None</button>
1093
+ <button type="button" class="btn sm" id="export-success">Success only</button>
1094
+ </div>
1095
+ <div class="export-body" id="export-body"></div>
1096
+ <div class="export-foot">
1097
+ <button type="button" class="btn sm" id="export-cancel">Cancel</button>
1098
+ <button type="button" class="btn primary sm" id="export-confirm">Download</button>
1099
+ </div>
1100
+ </div>
1101
+ </div>
1102
+ <div class="app" id="app">
743
1103
  <aside class="sidebar" id="nav"></aside>
1104
+ <button type="button" class="sidebar-resizer" id="sidebar-resizer" aria-label="Resize sidebar" title="Drag to resize · double-click to collapse"></button>
744
1105
  <main class="workbench" id="main"></main>
745
1106
  </div>
746
1107
  <script>
@@ -775,6 +1136,125 @@
775
1136
  const defaultBaseUrl = locationBaseUrl || defaultBaseUrlFromSpec;
776
1137
  const title = (spec.info && spec.info.title) || "API Docs";
777
1138
  const STORE_KEY = "openapi-docs-env:" + (workspace || "default");
1139
+ const SIDEBAR_STORE_KEY = "openapi-docs-sidebar:" + (workspace || "default");
1140
+ const SIDEBAR_MIN = 200;
1141
+ const SIDEBAR_MAX = 560;
1142
+ const SIDEBAR_DEFAULT = 320;
1143
+
1144
+ const docsBaseForApi = (() => {
1145
+ if (typeof location === "undefined") return docsPathSuffix;
1146
+ let pathname = (location.pathname || "/").replace(/\/$/, "") || "";
1147
+ if (pathname === docsPathSuffix || pathname.endsWith(docsPathSuffix)) return pathname || docsPathSuffix;
1148
+ const idx = pathname.indexOf(docsPathSuffix);
1149
+ if (idx >= 0) return pathname.slice(0, idx + docsPathSuffix.length) || docsPathSuffix;
1150
+ return docsPathSuffix;
1151
+ })();
1152
+ const ENV_STORE_URL = docsBaseForApi + "/env.json";
1153
+
1154
+ const loadSidebarLayout = () => {
1155
+ try {
1156
+ const raw = localStorage.getItem(SIDEBAR_STORE_KEY);
1157
+ if (!raw) return { width: SIDEBAR_DEFAULT, collapsed: false };
1158
+ const parsed = JSON.parse(raw);
1159
+ const width = Number(parsed.width);
1160
+ return {
1161
+ width: Number.isFinite(width) ? Math.min(SIDEBAR_MAX, Math.max(SIDEBAR_MIN, width)) : SIDEBAR_DEFAULT,
1162
+ collapsed: Boolean(parsed.collapsed),
1163
+ };
1164
+ } catch {
1165
+ return { width: SIDEBAR_DEFAULT, collapsed: false };
1166
+ }
1167
+ };
1168
+
1169
+ let sidebarLayout = loadSidebarLayout();
1170
+
1171
+ const applySidebarLayout = () => {
1172
+ const app = document.getElementById("app");
1173
+ const resizer = document.getElementById("sidebar-resizer");
1174
+ if (!app) return;
1175
+ app.style.setProperty("--sidebar-w", sidebarLayout.width + "px");
1176
+ app.classList.toggle("sidebar-collapsed", sidebarLayout.collapsed);
1177
+ if (resizer) {
1178
+ resizer.title = sidebarLayout.collapsed
1179
+ ? "Click to expand sidebar"
1180
+ : "Drag to resize · double-click to collapse";
1181
+ resizer.setAttribute("aria-label", sidebarLayout.collapsed ? "Expand sidebar" : "Resize sidebar");
1182
+ }
1183
+ };
1184
+
1185
+ const persistSidebarLayout = () => {
1186
+ try {
1187
+ localStorage.setItem(SIDEBAR_STORE_KEY, JSON.stringify(sidebarLayout));
1188
+ } catch {}
1189
+ };
1190
+
1191
+ const initSidebarResize = () => {
1192
+ const resizer = document.getElementById("sidebar-resizer");
1193
+ if (!resizer) return;
1194
+ applySidebarLayout();
1195
+
1196
+ let dragging = false;
1197
+ let startX = 0;
1198
+ let startWidth = 0;
1199
+ let moved = false;
1200
+
1201
+ const onMove = (event) => {
1202
+ if (!dragging) return;
1203
+ if (event.cancelable) event.preventDefault();
1204
+ const clientX = event.touches ? event.touches[0].clientX : event.clientX;
1205
+ const delta = clientX - startX;
1206
+ if (Math.abs(delta) > 2) moved = true;
1207
+ const next = Math.min(SIDEBAR_MAX, Math.max(SIDEBAR_MIN, startWidth + delta));
1208
+ sidebarLayout.width = next;
1209
+ sidebarLayout.collapsed = false;
1210
+ applySidebarLayout();
1211
+ };
1212
+
1213
+ const onUp = () => {
1214
+ if (!dragging) return;
1215
+ dragging = false;
1216
+ document.body.classList.remove("sidebar-resizing");
1217
+ window.removeEventListener("mousemove", onMove);
1218
+ window.removeEventListener("mouseup", onUp);
1219
+ window.removeEventListener("touchmove", onMove);
1220
+ window.removeEventListener("touchend", onUp);
1221
+ persistSidebarLayout();
1222
+ };
1223
+
1224
+ const onDown = (event) => {
1225
+ if (sidebarLayout.collapsed) return;
1226
+ if (event.button != null && event.button !== 0) return;
1227
+ event.preventDefault();
1228
+ dragging = true;
1229
+ moved = false;
1230
+ startX = event.touches ? event.touches[0].clientX : event.clientX;
1231
+ startWidth = sidebarLayout.width;
1232
+ document.body.classList.add("sidebar-resizing");
1233
+ window.addEventListener("mousemove", onMove);
1234
+ window.addEventListener("mouseup", onUp);
1235
+ window.addEventListener("touchmove", onMove, { passive: false });
1236
+ window.addEventListener("touchend", onUp);
1237
+ };
1238
+
1239
+ resizer.addEventListener("mousedown", onDown);
1240
+ resizer.addEventListener("touchstart", onDown, { passive: false });
1241
+ resizer.addEventListener("dblclick", (event) => {
1242
+ event.preventDefault();
1243
+ sidebarLayout.collapsed = !sidebarLayout.collapsed;
1244
+ if (!sidebarLayout.collapsed && sidebarLayout.width < SIDEBAR_MIN) sidebarLayout.width = SIDEBAR_DEFAULT;
1245
+ applySidebarLayout();
1246
+ persistSidebarLayout();
1247
+ });
1248
+ resizer.addEventListener("click", (event) => {
1249
+ if (!sidebarLayout.collapsed || moved) return;
1250
+ event.preventDefault();
1251
+ sidebarLayout.collapsed = false;
1252
+ applySidebarLayout();
1253
+ persistSidebarLayout();
1254
+ });
1255
+ };
1256
+
1257
+ initSidebarResize();
778
1258
 
779
1259
  let liveResult = null;
780
1260
 
@@ -820,10 +1300,23 @@
820
1300
 
821
1301
  const defaultHeaderValues = collectDefaultHeaderValues();
822
1302
 
823
- const buildDefaultStore = () => {
1303
+ const configuredPresets = (() => {
1304
+ const raw = viewer.envPresets;
1305
+ if (raw && typeof raw === "object" && Object.keys(raw).length) return raw;
1306
+ return { local: { baseUrl: defaultBaseUrl } };
1307
+ })();
1308
+
1309
+ const setEnvBaseUrl = (env, baseUrl) => {
1310
+ const variables = env.variables || (env.variables = []);
1311
+ const row = variables.find((entry) => entry.key === "baseUrl");
1312
+ if (row) row.value = baseUrl;
1313
+ else variables.unshift({ key: "baseUrl", value: baseUrl });
1314
+ };
1315
+
1316
+ const buildHeaderTemplate = () => {
824
1317
  const schemes = (spec.components && spec.components.securitySchemes) || {};
825
- const variables = [{ key: "baseUrl", value: defaultBaseUrl }];
826
- const varKeys = new Set(["baseUrl"]);
1318
+ const variables = [];
1319
+ const varKeys = new Set();
827
1320
  const headerGroups = {};
828
1321
  for (const [schemeId, scheme] of Object.entries(schemes)) {
829
1322
  if (!scheme || scheme.in !== "header" || !scheme.name) continue;
@@ -839,7 +1332,6 @@
839
1332
  { key: "content-type", value: "application/json" },
840
1333
  ];
841
1334
  }
842
- // Pre-build merged groups for operations that need multiple schemes together.
843
1335
  const seenCombos = new Set();
844
1336
  for (const pathItem of Object.values(spec.paths || {})) {
845
1337
  for (const op of Object.values(pathItem || {})) {
@@ -867,17 +1359,56 @@
867
1359
  headerGroups[comboKey] = Object.values(byKey);
868
1360
  }
869
1361
  }
870
-
871
1362
  const groupNames = Object.keys(headerGroups);
872
1363
  if (!groupNames.length) headerGroups.default = [{ key: "content-type", value: "application/json" }];
1364
+ return { variables, headerGroups };
1365
+ };
1366
+
1367
+ const envFromPreset = (preset) => {
1368
+ const template = buildHeaderTemplate();
1369
+ const baseUrl = String((preset && preset.baseUrl) || defaultBaseUrl).replace(/\/$/, "") || defaultBaseUrl;
1370
+ const variables = [{ key: "baseUrl", value: baseUrl }, ...template.variables.map((row) => ({ ...row }))];
1371
+ const known = new Set(variables.map((row) => row.key));
1372
+ if (preset && preset.variables && typeof preset.variables === "object") {
1373
+ for (const [key, value] of Object.entries(preset.variables)) {
1374
+ if (!key || key === "baseUrl") continue;
1375
+ if (known.has(key)) {
1376
+ const row = variables.find((entry) => entry.key === key);
1377
+ if (row) row.value = String(value ?? "");
1378
+ } else {
1379
+ variables.push({ key, value: String(value ?? "") });
1380
+ known.add(key);
1381
+ }
1382
+ }
1383
+ }
1384
+ const headerGroups = {};
1385
+ for (const [group, rows] of Object.entries(template.headerGroups)) {
1386
+ headerGroups[group] = rows.map((row) => ({ ...row }));
1387
+ }
1388
+ return { variables, headerGroups };
1389
+ };
1390
+
1391
+ const buildDefaultStore = () => {
1392
+ const envs = {};
1393
+ for (const [name, preset] of Object.entries(configuredPresets)) {
1394
+ envs[name] = envFromPreset(preset);
1395
+ }
1396
+ if (!Object.keys(envs).length) envs.local = envFromPreset({ baseUrl: defaultBaseUrl });
1397
+ const names = Object.keys(envs);
1398
+ const activeEnv = names.includes("local") ? "local" : names[0];
1399
+ const groupNames = Object.keys(envs[activeEnv].headerGroups || {});
873
1400
  return {
874
- activeEnv: "local",
1401
+ activeEnv,
875
1402
  activeGroup: groupNames[0] || "default",
876
- envs: { local: { variables, headerGroups } },
1403
+ envs,
877
1404
  };
878
1405
  };
879
1406
 
880
- const cloneDefaultEnv = () => JSON.parse(JSON.stringify(buildDefaultStore().envs.local));
1407
+ const cloneDefaultEnv = () => {
1408
+ const defaults = buildDefaultStore();
1409
+ const name = defaults.envs.local ? "local" : Object.keys(defaults.envs)[0];
1410
+ return JSON.parse(JSON.stringify(defaults.envs[name]));
1411
+ };
881
1412
 
882
1413
  const mergeStore = (saved) => {
883
1414
  const defaults = buildDefaultStore();
@@ -885,12 +1416,13 @@
885
1416
  const envs = {};
886
1417
  for (const [name, env] of Object.entries(saved.envs)) {
887
1418
  const base = cloneDefaultEnv();
888
- const variables = Array.isArray(env.variables) ? env.variables.map((row) => ({ key: String(row.key || ""), value: String(row.value ?? "") })) : base.variables.map((row) => ({ ...row }));
1419
+ const variables = Array.isArray(env.variables)
1420
+ ? env.variables.map((row) => ({ key: String(row.key || ""), value: String(row.value ?? "") }))
1421
+ : base.variables.map((row) => ({ ...row }));
889
1422
  const known = new Set(variables.map((row) => row.key).filter(Boolean));
890
1423
  for (const row of base.variables) {
891
1424
  if (row.key && !known.has(row.key)) variables.push({ ...row });
892
1425
  }
893
- // Backfill empty env values from recorded defaults so Try-it works out of the box.
894
1426
  const defaultsByKey = Object.fromEntries((base.variables || []).filter((row) => row.key).map((row) => [row.key, row.value ?? ""]));
895
1427
  for (const row of variables) {
896
1428
  if (!row.key) continue;
@@ -904,6 +1436,11 @@
904
1436
  if (!Object.keys(headerGroups).length) headerGroups.default = [{ key: "content-type", value: "application/json" }];
905
1437
  envs[name] = { variables, headerGroups };
906
1438
  }
1439
+ // Seed any config presets that are missing from the saved store (don't wipe existing).
1440
+ for (const [name, preset] of Object.entries(configuredPresets)) {
1441
+ if (envs[name]) continue;
1442
+ envs[name] = envFromPreset(preset);
1443
+ }
907
1444
  if (!Object.keys(envs).length) return defaults;
908
1445
  const activeEnv = envs[saved.activeEnv] ? saved.activeEnv : Object.keys(envs)[0];
909
1446
  const groups = Object.keys(envs[activeEnv].headerGroups || {});
@@ -911,33 +1448,75 @@
911
1448
  return { activeEnv, activeGroup, envs };
912
1449
  };
913
1450
 
914
- const loadStore = () => {
1451
+ const loadLocalStore = () => {
915
1452
  try {
916
1453
  const raw = localStorage.getItem(STORE_KEY);
917
1454
  if (raw) return mergeStore(JSON.parse(raw));
918
1455
  } catch {}
919
- return buildDefaultStore();
1456
+ return null;
920
1457
  };
921
1458
 
1459
+ /**
1460
+ * Only rewrite baseUrl for local-ish presets so staging/production stay intact.
1461
+ */
922
1462
  const applyServingBaseUrl = (state) => {
923
1463
  if (!locationBaseUrl || !state || !state.envs) return state;
924
- for (const env of Object.values(state.envs)) {
925
- const variables = env.variables || (env.variables = []);
926
- const row = variables.find((entry) => entry.key === "baseUrl");
927
- if (row) row.value = locationBaseUrl;
928
- else variables.unshift({ key: "baseUrl", value: locationBaseUrl });
1464
+ const preferred = ["local", "development", "dev"].find((name) => state.envs[name]);
1465
+ if (preferred) {
1466
+ setEnvBaseUrl(state.envs[preferred], locationBaseUrl);
1467
+ return state;
929
1468
  }
1469
+ const names = Object.keys(state.envs);
1470
+ if (names.length === 1) setEnvBaseUrl(state.envs[names[0]], locationBaseUrl);
930
1471
  return state;
931
1472
  };
932
1473
 
933
- let store = applyServingBaseUrl(loadStore());
1474
+ // Prefer disk (shared across browsers / deploy), then localStorage, then defaults.
1475
+ let store = applyServingBaseUrl(loadLocalStore() || buildDefaultStore());
1476
+ let persistTimer = null;
934
1477
 
935
- const persistStore = () => {
1478
+ const writeLocalStore = () => {
936
1479
  try {
937
1480
  localStorage.setItem(STORE_KEY, JSON.stringify(store));
938
1481
  } catch {}
939
1482
  };
940
1483
 
1484
+ const writeServerStore = async () => {
1485
+ try {
1486
+ const res = await fetch(ENV_STORE_URL, {
1487
+ method: "PUT",
1488
+ headers: { "content-type": "application/json" },
1489
+ body: JSON.stringify(store),
1490
+ });
1491
+ if (!res.ok) return;
1492
+ } catch {
1493
+ /* offline / file:// — localStorage still works */
1494
+ }
1495
+ };
1496
+
1497
+ const persistStore = () => {
1498
+ writeLocalStore();
1499
+ if (persistTimer) clearTimeout(persistTimer);
1500
+ persistTimer = setTimeout(() => {
1501
+ persistTimer = null;
1502
+ writeServerStore();
1503
+ }, 250);
1504
+ };
1505
+
1506
+ const hydrateStoreFromServer = async () => {
1507
+ try {
1508
+ const res = await fetch(ENV_STORE_URL, { cache: "no-store" });
1509
+ if (!res.ok) return false;
1510
+ const remote = await res.json();
1511
+ if (!remote || typeof remote !== "object" || !remote.envs) return false;
1512
+ store = applyServingBaseUrl(mergeStore(remote));
1513
+ writeLocalStore();
1514
+ return true;
1515
+ } catch {
1516
+ return false;
1517
+ }
1518
+ };
1519
+
941
1520
  const activeEnvConfig = () => store.envs[store.activeEnv] || store.envs[Object.keys(store.envs)[0]];
942
1521
 
943
1522
  const varMap = () => {
@@ -1033,7 +1612,27 @@
1033
1612
 
1034
1613
  const syncEnvTrigger = () => {
1035
1614
  const trigger = document.getElementById("env-trigger");
1036
- if (trigger) trigger.textContent = envLabel();
1615
+ if (!trigger) return;
1616
+ trigger.textContent = envLabel();
1617
+ const base = varMap().baseUrl || "";
1618
+ trigger.title = base ? store.activeEnv + " · " + base + " · " + store.activeGroup : envLabel();
1619
+ };
1620
+
1621
+ const presetBaseUrl = (name) => {
1622
+ const env = store.envs[name];
1623
+ if (!env) return "";
1624
+ const row = (env.variables || []).find((entry) => entry.key === "baseUrl");
1625
+ return row ? String(row.value || "") : "";
1626
+ };
1627
+
1628
+ const addNamedPreset = (name, baseUrl) => {
1629
+ if (!name || store.envs[name]) return false;
1630
+ const env = cloneDefaultEnv();
1631
+ setEnvBaseUrl(env, baseUrl || defaultBaseUrl);
1632
+ store.envs[name] = env;
1633
+ store.activeEnv = name;
1634
+ store.activeGroup = Object.keys(env.headerGroups || {})[0] || "default";
1635
+ return true;
1037
1636
  };
1038
1637
 
1039
1638
  const renderEnvPop = () => {
@@ -1044,26 +1643,43 @@
1044
1643
  const groupRows = env.headerGroups[store.activeGroup] || [];
1045
1644
  const canRemoveEnv = envNames.length > 1;
1046
1645
  const canRemoveGroup = groups.length > 1;
1646
+ const activeBase = presetBaseUrl(store.activeEnv) || defaultBaseUrl;
1647
+ const quickPresets = [
1648
+ { id: "staging", baseUrl: (configuredPresets.staging && configuredPresets.staging.baseUrl) || "https://api.staging.example.com" },
1649
+ { id: "production", baseUrl: (configuredPresets.production && configuredPresets.production.baseUrl) || "https://api.example.com" },
1650
+ ].filter((preset) => !store.envs[preset.id]);
1047
1651
 
1048
1652
  document.getElementById("env-pop").innerHTML = `
1049
1653
  <div class="env-block">
1050
- <div class="env-label">Env</div>
1654
+ <div class="env-label">Presets</div>
1051
1655
  <div class="chip-row">
1052
1656
  ${envNames
1053
- .map((id) => `<button type="button" class="chip-btn ${id === store.activeEnv ? "on" : ""}" data-env="${escapeAttr(id)}">${escapeAttr(id)}</button>`)
1657
+ .map((id) => `<button type="button" class="chip-btn ${id === store.activeEnv ? "on" : ""}" data-env="${escapeAttr(id)}" title="${escapeAttr(presetBaseUrl(id))}">${escapeAttr(id)}</button>`)
1054
1658
  .join("")}
1055
- <button type="button" class="ghost-btn" id="add-env" title="Add env">+</button>
1056
- <button type="button" class="ghost-btn" id="remove-env" title="Remove env" ${canRemoveEnv ? "" : "disabled"}>×</button>
1659
+ <button type="button" class="ghost-btn" id="add-env" title="Add preset">+</button>
1660
+ <button type="button" class="ghost-btn" id="dup-env" title="Duplicate preset">⧉</button>
1661
+ <button type="button" class="ghost-btn" id="remove-env" title="Remove preset" ${canRemoveEnv ? "" : "disabled"}>×</button>
1057
1662
  </div>
1663
+ <div class="env-base-line"><span>baseUrl</span> · ${escapeAttr(activeBase)}</div>
1664
+ ${
1665
+ quickPresets.length
1666
+ ? `<div class="env-quick">${quickPresets
1667
+ .map(
1668
+ (preset) =>
1669
+ `<button type="button" class="btn sm" data-quick-preset="${escapeAttr(preset.id)}" data-base="${escapeAttr(preset.baseUrl)}">+ ${escapeAttr(preset.id)}</button>`,
1670
+ )
1671
+ .join("")}</div>`
1672
+ : ""
1673
+ }
1058
1674
  </div>
1059
1675
  <div class="env-block">
1060
1676
  <div class="env-label">Variables</div>
1061
1677
  ${(env.variables || [])
1062
1678
  .map(
1063
- (row, index) => `<div class="env-kv" data-var="${index}">
1064
- <input class="env-cell" data-field="key" spellcheck="false" value="${escapeAttr(row.key)}" />
1679
+ (row, index) => `<div class="env-kv ${row.key === "baseUrl" ? "base-url" : ""}" data-var="${index}">
1680
+ <input class="env-cell" data-field="key" spellcheck="false" value="${escapeAttr(row.key)}" ${row.key === "baseUrl" ? "readonly" : ""} />
1065
1681
  <input class="env-cell" data-field="value" spellcheck="false" value="${escapeAttr(row.value)}" />
1066
- <button type="button" class="ghost-btn" data-remove-var="${index}">×</button>
1682
+ <button type="button" class="ghost-btn" data-remove-var="${index}" ${row.key === "baseUrl" ? "disabled" : ""}>×</button>
1067
1683
  </div>`,
1068
1684
  )
1069
1685
  .join("")}
@@ -1104,15 +1720,42 @@
1104
1720
  renderMain();
1105
1721
  };
1106
1722
  });
1723
+ document.getElementById("env-pop").querySelectorAll("[data-quick-preset]").forEach((button) => {
1724
+ button.onclick = (event) => {
1725
+ event.stopPropagation();
1726
+ if (!addNamedPreset(button.dataset.quickPreset, button.dataset.base)) return;
1727
+ persistStore();
1728
+ renderEnvPop();
1729
+ renderMain();
1730
+ };
1731
+ });
1107
1732
  document.getElementById("add-env").onclick = (event) => {
1108
1733
  event.stopPropagation();
1109
- let name = "env";
1110
- let n = 1;
1111
- while (store.envs[name + n]) n += 1;
1112
- name = name + n;
1113
- store.envs[name] = cloneDefaultEnv();
1734
+ const typed = window.prompt("Preset name (e.g. staging)", "staging");
1735
+ if (!typed) return;
1736
+ const name = typed.trim().replace(/\s+/g, "-");
1737
+ if (!name) return;
1738
+ if (store.envs[name]) {
1739
+ store.activeEnv = name;
1740
+ } else {
1741
+ const base = window.prompt("baseUrl", configuredPresets[name]?.baseUrl || defaultBaseUrl) || defaultBaseUrl;
1742
+ addNamedPreset(name, base.replace(/\/$/, ""));
1743
+ }
1744
+ persistStore();
1745
+ renderEnvPop();
1746
+ renderMain();
1747
+ };
1748
+ document.getElementById("dup-env").onclick = (event) => {
1749
+ event.stopPropagation();
1750
+ const source = store.activeEnv;
1751
+ let name = source + "-copy";
1752
+ let n = 2;
1753
+ while (store.envs[name]) {
1754
+ name = source + "-copy" + n;
1755
+ n += 1;
1756
+ }
1757
+ store.envs[name] = JSON.parse(JSON.stringify(activeEnvConfig()));
1114
1758
  store.activeEnv = name;
1115
- store.activeGroup = Object.keys(store.envs[name].headerGroups)[0] || "default";
1116
1759
  persistStore();
1117
1760
  renderEnvPop();
1118
1761
  renderMain();
@@ -1271,7 +1914,121 @@
1271
1914
  return "/" + parts.join("/");
1272
1915
  };
1273
1916
 
1274
- const toExportSpec = (source) => {
1917
+ const listOperationExamples = (operation) => {
1918
+ const byKey = new Map();
1919
+ const add = (key, summary) => {
1920
+ if (!key || byKey.has(key)) return;
1921
+ byKey.set(key, { key, summary: summary || key });
1922
+ };
1923
+ const reqExamples = operation?.requestBody?.content?.["application/json"]?.examples;
1924
+ for (const [key, example] of Object.entries(reqExamples || {})) {
1925
+ add(key, example && example.summary);
1926
+ }
1927
+ for (const response of Object.values(operation?.responses || {})) {
1928
+ const examples = response?.content?.["application/json"]?.examples;
1929
+ for (const [key, example] of Object.entries(examples || {})) {
1930
+ add(key, example && example.summary);
1931
+ }
1932
+ }
1933
+ return [...byKey.values()];
1934
+ };
1935
+
1936
+ const filterExamplesMap = (examples, allowedKeys) => {
1937
+ if (!examples || typeof examples !== "object") return examples;
1938
+ if (!allowedKeys) return examples;
1939
+ const out = {};
1940
+ for (const [key, value] of Object.entries(examples)) {
1941
+ if (allowedKeys.has(key)) out[key] = value;
1942
+ }
1943
+ return out;
1944
+ };
1945
+
1946
+ const filterOperationExamples = (operation, allowedKeys) => {
1947
+ if (!allowedKeys) return operation;
1948
+ const next = { ...operation };
1949
+ if (next.requestBody?.content?.["application/json"]?.examples) {
1950
+ const media = { ...next.requestBody.content["application/json"] };
1951
+ media.examples = filterExamplesMap(media.examples, allowedKeys);
1952
+ next.requestBody = {
1953
+ ...next.requestBody,
1954
+ content: { ...next.requestBody.content, "application/json": media },
1955
+ };
1956
+ }
1957
+ if (next.responses) {
1958
+ const responses = {};
1959
+ for (const [status, response] of Object.entries(next.responses)) {
1960
+ if (!response?.content?.["application/json"]?.examples) {
1961
+ responses[status] = response;
1962
+ continue;
1963
+ }
1964
+ const media = { ...response.content["application/json"] };
1965
+ media.examples = filterExamplesMap(media.examples, allowedKeys);
1966
+ responses[status] = {
1967
+ ...response,
1968
+ content: { ...response.content, "application/json": media },
1969
+ };
1970
+ }
1971
+ next.responses = responses;
1972
+ }
1973
+ return next;
1974
+ };
1975
+
1976
+ /** Rename example map keys to scenario titles; set summary+description (Postman-friendly). */
1977
+ const promoteExampleLabels = (examples) => {
1978
+ if (!examples || typeof examples !== "object") return examples;
1979
+ const out = {};
1980
+ for (const [key, example] of Object.entries(examples)) {
1981
+ if (!example || typeof example !== "object") continue;
1982
+ const summary = String(example.summary || example.description || key).trim() || key;
1983
+ let name = summary;
1984
+ let n = 2;
1985
+ while (Object.prototype.hasOwnProperty.call(out, name)) {
1986
+ name = summary + " (" + n + ")";
1987
+ n += 1;
1988
+ }
1989
+ out[name] = {
1990
+ summary,
1991
+ description: summary,
1992
+ value: example.value,
1993
+ };
1994
+ }
1995
+ return out;
1996
+ };
1997
+
1998
+ const promoteOperationExampleLabels = (operation) => {
1999
+ const next = { ...operation };
2000
+ if (next.requestBody?.content?.["application/json"]?.examples) {
2001
+ const media = { ...next.requestBody.content["application/json"] };
2002
+ media.examples = promoteExampleLabels(media.examples);
2003
+ next.requestBody = {
2004
+ ...next.requestBody,
2005
+ content: { ...next.requestBody.content, "application/json": media },
2006
+ };
2007
+ }
2008
+ if (next.responses) {
2009
+ const responses = {};
2010
+ for (const [status, response] of Object.entries(next.responses)) {
2011
+ const examples = response?.content?.["application/json"]?.examples;
2012
+ if (!examples) {
2013
+ responses[status] = response;
2014
+ continue;
2015
+ }
2016
+ const media = { ...response.content["application/json"] };
2017
+ media.examples = promoteExampleLabels(examples);
2018
+ const labels = Object.keys(media.examples);
2019
+ responses[status] = {
2020
+ ...response,
2021
+ // Single example: description becomes the scenario title (Postman uses this as the example name).
2022
+ description: labels.length === 1 ? labels[0] : response.description || status,
2023
+ content: { ...response.content, "application/json": media },
2024
+ };
2025
+ }
2026
+ next.responses = responses;
2027
+ }
2028
+ return next;
2029
+ };
2030
+
2031
+ const toExportSpec = (source, selectedByOpId) => {
1275
2032
  const pathsIn = source.paths || {};
1276
2033
  const pathsOut = {};
1277
2034
  const tagNames = new Set();
@@ -1298,7 +2055,12 @@
1298
2055
  continue;
1299
2056
  }
1300
2057
  const segments = operation["x-tree-segments"] || urlPath.split("/").filter(Boolean);
1301
- const cleaned = stripExt(operation);
2058
+ let cleaned = stripExt(operation);
2059
+ const opId = method + ":" + urlPath;
2060
+ if (selectedByOpId && selectedByOpId.has(opId)) {
2061
+ cleaned = filterOperationExamples(cleaned, selectedByOpId.get(opId));
2062
+ }
2063
+ cleaned = promoteOperationExampleLabels(cleaned);
1302
2064
  const tagParts = segments.filter((part) => !String(part).startsWith("{"));
1303
2065
  const tag = tagParts.length ? tagParts.join(" / ") : "API";
1304
2066
  cleaned.tags = [tag];
@@ -1322,24 +2084,364 @@
1322
2084
  };
1323
2085
  };
1324
2086
 
1325
- const downloadOpenApi = () => {
1326
- const exported = toExportSpec(spec);
1327
- const blob = new Blob([JSON.stringify(exported, null, 2) + "\n"], { type: "application/json" });
2087
+ const headerRowsForExport = () => {
2088
+ const env = activeEnvConfig();
2089
+ const groups = env.headerGroups || {};
2090
+ return groups[store.activeGroup] || groups[Object.keys(groups)[0]] || [];
2091
+ };
2092
+
2093
+ const applyTryItFill = (exported, fillMode) => {
2094
+ const vars = varMap();
2095
+ const rows = headerRowsForExport();
2096
+ const finalServer =
2097
+ fillMode === "variables" ? "{{baseUrl}}" : String(interpolate(vars.baseUrl || defaultBaseUrl, vars)).replace(/\/$/, "") || defaultBaseUrl;
2098
+
2099
+ exported.servers = [{ url: finalServer }];
2100
+
2101
+ const paths = exported.paths || {};
2102
+ for (const pathItem of Object.values(paths)) {
2103
+ if (!pathItem || typeof pathItem !== "object") continue;
2104
+ for (const method of HTTP_EXPORT) {
2105
+ if (!pathItem[method] || typeof pathItem[method] !== "object") continue;
2106
+ const operation = { ...pathItem[method] };
2107
+ const params = Array.isArray(operation.parameters) ? operation.parameters.map((p) => ({ ...p })) : [];
2108
+
2109
+ for (const row of rows) {
2110
+ if (!row.key) continue;
2111
+ const lower = String(row.key).toLowerCase();
2112
+ if (lower === "host" || lower === "content-length") continue;
2113
+ const exampleValue =
2114
+ fillMode === "resolved"
2115
+ ? String(interpolate(row.value || "", vars))
2116
+ : String(row.value ?? "");
2117
+ const existing = params.findIndex(
2118
+ (param) => param && param.in === "header" && String(param.name).toLowerCase() === lower,
2119
+ );
2120
+ if (existing >= 0) {
2121
+ const prev = params[existing];
2122
+ params[existing] = {
2123
+ ...prev,
2124
+ required: prev.required !== false,
2125
+ example: exampleValue,
2126
+ schema: {
2127
+ ...(prev.schema && typeof prev.schema === "object" ? prev.schema : {}),
2128
+ type: "string",
2129
+ example: exampleValue,
2130
+ },
2131
+ };
2132
+ } else {
2133
+ params.push({
2134
+ name: row.key,
2135
+ in: "header",
2136
+ required: true,
2137
+ schema: { type: "string", example: exampleValue },
2138
+ example: exampleValue,
2139
+ });
2140
+ }
2141
+ }
2142
+
2143
+ operation.parameters = params;
2144
+ pathItem[method] = operation;
2145
+ }
2146
+ }
2147
+
2148
+ return exported;
2149
+ };
2150
+
2151
+ const buildPostmanEnvironment = () => {
2152
+ const env = activeEnvConfig();
2153
+ const values = (env.variables || [])
2154
+ .filter((row) => row.key)
2155
+ .map((row) => ({
2156
+ key: row.key,
2157
+ value: String(row.value ?? ""),
2158
+ type: "default",
2159
+ enabled: true,
2160
+ }));
2161
+ // Ensure header template vars referenced as {{x}} appear even if missing from variables list.
2162
+ const known = new Set(values.map((row) => row.key));
2163
+ for (const row of headerRowsForExport()) {
2164
+ const text = String(row.value || "");
2165
+ const matches = text.matchAll(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g);
2166
+ for (const match of matches) {
2167
+ if (known.has(match[1])) continue;
2168
+ known.add(match[1]);
2169
+ values.push({ key: match[1], value: "", type: "default", enabled: true });
2170
+ }
2171
+ }
2172
+ return {
2173
+ id: typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : String(Date.now()),
2174
+ name: (workspace || title || "DAxTA") + " · " + store.activeEnv,
2175
+ values,
2176
+ _postman_variable_scope: "environment",
2177
+ _postman_exported_at: new Date().toISOString(),
2178
+ _postman_exported_using: "DAxTA",
2179
+ };
2180
+ };
2181
+
2182
+ const STATUS_EXPORT = {
2183
+ 200: "OK",
2184
+ 201: "Created",
2185
+ 204: "No Content",
2186
+ 400: "Bad Request",
2187
+ 401: "Unauthorized",
2188
+ 403: "Forbidden",
2189
+ 404: "Not Found",
2190
+ 409: "Conflict",
2191
+ 422: "Unprocessable Entity",
2192
+ 500: "Internal Server Error",
2193
+ };
2194
+
2195
+ const postmanUrlFromPath = (serverUrl, pathTemplate) => {
2196
+ const base = String(serverUrl || "{{baseUrl}}").replace(/\/$/, "");
2197
+ const path = String(pathTemplate || "/");
2198
+ const segments = path.split("/").filter(Boolean);
2199
+ const pathParams = [...path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]);
2200
+ return {
2201
+ raw: base + (path.startsWith("/") ? path : "/" + path),
2202
+ host: base.startsWith("{{") ? [base] : [base.replace(/^https?:\/\//, "").split("/")[0]],
2203
+ path: segments.map((seg) => (seg.startsWith("{") && seg.endsWith("}") ? ":" + seg.slice(1, -1) : seg)),
2204
+ variable: pathParams.map((key) => ({ key, value: "" })),
2205
+ };
2206
+ };
2207
+
2208
+ /**
2209
+ * Postman Collection v2.1 — example `name` = scenario title (not "Created" / "Bad Request").
2210
+ * OpenAPI→Postman import names every example after response.description; this bypasses that.
2211
+ */
2212
+ const buildPostmanCollection = (openapi) => {
2213
+ const serverUrl = (openapi.servers && openapi.servers[0] && openapi.servers[0].url) || "{{baseUrl}}";
2214
+ const folders = new Map();
2215
+
2216
+ for (const [urlPath, pathItem] of Object.entries(openapi.paths || {})) {
2217
+ if (!pathItem || typeof pathItem !== "object") continue;
2218
+ for (const method of HTTP_EXPORT) {
2219
+ const operation = pathItem[method];
2220
+ if (!operation || typeof operation !== "object") continue;
2221
+ const folderName = (operation.tags && operation.tags[0]) || "API";
2222
+ if (!folders.has(folderName)) folders.set(folderName, []);
2223
+
2224
+ const headerParams = (operation.parameters || []).filter((param) => param && param.in === "header" && param.name);
2225
+ const requestHeaders = headerParams.map((param) => ({
2226
+ key: param.name,
2227
+ value: param.example != null ? String(param.example) : "",
2228
+ type: "text",
2229
+ }));
2230
+
2231
+ const reqExamples = operation.requestBody?.content?.["application/json"]?.examples || {};
2232
+ const firstReq = Object.values(reqExamples)[0];
2233
+ const defaultBody =
2234
+ firstReq && firstReq.value !== undefined
2235
+ ? typeof firstReq.value === "string"
2236
+ ? firstReq.value
2237
+ : JSON.stringify(firstReq.value, null, 2)
2238
+ : undefined;
2239
+
2240
+ const baseRequest = {
2241
+ method: method.toUpperCase(),
2242
+ header: requestHeaders,
2243
+ url: postmanUrlFromPath(serverUrl, urlPath),
2244
+ description: operation.summary || "",
2245
+ };
2246
+ if (defaultBody !== undefined) {
2247
+ baseRequest.body = { mode: "raw", raw: defaultBody, options: { raw: { language: "json" } } };
2248
+ if (!requestHeaders.some((h) => String(h.key).toLowerCase() === "content-type")) {
2249
+ baseRequest.header = [...requestHeaders, { key: "Content-Type", value: "application/json", type: "text" }];
2250
+ }
2251
+ }
2252
+
2253
+ const responses = [];
2254
+ for (const [status, response] of Object.entries(operation.responses || {})) {
2255
+ const examples = response?.content?.["application/json"]?.examples || {};
2256
+ const entries = Object.entries(examples);
2257
+ if (!entries.length) {
2258
+ responses.push({
2259
+ name: response.description || STATUS_EXPORT[status] || status,
2260
+ originalRequest: baseRequest,
2261
+ status: STATUS_EXPORT[status] || response.description || status,
2262
+ code: Number(status) || 0,
2263
+ _postman_previewlanguage: "json",
2264
+ header: [{ key: "Content-Type", value: "application/json" }],
2265
+ body: "",
2266
+ });
2267
+ continue;
2268
+ }
2269
+ for (const [exKey, example] of entries) {
2270
+ const name = (example && (example.summary || example.description)) || exKey;
2271
+ const reqMatch = reqExamples[exKey] || reqExamples[name] || firstReq;
2272
+ const requestForExample = { ...baseRequest, header: [...(baseRequest.header || [])] };
2273
+ if (reqMatch && reqMatch.value !== undefined) {
2274
+ const raw =
2275
+ typeof reqMatch.value === "string" ? reqMatch.value : JSON.stringify(reqMatch.value, null, 2);
2276
+ requestForExample.body = { mode: "raw", raw, options: { raw: { language: "json" } } };
2277
+ }
2278
+ const bodyValue = example && example.value !== undefined ? example.value : "";
2279
+ responses.push({
2280
+ name,
2281
+ originalRequest: requestForExample,
2282
+ status: STATUS_EXPORT[status] || String(status),
2283
+ code: Number(status) || 0,
2284
+ _postman_previewlanguage: "json",
2285
+ header: [{ key: "Content-Type", value: "application/json" }],
2286
+ body: typeof bodyValue === "string" ? bodyValue : JSON.stringify(bodyValue, null, 2),
2287
+ });
2288
+ }
2289
+ }
2290
+
2291
+ folders.get(folderName).push({
2292
+ name: operation.summary || method.toUpperCase() + " " + urlPath,
2293
+ request: baseRequest,
2294
+ response: responses,
2295
+ });
2296
+ }
2297
+ }
2298
+
2299
+ const item = [...folders.entries()]
2300
+ .sort(([a], [b]) => a.localeCompare(b))
2301
+ .map(([name, children]) => ({ name, item: children }));
2302
+
2303
+ return {
2304
+ info: {
2305
+ _postman_id: typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : String(Date.now()),
2306
+ name: (openapi.info && openapi.info.title) || workspace || title || "DAxTA",
2307
+ description: (openapi.info && openapi.info.description) || "Exported from DAxTA with named examples",
2308
+ schema: "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
2309
+ },
2310
+ item,
2311
+ };
2312
+ };
2313
+
2314
+ const closeExportModal = () => {
2315
+ document.body.classList.remove("exporting");
2316
+ };
2317
+
2318
+ const syncExportTryItUi = () => {
2319
+ const meta = document.getElementById("export-tryit-meta");
2320
+ const modeWrap = document.getElementById("export-mode-wrap");
2321
+ const include = document.getElementById("export-include-tryit");
2322
+ if (meta) meta.textContent = store.activeEnv + " · " + store.activeGroup;
2323
+ if (modeWrap) modeWrap.classList.toggle("disabled", !(include && include.checked));
2324
+ };
2325
+
2326
+ const openExportModal = () => {
2327
+ const body = document.getElementById("export-body");
2328
+ const blocks = ops
2329
+ .map((item) => {
2330
+ const examples = listOperationExamples(item.op);
2331
+ if (!examples.length) return "";
2332
+ return `<div class="export-op" data-op="${escapeAttr(item.id)}">
2333
+ <div class="export-op-title">
2334
+ <span class="method ${item.method}">${item.method}</span>
2335
+ <span class="path" title="${escapeAttr(item.path)}">${escapeAttr(item.path)}</span>
2336
+ </div>
2337
+ ${examples
2338
+ .map(
2339
+ (example) => `<div class="export-ex">
2340
+ <input type="checkbox" id="ex-${escapeAttr(item.id)}-${escapeAttr(example.key)}" data-op="${escapeAttr(item.id)}" data-key="${escapeAttr(example.key)}" checked />
2341
+ <label for="ex-${escapeAttr(item.id)}-${escapeAttr(example.key)}">${escapeAttr(example.summary)}</label>
2342
+ </div>`,
2343
+ )
2344
+ .join("")}
2345
+ </div>`;
2346
+ })
2347
+ .filter(Boolean)
2348
+ .join("");
2349
+ body.innerHTML = blocks || `<div class="export-empty">No recorded examples yet — export will include schemas only.</div>`;
2350
+ syncExportTryItUi();
2351
+ document.body.classList.add("exporting");
2352
+ };
2353
+
2354
+ const collectSelectedExamples = () => {
2355
+ const selectedByOpId = new Map();
2356
+ document.querySelectorAll("#export-body input[type=checkbox]").forEach((input) => {
2357
+ const opId = input.dataset.op;
2358
+ const key = input.dataset.key;
2359
+ if (!opId || !key) return;
2360
+ if (!selectedByOpId.has(opId)) selectedByOpId.set(opId, new Set());
2361
+ if (input.checked) selectedByOpId.get(opId).add(key);
2362
+ });
2363
+ return selectedByOpId;
2364
+ };
2365
+
2366
+ const downloadJsonFile = (filename, value) => {
2367
+ const blob = new Blob([JSON.stringify(value, null, 2) + "\n"], { type: "application/json" });
1328
2368
  const url = URL.createObjectURL(blob);
1329
2369
  const link = document.createElement("a");
1330
- const safeName = String(workspace || title || "openapi")
1331
- .toLowerCase()
1332
- .replace(/[^a-z0-9]+/g, "-")
1333
- .replace(/^-|-$/g, "") || "openapi";
1334
2370
  link.href = url;
1335
- link.download = safeName + ".openapi.json";
2371
+ link.download = filename;
1336
2372
  document.body.appendChild(link);
1337
2373
  link.click();
1338
2374
  link.remove();
1339
2375
  URL.revokeObjectURL(url);
1340
2376
  };
1341
2377
 
1342
- document.getElementById("export-openapi").addEventListener("click", downloadOpenApi);
2378
+ const exportSafeName = () =>
2379
+ String(workspace || title || "openapi")
2380
+ .toLowerCase()
2381
+ .replace(/[^a-z0-9]+/g, "-")
2382
+ .replace(/^-|-$/g, "") || "openapi";
2383
+
2384
+ const runExportDownload = () => {
2385
+ const selectedByOpId = collectSelectedExamples();
2386
+ let exported = toExportSpec(spec, selectedByOpId);
2387
+ const includeTryIt = Boolean(document.getElementById("export-include-tryit")?.checked);
2388
+ const wantCollection = Boolean(document.getElementById("export-postman-collection")?.checked);
2389
+ const fillMode =
2390
+ document.querySelector('input[name="export-fill"]:checked')?.value === "variables" ? "variables" : "resolved";
2391
+ const base = exportSafeName();
2392
+
2393
+ if (includeTryIt) {
2394
+ exported = applyTryItFill(exported, fillMode);
2395
+ }
2396
+
2397
+ downloadJsonFile(base + ".openapi.json", exported);
2398
+
2399
+ let delay = 120;
2400
+ if (wantCollection) {
2401
+ setTimeout(() => {
2402
+ downloadJsonFile(base + ".postman_collection.json", buildPostmanCollection(exported));
2403
+ }, delay);
2404
+ delay += 120;
2405
+ }
2406
+
2407
+ if (includeTryIt && fillMode === "variables") {
2408
+ setTimeout(() => {
2409
+ downloadJsonFile(base + ".postman_environment.json", buildPostmanEnvironment());
2410
+ }, delay);
2411
+ }
2412
+ };
2413
+
2414
+ document.getElementById("export-openapi").addEventListener("click", (event) => {
2415
+ event.stopPropagation();
2416
+ openExportModal();
2417
+ });
2418
+ document.getElementById("export-cancel").addEventListener("click", closeExportModal);
2419
+ document.getElementById("export-backdrop").addEventListener("click", (event) => {
2420
+ if (event.target.id === "export-backdrop") closeExportModal();
2421
+ });
2422
+ document.getElementById("export-modal").addEventListener("click", (event) => event.stopPropagation());
2423
+ document.getElementById("export-include-tryit").addEventListener("change", syncExportTryItUi);
2424
+ document.getElementById("export-all").addEventListener("click", () => {
2425
+ document.querySelectorAll("#export-body input[type=checkbox]").forEach((input) => {
2426
+ input.checked = true;
2427
+ });
2428
+ });
2429
+ document.getElementById("export-none").addEventListener("click", () => {
2430
+ document.querySelectorAll("#export-body input[type=checkbox]").forEach((input) => {
2431
+ input.checked = false;
2432
+ });
2433
+ });
2434
+ document.getElementById("export-success").addEventListener("click", () => {
2435
+ document.querySelectorAll("#export-body input[type=checkbox]").forEach((input) => {
2436
+ const label = document.querySelector(`label[for="${CSS.escape(input.id)}"]`);
2437
+ const text = label ? label.textContent || "" : "";
2438
+ input.checked = /^2\d\d\b/.test(text.trim());
2439
+ });
2440
+ });
2441
+ document.getElementById("export-confirm").addEventListener("click", () => {
2442
+ runExportDownload();
2443
+ closeExportModal();
2444
+ });
1343
2445
 
1344
2446
  const HTTP = ["get", "post", "put", "patch", "delete"];
1345
2447
  const STATUS = { 200: "OK", 201: "Created", 204: "No Content", 400: "Bad Request", 401: "Unauthorized", 404: "Not Found", 409: "Conflict", 422: "Unprocessable Entity" };
@@ -1523,6 +2625,13 @@
1523
2625
  const expandedFolders = new Set(
1524
2626
  [...new Set(ops.map((item) => treePathSegments(item)[0]).filter(Boolean))].map((version) => "/" + version),
1525
2627
  );
2628
+ const expandedExampleOps = new Set();
2629
+
2630
+ const scenarioNavLabel = (scenario) => {
2631
+ const status = scenario.status != null ? String(scenario.status) : "";
2632
+ const name = scenario.name || "example";
2633
+ return status ? status + " — " + name : name;
2634
+ };
1526
2635
 
1527
2636
  const kv = (label, value) => {
1528
2637
  if (value === undefined || value === "") return "";
@@ -1574,13 +2683,30 @@
1574
2683
  const renderTreeNode = (node, prefix = "", q = "") => {
1575
2684
  const opsHtml = [...node.ops]
1576
2685
  .sort((left, right) => (METHOD_ORDER[left.method] ?? 99) - (METHOD_ORDER[right.method] ?? 99))
1577
- .map(
1578
- (item) =>
1579
- `<button class="nav-item ${item.id === currentId ? "active" : ""}" data-id="${item.id}" title="${item.path}">
1580
- <span class="method ${item.method}">${item.method}</span>
1581
- <span class="nav-title">${item.title}</span>
1582
- </button>`,
1583
- )
2686
+ .map((item) => {
2687
+ const hasExamples = Array.isArray(item.scenarios) && item.scenarios.length > 0;
2688
+ const examplesOpen = expandedExampleOps.has(item.id);
2689
+ const examplesHtml = hasExamples
2690
+ ? `<div class="nav-examples">${item.scenarios
2691
+ .map(
2692
+ (scenario, index) =>
2693
+ `<button type="button" class="nav-example ${item.id === currentId && index === scenarioIndex ? "on" : ""}" data-id="${escapeAttr(item.id)}" data-scenario="${index}" title="${escapeAttr(scenarioNavLabel(scenario))}">${escapeAttr(scenarioNavLabel(scenario))}</button>`,
2694
+ )
2695
+ .join("")}</div>`
2696
+ : "";
2697
+ return `<div class="nav-op ${item.id === currentId ? "active" : ""} ${examplesOpen ? "examples-open" : ""}" data-op-id="${escapeAttr(item.id)}">
2698
+ <div class="nav-op-row">
2699
+ <button type="button" class="nav-item" data-id="${escapeAttr(item.id)}" title="${escapeAttr(item.path)}">
2700
+ <span class="method ${item.method}">${item.method}</span>
2701
+ <span class="nav-title">${escapeAttr(item.title)}</span>
2702
+ </button>
2703
+ <button type="button" class="nav-expand" data-expand-id="${escapeAttr(item.id)}" title="Examples" aria-label="Toggle examples" aria-expanded="${examplesOpen ? "true" : "false"}" ${hasExamples ? "" : "disabled"}>
2704
+ <span class="chev"></span>
2705
+ </button>
2706
+ </div>
2707
+ ${examplesHtml}
2708
+ </div>`;
2709
+ })
1584
2710
  .join("");
1585
2711
 
1586
2712
  const foldersHtml = Object.entries(node.children)
@@ -1617,6 +2743,29 @@
1617
2743
  nav.querySelectorAll(".nav-item").forEach((button) => {
1618
2744
  button.onclick = () => select(button.dataset.id);
1619
2745
  });
2746
+ nav.querySelectorAll(".nav-expand").forEach((button) => {
2747
+ button.onclick = (event) => {
2748
+ event.stopPropagation();
2749
+ if (button.disabled) return;
2750
+ const opId = button.dataset.expandId;
2751
+ if (expandedExampleOps.has(opId)) expandedExampleOps.delete(opId);
2752
+ else expandedExampleOps.add(opId);
2753
+ const wrap = button.closest(".nav-op");
2754
+ if (wrap) {
2755
+ wrap.classList.toggle("examples-open", expandedExampleOps.has(opId));
2756
+ button.setAttribute("aria-expanded", expandedExampleOps.has(opId) ? "true" : "false");
2757
+ }
2758
+ };
2759
+ });
2760
+ nav.querySelectorAll(".nav-example").forEach((button) => {
2761
+ button.onclick = (event) => {
2762
+ event.stopPropagation();
2763
+ const opId = button.dataset.id;
2764
+ const index = Number(button.dataset.scenario);
2765
+ expandedExampleOps.add(opId);
2766
+ select(opId, Number.isFinite(index) ? index : 0);
2767
+ };
2768
+ });
1620
2769
  nav.querySelectorAll(".tree-folder-toggle").forEach((button) => {
1621
2770
  button.onclick = (event) => {
1622
2771
  event.stopPropagation();
@@ -1724,13 +2873,13 @@
1724
2873
  return fields
1725
2874
  .map((field) => {
1726
2875
  const depth = field.in === "body" ? fieldDepth(field.name) : 0;
1727
- const pad = depth ? ` style="padding-left:${depth * 14}px"` : "";
1728
2876
  const nestClass = depth ? " nested" : "";
2877
+ const depthAttr = depth ? ` data-depth="${Math.min(depth, 4)}"` : "";
1729
2878
  return `<div class="row">
1730
- <div class="name${nestClass}"${pad}>${field.name}</div>
1731
- <div class="type">${field.in}</div>
2879
+ <div class="name${nestClass}"${depthAttr}>${escapeHtml(field.name)}</div>
2880
+ <div class="loc">${escapeHtml(field.in)}</div>
1732
2881
  <div>
1733
- <div class="type">${field.type}</div>
2882
+ <div class="type">${escapeHtml(field.type)}</div>
1734
2883
  ${field.required === true ? `<div class="flag req">Required</div>` : field.required === false ? `<div class="flag">Optional</div>` : ""}
1735
2884
  </div>
1736
2885
  </div>`;
@@ -1849,6 +2998,8 @@
1849
2998
  scenarioIndex = Number(button.dataset.index);
1850
2999
  liveResult = null;
1851
3000
  root.classList.remove("open");
3001
+ expandedExampleOps.add(item.id);
3002
+ renderNav();
1852
3003
  renderMain();
1853
3004
  };
1854
3005
  });
@@ -1902,9 +3053,9 @@
1902
3053
  }
1903
3054
  };
1904
3055
 
1905
- const select = (id) => {
3056
+ const select = (id, nextScenarioIndex) => {
1906
3057
  currentId = id;
1907
- scenarioIndex = 0;
3058
+ scenarioIndex = typeof nextScenarioIndex === "number" ? nextScenarioIndex : 0;
1908
3059
  liveResult = null;
1909
3060
  const selected = ops.find((entry) => entry.id === id);
1910
3061
  if (selected) syncHeaderGroupForOp(selected.op);
@@ -1957,6 +3108,15 @@
1957
3108
 
1958
3109
  const initial = decodeURIComponent(location.hash.replace(/^#/, "")) || ops[0]?.id;
1959
3110
  select(ops.some((item) => item.id === initial) ? initial : ops[0]?.id);
3111
+
3112
+ hydrateStoreFromServer().then((loaded) => {
3113
+ if (!loaded) return;
3114
+ const selected = ops.find((entry) => entry.id === currentId);
3115
+ if (selected) syncHeaderGroupForOp(selected.op);
3116
+ syncEnvTrigger();
3117
+ if (document.getElementById("env-wrap")?.classList.contains("open")) renderEnvPop();
3118
+ renderMain();
3119
+ });
1960
3120
  </script>
1961
3121
  </body>
1962
3122
  </html>