generate.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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({
  357. data: Schema.Struct({ type: Schema.String, count: Schema.NumberFromString }),
  358. }),
  359. }),
  360. ),
  361. ),
  362. )
  363. const directory = await mkdtemp(join(tmpdir(), "opencode-httpapi-codegen-"))
  364. try {
  365. await Promise.all(output.files.map((file) => Bun.write(join(directory, file.path), file.content)))
  366. const generated = await import(`${join(directory, "index.ts")}?t=${crypto.randomUUID()}`)
  367. let requests = 0
  368. let url: string | undefined
  369. const client = generated.OpenCode.make({
  370. baseUrl: "https://example.com",
  371. fetch: async (input: RequestInfo | URL) => {
  372. requests++
  373. url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url
  374. const encoder = new TextEncoder()
  375. return new Response(
  376. new ReadableStream({
  377. start(controller) {
  378. controller.enqueue(encoder.encode('data: {"type":"ready","count":"1"}\r'))
  379. controller.enqueue(encoder.encode("\n\r\n"))
  380. controller.close()
  381. },
  382. }),
  383. { headers: { "content-type": "text/event-stream" } },
  384. )
  385. },
  386. })
  387. const events = client.session.subscribe({ after: 2 })
  388. expect(requests).toBe(0)
  389. const received = []
  390. for await (const event of events) received.push(event)
  391. expect(received).toEqual([{ type: "ready", count: "1" }])
  392. expect(requests).toBe(1)
  393. expect(url).toBe("https://example.com/event?after=2")
  394. } finally {
  395. await rm(directory, { recursive: true, force: true })
  396. }
  397. })
  398. test("preserves public group and endpoint identifiers exactly", () => {
  399. const output = compile(
  400. HttpApi.make("test").add(
  401. HttpApiGroup.make("session").add(HttpApiEndpoint.get("get", "/session/:sessionID", { success: Schema.String })),
  402. ),
  403. )
  404. expect(output.operations[0]).toMatchObject({ group: "session", name: "get" })
  405. })
  406. test("emits one client module per HttpApi group", () => {
  407. const source = HttpApi.make("test")
  408. .add(HttpApiGroup.make("session").add(HttpApiEndpoint.get("get", "/session", { success: Schema.String })))
  409. .add(HttpApiGroup.make("tool").add(HttpApiEndpoint.get("list", "/tool", { success: Schema.String })))
  410. const output = compile(source)
  411. expect(output.files.map((file) => file.path)).toEqual([
  412. "session.ts",
  413. "tool.ts",
  414. "client-error.ts",
  415. "client.ts",
  416. "index.ts",
  417. ])
  418. })
  419. test("emits syntactically valid TypeScript modules", () => {
  420. const output = compile(
  421. api(
  422. HttpApiEndpoint.get("get", "/session/:sessionID", {
  423. params: { sessionID: Schema.String },
  424. success: Schema.Struct({ data: Schema.String }),
  425. }),
  426. ),
  427. )
  428. const transpiler = new Bun.Transpiler({ loader: "ts" })
  429. for (const file of output.files) expect(() => transpiler.transformSync(file.content)).not.toThrow()
  430. })
  431. it.effect("keeps the strict generated-consumer fixture current", () =>
  432. Effect.gen(function* () {
  433. const output = compile(FixtureApi)
  434. const actual = yield* Effect.promise(() =>
  435. Array.fromAsync(new Bun.Glob("*.ts").scan(new URL("generated", import.meta.url).pathname)),
  436. )
  437. expect(actual.sort((a, b) => a.localeCompare(b))).toEqual(
  438. output.files.map((file) => file.path).sort((a, b) => a.localeCompare(b)),
  439. )
  440. yield* Effect.forEach(output.files, (file) =>
  441. Effect.tryPromise(() =>
  442. Promise.all([
  443. Bun.file(new URL(`generated/${file.path}`, import.meta.url)).text(),
  444. format(file.content, { parser: "typescript", semi: false, printWidth: 120 }),
  445. ]),
  446. ).pipe(Effect.map(([content, expected]) => expect(content).toBe(expected))),
  447. )
  448. }),
  449. )
  450. test("flattens transport input channels into one domain input", () => {
  451. const output = compile(
  452. api(
  453. HttpApiEndpoint.post("prompt", "/session/:sessionID", {
  454. params: { sessionID: Schema.String },
  455. query: { resume: Schema.String },
  456. headers: { traceID: Schema.String },
  457. payload: Schema.Struct({ prompt: Schema.String }),
  458. success: Schema.Struct({ data: Schema.String }),
  459. }),
  460. ),
  461. )
  462. expect(output.operations[0]?.input).toEqual([
  463. { name: "sessionID", source: "params" },
  464. { name: "resume", source: "query" },
  465. { name: "traceID", source: "headers" },
  466. { name: "prompt", source: "payload" },
  467. ])
  468. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  469. 'params: { "sessionID": input["sessionID"] }',
  470. )
  471. })
  472. test("uses no argument when an operation has no input fields", () => {
  473. const output = compile(api(HttpApiEndpoint.get("health", "/health", { success: Schema.String })))
  474. expect(output.operations[0]?.inputMode).toBe("none")
  475. })
  476. test("uses an optional object when every input field is optional", () => {
  477. const output = compile(
  478. api(
  479. HttpApiEndpoint.get("list", "/session", {
  480. query: { limit: Schema.optional(Schema.String) },
  481. success: Schema.Array(Schema.String),
  482. }),
  483. ),
  484. )
  485. expect(output.operations[0]?.inputMode).toBe("optional")
  486. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain('input?.["limit"]')
  487. })
  488. test("regenerates standard HttpApi transport codecs from decoded schemas", () => {
  489. const output = compile(
  490. api(
  491. HttpApiEndpoint.get("list", "/session", {
  492. query: { archived: Schema.optional(Schema.Boolean) },
  493. success: Schema.String,
  494. }),
  495. ),
  496. )
  497. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain("Schema.Boolean")
  498. })
  499. test("uses a required object when any input field is required", () => {
  500. const output = compile(
  501. api(
  502. HttpApiEndpoint.get("get", "/session/:sessionID", {
  503. params: { sessionID: Schema.String },
  504. query: { includeArchived: Schema.optional(Schema.String) },
  505. success: Schema.String,
  506. }),
  507. ),
  508. )
  509. expect(output.operations[0]?.inputMode).toBe("required")
  510. })
  511. test("rejects colliding input names across transport channels", () => {
  512. expect(() =>
  513. compile(
  514. api(
  515. HttpApiEndpoint.post("prompt", "/session/:id", {
  516. params: { id: Schema.String },
  517. payload: Schema.Struct({ id: Schema.String }),
  518. success: Schema.Void,
  519. }),
  520. ),
  521. ),
  522. ).toThrow("Input field collision: id")
  523. })
  524. test("rejects multiple payload alternatives until selection semantics are explicit", () => {
  525. expect(() =>
  526. compile(
  527. api(
  528. HttpApiEndpoint.post("prompt", "/session", {
  529. payload: [Schema.Struct({ text: Schema.String }), Schema.Struct({ count: Schema.Number })],
  530. success: Schema.String,
  531. }),
  532. ),
  533. ),
  534. ).toThrow("Multiple payload schemas: session.prompt")
  535. })
  536. test("unwraps an exact data success envelope", () => {
  537. const output = compile(
  538. api(
  539. HttpApiEndpoint.get("get", "/session/:sessionID", {
  540. params: { sessionID: Schema.String },
  541. success: Schema.Struct({ data: Schema.String }),
  542. }),
  543. ),
  544. )
  545. expect(output.operations[0]?.success).toBe("value")
  546. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  547. "Effect.map((value) => value.data)",
  548. )
  549. })
  550. test("maps no-content success to void", () => {
  551. const output = compile(
  552. api(HttpApiEndpoint.post("interrupt", "/session/:sessionID/interrupt", { success: HttpApiSchema.NoContent })),
  553. )
  554. expect(output.operations[0]?.success).toBe("void")
  555. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain('"httpApiStatus": 204')
  556. })
  557. test("preserves non-default empty response statuses", () => {
  558. const output = compile(api(HttpApiEndpoint.post("create", "/session", { success: HttpApiSchema.Created })))
  559. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain('"httpApiStatus": 201')
  560. })
  561. test("returns a non-envelope success unchanged", () => {
  562. const output = compile(api(HttpApiEndpoint.get("health", "/health", { success: Schema.String })))
  563. expect(output.operations[0]?.success).toBe("value")
  564. })
  565. test("rejects multiple success shapes until their public semantics are explicit", () => {
  566. expect(() =>
  567. compile(
  568. api(
  569. HttpApiEndpoint.get("get", "/session", {
  570. success: [Schema.String, Schema.Number],
  571. }),
  572. ),
  573. ),
  574. ).toThrow("Multiple success schemas: session.get")
  575. })
  576. test("models an SSE success as a direct stream", () => {
  577. const output = compile(
  578. api(
  579. HttpApiEndpoint.get("subscribe", "/event", {
  580. success: HttpApiSchema.StreamSse({ data: Schema.Struct({ type: Schema.String }) }),
  581. }),
  582. ),
  583. )
  584. expect(output.operations[0]?.success).toBe("stream")
  585. })
  586. test("preserves annotated stream response statuses", () => {
  587. const output = compile(
  588. api(
  589. HttpApiEndpoint.get("subscribe", "/event", {
  590. success: HttpApiSchema.StreamSse({ data: Schema.String }).pipe(HttpApiSchema.status(202)),
  591. }),
  592. ),
  593. )
  594. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  595. ".pipe(HttpApiSchema.status(202))",
  596. )
  597. })
  598. test("rejects schemas whose semantics cannot be emitted exactly", () => {
  599. const OpaqueUrl = Schema.declare((input): input is URL => input instanceof URL)
  600. expect(() => compile(api(HttpApiEndpoint.get("get", "/url", { success: OpaqueUrl })))).toThrow(
  601. "Unportable schema: session.get.success",
  602. )
  603. })
  604. test("rejects custom transformations hidden beneath standard HttpApi codecs", () => {
  605. const QueryBoolean = Schema.Literals(["yes", "no"]).pipe(
  606. Schema.decodeTo(Schema.Boolean, {
  607. decode: SchemaGetter.transform((value) => value === "yes"),
  608. encode: SchemaGetter.transform((value) => (value ? "yes" : "no")),
  609. }),
  610. )
  611. expect(() =>
  612. compile(
  613. api(
  614. HttpApiEndpoint.get("get", "/session", {
  615. query: { archived: QueryBoolean },
  616. success: Schema.String,
  617. }),
  618. ),
  619. ),
  620. ).toThrow("Effect schema requires authoritative import: session.get")
  621. })
  622. test("rejects custom validation checks without portable metadata", () => {
  623. const Positive = Schema.Number.check(Schema.makeFilter((value) => (value > 0 ? undefined : "positive")))
  624. expect(() => compile(api(HttpApiEndpoint.get("get", "/session", { success: Positive })))).toThrow(
  625. "Unportable schema: session.get.success",
  626. )
  627. })
  628. test("rejects spoofed and aborted validation checks", () => {
  629. const Spoofed = Schema.Number.check(
  630. Schema.makeFilter(() => "always fails", { meta: { _tag: "isFinite" }, arbitrary: {} }),
  631. )
  632. const Aborted = Schema.Number.check(Schema.isFinite().abort())
  633. expect(() => compile(api(HttpApiEndpoint.get("spoofed", "/session", { success: Spoofed })))).toThrow(
  634. "Unportable schema: session.spoofed.success",
  635. )
  636. expect(() => compile(api(HttpApiEndpoint.get("aborted", "/session", { success: Aborted })))).toThrow(
  637. "Unportable schema: session.aborted.success",
  638. )
  639. })
  640. test("rejects altered wire-side schemas even when the codec transformation is canonical", () => {
  641. const JsonNumber = Schema.toCodecJson(Schema.Number)
  642. const link = JsonNumber.ast.encoding?.[0]
  643. if (link === undefined) throw new Error("Expected JSON number encoding")
  644. // This helper is present at runtime but omitted from the public declaration surface.
  645. const replaceEncoding: unknown = Reflect.get(SchemaAST, "replaceEncoding")
  646. if (typeof replaceEncoding !== "function") throw new Error("Expected SchemaAST.replaceEncoding")
  647. const ast: unknown = replaceEncoding(JsonNumber.ast, [
  648. new SchemaAST.Link(Schema.String.check(Schema.isMinLength(2)).ast, link.transformation),
  649. ])
  650. if (!SchemaAST.isAST(ast)) throw new Error("Expected altered schema AST")
  651. const Altered = Schema.make(ast)
  652. expect(() => compile(api(HttpApiEndpoint.get("get", "/session", { success: Altered })))).toThrow(
  653. "Effect schema requires authoritative import: session.get",
  654. )
  655. })
  656. test("rejects lexical generation and annotation values", () => {
  657. const Generated = Schema.declare((input): input is string => typeof input === "string").annotate({
  658. generation: { runtime: "LocalOnly", Type: "string" },
  659. })
  660. const Annotated = Schema.declare((input): input is string => typeof input === "string").annotate({
  661. custom: () => "local",
  662. })
  663. expect(() => compile(api(HttpApiEndpoint.get("generated", "/session", { success: Generated })))).toThrow(
  664. "Unportable schema: session.generated.success",
  665. )
  666. expect(() => compile(api(HttpApiEndpoint.get("annotated", "/session", { success: Annotated })))).toThrow(
  667. "Unportable schema: session.annotated.success",
  668. )
  669. })
  670. test("preserves errors from server-only middleware", () => {
  671. class Unauthorized extends Schema.TaggedErrorClass<Unauthorized>()("Unauthorized", {}) {}
  672. class Authorization extends HttpApiMiddleware.Service<Authorization>()("Authorization", {
  673. error: Unauthorized,
  674. }) {}
  675. const output = compile(
  676. api(HttpApiEndpoint.get("get", "/session", { success: Schema.String }).middleware(Authorization)),
  677. )
  678. expect(output.operations[0]).toBeDefined()
  679. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  680. 'extends Schema.TaggedErrorClass<Endpoint0Error0Class>("Unauthorized")',
  681. )
  682. })
  683. test("preserves tagged error response statuses", () => {
  684. class Missing extends Schema.TaggedErrorClass<Missing>()("Missing", {}) {}
  685. const output = compile(
  686. api(
  687. HttpApiEndpoint.get("get", "/session", {
  688. success: Schema.String,
  689. error: Missing.pipe(HttpApiSchema.status(404)),
  690. }),
  691. ),
  692. )
  693. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  694. 'Endpoint0Error0Class.annotate({ "httpApiStatus": 404 })',
  695. )
  696. })
  697. test("supports every HttpApi method through the generic constructor", () => {
  698. const output = compile(api(HttpApiEndpoint.make("TRACE")("trace", "/trace", { success: Schema.String })))
  699. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain('HttpApiEndpoint.make("TRACE")')
  700. })
  701. test("uses safe unique module paths without changing public group identifiers", () => {
  702. const output = compile(
  703. HttpApi.make("test")
  704. .add(HttpApiGroup.make("../session").add(HttpApiEndpoint.get("get", "/session", { success: Schema.String })))
  705. .add(HttpApiGroup.make("GROUP-0").add(HttpApiEndpoint.get("list", "/session", { success: Schema.String }))),
  706. )
  707. expect(output.files.slice(0, 2).map((file) => file.path)).toEqual(["group-0.ts", "GROUP-0-1.ts"])
  708. expect(output.files[0]?.content).toContain('HttpApiGroup.make("../session"')
  709. })
  710. test("reserves support module names case-insensitively", () => {
  711. const output = compile(
  712. HttpApi.make("test")
  713. .add(HttpApiGroup.make("client").add(HttpApiEndpoint.get("get", "/client", { success: Schema.String })))
  714. .add(HttpApiGroup.make("INDEX").add(HttpApiEndpoint.get("get", "/index", { success: Schema.String }))),
  715. )
  716. expect(output.files.slice(0, 2).map((file) => file.path)).toEqual(["client-0.ts", "INDEX-1.ts"])
  717. })
  718. test("keeps searching when a reserved-name fallback is also occupied", () => {
  719. const output = compile(
  720. HttpApi.make("test")
  721. .add(HttpApiGroup.make("client-1").add(HttpApiEndpoint.get("first", "/first", { success: Schema.String })))
  722. .add(HttpApiGroup.make("client").add(HttpApiEndpoint.get("second", "/second", { success: Schema.String }))),
  723. )
  724. expect(output.files.slice(0, 2).map((file) => file.path)).toEqual(["client-1.ts", "client-1-1.ts"])
  725. })
  726. test("rejects collisions in the flattened client namespace", () => {
  727. expect(() =>
  728. compile(
  729. HttpApi.make("test")
  730. .add(HttpApiGroup.make("status").add(HttpApiEndpoint.get("get", "/nested", { success: Schema.String })))
  731. .add(
  732. HttpApiGroup.make("system", { topLevel: true }).add(
  733. HttpApiEndpoint.get("status", "/status", { success: Schema.String }),
  734. ),
  735. ),
  736. ),
  737. ).toThrow("Client name collision: status")
  738. })
  739. test("emits a usable raw type for top-level groups", () => {
  740. const output = compile(
  741. HttpApi.make("test").add(
  742. HttpApiGroup.make("health", { topLevel: true }).add(
  743. HttpApiEndpoint.get("check", "/health", { success: Schema.String }),
  744. ),
  745. ),
  746. )
  747. expect(output.files[0]?.content).toContain("type RawGroup = HttpApiClient.Client<typeof Group0")
  748. })
  749. it.effect("reports compiler failures in the generate Effect", () =>
  750. Effect.gen(function* () {
  751. const error = yield* generate(
  752. api(
  753. HttpApiEndpoint.get("get", "/url", {
  754. success: Schema.declare((input): input is URL => input instanceof URL),
  755. }),
  756. ),
  757. {
  758. directory: "/generated",
  759. },
  760. ).pipe(Effect.flip)
  761. expect(error).toBeInstanceOf(GenerationError)
  762. if (error instanceof GenerationError) expect(error.reason).toBe("Unportable schema: session.get.success")
  763. }).pipe(Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({}))),
  764. )
  765. test("rejects required client middleware without an adapter", () => {
  766. class SignedRequest extends HttpApiMiddleware.Service<SignedRequest>()("SignedRequest", {
  767. requiredForClient: true,
  768. }) {}
  769. expect(() =>
  770. compile(api(HttpApiEndpoint.get("get", "/session", { success: Schema.String }).middleware(SignedRequest))),
  771. ).toThrow("Client middleware requires adapter: SignedRequest")
  772. })
  773. test("maps transport and decode failures to one stable client error", () => {
  774. const output = compile(
  775. api(
  776. HttpApiEndpoint.get("get", "/session", {
  777. success: Schema.String,
  778. }),
  779. ),
  780. )
  781. expect(output.operations[0]?.errors).toContain("ClientError")
  782. expect(output.operations[0]?.errors).not.toContain("HttpClientError")
  783. expect(output.operations[0]?.errors).not.toContain("SchemaError")
  784. expect(output.files.find((file) => file.path === "session.ts")?.content).toContain(
  785. "new ClientError({ cause: error })",
  786. )
  787. })
  788. })