@ralphralphai/playwright 0.2.0 → 1.2.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["readFile","readFileSync","path","parse","printParseErrorCode","configPackage","pack","promisify","gzip","randomUUID","delay","mkdir","writeFile","packageInfo.version","playwrightPackage","readFile","base","path"],"sources":["../src/config.ts","../package.json","../src/image.ts","../src/layout.ts","../src/upload.ts","../src/recorder.ts","../src/screens.ts","../src/index.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport configPackage from '@ralphralphai/config/package.json' with { type: 'json' };\nimport { WebRalphConfigSchema } from '@ralphralphai/config/zod';\nimport { parse, printParseErrorCode, type ParseError } from 'jsonc-parser';\n\nimport type { ConfigSnapshot, RalphOptions } from './types';\n\nexport function resolveMode(options: RalphOptions): 'off' | 'local' | 'upload' {\n const mode =\n options.mode ??\n process.env['RALPH_MODE'] ??\n (process.env['RALPH_UPLOAD_KEY'] ? 'upload' : 'off');\n if (mode === 'off' || mode === 'local' || mode === 'upload') {\n return mode;\n }\n\n throw new Error('RALPH_MODE must be off, local, or upload.');\n}\n\ntype ConfigSource = Pick<RalphOptions, 'config' | 'configPath'>;\n\nexport async function loadConfig(\n options: ConfigSource,\n root: string,\n): Promise<ConfigSnapshot> {\n const file = configFile(options, root);\n return snapshot(options.config ?? parseConfig(await readFile(file, 'utf8')));\n}\n\n// Playwright config files may be CommonJS, so project generation cannot await.\nexport function loadConfigSync(\n options: ConfigSource,\n root: string,\n): ConfigSnapshot {\n const file = configFile(options, root);\n return snapshot(options.config ?? parseConfig(readFileSync(file, 'utf8')));\n}\n\nfunction configFile(options: ConfigSource, root: string): string {\n if (options.config && options.configPath) {\n throw new Error(\n 'Provide either ralphOptions.config or configPath, not both.',\n );\n }\n return path.resolve(root, options.configPath ?? 'ralph.jsonc');\n}\n\nfunction parseConfig(text: string): unknown {\n const errors: ParseError[] = [];\n const value: unknown = parse(text, errors, { allowTrailingComma: true });\n if (errors.length) {\n throw new Error(\n 'Invalid Ralph config: ' +\n errors\n .map(\n (error) => printParseErrorCode(error.error) + ' at ' + error.offset,\n )\n .join(', '),\n );\n }\n return value;\n}\n\nfunction snapshot(value: unknown): ConfigSnapshot {\n WebRalphConfigSchema.parse(value);\n return {\n config: JSON.parse(JSON.stringify(value)) as ConfigSnapshot['config'],\n packageVersion: configPackage.version,\n };\n}\n","","import type { Page } from '@playwright/test';\n\n/**\n * Matches the crawler's full-page screenshots: lossless measured larger than this\n * on real sites, which are mostly photographic content.\n */\nconst WEBP_QUALITY = 80;\n\nexport type Screenshot = {\n bytes: Buffer;\n contentType: 'image/webp' | 'image/png';\n width: number;\n height: number;\n};\n\nexport async function takeScreenshot(\n page: Page,\n deadline: number,\n): Promise<Screenshot> {\n const options = { fullPage: true, scale: 'css' } as const;\n const webp = await page.screenshot({\n ...options,\n type: 'webp',\n quality: WEBP_QUALITY,\n timeout: Math.max(1, deadline - Date.now()),\n });\n // WebP stores each dimension in 14 bits, so a page over 16383px has no valid\n // encoding. Chromium signals that with an empty buffer rather than an error;\n // PNG has no such limit.\n if (webp.length > 0) {\n return { bytes: webp, contentType: 'image/webp', ...webpSize(webp) };\n }\n const png = await page.screenshot({\n ...options,\n type: 'png',\n timeout: Math.max(1, deadline - Date.now()),\n });\n return {\n bytes: png,\n contentType: 'image/png',\n width: png.readUInt32BE(16),\n height: png.readUInt32BE(20),\n };\n}\n\nexport function imageExtension(contentType: Screenshot['contentType']): string {\n return contentType === 'image/png' ? '.png' : '.webp';\n}\n\nfunction webpSize(bytes: Buffer): { width: number; height: number } {\n if (\n bytes.toString('ascii', 0, 4) !== 'RIFF' ||\n bytes.toString('ascii', 8, 12) !== 'WEBP'\n ) {\n throw new Error('The screenshot is not a WebP image.');\n }\n const chunk = bytes.toString('ascii', 12, 16);\n if (chunk === 'VP8X') {\n return {\n width: 1 + bytes.readUIntLE(24, 3),\n height: 1 + bytes.readUIntLE(27, 3),\n };\n }\n if (chunk === 'VP8 ') {\n return {\n width: bytes.readUInt16LE(26) & 0x3fff,\n height: bytes.readUInt16LE(28) & 0x3fff,\n };\n }\n if (chunk === 'VP8L') {\n const bits = bytes.readUInt32LE(21);\n return { width: 1 + (bits & 0x3fff), height: 1 + ((bits >> 14) & 0x3fff) };\n }\n throw new Error('Unsupported WebP chunk: ' + chunk);\n}\n","import type { Page } from '@playwright/test';\n\nimport type { PageLayout } from './types';\n\nexport function readLayout(page: Page): Promise<PageLayout> {\n return page\n .locator('[data-track-id]')\n .filter({ visible: true })\n .evaluateAll((elements) => ({\n viewport: { width: window.innerWidth, height: window.innerHeight },\n document: {\n width: Math.max(\n document.documentElement.scrollWidth,\n document.documentElement.clientWidth,\n document.body?.scrollWidth ?? 0,\n ),\n height: Math.max(\n document.documentElement.scrollHeight,\n document.documentElement.clientHeight,\n document.body?.scrollHeight ?? 0,\n ),\n },\n scroll: { x: window.scrollX, y: window.scrollY },\n devicePixelRatio: window.devicePixelRatio,\n trackedElements: elements.flatMap((element) => {\n const trackId = element.getAttribute('data-track-id');\n const rect = element.getBoundingClientRect();\n // Off-screen horizontally (drawers, carousel slides) is dropped like\n // the crawler does; below the fold is kept, since the screenshot is\n // full-page.\n if (\n !trackId ||\n rect.width <= 0 ||\n rect.height <= 0 ||\n rect.right <= 0 ||\n rect.left >= window.innerWidth\n ) {\n return [];\n }\n return [\n {\n trackId,\n x: rect.x + window.scrollX,\n y: rect.y + window.scrollY,\n width: rect.width,\n height: rect.height,\n },\n ];\n }),\n }));\n}\n","import { promisify } from 'node:util';\nimport { gzip } from 'node:zlib';\n\nimport { pack } from 'tar-stream';\n\nimport { imageExtension, type Screenshot } from './image';\nimport type { RawGraphManifest, RalphOptions } from './types';\n\nexport type UploadOptions = {\n apiUrl: string;\n appId: string;\n uploadKey: string;\n timeoutMs?: number;\n};\nexport type RawGraphScreenshot = {\n nodeId: string;\n contentType: Screenshot['contentType'];\n bytes: Uint8Array;\n};\nexport type UploadReceipt = {\n result: 'ok';\n status: 'received';\n attemptId: string;\n resultId: string;\n replayed: boolean;\n};\n\nexport function resolveUploadOptions(options: RalphOptions): UploadOptions {\n const uploadKey = process.env['RALPH_UPLOAD_KEY'];\n const apiUrl = options.apiUrl ?? process.env['RALPH_API_URL'];\n const appId = options.appId ?? process.env['RALPH_APP_ID'];\n if (!uploadKey || !apiUrl || !appId) {\n throw new Error(\n 'Ralph upload requires RALPH_UPLOAD_KEY, RALPH_API_URL (or ralphOptions.apiUrl), and RALPH_APP_ID (or ralphOptions.appId).',\n );\n }\n return { uploadKey, apiUrl, appId, timeoutMs: options.uploadTimeoutMs };\n}\n\nexport const RAW_GRAPH_BUNDLE_INDEX = 'raw_graph.json';\nexport const RAW_GRAPH_BUNDLE_IMAGE_DIR = 'assets/images';\n\nexport type RawGraphBundleIndex = {\n manifest: RawGraphManifest;\n screenshots: { nodeId: string; path: string }[];\n};\n\n/**\n * Packs the manifest and screenshots into a gzipped tar archive:\n *\n * raw_graph.json { manifest, screenshots: [{ nodeId, path }] }\n * assets/images/<id>.webp raw screenshot bytes (.png when too large for WebP)\n */\nexport async function createRawGraphBundle(\n manifest: RawGraphManifest,\n screenshots: readonly RawGraphScreenshot[],\n): Promise<Uint8Array> {\n if (\n Buffer.byteLength(JSON.stringify(manifest)) > 2 * 1024 * 1024 ||\n screenshots.length > 500 ||\n screenshots.reduce(\n (total, screenshot) => total + screenshot.bytes.byteLength,\n 0,\n ) >\n 64 * 1024 * 1024\n ) {\n throw new Error('Ralph raw graph exceeds upload limits.');\n }\n\n const images = screenshots.map(({ nodeId, contentType, bytes }) => {\n if (!/^[A-Za-z0-9-]{1,64}$/.test(nodeId)) {\n throw new Error(`Ralph node id is not path-safe: ${nodeId}`);\n }\n return {\n nodeId,\n path: `${RAW_GRAPH_BUNDLE_IMAGE_DIR}/${nodeId}${imageExtension(contentType)}`,\n bytes,\n };\n });\n const index: RawGraphBundleIndex = {\n manifest,\n screenshots: images.map(({ nodeId, path }) => ({ nodeId, path })),\n };\n\n // Fixed attributes keep retries of the same attempt byte-identical.\n const attrs = { mtime: new Date(0), uid: 0, gid: 0 };\n const tar = pack();\n tar.entry({ name: RAW_GRAPH_BUNDLE_INDEX, ...attrs }, JSON.stringify(index));\n for (const { path, bytes } of images) {\n tar.entry({ name: path, ...attrs }, Buffer.from(bytes));\n }\n tar.finalize();\n const chunks: Buffer[] = [];\n for await (const chunk of tar) {\n chunks.push(chunk as Buffer);\n }\n const compressed = await promisify(gzip)(Buffer.concat(chunks));\n if (compressed.byteLength > 64 * 1024 * 1024) {\n throw new Error('Ralph compressed raw graph bundle exceeds upload limits.');\n }\n\n return compressed;\n}\n\nfunction isLoopback(url: URL): boolean {\n return (\n url.hostname === 'localhost' ||\n url.hostname === '[::1]' ||\n /^127(\\.\\d{1,3}){3}$/.test(url.hostname)\n );\n}\n\nexport async function uploadRawGraph(\n manifest: RawGraphManifest,\n screenshots: readonly RawGraphScreenshot[],\n options: UploadOptions,\n): Promise<UploadReceipt> {\n if (!/^[A-Za-z0-9_-]{1,64}$/.test(options.appId)) {\n throw new Error(`Ralph app id is not valid: ${options.appId}`);\n }\n const url = new URL(\n `/api/upload/playwright/apps/${options.appId}/attempts`,\n options.apiUrl,\n );\n if (\n !(\n url.protocol === 'https:' ||\n (url.protocol === 'http:' && isLoopback(url))\n ) ||\n !options.uploadKey\n ) {\n throw new Error(\n 'Ralph upload requires an HTTPS API URL (HTTP only for loopback hosts) and an upload key.',\n );\n }\n\n const timeoutMs = options.timeoutMs ?? 30_000;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new Error('Ralph uploadTimeoutMs must be positive and finite.');\n }\n\n const blob = new Blob(\n [new Uint8Array(await createRawGraphBundle(manifest, screenshots))],\n { type: 'application/gzip' },\n );\n\n const response = await fetch(url, {\n method: 'POST',\n headers: { Authorization: `Bearer ${options.uploadKey}` },\n body: blob,\n redirect: 'error',\n signal: AbortSignal.timeout(timeoutMs),\n });\n\n if (!response.ok) {\n throw new Error(\n `Ralph upload failed (HTTP ${response.status}). Local Ralph artifacts are retained for retry.`,\n );\n }\n\n const receipt = (await response.json()) as Partial<UploadReceipt>;\n if (\n receipt.result !== 'ok' ||\n receipt.status !== 'received' ||\n receipt.attemptId !== manifest.attemptId ||\n typeof receipt.resultId !== 'string' ||\n typeof receipt.replayed !== 'boolean'\n ) {\n throw new Error('Ralph server returned an invalid upload receipt.');\n }\n return receipt as UploadReceipt;\n}\n","import { randomUUID } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { setTimeout as delay } from 'node:timers/promises';\n\nimport type { BrowserContext, Frame, Page, TestInfo } from '@playwright/test';\nimport playwrightPackage from '@playwright/test/package.json' with { type: 'json' };\n\nimport packageInfo from '../package.json';\nimport { imageExtension, takeScreenshot, type Screenshot } from './image';\nimport { readLayout } from './layout';\nimport type {\n RawGraphManifest,\n RawNode,\n RecordNodeOptions,\n ConfigSnapshot,\n Ralph,\n RalphOptions,\n} from './types';\nimport { uploadRawGraph, type UploadOptions } from './upload';\n\nexport const MANIFEST_ATTACHMENT = 'ralph-raw-graph';\n\nconst DEFAULT_SETTLE_MS = 150;\nconst DEFAULT_RECORD_TIMEOUT_MS = 5_000;\n\n/** Where the raw graph and screenshots are written, inside Playwright's per-test output directory. */\nconst OUTPUT_DIR = 'ralph';\n\ntype PageInfo = RawGraphManifest['pages'][number];\n\ntype NodeRequest = Omit<RawNode, 'status'>;\n\ntype RecordedNode = Extract<RawNode, { status: 'recorded' }>;\n\n/** What the recorder tracks for one browser tab. */\ntype PageState = {\n page: Page;\n info: PageInfo;\n\n /** The URL of the last navigation, so a reload is not recorded again. */\n lastUrl: string;\n\n /**\n * Bumped on every main-frame navigation, including reloads. A recording that\n * sees a different generation when it finishes was overtaken by one.\n */\n generation: number;\n\n /** The next node's position within this tab. */\n sequence: number;\n\n /** The last queued recording. Recordings in a tab run one at a time. */\n tail: Promise<void>;\n\n /** Resolves once `info.openerPageId` is known. */\n opener: Promise<void>;\n\n onNavigation: (frame: Frame) => void;\n};\n\nexport class Recorder implements Ralph {\n /**\n * Identifies this run of the test. A retry gets a new recorder, and so a new\n * id, which is what lets the server tell retries apart and dedupe re-uploads.\n */\n private readonly attemptId = randomUUID();\n private readonly startedAt = new Date().toISOString();\n\n /** How long to wait after a navigation's DOM loads before recording. */\n private readonly settleMs: number;\n\n /**\n * The budget for recording one node, from settling through the screenshot.\n * Past it, the node is recorded as failed.\n */\n private readonly recordTimeoutMs: number;\n\n /**\n * Every context being watched. `onPage` is kept so `stopContext` can remove\n * the exact listener `observe` added. The id is stored in the manifest's\n * `pages[].contextId`.\n */\n private readonly contexts = new Map<\n BrowserContext,\n { id: string; onPage: (page: Page) => void }\n >();\n\n /**\n * Every tab seen in a watched context, including closed ones, so their\n * nodes and opener links still reach the manifest.\n */\n private readonly pages = new Map<Page, PageState>();\n\n /**\n * Each node's outcome, in completion order. Nodes in one tab complete\n * in sequence, but tabs interleave; `finish` sorts them.\n */\n private readonly nodes: RawNode[] = [];\n\n /**\n * When each node was requested, keyed by node id, for linking a\n * popup's first node to its opener's latest. Numbers, so they compare\n * without parsing each node's `requestedAt` string.\n */\n private readonly requestedAtMs = new Map<string, number>();\n\n /** Set by `finish`, after which `observe` throws. */\n private closed = false;\n\n constructor(\n private readonly options: RalphOptions,\n private readonly config: ConfigSnapshot,\n private readonly testInfo: TestInfo,\n private readonly upload?: UploadOptions,\n ) {\n this.settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;\n this.recordTimeoutMs = options.recordTimeoutMs ?? DEFAULT_RECORD_TIMEOUT_MS;\n\n const validTimings =\n Number.isFinite(this.settleMs) &&\n this.settleMs >= 0 &&\n Number.isFinite(this.recordTimeoutMs) &&\n this.recordTimeoutMs > this.settleMs;\n if (!validTimings) {\n throw new Error(\n 'Ralph recordTimeoutMs must be finite and greater than settleMs, which must be non-negative.',\n );\n }\n }\n\n // ---------------------------------------------------------------------------\n // Public API\n // ---------------------------------------------------------------------------\n\n /** Starts recording URL changes in every current and future tab of `context`. */\n observe(context: BrowserContext): void {\n if (this.closed) {\n throw new Error('The Ralph recorder has finished.');\n }\n if (this.contexts.has(context)) {\n return;\n }\n\n const id = 'context-' + this.contexts.size;\n const onPage = (page: Page) => this.watchPage(page, id);\n this.contexts.set(context, { id, onPage });\n\n context.on('page', onPage);\n for (const page of context.pages()) {\n onPage(page);\n }\n }\n\n /** Records the page as it is now, e.g. an open dialog at the same URL. */\n async recordNode(page: Page, options: RecordNodeOptions = {}): Promise<void> {\n this.observe(page.context());\n const state = this.pages.get(page);\n if (!state) {\n throw new Error('Cannot record a closed browser page.');\n }\n await this.enqueue(state, 'explicit', options);\n }\n\n /** Waits for every queued recording to finish. */\n async flush(): Promise<void> {\n await Promise.all([...this.pages.values()].map((state) => state.tail));\n }\n\n /** Stops watching `context` and waits for its queued recordings. */\n async stopContext(context: BrowserContext): Promise<void> {\n const entry = this.contexts.get(context);\n if (entry) {\n context.off('page', entry.onPage);\n }\n\n const states = [...this.pages.values()].filter(\n (state) => state.page.context() === context,\n );\n for (const state of states) {\n state.page.off('framenavigated', state.onNavigation);\n }\n await Promise.all(states.map((state) => state.tail));\n }\n\n /**\n * Stops recording, then writes the manifest, uploads it if configured, and\n * fails a passing test whose nodes failed to record.\n */\n async finish(): Promise<void> {\n this.closed = true;\n await Promise.all(\n [...this.contexts.keys()].map((context) => this.stopContext(context)),\n );\n await Promise.all([...this.pages.values()].map((state) => state.opener));\n\n const nodes = this.nodes.sort(\n (a, b) => a.pageId.localeCompare(b.pageId) || a.sequence - b.sequence,\n );\n linkPreviousNodes(\n nodes,\n (pageId) => this.pageInfo(pageId)?.openerPageId,\n (nodeId) => this.requestedAtMs.get(nodeId) ?? 0,\n );\n\n const failures = nodes.filter((item) => item.status === 'failed');\n const manifest = this.buildManifest(nodes, failures.length);\n await this.writeManifest(manifest);\n if (this.upload) {\n await this.uploadManifest(manifest, this.upload);\n }\n\n if (failures.length && this.testInfo.status === 'passed') {\n throw new Error(\n 'Ralph could not record ' +\n failures.length +\n ' page state(s). See the ralph-raw-graph attachment.',\n );\n }\n }\n\n // ---------------------------------------------------------------------------\n // Watching tabs\n // ---------------------------------------------------------------------------\n\n private watchPage(page: Page, contextId: string): void {\n if (this.pages.has(page)) {\n return;\n }\n\n const state: PageState = {\n page,\n info: {\n pageId: 'page-' + this.pages.size,\n contextId,\n browserName: page.context().browser()?.browserType().name(),\n },\n lastUrl: '',\n generation: 0,\n sequence: 0,\n tail: Promise.resolve(),\n opener: Promise.resolve(),\n onNavigation: (frame) => {\n if (frame === page.mainFrame()) {\n this.urlChanged(state);\n }\n },\n };\n this.pages.set(page, state);\n\n state.opener = page\n .opener()\n .then((opener) => {\n if (opener) {\n state.info.openerPageId = this.pages.get(opener)?.info.pageId;\n }\n })\n .catch(() => undefined);\n\n page.on('framenavigated', state.onNavigation);\n this.urlChanged(state);\n }\n\n private urlChanged(state: PageState): void {\n state.generation++;\n\n const url = state.page.url();\n if (url === state.lastUrl) {\n return;\n }\n state.lastUrl = url;\n\n if (isHttpUrl(url)) {\n // Automatic recordings never fail the test; failures land in the manifest.\n void this.enqueue(state, 'url-change', {}).catch(() => undefined);\n }\n }\n\n // ---------------------------------------------------------------------------\n // Recording\n // ---------------------------------------------------------------------------\n\n /** Queues a recording behind the tab's earlier ones. */\n private enqueue(\n state: PageState,\n trigger: RawNode['trigger'],\n options: RecordNodeOptions,\n ): Promise<void> {\n const actualUrl = state.page.url();\n const url =\n options.url === undefined\n ? actualUrl\n : new URL(options.url, actualUrl).href;\n if (!isHttpUrl(actualUrl) || !isHttpUrl(url)) {\n throw new Error(\n 'Ralph recordings require HTTP or HTTPS page and recorded URLs.',\n );\n }\n\n const request: NodeRequest = {\n nodeId: randomUUID(),\n pageId: state.info.pageId,\n sequence: state.sequence++,\n requestedAt: new Date().toISOString(),\n actualUrl,\n url,\n trigger,\n ...(options.state === undefined ? {} : { state: options.state }),\n };\n this.requestedAtMs.set(request.nodeId, Date.now());\n\n const generation = state.generation;\n const task = state.tail.then(() => this.record(state, generation, request));\n state.tail = task.catch(() => undefined);\n\n return task;\n }\n\n /**\n * Records one node and its outcome. Fails if the tab navigates or\n * closes before it finishes, or if it runs past the record timeout.\n */\n private async record(\n state: PageState,\n generation: number,\n request: NodeRequest,\n ): Promise<void> {\n const { page } = state;\n const deadline = startDeadline(\n this.recordTimeoutMs,\n 'Ralph recording timed out.',\n );\n const { wait } = deadline;\n const navigatedAway = () =>\n state.generation !== generation || page.url() !== request.actualUrl;\n\n const check = () => {\n deadline.signal.throwIfAborted();\n if (navigatedAway()) {\n throw new Error('The page navigated before its recording completed.');\n }\n if (page.isClosed()) {\n throw new Error('The page closed before its recording completed.');\n }\n };\n\n try {\n check();\n if (request.trigger === 'url-change') {\n await this.waitForPageToSettle(page, deadline, check);\n }\n\n // Geometry is read on both sides of the screenshot to detect layout drift.\n check();\n const before = await wait(readLayout(page));\n check();\n const image = await wait(takeScreenshot(page, deadline.endsAt));\n check();\n const after = await wait(readLayout(page));\n check();\n\n this.nodes.push({\n ...request,\n status: 'recorded',\n recordedAt: new Date().toISOString(),\n layout: before,\n geometryStable: JSON.stringify(before) === JSON.stringify(after),\n screenshot: await this.saveScreenshot(request.nodeId, image),\n });\n } catch (error) {\n this.nodes.push({\n ...request,\n status: navigatedAway() ? 'superseded' : 'failed',\n reason: error instanceof Error ? error.message : String(error),\n });\n if (request.trigger === 'explicit') {\n throw error;\n }\n } finally {\n deadline.cancel();\n }\n }\n\n /** After a navigation: the DOM, the settle delay, then the `ready` hook. */\n private async waitForPageToSettle(\n page: Page,\n { wait, signal }: Deadline,\n check: () => void,\n ): Promise<void> {\n await wait(\n page.waitForLoadState('domcontentloaded', {\n timeout: this.recordTimeoutMs,\n }),\n );\n await wait(delay(this.settleMs, undefined, { signal }));\n check();\n if (this.options.ready) {\n await wait(this.options.ready(page, signal));\n }\n }\n\n /** Writes the image to the test output and attaches it to the report. */\n private async saveScreenshot(\n nodeId: string,\n image: Screenshot,\n ): Promise<RecordedNode['screenshot']> {\n const path = OUTPUT_DIR + '/' + nodeId + imageExtension(image.contentType);\n const attachmentName = 'ralph-screenshot-' + nodeId;\n\n await mkdir(this.testInfo.outputPath(OUTPUT_DIR), { recursive: true });\n await writeFile(this.testInfo.outputPath(path), image.bytes);\n await this.testInfo.attach(attachmentName, {\n path: this.testInfo.outputPath(path),\n contentType: image.contentType,\n });\n\n return {\n path,\n attachmentName,\n width: image.width,\n height: image.height,\n scale: 'css',\n contentType: image.contentType,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Manifest\n // ---------------------------------------------------------------------------\n\n private pageInfo(pageId: string): PageInfo | undefined {\n return [...this.pages.values()].find(\n (state) => state.info.pageId === pageId,\n )?.info;\n }\n\n private buildManifest(\n nodes: RawNode[],\n failureCount: number,\n ): RawGraphManifest {\n const { testInfo } = this;\n const testPassed = testInfo.status === 'passed';\n\n return {\n formatVersion: 1,\n producer: {\n name: '@ralphralphai/playwright',\n version: packageInfo.version,\n playwrightVersion: playwrightPackage.version,\n },\n runId: this.options.runId ?? process.env['RALPH_RUN_ID'],\n buildId: this.options.buildId ?? process.env['RALPH_BUILD_ID'],\n attemptId: this.attemptId,\n test: {\n id: testInfo.testId,\n titlePath: testInfo.titlePath,\n project: testInfo.project.name,\n retry: testInfo.retry,\n repeatEachIndex: testInfo.repeatEachIndex,\n workerIndex: testInfo.workerIndex,\n parallelIndex: testInfo.parallelIndex,\n shard: testInfo.config.shard,\n // Failed nodes fail the test in `finish`, after this is written.\n status:\n failureCount && testPassed\n ? 'failed'\n : (testInfo.status ?? 'unknown'),\n expectedStatus: testInfo.expectedStatus,\n },\n startedAt: this.startedAt,\n finishedAt: new Date().toISOString(),\n config: this.config,\n pages: [...this.pages.values()].map((state) => state.info),\n nodes,\n complete:\n testPassed &&\n nodes.length > 0 &&\n nodes.every(\n (item) => item.status === 'recorded' && item.geometryStable,\n ),\n };\n }\n\n private async writeManifest(manifest: RawGraphManifest): Promise<void> {\n const file = this.testInfo.outputPath(OUTPUT_DIR, 'raw_graph.json');\n await mkdir(this.testInfo.outputPath(OUTPUT_DIR), { recursive: true });\n await writeFile(file, JSON.stringify(manifest, null, 2) + '\\n');\n await this.testInfo.attach(MANIFEST_ATTACHMENT, {\n path: file,\n contentType: 'application/json',\n });\n }\n\n private async uploadManifest(\n manifest: RawGraphManifest,\n upload: UploadOptions,\n ): Promise<void> {\n const recorded = manifest.nodes.filter(\n (item): item is RecordedNode => item.status === 'recorded',\n );\n const screenshots = [];\n for (const { nodeId, screenshot } of recorded) {\n screenshots.push({\n nodeId,\n contentType: screenshot.contentType,\n bytes: await readFile(this.testInfo.outputPath(screenshot.path)),\n });\n }\n\n const receipt = await uploadRawGraph(manifest, screenshots, upload);\n await this.testInfo.attach('ralph-upload-receipt', {\n body: JSON.stringify(receipt),\n contentType: 'application/json',\n });\n }\n}\n\n// -----------------------------------------------------------------------------\n// Helpers\n// -----------------------------------------------------------------------------\n\nfunction isHttpUrl(url: string): boolean {\n return /^https?:/.test(url);\n}\n\ntype Deadline = {\n signal: AbortSignal;\n /** Epoch milliseconds at which the deadline passes. */\n endsAt: number;\n /** Rejects with the timeout error if `promise` outlives the deadline. */\n wait: <T>(promise: Promise<T>) => Promise<T>;\n cancel: () => void;\n};\n\nfunction startDeadline(timeoutMs: number, message: string): Deadline {\n const controller = new AbortController();\n const { signal } = controller;\n const timer = setTimeout(\n () => controller.abort(new Error(message)),\n timeoutMs,\n );\n const aborted = new Promise<never>((_, reject) => {\n signal.addEventListener('abort', () => reject(signal.reason), {\n once: true,\n });\n });\n // Nothing may be waiting when the deadline passes.\n aborted.catch(() => undefined);\n\n return {\n signal,\n endsAt: Date.now() + timeoutMs,\n wait: (promise) => Promise.race([promise, aborted]),\n cancel: () => clearTimeout(timer),\n };\n}\n\n/**\n * Sets `previousNodeId` on each node: the one before it in the same\n * tab, or for a popup's first node, its opener's latest. Superseded nodes\n * are skipped, since their page state was never shown.\n *\n * `nodes` must be sorted by page, then sequence.\n */\nfunction linkPreviousNodes(\n nodes: RawNode[],\n openerOf: (pageId: string) => string | undefined,\n requestedAtMs: (nodeId: string) => number,\n): void {\n const byPage = new Map<string, RawNode[]>();\n for (const item of nodes) {\n byPage.set(item.pageId, [...(byPage.get(item.pageId) ?? []), item]);\n }\n\n const openerNodeBefore = (item: RawNode) => {\n const openerPageId = openerOf(item.pageId);\n const requestedAt = requestedAtMs(item.nodeId);\n return byPage\n .get(openerPageId ?? '')\n ?.filter((candidate) => requestedAtMs(candidate.nodeId) <= requestedAt)\n .at(-1);\n };\n\n // First the raw chain, superseded nodes included.\n const previous = new Map<RawNode, RawNode>();\n for (const items of byPage.values()) {\n items.forEach((item, index) => {\n const from = index > 0 ? items[index - 1] : openerNodeBefore(item);\n if (from) {\n previous.set(item, from);\n }\n });\n }\n\n // Then skip past superseded ones, e.g. a redirect or a replaced route.\n for (const item of nodes) {\n let from = previous.get(item);\n while (from?.status === 'superseded') {\n from = previous.get(from);\n }\n if (from) {\n item.previousNodeId = from.nodeId;\n }\n }\n}\n","import type {\n PlaywrightTestOptions,\n PlaywrightWorkerOptions,\n Project,\n TestInfo,\n} from '@playwright/test';\nimport type { ScreenSize } from '@ralphralphai/config';\n\nimport { loadConfigSync } from './config';\nimport type { RalphOptions } from './types';\n\ntype RalphProject = Project<\n PlaywrightTestOptions & { ralphOptions: RalphOptions },\n PlaywrightWorkerOptions\n>;\n\nexport const SCREEN_TAG_PREFIX = '@ralph-screen:';\n\nexport type RalphProjectOptions = Pick<\n RalphOptions,\n 'config' | 'configPath'\n> & {\n /** Resolves a relative `configPath`; defaults to the current directory. */\n root?: string;\n};\n\ntype ScreenMetadata = { screenSize: ScreenSize; screenSizes: ScreenSize[] };\n\nexport function screenLabel(size: ScreenSize): string {\n return size.width + 'x' + size.height;\n}\n\n/**\n * Expands `base` into one project per `screenSizes` entry of the Ralph config.\n * Each project's viewport is that screen size.\n */\nexport function ralphProjects(\n base: RalphProject = {},\n options: RalphProjectOptions = {},\n): RalphProject[] {\n const { screenSizes } = loadConfigSync(\n options,\n options.root ?? process.cwd(),\n ).config;\n if (!screenSizes.length) {\n throw new Error('The Ralph config declares no screenSizes.');\n }\n return screenSizes.map((screenSize) => {\n const label = screenLabel(screenSize);\n const ralph: ScreenMetadata = { screenSize, screenSizes };\n return {\n ...base,\n name: base.name ? base.name + ' ' + label : label,\n use: {\n ...base.use,\n viewport: { width: screenSize.width, height: screenSize.height },\n },\n metadata: { ...base.metadata, ralph },\n };\n });\n}\n\n/**\n * Skips a test whose `@ralph-screen:WxH` tags exclude the current project's\n * screen size. Untagged tests run at every size; other projects are untouched.\n */\nexport function applyScreenSelection(testInfo: TestInfo): void {\n const selected = testInfo.tags\n .filter((tag) => tag.startsWith(SCREEN_TAG_PREFIX))\n .map((tag) => tag.slice(SCREEN_TAG_PREFIX.length));\n const metadata = (testInfo.project.metadata as { ralph?: ScreenMetadata })\n .ralph;\n if (!selected.length || !metadata) {\n return;\n }\n const known = metadata.screenSizes.map(screenLabel);\n const unknown = selected.filter((label) => !known.includes(label));\n if (unknown.length) {\n throw new Error(\n 'Unknown Ralph screen size ' +\n unknown.join(', ') +\n '; the config declares ' +\n known.join(', ') +\n '.',\n );\n }\n const current = screenLabel(metadata.screenSize);\n testInfo.skip(\n !selected.includes(current),\n 'Not selected for Ralph screen size ' + current + '.',\n );\n}\n","import path from 'node:path';\n\nimport { test as base } from '@playwright/test';\nimport type {\n PlaywrightTestArgs,\n PlaywrightTestOptions,\n PlaywrightWorkerArgs,\n PlaywrightWorkerOptions,\n TestType,\n} from '@playwright/test';\n\nimport { loadConfig, resolveMode } from './config';\nimport { Recorder } from './recorder';\nimport { applyScreenSelection } from './screens';\nimport type { ConfigSnapshot, Ralph, RalphOptions } from './types';\nimport { resolveUploadOptions } from './upload';\n\nexport { expect, mergeTests } from '@playwright/test';\nexport type { WebRalphConfig } from '@ralphralphai/config';\nexport { createRawGraphBundle, uploadRawGraph } from './upload';\nexport type {\n UploadOptions,\n UploadReceipt,\n RawGraphScreenshot,\n RawGraphBundleIndex,\n} from './upload';\nexport { MANIFEST_ATTACHMENT } from './recorder';\nexport { ralphProjects, SCREEN_TAG_PREFIX } from './screens';\nexport type { RalphProjectOptions } from './screens';\nexport type {\n RawGraphManifest,\n RawNode,\n RecordNodeOptions,\n ConfigSnapshot,\n PageLayout,\n Ralph,\n RalphOptions,\n TrackedElement,\n} from './types';\n\nexport type RalphFixtures = { ralph: Ralph; ralphOptions: RalphOptions };\n\ntype InternalFixtures = {\n _ralphScreen: void;\n _ralphRecorder: Recorder | null;\n};\ntype WorkerFixtures = { _ralphConfigs: Map<string, Promise<ConfigSnapshot>> };\n\nexport const test: TestType<\n PlaywrightTestArgs & PlaywrightTestOptions & RalphFixtures,\n PlaywrightWorkerArgs & PlaywrightWorkerOptions\n> = base.extend<RalphFixtures & InternalFixtures, WorkerFixtures>({\n ralphOptions: [{}, { option: true }],\n _ralphConfigs: [\n // Playwright requires destructuring here to discover fixture dependencies.\n // oxlint-disable-next-line no-empty-pattern\n async ({}, use) => {\n await use(new Map());\n },\n { scope: 'worker' },\n ],\n _ralphScreen: [\n // Playwright requires destructuring here to discover fixture dependencies.\n // oxlint-disable-next-line no-empty-pattern\n async ({}, use, testInfo) => {\n // Screen selection chooses which flows run, so it applies in every mode.\n applyScreenSelection(testInfo);\n await use();\n },\n { auto: true },\n ],\n _ralphRecorder: [\n // _ralphScreen is specified here so that the playwright treat that it is\n // a dependency of this fixture.\n async ({ ralphOptions, _ralphConfigs, _ralphScreen }, use, testInfo) => {\n if (\n !testInfo.tags.includes('@ralph') ||\n resolveMode(ralphOptions) === 'off'\n ) {\n await use(null);\n return;\n }\n\n const upload =\n resolveMode(ralphOptions) === 'upload'\n ? resolveUploadOptions(ralphOptions)\n : undefined;\n\n const root = testInfo.config.configFile\n ? path.dirname(testInfo.config.configFile)\n : process.cwd();\n\n const key = JSON.stringify({\n root,\n config: ralphOptions.config,\n configPath: ralphOptions.configPath,\n });\n\n let pending = _ralphConfigs.get(key);\n if (!pending) {\n pending = loadConfig(ralphOptions, root);\n _ralphConfigs.set(key, pending);\n }\n\n const recorder = new Recorder(\n ralphOptions,\n await pending,\n testInfo,\n upload,\n );\n\n try {\n await use(recorder);\n } finally {\n await recorder.finish();\n }\n },\n { auto: true, timeout: 30_000 },\n ],\n ralph: async ({ _ralphRecorder, ralphOptions }, use) => {\n const checkOptIn = () => {\n if (resolveMode(ralphOptions) !== 'off') {\n throw new Error('Opt this test into Ralph with the @ralph tag.');\n }\n };\n\n await use(\n _ralphRecorder ?? {\n recordNode: async () => {\n checkOptIn();\n },\n flush: async () => {},\n observe: () => {\n checkOptIn();\n },\n },\n );\n },\n context: async ({ context, _ralphRecorder }, use) => {\n _ralphRecorder?.observe(context);\n try {\n await use(context);\n } finally {\n // The base context fixture closes its pages next; pending recordings still need them alive.\n await _ralphRecorder?.stopContext(context);\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,SAAgB,YAAY,SAAmD;CAC7E,MAAM,OACJ,QAAQ,QACR,QAAQ,IAAI,kBACX,QAAQ,IAAI,sBAAsB,WAAW;CAChD,IAAI,SAAS,SAAS,SAAS,WAAW,SAAS,UACjD,OAAO;CAGT,MAAM,IAAI,MAAM,2CAA2C;AAC7D;AAIA,eAAsB,WACpB,SACA,MACyB;CACzB,MAAM,OAAO,WAAW,SAAS,IAAI;CACrC,OAAO,SAAS,QAAQ,UAAU,YAAY,OAAA,GAAMA,iBAAAA,SAAAA,CAAS,MAAM,MAAM,CAAC,CAAC;AAC7E;AAGA,SAAgB,eACd,SACA,MACgB;CAChB,MAAM,OAAO,WAAW,SAAS,IAAI;CACrC,OAAO,SAAS,QAAQ,UAAU,aAAA,GAAYC,QAAAA,aAAAA,CAAa,MAAM,MAAM,CAAC,CAAC;AAC3E;AAEA,SAAS,WAAW,SAAuB,MAAsB;CAC/D,IAAI,QAAQ,UAA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ACjC,KAAA;EAEN,MAAM,OAAO,SAAS,OAAO,aACzBC,UAAAA,QAAK,QAAQ,SAAS,OAAO,UAAU,IACvC,QAAQ,IAAI;EAEhB,MAAM,MAAM,KAAK,UAAU;GACzB;GACA,QAAQ,aAAa;GACrB,YAAY,aAAa;EAC3B,CAAC;EAED,IAAI,UAAU,cAAc,IAAI,GAAG;EACnC,IAAI,CAAC,SAAS;GACZ,UAAU,WAAW,cAAc,IAAI;GACvC,cAAc,IAAI,KAAK,OAAO;EAChC;EAEA,MAAM,WAAW,IAAI,SACnB,cACA,MAAM,SACN,UACA,MACF;EAEA,IAAI;GACF,MAAM,IAAI,QAAQ;EACpB,UAAU;GACR,MAAM,SAAS,OAAO;EACxB;CACF,GACA;EAAE,MAAM;EAAM,SAAS;CAAO,CAChC;CACA,OAAO,OAAO,EAAE,gBAAgB,gBAAgB,QAAQ;EACtD,MAAM,mBAAmB;GACvB,IAAI,YAAY,YAAY,MAAM,OAChC,MAAM,IAAI,MAAM,+CAA+C;EAEnE;EAEA,MAAM,IACJ,kBAAkB;GAChB,YAAY,YAAY;IACtB,WAAW;GACb;GACA,OAAO,YAAY,CAAC;GACpB,eAAe;IACb,WAAW;GACb;EACF,CACF;CACF;CACA,SAAS,OAAO,EAAE,SAAS,kBAAkB,QAAQ;EACnD,gBAAgB,QAAQ,OAAO;EAC/B,IAAI;GACF,MAAM,IAAI,OAAO;EACnB,UAAU;GAER,MAAM,gBAAgB,YAAY,OAAO;EAC3C;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["loadConfigSync","base","resolveMode","path","loadConfig","Recorder"],"sources":["../src/screens.ts","../src/index.ts"],"sourcesContent":["import type {\n PlaywrightTestOptions,\n PlaywrightWorkerOptions,\n Project,\n TestInfo,\n} from '@playwright/test';\nimport type { ScreenSize } from '@ralphralphai/config';\n\nimport { loadConfigSync } from './config';\nimport type { RalphOptions } from './types';\n\ntype RalphProject = Project<\n PlaywrightTestOptions & { ralphOptions: RalphOptions },\n PlaywrightWorkerOptions\n>;\n\nexport const SCREEN_TAG_PREFIX = '@ralph-screen:';\n\nexport type RalphProjectOptions = Pick<\n RalphOptions,\n 'config' | 'configPath'\n> & {\n /** Resolves a relative `configPath`; defaults to the current directory. */\n root?: string;\n};\n\ntype ScreenMetadata = { screenSize: ScreenSize; screenSizes: ScreenSize[] };\n\nexport function screenLabel(size: ScreenSize): string {\n return size.width + 'x' + size.height;\n}\n\n/**\n * Expands `base` into one project per `screenSizes` entry of the Ralph config.\n * Each project's viewport is that screen size.\n */\nexport function ralphProjects(\n base: RalphProject = {},\n options: RalphProjectOptions = {},\n): RalphProject[] {\n const { screenSizes } = loadConfigSync(\n options,\n options.root ?? process.cwd(),\n ).config;\n if (!screenSizes.length) {\n throw new Error('The Ralph config declares no screenSizes.');\n }\n return screenSizes.map((screenSize) => {\n const label = screenLabel(screenSize);\n const ralph: ScreenMetadata = { screenSize, screenSizes };\n return {\n ...base,\n name: base.name ? base.name + ' ' + label : label,\n use: {\n ...base.use,\n viewport: { width: screenSize.width, height: screenSize.height },\n },\n metadata: { ...base.metadata, ralph },\n };\n });\n}\n\n/**\n * Skips a test whose `@ralph-screen:WxH` tags exclude the current project's\n * screen size. Untagged tests run at every size; other projects are untouched.\n */\nexport function applyScreenSelection(testInfo: TestInfo): void {\n const selected = testInfo.tags\n .filter((tag) => tag.startsWith(SCREEN_TAG_PREFIX))\n .map((tag) => tag.slice(SCREEN_TAG_PREFIX.length));\n const metadata = (testInfo.project.metadata as { ralph?: ScreenMetadata })\n .ralph;\n if (!selected.length || !metadata) {\n return;\n }\n const known = metadata.screenSizes.map(screenLabel);\n const unknown = selected.filter((label) => !known.includes(label));\n if (unknown.length) {\n throw new Error(\n 'Unknown Ralph screen size ' +\n unknown.join(', ') +\n '; the config declares ' +\n known.join(', ') +\n '.',\n );\n }\n const current = screenLabel(metadata.screenSize);\n testInfo.skip(\n !selected.includes(current),\n 'Not selected for Ralph screen size ' + current + '.',\n );\n}\n","import path from 'node:path';\n\nimport { test as base } from '@playwright/test';\nimport type {\n PlaywrightTestArgs,\n PlaywrightTestOptions,\n PlaywrightWorkerArgs,\n PlaywrightWorkerOptions,\n TestType,\n} from '@playwright/test';\n\nimport { loadConfig, resolveMode } from './config';\nimport { Recorder, REPORTER_ENV } from './recorder';\nimport { applyScreenSelection } from './screens';\nimport type { ConfigSnapshot, Ralph, RalphOptions } from './types';\n\nexport { expect, mergeTests } from '@playwright/test';\nexport type { WebRalphConfig } from '@ralphralphai/config';\nexport {\n createRawGraphBundle,\n prepareArtifactUpload,\n uploadRawGraph,\n} from './upload';\nexport type {\n PreparedUpload,\n UploadOptions,\n UploadReceipt,\n RawGraphScreenshot,\n RawGraphBundleIndex,\n} from './upload';\nexport { MANIFEST_ATTACHMENT } from './recorder';\nexport { ralphProjects, SCREEN_TAG_PREFIX } from './screens';\nexport type { RalphProjectOptions } from './screens';\nexport type { RalphReporterOptions } from './reporter';\nexport type {\n RawGraphManifest,\n RawGraph,\n RawGraphFile,\n RawPage,\n RawNode,\n RecordNodeOptions,\n ConfigSnapshot,\n PageLayout,\n Ralph,\n RalphOptions,\n TrackedElement,\n} from './types';\n\nexport type RalphFixtures = { ralph: Ralph; ralphOptions: RalphOptions };\n\ntype InternalFixtures = {\n _ralphScreen: void;\n _ralphRecorder: Recorder | null;\n};\ntype WorkerFixtures = { _ralphConfigs: Map<string, Promise<ConfigSnapshot>> };\n\nexport const test: TestType<\n PlaywrightTestArgs & PlaywrightTestOptions & RalphFixtures,\n PlaywrightWorkerArgs & PlaywrightWorkerOptions\n> = base.extend<RalphFixtures & InternalFixtures, WorkerFixtures>({\n ralphOptions: [{}, { option: true }],\n _ralphConfigs: [\n // Playwright requires destructuring here to discover fixture dependencies.\n // oxlint-disable-next-line no-empty-pattern\n async ({}, use) => {\n await use(new Map());\n },\n { scope: 'worker' },\n ],\n _ralphScreen: [\n // Playwright requires destructuring here to discover fixture dependencies.\n // oxlint-disable-next-line no-empty-pattern\n async ({}, use, testInfo) => {\n // Screen selection chooses which flows run, so it applies in every mode.\n applyScreenSelection(testInfo);\n await use();\n },\n { auto: true },\n ],\n _ralphRecorder: [\n // _ralphScreen is specified here so that the playwright treat that it is\n // a dependency of this fixture.\n async ({ ralphOptions, _ralphConfigs, _ralphScreen }, use, testInfo) => {\n const mode = resolveMode(ralphOptions);\n if (!testInfo.tags.includes('@ralph') || mode === 'off') {\n await use(null);\n return;\n }\n\n // A sharded run's blob reports are merged, and uploaded by the Ralph\n // reporter, in `playwright merge-reports`.\n const reported =\n process.env[REPORTER_ENV] ||\n testInfo.config.reporter.some(([name]) => name === 'blob');\n if (mode === 'upload' && !reported) {\n throw new Error(\n \"Ralph uploads one merged graph per run from its reporter. Add ['@ralphralphai/playwright/reporter'] to `reporter` in playwright.config, or use the blob reporter and merge-reports when sharding.\",\n );\n }\n\n const root = testInfo.config.configFile\n ? path.dirname(testInfo.config.configFile)\n : process.cwd();\n\n const key = JSON.stringify({\n root,\n config: ralphOptions.config,\n configPath: ralphOptions.configPath,\n });\n\n let pending = _ralphConfigs.get(key);\n if (!pending) {\n pending = loadConfig(ralphOptions, root);\n _ralphConfigs.set(key, pending);\n }\n\n const recorder = new Recorder(\n ralphOptions,\n await pending,\n testInfo,\n mode,\n );\n\n try {\n await use(recorder);\n } finally {\n await recorder.finish();\n }\n },\n { auto: true, timeout: 30_000 },\n ],\n ralph: async ({ _ralphRecorder, ralphOptions }, use) => {\n const checkOptIn = () => {\n if (resolveMode(ralphOptions) !== 'off') {\n throw new Error('Opt this test into Ralph with the @ralph tag.');\n }\n };\n\n await use(\n _ralphRecorder ?? {\n recordNode: async () => {\n checkOptIn();\n },\n waitForCapture: async () => {},\n pause: () => {},\n resume: () => {},\n observe: () => {\n checkOptIn();\n },\n },\n );\n },\n // On the context rather than per page, so popups start out reduced too.\n contextOptions: async ({ contextOptions, ralphOptions }, use, testInfo) => {\n const recording =\n testInfo.tags.includes('@ralph') && resolveMode(ralphOptions) !== 'off';\n await use(\n recording && ralphOptions.reduceMotion\n ? { ...contextOptions, reducedMotion: 'reduce' }\n : contextOptions,\n );\n },\n context: async ({ context, _ralphRecorder }, use) => {\n _ralphRecorder?.observe(context);\n try {\n await use(context);\n } finally {\n // The base context fixture closes its pages next; pending recordings still need them alive.\n await _ralphRecorder?.stopContext(context);\n }\n },\n});\n"],"mappings":";;;;;;AAgBA,MAAa,oBAAoB;AAYjC,SAAgB,YAAY,MAA0B;CACpD,OAAO,KAAK,QAAQ,MAAM,KAAK;AACjC;;;;;AAMA,SAAgB,cACd,OAAqB,CAAC,GACtB,UAA+B,CAAC,GAChB;CAChB,MAAM,EAAE,gBAAgBA,eAAAA,eACtB,SACA,QAAQ,QAAQ,QAAQ,IAAI,CAC9B,CAAC,CAAC;CACF,IAAI,CAAC,YAAY,QACf,MAAM,IAAI,MAAM,2CAA2C;CAE7D,OAAO,YAAY,KAAK,eAAe;EACrC,MAAM,QAAQ,YAAY,UAAU;EACpC,MAAM,QAAwB;GAAE;GAAY;EAAY;EACxD,OAAO;GACL,GAAG;GACH,MAAM,KAAK,OAAO,KAAK,OAAO,MAAM,QAAQ;GAC5C,KAAK;IACH,GAAG,KAAK;IACR,UAAU;KAAE,OAAO,WAAW;KAAO,QAAQ,WAAW;IAAO;GACjE;GACA,UAAU;IAAE,GAAG,KAAK;IAAU;GAAM;EACtC;CACF,CAAC;AACH;;;;;AAMA,SAAgB,qBAAqB,UAA0B;CAC7D,MAAM,WAAW,SAAS,KACvB,QAAQ,QAAQ,IAAI,WAAW,iBAAiB,CAAC,CAAC,CAClD,KAAK,QAAQ,IAAI,MAAM,EAAwB,CAAC;CACnD,MAAM,WAAY,SAAS,QAAQ,SAChC;CACH,IAAI,CAAC,SAAS,UAAU,CAAC,UACvB;CAEF,MAAM,QAAQ,SAAS,YAAY,IAAI,WAAW;CAClD,MAAM,UAAU,SAAS,QAAQ,UAAU,CAAC,MAAM,SAAS,KAAK,CAAC;CACjE,IAAI,QAAQ,QACV,MAAM,IAAI,MACR,+BAC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I;GACF,MAAM,IAAI,QAAQ;EACpB,UAAU;GACR,MAAM,SAAS,OAAO;EACxB;CACF,GACA;EAAE,MAAM;EAAM,SAAS;CAAO,CAChC;CACA,OAAO,OAAO,EAAE,gBAAgB,gBAAgB,QAAQ;EACtD,MAAM,mBAAmB;GACvB,IAAIH,eAAAA,YAAY,YAAY,MAAM,OAChC,MAAM,IAAI,MAAM,+CAA+C;EAEnE;EAEA,MAAM,IACJ,kBAAkB;GAChB,YAAY,YAAY;IACtB,WAAW;GACb;GACA,gBAAgB,YAAY,CAAC;GAC7B,aAAa,CAAC;GACd,cAAc,CAAC;GACf,eAAe;IACb,WAAW;GACb;EACF,CACF;CACF;CAEA,gBAAgB,OAAO,EAAE,gBAAgB,gBAAgB,KAAK,aAAa;EAGzE,MAAM,IADJ,SAAS,KAAK,SAAS,QAAQ,KAAKA,eAAAA,YAAY,YAAY,MAAM,SAErD,aAAa,eACtB;GAAE,GAAG;GAAgB,eAAe;EAAS,IAC7C,cACN;CACF;CACA,SAAS,OAAO,EAAE,SAAS,kBAAkB,QAAQ;EACnD,gBAAgB,QAAQ,OAAO;EAC/B,IAAI;GACF,MAAM,IAAI,OAAO;EACnB,UAAU;GAER,MAAM,gBAAgB,YAAY,OAAO;EAC3C;CACF;AACF,CAAC"}
package/dist/index.d.mts CHANGED
@@ -1,16 +1,15 @@
1
+ import { RalphReporterOptions } from "./reporter.mjs";
1
2
  import { BrowserContext, Page, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions, Project, TestType, expect, mergeTests } from "@playwright/test";
2
3
  import { WebRalphConfig, WebRalphConfig as WebRalphConfig$1 } from "@ralphralphai/config";
3
4
  //#region src/types.d.ts
4
5
  type RalphOptions = {
5
6
  mode?: 'off' | 'local' | 'upload';
6
- apiUrl?: string;
7
- appId?: string;
8
- uploadTimeoutMs?: number;
9
7
  config?: WebRalphConfig$1;
10
8
  configPath?: string;
11
9
  runId?: string;
12
10
  buildId?: string;
13
11
  settleMs?: number;
12
+ reduceMotion?: boolean;
14
13
  recordTimeoutMs?: number;
15
14
  ready?: (page: Page, signal: AbortSignal) => Promise<void>;
16
15
  };
@@ -20,7 +19,9 @@ type RecordNodeOptions = {
20
19
  };
21
20
  type Ralph = {
22
21
  recordNode(page: Page, options?: RecordNodeOptions): Promise<void>;
23
- flush(): Promise<void>;
22
+ waitForCapture(): Promise<void>;
23
+ pause(): void;
24
+ resume(): void;
24
25
  observe(context: BrowserContext): void;
25
26
  };
26
27
  type TrackedElement = {
@@ -57,8 +58,8 @@ type RawNode = {
57
58
  state?: string;
58
59
  /**
59
60
  * The node this page state was reached from: the previous one on the same
60
- * page, or for a popup's first node, its opener's latest. Superseded nodes
61
- * are skipped.
61
+ * page, or for a popup's first node, its opener's latest. Superseded and
62
+ * failed nodes are included; the server walks past the ones it doesn't show.
62
63
  */
63
64
  previousNodeId?: string;
64
65
  } & ({
@@ -75,48 +76,82 @@ type RawNode = {
75
76
  contentType: 'image/webp' | 'image/png';
76
77
  };
77
78
  } | {
78
- status: 'superseded' | 'failed';
79
- reason: string;
79
+ /** The page was visited but has no screenshot. */
80
+ status: 'uncaptured';
81
+ /**
82
+ * `navigated-away`: the tab navigated or closed first, e.g. the test
83
+ * moved on, a redirect, or a route replaced at once. `error`: the
84
+ * recording failed, e.g. it timed out.
85
+ */
86
+ reason: 'navigated-away' | 'error';
87
+ /** The error as thrown. */
88
+ message: string;
80
89
  });
81
90
  type ConfigSnapshot = {
82
91
  config: WebRalphConfig$1;
83
92
  packageVersion: string;
84
93
  };
94
+ type RawGraphProducer = {
95
+ name: '@ralphralphai/playwright';
96
+ version: string;
97
+ playwrightVersion: string;
98
+ };
99
+ type RawPage = {
100
+ /** Unique within its test only. */
101
+ pageId: string;
102
+ browserName?: string;
103
+ openerPageId?: string;
104
+ };
105
+ /** One test's recordings. Its nodes link only to each other. */
106
+ type RawGraph = {
107
+ id: string;
108
+ titlePath: string[];
109
+ project: string;
110
+ retry: number;
111
+ repeatEachIndex: number;
112
+ workerIndex: number;
113
+ parallelIndex: number;
114
+ status: string;
115
+ expectedStatus: string;
116
+ startedAt: string;
117
+ finishedAt: string;
118
+ pages: RawPage[];
119
+ nodes: RawNode[];
120
+ /** The test passed and every node was recorded with stable geometry. */
121
+ complete: boolean;
122
+ };
123
+ /**
124
+ * What a test writes and attaches as `ralph-raw-graph`, for the reporter to
125
+ * merge into the run's `RawGraphManifest`.
126
+ */
127
+ type RawGraphFile = {
128
+ formatVersion: 1;
129
+ producer: RawGraphProducer;
130
+ runId?: string;
131
+ buildId?: string;
132
+ config: ConfigSnapshot;
133
+ /** The test's mode. The reporter uploads the run if any test's is `upload`. */
134
+ mode: 'local' | 'upload';
135
+ rawGraph: RawGraph;
136
+ };
137
+ /** One Playwright run (or shard): every recorded test's raw graph, merged. */
85
138
  type RawGraphManifest = {
86
139
  formatVersion: 1;
87
- producer: {
88
- name: '@ralphralphai/playwright';
89
- version: string;
90
- playwrightVersion: string;
91
- };
140
+ producer: RawGraphProducer;
92
141
  runId?: string;
93
142
  buildId?: string;
94
- attemptId: string;
95
- test: {
96
- id: string;
97
- titlePath: string[];
98
- project: string;
99
- retry: number;
100
- repeatEachIndex: number;
101
- workerIndex: number;
102
- parallelIndex: number;
103
- shard: {
104
- current: number;
105
- total: number;
106
- } | null;
107
- status: string;
108
- expectedStatus: string;
109
- };
143
+ /** New for every run, so each run is its own artifact. */
144
+ artifactId: string;
145
+ shard: {
146
+ current: number;
147
+ total: number;
148
+ } | null;
110
149
  startedAt: string;
111
150
  finishedAt: string;
112
151
  config: ConfigSnapshot;
113
- pages: {
114
- pageId: string;
115
- contextId: string;
116
- browserName?: string;
117
- openerPageId?: string;
118
- }[];
119
- nodes: RawNode[];
152
+ /** The final attempt of each recorded test, one raw graph each. */
153
+ rawGraphs: RawGraph[];
154
+ /** Every raw graph is complete. */
120
155
  complete: boolean;
121
156
  };
122
157
  //#endregion
@@ -140,11 +175,18 @@ type RawGraphScreenshot = {
140
175
  contentType: Screenshot['contentType'];
141
176
  bytes: Uint8Array;
142
177
  };
178
+ /** An artifact the server reserved, which the upload and the manifest must name. */
179
+ type PreparedUpload = {
180
+ artifactId: string;
181
+ /** Where the result opens in the Ralph dashboard, when the server knows. */
182
+ resultUrl?: string;
183
+ };
184
+ /** The bundle is stored and queued; the result page shows it being processed. */
143
185
  type UploadReceipt = {
144
186
  result: 'ok';
145
- status: 'received';
146
- attemptId: string;
147
- resultId: string;
187
+ status: 'queued';
188
+ artifactId: string;
189
+ resultUrl?: string;
148
190
  replayed: boolean;
149
191
  };
150
192
  type RawGraphBundleIndex = {
@@ -154,16 +196,22 @@ type RawGraphBundleIndex = {
154
196
  path: string;
155
197
  }[];
156
198
  };
199
+ /** The bundle `uploadRawGraph` streams, whole, for saving or inspecting it. */
200
+ declare function createRawGraphBundle(manifest: RawGraphManifest, screenshots: readonly RawGraphScreenshot[]): Promise<Uint8Array>;
157
201
  /**
158
- * Packs the manifest and screenshots into a gzipped tar archive:
159
- *
160
- * raw_graph.json { manifest, screenshots: [{ nodeId, path }] }
161
- * assets/images/<id>.webp raw screenshot bytes (.png when too large for WebP)
202
+ * Reserves an artifact for the run. Its `resultUrl` works from now on, so the
203
+ * run can be followed while it uploads and while Ralph processes it.
204
+ */
205
+ declare function prepareArtifactUpload(options: UploadOptions): Promise<PreparedUpload>;
206
+ /**
207
+ * Streams the run's bundle to the artifact `manifest.artifactId` names, which
208
+ * `prepareArtifactUpload` has to have reserved. Ralph processes it after this
209
+ * returns; the result page shows when it is ready.
162
210
  */
163
- declare function createRawGraphBundle(manifest: RawGraphManifest, screenshots: readonly RawGraphScreenshot[]): Promise<Uint8Array>;
164
211
  declare function uploadRawGraph(manifest: RawGraphManifest, screenshots: readonly RawGraphScreenshot[], options: UploadOptions): Promise<UploadReceipt>;
165
212
  //#endregion
166
213
  //#region src/recorder.d.ts
214
+ /** The attachment holding a test's `RawGraphFile`, which the reporter merges. */
167
215
  declare const MANIFEST_ATTACHMENT = "ralph-raw-graph";
168
216
  //#endregion
169
217
  //#region src/screens.d.ts
@@ -188,5 +236,5 @@ type RalphFixtures = {
188
236
  };
189
237
  declare const test: TestType<PlaywrightTestArgs & PlaywrightTestOptions & RalphFixtures, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;
190
238
  //#endregion
191
- export { type ConfigSnapshot, MANIFEST_ATTACHMENT, type PageLayout, type Ralph, RalphFixtures, type RalphOptions, type RalphProjectOptions, type RawGraphBundleIndex, type RawGraphManifest, type RawGraphScreenshot, type RawNode, type RecordNodeOptions, SCREEN_TAG_PREFIX, type TrackedElement, type UploadOptions, type UploadReceipt, type WebRalphConfig, createRawGraphBundle, expect, mergeTests, ralphProjects, test, uploadRawGraph };
239
+ export { type ConfigSnapshot, MANIFEST_ATTACHMENT, type PageLayout, type PreparedUpload, type Ralph, RalphFixtures, type RalphOptions, type RalphProjectOptions, type RalphReporterOptions, type RawGraph, type RawGraphBundleIndex, type RawGraphFile, type RawGraphManifest, type RawGraphScreenshot, type RawNode, type RawPage, type RecordNodeOptions, SCREEN_TAG_PREFIX, type TrackedElement, type UploadOptions, type UploadReceipt, type WebRalphConfig, createRawGraphBundle, expect, mergeTests, prepareArtifactUpload, ralphProjects, test, uploadRawGraph };
192
240
  //# sourceMappingURL=index.d.mts.map