@t0.labs/daxta 1.1.2 → 1.1.4

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.
@@ -207,16 +207,98 @@ function selectHitsForDocs(hits) {
207
207
  }
208
208
  return selected;
209
209
  }
210
+ /** `/v1/users/:id` and `/v1/users/{userId}` describe the same route. */
211
+ function normalizedPathSegments(pathTemplate) {
212
+ return String(pathTemplate)
213
+ .split('?')[0]
214
+ .split('/')
215
+ .filter(Boolean)
216
+ .map((segment) => (segment.startsWith('{') || segment.startsWith(':') ? '*' : segment.toLowerCase()));
217
+ }
218
+ /**
219
+ * The declared path may omit a global prefix (`/api`) that the recorded URL carries,
220
+ * so a suffix match counts as the same route.
221
+ */
222
+ function sameRoute(declaredPath, hitPath) {
223
+ const declared = normalizedPathSegments(declaredPath);
224
+ const actual = normalizedPathSegments(hitPath);
225
+ if (!declared.length || !actual.length)
226
+ return true;
227
+ const [shorter, longer] = declared.length <= actual.length ? [declared, actual] : [actual, declared];
228
+ const offset = longer.length - shorter.length;
229
+ // A literal in the title can face a `{param}` in the recorded path (and vice versa)
230
+ // because templating happens after recording.
231
+ return shorter.every((segment, index) => {
232
+ const other = longer[offset + index];
233
+ return segment === other || segment === '*' || other === '*';
234
+ });
235
+ }
236
+ /**
237
+ * A test documents the endpoint named in its title. Arrange/teardown calls the test
238
+ * makes to *other* endpoints share the same Jest name, so they are filtered out here —
239
+ * otherwise those setup routes show up as their own operations carrying this test's case label.
240
+ */
210
241
  function isPrimaryHit(hit) {
211
242
  if (!hit.test)
212
243
  return false;
213
244
  if ((0, config_1.getConfig)().includeHit?.(hit.method, hit.path, hit.test) === false)
214
245
  return false;
246
+ const label = (0, catalog_1.parseOperationLabel)(hit.test);
247
+ if (label?.path && !sameRoute(label.path, hit.path))
248
+ return false;
215
249
  const methods = (0, catalog_1.declaredMethods)(hit.test);
216
250
  if (!methods)
217
251
  return true;
218
252
  return methods.includes(hit.method);
219
253
  }
254
+ const CASE_TAIL_RE = /\s+((?:FALSE\s+)?POSITIVE CASES|SEMANTIC ERROR CASES(?:\s*-\s*AUTH)?|INVALID CASES|OMITTED(?: FIELD)? CASES)\b[\s\S]*$/i;
255
+ /** All case sections of one describe collapse to the same suite, e.g. "Onboard Tr Merchant API". */
256
+ function suiteKey(test) {
257
+ return test.replace(CASE_TAIL_RE, '').trim() || test;
258
+ }
259
+ function routeKey(hit) {
260
+ return `${hit.method} ${hit.path}`;
261
+ }
262
+ /**
263
+ * When the test title does not name a path, infer the endpoint under test: the Act call
264
+ * is the last request an it() makes, so each case votes with its final route and the
265
+ * suite's winner wins. Arrange helpers (`insertMerchantWithKyc`, checkout flows, …) only
266
+ * ever appear mid-test, so they lose and stay out of the docs.
267
+ */
268
+ function subjectRouteBySuite(hits) {
269
+ const finalRouteByTest = new Map();
270
+ for (const hit of hits) {
271
+ if (!hit.test)
272
+ continue;
273
+ if ((0, catalog_1.parseOperationLabel)(hit.test)?.path)
274
+ continue;
275
+ finalRouteByTest.set(hit.test, routeKey(hit));
276
+ }
277
+ const votes = new Map();
278
+ for (const [test, route] of finalRouteByTest) {
279
+ const suite = votes.get(suiteKey(test)) ?? new Map();
280
+ suite.set(route, (suite.get(route) ?? 0) + 1);
281
+ votes.set(suiteKey(test), suite);
282
+ }
283
+ const winners = new Map();
284
+ for (const [suite, routes] of votes) {
285
+ const best = [...routes.entries()].sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0]))[0];
286
+ if (best)
287
+ winners.set(suite, best[0]);
288
+ }
289
+ return winners;
290
+ }
291
+ /** `isPrimaryHit` plus the inferred-subject pass for suites whose titles carry no path. */
292
+ function primaryHits(hits) {
293
+ const allowed = hits.filter(isPrimaryHit);
294
+ const winners = subjectRouteBySuite(allowed);
295
+ if (!winners.size)
296
+ return allowed;
297
+ return allowed.filter((hit) => {
298
+ const winner = hit.test ? winners.get(suiteKey(hit.test)) : undefined;
299
+ return !winner || routeKey(hit) === winner;
300
+ });
301
+ }
220
302
  function pathParamsFromHit(hit) {
221
303
  if (hit.pathParams && Object.keys(hit.pathParams).length)
222
304
  return hit.pathParams;
@@ -385,7 +467,7 @@ function securityForHits(opHits) {
385
467
  return [requirement];
386
468
  }
387
469
  function scenarioDisplayName(hit) {
388
- return (0, catalog_1.docsScenarioClause)((0, catalog_1.caseName)(hit.test));
470
+ return (0, catalog_1.exampleLabel)(hit);
389
471
  }
390
472
  function toScenario(hit) {
391
473
  return {
@@ -434,18 +516,36 @@ function dedupeScenarios(scenarios) {
434
516
  return true;
435
517
  });
436
518
  }
437
- /** `hits-w{workerId}-p{pid}.json` leftover from a previous Jest run must not stack. */
519
+ /**
520
+ * Hit files belonging to the run in progress. Files tagged with a different run id
521
+ * (or untagged leftovers from an older run) never stack onto the current one.
522
+ */
438
523
  function currentRunWorkerFiles(outDir) {
439
- const names = (0, fs_1.readdirSync)(outDir).filter((fileName) => fileName.startsWith('hits-w') && fileName.endsWith('.json'));
440
- if (!names.length)
524
+ const runId = (0, recorder_1.readRunId)();
525
+ const tagged = [];
526
+ for (const fileName of (0, fs_1.readdirSync)(outDir)) {
527
+ const match = fileName.match(recorder_1.HIT_FILE_PATTERN);
528
+ if (match)
529
+ tagged.push({ fileName, runId: match[1] ?? null });
530
+ }
531
+ if (!tagged.length)
441
532
  return [];
442
- const hitsJsonPath = (0, paths_1.getHitsJsonPath)();
443
- const watermark = (0, fs_1.existsSync)(hitsJsonPath) ? (0, fs_1.statSync)(hitsJsonPath).mtimeMs - 1000 : 0;
444
- const fromThisRun = names.filter((fileName) => (0, fs_1.statSync)(path.join(outDir, fileName)).mtimeMs >= watermark);
445
- const pool = fromThisRun.length ? fromThisRun : names;
533
+ let pool = tagged;
534
+ if (runId) {
535
+ pool = tagged.filter((entry) => entry.runId === runId);
536
+ if (!pool.length)
537
+ return [];
538
+ }
539
+ else {
540
+ // No run marker (e.g. plain `daxta generate`) — fall back to mtime proximity.
541
+ const hitsJsonPath = (0, paths_1.getHitsJsonPath)();
542
+ const watermark = (0, fs_1.existsSync)(hitsJsonPath) ? (0, fs_1.statSync)(hitsJsonPath).mtimeMs - 1000 : 0;
543
+ const fresh = tagged.filter((entry) => (0, fs_1.statSync)(path.join(outDir, entry.fileName)).mtimeMs >= watermark);
544
+ pool = fresh.length ? fresh : tagged;
545
+ }
446
546
  const newestByWorker = new Map();
447
- for (const fileName of pool) {
448
- const workerId = fileName.match(/^hits-w([^-]+)-p\d+\.json$/)?.[1] ?? fileName;
547
+ for (const { fileName } of pool) {
548
+ const workerId = fileName.match(/w([^-]+)-p\d+\.json$/)?.[1] ?? fileName;
449
549
  const mtime = (0, fs_1.statSync)(path.join(outDir, fileName)).mtimeMs;
450
550
  const prev = newestByWorker.get(workerId);
451
551
  if (!prev || mtime >= prev.mtime)
@@ -472,6 +572,10 @@ function loadHits() {
472
572
  if (loaded.length)
473
573
  return loaded;
474
574
  }
575
+ // Inside a Jest run the marker is authoritative: no hit files means this run
576
+ // recorded nothing, so never resurrect an earlier run's traffic from hits.json.
577
+ if ((0, recorder_1.readRunId)())
578
+ return [];
475
579
  // Fallback after workers were cleaned — last completed run's hits.json
476
580
  if (!(0, fs_1.existsSync)((0, paths_1.getHitsJsonPath)()))
477
581
  return [];
@@ -494,9 +598,49 @@ function sortOperations(entries) {
494
598
  return (METHOD_RANK[leftMethod] ?? 99) - (METHOD_RANK[rightMethod] ?? 99);
495
599
  });
496
600
  }
601
+ /**
602
+ * A URL segment earns a folder only when it holds more than one thing. A leaf that
603
+ * carries a single operation and no subfolders folds into its parent, so
604
+ * `merchants › tr › POST onboard` reads `merchants › POST onboard tr merchant`
605
+ * while `external-checkouts` (GET + POST + PUT …) keeps its folder. One level only.
606
+ */
607
+ function collapseLonelyLeafFolders(paths) {
608
+ if ((0, config_1.getConfig)().treeCollapseSingle === false)
609
+ return;
610
+ const entries = [];
611
+ for (const [pathTemplate, pathItem] of Object.entries(paths)) {
612
+ const pathParts = pathTemplate.split('/').filter(Boolean);
613
+ for (const [method, operation] of Object.entries(pathItem)) {
614
+ if (!(method in METHOD_RANK) || !operation || typeof operation !== 'object')
615
+ continue;
616
+ const segments = operation['x-tree-segments'];
617
+ if (!Array.isArray(segments) || !segments.length)
618
+ continue;
619
+ // Segments shorter than the URL were already shaped by param folding or an
620
+ // override; that folder is a deliberate grouping, so leave it alone.
621
+ entries.push({ operation, segments, foldable: segments.length === pathParts.length });
622
+ }
623
+ }
624
+ const opsPerFolder = new Map();
625
+ for (const { segments } of entries) {
626
+ const folder = segments.join('/');
627
+ opsPerFolder.set(folder, (opsPerFolder.get(folder) ?? 0) + 1);
628
+ }
629
+ const folders = [...opsPerFolder.keys()];
630
+ for (const entry of entries) {
631
+ if (!entry.foldable || entry.segments.length < 2)
632
+ continue;
633
+ const folder = entry.segments.join('/');
634
+ if (opsPerFolder.get(folder) !== 1)
635
+ continue;
636
+ if (folders.some((other) => other.startsWith(`${folder}/`)))
637
+ continue;
638
+ entry.operation['x-tree-segments'] = entry.segments.slice(0, -1);
639
+ }
640
+ }
497
641
  function buildSpec(hits) {
498
642
  const grouped = new Map();
499
- for (const hit of selectHitsForDocs(hits.filter(isPrimaryHit))) {
643
+ for (const hit of selectHitsForDocs(primaryHits(hits))) {
500
644
  const key = `${hit.method} ${hit.path}`;
501
645
  const opHits = grouped.get(key) ?? [];
502
646
  opHits.push(hit);
@@ -557,6 +701,7 @@ function buildSpec(hits) {
557
701
  }
558
702
  operation['x-scenarios'] = sortScenarios(dedupeScenarios(opHits.map(toScenario)));
559
703
  }
704
+ collapseLonelyLeafFolders(paths);
560
705
  const info = specInfo();
561
706
  return {
562
707
  openapi: '3.0.3',
@@ -567,12 +712,17 @@ function buildSpec(hits) {
567
712
  'x-workspace': info.workspace,
568
713
  },
569
714
  'x-viewer': (0, catalog_1.viewerTreeConfig)(),
570
- servers: [{ url: (0, config_1.getConfig)().baseUrl }],
715
+ servers: specServers(),
571
716
  tags: [...tags].sort().map((name) => ({ name })),
572
717
  paths,
573
718
  components: { securitySchemes },
574
719
  };
575
720
  }
721
+ /** One server entry per env preset; `description` carries the env name for the viewer. */
722
+ function specServers() {
723
+ const config = (0, config_1.getConfig)();
724
+ return (0, config_1.serversFromEnvPresets)(config.envPresets, config.baseUrl);
725
+ }
576
726
  function writeJson(filePath, value) {
577
727
  (0, fs_1.mkdirSync)(path.dirname(filePath), { recursive: true });
578
728
  (0, fs_1.writeFileSync)(filePath, `${JSON.stringify(value, null, 2)}\n`);
@@ -676,8 +826,8 @@ function hitSignature(hit) {
676
826
  function hitsStructureSame(existing, fresh) {
677
827
  if (!existing)
678
828
  return false;
679
- const left = existing.filter(isPrimaryHit).map(hitSignature).sort();
680
- const right = fresh.filter(isPrimaryHit).map(hitSignature).sort();
829
+ const left = primaryHits(existing).map(hitSignature).sort();
830
+ const right = primaryHits(fresh).map(hitSignature).sort();
681
831
  return JSON.stringify(left) === JSON.stringify(right);
682
832
  }
683
833
  function mergeSpecs(existing, fresh) {
@@ -718,22 +868,24 @@ function mergeSpecs(existing, fresh) {
718
868
  function countOperations(spec) {
719
869
  return Object.values(spec.paths).reduce((count, pathItem) => count + Object.keys(pathItem).length, 0);
720
870
  }
871
+ function pngDataUri(filePath) {
872
+ return (0, fs_1.existsSync)(filePath) ? `data:image/png;base64,${(0, fs_1.readFileSync)(filePath).toString('base64')}` : '';
873
+ }
721
874
  function toStandaloneHtml(spec) {
722
875
  const template = (0, fs_1.readFileSync)((0, paths_1.getViewerAssetPath)(), 'utf8');
723
- const faviconPath = (0, paths_1.getFaviconAssetPath)();
724
- const faviconUri = (0, fs_1.existsSync)(faviconPath)
725
- ? `data:image/png;base64,${(0, fs_1.readFileSync)(faviconPath).toString('base64')}`
726
- : '';
876
+ const faviconUri = pngDataUri((0, paths_1.getFaviconAssetPath)());
877
+ const faviconLightUri = pngDataUri((0, paths_1.getFaviconLightAssetPath)()) || faviconUri;
727
878
  return template
728
879
  .replace('__SPEC_JSON__', JSON.stringify(spec).replace(/</g, '\\u003c'))
729
- .replaceAll('__FAVICON_DATA_URI__', faviconUri);
880
+ .replaceAll('__FAVICON_DATA_URI__', faviconUri)
881
+ .replaceAll('__FAVICON_LIGHT_DATA_URI__', faviconLightUri);
730
882
  }
731
883
  function viewerTemplateNewerThanHtml() {
732
884
  if (!(0, fs_1.existsSync)((0, paths_1.getHtmlPath)()))
733
885
  return true;
734
886
  const htmlMtime = (0, fs_1.statSync)((0, paths_1.getHtmlPath)()).mtimeMs;
735
887
  const newerThan = (filePath) => (0, fs_1.existsSync)(filePath) && (0, fs_1.statSync)(filePath).mtimeMs > htmlMtime;
736
- return newerThan((0, paths_1.getViewerAssetPath)()) || newerThan((0, paths_1.getFaviconAssetPath)());
888
+ return newerThan((0, paths_1.getViewerAssetPath)()) || newerThan((0, paths_1.getFaviconAssetPath)()) || newerThan((0, paths_1.getFaviconLightAssetPath)());
737
889
  }
738
890
  function applyViewerMeta(spec) {
739
891
  const info = specInfo();
@@ -747,7 +899,7 @@ function applyViewerMeta(spec) {
747
899
  'x-workspace': info.workspace,
748
900
  },
749
901
  'x-viewer': (0, catalog_1.viewerTreeConfig)(),
750
- servers: [{ url: (0, config_1.getConfig)().baseUrl }],
902
+ servers: specServers(),
751
903
  };
752
904
  }
753
905
  function buildDaxtaSpec(options = {}) {
@@ -26,6 +26,7 @@ export declare function viewerTreeConfig(): {
26
26
  docsPath: string;
27
27
  treeLayout: TreeLayout;
28
28
  treeSkipParams: boolean;
29
+ treeCollapseSingle: boolean;
29
30
  treePathOverrides: Record<string, string[]>;
30
31
  exampleLabelStyle: "status-case" | "status-title-case" | "full";
31
32
  envPresets: Record<string, import("../config").EnvPreset> | undefined;
@@ -45,7 +45,7 @@ const METHOD_ALIASES = {
45
45
  merge: ['post', 'put', 'patch'],
46
46
  replace: ['put'],
47
47
  };
48
- const CASE_SECTION_RE = /^(POSITIVE CASES|SEMANTIC ERROR CASES(?:\s*-\s*AUTH)?|INVALID CASES|OMITTED(?: FIELD)? CASES)\s+/i;
48
+ const CASE_SECTION_RE = /^((?:FALSE\s+)?POSITIVE CASES|SEMANTIC ERROR CASES(?:\s*-\s*AUTH)?|INVALID CASES|OMITTED(?: FIELD)? CASES)\s+/i;
49
49
  function declaredMethods(test) {
50
50
  if (!test)
51
51
  return null;
@@ -101,6 +101,7 @@ function viewerTreeConfig() {
101
101
  docsPath: config.docsPath,
102
102
  treeLayout: (0, config_1.normalizeTreeLayout)(config.treeLayout),
103
103
  treeSkipParams: config.treeSkipParams !== false,
104
+ treeCollapseSingle: config.treeCollapseSingle !== false,
104
105
  treePathOverrides: config.treePathOverrides,
105
106
  exampleLabelStyle: config.exampleLabelStyle ?? 'status-title-case',
106
107
  envPresets: config.envPresets,
@@ -143,6 +144,9 @@ function caseGroup(test) {
143
144
  return 'Other';
144
145
  if (/SEMANTIC ERROR CASES\s*-\s*AUTH/i.test(test))
145
146
  return 'SEMANTIC ERROR CASES - AUTH';
147
+ // "FALSE POSITIVE CASES" is the same bucket the viewer renders as "False positive cases".
148
+ if (/FALSE\s+POSITIVE CASES/i.test(test))
149
+ return 'SEMANTIC ERROR CASES';
146
150
  if (/POSITIVE CASES/i.test(test))
147
151
  return 'POSITIVE CASES';
148
152
  if (/SEMANTIC ERROR CASES/i.test(test))
@@ -156,7 +160,7 @@ function caseGroup(test) {
156
160
  function caseSectionLabel(test) {
157
161
  if (!test)
158
162
  return '';
159
- const match = test.match(/(POSITIVE CASES|SEMANTIC ERROR CASES(?:\s*-\s*AUTH)?|INVALID CASES|OMITTED(?: FIELD)? CASES)/i);
163
+ const match = test.match(/((?:FALSE\s+)?POSITIVE CASES|SEMANTIC ERROR CASES(?:\s*-\s*AUTH)?|INVALID CASES|OMITTED(?: FIELD)? CASES)/i);
160
164
  return match?.[1]?.toUpperCase() ?? '';
161
165
  }
162
166
  /**
@@ -183,23 +187,32 @@ function apiTitle(test) {
183
187
  }
184
188
  return undefined;
185
189
  }
190
+ /**
191
+ * Drop a describe-level qualifier that only precedes the case section, e.g.
192
+ * "(solution partner) INVALID CASES field - should not be empty". The section itself
193
+ * is already shown as the example's group, so both are redundant in the label.
194
+ */
195
+ function stripSectionPrefix(value) {
196
+ let rest = value.replace(CASE_SECTION_RE, '').trim();
197
+ const qualifier = rest.match(/^\(([^)]*)\)\s*/);
198
+ if (qualifier && CASE_SECTION_RE.test(rest.slice(qualifier[0].length))) {
199
+ rest = rest.slice(qualifier[0].length).replace(CASE_SECTION_RE, '').trim();
200
+ }
201
+ return rest;
202
+ }
186
203
  function caseName(test) {
187
204
  if (!test)
188
205
  return 'example';
189
206
  let rest = test
190
207
  .replace(new RegExp(`^.+?\\s+[—–-]\\s+(?:${test_title_1.HTTP_VERBS})\\s+\\S+\\s*`, 'i'), '')
191
- .replace(new RegExp(`^.*?\\[(?:${test_title_1.HTTP_VERBS})\\]\\s*(?:\\(integration\\))?\\s*`, 'i'), '')
192
- .replace(CASE_SECTION_RE, '')
193
- .trim();
208
+ .replace(new RegExp(`^.*?\\[(?:${test_title_1.HTTP_VERBS})\\]\\s*(?:\\(integration\\))?\\s*`, 'i'), '');
209
+ rest = stripSectionPrefix(rest.trim());
194
210
  // "Admin Find One Basket By Id API - GET /path POSITIVE CASES returns…"
195
- rest = rest
196
- .replace(/^.+?\bAPI\s*[-–—]\s*(?:GET|POST|PUT|PATCH|DELETE)\s+\S+\s+/i, '')
197
- .replace(CASE_SECTION_RE, '')
198
- .trim();
211
+ rest = stripSectionPrefix(rest.replace(/^.+?\bAPI\s*[-–—]\s*(?:GET|POST|PUT|PATCH|DELETE)\s+\S+\s+/i, ''));
199
212
  // Drop leading human title if still present before the case text
200
213
  const title = apiTitle(test);
201
214
  if (title && rest.startsWith(title)) {
202
- rest = rest.slice(title.length).replace(/^[-–—\s]+/, '').replace(CASE_SECTION_RE, '').trim();
215
+ rest = stripSectionPrefix(rest.slice(title.length).replace(/^[-–—\s]+/, ''));
203
216
  }
204
217
  return rest || test;
205
218
  }
@@ -28,6 +28,8 @@ function parseCaseSection(raw) {
28
28
  return undefined;
29
29
  if (/SEMANTIC ERROR CASES\s*-\s*AUTH/i.test(raw))
30
30
  return 'auth';
31
+ if (/FALSE\s+POSITIVE CASES/i.test(raw))
32
+ return 'semantic';
31
33
  if (/POSITIVE CASES/i.test(raw))
32
34
  return 'positive';
33
35
  if (/SEMANTIC ERROR CASES/i.test(raw))
@@ -12,11 +12,13 @@ exports.suggestOperationTitles = suggestOperationTitles;
12
12
  /** Verbs that appear in TEST_TITLE `[METHOD]` / `— METHOD path`. */
13
13
  exports.HTTP_VERBS = 'GET|POST|PUT|PATCH|DELETE|UPDATE|UPSERT|INSERT|MERGE|REPLACE';
14
14
  const METHODS = exports.HTTP_VERBS;
15
- const PATH_ONLY_BRACKET_RE = new RegExp(`^(?<path>\\/\\S+)\\s+\\[(?<method>${METHODS})\\](?:\\s+\\(integration\\))?\\s*$`, 'i');
16
- const TITLE_BRACKET_RE = new RegExp(`^(?<title>.+?)\\s+(?<path>\\/\\S+)\\s+\\[(?<method>${METHODS})\\](?:\\s+\\(integration\\))?\\s*$`, 'i');
15
+ /** Trailing qualifiers such as `(integration)` or `(solution partner)`. */
16
+ const QUALIFIER = '(?:\\s+\\([^)]*\\))*';
17
+ const PATH_ONLY_BRACKET_RE = new RegExp(`^(?<path>\\/\\S+)\\s+\\[(?<method>${METHODS})\\]${QUALIFIER}\\s*$`, 'i');
18
+ const TITLE_BRACKET_RE = new RegExp(`^(?<title>.+?)\\s+(?<path>\\/\\S+)\\s+\\[(?<method>${METHODS})\\]${QUALIFIER}\\s*$`, 'i');
17
19
  /** `Create Mock Tbs — POST /v1/admin/mock-tbs` */
18
- const TITLE_DASH_RE = new RegExp(`^(?<title>.+?)\\s+[—–-]\\s+(?<method>${METHODS})\\s+(?<path>\\/\\S+)(?:\\s+\\(integration\\))?\\s*$`, 'i');
19
- const PATH_ONLY_DASH_RE = new RegExp(`^(?<method>${METHODS})\\s+(?<path>\\/\\S+)(?:\\s+\\(integration\\))?\\s*$`, 'i');
20
+ const TITLE_DASH_RE = new RegExp(`^(?<title>.+?)\\s+[—–-]\\s+(?<method>${METHODS})\\s+(?<path>\\/\\S+)${QUALIFIER}\\s*$`, 'i');
21
+ const PATH_ONLY_DASH_RE = new RegExp(`^(?<method>${METHODS})\\s+(?<path>\\/\\S+)${QUALIFIER}\\s*$`, 'i');
20
22
  const ROLE_WORDS = new Set([
21
23
  'admin',
22
24
  'user',
@@ -111,7 +113,7 @@ function isHumanOperationTitle(title) {
111
113
  }
112
114
  function stripCaseTail(raw) {
113
115
  return raw
114
- .replace(/\s+(POSITIVE CASES|SEMANTIC ERROR CASES(?:\s*-\s*AUTH)?|INVALID CASES|OMITTED(?: FIELD)? CASES)\b[\s\S]*$/i, '')
116
+ .replace(/\s+((?:FALSE\s+)?POSITIVE CASES|SEMANTIC ERROR CASES(?:\s*-\s*AUTH)?|INVALID CASES|OMITTED(?: FIELD)? CASES)\b[\s\S]*$/i, '')
115
117
  .trim();
116
118
  }
117
119
  /**
@@ -121,14 +121,13 @@ export default defineConfig({
121
121
  docsPath: '/docs',
122
122
  treeLayout: 'role-resource',
123
123
  treeSkipParams: true,
124
+ treeCollapseSingle: true,
124
125
  exampleLabelStyle: 'status-title-case',
125
126
  fieldsFile: '.daxta/out/fields.json',
126
127
  viewerStoreFile: '.daxta/viewer-store.json',
127
- envPresets: {
128
- local: { baseUrl: 'http://localhost:3000' },
129
- staging: { baseUrl: 'https://api.staging.example.com' },
130
- production: { baseUrl: 'https://api.example.com' },
131
- },
128
+ // Try-it envs are derived from baseUrl / spec servers. Add envPresets only to
129
+ // override or add extra environments:
130
+ // envPresets: { staging: { baseUrl: 'https://api.staging.example.com' } },
132
131
  });
133
132
  `;
134
133
  if (!dryRun)
@@ -158,20 +157,23 @@ function ensureGitignore(cwd, dryRun) {
158
157
  return added.map((e) => `.gitignore += ${e}`);
159
158
  }
160
159
  const ENV_CANDIDATES = ['.env', '.env.local', '.env.development', '.env.development.local'];
161
- /** Ensure DAXTA_DOCS is present (default on). Mirrors uninstall strip. */
162
- function ensureEnvDaxtaDocs(cwd, dryRun) {
160
+ /**
161
+ * Docs are gated on NODE_ENV, so the project needs one. Seed `development` only when
162
+ * no env file declares it; an existing value is the project's call and stays untouched.
163
+ */
164
+ function ensureEnvNodeEnv(cwd, dryRun) {
163
165
  for (const name of ENV_CANDIDATES) {
164
166
  const filePath = path.join(cwd, name);
165
167
  if (!(0, fs_1.existsSync)(filePath))
166
168
  continue;
167
- const text = (0, fs_1.readFileSync)(filePath, 'utf8');
168
- if (/^\s*DAXTA_DOCS\s*=/m.test(text))
169
- return `${name} · DAXTA_DOCS already set`;
169
+ const match = (0, fs_1.readFileSync)(filePath, 'utf8').match(/^\s*NODE_ENV\s*=\s*(\S*)/m);
170
+ if (match)
171
+ return `${name} · NODE_ENV=${match[1] || '(empty)'} — kept`;
170
172
  }
171
173
  const targetName = ENV_CANDIDATES.find((name) => (0, fs_1.existsSync)(path.join(cwd, name))) ?? '.env';
172
174
  const targetPath = path.join(cwd, targetName);
173
175
  const created = !(0, fs_1.existsSync)(targetPath);
174
- const line = 'DAXTA_DOCS=on';
176
+ const line = 'NODE_ENV=development';
175
177
  if (!dryRun) {
176
178
  if (created) {
177
179
  (0, fs_1.writeFileSync)(targetPath, `${line}\n`);
@@ -182,7 +184,7 @@ function ensureEnvDaxtaDocs(cwd, dryRun) {
182
184
  (0, fs_1.writeFileSync)(targetPath, next);
183
185
  }
184
186
  }
185
- return created ? `created ${targetName} (+ DAXTA_DOCS=on)` : `${targetName} += DAXTA_DOCS=on`;
187
+ return created ? `created ${targetName} (+ ${line})` : `${targetName} += ${line}`;
186
188
  }
187
189
  function runPackageInstall(cwd, pm, version, dryRun) {
188
190
  if (dryRun)
@@ -228,7 +230,7 @@ async function installDaxta(options = {}) {
228
230
  await (0, ui_1.step)('Package dependency', () => 'already installed — skip add', { paceMs, n: 1, of });
229
231
  }
230
232
  }
231
- (0, ui_1.phase)(2, of, 'Workspace files', 'config, gitignore, API docs env flag');
233
+ (0, ui_1.phase)(2, of, 'Workspace files', 'config, gitignore, NODE_ENV');
232
234
  await (0, ui_1.step)('Write daxta.config.ts', () => {
233
235
  const { created, rel } = writeConfig(cwd, dryRun);
234
236
  return created ? `created ${rel}` : `exists · ${rel}`;
@@ -258,7 +260,7 @@ async function installDaxta(options = {}) {
258
260
  return 'already ignored';
259
261
  return { summary: `${notes.length} entr${notes.length === 1 ? 'y' : 'ies'}`, details: notes };
260
262
  }, { paceMs, n: 2, of });
261
- await (0, ui_1.step)('Set DAXTA_DOCS in env', () => ensureEnvDaxtaDocs(cwd, dryRun), { paceMs, n: 2, of });
263
+ await (0, ui_1.step)('Ensure NODE_ENV in env', () => ensureEnvNodeEnv(cwd, dryRun), { paceMs, n: 2, of });
262
264
  (0, ui_1.phase)(3, of, 'Nest', 'apiDocs(app) on the HTTP bootstrap');
263
265
  if (!options.skipMain) {
264
266
  const target = await (0, inject_main_1.resolveMainTarget)({
@@ -344,7 +346,7 @@ async function installDaxta(options = {}) {
344
346
  }
345
347
  (0, ui_1.box)('Ready', [
346
348
  `${ui_1.c.mint('✔')} ${ui_1.c.bold(project)} · DAxTA ${ui_1.c.gold(`v${version}`)}`,
347
- `${ui_1.c.dim('api docs')} ${ui_1.c.ice('/docs')} · ${ui_1.c.ice('DAXTA_DOCS=on')}`,
349
+ `${ui_1.c.dim('api docs')} ${ui_1.c.ice('/docs')} · on when ${ui_1.c.ice('NODE_ENV')} is dev/test/staging`,
348
350
  `${ui_1.c.dim('tests')} same script — titles first, spec after`,
349
351
  `${ui_1.c.dim('retune')} ${ui_1.c.ice('daxta tree')} · ${ui_1.c.ice('daxta titles')}`,
350
352
  ]);
@@ -356,7 +358,7 @@ async function installDaxta(options = {}) {
356
358
  },
357
359
  {
358
360
  cmd: `${pm} start:dev`,
359
- why: 'open /docs (DAXTA_DOCS=on already in .env)',
361
+ why: 'open /docs — served outside production',
360
362
  },
361
363
  ]);
362
364
  }
@@ -13,21 +13,23 @@ async function pickFromSuggestions(finding, extra, validate) {
13
13
  if (extra)
14
14
  console.log(` ${ui_1.c.dim(extra)}`);
15
15
  if (!suggestions.length) {
16
- console.log(` ${ui_1.c.gold('no auto suggestion')} ${ui_1.c.dim('— type a title, or s to skip')}`);
16
+ console.log(` ${ui_1.c.gold('no auto suggestion')} ${ui_1.c.dim('— type a title, or s to skip one, n to skip all')}`);
17
17
  }
18
18
  suggestions.forEach((name, index) => {
19
19
  const mark = index === 0 ? ui_1.c.dim(' recommended') : '';
20
20
  console.log(` ${ui_1.c.ice(String(index + 1))} ${name}${mark}`);
21
21
  });
22
22
  console.log(suggestions.length
23
- ? ` ${ui_1.c.dim('Enter = 1')} ${ui_1.c.dim('·')} ${ui_1.c.ice('a')} remaining auto ${ui_1.c.dim('·')} ${ui_1.c.ice('s')} skip ${ui_1.c.dim('·')} ${ui_1.c.ice('c')} custom`
24
- : ` ${ui_1.c.ice('c')} custom ${ui_1.c.dim('·')} ${ui_1.c.ice('s')} skip`);
23
+ ? ` ${ui_1.c.dim('Enter = 1')} ${ui_1.c.dim('·')} ${ui_1.c.ice('a')} remaining auto ${ui_1.c.dim('·')} ${ui_1.c.ice('s')} skip one ${ui_1.c.dim('·')} ${ui_1.c.ice('n')} skip all ${ui_1.c.dim('·')} ${ui_1.c.ice('c')} custom`
24
+ : ` ${ui_1.c.ice('c')} custom ${ui_1.c.dim('·')} ${ui_1.c.ice('s')} skip one ${ui_1.c.dim('·')} ${ui_1.c.ice('n')} skip all`);
25
25
  const answer = (await (0, ui_1.readlineAsk)(` ${ui_1.c.ice('›')} `)).trim();
26
26
  const lower = answer.toLowerCase();
27
27
  if (!answer)
28
28
  return suggestions[0] ? suggestions[0] : 'skip';
29
29
  if (lower === 's')
30
30
  return 'skip';
31
+ if (lower === 'n' || lower === 'no' || lower === 'skip-all' || lower === 'skipall')
32
+ return 'skip-all';
31
33
  if (lower === 'a' || lower === 'all')
32
34
  return 'all';
33
35
  if (lower === 'y' || lower === 'yes')
@@ -128,12 +130,21 @@ async function runTitleCheck(options) {
128
130
  (0, scan_1.printNamingFindings)(report, ui_1.c);
129
131
  return options.strict ? 1 : 0;
130
132
  }
131
- (0, ui_1.banner)('Test naming', 'runs before Jest — API docs / Postman labels');
132
- console.log(` ${ui_1.c.dim('Title')} Create Mock Tbs — POST /v1/admin/mock-tbs`);
133
- console.log(` ${ui_1.c.dim('it()+')} creates mock tbs when cyprus payload shape`);
134
- console.log(` ${ui_1.c.dim('it()-')} returns error when tax id already exists`);
135
- console.log(` ${ui_1.c.dim('label')} 201 — cyprus payload shape`);
136
- console.log(` ${ui_1.c.gold(String(total))} to review — ${ui_1.c.ice('y')} one recommended, ${ui_1.c.ice('a')} all remaining, ${ui_1.c.ice('s')} skip.`);
133
+ (0, ui_1.banner)('Test naming', 'describe + it() → API docs labels');
134
+ console.log(` ${ui_1.c.dim('describe')} Create Mock Tbs — POST /v1/admin/mock-tbs`);
135
+ console.log(` ${ui_1.c.dim('→ operation title in sidebar')}`);
136
+ console.log(` ${ui_1.c.dim('it()')} creates mock tbs when cyprus payload shape`);
137
+ console.log(` ${ui_1.c.dim('→ scenario clause (text after')} ${ui_1.c.ice('when')}${ui_1.c.dim(')')}`);
138
+ console.log(` ${ui_1.c.dim('label')} 201 — Create Mock Tbs — cyprus payload shape`);
139
+ console.log(` ${ui_1.c.dim('→')} ${ui_1.c.ice('exampleLabelStyle')} ${ui_1.c.dim('in')} ${ui_1.c.ice('daxta tree')} ${ui_1.c.dim('· change with')} ${ui_1.c.ice('2')} ${ui_1.c.dim('for short labels')}`);
140
+ const start = await (0, ui_1.readlineAsk)(` ${ui_1.c.gold('?')} Review test names now?\n` +
141
+ ` ${ui_1.c.dim('Y')} yes · ${ui_1.c.dim('n')} skip all\n ${ui_1.c.ice('›')} `);
142
+ if (!start || /^n(o)?$/i.test(start)) {
143
+ console.log(` ${ui_1.c.dim('skipped')} ${ui_1.c.ice('daxta titles')} ${ui_1.c.dim('anytime')}`);
144
+ console.log('');
145
+ return 0;
146
+ }
147
+ console.log(` ${ui_1.c.gold(String(total))} to review — ${ui_1.c.ice('y')} one recommended, ${ui_1.c.ice('a')} all remaining, ${ui_1.c.ice('s')} skip one, ${ui_1.c.ice('n')} skip all.`);
137
148
  let written = 0;
138
149
  let skipped = 0;
139
150
  for (let i = 0; i < report.titles.length; i += 1) {
@@ -145,6 +156,14 @@ async function runTitleCheck(options) {
145
156
  skipped += rest.skipped;
146
157
  for (const pending of rest.pending) {
147
158
  const customChoice = await pickFromSuggestions(pending, `docs would show ${pending.path} — custom title required`, test_title_1.isHumanOperationTitle);
159
+ if (customChoice === 'skip-all') {
160
+ skipped += rest.pending.length;
161
+ console.log(` ${ui_1.c.dim('skipped remaining')}`);
162
+ console.log('');
163
+ console.log(` ${ui_1.c.mint('✔')} ${written} updated ${ui_1.c.dim(`${skipped} skipped`)}`);
164
+ console.log('');
165
+ return options.strict && skipped > 0 ? 1 : 0;
166
+ }
148
167
  if (!customChoice || customChoice === 'skip' || customChoice === 'all') {
149
168
  skipped += 1;
150
169
  continue;
@@ -161,6 +180,14 @@ async function runTitleCheck(options) {
161
180
  console.log('');
162
181
  return options.strict && skipped > 0 ? 1 : 0;
163
182
  }
183
+ if (choice === 'skip-all') {
184
+ skipped += report.titles.length - i + report.cases.length;
185
+ console.log(` ${ui_1.c.dim('skipped remaining')}`);
186
+ console.log('');
187
+ console.log(` ${ui_1.c.mint('✔')} ${written} updated ${ui_1.c.dim(`${skipped} skipped`)}`);
188
+ console.log('');
189
+ return options.strict && skipped > 0 ? 1 : 0;
190
+ }
164
191
  if (!choice || choice === 'skip') {
165
192
  skipped += 1;
166
193
  continue;
@@ -183,6 +210,11 @@ async function runTitleCheck(options) {
183
210
  skipped += rest.skipped;
184
211
  break;
185
212
  }
213
+ if (choice === 'skip-all') {
214
+ skipped += report.cases.length - i;
215
+ console.log(` ${ui_1.c.dim('skipped remaining')}`);
216
+ break;
217
+ }
186
218
  if (!choice || choice === 'skip') {
187
219
  skipped += 1;
188
220
  continue;
package/dist/cli/tree.js CHANGED
@@ -118,12 +118,22 @@ async function pickSkipParams(current) {
118
118
  async function pickExampleStyle(current) {
119
119
  console.log('');
120
120
  console.log(` ${ui_1.c.bold('Example / scenario labels')}`);
121
- console.log(` ${ui_1.c.ice('1')} status-title-case`);
122
- console.log(` ${ui_1.c.dim('201 — cyprus payload shape')}`);
123
- console.log(` ${ui_1.c.ice('2')} status-case`);
121
+ console.log(` ${ui_1.c.dim('Sidebar + OpenAPI export name for each test hit.')}`);
122
+ console.log(` ${ui_1.c.dim('From')} ${ui_1.c.ice('it()')} ${ui_1.c.dim('— text after')} ${ui_1.c.ice('when')} ${ui_1.c.dim('becomes the scenario clause.')}`);
123
+ console.log('');
124
+ console.log(` ${ui_1.c.dim('sample')} ${ui_1.c.ice('creates mock tbs when cyprus payload shape')}`);
125
+ console.log('');
126
+ console.log(` ${ui_1.c.ice('1')} status-title-case ${ui_1.c.dim('(default)')}`);
127
+ console.log(` ${ui_1.c.dim('201 — Create Mock Tbs — cyprus payload shape')}`);
128
+ console.log(` ${ui_1.c.dim('status + operation title + scenario')}`);
129
+ console.log('');
130
+ console.log(` ${ui_1.c.ice('2')} status-case ${ui_1.c.dim('(short)')}`);
124
131
  console.log(` ${ui_1.c.dim('201 — cyprus payload shape')}`);
125
- console.log(` ${ui_1.c.ice('3')} full`);
132
+ console.log(` ${ui_1.c.dim('status + scenario only')}`);
133
+ console.log('');
134
+ console.log(` ${ui_1.c.ice('3')} full ${ui_1.c.dim('(verbose — path + section)')}`);
126
135
  console.log(` ${ui_1.c.dim('201 — Create Mock Tbs - POST /v1/admin/mock-tbs POSITIVE CASES cyprus payload shape')}`);
136
+ console.log('');
127
137
  console.log(` ${ui_1.c.ice('4')} keep ${ui_1.c.dim(`(${current})`)}`);
128
138
  const answer = await (0, ui_1.readlineAsk)(` ${ui_1.c.gold('?')} Choose\n ${ui_1.c.ice('›')} `);
129
139
  if (!answer || answer === '4' || /^k(eep)?$/i.test(answer))
@@ -80,6 +80,7 @@ function stripGitignore(cwd, dryRun) {
80
80
  (0, fs_1.writeFileSync)(gitignorePath, `${kept.join('\n').replace(/\n+$/, '')}\n`);
81
81
  return [...remove].filter((entry) => lines.some((line) => line.trim() === entry));
82
82
  }
83
+ /** Legacy cleanup: older installs wrote a DAXTA_DOCS gate before NODE_ENV took over. */
83
84
  function stripEnvDaxta(cwd, dryRun) {
84
85
  const notes = [];
85
86
  for (const name of ['.env', '.env.local', '.env.development', '.env.development.local']) {
@@ -259,7 +260,7 @@ async function uninstallDaxta(options = {}) {
259
260
  details.push(`.gitignore − ${gi.join(', ')}`);
260
261
  const env = stripEnvDaxta(cwd, dryRun);
261
262
  if (env.length)
262
- details.push(`DAXTA_DOCS removed from ${env.join(', ')}`);
263
+ details.push(`legacy DAXTA_DOCS removed from ${env.join(', ')}`);
263
264
  if (!details.length)
264
265
  return 'nothing to clean';
265
266
  return { summary: 'cleaned', details };