@tempo-ai/visual-review 0.0.138 → 0.0.139

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/github-actions.ts","../src/ci-context.ts","../../git-provider/bitbucket/pipelines.ts","../src/constants.ts","../src/http.ts","../src/oidc.ts","../src/workflow-status.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\n\nexport type GithubActionsEvent = {\n number?: number;\n pull_request?: {\n number?: number;\n body?: string | null;\n labels?: Array<{ name?: string | null }>;\n head?: { ref?: string; sha?: string };\n base?: { ref?: string; sha?: string };\n };\n};\n\n/** Read Actions' event payload when it is available, without making a local\n * invocation depend on it. */\nexport function readGithubActionsEvent(\n eventPath = process.env.GITHUB_EVENT_PATH,\n): GithubActionsEvent | null {\n if (!eventPath) return null;\n try {\n return JSON.parse(readFileSync(eventPath, \"utf8\")) as GithubActionsEvent;\n } catch {\n return null;\n }\n}\n\nexport function githubPullRequestContext(event = readGithubActionsEvent()) {\n const pullRequest = event?.pull_request;\n if (!pullRequest) return null;\n return {\n number: pullRequest.number ?? event?.number,\n headRef: pullRequest.head?.ref,\n headSha: pullRequest.head?.sha,\n baseRef: pullRequest.base?.ref,\n baseSha: pullRequest.base?.sha,\n };\n}\n\n/** These PR-owned declarations are handled by the portable `report` command,\n * keeping customer workflow files free of dogfood-specific bypass jobs. */\nexport function visualReviewPrDeclaration(\n event: GithubActionsEvent | null = readGithubActionsEvent(),\n): { bypass: boolean; noVisualChange: boolean } {\n const pullRequest = event?.pull_request;\n return {\n bypass:\n pullRequest?.labels?.some(\n (label) => label.name === \"visual-review:bypass\",\n ) ?? false,\n noVisualChange:\n pullRequest?.body?.includes(\"<!-- tempo-no-visual-change -->\") ?? false,\n };\n}\n","import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport path from \"node:path\";\n\nimport { readBitbucketPipelinesEnv } from \"@tempo-modules/git-provider/bitbucket/pipelines\";\n\nimport {\n type GithubActionsEvent,\n githubPullRequestContext,\n readGithubActionsEvent,\n visualReviewPrDeclaration,\n} from \"./github-actions\";\n\ntype Env = Record<string, string | undefined>;\n\n/**\n * Where a capture runs, as the CLI needs it — independent of which CI\n * produced it (TEM-2737). GitHub Actions fills it from the event payload and\n * GITHUB_* environment exactly as the CLI always has; Bitbucket Pipelines\n * fills it from BITBUCKET_*; anything else is a local, Convex-free run.\n */\nexport type CiContext = {\n provider: \"github\" | \"bitbucket\" | \"local\";\n /** A CI run that uploads by default (local capture is opt-in). */\n isCi: boolean;\n trigger: \"pr\" | \"main\" | \"manual\";\n prNumber?: number;\n headSha?: string;\n branch?: string;\n /** The PR's target branch — the merge-base anchor. */\n baseRef?: string;\n /** The PR's base SHA from the event payload (GitHub only), a fallback\n * when the checkout carries no remote branch to compute a merge-base. */\n baseSha?: string;\n /** `owner/repo` (GitHub) or `workspace/repo` (Bitbucket) as the\n * provider spells it. */\n repoFullName?: string;\n /** Tempo's repo key when the provider fixes it (Bitbucket). GitHub runs\n * derive it from `repoFullName` exactly as before. */\n repoKey?: string;\n /** PR-owned declarations visible from the environment. Bitbucket has no\n * labels and no description in its environment; Tempo reads the\n * description server-side instead (`declareNoVisualChangeIfPresent`). */\n declaration: { bypass: boolean; noVisualChange: boolean };\n};\n\nexport function detectCiContext(\n env: Env = process.env,\n readEvent: () => GithubActionsEvent | null = () =>\n env.GITHUB_EVENT_PATH ? readGithubActionsEvent(env.GITHUB_EVENT_PATH) : null,\n): CiContext {\n const bitbucket =\n env.GITHUB_ACTIONS === \"true\" ? null : readBitbucketPipelinesEnv(env);\n if (bitbucket) {\n const trigger = bitbucket.prId !== null ? \"pr\" : bitbucket.branch ? \"main\" : \"manual\";\n return {\n provider: \"bitbucket\",\n isCi: true,\n trigger,\n prNumber: bitbucket.prId ?? undefined,\n headSha: bitbucket.commit,\n branch: bitbucket.branch ?? undefined,\n baseRef: bitbucket.prDestinationBranch ?? undefined,\n repoFullName: bitbucket.repoFullName,\n repoKey: `bitbucket.org/${bitbucket.repoFullName}`.toLowerCase(),\n declaration: { bypass: false, noVisualChange: false },\n };\n }\n\n const event = readEvent();\n const pullRequest = githubPullRequestContext(event);\n const eventName = env.GITHUB_EVENT_NAME;\n return {\n provider: env.GITHUB_ACTIONS === \"true\" ? \"github\" : \"local\",\n isCi: env.GITHUB_ACTIONS === \"true\",\n trigger:\n eventName === \"pull_request\"\n ? \"pr\"\n : eventName === \"push\"\n ? \"main\"\n : \"manual\",\n prNumber: pullRequest?.number,\n headSha: pullRequest?.headSha ?? env.GITHUB_SHA,\n branch: pullRequest?.headRef ?? env.GITHUB_HEAD_REF ?? env.GITHUB_REF_NAME,\n baseRef: pullRequest?.baseRef ?? env.GITHUB_BASE_REF,\n baseSha: pullRequest?.baseSha,\n repoFullName: env.GITHUB_REPOSITORY,\n declaration: visualReviewPrDeclaration(event),\n };\n}\n\n// ── Bitbucket step state ───────────────────────────────────────────────────\n//\n// GitHub hands values between steps through GITHUB_ENV / GITHUB_OUTPUT.\n// Bitbucket has no equivalent inside a step, and claim → capture → report run\n// as separate commands of ONE step (its OIDC token cannot be re-minted), so\n// they share a small JSON file in the step container's temp dir instead.\n// Keyed by the step UUID so concurrent steps on a self-hosted runner never\n// read each other's state.\n\nexport type CiStepState = {\n captureOwnerToken?: string;\n reportKey?: string;\n reportUrl?: string;\n statusUrl?: string;\n /** Capture was skipped because the PR declared no visual change. */\n declared?: \"no-visual-change\";\n};\n\nexport function ciStatePath(env: Env = process.env): string {\n if (env.TEMPO_VISUAL_REVIEW_STATE_FILE) return env.TEMPO_VISUAL_REVIEW_STATE_FILE;\n const step = (env.BITBUCKET_STEP_UUID ?? \"local\").replace(/[^A-Za-z0-9-]/g, \"\");\n return path.join(tmpdir(), \"tempo-visual-review\", `step-${step || \"local\"}.json`);\n}\n\nexport function readCiState(env: Env = process.env): CiStepState {\n try {\n return JSON.parse(readFileSync(ciStatePath(env), \"utf8\")) as CiStepState;\n } catch {\n return {};\n }\n}\n\nexport function writeCiState(patch: CiStepState, env: Env = process.env): void {\n const file = ciStatePath(env);\n mkdirSync(path.dirname(file), { recursive: true });\n writeFileSync(file, JSON.stringify({ ...readCiState(env), ...patch }));\n}\n","/**\n * Bitbucket Pipelines identity: the step OIDC token and the build env.\n *\n * A step with `oidc: true` receives `BITBUCKET_STEP_OIDC_TOKEN`, an RS256 JWT\n * issued by `https://api.bitbucket.org/2.0/workspaces/<workspace>/pipelines-config/identity/oidc`\n * whose JWKS lives at `<issuer>/keys.json`. Its audience is the workspace ARI\n * (`ari:cloud:bitbucket::workspace/<workspaceUuid>`), and it carries\n * workspace/repository/pipeline/step UUIDs — but not the commit or PR. The\n * verifier therefore resolves the pipeline through the Bitbucket API before\n * trusting a commit/PR claim made by the CLI.\n */\n\nexport const BITBUCKET_OIDC_ISSUER_RE =\n /^https:\\/\\/api\\.bitbucket\\.org\\/2\\.0\\/workspaces\\/([A-Za-z0-9_.-]+)\\/pipelines-config\\/identity\\/oidc$/;\n\nexport function bitbucketOidcIssuer(workspace: string): string {\n return `https://api.bitbucket.org/2.0/workspaces/${workspace}/pipelines-config/identity/oidc`;\n}\n\nexport function bitbucketOidcJwksUrl(issuer: string): string {\n return `${issuer.replace(/\\/+$/, \"\")}/keys.json`;\n}\n\n/** `ari:cloud:bitbucket::workspace/{uuid}` with or without braces. */\nexport function bitbucketWorkspaceAudience(workspaceUuid: string): string {\n return `ari:cloud:bitbucket::workspace/${stripBraces(workspaceUuid)}`;\n}\n\nexport function stripBraces(uuid: string): string {\n return uuid.replace(/^\\{|\\}$/g, \"\").toLowerCase();\n}\n\nexport function sameBitbucketUuid(a: string | null | undefined, b: string | null | undefined): boolean {\n return !!a && !!b && stripBraces(a) === stripBraces(b);\n}\n\n/** Claims Tempo relies on from a verified Pipelines step token. */\nexport interface BitbucketPipelinesClaims {\n workspace: string;\n workspaceUuid: string;\n repositoryUuid: string;\n pipelineUuid: string;\n stepUuid: string;\n branchName: string | null;\n}\n\n/** Extract + validate the Pipelines claim set from a verified payload. */\nexport function readBitbucketPipelinesClaims(\n issuer: string,\n payload: Record<string, unknown>,\n): BitbucketPipelinesClaims | null {\n const match = BITBUCKET_OIDC_ISSUER_RE.exec(issuer);\n if (!match) return null;\n const s = (k: string) => (typeof payload[k] === \"string\" ? (payload[k] as string) : null);\n const workspaceUuid = s(\"workspaceUuid\");\n const repositoryUuid = s(\"repositoryUuid\");\n const pipelineUuid = s(\"pipelineUuid\");\n const stepUuid = s(\"stepUuid\");\n if (!workspaceUuid || !repositoryUuid || !pipelineUuid || !stepUuid) return null;\n return {\n workspace: match[1]!,\n workspaceUuid,\n repositoryUuid,\n pipelineUuid,\n stepUuid,\n branchName: s(\"branchName\"),\n };\n}\n\n/** The CI context the visual-review CLI reads inside Bitbucket Pipelines. */\nexport interface BitbucketPipelinesEnv {\n provider: \"bitbucket\";\n repoFullName: string;\n workspace: string;\n commit: string;\n branch: string | null;\n prId: number | null;\n prDestinationBranch: string | null;\n buildNumber: string | null;\n pipelineUuid: string | null;\n stepUuid: string | null;\n oidcToken: string | null;\n}\n\n/** Null outside Bitbucket Pipelines. */\nexport function readBitbucketPipelinesEnv(env: Record<string, string | undefined>): BitbucketPipelinesEnv | null {\n const repoFullName = env.BITBUCKET_REPO_FULL_NAME;\n const commit = env.BITBUCKET_COMMIT;\n if (!repoFullName || !commit) return null;\n const prId = env.BITBUCKET_PR_ID && /^\\d+$/.test(env.BITBUCKET_PR_ID) ? Number(env.BITBUCKET_PR_ID) : null;\n return {\n provider: \"bitbucket\",\n repoFullName,\n workspace: env.BITBUCKET_WORKSPACE ?? repoFullName.split(\"/\")[0]!,\n commit,\n branch: env.BITBUCKET_BRANCH ?? null,\n prId,\n prDestinationBranch: env.BITBUCKET_PR_DESTINATION_BRANCH ?? null,\n buildNumber: env.BITBUCKET_BUILD_NUMBER ?? null,\n pipelineUuid: env.BITBUCKET_PIPELINE_UUID ?? null,\n stepUuid: env.BITBUCKET_STEP_UUID ?? null,\n oidcToken: env.BITBUCKET_STEP_OIDC_TOKEN ?? null,\n };\n}\n\n/** Bitbucket build-status key Tempo publishes visual-review verdicts under. */\nexport const BITBUCKET_VISUAL_REVIEW_STATUS_KEY = \"visual-review\";\n\n/** Commit-status state mapping from Tempo's GitHub-shaped vocabulary. */\nexport function bitbucketStatusState(state: \"pending\" | \"success\" | \"failure\" | \"error\"): \"INPROGRESS\" | \"SUCCESSFUL\" | \"FAILED\" {\n if (state === \"pending\") return \"INPROGRESS\";\n if (state === \"success\") return \"SUCCESSFUL\";\n return \"FAILED\";\n}\n","/** The production Convex HTTP origin customers ingest visual-review runs to. */\nexport const DEFAULT_VISUAL_REVIEW_INGEST_URL =\n \"https://greedy-jackal-526.convex.site\";\n","const ATTEMPTS = 3;\nconst REQUEST_TIMEOUT_MS = 30_000;\nconst TRANSIENT_STATUS = new Set([408, 429, 500, 502, 503, 504]);\nconst TRANSIENT_CODE = new Set([\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"EAI_AGAIN\",\n \"ENOTFOUND\",\n \"UND_ERR_SOCKET\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_HEADERS_TIMEOUT\",\n \"UND_ERR_BODY_TIMEOUT\",\n]);\n\nfunction networkFailure(error: unknown): {\n detail: string;\n retryable: boolean;\n} {\n const codes: string[] = [];\n let timeout = false;\n let current = error;\n for (let depth = 0; depth < 5 && current instanceof Error; depth++) {\n timeout ||= current.name === \"TimeoutError\";\n const code = (current as Error & { code?: unknown }).code;\n // Never print arbitrary messages: fetch errors can contain credentials,\n // query strings, headers, or response bodies. Node error codes are enough.\n if (typeof code === \"string\" && /^[A-Z][A-Z0-9_]{1,50}$/.test(code))\n codes.push(code);\n current = (current as Error & { cause?: unknown }).cause;\n }\n return {\n detail: timeout ? \"request timed out\" : codes.join(\" / \") || \"fetch failed\",\n retryable:\n timeout ||\n codes.some((code) => TRANSIENT_CODE.has(code)) ||\n (codes.length === 0 &&\n error instanceof TypeError &&\n error.message === \"fetch failed\"),\n };\n}\n\n/** Only for replayable, idempotent API requests. Ingest hashes, manifests and\n * claim identities make retries safe even when the server committed a write\n * before its response was lost. Stream request bodies must not be passed here. */\nexport async function fetchWithRetry(\n url: string,\n init: RequestInit | (() => Promise<RequestInit>),\n operation: string,\n retryResponse: (response: Response) => Promise<boolean> = async () => true,\n): Promise<Response> {\n const endpoint = new URL(url);\n const label = `${operation} (${endpoint.origin}${endpoint.pathname})`;\n for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {\n // Auth has its own retry budget; do not multiply it by this request's\n // budget. Resolve again before each attempt so tokens can refresh.\n const request = typeof init === \"function\" ? await init() : init;\n const controller = new AbortController();\n const timeout = setTimeout(\n () =>\n controller.abort(new DOMException(\"Request timed out\", \"TimeoutError\")),\n REQUEST_TIMEOUT_MS,\n );\n let response: Response;\n let failure: string;\n let retryAfter = 0;\n try {\n response = await fetch(url, { ...request, signal: controller.signal });\n // These APIs return small JSON bodies. Consume under the same deadline\n // so a connection lost after headers is also retried and diagnosed.\n const body = await response.arrayBuffer();\n response = new Response(body.byteLength ? body : null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n if (\n !TRANSIENT_STATUS.has(response.status) ||\n !(await retryResponse(response.clone())) ||\n attempt === ATTEMPTS\n )\n return response;\n failure = `HTTP ${response.status}`;\n const retryHeader = response.headers.get(\"retry-after\");\n if (retryHeader) {\n const seconds = Number(retryHeader);\n const requestedDelay = Number.isFinite(seconds)\n ? seconds * 1_000\n : Date.parse(retryHeader) - Date.now();\n // Respect the server's retry window. If it exceeds our short recovery\n // budget, fail with its response instead of retrying too early.\n if (requestedDelay > 5_000) return response;\n if (Number.isFinite(requestedDelay))\n retryAfter = Math.max(0, requestedDelay);\n }\n } catch (error) {\n // Body reads may reject with AbortError rather than our timeout reason.\n const info = networkFailure(\n controller.signal.aborted ? controller.signal.reason : error,\n );\n failure = info.detail;\n if (!info.retryable || attempt === ATTEMPTS) {\n throw new Error(\n `${label} failed after ${attempt}/${ATTEMPTS} attempts: ${failure}`,\n );\n }\n } finally {\n clearTimeout(timeout);\n }\n const delay = Math.max(retryAfter, 250 * 4 ** (attempt - 1));\n console.warn(\n `[visual-review] ${label}: ${failure}; retrying after ${delay}ms (attempt ${attempt + 1}/${ATTEMPTS})`,\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n throw new Error(`${label}: retry budget exhausted`);\n}\n","import { readBitbucketPipelinesEnv } from \"@tempo-modules/git-provider/bitbucket/pipelines\";\n\nimport type { IngestCredentialProvider } from \"./ingest-client\";\nimport { fetchWithRetry } from \"./http\";\n\nconst OIDC_TOKEN_LIFETIME_MS = 5 * 60_000;\nconst OIDC_TOKEN_REFRESH_MARGIN_MS = 60_000;\nexport const VISUAL_REVIEW_OIDC_AUDIENCE = \"tempo-visual-review\";\n\n/** Refresh lazily: captures can outlive GitHub's five-minute id-tokens. */\nfunction githubOidcProvider(\n requestUrl: string,\n requestToken: string,\n): IngestCredentialProvider {\n let cached: { value: string; mintedAtMs: number } | null = null;\n let pending: ReturnType<IngestCredentialProvider> | null = null;\n const mint: IngestCredentialProvider = async () => {\n const separator = requestUrl.includes(\"?\") ? \"&\" : \"?\";\n const response = await fetchWithRetry(\n `${requestUrl}${separator}audience=${VISUAL_REVIEW_OIDC_AUDIENCE}`,\n { headers: { Authorization: `Bearer ${requestToken}` } },\n \"GitHub OIDC token mint/refresh\",\n );\n if (!response.ok) {\n throw new Error(\n `minting the GitHub OIDC token failed: ${response.status} ${(await response.text()).slice(0, 200)}`,\n );\n }\n const body = (await response.json()) as { value?: string };\n if (!body.value)\n throw new Error(\"GitHub OIDC token endpoint returned no value\");\n cached = { value: body.value, mintedAtMs: Date.now() };\n return { kind: \"oidc\", value: body.value };\n };\n return async () => {\n if (\n cached &&\n Date.now() - cached.mintedAtMs <\n OIDC_TOKEN_LIFETIME_MS - OIDC_TOKEN_REFRESH_MARGIN_MS\n ) {\n return { kind: \"oidc\", value: cached.value };\n }\n // Concurrent blob uploads share the refresh, including its failure.\n // Clear it afterwards so a later request can retry a failed mint.\n pending ??= mint().finally(() => {\n pending = null;\n });\n return pending;\n };\n}\n\n/** The `exp` claim of a JWT (seconds), or null when unreadable. Not a\n * verification — the server verifies; this only explains an expiry. */\nexport function jwtExpirySeconds(token: string): number | null {\n const payload = token.split(\".\")[1];\n if (!payload) return null;\n try {\n const claims = JSON.parse(\n Buffer.from(payload, \"base64url\").toString(\"utf8\"),\n ) as { exp?: unknown };\n return typeof claims.exp === \"number\" ? claims.exp : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Bitbucket Pipelines hands a step with `oidc: true` ONE signed token in\n * `BITBUCKET_STEP_OIDC_TOKEN`; unlike GitHub's there is no endpoint to mint a\n * fresh one. Its lifetime therefore bounds the whole claim → capture →\n * report sequence, which is why the template runs them in a single step.\n * The request also names the repo key the token is used for: the token\n * carries only workspace/repository UUIDs, which Tempo resolves through the\n * repository's grant and checks against this key.\n */\nfunction bitbucketOidcProvider(\n token: string,\n repoKey: string,\n log: (line: string) => void,\n): IngestCredentialProvider {\n let announced = false;\n return async () => {\n const exp = jwtExpirySeconds(token);\n const nowSeconds = Date.now() / 1000;\n if (exp !== null && exp <= nowSeconds) {\n throw new Error(\n `the Bitbucket step OIDC token expired at ${new Date(exp * 1000).toISOString()}; it cannot be re-minted, so claim, capture and report must finish inside one step within its lifetime — re-run the step`,\n );\n }\n if (!announced) {\n announced = true;\n if (exp !== null) {\n log(\n `Bitbucket step OIDC token valid for ${Math.round((exp - nowSeconds) / 60)} more minute(s); it cannot be re-minted within this step`,\n );\n }\n }\n return { kind: \"oidc\", value: token, repoKey };\n };\n}\n\n/** Prefer ambient Actions OIDC, then the Bitbucket step token, then an\n * explicit debug token. Preview capture may use the shared secret;\n * publishing real statuses may not. */\nexport function resolveIngestCredential(\n oidcOnly = false,\n env: Record<string, string | undefined> = process.env,\n): IngestCredentialProvider {\n const requestUrl = env.ACTIONS_ID_TOKEN_REQUEST_URL;\n const requestToken = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;\n if (requestUrl && requestToken)\n return githubOidcProvider(requestUrl, requestToken);\n const bitbucket =\n env.GITHUB_ACTIONS === \"true\" ? null : readBitbucketPipelinesEnv(env);\n const bitbucketRepoKey = bitbucket\n ? `bitbucket.org/${bitbucket.repoFullName}`.toLowerCase()\n : null;\n if (bitbucket?.oidcToken && bitbucketRepoKey) {\n return bitbucketOidcProvider(bitbucket.oidcToken, bitbucketRepoKey, (line) =>\n console.log(`[visual-review] ${line}`),\n );\n }\n const oidc = env.VISUAL_REVIEW_OIDC_TOKEN;\n if (oidc) {\n return async () =>\n bitbucketRepoKey\n ? { kind: \"oidc\", value: oidc, repoKey: bitbucketRepoKey }\n : { kind: \"oidc\", value: oidc };\n }\n const secret = env.VISUAL_REVIEW_UPLOAD_SECRET;\n if (!oidcOnly && secret)\n return async () => ({ kind: \"secret\", value: secret });\n if (bitbucket) {\n throw new Error(\n oidcOnly\n ? \"BITBUCKET_STEP_OIDC_TOKEN is missing: add `oidc: true` to the visual-review step in bitbucket-pipelines.yml\"\n : \"BITBUCKET_STEP_OIDC_TOKEN is missing: add `oidc: true` to the visual-review step in bitbucket-pipelines.yml (or set VISUAL_REVIEW_OIDC_TOKEN / VISUAL_REVIEW_UPLOAD_SECRET)\",\n );\n }\n throw new Error(\n oidcOnly\n ? \"GitHub Actions id-token: write or VISUAL_REVIEW_OIDC_TOKEN is required to publish through the Tempo GitHub App\"\n : \"GitHub Actions id-token permission, VISUAL_REVIEW_OIDC_TOKEN, or VISUAL_REVIEW_UPLOAD_SECRET is required for --upload\",\n );\n}\n","import { detectCiContext } from \"./ci-context\";\nimport { DEFAULT_VISUAL_REVIEW_INGEST_URL } from \"./constants\";\nimport type { IngestCredential } from \"./ingest-client\";\nimport { resolveIngestCredential } from \"./oidc\";\n\ntype WorkflowStatusKind =\n | \"bypass\"\n | \"no-visual-change\"\n | \"capture-started\"\n | \"workflow-failed\";\n\nfunction publisherName(): string {\n return detectCiContext().provider === \"bitbucket\"\n ? \"Tempo Bitbucket status\"\n : \"Tempo GitHub App status\";\n}\n\nasync function postWorkflowStatus(\n kind: WorkflowStatusKind,\n headSha: string,\n): Promise<Response> {\n const credential: IngestCredential = await resolveIngestCredential(true)();\n const origin = (\n process.env.VISUAL_REVIEW_INGEST_URL ?? DEFAULT_VISUAL_REVIEW_INGEST_URL\n ).replace(/\\/$/, \"\");\n return await fetch(`${origin}/visual-review/workflow-status`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-visual-review-oidc\": credential.value,\n ...(credential.kind === \"oidc\" && credential.repoKey\n ? { \"x-visual-review-repo-key\": credential.repoKey }\n : {}),\n },\n body: JSON.stringify({ headSha, kind }),\n });\n}\n\n/** Ask Tempo to publish the `visual-review` status (as its GitHub App on\n * GitHub, through the repository grant on Bitbucket). The server derives the\n * repo/PR from OIDC and verifies the live declaration; CI cannot choose\n * success. */\nexport async function publishWorkflowStatus(\n kind: WorkflowStatusKind,\n headSha: string,\n): Promise<void> {\n const response = await postWorkflowStatus(kind, headSha);\n const publisher = publisherName();\n if (!response.ok) {\n throw new Error(\n `${publisher} publishing failed (${response.status}): ${(await response.text()).slice(0, 500)}`,\n );\n }\n const result = (await response.json()) as {\n status?: string;\n reason?: string;\n };\n if (result.status !== \"posted\" && result.status !== \"skipped\") {\n throw new Error(`${publisher} returned an invalid status publishing response`);\n }\n console.log(\n `${publisher}: ${result.status}${result.reason ? ` (${result.reason})` : \"\"}`,\n );\n}\n\n/**\n * Bitbucket has no PR labels and puts no PR description in the step's\n * environment, so the CLI cannot see the `<!-- tempo-no-visual-change -->`\n * declaration itself. It asks Tempo instead: the server reads the LIVE\n * description through the repository grant and publishes success only when\n * the marker is there. `true` = declared (status published, skip capture);\n * `false` = not declared (capture as usual).\n */\nexport async function declareNoVisualChangeIfPresent(\n headSha: string,\n): Promise<boolean> {\n const response = await postWorkflowStatus(\"no-visual-change\", headSha);\n if (response.ok) {\n const result = (await response.json()) as { status?: string };\n return result.status === \"posted\";\n }\n const body = await response.text();\n if (response.status === 403 && body.includes(\"visual_review_declaration_missing\")) {\n return false;\n }\n throw new Error(\n `checking the no-visual-change declaration failed (${response.status}): ${body.slice(0, 500)}`,\n );\n}\n"],"mappings":";;;AAAA,SAAS,oBAAoB;AAetB,SAAS,uBACd,YAAY,QAAQ,IAAI,mBACG;AAC3B,MAAI,CAAC,UAAW,QAAO;AACvB,MAAI;AACF,WAAO,KAAK,MAAM,aAAa,WAAW,MAAM,CAAC;AAAA,EACnD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,yBAAyB,QAAQ,uBAAuB,GAAG;AACzE,QAAM,cAAc,OAAO;AAC3B,MAAI,CAAC,YAAa,QAAO;AACzB,SAAO;AAAA,IACL,QAAQ,YAAY,UAAU,OAAO;AAAA,IACrC,SAAS,YAAY,MAAM;AAAA,IAC3B,SAAS,YAAY,MAAM;AAAA,IAC3B,SAAS,YAAY,MAAM;AAAA,IAC3B,SAAS,YAAY,MAAM;AAAA,EAC7B;AACF;AAIO,SAAS,0BACd,QAAmC,uBAAuB,GACZ;AAC9C,QAAM,cAAc,OAAO;AAC3B,SAAO;AAAA,IACL,QACE,aAAa,QAAQ;AAAA,MACnB,CAAC,UAAU,MAAM,SAAS;AAAA,IAC5B,KAAK;AAAA,IACP,gBACE,aAAa,MAAM,SAAS,iCAAiC,KAAK;AAAA,EACtE;AACF;;;ACpDA,SAAS,WAAW,gBAAAA,eAAc,qBAAqB;AACvD,SAAS,cAAc;AACvB,OAAO,UAAU;;;ACmFV,SAAS,0BAA0B,KAAuE;AAC/G,QAAM,eAAe,IAAI;AACzB,QAAM,SAAS,IAAI;AACnB,MAAI,CAAC,gBAAgB,CAAC,OAAQ,QAAO;AACrC,QAAM,OAAO,IAAI,mBAAmB,QAAQ,KAAK,IAAI,eAAe,IAAI,OAAO,IAAI,eAAe,IAAI;AACtG,SAAO;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ire as __tempoCreateRequire } from 'node:module'; const require = __tempoCreateRequire(import.meta.url);
2
2
  import {
3
- publishWorkflowStatus
4
- } from "./chunk-PDNKZ3PI.js";
3
+ buildBitbucketCommentBody,
4
+ buildBitbucketNoVisualChangeComment,
5
+ upsertBitbucketStickyComment
6
+ } from "./chunk-TEVWNWZ6.js";
5
7
  import {
8
+ detectCiContext,
9
+ publishWorkflowStatus,
10
+ readCiState,
6
11
  visualReviewPrDeclaration
7
- } from "./chunk-CKMUCU6E.js";
12
+ } from "./chunk-H7MXR6QX.js";
8
13
 
9
14
  // src/report.ts
10
15
  import { execFileSync } from "child_process";
@@ -16,7 +21,7 @@ function publisherDeliveryFailure(status) {
16
21
  if (status.statusPublishing !== false) return null;
17
22
  return publishError;
18
23
  }
19
- function parseArgs(argv) {
24
+ function parseArgs(argv, options = { shaRequired: true }) {
20
25
  const args = {
21
26
  pollTimeoutS: 900,
22
27
  bypass: false,
@@ -39,7 +44,7 @@ function parseArgs(argv) {
39
44
  else if (flag === "--fallback-failure") args.fallbackFailure = true;
40
45
  else throw new Error(`unknown flag ${flag}`);
41
46
  }
42
- if (!args.sha) throw new Error("--sha is required");
47
+ if (!args.sha && options.shaRequired) throw new Error("--sha is required");
43
48
  return args;
44
49
  }
45
50
  function gh(...ghArgs) {
@@ -118,7 +123,95 @@ function buildNoVisualChangeComment() {
118
123
  function isPermanentError(error) {
119
124
  return error instanceof Error && "permanent" in error && error.permanent === true;
120
125
  }
126
+ async function pollRunStatus(statusUrl, pollTimeoutS, sha) {
127
+ const deadline = Date.now() + pollTimeoutS * 1e3;
128
+ let status;
129
+ for (; ; ) {
130
+ try {
131
+ const response = await fetch(statusUrl);
132
+ if (response.status === 404) {
133
+ const error = new Error("status poll 404 \u2014 wrong report key");
134
+ Object.assign(error, { permanent: true });
135
+ throw error;
136
+ }
137
+ if (!response.ok)
138
+ throw new Error(`status poll failed: ${response.status}`);
139
+ status = await response.json();
140
+ } catch (error) {
141
+ if (isPermanentError(error)) throw error;
142
+ console.warn(
143
+ `transient status poll failure, retrying: ${error instanceof Error ? error.message : error}`
144
+ );
145
+ }
146
+ if (status && (status.state === "complete" || status.state === "error")) {
147
+ return status;
148
+ }
149
+ if (Date.now() > deadline) {
150
+ await publishWorkflowStatus("workflow-failed", sha);
151
+ throw new Error("timed out waiting for the run to complete");
152
+ }
153
+ await new Promise((resolve) => setTimeout(resolve, 5e3));
154
+ }
155
+ }
156
+ async function bitbucketMain(args, ci) {
157
+ const sha = args.sha ?? ci.headSha;
158
+ const pr = args.pr ?? ci.prNumber;
159
+ const repoFullName = ci.repoFullName;
160
+ if (args.bypass) {
161
+ throw new Error(
162
+ "Bitbucket pull requests have no labels, so the visual-review bypass declaration is unavailable. Use the no-visual-change declaration in the PR description when it applies, or approve the changes in the report."
163
+ );
164
+ }
165
+ if (!pr || !sha) {
166
+ console.log("not a pull-request pipeline \u2014 nothing to report");
167
+ return 0;
168
+ }
169
+ if (args.noVisualChange) {
170
+ await publishWorkflowStatus("no-visual-change", sha);
171
+ await upsertBitbucketStickyComment({
172
+ repoFullName,
173
+ prNumber: pr,
174
+ body: buildBitbucketNoVisualChangeComment()
175
+ });
176
+ return 0;
177
+ }
178
+ if (args.fallbackFailure) {
179
+ await publishWorkflowStatus("workflow-failed", sha);
180
+ return 0;
181
+ }
182
+ const state = readCiState();
183
+ if (!args.statusUrl && state.declared === "no-visual-change") {
184
+ console.log("no-visual-change declaration present \u2014 capture was skipped");
185
+ return 0;
186
+ }
187
+ const statusUrl = args.statusUrl ?? state.statusUrl;
188
+ if (!statusUrl) {
189
+ throw new Error(
190
+ "no status URL: capture did not finalize a run in this step (pass --status-url to report on a known run)"
191
+ );
192
+ }
193
+ const status = await pollRunStatus(statusUrl, args.pollTimeoutS, sha);
194
+ const publishFailure = publisherDeliveryFailure(status);
195
+ if (!status.publisherConfigured || publishFailure !== null) {
196
+ throw new Error(
197
+ `Tempo could not publish the visual-review build status to Bitbucket: ${publishFailure?.error ?? "publisher unconfigured"}. Authorize the repository for visual-review statuses in Tempo (visual_review_doctor \u2192 bitbucket_grant) and retry.`
198
+ );
199
+ }
200
+ console.log("visual-review build status is owned by Tempo");
201
+ if (await upsertBitbucketStickyComment({
202
+ repoFullName,
203
+ prNumber: pr,
204
+ body: buildBitbucketCommentBody(status)
205
+ })) {
206
+ console.log(`sticky comment upserted on #${pr}`);
207
+ }
208
+ return 0;
209
+ }
121
210
  async function main(argv = process.argv.slice(2)) {
211
+ const ci = detectCiContext();
212
+ if (ci.provider === "bitbucket") {
213
+ return await bitbucketMain(parseArgs(argv, { shaRequired: false }), ci);
214
+ }
122
215
  const args = parseArgs(argv);
123
216
  const repo = process.env.GITHUB_REPOSITORY;
124
217
  if (!repo) throw new Error("GITHUB_REPOSITORY is not set");
@@ -145,34 +238,7 @@ async function main(argv = process.argv.slice(2)) {
145
238
  }
146
239
  const statusUrl = args.statusUrl;
147
240
  if (!statusUrl) throw new Error("--status-url is required");
148
- const deadline = Date.now() + args.pollTimeoutS * 1e3;
149
- let status;
150
- for (; ; ) {
151
- try {
152
- const response = await fetch(statusUrl);
153
- if (response.status === 404) {
154
- const error = new Error("status poll 404 \u2014 wrong report key");
155
- Object.assign(error, { permanent: true });
156
- throw error;
157
- }
158
- if (!response.ok)
159
- throw new Error(`status poll failed: ${response.status}`);
160
- status = await response.json();
161
- } catch (error) {
162
- if (isPermanentError(error)) throw error;
163
- console.warn(
164
- `transient status poll failure, retrying: ${error instanceof Error ? error.message : error}`
165
- );
166
- }
167
- if (status && (status.state === "complete" || status.state === "error")) {
168
- break;
169
- }
170
- if (Date.now() > deadline) {
171
- await publishWorkflowStatus("workflow-failed", sha);
172
- throw new Error("timed out waiting for the run to complete");
173
- }
174
- await new Promise((resolve) => setTimeout(resolve, 5e3));
175
- }
241
+ const status = await pollRunStatus(statusUrl, args.pollTimeoutS, sha);
176
242
  const publishFailure = publisherDeliveryFailure(status);
177
243
  if (!status.publisherConfigured || publishFailure !== null) {
178
244
  throw new Error(
@@ -191,4 +257,4 @@ export {
191
257
  publisherDeliveryFailure,
192
258
  main
193
259
  };
194
- //# sourceMappingURL=chunk-IID6AAUD.js.map
260
+ //# sourceMappingURL=chunk-PI6TS733.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/report.ts"],"sourcesContent":["import { execFileSync } from \"node:child_process\";\n\nimport {\n buildBitbucketCommentBody,\n buildBitbucketNoVisualChangeComment,\n upsertBitbucketStickyComment,\n} from \"./bitbucket-report\";\nimport { type CiContext, detectCiContext, readCiState } from \"./ci-context\";\nimport { visualReviewPrDeclaration } from \"./github-actions\";\nimport { publishWorkflowStatus } from \"./workflow-status\";\n\nconst STICKY_MARKER = \"<!-- tempo-visual-review -->\";\n\ntype ReportArgs = {\n pollTimeoutS: number;\n bypass: boolean;\n noVisualChange: boolean;\n fallbackFailure: boolean;\n statusUrl?: string;\n pr?: number;\n sha?: string;\n};\n\ntype Gate = {\n satisfied?: boolean;\n required?: number;\n approvalsNeeded?: number;\n rejected?: number;\n blockingErrors?: number;\n};\n\n/**\n * Shape of the `/visual-review/status` poll. Convex serialises absent\n * optional fields as `null`, not `undefined` — every optional here must be\n * read null-safely.\n */\nexport type ReportStatus = {\n state?: \"complete\" | \"error\" | string;\n reportUrl?: string;\n trackedTotal?: number;\n counts?: Record<string, number | undefined>;\n gate?: Gate;\n topChanged?: Array<{\n name?: string;\n storyboardId: string;\n diffRatio?: number | null;\n verdict: string;\n error?: string;\n baselineHash?: string;\n candidateHash?: string;\n }>;\n blobUrlTemplate?: string;\n approximateBase?: boolean;\n freshEpoch?: boolean;\n publisherConfigured?: boolean;\n lastPublishError?: { revision: number; error: string } | null;\n lastPublish?: { revision: number } | null;\n statusPublishing?: boolean | null;\n};\n\n/**\n * `publisherConfigured` only means the GitHub App env is set GLOBALLY — it\n * does NOT mean the app can post on THIS repo (it may not be installed\n * there, or lack the permission). When the publisher has a TERMINAL\n * outstanding failure for the current revision, the report job fails\n * visibly without changing publisher identity. Terminal means the error is\n * current (revision-compare, mirroring the portal's \"delivery failing\"\n * banner) AND no publish worker holds the singleflight claim\n * (`statusPublishing === false`). A transient failure mid-retry-ladder keeps\n * the claim, so the report lets the publisher's retry finish.\n *\n * Returns the terminal failure, or `null` while publishing is healthy or retrying.\n */\nexport function publisherDeliveryFailure(\n status: ReportStatus,\n): { revision: number; error: string } | null {\n const publishError = status.lastPublishError;\n // A healthy run reports `lastPublishError: null` (0.0.1 compared against\n // `undefined` only and crashed on `.revision`).\n if (publishError == null) return null;\n if (publishError.revision < (status.lastPublish?.revision ?? 0)) return null;\n if (status.statusPublishing !== false) return null;\n return publishError;\n}\n\nfunction parseArgs(argv: string[], options: { shaRequired: boolean } = { shaRequired: true }): ReportArgs {\n const args: ReportArgs = {\n pollTimeoutS: 900,\n bypass: false,\n noVisualChange: false,\n fallbackFailure: false,\n };\n for (let index = 0; index < argv.length; index += 1) {\n const flag = argv[index];\n const next = () => {\n const value = argv[++index];\n if (value === undefined) throw new Error(`${flag} needs a value`);\n return value;\n };\n if (flag === \"--status-url\") args.statusUrl = next();\n else if (flag === \"--pr\") args.pr = Number(next());\n else if (flag === \"--sha\") args.sha = next();\n else if (flag === \"--poll-timeout-s\") args.pollTimeoutS = Number(next());\n else if (flag === \"--bypass\") args.bypass = true;\n else if (flag === \"--no-visual-change\") args.noVisualChange = true;\n else if (flag === \"--fallback-failure\") args.fallbackFailure = true;\n else throw new Error(`unknown flag ${flag}`);\n }\n if (!args.sha && options.shaRequired) throw new Error(\"--sha is required\");\n return args;\n}\n\nfunction gh(...ghArgs: string[]): string {\n return execFileSync(\"gh\", ghArgs, { encoding: \"utf-8\", windowsHide: true });\n}\n\nfunction upsertStickyComment(repo: string, pr: number, body: string): void {\n const comments = (\n JSON.parse(\n gh(\"api\", `repos/${repo}/issues/${pr}/comments`, \"--paginate\", \"--slurp\"),\n ) as Array<Array<{ id: number; body?: string }>>\n ).flat();\n const existing = comments.find(\n (comment) =>\n typeof comment.body === \"string\" && comment.body.includes(STICKY_MARKER),\n );\n if (existing) {\n gh(\n \"api\",\n \"--method\",\n \"PATCH\",\n `repos/${repo}/issues/comments/${existing.id}`,\n \"-f\",\n `body=${body}`,\n );\n } else {\n gh(\"api\", `repos/${repo}/issues/${pr}/comments`, \"-f\", `body=${body}`);\n }\n}\n\nfunction describeGate(\n gate: Gate,\n state: ReportStatus[\"state\"],\n): { state: \"success\" | \"failure\" | \"pending\"; description: string } {\n if (state === \"error\") {\n return {\n state: \"failure\",\n description: \"visual review run failed — see report\",\n };\n }\n if (state !== \"complete\") {\n return {\n state: \"pending\",\n description: \"capturing & comparing storyboards…\",\n };\n }\n if (gate.satisfied) {\n return {\n state: \"success\",\n description:\n gate.required === 0\n ? \"no visual changes\"\n : `${gate.required} visual change${gate.required === 1 ? \"\" : \"s\"} approved`,\n };\n }\n const parts: string[] = [];\n if ((gate.approvalsNeeded ?? 0) > 0) {\n parts.push(`${gate.approvalsNeeded} of ${gate.required} need approval`);\n }\n if ((gate.rejected ?? 0) > 0) parts.push(`${gate.rejected} rejected`);\n if ((gate.blockingErrors ?? 0) > 0) {\n parts.push(\n `${gate.blockingErrors} render error${gate.blockingErrors === 1 ? \"\" : \"s\"}`,\n );\n }\n return {\n state: \"failure\",\n description: `visual review: ${parts.join(\", \")} — see report`,\n };\n}\n\nfunction buildCommentBody(status: ReportStatus): string {\n const counts = status.counts ?? {};\n const gateLine = status.gate?.satisfied\n ? \"✅ **Check passing** — every visual change is approved.\"\n : `🔴 **Check failing** — ${status.gate?.approvalsNeeded ?? \"?\"} of ${status.gate?.required ?? \"?\"} storyboards need approval${status.gate?.blockingErrors ? `, ${status.gate.blockingErrors} render error(s)` : \"\"}${status.gate?.rejected ? `, ${status.gate.rejected} rejected` : \"\"}. Approving in the report flips the check instantly — no CI re-run.`;\n const summary = `| tracked | changed | new | removed | render errors | unchanged |\n| --- | --- | --- | --- | --- | --- |\n| ${status.trackedTotal ?? 0} | ${counts.changed ?? 0} | ${counts.added ?? 0} | ${counts.removed ?? 0} | ${counts.errors ?? 0} | ${counts.unchanged ?? 0} |`;\n\n const thumbs = (status.topChanged ?? [])\n .slice(0, 6)\n .map((board) => {\n const title = board.name ?? board.storyboardId;\n const meta =\n board.diffRatio !== undefined && board.diffRatio !== null\n ? ` · ${(board.diffRatio * 100).toFixed(2)}%`\n : \"\";\n if (board.verdict === \"render-error\") {\n return `**${title}** — render error${board.error ? `: \\`${board.error.slice(0, 120)}\\`` : \"\"}`;\n }\n const cell = (hash: string | undefined, label: string) =>\n hash && status.blobUrlTemplate\n ? `<img src=\"${status.blobUrlTemplate}${hash}\" alt=\"${label}\" width=\"360\" />`\n : \"—\";\n return `<details><summary><b>${title}</b> — ${board.verdict}${meta}</summary>\n\n| baseline | candidate |\n| --- | --- |\n| ${cell(board.baselineHash, \"baseline\")} | ${cell(board.candidateHash, \"candidate\")} |\n\n</details>`;\n })\n .join(\"\\n\");\n\n const notes: string[] = [];\n if (status.approximateBase) {\n notes.push(\n \"⚠ exact merge-base had no visual run — compared against the nearest captured ancestor.\",\n );\n }\n if (status.freshEpoch) {\n notes.push(\n \"ℹ fresh baseline epoch (capture environment changed) — everything reports as new.\",\n );\n }\n\n return `${STICKY_MARKER}\n## 👁 Visual review\n\n${gateLine}\n\n${summary}\n\n${notes.length > 0 ? `${notes.join(\"\\n\")}\\n` : \"\"}${thumbs}\n\n📷 **[Open the visual review report](${status.reportUrl})** — side-by-side, onion-skin and diff views; approve, reject, and comment there.`;\n}\n\nfunction buildNoVisualChangeComment(): string {\n return `${STICKY_MARKER}\n## 👁 Visual review\n\n✅ **Not applicable — no storyboard changes expected.** Storyboard capture was skipped from the PR declaration.`;\n}\n\nfunction isPermanentError(error: unknown): boolean {\n return (\n error instanceof Error && \"permanent\" in error && error.permanent === true\n );\n}\n\n/** Poll `/visual-review/status` until the run is compared. A deadline\n * publishes the fallback failure (only over pending/absent) and throws. */\nasync function pollRunStatus(\n statusUrl: string,\n pollTimeoutS: number,\n sha: string,\n): Promise<ReportStatus> {\n const deadline = Date.now() + pollTimeoutS * 1_000;\n let status: ReportStatus | undefined;\n for (;;) {\n try {\n const response = await fetch(statusUrl);\n if (response.status === 404) {\n const error = new Error(\"status poll 404 — wrong report key\");\n Object.assign(error, { permanent: true });\n throw error;\n }\n if (!response.ok)\n throw new Error(`status poll failed: ${response.status}`);\n status = (await response.json()) as ReportStatus;\n } catch (error) {\n if (isPermanentError(error)) throw error;\n console.warn(\n `transient status poll failure, retrying: ${error instanceof Error ? error.message : error}`,\n );\n }\n if (status && (status.state === \"complete\" || status.state === \"error\")) {\n return status;\n }\n if (Date.now() > deadline) {\n await publishWorkflowStatus(\"workflow-failed\", sha);\n throw new Error(\"timed out waiting for the run to complete\");\n }\n await new Promise((resolve) => setTimeout(resolve, 5_000));\n }\n}\n\n/**\n * Bitbucket Pipelines (TEM-2737). Runs inside the same step as capture: the\n * status URL comes from the step state capture wrote, the head SHA and PR\n * from BITBUCKET_*. Tempo owns the `visual-review` build status (posted\n * through the repository grant); this only waits for the verdict and keeps\n * the sticky comment current. Branch pipelines have no PR — nothing to do.\n */\nasync function bitbucketMain(args: ReportArgs, ci: CiContext): Promise<number> {\n const sha = args.sha ?? ci.headSha;\n const pr = args.pr ?? ci.prNumber;\n const repoFullName = ci.repoFullName!;\n if (args.bypass) {\n throw new Error(\n \"Bitbucket pull requests have no labels, so the visual-review bypass declaration is unavailable. Use the no-visual-change declaration in the PR description when it applies, or approve the changes in the report.\",\n );\n }\n if (!pr || !sha) {\n console.log(\"not a pull-request pipeline — nothing to report\");\n return 0;\n }\n if (args.noVisualChange) {\n await publishWorkflowStatus(\"no-visual-change\", sha);\n await upsertBitbucketStickyComment({\n repoFullName,\n prNumber: pr,\n body: buildBitbucketNoVisualChangeComment(),\n });\n return 0;\n }\n if (args.fallbackFailure) {\n await publishWorkflowStatus(\"workflow-failed\", sha);\n return 0;\n }\n const state = readCiState();\n if (!args.statusUrl && state.declared === \"no-visual-change\") {\n console.log(\"no-visual-change declaration present — capture was skipped\");\n return 0;\n }\n const statusUrl = args.statusUrl ?? state.statusUrl;\n if (!statusUrl) {\n throw new Error(\n \"no status URL: capture did not finalize a run in this step (pass --status-url to report on a known run)\",\n );\n }\n const status = await pollRunStatus(statusUrl, args.pollTimeoutS, sha);\n const publishFailure = publisherDeliveryFailure(status);\n if (!status.publisherConfigured || publishFailure !== null) {\n throw new Error(\n `Tempo could not publish the visual-review build status to Bitbucket: ${publishFailure?.error ?? \"publisher unconfigured\"}. Authorize the repository for visual-review statuses in Tempo (visual_review_doctor → bitbucket_grant) and retry.`,\n );\n }\n console.log(\"visual-review build status is owned by Tempo\");\n if (\n await upsertBitbucketStickyComment({\n repoFullName,\n prNumber: pr,\n body: buildBitbucketCommentBody(status),\n })\n ) {\n console.log(`sticky comment upserted on #${pr}`);\n }\n return 0;\n}\n\nexport async function main(argv = process.argv.slice(2)): Promise<number> {\n const ci = detectCiContext();\n if (ci.provider === \"bitbucket\") {\n return await bitbucketMain(parseArgs(argv, { shaRequired: false }), ci);\n }\n const args = parseArgs(argv);\n const repo = process.env.GITHUB_REPOSITORY;\n if (!repo) throw new Error(\"GITHUB_REPOSITORY is not set\");\n const sha = args.sha;\n if (!sha) throw new Error(\"--sha is required\");\n const declaration = visualReviewPrDeclaration();\n\n if (args.bypass || declaration.bypass) {\n await publishWorkflowStatus(\"bypass\", sha);\n console.log(\"bypass label present — posted success and skipped the report\");\n return 0;\n }\n\n if (args.noVisualChange || declaration.noVisualChange) {\n await publishWorkflowStatus(\"no-visual-change\", sha);\n if (args.pr)\n upsertStickyComment(repo, args.pr, buildNoVisualChangeComment());\n console.log(\n \"no-visual-change declaration present — posted success and skipped capture\",\n );\n return 0;\n }\n\n if (args.fallbackFailure) {\n await publishWorkflowStatus(\"workflow-failed\", sha);\n return 0;\n }\n\n const statusUrl = args.statusUrl;\n if (!statusUrl) throw new Error(\"--status-url is required\");\n const status = await pollRunStatus(statusUrl, args.pollTimeoutS, sha);\n\n const publishFailure = publisherDeliveryFailure(status);\n if (!status.publisherConfigured || publishFailure !== null) {\n throw new Error(\n `Tempo GitHub App could not publish visual-review: ${publishFailure?.error ?? \"publisher unconfigured\"}. Restore the app installation/configuration and retry; Actions cannot substitute for the required app.`,\n );\n }\n console.log(\"visual-review verdict is owned by the Tempo GitHub App\");\n\n if (args.pr) {\n upsertStickyComment(repo, args.pr, buildCommentBody(status));\n console.log(`sticky comment upserted on #${args.pr}`);\n }\n return 0;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAW7B,IAAM,gBAAgB;AA8Df,SAAS,yBACd,QAC4C;AAC5C,QAAM,eAAe,OAAO;AAG5B,MAAI,gBAAgB,KAAM,QAAO;AACjC,MAAI,aAAa,YAAY,OAAO,aAAa,YAAY,GAAI,QAAO;AACxE,MAAI,OAAO,qBAAqB,MAAO,QAAO;AAC9C,SAAO;AACT;AAEA,SAAS,UAAU,MAAgB,UAAoC,EAAE,aAAa,KAAK,GAAe;AACxG,QAAM,OAAmB;AAAA,IACvB,cAAc;AAAA,IACd,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,iBAAiB;AAAA,EACnB;AACA,WAAS,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GAAG;AACnD,UAAM,OAAO,KAAK,KAAK;AACvB,UAAM,OAAO,MAAM;AACjB,YAAM,QAAQ,KAAK,EAAE,KAAK;AAC1B,UAAI,UAAU,OAAW,OAAM,IAAI,MAAM,GAAG,IAAI,gBAAgB;AAChE,aAAO;AAAA,IACT;AACA,QAAI,SAAS,eAAgB,MAAK,YAAY,KAAK;AAAA,aAC1C,SAAS,OAAQ,MAAK,KAAK,OAAO,KAAK,CAAC;AAAA,aACxC,SAAS,QAAS,MAAK,MAAM,KAAK;AAAA,aAClC,SAAS,mBAAoB,MAAK,eAAe,OAAO,KAAK,CAAC;AAAA,aAC9D,SAAS,WAAY,MAAK,SAAS;AAAA,aACnC,SAAS,qBAAsB,MAAK,iBAAiB;AAAA,aACrD,SAAS,qBAAsB,MAAK,kBAAkB;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