Skip to main content

API Reference

The reference implementation, written in TypeScript, provides utilities for working with CTRF reports and is maintained alongside the specification.

It serves as the canonical guide for implementing CTRF in any language.

Installation​

npm install ctrf@0.6.0

Quick Start​

import {
ReportBuilder,
TestBuilder,
validate,
parse,
stringify,
} from 'ctrf'

const report = new ReportBuilder()
.runId('run-2026-08-15')
.tool({ name: 'jest', version: '29.0.0' })
.addTest(
new TestBuilder()
.testId('math/adds-numbers')
.executionId('execution-123')
.attemptId('attempt-1')
.name('should add numbers')
.description('Checks integer addition')
.status('passed')
.duration(150)
.build()
)
.build()

const result = validate(report)
if (result.valid) {
console.log('Report is valid!')
}

const parsedReport = parse(stringify(report), { validate: true })

Core Functions​

validate​

Validate a CTRF report against the JSON schema and normative cross-field rules, including provenance identity constraints.

function validate(report: unknown, options?: ValidateOptions): ValidationResult

Parameters:

  • report - The object to validate
  • options.specVersion - Supported specification version or latest (default). Current reports use 0.3.0.

SchemaSelector accepts latest or a published supported specification version; SupportedSpecVersion names the supported version strings.

Returns: ValidationResult with valid boolean and errors array

Example:

import { validate } from 'ctrf'

const result = validate(report)
if (!result.valid) {
console.log('Validation errors:', result.errors)
}

// Validate against specific version
const versionedResult = validate(report, { specVersion: '0.3.0' })

isValid​

Type guard to check if a report is valid.

function isValid(report: unknown, options?: ValidateOptions): report is CTRFReport

Example:

import { isValid } from 'ctrf'

if (isValid(report)) {
// TypeScript knows report is CTRFReport
console.log(report.results.summary.passed)
}

validateStrict​

Validate and throw if invalid.

function validateStrict(report: unknown, options?: ValidateOptions): asserts report is CTRFReport

Throws: ValidationError if the report is invalid

Example:

import { validateStrict, ValidationError } from 'ctrf'

try {
validateStrict(report)
// TypeScript knows report is CTRFReport
} catch (e) {
if (e instanceof ValidationError) {
console.log(e.errors)
}
}

parse​

Parse a JSON string into a CTRFReport.

function parse(json: string, options?: ParseOptions): CTRFReport

Parameters:

  • json - JSON string to parse
  • options.validate - Enable schema validation (default: false)

Throws: ParseError if JSON is invalid, ValidationError if validation fails

Example:

import { parse } from 'ctrf'

const report = parse(jsonString)

// With validation
const validatedReport = parse(jsonString, { validate: true })

stringify​

Serialize a CTRFReport to JSON.

function stringify(report: CTRFReport, options?: StringifyOptions): string

Parameters:

  • report - The CTRF report to serialize
  • options.pretty - Enable pretty printing (default: false)
  • options.indent - Indentation size (default: 2)

Example:

import { stringify } from 'ctrf'

const json = stringify(report)

// Pretty print
const prettyJson = stringify(report, { pretty: true })

// Custom indent
const indentedJson = stringify(report, { pretty: true, indent: 4 })

calculateSummary​

Calculate summary statistics from an array of tests.

function calculateSummary(tests: Test[], options?: SummaryOptions): Summary

Parameters:

  • tests - Array of test results
  • options.start - Override start timestamp
  • options.stop - Override stop timestamp

Example:

import { calculateSummary } from 'ctrf'

const summary = calculateSummary(tests)

// With timing overrides
const timedSummary = calculateSummary(tests, {
start: 1704067200000,
stop: 1704067260000,
})

Builders​

ReportBuilder​

Fluent builder for constructing CTRF reports.

class ReportBuilder {
constructor(options?: ReportBuilderOptions)

specVersion(version: string): this
reportId(uuid?: string): this
runId(id: string): this
timestamp(date?: Date | string): this
generatedBy(name: string): this
tool(tool: Tool): this
environment(env: Environment): this
addTest(test: Test): this
addTests(tests: Test[]): this
addError(error: GlobalError): this
insights(insights: Insights): this
baseline(baseline: Baseline): this
provenance(provenance: Provenance): this
extra(data: Record<string, unknown>): this
summaryOverrides(overrides: Partial<Summary>): this
build(): CTRFReport
}

Options:

  • autoGenerateId - Auto-generate report UUID
  • autoTimestamp - Auto-set current timestamp

Example:

import { ReportBuilder, TestBuilder } from 'ctrf'

const report = new ReportBuilder({ autoGenerateId: true, autoTimestamp: true })
.specVersion('0.3.0')
.runId('run-2026-08-15')
.tool({ name: 'jest', version: '29.0.0' })
.environment({ branchName: 'main', commit: 'abc123', shardId: 'shard-1-of-4' })
.addTest(
new TestBuilder()
.name('should add numbers')
.status('passed')
.duration(150)
.build()
)
.addTest(
new TestBuilder()
.name('should handle errors')
.status('failed')
.duration(200)
.message('Expected 5 but got 4')
.build()
)
.build()

Use addError for run-level errors; these do not add tests or change test counts. provenance accepts the direct source CTRF report IDs of a derived report. The builder validates supplied provenance; it does not infer it from native events.

TestBuilder​

Fluent builder for constructing Test objects.

class TestBuilder {
constructor(options?: TestBuilderOptions)

id(uuid?: string): this
testId(id: string): this
executionId(id: string): this
attemptId(id: string): this
name(name: string): this
description(description: string): this
addAssertionFailure(failure: AssertionFailure): this
status(status: TestStatus): this
duration(ms: number): this
start(timestamp: number): this
stop(timestamp: number): this
suite(suite: string[]): this
message(message: string): this
trace(trace: string): this
snippet(snippet: string): this
ai(ai: string): this
line(line: number): this
rawStatus(rawStatus: string): this
tags(tags: string[]): this
labels(labels: Record<string, LabelValue>): this
type(type: string): this
filePath(filePath: string): this
retries(retries: number): this
addAttemptHistoryEntry(attempt: AttemptHistoryEntry): this
addRetryAttempt(attempt: AttemptHistoryEntry): this
flaky(flaky?: boolean): this
stdout(stdout: string[]): this
stderr(stderr: string[]): this
threadId(threadId: string): this
browser(browser: string): this
device(device: string): this
screenshot(screenshot: string): this
parameters(params: Record<string, unknown>): this
addStep(step: Step): this
addAttachment(attachment: Attachment): this
insights(insights: TestInsights): this
extra(data: Record<string, unknown>): this
build(): Test
}

addAttemptHistoryEntry records attempts completed before the final attempt. addRetryAttempt remains a compatibility alias. Set retries to the history length, keep the final attempt on the test object, and attach assertion failures and worker IDs to the attempt that produced them.

Options:

  • autoGenerateId - Auto-generate test UUID based on name/suite/filePath

Example:

import { TestBuilder } from 'ctrf'

const test = new TestBuilder({ autoGenerateId: true })
.testId('authentication/validates-user-input')
.executionId('execution-123')
.name('should validate user input')
.suite(['Authentication', 'Login'])
.status('passed')
.duration(245)
.filePath('tests/auth/login.test.ts')
.tags(['smoke', 'auth'])
.labels({ priority: 'high', owners: ['qa', 'platform'] })
.type('integration')
.build()

Query & Filter​

filterTests​

Filter tests in a report by criteria.

function filterTests(report: CTRFReport, criteria: FilterCriteria): Test[]

FilterCriteria:

  • id - Legacy test UUID
  • testId - Stable logical test case ID
  • executionId - Specific test execution ID
  • name - Exact test name
  • status - Single status or array of statuses
  • tags - Tags to match (test must have all)
  • suite - Suite name to match
  • flaky - Filter by flaky status
  • browser - Browser name to match
  • device - Device name to match

Example:

import { filterTests } from 'ctrf'

// Filter by status
const failed = filterTests(report, { status: 'failed' })

// Multiple statuses
const notPassed = filterTests(report, {
status: ['failed', 'skipped'],
})

// Multiple criteria
const filtered = filterTests(report, {
status: 'failed',
tags: ['smoke'],
flaky: true,
})

findTest​

Find a single test in a report.

function findTest(
report: CTRFReport,
criteria: FilterCriteria
): Test | undefined

Example:

import { findTest } from 'ctrf'

// Find by stable logical test ID
const logicalTest = findTest(report, { testId: 'authentication/login' })

// Find one particular execution
const execution = findTest(report, { executionId: 'execution-123' })

// Find by name
const namedTest = findTest(report, { name: 'should login successfully' })

// Find by criteria
const failedFlakyTest = findTest(report, { status: 'failed', flaky: true })

Merge​

merge​

Merge multiple CTRF reports into a single report.

function merge(reports: CTRFReport[], options?: MergeOptions): CTRFReport

MergeOptions:

  • deduplicateTests - Remove duplicate tests by executionId, then testId, then legacy id (default: false)
  • mergeSummary - Recalculate summary (default: true)
  • preserveEnvironment - How to handle environments: 'first', 'last', 'merge' (default: 'merge')

Example:

import { merge } from 'ctrf'

// Basic merge
const merged = merge([report1, report2, report3])

// With deduplication
const deduplicated = merge(reports, {
deduplicateTests: true,
})

// Keep first environment only
const firstEnvironment = merge(reports, {
preserveEnvironment: 'first',
})

When merging multiple reports, the merged report receives a new reportId. A single input is returned as a shallow copy. A shared runId is preserved only when every source report has the same value. Global errors are retained from each input, including duplicates, without adding tests or changing their statuses. For current-version inputs, provenance lists the direct source report IDs when every input has one; otherwise provenance is omitted. Mixed-version merging does not convert or validate reports, so use compatible inputs and validate the output. The inputs remain unchanged: CTRF treats emitted reports as immutable artifacts. See Report Immutability for the document lifecycle rules.


Insights​

addInsights​

Add historical insights to a report by analyzing previous reports.

function addInsights(
report: CTRFReport,
historicalReports?: CTRFReport[],
options?: InsightsOptions
): CTRFReport

InsightsOptions:

  • baseline - Baseline report for comparison
  • window - Number of historical reports to analyze

Example:

import { addInsights } from 'ctrf'

// Add insights from historical data
const reportWithInsights = addInsights(currentReport, previousReports)

// With baseline comparison
const comparedReport = addInsights(currentReport, previousReports, {
baseline: baselineReport,
})

isTestFlaky​

Check whether the library identifies a test as flaky.

function isTestFlaky(test: Test): boolean

This helper returns true if:

  • flaky field is explicitly true, OR
  • Test has retries > 0 AND final status is 'passed'

Example:

import { isTestFlaky } from 'ctrf'

if (isTestFlaky(test)) {
console.log('Test is flaky:', test.name)
}

ID Generation​

generateTestId​

Generate a deterministic UUID v5 for a test based on its properties.

function generateTestId(properties: {
name: string
suite?: string[]
filePath?: string
}): string

The same inputs always produce the same UUID, enabling cross-run analysis.

Example:

import { generateTestId } from 'ctrf'

const id = generateTestId({
name: 'should add numbers',
suite: ['math', 'addition'],
filePath: 'tests/math.test.ts',
})
// Always returns the same UUID for these inputs

generateReportId​

Generate a random UUID v4 for report identification.

function generateReportId(): string

Example:

import { generateReportId } from 'ctrf'

const reportId = generateReportId()
// => 'f47ac10b-58cc-4372-a567-0e02b2c3d479'

Schema & Versioning​

getSchema​

Get the JSON Schema for a specific CTRF spec version.

function getSchema(version: SchemaSelector): object

Throws: SchemaVersionError if version is not supported

Example:

import { getSchema } from 'ctrf'

const schema = getSchema('0.3.0')

getCurrentSpecVersion​

Get the current spec version.

function getCurrentSpecVersion(): string

getSupportedSpecVersions​

Get all supported spec versions.

function getSupportedSpecVersions(): readonly string[]

schema​

The current version CTRF JSON Schema object.

import { schema } from 'ctrf'
console.log(schema)

Type Guards​

Lightweight structural checks. Use validate, isValid or validateStrict for full report validation.

isCTRFReport​

Quick check if an object has CTRF report structure.

function isCTRFReport(report: unknown): report is { reportFormat: 'CTRF' }

Example:

import { isCTRFReport } from 'ctrf'

if (isCTRFReport(data)) {
// data.reportFormat is 'CTRF'
}

isTest​

Type guard for Test objects.

function isTest(test: unknown): test is { name: string; status: string; duration: number }

isTestStatus​

Type guard for valid test statuses.

function isTestStatus(status: unknown): status is TestStatus

isAttemptHistoryEntry​

Checks the required fields of an attempt-history entry.

function isAttemptHistoryEntry(attempt: unknown): attempt is AttemptHistoryEntry

isRetryAttempt​

Compatibility alias for isAttemptHistoryEntry.

function isRetryAttempt(attempt: unknown): attempt is AttemptHistoryEntry

hasInsights​

Check if a report has insights data.

function hasInsights(report: CTRFReport): boolean

Constants​

import {
REPORT_FORMAT, // 'CTRF'
CURRENT_SPEC_VERSION, // '0.3.0'
TEST_STATUSES, // ['passed', 'failed', 'skipped', 'pending', 'other']
SUPPORTED_SPEC_VERSIONS, // ['0.0.1', '0.0.2', '0.0.3', '0.0.4', '0.1.0', '0.2.0', '0.3.0']
CTRF_NAMESPACE, // UUID namespace for deterministic IDs
} from 'ctrf'

Error Classes​

All errors extend CTRFError.

CTRFError​

Base error class for all CTRF errors.

class CTRFError extends Error {
name: string
}

ValidationError​

Thrown when schema validation fails.

class ValidationError extends CTRFError {
errors: ValidationErrorDetail[]
}

interface ValidationErrorDetail {
message: string
path: string
keyword: string
}

ParseError​

Thrown when JSON parsing fails.

class ParseError extends CTRFError {
cause?: Error
}

SchemaVersionError​

Thrown when an unsupported spec version is encountered.

class SchemaVersionError extends CTRFError {
version: string
supportedVersions: string[]
}

FileError​

Thrown when file operations fail.

class FileError extends CTRFError {
filePath: string
cause?: Error
}

BuilderError​

Thrown when builder validation fails.

class BuilderError extends CTRFError {}

CTRF Report Types​

These are the core schema types that define the CTRF structure. Import these to type your own reports.

CTRFReport​

The root report object.

interface CTRFReport {
reportFormat: 'CTRF'
specVersion: string
reportId?: string
runId?: string
timestamp?: string
generatedBy?: string
results: Results
insights?: Insights
baseline?: Baseline
provenance?: Provenance
extra?: Record<string, unknown>
}

Test​

Individual test result.

interface Test {
id?: string
testId?: string
executionId?: string
attemptId?: string
name: string
description?: string
status: TestStatus
duration: number
start?: number
stop?: number
suite?: string[]
message?: string
trace?: string
assertionFailures?: AssertionFailure[]
snippet?: string
ai?: string
line?: number
rawStatus?: string
tags?: string[]
labels?: Record<string, LabelValue>
type?: string
filePath?: string
retries?: number
retryAttempts?: AttemptHistoryEntry[]
flaky?: boolean
stdout?: string[]
stderr?: string[]
threadId?: string
browser?: string
device?: string
screenshot?: string
parameters?: Record<string, unknown>
steps?: Step[]
attachments?: Attachment[]
insights?: TestInsights
extra?: Record<string, unknown>
}
type LabelPrimitive = string | number | boolean
type LabelValue = LabelPrimitive | [LabelPrimitive, ...LabelPrimitive[]]

Results​

Container for test results.

interface Results {
tool: Tool
summary: Summary
tests: Test[]
errors?: GlobalError[]
environment?: Environment
extra?: Record<string, unknown>
}

Summary​

Aggregated test statistics.

interface Summary {
tests: number
passed: number
failed: number
skipped: number
pending: number
other: number
flaky?: number
suites?: number
start: number
stop: number
duration?: number
extra?: Record<string, unknown>
}

Tool​

Test tool information.

interface Tool {
name: string
version?: string
extra?: Record<string, unknown>
}

Environment​

Environment metadata.

interface Environment {
reportName?: string
appName?: string
appVersion?: string
buildId?: string
buildName?: string
buildNumber?: number
buildUrl?: string
repositoryName?: string
repositoryUrl?: string
commit?: string
branchName?: string
osPlatform?: string
osRelease?: string
osVersion?: string
testEnvironment?: string
shardId?: string
healthy?: boolean
extra?: Record<string, unknown>
}

TestStatus​

Valid test status values.

type TestStatus = 'passed' | 'failed' | 'skipped' | 'pending' | 'other'

Diagnostics and Provenance​

Assertion failures belong to their individual attempt. Run-level errors belong in results.errors, independently of test results. Each diagnostic object must have at least one property; omit unknown values rather than inventing them.

interface AssertionFailure {
message?: string
trace?: string
expected?: string
actual?: string
extra?: Record<string, unknown>
}

interface GlobalError {
message?: string
trace?: string
extra?: Record<string, unknown>
}

interface ProvenanceInput {
reportId: string
extra?: Record<string, unknown>
}

interface Provenance {
inputs: ProvenanceInput[]
extra?: Record<string, unknown>
}

When provenance is present, list every direct contributing CTRF source report. Input UUIDs must be distinct and must not reference the output's own ID. Omit provenance if any source lacks a report ID. See direct report provenance.

Supporting Types​

interface Attachment {
attachmentId?: string
name: string
contentType: string
path: string
extra?: Record<string, unknown>
}

interface Step {
name: string
status: TestStatus
extra?: Record<string, unknown>
}

interface AttemptHistoryEntry {
attempt: number
attemptId?: string
status: TestStatus
duration?: number
message?: string
trace?: string
assertionFailures?: AssertionFailure[]
threadId?: string
line?: number
snippet?: string
stdout?: string[]
stderr?: string[]
start?: number
stop?: number
attachments?: Attachment[]
extra?: Record<string, unknown>
}

type RetryAttempt = AttemptHistoryEntry

interface Insights {
passRate?: MetricDelta
failRate?: MetricDelta
flakyRate?: MetricDelta
averageRunDuration?: MetricDelta
p95RunDuration?: MetricDelta
averageTestDuration?: MetricDelta
runsAnalyzed?: number
extra?: Record<string, unknown>
}

interface TestInsights {
passRate?: MetricDelta
failRate?: MetricDelta
flakyRate?: MetricDelta
averageTestDuration?: MetricDelta
p95TestDuration?: MetricDelta
executedInRuns?: number
extra?: Record<string, unknown>
}

interface MetricDelta {
current?: number
baseline?: number
change?: number
}

interface Baseline {
reportId: string
timestamp?: string
source?: string
buildNumber?: number
buildName?: string
buildUrl?: string
commit?: string
extra?: Record<string, unknown>
}

Complete Example​

import {
ReportBuilder,
TestBuilder,
validate,
stringify,
filterTests,
} from 'ctrf'

// Build a report
const report = new ReportBuilder({ autoGenerateId: true, autoTimestamp: true })
.runId('run-2026-08-15-api-tests')
.tool({ name: 'vitest', version: '1.0.0' })
.environment({
branchName: 'main',
commit: 'abc123',
buildNumber: 42,
shardId: 'shard-1-of-3',
})
.addTest(
new TestBuilder({ autoGenerateId: true })
.testId('api/users/creates-user')
.executionId('execution-create-user-42')
.name('should create user')
.suite(['API', 'Users'])
.status('passed')
.duration(120)
.filePath('tests/api/users.test.ts')
.tags(['api', 'smoke'])
.build()
)
.addTest(
new TestBuilder({ autoGenerateId: true })
.testId('api/users/deletes-user')
.executionId('execution-delete-user-42')
.name('should delete user')
.suite(['API', 'Users'])
.status('failed')
.duration(85)
.message('User not found')
.addAssertionFailure({
message: 'Expected an existing user',
expected: 'user',
actual: 'null',
})
.trace('Error: User not found\n at deleteUser (users.ts:42)')
.filePath('tests/api/users.test.ts')
.build()
)
.build()

// Validate
const result = validate(report)
console.log('Valid:', result.valid)

// Filter failed tests
const failed = filterTests(report, { status: 'failed' })
console.log('Failed tests:', failed.length)

// Serialize
const prettyJson = stringify(report, { pretty: true })