@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 4,035 lines 140 KB
Raw
1 import * as OpenApiGenerator from "@effect/openapi-generator/OpenApiGenerator"
2 import { assert, describe, it } from "@effect/vitest"
3 import * as Effect from "effect/Effect"
4 import * as Exit from "effect/Exit"
5 import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/http-api"
6 import type { OpenAPISpec, OpenAPISpecOperation, OpenAPISpecPathItem } from "effect/http-api/OpenApi"
7 import * as HttpClient from "effect/http/HttpClient"
8 import * as HttpClientRequest from "effect/http/HttpClientRequest"
9 import * as HttpClientResponse from "effect/http/HttpClientResponse"
10 import type * as JsonSchema from "effect/JsonSchema"
11 import * as Schema from "effect/Schema"
12 import { spawn } from "node:child_process"
13 import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
14 import { dirname, join } from "node:path"
15 import { fileURLToPath } from "node:url"
16
17 // The first compile check starts the shared TypeScript compiler runs under CI load.
18 const compilationTimeout = 60_000
19
20 const assertRuntime = Effect.fnUntraced(function*(spec: OpenAPISpec, expected: string) {
21 const generator = yield* OpenApiGenerator.OpenApiGenerator
22
23 const result = yield* generator.generate(spec, {
24 name: "TestClient",
25 format: "httpclient"
26 })
27
28 // console.log(result)
29 assert.strictEqual(result, expected)
30 }, Effect.provide(OpenApiGenerator.layerTransformerSchema))
31
32 const assertTypeOnly = Effect.fnUntraced(function*(spec: OpenAPISpec, expected: string) {
33 const generator = yield* OpenApiGenerator.OpenApiGenerator
34
35 const result = yield* generator.generate(spec, {
36 name: "TestClient",
37 format: "httpclient-type-only"
38 })
39
40 // console.log(result)
41 assert.strictEqual(result, expected)
42 }, Effect.provide(OpenApiGenerator.layerTransformerTs))
43
44 const assertRuntimeIncludes = Effect.fnUntraced(function*(
45 spec: OpenAPISpec,
46 includes: ReadonlyArray<string>,
47 excludes: ReadonlyArray<string> = []
48 ) {
49 const generator = yield* OpenApiGenerator.OpenApiGenerator
50
51 const result = yield* generator.generate(spec, {
52 name: "TestClient",
53 format: "httpclient"
54 })
55
56 for (const expected of includes) {
57 assert.include(result, expected)
58 }
59 for (const excluded of excludes) {
60 assert.notInclude(result, excluded)
61 }
62 }, Effect.provide(OpenApiGenerator.layerTransformerSchema))
63
64 const assertTypeOnlyIncludes = Effect.fnUntraced(function*(
65 spec: OpenAPISpec,
66 includes: ReadonlyArray<string>,
67 excludes: ReadonlyArray<string> = []
68 ) {
69 const generator = yield* OpenApiGenerator.OpenApiGenerator
70
71 const result = yield* generator.generate(spec, {
72 name: "TestClient",
73 format: "httpclient-type-only"
74 })
75
76 for (const expected of includes) {
77 assert.include(result, expected)
78 }
79 for (const excluded of excludes) {
80 assert.notInclude(result, excluded)
81 }
82 }, Effect.provide(OpenApiGenerator.layerTransformerTs))
83
84 interface CompileOptions {
85 readonly exactOptionalPropertyTypes?: boolean | undefined
86 readonly formats?: ReadonlyArray<"httpclient" | "httpclient-type-only"> | undefined
87 readonly usage?: string | undefined
88 }
89
90 const repositoryRoot = join(dirname(fileURLToPath(import.meta.url)), "../../../..")
91
92 // Every case is registered while the file is collected, so a single compiler
93 // run per tsconfig variant can check all generated clients.
94 const compileCases: Array<{ readonly spec: OpenAPISpec; readonly options: CompileOptions }> = []
95
96 const generateClients = ({ options, spec }: (typeof compileCases)[number]) => {
97 const generate = (
98 format: "httpclient" | "httpclient-type-only",
99 layer: typeof OpenApiGenerator.layerTransformerSchema
100 ) =>
101 Effect.gen(function*() {
102 const generator = yield* OpenApiGenerator.OpenApiGenerator
103 return yield* generator.generate(spec, { name: "TestClient", format })
104 }).pipe(Effect.provide(layer))
105
106 const formats = options.formats ?? ["httpclient", "httpclient-type-only"]
107 return Effect.all(formats.map((format) =>
108 generate(
109 format,
110 format === "httpclient"
111 ? OpenApiGenerator.layerTransformerSchema
112 : OpenApiGenerator.layerTransformerTs
113 ).pipe(Effect.map((client) => `${client}\n${options.usage ?? ""}`))
114 ))
115 }
116
117 const runTsc = (configPath: string) =>
118 Effect.callback<{ readonly status: number | null; readonly output: string }>((resume) => {
119 const child = spawn(join(repositoryRoot, "node_modules/.bin/tsc"), ["-p", configPath, "--pretty", "false"], {
120 cwd: repositoryRoot
121 })
122 let output = ""
123 child.stdout.on("data", (chunk) => output += chunk)
124 child.stderr.on("data", (chunk) => output += chunk)
125 child.on("error", (error) => resume(Effect.die(error)))
126 child.on("close", (status) => resume(Effect.succeed({ status, output })))
127 return Effect.sync(() => child.kill())
128 })
129
130 // Each diagnostic starts on an unindented line; indented lines continue the
131 // previous diagnostic.
132 const parseDiagnostics = (output: string) => {
133 const diagnostics: Array<string> = []
134 for (const line of output.split(/\r?\n/)) {
135 if (line === "") continue
136 if (/^\s/.test(line) && diagnostics.length > 0) {
137 diagnostics[diagnostics.length - 1] += `\n${line}`
138 continue
139 }
140 diagnostics.push(line)
141 }
142 return diagnostics
143 }
144
145 // Type-checks every case with one compiler run per tsconfig variant and
146 // returns the diagnostics that fail each case. A syntax error in one file makes
147 // tsc skip semantic checks for the whole program, so a failed run cannot show
148 // which cases are clean; each of its cases is then checked on its own.
149 const typeCheckCases = Effect.fnUntraced(
150 function*(
151 cases: ReadonlyArray<{ readonly sources: ReadonlyArray<string>; readonly exactOptionalPropertyTypes: boolean }>
152 ) {
153 const directory = mkdtempSync(join(dirname(fileURLToPath(import.meta.url)), ".generated-clients-"))
154 return yield* Effect.gen(function*() {
155 const files = cases.map(({ sources }, caseIndex) =>
156 sources.map((source, sourceIndex) => {
157 const path = join(directory, `Case${caseIndex}Client${sourceIndex}.ts`)
158 writeFileSync(path, source)
159 return path
160 })
161 )
162 // Returns every diagnostic of one compiler run, or an empty list when it succeeds.
163 const check = (name: string, exactOptionalPropertyTypes: boolean, caseIndexes: ReadonlyArray<number>) => {
164 const configPath = join(directory, `tsconfig.${name}.json`)
165 writeFileSync(
166 configPath,
167 JSON.stringify({
168 compilerOptions: {
169 allowImportingTsExtensions: true,
170 exactOptionalPropertyTypes,
171 lib: ["ESNext", "DOM"],
172 module: "NodeNext",
173 noEmit: true,
174 skipLibCheck: true,
175 strict: true,
176 target: "ES2022",
177 types: [],
178 verbatimModuleSyntax: true
179 },
180 files: caseIndexes.flatMap((caseIndex) => files[caseIndex])
181 })
182 )
183 return runTsc(configPath).pipe(Effect.map(({ output, status }) => {
184 if (status === 0) return []
185 const diagnostics = parseDiagnostics(output)
186 return diagnostics.length === 0 ? [`tsc exited with ${status}`] : diagnostics
187 }))
188 }
189 const failures: Array<ReadonlyArray<string>> = cases.map(() => [])
190 const variants = [true, false].map((exactOptionalPropertyTypes) => ({
191 exactOptionalPropertyTypes,
192 caseIndexes: cases.flatMap((testCase, caseIndex) =>
193 testCase.exactOptionalPropertyTypes === exactOptionalPropertyTypes ? [caseIndex] : []
194 )
195 })).filter(({ caseIndexes }) => caseIndexes.length > 0)
196 yield* Effect.forEach(variants, ({ caseIndexes, exactOptionalPropertyTypes }) =>
197 Effect.gen(function*() {
198 const batch = yield* check(String(exactOptionalPropertyTypes), exactOptionalPropertyTypes, caseIndexes)
199 if (batch.length === 0) return
200 const isolated = yield* Effect.forEach(
201 caseIndexes,
202 (caseIndex) => check(`case${caseIndex}`, exactOptionalPropertyTypes, [caseIndex]),
203 { concurrency: 4 }
204 )
205 // If every case compiles alone, the failure comes from combining them, so it fails every case.
206 const combined = isolated.every((diagnostics) => diagnostics.length === 0)
207 caseIndexes.forEach((caseIndex, i) => {
208 failures[caseIndex] = combined ? batch : isolated[i]
209 })
210 }), { concurrency: "unbounded", discard: true })
211 return failures
212 }).pipe(Effect.ensuring(Effect.sync(() => rmSync(directory, { recursive: true, force: true }))))
213 }
214 )
215
216 const compileAll = Effect.gen(function*() {
217 const generated = yield* Effect.forEach(compileCases, (testCase) => Effect.exit(generateClients(testCase)))
218 const failures = yield* typeCheckCases(generated.map((exit, caseIndex) => ({
219 sources: Exit.isSuccess(exit) ? exit.value : [],
220 exactOptionalPropertyTypes: compileCases[caseIndex].options.exactOptionalPropertyTypes ?? true
221 })))
222 return { generated, failures }
223 })
224
225 const compiled = Effect.runSync(Effect.cached(compileAll))
226
227 const itGeneratedClientsCompile = (name: string, spec: OpenAPISpec, options: CompileOptions = {}) => {
228 const caseIndex = compileCases.push({ spec, options }) - 1
229 it.effect(name, () =>
230 Effect.gen(function*() {
231 const result = yield* compiled
232 const generated = result.generated[caseIndex]
233 if (Exit.isFailure(generated)) {
234 return yield* Effect.failCause(generated.cause)
235 }
236 assert.strictEqual(result.failures[caseIndex].join("\n"), "")
237 }), compilationTimeout)
238 }
239
240 const assertHttpApiIncludes = Effect.fnUntraced(function*(
241 spec: OpenAPISpec,
242 includes: ReadonlyArray<string>,
243 excludes: ReadonlyArray<string> = []
244 ) {
245 const generator = yield* OpenApiGenerator.OpenApiGenerator
246
247 const result = yield* generator.generate(spec, {
248 name: "TestClient",
249 format: "httpapi"
250 })
251
252 for (const expected of includes) {
253 assert.include(result, expected)
254 }
255 for (const excluded of excludes) {
256 assert.notInclude(result, excluded)
257 }
258 }, Effect.provide(OpenApiGenerator.layerTransformerSchema))
259
260 const assertHttpApiWithWarnings = Effect.fnUntraced(function*(
261 spec: OpenAPISpec,
262 options: {
263 readonly includes?: ReadonlyArray<string> | undefined
264 readonly excludes?: ReadonlyArray<string> | undefined
265 readonly occurrences?:
266 | ReadonlyArray<{
267 readonly substring: string
268 readonly count: number
269 }>
270 | undefined
271 readonly warnings: ReadonlyArray<
272 Pick<OpenApiGenerator.OpenApiGeneratorWarning, "code" | "path" | "method" | "operationId">
273 >
274 }
275 ) {
276 const generator = yield* OpenApiGenerator.OpenApiGenerator
277 const warnings: Array<OpenApiGenerator.OpenApiGeneratorWarning> = []
278
279 const result = yield* generator.generate(spec, {
280 name: "TestClient",
281 format: "httpapi",
282 onWarning: (warning) => {
283 warnings.push(warning)
284 }
285 })
286
287 for (const expected of options.includes ?? []) {
288 assert.include(result, expected)
289 }
290 for (const excluded of options.excludes ?? []) {
291 assert.notInclude(result, excluded)
292 }
293 for (const { substring, count } of options.occurrences ?? []) {
294 assert.strictEqual(result.split(substring).length - 1, count)
295 }
296
297 assert.deepStrictEqual(
298 warnings.map((warning) => ({
299 code: warning.code,
300 path: warning.path,
301 method: warning.method,
302 operationId: warning.operationId
303 })),
304 options.warnings
305 )
306 }, Effect.provide(OpenApiGenerator.layerTransformerSchema))
307
308 const generateHttpApi = Effect.fnUntraced(function*(spec: OpenAPISpec) {
309 const generator = yield* OpenApiGenerator.OpenApiGenerator
310 const warnings: Array<OpenApiGenerator.OpenApiGeneratorWarning> = []
311
312 const source = yield* generator.generate(spec, {
313 name: "TestClient",
314 format: "httpapi",
315 onWarning: (warning) => {
316 warnings.push(warning)
317 }
318 })
319
320 return { source, warnings }
321 }, Effect.provide(OpenApiGenerator.layerTransformerSchema))
322
323 const findEndpoint = (source: string, method: string, path: string): string => {
324 const line = source.split("\n").find((line) =>
325 line.includes(`HttpApiEndpoint.${method}(`) && line.includes(`", ${JSON.stringify(path)}`)
326 )
327 assert.isDefined(line, `Expected ${method} ${path} in:\n${source}`)
328 return line!
329 }
330
331 const assertRuntimeStableWithWarnings = Effect.fnUntraced(function*(
332 spec: OpenAPISpec,
333 expectedWarnings: ReadonlyArray<
334 Pick<OpenApiGenerator.OpenApiGeneratorWarning, "code" | "path" | "method" | "operationId">
335 >
336 ) {
337 const generator = yield* OpenApiGenerator.OpenApiGenerator
338 const warnings: Array<OpenApiGenerator.OpenApiGeneratorWarning> = []
339
340 const baseline = yield* generator.generate(spec, {
341 name: "TestClient",
342 format: "httpclient"
343 })
344 const withWarnings = yield* generator.generate(spec, {
345 name: "TestClient",
346 format: "httpclient",
347 onWarning: (warning) => {
348 warnings.push(warning)
349 }
350 })
351
352 assert.strictEqual(withWarnings, baseline)
353 assert.deepStrictEqual(
354 warnings.map((warning) => ({
355 code: warning.code,
356 path: warning.path,
357 method: warning.method,
358 operationId: warning.operationId
359 })),
360 expectedWarnings
361 )
362 }, Effect.provide(OpenApiGenerator.layerTransformerSchema))
363
364 const assertTypeOnlyStableWithWarnings = Effect.fnUntraced(function*(
365 spec: OpenAPISpec,
366 expectedWarnings: ReadonlyArray<
367 Pick<OpenApiGenerator.OpenApiGeneratorWarning, "code" | "path" | "method" | "operationId">
368 >
369 ) {
370 const generator = yield* OpenApiGenerator.OpenApiGenerator
371 const warnings: Array<OpenApiGenerator.OpenApiGeneratorWarning> = []
372
373 const baseline = yield* generator.generate(spec, {
374 name: "TestClient",
375 format: "httpclient-type-only"
376 })
377 const withWarnings = yield* generator.generate(spec, {
378 name: "TestClient",
379 format: "httpclient-type-only",
380 onWarning: (warning) => {
381 warnings.push(warning)
382 }
383 })
384
385 assert.strictEqual(withWarnings, baseline)
386 assert.deepStrictEqual(
387 warnings.map((warning) => ({
388 code: warning.code,
389 path: warning.path,
390 method: warning.method,
391 operationId: warning.operationId
392 })),
393 expectedWarnings
394 )
395 }, Effect.provide(OpenApiGenerator.layerTransformerTs))
396
397 const regressionSpec: OpenAPISpec = {
398 openapi: "3.1.0",
399 info: {
400 title: "Regression API",
401 version: "1.0.0"
402 },
403 paths: {
404 "/users/{id}": {
405 get: {
406 operationId: "getUser",
407 summary: "Get user",
408 description: "Read a user",
409 parameters: [
410 {
411 name: "id",
412 in: "path",
413 schema: {
414 type: "string"
415 },
416 required: true
417 },
418 {
419 name: "filter",
420 in: "query",
421 schema: {
422 type: "string"
423 },
424 required: false
425 },
426 {
427 name: "trace-id",
428 in: "header",
429 schema: {
430 type: "string"
431 },
432 required: false
433 },
434 {
435 name: "session",
436 in: "cookie",
437 schema: {
438 type: "string"
439 },
440 required: false
441 }
442 ],
443 responses: {
444 default: {
445 description: "Default user response",
446 content: {
447 "application/json": {
448 schema: {
449 type: "object",
450 properties: {
451 id: {
452 type: "string"
453 }
454 },
455 required: ["id"],
456 additionalProperties: false
457 }
458 }
459 }
460 }
461 } as any,
462 tags: ["Users"],
463 security: [{ apiKey: [] }]
464 }
465 }
466 },
467 components: {
468 schemas: {},
469 securitySchemes: {
470 apiKey: {
471 type: "apiKey",
472 name: "x-api-key",
473 in: "header"
474 }
475 }
476 },
477 security: [],
478 tags: [{ name: "Users" }]
479 }
480
481 const responseMatchingSpec: OpenAPISpec = {
482 openapi: "3.1.0",
483 info: {
484 title: "Response matching API",
485 version: "1.0.0"
486 },
487 paths: {
488 "/auth/device/token": {
489 post: {
490 operationId: "pollDeviceToken",
491 parameters: [],
492 tags: ["ResponseMatching"],
493 security: [],
494 responses: {
495 400: {
496 description: "Problem details or OAuth polling state",
497 content: {
498 "application/problem+json": {
499 schema: {
500 type: "object",
501 properties: {
502 kind: { const: "InvalidRequestError" },
503 code: { type: "string" }
504 },
505 required: ["kind", "code"],
506 additionalProperties: false
507 }
508 },
509 "application/json": {
510 schema: {
511 type: "object",
512 properties: {
513 kind: { const: "DeviceTokenOAuthError" },
514 error: { type: "string" }
515 },
516 required: ["kind", "error"],
517 additionalProperties: false
518 }
519 }
520 }
521 }
522 }
523 }
524 },
525 "/archive": {
526 get: {
527 operationId: "downloadArchive",
528 parameters: [],
529 tags: ["ResponseMatching"],
530 security: [],
531 responses: {
532 200: {
533 description: "Archive",
534 content: {
535 "application/zip": {
536 schema: { type: "string", format: "binary" }
537 }
538 }
539 },
540 404: {
541 description: "Not found",
542 content: {
543 "application/problem+json": {
544 schema: {
545 type: "object",
546 properties: {
547 title: { type: "string" }
548 },
549 required: ["title"],
550 additionalProperties: false
551 }
552 }
553 }
554 }
555 }
556 }
557 },
558 "/avatar": {
559 get: {
560 operationId: "downloadAvatar",
561 parameters: [],
562 tags: ["ResponseMatching"],
563 security: [],
564 responses: {
565 200: {
566 description: "Avatar",
567 content: {
568 "image/png": {
569 schema: { type: "string" }
570 }
571 }
572 }
573 }
574 }
575 },
576 "/custom-binary": {
577 get: {
578 operationId: "downloadCustomBinary",
579 parameters: [],
580 tags: ["ResponseMatching"],
581 security: [],
582 responses: {
583 200: {
584 description: "Custom binary",
585 content: {
586 "application/vnd.example.data": {
587 schema: { type: "string", format: "binary" }
588 }
589 }
590 }
591 }
592 }
593 },
594 "/mixed-content": {
595 get: {
596 operationId: "downloadMixedContent",
597 parameters: [],
598 tags: ["ResponseMatching"],
599 security: [],
600 responses: {
601 200: {
602 description: "JSON metadata or binary content",
603 content: {
604 "application/json; charset=utf-8": {
605 schema: {
606 type: "object",
607 properties: { href: { type: "string" } },
608 required: ["href"],
609 additionalProperties: false
610 }
611 },
612 "application/octet-stream; boundary=payload": {
613 schema: { type: "string" }
614 }
615 }
616 },
617 400: {
618 description: "Invalid request",
619 content: {
620 "application/problem+json; charset=utf-8": {
621 schema: {
622 type: "object",
623 properties: { title: { type: "string" } },
624 required: ["title"],
625 additionalProperties: false
626 }
627 }
628 }
629 }
630 }
631 }
632 },
633 "/resources/{id}": {
634 head: {
635 operationId: "checkResource",
636 parameters: [{
637 name: "id",
638 in: "path",
639 required: true,
640 schema: { type: "string" }
641 }],
642 tags: ["ResponseMatching"],
643 security: [],
644 responses: {
645 200: { description: "Exists" },
646 404: { description: "Not found" },
647 500: { description: "Server error" }
648 }
649 }
650 }
651 },
652 components: {
653 schemas: {},
654 securitySchemes: {}
655 },
656 security: [],
657 tags: [{ name: "ResponseMatching" }]
658 }
659
660 const voidSuccessSpec: OpenAPISpec = {
661 openapi: "3.1.0",
662 info: {
663 title: "Void success API",
664 version: "1.0.0"
665 },
666 paths: {
667 "/mixed": {
668 get: {
669 operationId: "mixedSuccess",
670 parameters: [],
671 tags: ["VoidSuccess"],
672 security: [],
673 responses: {
674 200: {
675 description: "JSON value",
676 content: {
677 "application/json": {
678 schema: { type: "string" }
679 }
680 }
681 },
682 204: { description: "No content" }
683 }
684 }
685 },
686 "/cached": {
687 get: {
688 operationId: "cached",
689 parameters: [],
690 tags: ["VoidSuccess"],
691 security: [],
692 responses: {
693 304: { description: "Not modified" }
694 }
695 }
696 }
697 },
698 components: {
699 schemas: {},
700 securitySchemes: {}
701 },
702 security: [],
703 tags: [{ name: "VoidSuccess" }]
704 }
705
706 function multipartSpec(schema: JsonSchema.JsonSchema, schemas: JsonSchema.Definitions = {}): OpenAPISpec {
707 return {
708 openapi: "3.1.0",
709 info: { title: "Upload API", version: "1.0.0" },
710 paths: {
711 "/upload": {
712 post: {
713 operationId: "upload",
714 parameters: [],
715 requestBody: {
716 required: true,
717 content: { "multipart/form-data": { schema } }
718 },
719 responses: { "204": { description: "Uploaded" } },
720 tags: ["Upload"],
721 security: []
722 }
723 }
724 },
725 components: { schemas, securitySchemes: {} },
726 security: [],
727 tags: [{ name: "Upload" }]
728 }
729 }
730
731 function sharedMultipartSpec(
732 schema: JsonSchema.JsonSchema,
733 schemas: JsonSchema.Definitions,
734 json: Record<string, unknown> = { schema }
735 ): OpenAPISpec {
736 const spec = multipartSpec(schema, schemas)
737 return {
738 ...spec,
739 paths: {
740 ...spec.paths,
741 "/json": {
742 post: {
743 operationId: "createJson",
744 parameters: [],
745 requestBody: { required: true, content: { "application/json": json } } as any,
746 responses: { "204": { description: "Created" } },
747 tags: ["Upload"],
748 security: []
749 }
750 }
751 }
752 }
753 }
754
755 const attachmentRef = { $ref: "#/components/schemas/Attachment" }
756
757 function attachmentSpec(paths: Record<string, OpenAPISpecPathItem>): OpenAPISpec {
758 return {
759 openapi: "3.1.0",
760 info: { title: "Attachment API", version: "1.0.0" },
761 paths: {
762 "/attachments": {
763 post: {
764 operationId: "createAttachment",
765 parameters: [],
766 requestBody: {
767 required: true,
768 content: { "application/json": { schema: attachmentRef } }
769 },
770 responses: {
771 "200": { description: "Created", content: { "application/json": { schema: attachmentRef } } }
772 },
773 tags: ["Attachments"],
774 security: []
775 }
776 },
777 ...paths
778 },
779 components: {
780 schemas: {
781 Attachment: {
782 type: "object",
783 properties: {
784 name: { type: "string" },
785 data: { type: "string", format: "binary" }
786 },
787 required: ["name", "data"],
788 additionalProperties: false
789 }
790 },
791 securitySchemes: {}
792 },
793 security: [],
794 tags: [{ name: "Attachments" }]
795 }
796 }
797
798 const cookieParameterSpec: OpenAPISpec = {
799 openapi: "3.1.0",
800 info: { title: "Cookie parameter API", version: "1.0.0" },
801 paths: {
802 "/greeting": {
803 get: {
804 operationId: "getGreeting",
805 parameters: [{ name: "locale", in: "cookie", required: true, schema: { type: "string" } }],
806 responses: { "204": { description: "No content" } },
807 tags: ["Greeting"],
808 security: []
809 }
810 }
811 },
812 components: { schemas: {}, securitySchemes: {} },
813 security: [],
814 tags: [{ name: "Greeting" }]
815 }
816
817 describe("OpenApiGenerator", () => {
818 describe("schema", () => {
819 it.effect("get operation", () =>
820 assertRuntime(
821 {
822 openapi: "3.1.0",
823 info: {
824 title: "Test API",
825 version: "1.0.0"
826 },
827 paths: {
828 "/users/{id}": {
829 get: {
830 operationId: "getUser",
831 parameters: [
832 {
833 name: "id",
834 in: "path",
835 schema: {
836 type: "string"
837 },
838 required: true
839 }
840 ],
841 responses: {
842 200: {
843 description: "User retrieved successfully",
844 content: {
845 "application/json": {
846 schema: {
847 type: "object",
848 properties: {
849 id: {
850 type: "string"
851 },
852 name: {
853 type: "string"
854 }
855 },
856 required: ["id", "name"],
857 additionalProperties: false,
858 description: "User object"
859 }
860 }
861 }
862 }
863 },
864 tags: ["Users"],
865 security: []
866 }
867 }
868 },
869 components: {
870 schemas: {},
871 securitySchemes: {}
872 },
873 security: [],
874 tags: []
875 },
876 `import * as Data from "effect/Data"
877 import * as Effect from "effect/Effect"
878 import type { SchemaError } from "effect/Schema"
879 import * as Schema from "effect/Schema"
880 import type * as HttpClient from "effect/http/HttpClient"
881 import * as HttpClientError from "effect/http/HttpClientError"
882 import * as HttpClientRequest from "effect/http/HttpClientRequest"
883 import * as HttpClientResponse from "effect/http/HttpClientResponse"
884 // schemas
885 export type GetUser200 = { readonly "id": string, readonly "name": string }
886 export const GetUser200 = Schema.Struct({ "id": Schema.String, "name": Schema.String }).annotate({ "description": "User object" })
887
888 export interface OperationConfig {
889 /**
890 * Whether or not the response should be included in the value returned from
891 * an operation.
892 *
893 * If set to \`true\`, a tuple of \`[A, HttpClientResponse]\` will be returned,
894 * where \`A\` is the success type of the operation.
895 *
896 * If set to \`false\`, only the success type of the operation will be returned.
897 */
898 readonly includeResponse?: boolean | undefined
899 }
900
901 /**
902 * A utility type which optionally includes the response in the return result
903 * of an operation based upon the value of the \`includeResponse\` configuration
904 * option.
905 */
906 export type WithOptionalResponse<A, Config extends OperationConfig | undefined> = Config extends {
907 readonly includeResponse: true
908 } ? [A, HttpClientResponse.HttpClientResponse]
909 : Config extends { readonly includeResponse?: false | undefined } | undefined ? A
910 : A | [A, HttpClientResponse.HttpClientResponse]
911
912 export const make = <E, R>(
913 httpClient: HttpClient.HttpClient.With<E, R>,
914 options: {
915 readonly transformClient?: ((client: HttpClient.HttpClient.With<E, R>) => Effect.Effect<HttpClient.HttpClient.With<E, R>>) | undefined
916 } = {}
917 ): TestClient<E, R> => {
918 const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) =>
919 Effect.flatMap(
920 Effect.orElseSucceed(response.json, () => "Unexpected status code"),
921 (description) =>
922 Effect.fail(
923 new HttpClientError.HttpClientError({
924 reason: new HttpClientError.StatusCodeError({
925 request: response.request,
926 response,
927 description: typeof description === "string" ? description : JSON.stringify(description),
928 }),
929 }),
930 ),
931 )
932 const withResponse = <Config extends OperationConfig>(config: Config | undefined) => (
933 f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<any, any>,
934 ): (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<any, any, R> => {
935 const withOptionalResponse = (
936 config?.includeResponse
937 ? (response: HttpClientResponse.HttpClientResponse) => Effect.map(f(response), (a) => [a, response])
938 : (response: HttpClientResponse.HttpClientResponse) => f(response)
939 ) as any
940 return options?.transformClient
941 ? (request) =>
942 Effect.flatMap(
943 Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)),
944 withOptionalResponse
945 )
946 : (request) => Effect.flatMap(httpClient.execute(request), withOptionalResponse)
947 }
948 const __encodePathParam = encodeURIComponent
949 const __makePathRequest = (
950 method: (url: string) => HttpClientRequest.HttpClientRequest,
951 parameters: ReadonlyArray<string>,
952 getPath: () => string,
953 ) => Effect.suspend(() => {
954 const fail = (description: string, cause?: unknown) => Effect.fail(
955 new HttpClientError.HttpClientError({
956 reason: new HttpClientError.InvalidUrlError({
957 request: method(""),
958 cause,
959 description,
960 }),
961 }),
962 )
963 if (parameters.some((value) => value === "" || /^(?:\\.|%2e){1,2}$/i.test(value))) {
964 return fail("Path parameters must be non-empty and cannot be dot segments")
965 }
966 let path: string
967 try {
968 path = getPath()
969 } catch (cause) {
970 return fail("Failed to encode path parameter", cause)
971 }
972 if (path.split("/").some((segment) => /^(?:\\.|%2e){1,2}$/i.test(segment))) {
973 return fail("Request paths cannot contain dot segments")
974 }
975 return Effect.succeed(method(path))
976 })
977 const decodeSuccess =
978 <Schema extends Schema.Constraint>(schema: Schema) =>
979 (response: HttpClientResponse.HttpClientResponse) =>
980 HttpClientResponse.schemaBodyJson(schema)(response)
981 return {
982 httpClient,
983 "getUser": (id, options: Parameters<TestClient["getUser"]>[1]) => __makePathRequest(HttpClientRequest.get, [id], () => "/users/" + __encodePathParam(id) + "").pipe(
984 Effect.flatMap((request) => request.pipe(
985 withResponse(options?.config)(HttpClientResponse.matchStatus({
986 "2xx": decodeSuccess(GetUser200),
987 orElse: unexpectedStatus
988 }))
989 ))
990 )
991 }
992 }
993
994 export interface TestClient<E = HttpClientError.HttpClientError, R = never> {
995 readonly httpClient: HttpClient.HttpClient.With<E, R>
996 readonly "getUser": {
997 <Config extends OperationConfig | undefined = undefined>(id: string, options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<GetUser200, Config>, E | HttpClientError.HttpClientError | SchemaError, R>;
998 <Config extends OperationConfig | undefined = undefined>(id: string, options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<GetUser200, Config | undefined>, E | HttpClientError.HttpClientError | SchemaError, R>;
999 }
1000 }
1001
1002 export interface TestClientError<Tag extends string, E> {
1003 readonly _tag: Tag
1004 readonly request: HttpClientRequest.HttpClientRequest
1005 readonly response: HttpClientResponse.HttpClientResponse
1006 readonly cause: E
1007 }
1008
1009 class TestClientErrorImpl extends Data.Error<{
1010 _tag: string
1011 cause: any
1012 request: HttpClientRequest.HttpClientRequest
1013 response: HttpClientResponse.HttpClientResponse
1014 }> {}
1015
1016 export const TestClientError = <Tag extends string, E>(
1017 tag: Tag,
1018 cause: E,
1019 response: HttpClientResponse.HttpClientResponse,
1020 ): TestClientError<Tag, E> =>
1021 new TestClientErrorImpl({
1022 _tag: tag,
1023 cause,
1024 response,
1025 request: response.request,
1026 }) as any`
1027 ))
1028
1029 it.effect("resolves JSON Pointer-escaped local references", () =>
1030 assertRuntimeIncludes(
1031 {
1032 openapi: "3.1.0",
1033 info: {
1034 title: "Test API",
1035 version: "1.0.0"
1036 },
1037 paths: {
1038 "/widgets": {
1039 get: {
1040 operationId: "listWidgets",
1041 parameters: [
1042 { $ref: "#/components/parameters/Page~1Limit" } as any,
1043 { $ref: "#/components/parameters/Tilde~0Name" } as any
1044 ],
1045 responses: {
1046 204: {
1047 description: "No content"
1048 }
1049 },
1050 tags: ["Widgets"],
1051 security: []
1052 }
1053 }
1054 },
1055 components: {
1056 schemas: {},
1057 parameters: {
1058 "Page/Limit": {
1059 name: "limit",
1060 in: "query",
1061 required: false,
1062 schema: { type: "integer" }
1063 },
1064 "Tilde~Name": {
1065 name: "tilde",
1066 in: "query",
1067 required: false,
1068 schema: { type: "string" }
1069 }
1070 }
1071 } as any,
1072 security: [],
1073 tags: [{ name: "Widgets" }]
1074 },
1075 [
1076 `readonly "limit"?: number`,
1077 `readonly "tilde"?: string`,
1078 `HttpClientRequest.setUrlParams({ "limit": options?.params?.["limit"] as any, "tilde": options?.params?.["tilde"] as any })`
1079 ]
1080 ))
1081
1082 it.effect("sse operation decodes event payload from json string", () =>
1083 assertRuntimeIncludes(
1084 {
1085 openapi: "3.1.0",
1086 info: {
1087 title: "Test API",
1088 version: "1.0.0"
1089 },
1090 paths: {
1091 "/events": {
1092 get: {
1093 operationId: "streamEvents",
1094 parameters: [],
1095 responses: {
1096 200: {
1097 description: "Events streamed successfully",
1098 content: {
1099 "text/event-stream": {
1100 schema: {
1101 type: "object",
1102 properties: {
1103 type: {
1104 type: "string"
1105 },
1106 value: {
1107 type: "string"
1108 }
1109 },
1110 required: ["type", "value"],
1111 additionalProperties: false
1112 }
1113 }
1114 }
1115 }
1116 },
1117 tags: ["Events"],
1118 security: []
1119 }
1120 }
1121 },
1122 components: {
1123 schemas: {},
1124 securitySchemes: {}
1125 },
1126 security: [],
1127 tags: []
1128 },
1129 [
1130 `import * as Sse from "effect/encoding/Sse"`,
1131 `readonly "streamEventsSse": () => Stream.Stream<{ readonly event: string; readonly id: string | undefined; readonly data: StreamEvents200Sse }, E | HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError, R | typeof StreamEvents200Sse.DecodingServices>`,
1132 `"streamEventsSse": () => HttpClientRequest.get("/events").pipe(`,
1133 `sseRequest(StreamEvents200Sse)`,
1134 `schema: Schema.ConstraintDecoder<Type, DecodingServices>`
1135 ]
1136 ))
1137
1138 it.effect("annotated sse operation decodes the full event schema", () =>
1139 assertRuntimeIncludes(
1140 {
1141 openapi: "3.1.0",
1142 info: {
1143 title: "Test API",
1144 version: "1.0.0"
1145 },
1146 paths: {
1147 "/events": {
1148 get: {
1149 operationId: "streamEvents",
1150 parameters: [],
1151 responses: {
1152 200: {
1153 description: "Events streamed successfully",
1154 content: {
1155 "text/event-stream": {
1156 schema: {
1157 type: "object",
1158 properties: {
1159 id: {
1160 anyOf: [{ type: "string" }, { type: "null" }]
1161 },
1162 event: { const: "message" },
1163 data: { type: "string" }
1164 },
1165 required: ["id", "event", "data"],
1166 additionalProperties: false
1167 },
1168 "x-effect-stream": {
1169 encoding: "sse",
1170 errorSchema: {},
1171 causeSchema: {},
1172 failureEvent: "effect/http-api/stream/failure"
1173 }
1174 }
1175 }
1176 }
1177 },
1178 tags: ["Events"],
1179 security: []
1180 }
1181 }
1182 },
1183 components: {
1184 schemas: {},
1185 securitySchemes: {}
1186 },
1187 security: [],
1188 tags: []
1189 },
1190 [
1191 `"id": Schema.optionalKey(Schema.String), "event": Schema.Literal("message"), "data": Schema.String`,
1192 `"id": Schema.optionalKey(Schema.String), "event": Schema.Literal("effect/http-api/stream/failure"), "data": Schema.String`,
1193 `readonly "streamEventsSse": () => Stream.Stream<StreamEvents200Sse, E | HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError, R | typeof StreamEvents200Sse.DecodingServices>`,
1194 `sseEventRequest(StreamEvents200Sse)`,
1195 `Stream.pipeThroughChannel(Sse.decodeSchema(schema))`
1196 ]
1197 ))
1198
1199 it.effect("form-urlencoded request body generates bodyUrlParams", () =>
1200 assertRuntimeIncludes(
1201 {
1202 openapi: "3.1.0",
1203 info: {
1204 title: "Test API",
1205 version: "1.0.0"
1206 },
1207 paths: {
1208 "/auth/token": {
1209 post: {
1210 operationId: "issueToken",
1211 parameters: [],
1212 requestBody: {
1213 required: true,
1214 content: {
1215 "application/x-www-form-urlencoded": {
1216 schema: {
1217 type: "object",
1218 properties: {
1219 grant_type: { type: "string" },
1220 client_id: { type: "string" }
1221 },
1222 required: ["grant_type", "client_id"],
1223 additionalProperties: false
1224 }
1225 }
1226 }
1227 } as any,
1228 responses: {
1229 200: {
1230 description: "Token response",
1231 content: {
1232 "application/json": {
1233 schema: {
1234 type: "object",
1235 properties: {
1236 access_token: { type: "string" }
1237 },
1238 required: ["access_token"],
1239 additionalProperties: false
1240 }
1241 }
1242 }
1243 }
1244 },
1245 tags: ["Auth"],
1246 security: []
1247 }
1248 }
1249 },
1250 components: {
1251 schemas: {},
1252 securitySchemes: {}
1253 },
1254 security: [],
1255 tags: []
1256 },
1257 [
1258 `HttpClientRequest.bodyUrlParams(options.payload as any)`,
1259 `readonly payload: typeof IssueTokenRequestFormUrlEncoded.Encoded`
1260 ]
1261 ))
1262
1263 it.effect("preserves response variants and routes binary and bodiless statuses", () =>
1264 assertRuntimeIncludes(responseMatchingSpec, [
1265 `export const PollDeviceToken400 = Schema.Union(`,
1266 `Schema.Literal("InvalidRequestError")`,
1267 `Schema.Literal("DeviceTokenOAuthError")`,
1268 `"400": decodeError("PollDeviceToken400", PollDeviceToken400)`,
1269 `TestClientError<"PollDeviceToken400", PollDeviceToken400>`,
1270 `export type DownloadArchive404 = { readonly "title": string }`,
1271 `const decodeBinary = (response: HttpClientResponse.HttpClientResponse) =>`,
1272 `Effect.map(response.arrayBuffer, (buffer) => new Uint8Array(buffer))`,
1273 `"2xx": decodeBinary`,
1274 `readonly "downloadArchive": {`,
1275 `<Config extends OperationConfig | undefined = undefined>(options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<Uint8Array, Config>`,
1276 `<Config extends OperationConfig | undefined = undefined>(options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<Uint8Array, Config | undefined>`,
1277 `readonly "downloadArchiveStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
1278 `readonly "downloadAvatarStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
1279 `"downloadAvatar": (options: Parameters<TestClient["downloadAvatar"]>[0]) => HttpClientRequest.get("/avatar").pipe(
1280 withResponse(options?.config)(HttpClientResponse.matchStatus({
1281 "2xx": decodeBinary`,
1282 `readonly "downloadCustomBinaryStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
1283 `"400": decodeError("DownloadMixedContent400", DownloadMixedContent400)`,
1284 `readonly "downloadMixedContent": {`,
1285 `<Config extends OperationConfig | undefined = undefined>(options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<Uint8Array, Config>`,
1286 `<Config extends OperationConfig | undefined = undefined>(options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<Uint8Array, Config | undefined>`,
1287 `readonly "downloadMixedContentStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
1288 `"200": () => Effect.void`,
1289 `"404": decodeVoidError("404")`,
1290 `"500": decodeVoidError("500")`,
1291 `TestClientError<"404", undefined>`,
1292 `TestClientError<"500", undefined>`
1293 ], [
1294 `"200": decodeSuccess(DownloadMixedContent200)`,
1295 `DownloadMixedContent200 | Uint8Array`
1296 ]))
1297
1298 it.effect("routes mixed and non-2xx bodiless success responses", () =>
1299 assertRuntimeIncludes(voidSuccessSpec, [
1300 `"200": decodeSuccess(MixedSuccess200)`,
1301 `"204": () => Effect.void`,
1302 `"304": () => Effect.void`,
1303 `WithOptionalResponse<MixedSuccess200 | void, Config>`
1304 ]))
1305
1306 it.effect("emits included component schemas that no operation references", () =>
1307 Effect.gen(function*() {
1308 const generator = yield* OpenApiGenerator.OpenApiGenerator
1309 const result = yield* generator.generate({
1310 openapi: "3.1.0",
1311 info: { title: "Test API", version: "1.0.0" },
1312 paths: {
1313 "/ping": {
1314 get: {
1315 operationId: "ping",
1316 parameters: [],
1317 responses: { 204: { description: "Pong" } },
1318 tags: ["Ping"],
1319 security: []
1320 }
1321 }
1322 },
1323 components: {
1324 schemas: {
1325 Legacy: {
1326 type: "object",
1327 properties: { value: { $ref: "#/components/schemas/LegacyValue" } },
1328 required: ["value"]
1329 },
1330 LegacyValue: { type: "string" },
1331 Unlisted: { type: "string" }
1332 },
1333 securitySchemes: {}
1334 },
1335 security: [],
1336 tags: [{ name: "Ping" }]
1337 }, { name: "TestClient", format: "httpclient", includeSchemas: ["Legacy"] })
1338
1339 assert.include(result, "export const Legacy = ")
1340 assert.include(result, "export const LegacyValue = ")
1341 assert.notInclude(result, "Unlisted")
1342 }).pipe(Effect.provide(OpenApiGenerator.layerTransformerSchema)))
1343 })
1344
1345 describe("type-only", () => {
1346 it.effect("get operation", () =>
1347 assertTypeOnly(
1348 {
1349 openapi: "3.1.0",
1350 info: {
1351 title: "Test API",
1352 version: "1.0.0"
1353 },
1354 paths: {
1355 "/users/{id}": {
1356 get: {
1357 operationId: "getUser",
1358 parameters: [
1359 {
1360 name: "id",
1361 in: "path",
1362 schema: {
1363 type: "string"
1364 },
1365 required: true
1366 }
1367 ],
1368 responses: {
1369 200: {
1370 description: "User retrieved successfully",
1371 content: {
1372 "application/json": {
1373 schema: {
1374 type: "object",
1375 properties: {
1376 id: {
1377 type: "string"
1378 },
1379 name: {
1380 type: "string"
1381 }
1382 },
1383 required: ["id", "name"],
1384 additionalProperties: false
1385 }
1386 }
1387 }
1388 }
1389 },
1390 tags: ["Users"],
1391 security: []
1392 }
1393 }
1394 },
1395 components: {
1396 schemas: {},
1397 securitySchemes: {}
1398 },
1399 security: [],
1400 tags: []
1401 },
1402 `import * as Data from "effect/Data"
1403 import * as Effect from "effect/Effect"
1404 import type * as HttpClient from "effect/http/HttpClient"
1405 import * as HttpClientError from "effect/http/HttpClientError"
1406 import * as HttpClientRequest from "effect/http/HttpClientRequest"
1407 import * as HttpClientResponse from "effect/http/HttpClientResponse"
1408 // schemas
1409 export type GetUser200 = { readonly "id": string, readonly "name": string }
1410
1411 export interface OperationConfig {
1412 /**
1413 * Whether or not the response should be included in the value returned from
1414 * an operation.
1415 *
1416 * If set to \`true\`, a tuple of \`[A, HttpClientResponse]\` will be returned,
1417 * where \`A\` is the success type of the operation.
1418 *
1419 * If set to \`false\`, only the success type of the operation will be returned.
1420 */
1421 readonly includeResponse?: boolean | undefined
1422 }
1423
1424 /**
1425 * A utility type which optionally includes the response in the return result
1426 * of an operation based upon the value of the \`includeResponse\` configuration
1427 * option.
1428 */
1429 export type WithOptionalResponse<A, Config extends OperationConfig | undefined> = Config extends {
1430 readonly includeResponse: true
1431 } ? [A, HttpClientResponse.HttpClientResponse]
1432 : Config extends { readonly includeResponse?: false | undefined } | undefined ? A
1433 : A | [A, HttpClientResponse.HttpClientResponse]
1434
1435 export const make = <E, R>(
1436 httpClient: HttpClient.HttpClient.With<E, R>,
1437 options: {
1438 readonly transformClient?: ((client: HttpClient.HttpClient.With<E, R>) => Effect.Effect<HttpClient.HttpClient.With<E, R>>) | undefined
1439 } = {}
1440 ): TestClient<E, R> => {
1441 const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) =>
1442 Effect.flatMap(
1443 Effect.orElseSucceed(response.json, () => "Unexpected status code"),
1444 (description) =>
1445 Effect.fail(
1446 new HttpClientError.HttpClientError({
1447 reason: new HttpClientError.StatusCodeError({
1448 request: response.request,
1449 response,
1450 description: typeof description === "string" ? description : JSON.stringify(description),
1451 }),
1452 }),
1453 ),
1454 )
1455 const withResponse = <Config extends OperationConfig>(config: Config | undefined) => (
1456 f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<any, any>,
1457 ): (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<any, any, R> => {
1458 const withOptionalResponse = (
1459 config?.includeResponse
1460 ? (response: HttpClientResponse.HttpClientResponse) => Effect.map(f(response), (a) => [a, response])
1461 : (response: HttpClientResponse.HttpClientResponse) => f(response)
1462 ) as any
1463 return options?.transformClient
1464 ? (request) =>
1465 Effect.flatMap(
1466 Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)),
1467 withOptionalResponse
1468 )
1469 : (request) => Effect.flatMap(httpClient.execute(request), withOptionalResponse)
1470 }
1471 const __encodePathParam = encodeURIComponent
1472 const __makePathRequest = (
1473 method: (url: string) => HttpClientRequest.HttpClientRequest,
1474 parameters: ReadonlyArray<string>,
1475 getPath: () => string,
1476 ) => Effect.suspend(() => {
1477 const fail = (description: string, cause?: unknown) => Effect.fail(
1478 new HttpClientError.HttpClientError({
1479 reason: new HttpClientError.InvalidUrlError({
1480 request: method(""),
1481 cause,
1482 description,
1483 }),
1484 }),
1485 )
1486 if (parameters.some((value) => value === "" || /^(?:\\.|%2e){1,2}$/i.test(value))) {
1487 return fail("Path parameters must be non-empty and cannot be dot segments")
1488 }
1489 let path: string
1490 try {
1491 path = getPath()
1492 } catch (cause) {
1493 return fail("Failed to encode path parameter", cause)
1494 }
1495 if (path.split("/").some((segment) => /^(?:\\.|%2e){1,2}$/i.test(segment))) {
1496 return fail("Request paths cannot contain dot segments")
1497 }
1498 return Effect.succeed(method(path))
1499 })
1500 const decodeSuccess = <A>(response: HttpClientResponse.HttpClientResponse) =>
1501 response.json as Effect.Effect<A, HttpClientError.HttpClientError>
1502 const decodeVoid = (_response: HttpClientResponse.HttpClientResponse) =>
1503 Effect.void
1504 const decodeError =
1505 <Tag extends string, E>(tag: Tag) =>
1506 (
1507 response: HttpClientResponse.HttpClientResponse,
1508 ): Effect.Effect<
1509 never,
1510 TestClientError<Tag, E> | HttpClientError.HttpClientError
1511 > =>
1512 Effect.flatMap(
1513 response.json as Effect.Effect<E, HttpClientError.HttpClientError>,
1514 (cause) => Effect.fail(TestClientError(tag, cause, response)),
1515 )
1516 const onRequest = <Config extends OperationConfig>(config: Config | undefined) => (
1517 successCodes: ReadonlyArray<string>,
1518 errorCodes?: Record<string, string>,
1519 ) => {
1520 const cases: any = { orElse: unexpectedStatus }
1521 for (const code of successCodes) {
1522 cases[code] = decodeSuccess
1523 }
1524 if (errorCodes) {
1525 for (const [code, tag] of Object.entries(errorCodes)) {
1526 cases[code] = decodeError(tag)
1527 }
1528 }
1529 if (successCodes.length === 0) {
1530 cases["2xx"] = decodeVoid
1531 }
1532 return withResponse(config)(HttpClientResponse.matchStatus(cases) as any)
1533 }
1534 return {
1535 httpClient,
1536 "getUser": (id, options: Parameters<TestClient["getUser"]>[1]) => __makePathRequest(HttpClientRequest.get, [id], () => "/users/" + __encodePathParam(id) + "").pipe(
1537 Effect.flatMap((request) => request.pipe(
1538 onRequest(options?.config)(["2xx"])
1539 ))
1540 )
1541 }
1542 }
1543
1544 export interface TestClient<E = HttpClientError.HttpClientError, R = never> {
1545 readonly httpClient: HttpClient.HttpClient.With<E, R>
1546 readonly "getUser": {
1547 <Config extends OperationConfig | undefined = undefined>(id: string, options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<GetUser200, Config>, E | HttpClientError.HttpClientError, R>;
1548 <Config extends OperationConfig | undefined = undefined>(id: string, options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<GetUser200, Config | undefined>, E | HttpClientError.HttpClientError, R>;
1549 }
1550 }
1551
1552 export interface TestClientError<Tag extends string, E> {
1553 readonly _tag: Tag
1554 readonly request: HttpClientRequest.HttpClientRequest
1555 readonly response: HttpClientResponse.HttpClientResponse
1556 readonly cause: E
1557 }
1558
1559 class TestClientErrorImpl extends Data.Error<{
1560 _tag: string
1561 cause: any
1562 request: HttpClientRequest.HttpClientRequest
1563 response: HttpClientResponse.HttpClientResponse
1564 }> {}
1565
1566 export const TestClientError = <Tag extends string, E>(
1567 tag: Tag,
1568 cause: E,
1569 response: HttpClientResponse.HttpClientResponse,
1570 ): TestClientError<Tag, E> =>
1571 new TestClientErrorImpl({
1572 _tag: tag,
1573 cause,
1574 response,
1575 request: response.request,
1576 }) as any`
1577 ))
1578
1579 it.effect("preserves response variants and routes binary and bodiless statuses", () =>
1580 assertTypeOnlyIncludes(responseMatchingSpec, [
1581 `export type PollDeviceToken400 =`,
1582 `readonly "kind": "InvalidRequestError"`,
1583 `readonly "kind": "DeviceTokenOAuthError"`,
1584 `onRequest(options?.config)([], {"400":"PollDeviceToken400"})`,
1585 `const decodeBinary = (response: HttpClientResponse.HttpClientResponse) =>`,
1586 `onRequest(options?.config)([], {"404":"DownloadArchive404"}, {"binary":["2xx"],"voidSuccess":[],"voidError":[]})`,
1587 `readonly "downloadArchive": {`,
1588 `<Config extends OperationConfig | undefined = undefined>(options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<Uint8Array, Config>`,
1589 `<Config extends OperationConfig | undefined = undefined>(options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<Uint8Array, Config | undefined>`,
1590 `readonly "downloadAvatarStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
1591 `"downloadAvatar": (options: Parameters<TestClient["downloadAvatar"]>[0]) => HttpClientRequest.get("/avatar").pipe(
1592 onRequest(options?.config)([], undefined, {"binary":["2xx"],"voidSuccess":[],"voidError":[]})`,
1593 `readonly "downloadCustomBinaryStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
1594 `import * as HttpClient from "effect/http/HttpClient"`,
1595 `onRequest(options?.config)([], {"400":"DownloadMixedContent400"}, {"binary":["2xx"],"voidSuccess":[],"voidError":[]})`,
1596 `readonly "downloadMixedContent": {`,
1597 `<Config extends OperationConfig | undefined = undefined>(options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<Uint8Array, Config>`,
1598 `<Config extends OperationConfig | undefined = undefined>(options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<Uint8Array, Config | undefined>`,
1599 `readonly "downloadMixedContentStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
1600 `onRequest(options?.config)([], undefined, {"binary":[],"voidSuccess":["200"],"voidError":["404","500"]})`,
1601 `cases[code] = decodeVoidError(code)`,
1602 `TestClientError<"404", undefined>`,
1603 `TestClientError<"500", undefined>`
1604 ], [
1605 `DownloadMixedContent200 | Uint8Array`
1606 ]))
1607
1608 it.effect("routes mixed and non-2xx bodiless success responses", () =>
1609 assertTypeOnlyIncludes(voidSuccessSpec, [
1610 `onRequest(options?.config)(["200"], undefined, {"binary":[],"voidSuccess":["204"],"voidError":[]})`,
1611 `onRequest(options?.config)([], undefined, {"binary":[],"voidSuccess":["304"],"voidError":[]})`,
1612 `WithOptionalResponse<MixedSuccess200 | void, Config>`
1613 ]))
1614
1615 itGeneratedClientsCompile("emits compilable clients for schema-backed and type-only formats", responseMatchingSpec)
1616 })
1617
1618 describe("httpapi", () => {
1619 it.effect("generates tagged groups with endpoint annotations and representable parameters", () =>
1620 assertHttpApiIncludes(
1621 {
1622 openapi: "3.1.0",
1623 info: {
1624 title: "Test API",
1625 version: "1.0.0",
1626 summary: "Summary",
1627 description: "Description"
1628 },
1629 paths: {
1630 "/users/{id}": {
1631 get: {
1632 operationId: "getUser",
1633 summary: "Get user",
1634 description: "Read a user",
1635 deprecated: true,
1636 externalDocs: {
1637 url: "https://example.com/get-user"
1638 },
1639 parameters: [
1640 {
1641 name: "id",
1642 in: "path",
1643 schema: { type: "string" },
1644 required: true
1645 },
1646 {
1647 name: "filter",
1648 in: "query",
1649 schema: { type: "string" },
1650 required: false
1651 },
1652 {
1653 name: "trace-id",
1654 in: "header",
1655 schema: { type: "string" },
1656 required: false
1657 }
1658 ],
1659 responses: {
1660 200: {
1661 description: "User",
1662 content: {
1663 "application/json": {
1664 schema: {
1665 type: "object",
1666 properties: {
1667 id: { type: "string" }
1668 },
1669 required: ["id"],
1670 additionalProperties: false
1671 }
1672 }
1673 }
1674 },
1675 404: {
1676 description: "Not found"
1677 }
1678 },
1679 tags: ["Users"],
1680 security: []
1681 }
1682 }
1683 },
1684 components: {
1685 schemas: {},
1686 securitySchemes: {}
1687 },
1688 security: [],
1689 tags: [
1690 {
1691 name: "Users",
1692 description: "User operations",
1693 externalDocs: {
1694 url: "https://example.com/users"
1695 }
1696 }
1697 ]
1698 },
1699 [
1700 `import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, HttpApiSecurity, OpenApi } from "effect/http-api"`,
1701 `export type GetUserPathParams = { readonly "id": string }`,
1702 `export const GetUserPathParams = Schema.Struct({ "id": Schema.String })`,
1703 `class UsersGroup extends HttpApiGroup.make("Users")`,
1704 `.annotate(OpenApi.Description, "User operations")`,
1705 `.annotate(OpenApi.ExternalDocs, {"url":"https://example.com/users"})`,
1706 `HttpApiEndpoint.get("getUser", "/users/:id", { params: GetUserPathParams, query: GetUserQuery, headers: GetUserHeaders, success: GetUser200, error: HttpApiSchema.Empty(404) })`,
1707 `.annotate(OpenApi.Identifier, "getUser")`,
1708 `.annotate(OpenApi.Summary, "Get user")`,
1709 `.annotate(OpenApi.Description, "Read a user")`,
1710 `.annotate(OpenApi.Deprecated, true)`,
1711 `.annotate(OpenApi.ExternalDocs, {"url":"https://example.com/get-user"})`,
1712 `export class TestClient extends HttpApi.make("TestClient")`,
1713 `.annotate(OpenApi.Title, "Test API")`,
1714 `.annotate(OpenApi.Version, "1.0.0")`,
1715 `.annotate(OpenApi.Summary, "Summary")`,
1716 `.annotate(OpenApi.Description, "Description")`,
1717 `.add(UsersGroup)`
1718 ],
1719 [
1720 `export class GetUserPathParams extends Schema.Class<GetUserPathParams>("GetUserPathParams")({ "id": Schema.String }) {}`
1721 ]
1722 ))
1723
1724 it.effect("includes path-level parameters in generated httpapi endpoints", () =>
1725 assertHttpApiIncludes(
1726 {
1727 openapi: "3.1.0",
1728 info: {
1729 title: "Discord-style API",
1730 version: "1.0.0"
1731 },
1732 paths: {
1733 "/applications/{application_id}": {
1734 parameters: [
1735 {
1736 name: "application_id",
1737 in: "path",
1738 schema: { type: "string" },
1739 required: true
1740 }
1741 ],
1742 get: {
1743 operationId: "getApplication",
1744 parameters: [],
1745 responses: {
1746 200: {
1747 description: "Application"
1748 }
1749 },
1750 tags: ["Applications"],
1751 security: []
1752 }
1753 }
1754 },
1755 components: {
1756 schemas: {},
1757 securitySchemes: {}
1758 },
1759 security: [],
1760 tags: [{ name: "Applications" }]
1761 },
1762 [
1763 `export type GetApplicationPathParams = { readonly "application_id": string }`,
1764 `export const GetApplicationPathParams = Schema.Struct({ "application_id": Schema.String })`,
1765 `HttpApiEndpoint.get("getApplication", "/applications/:application_id", { params: GetApplicationPathParams, success: HttpApiSchema.Empty(200) })`
1766 ],
1767 [
1768 `export class GetApplicationPathParams extends Schema.Class<GetApplicationPathParams>("GetApplicationPathParams")({ "application_id": Schema.String }) {}`
1769 ]
1770 ))
1771
1772 it.effect("creates top-level fallback group for untagged operations", () =>
1773 assertHttpApiIncludes(
1774 {
1775 openapi: "3.1.0",
1776 info: {
1777 title: "Test API",
1778 version: "1.0.0"
1779 },
1780 paths: {
1781 "/health": {
1782 get: {
1783 operationId: "getHealth",
1784 parameters: [],
1785 responses: {
1786 204: {
1787 description: "No content"
1788 }
1789 },
1790 tags: [] as any,
1791 security: []
1792 }
1793 }
1794 },
1795 components: {
1796 schemas: {},
1797 securitySchemes: {}
1798 },
1799 security: [],
1800 tags: []
1801 },
1802 [
1803 `class DefaultGroup extends HttpApiGroup.make("default", { topLevel: true })`,
1804 `HttpApiEndpoint.get("getHealth", "/health", { success: HttpApiSchema.Empty(204) })`,
1805 `.add(DefaultGroup)`
1806 ]
1807 ))
1808
1809 it.effect("keeps the fallback group top-level when tagged default operations are present", () =>
1810 assertHttpApiIncludes(
1811 {
1812 openapi: "3.1.0",
1813 info: {
1814 title: "Test API",
1815 version: "1.0.0"
1816 },
1817 paths: {
1818 "/tagged": {
1819 get: {
1820 operationId: "getTagged",
1821 parameters: [],
1822 responses: {
1823 200: {
1824 description: "Tagged"
1825 }
1826 },
1827 tags: ["default"],
1828 security: []
1829 }
1830 },
1831 "/untagged": {
1832 get: {
1833 operationId: "getUntagged",
1834 parameters: [],
1835 responses: {
1836 204: {
1837 description: "Untagged"
1838 }
1839 },
1840 tags: [] as any,
1841 security: []
1842 }
1843 }
1844 },
1845 components: {
1846 schemas: {},
1847 securitySchemes: {}
1848 },
1849 security: [],
1850 tags: []
1851 },
1852 [
1853 `class DefaultGroup extends HttpApiGroup.make("default", { topLevel: true })`,
1854 `HttpApiEndpoint.get("getTagged", "/tagged", { success: HttpApiSchema.Empty(200) })`,
1855 `HttpApiEndpoint.get("getUntagged", "/untagged", { success: HttpApiSchema.Empty(204) })`,
1856 `.add(DefaultGroup)`
1857 ]
1858 ))
1859
1860 it.effect("maps request and response encodings including optional request body approximation", () =>
1861 assertHttpApiIncludes(
1862 {
1863 openapi: "3.1.0",
1864 info: {
1865 title: "Test API",
1866 version: "1.0.0"
1867 },
1868 paths: {
1869 "/payload": {
1870 post: {
1871 operationId: "createPayload",
1872 parameters: [],
1873 requestBody: {
1874 required: false,
1875 content: {
1876 "application/json": {
1877 schema: {
1878 type: "object",
1879 properties: {
1880 a: { type: "string" }
1881 },
1882 required: ["a"],
1883 additionalProperties: false
1884 }
1885 },
1886 "multipart/form-data": {
1887 schema: {
1888 type: "object",
1889 properties: {
1890 file: { type: "string", format: "binary" },
1891 files: {
1892 type: "array",
1893 items: { type: "string", format: "binary" }
1894 }
1895 },
1896 required: ["file", "files"],
1897 additionalProperties: false
1898 }
1899 },
1900 "application/x-www-form-urlencoded": {
1901 schema: {
1902 type: "object",
1903 properties: {
1904 form: { type: "string" }
1905 },
1906 required: ["form"],
1907 additionalProperties: false
1908 }
1909 },
1910 "text/plain": {
1911 schema: {
1912 type: "string"
1913 }
1914 },
1915 "application/octet-stream": {
1916 schema: {
1917 type: "string",
1918 format: "binary"
1919 }
1920 }
1921 }
1922 } as any,
1923 responses: {
1924 200: {
1925 description: "Payload",
1926 content: {
1927 "application/json": {
1928 schema: {
1929 type: "object",
1930 properties: {
1931 ok: { type: "boolean" }
1932 },
1933 required: ["ok"],
1934 additionalProperties: false
1935 }
1936 },
1937 "text/plain": {
1938 schema: {
1939 type: "string"
1940 }
1941 },
1942 "application/octet-stream": {
1943 schema: {
1944 type: "string",
1945 format: "binary"
1946 }
1947 }
1948 }
1949 },
1950 201: {
1951 description: "Created"
1952 }
1953 },
1954 tags: ["Payload"],
1955 security: []
1956 }
1957 }
1958 },
1959 components: {
1960 schemas: {},
1961 securitySchemes: {}
1962 },
1963 security: [],
1964 tags: [{ name: "Payload" }]
1965 },
1966 [
1967 `import { Multipart } from "effect/http"`,
1968 `export type __HttpApiMultipartSingleFile = Multipart.PersistedFile
1969 export const __HttpApiMultipartSingleFile = Multipart.SingleFileSchema`,
1970 `export type __HttpApiMultipartFiles = ReadonlyArray<Multipart.PersistedFile>
1971 export const __HttpApiMultipartFiles = Multipart.FilesSchema`,
1972 `export type CreatePayloadRequestFormData = { readonly "file": __HttpApiMultipartSingleFile, readonly "files": __HttpApiMultipartFiles }`,
1973 `export const CreatePayloadRequestFormData = Schema.Struct({ "file": __HttpApiMultipartSingleFile, "files": __HttpApiMultipartFiles })`,
1974 `export type CreatePayloadRequestJson = { readonly "a": string }`,
1975 `export type CreatePayloadRequestText = string
1976 export const CreatePayloadRequestText = Schema.String`,
1977 `payload: [HttpApiSchema.NoContent, CreatePayloadRequestJson, CreatePayloadRequestFormData.pipe(HttpApiSchema.asMultipart()), CreatePayloadRequestFormUrlEncoded.pipe(HttpApiSchema.asFormUrlEncoded()), CreatePayloadRequestText.pipe(HttpApiSchema.asText()), CreatePayloadRequestBinary.pipe(HttpApiSchema.asUint8Array())]`,
1978 `success: [CreatePayload200, CreatePayload200Text.pipe(HttpApiSchema.asText()), CreatePayload200Binary.pipe(HttpApiSchema.asUint8Array()), HttpApiSchema.Empty(201)]`
1979 ],
1980 [
1981 "Schema.Opaque",
1982 `extends Schema.Class<CreatePayloadRequestJson>("CreatePayloadRequestJson")`
1983 ]
1984 ))
1985
1986 it.effect("preserves multiple JSON response representations with application/json preferred", () =>
1987 assertHttpApiIncludes(
1988 {
1989 openapi: "3.1.0",
1990 info: {
1991 title: "Test API",
1992 version: "1.0.0"
1993 },
1994 paths: {
1995 "/dual": {
1996 get: {
1997 operationId: "dualJson",
1998 parameters: [],
1999 responses: {
2000 200: {
2001 description: "Dual JSON response",
2002 content: {
2003 "application/problem+json": {
2004 schema: {
2005 type: "object",
2006 properties: {
2007 title: { type: "string" }
2008 },
2009 required: ["title"],
2010 additionalProperties: false
2011 }
2012 },
2013 "application/json": {
2014 schema: {
2015 type: "object",
2016 properties: {
2017 value: { type: "string" }
2018 },
2019 required: ["value"],
2020 additionalProperties: false
2021 }
2022 }
2023 }
2024 }
2025 },
2026 tags: ["DualJson"],
2027 security: []
2028 }
2029 }
2030 },
2031 components: {
2032 schemas: {},
2033 securitySchemes: {}
2034 },
2035 security: [],
2036 tags: [{ name: "DualJson" }]
2037 },
2038 [
2039 `export type DualJson200 = { readonly "value": string }`,
2040 `export type DualJson200ApplicationProblemJson = { readonly "title": string }`,
2041 `HttpApiEndpoint.get("dualJson", "/dual", { success: [DualJson200, DualJson200ApplicationProblemJson.pipe(HttpApiSchema.asJson({ contentType: "application/problem+json" }))] })`
2042 ]
2043 ))
2044
2045 it.effect("maps explicit SSE stream responses to HttpApiSchema.StreamSse", () =>
2046 assertHttpApiIncludes(
2047 {
2048 openapi: "3.1.0",
2049 info: {
2050 title: "Test API",
2051 version: "1.0.0"
2052 },
2053 paths: {
2054 "/events": {
2055 get: {
2056 operationId: "streamEvents",
2057 parameters: [],
2058 responses: {
2059 200: {
2060 description: "Events",
2061 content: {
2062 "text/event-stream": {
2063 schema: {
2064 type: "object",
2065 properties: {
2066 event: { const: "message" },
2067 data: { type: "string" }
2068 },
2069 required: ["event", "data"],
2070 additionalProperties: false
2071 },
2072 "x-effect-stream": {
2073 encoding: "sse",
2074 errorSchema: {
2075 type: "object",
2076 properties: {
2077 message: { type: "string" }
2078 },
2079 required: ["message"],
2080 additionalProperties: false
2081 },
2082 causeSchema: {
2083 type: "object"
2084 },
2085 failureEvent: "effect/http-api/stream/failure"
2086 }
2087 }
2088 }
2089 }
2090 },
2091 tags: ["Events"],
2092 security: []
2093 }
2094 },
2095 "/events/custom": {
2096 get: {
2097 operationId: "streamEventsCustom",
2098 parameters: [],
2099 responses: {
2100 200: {
2101 description: "Custom events",
2102 content: {
2103 "application/custom-sse": {
2104 schema: {
2105 type: "object",
2106 properties: {
2107 event: { const: "message" },
2108 data: { type: "string" }
2109 },
2110 required: ["event", "data"],
2111 additionalProperties: false
2112 },
2113 "x-effect-stream": {
2114 encoding: "sse",
2115 errorSchema: {
2116 type: "object",
2117 properties: {
2118 message: { type: "string" }
2119 },
2120 required: ["message"],
2121 additionalProperties: false
2122 },
2123 causeSchema: {
2124 type: "object"
2125 },
2126 failureEvent: "effect/http-api/stream/failure"
2127 }
2128 }
2129 }
2130 }
2131 },
2132 tags: ["Events"],
2133 security: []
2134 }
2135 }
2136 },
2137 components: {
2138 schemas: {},
2139 securitySchemes: {}
2140 },
2141 security: [],
2142 tags: [{ name: "Events" }]
2143 },
2144 [
2145 `HttpApiEndpoint.get("streamEvents", "/events", { success: HttpApiSchema.StreamSse({ events: StreamEvents200Sse, error: StreamEvents200SseError }) })`,
2146 `HttpApiEndpoint.get("streamEventsCustom", "/events/custom", { success: HttpApiSchema.StreamSse({ contentType: "application/custom-sse", events: StreamEventsCustom200Sse, error: StreamEventsCustom200SseError }) })`
2147 ],
2148 [
2149 `StreamEvents200Sse.pipe(HttpApiSchema.asText())`,
2150 `StreamEventsCustom200ApplicationCustomSse.pipe(HttpApiSchema.asText({ contentType: "application/custom-sse" }))`
2151 ]
2152 ))
2153
2154 it.effect("warns and skips unannotated successful SSE responses in HttpApi generation", () =>
2155 assertHttpApiWithWarnings(
2156 {
2157 openapi: "3.1.0",
2158 info: {
2159 title: "Test API",
2160 version: "1.0.0"
2161 },
2162 paths: {
2163 "/events": {
2164 get: {
2165 operationId: "streamEvents",
2166 parameters: [],
2167 responses: {
2168 200: {
2169 description: "Events",
2170 content: {
2171 "text/event-stream": {
2172 schema: {
2173 type: "string"
2174 }
2175 }
2176 }
2177 }
2178 },
2179 tags: ["Events"],
2180 security: []
2181 }
2182 },
2183 "/events/cause-only": {
2184 get: {
2185 operationId: "streamEventsCauseOnly",
2186 parameters: [],
2187 responses: {
2188 200: {
2189 description: "Events",
2190 content: {
2191 "text/event-stream": {
2192 schema: {
2193 type: "string"
2194 },
2195 "x-effect-stream": {
2196 encoding: "sse",
2197 causeSchema: {
2198 type: "object"
2199 },
2200 failureEvent: "effect/http-api/stream/failure"
2201 } as any
2202 }
2203 }
2204 }
2205 },
2206 tags: ["Events"],
2207 security: []
2208 }
2209 }
2210 },
2211 components: {
2212 schemas: {},
2213 securitySchemes: {}
2214 },
2215 security: [],
2216 tags: [{ name: "Events" }]
2217 },
2218 {
2219 excludes: [
2220 `HttpApiEndpoint.get("streamEvents", "/events"`,
2221 `HttpApiEndpoint.get("streamEventsCauseOnly", "/events/cause-only"`
2222 ],
2223 warnings: [
2224 {
2225 code: "sse-operation-skipped",
2226 path: "/events",
2227 method: "get",
2228 operationId: "streamEvents"
2229 },
2230 {
2231 code: "sse-operation-skipped",
2232 path: "/events/cause-only",
2233 method: "get",
2234 operationId: "streamEventsCauseOnly"
2235 }
2236 ]
2237 }
2238 ))
2239
2240 it.effect("maps explicit uint8array stream responses to HttpApiSchema.StreamUint8Array", () =>
2241 assertHttpApiIncludes(
2242 {
2243 openapi: "3.1.0",
2244 info: {
2245 title: "Test API",
2246 version: "1.0.0"
2247 },
2248 paths: {
2249 "/download": {
2250 get: {
2251 operationId: "download",
2252 parameters: [],
2253 responses: {
2254 200: {
2255 description: "Download",
2256 content: {
2257 "application/octet-stream": {
2258 schema: {
2259 type: "string",
2260 format: "binary"
2261 },
2262 "x-effect-stream": {
2263 encoding: "uint8array"
2264 }
2265 }
2266 }
2267 }
2268 },
2269 tags: ["Downloads"],
2270 security: []
2271 }
2272 },
2273 "/download/custom": {
2274 get: {
2275 operationId: "downloadCustom",
2276 parameters: [],
2277 responses: {
2278 200: {
2279 description: "Custom download",
2280 content: {
2281 "application/custom-bytes": {
2282 schema: {
2283 type: "string",
2284 format: "binary"
2285 },
2286 "x-effect-stream": {
2287 encoding: "uint8array"
2288 }
2289 }
2290 }
2291 }
2292 },
2293 tags: ["Downloads"],
2294 security: []
2295 }
2296 }
2297 },
2298 components: {
2299 schemas: {},
2300 securitySchemes: {}
2301 },
2302 security: [],
2303 tags: [{ name: "Downloads" }]
2304 },
2305 [
2306 `HttpApiEndpoint.get("download", "/download", { success: HttpApiSchema.StreamUint8Array() })`,
2307 `HttpApiEndpoint.get("downloadCustom", "/download/custom", { success: HttpApiSchema.StreamUint8Array({ contentType: "application/custom-bytes" }) })`
2308 ],
2309 [
2310 `Download200Binary.pipe(HttpApiSchema.asUint8Array())`,
2311 `DownloadCustom200ApplicationCustomBytes.pipe(HttpApiSchema.asUint8Array({ contentType: "application/custom-bytes" }))`
2312 ]
2313 ))
2314
2315 it.effect("keeps unannotated octet-stream responses as buffered Uint8Array schemas", () =>
2316 assertHttpApiIncludes(
2317 {
2318 openapi: "3.1.0",
2319 info: {
2320 title: "Test API",
2321 version: "1.0.0"
2322 },
2323 paths: {
2324 "/download/buffered": {
2325 get: {
2326 operationId: "downloadBuffered",
2327 parameters: [],
2328 responses: {
2329 200: {
2330 description: "Buffered download",
2331 content: {
2332 "application/octet-stream": {
2333 schema: {
2334 type: "string",
2335 format: "binary"
2336 }
2337 }
2338 }
2339 }
2340 },
2341 tags: ["Downloads"],
2342 security: []
2343 }
2344 }
2345 },
2346 components: {
2347 schemas: {},
2348 securitySchemes: {}
2349 },
2350 security: [],
2351 tags: [{ name: "Downloads" }]
2352 },
2353 [
2354 `HttpApiEndpoint.get("downloadBuffered", "/download/buffered", { success: DownloadBuffered200Binary.pipe(HttpApiSchema.asUint8Array()) })`
2355 ],
2356 [
2357 `HttpApiSchema.StreamUint8Array()`
2358 ]
2359 ))
2360
2361 describe("streaming payloads", () => {
2362 const Item = Schema.Struct({ id: Schema.Finite }).annotate({ identifier: "Item" })
2363 const ndjson = (contentType?: string) =>
2364 `HttpApiSchema\\.StreamNdjson\\(\\{ schema: \\w+${
2365 contentType === undefined
2366 ? `(, contentType: "application/x-ndjson")?`
2367 : `, contentType: ${JSON.stringify(contentType)}`
2368 } \\}\\)`
2369
2370 it.effect("round-trips streaming payloads and successes", () =>
2371 Effect.gen(function*() {
2372 // Inline, because every component goes through the multipart rewrite
2373 const FormItem = Schema.Struct({ data: Schema.String.annotate({ format: "binary" }) })
2374 const Api = HttpApi.make("Api").add(
2375 HttpApiGroup.make("items").add(
2376 HttpApiEndpoint.post("upload", "/upload", {
2377 payload: HttpApiSchema.StreamUint8Array({ maxBytes: "1 MiB" })
2378 }),
2379 // NDJSON markers win over the SSE and multipart handling of these content types
2380 HttpApiEndpoint.post("ingest", "/ingest", {
2381 payload: HttpApiSchema.StreamNdjson({ schema: Item, contentType: "text/event-stream" })
2382 }),
2383 HttpApiEndpoint.post("ingestForm", "/ingest/form", {
2384 payload: HttpApiSchema.StreamNdjson({ schema: FormItem, contentType: "multipart/form-data" })
2385 }),
2386 HttpApiEndpoint.get("export", "/export", {
2387 success: HttpApiSchema.StreamNdjson({ schema: Item, contentType: "text/event-stream" })
2388 })
2389 )
2390 )
2391
2392 const { source } = yield* generateHttpApi(OpenApi.fromApi(Api))
2393
2394 assert.include(findEndpoint(source, "post", "/upload"), `payload: HttpApiSchema.StreamUint8Array(),`)
2395 assert.match(findEndpoint(source, "post", "/ingest"), new RegExp(`payload: ${ndjson("text/event-stream")}`))
2396 const form = findEndpoint(source, "post", "/ingest/form").match(
2397 /payload: HttpApiSchema\.StreamNdjson\(\{ schema: (\w+), contentType: "multipart\/form-data" \}\)/
2398 )
2399 assert.isNotNull(form, source)
2400 assert.include(source, `export type ${form![1]} = { readonly "data": string }`)
2401 assert.match(findEndpoint(source, "get", "/export"), new RegExp(`success: ${ndjson("text/event-stream")}`))
2402 }))
2403
2404 it.effect("maps third-party NDJSON itemSchema media types to StreamNdjson", () =>
2405 Effect.gen(function*() {
2406 const item = {
2407 type: "object",
2408 properties: { id: { type: "number" } },
2409 required: ["id"],
2410 additionalProperties: false
2411 }
2412 const { source } = yield* generateHttpApi({
2413 openapi: "3.2.0",
2414 info: { title: "Test API", version: "1.0.0" },
2415 paths: {
2416 "/ingest": {
2417 post: {
2418 operationId: "ingest",
2419 parameters: [],
2420 requestBody: { content: { "application/x-ndjson": { itemSchema: item } }, required: true },
2421 responses: { 204: { description: "Accepted" } },
2422 tags: ["Items"],
2423 security: []
2424 }
2425 },
2426 "/export": {
2427 get: {
2428 operationId: "export",
2429 parameters: [],
2430 responses: {
2431 200: { description: "Items", content: { "application/x-ndjson": { itemSchema: item } } }
2432 },
2433 tags: ["Items"],
2434 security: []
2435 }
2436 }
2437 },
2438 components: { schemas: {}, securitySchemes: {} },
2439 security: [],
2440 tags: [{ name: "Items" }]
2441 } as unknown as OpenAPISpec)
2442
2443 assert.match(findEndpoint(source, "post", "/ingest"), new RegExp(`payload: ${ndjson()}`))
2444 assert.match(findEndpoint(source, "get", "/export"), new RegExp(`success: ${ndjson()}`))
2445 }))
2446
2447 it.effect("skips json-seq and SSE request bodies with a warning", () =>
2448 Effect.gen(function*() {
2449 const event = { type: "object", properties: { id: { type: "number" } } }
2450 const { source, warnings } = yield* generateHttpApi({
2451 openapi: "3.1.0",
2452 info: { title: "Test API", version: "1.0.0" },
2453 paths: {
2454 "/seq": {
2455 post: {
2456 operationId: "seq",
2457 parameters: [],
2458 requestBody: { content: { "application/json-seq": { schema: event } }, required: true },
2459 responses: { 204: { description: "Accepted" } },
2460 tags: ["Events"],
2461 security: []
2462 }
2463 },
2464 "/events": {
2465 post: {
2466 operationId: "events",
2467 parameters: [],
2468 requestBody: { content: { "text/event-stream": { schema: event } }, required: true },
2469 responses: { 204: { description: "Accepted" } },
2470 tags: ["Events"],
2471 security: []
2472 }
2473 }
2474 },
2475 components: { schemas: {}, securitySchemes: {} },
2476 security: [],
2477 tags: [{ name: "Events" }]
2478 })
2479
2480 assert.notInclude(findEndpoint(source, "post", "/seq"), "payload")
2481 assert.notInclude(findEndpoint(source, "post", "/events"), "payload")
2482 assert.deepStrictEqual(
2483 warnings.map((warning) => ({ path: warning.path, method: warning.method })),
2484 [{ path: "/seq", method: "post" }, { path: "/events", method: "post" }]
2485 )
2486 }))
2487 })
2488
2489 it.effect("maps multipart schemas referenced through components to Multipart file schemas", () =>
2490 assertHttpApiIncludes(
2491 {
2492 openapi: "3.1.0",
2493 info: {
2494 title: "Test API",
2495 version: "1.0.0"
2496 },
2497 paths: {
2498 "/upload": {
2499 post: {
2500 operationId: "upload",
2501 parameters: [],
2502 requestBody: {
2503 required: true,
2504 content: {
2505 "multipart/form-data": {
2506 schema: {
2507 $ref: "#/components/schemas/UploadBody"
2508 }
2509 }
2510 }
2511 } as any,
2512 responses: {
2513 200: {
2514 description: "Uploaded"
2515 }
2516 },
2517 tags: ["Payload"],
2518 security: []
2519 }
2520 }
2521 },
2522 components: {
2523 schemas: {
2524 UploadBody: {
2525 type: "object",
2526 properties: {
2527 file: { type: "string", format: "binary" },
2528 files: {
2529 type: "array",
2530 items: { type: "string", format: "binary" }
2531 }
2532 },
2533 required: ["file", "files"],
2534 additionalProperties: false
2535 }
2536 },
2537 securitySchemes: {}
2538 },
2539 security: [],
2540 tags: [{ name: "Payload" }]
2541 },
2542 [
2543 `import { Multipart } from "effect/http"`,
2544 `export type __HttpApiMultipartSingleFile = Multipart.PersistedFile
2545 export const __HttpApiMultipartSingleFile = Multipart.SingleFileSchema`,
2546 `export type __HttpApiMultipartFiles = ReadonlyArray<Multipart.PersistedFile>
2547 export const __HttpApiMultipartFiles = Multipart.FilesSchema`,
2548 `export type UploadRequestFormData = { readonly "file": __HttpApiMultipartSingleFile, readonly "files": __HttpApiMultipartFiles }`,
2549 `export const UploadRequestFormData = Schema.Struct({ "file": __HttpApiMultipartSingleFile, "files": __HttpApiMultipartFiles })`,
2550 `HttpApiEndpoint.post("upload", "/upload", { payload: UploadRequestFormData.pipe(HttpApiSchema.asMultipart()), success: HttpApiSchema.Empty(200) })`
2551 ],
2552 [
2553 `Schema.String.annotate({ "format": "binary" })`,
2554 `export type UploadBody =`
2555 ]
2556 ))
2557
2558 it.effect("preserves multipart component reference siblings", () =>
2559 assertHttpApiIncludes(
2560 {
2561 openapi: "3.1.0",
2562 info: {
2563 title: "Test API",
2564 version: "1.0.0"
2565 },
2566 paths: {
2567 "/upload": {
2568 post: {
2569 operationId: "upload",
2570 parameters: [],
2571 requestBody: {
2572 required: true,
2573 content: {
2574 "multipart/form-data": {
2575 schema: {
2576 type: "object",
2577 properties: {
2578 first: {
2579 $ref: "#/components/schemas/UploadBody",
2580 minProperties: 1,
2581 description: "First upload"
2582 },
2583 second: {
2584 $ref: "#/components/schemas/UploadBody",
2585 minProperties: 2,
2586 description: "Second upload"
2587 }
2588 },
2589 required: ["first", "second"],
2590 additionalProperties: false
2591 }
2592 }
2593 }
2594 } as any,
2595 responses: {
2596 200: {
2597 description: "Uploaded"
2598 }
2599 },
2600 tags: ["Payload"],
2601 security: []
2602 }
2603 }
2604 },
2605 components: {
2606 schemas: {
2607 UploadBody: {
2608 type: "object",
2609 properties: {
2610 file: { type: "string", format: "binary" }
2611 },
2612 required: ["file"],
2613 additionalProperties: false
2614 }
2615 },
2616 securitySchemes: {}
2617 },
2618 security: [],
2619 tags: [{ name: "Payload" }]
2620 },
2621 [
2622 `"first": Schema.Struct({ "file": __HttpApiMultipartSingleFile })`,
2623 `Schema.isMinProperties(1)`,
2624 `"description": "First upload"`,
2625 `"second": Schema.Struct({ "file": __HttpApiMultipartSingleFile })`,
2626 `Schema.isMinProperties(2)`,
2627 `"description": "Second upload"`
2628 ]
2629 ))
2630
2631 it.effect("preserves multipart component alias siblings", () =>
2632 assertHttpApiIncludes(
2633 {
2634 openapi: "3.1.0",
2635 info: {
2636 title: "Test API",
2637 version: "1.0.0"
2638 },
2639 paths: {
2640 "/upload": {
2641 post: {
2642 operationId: "upload",
2643 parameters: [],
2644 requestBody: {
2645 required: true,
2646 content: {
2647 "multipart/form-data": {
2648 schema: {
2649 $ref: "#/components/schemas/UploadAlias"
2650 }
2651 }
2652 }
2653 } as any,
2654 responses: {
2655 200: {
2656 description: "Uploaded"
2657 }
2658 },
2659 tags: ["Payload"],
2660 security: []
2661 }
2662 }
2663 },
2664 components: {
2665 schemas: {
2666 UploadAlias: {
2667 $ref: "#/components/schemas/UploadBody",
2668 minProperties: 1,
2669 description: "Aliased upload"
2670 },
2671 UploadBody: {
2672 type: "object",
2673 properties: {
2674 file: { type: "string", format: "binary" }
2675 },
2676 required: ["file"],
2677 additionalProperties: false
2678 }
2679 },
2680 securitySchemes: {}
2681 },
2682 security: [],
2683 tags: [{ name: "Payload" }]
2684 },
2685 [
2686 `export type UploadRequestFormData = { readonly "file": __HttpApiMultipartSingleFile }`,
2687 `Schema.isMinProperties(1)`,
2688 `"description": "Aliased upload"`
2689 ],
2690 [
2691 `export type UploadAlias =`,
2692 `export type UploadBody =`
2693 ]
2694 ))
2695
2696 it.effect("maps multipart contentEncoding binary schemas (case-insensitive) to Multipart file schemas", () =>
2697 assertHttpApiIncludes(
2698 {
2699 openapi: "3.1.0",
2700 info: {
2701 title: "Test API",
2702 version: "1.0.0"
2703 },
2704 paths: {
2705 "/upload-content-encoding": {
2706 post: {
2707 operationId: "uploadWithContentEncoding",
2708 parameters: [],
2709 requestBody: {
2710 required: true,
2711 content: {
2712 "multipart/form-data": {
2713 schema: {
2714 $ref: "#/components/schemas/UploadBodyContentEncoding"
2715 }
2716 }
2717 }
2718 } as any,
2719 responses: {
2720 200: {
2721 description: "Uploaded"
2722 }
2723 },
2724 tags: ["Payload"],
2725 security: []
2726 }
2727 }
2728 },
2729 components: {
2730 schemas: {
2731 UploadBodyContentEncoding: {
2732 type: "object",
2733 properties: {
2734 file: { type: "string", contentEncoding: "BINARY" },
2735 files: {
2736 type: "array",
2737 items: { type: "string", contentEncoding: "BINARY" }
2738 }
2739 },
2740 required: ["file", "files"],
2741 additionalProperties: false
2742 }
2743 },
2744 securitySchemes: {}
2745 },
2746 security: [],
2747 tags: [{ name: "Payload" }]
2748 },
2749 [
2750 `import { Multipart } from "effect/http"`,
2751 `export type UploadWithContentEncodingRequestFormData = { readonly "file": __HttpApiMultipartSingleFile, readonly "files": __HttpApiMultipartFiles }`,
2752 `export const UploadWithContentEncodingRequestFormData = Schema.Struct({ "file": __HttpApiMultipartSingleFile, "files": __HttpApiMultipartFiles })`,
2753 `HttpApiEndpoint.post("uploadWithContentEncoding", "/upload-content-encoding", { payload: UploadWithContentEncodingRequestFormData.pipe(HttpApiSchema.asMultipart()), success: HttpApiSchema.Empty(200) })`
2754 ],
2755 [
2756 `contentEncoding`,
2757 `export type UploadBodyContentEncoding =`
2758 ]
2759 ))
2760
2761 it.effect("keeps binary strings in components used only by JSON bodies", () =>
2762 assertHttpApiIncludes(
2763 attachmentSpec({}),
2764 [
2765 `export type Attachment = { readonly "name": string, readonly "data": string }`,
2766 `export const Attachment = Schema.Struct({ "name": Schema.String, "data": Schema.String`
2767 ],
2768 [
2769 `Multipart`
2770 ]
2771 ))
2772
2773 it.effect("copies components shared by JSON and multipart bodies for the multipart body", () =>
2774 assertHttpApiIncludes(
2775 attachmentSpec({
2776 "/attachments/upload": {
2777 post: {
2778 operationId: "uploadAttachment",
2779 parameters: [],
2780 requestBody: {
2781 required: true,
2782 content: { "multipart/form-data": { schema: attachmentRef } }
2783 },
2784 responses: { "204": { description: "Uploaded" } },
2785 tags: ["Attachments"],
2786 security: []
2787 }
2788 }
2789 }),
2790 [
2791 `export type Attachment = { readonly "name": string, readonly "data": string }`,
2792 `export const Attachment = Schema.Struct({ "name": Schema.String, "data": Schema.String`,
2793 `export type AttachmentMultipart = { readonly "name": string, readonly "data": __HttpApiMultipartSingleFile }`,
2794 `export const CreateAttachmentRequestJson = Attachment`,
2795 `export const CreateAttachment200 = Attachment`,
2796 `export const UploadAttachmentRequestFormData = AttachmentMultipart`,
2797 `payload: UploadAttachmentRequestFormData.pipe(HttpApiSchema.asMultipart())`
2798 ],
2799 [
2800 `__HttpApiMultipartFiles`
2801 ]
2802 ))
2803
2804 it.effect("keeps multipart copies of shared components nested in other shared components", () =>
2805 assertHttpApiIncludes(
2806 sharedMultipartSpec({ $ref: "#/components/schemas/Outer" }, {
2807 Outer: {
2808 type: "object",
2809 properties: { inner: { $ref: "#/components/schemas/Inner" } },
2810 required: ["inner"],
2811 additionalProperties: false
2812 },
2813 Inner: {
2814 type: "object",
2815 properties: { file: { type: "string", format: "binary" } },
2816 required: ["file"],
2817 additionalProperties: false
2818 }
2819 }),
2820 [
2821 `export type Inner = { readonly "file": string }`,
2822 `export type Outer = { readonly "inner": Inner }`,
2823 `export type InnerMultipart = { readonly "file": __HttpApiMultipartSingleFile }`,
2824 `export type OuterMultipart = { readonly "inner": InnerMultipart }`,
2825 `export const UploadRequestFormData = OuterMultipart`
2826 ]
2827 ))
2828
2829 it.effect("maps shared binary string components to Multipart file schemas", () =>
2830 assertHttpApiIncludes(
2831 sharedMultipartSpec(
2832 {
2833 type: "object",
2834 properties: {
2835 file: { $ref: "#/components/schemas/BinaryData" },
2836 files: { type: "array", items: { $ref: "#/components/schemas/BinaryData" } }
2837 },
2838 required: ["file", "files"],
2839 additionalProperties: false
2840 },
2841 { BinaryData: { type: "string", format: "binary" } },
2842 { schema: { $ref: "#/components/schemas/BinaryData" } }
2843 ),
2844 [
2845 `export type BinaryData = string`,
2846 `export const CreateJsonRequestJson = BinaryData`,
2847 `export type UploadRequestFormData = { readonly "file": __HttpApiMultipartSingleFile, readonly "files": __HttpApiMultipartFiles }`
2848 ]
2849 ))
2850
2851 it.effect("treats $ref inside media type examples as data", () =>
2852 assertHttpApiIncludes(
2853 sharedMultipartSpec(
2854 { type: "object", properties: { file: { type: "string", format: "binary" } } },
2855 {},
2856 {
2857 schema: { type: "object", properties: { name: { type: "string" } } },
2858 example: { $ref: "#/this/is/arbitrary-user-data" }
2859 }
2860 ),
2861 [
2862 `export type CreateJsonRequestJson = { readonly "name"?: string }`
2863 ]
2864 ))
2865
2866 for (
2867 const [position, link] of [
2868 ["requestBody", { operationId: "createJson", requestBody: { $ref: "#/this/is/arbitrary-user-data" } }],
2869 ["parameters", {
2870 operationId: "createJson",
2871 parameters: { payload: { $ref: "#/this/is/arbitrary-user-data" } }
2872 }]
2873 ] as const
2874 ) {
2875 it.effect(`treats $ref inside link ${position} as data`, () => {
2876 const spec = sharedMultipartSpec(
2877 { type: "object", properties: { file: { type: "string", format: "binary" } } },
2878 {},
2879 { schema: { type: "object", properties: { name: { type: "string" } } } }
2880 )
2881 const operation = spec.paths["/json"].post!
2882 return assertHttpApiIncludes(
2883 {
2884 ...spec,
2885 paths: {
2886 ...spec.paths,
2887 "/json": {
2888 post: {
2889 ...operation,
2890 responses: { "204": { description: "Created", links: { next: link } } } as any
2891 }
2892 }
2893 }
2894 },
2895 [
2896 `export type CreateJsonRequestJson = { readonly "name"?: string }`
2897 ]
2898 )
2899 })
2900 }
2901
2902 it.effect("copies self-recursive components shared by JSON and multipart bodies", () =>
2903 assertHttpApiIncludes(
2904 sharedMultipartSpec({ $ref: "#/components/schemas/Node" }, {
2905 Node: {
2906 type: "object",
2907 properties: {
2908 file: { type: "string", format: "binary" },
2909 child: { $ref: "#/components/schemas/Node" }
2910 },
2911 required: ["file"],
2912 additionalProperties: false
2913 }
2914 }),
2915 [
2916 `export type Node = { readonly "file": string, readonly "child"?: Node }`,
2917 `export type NodeMultipart = { readonly "file": __HttpApiMultipartSingleFile, readonly "child"?: NodeMultipart }`,
2918 `export const CreateJsonRequestJson = Node`,
2919 `export const UploadRequestFormData = NodeMultipart`
2920 ]
2921 ))
2922
2923 it.effect("generates security declarations and middleware placeholders", () =>
2924 assertHttpApiWithWarnings(
2925 {
2926 openapi: "3.1.0",
2927 info: {
2928 title: "Security API",
2929 version: "1.0.0"
2930 },
2931 paths: {
2932 "/secure": {
2933 get: {
2934 operationId: "getSecure",
2935 parameters: [],
2936 responses: {
2937 200: {
2938 description: "Secure"
2939 }
2940 },
2941 tags: ["Security"],
2942 security: [
2943 { apiKeyAuth: [] },
2944 { bearerAuth: [] },
2945 { apiKeyAuth: [], basicAuth: [] }
2946 ]
2947 }
2948 },
2949 "/public": {
2950 get: {
2951 operationId: "getPublic",
2952 parameters: [],
2953 responses: {
2954 200: {
2955 description: "Public"
2956 }
2957 },
2958 tags: ["Security"],
2959 security: []
2960 }
2961 }
2962 },
2963 components: {
2964 schemas: {},
2965 securitySchemes: {
2966 apiKeyAuth: {
2967 type: "apiKey",
2968 name: "x-api-key",
2969 in: "header",
2970 description: "API key"
2971 },
2972 bearerAuth: {
2973 type: "http",
2974 scheme: "bearer",
2975 bearerFormat: "JWT",
2976 description: "Bearer token"
2977 },
2978 basicAuth: {
2979 type: "http",
2980 scheme: "basic"
2981 }
2982 }
2983 },
2984 security: [],
2985 tags: [{ name: "Security" }]
2986 },
2987 {
2988 includes: [
2989 `const ApiKeyAuthSecurity = HttpApiSecurity.apiKey({ key: "x-api-key", in: "header" }).pipe(HttpApiSecurity.annotate(OpenApi.Description, "API key"))`,
2990 `const BearerAuthSecurity = HttpApiSecurity.bearer.pipe(HttpApiSecurity.annotate(OpenApi.Description, "Bearer token")).pipe(HttpApiSecurity.annotate(OpenApi.Format, "JWT"))`,
2991 `const BasicAuthSecurity = HttpApiSecurity.basic`,
2992 `class ApiKeyAuthOrBearerAuthSecurityMiddleware extends HttpApiMiddleware.Service<ApiKeyAuthOrBearerAuthSecurityMiddleware>()("apiKeyAuth | bearerAuth security", { security: { "apiKeyAuth": ApiKeyAuthSecurity, "bearerAuth": BearerAuthSecurity } }) {}`,
2993 `class ApiKeyAuthAndBasicAuthSecurityMiddleware extends HttpApiMiddleware.Service<ApiKeyAuthAndBasicAuthSecurityMiddleware>()("apiKeyAuth & basicAuth security") {}`,
2994 `HttpApiEndpoint.get("getSecure", "/secure", { success: HttpApiSchema.Empty(200) })\n .middleware(ApiKeyAuthOrBearerAuthSecurityMiddleware)\n .middleware(ApiKeyAuthAndBasicAuthSecurityMiddleware)`,
2995 `HttpApiEndpoint.get("getPublic", "/public", { success: HttpApiSchema.Empty(200) })`
2996 ],
2997 excludes: [
2998 `HttpApiEndpoint.get("getPublic", "/public", { success: HttpApiSchema.Empty(200) })\n .middleware(`
2999 ],
3000 warnings: [
3001 {
3002 code: "security-and-downgraded",
3003 path: "/secure",
3004 method: "get",
3005 operationId: "getSecure"
3006 }
3007 ]
3008 }
3009 ))
3010
3011 it.effect("generates custom http security schemes", () =>
3012 assertHttpApiWithWarnings(
3013 {
3014 openapi: "3.1.0",
3015 info: {
3016 title: "Custom Security API",
3017 version: "1.0.0"
3018 },
3019 paths: {
3020 "/secure": {
3021 get: {
3022 operationId: "getSecure",
3023 parameters: [],
3024 responses: {
3025 200: {
3026 description: "Secure"
3027 }
3028 },
3029 tags: ["Security"],
3030 security: [{ digestAuth: [] }]
3031 }
3032 }
3033 },
3034 components: {
3035 schemas: {},
3036 securitySchemes: {
3037 digestAuth: {
3038 type: "http",
3039 scheme: "Digest",
3040 bearerFormat: "DigestToken",
3041 description: "Digest token"
3042 }
3043 }
3044 },
3045 security: [],
3046 tags: [{ name: "Security" }]
3047 },
3048 {
3049 includes: [
3050 `const DigestAuthSecurity = HttpApiSecurity.http({ scheme: "Digest" }).pipe(HttpApiSecurity.annotate(OpenApi.Description, "Digest token")).pipe(HttpApiSecurity.annotate(OpenApi.Format, "DigestToken"))`,
3051 `class DigestAuthSecurityMiddleware extends HttpApiMiddleware.Service<DigestAuthSecurityMiddleware>()("digestAuth security", { security: { "digestAuth": DigestAuthSecurity } }) {}`
3052 ],
3053 warnings: []
3054 }
3055 ))
3056
3057 it.effect("inherits global security and respects operation-level clearing", () =>
3058 assertHttpApiWithWarnings(
3059 {
3060 openapi: "3.1.0",
3061 info: {
3062 title: "Security inheritance API",
3063 version: "1.0.0"
3064 },
3065 paths: {
3066 "/inherited": {
3067 get: {
3068 operationId: "getInherited",
3069 parameters: [],
3070 responses: {
3071 200: {
3072 description: "Inherited"
3073 }
3074 },
3075 tags: ["Security"]
3076 } as any
3077 },
3078 "/inherited-two": {
3079 get: {
3080 operationId: "getInheritedTwo",
3081 parameters: [],
3082 responses: {
3083 200: {
3084 description: "Inherited two"
3085 }
3086 },
3087 tags: ["Security"]
3088 } as any
3089 },
3090 "/cleared": {
3091 get: {
3092 operationId: "getCleared",
3093 parameters: [],
3094 responses: {
3095 200: {
3096 description: "Cleared"
3097 }
3098 },
3099 tags: ["Security"],
3100 security: []
3101 }
3102 },
3103 "/anonymous": {
3104 get: {
3105 operationId: "getAnonymous",
3106 parameters: [],
3107 responses: {
3108 200: {
3109 description: "Anonymous"
3110 }
3111 },
3112 tags: ["Security"],
3113 security: [{}]
3114 }
3115 },
3116 "/override": {
3117 get: {
3118 operationId: "getOverride",
3119 parameters: [],
3120 responses: {
3121 200: {
3122 description: "Override"
3123 }
3124 },
3125 tags: ["Security"],
3126 security: [{ bearerAuth: [] }]
3127 }
3128 }
3129 },
3130 components: {
3131 schemas: {},
3132 securitySchemes: {
3133 apiKeyAuth: {
3134 type: "apiKey",
3135 name: "x-api-key",
3136 in: "header"
3137 },
3138 bearerAuth: {
3139 type: "http",
3140 scheme: "bearer"
3141 }
3142 }
3143 },
3144 security: [{ apiKeyAuth: [] }],
3145 tags: [{ name: "Security" }]
3146 },
3147 {
3148 includes: [
3149 `class ApiKeyAuthSecurityMiddleware extends HttpApiMiddleware.Service<ApiKeyAuthSecurityMiddleware>()("apiKeyAuth security", { security: { "apiKeyAuth": ApiKeyAuthSecurity } }) {}`,
3150 `class BearerAuthSecurityMiddleware extends HttpApiMiddleware.Service<BearerAuthSecurityMiddleware>()("bearerAuth security", { security: { "bearerAuth": BearerAuthSecurity } }) {}`,
3151 `HttpApiEndpoint.get("getInherited", "/inherited", { success: HttpApiSchema.Empty(200) })\n .middleware(ApiKeyAuthSecurityMiddleware)`,
3152 `HttpApiEndpoint.get("getInheritedTwo", "/inherited-two", { success: HttpApiSchema.Empty(200) })\n .middleware(ApiKeyAuthSecurityMiddleware)`,
3153 `HttpApiEndpoint.get("getCleared", "/cleared", { success: HttpApiSchema.Empty(200) })`,
3154 `HttpApiEndpoint.get("getAnonymous", "/anonymous", { success: HttpApiSchema.Empty(200) })`,
3155 `HttpApiEndpoint.get("getOverride", "/override", { success: HttpApiSchema.Empty(200) })\n .middleware(BearerAuthSecurityMiddleware)`
3156 ],
3157 excludes: [
3158 `HttpApiEndpoint.get("getCleared", "/cleared", { success: HttpApiSchema.Empty(200) })\n .middleware(`,
3159 `HttpApiEndpoint.get("getAnonymous", "/anonymous", { success: HttpApiSchema.Empty(200) })\n .middleware(`
3160 ],
3161 occurrences: [
3162 {
3163 substring:
3164 `class ApiKeyAuthSecurityMiddleware extends HttpApiMiddleware.Service<ApiKeyAuthSecurityMiddleware>()("apiKeyAuth security", { security: { "apiKeyAuth": ApiKeyAuthSecurity } }) {}`,
3165 count: 1
3166 }
3167 ],
3168 warnings: []
3169 }
3170 ))
3171
3172 it.effect("emits lossy warnings and skips unsupported httpapi operations", () =>
3173 assertHttpApiWithWarnings(
3174 {
3175 openapi: "3.1.0",
3176 info: {
3177 title: "Warnings API",
3178 version: "1.0.0"
3179 },
3180 paths: {
3181 "/cookies": {
3182 get: {
3183 operationId: "getCookie",
3184 parameters: [
3185 {
3186 name: "session",
3187 in: "cookie",
3188 schema: { type: "string" },
3189 required: false
3190 }
3191 ],
3192 responses: {
3193 200: {
3194 description: "Cookie"
3195 }
3196 },
3197 tags: ["Warnings"],
3198 security: []
3199 }
3200 },
3201 "/tags": {
3202 get: {
3203 operationId: "getTagged",
3204 parameters: [],
3205 responses: {
3206 200: {
3207 description: "Tagged"
3208 }
3209 },
3210 tags: ["Warnings", "ExtraTag"],
3211 security: []
3212 }
3213 },
3214 "/sse": {
3215 get: {
3216 operationId: "streamEvents",
3217 parameters: [],
3218 responses: {
3219 200: {
3220 description: "Events",
3221 content: {
3222 "text/event-stream": {
3223 schema: {
3224 type: "string"
3225 }
3226 }
3227 }
3228 }
3229 },
3230 tags: ["Warnings"],
3231 security: []
3232 }
3233 },
3234 "/headers": {
3235 get: {
3236 operationId: "getHeaders",
3237 parameters: [],
3238 responses: {
3239 200: {
3240 description: "Headers",
3241 headers: {
3242 "x-rate-limit": {
3243 schema: {
3244 type: "integer"
3245 }
3246 }
3247 }
3248 }
3249 } as any,
3250 tags: ["Warnings"],
3251 security: []
3252 }
3253 },
3254 "/default-success": {
3255 get: {
3256 operationId: "getDefaultSuccess",
3257 parameters: [],
3258 responses: {
3259 200: {
3260 description: "OK"
3261 },
3262 default: {
3263 description: "Fallback"
3264 }
3265 } as any,
3266 tags: ["Warnings"],
3267 security: []
3268 }
3269 },
3270 "/default-only": {
3271 get: {
3272 operationId: "getDefaultOnly",
3273 parameters: [],
3274 responses: {
3275 default: {
3276 description: "Fallback"
3277 }
3278 } as any,
3279 tags: ["Warnings"],
3280 security: []
3281 }
3282 },
3283 "/nobody": {
3284 get: {
3285 operationId: "getNoBody",
3286 parameters: [],
3287 requestBody: {
3288 required: true,
3289 content: {
3290 "application/json": {
3291 schema: {
3292 type: "object",
3293 properties: {
3294 a: { type: "string" }
3295 },
3296 required: ["a"],
3297 additionalProperties: false
3298 }
3299 }
3300 }
3301 },
3302 responses: {
3303 200: {
3304 description: "No body"
3305 }
3306 },
3307 tags: ["Warnings"],
3308 security: []
3309 }
3310 }
3311 },
3312 components: {
3313 schemas: {},
3314 securitySchemes: {}
3315 },
3316 security: [],
3317 tags: [{ name: "Warnings" }]
3318 },
3319 {
3320 includes: [
3321 `HttpApiEndpoint.get("getCookie", "/cookies", { success: HttpApiSchema.Empty(200) })`,
3322 `HttpApiEndpoint.get("getHeaders", "/headers", { success: HttpApiSchema.Empty(200) })`,
3323 `HttpApiEndpoint.get("getDefaultSuccess", "/default-success", { success: HttpApiSchema.Empty(200), error: HttpApiSchema.Empty(500) })`,
3324 `HttpApiEndpoint.get("getDefaultOnly", "/default-only", { success: HttpApiSchema.Empty(200) })`
3325 ],
3326 excludes: [
3327 `HttpApiEndpoint.get("streamEvents", "/sse"`,
3328 `HttpApiEndpoint.get("getNoBody", "/nobody"`
3329 ],
3330 warnings: [
3331 {
3332 code: "cookie-parameter-dropped",
3333 path: "/cookies",
3334 method: "get",
3335 operationId: "getCookie"
3336 },
3337 {
3338 code: "additional-tags-dropped",
3339 path: "/tags",
3340 method: "get",
3341 operationId: "getTagged"
3342 },
3343 {
3344 code: "sse-operation-skipped",
3345 path: "/sse",
3346 method: "get",
3347 operationId: "streamEvents"
3348 },
3349 {
3350 code: "response-headers-ignored",
3351 path: "/headers",
3352 method: "get",
3353 operationId: "getHeaders"
3354 },
3355 {
3356 code: "default-response-remapped",
3357 path: "/default-success",
3358 method: "get",
3359 operationId: "getDefaultSuccess"
3360 },
3361 {
3362 code: "default-response-remapped",
3363 path: "/default-only",
3364 method: "get",
3365 operationId: "getDefaultOnly"
3366 },
3367 {
3368 code: "no-body-method-request-body-skipped",
3369 path: "/nobody",
3370 method: "get",
3371 operationId: "getNoBody"
3372 }
3373 ]
3374 }
3375 ))
3376 })
3377
3378 describe("QUERY", () => {
3379 const queryOperation: OpenAPISpecOperation = {
3380 operationId: "search",
3381 parameters: [],
3382 tags: ["Search"],
3383 security: [],
3384 requestBody: {
3385 required: true,
3386 content: {
3387 "application/json": {
3388 schema: {
3389 type: "object",
3390 properties: { query: { type: "string" } },
3391 required: ["query"],
3392 additionalProperties: false
3393 }
3394 }
3395 }
3396 },
3397 responses: { "204": { description: "No content" } }
3398 }
3399
3400 const makeQuerySpec = (pathItem: OpenAPISpecPathItem & { query?: OpenAPISpecOperation }): OpenAPISpec => ({
3401 openapi: "3.1.0",
3402 info: { title: "QUERY API", version: "1.0.0" },
3403 components: { schemas: {}, securitySchemes: {} },
3404 security: [],
3405 tags: [{ name: "Search" }],
3406 paths: {
3407 "/search": {
3408 get: {
3409 operationId: "list",
3410 parameters: [],
3411 tags: ["Search"],
3412 security: [],
3413 responses: { "204": { description: "No content" } }
3414 },
3415 ...pathItem
3416 }
3417 }
3418 })
3419
3420 it.effect.each([
3421 {
3422 name: "OpenAPI 3.1 extension",
3423 spec: makeQuerySpec({ "x-oai-additionalOperations": { QUERY: queryOperation } })
3424 },
3425 {
3426 name: "native OpenAPI 3.2 field",
3427 spec: {
3428 ...makeQuerySpec({
3429 query: queryOperation,
3430 "x-oai-additionalOperations": { QUERY: { ...queryOperation, operationId: "legacySearch" } }
3431 }),
3432 openapi: "3.2.0"
3433 } as unknown as OpenAPISpec
3434 }
3435 ])("generates QUERY request bodies from the $name", ({ spec }) =>
3436 Effect.all([
3437 assertRuntimeIncludes(spec, [
3438 `HttpClientRequest.get("/search")`,
3439 `HttpClientRequest.query("/search")`,
3440 `export const SearchRequestJson = Schema.Struct({ "query": Schema.String })`,
3441 `HttpClientRequest.bodyJsonUnsafe(options.payload)`,
3442 `readonly payload: typeof SearchRequestJson.Encoded`
3443 ], ["legacySearch", "LegacySearch"]),
3444 assertTypeOnlyIncludes(spec, [
3445 `HttpClientRequest.get("/search")`,
3446 `HttpClientRequest.query("/search")`,
3447 `HttpClientRequest.bodyJsonUnsafe(options.payload)`,
3448 `export type SearchRequestJson = { readonly "query": string }`,
3449 `readonly payload: SearchRequestJson`
3450 ], ["legacySearch", "LegacySearch"]),
3451 assertHttpApiIncludes(spec, [
3452 `HttpApiEndpoint.get("list", "/search"`,
3453 `export const SearchRequestJson = Schema.Struct({ "query": Schema.String })`,
3454 `HttpApiEndpoint.query("search", "/search", { payload: SearchRequestJson, success: HttpApiSchema.Empty(204) })`
3455 ], ["legacySearch", "LegacySearch"])
3456 ]))
3457 })
3458
3459 describe("regression", () => {
3460 for (const format of ["httpclient", "httpclient-type-only"] as const) {
3461 for (const exactOptionalPropertyTypes of [true, false]) {
3462 itGeneratedClientsCompile(
3463 `preserves includeResponse success types (${format}, exactOptionalPropertyTypes=${exactOptionalPropertyTypes})`,
3464 {
3465 openapi: "3.1.0",
3466 info: { title: "Value", version: "1.0.0" },
3467 components: { schemas: {}, securitySchemes: {} },
3468 security: [],
3469 tags: [],
3470 paths: {
3471 "/value": {
3472 get: {
3473 operationId: "getValue",
3474 parameters: [],
3475 security: [],
3476 tags: ["Value"],
3477 responses: {
3478 "200": {
3479 description: "Value",
3480 content: { "application/json": { schema: { type: "string" } } }
3481 }
3482 }
3483 }
3484 }
3485 }
3486 },
3487 {
3488 formats: [format],
3489 exactOptionalPropertyTypes,
3490 usage: `type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends
3491 (<T>() => T extends B ? 1 : 2) ? true : false
3492 type Assert<T extends true> = T
3493 type WithResponse = [string, HttpClientResponse.HttpClientResponse]
3494 declare const client: TestClient
3495 declare const dynamic: boolean
3496 declare const optionalTrue: { readonly includeResponse?: true }
3497 declare const optionalBoolean: { readonly includeResponse?: boolean }
3498 declare const nullableConfig: { readonly includeResponse: true } | undefined
3499
3500 const enabled = client.getValue({ config: { includeResponse: true } })
3501 const disabled = client.getValue({ config: { includeResponse: false } })
3502 const omitted = client.getValue(undefined)
3503 const emptyOptions = client.getValue({})
3504 const undefinedConfig = client.getValue({ config: undefined })
3505 const dynamicResult = client.getValue({ config: { includeResponse: dynamic } })
3506 const optionalTrueResult = client.getValue({ config: optionalTrue })
3507 const optionalBooleanResult = client.getValue({ config: optionalBoolean })
3508 const nullableConfigResult = client.getValue({ config: nullableConfig })
3509 const conditionalConfig = Math.random() > 0.5 ? { includeResponse: true as const } : undefined
3510 const conditionalConfigResult = client.getValue({ config: conditionalConfig })
3511
3512 export type Enabled = Assert<Equal<Effect.Success<typeof enabled>, WithResponse>>
3513 export type Disabled = Assert<Equal<Effect.Success<typeof disabled>, string>>
3514 export type Omitted = Assert<Equal<Effect.Success<typeof omitted>, string>>
3515 export type EmptyOptions = Assert<Equal<Effect.Success<typeof emptyOptions>, string>>
3516 export type UndefinedConfig = Assert<Equal<Effect.Success<typeof undefinedConfig>, string>>
3517 export type Dynamic = Assert<Equal<Effect.Success<typeof dynamicResult>, string | WithResponse>>
3518 export type OptionalTrue = Assert<Equal<Effect.Success<typeof optionalTrueResult>, string | WithResponse>>
3519 export type OptionalBoolean = Assert<Equal<Effect.Success<typeof optionalBooleanResult>, string | WithResponse>>
3520 export type NullableConfig = Assert<Equal<Effect.Success<typeof nullableConfigResult>, string | WithResponse>>
3521 export type ConditionalConfig = Assert<Equal<Effect.Success<typeof conditionalConfigResult>, string | WithResponse>>
3522 `
3523 }
3524 )
3525 }
3526
3527 itGeneratedClientsCompile(`preserves HttpClient error and requirement types (${format})`, {
3528 openapi: "3.1.0",
3529 info: { title: "Channels", version: "1.0.0" },
3530 components: { schemas: {}, securitySchemes: {} },
3531 security: [],
3532 tags: [],
3533 paths: Object.fromEntries(
3534 [
3535 ["/value", "getValue", "application/json"],
3536 ["/download", "download", "application/octet-stream"],
3537 ...(format === "httpclient" ? [["/events", "events", "text/event-stream"]] : [])
3538 ].map(([path, operationId, contentType]) => [path, {
3539 get: {
3540 operationId,
3541 parameters: [],
3542 security: [],
3543 tags: ["Channels"],
3544 responses: {
3545 "200": { description: "OK", content: { [contentType]: { schema: { type: "string" } } } }
3546 }
3547 }
3548 }])
3549 )
3550 }, {
3551 formats: [format],
3552 usage: `type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends
3553 (<T>() => T extends B ? 1 : 2) ? true : false
3554 type Assert<T extends true> = T
3555 interface CustomError { readonly _tag: "CustomError" }
3556 interface CustomService { readonly _tag: "CustomService" }
3557 declare const httpClient: HttpClient.HttpClient.With<CustomError, CustomService>
3558 declare const defaultHttpClient: HttpClient.HttpClient
3559
3560 const client = make(httpClient)
3561 const value = client.getValue(undefined)
3562 const download = client.downloadStream()
3563
3564 export const defaultClient: TestClient = make(defaultHttpClient)
3565 export type ValueError = Assert<CustomError | HttpClientError.HttpClientError extends Effect.Error<typeof value> ? true : false>
3566 export type ValueServices = Assert<Equal<Effect.Services<typeof value>, CustomService>>
3567 export type DownloadError = Assert<Equal<Stream.Error<typeof download>, CustomError | HttpClientError.HttpClientError>>
3568 export type DownloadServices = Assert<Equal<Stream.Services<typeof download>, CustomService>>
3569 ${
3570 format === "httpclient"
3571 ? `const events = client.eventsSse()
3572 export type EventsError = Assert<CustomError | HttpClientError.HttpClientError extends Stream.Error<typeof events> ? true : false>
3573 export type EventsServices = Assert<CustomService extends Stream.Services<typeof events> ? true : false>
3574 `
3575 : ""
3576 }`
3577 })
3578 }
3579
3580 it.effect("quotes static path text with and without parameters", () => {
3581 const prefix = "/files/\"`\\\n/"
3582 const suffix = "/content\"`"
3583 const operation: OpenAPISpecOperation = {
3584 operationId: "read",
3585 parameters: [],
3586 tags: ["Files"],
3587 security: [],
3588 responses: { "204": { description: "No content" } }
3589 }
3590 return assertRuntimeIncludes({
3591 openapi: "3.1.0",
3592 info: { title: "Quoted paths", version: "1.0.0" },
3593 components: { schemas: {}, securitySchemes: {} },
3594 security: [],
3595 tags: [],
3596 paths: {
3597 [prefix + suffix]: { get: operation },
3598 [prefix + "{id}" + suffix]: {
3599 get: {
3600 ...operation,
3601 operationId: "readById",
3602 parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }]
3603 }
3604 }
3605 }
3606 }, [
3607 `HttpClientRequest.get(${JSON.stringify(prefix + suffix)})`,
3608 `() => ${JSON.stringify(prefix)} + __encodePathParam(id) + ${JSON.stringify(suffix)}`
3609 ])
3610 })
3611
3612 itGeneratedClientsCompile("types required cookie parameters as operation params", cookieParameterSpec, {
3613 usage: `declare const client: TestClient
3614 export const withLocale = client.getGreeting({ params: { locale: "en-US" } })
3615 // @ts-expect-error the locale cookie is required
3616 export const withoutLocale = client.getGreeting({ params: {} })
3617 `
3618 })
3619
3620 it.effect("sends cookie parameters with the request", () =>
3621 Effect.gen(function*() {
3622 const generator = yield* OpenApiGenerator.OpenApiGenerator
3623 const source = yield* generator.generate(cookieParameterSpec, { name: "TestClient", format: "httpclient" })
3624 const directory = yield* Effect.acquireRelease(
3625 Effect.sync(() => mkdtempSync(join(dirname(fileURLToPath(import.meta.url)), ".generated-clients-"))),
3626 (directory) => Effect.sync(() => rmSync(directory, { recursive: true, force: true }))
3627 )
3628 const path = join(directory, "Client.ts")
3629 writeFileSync(path, source)
3630 const { make }: {
3631 make: (client: HttpClient.HttpClient) => {
3632 getGreeting: (options: { params: { locale: string } }) => Effect.Effect<unknown, unknown>
3633 }
3634 } = yield* Effect.promise(() => import(path))
3635 const requests: Array<HttpClientRequest.HttpClientRequest> = []
3636 const client = make(
3637 HttpClient.make((request) => {
3638 requests.push(request)
3639 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status: 204 })))
3640 }).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl("http://api.test")))
3641 )
3642
3643 yield* client.getGreeting({ params: { locale: "en-US" } })
3644
3645 assert.strictEqual(requests.length, 1)
3646 assert.strictEqual(requests[0].headers["cookie"], "locale=en-US")
3647 }).pipe(Effect.scoped, Effect.provide(OpenApiGenerator.layerTransformerSchema)))
3648
3649 it.effect("escapes spec-controlled names in generated source", () =>
3650 Effect.gen(function*() {
3651 const path = "/items\"q"
3652 const content = { "application/json": { schema: { type: "string" } } }
3653 const spec = {
3654 openapi: "3.1.0",
3655 info: { title: "Quoted names", version: "1.0.0" },
3656 paths: {
3657 [path]: {
3658 get: {
3659 parameters: (["query", "header", "cookie"] as const).map((location) => ({
3660 name: `${location}"`,
3661 in: location,
3662 schema: { type: "string" }
3663 })),
3664 responses: {
3665 "200": { description: "OK", content },
3666 "x-extension": { description: "Extension", content },
3667 "4\"0": { description: "Invalid status", content }
3668 },
3669 tags: ["Items"],
3670 security: []
3671 }
3672 }
3673 },
3674 components: { schemas: {}, securitySchemes: {} },
3675 security: [],
3676 tags: [{ name: "Items" }]
3677 } as unknown as OpenAPISpec
3678 const directory = yield* Effect.acquireRelease(
3679 Effect.sync(() => mkdtempSync(join(dirname(fileURLToPath(import.meta.url)), ".generated-clients-"))),
3680 (directory) => Effect.sync(() => rmSync(directory, { recursive: true, force: true }))
3681 )
3682 const modules: Record<string, unknown> = {}
3683 for (const format of ["httpclient", "httpclient-type-only", "httpapi"] as const) {
3684 const source = yield* OpenApiGenerator.OpenApiGenerator.use((generator) =>
3685 generator.generate(spec, { name: "TestClient", format })
3686 ).pipe(
3687 Effect.provide(
3688 format === "httpclient-type-only"
3689 ? OpenApiGenerator.layerTransformerTs
3690 : OpenApiGenerator.layerTransformerSchema
3691 )
3692 )
3693 const file = join(directory, `${format}.ts`)
3694 writeFileSync(file, source)
3695 modules[format] = yield* Effect.promise(() => import(file))
3696 }
3697
3698 const requests: Array<HttpClientRequest.HttpClientRequest> = []
3699 const { make } = modules.httpclient as {
3700 make: (client: HttpClient.HttpClient) => Record<
3701 string,
3702 (options: { params: Record<string, string> }) => Effect.Effect<unknown, unknown>
3703 >
3704 }
3705 const client = make(
3706 HttpClient.make((request) => {
3707 requests.push(request)
3708 return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json("ok")))
3709 }).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl("http://api.test")))
3710 )
3711
3712 const result = yield* client[`GET${path}`]({ params: { "query\"": "a", "header\"": "b", "cookie\"": "c" } })
3713
3714 assert.strictEqual(result, "ok")
3715 assert.strictEqual(requests.length, 1)
3716 assert.deepStrictEqual(requests[0].urlParams.params, [["query\"", "a"]])
3717 assert.strictEqual(requests[0].headers["header\""], "b")
3718 assert.strictEqual(requests[0].headers["cookie"], "cookie\"=c")
3719 }).pipe(Effect.scoped))
3720
3721 it.effect("drops structured cookie parameters with a warning", () =>
3722 Effect.gen(function*() {
3723 const generator = yield* OpenApiGenerator.OpenApiGenerator
3724 const warnings: Array<OpenApiGenerator.OpenApiGeneratorWarning> = []
3725 const result = yield* generator.generate({
3726 ...cookieParameterSpec,
3727 paths: {
3728 "/greeting": {
3729 get: {
3730 ...cookieParameterSpec.paths["/greeting"].get!,
3731 parameters: [
3732 {
3733 name: "inlinePrefs",
3734 in: "cookie",
3735 required: true,
3736 schema: { type: "object", properties: { locale: { type: "string" } }, required: ["locale"] }
3737 },
3738 {
3739 name: "refPrefs",
3740 in: "cookie",
3741 required: true,
3742 schema: { $ref: "#/components/schemas/Preferences" }
3743 }
3744 ]
3745 }
3746 }
3747 },
3748 components: {
3749 schemas: {
3750 Preferences: { type: "object", properties: { locale: { type: "string" } }, required: ["locale"] }
3751 },
3752 securitySchemes: {}
3753 }
3754 }, {
3755 name: "TestClient",
3756 format: "httpclient",
3757 onWarning: (warning) => {
3758 warnings.push(warning)
3759 }
3760 })
3761
3762 assert.deepStrictEqual(
3763 warnings.map((warning) => [warning.code, warning.operationId]),
3764 [["cookie-parameter-dropped", "getGreeting"], ["cookie-parameter-dropped", "getGreeting"]]
3765 )
3766 assert.notInclude(result, "inlinePrefs")
3767 assert.notInclude(result, "refPrefs")
3768 }).pipe(Effect.provide(OpenApiGenerator.layerTransformerSchema)))
3769
3770 itGeneratedClientsCompile("emits compilable clients when schema examples are invalid", {
3771 openapi: "3.0.3",
3772 info: {
3773 title: "Invalid examples API",
3774 version: "1.0.0"
3775 },
3776 paths: {
3777 "/triggers": {
3778 get: {
3779 operationId: "getTriggers",
3780 parameters: [],
3781 responses: {
3782 200: {
3783 description: "OK",
3784 content: {
3785 "application/json": {
3786 schema: {
3787 type: "array",
3788 items: { type: "string" },
3789 example: "create"
3790 }
3791 }
3792 }
3793 }
3794 },
3795 tags: ["Triggers"],
3796 security: []
3797 }
3798 }
3799 },
3800 components: {
3801 schemas: {},
3802 securitySchemes: {}
3803 },
3804 security: [],
3805 tags: [{ name: "Triggers" }]
3806 } as unknown as OpenAPISpec)
3807
3808 it.effect("runtime warnings do not report additional-tags-dropped outside httpapi", () =>
3809 assertRuntimeStableWithWarnings(
3810 {
3811 openapi: "3.1.0",
3812 info: {
3813 title: "Warnings regression API",
3814 version: "1.0.0"
3815 },
3816 paths: {
3817 "/multi-tag": {
3818 get: {
3819 operationId: "getMultiTag",
3820 parameters: [],
3821 responses: {
3822 200: {
3823 description: "OK"
3824 }
3825 },
3826 tags: ["One", "Two"],
3827 security: []
3828 }
3829 }
3830 },
3831 components: {
3832 schemas: {},
3833 securitySchemes: {}
3834 },
3835 security: [],
3836 tags: [{ name: "One" }, { name: "Two" }]
3837 },
3838 []
3839 ))
3840
3841 it.effect("runtime output remains stable when using onWarning", () =>
3842 assertRuntimeStableWithWarnings(regressionSpec, [
3843 {
3844 code: "default-response-remapped",
3845 path: "/users/{id}",
3846 method: "get",
3847 operationId: "getUser"
3848 }
3849 ]))
3850
3851 it.effect("type-only output remains stable when using onWarning", () =>
3852 assertTypeOnlyStableWithWarnings(regressionSpec, [
3853 {
3854 code: "default-response-remapped",
3855 path: "/users/{id}",
3856 method: "get",
3857 operationId: "getUser"
3858 }
3859 ]))
3860
3861 itGeneratedClientsCompile("emits compilable open objects with optional properties", {
3862 openapi: "3.1.0",
3863 info: {
3864 title: "Open object regression API",
3865 version: "1.0.0"
3866 },
3867 paths: {
3868 "/widget": {
3869 get: {
3870 operationId: "getWidget",
3871 parameters: [],
3872 responses: {
3873 200: {
3874 description: "OK",
3875 content: {
3876 "application/json": {
3877 schema: {
3878 type: "object",
3879 properties: {
3880 optionalValue: {
3881 type: "string"
3882 }
3883 },
3884 additionalProperties: true
3885 }
3886 }
3887 }
3888 }
3889 },
3890 tags: ["Widgets"],
3891 security: []
3892 }
3893 }
3894 },
3895 components: {
3896 schemas: {},
3897 securitySchemes: {}
3898 },
3899 security: [],
3900 tags: []
3901 }, {
3902 exactOptionalPropertyTypes: false,
3903 formats: ["httpclient"]
3904 })
3905
3906 itGeneratedClientsCompile(
3907 "types multipart binary fields as File | Blob for generated clients",
3908 multipartSpec({
3909 type: "object",
3910 properties: { file: { type: "string", format: "binary" } },
3911 required: ["file"],
3912 additionalProperties: false
3913 }),
3914 {
3915 usage: `export const withFile: UploadRequestFormData = { file: new File([], "upload.txt") }
3916 export const withBlob: UploadRequestFormData = { file: new Blob([]) }
3917 // @ts-expect-error Binary multipart fields do not accept strings.
3918 export const withString: UploadRequestFormData = { file: "upload.txt" }
3919 `
3920 }
3921 )
3922
3923 itGeneratedClientsCompile(
3924 "types recursive multipart binary references as File | Blob for generated clients",
3925 multipartSpec({ $ref: "#/components/schemas/Node" }, {
3926 Node: {
3927 type: "object",
3928 properties: {
3929 file: { type: "string", format: "binary" },
3930 child: { $ref: "#/components/schemas/Node" }
3931 },
3932 required: ["file"],
3933 additionalProperties: false
3934 }
3935 }),
3936 {
3937 usage: `const file = new File([], "upload.txt")
3938 const blob = new Blob([])
3939 export const payload: UploadRequestFormData = { file, child: { file: blob, child: { file } } }
3940 // @ts-expect-error Recursive binary fields do not accept strings.
3941 export const withString: UploadRequestFormData = { file, child: { file: "upload.txt" } }
3942 `
3943 }
3944 )
3945
3946 for (
3947 const [format, assertIncludes] of [
3948 ["httpclient", assertRuntimeIncludes],
3949 ["httpclient-type-only", assertTypeOnlyIncludes]
3950 ] as const
3951 ) {
3952 it.effect(`preserves named multipart components without binary fields (${format})`, () =>
3953 assertIncludes(
3954 multipartSpec({ $ref: "#/components/schemas/FormBody" }, {
3955 FormBody: {
3956 type: "object",
3957 properties: {
3958 name: { type: "string" },
3959 meta: { $ref: "#/components/schemas/Meta" }
3960 },
3961 required: ["name"],
3962 additionalProperties: false
3963 },
3964 Meta: {
3965 type: "object",
3966 properties: { k: { type: "string" } },
3967 required: ["k"],
3968 additionalProperties: false
3969 }
3970 }),
3971 [
3972 "export type Meta =",
3973 "export type FormBody =",
3974 "export type UploadRequestFormData = FormBody"
3975 ]
3976 ))
3977 }
3978
3979 it.effect("maps aliased binary string components to multipart files for generated clients", () =>
3980 assertRuntimeIncludes(
3981 sharedMultipartSpec(
3982 {
3983 type: "object",
3984 properties: {
3985 file: { $ref: "#/components/schemas/Upload" },
3986 files: { type: "array", items: { $ref: "#/components/schemas/Upload" } }
3987 },
3988 required: ["file", "files"],
3989 additionalProperties: false
3990 },
3991 {
3992 Upload: { $ref: "#/components/schemas/BinaryData" },
3993 BinaryData: { type: "string", format: "binary" }
3994 },
3995 { schema: { $ref: "#/components/schemas/Upload" } }
3996 ),
3997 [
3998 `export type Upload = string`,
3999 `export type CreateJsonRequestJson = Upload`,
4000 `export type UploadRequestFormData = { readonly "file": __ClientMultipartFile, readonly "files": ReadonlyArray<__ClientMultipartFile> }`
4001 ]
4002 ))
4003
4004 itGeneratedClientsCompile(
4005 "types multipart binary arrays as File | Blob arrays for generated clients",
4006 multipartSpec({
4007 type: "object",
4008 properties: { files: { type: "array", items: { type: "string", format: "binary" } } },
4009 required: ["files"],
4010 additionalProperties: false
4011 }),
4012 {
4013 usage: `export const payload: UploadRequestFormData = { files: [new File([], "upload.txt"), new Blob([])] }
4014 // @ts-expect-error Binary multipart arrays do not accept strings.
4015 export const withString: UploadRequestFormData = { files: ["upload.txt"] }
4016 `
4017 }
4018 )
4019 })
4020 })
4021
4022 describe("generated client type checks", () => {
4023 it.effect(
4024 "do not pass a case whose type errors were hidden by another case's syntax error",
4025 () =>
4026 Effect.gen(function*() {
4027 const [, typeError] = yield* typeCheckCases([
4028 { sources: ["export const broken = ;\n"], exactOptionalPropertyTypes: true },
4029 { sources: ["export const value: string = 42\n"], exactOptionalPropertyTypes: true }
4030 ])
4031 assert.isNotEmpty(typeError)
4032 }),
4033 compilationTimeout
4034 )
4035 })