@fyndlitmus/playwright
Zero-friction drop-in Playwright Test analytics, full-stack Browser E2E + Native API + Visual/DOM observability, OpenAPI contract coverage, and offline Agentic HTML, A4 Audit PDF, and llms.txt-style agent-triage.md reports.
- 1-Line Drop-In Swap: Change
from "@playwright/test" to from "@fyndlitmus/playwright" in playwright.config.ts and your *.spec.ts files—your existing { page, request } tests and expect(...) assertions work unchanged (zod is optional).
- Full-Stack E2E + API + Visual Forensics: Auto-captures page navigations, SPA History routing, Core Web Vitals (
LCP, CLS, TTFB), DevTools network waterfalls, console/pageerror/terminal logs, time-synced <video> seeking, 4-mode visual diffs (Side-by-Side | Slider | Onion | Diff), semantic DOM root-cause vs. knock-on shift diffing, and native request/expect exchanges.
- Zero Hosted Lock-In & Redacted by Default: 100% offline single-file HTML (
shadcn/ui + strict SHA-256 CSP) and A4 PDF reports with automatic scrubbing of Authorization, Bearer/Basic tokens, masked Cookies (••••), API keys, and URL credentials before disk write.
Licensed under Apache-2.0. See LICENSE. Copyright attribution: NOTICE.
Interactive HTML & A4 Audit PDF Report Tour
1. Interactive Offline HTML Workspace (index.html)
Tests Overview — Clean centered layout (Tests | AI Triage | Endpoints), SVG pass-rate donut, p50/p95 API latency pulse, deduplicated root-cause failure clusters (SCHEMA_DRIFT, HTTP_5XX_FAULT), signal filter chips, and collapsible run provenance:
Dark Mode (t hotkey) + Q786 Accent Presets + Hierarchical Suite Tree Explorer (Project → Spec File → Describe → Case):
Single-Column Case Inspector — Playwright-inspired calm single-column layout with full-width .spec.ts source code frame (> active line + ^ column caret), inline test steps, click-to-inspect HTTP exchanges (auto-expanded only on HTTP faults, polling loops collapsed), [REDACTED] secret scrubbing, Copy cURL, and collapsed passing assertions:
AI Triage Workbench (#/run?tab=agent & agent-triage.md) — Prioritized repair queue paired with a live Markdown/JSON fix prompt (Evidence Coverage: accounting, suspect layer, source frame, and one-click CLI repro):
Normalized Endpoints p50/p95 Coverage Matrix & Parallel Worker Swimlane (#/run?tab=endpoints):
2. Streamlined A4 Executive & Compliance Audit PDF (report.pdf)
Page 1 — Executive Release Gate (GO / CONDITIONAL / NO-GO), Scorecard Bento, Suite Health, and By priority (P0–P3) & By tag Rollups:
Page 2 — Normalized Endpoint p50/p95 Telemetry, Lane-Packed Parallel Worker Gantt (Execution timeline), & Deduplicated Failure Clusters:
Compact HTTP Trace Ledger, Failing Exchange Cards, & Cryptographic SHA-256 EmbeddedFiles Inventory:
Case Dossier, .spec.ts Code Frame & Failing HTTP Exchange |
Sealed SHA-256 EmbeddedFiles Chain-of-Custody Manifest |
|
|
Package entry points
| Import path |
Purpose |
@fyndlitmus/playwright |
Drop-in primary entrypoint: test, expect, defineConfig, devices, trackPage, recordNavigation, plus { page, request, api } |
@fyndlitmus/playwright/reporter |
LitmusReporter generating index.html, agent-triage.md, report.pdf, results.json, and junit.xml |
@fyndlitmus/playwright/merge |
mergeReports() for lossless multi-shard CI report & attachment merging |
@fyndlitmus/playwright/server |
startReportServer() (streaming .litmus-stream/ + HTTP 206 video Range server) & initLitmusProject() |
@fyndlitmus/playwright/api |
createApiClient, apiAuth (bearer, basic), and apiTest alias |
@fyndlitmus/playwright/ui |
uiTest alias and expect |
@fyndlitmus/playwright/openapi |
createOpenApiApiClient<paths>() for compile-time typed paths, params, bodies, and responses |
@fyndlitmus/playwright/openapi/generator |
generateOpenApiTypes() from local/remote OpenAPI 3.x YAML or JSON |
@fyndlitmus/playwright/openapi/reporter |
OpenApiCoverageReporter for operation-level route & schema coverage |
@fyndlitmus/playwright/schemas/litmus-run-report.v1.schema.json |
Published Draft-07 JSON Schema for results.json (schemaVersion: 1) |
Install & 30-second drop-in setup
npm install -D @fyndlitmus/playwright @playwright/test
# Optional: install zod if you also want runtime request/response schema validation
npm install -D zod
1. Wrap playwright.config.ts with defineConfig
import { defineConfig, devices } from "@fyndlitmus/playwright";
export default defineConfig(
{
testDir: "./tests",
use: {
baseURL: process.env.BASE_URL ?? "http://127.0.0.1:3000",
video: "retain-on-failure",
trace: "on-first-retry",
},
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
},
{
preset: "balanced", // "balanced" (default) | "full" | "minimal" | "ci"
outputDir: "litmus-report",
environment: process.env.TEST_ENV ?? "staging",
excludeUrls: ["**/analytics/**", "**/*.woff2"],
redactPatterns: [/customer_secret_\w+/g],
branding: {
title: "Storefront E2E & API Verification",
accent: "teal", // "blue" | "indigo" | "teal" | "green" | "rose" | "graphite"
},
qualityGate: { maxFailed: 0, maxFlaky: 2, maxP95Ms: 1500 },
pdf: false, // set true or { landscape: false, mode: "full" | "failures" | "summary" }
openReport: "never", // "always" | "never" | "on-failure"
},
);
2. Swap 1 import line in your tests
// Before: import { test, expect } from "@playwright/test";
import { test, expect } from "@fyndlitmus/playwright";
test("completes checkout and verifies order API", async ({ page, request }) => {
await page.goto("/cart");
await page.getByRole("button", { name: "Checkout" }).click();
await expect(page).toHaveURL(/\/checkout/);
// Native Playwright request + expect are automatically intercepted & correlated!
const res = await request.post("/api/orders", { data: { sku: "PRO-PLAN" } });
expect(res.status()).toBe(201);
// Visual regression with 4-mode viewer + semantic DOM root-cause vs. knock-on shift diffing:
await expect(page).toMatchVisualBaseline("checkout-summary.png");
});
If a test creates a custom browser.newContext() / context.newPage() manually instead of using { page }, call trackPage(customPage, testInfo) to attach full navigation, Web Vitals, network, and console telemetry.
Supported versions: Node.js >=22, @playwright/test >=1.51.0 <2, and optional zod >=3.23.0 <5 (Zod v3 & v4). ESM-only.
API checks
For Playwright Test suites, use the apiTest fixture. It creates an isolated request context per test and attaches
redacted structured API logs to that test's normal Playwright report:
import { expect } from "@playwright/test";
import { z } from "zod";
import { apiTest } from "@fyndlitmus/playwright/api";
apiTest("returns a valid user", async ({ api }) => {
const result = await api.get("/users/me", {
expectedStatus: 200,
responseSchema: z.object({ id: z.string(), email: z.string().email() }),
});
expect(result.data.email).toMatch(/@/);
});
Set the service URL in Playwright config with use.baseURL. The fixture disposes its request context after each test.
Use the standalone factory below for scripts or custom runners.
import { z } from "zod";
import { apiAuth, createApiClient } from "@fyndlitmus/playwright/api";
const User = z.object({ id: z.string(), email: z.string().email() });
const api = await createApiClient({
baseURL: process.env.API_BASE_URL,
extraHTTPHeaders: apiAuth.bearer(process.env.API_TOKEN!),
});
try {
const result = await api.get("/users/me", {
expectedStatus: 200,
responseSchema: User,
});
// result.data is inferred from User's parsed output.
console.log(result.data?.email, result.durationMs, result.requestId);
} finally {
await api.dispose();
}
Request payloads can be checked before they are sent:
const CreateUser = z.object({ email: z.string().email(), role: z.enum(["admin", "member"]) });
await api.post("/users", {
data: { email: "qa@example.com", role: "member" },
requestSchema: CreateUser,
expectedStatus: 201,
});
The client has named helpers for get, post, put, patch, delete, options, head and trace; fetch accepts
any method string. All Playwright request options are passed through. The client also supports expected response headers
and a maximum duration. It returns the native Playwright response, validated data, sanitized URL, elapsed milliseconds
and a request ID when the server returns x-request-id or request-id.
Multi-request workflows use ordinary Playwright tests and JavaScript values. Use unique data when tests run in parallel,
and remember that Playwright retries rerun the whole test and may repeat writes:
import { expect } from "@playwright/test";
import { z } from "zod";
import { apiTest } from "@fyndlitmus/playwright/api";
apiTest("creates, verifies and removes a user", async ({ api }) => {
const email = `qa-${crypto.randomUUID()}@example.test`;
const created = await api.post("/users", {
data: { email },
requestSchema: z.object({ email: z.string().email() }),
expectedStatus: 201,
responseSchema: z.object({ id: z.string(), email: z.string() }),
});
try {
const fetched = await api.get(`/users/${created.data.id}`, {
expectedStatus: 200,
responseSchema: z.object({ id: z.string(), email: z.string() }),
});
expect(fetched.data.email).toBe(email);
} finally {
await api.delete(`/users/${created.data.id}`, { expectedStatus: 204 });
}
});
Playwright beforeEach, afterEach and fixtures are available for shared setup and cleanup. A cleanup failure fails the
test and appears in its report. Do not assume a write is safe to repeat unless the service supports idempotency or the
test creates unique resources.
UI and combined API/UI checks
Import uiTest from the separate UI entry point. It keeps Playwright's native browser, context, page, project, trace
and retry behavior, and composes the API fixture for tests that need to compare what the browser displays with the
backend response:
import { uiTest, expect } from "@fyndlitmus/playwright/ui";
import { z } from "zod";
const Profile = z.object({ name: z.string() });
uiTest("shows the profile returned by the API", async ({ page, api }) => {
await page.goto("/profile");
const profile = await api.get("/api/profile", {
expectedStatus: 200,
responseSchema: Profile,
});
await expect(page.getByRole("heading", { name: profile.data.name })).toBeVisible();
});
Set use.baseURL to the application origin for relative page.goto() and API paths. Pass an absolute URL to api
when the API uses another origin. Install browser binaries for UI tests with npx playwright install chromium;
API-only tests using @fyndlitmus/playwright/api do not launch a browser. Configure Playwright's trace option (for
example, on-first-retry) when you want browser traces for UI failures.
Use Playwright's native page.route() when a UI test should mock browser traffic. That route does not intercept the
separate api fixture, which continues to call the service through APIRequestContext; API checks should use a local
test service when they need deterministic mock responses.
OpenAPI operation typing
Generate TypeScript definitions from an OpenAPI document with the bundled helper. It accepts an OpenAPI object, a JSON
or YAML document string, or a URL to a local or remote document, and writes the generated declarations to the
explicit output path:
import { generateOpenApiTypes } from "@fyndlitmus/playwright/openapi/generator";
await generateOpenApiTypes(new URL("./openapi.yaml", import.meta.url), {
outputFile: "./openapi-types.d.ts",
});
The generated file is compile-time typing only. Pass Zod schemas separately when tests need runtime validation. The
Litmus helper types operation paths, query parameters, JSON request bodies and successful JSON responses while
preserving the native APIResponse:
import type { paths } from "./openapi-types";
import { expect } from "@playwright/test";
import { z } from "zod";
import { createOpenApiApiClient } from "@fyndlitmus/playwright/openapi";
import { apiTest } from "@fyndlitmus/playwright/api";
apiTest("reads a user through the OpenAPI contract", async ({ api }) => {
const contractApi = createOpenApiApiClient<paths>(api);
const user = await contractApi.request("get", "/users/{id}", {
pathParams: { id: "usr_123" },
query: { include: "roles" },
responseSchema: z.object({ id: z.string(), email: z.string().email() }),
});
const typedUser = await user.json();
expect(typedUser.id).toBe("usr_123");
});
TypeScript types do not validate live data; use Zod schemas for runtime request and response checks. Path parameters
are URL encoded, query arrays use repeated keys, and scalar values are serialized directly. Use contractApi.raw for
custom OpenAPI styles, cookie parameters, form bodies or routes outside the document.
OpenAPI operation coverage
Add the optional coverage reporter beside the Litmus report in Playwright config. It reads request.start and response
schema events from apiTest attachments, matches method and path templates, and writes an operation-level JSON summary:
import { readFileSync } from "node:fs";
import { defineConfig } from "@playwright/test";
import type { OpenApiCoverageDocument } from "@fyndlitmus/playwright/openapi/reporter";
const openApiDocument = JSON.parse(readFileSync("./openapi.json", "utf8")) as OpenApiCoverageDocument;
export default defineConfig({
reporter: [
["@fyndlitmus/playwright/api/reporter", { outputDir: "reports/api" }],
["@fyndlitmus/playwright/openapi/reporter", {
document: openApiDocument,
basePath: "/v1",
outputFile: "reports/api/openapi-coverage.json",
}],
],
});
The report includes covered operations, request and test counts, and counts of successful or failed Zod response
validation. It does not save request URLs, query values, payloads or schema field coverage. Unmatched requests are counted
without recording their URLs. Retried attempts contribute their own requests. The reporter uses attachments from the
apiTest fixture; a standalone createApiClient run needs to attach equivalent events for coverage to be observed. If
any fixture attachment was truncated, the report sets summary.complete to false and counts affected tests in
summary.truncatedTests.
Diagnostics and security