Skip to content
Merged
36 changes: 36 additions & 0 deletions packages/api-client/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,4 +275,40 @@ export async function apiDelete<T>(
return handleResponse<T>(res);
}

/** A write's method and body, for the APIs built on `ApiRequest`. */
export interface ApiRequestInit {
method: "POST" | "PUT";
/** JSON text, so a host's own fetch wrapper can send it unchanged. */
body?: string;
}

/**
* The one request primitive the `create*Api` factories need: a path relative
* to the host's API base, its query already on it. A host with its own fetch
* layer (auth, timeouts, errors) passes its wrapper; this package passes
* `apiRequest`.
*/
export type ApiRequest = <T>(path: string, init?: ApiRequestInit) => Promise<T>;

/** `ApiRequest` over this client's base URL, token and fetch. */
export function apiRequest<T>(path: string, init?: ApiRequestInit): Promise<T> {
if (!init) return apiGet<T>(path);
return init.method === "PUT"
? apiPut<T>(path, undefined, init)
: apiPost<T>(path, undefined, init);
}

/** *path* with the defined *params* as its query, encoded as `apiGet` encodes them. */
export function withQuery(
path: string,
params: Record<string, string | number | boolean | null | undefined>,
): string {
const query = new URLSearchParams();
for (const [k, v] of Object.entries(params)) {
if (v !== undefined && v !== null) query.set(k, String(v));
}
const text = query.toString();
return text ? `${path}?${text}` : path;
}

export { buildHeaders };
77 changes: 77 additions & 0 deletions packages/api-client/src/reports.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { afterEach, describe, expect, it } from "vitest";

import { configureApiClient, createAdapterFetch, type ApiRequestInit } from "./client";
import {
createFirstLookApi,
firstLookMarkdownPath,
getFirstLook,
getFirstLookPrompt,
markFirstLookItem,
rewriteFirstLook,
} from "./reports";

function serve() {
const sent: { url: string; method?: string | undefined; body?: string }[] = [];
configureApiClient({
baseUrl: "http://127.0.0.1:7337",
fetch: createAdapterFetch(async (url, init) => {
sent.push({
url: url.replace("http://127.0.0.1:7337", ""),
method: init.method,
...(init.body !== undefined ? { body: init.body } : {}),
});
return { status: 200, ok: true, headers: {}, text: "{}" };
}),
});
return sent;
}

const ROOT = "/api/repos/r1/reports/first-look";

describe("repo report requests", () => {
afterEach(() => configureApiClient({ baseUrl: "" }));

it("reads the report and its prompts with the flavor and target", async () => {
const sent = serve();
await getFirstLook("r1", { flavor: "cursor" });
await getFirstLookPrompt("r1", { section: "security" }, "generic");
await getFirstLookPrompt("r1", null, "generic");
expect(sent).toEqual([
{ url: `${ROOT}?flavor=cursor`, method: "GET" },
{ url: `${ROOT}/prompt?flavor=generic&section=security`, method: "GET" },
{ url: `${ROOT}/prompt?flavor=generic`, method: "GET" },
]);
});

it("writes a mark and a rewrite", async () => {
const sent = serve();
await markFirstLookItem("r1", "sec/1", { status: "done" });
await rewriteFirstLook("r1", { flavor: "generic" });
expect(sent).toEqual([
{ url: `${ROOT}/items/sec%2F1/mark`, method: "PUT", body: '{"status":"done"}' },
{ url: `${ROOT}/rewrite?flavor=generic`, method: "POST" },
]);
expect(firstLookMarkdownPath("r1")).toBe(`${ROOT}/export.md`);
});

it("builds a host's client over its own request and routes", async () => {
const calls: [string, ApiRequestInit | undefined][] = [];
const api = createFirstLookApi(
async <T,>(path: string, init?: ApiRequestInit) => {
calls.push([path, init]);
return {} as T;
},
(id) => `/snapshots/${id}/report`,
);
await api.getFirstLook("s1");
await api.markFirstLookItem("s1", "a", { status: "ack", reason: "known" });
expect(calls).toEqual([
["/snapshots/s1/report", undefined],
[
"/snapshots/s1/report/items/a/mark",
{ method: "PUT", body: '{"status":"ack","reason":"known"}' },
],
]);
expect(api.firstLookMarkdownPath("s1")).toBe("/snapshots/s1/report/export.md");
});
});
80 changes: 40 additions & 40 deletions packages/api-client/src/reports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,50 +4,50 @@ import type {
FirstLookMarkResponse,
FirstLookPage,
} from "@repowise-dev/types/first-look";
import { apiGet, apiPost, apiPut } from "./client";
import { apiRequest, withQuery, type ApiRequest } from "./client";

const firstLook = (repoId: string) => `/api/repos/${repoId}/reports/first-look`;
/**
* The repo report requests over *request*, under *base*: the report root for
* a repository (`/api/repos/{id}/reports/first-look` here). A host with its
* own fetch layer and routes builds its client from this, so paths, query
* names and types stay in one place.
*/
export function createFirstLookApi(request: ApiRequest, base: (repoId: string) => string) {
return {
/** The repo report now, each item's status against the first look, and the open items' prompt for `flavor`. */
getFirstLook: (repoId: string, opts: { flavor?: AgentPromptFlavor } = {}) =>
request<FirstLookPage>(withQuery(base(repoId), { flavor: opts.flavor })),

/** The repo report now, each item's status against the first look, and the open items' prompt for `flavor`. */
export async function getFirstLook(
repoId: string,
opts: { flavor?: AgentPromptFlavor } = {},
): Promise<FirstLookPage> {
return apiGet<FirstLookPage>(firstLook(repoId), { flavor: opts.flavor });
}
/** One item's prompt, one section's, or the whole report's (null), rendered by core for `flavor`. */
getFirstLookPrompt: (
repoId: string,
target: { item: string } | { section: string } | null,
flavor: AgentPromptFlavor,
) =>
request<AgentPromptResponse>(withQuery(`${base(repoId)}/prompt`, { flavor, ...(target ?? {}) })),

/** One item's prompt, one section's, or the whole report's (null), rendered by core for `flavor`. */
export async function getFirstLookPrompt(
repoId: string,
target: { item: string } | { section: string } | null,
flavor: AgentPromptFlavor,
): Promise<AgentPromptResponse> {
return apiGet<AgentPromptResponse>(`${firstLook(repoId)}/prompt`, { flavor, ...(target ?? {}) });
}
/** Done, acknowledged, a false positive or snoozed: what `repowise mark` records. */
markFirstLookItem: (repoId: string, itemId: string, body: FirstLookMarkRequest) =>
request<FirstLookMarkResponse>(`${base(repoId)}/items/${encodeURIComponent(itemId)}/mark`, {
method: "PUT",
body: JSON.stringify(body),
}),

/** Done, acknowledged, a false positive or snoozed: what `repowise mark` records. */
export async function markFirstLookItem(
repoId: string,
itemId: string,
body: FirstLookMarkRequest,
): Promise<FirstLookMarkResponse> {
return apiPut<FirstLookMarkResponse>(
`${firstLook(repoId)}/items/${encodeURIComponent(itemId)}/mark`,
body,
);
}
/** The report as a Markdown download, relative to the API base. */
firstLookMarkdownPath: (repoId: string) => `${base(repoId)}/export.md`,

/** The report as a Markdown download, relative to the API base. */
export function firstLookMarkdownPath(repoId: string): string {
return `${firstLook(repoId)}/export.md`;
/** Write the report again with the repository's model: one call. */
rewriteFirstLook: (repoId: string, opts: { flavor?: AgentPromptFlavor } = {}) =>
request<FirstLookPage>(withQuery(`${base(repoId)}/rewrite`, { flavor: opts.flavor }), {
method: "POST",
}),
};
}

/** Write the report again with the repository's model: one call. */
export async function rewriteFirstLook(
repoId: string,
opts: { flavor?: AgentPromptFlavor } = {},
): Promise<FirstLookPage> {
return apiPost<FirstLookPage>(`${firstLook(repoId)}/rewrite`, undefined, undefined, {
flavor: opts.flavor,
});
}
export const {
getFirstLook,
getFirstLookPrompt,
markFirstLookItem,
firstLookMarkdownPath,
rewriteFirstLook,
} = createFirstLookApi(apiRequest, (repoId) => `/api/repos/${repoId}/reports/first-look`);
70 changes: 47 additions & 23 deletions packages/api-client/src/runtime-evidence.test.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,65 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it } from "vitest";

const apiGet = vi.fn();
vi.mock("./client", () => ({
apiGet: (...args: unknown[]) => apiGet(...args),
}));
import { configureApiClient, createAdapterFetch, type ApiRequest } from "./client";
import {
createRuntimeEvidenceApi,
getEvidenceTests,
getMeasured,
getMeasuredFunctions,
} from "./runtime-evidence";

import { getEvidenceTests, getMeasured, getMeasuredFunctions } from "./runtime-evidence";
function serve() {
const sent: string[] = [];
configureApiClient({
baseUrl: "http://127.0.0.1:7337",
fetch: createAdapterFetch(async (url) => {
sent.push(url.replace("http://127.0.0.1:7337", ""));
return { status: 200, ok: true, headers: {}, text: "{}" };
}),
});
return sent;
}

describe("runtime evidence requests", () => {
beforeEach(() => {
apiGet.mockReset();
apiGet.mockResolvedValue({});
});
afterEach(() => configureApiClient({ baseUrl: "" }));

it("sends the run and limit under the server's names", async () => {
const sent = serve();
await getMeasured("repo", { runId: "r1", limit: 0 });
expect(apiGet).toHaveBeenCalledWith("/api/repos/repo/evidence/measured", {
run_id: "r1",
limit: 0,
});
expect(sent).toEqual(["/api/repos/repo/evidence/measured?run_id=r1&limit=0"]);
});

it("asks for one function or one file", async () => {
const sent = serve();
await getMeasuredFunctions("repo", { symbolId: "src/a.py::f" });
expect(apiGet).toHaveBeenLastCalledWith("/api/repos/repo/evidence/functions", {
symbol_id: "src/a.py::f",
file: undefined,
});
await getMeasuredFunctions("repo", { file: "src/a.py" });
expect(apiGet).toHaveBeenLastCalledWith("/api/repos/repo/evidence/functions", {
symbol_id: undefined,
file: "src/a.py",
});
expect(sent).toEqual([
"/api/repos/repo/evidence/functions?symbol_id=src%2Fa.py%3A%3Af",
"/api/repos/repo/evidence/functions?file=src%2Fa.py",
]);
});

it("asks for the slowest tests with a limit", async () => {
const sent = serve();
await getEvidenceTests("repo", { limit: 10 });
expect(apiGet).toHaveBeenCalledWith("/api/repos/repo/evidence/tests", { limit: 10 });
await getEvidenceTests("repo");
expect(sent).toEqual(["/api/repos/repo/evidence/tests?limit=10", "/api/repos/repo/evidence/tests"]);
});

it("builds a host's client over its own request and routes", async () => {
const paths: string[] = [];
const request: ApiRequest = async <T,>(path: string) => {
paths.push(path);
return {} as T;
};
const api = createRuntimeEvidenceApi(request, (id) => `/snapshots/${id}/evidence`);
await api.getEvidenceStatus("s1");
await api.listEvidenceRuns("s1");
await api.getMeasured("s1", { limit: 5 });
expect(paths).toEqual([
"/snapshots/s1/evidence/status",
"/snapshots/s1/evidence/runs",
"/snapshots/s1/evidence/measured?limit=5",
]);
});
});
85 changes: 46 additions & 39 deletions packages/api-client/src/runtime-evidence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type {
MeasuredResponse,
SuiteCostResponse,
} from "@repowise-dev/types/runtime-evidence";
import { apiGet } from "./client";
import { apiRequest, withQuery, type ApiRequest } from "./client";

export type {
EvidenceRunSummary,
Expand All @@ -28,46 +28,53 @@ export type {
SuiteCostResponse,
} from "@repowise-dev/types/runtime-evidence";

/** The newest run of every workload, and whether anything is ranked. */
export async function getEvidenceStatus(repoId: string): Promise<EvidenceStatusResponse> {
return apiGet<EvidenceStatusResponse>(`/api/repos/${repoId}/evidence/status`);
}
/**
* The runtime-evidence requests over *request*, under *base*: the evidence
* root for a repository (`/api/repos/{id}/evidence` here). A host with its own
* fetch layer and routes builds its client from this, so paths, query names
* and types stay in one place.
*/
export function createRuntimeEvidenceApi(request: ApiRequest, base: (repoId: string) => string) {
return {
/** The newest run of every workload, and whether anything is ranked. */
getEvidenceStatus: (repoId: string) =>
request<EvidenceStatusResponse>(`${base(repoId)}/status`),

/** Every stored run, newest first. */
export async function listEvidenceRuns(repoId: string): Promise<EvidenceRunsResponse> {
return apiGet<EvidenceRunsResponse>(`/api/repos/${repoId}/evidence/runs`);
}
/** Every stored run, newest first. */
listEvidenceRuns: (repoId: string) => request<EvidenceRunsResponse>(`${base(repoId)}/runs`),

/** Each workload's newest run with its ranked functions; `runId` keeps one run. */
export async function getMeasured(
repoId: string,
opts: {
runId?: string;
/** Rows per run, 0-100; the server defaults to 10. */
limit?: number;
} = {},
): Promise<MeasuredResponse> {
return apiGet<MeasuredResponse>(`/api/repos/${repoId}/evidence/measured`, {
run_id: opts.runId,
limit: opts.limit,
});
}
/** Each workload's newest run with its ranked functions; `runId` keeps one run. */
getMeasured: (
repoId: string,
opts: {
runId?: string;
/** Rows per run, 0-100; the server defaults to 10. */
limit?: number;
} = {},
) =>
request<MeasuredResponse>(
withQuery(`${base(repoId)}/measured`, { run_id: opts.runId, limit: opts.limit }),
),

/** The measured view of one function or of every function in a file. */
export async function getMeasuredFunctions(
repoId: string,
target: { symbolId: string; file?: never } | { file: string; symbolId?: never },
): Promise<MeasuredFunctionsResponse> {
return apiGet<MeasuredFunctionsResponse>(`/api/repos/${repoId}/evidence/functions`, {
symbol_id: target.symbolId,
file: target.file,
});
}
/** The measured view of one function or of every function in a file. */
getMeasuredFunctions: (
repoId: string,
target: { symbolId: string; file?: never } | { file: string; symbolId?: never },
) =>
request<MeasuredFunctionsResponse>(
withQuery(`${base(repoId)}/functions`, { symbol_id: target.symbolId, file: target.file }),
),

/** The slowest timed tests and the test time per production file, from stored JUnit timings. */
export async function getEvidenceTests(
repoId: string,
opts: { limit?: number } = {},
): Promise<SuiteCostResponse> {
return apiGet<SuiteCostResponse>(`/api/repos/${repoId}/evidence/tests`, { limit: opts.limit });
/** The slowest timed tests and the test time per production file, from stored JUnit timings. */
getEvidenceTests: (repoId: string, opts: { limit?: number } = {}) =>
request<SuiteCostResponse>(withQuery(`${base(repoId)}/tests`, { limit: opts.limit })),
};
}

export const {
getEvidenceStatus,
listEvidenceRuns,
getMeasured,
getMeasuredFunctions,
getEvidenceTests,
} = createRuntimeEvidenceApi(apiRequest, (repoId) => `/api/repos/${repoId}/evidence`);
Loading
Loading