tolkira 0.2.0 → 0.3.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/GLOSSARY.md +93 -0
- package/README.md +207 -15
- package/SECURITY.md +3 -0
- package/dist/cli.js +1455 -579
- package/dist/cli.js.map +4 -4
- package/dist/compat/cucumber-html-reporter.cjs +12 -0
- package/dist/compat/cucumber-html-reporter.d.cts +10 -0
- package/dist/compat/cucumber-html-reporter.js +95 -24
- package/dist/compat/cucumber-html-reporter.js.map +4 -4
- package/dist/compat/options.d.ts +2 -0
- package/dist/index.d.ts +4 -7
- package/dist/index.js +1449 -552
- package/dist/index.js.map +4 -4
- package/dist/input/background.d.ts +4 -0
- package/dist/input/load.d.ts +2 -0
- package/dist/options.d.ts +12 -0
- package/dist/output.d.ts +2 -0
- package/dist/render/ansi.d.ts +2 -0
- package/dist/render/client-bundle.d.ts +1 -0
- package/dist/render/markdown.d.ts +1 -0
- package/dist/render/search.d.ts +18 -0
- package/dist/report/attachment.d.ts +10 -0
- package/dist/report/model.d.ts +85 -4
- package/dist/report/status.d.ts +12 -0
- package/dist/stream.d.ts +15 -0
- package/dist/summary.d.ts +14 -2
- package/dist/text.d.ts +15 -0
- package/docs/AGENT-INTERFACE.md +158 -21
- package/docs/COMPATIBILITY.md +51 -7
- package/docs/CUCUMBER-COMPATIBILITY.md +193 -0
- package/docs/JUNIT-XML.md +27 -2
- package/docs/LIMITATIONS.md +17 -0
- package/llms.txt +31 -0
- package/package.json +30 -8
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
function generate(options, callback) {
|
|
3
|
+
const promise = import('./cucumber-html-reporter.js').then((mod) => mod.generate(options, callback));
|
|
4
|
+
if (callback) {
|
|
5
|
+
// Callback-only callers ignore the returned promise; keep its rejection
|
|
6
|
+
// handled without changing what awaiting callers see.
|
|
7
|
+
promise.catch(() => undefined);
|
|
8
|
+
}
|
|
9
|
+
return promise;
|
|
10
|
+
}
|
|
11
|
+
const compat = { generate };
|
|
12
|
+
module.exports = compat;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { CompatResult, CucumberHtmlReporterOptions } from './options.js';
|
|
2
|
+
declare function generate(options: CucumberHtmlReporterOptions, callback?: (error?: Error | null) => void): Promise<CompatResult>;
|
|
3
|
+
declare const compat: {
|
|
4
|
+
generate: typeof generate;
|
|
5
|
+
};
|
|
6
|
+
declare namespace compat {
|
|
7
|
+
type CucumberHtmlReporterOptions = import('./options.js').CucumberHtmlReporterOptions;
|
|
8
|
+
type CompatResult = import('./options.js').CompatResult;
|
|
9
|
+
}
|
|
10
|
+
export = compat;
|
|
@@ -3,31 +3,13 @@ import { generateReport } from "../index.js";
|
|
|
3
3
|
|
|
4
4
|
// src/output.ts
|
|
5
5
|
import { randomUUID } from "node:crypto";
|
|
6
|
-
import {
|
|
7
|
-
import
|
|
8
|
-
|
|
9
|
-
const directory = path.dirname(output);
|
|
10
|
-
await mkdir(directory, { recursive: true });
|
|
11
|
-
const temp = path.join(
|
|
12
|
-
directory,
|
|
13
|
-
`.${path.basename(output)}.${randomUUID()}.tmp`
|
|
14
|
-
);
|
|
15
|
-
try {
|
|
16
|
-
await writeFile(temp, content, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
17
|
-
await rename(temp, output);
|
|
18
|
-
} catch (error) {
|
|
19
|
-
await rm(temp, { force: true }).catch(() => void 0);
|
|
20
|
-
throw error;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// src/compat/options.ts
|
|
25
|
-
import { readFile } from "node:fs/promises";
|
|
26
|
-
import path3 from "node:path";
|
|
6
|
+
import { realpathSync } from "node:fs";
|
|
7
|
+
import { mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
8
|
+
import path2 from "node:path";
|
|
27
9
|
|
|
28
10
|
// src/input/files.ts
|
|
29
11
|
import { readdir } from "node:fs/promises";
|
|
30
|
-
import
|
|
12
|
+
import path from "node:path";
|
|
31
13
|
var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
32
14
|
".json",
|
|
33
15
|
".jsonl",
|
|
@@ -46,14 +28,14 @@ async function collectReportFiles(directory, depth = 0) {
|
|
|
46
28
|
const files = [];
|
|
47
29
|
for (const entry of entries) {
|
|
48
30
|
if (entry.isSymbolicLink()) continue;
|
|
49
|
-
const full =
|
|
31
|
+
const full = path.join(directory, entry.name);
|
|
50
32
|
if (entry.isDirectory()) {
|
|
51
33
|
if (IGNORED_DIRECTORIES.has(entry.name)) continue;
|
|
52
34
|
files.push(...await collectReportFiles(full, depth + 1));
|
|
53
35
|
continue;
|
|
54
36
|
}
|
|
55
37
|
if (!entry.isFile()) continue;
|
|
56
|
-
if (!SUPPORTED_EXTENSIONS.has(
|
|
38
|
+
if (!SUPPORTED_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {
|
|
57
39
|
continue;
|
|
58
40
|
}
|
|
59
41
|
files.push(full);
|
|
@@ -61,6 +43,71 @@ async function collectReportFiles(directory, depth = 0) {
|
|
|
61
43
|
return files;
|
|
62
44
|
}
|
|
63
45
|
|
|
46
|
+
// src/output.ts
|
|
47
|
+
async function outputOverwritesInput(inputs, output, logo) {
|
|
48
|
+
const outputPath = path2.resolve(output);
|
|
49
|
+
const outputInfo = await stat(outputPath).catch(() => void 0);
|
|
50
|
+
if (!outputInfo?.isFile()) return false;
|
|
51
|
+
const outputReal = realpathSync(outputPath);
|
|
52
|
+
if (logo) {
|
|
53
|
+
const logoInfo = await stat(logo).catch(() => void 0);
|
|
54
|
+
if (logoInfo?.isFile() && realpathSync(logo) === outputReal) return true;
|
|
55
|
+
}
|
|
56
|
+
for (const input of inputs) {
|
|
57
|
+
const inputInfo = await stat(input).catch(() => void 0);
|
|
58
|
+
if (!inputInfo) continue;
|
|
59
|
+
if (inputInfo.isFile() && realpathSync(input) === outputReal) return true;
|
|
60
|
+
if (inputInfo.isDirectory()) {
|
|
61
|
+
const directory = realpathSync(input);
|
|
62
|
+
for (const file of await collectReportFiles(directory)) {
|
|
63
|
+
if (realpathSync(file) === outputReal) return true;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
async function writeAtomic(output, content) {
|
|
70
|
+
const directory = path2.dirname(output);
|
|
71
|
+
await mkdir(directory, { recursive: true });
|
|
72
|
+
const temp = path2.join(
|
|
73
|
+
directory,
|
|
74
|
+
`.${path2.basename(output)}.${randomUUID()}.tmp`
|
|
75
|
+
);
|
|
76
|
+
try {
|
|
77
|
+
await writeFile(temp, content, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
78
|
+
await rename(temp, output);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
await rm(temp, { force: true }).catch(() => void 0);
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// src/compat/options.ts
|
|
86
|
+
import { readFile, stat as stat2 } from "node:fs/promises";
|
|
87
|
+
import path3 from "node:path";
|
|
88
|
+
|
|
89
|
+
// src/input/legacy.ts
|
|
90
|
+
import {
|
|
91
|
+
AttachmentContentEncoding,
|
|
92
|
+
HookType,
|
|
93
|
+
TestStepResultStatus
|
|
94
|
+
} from "@cucumber/messages";
|
|
95
|
+
|
|
96
|
+
// src/input/messages.ts
|
|
97
|
+
import { TestStepResultStatus as TestStepResultStatus2 } from "@cucumber/messages";
|
|
98
|
+
var STATUS_VALUES = new Set(Object.values(TestStepResultStatus2));
|
|
99
|
+
|
|
100
|
+
// src/input/load.ts
|
|
101
|
+
var MAX_TOTAL_INPUT_BYTES = 100 * 1024 * 1024;
|
|
102
|
+
function addInputBytes(totalBytes, size) {
|
|
103
|
+
if (totalBytes + size > MAX_TOTAL_INPUT_BYTES) {
|
|
104
|
+
throw new Error(
|
|
105
|
+
"Inputs exceed 100 MB in total. Split the report or use external attachments."
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
return totalBytes + size;
|
|
109
|
+
}
|
|
110
|
+
|
|
64
111
|
// src/compat/options.ts
|
|
65
112
|
var HANDLED_OPTIONS = /* @__PURE__ */ new Set([
|
|
66
113
|
"jsonFile",
|
|
@@ -92,6 +139,11 @@ function warnIgnoredOptions(options, warnings) {
|
|
|
92
139
|
);
|
|
93
140
|
}
|
|
94
141
|
}
|
|
142
|
+
function inputRoot(options) {
|
|
143
|
+
const jsonFile = typeof options.jsonFile === "string" && options.jsonFile.trim() ? options.jsonFile.trim() : void 0;
|
|
144
|
+
if (jsonFile) return jsonFile;
|
|
145
|
+
return typeof options.jsonDir === "string" && options.jsonDir.trim() ? options.jsonDir.trim() : void 0;
|
|
146
|
+
}
|
|
95
147
|
function requireOutput(options) {
|
|
96
148
|
const output = typeof options.output === "string" ? options.output.trim() : "";
|
|
97
149
|
if (!output) throw new Error("compat: output is required");
|
|
@@ -143,7 +195,21 @@ async function resolveInputs(options, warnings) {
|
|
|
143
195
|
}
|
|
144
196
|
if (!options.ignoreBadJsonFile) return files;
|
|
145
197
|
const valid = [];
|
|
198
|
+
let totalBytes = 0;
|
|
146
199
|
for (const file of files) {
|
|
200
|
+
let info;
|
|
201
|
+
try {
|
|
202
|
+
info = await stat2(file);
|
|
203
|
+
} catch (error) {
|
|
204
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
205
|
+
warnings.push(`skipped invalid JSON file ${file}: ${detail}`);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (info.size > MAX_TOTAL_INPUT_BYTES) {
|
|
209
|
+
warnings.push(`skipped oversized JSON file ${file}: over 100 MB`);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
totalBytes = addInputBytes(totalBytes, info.size);
|
|
147
213
|
try {
|
|
148
214
|
const parsed = JSON.parse(await readFile(file, "utf8"));
|
|
149
215
|
if (!Array.isArray(parsed)) throw new Error("not a feature array");
|
|
@@ -164,6 +230,10 @@ async function run(options) {
|
|
|
164
230
|
const warnings = [];
|
|
165
231
|
const output = requireOutput(options);
|
|
166
232
|
warnIgnoredOptions(options, warnings);
|
|
233
|
+
const root = inputRoot(options);
|
|
234
|
+
if (root && await outputOverwritesInput([root], output)) {
|
|
235
|
+
throw new Error("compat: output must not overwrite an input file");
|
|
236
|
+
}
|
|
167
237
|
const inputs = await resolveInputs(options, warnings);
|
|
168
238
|
const title = mapTitle(options, warnings);
|
|
169
239
|
const metadata = flattenMetadata(options.metadata, warnings);
|
|
@@ -178,6 +248,7 @@ function generate(options, callback) {
|
|
|
178
248
|
() => callback(null),
|
|
179
249
|
(error) => callback(error instanceof Error ? error : new Error(String(error)))
|
|
180
250
|
);
|
|
251
|
+
promise.catch(() => void 0);
|
|
181
252
|
}
|
|
182
253
|
return promise;
|
|
183
254
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../src/compat/cucumber-html-reporter.ts", "../../src/output.ts", "../../src/compat/options.ts", "../../src/input/
|
|
4
|
-
"sourcesContent": ["import { generateReport } from '../index.js';\nimport { writeAtomic } from '../output.js';\nimport {\n flattenMetadata,\n mapTitle,\n requireOutput,\n resolveInputs,\n warnIgnoredOptions,\n} from './options.js';\nimport type { CompatResult, CucumberHtmlReporterOptions } from './options.js';\n\nexport type { CompatResult, CucumberHtmlReporterOptions } from './options.js';\n\nasync function run(\n options: CucumberHtmlReporterOptions,\n): Promise<CompatResult> {\n const warnings: string[] = [];\n const output = requireOutput(options);\n warnIgnoredOptions(options, warnings);\n const inputs = await resolveInputs(options, warnings);\n const title = mapTitle(options, warnings);\n const metadata = flattenMetadata(options.metadata, warnings);\n\n const { html, summary } = await generateReport(inputs, { title, metadata });\n await writeAtomic(output, html);\n\n return { output, warnings, summary };\n}\n\n/**\n * Drop-in for `cucumber-html-reporter`'s `generate(options, callback?)`.\n * The returned promise is additive; old callback-only callers still work.\n */\nexport function generate(\n options: CucumberHtmlReporterOptions,\n callback?: (error?: Error | null) => void,\n): Promise<CompatResult> {\n const promise = run(options);\n if (callback) {\n promise.then(\n () => callback(null),\n (error: unknown) =>\n callback(error instanceof Error ? error : new Error(String(error))),\n );\n }\n return promise;\n}\n", "import { randomUUID } from 'node:crypto';\nimport { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nexport async function writeAtomic(\n output: string,\n content: string,\n): Promise<void> {\n const directory = path.dirname(output);\n await mkdir(directory, { recursive: true });\n const temp = path.join(\n directory,\n `.${path.basename(output)}.${randomUUID()}.tmp`,\n );\n\n try {\n await writeFile(temp, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });\n await rename(temp, output);\n } catch (error) {\n await rm(temp, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n", "import { readFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport type { ReportSummary } from '../summary.js';\nimport { collectReportFiles } from '../input/files.js';\n\nexport interface CompatResult {\n output: string;\n warnings: string[];\n summary: ReportSummary;\n}\n\nexport interface CucumberHtmlReporterOptions {\n jsonFile?: string;\n jsonDir?: string;\n output?: string;\n theme?: string;\n name?: string;\n brandTitle?: string;\n metadata?: Record<string, unknown>;\n storeScreenshots?: boolean;\n screenshotsDirectory?: string;\n noInlineScreenshots?: boolean;\n launchReport?: boolean;\n ignoreBadJsonFile?: boolean;\n reportSuiteAsScenarios?: boolean;\n scenarioTimestamp?: boolean;\n columnLayout?: boolean;\n failedSummaryReport?: boolean;\n [key: string]: unknown;\n}\n\nconst HANDLED_OPTIONS = new Set([\n 'jsonFile',\n 'jsonDir',\n 'output',\n 'name',\n 'brandTitle',\n 'metadata',\n 'ignoreBadJsonFile',\n]);\n\nconst IGNORED_OPTIONS: Record<string, string> = {\n theme: 'ignored; Tolkira uses its own theme',\n reportSuiteAsScenarios: 'ignored; Tolkira uses its own scenario grouping',\n scenarioTimestamp: 'ignored; Tolkira shows the run timestamp',\n columnLayout: 'ignored; Tolkira uses its own layout',\n failedSummaryReport: 'ignored; Tolkira has its own failed-first view',\n storeScreenshots: 'ignored; attachments stay inline',\n screenshotsDirectory: 'ignored; attachments stay inline',\n noInlineScreenshots: 'ignored; attachments stay inline',\n launchReport: 'ignored; Tolkira never opens a browser',\n};\n\nexport function warnIgnoredOptions(\n options: CucumberHtmlReporterOptions,\n warnings: string[],\n): void {\n for (const key of Object.keys(options)) {\n if (HANDLED_OPTIONS.has(key)) continue;\n const value = options[key];\n if (value === undefined || value === false || value === '') continue;\n warnings.push(\n `${key}: ${IGNORED_OPTIONS[key] ?? 'not supported by Tolkira; ignored'}`,\n );\n }\n}\n\nexport function requireOutput(options: CucumberHtmlReporterOptions): string {\n const output =\n typeof options.output === 'string' ? options.output.trim() : '';\n if (!output) throw new Error('compat: output is required');\n return output;\n}\n\nexport function mapTitle(\n options: CucumberHtmlReporterOptions,\n warnings: string[],\n): string {\n const brand =\n typeof options.brandTitle === 'string' ? options.brandTitle.trim() : '';\n const name = typeof options.name === 'string' ? options.name.trim() : '';\n if (brand && name && brand !== name) {\n warnings.push('brandTitle and name differ; using brandTitle');\n }\n return brand || name || 'Tolkira report';\n}\n\nexport function flattenMetadata(\n value: unknown,\n warnings: string[],\n): Record<string, string> {\n if (value === undefined) return {};\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n warnings.push('metadata: expected an object; ignored');\n return {};\n }\n const result: Record<string, string> = {};\n for (const [key, raw] of Object.entries(value)) {\n if (typeof raw === 'string') {\n result[key] = raw;\n } else if (typeof raw === 'number' || typeof raw === 'boolean') {\n result[key] = String(raw);\n } else {\n warnings.push(\n `metadata.${key}: only string, number or boolean values are supported; ignored`,\n );\n }\n }\n return result;\n}\n\nexport async function resolveInputs(\n options: CucumberHtmlReporterOptions,\n warnings: string[],\n): Promise<string[]> {\n const jsonFile =\n typeof options.jsonFile === 'string' && options.jsonFile.trim()\n ? options.jsonFile.trim()\n : undefined;\n const jsonDir =\n typeof options.jsonDir === 'string' && options.jsonDir.trim()\n ? options.jsonDir.trim()\n : undefined;\n\n if (jsonFile && jsonDir) {\n warnings.push('jsonFile and jsonDir are both set; using jsonFile');\n }\n if (!jsonFile && !jsonDir) {\n throw new Error('compat: jsonFile or jsonDir is required');\n }\n if (jsonFile) return [jsonFile];\n\n const files = (await collectReportFiles(jsonDir!)).filter(\n (file) => path.extname(file).toLowerCase() === '.json',\n );\n if (files.length === 0) {\n throw new Error('No supported report files found.');\n }\n if (!options.ignoreBadJsonFile) return files;\n\n const valid: string[] = [];\n for (const file of files) {\n try {\n const parsed: unknown = JSON.parse(await readFile(file, 'utf8'));\n if (!Array.isArray(parsed)) throw new Error('not a feature array');\n valid.push(file);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n warnings.push(`skipped invalid JSON file ${file}: ${detail}`);\n }\n }\n if (valid.length === 0) {\n throw new Error(`No valid JSON reports in ${jsonDir}.`);\n }\n return valid;\n}\n", "import { readdir } from 'node:fs/promises';\nimport path from 'node:path';\n\nexport const SUPPORTED_EXTENSIONS = new Set([\n '.json',\n '.jsonl',\n '.ndjson',\n '.xml',\n]);\n\nconst MAX_DIRECTORY_DEPTH = 20;\nconst IGNORED_DIRECTORIES = new Set(['node_modules', '.git', '.hg', '.svn']);\n\nexport async function collectReportFiles(\n directory: string,\n depth = 0,\n): Promise<string[]> {\n if (depth > MAX_DIRECTORY_DEPTH) {\n throw new Error(\n `Input directory nesting exceeds ${MAX_DIRECTORY_DEPTH} levels: ${directory}`,\n );\n }\n const entries = await readdir(directory, { withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n // Symlinks could loop or read outside the input tree.\n if (entry.isSymbolicLink()) continue;\n const full = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n if (IGNORED_DIRECTORIES.has(entry.name)) continue;\n files.push(...(await collectReportFiles(full, depth + 1)));\n continue;\n }\n if (!entry.isFile()) continue;\n if (!SUPPORTED_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {\n continue;\n }\n files.push(full);\n }\n return files;\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,sBAAsB;;;ACA/B,SAAS,kBAAkB;AAC3B,SAAS,
|
|
6
|
-
"names": ["path", "path", "path"]
|
|
3
|
+
"sources": ["../../src/compat/cucumber-html-reporter.ts", "../../src/output.ts", "../../src/input/files.ts", "../../src/compat/options.ts", "../../src/input/legacy.ts", "../../src/input/messages.ts", "../../src/input/load.ts"],
|
|
4
|
+
"sourcesContent": ["import { generateReport } from '../index.js';\nimport { outputOverwritesInput, writeAtomic } from '../output.js';\nimport {\n flattenMetadata,\n inputRoot,\n mapTitle,\n requireOutput,\n resolveInputs,\n warnIgnoredOptions,\n} from './options.js';\nimport type { CompatResult, CucumberHtmlReporterOptions } from './options.js';\n\nexport type { CompatResult, CucumberHtmlReporterOptions } from './options.js';\n\nasync function run(\n options: CucumberHtmlReporterOptions,\n): Promise<CompatResult> {\n const warnings: string[] = [];\n const output = requireOutput(options);\n warnIgnoredOptions(options, warnings);\n const root = inputRoot(options);\n if (root && (await outputOverwritesInput([root], output))) {\n throw new Error('compat: output must not overwrite an input file');\n }\n const inputs = await resolveInputs(options, warnings);\n const title = mapTitle(options, warnings);\n const metadata = flattenMetadata(options.metadata, warnings);\n\n const { html, summary } = await generateReport(inputs, { title, metadata });\n await writeAtomic(output, html);\n\n return { output, warnings, summary };\n}\n\n/**\n * Drop-in for `cucumber-html-reporter`'s `generate(options, callback?)`.\n * The returned promise is additive; old callback-only callers still work.\n */\nexport function generate(\n options: CucumberHtmlReporterOptions,\n callback?: (error?: Error | null) => void,\n): Promise<CompatResult> {\n const promise = run(options);\n if (callback) {\n promise.then(\n () => callback(null),\n (error: unknown) =>\n callback(error instanceof Error ? error : new Error(String(error))),\n );\n // Callback-only callers ignore the returned promise; keep its rejection\n // handled without changing what awaiting callers see.\n promise.catch(() => undefined);\n }\n return promise;\n}\n", "import { randomUUID } from 'node:crypto';\nimport { realpathSync } from 'node:fs';\nimport { mkdir, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport { collectReportFiles } from './input/files.js';\n\n/** True when writing `output` would replace an input file or the logo. */\nexport async function outputOverwritesInput(\n inputs: string[],\n output: string,\n logo?: string,\n): Promise<boolean> {\n const outputPath = path.resolve(output);\n const outputInfo = await stat(outputPath).catch(() => undefined);\n if (!outputInfo?.isFile()) return false;\n const outputReal = realpathSync(outputPath);\n\n if (logo) {\n const logoInfo = await stat(logo).catch(() => undefined);\n if (logoInfo?.isFile() && realpathSync(logo) === outputReal) return true;\n }\n\n for (const input of inputs) {\n const inputInfo = await stat(input).catch(() => undefined);\n if (!inputInfo) continue;\n if (inputInfo.isFile() && realpathSync(input) === outputReal) return true;\n if (inputInfo.isDirectory()) {\n const directory = realpathSync(input);\n for (const file of await collectReportFiles(directory)) {\n if (realpathSync(file) === outputReal) return true;\n }\n }\n }\n return false;\n}\n\nexport async function writeAtomic(\n output: string,\n content: string,\n): Promise<void> {\n const directory = path.dirname(output);\n await mkdir(directory, { recursive: true });\n const temp = path.join(\n directory,\n `.${path.basename(output)}.${randomUUID()}.tmp`,\n );\n\n try {\n await writeFile(temp, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });\n await rename(temp, output);\n } catch (error) {\n await rm(temp, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n", "import { readdir } from 'node:fs/promises';\nimport path from 'node:path';\n\nexport const SUPPORTED_EXTENSIONS = new Set([\n '.json',\n '.jsonl',\n '.ndjson',\n '.xml',\n]);\n\nconst MAX_DIRECTORY_DEPTH = 20;\nconst IGNORED_DIRECTORIES = new Set(['node_modules', '.git', '.hg', '.svn']);\n\nexport async function collectReportFiles(\n directory: string,\n depth = 0,\n): Promise<string[]> {\n if (depth > MAX_DIRECTORY_DEPTH) {\n throw new Error(\n `Input directory nesting exceeds ${MAX_DIRECTORY_DEPTH} levels: ${directory}`,\n );\n }\n const entries = await readdir(directory, { withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n // Symlinks could loop or read outside the input tree.\n if (entry.isSymbolicLink()) continue;\n const full = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n if (IGNORED_DIRECTORIES.has(entry.name)) continue;\n files.push(...(await collectReportFiles(full, depth + 1)));\n continue;\n }\n if (!entry.isFile()) continue;\n if (!SUPPORTED_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {\n continue;\n }\n files.push(full);\n }\n return files;\n}\n", "import { readFile, stat } from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport path from 'node:path';\nimport type { ReportSummary } from '../summary.js';\nimport { collectReportFiles } from '../input/files.js';\nimport { addInputBytes, MAX_TOTAL_INPUT_BYTES } from '../input/load.js';\n\nexport interface CompatResult {\n output: string;\n warnings: string[];\n summary: ReportSummary;\n}\n\nexport interface CucumberHtmlReporterOptions {\n jsonFile?: string;\n jsonDir?: string;\n output?: string;\n theme?: string;\n name?: string;\n brandTitle?: string;\n metadata?: Record<string, unknown>;\n storeScreenshots?: boolean;\n screenshotsDirectory?: string;\n noInlineScreenshots?: boolean;\n launchReport?: boolean;\n ignoreBadJsonFile?: boolean;\n reportSuiteAsScenarios?: boolean;\n scenarioTimestamp?: boolean;\n columnLayout?: boolean;\n failedSummaryReport?: boolean;\n [key: string]: unknown;\n}\n\nconst HANDLED_OPTIONS = new Set([\n 'jsonFile',\n 'jsonDir',\n 'output',\n 'name',\n 'brandTitle',\n 'metadata',\n 'ignoreBadJsonFile',\n]);\n\nconst IGNORED_OPTIONS: Record<string, string> = {\n theme: 'ignored; Tolkira uses its own theme',\n reportSuiteAsScenarios: 'ignored; Tolkira uses its own scenario grouping',\n scenarioTimestamp: 'ignored; Tolkira shows the run timestamp',\n columnLayout: 'ignored; Tolkira uses its own layout',\n failedSummaryReport: 'ignored; Tolkira has its own failed-first view',\n storeScreenshots: 'ignored; attachments stay inline',\n screenshotsDirectory: 'ignored; attachments stay inline',\n noInlineScreenshots: 'ignored; attachments stay inline',\n launchReport: 'ignored; Tolkira never opens a browser',\n};\n\nexport function warnIgnoredOptions(\n options: CucumberHtmlReporterOptions,\n warnings: string[],\n): void {\n for (const key of Object.keys(options)) {\n if (HANDLED_OPTIONS.has(key)) continue;\n const value = options[key];\n if (value === undefined || value === false || value === '') continue;\n warnings.push(\n `${key}: ${IGNORED_OPTIONS[key] ?? 'not supported by Tolkira; ignored'}`,\n );\n }\n}\n\n/** The configured input root: jsonFile wins over jsonDir, as in resolveInputs. */\nexport function inputRoot(\n options: CucumberHtmlReporterOptions,\n): string | undefined {\n const jsonFile =\n typeof options.jsonFile === 'string' && options.jsonFile.trim()\n ? options.jsonFile.trim()\n : undefined;\n if (jsonFile) return jsonFile;\n return typeof options.jsonDir === 'string' && options.jsonDir.trim()\n ? options.jsonDir.trim()\n : undefined;\n}\n\nexport function requireOutput(options: CucumberHtmlReporterOptions): string {\n const output =\n typeof options.output === 'string' ? options.output.trim() : '';\n if (!output) throw new Error('compat: output is required');\n return output;\n}\n\nexport function mapTitle(\n options: CucumberHtmlReporterOptions,\n warnings: string[],\n): string {\n const brand =\n typeof options.brandTitle === 'string' ? options.brandTitle.trim() : '';\n const name = typeof options.name === 'string' ? options.name.trim() : '';\n if (brand && name && brand !== name) {\n warnings.push('brandTitle and name differ; using brandTitle');\n }\n return brand || name || 'Tolkira report';\n}\n\nexport function flattenMetadata(\n value: unknown,\n warnings: string[],\n): Record<string, string> {\n if (value === undefined) return {};\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n warnings.push('metadata: expected an object; ignored');\n return {};\n }\n const result: Record<string, string> = {};\n for (const [key, raw] of Object.entries(value)) {\n if (typeof raw === 'string') {\n result[key] = raw;\n } else if (typeof raw === 'number' || typeof raw === 'boolean') {\n result[key] = String(raw);\n } else {\n warnings.push(\n `metadata.${key}: only string, number or boolean values are supported; ignored`,\n );\n }\n }\n return result;\n}\n\nexport async function resolveInputs(\n options: CucumberHtmlReporterOptions,\n warnings: string[],\n): Promise<string[]> {\n const jsonFile =\n typeof options.jsonFile === 'string' && options.jsonFile.trim()\n ? options.jsonFile.trim()\n : undefined;\n const jsonDir =\n typeof options.jsonDir === 'string' && options.jsonDir.trim()\n ? options.jsonDir.trim()\n : undefined;\n\n if (jsonFile && jsonDir) {\n warnings.push('jsonFile and jsonDir are both set; using jsonFile');\n }\n if (!jsonFile && !jsonDir) {\n throw new Error('compat: jsonFile or jsonDir is required');\n }\n if (jsonFile) return [jsonFile];\n\n const files = (await collectReportFiles(jsonDir!)).filter(\n (file) => path.extname(file).toLowerCase() === '.json',\n );\n if (files.length === 0) {\n throw new Error('No supported report files found.');\n }\n if (!options.ignoreBadJsonFile) return files;\n\n const valid: string[] = [];\n let totalBytes = 0;\n for (const file of files) {\n let info: Stats;\n try {\n info = await stat(file);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n warnings.push(`skipped invalid JSON file ${file}: ${detail}`);\n continue;\n }\n if (info.size > MAX_TOTAL_INPUT_BYTES) {\n warnings.push(`skipped oversized JSON file ${file}: over 100 MB`);\n continue;\n }\n totalBytes = addInputBytes(totalBytes, info.size);\n try {\n const parsed: unknown = JSON.parse(await readFile(file, 'utf8'));\n if (!Array.isArray(parsed)) throw new Error('not a feature array');\n valid.push(file);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n warnings.push(`skipped invalid JSON file ${file}: ${detail}`);\n }\n }\n if (valid.length === 0) {\n throw new Error(`No valid JSON reports in ${jsonDir}.`);\n }\n return valid;\n}\n", "import {\n AttachmentContentEncoding,\n HookType,\n TestStepResultStatus,\n} from '@cucumber/messages';\nimport { markSyntheticBackground } from './background.js';\nimport type {\n Attachment,\n Background,\n DataTable,\n DocString,\n Duration,\n Envelope,\n Feature,\n FeatureChild,\n Hook,\n Location,\n Meta,\n Pickle,\n PickleStep,\n Scenario,\n Step,\n TableRow,\n Tag,\n TestCase,\n TestStep,\n TestStepResult,\n Timestamp,\n} from '@cucumber/messages';\n\ninterface LegacyTag {\n name?: string;\n line?: number;\n}\n\ntype LegacyTags = Array<LegacyTag | string> | undefined;\n\ninterface LegacyArgument {\n content?: string;\n line?: number;\n rows?: Array<{ cells?: string[] }>;\n}\n\ninterface LegacyEmbedding {\n data?: string;\n media?: { type?: string };\n mime_type?: string;\n}\n\ninterface LegacyResult {\n status?: string;\n duration?: number;\n error_message?: string;\n}\n\ninterface LegacyDocString {\n content?: string;\n value?: string;\n line?: number;\n contentType?: string;\n content_type?: string;\n}\n\ninterface LegacyStep {\n keyword?: string;\n name?: string;\n text?: string;\n line?: number;\n hidden?: boolean;\n result?: LegacyResult;\n embeddings?: LegacyEmbedding[];\n arguments?: LegacyArgument[];\n docString?: string | LegacyDocString;\n rows?: Array<{ cells?: string[] }>;\n table?:\n | { headings?: string[]; rows?: string[][] }\n | { rows?: Array<{ cells?: string[] }> }\n | Array<{ cells?: string[] }>;\n match?: { location?: string };\n}\n\ninterface LegacyElement {\n keyword?: string;\n type?: string;\n name?: string;\n description?: string | string[];\n line?: number;\n location?: string;\n status?: string;\n tags?: LegacyTags;\n steps?: LegacyStep[];\n before?: LegacyStep[];\n after?: LegacyStep[];\n}\n\ninterface LegacyFeature {\n uri?: string;\n location?: string;\n keyword?: string;\n name?: string;\n description?: string | string[];\n line?: number;\n tags?: LegacyTags;\n elements?: LegacyElement[];\n}\n\ninterface LegacyJsonOptions {\n idPrefix?: string;\n startedAt?: Date;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nconst LEGACY_STATUSES = new Set([\n 'passed',\n 'failed',\n 'skipped',\n 'pending',\n 'undefined',\n 'ambiguous',\n 'unknown',\n]);\n\nfunction invalidLegacy(source: string, detail: string): Error {\n return new Error(`Invalid legacy JSON in ${source}: ${detail}`);\n}\n\nfunction validateStep(\n step: Record<string, unknown>,\n source: string,\n where: string,\n): void {\n if (step.embeddings !== undefined && !Array.isArray(step.embeddings)) {\n throw invalidLegacy(source, `${where}.embeddings must be an array.`);\n }\n for (const embedding of step.embeddings ?? []) {\n if (\n !isRecord(embedding) ||\n (embedding.data !== undefined && typeof embedding.data !== 'string')\n ) {\n throw invalidLegacy(source, `${where}.embeddings entries must have string data.`);\n }\n if (\n embedding.media !== undefined &&\n (!isRecord(embedding.media) ||\n (embedding.media.type !== undefined &&\n typeof embedding.media.type !== 'string'))\n ) {\n throw invalidLegacy(source, `${where}.embeddings media type must be a string.`);\n }\n if (\n embedding.mime_type !== undefined &&\n typeof embedding.mime_type !== 'string'\n ) {\n throw invalidLegacy(source, `${where}.embeddings mime_type must be a string.`);\n }\n }\n if (step.arguments !== undefined && !Array.isArray(step.arguments)) {\n throw invalidLegacy(source, `${where}.arguments must be an array.`);\n }\n if (step.result !== undefined) {\n if (!isRecord(step.result)) {\n throw invalidLegacy(source, `${where}.result must be an object.`);\n }\n if (\n step.result.status !== undefined &&\n (typeof step.result.status !== 'string' ||\n !LEGACY_STATUSES.has(step.result.status.toLowerCase()))\n ) {\n throw invalidLegacy(source, `${where}.result.status must be a known status.`);\n }\n }\n if (\n step.docString !== undefined &&\n typeof step.docString !== 'string' &&\n !isRecord(step.docString)\n ) {\n throw invalidLegacy(source, `${where}.docString must be a string or object.`);\n }\n if (step.rows !== undefined && !Array.isArray(step.rows)) {\n throw invalidLegacy(source, `${where}.rows must be an array.`);\n }\n}\n\nfunction validateLegacyFeatures(\n values: unknown[],\n source: string,\n): asserts values is LegacyFeature[] {\n for (const [featureIndex, feature] of values.entries()) {\n if (!isRecord(feature)) {\n throw invalidLegacy(source, `feature ${featureIndex + 1} must be an object.`);\n }\n\n if (feature.elements !== undefined && !Array.isArray(feature.elements)) {\n throw invalidLegacy(\n source,\n `feature ${featureIndex + 1}.elements must be an array.`,\n );\n }\n if (feature.uri !== undefined && typeof feature.uri !== 'string') {\n throw invalidLegacy(source, `feature ${featureIndex + 1}.uri must be a string.`);\n }\n if (feature.location !== undefined && typeof feature.location !== 'string') {\n throw invalidLegacy(\n source,\n `feature ${featureIndex + 1}.location must be a string.`,\n );\n }\n if (\n feature.description !== undefined &&\n typeof feature.description !== 'string' &&\n !Array.isArray(feature.description)\n ) {\n throw invalidLegacy(\n source,\n `feature ${featureIndex + 1}.description must be a string or array.`,\n );\n }\n if (feature.tags !== undefined && !Array.isArray(feature.tags)) {\n throw invalidLegacy(\n source,\n `feature ${featureIndex + 1}.tags must be an array.`,\n );\n }\n\n for (const [elementIndex, element] of (feature.elements ?? []).entries()) {\n if (!isRecord(element)) {\n throw invalidLegacy(\n source,\n `feature ${featureIndex + 1} element ${elementIndex + 1} must be an object.`,\n );\n }\n const where = `feature ${featureIndex + 1} element ${elementIndex + 1}`;\n if (element.steps !== undefined && !Array.isArray(element.steps)) {\n throw invalidLegacy(source, `${where}.steps must be an array.`);\n }\n if (element.before !== undefined && !Array.isArray(element.before)) {\n throw invalidLegacy(source, `${where}.before must be an array.`);\n }\n if (element.after !== undefined && !Array.isArray(element.after)) {\n throw invalidLegacy(source, `${where}.after must be an array.`);\n }\n if (element.tags !== undefined && !Array.isArray(element.tags)) {\n throw invalidLegacy(source, `${where}.tags must be an array.`);\n }\n if (\n element.description !== undefined &&\n typeof element.description !== 'string' &&\n !Array.isArray(element.description)\n ) {\n throw invalidLegacy(\n source,\n `${where}.description must be a string or array.`,\n );\n }\n for (const [stepIndex, step] of (element.steps ?? []).entries()) {\n if (!isRecord(step)) {\n throw invalidLegacy(\n source,\n `${where} step ${stepIndex + 1} must be an object.`,\n );\n }\n validateStep(step, source, `${where} step ${stepIndex + 1}`);\n }\n for (const [stepIndex, step] of [\n ...(element.before ?? []),\n ...(element.after ?? []),\n ].entries()) {\n if (!isRecord(step)) {\n throw invalidLegacy(source, `${where} hook ${stepIndex + 1} must be an object.`);\n }\n validateStep(step, source, `${where} hook ${stepIndex + 1}`);\n }\n }\n }\n}\n\ninterface StepPlan {\n testStep: TestStep;\n legacyStep: LegacyStep;\n}\n\nfunction createIdFactory(prefix: string): (kind: string) => string {\n let counter = 0;\n return (kind: string) => `${prefix}-${kind}-${counter++}`;\n}\n\nfunction normalizeUri(uri: string | undefined, index: number): string {\n if (!uri) return `features/legacy-${index}.feature`;\n const slashed = uri.replace(/\\\\/g, '/').replace(/^file:\\/\\/+/i, '');\n const normalized = slashed.replace(/^\\.\\//, '');\n if (/^[a-z]:\\//i.test(normalized) || slashed.startsWith('/')) {\n const marker = slashed.lastIndexOf('/features/');\n if (marker >= 0) return slashed.slice(marker + 1);\n const parts = slashed.split('/').filter(Boolean);\n return parts[parts.length - 1] ?? `features/legacy-${index}.feature`;\n }\n return normalized || `features/legacy-${index}.feature`;\n}\n\nfunction normalizeText(value: string | string[] | undefined): string {\n if (Array.isArray(value)) return value.join('\\n');\n return value ?? '';\n}\n\nfunction normalizeTags(tags: LegacyTags): LegacyTag[] {\n return (tags ?? []).map((tag) => (typeof tag === 'string' ? { name: tag } : tag));\n}\n\nfunction location(line?: number, column?: number): Location {\n return column === undefined ? { line: line ?? 1 } : { line: line ?? 1, column };\n}\n\nfunction timestamp(seconds: number, nanos = 0): Timestamp {\n return { seconds, nanos };\n}\n\nfunction duration(nanoseconds?: number): Duration {\n const value = Math.max(0, Math.round(nanoseconds ?? 0));\n return {\n seconds: Math.floor(value / 1_000_000_000),\n nanos: value % 1_000_000_000,\n };\n}\n\nfunction isBehaveFeature(feature: LegacyFeature): boolean {\n return (feature.elements ?? []).some(\n (element) =>\n typeof element.status === 'string' ||\n (typeof element.location === 'string' && element.line === undefined),\n );\n}\n\nfunction addDuration(base: Timestamp, value: Duration): Timestamp {\n let seconds = base.seconds + value.seconds;\n let nanos = base.nanos + value.nanos;\n if (nanos >= 1_000_000_000) {\n seconds += Math.floor(nanos / 1_000_000_000);\n nanos %= 1_000_000_000;\n }\n return { seconds, nanos };\n}\n\nfunction statusOf(value: string | undefined): TestStepResultStatus {\n switch ((value ?? '').toLowerCase()) {\n case 'passed':\n return TestStepResultStatus.PASSED;\n case 'failed':\n return TestStepResultStatus.FAILED;\n case 'skipped':\n return TestStepResultStatus.SKIPPED;\n case 'pending':\n return TestStepResultStatus.PENDING;\n case 'undefined':\n return TestStepResultStatus.UNDEFINED;\n case 'ambiguous':\n return TestStepResultStatus.AMBIGUOUS;\n default:\n return TestStepResultStatus.UNKNOWN;\n }\n}\n\nfunction isHook(step: LegacyStep): boolean {\n if (step.hidden === true) return true;\n return /^(before|after)\\b/i.test((step.keyword ?? '').trim());\n}\n\nfunction isBackgroundElement(element: LegacyElement): boolean {\n return (\n (element.type ?? '').toLowerCase() === 'background' ||\n /^background\\b/i.test((element.keyword ?? '').trim())\n );\n}\n\nfunction mapTags(tags: LegacyTags, nextId: (kind: string) => string): Tag[] {\n return normalizeTags(tags).map((tag) => ({\n id: nextId('tag'),\n name: tag.name ?? '',\n location: location(tag.line),\n }));\n}\n\nfunction mapDataTable(\n rows: Array<{ cells?: string[] }> | undefined,\n line: number | undefined,\n nextId: (kind: string) => string,\n): DataTable {\n return {\n location: location(line),\n rows: (rows ?? []).map(\n (row): TableRow => ({\n id: nextId('row'),\n location: location(line),\n cells: (row.cells ?? []).map((value) => ({\n location: location(line),\n value,\n })),\n }),\n ),\n };\n}\n\nfunction mapDocString(\n content: string,\n line: number | undefined,\n): DocString {\n return {\n location: location(line),\n content,\n delimiter: '\"\"\"',\n };\n}\n\nfunction tableRows(\n table: LegacyStep['table'],\n): Array<{ cells?: string[] }> | undefined {\n if (table === undefined) return undefined;\n if (Array.isArray(table)) return table;\n if ('headings' in table && table.headings && table.rows) {\n return [\n { cells: table.headings },\n ...table.rows.map((row) => ({ cells: row })),\n ];\n }\n if ('rows' in table && table.rows) {\n if (Array.isArray(table.rows[0])) {\n return (table.rows as string[][]).map((cells) => ({ cells }));\n }\n return table.rows as Array<{ cells?: string[] }>;\n }\n return undefined;\n}\n\nfunction stepArgument(legacyStep: LegacyStep): {\n content?: string;\n rows?: Array<{ cells?: string[] }>;\n line?: number;\n} {\n const argument = legacyStep.arguments?.[0];\n if (argument) return argument;\n\n if (legacyStep.docString !== undefined) {\n const docString =\n typeof legacyStep.docString === 'string'\n ? { content: legacyStep.docString }\n : legacyStep.docString;\n return {\n content: docString.content ?? docString.value ?? '',\n line: docString.line ?? legacyStep.line,\n };\n }\n\n if (legacyStep.text !== undefined) {\n return { content: legacyStep.text, line: legacyStep.line };\n }\n\n const rows = tableRows(legacyStep.rows ?? legacyStep.table);\n if (rows !== undefined) {\n return { rows, line: legacyStep.line };\n }\n\n return {};\n}\n\nfunction mapStepArguments(\n legacyStep: LegacyStep,\n nextId: (kind: string) => string,\n): { docString?: DocString; dataTable?: DataTable } {\n const argument = stepArgument(legacyStep);\n if (argument.rows !== undefined) {\n return {\n dataTable: mapDataTable(argument.rows, argument.line, nextId),\n };\n }\n if (argument.content !== undefined) {\n return { docString: mapDocString(argument.content, argument.line) };\n }\n return {};\n}\n\nfunction mapStep(\n legacyStep: LegacyStep,\n nextId: (kind: string) => string,\n): Step {\n const mapped: Step = {\n id: nextId('step'),\n location: location(legacyStep.line),\n keyword: (legacyStep.keyword ?? 'Given').trim() || 'Given',\n text: legacyStep.name ?? '',\n };\n const args = mapStepArguments(legacyStep, nextId);\n if (args.docString) mapped.docString = args.docString;\n if (args.dataTable) mapped.dataTable = args.dataTable;\n return mapped;\n}\n\nfunction mapPickleArgument(\n legacyStep: LegacyStep,\n): PickleStep['argument'] {\n const argument = stepArgument(legacyStep);\n if (argument.rows !== undefined) {\n return {\n dataTable: {\n rows: (argument.rows ?? []).map((row) => ({\n cells: (row.cells ?? []).map((value) => ({ value })),\n })),\n },\n };\n }\n if (argument.content !== undefined) {\n return { docString: { content: argument.content } };\n }\n return undefined;\n}\n\nfunction resultOf(legacyStep: LegacyStep, scale = 1): TestStepResult {\n const raw = legacyStep.result;\n const message = raw?.error_message;\n const result: TestStepResult = {\n status: statusOf(raw?.status),\n duration: duration((raw?.duration ?? 0) * scale),\n };\n if (message) {\n result.message = message;\n result.exception = { type: 'Error', message };\n }\n return result;\n}\n\nfunction isLikelyBase64(value: string): boolean {\n const compact = value.replace(/\\s/g, '');\n return (\n compact.length > 0 &&\n compact.length % 4 === 0 &&\n /^[A-Za-z0-9+/]*={0,2}$/.test(compact)\n );\n}\n\nexport function parseLegacyJson(\n content: string,\n source: string,\n options: LegacyJsonOptions = {},\n): Envelope[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content.replace(/^\\uFEFF/, ''));\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid legacy JSON in ${source}: ${detail}`);\n }\n return parseLegacyValue(parsed, source, options);\n}\n\nexport function parseLegacyValue(\n parsed: unknown,\n source: string,\n options: LegacyJsonOptions = {},\n): Envelope[] {\n if (!Array.isArray(parsed)) {\n throw new Error(`Invalid legacy JSON in ${source}: expected an array of features.`);\n }\n\n validateLegacyFeatures(parsed, source);\n const features = parsed;\n const nextId = createIdFactory(options.idPrefix ?? 'legacy');\n const startedAt = Math.floor((options.startedAt ?? new Date()).getTime() / 1000);\n const runId = nextId('run');\n const envelopes: Envelope[] = [];\n const statuses: TestStepResultStatus[] = [];\n\n const meta: Meta = {\n protocolVersion: '',\n implementation: { name: 'tolkira-legacy-json' },\n runtime: { name: '' },\n os: { name: '' },\n cpu: { name: '' },\n };\n envelopes.push({ meta });\n envelopes.push({ testRunStarted: { id: runId, timestamp: timestamp(startedAt) } });\n\n let clock = timestamp(startedAt);\n\n for (const [featureIndex, legacyFeature] of features.entries()) {\n const uri = normalizeUri(\n legacyFeature.uri ?? legacyFeature.location?.replace(/:\\d+$/, ''),\n featureIndex,\n );\n const durationScale = isBehaveFeature(legacyFeature) ? 1_000_000_000 : 1;\n const featureTags = mapTags(legacyFeature.tags, nextId);\n const featureChildren: FeatureChild[] = [];\n const scenarioEnvelopes: Envelope[] = [];\n const featureNode: Feature = {\n location: location(legacyFeature.line),\n tags: featureTags,\n language: 'en',\n keyword: 'Feature',\n name: legacyFeature.name ?? `Feature ${featureIndex + 1}`,\n description: normalizeText(legacyFeature.description),\n children: [],\n };\n\n const backgroundElement = (legacyFeature.elements ?? []).find(\n isBackgroundElement,\n );\n const backgroundSteps = (backgroundElement?.steps ?? []).filter(\n (step) => !isHook(step),\n );\n const backgroundNodes = backgroundSteps.map((step) => mapStep(step, nextId));\n\n if (backgroundElement) {\n const background: Background = {\n id: nextId('background'),\n location: location(backgroundElement.line),\n keyword: 'Background',\n name: backgroundElement.name ?? 'Background',\n description: normalizeText(backgroundElement.description),\n steps: backgroundNodes,\n };\n markSyntheticBackground(background);\n featureChildren.push({ background });\n }\n\n const scenarios: LegacyElement[] = (legacyFeature.elements ?? []).filter(\n (element) => !isBackgroundElement(element),\n );\n\n // Legacy producers repeat inherited feature tags on every element; the\n // scenario AST node keeps only its own tags so rows do not repeat them.\n const featureTagNames = new Set(featureTags.map((tag) => tag.name));\n\n for (const [scenarioIndex, element] of scenarios.entries()) {\n const scenarioId = nextId('scenario');\n const scenarioTags = mapTags(element.tags, nextId).filter(\n (tag) => !featureTagNames.has(tag.name),\n );\n const scenarioSteps = (element.steps ?? []).filter((step) => !isHook(step));\n const stepNodes = scenarioSteps.map((step) => mapStep(step, nextId));\n const backgroundInline =\n backgroundSteps.length > 0 &&\n backgroundSteps.every((backgroundStep) =>\n scenarioSteps.some(\n (step) =>\n step.name === backgroundStep.name &&\n (step.keyword ?? '').trim() ===\n (backgroundStep.keyword ?? '').trim(),\n ),\n );\n const executableSteps = backgroundInline\n ? scenarioSteps\n : [...backgroundSteps, ...scenarioSteps];\n const executableNodes = backgroundInline\n ? stepNodes\n : [...backgroundNodes, ...stepNodes];\n\n const scenario: Scenario = {\n id: scenarioId,\n location: location(element.line),\n tags: scenarioTags,\n keyword: (element.keyword ?? 'Scenario').trim() || 'Scenario',\n name: element.name ?? `Scenario ${scenarioIndex + 1}`,\n description: normalizeText(element.description),\n steps: stepNodes,\n examples: [],\n };\n featureChildren.push({ scenario });\n\n const pickleSteps: PickleStep[] = executableSteps.map(\n (legacyStep, index) => {\n const step = executableNodes[index] as Step;\n const pickleStep: PickleStep = {\n id: nextId('pickle-step'),\n text: step.text,\n astNodeIds: [step.id],\n };\n const argument = mapPickleArgument(legacyStep);\n if (argument) pickleStep.argument = argument;\n return pickleStep;\n },\n );\n\n const pickle: Pickle = {\n id: nextId('pickle'),\n uri,\n location: location(element.line),\n name: scenario.name,\n language: 'en',\n steps: pickleSteps,\n tags: [...featureTags, ...scenarioTags].map((tag) => ({\n name: tag.name,\n astNodeId: tag.id,\n })),\n astNodeIds: [scenario.id],\n };\n\n const plans: StepPlan[] = [];\n const hooks: Envelope[] = [];\n const inlineHooks = (element.steps ?? []).filter((step) => isHook(step));\n const beforeHooks = [\n ...(element.before ?? []),\n ...inlineHooks.filter(\n (step) => !/^after/i.test((step.keyword ?? '').trim()),\n ),\n ];\n const afterHooks = [\n ...inlineHooks.filter((step) =>\n /^after/i.test((step.keyword ?? '').trim()),\n ),\n ...(element.after ?? []),\n ];\n\n for (const hookStep of beforeHooks) {\n const hookId = nextId('hook');\n const hook: Hook = {\n id: hookId,\n sourceReference: {\n uri,\n location: location(hookStep.line),\n },\n type: HookType.BEFORE_TEST_CASE,\n };\n hooks.push({ hook });\n plans.push({\n testStep: { id: nextId('test-step'), hookId },\n legacyStep: hookStep,\n });\n }\n\n for (const [index, pickleStep] of pickleSteps.entries()) {\n const legacyStep = executableSteps[index] as LegacyStep;\n plans.push({\n testStep: { id: nextId('test-step'), pickleStepId: pickleStep.id },\n legacyStep,\n });\n }\n\n for (const hookStep of afterHooks) {\n const hookId = nextId('hook');\n const hook: Hook = {\n id: hookId,\n sourceReference: {\n uri,\n location: location(hookStep.line),\n },\n type: HookType.AFTER_TEST_CASE,\n };\n hooks.push({ hook });\n plans.push({\n testStep: { id: nextId('test-step'), hookId },\n legacyStep: hookStep,\n });\n }\n\n const testCase: TestCase = {\n id: nextId('test-case'),\n pickleId: pickle.id,\n testSteps: plans.map((plan) => plan.testStep),\n testRunStartedId: runId,\n };\n const testCaseStartedId = nextId('test-case-started');\n\n scenarioEnvelopes.push({ pickle });\n scenarioEnvelopes.push(...hooks);\n scenarioEnvelopes.push({ testCase });\n scenarioEnvelopes.push({\n testCaseStarted: {\n id: testCaseStartedId,\n testCaseId: testCase.id,\n attempt: 0,\n timestamp: clock,\n },\n });\n\n for (const plan of plans) {\n scenarioEnvelopes.push({\n testStepStarted: {\n testCaseStartedId,\n testStepId: plan.testStep.id,\n timestamp: clock,\n },\n });\n\n const stepResult = resultOf(plan.legacyStep, durationScale);\n statuses.push(stepResult.status);\n const finishedAt = addDuration(clock, stepResult.duration);\n scenarioEnvelopes.push({\n testStepFinished: {\n testCaseStartedId,\n testStepId: plan.testStep.id,\n testStepResult: stepResult,\n timestamp: finishedAt,\n },\n });\n\n for (const embedding of plan.legacyStep.embeddings ?? []) {\n if (!embedding.data) continue;\n const mediaType =\n embedding.media?.type ??\n embedding.mime_type ??\n 'application/octet-stream';\n const attachment: Attachment = {\n body: embedding.data,\n contentEncoding: isLikelyBase64(embedding.data)\n ? AttachmentContentEncoding.BASE64\n : AttachmentContentEncoding.IDENTITY,\n mediaType,\n testCaseStartedId,\n testStepId: plan.testStep.id,\n timestamp: finishedAt,\n };\n scenarioEnvelopes.push({ attachment });\n }\n\n clock = finishedAt;\n }\n\n scenarioEnvelopes.push({\n testCaseFinished: {\n testCaseStartedId,\n timestamp: clock,\n willBeRetried: false,\n },\n });\n }\n\n // Emit the document before its pickles and test events so the renderer can\n // resolve the feature/scenario tree while consuming the stream.\n featureNode.children = featureChildren;\n envelopes.push({\n gherkinDocument: { uri, feature: featureNode, comments: [] },\n });\n // Spread would exceed the argument limit on very large feature files.\n for (const envelope of scenarioEnvelopes) envelopes.push(envelope);\n }\n\n const success = !statuses.some(\n (status) =>\n status === TestStepResultStatus.FAILED ||\n status === TestStepResultStatus.AMBIGUOUS ||\n status === TestStepResultStatus.UNDEFINED,\n );\n\n envelopes.push({\n testRunFinished: {\n testRunStartedId: runId,\n success,\n timestamp: clock,\n },\n });\n\n return envelopes;\n}\n", "import { TestStepResultStatus } from '@cucumber/messages';\nimport type { Envelope } from '@cucumber/messages';\n\nconst STATUS_VALUES = new Set(Object.values(TestStepResultStatus));\n\nconst ENVELOPE_KEYS = new Set([\n 'attachment',\n 'externalAttachment',\n 'gherkinDocument',\n 'hook',\n 'meta',\n 'parameterType',\n 'parseError',\n 'pickle',\n 'source',\n 'stepDefinition',\n 'suggestion',\n 'testCase',\n 'testCaseFinished',\n 'testCaseStarted',\n 'testRunFinished',\n 'testRunHookFinished',\n 'testRunHookStarted',\n 'testRunStarted',\n 'testStepFinished',\n 'testStepStarted',\n 'undefinedParameterType',\n]);\n\ntype JsonObject = Record<string, unknown>;\n\nfunction isObject(value: unknown): value is JsonObject {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\nfunction isArray(value: unknown): value is unknown[] {\n return Array.isArray(value);\n}\n\nfunction requireString(\n payload: JsonObject,\n field: string,\n key: string,\n source: string,\n line: number,\n): void {\n if (!isString(payload[field])) {\n throw new Error(\n `Invalid Cucumber Messages on line ${line} of ${source}: \"${key}.${field}\" must be a string.`,\n );\n }\n}\n\nfunction requireObject(\n payload: JsonObject,\n field: string,\n key: string,\n source: string,\n line: number,\n): void {\n if (!isObject(payload[field])) {\n throw new Error(\n `Invalid Cucumber Messages on line ${line} of ${source}: \"${key}.${field}\" must be an object.`,\n );\n }\n}\n\nfunction requireArray(\n payload: JsonObject,\n field: string,\n key: string,\n source: string,\n line: number,\n): void {\n if (!isArray(payload[field])) {\n throw new Error(\n `Invalid Cucumber Messages on line ${line} of ${source}: \"${key}.${field}\" must be an array.`,\n );\n }\n}\n\nfunction requireStepResult(\n payload: JsonObject,\n field: string,\n key: string,\n source: string,\n line: number,\n): void {\n requireObject(payload, field, key, source, line);\n const result = payload[field] as JsonObject;\n if (!isString(result.status) || !STATUS_VALUES.has(result.status as TestStepResultStatus)) {\n throw new Error(\n `Invalid Cucumber Messages on line ${line} of ${source}: \"${key}.${field}.status\" must be a known Cucumber status.`,\n );\n }\n if (!isObject(result.duration)) {\n throw new Error(\n `Invalid Cucumber Messages on line ${line} of ${source}: \"${key}.${field}.duration\" must be an object.`,\n );\n }\n for (const part of ['seconds', 'nanos']) {\n if (typeof result.duration[part] !== 'number') {\n throw new Error(\n `Invalid Cucumber Messages on line ${line} of ${source}: \"${key}.${field}.duration.${part}\" must be a number.`,\n );\n }\n }\n}\n\nfunction validatePayload(\n key: string,\n payload: JsonObject,\n source: string,\n line: number,\n): void {\n switch (key) {\n case 'meta':\n requireString(payload, 'protocolVersion', key, source, line);\n requireObject(payload, 'implementation', key, source, line);\n requireObject(payload, 'runtime', key, source, line);\n requireObject(payload, 'os', key, source, line);\n requireObject(payload, 'cpu', key, source, line);\n break;\n case 'source':\n requireString(payload, 'uri', key, source, line);\n requireString(payload, 'data', key, source, line);\n requireString(payload, 'mediaType', key, source, line);\n break;\n case 'gherkinDocument':\n requireArray(payload, 'comments', key, source, line);\n break;\n case 'pickle':\n requireString(payload, 'id', key, source, line);\n requireString(payload, 'uri', key, source, line);\n requireString(payload, 'name', key, source, line);\n requireArray(payload, 'steps', key, source, line);\n requireArray(payload, 'tags', key, source, line);\n requireArray(payload, 'astNodeIds', key, source, line);\n break;\n case 'testCase':\n requireString(payload, 'id', key, source, line);\n requireString(payload, 'pickleId', key, source, line);\n requireArray(payload, 'testSteps', key, source, line);\n break;\n case 'testCaseStarted':\n requireString(payload, 'id', key, source, line);\n requireString(payload, 'testCaseId', key, source, line);\n requireObject(payload, 'timestamp', key, source, line);\n break;\n case 'testStepStarted':\n requireString(payload, 'testCaseStartedId', key, source, line);\n requireString(payload, 'testStepId', key, source, line);\n requireObject(payload, 'timestamp', key, source, line);\n break;\n case 'testStepFinished':\n requireString(payload, 'testCaseStartedId', key, source, line);\n requireString(payload, 'testStepId', key, source, line);\n requireStepResult(payload, 'testStepResult', key, source, line);\n requireObject(payload, 'timestamp', key, source, line);\n break;\n case 'testCaseFinished':\n requireString(payload, 'testCaseStartedId', key, source, line);\n requireObject(payload, 'timestamp', key, source, line);\n break;\n case 'testRunStarted':\n requireObject(payload, 'timestamp', key, source, line);\n break;\n case 'testRunFinished':\n requireObject(payload, 'timestamp', key, source, line);\n if (typeof payload.success !== 'boolean') {\n throw new Error(\n `Invalid Cucumber Messages on line ${line} of ${source}: \"testRunFinished.success\" must be a boolean.`,\n );\n }\n break;\n case 'attachment':\n if (!isString(payload.body) && !isString(payload.url)) {\n throw new Error(\n `Invalid Cucumber Messages on line ${line} of ${source}: \"attachment.body\" or \"attachment.url\" is required.`,\n );\n }\n requireString(payload, 'mediaType', key, source, line);\n break;\n case 'externalAttachment':\n requireString(payload, 'url', key, source, line);\n requireString(payload, 'mediaType', key, source, line);\n break;\n case 'hook':\n requireString(payload, 'id', key, source, line);\n requireObject(payload, 'sourceReference', key, source, line);\n break;\n case 'testRunHookStarted':\n requireString(payload, 'id', key, source, line);\n requireString(payload, 'testRunStartedId', key, source, line);\n requireString(payload, 'hookId', key, source, line);\n requireObject(payload, 'timestamp', key, source, line);\n break;\n case 'testRunHookFinished':\n requireString(payload, 'testRunHookStartedId', key, source, line);\n requireStepResult(payload, 'result', key, source, line);\n requireObject(payload, 'timestamp', key, source, line);\n break;\n case 'parseError':\n requireString(payload, 'message', key, source, line);\n requireObject(payload, 'source', key, source, line);\n break;\n default:\n // Remaining known envelopes are passed to the renderer; their shape is\n // validated by the schema version that produced them.\n break;\n }\n}\n\nexport function isEnvelopeLike(value: unknown): value is Envelope {\n if (!isObject(value)) return false;\n const keys = Object.keys(value);\n return keys.length === 1 && ENVELOPE_KEYS.has(keys[0] ?? '');\n}\n\nexport function parseMessages(content: string, source: string): Envelope[] {\n const lines = content\n .split(/\\r?\\n/)\n .map((line, index) => ({\n text: line.replace(/^\\uFEFF/, '').trim(),\n number: index + 1,\n }))\n .filter((line) => line.text.length > 0);\n\n if (lines.length === 0) {\n throw new Error(`Input is empty: ${source}`);\n }\n\n return lines.map(({ text, number }) => {\n try {\n const value: unknown = JSON.parse(text);\n if (!isEnvelopeLike(value)) {\n throw new Error(\n 'expected a Cucumber Messages envelope with exactly one known key',\n );\n }\n\n const key = Object.keys(value)[0] as string;\n const payload = (value as JsonObject)[key];\n if (!isObject(payload)) {\n throw new Error(`\"${key}\" must be an object`);\n }\n validatePayload(key, payload, source, number);\n return value;\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n const clean = detail.replace(\n /^Invalid Cucumber Messages on line \\d+ of .*?: /,\n '',\n );\n throw new Error(\n `Invalid Cucumber Messages on line ${number} of ${source}: ${clean}`,\n );\n }\n });\n}\n", "import { createHash } from 'node:crypto';\nimport { readFile, realpath, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport type { Envelope } from '@cucumber/messages';\nimport { parseLegacyJson, parseLegacyValue } from './legacy.js';\nimport { collectReportFiles } from './files.js';\nimport { looksLikeJUnit, parseJUnitXml } from './junit.js';\nimport { isEnvelopeLike, parseMessages } from './messages.js';\n\nconst MESSAGES_EXTENSIONS = new Set(['.jsonl', '.ndjson']);\nexport const MAX_TOTAL_INPUT_BYTES = 100 * 1024 * 1024;\n\nexport function addInputBytes(totalBytes: number, size: number): number {\n if (totalBytes + size > MAX_TOTAL_INPUT_BYTES) {\n throw new Error(\n 'Inputs exceed 100 MB in total. Split the report or use external attachments.',\n );\n }\n return totalBytes + size;\n}\n\ntype JsonObject = Record<string, unknown>;\n\nfunction isObject(value: unknown): value is JsonObject {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isFeatureLike(value: unknown): boolean {\n return (\n isObject(value) &&\n (Array.isArray(value.elements) ||\n (typeof value.keyword === 'string' && typeof value.name === 'string'))\n );\n}\n\ntype LegacySniff =\n | { kind: 'legacy'; parsed: unknown[] }\n | { kind: 'malformed' }\n | undefined;\n\nfunction sniffLegacy(content: string): LegacySniff {\n const trimmed = content.replace(/^\\uFEFF/, '').trimStart();\n if (!trimmed.startsWith('[')) return undefined;\n try {\n const parsed: unknown = JSON.parse(trimmed);\n if (!Array.isArray(parsed)) return undefined;\n return parsed.every(isFeatureLike)\n ? { kind: 'legacy', parsed }\n : undefined;\n } catch {\n return { kind: 'malformed' };\n }\n}\n\nfunction looksLikeMessages(content: string): boolean {\n const firstLine = content\n .replace(/^\\uFEFF/, '')\n .split(/\\r?\\n/, 20)\n .map((line) => line.trim())\n .find(Boolean);\n if (!firstLine) return false;\n\n try {\n return isEnvelopeLike(JSON.parse(firstLine));\n } catch {\n return false;\n }\n}\n\nfunction invalidJson(content: string, file: string): never {\n try {\n JSON.parse(content.replace(/^\\uFEFF/, '').trimStart());\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid JSON in ${file}: ${detail}`);\n }\n throw new Error(`Unsupported input: ${file}`);\n}\n\ninterface InputFile {\n file: string;\n explicit: boolean;\n}\n\nasync function canonicalPath(file: string): Promise<string> {\n try {\n return await realpath(file);\n } catch {\n return path.resolve(file);\n }\n}\n\nfunction collectGherkinIds(value: unknown): string[] {\n const ids: string[] = [];\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const child of node) visit(child);\n return;\n }\n if (!node || typeof node !== 'object') return;\n for (const [key, child] of Object.entries(node)) {\n if (key === 'id' && typeof child === 'string') ids.push(child);\n else visit(child);\n }\n };\n visit(value);\n return ids;\n}\n\nexport interface LoadedInput {\n file: string;\n envelopes: Envelope[];\n}\n\nexport async function loadInputs(\n inputs: string | string[],\n): Promise<LoadedInput[]> {\n const requested = Array.isArray(inputs) ? inputs : [inputs];\n if (requested.length === 0) {\n throw new Error('No input files provided.');\n }\n\n const files = new Map<string, InputFile>();\n\n const add = async (file: string, explicit: boolean): Promise<void> => {\n const resolved = await canonicalPath(file);\n const existing = files.get(resolved);\n files.set(resolved, {\n file: resolved,\n explicit: explicit || existing?.explicit === true,\n });\n };\n\n for (const input of requested) {\n const info = await stat(input);\n\n if (info.isDirectory()) {\n const directory = await canonicalPath(input);\n for (const file of await collectReportFiles(directory)) {\n await add(file, false);\n }\n continue;\n }\n\n if (!info.isFile()) {\n throw new Error(`Unsupported input: ${input}`);\n }\n\n await add(input, true);\n }\n\n const ordered = [...files.values()].sort((a, b) =>\n a.file.localeCompare(b.file),\n );\n\n const groups: LoadedInput[] = [];\n const seenContent = new Set<string>();\n let totalBytes = 0;\n\n for (const [index, input] of ordered.entries()) {\n const info = await stat(input.file);\n const nextTotal = addInputBytes(totalBytes, info.size);\n const content = await readFile(input.file, 'utf8');\n const hash = createHash('sha256').update(content).digest('hex');\n if (seenContent.has(hash)) continue;\n seenContent.add(hash);\n\n totalBytes = nextTotal;\n\n const extension = path.extname(input.file).toLowerCase();\n const legacy = sniffLegacy(content);\n let parsed: Envelope[] = [];\n\n if (legacy?.kind === 'legacy') {\n parsed = parseLegacyValue(legacy.parsed, input.file, {\n idPrefix: `legacy-${index}`,\n });\n } else if (legacy?.kind === 'malformed') {\n // Validation-only: throws on malformed JSON; there is no result to add.\n parseLegacyJson(content, input.file, { idPrefix: `legacy-${index}` });\n } else if (looksLikeJUnit(content)) {\n parsed = await parseJUnitXml(content, input.file, {\n idPrefix: `junit-${index}`,\n });\n } else if (looksLikeMessages(content)) {\n parsed = parseMessages(content, input.file);\n } else if (input.explicit && extension === '.xml') {\n // Validation-only: throws when the explicit XML is not usable JUnit.\n await parseJUnitXml(content, input.file, { idPrefix: `junit-${index}` });\n } else {\n if (\n input.explicit &&\n MESSAGES_EXTENSIONS.has(extension) &&\n content.trim().length === 0\n ) {\n throw new Error(`Input is empty: ${input.file}`);\n }\n if (input.explicit) {\n invalidJson(content, input.file);\n }\n if (MESSAGES_EXTENSIONS.has(extension)) {\n // Validation-only fallback; valid Messages are handled above.\n parseMessages(content, input.file);\n }\n }\n\n groups.push({ file: input.file, envelopes: parsed });\n }\n\n if (groups.every((group) => group.envelopes.length === 0)) {\n throw new Error('No supported report files found.');\n }\n\n const seenIds = new Map<string, string>();\n for (const group of groups) {\n const file = path.basename(group.file);\n for (const envelope of group.envelopes) {\n const ids: Array<[string, string | undefined]> = [\n ['pickle', envelope.pickle?.id],\n ['testCase', envelope.testCase?.id],\n ['testCaseStarted', envelope.testCaseStarted?.id],\n ['hook', envelope.hook?.id],\n ];\n for (const step of envelope.testCase?.testSteps ?? []) {\n ids.push(['testStep', step.id]);\n }\n for (const id of collectGherkinIds(envelope.gherkinDocument)) {\n ids.push(['gherkin', id]);\n }\n for (const [kind, id] of ids) {\n if (!id) continue;\n const key = `${kind}:${id}`;\n const previous = seenIds.get(key);\n if (previous) {\n throw new Error(\n `Duplicate Cucumber Messages ${kind} id in ${previous} and ${file}. Merge the streams before splitting or use unique ids.`,\n );\n }\n seenIds.set(key, file);\n }\n }\n }\n\n return groups;\n}\n\nexport async function loadEnvelopes(\n inputs: string | string[],\n): Promise<Envelope[]> {\n return (await loadInputs(inputs)).flatMap((group) => group.envelopes);\n}\n\n/**\n * Maps a feature URI to its input file name, but only when the URI belongs to\n * exactly one file. Shared or missing provenance is omitted so the report can\n * render a flat list instead of an invented group.\n */\nexport function provenanceFor(groups: LoadedInput[]): Map<string, string> {\n const names = new Map<string, Set<string>>();\n for (const group of groups) {\n if (\n !group.envelopes.some(\n (envelope) => envelope.gherkinDocument || envelope.pickle,\n )\n ) {\n continue;\n }\n const name = path.basename(group.file);\n const set = names.get(name) ?? new Set<string>();\n set.add(group.file);\n names.set(name, set);\n }\n const ambiguous = new Set(\n [...names.entries()]\n .filter(([, files]) => files.size > 1)\n .map(([name]) => name),\n );\n\n const uriFiles = new Map<string, Set<string>>();\n for (const group of groups) {\n const name = path.basename(group.file);\n if (ambiguous.has(name)) continue;\n for (const envelope of group.envelopes) {\n for (const uri of [envelope.gherkinDocument?.uri, envelope.pickle?.uri]) {\n if (!uri) continue;\n const set = uriFiles.get(uri) ?? new Set<string>();\n set.add(name);\n uriFiles.set(uri, set);\n }\n }\n }\n\n const provenance = new Map<string, string>();\n for (const [uri, files] of uriFiles) {\n if (files.size === 1) provenance.set(uri, [...files][0] as string);\n }\n return provenance;\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,sBAAsB;;;ACA/B,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,SAAS,OAAO,QAAQ,IA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AAQ;AAE3D,QAAM,EAAE,MAAM,QAAQ,IAAI,MAAM,eAAe,QAAQ,EAAE,OAAO,SAAS,CAAC;AAC1E,QAAM,YAAY,QAAQ,IAAI;AAE9B,SAAO,EAAE,QAAQ,UAAU,QAAQ;AACrC;AAMO,SAAS,SACd,SACA,UACuB;AACvB,QAAM,UAAU,IAAI,OAAO;AAC3B,MAAI,UAAU;AACZ,YAAQ;AAAA,MACN,MAAM,SAAS,IAAI;AAAA,MACnB,CAAC,UACC,SAAS,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;AAAA,IACtE;AAGA,YAAQ,MAAM,MAAM,MAAS;AAAA,EAC/B;AACA,SAAO;AACT;",
|
|
6
|
+
"names": ["path", "path", "stat", "path", "TestStepResultStatus", "path", "stat"]
|
|
7
7
|
}
|
package/dist/compat/options.d.ts
CHANGED
|
@@ -24,6 +24,8 @@ export interface CucumberHtmlReporterOptions {
|
|
|
24
24
|
[key: string]: unknown;
|
|
25
25
|
}
|
|
26
26
|
export declare function warnIgnoredOptions(options: CucumberHtmlReporterOptions, warnings: string[]): void;
|
|
27
|
+
/** The configured input root: jsonFile wins over jsonDir, as in resolveInputs. */
|
|
28
|
+
export declare function inputRoot(options: CucumberHtmlReporterOptions): string | undefined;
|
|
27
29
|
export declare function requireOutput(options: CucumberHtmlReporterOptions): string;
|
|
28
30
|
export declare function mapTitle(options: CucumberHtmlReporterOptions, warnings: string[]): string;
|
|
29
31
|
export declare function flattenMetadata(value: unknown, warnings: string[]): Record<string, string>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
|
+
import { type RenderReportOptions } from './options.js';
|
|
1
2
|
import type { ReportSummary } from './summary.js';
|
|
2
|
-
export declare const version = "0.
|
|
3
|
+
export declare const version = "0.3.0";
|
|
3
4
|
export declare const phase = "development";
|
|
4
5
|
export type { ReportSummary, StatusCounts, SummaryScenario, SummaryStatus, SummaryStep, } from './summary.js';
|
|
5
6
|
export { summarizeReport, SUMMARY_SCHEMA_VERSION } from './summary.js';
|
|
6
|
-
export
|
|
7
|
-
|
|
8
|
-
metadata?: Record<string, string>;
|
|
9
|
-
logo?: string;
|
|
10
|
-
accent?: string;
|
|
11
|
-
}
|
|
7
|
+
export type { RenderReportOptions } from './options.js';
|
|
8
|
+
export { CucumberHtmlStream } from './stream.js';
|
|
12
9
|
export interface GeneratedReport {
|
|
13
10
|
html: string;
|
|
14
11
|
summary: ReportSummary;
|