Open History to see the last commit
1/**
2 * OpenAPI-to-HttpClient code generation for the OpenAPI generator.
3 *
4 * This module defines the `OpenApiTransformer` service used to render parsed
5 * OpenAPI operations into Effect `HttpClient` modules. It provides both
6 * schema-backed and type-only transformer implementations, including generated
7 * imports, public client interfaces, operation implementations, typed API
8 * errors, optional response handling, and helpers for server-sent events and
9 * binary response streams.
10 *
11 * @since 4.0.0
12 */
13import * as Context from "effect/Context"
14import * as Layer from "effect/Layer"
15import * as Predicate from "effect/Predicate"
16import type { ParsedOpenApi, ParsedOperation, ParsedOperationHttpClientResponses } from "./ParsedOperation.ts"
17import * as Utils from "./Utils.ts"
18
19/**
20 * Service used by the OpenAPI generator to render parsed operations as an
21 * Effect HttpClient module.
22 *
23 * **Details**
24 *
25 * A transformer owns the code-generation dialect for imports, public client
26 * types, and the implementation body. The generator swaps implementations to
27 * choose between schema-backed clients and type-only clients.
28 *
29 * @category services
30 * @since 4.0.0
31 */
32export class OpenApiTransformer extends Context.Service<
33 OpenApiTransformer,
34 {
35 readonly imports: (importName: string, parsed: ParsedOpenApi) => string
36 readonly toTypes: (importName: string, name: string, parsed: ParsedOpenApi) => string
37 readonly toImplementation: (importName: string, name: string, parsed: ParsedOpenApi) => string
38 }
39>()("OpenApiTransformer") {}
40
41interface ImportRequirements {
42 readonly eventStream: boolean
43 readonly eventStreamData: boolean
44 readonly eventStreamSchema: boolean
45 readonly octetStream: boolean
46}
47
48const computeImportRequirements = (operations: ReadonlyArray<ParsedOperation>): ImportRequirements => {
49 let eventStream = false
50 let eventStreamData = false
51 let eventStreamSchema = false
52 let octetStream = false
53 for (const op of operations) {
54 const responses = op.httpClientResponses
55 if (responses.sseSchema) {
56 eventStream = true
57 if (responses.sseSchemaMode === "event") {
58 eventStreamSchema = true
59 } else {
60 eventStreamData = true
61 }
62 }
63 if (responses.binarySuccessStatuses.size > 0) {
64 octetStream = true
65 }
66 }
67 return { eventStream, eventStreamData, eventStreamSchema, octetStream }
68}
69
70const requiresStreaming = (requirements: ImportRequirements): boolean =>
71 requirements.eventStream || requirements.octetStream
72
73const hasResponseVariants = (responses: ParsedOperationHttpClientResponses): boolean =>
74 responses.binarySuccessStatuses.size > 0 ||
75 responses.voidSuccessStatuses.size > 0 ||
76 responses.voidErrorStatuses.size > 0
77
78const normalizeSuccessStatus = (
79 responses: ParsedOperationHttpClientResponses,
80 status: string
81): string => {
82 const successCount = responses.successSchemas.size +
83 responses.binarySuccessStatuses.size +
84 responses.voidSuccessStatuses.size
85 return successCount === 1 && status.startsWith("2") ? "2xx" : status
86}
87
88const paramsToPipeline = (operation: ParsedOperation): Array<string> => {
89 const pipeline: Array<string> = []
90 if (!operation.params) {
91 return pipeline
92 }
93 const paramsAccessor = resolveParamsAccessor(operation, "options", "params")
94 if (operation.urlParams.length > 0) {
95 const props = operation.urlParams.map((param) => {
96 const key = JSON.stringify(param)
97 const value = `${paramsAccessor}[${key}]`
98 return `${key}: ${operation.commaUrlParams.includes(param) ? `__joinComma(${value})` : value} as any`
99 })
100 pipeline.push(`HttpClientRequest.setUrlParams({ ${props.join(", ")} })`)
101 }
102 if (operation.headers.length > 0) {
103 const props = operation.headers.map(
104 (param) => `${JSON.stringify(param)}: ${paramsAccessor}[${JSON.stringify(param)}] ?? undefined`
105 )
106 pipeline.push(`HttpClientRequest.setHeaders({ ${props.join(", ")} })`)
107 }
108 if (operation.cookies.length > 0) {
109 const props = operation.cookies.map(
110 (param) => `${JSON.stringify(param)}: ${paramsAccessor}[${JSON.stringify(param)}]`
111 )
112 pipeline.push(`HttpClientRequest.setHeaders({ "cookie": __cookieHeader({ ${props.join(", ")} }) })`)
113 }
114 return pipeline
115}
116
117const requestToImpl = (operation: ParsedOperation, pipeline: Array<string>, streaming = false): string => {
118 const request = `HttpClientRequest.${operation.method}`
119 const pipe = `.pipe(\n ${pipeline.join(",\n ")}\n )`
120 if (operation.pathIds.length === 0) {
121 return `${request}(${operation.pathTemplate})${pipe}`
122 }
123 const effect = `__makePathRequest(${request}, [${
124 operation.pathIds.join(", ")
125 }], () => ${operation.pathTemplate}).pipe(
126 Effect.${streaming ? "map" : "flatMap"}((request) => request${pipe})
127 )`
128 return streaming ? `Stream.unwrap(${effect})` : effect
129}
130
131/**
132 * Create the transformer used for schema-backed HttpClient output.
133 *
134 * **Details**
135 *
136 * Generated clients import Effect Schema values and use them at runtime to
137 * decode successful responses and typed API errors. Request parameters and
138 * payloads are typed against each schema's encoded representation.
139 *
140 * @category code generation
141 * @since 4.0.0
142 */
143export const makeTransformerSchema = () => {
144 const operationsToInterface = (
145 _importName: string,
146 name: string,
147 operations: ReadonlyArray<ParsedOperation>
148 ) => {
149 const methods: Array<string> = []
150 for (const op of operations) {
151 methods.push(operationToMethod(name, op))
152 if (op.httpClientResponses.sseSchema) {
153 methods.push(operationToSseMethod(name, op))
154 }
155 if (op.httpClientResponses.binarySuccessStatuses.size > 0) {
156 methods.push(operationToBinaryMethod(name, op))
157 }
158 }
159 return `export interface ${name}<E = HttpClientError.HttpClientError, R = never> {
160 readonly httpClient: HttpClient.HttpClient.With<E, R>
161 ${methods.join("\n ")}
162}
163
164${clientErrorSource(name)}`
165 }
166
167 const operationToMethod = (name: string, operation: ParsedOperation) => {
168 const responses = operation.httpClientResponses
169 const args: Array<string> = []
170 if (operation.pathIds.length > 0) {
171 Utils.spreadElementsInto(operation.pathIds.map((id) => `${id}: string`), args)
172 }
173
174 const options: Array<string> = []
175 if (operation.params) {
176 const key = `readonly params${operation.paramsOptional ? "?" : ""}`
177 const type = `typeof ${operation.params}.Encoded${operation.paramsOptional ? " | undefined" : ""}`
178 options.push(`${key}: ${type}`)
179 }
180 if (operation.payload) {
181 const key = `readonly payload`
182 const type = `typeof ${operation.payload}.Encoded`
183 options.push(`${key}: ${type}`)
184 }
185 const hasOptions = (operation.params && !operation.paramsOptional) || operation.payload
186
187 const successTypes = new Set(responses.successSchemas.values())
188 if (responses.binarySuccessStatuses.size > 0) {
189 successTypes.add("Uint8Array")
190 }
191 if (responses.voidSuccessStatuses.size > 0) {
192 successTypes.add("void")
193 }
194 const success = successTypes.size > 0 ? Array.from(successTypes).join(" | ") : "void"
195 const errors = ["E", "HttpClientError.HttpClientError", "SchemaError"]
196 if (responses.errorSchemas.size > 0) {
197 Utils.spreadElementsInto(
198 Array.from(responses.errorSchemas.values()).map(
199 (schema) => `${name}Error<"${schema}", ${schema}>`
200 ),
201 errors
202 )
203 }
204 for (const status of responses.voidErrorStatuses) {
205 errors.push(`${name}Error<"${status}", undefined>`)
206 }
207
208 const jsdoc = Utils.toComment(operation.description)
209 const methodKey = `readonly ${JSON.stringify(operation.id)}`
210 return `${jsdoc}${methodKey}: ${operationSignatures(args, options, Boolean(hasOptions), success, errors)}`
211 }
212
213 const operationToSseMethod = (_name: string, operation: ParsedOperation) => {
214 const responses = operation.httpClientResponses
215 const args: Array<string> = []
216 if (operation.pathIds.length > 0) {
217 Utils.spreadElementsInto(operation.pathIds.map((id) => `${id}: string`), args)
218 }
219
220 const options: Array<string> = []
221 if (operation.params) {
222 const key = `readonly params${operation.paramsOptional ? "?" : ""}`
223 const type = `typeof ${operation.params}.Encoded${operation.paramsOptional ? " | undefined" : ""}`
224 options.push(`${key}: ${type}`)
225 }
226 if (operation.payload) {
227 options.push(`readonly payload: typeof ${operation.payload}.Encoded`)
228 }
229
230 const hasOptions = (operation.params && !operation.paramsOptional) || operation.payload
231 if (hasOptions) {
232 args.push(`options: { ${options.join("; ")} }`)
233 } else if (options.length > 0) {
234 args.push(`options: { ${options.join("; ")} } | undefined`)
235 }
236
237 const jsdoc = Utils.toComment(operation.description)
238 const methodKey = `readonly ${JSON.stringify(`${operation.id}Sse`)}`
239 const parameters = args.join(", ")
240 const value = responses.sseSchemaMode === "event"
241 ? responses.sseSchema
242 : `{ readonly event: string; readonly id: string | undefined; readonly data: ${responses.sseSchema} }`
243 const returnType =
244 `Stream.Stream<${value}, E | HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError, R | typeof ${responses.sseSchema}.DecodingServices>`
245 return `${jsdoc}${methodKey}: (${parameters}) => ${returnType}`
246 }
247
248 const operationToBinaryMethod = (_name: string, operation: ParsedOperation) => {
249 const args: Array<string> = []
250 if (operation.pathIds.length > 0) {
251 Utils.spreadElementsInto(operation.pathIds.map((id) => `${id}: string`), args)
252 }
253
254 const options: Array<string> = []
255 if (operation.params) {
256 const key = `readonly params${operation.paramsOptional ? "?" : ""}`
257 const type = `typeof ${operation.params}.Encoded${operation.paramsOptional ? " | undefined" : ""}`
258 options.push(`${key}: ${type}`)
259 }
260 if (operation.payload) {
261 options.push(`readonly payload: typeof ${operation.payload}.Encoded`)
262 }
263
264 const hasOptions = (operation.params && !operation.paramsOptional) || operation.payload
265 if (hasOptions) {
266 args.push(`options: { ${options.join("; ")} }`)
267 } else if (options.length > 0) {
268 args.push(`options: { ${options.join("; ")} } | undefined`)
269 }
270
271 const jsdoc = Utils.toComment(operation.description)
272 const methodKey = `readonly ${JSON.stringify(`${operation.id}Stream`)}`
273 const parameters = args.join(", ")
274 const returnType = `Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`
275 return `${jsdoc}${methodKey}: (${parameters}) => ${returnType}`
276 }
277
278 const operationsToImpl = (
279 importName: string,
280 name: string,
281 operations: ReadonlyArray<ParsedOperation>
282 ) => {
283 const requirements = computeImportRequirements(operations)
284 const implMethods: Array<string> = []
285 for (const op of operations) {
286 implMethods.push(operationToImpl(name, op))
287 if (op.httpClientResponses.sseSchema) {
288 implMethods.push(operationToSseImpl(importName, op))
289 }
290 if (op.httpClientResponses.binarySuccessStatuses.size > 0) {
291 implMethods.push(operationToBinaryImpl(op))
292 }
293 }
294
295 const helpers: Array<string> = [commonSource]
296 if (operations.some((operation) => operation.commaUrlParams.length > 0)) {
297 helpers.push(commaUrlParamsSource)
298 }
299 if (operations.some((operation) => operation.pathIds.length > 0)) {
300 helpers.push(pathRequestSource)
301 }
302 if (operations.some((operation) => operation.cookies.length > 0)) {
303 helpers.push(cookieHeaderSource)
304 }
305 if (requiresStreaming(requirements)) {
306 helpers.push(executeStreamRequestSource)
307 }
308 if (requirements.eventStreamData) {
309 helpers.push(sseRequestSource(importName))
310 }
311 if (requirements.eventStreamSchema) {
312 helpers.push(sseEventRequestSource)
313 }
314 if (requirements.octetStream) {
315 helpers.push(decodeBinarySource)
316 helpers.push(binaryRequestSource)
317 }
318 if (operations.some((operation) => operation.httpClientResponses.voidErrorStatuses.size > 0)) {
319 helpers.push(decodeVoidErrorSource(name))
320 }
321 helpers.push(decodeSuccessSource(importName))
322 if (operations.some((operation) => operation.httpClientResponses.errorSchemas.size > 0)) {
323 helpers.push(decodeErrorSource(importName, name))
324 }
325 return `export interface OperationConfig {
326 /**
327 * Whether or not the response should be included in the value returned from
328 * an operation.
329 *
330 * If set to \`true\`, a tuple of \`[A, HttpClientResponse]\` will be returned,
331 * where \`A\` is the success type of the operation.
332 *
333 * If set to \`false\`, only the success type of the operation will be returned.
334 */
335 readonly includeResponse?: boolean | undefined
336}
337
338/**
339 * A utility type which optionally includes the response in the return result
340 * of an operation based upon the value of the \`includeResponse\` configuration
341 * option.
342 */
343export type WithOptionalResponse<A, Config extends OperationConfig | undefined> = Config extends {
344 readonly includeResponse: true
345} ? [A, HttpClientResponse.HttpClientResponse]
346 : Config extends { readonly includeResponse?: false | undefined } | undefined ? A
347 : A | [A, HttpClientResponse.HttpClientResponse]
348
349export const make = <E, R>(
350 httpClient: HttpClient.HttpClient.With<E, R>,
351 options: {
352 readonly transformClient?: ((client: HttpClient.HttpClient.With<E, R>) => Effect.Effect<HttpClient.HttpClient.With<E, R>>) | undefined
353 } = {}
354): ${name}<E, R> => {
355 ${helpers.join("\n ")}
356 return {
357 httpClient,
358 ${implMethods.join(",\n ")}
359 }
360}`
361 }
362
363 const operationToImpl = (name: string, operation: ParsedOperation) => {
364 const responses = operation.httpClientResponses
365 const params = [
366 ...operation.pathIds,
367 `options: Parameters<${name}[${JSON.stringify(operation.id)}]>[${operation.pathIds.length}]`
368 ].join(", ")
369
370 const pipeline: Array<string> = []
371
372 pipeline.push(...paramsToPipeline(operation))
373
374 const payloadVarName = "options.payload"
375 if (operation.payloadFormData) {
376 pipeline.push(`HttpClientRequest.bodyFormDataRecord(${payloadVarName} as any)`)
377 } else if (operation.payloadFormUrlEncoded) {
378 pipeline.push(`HttpClientRequest.bodyUrlParams(${payloadVarName} as any)`)
379 } else if (operation.payload) {
380 pipeline.push(`HttpClientRequest.bodyJsonUnsafe(${payloadVarName})`)
381 }
382
383 const decodes: Array<string> = []
384 responses.successSchemas.forEach((schema, status) => {
385 decodes.push(`"${normalizeSuccessStatus(responses, status)}": decodeSuccess(${schema})`)
386 })
387 responses.binarySuccessStatuses.forEach((status) => {
388 decodes.push(`"${normalizeSuccessStatus(responses, status)}": decodeBinary`)
389 })
390 responses.errorSchemas.forEach((schema, status) => {
391 decodes.push(`"${status}": decodeError("${schema}", ${schema})`)
392 })
393 responses.voidSuccessStatuses.forEach((status) => {
394 decodes.push(`"${status}": () => Effect.void`)
395 })
396 responses.voidErrorStatuses.forEach((status) => {
397 decodes.push(`"${status}": decodeVoidError("${status}")`)
398 })
399 decodes.push(`orElse: unexpectedStatus`)
400
401 const configAccessor = resolveConfigAccessor(operation, "options", "config")
402 pipeline.push(`withResponse(${configAccessor})(HttpClientResponse.matchStatus({
403 ${decodes.join(",\n ")}
404 }))`)
405
406 return (
407 `${JSON.stringify(operation.id)}: (${params}) => ` +
408 requestToImpl(operation, pipeline)
409 )
410 }
411
412 const operationToSseImpl = (_importName: string, operation: ParsedOperation) => {
413 const responses = operation.httpClientResponses
414 const args: Array<string> = [...operation.pathIds]
415 const hasOptions = (operation.params && !operation.paramsOptional) || operation.payload
416 if (hasOptions || operation.params || operation.payload) {
417 args.push("options")
418 }
419 const params = args.join(", ")
420
421 const pipeline: Array<string> = []
422
423 pipeline.push(...paramsToPipeline(operation))
424
425 if (operation.payloadFormData) {
426 pipeline.push(`HttpClientRequest.bodyFormDataRecord(options.payload as any)`)
427 } else if (operation.payloadFormUrlEncoded) {
428 pipeline.push(`HttpClientRequest.bodyUrlParams(options.payload as any)`)
429 } else if (operation.payload) {
430 pipeline.push(`HttpClientRequest.bodyJsonUnsafe(options.payload)`)
431 }
432
433 pipeline.push(`${responses.sseSchemaMode === "event" ? "sseEventRequest" : "sseRequest"}(${responses.sseSchema})`)
434
435 return (
436 `${JSON.stringify(`${operation.id}Sse`)}: (${params}) => ` +
437 requestToImpl(operation, pipeline, true)
438 )
439 }
440
441 const operationToBinaryImpl = (operation: ParsedOperation) => {
442 const args: Array<string> = [...operation.pathIds]
443 const hasOptions = (operation.params && !operation.paramsOptional) || operation.payload
444 if (hasOptions || operation.params || operation.payload) {
445 args.push("options")
446 }
447 const params = args.join(", ")
448
449 const pipeline: Array<string> = []
450
451 pipeline.push(...paramsToPipeline(operation))
452
453 if (operation.payloadFormData) {
454 pipeline.push(`HttpClientRequest.bodyFormDataRecord(options.payload as any)`)
455 } else if (operation.payloadFormUrlEncoded) {
456 pipeline.push(`HttpClientRequest.bodyUrlParams(options.payload as any)`)
457 } else if (operation.payload) {
458 pipeline.push(`HttpClientRequest.bodyJsonUnsafe(options.payload)`)
459 }
460
461 pipeline.push(`binaryRequest`)
462
463 return (
464 `${JSON.stringify(`${operation.id}Stream`)}: (${params}) => ` +
465 requestToImpl(operation, pipeline, true)
466 )
467 }
468
469 return OpenApiTransformer.of({
470 imports: (importName, parsed) => {
471 const operations = parsed.operations
472 const requirements = computeImportRequirements(operations)
473 const imports = [
474 `import * as Data from "effect/Data"`,
475 `import * as Effect from "effect/Effect"`,
476 `import type { SchemaError } from "effect/Schema"`,
477 `import * as ${importName} from "effect/Schema"`
478 ]
479 if (requiresStreaming(requirements)) {
480 imports.push(`import * as Stream from "effect/Stream"`)
481 }
482 if (requirements.eventStream) {
483 imports.push(`import * as Sse from "effect/encoding/Sse"`)
484 }
485 // HttpClient needs to be a value import when streaming is used (for filterStatusOk)
486 if (requiresStreaming(requirements)) {
487 imports.push(`import * as HttpClient from "effect/http/HttpClient"`)
488 } else {
489 imports.push(`import type * as HttpClient from "effect/http/HttpClient"`)
490 }
491 imports.push(
492 `import * as HttpClientError from "effect/http/HttpClientError"`,
493 `import * as HttpClientRequest from "effect/http/HttpClientRequest"`,
494 `import * as HttpClientResponse from "effect/http/HttpClientResponse"`
495 )
496 return imports.join("\n")
497 },
498 toTypes: (importName, name, parsed) => operationsToInterface(importName, name, parsed.operations),
499 toImplementation: (importName, name, parsed) => operationsToImpl(importName, name, parsed.operations)
500 })
501}
502
503/**
504 * Layer that provides the schema-backed OpenApiTransformer service.
505 *
506 * **When to use**
507 *
508 * Use when you use this layer when generated HttpClient code should perform runtime response
509 * decoding with generated Effect Schema values.
510 *
511 * @category layers
512 * @since 4.0.0
513 */
514export const layerTransformerSchema = Layer.sync(
515 OpenApiTransformer,
516 makeTransformerSchema
517)
518
519/**
520 * Create the transformer used for type-only HttpClient output.
521 *
522 * **Details**
523 *
524 * Generated clients reference emitted TypeScript types directly and do not
525 * import schema decoders for JSON response bodies. Responses are typed as the
526 * declared operation result while preserving generated error and stream method
527 * shapes.
528 *
529 * @category code generation
530 * @since 4.0.0
531 */
532export const makeTransformerTs = () => {
533 const operationsToInterface = (
534 _importName: string,
535 name: string,
536 operations: ReadonlyArray<ParsedOperation>
537 ) => {
538 const methods: Array<string> = []
539 for (const op of operations) {
540 methods.push(operationToMethod(name, op))
541 if (op.httpClientResponses.sseSchema) {
542 methods.push(operationToSseMethod(op))
543 }
544 if (op.httpClientResponses.binarySuccessStatuses.size > 0) {
545 methods.push(operationToBinaryMethod(op))
546 }
547 }
548 return `export interface ${name}<E = HttpClientError.HttpClientError, R = never> {
549 readonly httpClient: HttpClient.HttpClient.With<E, R>
550 ${methods.join("\n ")}
551}
552
553${clientErrorSource(name)}`
554 }
555
556 const operationToMethod = (name: string, operation: ParsedOperation) => {
557 const responses = operation.httpClientResponses
558 const args: Array<string> = []
559 if (operation.pathIds.length > 0) {
560 Utils.spreadElementsInto(operation.pathIds.map((id) => `${id}: string`), args)
561 }
562
563 const options: Array<string> = []
564 if (operation.params) {
565 const key = `readonly params${operation.paramsOptional ? "?" : ""}`
566 const type = `${operation.params}${operation.paramsOptional ? " | undefined" : ""}`
567 options.push(`${key}: ${type}`)
568 }
569 if (operation.payload) {
570 options.push(`readonly payload: ${operation.payload}`)
571 }
572 const hasOptions = (operation.params && !operation.paramsOptional) || operation.payload
573
574 const successTypes = new Set(responses.successSchemas.values())
575 if (responses.binarySuccessStatuses.size > 0) {
576 successTypes.add("Uint8Array")
577 }
578 if (responses.voidSuccessStatuses.size > 0) {
579 successTypes.add("void")
580 }
581 const success = successTypes.size > 0 ? Array.from(successTypes).join(" | ") : "void"
582
583 const errors = ["E", "HttpClientError.HttpClientError"]
584 if (responses.errorSchemas.size > 0) {
585 for (const schema of responses.errorSchemas.values()) {
586 errors.push(`${name}Error<"${schema}", ${schema}>`)
587 }
588 }
589 for (const status of responses.voidErrorStatuses) {
590 errors.push(`${name}Error<"${status}", undefined>`)
591 }
592
593 const jsdoc = Utils.toComment(operation.description)
594 const methodKey = `readonly ${JSON.stringify(operation.id)}`
595 return `${jsdoc}${methodKey}: ${operationSignatures(args, options, Boolean(hasOptions), success, errors)}`
596 }
597
598 const operationToSseMethod = (operation: ParsedOperation) => {
599 const responses = operation.httpClientResponses
600 const args: Array<string> = []
601 if (operation.pathIds.length > 0) {
602 Utils.spreadElementsInto(operation.pathIds.map((id) => `${id}: string`), args)
603 }
604
605 const options: Array<string> = []
606 if (operation.params) {
607 const key = `readonly params${operation.paramsOptional ? "?" : ""}`
608 const type = `${operation.params}${operation.paramsOptional ? " | undefined" : ""}`
609 options.push(`${key}: ${type}`)
610 }
611 if (operation.payload) {
612 options.push(`readonly payload: ${operation.payload}`)
613 }
614
615 const hasOptions = (operation.params && !operation.paramsOptional) || operation.payload
616 if (hasOptions) {
617 args.push(`options: { ${options.join("; ")} }`)
618 } else if (options.length > 0) {
619 args.push(`options: { ${options.join("; ")} } | undefined`)
620 }
621
622 const jsdoc = Utils.toComment(operation.description)
623 const methodKey = `readonly ${JSON.stringify(`${operation.id}Sse`)}`
624 const parameters = args.join(", ")
625 const returnType = `Stream.Stream<${responses.sseSchema}, E | HttpClientError.HttpClientError, R>`
626 return `${jsdoc}${methodKey}: (${parameters}) => ${returnType}`
627 }
628
629 const operationToBinaryMethod = (operation: ParsedOperation) => {
630 const args: Array<string> = []
631 if (operation.pathIds.length > 0) {
632 Utils.spreadElementsInto(operation.pathIds.map((id) => `${id}: string`), args)
633 }
634
635 const options: Array<string> = []
636 if (operation.params) {
637 const key = `readonly params${operation.paramsOptional ? "?" : ""}`
638 const type = `${operation.params}${operation.paramsOptional ? " | undefined" : ""}`
639 options.push(`${key}: ${type}`)
640 }
641 if (operation.payload) {
642 options.push(`readonly payload: ${operation.payload}`)
643 }
644
645 const hasOptions = (operation.params && !operation.paramsOptional) || operation.payload
646 if (hasOptions) {
647 args.push(`options: { ${options.join("; ")} }`)
648 } else if (options.length > 0) {
649 args.push(`options: { ${options.join("; ")} } | undefined`)
650 }
651
652 const jsdoc = Utils.toComment(operation.description)
653 const methodKey = `readonly ${JSON.stringify(`${operation.id}Stream`)}`
654 const parameters = args.join(", ")
655 const returnType = `Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`
656 return `${jsdoc}${methodKey}: (${parameters}) => ${returnType}`
657 }
658
659 const operationsToImpl = (
660 _importName: string,
661 name: string,
662 operations: ReadonlyArray<ParsedOperation>
663 ) => {
664 const requirements = computeImportRequirements(operations)
665 const implMethods: Array<string> = []
666 for (const op of operations) {
667 implMethods.push(operationToImpl(name, op))
668 if (op.httpClientResponses.sseSchema) {
669 implMethods.push(operationToSseImpl(op))
670 }
671 if (op.httpClientResponses.binarySuccessStatuses.size > 0) {
672 implMethods.push(operationToBinaryImpl(op))
673 }
674 }
675
676 const helpers: Array<string> = [commonSource]
677 if (operations.some((operation) => operation.commaUrlParams.length > 0)) {
678 helpers.push(commaUrlParamsSource)
679 }
680 if (operations.some((operation) => operation.pathIds.length > 0)) {
681 helpers.push(pathRequestSource)
682 }
683 if (operations.some((operation) => operation.cookies.length > 0)) {
684 helpers.push(cookieHeaderSource)
685 }
686 if (requiresStreaming(requirements)) {
687 helpers.push(executeStreamRequestSource)
688 }
689 if (requirements.eventStream) {
690 helpers.push(sseRequestSourceTs)
691 }
692 const withResponseVariants = operations.some((op) => hasResponseVariants(op.httpClientResponses))
693 if (withResponseVariants) {
694 helpers.push(decodeBinarySource)
695 helpers.push(decodeVoidErrorSource(name))
696 }
697 if (requirements.octetStream) {
698 helpers.push(binaryRequestSourceTs)
699 }
700
701 return `export interface OperationConfig {
702 /**
703 * Whether or not the response should be included in the value returned from
704 * an operation.
705 *
706 * If set to \`true\`, a tuple of \`[A, HttpClientResponse]\` will be returned,
707 * where \`A\` is the success type of the operation.
708 *
709 * If set to \`false\`, only the success type of the operation will be returned.
710 */
711 readonly includeResponse?: boolean | undefined
712}
713
714/**
715 * A utility type which optionally includes the response in the return result
716 * of an operation based upon the value of the \`includeResponse\` configuration
717 * option.
718 */
719export type WithOptionalResponse<A, Config extends OperationConfig | undefined> = Config extends {
720 readonly includeResponse: true
721} ? [A, HttpClientResponse.HttpClientResponse]
722 : Config extends { readonly includeResponse?: false | undefined } | undefined ? A
723 : A | [A, HttpClientResponse.HttpClientResponse]
724
725export const make = <E, R>(
726 httpClient: HttpClient.HttpClient.With<E, R>,
727 options: {
728 readonly transformClient?: ((client: HttpClient.HttpClient.With<E, R>) => Effect.Effect<HttpClient.HttpClient.With<E, R>>) | undefined
729 } = {}
730): ${name}<E, R> => {
731 ${helpers.join("\n ")}
732 const decodeSuccess = <A>(response: HttpClientResponse.HttpClientResponse) =>
733 response.json as Effect.Effect<A, HttpClientError.HttpClientError>
734 const decodeVoid = (_response: HttpClientResponse.HttpClientResponse) =>
735 Effect.void
736 const decodeError =
737 <Tag extends string, E>(tag: Tag) =>
738 (
739 response: HttpClientResponse.HttpClientResponse,
740 ): Effect.Effect<
741 never,
742 ${name}Error<Tag, E> | HttpClientError.HttpClientError
743 > =>
744 Effect.flatMap(
745 response.json as Effect.Effect<E, HttpClientError.HttpClientError>,
746 (cause) => Effect.fail(${name}Error(tag, cause, response)),
747 )
748 ${onRequestSource(withResponseVariants)}
749 return {
750 httpClient,
751 ${implMethods.join(",\n ")}
752 }
753}`
754 }
755
756 const operationToImpl = (name: string, operation: ParsedOperation) => {
757 const responses = operation.httpClientResponses
758 const params = [
759 ...operation.pathIds,
760 `options: Parameters<${name}[${JSON.stringify(operation.id)}]>[${operation.pathIds.length}]`
761 ].join(", ")
762
763 const pipeline: Array<string> = []
764
765 pipeline.push(...paramsToPipeline(operation))
766
767 const payloadAccessor = "options.payload"
768 if (operation.payloadFormData) {
769 pipeline.push(`HttpClientRequest.bodyFormDataRecord(${payloadAccessor} as any)`)
770 } else if (operation.payloadFormUrlEncoded) {
771 pipeline.push(`HttpClientRequest.bodyUrlParams(${payloadAccessor} as any)`)
772 } else if (operation.payload) {
773 pipeline.push(`HttpClientRequest.bodyJsonUnsafe(${payloadAccessor})`)
774 }
775
776 const successCodes = Array.from(
777 responses.successSchemas.keys(),
778 (status) => JSON.stringify(normalizeSuccessStatus(responses, status))
779 ).join(", ")
780 const errorCodes = responses.errorSchemas.size > 0 &&
781 Object.fromEntries(responses.errorSchemas.entries())
782 const configAccessor = resolveConfigAccessor(operation, "options", "config")
783 const requestArgs = [`[${successCodes}]`]
784 if (hasResponseVariants(responses)) {
785 const responseCodes = {
786 binary: Array.from(
787 responses.binarySuccessStatuses,
788 (status) => normalizeSuccessStatus(responses, status)
789 ),
790 voidSuccess: Array.from(responses.voidSuccessStatuses),
791 voidError: Array.from(responses.voidErrorStatuses)
792 }
793 requestArgs.push(errorCodes ? JSON.stringify(errorCodes) : "undefined", JSON.stringify(responseCodes))
794 } else if (errorCodes) {
795 requestArgs.push(JSON.stringify(errorCodes))
796 }
797 pipeline.push(`onRequest(${configAccessor})(${requestArgs.join(", ")})`)
798
799 return (
800 `${JSON.stringify(operation.id)}: (${params}) => ` +
801 requestToImpl(operation, pipeline)
802 )
803 }
804
805 const operationToSseImpl = (operation: ParsedOperation) => {
806 const args: Array<string> = [...operation.pathIds]
807 const hasOptions = (operation.params && !operation.paramsOptional) || operation.payload
808 if (hasOptions || operation.params || operation.payload) {
809 args.push("options")
810 }
811 const params = args.join(", ")
812
813 const pipeline: Array<string> = []
814
815 pipeline.push(...paramsToPipeline(operation))
816
817 if (operation.payloadFormData) {
818 pipeline.push(`HttpClientRequest.bodyFormDataRecord(options.payload as any)`)
819 } else if (operation.payloadFormUrlEncoded) {
820 pipeline.push(`HttpClientRequest.bodyUrlParams(options.payload as any)`)
821 } else if (operation.payload) {
822 pipeline.push(`HttpClientRequest.bodyJsonUnsafe(options.payload)`)
823 }
824
825 pipeline.push(`sseRequest`)
826
827 return (
828 `${JSON.stringify(`${operation.id}Sse`)}: (${params}) => ` +
829 requestToImpl(operation, pipeline, true)
830 )
831 }
832
833 const operationToBinaryImpl = (operation: ParsedOperation) => {
834 const args: Array<string> = [...operation.pathIds]
835 const hasOptions = (operation.params && !operation.paramsOptional) || operation.payload
836 if (hasOptions || operation.params || operation.payload) {
837 args.push("options")
838 }
839 const params = args.join(", ")
840
841 const pipeline: Array<string> = []
842
843 pipeline.push(...paramsToPipeline(operation))
844
845 if (operation.payloadFormData) {
846 pipeline.push(`HttpClientRequest.bodyFormDataRecord(options.payload as any)`)
847 } else if (operation.payloadFormUrlEncoded) {
848 pipeline.push(`HttpClientRequest.bodyUrlParams(options.payload as any)`)
849 } else if (operation.payload) {
850 pipeline.push(`HttpClientRequest.bodyJsonUnsafe(options.payload)`)
851 }
852
853 pipeline.push(`binaryRequest`)
854
855 return (
856 `${JSON.stringify(`${operation.id}Stream`)}: (${params}) => ` +
857 requestToImpl(operation, pipeline, true)
858 )
859 }
860
861 return OpenApiTransformer.of({
862 imports: (_importName, parsed) => {
863 const operations = parsed.operations
864 const requirements = computeImportRequirements(operations)
865 const imports = [
866 `import * as Data from "effect/Data"`,
867 `import * as Effect from "effect/Effect"`
868 ]
869 if (requiresStreaming(requirements)) {
870 imports.push(
871 `import * as Stream from "effect/Stream"`,
872 `import * as HttpClient from "effect/http/HttpClient"`
873 )
874 } else {
875 imports.push(`import type * as HttpClient from "effect/http/HttpClient"`)
876 }
877 imports.push(
878 `import * as HttpClientError from "effect/http/HttpClientError"`,
879 `import * as HttpClientRequest from "effect/http/HttpClientRequest"`,
880 `import * as HttpClientResponse from "effect/http/HttpClientResponse"`
881 )
882 return imports.join("\n")
883 },
884 toTypes: (importName, name, parsed) => operationsToInterface(importName, name, parsed.operations),
885 toImplementation: (importName, name, parsed) => operationsToImpl(importName, name, parsed.operations)
886 })
887}
888
889/**
890 * Layer that provides the type-only OpenApiTransformer service.
891 *
892 * **When to use**
893 *
894 * Use when you use this layer for the `httpclient-type-only` generator format, where the
895 * generated client relies on TypeScript types instead of runtime Schema
896 * decoding.
897 *
898 * @category layers
899 * @since 4.0.0
900 */
901export const layerTransformerTs = Layer.sync(
902 OpenApiTransformer,
903 makeTransformerTs
904)
905
906const pathRequestSource = `const __encodePathParam = encodeURIComponent
907 const __makePathRequest = (
908 method: (url: string) => HttpClientRequest.HttpClientRequest,
909 parameters: ReadonlyArray<string>,
910 getPath: () => string,
911 ) => Effect.suspend(() => {
912 const fail = (description: string, cause?: unknown) => Effect.fail(
913 new HttpClientError.HttpClientError({
914 reason: new HttpClientError.InvalidUrlError({
915 request: method(""),
916 cause,
917 description,
918 }),
919 }),
920 )
921 if (parameters.some((value) => value === "" || /^(?:\\.|%2e){1,2}$/i.test(value))) {
922 return fail("Path parameters must be non-empty and cannot be dot segments")
923 }
924 let path: string
925 try {
926 path = getPath()
927 } catch (cause) {
928 return fail("Failed to encode path parameter", cause)
929 }
930 if (path.split("/").some((segment) => /^(?:\\.|%2e){1,2}$/i.test(segment))) {
931 return fail("Request paths cannot contain dot segments")
932 }
933 return Effect.succeed(method(path))
934 })`
935
936const commaUrlParamsSource =
937 `const __joinComma = (value: unknown) => Array.isArray(value) && value.length > 0 ? value.join(",") : value`
938
939const cookieHeaderSource = `const __cookieHeader = (cookies: Record<string, unknown>) => {
940 const header = Object.entries(cookies)
941 .filter(([, value]) => value !== undefined && value !== null)
942 .map(([name, value]) => \`\${name}=\${encodeURIComponent(String(value))}\`)
943 .join("; ")
944 return header === "" ? undefined : header
945 }`
946
947const commonSource = `const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) =>
948 Effect.flatMap(
949 Effect.orElseSucceed(response.json, () => "Unexpected status code"),
950 (description) =>
951 Effect.fail(
952 new HttpClientError.HttpClientError({
953 reason: new HttpClientError.StatusCodeError({
954 request: response.request,
955 response,
956 description: typeof description === "string" ? description : JSON.stringify(description),
957 }),
958 }),
959 ),
960 )
961 const withResponse = <Config extends OperationConfig>(config: Config | undefined) => (
962 f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<any, any>,
963 ): (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<any, any, R> => {
964 const withOptionalResponse = (
965 config?.includeResponse
966 ? (response: HttpClientResponse.HttpClientResponse) => Effect.map(f(response), (a) => [a, response])
967 : (response: HttpClientResponse.HttpClientResponse) => f(response)
968 ) as any
969 return options?.transformClient
970 ? (request) =>
971 Effect.flatMap(
972 Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)),
973 withOptionalResponse
974 )
975 : (request) => Effect.flatMap(httpClient.execute(request), withOptionalResponse)
976 }`
977
978const decodeBinarySource = `const decodeBinary = (response: HttpClientResponse.HttpClientResponse) =>
979 Effect.map(response.arrayBuffer, (buffer) => new Uint8Array(buffer))`
980
981const decodeSuccessSource = (importName: string) =>
982 `const decodeSuccess =
983 <Schema extends ${importName}.Constraint>(schema: Schema) =>
984 (response: HttpClientResponse.HttpClientResponse) =>
985 HttpClientResponse.schemaBodyJson(schema)(response)`
986
987const decodeErrorSource = (importName: string, name: string) =>
988 `const decodeError =
989 <const Tag extends string, Schema extends ${importName}.Constraint>(tag: Tag, schema: Schema) =>
990 (response: HttpClientResponse.HttpClientResponse) =>
991 Effect.flatMap(
992 HttpClientResponse.schemaBodyJson(schema)(response),
993 (cause) => Effect.fail(${name}Error(tag, cause, response)),
994 )`
995
996const decodeVoidErrorSource = (name: string) =>
997 `const decodeVoidError = <const Tag extends string>(tag: Tag) =>
998 (response: HttpClientResponse.HttpClientResponse) =>
999 Effect.fail(${name}Error(tag, undefined, response))`
1000
1001const onRequestSource = (withResponseVariants: boolean) => {
1002 const responseCodesParam = withResponseVariants
1003 ? `
1004 responseCodes: {
1005 readonly binary: ReadonlyArray<string>
1006 readonly voidSuccess: ReadonlyArray<string>
1007 readonly voidError: ReadonlyArray<string>
1008 } = { binary: [], voidSuccess: [], voidError: [] },`
1009 : ""
1010 const responseCodesCases = withResponseVariants
1011 ? `
1012 for (const code of responseCodes.binary) {
1013 cases[code] = decodeBinary
1014 }
1015 for (const code of responseCodes.voidSuccess) {
1016 cases[code] = decodeVoid
1017 }
1018 for (const code of responseCodes.voidError) {
1019 cases[code] = decodeVoidError(code)
1020 }`
1021 : ""
1022 const voidFallbackCondition = withResponseVariants
1023 ? "successCodes.length === 0 && responseCodes.binary.length === 0 && responseCodes.voidSuccess.length === 0"
1024 : "successCodes.length === 0"
1025 return `const onRequest = <Config extends OperationConfig>(config: Config | undefined) => (
1026 successCodes: ReadonlyArray<string>,
1027 errorCodes?: Record<string, string>,${responseCodesParam}
1028 ) => {
1029 const cases: any = { orElse: unexpectedStatus }
1030 for (const code of successCodes) {
1031 cases[code] = decodeSuccess
1032 }
1033 if (errorCodes) {
1034 for (const [code, tag] of Object.entries(errorCodes)) {
1035 cases[code] = decodeError(tag)
1036 }
1037 }${responseCodesCases}
1038 if (${voidFallbackCondition}) {
1039 cases["2xx"] = decodeVoid
1040 }
1041 return withResponse(config)(HttpClientResponse.matchStatus(cases) as any)
1042 }`
1043}
1044
1045const executeStreamRequestSource = `const executeStreamRequest = (request: HttpClientRequest.HttpClientRequest) =>
1046 Effect.suspend(() =>
1047 options.transformClient
1048 ? Effect.flatMap(options.transformClient(httpClient), (client) => HttpClient.filterStatusOk(client).execute(request))
1049 : HttpClient.filterStatusOk(httpClient).execute(request)
1050 )`
1051
1052const sseRequestSource = (_importName: string) =>
1053 `const sseRequest = <
1054 Type,
1055 DecodingServices
1056 >(
1057 schema: Schema.ConstraintDecoder<Type, DecodingServices>
1058 ) =>
1059 (
1060 request: HttpClientRequest.HttpClientRequest
1061 ): Stream.Stream<
1062 { readonly event: string; readonly id: string | undefined; readonly data: Type },
1063 E | HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError,
1064 R | DecodingServices
1065 > =>
1066 executeStreamRequest(request).pipe(
1067 Effect.map((response) => response.stream),
1068 Stream.unwrap,
1069 Stream.decodeText(),
1070 Stream.pipeThroughChannel(Sse.decodeDataSchema(schema))
1071 )`
1072
1073const sseEventRequestSource = `const sseEventRequest = <S extends Sse.EventCodec>(schema: S) =>
1074 (
1075 request: HttpClientRequest.HttpClientRequest
1076 ): Stream.Stream<
1077 S["Type"],
1078 E | HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError,
1079 R | S["DecodingServices"]
1080 > =>
1081 executeStreamRequest(request).pipe(
1082 Effect.map((response) => response.stream),
1083 Stream.unwrap,
1084 Stream.decodeText(),
1085 Stream.pipeThroughChannel(Sse.decodeSchema(schema))
1086 )`
1087
1088const binaryRequestSource =
1089 `const binaryRequest = (request: HttpClientRequest.HttpClientRequest): Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R> =>
1090 executeStreamRequest(request).pipe(
1091 Effect.map((response) => response.stream),
1092 Stream.unwrap
1093 )`
1094
1095// Type-only mode helpers (no schema decoding)
1096const sseRequestSourceTs =
1097 `const sseRequest = (request: HttpClientRequest.HttpClientRequest): Stream.Stream<unknown, E | HttpClientError.HttpClientError, R> =>
1098 executeStreamRequest(request).pipe(
1099 Effect.map((response) => response.stream),
1100 Stream.unwrap,
1101 Stream.decodeText(),
1102 Stream.splitLines,
1103 Stream.filter((line) => line.startsWith("data: ")),
1104 Stream.map((line) => JSON.parse(line.slice(6)))
1105 )`
1106
1107const binaryRequestSourceTs =
1108 `const binaryRequest = (request: HttpClientRequest.HttpClientRequest): Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R> =>
1109 executeStreamRequest(request).pipe(
1110 Effect.map((response) => response.stream),
1111 Stream.unwrap
1112 )`
1113
1114const clientErrorSource = (
1115 name: string
1116) =>
1117 `export interface ${name}Error<Tag extends string, E> {
1118 readonly _tag: Tag
1119 readonly request: HttpClientRequest.HttpClientRequest
1120 readonly response: HttpClientResponse.HttpClientResponse
1121 readonly cause: E
1122}
1123
1124class ${name}ErrorImpl extends Data.Error<{
1125 _tag: string
1126 cause: any
1127 request: HttpClientRequest.HttpClientRequest
1128 response: HttpClientResponse.HttpClientResponse
1129}> {}
1130
1131export const ${name}Error = <Tag extends string, E>(
1132 tag: Tag,
1133 cause: E,
1134 response: HttpClientResponse.HttpClientResponse,
1135): ${name}Error<Tag, E> =>
1136 new ${name}ErrorImpl({
1137 _tag: tag,
1138 cause,
1139 response,
1140 request: response.request,
1141 }) as any`
1142
1143const operationSignatures = (
1144 args: ReadonlyArray<string>,
1145 options: ReadonlyArray<string>,
1146 optionsRequired: boolean,
1147 success: string,
1148 errors: ReadonlyArray<string>
1149): string => {
1150 const signature = (configOptional: boolean) => {
1151 const config = configOptional ? "Config | undefined" : "Config"
1152 const fields = [...options, `readonly config${configOptional ? "?" : ""}: ${config}`].join("; ")
1153 const parameters = [...args, `options: { ${fields} }${configOptional && !optionsRequired ? " | undefined" : ""}`]
1154 return ` <Config extends OperationConfig | undefined = undefined>(${
1155 parameters.join(", ")
1156 }): Effect.Effect<WithOptionalResponse<${success}, ${config}>, ${errors.join(" | ")}, R>;`
1157 }
1158 // Infer the whole config from a required property before allowing omitted config.
1159 // An optional property would otherwise discard undefined during inference.
1160 return `{
1161${signature(false)}
1162${signature(true)}
1163 }`
1164}
1165
1166const resolveConfigAccessor = (operation: ParsedOperation, rootKey: string, configKey: string): string => {
1167 // If an operation payload is defined, then the root object must exist
1168 if (Predicate.isNotUndefined(operation.payload)) {
1169 return `${rootKey}.${configKey}`
1170 }
1171
1172 // If operation parameters are defined and non-optional, then the root object must exist
1173 if (Predicate.isNotUndefined(operation.params) && !operation.paramsOptional) {
1174 return `${rootKey}.${configKey}`
1175 }
1176
1177 // User-specified arguments are allowed but are not required, so the root object is optional
1178 return `${rootKey}?.${configKey}`
1179}
1180
1181const resolveParamsAccessor = (operation: ParsedOperation, rootKey: string, paramsKey: string): string => {
1182 // If an operation payload is not defined and parameters are optional, then the
1183 // root object may or may not exist and parameters must be marked as optional
1184 if (Predicate.isUndefined(operation.payload) && operation.paramsOptional) {
1185 return `${rootKey}?.${paramsKey}?.`
1186 }
1187
1188 // If parameters are optional, they must be marked as optional
1189 if (operation.paramsOptional) {
1190 return `${rootKey}.${paramsKey}?.`
1191 }
1192
1193 return `${rootKey}.${paramsKey}`
1194}