generate.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. import { describe, expect, test } from "bun:test"
  2. import { mkdtemp, rm } from "node:fs/promises"
  3. import { tmpdir } from "node:os"
  4. import { join } from "node:path"
  5. import { Effect, FileSystem, Schema, SchemaAST, SchemaGetter } from "effect"
  6. import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema } from "effect/unstable/httpapi"
  7. import { format } from "prettier"
  8. import {
  9. compile as compileContract,
  10. emitEffect,
  11. emitEffectImported,
  12. emitPromise,
  13. generate,
  14. GenerationError,
  15. } from "../src"
  16. import { it } from "./effect"
  17. import { Api as FixtureApi, Missing } from "./fixture"
  18. function api(endpoint: HttpApiEndpoint.Any) {
  19. return HttpApi.make("test").add(HttpApiGroup.make("session").add(endpoint))
  20. }
  21. function compile<Id extends string, Groups extends HttpApiGroup.Any>(source: HttpApi.HttpApi<Id, Groups>) {
  22. return emitEffect(compileContract(source))
  23. }
  24. describe("HttpApiCodegen.generate", () => {
  25. test("compiles one contract for Promise and Effect emitters", () => {
  26. const contract = compileContract(
  27. api(
  28. HttpApiEndpoint.get("get", "/session/:sessionID", {
  29. params: { sessionID: Schema.String },
  30. success: Schema.Struct({ data: Schema.String }),
  31. }),
  32. ),
  33. )
  34. const promise = emitPromise(contract)
  35. const effect = emitEffect(contract)
  36. expect(promise.operations).toEqual(effect.operations)
  37. expect(promise.files.map((file) => file.path)).toEqual(["types.ts", "client-error.ts", "client.ts", "index.ts"])
  38. const promiseClient = promise.files.find((file) => file.path === "client.ts")?.content
  39. expect(promiseClient).toContain('"get": (input: SessionGetInput, requestOptions?: RequestOptions)')
  40. expect(promiseClient).toContain("`/session/${encodeURIComponent(input.sessionID)}`")
  41. expect(effect.files.find((file) => file.path === "session.ts")?.content).toContain(
  42. 'params: { "sessionID": input["sessionID"] }',
  43. )
  44. })
  45. test("emits an Effect client against an imported authoritative API", () => {
  46. const output = emitEffectImported(
  47. compileContract(
  48. api(
  49. HttpApiEndpoint.get("get", "/session/:sessionID", {
  50. params: { sessionID: Schema.String },
  51. success: Schema.Struct({ data: Schema.String }),
  52. }),
  53. ),
  54. ),
  55. { module: "@example/api", api: "Api" },
  56. )
  57. expect(output.files.map((file) => file.path)).toEqual(["client-error.ts", "client.ts", "index.ts"])
  58. expect(output.files.find((file) => file.path === "client.ts")?.content).toContain(
  59. 'import { Api } from "@example/api"',
  60. )
  61. expect(output.files.find((file) => file.path === "client.ts")?.content).toContain(
  62. "HttpApiClient.ForApi<typeof Api>",
  63. )
  64. })
  65. test("projects imported endpoint constants into a generated API", () => {
  66. const output = emitEffectImported(
  67. compileContract(
  68. api(
  69. HttpApiEndpoint.get("get", "/session/:sessionID", {
  70. params: { sessionID: Schema.String },
  71. success: Schema.Struct({ data: Schema.String }),
  72. }),
  73. ),
  74. ),
  75. { module: "@example/api", endpoints: { "session.get": "SessionGet" } },
  76. )
  77. const client = output.files.find((file) => file.path === "client.ts")?.content
  78. expect(client).toContain('import { SessionGet } from "@example/api"')
  79. expect(client).toContain('const Api = HttpApi.make("generated").add(HttpApiGroup.make("session").add(SessionGet))')
  80. })
  81. test("imports an authoritative group without reconstructing it", () => {
  82. const output = emitEffectImported(
  83. compileContract(
  84. api(
  85. HttpApiEndpoint.get("get", "/session/:sessionID", {
  86. params: { sessionID: Schema.String },
  87. success: Schema.String,
  88. }),
  89. ),
  90. ),
  91. { module: "@example/api", group: "SessionGroup" },
  92. )
  93. const client = output.files.find((file) => file.path === "client.ts")?.content
  94. expect(client).toContain('import { SessionGroup } from "@example/api"')
  95. expect(client).toContain('const Api = HttpApi.make("generated").add(SessionGroup)')
  96. expect(client).not.toContain("HttpApiGroup")
  97. })
  98. test("separates hosted and consumer group names", () => {
  99. const source = HttpApi.make("test").add(
  100. HttpApiGroup.make("server.session").add(
  101. HttpApiEndpoint.get("session.get", "/session", { success: Schema.String }),
  102. ),
  103. )
  104. const contract = compileContract(source, { groupNames: { "server.session": "sessions" } })
  105. expect(contract.groups[0]?.identifier).toBe("sessions")
  106. expect(contract.groups[0]?.sourceIdentifier).toBe("server.session")
  107. expect(contract.groups[0]?.endpoints[0]?.operation).toMatchObject({ group: "sessions", name: "get" })
  108. })
  109. test("rejects consumer group name collisions", () => {
  110. const source = HttpApi.make("test")
  111. .add(HttpApiGroup.make("first").add(HttpApiEndpoint.get("one", "/one", { success: Schema.String })))
  112. .add(HttpApiGroup.make("second").add(HttpApiEndpoint.get("two", "/two", { success: Schema.String })))
  113. expect(() => compileContract(source, { groupNames: { first: "same", second: "same" } })).toThrow(
  114. "Client group name collision: same",
  115. )
  116. })
  117. test("uses the unqualified endpoint name for the public client", () => {
  118. const contract = compileContract(
  119. api(
  120. HttpApiEndpoint.get("session.get", "/session/:sessionID", {
  121. params: { sessionID: Schema.String },
  122. success: Schema.String,
  123. }),
  124. ),
  125. )
  126. const promise = emitPromise(contract).files.find((file) => file.path === "client.ts")?.content
  127. const effect = emitEffectImported(contract, {
  128. module: "@example/api",
  129. endpoints: { "session.session.get": "SessionGet" },
  130. }).files.find((file) => file.path === "client.ts")?.content
  131. expect(contract.groups[0]?.endpoints[0]?.operation.name).toBe("get")
  132. expect(promise).toContain('"get": (input: SessionGetInput, requestOptions?: RequestOptions)')
  133. expect(effect).toContain('const adaptGroup0 = (raw: RawClient["session"]) => ({ "get": Endpoint0_0(raw) })')
  134. expect(effect).toContain('raw["session.get"]')
  135. })
  136. test("preserves optional keys in Promise error types", () => {
  137. class OptionalError extends Schema.TaggedErrorClass<OptionalError>()(
  138. "OptionalError",
  139. { message: Schema.String, detail: Schema.String.pipe(Schema.optional) },
  140. { httpApiStatus: 400 },
  141. ) {}
  142. const output = emitPromise(
  143. compileContract(api(HttpApiEndpoint.get("get", "/session", { success: Schema.String, error: OptionalError }))),
  144. )
  145. expect(output.files.find((file) => file.path === "types.ts")?.content).toContain(
  146. 'readonly "message": string; readonly "detail"?: string | undefined',
  147. )
  148. })
  149. test("erases brands from Promise wire types", () => {
  150. const output = emitPromise(
  151. compileContract(
  152. api(
  153. HttpApiEndpoint.get("get", "/session/:sessionID", {
  154. params: { sessionID: Schema.String.pipe(Schema.brand("SessionID")) },
  155. success: Schema.Struct({ data: Schema.String.pipe(Schema.brand("SessionID")) }),
  156. }),
  157. ),
  158. ),
  159. )
  160. const types = output.files.find((file) => file.path === "types.ts")?.content
  161. expect(types).toContain('readonly "sessionID": string')
  162. expect(types).not.toContain("Brand")
  163. })
  164. test("inlines non-recursive references in Promise wire types", () => {
  165. const Referenced = Schema.Struct({ value: Schema.String }).annotate({ identifier: "Referenced" })
  166. const output = emitPromise(
  167. compileContract(
  168. api(
  169. HttpApiEndpoint.get("get", "/session", {
  170. success: Schema.Struct({ data: Referenced }),
  171. }),
  172. ),
  173. ),
  174. )
  175. expect(output.files.find((file) => file.path === "types.ts")?.content).toContain(
  176. 'export type SessionGetOutput = ({ readonly "data": ({ readonly "value": string }) })["data"]',
  177. )
  178. })
  179. test("emits Effect Json schemas as standalone Promise types", () => {
  180. const output = emitPromise(
  181. compileContract(
  182. api(
  183. HttpApiEndpoint.get("get", "/session", {
  184. success: Schema.Json,
  185. }),
  186. ),
  187. ),
  188. )
  189. const types = output.files.find((file) => file.path === "types.ts")?.content
  190. expect(types).toContain("export type JsonValue =")
  191. expect(types).toContain("{ readonly [key: string]: JsonValue }")
  192. expect(types).not.toContain("Schema.Json")
  193. })
  194. test("emits an optional Promise input when every field is optional", () => {
  195. const output = emitPromise(
  196. compileContract(
  197. api(
  198. HttpApiEndpoint.get("list", "/session", {
  199. query: { limit: Schema.optional(Schema.Number) },
  200. success: Schema.Array(Schema.String),
  201. }),
  202. ),
  203. ),
  204. )
  205. expect(output.files.find((file) => file.path === "client.ts")?.content).toContain(
  206. '"list": (input?: SessionListInput, requestOptions?: RequestOptions)',
  207. )
  208. })
  209. test("rejects Promise transports that are not implemented", () => {
  210. expect(() =>
  211. emitPromise(
  212. compileContract(
  213. api(
  214. HttpApiEndpoint.get("text", "/text", {
  215. success: Schema.String.pipe(HttpApiSchema.asText()),
  216. }),
  217. ),
  218. ),
  219. ),
  220. ).toThrow("Unsupported Promise success encoding: session.text")
  221. expect(() =>
  222. emitPromise(
  223. compileContract(
  224. api(
  225. HttpApiEndpoint.get("events", "/events", {
  226. success: HttpApiSchema.StreamSse({ data: Schema.String, error: Missing }),
  227. }),
  228. ),
  229. ),
  230. ),
  231. ).toThrow("Unsupported Promise stream: session.events")
  232. })
  233. test("executes an emitted Promise GET through fetch", async () => {
  234. const output = emitPromise(
  235. compileContract(
  236. api(
  237. HttpApiEndpoint.get("get", "/session/:sessionID", {
  238. params: { sessionID: Schema.String },
  239. success: Schema.Struct({ data: Schema.String }),
  240. }),
  241. ),
  242. ),
  243. )
  244. const directory = await mkdtemp(join(tmpdir(), "opencode-httpapi-codegen-"))
  245. try {
  246. await Promise.all(output.files.map((file) => Bun.write(join(directory, file.path), file.content)))
  247. const generated = await import(`${join(directory, "index.ts")}?t=${crypto.randomUUID()}`)
  248. let request: Request | undefined
  249. const client = generated.OpenCode.make({
  250. baseUrl: "https://example.com",
  251. fetch: async (input: RequestInfo | URL) => {
  252. request = input instanceof Request ? input : new Request(input)
  253. return Response.json({ data: "hello" })
  254. },
  255. })
  256. expect(await client.session.get({ sessionID: "a/b" })).toBe("hello")
  257. expect(request?.method).toBe("GET")
  258. expect(request?.url).toBe("https://example.com/session/a%2Fb")
  259. } finally {
  260. await rm(directory, { recursive: true, force: true })
  261. }
  262. })
  263. test("maps an emitted no-content response to undefined", async () => {
  264. const output = emitPromise(
  265. compileContract(
  266. api(
  267. HttpApiEndpoint.post("interrupt", "/session/:sessionID/interrupt", {
  268. params: { sessionID: Schema.String },
  269. success: HttpApiSchema.NoContent,
  270. }),
  271. ),
  272. ),
  273. )
  274. const directory = await mkdtemp(join(tmpdir(), "opencode-httpapi-codegen-"))
  275. try {
  276. await Promise.all(output.files.map((file) => Bun.write(join(directory, file.path), file.content)))
  277. const generated = await import(`${join(directory, "index.ts")}?t=${crypto.randomUUID()}`)
  278. const client = generated.OpenCode.make({
  279. baseUrl: "https://example.com",
  280. fetch: async () => new Response(null, { status: 204 }),
  281. })
  282. expect(await client.session.interrupt({ sessionID: "session" })).toBeUndefined()
  283. } finally {
  284. await rm(directory, { recursive: true, force: true })
  285. }
  286. })
  287. test("serializes flattened query, header, and JSON payload inputs", async () => {
  288. const output = emitPromise(
  289. compileContract(
  290. api(
  291. HttpApiEndpoint.post("prompt", "/session/:sessionID", {
  292. params: { sessionID: Schema.String },
  293. query: { resume: Schema.optional(Schema.Boolean) },
  294. headers: { traceID: Schema.String },
  295. payload: Schema.Struct({ prompt: Schema.String }),
  296. success: Schema.Struct({ data: Schema.String }),
  297. }),
  298. ),
  299. ),
  300. )
  301. const directory = await mkdtemp(join(tmpdir(), "opencode-httpapi-codegen-"))
  302. try {
  303. await Promise.all(output.files.map((file) => Bun.write(join(directory, file.path), file.content)))
  304. const generated = await import(`${join(directory, "index.ts")}?t=${crypto.randomUUID()}`)
  305. let request: Request | undefined
  306. const client = generated.OpenCode.make({
  307. baseUrl: "https://example.com",
  308. fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
  309. request = input instanceof Request ? input : new Request(input, init)
  310. return Response.json({ data: "admitted" })
  311. },
  312. })
  313. expect(
  314. await client.session.prompt({ sessionID: "session", resume: true, traceID: "trace", prompt: "hello" }),
  315. ).toBe("admitted")
  316. expect(request?.url).toBe("https://example.com/session/session?resume=true")
  317. expect(request?.headers.get("traceID")).toBe("trace")
  318. expect(await request?.json()).toEqual({ prompt: "hello" })
  319. } finally {
  320. await rm(directory, { recursive: true, force: true })
  321. }
  322. })
  323. test("rejects with declared tagged errors and exports a type guard", async () => {
  324. const output = emitPromise(
  325. compileContract(
  326. api(
  327. HttpApiEndpoint.get("get", "/session/:sessionID", {
  328. params: { sessionID: Schema.String },
  329. success: Schema.Struct({ data: Schema.String }),
  330. error: Missing.pipe(HttpApiSchema.status(404)),
  331. }),
  332. ),
  333. ),
  334. )
  335. const directory = await mkdtemp(join(tmpdir(), "opencode-httpapi-codegen-"))
  336. try {
  337. await Promise.all(output.files.map((file) => Bun.write(join(directory, file.path), file.content)))
  338. const generated = await import(`${join(directory, "index.ts")}?t=${crypto.randomUUID()}`)
  339. const client = generated.OpenCode.make({
  340. baseUrl: "https://example.com",
  341. fetch: async () => Response.json({ _tag: "Missing", message: "gone" }, { status: 404 }),
  342. })
  343. const error = await client.session.get({ sessionID: "missing" }).catch((cause: unknown) => cause)
  344. expect(error).toEqual({ _tag: "Missing", message: "gone" })
  345. expect(generated.isMissing(error)).toBeTrue()
  346. } finally {
  347. await rm(directory, { recursive: true, force: true })
  348. }
  349. })
  350. test("iterates an emitted SSE stream lazily without reconnecting", async () => {
  351. const output = emitPromise(
  352. compileContract(
  353. api(
  354. HttpApiEndpoint.get("subscribe", "/event", {
  355. query: { after: Schema.optional(Schema.Number) },
  356. success: HttpApiSchema.StreamSse({ data: Schema.Struct({ type: Schema.String }) }),
  357. }),
  358. ),
  359. ),
  360. )
  361. const directory = await mkdtemp(join(tmpdir(), "opencode-httpapi-codegen-"))
  362. try {
  363. await Promise.all(output.files.map((file) => Bun.write(join(directory, file.path), file.content)))
  364. const generated = await import(`${join(directory, "index.ts")}?t=${crypto.randomUUID()}`)
  365. let requests = 0
  366. let url: string | undefined
  367. const client = generated.OpenCode.make({
  368. baseUrl: "https://example.com",
  369. fetch: async (input: RequestInfo | URL) => {
  370. requests++
  371. url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url
  372. const encoder = new TextEncoder()
  373. return new Response(
  374. new ReadableStream({
  375. start(controller) {
  376. controller.enqueue(encoder.encode('data: {"type":"ready"}\r'))
  377. controller.enqueue(encoder.encode("\n\r\n"))
  378. controller.close()
  379. },
  380. }),
  381. { headers: { "content-type": "text/event-stream" } },
  382. )
  383. },
  384. })
  385. const events = client.session.subscribe({ after: 2 })
  386. expect(requests).toBe(0)
  387. const received = []
  388. for await (const event of events) received.push(event)
  389. expect(received).toEqual([{ type: "ready" }])
  390. expect(requests).toBe(1)
  391. expect(url).toBe("https://example.com/event?after=2")
  392. } finally {
  393. await rm(directory, { recursive: true, force: true })
  394. }
  395. })
  396. test("preserves public group and endpoint identifiers exactly", () => {
  397. const output = compile(
  398. HttpApi.make("test").add(
  399. HttpApiGroup.make("session").add(HttpApiEndpoint.get("get", "/session/:sessionID", { success: Schema.String })),
  400. ),
  401. )
  402. expect(output.operations[0]).toMatchObject({ group: "session", name: "get" })
  403. })
  404. test("emits one client module per HttpApi group", () => {
  405. const source = HttpApi.make("test")
  406. .add(HttpApiGroup.make("session").add(HttpApiEndpoint.get("get", "/session", { success: Schema.String })))
  407. .add(HttpApiGroup.make("tool").add(HttpApiEndpoint.get("list", "/tool", { success: Schema.String })))
  408. const output = compile(source)
  409. expect(output.files.map((file) => file.path)).toEqual([
  410. "session.ts",
  411. "tool.ts",
  412. "client-error.ts",
  413. "client.ts",
  414. "index.ts",
  415. ])
  416. })
  417. test("emits syntactically valid TypeScript modules", () => {
  418. const output = compile(
  419. api(
  420. HttpApiEndpoint.get("get", "/session/:sessionID", {
  421. params: { sessionID: Schema.String },
  422. success: Schema.Struct({ data: Schema.String }),
  423. }),
  424. ),
  425. )
  426. const transpiler = new Bun.Transpiler({ loader: "ts" })
  427. for (const file of output.files) expect(() => transpiler.transformSync(file.content)).not.toThrow()
  428. })
  429. it.effect("keeps the strict generated-consumer fixture current", () =>
  430. Effect.gen(function* () {
  431. const output = compile(FixtureApi)
  432. const actual = yield* Effect.promise(() =>
  433. Array.fromAsync(new Bun.Glob("*.ts").scan(new URL("generated", import.meta.url).pathname)),
  434. )
  435. expect(actual.sort((a, b) => a.localeCompare(b))).toEqual(
  436. output.files.map((file) => file.path).sort((a, b) => a.localeCompare(b)),
  437. )
  438. yield* Effect.forEach(output.files, (file) =>
  439. Effect.tryPromise(() =>
  440. Promise.all([
  441. Bun.file(new URL(`generated/${file.path}`, import.meta.url)).text(),
  442. format(file.content, { parser: "typescript", semi: false, printWidth: 120 }),
  443. ]),
  444. ).pipe(Effect.map(([content, expected]) => expect(content).toBe(expected))),
  445. )
  446. }),
  447. )
  448. test("flattens transport input channels into one domain input", () => {
  449. const output = compile(
  450. api(
  451. HttpApiEndpoint.post("prompt", "/session/:sessionID", {
  452. params: { sessionID: Schema.String },
  453. query: { resume: Schema.String },
  454. headers: { traceID: Schema.String },
  455. payload: Schema.Struct({ prompt: Schema.String }),
  456. success: Schema.Struct({ data: Schema.String }),
  457. }),
  458. ),
  459. )
  460. expect(output.operations[0]?.input).toEqual([
  461. { name: "sessionID", source: "params" },
  462. { name: "resume", source: "query" },
  463. { name: "traceID", source: "headers" },
  464. { name: "prompt", source: "payload" },
  465. ])
  466. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  467. 'params: { "sessionID": input["sessionID"] }',
  468. )
  469. })
  470. test("uses no argument when an operation has no input fields", () => {
  471. const output = compile(api(HttpApiEndpoint.get("health", "/health", { success: Schema.String })))
  472. expect(output.operations[0]?.inputMode).toBe("none")
  473. })
  474. test("uses an optional object when every input field is optional", () => {
  475. const output = compile(
  476. api(
  477. HttpApiEndpoint.get("list", "/session", {
  478. query: { limit: Schema.optional(Schema.String) },
  479. success: Schema.Array(Schema.String),
  480. }),
  481. ),
  482. )
  483. expect(output.operations[0]?.inputMode).toBe("optional")
  484. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain('input?.["limit"]')
  485. })
  486. test("regenerates standard HttpApi transport codecs from decoded schemas", () => {
  487. const output = compile(
  488. api(
  489. HttpApiEndpoint.get("list", "/session", {
  490. query: { archived: Schema.optional(Schema.Boolean) },
  491. success: Schema.String,
  492. }),
  493. ),
  494. )
  495. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain("Schema.Boolean")
  496. })
  497. test("uses a required object when any input field is required", () => {
  498. const output = compile(
  499. api(
  500. HttpApiEndpoint.get("get", "/session/:sessionID", {
  501. params: { sessionID: Schema.String },
  502. query: { includeArchived: Schema.optional(Schema.String) },
  503. success: Schema.String,
  504. }),
  505. ),
  506. )
  507. expect(output.operations[0]?.inputMode).toBe("required")
  508. })
  509. test("rejects colliding input names across transport channels", () => {
  510. expect(() =>
  511. compile(
  512. api(
  513. HttpApiEndpoint.post("prompt", "/session/:id", {
  514. params: { id: Schema.String },
  515. payload: Schema.Struct({ id: Schema.String }),
  516. success: Schema.Void,
  517. }),
  518. ),
  519. ),
  520. ).toThrow("Input field collision: id")
  521. })
  522. test("rejects multiple payload alternatives until selection semantics are explicit", () => {
  523. expect(() =>
  524. compile(
  525. api(
  526. HttpApiEndpoint.post("prompt", "/session", {
  527. payload: [Schema.Struct({ text: Schema.String }), Schema.Struct({ count: Schema.Number })],
  528. success: Schema.String,
  529. }),
  530. ),
  531. ),
  532. ).toThrow("Multiple payload schemas: session.prompt")
  533. })
  534. test("unwraps an exact data success envelope", () => {
  535. const output = compile(
  536. api(
  537. HttpApiEndpoint.get("get", "/session/:sessionID", {
  538. params: { sessionID: Schema.String },
  539. success: Schema.Struct({ data: Schema.String }),
  540. }),
  541. ),
  542. )
  543. expect(output.operations[0]?.success).toBe("value")
  544. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  545. "Effect.map((value) => value.data)",
  546. )
  547. })
  548. test("maps no-content success to void", () => {
  549. const output = compile(
  550. api(HttpApiEndpoint.post("interrupt", "/session/:sessionID/interrupt", { success: HttpApiSchema.NoContent })),
  551. )
  552. expect(output.operations[0]?.success).toBe("void")
  553. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain('"httpApiStatus": 204')
  554. })
  555. test("preserves non-default empty response statuses", () => {
  556. const output = compile(api(HttpApiEndpoint.post("create", "/session", { success: HttpApiSchema.Created })))
  557. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain('"httpApiStatus": 201')
  558. })
  559. test("returns a non-envelope success unchanged", () => {
  560. const output = compile(api(HttpApiEndpoint.get("health", "/health", { success: Schema.String })))
  561. expect(output.operations[0]?.success).toBe("value")
  562. })
  563. test("rejects multiple success shapes until their public semantics are explicit", () => {
  564. expect(() =>
  565. compile(
  566. api(
  567. HttpApiEndpoint.get("get", "/session", {
  568. success: [Schema.String, Schema.Number],
  569. }),
  570. ),
  571. ),
  572. ).toThrow("Multiple success schemas: session.get")
  573. })
  574. test("models an SSE success as a direct stream", () => {
  575. const output = compile(
  576. api(
  577. HttpApiEndpoint.get("subscribe", "/event", {
  578. success: HttpApiSchema.StreamSse({ data: Schema.Struct({ type: Schema.String }) }),
  579. }),
  580. ),
  581. )
  582. expect(output.operations[0]?.success).toBe("stream")
  583. })
  584. test("preserves annotated stream response statuses", () => {
  585. const output = compile(
  586. api(
  587. HttpApiEndpoint.get("subscribe", "/event", {
  588. success: HttpApiSchema.StreamSse({ data: Schema.String }).pipe(HttpApiSchema.status(202)),
  589. }),
  590. ),
  591. )
  592. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  593. ".pipe(HttpApiSchema.status(202))",
  594. )
  595. })
  596. test("rejects schemas whose semantics cannot be emitted exactly", () => {
  597. const OpaqueUrl = Schema.declare((input): input is URL => input instanceof URL)
  598. expect(() => compile(api(HttpApiEndpoint.get("get", "/url", { success: OpaqueUrl })))).toThrow(
  599. "Unportable schema: session.get.success",
  600. )
  601. })
  602. test("rejects custom transformations hidden beneath standard HttpApi codecs", () => {
  603. const QueryBoolean = Schema.Literals(["yes", "no"]).pipe(
  604. Schema.decodeTo(Schema.Boolean, {
  605. decode: SchemaGetter.transform((value) => value === "yes"),
  606. encode: SchemaGetter.transform((value) => (value ? "yes" : "no")),
  607. }),
  608. )
  609. expect(() =>
  610. compile(
  611. api(
  612. HttpApiEndpoint.get("get", "/session", {
  613. query: { archived: QueryBoolean },
  614. success: Schema.String,
  615. }),
  616. ),
  617. ),
  618. ).toThrow("Effect schema requires authoritative import: session.get")
  619. })
  620. test("rejects custom validation checks without portable metadata", () => {
  621. const Positive = Schema.Number.check(Schema.makeFilter((value) => (value > 0 ? undefined : "positive")))
  622. expect(() => compile(api(HttpApiEndpoint.get("get", "/session", { success: Positive })))).toThrow(
  623. "Unportable schema: session.get.success",
  624. )
  625. })
  626. test("rejects spoofed and aborted validation checks", () => {
  627. const Spoofed = Schema.Number.check(
  628. Schema.makeFilter(() => "always fails", { meta: { _tag: "isFinite" }, arbitrary: {} }),
  629. )
  630. const Aborted = Schema.Number.check(Schema.isFinite().abort())
  631. expect(() => compile(api(HttpApiEndpoint.get("spoofed", "/session", { success: Spoofed })))).toThrow(
  632. "Unportable schema: session.spoofed.success",
  633. )
  634. expect(() => compile(api(HttpApiEndpoint.get("aborted", "/session", { success: Aborted })))).toThrow(
  635. "Unportable schema: session.aborted.success",
  636. )
  637. })
  638. test("rejects altered wire-side schemas even when the codec transformation is canonical", () => {
  639. const JsonNumber = Schema.toCodecJson(Schema.Number)
  640. const link = JsonNumber.ast.encoding?.[0]
  641. if (link === undefined) throw new Error("Expected JSON number encoding")
  642. // This helper is present at runtime but omitted from the public declaration surface.
  643. const replaceEncoding: unknown = Reflect.get(SchemaAST, "replaceEncoding")
  644. if (typeof replaceEncoding !== "function") throw new Error("Expected SchemaAST.replaceEncoding")
  645. const ast: unknown = replaceEncoding(JsonNumber.ast, [
  646. new SchemaAST.Link(Schema.String.check(Schema.isMinLength(2)).ast, link.transformation),
  647. ])
  648. if (!SchemaAST.isAST(ast)) throw new Error("Expected altered schema AST")
  649. const Altered = Schema.make(ast)
  650. expect(() => compile(api(HttpApiEndpoint.get("get", "/session", { success: Altered })))).toThrow(
  651. "Effect schema requires authoritative import: session.get",
  652. )
  653. })
  654. test("rejects lexical generation and annotation values", () => {
  655. const Generated = Schema.declare((input): input is string => typeof input === "string").annotate({
  656. generation: { runtime: "LocalOnly", Type: "string" },
  657. })
  658. const Annotated = Schema.declare((input): input is string => typeof input === "string").annotate({
  659. custom: () => "local",
  660. })
  661. expect(() => compile(api(HttpApiEndpoint.get("generated", "/session", { success: Generated })))).toThrow(
  662. "Unportable schema: session.generated.success",
  663. )
  664. expect(() => compile(api(HttpApiEndpoint.get("annotated", "/session", { success: Annotated })))).toThrow(
  665. "Unportable schema: session.annotated.success",
  666. )
  667. })
  668. test("preserves errors from server-only middleware", () => {
  669. class Unauthorized extends Schema.TaggedErrorClass<Unauthorized>()("Unauthorized", {}) {}
  670. class Authorization extends HttpApiMiddleware.Service<Authorization>()("Authorization", {
  671. error: Unauthorized,
  672. }) {}
  673. const output = compile(
  674. api(HttpApiEndpoint.get("get", "/session", { success: Schema.String }).middleware(Authorization)),
  675. )
  676. expect(output.operations[0]).toBeDefined()
  677. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  678. 'extends Schema.TaggedErrorClass<Endpoint0Error0Class>("Unauthorized")',
  679. )
  680. })
  681. test("preserves tagged error response statuses", () => {
  682. class Missing extends Schema.TaggedErrorClass<Missing>()("Missing", {}) {}
  683. const output = compile(
  684. api(
  685. HttpApiEndpoint.get("get", "/session", {
  686. success: Schema.String,
  687. error: Missing.pipe(HttpApiSchema.status(404)),
  688. }),
  689. ),
  690. )
  691. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  692. 'Endpoint0Error0Class.annotate({ "httpApiStatus": 404 })',
  693. )
  694. })
  695. test("supports every HttpApi method through the generic constructor", () => {
  696. const output = compile(api(HttpApiEndpoint.make("TRACE")("trace", "/trace", { success: Schema.String })))
  697. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain('HttpApiEndpoint.make("TRACE")')
  698. })
  699. test("uses safe unique module paths without changing public group identifiers", () => {
  700. const output = compile(
  701. HttpApi.make("test")
  702. .add(HttpApiGroup.make("../session").add(HttpApiEndpoint.get("get", "/session", { success: Schema.String })))
  703. .add(HttpApiGroup.make("GROUP-0").add(HttpApiEndpoint.get("list", "/session", { success: Schema.String }))),
  704. )
  705. expect(output.files.slice(0, 2).map((file) => file.path)).toEqual(["group-0.ts", "GROUP-0-1.ts"])
  706. expect(output.files[0]?.content).toContain('HttpApiGroup.make("../session"')
  707. })
  708. test("reserves support module names case-insensitively", () => {
  709. const output = compile(
  710. HttpApi.make("test")
  711. .add(HttpApiGroup.make("client").add(HttpApiEndpoint.get("get", "/client", { success: Schema.String })))
  712. .add(HttpApiGroup.make("INDEX").add(HttpApiEndpoint.get("get", "/index", { success: Schema.String }))),
  713. )
  714. expect(output.files.slice(0, 2).map((file) => file.path)).toEqual(["client-0.ts", "INDEX-1.ts"])
  715. })
  716. test("keeps searching when a reserved-name fallback is also occupied", () => {
  717. const output = compile(
  718. HttpApi.make("test")
  719. .add(HttpApiGroup.make("client-1").add(HttpApiEndpoint.get("first", "/first", { success: Schema.String })))
  720. .add(HttpApiGroup.make("client").add(HttpApiEndpoint.get("second", "/second", { success: Schema.String }))),
  721. )
  722. expect(output.files.slice(0, 2).map((file) => file.path)).toEqual(["client-1.ts", "client-1-1.ts"])
  723. })
  724. test("rejects collisions in the flattened client namespace", () => {
  725. expect(() =>
  726. compile(
  727. HttpApi.make("test")
  728. .add(HttpApiGroup.make("status").add(HttpApiEndpoint.get("get", "/nested", { success: Schema.String })))
  729. .add(
  730. HttpApiGroup.make("system", { topLevel: true }).add(
  731. HttpApiEndpoint.get("status", "/status", { success: Schema.String }),
  732. ),
  733. ),
  734. ),
  735. ).toThrow("Client name collision: status")
  736. })
  737. test("emits a usable raw type for top-level groups", () => {
  738. const output = compile(
  739. HttpApi.make("test").add(
  740. HttpApiGroup.make("health", { topLevel: true }).add(
  741. HttpApiEndpoint.get("check", "/health", { success: Schema.String }),
  742. ),
  743. ),
  744. )
  745. expect(output.files[0]?.content).toContain("type RawGroup = HttpApiClient.Client<typeof Group0")
  746. })
  747. it.effect("reports compiler failures in the generate Effect", () =>
  748. Effect.gen(function* () {
  749. const error = yield* generate(
  750. api(
  751. HttpApiEndpoint.get("get", "/url", {
  752. success: Schema.declare((input): input is URL => input instanceof URL),
  753. }),
  754. ),
  755. {
  756. directory: "/generated",
  757. },
  758. ).pipe(Effect.flip)
  759. expect(error).toBeInstanceOf(GenerationError)
  760. if (error instanceof GenerationError) expect(error.reason).toBe("Unportable schema: session.get.success")
  761. }).pipe(Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({}))),
  762. )
  763. test("rejects required client middleware without an adapter", () => {
  764. class SignedRequest extends HttpApiMiddleware.Service<SignedRequest>()("SignedRequest", {
  765. requiredForClient: true,
  766. }) {}
  767. expect(() =>
  768. compile(api(HttpApiEndpoint.get("get", "/session", { success: Schema.String }).middleware(SignedRequest))),
  769. ).toThrow("Client middleware requires adapter: SignedRequest")
  770. })
  771. test("maps transport and decode failures to one stable client error", () => {
  772. const output = compile(
  773. api(
  774. HttpApiEndpoint.get("get", "/session", {
  775. success: Schema.String,
  776. }),
  777. ),
  778. )
  779. expect(output.operations[0]?.errors).toContain("ClientError")
  780. expect(output.operations[0]?.errors).not.toContain("HttpClientError")
  781. expect(output.operations[0]?.errors).not.toContain("SchemaError")
  782. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  783. "new ClientError({ cause: error })",
  784. )
  785. })
  786. })