Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@ const repository = await client.resolveSourceRepository({

A provider object ID can replace `full_name` on the same host. For later requests, use the returned Proofline `repository_id`, which also resolves on its own within the organization.

## Pull request merge gates

`readReviewMergeGate` reads and validates the server-recorded `PullRequestMergeGate` projection from a `Review` (`getReview`) or `ReviewOutcome` (`waitForReview`).

```typescript
import { ProoflineClient, readReviewMergeGate } from "@proofline/sdk";

const outcome = await client.waitForReview(organizationId, reviewId);
const gate = readReviewMergeGate(outcome, { headSha: expectedHeadSha });
if (gate.status === "BLOCKED") {
console.error(`Merge gate blocked (${gate.findingCount} blocking findings).`);
}
```

When `review` is unavailable (`TIMED_OUT` before a response) it returns `status: "UNAVAILABLE"`, and when the repository has not opted into merge gates (`merge_gate: null`) it returns `status: "NOT_CONFIGURED"`. Passing `headSha` pins the projection to an expected 40-character commit SHA and yields `status: "HEAD_MISMATCH"` with `decision: null` if the recorded gate belongs to another head. Malformed or contradictory gate fields raise `ProoflineError` with `urn:proofline:sdk:invalid-response`.

## Errors and refusals

A refused request throws `ProoflineError` with the server problem's `status`, `type`, `title` and `detail`. When a review request creates nothing, the error also carries `refusal`, whose `reason` names the setting to change, such as `NO_LINKED_ENVIRONMENT` or `ENVIRONMENT_NOT_READY`, and `repositoryName`. A refusal that does not match the public contract keeps its status, `title` and `detail` with the type `urn:proofline:sdk:invalid-response` and no `refusal`. Any other status, such as the 402 a review request answers when credits cannot pay, is a plain problem with no `refusal`. The token is redacted from every text field, and `String(error)`, `inspect(error)` and `JSON.stringify(error)` show only the status.
Expand Down
11 changes: 11 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,17 @@ import { KnowledgeClient } from "./knowledge.js";

export type { KnowledgeResult, RepositoryKnowledge } from "./knowledge.js";

export {
type MergeGateBypass,
type MergeGateDecision,
type MergeGateStatus,
type PullRequestMergeGate,
type ReadReviewMergeGateOptions,
type ReviewMergeGate,
type ReviewMergeGateStatus,
readReviewMergeGate,
} from "./merge-gate.js";

import {
decodeExport,
type ExportPage,
Expand Down
268 changes: 268 additions & 0 deletions src/merge-gate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,268 @@
import type { Review, ReviewOutcome } from "./index.js";
import type { components } from "./schema.js";
import { ProoflineError } from "./transport.js";

export type PullRequestMergeGate =
components["schemas"]["PullRequestMergeGate"];
export type MergeGateStatus = components["schemas"]["GateStatus"];
export type MergeGateDecision = components["schemas"]["Outcome"];

export type ReviewMergeGateStatus =
| MergeGateStatus
| "NOT_CONFIGURED"
| "UNAVAILABLE"
| "HEAD_MISMATCH";

export interface MergeGateBypass {
bypassedAt: string | null;
mergeCommitSha: string | null;
mergedPullRequestNumber: number | null;
mergedByGithubUserId: number | null;
mergedByLogin: string | null;
mergedByName: string | null;
}

export interface ReadReviewMergeGateOptions {
/** Expected full 40-character commit SHA; mismatches yield `HEAD_MISMATCH`. */
headSha?: string;
}

export interface ReviewMergeGate {
status: ReviewMergeGateStatus;
decision: MergeGateDecision | null;
gateId: string | null;
reviewId: string | null;
pullRequestNumber: number | null;
headSha: string | null;
policyVersion: string | null;
blockingSeverity: string | null;
severityApplied: string | null;
findingCount: number | null;
assessmentCount: number | null;
coverageDigest: string | null;
reasonCode: string | null;
decidedAt: string | null;
bypass: MergeGateBypass | null;
raw: PullRequestMergeGate | null;
}

const GATE_STATUSES = new Set<MergeGateStatus>([
"REQUESTED",
"EVALUATING",
"ALLOWED",
"BLOCKED",
"BYPASSED",
"SUPERSEDED",
]);

function invalidGate(detail: string): ProoflineError {
return new ProoflineError(0, "urn:proofline:sdk:invalid-response", detail);
}

function isObject(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}

function optionalString(
record: Record<string, unknown>,
field: string,
): string | null {
const value = record[field];
if (value === undefined || value === null) return null;
if (typeof value !== "string") {
throw invalidGate(`merge_gate.${field} must be a string or null`);
}
return value;
}

function optionalInteger(
record: Record<string, unknown>,
field: string,
nonnegative = false,
): number | null {
const value = record[field];
if (value === undefined || value === null) return null;
if (
typeof value !== "number" ||
!Number.isSafeInteger(value) ||
(nonnegative && value < 0)
) {
throw invalidGate(
`merge_gate.${field} must be a${nonnegative ? " nonnegative" : ""} integer or null`,
);
}
return value;
}

function requiredString(
record: Record<string, unknown>,
field: string,
): string {
const value = record[field];
if (typeof value !== "string" || value.length === 0) {
throw invalidGate(`merge_gate.${field} must be a nonempty string`);
}
return value;
}

function emptyGate(status: "NOT_CONFIGURED" | "UNAVAILABLE"): ReviewMergeGate {
return {
status,
decision: null,
gateId: null,
reviewId: null,
pullRequestNumber: null,
headSha: null,
policyVersion: null,
blockingSeverity: null,
severityApplied: null,
findingCount: null,
assessmentCount: null,
coverageDigest: null,
reasonCode: null,
decidedAt: null,
bypass: null,
raw: null,
};
}

function extractReview(source: Review | ReviewOutcome): {
available: boolean;
review: Review | null;
} {
if (!isObject(source)) {
throw invalidGate("the review source is not an object");
}
if ("reviewUrl" in source && "review" in source) {
if (source.review === null) return { available: false, review: null };
if (!isObject(source.review)) {
throw invalidGate("the review outcome contains an invalid review");
}
return { available: true, review: source.review as Review };
}
return { available: true, review: source as Review };
}

function validateGate(rawGate: unknown): PullRequestMergeGate {
if (!isObject(rawGate)) {
throw invalidGate("the review merge_gate projection is malformed");
}
const id = requiredString(rawGate, "id");
const headSha = requiredString(rawGate, "head_sha");
const policyVersion = requiredString(rawGate, "policy_version");
const blockingSeverity = requiredString(rawGate, "blocking_severity");
const status = requiredString(rawGate, "status");
if (!GATE_STATUSES.has(status as MergeGateStatus)) {
throw invalidGate(`merge_gate.status ${JSON.stringify(status)} is unknown`);
}
const pullRequestNumber = rawGate.pull_request_number;
if (
typeof pullRequestNumber !== "number" ||
!Number.isSafeInteger(pullRequestNumber) ||
pullRequestNumber <= 0
) {
throw invalidGate(
"merge_gate.pull_request_number must be a positive integer",
);
}
const decision = rawGate.decision;
if (
decision !== undefined &&
decision !== null &&
decision !== "ALLOW" &&
decision !== "BLOCK"
) {
throw invalidGate("merge_gate.decision must be ALLOW, BLOCK, or null");
}
if (status === "ALLOWED" && decision !== "ALLOW") {
throw invalidGate("an ALLOWED merge gate must carry an ALLOW decision");
}
if (status === "BLOCKED" && decision !== "BLOCK") {
throw invalidGate("a BLOCKED merge gate must carry a BLOCK decision");
}

optionalInteger(rawGate, "assessment_count", true);
optionalInteger(rawGate, "finding_count", true);
optionalInteger(rawGate, "merged_by_github_user_id");
optionalInteger(rawGate, "merged_pull_request_number");
for (const field of [
"review_id",
"coverage_digest",
"reason_code",
"decided_at",
"bypassed_at",
"merge_commit_sha",
"merged_by_login",
"merged_by_name",
"severity_applied",
]) {
optionalString(rawGate, field);
}

return {
...rawGate,
id,
head_sha: headSha,
policy_version: policyVersion,
blocking_severity: blockingSeverity,
status: status as MergeGateStatus,
pull_request_number: pullRequestNumber,
} as PullRequestMergeGate;
}

/**
* Normalizes and validates the server-recorded `PullRequestMergeGate` projection
* from a `Review` or `ReviewOutcome`.
*/
export function readReviewMergeGate(
source: Review | ReviewOutcome,
options: ReadReviewMergeGateOptions = {},
): ReviewMergeGate {
if (
options.headSha !== undefined &&
!/^[0-9a-f]{40}$/i.test(options.headSha)
) {
throw new TypeError("headSha must be a full 40-character commit SHA");
}
const { available, review } = extractReview(source);
if (!available || !review) return emptyGate("UNAVAILABLE");
const rawMergeGate = (review as unknown as Record<string, unknown>)
.merge_gate;
if (rawMergeGate === undefined || rawMergeGate === null) {
return emptyGate("NOT_CONFIGURED");
}
const gate = validateGate(rawMergeGate);
const bypassFields: MergeGateBypass = {
bypassedAt: gate.bypassed_at ?? null,
mergeCommitSha: gate.merge_commit_sha ?? null,
mergedPullRequestNumber: gate.merged_pull_request_number ?? null,
mergedByGithubUserId: gate.merged_by_github_user_id ?? null,
mergedByLogin: gate.merged_by_login ?? null,
mergedByName: gate.merged_by_name ?? null,
};
const hasBypass =
gate.status === "BYPASSED" ||
Object.values(bypassFields).some((value) => value !== null);
const headMismatch =
options.headSha !== undefined &&
gate.head_sha.toLowerCase() !== options.headSha.toLowerCase();

return {
status: headMismatch ? "HEAD_MISMATCH" : gate.status,
decision: headMismatch ? null : (gate.decision ?? null),
gateId: gate.id,
reviewId: gate.review_id ?? null,
pullRequestNumber: gate.pull_request_number,
headSha: gate.head_sha,
policyVersion: gate.policy_version,
blockingSeverity: gate.blocking_severity,
severityApplied: gate.severity_applied ?? null,
findingCount: gate.finding_count ?? null,
assessmentCount: gate.assessment_count ?? null,
coverageDigest: gate.coverage_digest ?? null,
reasonCode: gate.reason_code ?? null,
decidedAt: gate.decided_at ?? null,
bypass: hasBypass ? bypassFields : null,
raw: gate,
};
}
Loading