@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 401 lines 15.7 KB
Raw
1 import * as OpenApiGenerator from "@effect/openapi-generator/OpenApiGenerator"
2 import { assert, describe, it } from "@effect/vitest"
3 import * as Data from "effect/Data"
4 import * as Effect from "effect/Effect"
5 import * as Sse from "effect/encoding/Sse"
6 import type { OpenAPISpec } from "effect/http-api/OpenApi"
7 import * as HttpClient from "effect/http/HttpClient"
8 import * as HttpClientError from "effect/http/HttpClientError"
9 import * as HttpClientRequest from "effect/http/HttpClientRequest"
10 import * as HttpClientResponse from "effect/http/HttpClientResponse"
11 import * as Schema from "effect/Schema"
12 import * as Stream from "effect/Stream"
13 import { rolldown } from "rolldown"
14
15 const modules = {
16 "effect/Data": Data,
17 "effect/Effect": Effect,
18 "effect/Schema": Schema,
19 "effect/Stream": Stream,
20 "effect/encoding/Sse": Sse,
21 "effect/http/HttpClient": HttpClient,
22 "effect/http/HttpClientError": HttpClientError,
23 "effect/http/HttpClientRequest": HttpClientRequest,
24 "effect/http/HttpClientResponse": HttpClientResponse
25 }
26
27 type TransformClient = (client: HttpClient.HttpClient) => Effect.Effect<HttpClient.HttpClient>
28
29 async function loadClient<
30 Client = {
31 readStream: () => Stream.Stream<unknown, HttpClientError.HttpClientError>
32 readSse: () => Stream.Stream<unknown, HttpClientError.HttpClientError>
33 }
34 >(source: string) {
35 const bundle = await rolldown({
36 input: "client.ts",
37 external: (id) => id !== "client.ts",
38 plugins: [{
39 name: "generated-client",
40 resolveId: (id) => id === "client.ts" ? id : undefined,
41 load: (id) => id === "client.ts" ? source : undefined
42 }]
43 })
44 try {
45 const { output } = await bundle.generate({ format: "cjs" })
46 const compiled = output[0]
47 assert.strictEqual(compiled.type, "chunk")
48 const exports = {} as {
49 make: (httpClient: HttpClient.HttpClient, options?: { transformClient: TransformClient }) => Client
50 }
51 new Function("require", "exports", compiled.code)(
52 (id: keyof typeof modules) => {
53 assert.property(modules, id)
54 return modules[id]
55 },
56 exports
57 )
58 return exports.make
59 } finally {
60 await bundle.close()
61 }
62 }
63
64 const paths = [
65 { format: "httpclient", encoding: "binary" },
66 { format: "httpclient", encoding: "sse-data" },
67 { format: "httpclient", encoding: "sse-event" },
68 { format: "httpclient-type-only", encoding: "binary" },
69 { format: "httpclient-type-only", encoding: "sse-data" }
70 ] as const
71
72 describe("OpenApiTransformer", () => {
73 it.effect("returns only the body when a nullable response config is undefined", () =>
74 Effect.gen(function*() {
75 const spec: OpenAPISpec = {
76 openapi: "3.1.0",
77 info: { title: "Nullable include response", version: "1.0.0" },
78 components: { schemas: {}, securitySchemes: {} },
79 security: [],
80 tags: [],
81 paths: {
82 "/value": {
83 get: {
84 operationId: "getValue",
85 parameters: [],
86 tags: ["Value"],
87 security: [],
88 responses: {
89 "200": {
90 description: "Value",
91 content: { "application/json": { schema: { type: "string" } } }
92 }
93 }
94 }
95 }
96 }
97 }
98 for (const format of ["httpclient", "httpclient-type-only"] as const) {
99 const source = yield* Effect.gen(function*() {
100 const generator = yield* OpenApiGenerator.OpenApiGenerator
101 return yield* generator.generate(spec, { name: "TestClient", format })
102 }).pipe(Effect.provide(
103 format === "httpclient"
104 ? OpenApiGenerator.layerTransformerSchema
105 : OpenApiGenerator.layerTransformerTs
106 ))
107 const make = yield* Effect.promise(() =>
108 loadClient<{
109 getValue: (options?: { config?: { includeResponse?: boolean } | undefined }) => Effect.Effect<unknown>
110 }>(source)
111 )
112 const client = make(
113 HttpClient.make((request) =>
114 Effect.succeed(HttpClientResponse.fromWeb(request, new Response(JSON.stringify("hello"))))
115 ).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl("https://example.com")))
116 )
117
118 const body = yield* client.getValue({ config: undefined })
119 assert.strictEqual(body, "hello")
120
121 const withResponse = yield* client.getValue({ config: { includeResponse: true } })
122 if (!Array.isArray(withResponse)) throw new Error("Expected response tuple")
123 assert.strictEqual(withResponse[0], "hello")
124 assert.strictEqual((withResponse[1] as HttpClientResponse.HttpClientResponse).status, 200)
125 }
126 }))
127
128 it.effect("joins non-exploded form query arrays", () =>
129 Effect.gen(function*() {
130 const generator = yield* OpenApiGenerator.OpenApiGenerator
131 const source = yield* generator.generate({
132 openapi: "3.1.0",
133 info: { title: "Items", version: "1.0.0" },
134 paths: {
135 "/items": {
136 get: {
137 operationId: "list",
138 parameters: [
139 { name: "tags", in: "query", explode: false, schema: { type: "array" } },
140 { name: "ids", in: "query", schema: { type: "array" } }
141 ],
142 responses: { "204": { description: "No content" } }
143 }
144 }
145 }
146 } as unknown as OpenAPISpec, { name: "TestClient", format: "httpclient-type-only" })
147 const make = yield* Effect.promise(() =>
148 loadClient<{ list: (options: { params: object }) => Effect.Effect<unknown> }>(source)
149 )
150 let search = ""
151 const client = make(
152 HttpClient.make((request, url) => {
153 search = url.search
154 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status: 204 })))
155 }).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl("https://example.com")))
156 )
157 yield* client.list({ params: { tags: ["a", "b"], ids: [1, 2] } })
158 assert.strictEqual(search, "?tags=a%2Cb&ids=1&ids=2")
159 }).pipe(Effect.provide(OpenApiGenerator.layerTransformerTs)))
160
161 describe("path parameters", () => {
162 const generate = Effect.gen(function*() {
163 const generator = yield* OpenApiGenerator.OpenApiGenerator
164 const source = yield* generator.generate({
165 openapi: "3.1.0",
166 info: { title: "Files", version: "1.0.0" },
167 components: { schemas: {}, securitySchemes: {} },
168 security: [],
169 tags: [],
170 paths: {
171 "/files/{id}/content": {
172 get: {
173 operationId: "read",
174 parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
175 tags: ["Files"],
176 security: [],
177 responses: {
178 "200": {
179 description: "File contents",
180 content: { "application/octet-stream": { schema: { type: "string" } } }
181 }
182 }
183 }
184 }
185 }
186 }, { name: "TestClient", format: "httpclient-type-only" })
187 return yield* Effect.promise(() =>
188 loadClient<{
189 read: (id: string) => Effect.Effect<unknown, HttpClientError.HttpClientError>
190 readStream: (id: string) => Stream.Stream<unknown, HttpClientError.HttpClientError>
191 }>(source)
192 )
193 }).pipe(Effect.provide(OpenApiGenerator.layerTransformerTs))
194
195 it.effect("percent-encodes each parameter as one path segment", () =>
196 Effect.gen(function*() {
197 const make = yield* generate
198 const urls: Array<string> = []
199 const client = make(
200 HttpClient.make((request, url) => {
201 urls.push(url.href)
202 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response("")))
203 }).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl("https://example.com")))
204 )
205 for (
206 const [value, encoded] of [
207 ["alice", "alice"],
208 ["../a/b?c#d\\e%20", "..%2Fa%2Fb%3Fc%23d%5Ce%2520"],
209 ["hello world/é", "hello%20world%2F%C3%A9"]
210 ]
211 ) {
212 yield* client.read(value)
213 assert.strictEqual(urls.at(-1), `https://example.com/files/${encoded}/content`)
214 }
215 assert.strictEqual(urls.length, 3)
216 }))
217
218 it.effect("rejects empty and dot parameters with a typed error before sending", () =>
219 Effect.gen(function*() {
220 const make = yield* generate
221 let requests = 0
222 const client = make(
223 HttpClient.make(() => {
224 requests++
225 return Effect.die("Unexpected request")
226 }).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl("https://example.com")))
227 )
228 for (const value of ["", ".", ".."]) {
229 const error = yield* Effect.flip(client.read(value))
230 assert.instanceOf(error, HttpClientError.HttpClientError)
231 assert.instanceOf(error.reason, HttpClientError.InvalidUrlError)
232 }
233 assert.strictEqual(requests, 0)
234 }))
235
236 it.effect("propagates path rejection through the stream error channel", () =>
237 Effect.gen(function*() {
238 const make = yield* generate
239 let requests = 0
240 const client = make(
241 HttpClient.make(() => {
242 requests++
243 return Effect.die("Unexpected request")
244 }).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl("https://example.com")))
245 )
246 const error = yield* Effect.flip(Stream.runCollect(client.readStream("..")))
247 assert.instanceOf(error, HttpClientError.HttpClientError)
248 assert.instanceOf(error.reason, HttpClientError.InvalidUrlError)
249 assert.strictEqual(requests, 0)
250 }))
251 })
252
253 for (const { encoding, format } of paths) {
254 const binary = encoding === "binary"
255 const body = binary
256 ? "download"
257 : encoding === "sse-event"
258 ? "event: message\nid: 1\ndata: hello\n\n"
259 : "event: message\nid: 1\ndata: \"hello\"\n\n"
260 const expected = binary
261 ? [new TextEncoder().encode(body)]
262 : format === "httpclient-type-only"
263 ? ["hello"]
264 : [{ event: "message", id: "1", data: "hello" }]
265 const spec: OpenAPISpec = {
266 openapi: "3.1.0",
267 info: { title: "Streaming API", version: "1.0.0" },
268 components: { schemas: {}, securitySchemes: {} },
269 security: [],
270 tags: [],
271 paths: {
272 "/read": {
273 get: {
274 operationId: "read",
275 parameters: [],
276 tags: ["Streams"],
277 security: [],
278 responses: {
279 "200": {
280 description: "Success",
281 content: {
282 [binary ? "application/octet-stream" : "text/event-stream"]: {
283 schema: encoding === "sse-event"
284 ? {
285 type: "object",
286 properties: {
287 id: { anyOf: [{ type: "string" }, { type: "null" }] },
288 event: { const: "message" },
289 data: { type: "string" }
290 },
291 required: ["id", "event", "data"],
292 additionalProperties: false
293 }
294 : { type: "string" },
295 ...(encoding === "sse-event"
296 ? {
297 "x-effect-stream": {
298 encoding: "sse",
299 errorSchema: {},
300 causeSchema: {},
301 failureEvent: "effect/http-api/stream/failure"
302 }
303 }
304 : {})
305 }
306 }
307 }
308 }
309 }
310 }
311 }
312 }
313 const generate = Effect.gen(function*() {
314 const generator = yield* OpenApiGenerator.OpenApiGenerator
315 const source = yield* generator.generate(spec, { name: "TestClient", format })
316 return yield* Effect.promise(() => loadClient(source))
317 }).pipe(Effect.provide(
318 format === "httpclient" ? OpenApiGenerator.layerTransformerSchema : OpenApiGenerator.layerTransformerTs
319 ))
320
321 describe(`${format} ${encoding}`, () => {
322 it.effect("defers transformation and applies fresh headers on each consumption", () =>
323 Effect.gen(function*() {
324 const make = yield* generate
325 const requests: Array<HttpClientRequest.HttpClientRequest> = []
326 let transforms = 0
327 let transformEffects = 0
328 const httpClient = HttpClient.make((request) => {
329 requests.push(request)
330 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body)))
331 }).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl("https://example.com")))
332 const client = make(httpClient, {
333 transformClient: (client) => {
334 transforms++
335 return Effect.sync(() => {
336 transformEffects++
337 return HttpClient.mapRequest(client, HttpClientRequest.setHeader("x-transformed", String(transforms)))
338 })
339 }
340 })
341 const stream = binary ? client.readStream() : client.readSse()
342 assert.strictEqual(transforms, 0)
343 assert.strictEqual(transformEffects, 0)
344 assert.deepStrictEqual(requests, [])
345 for (let run = 1; run <= 2; run++) {
346 assert.deepStrictEqual(yield* Stream.runCollect(stream), expected)
347 assert.strictEqual(requests.length, run)
348 assert.strictEqual(requests[run - 1].headers["x-transformed"], String(run))
349 assert.strictEqual(transforms, run)
350 assert.strictEqual(transformEffects, run)
351 }
352 }))
353
354 it.effect("filters the response returned by the transformed client", () =>
355 Effect.gen(function*() {
356 const make = yield* generate
357 const httpClient = HttpClient.make((request) =>
358 Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body)))
359 ).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl("https://example.com")))
360 const client = make(httpClient, {
361 transformClient: (client) =>
362 Effect.succeed(HttpClient.transformResponse(
363 client,
364 Effect.map((response) =>
365 HttpClientResponse.fromWeb(response.request, new Response(body, { status: 403 }))
366 )
367 ))
368 })
369 const stream = binary ? client.readStream() : client.readSse()
370 const error = yield* Effect.flip(Stream.runCollect(stream))
371 assert.strictEqual(error._tag, "HttpClientError")
372 assert.strictEqual(error.reason._tag, "StatusCodeError")
373 if (error.reason._tag === "StatusCodeError") {
374 assert.strictEqual(error.reason.response.status, 403)
375 }
376 }))
377
378 for (const status of [200, 403]) {
379 it.effect(`preserves status ${status} handling without a transform`, () =>
380 Effect.gen(function*() {
381 const make = yield* generate
382 let requests = 0
383 const httpClient = HttpClient.make((request) => {
384 requests++
385 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body, { status })))
386 }).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl("https://example.com")))
387 const client = make(httpClient)
388 const stream = binary ? client.readStream() : client.readSse()
389 assert.strictEqual(requests, 0)
390 if (status === 200) {
391 assert.deepStrictEqual(yield* Stream.runCollect(stream), expected)
392 } else {
393 const error = yield* Effect.flip(Stream.runCollect(stream))
394 assert.strictEqual(error.reason._tag, "StatusCodeError")
395 }
396 assert.strictEqual(requests, 1)
397 }))
398 }
399 })
400 }
401 })