@nokout/big-dill-core 0.0.1

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.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +202 -0
  3. package/dist/completion/complete.d.ts +40 -0
  4. package/dist/completion/complete.d.ts.map +1 -0
  5. package/dist/completion/complete.js +134 -0
  6. package/dist/completion/complete.js.map +1 -0
  7. package/dist/format/tables.d.ts +7 -0
  8. package/dist/format/tables.d.ts.map +1 -0
  9. package/dist/format/tables.js +87 -0
  10. package/dist/format/tables.js.map +1 -0
  11. package/dist/gherkin/parser.d.ts +28 -0
  12. package/dist/gherkin/parser.d.ts.map +1 -0
  13. package/dist/gherkin/parser.js +44 -0
  14. package/dist/gherkin/parser.js.map +1 -0
  15. package/dist/index.d.ts +25 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +92 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/ipc/server.d.ts +13 -0
  20. package/dist/ipc/server.d.ts.map +1 -0
  21. package/dist/ipc/server.js +106 -0
  22. package/dist/ipc/server.js.map +1 -0
  23. package/dist/lint/rules.d.ts +46 -0
  24. package/dist/lint/rules.d.ts.map +1 -0
  25. package/dist/lint/rules.js +387 -0
  26. package/dist/lint/rules.js.map +1 -0
  27. package/dist/protocol/types.d.ts +97 -0
  28. package/dist/protocol/types.d.ts.map +1 -0
  29. package/dist/protocol/types.js +5 -0
  30. package/dist/protocol/types.js.map +1 -0
  31. package/dist/pytest/runner.d.ts +29 -0
  32. package/dist/pytest/runner.d.ts.map +1 -0
  33. package/dist/pytest/runner.js +225 -0
  34. package/dist/pytest/runner.js.map +1 -0
  35. package/dist/results/outcomes.d.ts +36 -0
  36. package/dist/results/outcomes.d.ts.map +1 -0
  37. package/dist/results/outcomes.js +69 -0
  38. package/dist/results/outcomes.js.map +1 -0
  39. package/dist/steps/browser.d.ts +42 -0
  40. package/dist/steps/browser.d.ts.map +1 -0
  41. package/dist/steps/browser.js +110 -0
  42. package/dist/steps/browser.js.map +1 -0
  43. package/dist/steps/documentation.d.ts +10 -0
  44. package/dist/steps/documentation.d.ts.map +1 -0
  45. package/dist/steps/documentation.js +39 -0
  46. package/dist/steps/documentation.js.map +1 -0
  47. package/dist/steps/references.d.ts +10 -0
  48. package/dist/steps/references.d.ts.map +1 -0
  49. package/dist/steps/references.js +34 -0
  50. package/dist/steps/references.js.map +1 -0
  51. package/dist/steps/stepCache.d.ts +50 -0
  52. package/dist/steps/stepCache.d.ts.map +1 -0
  53. package/dist/steps/stepCache.js +149 -0
  54. package/dist/steps/stepCache.js.map +1 -0
  55. package/dist/steps/stubs.d.ts +10 -0
  56. package/dist/steps/stubs.d.ts.map +1 -0
  57. package/dist/steps/stubs.js +46 -0
  58. package/dist/steps/stubs.js.map +1 -0
  59. package/dist/steps/unimplemented.d.ts +10 -0
  60. package/dist/steps/unimplemented.d.ts.map +1 -0
  61. package/dist/steps/unimplemented.js +26 -0
  62. package/dist/steps/unimplemented.js.map +1 -0
  63. package/dist/symbols/outline.d.ts +13 -0
  64. package/dist/symbols/outline.d.ts.map +1 -0
  65. package/dist/symbols/outline.js +38 -0
  66. package/dist/symbols/outline.js.map +1 -0
  67. package/dist/tokens/semanticTokens.d.ts +13 -0
  68. package/dist/tokens/semanticTokens.d.ts.map +1 -0
  69. package/dist/tokens/semanticTokens.js +77 -0
  70. package/dist/tokens/semanticTokens.js.map +1 -0
  71. package/dist/tree/builder.d.ts +40 -0
  72. package/dist/tree/builder.d.ts.map +1 -0
  73. package/dist/tree/builder.js +178 -0
  74. package/dist/tree/builder.js.map +1 -0
  75. package/package.json +58 -0
  76. package/src/completion/complete.ts +165 -0
  77. package/src/format/tables.ts +108 -0
  78. package/src/gherkin/parser.ts +69 -0
  79. package/src/index.ts +136 -0
  80. package/src/ipc/server.ts +84 -0
  81. package/src/lint/rules.ts +425 -0
  82. package/src/protocol/types.ts +114 -0
  83. package/src/pytest/runner.ts +249 -0
  84. package/src/results/outcomes.ts +102 -0
  85. package/src/steps/browser.ts +105 -0
  86. package/src/steps/documentation.ts +43 -0
  87. package/src/steps/references.ts +33 -0
  88. package/src/steps/stepCache.ts +168 -0
  89. package/src/steps/stubs.ts +48 -0
  90. package/src/steps/unimplemented.ts +31 -0
  91. package/src/symbols/outline.ts +52 -0
  92. package/src/tokens/semanticTokens.ts +98 -0
  93. package/src/tree/builder.ts +187 -0
@@ -0,0 +1,168 @@
1
+ import { StepDefinition, StepParameter } from '../protocol/types';
2
+
3
+ export type LineMatch = {
4
+ step: StepDefinition;
5
+ params: Record<string, string>;
6
+ };
7
+
8
+ export type ParamAtPosition = {
9
+ parameter: StepParameter;
10
+ valueStart: number;
11
+ valueEnd: number;
12
+ };
13
+
14
+ /** Convert a step pattern to a regex with named capture groups for each parameter. */
15
+ /**
16
+ * Convert a step pattern to an anchored regex with a named capture per parameter.
17
+ *
18
+ * Exported because reference-finding needs the identical conversion; a second
19
+ * copy of this drifted once already (it missed the bounded-quantifier fix for
20
+ * ReDoS), so there is deliberately only one.
21
+ */
22
+ export function patternToRegex(pattern: string): RegExp {
23
+ // Escape regex metacharacters except our own {} placeholders
24
+ const parts = pattern.split(/(\{[^}]{1,200}\})/);
25
+ const regexStr = parts
26
+ .map((part, i) => {
27
+ if (i % 2 === 1) {
28
+ // parameter placeholder — extract name, create named capture group
29
+ const name = part.replace(/^\{(\w+)(?::[^}]{1,200})?\}$/, '$1');
30
+ return `(?<${name}>.+?)`;
31
+ }
32
+ // literal text — escape regex metacharacters
33
+ return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
34
+ })
35
+ .join('');
36
+ return new RegExp(`^${regexStr}$`);
37
+ }
38
+
39
+ /** Strip Gherkin keyword prefix from a raw feature file step line. */
40
+ const KEYWORD_RE = /^\s*(?:Given|When|Then|And|But|\*)\s+/i;
41
+ function stripKeyword(line: string): string | null {
42
+ const m = KEYWORD_RE.exec(line);
43
+ return m ? line.slice(m[0].length) : null;
44
+ }
45
+
46
+ export class StepCache {
47
+ private steps: StepDefinition[] = [];
48
+ private distributedSteps: StepDefinition[] = [];
49
+
50
+ update(steps: StepDefinition[]): void {
51
+ this.steps = steps.map(s => ({ ...s, usage_count: s.usage_count ?? 0 }));
52
+ }
53
+
54
+ updateDistributed(steps: StepDefinition[]): void {
55
+ this.distributedSteps = steps.map(s => ({ ...s, usage_count: s.usage_count ?? 0 }));
56
+ }
57
+
58
+ /**
59
+ * Scan *lines* (raw text lines from .feature files) and set `usage_count`
60
+ * on each step in the cache to the number of times that step pattern matches.
61
+ * Resets all counts to 0 before counting.
62
+ */
63
+ updateUsageCounts(lines: string[]): void {
64
+ // Reset
65
+ for (const s of [...this.steps, ...this.distributedSteps]) {
66
+ s.usage_count = 0;
67
+ }
68
+
69
+ // Precompile one regex per step (not per line)
70
+ const allSteps = [...this.steps, ...this.distributedSteps];
71
+ const compiled = allSteps.map(s => ({ step: s, rx: patternToRegex(s.pattern) }));
72
+
73
+ for (const line of lines) {
74
+ const stepText = stripKeyword(line);
75
+ if (!stepText) continue;
76
+ const trimmed = stepText.trim();
77
+ for (const { step, rx } of compiled) {
78
+ if (rx.test(trimmed)) {
79
+ step.usage_count = (step.usage_count ?? 0) + 1;
80
+ }
81
+ }
82
+ }
83
+ }
84
+
85
+ getAll(): StepDefinition[] {
86
+ return [...this.distributedSteps, ...this.steps];
87
+ }
88
+
89
+ getForKeyword(keyword: string): StepDefinition[] {
90
+ const norm = keyword.toLowerCase();
91
+ return this.getAll().filter(
92
+ (s) => s.keyword === norm || s.keyword === 'step'
93
+ );
94
+ }
95
+
96
+ /** Match full step text (no keyword prefix) against cached patterns. */
97
+ matchLine(stepText: string): LineMatch | null {
98
+ for (const step of this.steps) {
99
+ const rx = patternToRegex(step.pattern);
100
+ const m = rx.exec(stepText);
101
+ if (m?.groups) {
102
+ return { step, params: { ...m.groups } };
103
+ }
104
+ }
105
+ return null;
106
+ }
107
+
108
+ /**
109
+ * Return the step definition whose pattern matches *stepText* (no keyword prefix),
110
+ * or null if no pattern matches. Used by hover, definition, and linting.
111
+ */
112
+ matchPattern(stepText: string): StepDefinition | null {
113
+ const trimmed = stepText.trim();
114
+ for (const step of this.getAll()) {
115
+ const rx = patternToRegex(step.pattern);
116
+ if (rx.test(trimmed)) {
117
+ return step;
118
+ }
119
+ }
120
+ return null;
121
+ }
122
+
123
+ /**
124
+ * Return the parameter the cursor (at *column*) sits inside on *lineText*,
125
+ * or null if the cursor is not inside a parameter value.
126
+ *
127
+ * Positions are computed by walking literal segment lengths so that a
128
+ * placeholder value that also appears in the literal prefix (e.g. "state"
129
+ * in "the state is {state:AustralianState}") resolves to the correct span.
130
+ */
131
+ paramPositionAt(lineText: string, column: number): ParamAtPosition | null {
132
+ for (const step of this.steps) {
133
+ const rx = patternToRegex(step.pattern);
134
+ const m = rx.exec(lineText);
135
+ if (!m?.groups) continue;
136
+
137
+ // Split pattern into alternating [literal, placeholder, literal, ...]
138
+ const segments = step.pattern.split(/(\{[^}]{1,200}\})/);
139
+
140
+ let pos = 0; // cursor into lineText as we consume each segment
141
+ let paramIdx = 0; // index into step.parameters
142
+
143
+ for (let i = 0; i < segments.length; i++) {
144
+ if (i % 2 === 0) {
145
+ // literal segment — advance pos by its length
146
+ pos += segments[i].length;
147
+ } else {
148
+ // parameter placeholder — the captured value starts at pos
149
+ const name = segments[i].replace(/^\{(\w+)(?::[^}]{1,200})?\}$/, '$1');
150
+ const value = m.groups[name];
151
+ if (value !== undefined) {
152
+ const valueStart = pos;
153
+ const valueEnd = pos + value.length;
154
+ if (column >= valueStart && column <= valueEnd) {
155
+ const param = step.parameters[paramIdx];
156
+ if (param) {
157
+ return { parameter: param, valueStart, valueEnd };
158
+ }
159
+ }
160
+ pos = valueEnd;
161
+ }
162
+ paramIdx++;
163
+ }
164
+ }
165
+ }
166
+ return null;
167
+ }
168
+ }
@@ -0,0 +1,48 @@
1
+ // Copyright (c) 2026 Nigel O'Keefe. All rights reserved.
2
+ // Licensed under the MIT License.
3
+ //
4
+ // Generates a pytest-bdd step function stub for an unimplemented step.
5
+
6
+ const PARAM_RE = /\{(\w+)(?::[^}]{1,200})?\}/g;
7
+
8
+ const KEYWORD_TO_DECORATOR: Record<string, string> = {
9
+ given: 'given',
10
+ when: 'when',
11
+ then: 'then',
12
+ };
13
+
14
+ /** Convert a step pattern to a Python snake_case function name. */
15
+ export function patternToFunctionName(pattern: string): string {
16
+ return pattern
17
+ .replace(new RegExp(PARAM_RE.source, 'g'), '$1')
18
+ .replace(/[^\w\s]/g, ' ')
19
+ .trim()
20
+ .replace(/\s+/g, '_')
21
+ .replace(/_+/g, '_')
22
+ .toLowerCase();
23
+ }
24
+
25
+ /**
26
+ * A Python step function stub for *stepText*.
27
+ *
28
+ * And/But map to `step`, since pytest-bdd has no decorator for them — they bind
29
+ * to whichever of given/when/then precedes them at runtime.
30
+ */
31
+ export function buildStepStub(stepText: string, keyword: string): string {
32
+ const decorator = KEYWORD_TO_DECORATOR[keyword.toLowerCase()] ?? 'step';
33
+
34
+ const paramNames: string[] = [];
35
+ const re = new RegExp(PARAM_RE.source, 'g');
36
+ let m: RegExpExecArray | null;
37
+ while ((m = re.exec(stepText)) !== null) {
38
+ paramNames.push(m[1]);
39
+ }
40
+
41
+ const fnArgs = paramNames.length > 0 ? `(${paramNames.join(', ')})` : '()';
42
+
43
+ return [
44
+ `@${decorator}("${stepText}")`,
45
+ `def ${patternToFunctionName(stepText)}${fnArgs}:`,
46
+ ` raise NotImplementedError`,
47
+ ].join('\n');
48
+ }
@@ -0,0 +1,31 @@
1
+ // Copyright (c) 2026 Nigel O'Keefe. All rights reserved.
2
+ // Licensed under the MIT License.
3
+ //
4
+ // Finds steps in a feature file with no matching definition.
5
+
6
+ import type { StepCache } from './stepCache';
7
+ import { extractStepText } from '../completion/complete';
8
+
9
+ const COMMENT_RE = /^\s*#/;
10
+
11
+ export type UnimplementedStep = {
12
+ /** 0-indexed line. */
13
+ lineIndex: number;
14
+ /** Step text with the Gherkin keyword stripped. */
15
+ stepText: string;
16
+ };
17
+
18
+ /** Steps in *lines* that no definition in *cache* matches. Comments are skipped. */
19
+ export function findUnimplementedSteps(lines: string[], cache: StepCache): UnimplementedStep[] {
20
+ const results: UnimplementedStep[] = [];
21
+ for (let i = 0; i < lines.length; i++) {
22
+ const line = lines[i];
23
+ if (COMMENT_RE.test(line)) continue;
24
+ const parsed = extractStepText(line);
25
+ if (!parsed) continue;
26
+ if (!cache.matchPattern(parsed.text)) {
27
+ results.push({ lineIndex: i, stepText: parsed.text });
28
+ }
29
+ }
30
+ return results;
31
+ }
@@ -0,0 +1,52 @@
1
+ // Copyright (c) 2026 Nigel O'Keefe. All rights reserved.
2
+ // Licensed under the MIT License.
3
+ //
4
+ // Builds a document outline for a Gherkin file: the feature, with its scenarios
5
+ // and background beneath it.
6
+ //
7
+ // Returns plain nodes carrying a line number; hosts map `kind` onto their own
8
+ // symbol vocabulary and turn `line` into whatever range type they use.
9
+
10
+ import type { GherkinDocument } from '@cucumber/messages';
11
+
12
+ export type SymbolNodeKind = 'feature' | 'scenario';
13
+
14
+ export interface SymbolNode {
15
+ name: string;
16
+ /** Secondary text — tags, for scenarios. Empty when there is none. */
17
+ detail: string;
18
+ kind: SymbolNodeKind;
19
+ /** 0-indexed line the symbol starts on. */
20
+ line: number;
21
+ children: SymbolNode[];
22
+ }
23
+
24
+ export function buildSymbolTree(doc: GherkinDocument): SymbolNode[] {
25
+ if (!doc.feature) return [];
26
+
27
+ const feature = doc.feature;
28
+ const featureNode: SymbolNode = {
29
+ name: feature.name || '(unnamed feature)',
30
+ detail: '',
31
+ kind: 'feature',
32
+ line: (feature.location?.line ?? 1) - 1,
33
+ children: [],
34
+ };
35
+
36
+ for (const child of feature.children) {
37
+ const scenario = child.scenario ?? child.background;
38
+ if (!scenario) continue;
39
+
40
+ const tags = ('tags' in scenario ? scenario.tags ?? [] : []).map((t) => t.name).join(' ');
41
+
42
+ featureNode.children.push({
43
+ name: scenario.name || (child.background ? '(background)' : '(unnamed scenario)'),
44
+ detail: tags,
45
+ kind: 'scenario',
46
+ line: (scenario.location?.line ?? 1) - 1,
47
+ children: [],
48
+ });
49
+ }
50
+
51
+ return [featureNode];
52
+ }
@@ -0,0 +1,98 @@
1
+ // Copyright (c) 2026 Nigel O'Keefe. All rights reserved.
2
+ // Licensed under the MIT License.
3
+ //
4
+ // Computes semantic token positions for Gherkin tables — pipes, cells, and
5
+ // quoted cells, distinguished between datatables and Examples tables.
6
+ //
7
+ // Returns plain positions. Encoding them into whatever the host's highlighter
8
+ // expects, and declaring the legend, is the host's job.
9
+
10
+ import type { GherkinDocument, TableRow } from '@cucumber/messages';
11
+
12
+ export const TOKEN_TYPES = [
13
+ 'gherkinDatatablePipe',
14
+ 'gherkinDatatableCell',
15
+ 'gherkinDatatableCellString',
16
+ 'gherkinExamplesPipe',
17
+ 'gherkinExamplesCell',
18
+ 'gherkinExamplesCellString',
19
+ 'gherkinExamplesHeaderCell',
20
+ ] as const;
21
+
22
+ export type TokenType = (typeof TOKEN_TYPES)[number];
23
+
24
+ export interface TokenEntry {
25
+ line: number; // 0-indexed
26
+ startChar: number; // 0-indexed
27
+ length: number;
28
+ tokenType: TokenType;
29
+ }
30
+ function isQuoted(value: string): boolean {
31
+ const v = value.trim();
32
+ return (v.startsWith('"') && v.endsWith('"') && v.length >= 2) ||
33
+ (v.startsWith("'") && v.endsWith("'") && v.length >= 2);
34
+ }
35
+
36
+ function emitRow(
37
+ row: TableRow,
38
+ lines: string[],
39
+ pipeType: TokenType,
40
+ cellType: TokenType,
41
+ cellStringType: TokenType,
42
+ out: TokenEntry[],
43
+ ): void {
44
+ const lineIndex = row.location.line - 1;
45
+ const lineText = lines[lineIndex] ?? '';
46
+
47
+ const pipePositions: number[] = [];
48
+ for (let i = 0; i < lineText.length; i++) {
49
+ if (lineText[i] === '|') pipePositions.push(i);
50
+ }
51
+
52
+ for (const pos of pipePositions) {
53
+ out.push({ line: lineIndex, startChar: pos, length: 1, tokenType: pipeType });
54
+ }
55
+
56
+ row.cells.forEach((cell, i) => {
57
+ const start = pipePositions[i];
58
+ const end = pipePositions[i + 1];
59
+ if (start === undefined || end === undefined) return;
60
+ out.push({
61
+ line: lineIndex,
62
+ startChar: start + 1,
63
+ length: end - start - 1,
64
+ tokenType: isQuoted(cell.value) ? cellStringType : cellType,
65
+ });
66
+ });
67
+ }
68
+
69
+ export function buildTableTokens(doc: GherkinDocument, lines: string[]): TokenEntry[] {
70
+ const tokens: TokenEntry[] = [];
71
+
72
+ for (const child of doc.feature?.children ?? []) {
73
+ const scenario = child.scenario;
74
+ if (!scenario) continue;
75
+
76
+ for (const step of scenario.steps) {
77
+ if (step.dataTable) {
78
+ for (const row of step.dataTable.rows) {
79
+ emitRow(row, lines, 'gherkinDatatablePipe', 'gherkinDatatableCell', 'gherkinDatatableCellString', tokens);
80
+ }
81
+ }
82
+ }
83
+
84
+ for (const examples of scenario.examples) {
85
+ if (examples.tableHeader) {
86
+ emitRow(examples.tableHeader, lines, 'gherkinExamplesPipe', 'gherkinExamplesHeaderCell', 'gherkinExamplesHeaderCell', tokens);
87
+ }
88
+ for (const row of examples.tableBody) {
89
+ emitRow(row, lines, 'gherkinExamplesPipe', 'gherkinExamplesCell', 'gherkinExamplesCellString', tokens);
90
+ }
91
+ }
92
+ }
93
+
94
+ return tokens;
95
+ }
96
+
97
+ /** Position of each token type in the legend a host declares. */
98
+ export const TYPE_INDEX = Object.fromEntries(TOKEN_TYPES.map((t, i) => [t, i])) as Record<TokenType, number>;
@@ -0,0 +1,187 @@
1
+ // Copyright (c) 2026 Nigel O'Keefe. All rights reserved.
2
+ // Licensed under the MIT License.
3
+ //
4
+ // Computes the shape of the test tree from a discovery payload.
5
+ //
6
+ // Returns plain nodes. Turning them into whatever the host uses to display a
7
+ // tree — TestItems, for a VS Code host — is the host's job.
8
+
9
+ import * as path from 'path';
10
+ import type { DiscoveredTestItem, DiscoveredTestNode } from '../protocol/types';
11
+
12
+ export interface TreeNodeRange {
13
+ start: { line: number; character: number };
14
+ end: { line: number; character: number };
15
+ }
16
+
17
+ export interface TreeNodeUri {
18
+ /** Resolved against the run's working directory unless `absolute` is set. */
19
+ path: string;
20
+ absolute?: boolean;
21
+ }
22
+
23
+ export interface TreeNode {
24
+ id: string;
25
+ label: string;
26
+ uri: TreeNodeUri;
27
+ canResolveChildren: boolean;
28
+ tags: string[];
29
+ description?: string;
30
+ range?: TreeNodeRange;
31
+ children: TreeNode[];
32
+ }
33
+
34
+ export interface BuiltTree {
35
+ roots: TreeNode[];
36
+ /** Leaf node id → pytest runID. Hosts index their own items from this. */
37
+ idToRunId: Map<string, string>;
38
+ }
39
+
40
+ function toSentenceCase(s: string): string {
41
+ const spaced = s.replace(/_/g, ' ');
42
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
43
+ }
44
+
45
+ function isTestItem(node: DiscoveredTestNode | DiscoveredTestItem): node is DiscoveredTestItem {
46
+ return node.type_ === 'test';
47
+ }
48
+
49
+ function collectLeaves(node: DiscoveredTestNode | DiscoveredTestItem): DiscoveredTestItem[] {
50
+ if (isTestItem(node)) return [node];
51
+ const results: DiscoveredTestItem[] = [];
52
+ for (const child of node.children) {
53
+ results.push(...collectLeaves(child));
54
+ }
55
+ return results;
56
+ }
57
+
58
+ /** pytest reports line numbers 1-based, and as a string in some payloads. */
59
+ function toRange(lineno: number | string | undefined): TreeNodeRange | undefined {
60
+ const n = typeof lineno === 'string' ? parseInt(lineno, 10) : lineno;
61
+ if (n === undefined || !Number.isFinite(n) || n <= 0) return undefined;
62
+ return { start: { line: n - 1, character: 0 }, end: { line: n, character: 0 } };
63
+ }
64
+
65
+ function findChild(children: TreeNode[], id: string): TreeNode | undefined {
66
+ return children.find((c) => c.id === id);
67
+ }
68
+
69
+ /**
70
+ * Ensure a folder chain exists, returning the children array of the deepest one.
71
+ * An empty `parts` yields the roots, which is how a .feature file sitting at the
72
+ * workspace root is handled.
73
+ */
74
+ function ensureFolderPath(roots: TreeNode[], parts: string[]): TreeNode[] {
75
+ let children = roots;
76
+ for (const part of parts) {
77
+ let existing = findChild(children, part);
78
+ if (!existing) {
79
+ existing = {
80
+ id: part,
81
+ label: `${toSentenceCase(part)} 🗂`,
82
+ // Note: only the segment, not the accumulated path. A nested folder
83
+ // therefore claims <cwd>/<segment> rather than its true location.
84
+ // Preserved deliberately — changing it is a separate fix.
85
+ uri: { path: part },
86
+ canResolveChildren: true,
87
+ tags: [],
88
+ children: [],
89
+ };
90
+ children.push(existing);
91
+ }
92
+ children = existing.children;
93
+ }
94
+ return children;
95
+ }
96
+
97
+ /**
98
+ * Build the tree.
99
+ *
100
+ * BDD items — those carrying `feature_path` — are organised under a hierarchy
101
+ * mirroring the .feature file layout. Anything else falls back to a flat
102
+ * file-based hierarchy.
103
+ */
104
+ export function buildTestTree(rootNode: DiscoveredTestNode): BuiltTree {
105
+ const roots: TreeNode[] = [];
106
+ const idToRunId = new Map<string, string>();
107
+
108
+ const leaves = collectLeaves(rootNode);
109
+ const bddLeaves = leaves.filter((l) => l.feature_path !== undefined);
110
+ const plainLeaves = leaves.filter((l) => l.feature_path === undefined);
111
+
112
+ for (const leaf of bddLeaves) {
113
+ const featurePath = leaf.feature_path!;
114
+ const scenarioName = leaf.scenario_name ?? leaf.name;
115
+
116
+ const parsed = path.parse(featurePath);
117
+ const dirParts = parsed.dir ? parsed.dir.split('/') : [];
118
+ const folderChildren = ensureFolderPath(roots, dirParts);
119
+
120
+ let featureFile = findChild(folderChildren, featurePath);
121
+ if (!featureFile) {
122
+ const featureTags = leaf.feature_tags ?? [];
123
+ featureFile = {
124
+ id: featurePath,
125
+ label: `${leaf.feature_name ?? toSentenceCase(parsed.name)} 🗒`,
126
+ uri: { path: featurePath },
127
+ canResolveChildren: true,
128
+ tags: [...featureTags],
129
+ ...(featureTags.length
130
+ ? { description: featureTags.map((t) => `@${t}`).join(' ') }
131
+ : {}),
132
+ children: [],
133
+ };
134
+ folderChildren.push(featureFile);
135
+ }
136
+
137
+ const scenarioTags = leaf.scenario_tags ?? [];
138
+ const id = `${featurePath}::${scenarioName}`;
139
+ const range = toRange(leaf.lineno);
140
+ featureFile.children.push({
141
+ id,
142
+ label: scenarioName,
143
+ uri: { path: featurePath },
144
+ canResolveChildren: false,
145
+ tags: [...(leaf.feature_tags ?? []), ...scenarioTags],
146
+ ...(scenarioTags.length
147
+ ? { description: scenarioTags.map((t) => `@${t}`).join(' ') }
148
+ : {}),
149
+ ...(range ? { range } : {}),
150
+ children: [],
151
+ });
152
+
153
+ idToRunId.set(id, leaf.runID);
154
+ }
155
+
156
+ for (const leaf of plainLeaves) {
157
+ const filePath = leaf.path;
158
+
159
+ let fileNode = roots.find((n) => n.uri.absolute && n.uri.path === filePath);
160
+ if (!fileNode) {
161
+ fileNode = {
162
+ id: filePath,
163
+ label: path.basename(filePath),
164
+ uri: { path: filePath, absolute: true },
165
+ canResolveChildren: true,
166
+ tags: [],
167
+ children: [],
168
+ };
169
+ roots.push(fileNode);
170
+ }
171
+
172
+ const range = toRange(leaf.lineno);
173
+ fileNode.children.push({
174
+ id: leaf.id_,
175
+ label: leaf.name,
176
+ uri: { path: filePath, absolute: true },
177
+ canResolveChildren: false,
178
+ tags: [],
179
+ ...(range ? { range } : {}),
180
+ children: [],
181
+ });
182
+
183
+ idToRunId.set(leaf.id_, leaf.runID);
184
+ }
185
+
186
+ return { roots, idToRunId };
187
+ }