@clipboard-health/playwright-toolkit

中文文档
1.5.15发布于 2026/11/05MITTypeScriptCommonJS近 30 天下载 1.2万

Shared anti-flake primitives for Clipboard Health Playwright suites.

原始使用文档
文档目录13 节
  1. Install
  2. API map
  3. Retry contract
  4. Classified retry
  5. Poll until pass
  6. JSON response lifetime
  7. Per-test traceparent fixture
  8. Admin tokens
  9. Deployed assets
  10. Mailpit
  11. Cognito OTP and login diagnostics
  12. Setup retry classification
  13. Migration checklist

@clipboard-health/playwright-toolkit

Shared anti-flake primitives for Clipboard Health Playwright suites.

The package owns retry policy, APM correlation, shared admin-token caching, deployed-asset checks, JSON response lifetime capture, Mailpit polling, Cognito login diagnostics, and setup retry classification. Consuming repositories keep only configuration and domain-specific matching.

Install

npm install --save-dev @clipboard-health/playwright-toolkit

@playwright/test is a peer dependency. The package supports Playwright 1.50 and newer.

API map

Local capabilityPackage replacement
retryWithBailrunWithRetry({ mode: { kind: "classified", ... } })
retryUntilPassOrTimeoutrunWithRetry({ mode: { kind: "poll", ... } })
Copy-pasted traceparent page fixturecreateTraceparentFixtures()
Admin token promise cache and file lockgenerateAdminAuthToken() or getOrCreateAdminAuthToken()
Deployed frontend/mobile asset loopsverifyDeployedAssets() and waitForDeployedAssets()
Deferred Playwright JSON response readswaitForParsedJsonResponse()
Mailpit search/fetch loopscreateMailpitClient(), fetchMagicLinkFromMailpit(), fetchEmailOtpCodeFromMailpit()
Cognito OTP redirect debuggingfillOtpAndWaitForCognitoRedirect()
Setup HTTP and identity retry checksclassifySetupRetry() and isRetryableHttpStatus()

Retry contract

runWithRetry is the only retry abstraction in this package. It has two modes because retries and polling answer different questions.

Classified retry

Use classified retry for an operation that should normally pass on the first attempt. The caller must provide isTransient. There is no default that retries arbitrary failures.

import { runWithRetry } from "@clipboard-health/playwright-toolkit";

const result = await runWithRetry({
  operationName: "create shift offer",
  operation: async () => await createShiftOffer(),
  mode: {
    kind: "classified",
    maxAttempts: 4,
    delayMs: 2000,
    isTransient: ({ error }) => isKnownCdcReadinessError(error),
  },
});

const shiftOffer = result.value;

A legal classified retry satisfies the flaky-critic B1 contract:

  • The operation is safe to repeat.
  • isTransient positively identifies a known transient condition.
  • Validation, permission, and other deterministic failures return false.
  • The retry has a fixed attempt budget.
  • Exhaustion throws RetryError with the attempt count, elapsed time, terminal reason, and last cause.

Do not use a broad status such as every 422 as the predicate. Match the specific readiness message or service condition that can resolve without changing the request.

Poll until pass

Use poll mode for an idempotent readiness probe where failure means "not ready yet."

const result = await runWithRetry({
  operationName: "wait for worker profile",
  operation: async () => await assertWorkerProfileReady(),
  mode: {
    kind: "poll",
    timeoutMs: 90_000,
    intervalsMs: [1000, 2000, 3000, 5000],
  },
});

Set mode.isTransient when the probe can also throw deterministic failures. Returning false stops immediately with reason: "non-transient".

Poll mode races each attempt against the remaining timeout budget and aborts the attempt's signal when the deadline expires. Pass that signal to network calls so timed-out work is cancelled:

operation: async ({ signal }) =>
  await fetch(readinessUrl, {
    signal,
  });

JSON response lifetime

Playwright response bodies can become unreadable after a document navigation. Use waitForParsedJsonResponse when a page action both waits for a JSON response and crosses a navigation boundary. The helper parses each candidate inside the waitForResponse predicate and returns only the parsed value, so callers cannot accidentally retain a lazy Response handle. Predicate-local parsing narrows the response-lifetime window but cannot eliminate it: Chromium can discard the underlying CDP resource while response.json() is still pending.

const workerResponsePromise = waitForParsedJsonResponse({
  page,
  timeoutMs: 30_000,
  isCandidate: ({ response }) =>
    response.ok() && new URL(response.url()).pathname === "/api/worker",
  parseCandidate: ({ body }) => workerResponseSchema.parse(body),
});

await page.reload({ waitUntil: "domcontentloaded" });

const workerResponse = await workerResponsePromise;

Return undefined from parseCandidate when the URL-level candidate is valid but its body is not the response the test needs. If a candidate body read fails with the exact Chromium Network.getResponseBody / No resource with given identifier found signature, the helper rejects only that candidate and continues inside the original finite waiter. It does not issue another request or navigation, add a retry or sleep, or widen the timeout. Invalid JSON, parsing and schema errors, near-match protocol errors, page or target closure, and cancellation propagate immediately. If the outer waiter times out after classified losses, the error preserves the original timeout as its cause and adds only bounded diagnostics with the loss count, method, status, and a redacted path template. Keep repository-specific URL, method, resource-type, and schema matching in the consumer.

Per-test traceparent fixture

Extend the repository's existing Playwright test object once:

import { test as base } from "@playwright/test";
import {
  createTraceparentFixtures,
  type TraceparentFixtures,
} from "@clipboard-health/playwright-toolkit";

export const test = base.extend<TraceparentFixtures>(createTraceparentFixtures());

The auto fixture creates one non-zero W3C traceparent, preserves project-level extraHTTPHeaders, installs the merged headers on the browser context before the test body runs, and adds a traceparent test annotation. Pass existing headers to installTraceparentForTest if a custom fixture installs the header manually.

Admin tokens

generateAdminAuthToken runs cbh auth gentoken user, retries only approved transient CLI signatures, redacts the admin email from errors, and caches the bearer token behind an atomic filesystem lock.

const tokenEntry = await generateAdminAuthToken({
  adminEmail: adminUser.email,
  apiEnvironmentName: "staging",
  cacheIdentity: {
    namespace: "cbh-admin-frontend",
    clientName: "admin-app",
    issuer: "clipboard-health-staging",
    tokenKind: "access",
  },
  clientName: "admin-app",
  cacheDurationMs: 10 * 60 * 1000,
  validationPolicy: "admin-session-v1",
  validateToken: async ({ authToken, signal }) => {
    const response = await fetch(`${adminApiUrl}/auth/session`, {
      headers: { Authorization: authToken },
      signal,
    });

    if (response.status === 401 || response.status === 403) {
      return false;
    }

    if (!response.ok) {
      throw new Error(`Admin token validation failed with HTTP ${response.status}`);
    }

    return true;
  },
});

const adminAuthToken = tokenEntry.authToken;

The cache key contains the environment, a SHA-256 digest of the email, and the optional explicit cache identity; it never contains the email itself. Give each repository a stable namespace, and distinguish credentials by token kind, client, audience, and issuer when those values differ. generateAdminAuthToken automatically distinguishes different clientName values even when cacheIdentity is omitted.

JWT cache freshness is bounded to the earlier of cacheDurationMs and the token's exp claim minus a 60-second safety skew. Opaque bearer tokens continue to use cacheDurationMs. Set jwtExpirationSafetySkewMs when a suite needs a different skew.

When validateToken is provided, the toolkit runs the read-only probe while holding the cache lock and records successful validation in the cache entry, so waiting Playwright workers share one probe. Give the probe an explicit validationPolicy and increment it whenever the validation contract becomes stricter or otherwise changes; a policy change forces revalidation. The toolkit aborts validation after 30 seconds by default, bounded below the lock's stale lease. Pass the provided signal to network requests, and set validationTimeoutMs when the endpoint needs a shorter deadline.

Return false only when the consumer rejects the credential, such as HTTP 401 or 403; throw for 5xx responses and other validation infrastructure failures. A rejected cached token is evicted and replaced once for all waiting workers and shards sharing the cache filesystem. A rejected generated token is not cached. The probe should verify the same audience and permission boundary the suite needs without mutating application state.

The cache and lock files use mode 0600. A process that acquires the lock re-reads the cache before generating, which prevents duplicate token mints across Playwright workers, shards, and local processes that share cacheDirectory. Separate CI hosts or containers with independent filesystems may still mint independently.

Use getOrCreateAdminAuthToken when the repository needs a different token command:

const tokenEntry = await getOrCreateAdminAuthToken({
  adminEmail,
  apiEnvironmentName,
  cacheIdentity: {
    namespace: "cbh-mobile-app",
    audience: "monolith-api",
    clientName: "mobile-app",
    tokenKind: "access",
  },
  cacheDurationMs: 10 * 60 * 1000,
  createToken: async () => await generateTokenWithRepositoryCli(),
});

After a consumer rejects a token, pass that credential to forceRefresh. Callers reporting the same rejected credential share one replacement, including callers that arrive after another worker has already refreshed the cache:

import { getOrCreateAdminAuthToken } from "@clipboard-health/playwright-toolkit";

const freshTokenEntry = await getOrCreateAdminAuthToken({
  ...tokenParams,
  forceRefresh: {
    rejectedAuthToken,
  },
});

Keep forceRefresh: true for deliberate unconditional rotation when no rejected credential is available.

Alternatively, invalidate a generated token explicitly with the API that applies the same default identity as generateAdminAuthToken:

import { invalidateGeneratedAdminAuthToken } from "@clipboard-health/playwright-toolkit";

await invalidateGeneratedAdminAuthToken({
  adminEmail,
  apiEnvironmentName,
  clientName: "admin-app",
});

Use invalidateAdminAuthToken for getOrCreateAdminAuthToken entries, passing the same cacheIdentity used to create the entry.

Only retry a request automatically when it is read-only or otherwise safe to repeat. The toolkit does not replay consumer requests because it cannot determine whether a failed mutation had side effects.

Use onCacheEvent for safe diagnostics. Events expose kind, cache-key and credential fingerprints, the optional audience, and mint/expiration/validation timestamps. Fingerprints distinguish successive credentials without exposing the token, email, or raw cache identity.

Deployed assets

Repository wrappers still discover assets and decide which files are runtime or fingerprinted. The package owns request concurrency, timeouts, cache busting, content-type checks, transient HTTP retries, attempt diagnostics, and stable-window polling.

const report = await waitForDeployedAssets({
  checks: localAssetManifest.map((asset) => ({
    path: asset.path,
    url: new URL(asset.path, deploymentBaseUrl).toString(),
    method: asset.isFingerprintNamedJavaScript ? "GET" : "HEAD",
    cacheMode: asset.isRuntimeAsset ? "cache-busted" : "normal",
    expectedContentTypes: [asset.contentType],
  })),
  timeoutMs: 10 * 60 * 1000,
  pollIntervalMs: 10_000,
  stableWindowMs: 30_000,
});

HTTP 408, 425, 429, and 5xx responses are transient for asset delivery. Content-type mismatches and failed custom validators are deterministic unless the validator returns isTransient: true.

Use validateResponse for repository-specific checks such as build-info.json commit matching. The verifier does not consume a successful response body before calling the wrapper, so the callback can read it directly.

Mailpit

Create a client from repository configuration, then use the typed pollers:

const mailpit = createMailpitClient({
  password: process.env.MAILPIT_PASSWORD ?? "",
});

const code = await fetchEmailOtpCodeFromMailpit({
  client: mailpit,
  email,
  sentAfter: codeRequestedAt,
  excludeCodes: [previousCode],
});

await page.getByLabel("Verification Code").fill(code.value);

The pollers search newest-first, tolerate incomplete dates in search results, fetch at most three candidates per probe, and retry Mailpit network errors, 404, 408, 429, and 5xx. They return both the extracted value and source message ID.

Timeout errors and successful results include polling diagnostics. These distinguish transient search errors from message-fetch errors and count skips of cached extraction misses. The first three extraction misses across the entire wait carry only a SHA-256 message-ID hash, content channel, combined Text/HTML character-count bucket, candidate age at fetch, and OTP shape. Shape classification observes the documented four-plus-four OTP format; it does not select a value or change the parser. other means the built-in OTP parser recognized a value that the caller’s extractor did not select. Samples contain no raw message fields or extracted secrets. The error retains this evidence for Playwright reports without a separate logging hook.

Misses remain cached by message ID, and the default wait remains 60 seconds. These diagnostics help classify a future failure; they do not establish why a historical message failed extraction.

Cognito OTP and login diagnostics

fillOtpAndWaitForCognitoRedirect monitors RespondToAuthChallenge requests for SMS_OTP and EMAIL_OTP while it waits for the expected redirect.

await fillOtpAndWaitForCognitoRedirect({
  page,
  testInfo,
  otp,
  expectedUrl: /\/dashboard/,
});

On failure, the error includes the sanitized Cognito request summary, response or request-failure detail, current URL, and visible page-text sample. When testInfo is provided, it attaches a redacted screenshot. sanitizeCognitoDiagnosticText and isCognitoOtpChallengeRequest are public for repository-specific login flows.

Setup retry classification

classifySetupRetry separates identity collisions from transient infrastructure failures:

const classification = classifySetupRetry({
  error,
  isIdentityCollision: ({ error: candidate }) => isWorkerCreationPhoneCollision(candidate),
});

The result follows the flaky-critic C1 contract:

ClassificationDecisionIdentity behavior
identity-collisionregenerate-identityGenerate a fresh phone, email, or ID before the next attempt.
transientretry-same-identityRepeat the same request and identity.
deterministicdo-not-retryFail immediately.

isRetryableHttpStatus returns true only for 408, 429, and 5xx. A repository can add a narrow isTransientError predicate for a known non-HTTP transient signature.

Migration checklist

  1. Replace the local helper import with the package export.
  2. Move repository-specific URLs, selectors, asset discovery, and error-message matching into a thin wrapper.
  3. Keep retry classification narrow. Record why the operation is safe to repeat.
  4. For identity collisions, generate the identity inside the retry operation so each collision attempt gets a fresh value.
  5. Delete the local helper and port its boundary tests to the wrapper.
  6. Run the consuming repository's Playwright unit tests and E2E setup checks.

版本与发布记录

@clipboard-health/playwright-toolkit 共发布 51 个版本,首次发布于 2026/07/17;过去 12 个月发布了 51 个版本。

版本发布日期距今
1.5.15latest2026/11/054 天前
1.5.142026/11/055 天前
1.5.132026/11/045 天前
1.5.122026/10/3110 天前
1.5.112026/10/2812 天前
1.5.102026/10/2813 天前

关于 @clipboard-health/playwright-toolkit 的常见问题

@clipboard-health/playwright-toolkit 是什么?

Shared anti-flake primitives for Clipboard Health Playwright suites.

如何安装 @clipboard-health/playwright-toolkit?

在项目目录运行 npm install @clipboard-health/playwright-toolkit,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@playwright/test(>=1.50.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@clipboard-health/playwright-toolkit 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@clipboard-health/playwright-toolkit 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@clipboard-health/playwright-toolkit 可以商用吗?

@clipboard-health/playwright-toolkit 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@clipboard-health/playwright-toolkit 的下载量有多少?

根据 npm 官方下载统计,@clipboard-health/playwright-toolkit 在 2026/10/10 – 2026/11/08 这 30 天内被下载 11,913 次,日均约 397 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@clipboard-health/playwright-toolkit 还在维护吗?

最新版本 1.5.15 发布于 2026/11/05(4 天前);至今共发布 51 个版本,其中过去 12 个月发布了 51 个;首次发布于 2026/07/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。