@t0.labs/daxta 1.1.8 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,6 +23,14 @@ DAxTA captures that real traffic while your tests run and turns it into interact
23
23
 
24
24
  **No duplicate API definitions. No manually maintained examples. No documentation-specific decorators.**
25
25
 
26
+ ### Quick Start
27
+
28
+ ```bash
29
+ pnpm dlx @t0.labs/daxta install
30
+ ```
31
+
32
+ > Prefer `pnpm dlx @t0.labs/daxta <command>` (or `npx @t0.labs/daxta <command>`) — no manual `npm i` setup required.
33
+
26
34
  ```ts
27
35
  import { apiDocs } from '@t0.labs/daxta';
28
36
 
@@ -150,7 +158,7 @@ DAxTA records **real HTTP traffic** from NestJS API integration tests.
150
158
 
151
159
  That is the point. Documentation is generated from the same requests your tests already send against the running application — not from controller decorators, and not from unit tests that never hit HTTP.
152
160
 
153
- **Covered** — Nest e2e / integration tests that go through **supertest** or **superagent**:
161
+ **Covered** — Nest e2e / integration tests that go through **supertest**, **superagent**, or Node's built-in **`fetch`**:
154
162
 
155
163
  ```ts
156
164
  request(app.getHttpServer())
@@ -162,16 +170,17 @@ request(app.getHttpServer())
162
170
 
163
171
  If Jest is wired (`setupFilesAfterEnv` + reporter), those hits become `/api-docs` when the suite finishes.
164
172
 
165
- **Not covered** — anything that never passes through that HTTP client:
173
+ **Not covered** — anything that never passes through those HTTP clients:
166
174
 
167
175
 
168
176
  | Test style | Recorded? |
169
177
  | -------------------------------------------------- | --------- |
170
178
  | Nest e2e with `request(app.getHttpServer())` | Yes |
179
+ | Tests using global `fetch` (Node 18+) | Yes |
171
180
  | Service / unit tests (`TestingModule`, no HTTP) | No |
172
- | `axios`, `fetch`, `got` | No |
181
+ | `axios`, `got` | No |
173
182
  | Playwright / Cypress | No |
174
- | GraphQL or WebSocket (unless over superagent HTTP) | No |
183
+ | GraphQL or WebSocket (unless over superagent/fetch)| No |
175
184
 
176
185
 
177
186
  If the test does not hit the API over HTTP the way your clients do, DAxTA has nothing to document. That is intentional: the source of truth is **observed API behavior**, not mocked internals.
@@ -303,31 +312,39 @@ This allows DAxTA to understand required and optional fields without another doc
303
312
 
304
313
 
305
314
 
306
- ## OpenAPI export
315
+ ## OpenAPI & Postman export
307
316
 
308
317
  DAxTA is not limited to `/api-docs`.
309
318
 
310
- You can select the **APIs and examples** you want, combine them with the appropriate **environment and header groups**, and export using the **OpenAPI** spec plus a **Postman Collection**.
319
+ You can export a **Postman Collection v2.1** (with nested folders and named examples), a **Postman Environment**, or a stripped **OpenAPI** spec directly from the CLI or from the `/api-docs` UI:
320
+
321
+ ```bash
322
+ # Export Postman collection + environment from recorded spec
323
+ pnpm dlx @t0.labs/daxta export
324
+
325
+ # Or specify format and output directory
326
+ pnpm dlx @t0.labs/daxta export postman --out ./postman
327
+ pnpm dlx @t0.labs/daxta export openapi --out ./openapi.json
328
+
329
+ # Generate OpenAPI + HTML + Postman in one step
330
+ pnpm dlx @t0.labs/daxta generate --postman
331
+ ```
332
+
333
+ In the `/api-docs` UI, you can also select specific **APIs and examples**, combine them with **environment and header groups**, and export on demand.
311
334
 
312
335
  ```text
313
336
  Tests
314
337
  ↓
315
338
  DAxTA
316
339
  ↓
317
- Select APIs + Examples
340
+ OpenAPI + Named Examples
318
341
  ↓
319
- Environment + Header Groups
320
- ↓
321
- OpenAPI / Postman
322
- ↓
323
- Other tools
342
+ Postman Collection v2.1 + Environment / Other tools
324
343
  ```
325
344
 
326
- This also allows you to create customized API sets without exposing the entire `/api-docs` interface from your service.
327
-
328
345
  Your tests remain the source of truth.
329
346
 
330
- **OpenAPI becomes the portable output.**
347
+ **OpenAPI and Postman collections become the portable output.**
331
348
 
332
349
  ---
333
350
 
@@ -369,21 +386,32 @@ The path defaults to `/docs`. Override with `DAXTA_DOCS_PATH` or `docsPath` in `
369
386
 
370
387
  ## Commands
371
388
 
389
+ Every command can be run directly via `pnpm dlx @t0.labs/daxta <command>` (or `daxta <command>` if installed):
390
+
372
391
  ```bash
373
- daxta install # one-shot project setup, including sidebar layout
374
- daxta uninstall # remove DAxTA wiring from the project
375
- daxta migrate # upgrade integration after a package bump
376
- daxta generate # rebuild OpenAPI + UI from recorded traffic
377
- daxta serve # optional standalone viewer
378
- daxta tree # reconfigure the /api-docs sidebar
379
- daxta titles # align test titles with API docs examples
380
- daxta fields … # export the field map for an operation
381
- daxta call … # execute an API operation from the CLI
392
+ # Setup
393
+ pnpm dlx @t0.labs/daxta install # attach DAxTA to Jest and NestJS
394
+ pnpm dlx @t0.labs/daxta migrate # upgrade project wiring after a package bump
395
+ pnpm dlx @t0.labs/daxta uninstall # remove DAxTA wiring from the project
396
+
397
+ # Generate & Export
398
+ pnpm dlx @t0.labs/daxta generate # build OpenAPI + HTML (--postman to also export Postman)
399
+ pnpm dlx @t0.labs/daxta export # export Postman collection + env, or OpenAPI JSON
400
+ pnpm dlx @t0.labs/daxta serve # optional standalone viewer
401
+
402
+ # Tests & Naming
403
+ pnpm dlx @t0.labs/daxta test # run project test script (--check-titles to lint names)
404
+ pnpm dlx @t0.labs/daxta titles # align describe/it() names with API docs & examples
405
+ pnpm dlx @t0.labs/daxta tree # configure sidebar folder layout & example label style
406
+
407
+ # Try-it
408
+ pnpm dlx @t0.labs/daxta fields … # export the field map for an operation
409
+ pnpm dlx @t0.labs/daxta call … # execute an API operation from the CLI
382
410
  ```
383
411
 
384
- `daxta build` is an alias of `daxta generate`.
412
+ Run `pnpm dlx @t0.labs/daxta <command> --help` for flags and examples.
385
413
 
386
- For most NestJS applications, `apiDocs(app)` is preferred over `daxta serve`.
414
+ `build` is an alias of `generate`. For most NestJS applications, `apiDocs(app)` is preferred over `serve`.
387
415
 
388
416
  ---
389
417
 
@@ -829,6 +829,15 @@
829
829
  }
830
830
  .nav-example:hover { background: color-mix(in srgb, var(--obsidian) 4%, transparent); color: var(--charcoal); }
831
831
  .nav-example.on { color: var(--obsidian); background: color-mix(in srgb, var(--obsidian) 8%, transparent); font-weight: 500; }
832
+ .nav-ver {
833
+ flex: none;
834
+ padding: 1px 4px;
835
+ border-radius: 2px;
836
+ border: 1px solid color-mix(in srgb, var(--obsidian) 14%, transparent);
837
+ color: var(--slate);
838
+ font: 600 9px/1.3 var(--mono);
839
+ letter-spacing: 0.02em;
840
+ }
832
841
  .nav-ex-total {
833
842
  flex: none;
834
843
  min-width: 16px;
@@ -2974,12 +2983,17 @@
2974
2983
  };
2975
2984
 
2976
2985
  const collectionRequestHeaders = (operation, includeTryIt) => {
2986
+ const headerVars = (spec["x-viewer"] && spec["x-viewer"].headerVariables) || {};
2987
+ const headerVarsLower = Object.fromEntries(
2988
+ Object.entries(headerVars).map(([k, v]) => [String(k).toLowerCase(), String(v)]),
2989
+ );
2977
2990
  const byLower = new Map();
2978
2991
  const add = (key, value) => {
2979
2992
  if (!key) return;
2980
2993
  const lower = String(key).toLowerCase();
2981
2994
  if (lower === "host" || lower === "content-length") return;
2982
- byLower.set(lower, { key, value: value != null ? String(value) : "", type: "text" });
2995
+ const mapped = lower !== "content-type" ? headerVarsLower[lower] : undefined;
2996
+ byLower.set(lower, { key, value: mapped ?? (value != null ? String(value) : ""), type: "text" });
2983
2997
  };
2984
2998
  for (const param of operation.parameters || []) {
2985
2999
  if (param && param.in === "header" && param.name) add(param.name, param.example != null ? param.example : "");
@@ -3627,10 +3641,19 @@
3627
3641
  let exampleQuery = "";
3628
3642
  let exampleOpen = false;
3629
3643
  let jsonMode = { req: "pretty", res: "pretty" };
3630
- const treePathSegments = (item) => item.treeSegments || item.path.split("/").filter(Boolean);
3631
- const apiVersions = [...new Set(ops.map((item) => treePathSegments(item)[0]).filter(Boolean))];
3632
- let activeVersion = apiVersions[0] || "";
3633
- const expandedFolders = new Set(apiVersions.map((version) => "/" + version));
3644
+ const opVersion = (item) => {
3645
+ const m = String(item.path || "").match(/^\/(v\d+)\b/i);
3646
+ return m ? m[1].toLowerCase() : "";
3647
+ };
3648
+ const treePathSegments = (item) => {
3649
+ const segs = item.treeSegments || item.path.split("/").filter(Boolean);
3650
+ return /^v\d+$/i.test(segs[0] || "") && segs.length > 1 ? segs.slice(1) : segs;
3651
+ };
3652
+ const apiVersions = [...new Set(ops.map(opVersion).filter(Boolean))].sort((a, b) =>
3653
+ a.localeCompare(b, undefined, { numeric: true }),
3654
+ );
3655
+ let activeVersion = "";
3656
+ const expandedFolders = new Set();
3634
3657
  const expandedExampleOps = new Set();
3635
3658
  /** `${opId}::${group}` entries the user opened; groups start collapsed. */
3636
3659
  const expandedExampleGroups = new Set();
@@ -3727,12 +3750,14 @@
3727
3750
  const hasExamples = Array.isArray(item.scenarios) && item.scenarios.length > 0;
3728
3751
  const examplesOpen = expandedExampleOps.has(item.id);
3729
3752
  const exampleCount = hasExamples ? item.scenarios.length : 0;
3753
+ const ver = opVersion(item);
3730
3754
  return `<div class="nav-op ${item.id === currentId ? "active" : ""} ${examplesOpen ? "examples-open" : ""}" data-op-id="${escapeAttr(item.id)}">
3731
3755
  <div class="nav-op-row">
3732
3756
  <button type="button" class="nav-item" data-id="${escapeAttr(item.id)}" title="${escapeAttr(item.path)}">
3733
3757
  <span class="method ${item.method}">${item.method}</span>
3734
3758
  <span class="nav-title">${escapeAttr(item.title)}</span>
3735
3759
  </button>
3760
+ ${ver ? `<span class="nav-ver" title="API ${escapeAttr(ver)}">${escapeHtml(ver)}</span>` : ""}
3736
3761
  ${hasExamples ? `<span class="nav-ex-total" title="${exampleCount} examples">${exampleCount}</span>` : ""}
3737
3762
  <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"}>
3738
3763
  <span class="chev"></span>
@@ -3765,7 +3790,7 @@
3765
3790
 
3766
3791
  const visibleOps = () => {
3767
3792
  if (!activeVersion) return ops;
3768
- return ops.filter((item) => treePathSegments(item)[0] === activeVersion);
3793
+ return ops.filter((item) => opVersion(item) === activeVersion);
3769
3794
  };
3770
3795
 
3771
3796
  const renderNav = () => {
@@ -4245,8 +4270,8 @@
4245
4270
  const selected = ops.find((entry) => entry.id === id);
4246
4271
  if (selected) {
4247
4272
  syncHeaderGroupForOp(selected.op);
4248
- const version = treePathSegments(selected)[0];
4249
- if (version) activeVersion = version;
4273
+ const version = opVersion(selected);
4274
+ if (activeVersion && version) activeVersion = version;
4250
4275
  expandedExampleOps.add(id);
4251
4276
  const scenario = (selected.scenarios || [])[scenarioIndex];
4252
4277
  if (scenario) expandedExampleGroups.add(exampleGroupKey(id, scenario.group || "Other"));
@@ -4338,7 +4363,7 @@
4338
4363
  }
4339
4364
  });
4340
4365
 
4341
- const prefixLabel = (name) => (String(name).startsWith("/") ? name : "/" + name);
4366
+ const prefixLabel = (name) => (name ? (String(name).startsWith("/") ? name : "/" + name) : "All");
4342
4367
  const renderPrefixBar = () => {
4343
4368
  const bar = document.getElementById("prefix-bar");
4344
4369
  if (!bar) return;
@@ -4348,7 +4373,8 @@
4348
4373
  return;
4349
4374
  }
4350
4375
  bar.hidden = false;
4351
- bar.innerHTML = apiVersions
4376
+ const choices = ["", ...apiVersions];
4377
+ bar.innerHTML = choices
4352
4378
  .map(
4353
4379
  (name) =>
4354
4380
  `<button type="button" class="prefix-chip ${name === activeVersion ? "on" : ""}" data-prefix="${escapeAttr(name)}" aria-pressed="${name === activeVersion ? "true" : "false"}">${escapeHtml(prefixLabel(name))}</button>`,
@@ -4356,7 +4382,7 @@
4356
4382
  .join("");
4357
4383
  bar.querySelectorAll(".prefix-chip").forEach((button) => {
4358
4384
  button.onclick = () => {
4359
- activeVersion = button.dataset.prefix;
4385
+ activeVersion = button.dataset.prefix || "";
4360
4386
  const first = visibleOps()[0];
4361
4387
  if (first) select(first.id);
4362
4388
  else {
@@ -23,6 +23,8 @@ export declare function buildDaxtaSpec(options?: {
23
23
  silent?: boolean;
24
24
  requireHits?: boolean;
25
25
  html?: boolean;
26
+ clearWorkers?: boolean;
27
+ uiOnly?: boolean;
26
28
  }): BuildResult;
27
29
  /** Generate API documentation (OpenAPI spec + HTML viewer) from recorded test execution. */
28
30
  export declare const generateApiDocs: typeof buildDaxtaSpec;
@@ -67,7 +67,8 @@ function canonicalizeHits(hits) {
67
67
  function readPackageMeta() {
68
68
  try {
69
69
  const pkg = JSON.parse((0, fs_1.readFileSync)(path.join(process.cwd(), 'package.json'), 'utf8'));
70
- const title = pkg.name?.replace(/-/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase()) ?? 'API';
70
+ const cleanName = pkg.name?.replace(/^@[^/]+\//, '');
71
+ const title = cleanName?.replace(/[-_]/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase()) ?? 'API';
71
72
  return {
72
73
  title,
73
74
  version: pkg.version ?? '0.0.0',
@@ -82,11 +83,13 @@ function specInfo() {
82
83
  const pkg = readPackageMeta();
83
84
  const custom = (0, config_1.getConfig)().specInfo?.();
84
85
  const workspace = (0, config_1.getConfig)().workspace;
86
+ const envTitle = process.env.DAXTA_SPEC_TITLE?.trim();
87
+ const envVersion = process.env.DAXTA_SPEC_VERSION?.trim();
85
88
  return {
86
- title: custom?.title ?? pkg.title,
87
- version: custom?.version ?? pkg.version,
89
+ title: envTitle || custom?.title || pkg.title,
90
+ version: envVersion || custom?.version || pkg.version,
88
91
  description: custom?.description ?? pkg.description,
89
- workspace,
92
+ workspace: envTitle || workspace,
90
93
  };
91
94
  }
92
95
  function schemeIdFromHeader(headerName) {
@@ -146,8 +149,23 @@ function mergeSchema(left, right) {
146
149
  }
147
150
  return { ...left, description: left.description ?? right.description };
148
151
  }
152
+ const TURKISH_ASCII_MAP = {
153
+ ç: 'c',
154
+ Ç: 'c',
155
+ ğ: 'g',
156
+ Ğ: 'g',
157
+ ı: 'i',
158
+ İ: 'i',
159
+ ö: 'o',
160
+ Ö: 'o',
161
+ ş: 's',
162
+ Ş: 's',
163
+ ü: 'u',
164
+ Ü: 'u',
165
+ };
149
166
  function slug(value, index) {
150
- const base = value
167
+ const normalized = value.replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => TURKISH_ASCII_MAP[ch] ?? ch);
168
+ const base = normalized
151
169
  .toLowerCase()
152
170
  .replace(/[^a-z0-9]+/g, '-')
153
171
  .replace(/^-|-$/g, '')
@@ -455,7 +473,7 @@ function securityForHits(opHits) {
455
473
  const headers = new Set();
456
474
  for (const hit of opHits) {
457
475
  for (const name of Object.keys(hit.headers ?? {})) {
458
- if (name.startsWith('x-'))
476
+ if (name === 'authorization' || name.startsWith('x-'))
459
477
  headers.add(name);
460
478
  }
461
479
  }
@@ -463,8 +481,10 @@ function securityForHits(opHits) {
463
481
  return undefined;
464
482
  // One requirement object = AND (all headers used together on this operation).
465
483
  const requirement = {};
466
- for (const header of headers)
467
- requirement[schemeIdFromHeader(header)] = [];
484
+ for (const header of headers) {
485
+ const id = header === 'authorization' ? 'bearerAuth' : schemeIdFromHeader(header);
486
+ requirement[id] = [];
487
+ }
468
488
  return [requirement];
469
489
  }
470
490
  function scenarioDisplayName(hit) {
@@ -659,6 +679,10 @@ function buildSpec(hits) {
659
679
  const security = securityForHits(opHits);
660
680
  for (const item of security ?? []) {
661
681
  for (const schemeId of Object.keys(item)) {
682
+ if (schemeId === 'bearerAuth') {
683
+ securitySchemes[schemeId] = { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' };
684
+ continue;
685
+ }
662
686
  const headerName = [...new Set(opHits.flatMap((hit) => Object.keys(hit.headers ?? {})))].find((header) => schemeIdFromHeader(header) === schemeId);
663
687
  if (headerName)
664
688
  securitySchemes[schemeId] = { type: 'apiKey', in: 'header', name: headerName };
@@ -677,10 +701,14 @@ function buildSpec(hits) {
677
701
  const parameters = buildParameters(pathTemplate, opHits);
678
702
  if (parameters.length)
679
703
  operation.parameters = parameters;
704
+ const seenLabels = new Map();
680
705
  for (let index = 0; index < opHits.length; index += 1) {
681
706
  const hit = opHits[index];
682
- const label = (0, catalog_1.exampleLabel)(hit);
683
- const exampleKey = exampleKeyForHit(hit, index);
707
+ const baseLabel = (0, catalog_1.exampleLabel)(hit);
708
+ const count = (seenLabels.get(baseLabel) ?? 0) + 1;
709
+ seenLabels.set(baseLabel, count);
710
+ const label = count > 1 ? `${baseLabel} (${count})` : baseLabel;
711
+ const exampleKey = exampleKeyForHit({ ...hit }, index);
684
712
  if (hit.reqBody !== undefined) {
685
713
  operation.requestBody ??= { required: method === 'post' || method === 'put', content: { 'application/json': { schema: inferSchema(hit.reqBody), examples: {} } } };
686
714
  const media = operation.requestBody.content['application/json'];
@@ -904,9 +932,28 @@ function applyViewerMeta(spec) {
904
932
  };
905
933
  }
906
934
  function buildDaxtaSpec(options = {}) {
935
+ const existingSpec = readJson((0, paths_1.getSpecJsonPath)());
936
+ if (options.uiOnly) {
937
+ if (!existingSpec) {
938
+ throw new Error('No openapi.json found. Run tests or `daxta generate` first.');
939
+ }
940
+ const refreshed = applyViewerMeta(existingSpec);
941
+ writeJson((0, paths_1.getSpecJsonPath)(), refreshed);
942
+ (0, fs_1.writeFileSync)((0, paths_1.getHtmlPath)(), toStandaloneHtml(refreshed));
943
+ if (!options.silent)
944
+ console.log(`Wrote ${(0, paths_1.getHtmlPath)()} from existing spec`);
945
+ return {
946
+ skipped: false,
947
+ reason: 'viewer only',
948
+ hits: 0,
949
+ operations: countOperations(refreshed),
950
+ updated: 0,
951
+ unchanged: countOperations(refreshed),
952
+ changed: true,
953
+ };
954
+ }
907
955
  const hits = loadHits();
908
956
  const existingHits = readJson((0, paths_1.getHitsJsonPath)());
909
- const existingSpec = readJson((0, paths_1.getSpecJsonPath)());
910
957
  const writeHtml = options.html !== false;
911
958
  const seededStore = (0, viewer_store_1.ensureViewerStoreSeeded)();
912
959
  if (seededStore && !options.silent) {
@@ -946,7 +993,8 @@ function buildDaxtaSpec(options = {}) {
946
993
  else {
947
994
  writeJson((0, paths_1.getHitsJsonPath)(), hits);
948
995
  }
949
- (0, recorder_1.clearWorkerHits)();
996
+ if (options.clearWorkers !== false)
997
+ (0, recorder_1.clearWorkerHits)();
950
998
  const operations = countOperations(spec);
951
999
  const result = {
952
1000
  skipped: false,
@@ -3,10 +3,12 @@ export declare function rebuildFromDisk(options?: {
3
3
  silent?: boolean;
4
4
  force?: boolean;
5
5
  html?: boolean;
6
+ clearWorkers?: boolean;
6
7
  }): BuildResult | null;
7
8
  export declare function flushAndRebuild(options?: {
8
9
  silent?: boolean;
9
10
  force?: boolean;
11
+ html?: boolean;
10
12
  }): BuildResult | null;
11
13
  export declare function touchPartialMarker(result: BuildResult): void;
12
14
  export declare function clearPartialMarker(): void;
@@ -91,7 +91,11 @@ function withLock(options, run) {
91
91
  }
92
92
  function rebuildFromDisk(options = {}) {
93
93
  return withLock({ force: options.force }, () => {
94
- const result = (0, build_spec_1.buildDaxtaSpec)({ silent: options.silent ?? true, html: options.html });
94
+ const result = (0, build_spec_1.buildDaxtaSpec)({
95
+ silent: options.silent ?? true,
96
+ html: options.html,
97
+ clearWorkers: options.clearWorkers ?? false,
98
+ });
95
99
  if (!options.silent && result.changed) {
96
100
  console.log(`DAxTA (partial) ${result.hits} hits, ${result.operations} ops — ${result.updated} updated, ${result.unchanged} unchanged`);
97
101
  }
@@ -102,7 +106,7 @@ function rebuildFromDisk(options = {}) {
102
106
  }
103
107
  function flushAndRebuild(options = {}) {
104
108
  (0, recorder_1.flush)();
105
- return rebuildFromDisk(options);
109
+ return rebuildFromDisk({ ...options, clearWorkers: false });
106
110
  }
107
111
  function touchPartialMarker(result) {
108
112
  const marker = path.join((0, config_1.getConfig)().outDir, 'partial.json');
@@ -17,7 +17,7 @@ export declare function declaredMethods(test?: string): string[] | null;
17
17
  export declare function pathSegments(pathTemplate: string): string[];
18
18
  /**
19
19
  * Sidebar / export-tag folder segments for a path.
20
- * Honors treeLayout, treeSkipParams, and per-path overrides.
20
+ * Honors treeLayout, treeSkipParams, treeResourceAliases, treeSubResourceMode, and per-path overrides.
21
21
  */
22
22
  export declare function treePathSegments(pathTemplate: string): string[];
23
23
  export declare function viewerTreeConfig(): {
@@ -30,6 +30,7 @@ export declare function viewerTreeConfig(): {
30
30
  treePathOverrides: Record<string, string[]>;
31
31
  exampleLabelStyle: "status-case" | "status-title-case" | "full";
32
32
  envPresets: Record<string, import("../config").EnvPreset> | undefined;
33
+ headerVariables: Record<string, string>;
33
34
  };
34
35
  export declare function operationTag(pathTemplate: string, method: string): string;
35
36
  export declare function defaultTitle(method: string, pathTemplate: string): string;
@@ -77,9 +77,41 @@ function applyFold(parts, skipParams) {
77
77
  return parts;
78
78
  return parts.slice(0, paramIdx);
79
79
  }
80
+ function applyResourceAliases(parts, aliases) {
81
+ if (!aliases)
82
+ return parts;
83
+ const entries = Object.entries(aliases).filter(([k, v]) => k && v);
84
+ if (!entries.length)
85
+ return parts;
86
+ let current = [...parts];
87
+ for (const [pattern, target] of entries) {
88
+ const seq = pattern.split('/').filter(Boolean);
89
+ if (!seq.length)
90
+ continue;
91
+ for (let i = 0; i <= current.length - seq.length; i += 1) {
92
+ const matches = seq.every((seg, offset) => current[i + offset].toLowerCase() === seg.toLowerCase());
93
+ if (matches) {
94
+ current = [...current.slice(0, i), target, ...current.slice(i + seq.length)];
95
+ break;
96
+ }
97
+ }
98
+ }
99
+ return current;
100
+ }
101
+ function applySubResourceMode(parts, mode) {
102
+ if (!mode || mode === 'nested')
103
+ return parts;
104
+ const startIdx = /^v\d+$/i.test(parts[0] || '') ? 2 : 1;
105
+ if (parts.length <= startIdx + 1)
106
+ return parts;
107
+ if (mode === 'root')
108
+ return parts.slice(0, startIdx + 1);
109
+ // mode === 'merge': join resource + sub-resource segments into one folder name
110
+ return [...parts.slice(0, startIdx), parts.slice(startIdx).join('-')];
111
+ }
80
112
  /**
81
113
  * Sidebar / export-tag folder segments for a path.
82
- * Honors treeLayout, treeSkipParams, and per-path overrides.
114
+ * Honors treeLayout, treeSkipParams, treeResourceAliases, treeSubResourceMode, and per-path overrides.
83
115
  */
84
116
  function treePathSegments(pathTemplate) {
85
117
  const config = (0, config_1.getConfig)();
@@ -90,8 +122,10 @@ function treePathSegments(pathTemplate) {
90
122
  if (exact?.length)
91
123
  return exact;
92
124
  const layout = (0, config_1.normalizeTreeLayout)(config.treeLayout);
93
- const parts = applyLayout(pathTemplate.split('/').filter(Boolean), layout);
94
- return applyFold(parts, config.treeSkipParams !== false);
125
+ const folded = applyFold(pathTemplate.split('/').filter(Boolean), config.treeSkipParams !== false);
126
+ const aliased = applyResourceAliases(folded, config.treeResourceAliases);
127
+ const shaped = applySubResourceMode(aliased, config.treeSubResourceMode);
128
+ return applyLayout(shaped, layout);
95
129
  }
96
130
  function viewerTreeConfig() {
97
131
  const config = (0, config_1.getConfig)();
@@ -105,6 +139,7 @@ function viewerTreeConfig() {
105
139
  treePathOverrides: config.treePathOverrides,
106
140
  exampleLabelStyle: config.exampleLabelStyle ?? 'status-title-case',
107
141
  envPresets: config.envPresets,
142
+ headerVariables: config.headerVariables ?? {},
108
143
  };
109
144
  }
110
145
  function titleCase(value) {
@@ -203,10 +203,10 @@ function docsScenarioClause(raw) {
203
203
  const field = s.match(/^([A-Za-z0-9_.]+)\s+-\s+(should not be\s+.+)$/i);
204
204
  if (field)
205
205
  return `${field[1]} ${field[2]}`.trim();
206
- const whenMatch = s.match(/^(.*?)\bwhen\s+(.+)$/i);
207
- if (whenMatch) {
208
- let before = whenMatch[1].trim().replace(/^should\s+/i, '');
209
- const after = whenMatch[2].trim();
206
+ const condMatch = s.match(/^(.*?)\b(when|if)\s+(.+)$/i);
207
+ if (condMatch) {
208
+ let before = condMatch[1].trim().replace(/^should\s+/i, '');
209
+ const after = condMatch[3].trim();
210
210
  if (!after)
211
211
  return before || 'example';
212
212
  const hadOutcome = OUTCOME_PREFIX.test(before);
@@ -218,7 +218,18 @@ function docsScenarioClause(raw) {
218
218
  if (!before || (hadOutcome && isResourceOnlyBefore(before)))
219
219
  return after;
220
220
  before = before.replace(LEADING_ACTION, '').trim();
221
- return before ? `${before} when ${after}` : after;
221
+ const joiner = condMatch[2].toLowerCase();
222
+ return before ? `${before} ${joiner} ${after}` : after;
223
+ }
224
+ const withMatch = s.match(/^(.*?)\bwith\s+(.+)$/i);
225
+ if (withMatch) {
226
+ let before = withMatch[1].trim().replace(/^should\s+/i, '');
227
+ const after = withMatch[2].trim();
228
+ if (after && OUTCOME_PREFIX.test(before)) {
229
+ before = before.replace(OUTCOME_PREFIX, '').replace(/^resource\s+/i, '').replace(/^error\s+/i, '').trim();
230
+ if (!before || isResourceOnlyBefore(before))
231
+ return after;
232
+ }
222
233
  }
223
234
  s = s.replace(/^should\s+/i, '').replace(OUTCOME_PREFIX, '').replace(/^resource\s+/i, '').trim();
224
235
  return s || 'example';
@@ -18,6 +18,8 @@ const PATH_ONLY_BRACKET_RE = new RegExp(`^(?<path>\\/\\S+)\\s+\\[(?<method>${MET
18
18
  const TITLE_BRACKET_RE = new RegExp(`^(?<title>.+?)\\s+(?<path>\\/\\S+)\\s+\\[(?<method>${METHODS})\\]${QUALIFIER}\\s*$`, 'i');
19
19
  /** `Create Mock Tbs — POST /v1/admin/mock-tbs` */
20
20
  const TITLE_DASH_RE = new RegExp(`^(?<title>.+?)\\s+[—–-]\\s+(?<method>${METHODS})\\s+(?<path>\\/\\S+)${QUALIFIER}\\s*$`, 'i');
21
+ /** `POST /v1/admin/mock-tbs — Create Mock Tbs` */
22
+ const METHOD_PATH_TITLE_RE = new RegExp(`^(?<method>${METHODS})\\s+(?<path>\\/\\S+)\\s+[—–-]\\s+(?<title>.+?)${QUALIFIER}\\s*$`, 'i');
21
23
  const PATH_ONLY_DASH_RE = new RegExp(`^(?<method>${METHODS})\\s+(?<path>\\/\\S+)${QUALIFIER}\\s*$`, 'i');
22
24
  const ROLE_WORDS = new Set([
23
25
  'admin',
@@ -138,6 +140,7 @@ function parseOperationLabel(raw) {
138
140
  };
139
141
  };
140
142
  return (fromGroups(cut.match(TITLE_DASH_RE)) ||
143
+ fromGroups(cut.match(METHOD_PATH_TITLE_RE)) ||
141
144
  fromGroups(cut.match(PATH_ONLY_DASH_RE)) ||
142
145
  fromGroups(cut.match(PATH_ONLY_BRACKET_RE)) ||
143
146
  fromGroups(cut.match(TITLE_BRACKET_RE)));
@@ -110,31 +110,33 @@ async function resolveTestScript(options) {
110
110
  const def = shown[0];
111
111
  if (options.yes || !process.stdin.isTTY)
112
112
  return def.name;
113
- console.log(` ${ui_1.c.gold('?')} ${ui_1.c.bold('Test script')} ${ui_1.c.dim('— reporter + globalSetup')}`);
114
- shown.forEach((choice, i) => {
115
- const n = String(i + 1);
116
- const rec = i === 0 ? ui_1.c.dim(' recommended') : '';
117
- const cmd = isDaxtaWrappedScript(choice.command)
118
- ? '(already wired → daxta test)'
119
- : choice.command.length > 52
120
- ? `${choice.command.slice(0, 52)}…`
121
- : choice.command;
122
- console.log(` ${ui_1.c.ice(n)} ${ui_1.c.bold(choice.name)}${rec}`);
123
- console.log(` ${ui_1.c.dim(cmd)}`);
113
+ const picked = await (0, ui_1.selectMenu)({
114
+ title: 'Test script',
115
+ subtitle: 'reporter + globalSetup',
116
+ options: [
117
+ ...shown.map((choice, i) => ({
118
+ value: choice.name,
119
+ label: choice.name,
120
+ badge: i === 0 ? 'recommended' : undefined,
121
+ hint: isDaxtaWrappedScript(choice.command)
122
+ ? '(already wired → daxta test)'
123
+ : choice.command.length > 64
124
+ ? `${choice.command.slice(0, 64)}…`
125
+ : choice.command,
126
+ })),
127
+ { value: '__custom__', label: 'Custom script name', hint: 'Type a script name from package.json' },
128
+ { value: '__skip__', label: 'Skip', hint: 'Configure testScript later' },
129
+ ],
124
130
  });
125
- console.log(` ${ui_1.c.dim('n')} skip`);
126
- const answer = await (0, ui_1.readlineAsk)(` ${ui_1.c.dim(`Enter = 1 (${def.name})`)} ${ui_1.c.dim('·')} ${ui_1.c.dim('or type a script name')}\n ${ui_1.c.ice('›')} `);
127
- if (!answer)
128
- return def.name;
129
- if (/^n(o)?$/i.test(answer))
131
+ if (picked === '__skip__')
130
132
  return null;
131
- if (/^\d+$/.test(answer)) {
132
- const picked = shown[Number(answer) - 1];
133
- if (!picked)
134
- throw new Error(`No script #${answer}`);
135
- return picked.name;
133
+ if (picked === '__custom__') {
134
+ const typed = await (0, ui_1.readlineAsk)((0, ui_1.askLine)('Test script name', 'or n to skip'));
135
+ if (!typed || /^n(o)?$/i.test(typed))
136
+ return null;
137
+ return typed;
136
138
  }
137
- return answer;
139
+ return picked;
138
140
  }
139
141
  function upsertConfigFields(cwd, fields, dryRun = false) {
140
142
  const configPath = path.join(cwd, 'daxta.config.ts');