cloud / scripts / cloud-rehearsal / cloudflare-routes.tsmain at aacbc74
// cloudflare-routes.ts — WHICH CALLS ARE CLOUDFLARE'S: the routes of Cloudflare's public API spec
// (https://github.com/cloudflare/api-schemas, about 28 MB), read once into a small index. The fake
// refuses a call that is no route with Cloudflare's own 404, and tells the agent what the spec
// says about a route it must write a rule for.
//
// The spec is downloaded into a folder of its own (`cacheDir`), and only ever parsed as JSON.
// `extraRoutes` are routes that a real install was seen to call, for those the public spec lacks.
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
const METHODS = ["get", "post", "put", "patch", "delete"];
const MOST_ABOUT_CHARACTERS = 6000;
type Route = { method: string; template: string };
export async function loadCloudflareRoutes(input: { cacheDir: string; extraRoutes: Route[] }) {
const specFile = join(input.cacheDir, "openapi.json");
const indexFile = join(input.cacheDir, "routes.json");
if (!existsSync(specFile)) {
mkdirSync(input.cacheDir, { recursive: true });
const response = await fetch(
"https://raw.githubusercontent.com/cloudflare/api-schemas/main/openapi.json",
);
if (!response.ok) throw new Error(`Cloudflare's API spec did not download: ${response.status}`);
writeFileSync(specFile, Buffer.from(await response.arrayBuffer()));
}
// `any`: an OpenAPI document: read by path, never trusted for more than text
const readSpec = (): { paths: Record<string, Record<string, any>> } =>
JSON.parse(readFileSync(specFile, "utf8"));
if (!existsSync(indexFile)) {
const routes = Object.entries(readSpec().paths).flatMap(([template, operations]) =>
METHODS.filter((method) => method in operations).map((method) => ({
method: method.toUpperCase(),
template,
})),
);
writeFileSync(indexFile, JSON.stringify(routes));
}
const fromSpec: Route[] = JSON.parse(readFileSync(indexFile, "utf8"));
// a template's `{name}` is one part of a path
const routes = [...fromSpec, ...input.extraRoutes].map((route) => ({
...route,
pattern: new RegExp(
`^${route.template.replace(/[.*+?^$()|[\]\\]/g, "\\$&").replace(/\{[^/}]+\}/g, "[^/]+")}$`,
),
}));
const find = (method: string, path: string) =>
routes.find((route) => route.method === method && route.pattern.test(path));
return {
count: routes.length,
has: (method: string, path: string) => Boolean(find(method, path)),
/** What the spec says about the route of `method path`, for the agent: the operation, with
* the schemas it names written out to four levels, cut to a size a prompt can carry. */
about(method: string, path: string) {
const route = find(method, path);
if (!route) return "";
const spec = readSpec();
const operation = spec.paths[route.template]?.[method.toLowerCase()];
if (!operation)
return `${method} ${route.template}: seen in a real install; Cloudflare's public spec does not describe it.`;
const resolve = (value: unknown, depth: number): unknown => {
if (Array.isArray(value)) return value.map((item) => resolve(item, depth));
if (value instanceof Object) {
const ref = "$ref" in value ? value.$ref : null;
if (typeof ref === "string" && ref.startsWith("#/")) {
if (depth === 0) return { $ref: ref };
// a pointer into the document: "#/components/schemas/x" is spec.components.schemas.x
const target = ref
.slice(2)
.split("/")
.reduce<unknown>(
(at, key) => (at instanceof Object ? Reflect.get(at, key) : undefined),
spec,
);
return resolve(target, depth - 1);
}
return Object.fromEntries(
Object.entries(value).map(([key, inner]) => [key, resolve(inner, depth)]),
);
}
return value;
};
const text = JSON.stringify(
{
route: `${method} ${route.template}`,
summary: operation.summary,
description: operation.description,
requestBody: resolve(operation.requestBody, 4),
responses: resolve(operation.responses, 4),
},
null,
1,
);
return text.length > MOST_ABOUT_CHARACTERS
? `${text.slice(0, MOST_ABOUT_CHARACTERS)}\n…(cut)`
: text;
},
};
}
/** The routes of api.cloudflare.com in a list of a real install's calls, one `METHOD<tab>host<tab>path`
* a line, with `:hex`, `:uuid` and `<stage>` where a real run had an id (iterate-config's
* apps/cloudflare-simulator/test/real-routes.txt). */
export function routesOfARealInstall(text: string): Route[] {
return text
.split("\n")
.map((line) => line.split("\t"))
.filter(
([method, host, path]) =>
method && host === "api.cloudflare.com" && path?.startsWith("/client/v4/"),
)
.map(([method = "", , path = ""]) => ({
method,
template: path.slice("/client/v4".length).replace(/:[a-z]+|<[a-z]+>/g, "{id}"),
}));
}