tolkira 0.2.0 → 0.4.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.
Files changed (64) hide show
  1. package/DESIGN.md +131 -9
  2. package/GLOSSARY.md +201 -1
  3. package/README.md +413 -29
  4. package/SECURITY.md +3 -0
  5. package/dist/attachment.d.ts +33 -0
  6. package/dist/attempt-diagnostics.d.ts +2 -0
  7. package/dist/ci.d.ts +12 -0
  8. package/dist/cli.js +6881 -2691
  9. package/dist/cli.js.map +4 -4
  10. package/dist/compat/cucumber-html-reporter.cjs +12 -0
  11. package/dist/compat/cucumber-html-reporter.d.cts +10 -0
  12. package/dist/compat/cucumber-html-reporter.js +263 -26
  13. package/dist/compat/cucumber-html-reporter.js.map +4 -4
  14. package/dist/compat/options.d.ts +4 -0
  15. package/dist/email.d.ts +18 -0
  16. package/dist/history.d.ts +41 -0
  17. package/dist/i18n/catalogs.d.ts +7 -0
  18. package/dist/index.d.ts +15 -7
  19. package/dist/index.js +5301 -1709
  20. package/dist/index.js.map +4 -4
  21. package/dist/input/background.d.ts +4 -0
  22. package/dist/input/detect.d.ts +30 -0
  23. package/dist/input/load.d.ts +3 -0
  24. package/dist/input/playwright.d.ts +14 -0
  25. package/dist/options.d.ts +18 -0
  26. package/dist/output.d.ts +9 -1
  27. package/dist/pdf.d.ts +9 -0
  28. package/dist/render/ansi.d.ts +2 -0
  29. package/dist/render/attachments.d.ts +3 -0
  30. package/dist/render/ci.d.ts +4 -0
  31. package/dist/render/client-bundle.d.ts +1 -0
  32. package/dist/render/client-i18n.d.ts +7 -0
  33. package/dist/render/details.d.ts +5 -0
  34. package/dist/render/dom-contract.d.ts +42 -0
  35. package/dist/render/format.d.ts +34 -0
  36. package/dist/render/html.d.ts +2 -9
  37. package/dist/render/i18n.d.ts +30 -0
  38. package/dist/render/markdown.d.ts +2 -0
  39. package/dist/render/matrix.d.ts +3 -0
  40. package/dist/render/print-script.d.ts +1 -0
  41. package/dist/render/report-client.d.ts +1 -0
  42. package/dist/render/report.d.ts +4 -0
  43. package/dist/render/search.d.ts +21 -0
  44. package/dist/render/trends.d.ts +7 -0
  45. package/dist/render/triage.d.ts +5 -0
  46. package/dist/render/types.d.ts +26 -0
  47. package/dist/report/index-run.d.ts +69 -0
  48. package/dist/report/model.d.ts +96 -6
  49. package/dist/report/status.d.ts +12 -0
  50. package/dist/stream.d.ts +15 -0
  51. package/dist/summary.d.ts +17 -2
  52. package/dist/text.d.ts +15 -0
  53. package/dist/warnings.d.ts +6 -0
  54. package/docs/AGENT-INTERFACE.md +504 -33
  55. package/docs/CI.md +185 -0
  56. package/docs/COMPATIBILITY.md +121 -16
  57. package/docs/CUCUMBER-COMPATIBILITY.md +232 -15
  58. package/docs/EMAIL.md +273 -0
  59. package/docs/I18N.md +241 -0
  60. package/docs/JUNIT-XML.md +46 -4
  61. package/docs/LIMITATIONS.md +21 -0
  62. package/docs/PDF.md +255 -0
  63. package/llms.txt +63 -0
  64. package/package.json +46 -8
@@ -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/files.ts"],
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;\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;AAAA,EACF;AACA,SAAO;AACT;",
6
- "names": ["path", "path", "path"]
3
+ "sources": ["../../src/compat/cucumber-html-reporter.ts", "../../src/output.ts", "../../src/input/files.ts", "../../src/warnings.ts", "../../src/compat/options.ts", "../../src/input/legacy.ts", "../../src/input/messages.ts", "../../src/input/playwright.ts", "../../src/attachment.ts", "../../src/input/load.ts"],
4
+ "sourcesContent": ["import { readFile } from 'node:fs/promises';\nimport { generateReport } from '../index.js';\nimport { outputOverwritesInput, samePath, writeAtomic } from '../output.js';\nimport { ATTACHMENT_HINT, attachmentWarning } from '../warnings.js';\nimport {\n flattenMetadata,\n inputRoot,\n mapTitle,\n requireOutput,\n resolveInputs,\n stripBom,\n warnIgnoredOptions,\n} from './options.js';\nimport type { CompatResult, CucumberHtmlReporterOptions } from './options.js';\n\nexport type { CompatResult, CucumberHtmlReporterOptions } from './options.js';\n\nconst FALLBACK_URI = 'Feature: URI Not Present';\n\ninterface MergedFeature {\n feature: Record<string, unknown>;\n elements: unknown[];\n}\n\nfunction featureKey(feature: Record<string, unknown>): string {\n return typeof feature.uri === 'string' && feature.uri\n ? feature.uri\n : FALLBACK_URI;\n}\n\ninterface ParsedInput {\n file: string;\n features: Record<string, unknown>[];\n}\n\ninterface SidecarPlan {\n inputs: string[];\n merged: MergedFeature[];\n}\n\n/** A valid legacy feature array, or undefined for parse/shape failure. */\nasync function readFeatures(\n file: string,\n): Promise<Record<string, unknown>[] | undefined> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(stripBom(await readFile(file, 'utf8')));\n } catch {\n return undefined;\n }\n if (\n !Array.isArray(parsed) ||\n parsed.some((feature) => typeof feature !== 'object' || feature === null)\n ) {\n return undefined;\n }\n return parsed as Record<string, unknown>[];\n}\n\nfunction collisionError(sidecar: string, input: string): Error {\n return new Error(\n `compat: sidecar ${sidecar} must not overwrite an input file (${input})`,\n );\n}\n\n/** True when every candidate feature key also appears in another input. */\nfunction isPreviousSidecar(\n candidate: ParsedInput,\n others: ParsedInput[],\n): boolean {\n if (others.length === 0) return false;\n const represented = new Set<string>();\n for (const { features } of others) {\n for (const feature of features) represented.add(featureKey(feature));\n }\n return candidate.features.every((feature) =>\n represented.has(featureKey(feature)),\n );\n}\n\n/** Parses every input once, validates it and plans the merged sidecar. */\nasync function planSidecar(\n inputs: string[],\n sidecar: string,\n): Promise<SidecarPlan> {\n const parsed: ParsedInput[] = [];\n for (const file of inputs) {\n const features = await readFeatures(file);\n if (!features) {\n throw new Error(`compat: ${file} is not a legacy feature array`);\n }\n parsed.push({ file, features });\n }\n\n const index = parsed.findIndex(({ file }) => samePath(file, sidecar));\n let selected = parsed;\n if (index !== -1) {\n const candidate = parsed[index];\n const others = parsed.filter((_, position) => position !== index);\n if (!isPreviousSidecar(candidate, others)) {\n throw collisionError(sidecar, candidate.file);\n }\n selected = others;\n }\n\n const merged = new Map<string, MergedFeature>();\n for (const { features } of selected) {\n for (const feature of features) {\n const key = featureKey(feature);\n const elements = (\n Array.isArray(feature.elements) ? feature.elements : []\n ).map((element) => ({ ...(element as object), retried: 0 }));\n const existing = merged.get(key);\n if (existing) {\n existing.elements.push(...elements);\n } else {\n merged.set(key, { feature, elements });\n }\n }\n }\n\n return {\n inputs: selected.map(({ file }) => file),\n merged: [...merged.values()],\n };\n}\n\n/** Writes the planned merged array; a same-path input is refused as defense. */\nasync function writeMergedJson(\n plan: SidecarPlan,\n sidecar: string,\n): Promise<void> {\n for (const input of plan.inputs) {\n if (samePath(input, sidecar)) throw collisionError(sidecar, input);\n }\n const result = plan.merged.map(({ feature, elements }) => ({\n ...feature,\n elements,\n }));\n await writeAtomic(sidecar, JSON.stringify(result, null, 2));\n}\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 hasJsonFile = Boolean(\n typeof options.jsonFile === 'string' && options.jsonFile.trim(),\n );\n const hasJsonDir = Boolean(\n typeof options.jsonDir === 'string' && options.jsonDir.trim(),\n );\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 sidecar = `${output}.json`;\n const plan =\n !hasJsonFile && hasJsonDir ? await planSidecar(inputs, sidecar) : undefined;\n const title = mapTitle(options, warnings);\n const metadata = flattenMetadata(options.metadata, warnings);\n\n const { html, summary, skippedAttachments } = await generateReport(\n plan?.inputs ?? inputs,\n { title, metadata },\n );\n await writeAtomic(output, html);\n if (plan) await writeMergedJson(plan, sidecar);\n if (skippedAttachments > 0) {\n warnings.push(\n `${attachmentWarning(skippedAttachments)} ${ATTACHMENT_HINT}`,\n );\n }\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\n if (logo) {\n const logoInfo = await stat(logo).catch(() => undefined);\n if (logoInfo?.isFile() && samePath(logo, outputPath)) 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() && samePath(input, outputPath)) return true;\n if (inputInfo.isDirectory()) {\n for (const file of await collectReportFiles(input)) {\n if (samePath(file, outputPath)) return true;\n }\n }\n }\n return false;\n}\n\nfunction foldCase(value: string): string {\n return process.platform === 'win32' || process.platform === 'darwin'\n ? value.toLowerCase()\n : value;\n}\n\nfunction existingRealPath(file: string): string | undefined {\n try {\n return realpathSync(file);\n } catch {\n return undefined;\n }\n}\n\n// Canonicalizes a path even when the file itself is missing: resolve the\n// nearest existing ancestor through symlinks, keep the rest as given, then\n// fold case on case-insensitive filesystems.\nfunction canonicalPath(file: string): string {\n const resolved = path.resolve(file);\n let current = resolved;\n const tail: string[] = [];\n for (;;) {\n const real = existingRealPath(current);\n if (real !== undefined) return foldCase(path.join(real, ...tail));\n const parent = path.dirname(current);\n if (parent === current) return foldCase(resolved);\n tail.unshift(path.basename(current));\n current = parent;\n }\n}\n\n/**\n * True when both paths name the same file. Windows and macOS compare\n * case-insensitively; symlinked or junctioned parents resolve even when the\n * target file does not exist yet.\n */\nexport function samePath(a: string, b: string): boolean {\n return canonicalPath(a) === canonicalPath(b);\n}\n\nexport async function writeAtomic(\n output: string,\n content: string | Uint8Array,\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", "/**\n * Copy for the skipped path attachment notice. Shared by the HTML report, the\n * CLI stderr warning and the compat shim so the wording stays one string.\n */\nexport const ATTACHMENT_HINT =\n 'Run from the folder that contains the referenced files, or regenerate the JSON where the files live.';\n\nexport function attachmentWarning(count: number): string {\n if (count === 1) {\n return \"1 path attachment was skipped: it is outside the allowed roots (its input file's folder and Tolkira's working directory). The report may be missing screenshots or files.\";\n }\n return `${count} path attachments were skipped: they are outside the allowed roots (each input file's folder and Tolkira's working directory). The report may be missing screenshots or 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\n/** Strips one leading UTF-8 BOM, as the core loader does. */\nexport function stripBom(content: string): string {\n return content.replace(/^\\uFEFF/, '');\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(\n stripBom(await readFile(file, 'utf8')),\n );\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 name?: string;\n fileName?: string;\n}\n\ninterface LegacyResult {\n status?: string;\n duration?: number;\n error_message?: string | 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 | string[];\n output?: string | string[] | null;\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 'error',\n 'hook_error',\n 'cleanup_error',\n]);\n\nfunction invalidLegacy(source: string, detail: string): Error {\n return new Error(`Invalid legacy JSON in ${source}: ${detail}`);\n}\n\nfunction isTextValue(value: unknown): value is string | string[] {\n return (\n typeof value === 'string' ||\n (Array.isArray(value) && value.every((line) => typeof line === 'string'))\n );\n}\n\nfunction validateStep(\n step: Record<string, unknown>,\n source: string,\n where: string,\n hook = false,\n): void {\n if (step.text !== undefined && !isTextValue(step.text)) {\n throw invalidLegacy(\n source,\n `${where}.text must be a string or an array of strings.`,\n );\n }\n // Only hook output is mapped; non-hook output is ignored, and null is absent.\n if (hook && step.output != null && !isTextValue(step.output)) {\n throw invalidLegacy(\n source,\n `${where}.output must be a string or an array of strings.`,\n );\n }\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 if (\n step.result.error_message !== undefined &&\n !isTextValue(step.result.error_message)\n ) {\n throw invalidLegacy(\n source,\n `${where}.result.error_message must be a string or an array of strings.`,\n );\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(\n step,\n source,\n `${where} step ${stepIndex + 1}`,\n isHook(step),\n );\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}`, true);\n }\n }\n }\n}\n\ninterface StepPlan {\n testStep: TestStep;\n legacyStep: LegacyStep;\n hookOutputName?: string;\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[] | null | 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\n// AST locations use line 1 as a placeholder, but the report now shows a pickle\n// line, so an absent legacy line must read as unknown (0), never as line 1.\nfunction pickleLocation(line?: number): Location {\n return {\n line:\n typeof line === 'number' && Number.isInteger(line) && line > 0 ? line : 0,\n };\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 case 'error':\n case 'hook_error':\n case 'cleanup_error':\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: normalizeText(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 = normalizeText(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: pickleLocation(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 hookOutputName: 'Before hook output',\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 hookOutputName: 'After hook output',\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 if (plan.hookOutputName) {\n const hookOutput = normalizeText(plan.legacyStep.output);\n if (hookOutput) {\n scenarioEnvelopes.push({\n attachment: {\n body: hookOutput,\n contentEncoding: AttachmentContentEncoding.IDENTITY,\n fileName: plan.hookOutputName,\n mediaType: 'text/plain',\n testCaseStartedId,\n testStepId: plan.testStep.id,\n timestamp: finishedAt,\n },\n });\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 rawFileName = embedding.fileName ?? embedding.name;\n const fileName =\n typeof rawFileName === 'string' && rawFileName.trim()\n ? rawFileName\n : undefined;\n const attachment: Attachment = {\n body: embedding.data,\n contentEncoding: isLikelyBase64(embedding.data)\n ? AttachmentContentEncoding.BASE64\n : AttachmentContentEncoding.IDENTITY,\n ...(fileName ? { fileName } : {}),\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 { lstat, open, realpath } from 'node:fs/promises';\nimport path from 'node:path';\nimport {\n AttachmentContentEncoding,\n TestStepResultStatus,\n} from '@cucumber/messages';\nimport type {\n Attachment,\n Duration,\n Envelope,\n Feature,\n FeatureChild,\n Location,\n Meta,\n Pickle,\n PickleStep,\n Rule,\n RuleChild,\n Scenario,\n Step,\n TestCase,\n TestCaseStarted,\n TestStep,\n TestStepResult,\n Timestamp,\n} from '@cucumber/messages';\nimport {\n MAX_ATTACHMENT_BYTES,\n MAX_TOTAL_ATTACHMENT_BYTES,\n} from '../attachment.js';\nimport { stripAnsi } from '../text.js';\nimport { recordSkippedAttachments } from '../attempt-diagnostics.js';\n\nconst FAILED_STATUSES = new Set(['failed', 'timedOut', 'interrupted']);\nconst KNOWN_ANNOTATIONS = new Set(['skip', 'fixme', 'fail', 'slow']);\n\ntype JsonObject = Record<string, unknown>;\n\ninterface PlaywrightError {\n message?: string;\n value?: string;\n stack?: string;\n snippet?: string;\n location?: { file?: string; line?: number; column?: number };\n}\n\ninterface PlaywrightStep {\n title: string;\n subtitle?: string;\n duration: number;\n error?: PlaywrightError;\n steps: PlaywrightStep[];\n}\n\ninterface PlaywrightAttachment {\n name: string;\n contentType: string;\n body?: string;\n path?: string;\n}\n\ninterface PlaywrightOutput {\n text?: string;\n buffer?: string;\n}\n\ninterface PlaywrightAnnotation {\n type: string;\n description?: string;\n}\n\ninterface PlaywrightResult {\n status: string;\n duration: number;\n retry: number;\n startTime?: string;\n error?: PlaywrightError;\n errors: PlaywrightError[];\n steps: PlaywrightStep[];\n attachments: PlaywrightAttachment[];\n stdout: PlaywrightOutput[];\n stderr: PlaywrightOutput[];\n}\n\ninterface PlaywrightTest {\n projectName?: string;\n projectId?: string;\n status?: string;\n expectedStatus?: string;\n annotations: PlaywrightAnnotation[];\n results: PlaywrightResult[];\n}\n\ninterface PlaywrightSpec {\n title: string;\n file?: string;\n line?: number;\n column?: number;\n tags: string[];\n tests: PlaywrightTest[];\n}\n\ninterface PlaywrightSuite {\n title?: string;\n file?: string;\n line?: number;\n column?: number;\n specs: PlaywrightSpec[];\n suites: PlaywrightSuite[];\n}\n\nexport interface PlaywrightJsonOptions {\n idPrefix?: string;\n}\n\nexport interface PlaywrightParseResult {\n envelopes: Envelope[];\n skippedAttachments: number;\n}\n\ninterface CanonicalStep {\n text: string;\n durationMs: number;\n status: TestStepResultStatus;\n message?: string;\n}\n\ninterface PlannedAttachment {\n fileName: string;\n mediaType: string;\n body: string;\n contentEncoding: AttachmentContentEncoding.BASE64;\n}\n\ninterface PlannedAttempt {\n attempt: number;\n timestamp: Timestamp;\n steps: CanonicalStep[];\n attachments: PlannedAttachment[];\n skippedAttachments: number;\n willBeRetried: boolean;\n}\n\ninterface ScenarioPlan {\n scenario: Scenario;\n pickle: Pickle;\n testCase: TestCase;\n attempts: PlannedAttempt[];\n}\n\ninterface RulePlan {\n id: string;\n name: string;\n scenarios: ScenarioPlan[];\n}\n\ninterface FeaturePlan {\n name: string;\n uri: string;\n rules: Map<string, RulePlan>;\n order: RulePlan[];\n}\n\ninterface PlanContext {\n source: string;\n idPrefix: string;\n inputDir: string;\n roots: string[];\n nextId: (kind: string) => string;\n totalAttachmentBytes: number;\n features: Map<string, FeaturePlan>;\n featureOrder: FeaturePlan[];\n runId: string;\n runTimestamp: Timestamp;\n skippedAttachments: number;\n}\n\nfunction isObject(value: unknown): value is JsonObject {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction invalid(source: string, detail: string): Error {\n return new Error(`Invalid Playwright JSON in ${source}: ${detail}`);\n}\n\nfunction optionalString(\n value: JsonObject,\n field: string,\n source: string,\n where: string,\n): string | undefined {\n const fieldValue = value[field];\n if (fieldValue === undefined) return undefined;\n if (typeof fieldValue !== 'string') {\n throw invalid(source, `${where}.${field} must be a string.`);\n }\n return fieldValue;\n}\n\nfunction optionalNumber(\n value: JsonObject,\n field: string,\n source: string,\n where: string,\n): number | undefined {\n const fieldValue = value[field];\n if (fieldValue === undefined) return undefined;\n if (typeof fieldValue !== 'number' || !Number.isFinite(fieldValue)) {\n throw invalid(source, `${where}.${field} must be a number.`);\n }\n return fieldValue;\n}\n\nfunction arrayOf(\n value: JsonObject,\n field: string,\n source: string,\n where: string,\n): unknown[] {\n const fieldValue = value[field];\n if (!Array.isArray(fieldValue)) {\n throw invalid(source, `${where}.${field} must be an array.`);\n }\n return fieldValue;\n}\n\nfunction validateError(\n value: unknown,\n source: string,\n where: string,\n): PlaywrightError {\n if (!isObject(value)) {\n throw invalid(source, `${where} must be an object.`);\n }\n const error: PlaywrightError = {};\n for (const field of ['message', 'value', 'stack', 'snippet'] as const) {\n const text = optionalString(value, field, source, where);\n if (text !== undefined) error[field] = text;\n }\n if (value.location !== undefined) {\n if (!isObject(value.location)) {\n throw invalid(source, `${where}.location must be an object.`);\n }\n error.location = {\n file: optionalString(value.location, 'file', source, `${where}.location`),\n line: optionalNumber(value.location, 'line', source, `${where}.location`),\n column: optionalNumber(value.location, 'column', source, `${where}.location`),\n };\n }\n return error;\n}\n\nfunction validateStep(\n value: unknown,\n source: string,\n where: string,\n): PlaywrightStep {\n if (!isObject(value)) {\n throw invalid(source, `${where} must be an object.`);\n }\n if (typeof value.title !== 'string') {\n throw invalid(source, `${where}.title must be a string.`);\n }\n if (typeof value.duration !== 'number' || !Number.isFinite(value.duration)) {\n throw invalid(source, `${where}.duration must be a number.`);\n }\n const step: PlaywrightStep = {\n title: value.title,\n duration: value.duration,\n steps: [],\n };\n const subtitle = optionalString(value, 'subtitle', source, where);\n if (subtitle !== undefined) step.subtitle = subtitle;\n if (value.error !== undefined) {\n step.error = validateError(value.error, source, `${where}.error`);\n }\n if (value.steps !== undefined) {\n step.steps = arrayOf(value, 'steps', source, where).map((child, index) =>\n validateStep(child, source, `${where}.steps[${index}]`),\n );\n }\n return step;\n}\n\nfunction validateAttachment(\n value: unknown,\n source: string,\n where: string,\n): PlaywrightAttachment {\n if (!isObject(value)) {\n throw invalid(source, `${where} must be an object.`);\n }\n if (typeof value.contentType !== 'string') {\n throw invalid(source, `${where}.contentType must be a string.`);\n }\n const attachment: PlaywrightAttachment = {\n name: 'attachment',\n contentType: value.contentType,\n };\n const name = optionalString(value, 'name', source, where);\n if (name !== undefined) attachment.name = name;\n const body = optionalString(value, 'body', source, where);\n if (body !== undefined) attachment.body = body;\n const file = optionalString(value, 'path', source, where);\n if (file !== undefined) attachment.path = file;\n return attachment;\n}\n\nfunction validateOutput(\n value: unknown,\n source: string,\n where: string,\n): PlaywrightOutput {\n if (!isObject(value)) {\n throw invalid(source, `${where} must be an object.`);\n }\n const output: PlaywrightOutput = {};\n const text = optionalString(value, 'text', source, where);\n if (text !== undefined) output.text = text;\n const buffer = optionalString(value, 'buffer', source, where);\n if (buffer !== undefined) output.buffer = buffer;\n if (output.text === undefined && output.buffer === undefined) {\n throw invalid(source, `${where} must have a text or buffer string.`);\n }\n return output;\n}\n\nfunction validateResult(\n value: unknown,\n source: string,\n where: string,\n): PlaywrightResult {\n if (!isObject(value)) {\n throw invalid(source, `${where} must be an object.`);\n }\n if (typeof value.status !== 'string') {\n throw invalid(source, `${where}.status must be a string.`);\n }\n if (typeof value.duration !== 'number' || !Number.isFinite(value.duration)) {\n throw invalid(source, `${where}.duration must be a number.`);\n }\n const result: PlaywrightResult = {\n status: value.status,\n duration: value.duration,\n retry: optionalNumber(value, 'retry', source, where) ?? 0,\n errors: [],\n steps: [],\n attachments: [],\n stdout: [],\n stderr: [],\n };\n const startTime = optionalString(value, 'startTime', source, where);\n if (startTime !== undefined) result.startTime = startTime;\n if (value.error !== undefined) {\n result.error = validateError(value.error, source, `${where}.error`);\n }\n if (value.errors !== undefined) {\n result.errors = arrayOf(value, 'errors', source, where).map((entry, index) =>\n validateError(entry, source, `${where}.errors[${index}]`),\n );\n }\n if (value.steps !== undefined) {\n result.steps = arrayOf(value, 'steps', source, where).map((entry, index) =>\n validateStep(entry, source, `${where}.steps[${index}]`),\n );\n }\n if (value.attachments !== undefined) {\n result.attachments = arrayOf(value, 'attachments', source, where).map(\n (entry, index) =>\n validateAttachment(entry, source, `${where}.attachments[${index}]`),\n );\n }\n for (const field of ['stdout', 'stderr'] as const) {\n if (value[field] !== undefined) {\n result[field] = arrayOf(value, field, source, where).map((entry, index) =>\n validateOutput(entry, source, `${where}.${field}[${index}]`),\n );\n }\n }\n return result;\n}\n\nfunction validateAnnotation(\n value: unknown,\n source: string,\n where: string,\n): PlaywrightAnnotation {\n if (!isObject(value)) {\n throw invalid(source, `${where} must be an object.`);\n }\n if (typeof value.type !== 'string') {\n throw invalid(source, `${where}.type must be a string.`);\n }\n const description = optionalString(value, 'description', source, where);\n return { type: value.type, ...(description ? { description } : {}) };\n}\n\nfunction validateTest(\n value: unknown,\n source: string,\n where: string,\n): PlaywrightTest {\n if (!isObject(value)) {\n throw invalid(source, `${where} must be an object.`);\n }\n const test: PlaywrightTest = {\n annotations: [],\n results: arrayOf(value, 'results', source, where).map((entry, index) =>\n validateResult(entry, source, `${where}.results[${index}]`),\n ),\n };\n const projectName = optionalString(value, 'projectName', source, where);\n if (projectName !== undefined) test.projectName = projectName;\n const projectId = optionalString(value, 'projectId', source, where);\n if (projectId !== undefined) test.projectId = projectId;\n const status = optionalString(value, 'status', source, where);\n if (status !== undefined) test.status = status;\n const expectedStatus = optionalString(value, 'expectedStatus', source, where);\n if (expectedStatus !== undefined) test.expectedStatus = expectedStatus;\n if (value.annotations !== undefined) {\n test.annotations = arrayOf(value, 'annotations', source, where).map(\n (entry, index) =>\n validateAnnotation(entry, source, `${where}.annotations[${index}]`),\n );\n }\n return test;\n}\n\nfunction validateSpec(\n value: unknown,\n source: string,\n where: string,\n): PlaywrightSpec {\n if (!isObject(value)) {\n throw invalid(source, `${where} must be an object.`);\n }\n if (typeof value.title !== 'string') {\n throw invalid(source, `${where}.title must be a string.`);\n }\n const spec: PlaywrightSpec = {\n title: value.title,\n tags: [],\n tests: arrayOf(value, 'tests', source, where).map((entry, index) =>\n validateTest(entry, source, `${where}.tests[${index}]`),\n ),\n };\n const file = optionalString(value, 'file', source, where);\n if (file !== undefined) spec.file = file;\n const line = optionalNumber(value, 'line', source, where);\n if (line !== undefined) spec.line = line;\n const column = optionalNumber(value, 'column', source, where);\n if (column !== undefined) spec.column = column;\n if (value.tags !== undefined) {\n spec.tags = arrayOf(value, 'tags', source, where).map((tag, index) => {\n if (typeof tag !== 'string') {\n throw invalid(source, `${where}.tags[${index}] must be a string.`);\n }\n return tag;\n });\n }\n return spec;\n}\n\nfunction validateSuite(\n value: unknown,\n source: string,\n where: string,\n): PlaywrightSuite {\n if (!isObject(value)) {\n throw invalid(source, `${where} must be an object.`);\n }\n const suite: PlaywrightSuite = {\n specs: arrayOf(value, 'specs', source, where).map((entry, index) =>\n validateSpec(entry, source, `${where}.specs[${index}]`),\n ),\n suites: [],\n };\n const title = optionalString(value, 'title', source, where);\n if (title !== undefined) suite.title = title;\n const file = optionalString(value, 'file', source, where);\n if (file !== undefined) suite.file = file;\n const line = optionalNumber(value, 'line', source, where);\n if (line !== undefined) suite.line = line;\n const column = optionalNumber(value, 'column', source, where);\n if (column !== undefined) suite.column = column;\n if (value.suites !== undefined) {\n suite.suites = arrayOf(value, 'suites', source, where).map((entry, index) =>\n validateSuite(entry, source, `${where}.suites[${index}]`),\n );\n }\n return suite;\n}\n\nfunction timestamp(milliseconds: number): Timestamp {\n const safe = Number.isFinite(milliseconds) ? milliseconds : 0;\n const seconds = Math.floor(safe / 1000);\n const nanos = Math.round((safe - seconds * 1000) * 1_000_000);\n return nanos >= 1_000_000_000\n ? { seconds: seconds + 1, nanos: nanos - 1_000_000_000 }\n : { seconds, nanos };\n}\n\nfunction timestampOf(value: string | undefined, fallback: Timestamp): Timestamp {\n if (!value) return fallback;\n const milliseconds = Date.parse(value);\n return Number.isFinite(milliseconds) ? timestamp(milliseconds) : fallback;\n}\n\nfunction addDuration(base: Timestamp, milliseconds: number): Timestamp {\n return timestamp(base.seconds * 1000 + base.nanos / 1_000_000 + milliseconds);\n}\n\n// Playwright durations are milliseconds; Messages uses nanoseconds. The legacy\n// adapter's time helpers do not fit, so the conversion stays local until a third\n// adapter justifies a shared module.\nfunction durationOf(milliseconds: number): Duration {\n const nanos = Math.max(0, Math.round(milliseconds * 1_000_000));\n return {\n seconds: Math.floor(nanos / 1_000_000_000),\n nanos: nanos % 1_000_000_000,\n };\n}\n\nfunction location(line?: number, column?: number): Location {\n const safeLine = line !== undefined && line > 0 ? line : 1;\n return column !== undefined && column > 0\n ? { line: safeLine, column }\n : { line: safeLine };\n}\n\n// The report shows a positive Pickle line; a missing or zero spec.line must stay\n// unknown (0), while AST nodes keep the line-1 placeholder.\nfunction pickleLocation(line?: number, column?: number): Location {\n const safeLine =\n typeof line === 'number' && Number.isInteger(line) && line > 0 ? line : 0;\n return safeLine > 0 && column !== undefined && Number.isInteger(column) && column > 0\n ? { line: safeLine, column }\n : { line: safeLine };\n}\n\n// Right-to-left token scan; a regex here backtracked quadratically on long\n// titles with many trailing @tags.\nfunction stripTrailingTags(value: string): string {\n let end = value.length;\n while (end > 0) {\n let tokenEnd = end;\n while (tokenEnd > 0 && /\\s/.test(value[tokenEnd - 1] as string)) tokenEnd -= 1;\n let tokenStart = tokenEnd;\n while (tokenStart > 0 && !/\\s/.test(value[tokenStart - 1] as string)) {\n tokenStart -= 1;\n }\n const token = value.slice(tokenStart, tokenEnd);\n if (\n tokenStart === 0 ||\n token.length < 2 ||\n token[0] !== '@' ||\n token.includes('@', 1)\n ) {\n break;\n }\n end = tokenStart;\n }\n return value.slice(0, end).trim();\n}\n\nfunction fileUri(value: string | undefined, inputDir: string): string {\n return relativeFile(value ?? 'playwright.spec.ts', inputDir);\n}\n\nfunction isInside(root: string, target: string): boolean {\n const relative = path.relative(root, target);\n return (\n relative === '' ||\n (!path.isAbsolute(relative) &&\n relative !== '..' &&\n !relative.startsWith(`..${path.sep}`))\n );\n}\n\nfunction relativeFile(file: string, inputDir: string): string {\n if (!path.isAbsolute(file)) {\n const normalized = file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n return normalized || path.basename(file);\n }\n const resolved = path.resolve(file);\n for (const root of [inputDir, process.cwd()]) {\n const relative = path.relative(root, resolved);\n if (\n relative &&\n !path.isAbsolute(relative) &&\n relative !== '..' &&\n !relative.startsWith(`..${path.sep}`)\n ) {\n return relative.replace(/\\\\/g, '/');\n }\n }\n return path.basename(file);\n}\n\nfunction locationText(\n value: PlaywrightError['location'],\n inputDir: string,\n): string | undefined {\n if (!value?.file) return undefined;\n const file = relativeFile(value.file, inputDir);\n const line = value.line !== undefined ? `:${value.line}` : '';\n const column = value.column !== undefined ? `:${value.column}` : '';\n return `${file}${line}${column}`;\n}\n\n// Common local roots on POSIX plus Windows drive paths. The lookbehinds keep\n// URL text such as https://example.com/tmp/report intact.\nconst ABSOLUTE_LOCAL_PATH =\n /(?:(?<![A-Za-z0-9_])[A-Za-z]:[\\\\/]|(?<![A-Za-z0-9_/])\\/(?:Users|home|tmp|var|opt|etc|usr|private|mnt|srv|root|workspace|builds|app|data|github)\\/)[^\\s\"'<>|]+/g;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction rootPattern(root: string): RegExp | undefined {\n const trimmed = root.replace(/[\\\\/]+$/, '');\n if (!trimmed) return undefined;\n const body = trimmed\n .split(/[\\\\/]/)\n .map((part) => escapeRegExp(part))\n .join('[\\\\\\\\/]');\n return new RegExp(`${body}(?:[\\\\\\\\/]|(?=$|[^\\\\w.-]))`, 'gi');\n}\n\n// Error text is untrusted and must not carry the machine's absolute paths into\n// a shared report. Roots become relative; other local paths keep the basename.\nfunction scrubPaths(text: string, inputDir: string): string {\n let scrubbed = text;\n for (const root of [inputDir, process.cwd()]) {\n const pattern = rootPattern(root);\n if (pattern) scrubbed = scrubbed.replace(pattern, '');\n }\n return scrubbed.replace(ABSOLUTE_LOCAL_PATH, (match) =>\n path.basename(match.replace(/\\\\/g, '/')),\n );\n}\n\nfunction locationAlreadyPresent(part: string, at: string): boolean {\n const normalized = part.replace(/\\\\/g, '/');\n const needle = at.replace(/\\\\/g, '/');\n const escaped = escapeRegExp(needle);\n // A location without a column also matches the same file and line with one.\n const column = /:\\d+:\\d+$/.test(needle) ? '' : '(?::\\\\d+)?';\n return new RegExp(`(?:^|[^\\\\w:./-])${escaped}${column}(?![\\\\w:])`).test(normalized);\n}\n\nfunction errorText(\n error: PlaywrightError | undefined,\n inputDir: string,\n): string | undefined {\n if (!error) return undefined;\n const message = [error.message, error.value, error.stack]\n .find((entry): entry is string => typeof entry === 'string' && entry.trim() !== '');\n const parts: string[] = [];\n if (message) parts.push(scrubPaths(stripAnsi(message), inputDir).trim());\n if (error.snippet) parts.push(scrubPaths(stripAnsi(error.snippet), inputDir).trim());\n const at = locationText(error.location, inputDir);\n if (at && !parts.some((part) => locationAlreadyPresent(part, at))) {\n parts.push(`at ${at}`);\n }\n return parts.filter(Boolean).join('\\n\\n') || undefined;\n}\n\nfunction resultErrorText(\n result: PlaywrightResult | undefined,\n inputDir: string,\n): string | undefined {\n // Playwright reports the same failure in `error` and `errors[0]`, so prefer\n // the array when it has entries and fall back to the single error otherwise.\n const errors =\n result?.errors && result.errors.length > 0 ? result.errors : [result?.error];\n const texts: string[] = [];\n for (const error of errors) {\n const text = errorText(error, inputDir);\n if (text && !texts.includes(text)) texts.push(text);\n }\n return texts.length > 0 ? texts.join('\\n\\n') : undefined;\n}\n\nfunction stepText(step: PlaywrightStep, depth: number): string {\n const subtitle = step.subtitle ? ` \u2014 ${step.subtitle}` : '';\n return `${'\u203A '.repeat(depth)}${step.title}${subtitle}`;\n}\n\nfunction flattenSteps(\n steps: PlaywrightStep[],\n depth = 0,\n): Array<{ text: string; durationMs: number; error?: PlaywrightError }> {\n const rows: Array<{ text: string; durationMs: number; error?: PlaywrightError }> = [];\n for (const step of steps) {\n // Playwright step durations are inclusive; subtract children so parent and\n // child are not counted twice by the report model.\n const childMs = step.steps.reduce((sum, child) => sum + child.duration, 0);\n rows.push({\n text: stepText(step, depth),\n durationMs: Math.max(0, step.duration - childMs),\n ...(step.error ? { error: step.error } : {}),\n });\n rows.push(...flattenSteps(step.steps, depth + 1));\n }\n return rows;\n}\n\nfunction statusOf(value: string): TestStepResultStatus {\n switch (value) {\n case 'passed':\n return TestStepResultStatus.PASSED;\n case 'skipped':\n return TestStepResultStatus.SKIPPED;\n case 'failed':\n case 'timedOut':\n case 'interrupted':\n return TestStepResultStatus.FAILED;\n default:\n return TestStepResultStatus.UNKNOWN;\n }\n}\n\nconst PASSED = TestStepResultStatus.PASSED;\nconst FAILED = TestStepResultStatus.FAILED;\nconst SKIPPED = TestStepResultStatus.SKIPPED;\n\nfunction canonicalSteps(\n result: PlaywrightResult | undefined,\n mode: 'expected-failure' | 'unexpected-pass' | 'skipped' | 'normal',\n inputDir: string,\n): CanonicalStep[] {\n const flat = flattenSteps(result?.steps ?? []);\n let steps: CanonicalStep[];\n\n if (mode === 'unexpected-pass') {\n steps = flat.map((step) => ({\n text: step.text,\n durationMs: step.durationMs,\n status: PASSED,\n }));\n steps.push({\n text: 'Unexpected pass',\n durationMs: steps.length > 0 ? 0 : (result?.duration ?? 0),\n status: FAILED,\n message: 'Unexpected pass: expected to fail, but passed.',\n });\n } else if (mode === 'expected-failure' || mode === 'skipped') {\n const status = mode === 'skipped' ? SKIPPED : PASSED;\n steps = flat.map((step) => ({\n text: step.text,\n durationMs: step.durationMs,\n status,\n }));\n if (steps.length === 0) {\n steps.push({\n text: mode === 'skipped' ? 'Skipped' : 'Expected failure',\n durationMs: result?.duration ?? 0,\n status,\n });\n }\n } else {\n if (!result) return [];\n\n const failed = FAILED_STATUSES.has(result.status);\n steps = flat.map((step) => {\n const message = errorText(step.error, inputDir);\n return {\n text: step.text,\n durationMs: step.durationMs,\n status: step.error ? FAILED : PASSED,\n ...(message ? { message } : {}),\n };\n });\n\n if (failed && !flat.some((step) => step.error)) {\n steps.push({\n text: 'Error',\n durationMs: steps.length > 0 ? 0 : result.duration,\n status: FAILED,\n message:\n resultErrorText(result, inputDir) ??\n `Playwright reported a ${result.status} result.`,\n });\n }\n\n if (steps.length === 0) {\n steps.push({\n text: 'Test',\n durationMs: result.duration,\n status: statusOf(result.status),\n });\n }\n }\n\n if (!result) return steps;\n const visibleMs = steps.reduce((sum, step) => sum + step.durationMs, 0);\n const residual = result.duration - visibleMs;\n if (residual > 0) {\n steps.push({\n text: 'Playwright overhead',\n durationMs: residual,\n status: mode === 'skipped' ? SKIPPED : PASSED,\n });\n }\n return steps;\n}\n\nfunction attemptSteps(result: PlaywrightResult, inputDir: string): CanonicalStep[] {\n return canonicalSteps(\n result,\n result.status === 'skipped' ? 'skipped' : 'normal',\n inputDir,\n );\n}\n\nconst NON_LOCAL_PATH = /^(?:https?|file):/i;\n\n// Reject URL schemes and UNC/device paths before any lstat, so a crafted JSON\n// report cannot make the adapter touch an SMB or device path.\nfunction isNonLocalPath(file: string): boolean {\n return (\n NON_LOCAL_PATH.test(file) ||\n file.startsWith('\\\\\\\\') ||\n file.startsWith('//')\n );\n}\n\nasync function readAttachment(\n candidate: string,\n context: PlanContext,\n): Promise<PlannedAttachment | undefined> {\n const info = await lstat(candidate).catch(() => undefined);\n if (!info || info.isSymbolicLink() || !info.isFile()) return undefined;\n\n const target = await realpath(candidate).catch(() => undefined);\n if (!target || !context.roots.some((root) => isInside(root, target))) {\n return undefined;\n }\n\n // Stat and read through the opened handle; the path could change after\n // realpath. Size caps are enforced on the descriptor, not the earlier lstat.\n const handle = await open(target, 'r').catch(() => undefined);\n if (!handle) return undefined;\n try {\n const stats = await handle.stat().catch(() => undefined);\n if (!stats || !stats.isFile()) return undefined;\n if (stats.size > MAX_ATTACHMENT_BYTES) {\n throw new Error('Attachment is larger than 50 MB. Use a smaller asset.');\n }\n if (context.totalAttachmentBytes + stats.size > MAX_TOTAL_ATTACHMENT_BYTES) {\n throw new Error(\n 'Attachments exceed 100 MB in total. Split the report or use smaller assets.',\n );\n }\n const data = await handle.readFile().catch(() => undefined);\n if (!data) return undefined;\n context.totalAttachmentBytes += stats.size;\n return {\n fileName: path.basename(candidate),\n mediaType: 'application/octet-stream',\n body: data.toString('base64'),\n contentEncoding: AttachmentContentEncoding.BASE64,\n };\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\nasync function resolveAttachmentPath(\n file: string,\n context: PlanContext,\n onSkip?: () => void,\n): Promise<PlannedAttachment | undefined> {\n if (isNonLocalPath(file)) return undefined;\n // Relative paths use the input directory first, then cwd for CI layouts where\n // reports/results.json and test-results/ are siblings.\n const candidates = path.isAbsolute(file)\n ? [file]\n : [path.resolve(context.inputDir, file), path.resolve(process.cwd(), file)];\n // Classify before reading: only a file that exists and resolves outside every\n // root is a skip. readAttachment keeps its own checks; a swap between the two\n // can only cause a false negative, never a read outside the roots.\n let outside = 0;\n let inside = 0;\n for (const candidate of candidates) {\n const info = await lstat(candidate).catch(() => undefined);\n if (!info || info.isSymbolicLink() || !info.isFile()) continue;\n const target = await realpath(candidate).catch(() => undefined);\n if (!target) continue;\n if (!context.roots.some((root) => isInside(root, target))) {\n outside += 1;\n continue;\n }\n inside += 1;\n const attachment = await readAttachment(candidate, context);\n if (attachment) return attachment;\n }\n if (outside > 0 && inside === 0) {\n context.skippedAttachments += 1;\n onSkip?.();\n }\n return undefined;\n}\n\n// Only folds Playwright's documented markdown case here; the shared\n// `src/attachment` module normalises and allow-lists media types.\nfunction playwrightMediaType(mediaType: string): string {\n return mediaType.split(';', 1)[0]?.trim().toLowerCase() === 'text/markdown'\n ? 'text/plain'\n : mediaType;\n}\n\nasync function attachmentsForResult(\n result: PlaywrightResult,\n context: PlanContext,\n): Promise<{ attachments: PlannedAttachment[]; skipped: number }> {\n const planned: PlannedAttachment[] = [];\n let skipped = 0;\n\n for (const attachment of result.attachments) {\n if (\n attachment.name.toLowerCase() === 'trace' &&\n attachment.contentType.toLowerCase().startsWith('application/zip')\n ) {\n // Trace zips are not readable in a report; keep them out of the budget.\n continue;\n }\n if (attachment.body !== undefined && attachment.body !== '') {\n planned.push({\n fileName: attachment.name,\n mediaType: playwrightMediaType(attachment.contentType),\n body: attachment.body,\n contentEncoding: AttachmentContentEncoding.BASE64,\n });\n continue;\n }\n if (attachment.path === undefined) continue;\n const file = await resolveAttachmentPath(attachment.path, context, () => {\n skipped += 1;\n });\n if (!file) continue;\n planned.push({\n ...file,\n fileName: attachment.name || file.fileName,\n mediaType: playwrightMediaType(attachment.contentType),\n });\n }\n\n for (const field of ['stdout', 'stderr'] as const) {\n for (const [index, output] of result[field].entries()) {\n if (output.text !== undefined) {\n planned.push({\n fileName: `${field} ${index + 1}`,\n mediaType: 'text/plain',\n body: Buffer.from(output.text, 'utf8').toString('base64'),\n contentEncoding: AttachmentContentEncoding.BASE64,\n });\n } else if (output.buffer !== undefined) {\n planned.push({\n fileName: `${field} ${index + 1} buffer`,\n mediaType: 'application/octet-stream',\n body: output.buffer,\n contentEncoding: AttachmentContentEncoding.BASE64,\n });\n }\n }\n }\n\n return { attachments: planned, skipped };\n}\n\nfunction featureFor(\n context: PlanContext,\n project: string | undefined,\n file: string,\n): FeaturePlan {\n const hasProject = Boolean(project);\n const name = project || file;\n const key = hasProject ? `project:${name}` : `file:${file}`;\n const existing = context.features.get(key);\n if (existing) return existing;\n const feature: FeaturePlan = {\n name,\n uri: hasProject\n ? `playwright://${context.idPrefix}/${encodeURIComponent(name)}`\n : `playwright://${context.idPrefix}/file/${encodeURIComponent(file)}`,\n rules: new Map(),\n order: [],\n };\n context.features.set(key, feature);\n context.featureOrder.push(feature);\n return feature;\n}\n\nfunction ruleFor(\n context: PlanContext,\n feature: FeaturePlan,\n name: string,\n): RulePlan {\n const existing = feature.rules.get(name);\n if (existing) return existing;\n const rule: RulePlan = {\n id: context.nextId('rule'),\n name,\n scenarios: [],\n };\n feature.rules.set(name, rule);\n feature.order.push(rule);\n return rule;\n}\n\nasync function scenarioPlan(\n context: PlanContext,\n feature: FeaturePlan,\n spec: PlaywrightSpec,\n test: PlaywrightTest,\n describes: string[],\n): Promise<ScenarioPlan> {\n const file = fileUri(spec.file, context.inputDir);\n const ruleName = [stripTrailingTags(file), ...describes]\n .filter(Boolean)\n .join(' \u203A ');\n const rule = ruleFor(context, feature, ruleName || file);\n const name = stripTrailingTags(spec.title) || `Test ${rule.scenarios.length + 1}`;\n const results = test.results;\n const finalIndex =\n results.length > 0\n ? results.reduce(\n (best, candidate, index) =>\n candidate.retry > (results[best] as PlaywrightResult).retry ? index : best,\n 0,\n )\n : -1;\n const final = finalIndex >= 0 ? results[finalIndex] : undefined;\n const finalStatus = final?.status;\n const skipped =\n test.status === 'skipped' ||\n test.expectedStatus === 'skipped' ||\n finalStatus === 'skipped';\n const failedFinal =\n finalStatus !== undefined && FAILED_STATUSES.has(finalStatus);\n const passedFinal = finalStatus === 'passed';\n const expectsFailure = test.expectedStatus === 'failed';\n const expectedFailure =\n failedFinal && (test.status === 'expected' || expectsFailure);\n const unexpectedPass =\n passedFinal && (test.status === 'unexpected' || expectsFailure);\n const flakyPass = passedFinal && test.status === 'flaky';\n\n const mode = expectedFailure\n ? 'expected-failure'\n : unexpectedPass\n ? 'unexpected-pass'\n : skipped\n ? 'skipped'\n : 'normal';\n const canonical = canonicalSteps(final, mode, context.inputDir);\n\n const tagNames: string[] = [];\n const addTag = (value: string): void => {\n const name = value.startsWith('@') ? value : `@${value}`;\n if (name.length > 1 && !tagNames.includes(name)) tagNames.push(name);\n };\n for (const tag of spec.tags) addTag(tag);\n for (const annotation of test.annotations) {\n if (KNOWN_ANNOTATIONS.has(annotation.type.toLowerCase())) {\n addTag(annotation.type);\n }\n }\n if (expectedFailure) addTag('expected-failure');\n if (unexpectedPass) addTag('unexpected-pass');\n if (flakyPass) addTag('flaky');\n\n const descriptionParts = test.annotations.map((annotation) =>\n annotation.description\n ? `Annotation: ${annotation.type} - ${annotation.description}`\n : `Annotation: ${annotation.type}`,\n );\n if (expectedFailure) {\n const text = resultErrorText(final, context.inputDir);\n if (text) descriptionParts.push(text);\n }\n if (unexpectedPass) {\n descriptionParts.push('Unexpected pass: expected to fail, but passed.');\n }\n\n const scenarioId = context.nextId('scenario');\n const stepNodes: Step[] = canonical.map((step) => ({\n id: context.nextId('step'),\n location: location(spec.line),\n keyword: '',\n text: step.text,\n }));\n const scenario: Scenario = {\n id: scenarioId,\n location: location(spec.line, spec.column),\n tags: tagNames.map((tag) => ({\n id: context.nextId('tag'),\n name: tag,\n location: location(spec.line),\n })),\n keyword: 'Scenario',\n name,\n description: descriptionParts.join('\\n\\n'),\n steps: stepNodes,\n examples: [],\n };\n\n const pickleSteps: PickleStep[] = stepNodes.map((step) => ({\n id: context.nextId('pickle-step'),\n text: step.text,\n astNodeIds: [step.id],\n }));\n const pickle: Pickle = {\n id: context.nextId('pickle'),\n uri: file,\n location: pickleLocation(spec.line, spec.column),\n name,\n language: 'en',\n steps: pickleSteps,\n tags: scenario.tags.map((tag) => ({\n name: tag.name,\n astNodeId: tag.id,\n })),\n astNodeIds: [scenarioId],\n };\n const testSteps: TestStep[] = pickleSteps.map((step) => ({\n id: context.nextId('test-step'),\n pickleStepId: step.id,\n }));\n const testCase: TestCase = {\n id: context.nextId('test-case'),\n pickleId: pickle.id,\n testSteps,\n testRunStartedId: context.runId,\n };\n\n // Register before the attachment reads: scenario collection starts every\n // async plan up front, so a later push could otherwise reorder the report.\n const plan: ScenarioPlan = { scenario, pickle, testCase, attempts: [] };\n rule.scenarios.push(plan);\n if (results.length === 0) {\n plan.attempts.push({\n attempt: 0,\n timestamp: context.runTimestamp,\n steps: skipped ? canonical : [],\n attachments: [],\n skippedAttachments: 0,\n willBeRetried: false,\n });\n } else {\n for (const [index, result] of results.entries()) {\n const isFinal = index === finalIndex;\n // Earlier attempts are never rendered; reading their attachments would\n // spend the total byte budget twice per retry.\n const finalAttachments = isFinal\n ? await attachmentsForResult(result, context)\n : undefined;\n plan.attempts.push({\n attempt: result.retry,\n timestamp: timestampOf(result.startTime, context.runTimestamp),\n steps: isFinal ? canonical : attemptSteps(result, context.inputDir),\n attachments: finalAttachments?.attachments ?? [],\n skippedAttachments: finalAttachments?.skipped ?? 0,\n willBeRetried: index < results.length - 1,\n });\n }\n }\n\n return plan;\n}\n\nfunction collectScenarios(\n context: PlanContext,\n suite: PlaywrightSuite,\n describes: string[],\n file: string,\n): Array<() => Promise<void>> {\n const suiteFile = stripTrailingTags(suite.file ?? file);\n const jobs: Array<() => Promise<void>> = [];\n\n for (const spec of suite.specs) {\n const specFile = stripTrailingTags(spec.file ?? suiteFile);\n for (const test of spec.tests) {\n const project = test.projectName || test.projectId;\n jobs.push(() =>\n scenarioPlan(\n context,\n featureFor(context, project, specFile),\n spec,\n test,\n describes,\n ).then(() => undefined),\n );\n }\n }\n\n for (const child of suite.suites) {\n const title = stripTrailingTags(child.title ?? '');\n const childFile = stripTrailingTags(child.file ?? suiteFile);\n const nextDescribes =\n title && title !== suiteFile && title !== childFile\n ? [...describes, title]\n : describes;\n jobs.push(...collectScenarios(context, child, nextDescribes, childFile));\n }\n\n return jobs;\n}\n\nfunction addErrorFeature(\n context: PlanContext,\n errors: unknown[],\n): void {\n if (errors.length === 0) return;\n const feature: FeaturePlan = {\n name: 'Playwright',\n uri: `playwright://${context.idPrefix}/errors`,\n rules: new Map(),\n order: [],\n };\n for (const [index, value] of errors.entries()) {\n if (!isObject(value)) {\n throw invalid(context.source, `errors[${index}] must be an object.`);\n }\n const error = validateError(value, context.source, `errors[${index}]`);\n const name = `Run error ${index + 1}`;\n const message =\n errorText(error, context.inputDir) ?? 'Playwright reported a run error.';\n const scenarioId = context.nextId('scenario');\n const stepId = context.nextId('step');\n const scenario: Scenario = {\n id: scenarioId,\n location: location(1),\n tags: [],\n keyword: 'Scenario',\n name,\n description: '',\n steps: [{ id: stepId, location: location(1), keyword: '', text: 'Playwright error' }],\n examples: [],\n };\n const pickleStep: PickleStep = {\n id: context.nextId('pickle-step'),\n text: 'Playwright error',\n astNodeIds: [stepId],\n };\n const pickle: Pickle = {\n id: context.nextId('pickle'),\n uri: `playwright://${context.idPrefix}/errors`,\n // The pseudo-file has no source line; the AST placeholder stays at 1.\n location: pickleLocation(),\n name,\n language: 'en',\n steps: [pickleStep],\n tags: [],\n astNodeIds: [scenarioId],\n };\n const testStep: TestStep = {\n id: context.nextId('test-step'),\n pickleStepId: pickleStep.id,\n };\n const testCase: TestCase = {\n id: context.nextId('test-case'),\n pickleId: pickle.id,\n testSteps: [testStep],\n testRunStartedId: context.runId,\n };\n const plan: ScenarioPlan = {\n scenario,\n pickle,\n testCase,\n attempts: [\n {\n attempt: 0,\n timestamp: context.runTimestamp,\n steps: [{ text: 'Playwright error', durationMs: 0, status: FAILED, message }],\n attachments: [],\n skippedAttachments: 0,\n willBeRetried: false,\n },\n ],\n };\n const rule = ruleFor(context, feature, 'Playwright');\n rule.scenarios.push(plan);\n }\n context.features.set('errors', feature);\n context.featureOrder.push(feature);\n}\n\nfunction featureDocument(feature: FeaturePlan): Feature {\n const children: FeatureChild[] = feature.order.map((plan) => {\n const rule: Rule = {\n id: plan.id,\n location: location(1),\n tags: [],\n keyword: 'Rule',\n name: plan.name,\n description: '',\n children: plan.scenarios.map((scenario): RuleChild => ({\n scenario: scenario.scenario,\n })),\n };\n return { rule };\n });\n return {\n location: location(1),\n tags: [],\n language: 'en',\n keyword: 'Feature',\n name: feature.name,\n description: '',\n children,\n };\n}\n\n/**\n * Normalises a Playwright JSON reporter file into Cucumber Messages. It builds\n * the envelopes directly so retries stay separate attempts; the latest attempt\n * is the rendered result.\n */\nexport async function parsePlaywrightJson(\n parsed: unknown,\n source: string,\n options: PlaywrightJsonOptions = {},\n): Promise<PlaywrightParseResult> {\n if (!isObject(parsed)) {\n throw invalid(source, 'expected a Playwright report object.');\n }\n if (!isObject(parsed.config)) {\n throw invalid(source, 'config must be an object.');\n }\n if (!isObject(parsed.stats)) {\n throw invalid(source, 'stats must be an object.');\n }\n if (parsed.suites !== undefined && !Array.isArray(parsed.suites)) {\n throw invalid(source, 'suites must be an array.');\n }\n if (parsed.errors !== undefined && !Array.isArray(parsed.errors)) {\n throw invalid(source, 'errors must be an array.');\n }\n\n const idPrefix = options.idPrefix ?? 'playwright';\n let counter = 0;\n const nextId = (kind: string): string => `${idPrefix}-${kind}-${counter++}`;\n const runId = nextId('run');\n\n const startTime = optionalString(parsed.stats, 'startTime', source, 'stats');\n const startMs = startTime ? Date.parse(startTime) : Number.NaN;\n const runTimestamp = timestamp(Number.isFinite(startMs) ? startMs : 0);\n const sourcePath = path.resolve(source);\n const inputDir = await realpath(sourcePath)\n .then((resolved) => path.dirname(resolved))\n .catch(() => path.dirname(sourcePath));\n const roots: string[] = [];\n for (const root of [inputDir, process.cwd()]) {\n try {\n roots.push(await realpath(root));\n } catch {\n roots.push(path.resolve(root));\n }\n }\n\n const context: PlanContext = {\n source,\n idPrefix,\n inputDir,\n roots,\n nextId,\n totalAttachmentBytes: 0,\n features: new Map(),\n featureOrder: [],\n runId,\n runTimestamp,\n skippedAttachments: 0,\n };\n\n const suites = (parsed.suites ?? []) as unknown[];\n const rootsSuites = suites.map((suite, index) =>\n validateSuite(suite, source, `suites[${index}]`),\n );\n\n for (const suite of rootsSuites) {\n const file = stripTrailingTags(suite.file ?? suite.title ?? 'playwright.spec.ts');\n // Await in collection order so I/O timing cannot reorder scenarios.\n for (const job of collectScenarios(context, suite, [], file)) await job();\n }\n\n addErrorFeature(context, Array.isArray(parsed.errors) ? parsed.errors : []);\n\n const featureEnvelopes: Envelope[][] = [];\n\n for (const feature of context.featureOrder) {\n const envelopes: Envelope[] = [\n {\n gherkinDocument: {\n uri: feature.uri,\n feature: featureDocument(feature),\n comments: [],\n },\n },\n ];\n for (const rule of feature.order) {\n for (const plan of rule.scenarios) {\n envelopes.push({ pickle: plan.pickle });\n envelopes.push({ testCase: plan.testCase });\n for (const attempt of plan.attempts) {\n const startedId = nextId('test-case-started');\n const started: TestCaseStarted = {\n id: startedId,\n testCaseId: plan.testCase.id,\n attempt: attempt.attempt,\n timestamp: attempt.timestamp,\n };\n if (attempt.skippedAttachments > 0) {\n recordSkippedAttachments(started, attempt.skippedAttachments);\n }\n envelopes.push({\n testCaseStarted: started,\n });\n let clock = attempt.timestamp;\n const count = Math.min(attempt.steps.length, plan.testCase.testSteps.length);\n for (let index = 0; index < count; index += 1) {\n const testStep = plan.testCase.testSteps[index] as TestStep;\n const step = attempt.steps[index] as CanonicalStep;\n envelopes.push({\n testStepStarted: {\n testCaseStartedId: startedId,\n testStepId: testStep.id,\n timestamp: clock,\n },\n });\n const duration = durationOf(step.durationMs);\n const result: TestStepResult = {\n status: step.status,\n duration,\n };\n if (step.message) result.message = step.message;\n clock = addDuration(clock, step.durationMs);\n envelopes.push({\n testStepFinished: {\n testCaseStartedId: startedId,\n testStepId: testStep.id,\n testStepResult: result,\n timestamp: clock,\n },\n });\n }\n for (const attachment of attempt.attachments) {\n const envelope: Attachment = {\n ...attachment,\n testCaseStartedId: startedId,\n timestamp: clock,\n };\n envelopes.push({ attachment: envelope });\n }\n envelopes.push({\n testCaseFinished: {\n testCaseStartedId: startedId,\n timestamp: clock,\n willBeRetried: attempt.willBeRetried,\n },\n });\n }\n }\n }\n featureEnvelopes.push(envelopes);\n }\n\n const meta: Meta = {\n protocolVersion: '',\n implementation: {\n name: 'Playwright',\n ...(typeof parsed.config.version === 'string'\n ? { version: parsed.config.version }\n : {}),\n },\n runtime: { name: '' },\n os: { name: '' },\n cpu: { name: '' },\n };\n const envelopes: Envelope[] = [\n { meta },\n { testRunStarted: { id: runId, timestamp: runTimestamp } },\n ];\n for (const feature of featureEnvelopes) {\n for (const envelope of feature) envelopes.push(envelope);\n }\n\n const duration = optionalNumber(parsed.stats, 'duration', source, 'stats') ?? 0;\n const success = !envelopes.some(\n (envelope) => envelope.testStepFinished?.testStepResult.status === FAILED,\n );\n envelopes.push({\n testRunFinished: {\n testRunStartedId: runId,\n success,\n timestamp: addDuration(runTimestamp, duration),\n },\n });\n\n return { envelopes, skippedAttachments: context.skippedAttachments };\n}\n", "import type { Attachment } from '@cucumber/messages';\n\n/** Per-attachment cap; the sanitizer checks decoded bytes, the Playwright adapter checks file size. */\nexport const MAX_ATTACHMENT_BYTES = 50 * 1024 * 1024;\n/** Total attachment cap; the sanitizer applies it per report, the Playwright adapter per input. */\nexport const MAX_TOTAL_ATTACHMENT_BYTES = 100 * 1024 * 1024;\n/** Text attachments above this size skip JSON pretty-printing and ANSI colouring. */\nexport const MAX_TEXT_ATTACHMENT_BYTES = 262_144;\n\nexport type AttachmentKind = 'image' | 'video' | 'audio' | 'text' | 'binary';\nexport type AttachmentTextFormat = 'json' | 'uri-list' | 'log' | 'plain';\n\nexport interface AttachmentMetadata {\n /** Allowlisted media type. */\n mediaType: string;\n kind: AttachmentKind;\n /** Non-empty Cucumber file name; otherwise the deterministic fallback. */\n fileName: string;\n /** Decoded bytes, not the base64 length. */\n bytes: number;\n /** Text presentation the renderer uses. */\n textFormat: AttachmentTextFormat;\n}\n\ninterface MediaTypeInfo {\n extension: string;\n kind: AttachmentKind;\n textFormat: AttachmentTextFormat;\n}\n\nconst MEDIA_TYPES: Record<string, MediaTypeInfo> = {\n 'application/json': { extension: 'json', kind: 'text', textFormat: 'json' },\n 'application/octet-stream': { extension: 'bin', kind: 'binary', textFormat: 'plain' },\n 'image/gif': { extension: 'gif', kind: 'image', textFormat: 'plain' },\n 'image/jpeg': { extension: 'jpg', kind: 'image', textFormat: 'plain' },\n 'image/png': { extension: 'png', kind: 'image', textFormat: 'plain' },\n 'image/svg+xml': { extension: 'svg', kind: 'image', textFormat: 'plain' },\n 'image/webp': { extension: 'webp', kind: 'image', textFormat: 'plain' },\n 'text/csv': { extension: 'csv', kind: 'text', textFormat: 'plain' },\n 'text/html': { extension: 'html', kind: 'text', textFormat: 'plain' },\n 'text/plain': { extension: 'txt', kind: 'text', textFormat: 'plain' },\n 'text/uri-list': { extension: 'txt', kind: 'text', textFormat: 'uri-list' },\n 'text/x.cucumber.log+plain': { extension: 'log', kind: 'text', textFormat: 'log' },\n 'video/mp4': { extension: 'mp4', kind: 'video', textFormat: 'plain' },\n 'video/webm': { extension: 'webm', kind: 'video', textFormat: 'plain' },\n};\n\n// `text/html` is only ever rendered as escaped text inside <pre>, never as\n// markup. `image/svg+xml` is only used as an <img> data-URI source, where\n// scripts do not run. Neither type reaches the document as HTML.\n\nexport function normalizedMediaType(mediaType: string): string {\n return mediaType.split(';')[0]?.trim().toLowerCase() ?? '';\n}\n\nconst SAFE_MEDIA_TYPES = new Set(Object.keys(MEDIA_TYPES));\n\n/**\n * Normalises a declared media type and drops everything outside the report's\n * renderer list. Unknown or forged types (XHTML, XML, comma-joined values)\n * become application/octet-stream so they can never reach a data URI verbatim.\n */\nexport function safeMediaType(mediaType: string): string {\n const base = normalizedMediaType(mediaType || '');\n return SAFE_MEDIA_TYPES.has(base) ? base : 'application/octet-stream';\n}\n\n/**\n * Counts canonical base64 decoded bytes without decoding; non-canonical bodies\n * keep the length-based estimate. This is the summary's `attachments.bytes`.\n */\nexport function attachmentBytes(\n attachment: Pick<Attachment, 'body' | 'contentEncoding'>,\n): number {\n const body = attachment.body ?? '';\n if (attachment.contentEncoding === 'BASE64') {\n const padding = body.endsWith('==') ? 2 : body.endsWith('=') ? 1 : 0;\n return Math.max(0, Math.floor((body.length * 3) / 4) - padding);\n }\n return Buffer.byteLength(body, 'utf8');\n}\n\nexport function attachmentMetadata(\n attachment: Pick<\n Attachment,\n 'body' | 'contentEncoding' | 'fileName' | 'mediaType'\n >,\n): AttachmentMetadata {\n const mediaType = safeMediaType(\n attachment.mediaType || 'application/octet-stream',\n );\n const info =\n MEDIA_TYPES[mediaType] ?? MEDIA_TYPES['application/octet-stream'];\n return {\n mediaType,\n kind: info.kind,\n fileName: attachment.fileName || `attachment.${info.extension}`,\n bytes: attachmentBytes(attachment),\n textFormat: info.textFormat,\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 { detectInput } from './detect.js';\nimport { parseLegacyJson, parseLegacyValue } from './legacy.js';\nimport { collectReportFiles } from './files.js';\nimport { parseJUnitXml } from './junit.js';\nimport { parseMessages } from './messages.js';\nimport { parsePlaywrightJson } from './playwright.js';\n\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\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 skippedAttachments: number;\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 decision = detectInput(content, input);\n let parsed: Envelope[] = [];\n let skippedAttachments = 0;\n\n switch (decision.kind) {\n case 'legacy':\n parsed = parseLegacyValue(decision.parsed, input.file, {\n idPrefix: `legacy-${index}`,\n });\n break;\n case 'legacy-validation':\n // Validation-only: throws on malformed JSON; there is no result to add.\n parseLegacyJson(content, input.file, { idPrefix: `legacy-${index}` });\n break;\n case 'junit':\n parsed = await parseJUnitXml(content, input.file, {\n idPrefix: `junit-${index}`,\n });\n break;\n case 'junit-validation':\n // Validation-only: throws when the explicit XML is not usable JUnit.\n await parseJUnitXml(content, input.file, {\n idPrefix: `junit-${index}`,\n });\n break;\n case 'messages':\n parsed = parseMessages(content, input.file);\n break;\n case 'messages-validation':\n // Validation-only fallback; valid Messages are handled above.\n parseMessages(content, input.file);\n break;\n case 'playwright':\n ({\n envelopes: parsed,\n skippedAttachments,\n } = await parsePlaywrightJson(decision.parsed, input.file, {\n idPrefix: `playwright-${index}`,\n }));\n break;\n case 'json-validation':\n invalidJson(content, input.file);\n break;\n case 'skip':\n break;\n }\n\n groups.push({ file: input.file, envelopes: parsed, skippedAttachments });\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,YAAAA,iBAAgB;AACzB,SAAS,sBAAsB;;;ACD/B,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,SAAS,OAAO,QAAQ,IAAI,MAAM,iBAAiB;AACnD,OAAOC,WAAU;;;ACHjB,SAAS,eAAe;AACxB,OAAO,UAAU;AAEV,IAAM,uBAAuB,oBAAI,IAAI;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,sBAAsB;AAC5B,IAAM,sBAAsB,oBAAI,IAAI,CAAC,gBAAgB,QAAQ,OAAO,MAAM,CAAC;AAE3E,eAAsB,mBACpB,WACA,QAAQ,GACW;AACnB,MAAI,QAAQ,qBAAqB;AAC/B,UAAM,IAAI;AAAA,MAC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epResultStatus", "path", "stat", "readFile"]
7
7
  }
@@ -24,7 +24,11 @@ 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>;
32
+ /** Strips one leading UTF-8 BOM, as the core loader does. */
33
+ export declare function stripBom(content: string): string;
30
34
  export declare function resolveInputs(options: CucumberHtmlReporterOptions, warnings: string[]): Promise<string[]>;
@@ -0,0 +1,18 @@
1
+ import type { ReportSummary } from './summary.js';
2
+ export interface EmailOptions {
3
+ /** Used verbatim after escaping; defaults to Tolkira report. */
4
+ title?: string;
5
+ /** Email language tag; defaults to English. */
6
+ locale?: string;
7
+ /** Full report name; only its basename reaches the note. */
8
+ reportName?: string;
9
+ /** Hex accent; invalid values are ignored. */
10
+ accent?: string;
11
+ /** Generation time, labelled Generated; defaults to now. */
12
+ now?: Date;
13
+ }
14
+ /**
15
+ * Renders one self-contained HTML email summary from a stable report summary.
16
+ * Writes nothing, sends nothing and makes no request.
17
+ */
18
+ export declare function renderEmail(summary: ReportSummary, options?: EmailOptions): string;
@@ -0,0 +1,41 @@
1
+ import type { ReportSummary, StatusCounts, SummaryStatus } from './summary.js';
2
+ export declare const HISTORY_SCHEMA_VERSION = 1;
3
+ export declare const HISTORY_LIMIT = 30;
4
+ export declare const HISTORY_MAX_BYTES: number;
5
+ /** Stored titles are capped at 200 characters, the last one being an ellipsis. */
6
+ export declare const HISTORY_MAX_TITLE = 200;
7
+ /** One aggregate run in the history sidecar; no scenario names or steps. */
8
+ export interface HistoryRun {
9
+ id: string;
10
+ recordedAt: string;
11
+ title: string;
12
+ status: SummaryStatus;
13
+ counts: {
14
+ features: number;
15
+ scenarios: StatusCounts;
16
+ steps: StatusCounts;
17
+ };
18
+ durationMs: number;
19
+ attachments: {
20
+ total: number;
21
+ bytes: number;
22
+ };
23
+ }
24
+ /**
25
+ * Builds one aggregate history entry. The id hashes everything except the
26
+ * recorded time, so regenerating an identical run dedupes instead of growing.
27
+ */
28
+ export declare function buildHistoryRun(summary: ReportSummary, title: string, now?: Date): HistoryRun;
29
+ /** Appends a run unless the last entry is the same aggregate; keeps the last 30. */
30
+ export declare function appendHistory(runs: readonly HistoryRun[], run: HistoryRun): HistoryRun[];
31
+ /**
32
+ * Reads the sidecar. A missing file is an empty history; a corrupt, oversized,
33
+ * non-regular or unsupported file throws without touching it. The descriptor
34
+ * is opened non-blocking and capped before any content is read.
35
+ */
36
+ export declare function readHistory(file: string): Promise<HistoryRun[]>;
37
+ /**
38
+ * Writes schema version 1 JSON atomically, with a trailing newline. The list is
39
+ * bounded to the newest 30 runs and every stored title to the documented cap.
40
+ */
41
+ export declare function writeHistory(file: string, runs: readonly HistoryRun[]): Promise<void>;
@@ -0,0 +1,7 @@
1
+ export type MessageKey = "attachment.attachmentName" | "attachment.copyLog" | "attachment.copyLogLabel" | "attachment.screenshotFor" | "attachment.viewFullSize" | "ci.branch" | "ci.label" | "ci.revision" | "ci.tag" | "client.clipboardError" | "client.clipboardExample" | "client.clipboardFeature" | "client.clipboardHook" | "client.clipboardScenario" | "client.clipboardStep" | "client.clipboardUri" | "client.copied" | "client.copyFailed" | "client.copyFailure" | "client.copyFailureDone" | "client.copyFailureFailed" | "client.copyLog" | "client.empty" | "client.emptyPreset" | "client.logCopied" | "client.logCopyFailed" | "client.searchNote" | "client.visibleCount" | "details.agentSummary" | "details.agentSummaryJson" | "details.agentSummaryNote" | "details.attachmentSize" | "details.attachments" | "details.cpu" | "details.customMetadata" | "details.durationNote" | "details.featureSpend" | "details.features" | "details.fullSummary" | "details.hooks" | "details.matrixHint" | "details.matrixLabel" | "details.os" | "details.passRateNote" | "details.path" | "details.producer" | "details.protocol" | "details.run" | "details.runAttachments" | "details.runEnvironment" | "details.runtime" | "details.scenarios" | "details.source" | "details.statusDistribution" | "details.steps" | "details.tab" | "details.testTime" | "details.title" | "email.attachments" | "email.duration" | "email.empty" | "email.failedTitle" | "email.features" | "email.footer" | "email.generated" | "email.moreFailures" | "email.noFailures" | "email.noFailuresStatus" | "email.passRate" | "email.passRateNote" | "email.reportMissing" | "email.reportNote" | "email.steps" | "email.title" | "email.unexecuted" | "format.attemptedRatio" | "format.bytes" | "format.emptyRatio" | "format.noAttempts" | "format.passedOfAttempted" | "format.skippedNotAttempts" | "format.specFiles" | "lightbox.close" | "lightbox.label" | "markdown.descriptionTable" | "matrix.feature" | "matrix.scenarioTime" | "matrix.total" | "report.allTags" | "report.attachmentCount" | "report.attachmentNotice" | "report.attachments" | "report.attemptMeta" | "report.collapseAll" | "report.copyFailure" | "report.dataTable" | "report.diagnostic.ambiguous" | "report.diagnostic.undefined" | "report.diagnostic.undefinedSuggestions" | "report.exampleLabel" | "report.examplesLabel" | "report.expandAll" | "report.failedOnly" | "report.featureCount" | "report.featureCounts" | "report.featureCountsAttention" | "report.featureCountsZero" | "report.featureCountsZeroAttention" | "report.featureMeta" | "report.flakyBadge" | "report.flakySummary" | "report.footer" | "report.hookCount" | "report.noMatches" | "report.noScenarios" | "report.notExecuted" | "report.outlineLabel" | "report.passedHooks" | "report.ruleMeta" | "report.run" | "report.runHooks" | "report.scenarioCount" | "report.scenarioMeta" | "report.scenarioWithResults" | "report.searchLabel" | "report.searchPlaceholder" | "report.sourceFrom" | "report.startedMeta" | "report.stepCount" | "report.steps" | "report.stepsAndHooks" | "report.tab" | "report.tag" | "report.testTime" | "report.testTimeTitle" | "report.unexecuted" | "report.views" | "status.ambiguous" | "status.failed" | "status.passed" | "status.pending" | "status.skipped" | "status.undefined" | "status.unknown" | "trends.current" | "trends.duration" | "trends.newestFirst" | "trends.passRate" | "trends.passRateNote" | "trends.path" | "trends.recorded" | "trends.recordedRuns" | "trends.runs" | "trends.sparkLead" | "trends.status" | "trends.tab" | "trends.tableHint" | "trends.tableLabel" | "trends.title" | "trends.titleColumn" | "trends.total" | "triage.featureCount" | "triage.firstFailure" | "triage.lead" | "triage.moreBelow" | "triage.moreInReport" | "triage.moreInputs" | "triage.needsAttention" | "triage.scenarioCount" | "triage.showMore" | "triage.sources";
2
+ export declare const en: Record<MessageKey, string>;
3
+ export declare const de: Record<MessageKey, string>;
4
+ export declare const catalogs: {
5
+ readonly en: Record<MessageKey, string>;
6
+ readonly de: Record<MessageKey, string>;
7
+ };
package/dist/index.d.ts CHANGED
@@ -1,17 +1,25 @@
1
+ import { type HistoryRun } from './history.js';
2
+ import { type RenderReportOptions } from './options.js';
1
3
  import type { ReportSummary } from './summary.js';
2
- export declare const version = "0.2.0";
4
+ export declare const version = "0.4.0";
3
5
  export declare const phase = "development";
4
6
  export type { ReportSummary, StatusCounts, SummaryScenario, SummaryStatus, SummaryStep, } from './summary.js';
5
7
  export { summarizeReport, SUMMARY_SCHEMA_VERSION } from './summary.js';
6
- export interface RenderReportOptions {
7
- title?: string;
8
- metadata?: Record<string, string>;
9
- logo?: string;
10
- accent?: string;
11
- }
8
+ export type { HistoryRun } from './history.js';
9
+ export { HISTORY_LIMIT, HISTORY_MAX_BYTES, HISTORY_MAX_TITLE, HISTORY_SCHEMA_VERSION, appendHistory, buildHistoryRun, readHistory, writeHistory, } from './history.js';
10
+ export type { RenderReportOptions } from './options.js';
11
+ export type { EmailOptions } from './email.js';
12
+ export { renderEmail } from './email.js';
13
+ export type { PdfOptions } from './pdf.js';
14
+ export { renderPdf } from './pdf.js';
15
+ export { CucumberHtmlStream } from './stream.js';
12
16
  export interface GeneratedReport {
13
17
  html: string;
14
18
  summary: ReportSummary;
19
+ skippedAttachments: number;
20
+ /** The history the report was rendered with, current run appended. */
21
+ history?: HistoryRun[];
15
22
  }
16
23
  export declare function generateReport(inputs: string | string[], options?: RenderReportOptions): Promise<GeneratedReport>;
24
+ /** Renders the HTML with the given history; records nothing. */
17
25
  export declare function renderReport(inputs: string | string[], options?: RenderReportOptions): Promise<string>;