openapi.test.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. import { describe, expect, test } from "bun:test"
  2. import { Effect, Layer, Option } from "effect"
  3. import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
  4. import { CodeMode, OpenAPI, Tool } from "../src/index.js"
  5. import { inputTypeScript, outputTypeScript } from "../src/tool-schema.js"
  6. const baseUrl = "http://localhost:4096"
  7. type Document = OpenAPI.Document
  8. type Recorded = {
  9. readonly method: string
  10. readonly url: string
  11. readonly headers: Record<string, string>
  12. readonly body: unknown
  13. }
  14. const opencodeSpec = async (): Promise<Document> => {
  15. return Bun.file(new URL("./fixtures/opencode-v2-openapi.json", import.meta.url)).json() as Promise<Document>
  16. }
  17. const happyPathSpec = async (): Promise<Document> => {
  18. return Bun.file(new URL("./fixtures/openapi-happy-path.json", import.meta.url)).json() as Promise<Document>
  19. }
  20. const isRecord = (value: unknown): value is Record<string, unknown> =>
  21. typeof value === "object" && value !== null && !Array.isArray(value)
  22. const toolAt = (tools: unknown, name: string) =>
  23. name.split(".").reduce<unknown>((current, segment) => (isRecord(current) ? current[segment] : undefined), tools)
  24. const recordingClient = (respond: (request: HttpClientRequest.HttpClientRequest) => Response) => {
  25. const requests: Array<Recorded> = []
  26. const layer = Layer.succeed(HttpClient.HttpClient)(
  27. HttpClient.make((request) =>
  28. Effect.gen(function* () {
  29. const body =
  30. request.body._tag === "Uint8Array" ? JSON.parse(new TextDecoder().decode(request.body.body)) : undefined
  31. const url = Option.map(HttpClientRequest.toUrl(request), (resolved) => resolved.toString())
  32. requests.push({
  33. method: request.method,
  34. url: Option.getOrElse(url, () => request.url),
  35. headers: { ...request.headers },
  36. body,
  37. })
  38. return HttpClientResponse.fromWeb(request, respond(request))
  39. }),
  40. ),
  41. )
  42. return { requests, layer }
  43. }
  44. const json = (value: unknown, status = 200) =>
  45. new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json" } })
  46. const singleOperation = (operation: Record<string, unknown>, method = "get"): Document => ({
  47. openapi: "3.1.0",
  48. paths: { "/test": { [method]: { operationId: "test", responses: { 200: { description: "Success" } }, ...operation } } },
  49. })
  50. describe("OpenAPI.fromSpec", () => {
  51. test("covers a representative API from generation through execution", async () => {
  52. const resolutions: Array<string> = []
  53. const client = recordingClient((request) => {
  54. const url = Option.getOrElse(HttpClientRequest.toUrl(request), () => new URL(request.url))
  55. if (request.method === "POST") {
  56. return new Response(
  57. JSON.stringify({ id: "user-2", name: "Grace", email: "grace@example.test", role: "admin" }),
  58. { status: 201, headers: { "content-type": "application/vnd.example+json" } },
  59. )
  60. }
  61. if (request.method === "DELETE") return new Response(null, { status: 204 })
  62. if (url.pathname === "/search") {
  63. return new Response("2 matches", { headers: { "content-type": "text/plain" } })
  64. }
  65. return json({ id: "user-1", name: "Ada", email: "ada@example.test", role: "member" })
  66. })
  67. const api = OpenAPI.fromSpec({
  68. spec: await happyPathSpec(),
  69. baseUrl,
  70. auth: {
  71. resolve: ({ name }) => {
  72. resolutions.push(name)
  73. return Effect.succeed(
  74. name === "BearerAuth"
  75. ? { type: "bearer", token: "bearer-secret" }
  76. : { type: "apiKey", value: "api-secret" },
  77. )
  78. },
  79. },
  80. })
  81. const get = toolAt(api.tools, "users.get")
  82. const create = toolAt(api.tools, "users.create")
  83. const search = toolAt(api.tools, "search.run")
  84. const remove = toolAt(api.tools, "users.remove")
  85. expect(api.skipped).toEqual([])
  86. if (!Tool.isDefinition(get) || !Tool.isDefinition(create) || !Tool.isDefinition(search) || !Tool.isDefinition(remove)) {
  87. throw new Error("happy-path fixture did not generate every operation")
  88. }
  89. expect(inputTypeScript(get)).toBe(
  90. '{ userId: string; include?: Array<string>; verbose?: boolean; "X-Trace-ID"?: string }',
  91. )
  92. expect(inputTypeScript(create)).toBe('{ name: string; email: string; role?: "admin" | "member" }')
  93. expect(inputTypeScript(search)).toBe("{ filter?: { query: string; page?: number }; tags?: Array<string> }")
  94. expect(inputTypeScript(remove)).toBe("{ userId: string }")
  95. expect(outputTypeScript(get)).toContain("id: string")
  96. expect(outputTypeScript(create)).toContain('role?: "admin" | "member"')
  97. expect(outputTypeScript(search)).toBe("string")
  98. expect(outputTypeScript(remove)).toBe("null")
  99. const result = await Effect.runPromise(
  100. CodeMode.make({ tools: { api: api.tools } })
  101. .execute(`
  102. const user = await tools.api.users.get({
  103. userId: "user-1",
  104. include: ["profile", "permissions"],
  105. verbose: true,
  106. "X-Trace-ID": "trace-1",
  107. })
  108. const created = await tools.api.users.create({
  109. name: "Grace",
  110. email: "grace@example.test",
  111. role: "admin",
  112. })
  113. const summary = await tools.api.search.run({
  114. filter: { query: "effect", page: 2 },
  115. tags: ["typescript", "runtime"],
  116. })
  117. const removed = await tools.api.users.remove({ userId: "user-1" })
  118. return { user, created, summary, removed }
  119. `)
  120. .pipe(Effect.provide(client.layer)),
  121. )
  122. expect(result).toMatchObject({
  123. ok: true,
  124. value: {
  125. user: { id: "user-1", name: "Ada" },
  126. created: { id: "user-2", name: "Grace" },
  127. summary: "2 matches",
  128. removed: null,
  129. },
  130. })
  131. expect(resolutions).toEqual(["BearerAuth", "ApiKey", "BearerAuth"])
  132. expect(client.requests).toHaveLength(4)
  133. const getUrl = new URL(client.requests[0]!.url)
  134. expect(getUrl.pathname).toBe("/users/user-1")
  135. expect(getUrl.searchParams.get("include")).toBe("profile,permissions")
  136. expect(getUrl.searchParams.get("verbose")).toBe("true")
  137. expect(client.requests[0]!.headers["x-trace-id"]).toBe("trace-1")
  138. expect(client.requests[0]!.headers.authorization).toBe("Bearer bearer-secret")
  139. const createUrl = new URL(client.requests[1]!.url)
  140. expect(createUrl.searchParams.get("api_key")).toBe("api-secret")
  141. expect(client.requests[1]!.body).toEqual({ name: "Grace", email: "grace@example.test", role: "admin" })
  142. const searchUrl = new URL(client.requests[2]!.url)
  143. expect(searchUrl.searchParams.get("filter[query]")).toBe("effect")
  144. expect(searchUrl.searchParams.get("filter[page]")).toBe("2")
  145. expect(searchUrl.searchParams.getAll("tags")).toEqual(["typescript", "runtime"])
  146. expect(client.requests[2]!.headers.authorization).toBeUndefined()
  147. expect(new URL(client.requests[3]!.url).pathname).toBe("/users/user-1")
  148. expect(client.requests[3]!.headers.authorization).toBe("Bearer bearer-secret")
  149. })
  150. test("converts representative opencode operations into the expected tool shape", async () => {
  151. const spec = await opencodeSpec()
  152. const result = OpenAPI.fromSpec({ spec, baseUrl })
  153. expect(result.skipped).toHaveLength(5)
  154. expect(result.skipped).toContainEqual({
  155. method: "GET",
  156. path: "/api/pty/{ptyID}/connect",
  157. reason: "WebSocket operations are not supported",
  158. })
  159. expect(result.skipped.filter((item) => item.reason === "SSE operations are not supported")).toHaveLength(3)
  160. expect(result.skipped).toContainEqual({
  161. method: "GET",
  162. path: "/api/fs/read/*",
  163. reason: "binary responses are not supported",
  164. })
  165. expect(toolAt(result.tools, "v2.health.get")).not.toBeUndefined()
  166. expect(toolAt(result.tools, "v2.session.get")).not.toBeUndefined()
  167. expect(toolAt(result.tools, "v2.session.create")).not.toBeUndefined()
  168. const sessionGet = toolAt(result.tools, "v2.session.get")
  169. expect(Tool.isDefinition(sessionGet)).toBe(true)
  170. if (!Tool.isDefinition(sessionGet)) throw new Error("v2.session.get was not generated")
  171. expect(inputTypeScript(sessionGet)).toBe("{ sessionID: string }")
  172. expect(outputTypeScript(sessionGet)).toContain("id: string")
  173. expect(outputTypeScript(sessionGet)).toContain("additions: number")
  174. const switchAgent = toolAt(result.tools, "v2.session.switchAgent")
  175. expect(Tool.isDefinition(switchAgent)).toBe(true)
  176. if (!Tool.isDefinition(switchAgent)) throw new Error("v2.session.switchAgent was not generated")
  177. expect(inputTypeScript(switchAgent)).toBe("{ sessionID: string; agent: string }")
  178. const contextEntryPut = toolAt(result.tools, "v2.session.contextEntry.put")
  179. expect(Tool.isDefinition(contextEntryPut)).toBe(true)
  180. if (!Tool.isDefinition(contextEntryPut)) throw new Error("v2.session.contextEntry.put was not generated")
  181. expect(inputTypeScript(contextEntryPut)).toBe("{ sessionID: string; key: string; value: unknown }")
  182. expect(toolAt(result.tools, "v2_session_context_entry_put_2")).toBeUndefined()
  183. expect(toolAt(result.tools, "v2.pty.connect")).toBeUndefined()
  184. expect(toolAt(result.tools, "v2.session.log")).toBeUndefined()
  185. expect(toolAt(result.tools, "v2.event.subscribe")).toBeUndefined()
  186. expect(toolAt(result.tools, "v2.event.changes")).toBeUndefined()
  187. expect(toolAt(result.tools, "v2.fs.read")).toBeUndefined()
  188. expect(toolAt(result.tools, "v2.pty.connectToken")).not.toBeUndefined()
  189. })
  190. test("preserves operation path sanitization and collision handling", () => {
  191. const response = { responses: { 200: { description: "Success" } } }
  192. const result = OpenAPI.fromSpec({
  193. baseUrl,
  194. spec: {
  195. openapi: "3.1.0",
  196. paths: {
  197. "/first": { get: { ...response, operationId: "group.item" } },
  198. "/second": { get: { ...response, operationId: "group.item" } },
  199. "/third": { get: { ...response, operationId: "group..other" } },
  200. },
  201. },
  202. })
  203. expect(Tool.isDefinition(toolAt(result.tools, "group.item"))).toBe(true)
  204. expect(Tool.isDefinition(toolAt(result.tools, "group_item_2"))).toBe(true)
  205. expect(Tool.isDefinition(toolAt(result.tools, "group.operation.other"))).toBe(true)
  206. })
  207. test("synthesizes flat operation IDs from methods and paths", () => {
  208. const response = { responses: { 200: { description: "Success" } } }
  209. const tools = OpenAPI.fromSpec({
  210. baseUrl,
  211. spec: {
  212. openapi: "3.1.0",
  213. paths: {
  214. "/users": { get: response, post: response },
  215. "/users/{id}": { get: response, patch: response, delete: response },
  216. "/organizations/{organizationId}/users/{id}": { get: response },
  217. },
  218. },
  219. }).tools
  220. for (const path of [
  221. "getUsers",
  222. "postUsers",
  223. "getUsersById",
  224. "patchUsersById",
  225. "deleteUsersById",
  226. "getOrganizationsByOrganizationidUsersById",
  227. ]) {
  228. expect(Tool.isDefinition(toolAt(tools, path))).toBe(true)
  229. }
  230. })
  231. test("lets operation parameters override matching path parameters", () => {
  232. const tool = toolAt(
  233. OpenAPI.fromSpec({
  234. baseUrl,
  235. spec: {
  236. openapi: "3.1.0",
  237. paths: {
  238. "/test": {
  239. parameters: [{ name: "limit", in: "query", schema: { type: "string" } }],
  240. get: {
  241. operationId: "test",
  242. parameters: [{ name: "limit", in: "query", required: true, schema: { type: "number" } }],
  243. responses: { 200: { description: "Success" } },
  244. },
  245. },
  246. },
  247. },
  248. }).tools,
  249. "test",
  250. )
  251. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  252. expect(inputTypeScript(tool)).toBe("{ limit: number }")
  253. })
  254. test("normalizes OpenAPI 3.0 schemas with Effect", () => {
  255. const result = OpenAPI.fromSpec({
  256. baseUrl,
  257. spec: {
  258. openapi: "3.0.3",
  259. paths: {
  260. "/search": {
  261. get: {
  262. operationId: "search",
  263. parameters: [
  264. {
  265. in: "query",
  266. name: "value",
  267. schema: { type: "string", nullable: true, minLength: 2 },
  268. },
  269. ],
  270. responses: { 200: { description: "Success" } },
  271. },
  272. },
  273. },
  274. },
  275. })
  276. const search = toolAt(result.tools, "search")
  277. expect(Tool.isDefinition(search)).toBe(true)
  278. if (!Tool.isDefinition(search)) throw new Error("search was not generated")
  279. expect(inputTypeScript(search)).toBe("{ value?: string | null }")
  280. const schema: unknown = search.input
  281. const input = isRecord(schema) ? schema : {}
  282. const properties = isRecord(input.properties) ? input.properties : {}
  283. const value = isRecord(properties.value) ? properties.value : {}
  284. expect(value.minLength).toBe(2)
  285. })
  286. test("preserves schema-local definitions alongside component definitions", () => {
  287. const tool = toolAt(
  288. OpenAPI.fromSpec({
  289. baseUrl,
  290. spec: {
  291. openapi: "3.1.0",
  292. paths: {
  293. "/test": {
  294. get: {
  295. operationId: "test",
  296. responses: {
  297. 200: {
  298. description: "Success",
  299. content: {
  300. "application/json": {
  301. schema: { $ref: "#/$defs/Local", $defs: { Local: { type: "string" } } },
  302. },
  303. },
  304. },
  305. },
  306. },
  307. },
  308. },
  309. components: { schemas: { Global: { type: "number" } } },
  310. },
  311. }).tools,
  312. "test",
  313. )
  314. if (!Tool.isDefinition(tool) || !isRecord(tool.output)) throw new Error("test output was not generated")
  315. expect(tool.output.$defs).toMatchObject({ Local: { type: "string" }, Global: { type: "number" } })
  316. })
  317. test("documents that the opencode fixture is unauthenticated", async () => {
  318. const spec = await opencodeSpec()
  319. const components = isRecord(spec.components) ? spec.components : {}
  320. const result = OpenAPI.fromSpec({ spec, baseUrl })
  321. expect(spec.security).toStrictEqual([])
  322. expect(isRecord(components.securitySchemes) ? Object.keys(components.securitySchemes) : []).toStrictEqual([])
  323. const health = toolAt(result.tools, "v2.health.get")
  324. const healthInput = isRecord(health) ? health.input : undefined
  325. expect(healthInput).toMatchObject({ type: "object", properties: {} })
  326. const input = isRecord(healthInput) ? healthInput : {}
  327. expect(Object.keys(isRecord(input.properties) ? input.properties : {})).toStrictEqual([])
  328. })
  329. test("exposes real opencode operations through CodeMode discovery", async () => {
  330. const { layer } = recordingClient(() => json({}))
  331. const runtime = CodeMode.make({
  332. tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools },
  333. })
  334. const result = await Effect.runPromise(
  335. runtime
  336. .execute(
  337. `
  338. return await tools.$codemode.search({ query: "global health", namespace: "opencode", limit: 1 })
  339. `,
  340. )
  341. .pipe(Effect.provide(layer)),
  342. )
  343. expect(result).toMatchObject({ ok: true })
  344. if (!result.ok) return
  345. expect(result.value).toMatchObject({
  346. items: [
  347. {
  348. path: "tools.opencode.v2.health.get",
  349. description: "Check whether the API server is ready to accept requests.",
  350. },
  351. ],
  352. })
  353. expect(JSON.stringify(result.value)).toContain("healthy: true")
  354. })
  355. test("invokes real opencode path parameters and JSON request bodies", async () => {
  356. const { requests, layer } = recordingClient((request) => {
  357. if (request.method === "GET") return json({ id: "ses_123" })
  358. return json({ id: "ses_456" })
  359. })
  360. const runtime = CodeMode.make({
  361. tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools },
  362. })
  363. const result = await Effect.runPromise(
  364. runtime
  365. .execute(
  366. `
  367. const existing = await tools.opencode.v2.session.get({ sessionID: "ses_123" })
  368. const created = await tools.opencode.v2.session.create({ id: "ses_456" })
  369. return { existing, created }
  370. `,
  371. )
  372. .pipe(Effect.provide(layer)),
  373. )
  374. expect(result).toMatchObject({ ok: true })
  375. expect(requests).toHaveLength(2)
  376. expect(requests[0]).toMatchObject({ method: "GET", body: undefined })
  377. expect(new URL(requests[0]!.url).pathname).toBe("/api/session/ses_123")
  378. expect(requests[1]).toMatchObject({
  379. method: "POST",
  380. url: "http://localhost:4096/api/session",
  381. body: { id: "ses_456" },
  382. })
  383. })
  384. test("serializes deep-object query parameters from the opencode fixture", async () => {
  385. const client = recordingClient(() => json({ directory: "/tmp" }))
  386. const location = toolAt(OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools, "v2.location.get")
  387. if (!Tool.isDefinition(location)) throw new Error("v2.location.get was not generated")
  388. await Effect.runPromise(
  389. location.run({ location: { directory: "/tmp", workspace: "workspace-1" } }).pipe(Effect.provide(client.layer)),
  390. )
  391. const url = new URL(client.requests[0]!.url)
  392. expect(url.searchParams.get("location[directory]")).toBe("/tmp")
  393. expect(url.searchParams.get("location[workspace]")).toBe("workspace-1")
  394. })
  395. test("serializes supported simple and form parameter shapes", async () => {
  396. const client = recordingClient(() => json({ ok: true }))
  397. const result = OpenAPI.fromSpec({
  398. baseUrl,
  399. spec: {
  400. openapi: "3.1.0",
  401. paths: {
  402. "/items/{keys}": {
  403. get: {
  404. operationId: "items",
  405. parameters: [
  406. { name: "keys", in: "path", required: true, schema: { type: "array", items: { type: "string" } } },
  407. { name: "tags", in: "query", style: "form", explode: false, schema: { type: "array" } },
  408. { name: "filter", in: "query", style: "form", explode: true, schema: { type: "object" } },
  409. { name: "nullable", in: "query", required: true, schema: { type: ["string", "null"] } },
  410. { name: "constructor", in: "query", schema: { type: "string" } },
  411. { name: "meta", in: "header", style: "simple", explode: true, schema: { type: "object" } },
  412. ],
  413. responses: { 200: { description: "Success" } },
  414. },
  415. },
  416. },
  417. },
  418. })
  419. const tool = toolAt(result.tools, "items")
  420. if (!Tool.isDefinition(tool)) throw new Error("items was not generated")
  421. await Effect.runPromise(
  422. tool
  423. .run({
  424. keys: ["a!", "b*"],
  425. tags: ["x", "y"],
  426. filter: { state: "open", page: 2 },
  427. nullable: null,
  428. constructor_2: "safe",
  429. meta: { a: "b", c: "d" },
  430. })
  431. .pipe(Effect.provide(client.layer)),
  432. )
  433. const url = new URL(client.requests[0]!.url)
  434. expect(url.pathname).toBe("/items/a%21,b%2A")
  435. expect(url.searchParams.get("tags")).toBe("x,y")
  436. expect(url.searchParams.get("state")).toBe("open")
  437. expect(url.searchParams.get("page")).toBe("2")
  438. expect(url.searchParams.get("nullable")).toBe("null")
  439. expect(url.searchParams.get("constructor")).toBe("safe")
  440. expect(client.requests[0]!.headers.meta).toBe("a=b,c=d")
  441. await expect(
  442. Effect.runPromise(tool.run({ keys: [undefined] }).pipe(Effect.provide(client.layer))),
  443. ).rejects.toThrow("unsupported nested value")
  444. })
  445. test("skips unsupported parameter encodings and malformed security", () => {
  446. const result = OpenAPI.fromSpec({
  447. baseUrl,
  448. spec: {
  449. openapi: "3.1.0",
  450. security: [{ bearer: [] }],
  451. paths: {
  452. "/cookie": {
  453. get: {
  454. operationId: "cookie",
  455. parameters: [{ name: "session", in: "cookie", schema: { type: "string" } }],
  456. responses: { 200: { description: "Success" } },
  457. },
  458. },
  459. "/reserved": {
  460. get: {
  461. operationId: "reserved",
  462. parameters: [{ name: "query", in: "query", allowReserved: true, schema: { type: "string" } }],
  463. responses: { 200: { description: "Success" } },
  464. },
  465. },
  466. "/invalid-style": {
  467. get: {
  468. operationId: "invalidStyle",
  469. parameters: [{ name: "query", in: "query", style: 42, schema: { type: "string" } }],
  470. responses: { 200: { description: "Success" } },
  471. },
  472. },
  473. "/security": {
  474. get: { operationId: "security", security: null, responses: { 200: { description: "Success" } } },
  475. },
  476. },
  477. },
  478. })
  479. expect(result.tools).toEqual({})
  480. expect(result.skipped.map((item) => item.reason)).toEqual([
  481. "cookie parameter 'session' is not supported",
  482. "parameter 'query' uses unsupported allowReserved encoding",
  483. "parameter 'query' has an invalid style",
  484. "security declaration is not an array",
  485. ])
  486. })
  487. test("fails closed on prototype-named missing security schemes", () => {
  488. const result = OpenAPI.fromSpec({
  489. baseUrl,
  490. spec: singleOperation({ security: [JSON.parse('{"__proto__":[]}')] }),
  491. })
  492. expect(result.tools).toEqual({})
  493. expect(result.skipped[0]?.reason).toBe("security requirement references missing or malformed scheme: __proto__")
  494. })
  495. test("resolves bearer authentication without exposing it as input", async () => {
  496. const contexts: Array<Parameters<OpenAPI.AuthResolver>[0]> = []
  497. const client = recordingClient(() => json({ ok: true }))
  498. const spec = {
  499. ...singleOperation({ operationId: undefined }),
  500. security: [{ bearer: [] }],
  501. components: { securitySchemes: { bearer: { type: "http", scheme: "bearer" } } },
  502. } satisfies Document
  503. const tool = toolAt(
  504. OpenAPI.fromSpec({
  505. baseUrl,
  506. spec,
  507. auth: {
  508. resolve: (context) => {
  509. contexts.push(context)
  510. return Effect.succeed({ type: "bearer", token: "secret" })
  511. },
  512. },
  513. }).tools,
  514. "getTest",
  515. )
  516. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  517. await Effect.runPromise(tool.run({}).pipe(Effect.provide(client.layer)))
  518. expect(inputTypeScript(tool)).toBe("{}")
  519. expect(client.requests[0]!.headers.authorization).toBe("Bearer secret")
  520. expect(contexts).toEqual([
  521. {
  522. name: "bearer",
  523. definition: { type: "http", scheme: "bearer" },
  524. scopes: [],
  525. operation: {
  526. operationId: undefined,
  527. method: "GET",
  528. path: "/test",
  529. summary: undefined,
  530. description: undefined,
  531. },
  532. },
  533. ])
  534. })
  535. test("applies authentication carriers without prototype or collision loss", async () => {
  536. const client = recordingClient(() => json({ ok: true }))
  537. const authenticated = (security: ReadonlyArray<Record<string, ReadonlyArray<string>>>, schemes: Record<string, unknown>) =>
  538. OpenAPI.fromSpec({
  539. baseUrl,
  540. spec: { ...singleOperation({}), security, components: { securitySchemes: schemes } },
  541. auth: { resolve: () => Effect.succeed({ type: "apiKey", value: "secret" }) },
  542. })
  543. const prototype = toolAt(
  544. authenticated([{ key: [] }], { key: { type: "apiKey", in: "query", name: "__proto__" } }).tools,
  545. "test",
  546. )
  547. if (!Tool.isDefinition(prototype)) throw new Error("prototype auth tool was not generated")
  548. await Effect.runPromise(prototype.run({}).pipe(Effect.provide(client.layer)))
  549. expect(new URL(client.requests[0]!.url).searchParams.get("__proto__")).toBe("secret")
  550. const duplicate = toolAt(
  551. authenticated(
  552. [{ first: [], second: [] }],
  553. {
  554. first: { type: "apiKey", in: "header", name: "x-key" },
  555. second: { type: "apiKey", in: "header", name: "x-key" },
  556. },
  557. ).tools,
  558. "test",
  559. )
  560. if (!Tool.isDefinition(duplicate)) throw new Error("duplicate auth tool was not generated")
  561. await expect(Effect.runPromise(duplicate.run({}).pipe(Effect.provide(client.layer)))).rejects.toThrow(
  562. "multiple credentials",
  563. )
  564. const cookie = authenticated([{ key: [] }], { key: { type: "apiKey", in: "cookie", name: "session" } })
  565. expect(cookie.tools).toEqual({})
  566. expect(cookie.skipped[0]?.reason).toBe("cookie authentication 'key' is not supported")
  567. const alternative = OpenAPI.fromSpec({
  568. baseUrl,
  569. spec: {
  570. ...singleOperation({}),
  571. security: [{ cookie: [] }, { bearer: [] }],
  572. components: {
  573. securitySchemes: {
  574. cookie: { type: "apiKey", in: "cookie", name: "session" },
  575. bearer: { type: "http", scheme: "bearer" },
  576. },
  577. },
  578. },
  579. auth: {
  580. resolve: ({ name }) =>
  581. Effect.succeed(name === "bearer" ? { type: "bearer", token: "secret" } : undefined),
  582. },
  583. })
  584. const alternativeTool = toolAt(alternative.tools, "test")
  585. if (!Tool.isDefinition(alternativeTool)) throw new Error("supported auth alternative was not generated")
  586. await Effect.runPromise(alternativeTool.run({}).pipe(Effect.provide(client.layer)))
  587. expect(client.requests.at(-1)?.headers.authorization).toBe("Bearer secret")
  588. })
  589. test("honors server precedence and rejects ambiguous base URLs", async () => {
  590. const client = recordingClient(() => json({ ok: true }))
  591. const spec = {
  592. ...singleOperation({ servers: [{ url: "https://operation.example/v1" }] }),
  593. servers: [{ url: "https://document.example" }],
  594. } satisfies Document
  595. const tool = toolAt(OpenAPI.fromSpec({ spec }).tools, "test")
  596. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  597. await Effect.runPromise(tool.run({}).pipe(Effect.provide(client.layer)))
  598. expect(client.requests[0]?.url).toBe("https://operation.example/v1/test")
  599. const invalid = OpenAPI.fromSpec({ spec, baseUrl: "https://example.com/api?tenant=one" })
  600. expect(invalid.tools).toEqual({})
  601. expect(invalid.skipped[0]?.reason).toContain("unsupported query string or fragment")
  602. const malformed = OpenAPI.fromSpec({ spec, baseUrl: "https:/example.com" })
  603. expect(malformed.tools).toEqual({})
  604. expect(malformed.skipped[0]?.reason).toContain("not an absolute HTTP(S) URL")
  605. })
  606. test("resolves chained response refs before detecting unsupported transports", () => {
  607. const result = OpenAPI.fromSpec({
  608. baseUrl,
  609. spec: {
  610. ...singleOperation({ responses: { 200: { $ref: "#/components/responses/First" } } }),
  611. components: {
  612. responses: {
  613. First: { $ref: "#/components/responses/Stream" },
  614. Stream: { content: { "text/event-stream": { schema: { type: "string" } } } },
  615. },
  616. },
  617. },
  618. })
  619. expect(result.tools).toEqual({})
  620. expect(result.skipped[0]?.reason).toBe("SSE operations are not supported")
  621. })
  622. test("resolves response schemas before detecting binary output", () => {
  623. const result = OpenAPI.fromSpec({
  624. baseUrl,
  625. spec: {
  626. ...singleOperation({
  627. responses: {
  628. 200: {
  629. content: { "text/plain": { schema: { $ref: "#/components/schemas/File" } } },
  630. },
  631. },
  632. }),
  633. components: { schemas: { File: { type: "string", format: "binary" } } },
  634. },
  635. })
  636. expect(result.tools).toEqual({})
  637. expect(result.skipped[0]?.reason).toBe("binary responses are not supported")
  638. })
  639. test("validates composite parameters before resolving auth", async () => {
  640. const resolutions: Array<string> = []
  641. const client = recordingClient(() => json({ ok: true }))
  642. const tool = toolAt(
  643. OpenAPI.fromSpec({
  644. baseUrl,
  645. spec: {
  646. ...singleOperation({
  647. parameters: [{ name: "filter", in: "query", style: "form", explode: true, schema: { type: "object" } }],
  648. }),
  649. security: [{ bearer: [] }],
  650. components: { securitySchemes: { bearer: { type: "http", scheme: "bearer" } } },
  651. },
  652. auth: {
  653. resolve: ({ name }) => {
  654. resolutions.push(name)
  655. return Effect.succeed({ type: "bearer", token: "secret" })
  656. },
  657. },
  658. }).tools,
  659. "test",
  660. )
  661. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  662. await expect(
  663. Effect.runPromise(tool.run({ filter: { value: undefined } }).pipe(Effect.provide(client.layer))),
  664. ).rejects.toThrow("unsupported nested value")
  665. expect(resolutions).toEqual([])
  666. expect(client.requests).toEqual([])
  667. })
  668. test("preserves JSON media types and rejects unencodable bodies", async () => {
  669. const client = recordingClient(() => json({ ok: true }))
  670. const tool = toolAt(
  671. OpenAPI.fromSpec({
  672. baseUrl,
  673. spec: singleOperation(
  674. {
  675. requestBody: {
  676. required: true,
  677. content: { "application/merge-patch+json": { schema: { type: "object" } } },
  678. },
  679. },
  680. "post",
  681. ),
  682. }).tools,
  683. "test",
  684. )
  685. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  686. await Effect.runPromise(tool.run({ body: { name: "updated" } }).pipe(Effect.provide(client.layer)))
  687. expect(client.requests[0]!.headers["content-type"]).toBe("application/merge-patch+json")
  688. const cyclic: Record<string, unknown> = {}
  689. cyclic.self = cyclic
  690. await expect(Effect.runPromise(tool.run({ body: cyclic }).pipe(Effect.provide(client.layer)))).rejects.toThrow(
  691. "Invalid JSON body",
  692. )
  693. })
  694. test("rejects oversized and malformed JSON responses", async () => {
  695. const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec: singleOperation({}) }).tools, "test")
  696. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  697. const oversized = recordingClient(
  698. () => new Response(null, { headers: { "content-length": String(50 * 1024 * 1024 + 1) } }),
  699. )
  700. const malformed = recordingClient(
  701. () => new Response("{", { headers: { "content-type": "application/json" } }),
  702. )
  703. const chunked = recordingClient(() => new Response(new Uint8Array(50 * 1024 * 1024 + 1)))
  704. await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(oversized.layer)))).rejects.toThrow(
  705. "response exceeds 50 MiB",
  706. )
  707. await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(malformed.layer)))).rejects.toThrow(
  708. "returned malformed JSON",
  709. )
  710. await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(chunked.layer)))).rejects.toThrow(
  711. "response exceeds 50 MiB",
  712. )
  713. })
  714. test("keeps non-JSON responses raw and unions every success output", async () => {
  715. const spec = singleOperation({
  716. responses: {
  717. 200: { description: "Text", content: { "text/plain": { schema: { type: "string" } } } },
  718. 204: { description: "Empty" },
  719. },
  720. })
  721. const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec }).tools, "test")
  722. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  723. const client = recordingClient(() => new Response("123", { headers: { "content-type": "text/plain" } }))
  724. expect(outputTypeScript(tool)).toBe("string | null")
  725. await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(client.layer)))).resolves.toBe("123")
  726. })
  727. test("fails missing required parameters before auth and network", async () => {
  728. const { requests, layer } = recordingClient(() => json({}))
  729. const runtime = CodeMode.make({
  730. tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools },
  731. })
  732. const result = await Effect.runPromise(
  733. runtime.execute("return await tools.opencode.v2.session.get({})").pipe(Effect.provide(layer)),
  734. )
  735. expect(result).toMatchObject({ ok: false })
  736. expect(JSON.stringify(result)).toContain("Missing required path parameter 'sessionID'")
  737. expect(requests).toHaveLength(0)
  738. })
  739. test("prefixes cross-location collisions and reconstructs the HTTP request", async () => {
  740. const spec = {
  741. openapi: "3.1.0",
  742. info: { title: "collision", version: "1.0.0" },
  743. paths: {
  744. "/echo": {
  745. post: {
  746. operationId: "echo",
  747. requestBody: {
  748. required: true,
  749. content: { "application/json": { schema: { type: "string" } } },
  750. },
  751. responses: { "204": { description: "Echoed" } },
  752. },
  753. },
  754. "/things/{id}": {
  755. post: {
  756. operationId: "things.update",
  757. parameters: [
  758. { name: "id", in: "path", required: true, schema: { type: "string" } },
  759. { name: "id", in: "query", required: true, schema: { type: "string" } },
  760. { name: "path_id", in: "query", schema: { type: "string" } },
  761. { name: "id", in: "header", required: true, schema: { type: "string" } },
  762. ],
  763. requestBody: {
  764. required: true,
  765. content: {
  766. "application/json": {
  767. schema: {
  768. type: "object",
  769. properties: { id: { type: "string" } },
  770. required: ["id"],
  771. additionalProperties: false,
  772. },
  773. },
  774. },
  775. },
  776. responses: { "204": { description: "Updated" } },
  777. },
  778. },
  779. },
  780. } satisfies Document
  781. const { requests, layer } = recordingClient(() => new Response(null, { status: 204 }))
  782. const tools = OpenAPI.fromSpec({ spec, baseUrl }).tools
  783. const update = toolAt(tools, "things.update")
  784. const echo = toolAt(tools, "echo")
  785. expect(Tool.isDefinition(update)).toBe(true)
  786. if (!Tool.isDefinition(update)) throw new Error("things.update was not generated")
  787. expect(inputTypeScript(update)).toBe(
  788. "{ path_id: string; query_id: string; path_id_2?: string; header_id: string; body_id: string }",
  789. )
  790. expect(Tool.isDefinition(echo)).toBe(true)
  791. if (!Tool.isDefinition(echo)) throw new Error("echo was not generated")
  792. expect(inputTypeScript(echo)).toBe("{ body: string }")
  793. const runtime = CodeMode.make({ tools })
  794. const result = await Effect.runPromise(
  795. runtime
  796. .execute(
  797. `
  798. const updated = await tools.things.update({ path_id: "path", query_id: "query", path_id_2: "literal", header_id: "header", body_id: "body" })
  799. const echoed = await tools.echo({ body: "hello" })
  800. return { updated, echoed }
  801. `,
  802. )
  803. .pipe(Effect.provide(layer)),
  804. )
  805. expect(result).toMatchObject({ ok: true })
  806. expect(requests).toHaveLength(2)
  807. expect(new URL(requests[0]!.url).pathname).toBe("/things/path")
  808. expect(new URL(requests[0]!.url).searchParams.get("id")).toBe("query")
  809. expect(new URL(requests[0]!.url).searchParams.get("path_id")).toBe("literal")
  810. expect(requests[0]!.headers.id).toBe("header")
  811. expect(requests[0]!.body).toStrictEqual({ id: "body" })
  812. expect(requests[1]!.body).toBe("hello")
  813. })
  814. test("keeps bodies nested when flattening would lose schema semantics", () => {
  815. const body = (schema: Record<string, unknown>, required = true) => ({
  816. required,
  817. content: { "application/json": { schema } },
  818. })
  819. const spec = {
  820. openapi: "3.1.0",
  821. info: { title: "bodies", version: "1.0.0" },
  822. paths: Object.fromEntries(
  823. [
  824. [
  825. "optional",
  826. body(
  827. {
  828. type: "object",
  829. properties: { name: { type: "string" } },
  830. required: ["name"],
  831. additionalProperties: false,
  832. },
  833. false,
  834. ),
  835. ],
  836. ["dictionary", body({ type: "object", additionalProperties: { type: "string" } })],
  837. [
  838. "composed",
  839. body({
  840. type: "object",
  841. allOf: [{ type: "object", properties: { name: { type: "string" } }, required: ["name"] }],
  842. additionalProperties: false,
  843. }),
  844. ],
  845. [
  846. "nullable",
  847. body({
  848. type: ["object", "null"],
  849. properties: { name: { type: "string" } },
  850. additionalProperties: false,
  851. }),
  852. ],
  853. ].map(([name, requestBody]) => [
  854. `/body/${name}`,
  855. {
  856. post: {
  857. operationId: `body.${name}`,
  858. requestBody,
  859. responses: { "204": { description: "Accepted" } },
  860. },
  861. },
  862. ]),
  863. ),
  864. } satisfies Document
  865. const tools = OpenAPI.fromSpec({ spec, baseUrl }).tools
  866. for (const name of ["optional", "dictionary", "composed", "nullable"]) {
  867. const tool = toolAt(tools, `body.${name}`)
  868. expect(Tool.isDefinition(tool)).toBe(true)
  869. if (!Tool.isDefinition(tool)) throw new Error(`body.${name} was not generated`)
  870. const input = isRecord(tool.input) ? tool.input : {}
  871. expect(Object.keys(isRecord(input.properties) ? input.properties : {})).toStrictEqual(["body"])
  872. }
  873. const optional = toolAt(tools, "body.optional")
  874. if (!Tool.isDefinition(optional)) throw new Error("body.optional was not generated")
  875. expect(inputTypeScript(optional)).toBe("{ body?: { name: string } }")
  876. })
  877. })