Public: anyone can read this; the crew can change it.

openapi.json describes what each route answers #17917

opened this in answer to

Merged 21h 51m ago, live in production

mason/forge:mason/17911-openapi-json-describes-what-each-route-a → main 0 commits fork

  • Merged. mason/17911-openapi-json-describes-what-each-route-a was merged into main as d398aa1.

Review

Sign in to review this change.
38 files changed +837 −23
docs/features/api-reference.md +2
@@ -22,6 +22,8 @@ operations: they live on another origin.
2222 **In the terminal:** `API` in the command palette lists the same operations; `/` narrows; Enter on a GET with no
2323 path parameter runs it as the person at the terminal and shows the status, time, Server-Timing and body.
2424
25 **What a route answers is written in full for the routes a client generates from** (#17911): repositories' contents, commits, branches, issues, pulls with their files, checks, reviews, verdicts, comments and merge, edits, conversations and `conversation/messages` name their request and response as JSON Schema under `components.schemas` (`src/contract/openapi/schemas/`), and the operation points at it. `/api`, the terminal's `API` and `?tag=` slices all read this one document; a slice carries only the schemas its operations reach. `test/openapi-schemas.test.ts` calls each route and holds its real body to the schema, so a field a handler gains without its line there fails by name. A file over 5 MB answers 413 `{ type: "file", tooLarge: true, size }`, declared on both contents routes as `ContentsTooLarge`; `Contents` is a `oneOf` with a `type` discriminator (`dir` or `file`). Runs, looks, plans and proposals are named too (`schemas/run.ts`), none left an open object.
26
2527 `/api` answers `no_route` in JSON to a caller whose `Accept` prefers JSON, as the rest of `/api` does.
2628
2729 A list the contract gives a `cursor` pages by it: `?page=` or `?offset=` on one is a 400 `invalid_query` ("This list pages by cursor: pass next_cursor as ?cursor="), answered by one guard in `src/http/cursor_lists.ts` before any handler runs, and named in the document as the route's 400.
src/contract/openapi.ts +6 −3
@@ -14,6 +14,7 @@
1414 import type { QueryType, ReplyShape, Role, Route } from "./openapi/shared.ts";
1515 import { OAUTH_SCOPES, type OAuthScope } from "../core/oauth.ts";
1616 import { tagList, tagOf } from "./tags.ts";
17 import { COMPONENT_SCHEMAS } from "./openapi/schemas/index.ts";
1718 import * as each from "./openapi/routes/index.ts";
1819
1920 /**
@@ -143,6 +144,7 @@ function shapesSchema(shapes: Readonly<Record<string, ReplyShape>>, list: boolea
143144 * from `replyShapes` beside them when a route declares both.
144145 */
145146 function replySchema(r: Route) {
147 if (r.response !== undefined) return r.response;
146148 const flat = { type: "object", properties: Object.fromEntries(Object.entries(r.reply ?? {}).map(([k, t]) => [k, schema(t)])) };
147149 if (r.replyShapes === undefined) return flat;
148150 const shaped = shapesSchema(r.replyShapes, pagesByCursor(r));
@@ -207,7 +209,7 @@ export function openapi(origin: string, version: string, role: Role): Record<str
207209 required: true,
208210 content: {
209211 "application/json": {
210 schema: {
212 schema: r.request ?? {
211213 type: "object",
212214 properties: Object.fromEntries(
213215 Object.entries(r.body).map(([k, t]) => [k, schema(t)]),
@@ -222,11 +224,12 @@ export function openapi(origin: string, version: string, role: Role): Record<str
222224 responses: {
223225 [String(r.status ?? 200)]: {
224226 description: "Done",
225 ...(r.replyShapes === undefined && r.reply === undefined
227 ...(r.replyShapes === undefined && r.reply === undefined && r.response === undefined
226228 ? {}
227229 : { content: { "application/json": { schema: replySchema(r) } } }),
228230 },
229231 ...Object.fromEntries((r.alsoStatus ?? []).map((c) => [String(c), c >= 400 ? sharedRef("Refused") : c === 304 ? { description: "Not modified: the If-None-Match sent is still current; no body" } : { description: "Done" }])),
232 ...Object.fromEntries(Object.entries(r.answers ?? {}).map(([c, a]) => [c, { description: a.says, content: { "application/json": { schema: a.schema } } }])),
230233 ...(pagesByCursor(r) ? { "400": sharedRef("PageRefused") } : readsJsonBody(r) ? { "400": sharedRef("NotJson") } : {}),
231234 ...sharedRefusals(r),
232235 ...Object.fromEntries(Object.entries(r.errorStatus ?? {}).map(([c, d]) => [c, errorAnswer(d)])),
@@ -256,7 +259,7 @@ export function openapi(origin: string, version: string, role: Role): Record<str
256259 paths,
257260 components: {
258261 parameters: { fields: FIELDS_PARAM },
259 schemas: { Error: ERROR_SCHEMA },
262 schemas: { Error: ERROR_SCHEMA, ...COMPONENT_SCHEMAS },
260263 responses: sharedResponses(),
261264 securitySchemes: {
262265 token: { type: "http", scheme: "bearer" },
src/contract/openapi/routes/getApiV1Conversations.ts +2 −1
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import type { Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -8,6 +9,6 @@ export const route: Route = {
89 auth: true,
910 role: "member",
1011 query: { archived: "string" },
11 reply: { conversations: "array" },
12 response: ref("ConversationList"),
1213 refuses: [401],
1314 };
src/contract/openapi/routes/getApiV1ReposOwnerNameBranches.ts +2
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route, limitTo } from "../shared.ts";
23 import { LIST_LIMIT_MAX } from "../../../core/issues.ts";
34
@@ -16,5 +17,6 @@ export const route: Route = {
1617 invalid_limit: "limit is not a whole number from 1 to 200 (422)",
1718 invalid_cursor: "cursor is not the next_cursor of a page before (422)",
1819 },
20 response: ref("BranchList"),
1921 refuses: [404],
2022 };
src/contract/openapi/routes/getApiV1ReposOwnerNameCommits.ts +2 −1
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route, limitTo } from "../shared.ts";
23
3 export const route: Route = { method: "get", path: `${REPO}/commits`, summary: "List commits newest first from `ref` as `{ items, next_cursor }`", detail: "List commits newest first from `ref` (default: the default branch) as `{ items, next_cursor }`, items of { oid, parents, author, email, date, subject, body }; limit 1 to 100 (default 30); a cursor (the next_cursor of the page before, 40 to 64 hex) continues the log after that commit and `ref` is then ignored, so the cursor's own history is paged (a malformed cursor or one naming no commit is a 422 invalid_cursor); an unsafe ref is a 422 bad_ref; a private repository needs a token; the 200 carries a weak etag, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body until the ref moves", auth: false, role: "anonymous", alsoStatus: [304], query: { ref: "string", cursor: "string", limit: limitTo(100) }, refuses: [404] };
4 export const route: Route = { method: "get", path: `${REPO}/commits`, summary: "List commits newest first from `ref` as `{ items, next_cursor }`", detail: "List commits newest first from `ref` (default: the default branch) as `{ items, next_cursor }`, items of { oid, parents, author, email, date, subject, body }; limit 1 to 100 (default 30); a cursor (the next_cursor of the page before, 40 to 64 hex) continues the log after that commit and `ref` is then ignored, so the cursor's own history is paged (a malformed cursor or one naming no commit is a 422 invalid_cursor); an unsafe ref is a 422 bad_ref; a private repository needs a token; the 200 carries a weak etag, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body until the ref moves", auth: false, role: "anonymous", alsoStatus: [304], query: { ref: "string", cursor: "string", limit: limitTo(100) }, response: ref("CommitList"), refuses: [404] };
src/contract/openapi/routes/getApiV1ReposOwnerNameCommitsOid.ts +2 −1
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
3 export const route: Route = { method: "get", path: `${REPO}/commits/{oid}`, summary: "Read one commit", detail: "Read one commit (a full or abbreviated id, or a ref) as { oid, parents, author, email, date, subject, body, diff: { files, additions, deletions } }; a private repository needs a token", auth: false, role: "anonymous", refuses: [404] };
4 export const route: Route = { method: "get", path: `${REPO}/commits/{oid}`, summary: "Read one commit", detail: "Read one commit (a full or abbreviated id, or a ref) as { oid, parents, author, email, date, subject, body, diff: { files, additions, deletions } }; a private repository needs a token", auth: false, role: "anonymous", response: ref("CommitDetail"), refuses: [404] };
src/contract/openapi/routes/getApiV1ReposOwnerNameContents.ts +2 −1
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
3 export const route: Route = { method: "get", path: `${REPO}/contents`, summary: "Read the tree or a file at `ref`", detail: "Read the tree or a file at `ref` (default: the default branch); no `path` or a directory answers { type: \"dir\", ref, path, entries }, a file answers { type: \"file\", ref, path, size, encoding: \"utf-8\" | \"base64\", content }, a file over 5 MB is a 413 { type: \"file\", tooLarge: true, size }; a private repository needs a token", auth: false, role: "anonymous", query: { path: "string", ref: "string" }, refuses: [404] };
4 export const route: Route = { method: "get", path: `${REPO}/contents`, summary: "Read the tree or a file at `ref`", detail: "Read the tree or a file at `ref` (default: the default branch); no `path` or a directory answers { type: \"dir\", ref, path, entries }, a file answers { type: \"file\", ref, path, size, encoding: \"utf-8\" | \"base64\", content }, a file over 5 MB is a 413 { type: \"file\", tooLarge: true, size }; a private repository needs a token", auth: false, role: "anonymous", query: { path: "string", ref: "string" }, response: ref("Contents"), answers: { 413: { says: "A file over 5 MB: its size, no content", schema: ref("ContentsTooLarge") } }, refuses: [404] };
src/contract/openapi/routes/getApiV1ReposOwnerNameContentsPath.ts +2 −1
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
3 export const route: Route = { method: "get", path: `${REPO}/contents/{path}`, summary: "Read a directory or a file at a path", detail: "Read a path at `ref` (default: the default branch): a directory answers { type: dir, ref, path, entries }, a file { type: file, ref, path, size, encoding, content } (utf-8, or base64 for binary); a file over 5 MB answers 413 { type: file, tooLarge, size }; 404 for an unsafe ref or path or one that is missing", auth: false, role: "anonymous", query: { ref: "string" }, refuses: [404] };
4 export const route: Route = { method: "get", path: `${REPO}/contents/{path}`, summary: "Read a directory or a file at a path", detail: "Read a path at `ref` (default: the default branch): a directory answers { type: dir, ref, path, entries }, a file { type: file, ref, path, size, encoding, content } (utf-8, or base64 for binary); a file over 5 MB answers 413 { type: file, tooLarge, size }; 404 for an unsafe ref or path or one that is missing", auth: false, role: "anonymous", query: { ref: "string" }, response: ref("Contents"), answers: { 413: { says: "A file over 5 MB: its size, no content", schema: ref("ContentsTooLarge") } }, refuses: [404] };
src/contract/openapi/routes/getApiV1ReposOwnerNameIssuesNumber.ts +2 −1
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
3 export const route: Route = { method: "get", path: `${REPO}/issues/{number}`, summary: "Read one issue with its newest 50 comments, oldest first, commentsTotal and commentsNext", detail: "Read one issue with its newest 50 comments, oldest first, commentsTotal and commentsNext (a cursor for …/comments?cursor=, null when no older comment is left to fetch, and with comments=0, which shows none: read …/comments); comments=N (0 to 200) asks for another count, adds commentCount, any other value is a 422 invalid_comments; the 200 carries a weak etag of the exact JSON and cache-control private, no-cache (it varies by reader), and a repeat sending If-None-Match gets 304 with no body once access is checked", auth: false, role: "anonymous", alsoStatus: [304], query: { comments: "integer" }, refuses: [404] };
4 export const route: Route = { method: "get", path: `${REPO}/issues/{number}`, summary: "Read one issue with its newest 50 comments, oldest first, commentsTotal and commentsNext", detail: "Read one issue with its newest 50 comments, oldest first, commentsTotal and commentsNext (a cursor for …/comments?cursor=, null when no older comment is left to fetch, and with comments=0, which shows none: read …/comments); comments=N (0 to 200) asks for another count, adds commentCount, any other value is a 422 invalid_comments; the 200 carries a weak etag of the exact JSON and cache-control private, no-cache (it varies by reader), and a repeat sending If-None-Match gets 304 with no body once access is checked", auth: false, role: "anonymous", alsoStatus: [304], query: { comments: "integer" }, response: ref("IssueDetail"), refuses: [404] };
src/contract/openapi/routes/getApiV1ReposOwnerNamePulls.ts +2 −1
@@ -1,3 +1,4 @@
1 import { ref, page } from "../schema_kit.ts";
12 import { ISSUE_ITEM_KEYS, LIST_QUERY, REPO, type Route } from "../shared.ts";
23
3 export const route: Route = { method: "get", path: `${REPO}/pulls`, summary: "List a repository's pulls", detail: "List a repository's pulls; carries a weak `etag` of the page sent (cache-control private, no-cache; vary authorization, cookie), and a repeat sending If-None-Match gets 304 with no body until a pull in the page is opened, pushed to, checked, merged or closed", auth: false, role: "anonymous", alsoStatus: [304], itemKeys: [...ISSUE_ITEM_KEYS, "baseBranch", "headBranch", "baseOid", "headOid", "mergedAt", "mergedOid", "headRepoId", "crossRepo", "originHeadRepo", "revertsPullId", "variantGroup", "author", "check", "preview", "variantSiblings", "mergeable", "conflicts"], query: LIST_QUERY, refusals: { invalid_limit: "limit is not a whole number from 1 to 200 (422)", invalid_cursor: "cursor is not the next_cursor of a previous page (422)", invalid_state: "state is not open, closed or all (422)", unknown_parameter: "a parameter this list does not read (422)", invalid_labels: "over 20 labels (422)" }, refuses: [404] };
4 export const route: Route = { method: "get", path: `${REPO}/pulls`, summary: "List a repository's pulls", detail: "List a repository's pulls; carries a weak `etag` of the page sent (cache-control private, no-cache; vary authorization, cookie), and a repeat sending If-None-Match gets 304 with no body until a pull in the page is opened, pushed to, checked, merged or closed", auth: false, role: "anonymous", alsoStatus: [304], itemKeys: [...ISSUE_ITEM_KEYS, "baseBranch", "headBranch", "baseOid", "headOid", "mergedAt", "mergedOid", "headRepoId", "crossRepo", "originHeadRepo", "revertsPullId", "variantGroup", "author", "check", "preview", "variantSiblings", "mergeable", "conflicts"], query: LIST_QUERY, refusals: { invalid_limit: "limit is not a whole number from 1 to 200 (422)", invalid_cursor: "cursor is not the next_cursor of a previous page (422)", invalid_state: "state is not open, closed or all (422)", unknown_parameter: "a parameter this list does not read (422)", invalid_labels: "over 20 labels (422)" }, response: page(ref("PullItem")), refuses: [404] };
src/contract/openapi/routes/getApiV1ReposOwnerNamePullsNumber.ts +2 −1
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
3 export const route: Route = { method: "get", path: `${REPO}/pulls/{number}`, summary: "Read one pull with its diff and review gate", detail: "Read one pull with its diff and review gate (diff=0 leaves the diff out; a diff over 4 MiB of git text is left out too, and `diffTooLarge` {limitBytes, says} replaces it: read it at …/pulls/{number}/diff); `check` is the word for the head's check: green, red, running or none; `checkedAgainst` is the base tip that check merged with (null before one recorded it), `checkStale` says the base has moved since, and `approvedAt` is the standing approval {at, head, base, current} or null, current false once the head or the base moved, and `approvedAgainst` is the same approval as one string, \"<head7> against <base7>\" (the head alone for an approval from before bases were recorded, null with none); `waitsFor` is {cause, says, action, line} for an open pull green and unlanded over six hours, else null; the 200 carries a weak etag of the exact body, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body and the same etag until the head, a check verdict, a review or the state changes", auth: false, role: "anonymous", alsoStatus: [304], query: { diff: "string" }, reply: { check: "string", checkedAgainst: "string", approvedAt: "object", approvedAgainst: "string", waitsFor: "object" }, refuses: [404] };
4 export const route: Route = { method: "get", path: `${REPO}/pulls/{number}`, summary: "Read one pull with its diff and review gate", detail: "Read one pull with its diff and review gate (diff=0 leaves the diff out; a diff over 4 MiB of git text is left out too, and `diffTooLarge` {limitBytes, says} replaces it: read it at …/pulls/{number}/diff); `check` is the word for the head's check: green, red, running or none; `checkedAgainst` is the base tip that check merged with (null before one recorded it), `checkStale` says the base has moved since, and `approvedAt` is the standing approval {at, head, base, current} or null, current false once the head or the base moved, and `approvedAgainst` is the same approval as one string, \"<head7> against <base7>\" (the head alone for an approval from before bases were recorded, null with none); `waitsFor` is {cause, says, action, line} for an open pull green and unlanded over six hours, else null; the 200 carries a weak etag of the exact body, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body and the same etag until the head, a check verdict, a review or the state changes", auth: false, role: "anonymous", alsoStatus: [304], query: { diff: "string" }, response: ref("PullDetail"), refuses: [404] };
src/contract/openapi/routes/getApiV1ReposOwnerNamePullsNumberChecks.ts +2 −1
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -8,6 +9,6 @@ export const route: Route = {
89 auth: false,
910 role: "anonymous",
1011 query: { format: "string" },
11 reply: { head: "string", state: "string", required: "boolean", run: "object", runs: "array" },
12 response: ref("Checks"),
1213 refuses: [404],
1314 };
src/contract/openapi/routes/getApiV1ReposOwnerNamePullsNumberFiles.ts +2
@@ -1,3 +1,4 @@
1 import { ref, list } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -7,5 +8,6 @@ export const route: Route = {
78 detail: "Each changed file: path, status, additions, deletions",
89 auth: false,
910 role: "anonymous",
11 response: list(ref("FileChange")),
1012 refuses: [404],
1113 };
src/contract/openapi/routes/getApiV1ReposOwnerNamePullsNumberReviewStates.ts +2
@@ -1,3 +1,4 @@
1 import { ref, list } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -7,5 +8,6 @@ export const route: Route = {
78 detail: "List a pull's reviews, the verdicts (approved, changes_requested or commented), each with its body",
89 auth: false,
910 role: "anonymous",
11 response: list(ref("Review")),
1012 refuses: [404],
1113 };
src/contract/openapi/routes/getApiV1ReposOwnerNamePullsNumberReviews.ts +2 −1
@@ -1,3 +1,4 @@
1 import { ref, list } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
3 export const route: Route = { method: "get", path: `${REPO}/pulls/{number}/reviews`, summary: "List a pull's line-anchored review comments", detail: "List a pull's line-anchored review comments, each with its `anchor` and whether it is `outdated`", auth: false, role: "anonymous", refuses: [404] };
4 export const route: Route = { method: "get", path: `${REPO}/pulls/{number}/reviews`, summary: "List a pull's line-anchored review comments", detail: "List a pull's line-anchored review comments, each with its `anchor` and whether it is `outdated`", auth: false, role: "anonymous", response: list(ref("ReviewComment")), refuses: [404] };
src/contract/openapi/routes/patchApiV1ConversationsId.ts +3 −1
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import type { Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -8,7 +9,8 @@ export const route: Route = {
89 auth: true,
910 role: "member",
1011 body: { title: "string", archived: "boolean" },
11 reply: { conversation: "object" },
1212 refusals: { invalid_title: "title is over 80 characters or has a line break (422)", not_found: "no such conversation of yours (404)", forbidden: "the request is cross-origin, or the token is read-only" },
13 response: ref("ConversationEnvelope"),
14 request: ref("ConversationRequest"),
1315 refuses: [401, 404],
1416 };
src/contract/openapi/routes/postApiV1ConversationMessages.ts +3 −1
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import type { Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -9,7 +10,6 @@ export const route: Route = {
910 role: "member",
1011 status: 202,
1112 body: { text: "string", conversation: "string" },
12 reply: { how: "string" },
1313 refusals: {
1414 not_found: "conversation names none of the person's (404)",
1515 invalid_text: "text is not a string of 1 to 20000 characters",
@@ -20,5 +20,7 @@ export const route: Route = {
2020 rate_limited: "more than 12 messages in a minute (429)",
2121 forbidden: "the request is cross-origin",
2222 },
23 response: ref("MessageReply"),
24 request: ref("MessageRequest"),
2325 refuses: [401, 422],
2426 };
src/contract/openapi/routes/postApiV1Conversations.ts +3 −1
@@ -1,3 +1,4 @@
1 import { ref, obj, str } from "../schema_kit.ts";
12 import type { Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -9,7 +10,8 @@ export const route: Route = {
910 role: "member",
1011 status: 201,
1112 body: { title: "string" },
12 reply: { conversation: "object" },
1313 refusals: { invalid_title: "title is over 80 characters or has a line break (422)", forbidden: "the request is cross-origin, or the token is read-only" },
14 response: ref("ConversationEnvelope"),
15 request: obj({ title: str }, ["title"]),
1416 refuses: [401],
1517 };
src/contract/openapi/routes/postApiV1ReposOwnerNameContents.ts +3
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -23,5 +24,7 @@ export const route: Route = {
2324 land_refused: "the commit could not be landed on the branch",
2425 git: "git failed while committing",
2526 },
27 response: ref("Committed"),
28 request: ref("FilesWrite"),
2629 refuses: [401, 404],
2730 };
src/contract/openapi/routes/postApiV1ReposOwnerNameEdits.ts +3
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -12,5 +13,7 @@ export const route: Route = {
1213 status: 201,
1314 body: { branch: "string", base: "string", message: "string", newBranch: "string", files: "array", openPull: "object" },
1415 refusals: { no_files: "files holds nothing to write" },
16 response: ref("EditReply"),
17 request: ref("EditRequest"),
1518 refuses: [401, 404],
1619 };
src/contract/openapi/routes/postApiV1ReposOwnerNameIssuesNumberComments.ts +3
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -5,7 +6,9 @@ export const route: Route = {
56 path: `${REPO}/issues/{number}/comments`,
67 summary: "Comment on an issue or pull",
78 auth: true,
9 status: 201,
810 role: "member",
911 body: { body: "string" },
12 response: ref("Comment"),
1013 refuses: [401, 404],
1114 };
src/contract/openapi/routes/postApiV1ReposOwnerNamePullsNumberComments.ts +2
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -13,5 +14,6 @@ export const route: Route = {
1314 empty_body: "`body` is empty (422)",
1415 mirrored: "the repository mirrors an origin; comment there (409)",
1516 },
17 response: ref("Comment"),
1618 refuses: [401, 404],
1719 };
src/contract/openapi/routes/postApiV1ReposOwnerNamePullsNumberMerge.ts +2 −1
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
3 export const route: Route = { method: "post", path: `${REPO}/pulls/{number}/merge`, summary: "Merge a pull (a person's)", detail: "Answers { merged, mergeOid, carried, message }: carried is true when the base already had the change, so no merge commit is made", auth: true, role: "member", refuses: [401, 404] };
4 export const route: Route = { method: "post", path: `${REPO}/pulls/{number}/merge`, summary: "Merge a pull (a person's)", detail: "Answers { merged, mergeOid, carried, message }: carried is true when the base already had the change, so no merge commit is made", auth: true, role: "member", response: ref("Merged"), refuses: [401, 404] };
src/contract/openapi/routes/postApiV1ReposOwnerNamePullsNumberReviewStates.ts +2
@@ -1,3 +1,4 @@
1 import { ref } from "../schema_kit.ts";
12 import { REPO, type Route } from "../shared.ts";
23
34 export const route: Route = {
@@ -17,5 +18,6 @@ export const route: Route = {
1718 bad_anchor: "a comment's anchor is not in the diff; nothing was posted (422)",
1819 too_many_lines: "the review carries more line comments than the cap (422)",
1920 },
21 response: ref("Review"),
2022 refuses: [401, 404],
2123 };
src/contract/openapi/schema_kit.ts added +38
@@ -0,0 +1,38 @@
1 /**
2 * The few words a response or request schema is written in (#17911): a JSON Schema as plain data,
3 * so a route's row can say what it answers in full and a client generator (swift-openapi-generator)
4 * can build its types from it. `test/openapi-schemas.test.ts` calls the real routes and holds each
5 * schema to the JSON they write, both ways, so a field added to a handler without its line here
6 * fails there.
7 */
8
9 export type Schema = Readonly<Record<string, unknown>>;
10
11 export const str: Schema = { type: "string" };
12 export const int: Schema = { type: "integer" };
13 export const bool: Schema = { type: "boolean" };
14
15 /** A value that may also be null (OpenAPI 3.1: a type array, or `anyOf` with null for a `$ref`). */
16 export const orNull = (s: Schema): Schema =>
17 typeof s.type === "string" ? { ...s, type: [s.type, "null"] } : { anyOf: [s, { type: "null" }] };
18
19 export const list = (items: Schema): Schema => ({ type: "array", items });
20
21 /** One of a fixed set of words. */
22 export const words = (...of: string[]): Schema => ({ type: "string", enum: of });
23
24 /** A pointer to a schema named under `components.schemas`. */
25 export const ref = (name: string): Schema => ({ $ref: `#/components/schemas/${name}` });
26
27 /**
28 * An object whose every property is required, but those named in `optional`, which the handler
29 * leaves out at times. Properties not named are allowed: the forge may add one.
30 */
31 export const obj = (properties: Readonly<Record<string, Schema>>, optional: readonly string[] = []): Schema => ({
32 type: "object",
33 required: Object.keys(properties).filter((k) => !optional.includes(k)),
34 properties,
35 });
36
37 /** A cursor list: `items` and the cursor of the next page, null on the last. */
38 export const page = (item: Schema): Schema => obj({ items: list(item), next_cursor: orNull(str) });
src/contract/openapi/schemas/conversation.ts added +54
@@ -0,0 +1,54 @@
1 /**
2 * What a conversation with the forge's own agent is on the wire: the message sent, its answer, the
3 * conversation.
4 */
5
6 import { bool, int, list, obj, orNull, ref, str, words, type Schema } from "../schema_kit.ts";
7
8 const MESSAGE_REQUEST: Schema = obj(
9 { text: str, conversation: str, files: list(str), during: words("queue", "steer"), about: str },
10 ["conversation", "files", "during", "about"],
11 );
12
13 /**
14 * 202: the message started a turn, was queued, or was kept with the line saying why it could not
15 * start.
16 */
17 const MESSAGE_REPLY: Schema = obj(
18 {
19 how: str,
20 queued: int,
21 why: str,
22 message: str,
23 turn: str,
24 until: str,
25 says: str,
26 fix: obj({ href: str, label: str }),
27 who: str,
28 ask: obj({ method: str, path: str, body: { type: "object" } }),
29 setting: str,
30 },
31 ["queued", "why", "message", "turn", "until", "says", "fix", "who", "ask", "setting"],
32 );
33
34 const CONVERSATION: Schema = obj({
35 id: str,
36 userId: str,
37 claudeSessionId: str,
38 createdAt: str,
39 updatedAt: str,
40 title: str,
41 archivedAt: orNull(str),
42 pinnedAt: orNull(str),
43 });
44
45 const CONVERSATION_REQUEST: Schema = obj({ title: str, archived: bool }, ["title", "archived"]);
46
47 export const CONVERSATION_SCHEMAS: Readonly<Record<string, Schema>> = {
48 MessageRequest: MESSAGE_REQUEST,
49 MessageReply: MESSAGE_REPLY,
50 Conversation: CONVERSATION,
51 ConversationEnvelope: obj({ conversation: ref("Conversation") }),
52 ConversationList: obj({ conversations: list(ref("Conversation")) }),
53 ConversationRequest: CONVERSATION_REQUEST,
54 };
src/contract/openapi/schemas/diff.ts added +26
@@ -0,0 +1,26 @@
1 /** A diff as the pull and the commit write it: files, hunks and numbered lines (`git/diff.ts`). */
2
3 import { bool, int, list, obj, orNull, ref, str, words, type Schema } from "../schema_kit.ts";
4
5 const LINE: Schema = obj({ kind: words("context", "add", "del"), oldNumber: orNull(int), newNumber: orNull(int), content: str, noNewline: bool });
6
7 const HUNK: Schema = obj({ oldStart: int, oldLines: int, newStart: int, newLines: int, section: str, lines: list(ref("DiffLine")) });
8
9 const FILE: Schema = obj({
10 status: words("added", "deleted", "modified", "renamed", "copied"),
11 oldPath: orNull(str),
12 newPath: orNull(str),
13 path: str,
14 binary: bool,
15 additions: int,
16 deletions: int,
17 similarity: orNull(int),
18 hunks: list(ref("DiffHunk")),
19 });
20
21 export const DIFF_SCHEMAS: Readonly<Record<string, Schema>> = {
22 DiffLine: LINE,
23 DiffHunk: HUNK,
24 DiffFile: FILE,
25 Diff: obj({ files: list(ref("DiffFile")), additions: int, deletions: int }),
26 };
src/contract/openapi/schemas/index.ts added +10
@@ -0,0 +1,10 @@
1 /** Every named schema a route row points at, gathered for `components.schemas`. */
2
3 import { CONVERSATION_SCHEMAS } from "./conversation.ts";
4 import { DIFF_SCHEMAS } from "./diff.ts";
5 import { PULL_SCHEMAS } from "./pull.ts";
6 import { REPO_SCHEMAS } from "./repo.ts";
7 import { RUN_SCHEMAS } from "./run.ts";
8 import type { Schema } from "../schema_kit.ts";
9
10 export const COMPONENT_SCHEMAS: Readonly<Record<string, Schema>> = { ...DIFF_SCHEMAS, ...PULL_SCHEMAS, ...REPO_SCHEMAS, ...RUN_SCHEMAS, ...CONVERSATION_SCHEMAS };
src/contract/openapi/schemas/pull.ts added +193
@@ -0,0 +1,193 @@
1 /**
2 * What a pull and an issue are on the wire: the rows `GET …/pulls/{number}`, `…/issues/{number}`
3 * and their lists write.
4 */
5
6 import { bool, int, list, obj, orNull, ref, str, words, type Schema } from "../schema_kit.ts";
7
8 /** A label as the list and the single reads carry it. */
9 const LABEL: Schema = obj({ id: str, name: str, color: str });
10
11 /** The stored row of an issue or a pull, as every read writes it. */
12 const STORED_ROW = {
13 id: str,
14 repoId: str,
15 number: int,
16 kind: words("issue", "pull"),
17 title: str,
18 body: str,
19 authorId: str,
20 authorName: str,
21 state: words("open", "closed"),
22 createdAt: str,
23 updatedAt: str,
24 closedAt: orNull(str),
25 closeReason: orNull(str),
26 originAuthor: orNull(str),
27 originUrl: orNull(str),
28 assigneeId: orNull(str),
29 assigneeName: orNull(str),
30 assigneeIsAgent: bool,
31 authorIsAgent: bool,
32 sealed: bool,
33 estimated: bool,
34 } as const;
35
36 /** The stored row with its labels, and the mark a reader of crew threads gets (`readerMarked`). */
37 const ISSUE_ROW = { ...STORED_ROW, labels: list(ref("Label")), untrusted: str } as const;
38
39 const PULL_ROW = {
40 baseBranch: str,
41 headBranch: str,
42 baseOid: str,
43 headOid: str,
44 mergedAt: orNull(str),
45 mergedOid: orNull(str),
46 headRepoId: str,
47 crossRepo: bool,
48 originHeadRepo: orNull(str),
49 revertsPullId: orNull(str),
50 variantGroup: orNull(str),
51 draftRun: orNull(str),
52 } as const;
53
54 const APPROVAL: Schema = obj({ at: str, head: str, base: orNull(str), current: bool });
55
56 /** A pull as `POST …/edits` opens one: the stored rows, before labels. */
57 const PULL_STORED: Schema = obj({ ...STORED_ROW, ...PULL_ROW });
58
59 /** The pull with the review gate beside it: what `GET …/pulls/{number}` answers. */
60 const PULL_DETAIL: Schema = obj(
61 {
62 ...ISSUE_ROW,
63 ...PULL_ROW,
64 check: words("green", "red", "running", "none"),
65 checkStale: bool,
66 checkedAgainst: orNull(str),
67 approvedAt: orNull(APPROVAL),
68 approvedAgainst: orNull(str),
69 variantSiblings: list(int),
70 mergeable: bool,
71 conflicts: list(str),
72 proposal: orNull(ref("Proposal")),
73 status: obj({
74 baseOid: str,
75 headOid: str,
76 ahead: int,
77 mergeable: bool,
78 conflicts: list(str),
79 reviews: orNull(obj({ approved: int, changesRequested: int, required: bool, mergeable: bool, approval: orNull(APPROVAL) })),
80 }),
81 diff: ref("Diff"),
82 diffTooLarge: obj({ limitBytes: int, says: str }),
83 hold: orNull(obj({ by: str, why: str, at: str, until: words("green") }, ["until"])),
84 waitsFor: orNull(obj({ cause: str, says: str, action: str, line: str })),
85 },
86 // `mergeable` and `conflicts` are for a live pull; the diff is left out by `?diff=0` or when it
87 // is too large.
88 ["mergeable", "conflicts", "diff", "diffTooLarge", "untrusted"],
89 );
90
91 /** One item of the pulls list: the row, its counts and the head's check word. */
92 const PULL_ITEM: Schema = obj(
93 {
94 ...ISSUE_ROW,
95 ...PULL_ROW,
96 comments: int,
97 author: str,
98 check: words("green", "red", "running", "none"),
99 preview: orNull(str),
100 variantSiblings: list(int),
101 mergeable: bool,
102 conflicts: list(str),
103 },
104 ["mergeable", "conflicts", "untrusted"],
105 );
106
107 /** One comment under an issue or a pull. */
108 const COMMENT: Schema = obj(
109 {
110 id: str,
111 issueId: str,
112 authorId: str,
113 authorName: str,
114 body: str,
115 createdAt: str,
116 originAuthor: orNull(str),
117 heardIn: orNull(str),
118 question: { type: ["string", "null"], enum: ["open", "settled", null] },
119 untrusted: str,
120 },
121 ["untrusted"],
122 );
123
124 /** The issue read: its row, labels and the first page of its comments. */
125 const ISSUE_DETAIL: Schema = obj(
126 {
127 ...ISSUE_ROW,
128 plan: orNull(ref("Plan")),
129 comments: list(ref("Comment")),
130 commentsTotal: int,
131 commentsNext: orNull(str),
132 },
133 ["untrusted"],
134 );
135
136 const FILE_CHANGE: Schema = obj({ path: str, status: str, additions: int, deletions: int, binary: bool });
137
138 const REVIEW: Schema = obj(
139 {
140 id: str,
141 authorId: str,
142 authorName: str,
143 originAuthor: orNull(str),
144 state: words("approved", "changes_requested", "commented"),
145 body: str,
146 commitOid: str,
147 baseOid: str,
148 createdAt: str,
149 untrusted: str,
150 },
151 ["untrusted"],
152 );
153
154 /** A line comment on a pull, as the list answers it. */
155 const REVIEW_COMMENT: Schema = obj(
156 {
157 id: str,
158 authorName: str,
159 body: str,
160 createdAt: str,
161 path: str,
162 line: int,
163 side: words("new", "old"),
164 commitOid: str,
165 lineHash: str,
166 originAuthor: orNull(str),
167 outdated: bool,
168 anchor: str,
169 untrusted: str,
170 },
171 ["untrusted"],
172 );
173
174 const CHECKS: Schema = obj(
175 { head: str, state: str, required: bool, why: str, run: orNull(ref("Run")), looks: list(ref("Look")), runs: list(ref("Run")) },
176 ["why"],
177 );
178
179 const MERGED: Schema = obj({ merged: bool, mergeOid: str, carried: bool, message: str });
180
181 export const PULL_SCHEMAS: Readonly<Record<string, Schema>> = {
182 Label: LABEL,
183 Comment: COMMENT,
184 PullDetail: PULL_DETAIL,
185 PullItem: PULL_ITEM,
186 IssueDetail: ISSUE_DETAIL,
187 FileChange: FILE_CHANGE,
188 Review: REVIEW,
189 ReviewComment: REVIEW_COMMENT,
190 Checks: CHECKS,
191 PullStored: PULL_STORED,
192 Merged: MERGED,
193 };
src/contract/openapi/schemas/repo.ts added +81
@@ -0,0 +1,81 @@
1 /**
2 * What a repository's code is on the wire: contents, commits, branches and the writes that make
3 * them.
4 */
5
6 import { bool, int, list, obj, orNull, page, ref, str, words, type Schema } from "../schema_kit.ts";
7
8 const ENTRY: Schema = obj({ mode: str, type: words("blob", "tree", "commit"), oid: str, size: int, name: str });
9
10 /** A directory: its entries. */
11 const CONTENTS_DIR: Schema = obj({ type: words("dir"), ref: str, path: str, entries: list(ref("TreeEntry")) });
12
13 /** A file: its text, or base64 when it is binary. */
14 const CONTENTS_FILE: Schema = obj({ type: words("file"), ref: str, path: str, size: int, encoding: words("utf-8", "base64"), content: str });
15
16 /** A directory or a file; `type` says which, so a generator decodes the two apart. */
17 const CONTENTS: Schema = {
18 oneOf: [ref("ContentsDir"), ref("ContentsFile")],
19 discriminator: { propertyName: "type", mapping: { dir: "#/components/schemas/ContentsDir", file: "#/components/schemas/ContentsFile" } },
20 };
21
22 /** What a file over 5 MB answers, with status 413: its size and no content. */
23 const CONTENTS_TOO_LARGE: Schema = obj({ type: words("file"), tooLarge: { type: "boolean", enum: [true] }, size: int });
24
25 const COMMIT: Schema = obj({ oid: str, parents: list(str), author: str, email: str, date: str, subject: str, body: str });
26
27 /** A commit with what it changed: the files with their hunks, and the totals. */
28 const COMMIT_DETAIL: Schema = obj({
29 oid: str,
30 parents: list(str),
31 author: str,
32 email: str,
33 date: str,
34 subject: str,
35 body: str,
36 diff: ref("Diff"),
37 });
38
39 /** What a commit or an edit made: the new tip, the branch, and whether the branch is new. */
40 const COMMITTED: Schema = obj({ commitOid: str, branch: str, created: bool });
41
42 const EDIT_REPLY: Schema = obj({ commit: ref("Committed"), branch: str, pull: orNull(ref("PullStored")) });
43
44 const BRANCH: Schema = obj({ name: str, oid: str, isDefault: bool, ahead: orNull(int), behind: orNull(int), protected: bool });
45
46 /** The body of a write of files: a plain commit, or an edit that may open a pull. */
47 const FILE_WRITE = {
48 branch: str,
49 base: str,
50 message: str,
51 files: list(obj({ path: str, content: str })),
52 } as const;
53
54 const EDIT_REQUEST: Schema = obj(
55 {
56 ...FILE_WRITE,
57 newBranch: str,
58 files: list(obj({ path: str, content: orNull(str) })),
59 openPull: obj({ title: str, body: str }, ["title", "body"]),
60 },
61 ["branch", "base", "message", "newBranch", "openPull"],
62 );
63
64 const CONTENTS_REQUEST: Schema = obj(FILE_WRITE, ["branch", "base", "message"]);
65
66 export const REPO_SCHEMAS: Readonly<Record<string, Schema>> = {
67 TreeEntry: ENTRY,
68 Contents: CONTENTS,
69 ContentsDir: CONTENTS_DIR,
70 ContentsFile: CONTENTS_FILE,
71 ContentsTooLarge: CONTENTS_TOO_LARGE,
72 Commit: COMMIT,
73 CommitList: page(ref("Commit")),
74 CommitDetail: COMMIT_DETAIL,
75 Committed: COMMITTED,
76 EditReply: EDIT_REPLY,
77 Branch: BRANCH,
78 BranchList: page(ref("Branch")),
79 FilesWrite: CONTENTS_REQUEST,
80 EditRequest: EDIT_REQUEST,
81 };
src/contract/openapi/schemas/run.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * What a run, the looks of its page and a plan are on the wire: the shapes a pull's checks, an
3 * issue's plan and a pull's proposal carry (#17911). A run is written whole, as `core/runs.ts`
4 * holds it. Nothing here is left an open object: a client generator names every one.
5 */
6
7 import { bool, int, list, obj, orNull, ref, str, words, type Schema } from "../schema_kit.ts";
8
9 const num: Schema = { type: "number" };
10
11 /** What a failed check said about itself, when its output was recognised. */
12 const CHECK_DETAIL: Schema = obj(
13 {
14 passed: int,
15 failed: int,
16 names: list(str),
17 files: list(str),
18 failures: list(obj({ file: str, name: str, assertion: str, excerpt: list(str) }, ["assertion", "excerpt"])),
19 },
20 ["files", "failures"],
21 );
22
23 /** One run of a deploy, an agent or a check. */
24 const RUN: Schema = obj({
25 id: str,
26 repoId: str,
27 kind: words("deploy", "agent", "check"),
28 issueId: orNull(str),
29 env: str,
30 commitOid: str,
31 branch: str,
32 state: words("queued", "running", "ok", "failed", "cancelled"),
33 summary: str,
34 actorId: orNull(str),
35 reason: str,
36 sessionId: str,
37 costUsd: num,
38 notBefore: orNull(str),
39 attempt: int,
40 interruptions: int,
41 heartbeatAt: orNull(str),
42 turns: int,
43 contextTokens: int,
44 model: str,
45 tokensIn: orNull(int),
46 tokensOut: orNull(int),
47 pushed: orNull(bool),
48 sandboxEnforced: orNull(bool),
49 sandboxNote: str,
50 placement: str,
51 node: str,
52 start: str,
53 setupMs: int,
54 checkDetail: orNull(ref("CheckDetail")),
55 checkPlan: str,
56 baseOid: str,
57 combinedOid: str,
58 variantGroup: orNull(str),
59 sent: bool,
60 createdAt: str,
61 startedAt: orNull(str),
62 servingAt: orNull(str),
63 finishedAt: orNull(str),
64 });
65
66 /** The figures of one look at a page: how many screens, whether it scrolls sideways, its size. */
67 const LOOK: Schema = obj(
68 {
69 look: str,
70 screens: str,
71 sideways: bool,
72 size: obj({ scrollWidth: int, scrollHeight: int, innerWidth: int, innerHeight: int }),
73 },
74 ["size"],
75 );
76
77 /** An issue's plan: the checklist a crew run keeps, and what it needs a person to answer. */
78 const PLAN: Schema = obj({
79 issueId: str,
80 runId: orNull(str),
81 items: list(obj({ text: str, done: bool })),
82 ask: str,
83 updatedAt: str,
84 });
85
86 /** What a pull proposes from a child forge, and the verdict a child attested to for a tree. */
87 const PROPOSAL: Schema = obj(
88 {
89 child: str,
90 origin: str,
91 folds: bool,
92 attestation: obj({ verdict: words("green", "red", "pending", "none"), tree: str }),
93 },
94 ["attestation"],
95 );
96
97 export const RUN_SCHEMAS: Readonly<Record<string, Schema>> = {
98 CheckDetail: CHECK_DETAIL,
99 Run: RUN,
100 Look: LOOK,
101 Plan: PLAN,
102 Proposal: PROPOSAL,
103 };
src/contract/openapi/shared.ts +13
@@ -4,6 +4,7 @@
44 * uses lives in that route's file.
55 */
66
7 import type { Schema } from "./schema_kit.ts";
78 import { ORIGIN_UNREACHABLE } from "../../actions/origin_app_words.ts";
89 import { LIST_LIMIT_MAX } from "../../core/issues.ts";
910 import {
@@ -64,6 +65,11 @@ export interface Route {
6465 * what it answers, both ways.
6566 */
6667 readonly refuses?: readonly (401 | 403 | 404 | 422)[];
68 /**
69 * Other answers with a body of their own, by status: what it means and its schema (a 413 that
70 * names the size).
71 */
72 readonly answers?: Readonly<Record<number, { readonly says: string; readonly schema: Schema }>>;
6773 /** The success body's fields, by name and type, when it is worth a schema. */
6874 readonly reply?: Readonly<Record<string, string>>;
6975 /**
@@ -71,6 +77,13 @@ export interface Route {
7177 * changes what comes back (published as `anyOf`; a cursor list's `items`).
7278 */
7379 readonly replyShapes?: Readonly<Record<string, ReplyShape>>;
80 /**
81 * The success body as a full JSON Schema (`schema_kit.ts`, #17911), when `reply` is too thin for
82 * a client to decode it. Wins over `reply` and `replyShapes`.
83 */
84 readonly response?: Schema;
85 /** The JSON body it takes as a full JSON Schema, in place of the flat `body` fields. */
86 readonly request?: Schema;
7487 /** The refusals it answers, by stable `error` code. */
7588 readonly refusals?: Readonly<Record<string, string>>;
7689 }
src/contract/served.ts +21 −2
@@ -54,13 +54,14 @@ export function openapiSliceText(origin: string, version: string, tag: string, r
5454 const key = `${version}\n${origin}\n${role}\n${tag}`;
5555 let hit = built.get(key);
5656 if (!hit) {
57 const doc = openapi(origin, version, role) as { paths: Record<string, Record<string, { tags: string[] }>>; tags: { name: string }[] };
57 const doc = openapi(origin, version, role) as { paths: Record<string, Record<string, { tags: string[] }>>; tags: { name: string }[]; components: { schemas: Record<string, unknown> } };
5858 const paths: typeof doc.paths = {};
5959 for (const [path, ops] of Object.entries(doc.paths)) {
6060 const kept = Object.entries(ops).filter(([, op]) => op.tags.includes(tag));
6161 if (kept.length > 0) paths[path] = Object.fromEntries(kept);
6262 }
63 const text = JSON.stringify({ ...doc, tags: doc.tags.filter((t) => t.name === tag), paths });
63 const components = { ...doc.components, schemas: schemasReached(JSON.stringify(paths), doc.components.schemas) };
64 const text = JSON.stringify({ ...doc, tags: doc.tags.filter((t) => t.name === tag), paths, components });
6465 hit = { text, etag: weakEtag(text) };
6566 if (built.size >= MAX * 4 * ROLES) built.delete(built.keys().next().value as string);
6667 built.set(key, hit);
@@ -68,6 +69,24 @@ export function openapiSliceText(origin: string, version: string, tag: string, r
6869 return hit;
6970 }
7071
72 /**
73 * The named schemas `text` points at, and those they point at in turn, so a slice carries only what
74 * it uses (#17911).
75 */
76 function schemasReached(text: string, all: Record<string, unknown>): Record<string, unknown> {
77 const kept: Record<string, unknown> = {};
78 const queue = [text];
79 while (queue.length > 0) {
80 for (const m of queue.pop()!.matchAll(/#\/components\/schemas\/(\w+)/g)) {
81 const name = m[1]!;
82 if (name in kept || !(name in all)) continue;
83 kept[name] = all[name];
84 queue.push(JSON.stringify(all[name]));
85 }
86 }
87 return kept;
88 }
89
7190 /**
7291 * The document at its canonical path and at the root path an agent guesses;
7392 * /api/v1/openapi.json shares the handler.
test/contract-openapi-tags.test.ts +11 −2
@@ -27,11 +27,20 @@ test("a path's tag is its resource", () => {
2727 test("a slice keeps only its tag's operations and the rest of the document", () => {
2828 const slice = JSON.parse(openapiSliceText("https://x.test", "v", "pulls", "admin").text) as Doc;
2929 expect(slice.info).toEqual(doc.info);
30 expect(slice.components).toEqual(doc.components);
30 // The size guard holds each part to its own cap (#17911): the operations keep the 45 KB the whole
31 // slice had, and the named schemas they reach, the part that is new, have 15 KB. Their components
32 // are the document's, the named schemas cut to the ones its operations reach.
33 const { schemas, ...others } = slice.components as { schemas: Record<string, unknown> };
34 const { schemas: _all, ...rest } = doc.components as { schemas: unknown };
35 expect(others).toEqual(rest);
36 expect(Object.keys(schemas)).toContain("PullDetail");
37 expect(Object.keys(schemas)).not.toContain("Conversation");
38 for (const [name, one] of Object.entries(schemas)) expect(one).toEqual((doc.components as { schemas: Record<string, unknown> }).schemas[name]);
3139 expect(slice.tags.map((t) => t.name)).toEqual(["pulls"]);
3240 const n = Object.values(slice.paths).flatMap((o) => Object.values(o)).length;
3341 expect(n).toBe(ROUTES.filter((r) => tagOf(r.path) === "pulls").length);
34 expect(openapiSliceText("https://x.test", "v", "pulls", "admin").text.length).toBeLessThan(45_000);
42 expect(JSON.stringify(slice.paths).length).toBeLessThan(45_000);
43 expect(JSON.stringify(schemas).length).toBeLessThan(15_000);
3544 });
3645
3746 test("?tag= over HTTP: a slice, the whole, and a 400 naming the tags", async () => {
test/helpers/json_schema.ts added +43
@@ -0,0 +1,43 @@
1 /**
2 * A strict JSON Schema check for the shapes `contract/openapi/schema_kit.ts` writes: type (a name
3 * or a list), enum, required, properties, items, oneOf, anyOf and `$ref` into `components.schemas`.
4 * Strict where the published document is open: a property a schema does not name is an error, so a
5 * field a handler gains without its line in the schema fails the test that calls it (#17911).
6 */
7
8 type Json = unknown;
9 type Node = Record<string, unknown>;
10
11 const kind = (v: Json): string => (v === null ? "null" : Array.isArray(v) ? "array" : Number.isInteger(v) ? "integer" : typeof v);
12
13 /** The problems of `value` against `schema`, each prefixed by where it is; none when it fits. */
14 export function misfits(value: Json, schema: Node, components: Record<string, Node>, at = "$"): string[] {
15 if (typeof schema.$ref === "string") {
16 const named = components[schema.$ref.replace("#/components/schemas/", "")];
17 return named === undefined ? [`${at}: ${schema.$ref} names no schema`] : misfits(value, named, components, at);
18 }
19 for (const key of ["anyOf", "oneOf"] as const) {
20 const options = schema[key];
21 if (Array.isArray(options)) {
22 const tried = options.map((o) => misfits(value, o as Node, components, at));
23 return tried.some((t) => t.length === 0) ? [] : [`${at}: fits none of ${key}: ${tried.map((t) => t.join("; ")).join(" | ")}`];
24 }
25 }
26 const out: string[] = [];
27 const types = schema.type === undefined ? undefined : ([] as string[]).concat(schema.type as string | string[]);
28 const have = kind(value);
29 if (types !== undefined && !types.some((t) => t === have || (t === "number" && have === "integer"))) return [`${at}: is ${have}, not ${types.join("|")}`];
30 if (Array.isArray(schema.enum) && !schema.enum.includes(value)) out.push(`${at}: ${JSON.stringify(value)} is not one of ${JSON.stringify(schema.enum)}`);
31 if (have === "array" && schema.items !== undefined)
32 (value as Json[]).forEach((v, i) => out.push(...misfits(v, schema.items as Node, components, `${at}[${i}]`)));
33 if (have === "object") {
34 const given = value as Record<string, Json>;
35 const props = (schema.properties ?? {}) as Record<string, Node>;
36 for (const k of (schema.required ?? []) as string[]) if (!(k in given)) out.push(`${at}: lacks ${k}`);
37 for (const [k, v] of Object.entries(given)) {
38 if (k in props) out.push(...misfits(v, props[k]!, components, `${at}.${k}`));
39 else if (schema.properties !== undefined) out.push(`${at}: has ${k}, which the schema does not name`);
40 }
41 }
42 return out;
43 }
test/openapi-errors.test.ts +2 −1
@@ -94,7 +94,8 @@ test("every non-2xx response of every route references it, directly or through a
9494 const shared = res.$ref?.replace("#/components/responses/", "");
9595 const held = shared === undefined ? res : doc.components.responses[shared];
9696 expect({ path, method, code, ref: held?.content?.["application/json"]?.schema?.$ref }).toEqual({
97 path, method, code, ref: "#/components/schemas/Error",
97 // A 413 on the contents routes is the file's own shape, not an error (#17911).
98 path, method, code, ref: code === "413" && path.includes("/contents") ? "#/components/schemas/ContentsTooLarge" : "#/components/schemas/Error",
9899 });
99100 }
100101 }
test/openapi-oa-pull-checks.test.ts +3 −1
@@ -12,7 +12,9 @@ test("GET and POST …/pulls/{number}/checks are described", () => {
1212 expect(paths[P]?.post?.security).toEqual([{ token: [] }, { oauth2: ["rw"] }]);
1313 const ok = (m: string, code: string) =>
1414 paths[P]?.[m]?.responses?.[code]?.content?.["application/json"]?.schema?.properties;
15 expect(Object.keys(ok("get", "200"))).toEqual(["head", "state", "required", "run", "runs"]);
15 const checks = openapi("http://x", "1", "admin") as { components: { schemas: Record<string, { properties: object }> } };
16 expect(paths[P]?.get?.responses?.["200"]?.content?.["application/json"]?.schema).toEqual({ $ref: "#/components/schemas/Checks" });
17 expect(Object.keys(checks.components.schemas.Checks!.properties)).toEqual(["head", "state", "required", "why", "run", "looks", "runs"]);
1618 expect(Object.keys(ok("post", "202"))).toEqual(["run", "place", "says"]);
1719 expect(JSON.stringify(paths[P]?.post)).toContain("no_check_declared");
1820 });
test/openapi-schemas.test.ts added +181
@@ -0,0 +1,181 @@
1 /**
2 * The routes a client generates its types from (#17911) answer what the document says: each call
3 * below is made for real and its body held to the operation's published schema, strictly, so a
4 * field added to a handler without its line in `contract/openapi/schemas/` fails here by name. A
5 * request body the document declares is held to its schema the same way.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { openIssue } from "../src/actions/issues.ts";
12 import { openPull } from "../src/actions/pulls.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { openapi } from "../src/contract/openapi.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { repoDir } from "../src/git/repos.ts";
18 import { createUser } from "../src/core/users.ts";
19 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21 import { misfits } from "./helpers/json_schema.ts";
22
23 quietLogs();
24
25 type Node = Record<string, unknown>;
26 const doc = openapi("http://forge.test", "1", "admin") as { paths: Record<string, Record<string, Node>>; components: { schemas: Record<string, Node> } };
27 const R = "/api/v1/repos/{owner}/{name}";
28
29 let dir: string;
30 let app: App;
31 let http: ForgeHttp;
32 let token: string;
33 let pull: number;
34 let issue: number;
35
36 beforeAll(async () => {
37 dir = await mkdtemp(join(tmpdir(), "forge-openapi-schemas-"));
38 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
39 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
40 if (!made.ok) throw new Error(made.error);
41 const alice = made.value;
42 const repo = await createRepo(app, alice, { name: "lib", visibility: "public" });
43 if (!repo.ok) throw new Error(String(repo.error));
44 const first = await commitToBranch(app, alice, repo.value, { message: "Start", files: [{ path: "README.md", content: "# lib\n" }, { path: "src/a.ts", content: "x\n" }] });
45 if (!first.ok) throw new Error(JSON.stringify(first.error));
46 const feat = await commitToBranch(app, alice, repo.value, { branch: "feat", message: "A change", files: [{ path: "a.md", content: "hi\n" }] });
47 if (!feat.ok) throw new Error(JSON.stringify(feat.error));
48 const opened = await openPull(app, alice, repo.value, { title: "Mine", baseBranch: "main", headBranch: "feat" });
49 if (!opened.ok) throw new Error(String(opened.error));
50 pull = opened.value.number;
51 const filed = openIssue(app, alice, repo.value, { title: "An issue" });
52 if (!filed.ok) throw new Error(String(filed.error));
53 issue = filed.value.number;
54 token = createToken(app.db, alice.id, "t", "rw").token;
55 http = forgeHttp(app);
56 }, 120_000);
57
58 afterAll(async () => {
59 http?.close();
60 app.close();
61 await rm(dir, { recursive: true, force: true });
62 });
63
64 /**
65 * Calls `method` `concrete` as the operation `template`, and returns what the document's schema
66 * finds wrong with the request and the answer.
67 */
68 async function check(method: string, template: string, concrete: string, body?: unknown): Promise<{ status: number; json: unknown; problems: string[] }> {
69 const op = doc.paths[template]?.[method];
70 if (op === undefined) throw new Error(`${method} ${template} is not in the document`);
71 const problems: string[] = [];
72 const requestSchema = ((op.requestBody as Node | undefined)?.content as Node | undefined)?.["application/json"] as { schema: Node } | undefined;
73 if (body !== undefined && requestSchema !== undefined) problems.push(...misfits(body, requestSchema.schema, doc.components.schemas, "request"));
74 const res = await http.handle(
75 new Request(`http://forge.test${concrete}`, {
76 method: method.toUpperCase(),
77 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
78 body: body === undefined ? undefined : JSON.stringify(body),
79 }),
80 );
81 const json = (await res.json()) as unknown;
82 const declared = (op.responses as Record<string, Node>)[String(res.status)];
83 const schema = ((declared?.content as Node | undefined)?.["application/json"] as { schema: Node } | undefined)?.schema;
84 if (schema === undefined) problems.push(`${res.status} has no declared schema`);
85 else problems.push(...misfits(json, schema, doc.components.schemas, "response"));
86 return { status: res.status, json, problems };
87 }
88
89 const repoAt = (path: string) => `/api/v1/repos/alice/lib${path}`;
90
91 test("the document's own pointers all resolve, and its schemas are objects a generator can name", () => {
92 const text = JSON.stringify(doc);
93 const named = new Set(Object.keys(doc.components.schemas));
94 for (const m of text.matchAll(/#\/components\/schemas\/(\w+)/g)) expect(named.has(m[1]!), m[1]).toBe(true);
95 expect(Object.keys(doc.components.schemas).length).toBeGreaterThan(20);
96 });
97
98 test("a pull, its list, files, checks, reviews, verdicts, comment and merge answer their schemas", async () => {
99 expect((await check("get", `${R}/pulls/{number}`, repoAt(`/pulls/${pull}`))).problems).toEqual([]);
100 expect((await check("get", `${R}/pulls/{number}`, repoAt(`/pulls/${pull}?diff=0`))).problems).toEqual([]);
101 expect((await check("get", `${R}/pulls`, repoAt("/pulls"))).problems).toEqual([]);
102 expect((await check("get", `${R}/pulls/{number}/files`, repoAt(`/pulls/${pull}/files`))).problems).toEqual([]);
103 expect((await check("get", `${R}/pulls/{number}/checks`, repoAt(`/pulls/${pull}/checks`))).problems).toEqual([]);
104 const line = await http.handle(
105 new Request(`http://forge.test${repoAt(`/pulls/${pull}/reviews`)}`, {
106 method: "POST",
107 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
108 body: JSON.stringify({ path: "a.md", line: 1, side: "new", body: "x" }),
109 }),
110 );
111 expect(line.status).toBe(201);
112 expect((await check("get", `${R}/pulls/{number}/reviews`, repoAt(`/pulls/${pull}/reviews`))).problems).toEqual([]);
113 const verdict = await check("post", `${R}/pulls/{number}/review-states`, repoAt(`/pulls/${pull}/review-states`), { state: "commented", body: "ok" });
114 expect([verdict.status, verdict.problems]).toEqual([201, []]);
115 expect((await check("get", `${R}/pulls/{number}/review-states`, repoAt(`/pulls/${pull}/review-states`))).problems).toEqual([]);
116 const said = await check("post", `${R}/pulls/{number}/comments`, repoAt(`/pulls/${pull}/comments`), { body: "hi" });
117 expect([said.status, said.problems]).toEqual([201, []]);
118 const merged = await check("post", `${R}/pulls/{number}/merge`, repoAt(`/pulls/${pull}/merge`), {});
119 expect([merged.status, merged.problems]).toEqual([200, []]);
120 expect((await check("get", `${R}/pulls/{number}`, repoAt(`/pulls/${pull}?diff=0`))).problems).toEqual([]);
121 });
122
123 test("an issue and its comment answer their schemas", async () => {
124 expect((await check("get", `${R}/issues/{number}`, repoAt(`/issues/${issue}`))).problems).toEqual([]);
125 const said = await check("post", `${R}/issues/{number}/comments`, repoAt(`/issues/${issue}/comments`), { body: "hi" });
126 expect([said.status, said.problems]).toEqual([201, []]);
127 expect((await check("get", `${R}/issues/{number}`, repoAt(`/issues/${issue}`))).problems).toEqual([]);
128 });
129
130 test("contents, commits and branches answer their schemas, a directory and a file alike", async () => {
131 for (const path of ["/contents", "/contents/src"]) expect((await check("get", `${R}/contents`, repoAt(path))).problems, path).toEqual([]);
132 expect((await check("get", `${R}/contents/{path}`, repoAt("/contents/README.md"))).problems).toEqual([]);
133 expect((await check("get", `${R}/contents/{path}`, repoAt("/contents/src"))).problems).toEqual([]);
134 expect((await check("get", `${R}/commits`, repoAt("/commits"))).problems).toEqual([]);
135 expect((await check("get", `${R}/commits/{oid}`, repoAt("/commits/main"))).problems).toEqual([]);
136 expect((await check("get", `${R}/branches`, repoAt("/branches"))).problems).toEqual([]);
137 });
138
139 test("a file over 5 MB answers 413 with the shape the document declares for it", async () => {
140 // The write routes refuse such a file, so the branch is made in git as a push would make it.
141 const git = async (input: string | undefined, ...args: string[]): Promise<string> => {
142 const proc = Bun.spawn(["git", "-C", repoDir(join(dir, "repos"), "alice", "lib"), ...args], {
143 stdin: input === undefined ? "ignore" : new Blob([input]),
144 stdout: "pipe",
145 env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" },
146 });
147 const out = await new Response(proc.stdout).text();
148 expect(await proc.exited).toBe(0);
149 return out.trim();
150 };
151 const blob = await git("x".repeat(5_000_001), "hash-object", "-w", "--stdin");
152 const tree = await git(`100644 blob ${blob}\tbig.txt\n`, "mktree");
153 const commit = await git(undefined, "commit-tree", tree, "-m", "Big");
154 await git(undefined, "update-ref", "refs/heads/big", commit);
155 const res = await check("get", `${R}/contents/{path}`, repoAt("/contents/big.txt?ref=big"));
156 expect([res.status, res.problems]).toEqual([413, []]);
157 expect(res.json).toEqual({ type: "file", tooLarge: true, size: 5_000_001 });
158 // Both contents routes declare it: the bare one reads the root tree only (it takes no `path`).
159 for (const template of [`${R}/contents`, `${R}/contents/{path}`])
160 expect((doc.paths[template]!.get!.responses as Record<string, Node>)["413"]).toMatchObject({ content: { "application/json": { schema: { $ref: "#/components/schemas/ContentsTooLarge" } } } });
161 });
162
163 test("writing files and editing answer their schemas, and take the bodies they declare", async () => {
164 const wrote = await check("post", `${R}/contents`, repoAt("/contents"), { branch: "w1", message: "m", files: [{ path: "z.md", content: "z" }] });
165 expect([wrote.status, wrote.problems]).toEqual([201, []]);
166 const opened = await check("post", `${R}/edits`, repoAt("/edits"), { newBranch: "w2", message: "m", files: [{ path: "y.md", content: "z" }], openPull: { title: "T" } });
167 expect([opened.status, opened.problems]).toEqual([201, []]);
168 const deleted = await check("post", `${R}/edits`, repoAt("/edits"), { branch: "w1", message: "m", files: [{ path: "z.md", content: null }] });
169 expect([deleted.status, deleted.problems]).toEqual([201, []]);
170 });
171
172 test("conversations and a message to the forge's agent answer their schemas", async () => {
173 const made = await check("post", "/api/v1/conversations", "/api/v1/conversations", { title: "Hello" });
174 expect([made.status, made.problems]).toEqual([201, []]);
175 const id = (made.json as { conversation: { id: string } }).conversation.id;
176 expect((await check("get", "/api/v1/conversations", "/api/v1/conversations")).problems).toEqual([]);
177 const renamed = await check("patch", "/api/v1/conversations/{id}", `/api/v1/conversations/${id}`, { title: "Renamed", archived: false });
178 expect([renamed.status, renamed.problems]).toEqual([200, []]);
179 const sent = await check("post", "/api/v1/conversation/messages", "/api/v1/conversation/messages", { text: "hello", conversation: id });
180 expect([sent.status, sent.problems]).toEqual([202, []]);
181 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs