sailfork / t3code-github / .repos/ effect/ packages/ tools/ openapi-generator/ test/ OpenApiGenerator.test.ts

import * as OpenApiGenerator from "@effect/openapi-generator/OpenApiGenerator"
import { assert, describe, it } from "@effect/vitest"
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/http-api"
import type { OpenAPISpec, OpenAPISpecOperation, OpenAPISpecPathItem } from "effect/http-api/OpenApi"
import * as HttpClient from "effect/http/HttpClient"
import * as HttpClientRequest from "effect/http/HttpClientRequest"
import * as HttpClientResponse from "effect/http/HttpClientResponse"
import type * as JsonSchema from "effect/JsonSchema"
import * as Schema from "effect/Schema"
import { spawn } from "node:child_process"
import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { dirname, join } from "node:path"
import { fileURLToPath } from "node:url"

// The first compile check starts the shared TypeScript compiler runs under CI load.
const compilationTimeout = 60_000

const assertRuntime = Effect.fnUntraced(function*(spec: OpenAPISpec, expected: string) {
  const generator = yield* OpenApiGenerator.OpenApiGenerator

  const result = yield* generator.generate(spec, {
    name: "TestClient",
    format: "httpclient"
  })

  // console.log(result)
  assert.strictEqual(result, expected)
}, Effect.provide(OpenApiGenerator.layerTransformerSchema))

const assertTypeOnly = Effect.fnUntraced(function*(spec: OpenAPISpec, expected: string) {
  const generator = yield* OpenApiGenerator.OpenApiGenerator

  const result = yield* generator.generate(spec, {
    name: "TestClient",
    format: "httpclient-type-only"
  })

  // console.log(result)
  assert.strictEqual(result, expected)
}, Effect.provide(OpenApiGenerator.layerTransformerTs))

const assertRuntimeIncludes = Effect.fnUntraced(function*(
  spec: OpenAPISpec,
  includes: ReadonlyArray<string>,
  excludes: ReadonlyArray<string> = []
) {
  const generator = yield* OpenApiGenerator.OpenApiGenerator

  const result = yield* generator.generate(spec, {
    name: "TestClient",
    format: "httpclient"
  })

  for (const expected of includes) {
    assert.include(result, expected)
  }
  for (const excluded of excludes) {
    assert.notInclude(result, excluded)
  }
}, Effect.provide(OpenApiGenerator.layerTransformerSchema))

const assertTypeOnlyIncludes = Effect.fnUntraced(function*(
  spec: OpenAPISpec,
  includes: ReadonlyArray<string>,
  excludes: ReadonlyArray<string> = []
) {
  const generator = yield* OpenApiGenerator.OpenApiGenerator

  const result = yield* generator.generate(spec, {
    name: "TestClient",
    format: "httpclient-type-only"
  })

  for (const expected of includes) {
    assert.include(result, expected)
  }
  for (const excluded of excludes) {
    assert.notInclude(result, excluded)
  }
}, Effect.provide(OpenApiGenerator.layerTransformerTs))

interface CompileOptions {
  readonly exactOptionalPropertyTypes?: boolean | undefined
  readonly formats?: ReadonlyArray<"httpclient" | "httpclient-type-only"> | undefined
  readonly usage?: string | undefined
}

const repositoryRoot = join(dirname(fileURLToPath(import.meta.url)), "../../../..")

// Every case is registered while the file is collected, so a single compiler
// run per tsconfig variant can check all generated clients.
const compileCases: Array<{ readonly spec: OpenAPISpec; readonly options: CompileOptions }> = []

const generateClients = ({ options, spec }: (typeof compileCases)[number]) => {
  const generate = (
    format: "httpclient" | "httpclient-type-only",
    layer: typeof OpenApiGenerator.layerTransformerSchema
  ) =>
    Effect.gen(function*() {
      const generator = yield* OpenApiGenerator.OpenApiGenerator
      return yield* generator.generate(spec, { name: "TestClient", format })
    }).pipe(Effect.provide(layer))

  const formats = options.formats ?? ["httpclient", "httpclient-type-only"]
  return Effect.all(formats.map((format) =>
    generate(
      format,
      format === "httpclient"
        ? OpenApiGenerator.layerTransformerSchema
        : OpenApiGenerator.layerTransformerTs
    ).pipe(Effect.map((client) => `${client}\n${options.usage ?? ""}`))
  ))
}

const runTsc = (configPath: string) =>
  Effect.callback<{ readonly status: number | null; readonly output: string }>((resume) => {
    const child = spawn(join(repositoryRoot, "node_modules/.bin/tsc"), ["-p", configPath, "--pretty", "false"], {
      cwd: repositoryRoot
    })
    let output = ""
    child.stdout.on("data", (chunk) => output += chunk)
    child.stderr.on("data", (chunk) => output += chunk)
    child.on("error", (error) => resume(Effect.die(error)))
    child.on("close", (status) => resume(Effect.succeed({ status, output })))
    return Effect.sync(() => child.kill())
  })

// Each diagnostic starts on an unindented line; indented lines continue the
// previous diagnostic.
const parseDiagnostics = (output: string) => {
  const diagnostics: Array<string> = []
  for (const line of output.split(/\r?\n/)) {
    if (line === "") continue
    if (/^\s/.test(line) && diagnostics.length > 0) {
      diagnostics[diagnostics.length - 1] += `\n${line}`
      continue
    }
    diagnostics.push(line)
  }
  return diagnostics
}

// Type-checks every case with one compiler run per tsconfig variant and
// returns the diagnostics that fail each case. A syntax error in one file makes
// tsc skip semantic checks for the whole program, so a failed run cannot show
// which cases are clean; each of its cases is then checked on its own.
const typeCheckCases = Effect.fnUntraced(
  function*(
    cases: ReadonlyArray<{ readonly sources: ReadonlyArray<string>; readonly exactOptionalPropertyTypes: boolean }>
  ) {
    const directory = mkdtempSync(join(dirname(fileURLToPath(import.meta.url)), ".generated-clients-"))
    return yield* Effect.gen(function*() {
      const files = cases.map(({ sources }, caseIndex) =>
        sources.map((source, sourceIndex) => {
          const path = join(directory, `Case${caseIndex}Client${sourceIndex}.ts`)
          writeFileSync(path, source)
          return path
        })
      )
      // Returns every diagnostic of one compiler run, or an empty list when it succeeds.
      const check = (name: string, exactOptionalPropertyTypes: boolean, caseIndexes: ReadonlyArray<number>) => {
        const configPath = join(directory, `tsconfig.${name}.json`)
        writeFileSync(
          configPath,
          JSON.stringify({
            compilerOptions: {
              allowImportingTsExtensions: true,
              exactOptionalPropertyTypes,
              lib: ["ESNext", "DOM"],
              module: "NodeNext",
              noEmit: true,
              skipLibCheck: true,
              strict: true,
              target: "ES2022",
              types: [],
              verbatimModuleSyntax: true
            },
            files: caseIndexes.flatMap((caseIndex) => files[caseIndex])
          })
        )
        return runTsc(configPath).pipe(Effect.map(({ output, status }) => {
          if (status === 0) return []
          const diagnostics = parseDiagnostics(output)
          return diagnostics.length === 0 ? [`tsc exited with ${status}`] : diagnostics
        }))
      }
      const failures: Array<ReadonlyArray<string>> = cases.map(() => [])
      const variants = [true, false].map((exactOptionalPropertyTypes) => ({
        exactOptionalPropertyTypes,
        caseIndexes: cases.flatMap((testCase, caseIndex) =>
          testCase.exactOptionalPropertyTypes === exactOptionalPropertyTypes ? [caseIndex] : []
        )
      })).filter(({ caseIndexes }) => caseIndexes.length > 0)
      yield* Effect.forEach(variants, ({ caseIndexes, exactOptionalPropertyTypes }) =>
        Effect.gen(function*() {
          const batch = yield* check(String(exactOptionalPropertyTypes), exactOptionalPropertyTypes, caseIndexes)
          if (batch.length === 0) return
          const isolated = yield* Effect.forEach(
            caseIndexes,
            (caseIndex) => check(`case${caseIndex}`, exactOptionalPropertyTypes, [caseIndex]),
            { concurrency: 4 }
          )
          // If every case compiles alone, the failure comes from combining them, so it fails every case.
          const combined = isolated.every((diagnostics) => diagnostics.length === 0)
          caseIndexes.forEach((caseIndex, i) => {
            failures[caseIndex] = combined ? batch : isolated[i]
          })
        }), { concurrency: "unbounded", discard: true })
      return failures
    }).pipe(Effect.ensuring(Effect.sync(() => rmSync(directory, { recursive: true, force: true }))))
  }
)

const compileAll = Effect.gen(function*() {
  const generated = yield* Effect.forEach(compileCases, (testCase) => Effect.exit(generateClients(testCase)))
  const failures = yield* typeCheckCases(generated.map((exit, caseIndex) => ({
    sources: Exit.isSuccess(exit) ? exit.value : [],
    exactOptionalPropertyTypes: compileCases[caseIndex].options.exactOptionalPropertyTypes ?? true
  })))
  return { generated, failures }
})

const compiled = Effect.runSync(Effect.cached(compileAll))

const itGeneratedClientsCompile = (name: string, spec: OpenAPISpec, options: CompileOptions = {}) => {
  const caseIndex = compileCases.push({ spec, options }) - 1
  it.effect(name, () =>
    Effect.gen(function*() {
      const result = yield* compiled
      const generated = result.generated[caseIndex]
      if (Exit.isFailure(generated)) {
        return yield* Effect.failCause(generated.cause)
      }
      assert.strictEqual(result.failures[caseIndex].join("\n"), "")
    }), compilationTimeout)
}

const assertHttpApiIncludes = Effect.fnUntraced(function*(
  spec: OpenAPISpec,
  includes: ReadonlyArray<string>,
  excludes: ReadonlyArray<string> = []
) {
  const generator = yield* OpenApiGenerator.OpenApiGenerator

  const result = yield* generator.generate(spec, {
    name: "TestClient",
    format: "httpapi"
  })

  for (const expected of includes) {
    assert.include(result, expected)
  }
  for (const excluded of excludes) {
    assert.notInclude(result, excluded)
  }
}, Effect.provide(OpenApiGenerator.layerTransformerSchema))

const assertHttpApiWithWarnings = Effect.fnUntraced(function*(
  spec: OpenAPISpec,
  options: {
    readonly includes?: ReadonlyArray<string> | undefined
    readonly excludes?: ReadonlyArray<string> | undefined
    readonly occurrences?:
      | ReadonlyArray<{
        readonly substring: string
        readonly count: number
      }>
      | undefined
    readonly warnings: ReadonlyArray<
      Pick<OpenApiGenerator.OpenApiGeneratorWarning, "code" | "path" | "method" | "operationId">
    >
  }
) {
  const generator = yield* OpenApiGenerator.OpenApiGenerator
  const warnings: Array<OpenApiGenerator.OpenApiGeneratorWarning> = []

  const result = yield* generator.generate(spec, {
    name: "TestClient",
    format: "httpapi",
    onWarning: (warning) => {
      warnings.push(warning)
    }
  })

  for (const expected of options.includes ?? []) {
    assert.include(result, expected)
  }
  for (const excluded of options.excludes ?? []) {
    assert.notInclude(result, excluded)
  }
  for (const { substring, count } of options.occurrences ?? []) {
    assert.strictEqual(result.split(substring).length - 1, count)
  }

  assert.deepStrictEqual(
    warnings.map((warning) => ({
      code: warning.code,
      path: warning.path,
      method: warning.method,
      operationId: warning.operationId
    })),
    options.warnings
  )
}, Effect.provide(OpenApiGenerator.layerTransformerSchema))

const generateHttpApi = Effect.fnUntraced(function*(spec: OpenAPISpec) {
  const generator = yield* OpenApiGenerator.OpenApiGenerator
  const warnings: Array<OpenApiGenerator.OpenApiGeneratorWarning> = []

  const source = yield* generator.generate(spec, {
    name: "TestClient",
    format: "httpapi",
    onWarning: (warning) => {
      warnings.push(warning)
    }
  })

  return { source, warnings }
}, Effect.provide(OpenApiGenerator.layerTransformerSchema))

const findEndpoint = (source: string, method: string, path: string): string => {
  const line = source.split("\n").find((line) =>
    line.includes(`HttpApiEndpoint.${method}(`) && line.includes(`", ${JSON.stringify(path)}`)
  )
  assert.isDefined(line, `Expected ${method} ${path} in:\n${source}`)
  return line!
}

const assertRuntimeStableWithWarnings = Effect.fnUntraced(function*(
  spec: OpenAPISpec,
  expectedWarnings: ReadonlyArray<
    Pick<OpenApiGenerator.OpenApiGeneratorWarning, "code" | "path" | "method" | "operationId">
  >
) {
  const generator = yield* OpenApiGenerator.OpenApiGenerator
  const warnings: Array<OpenApiGenerator.OpenApiGeneratorWarning> = []

  const baseline = yield* generator.generate(spec, {
    name: "TestClient",
    format: "httpclient"
  })
  const withWarnings = yield* generator.generate(spec, {
    name: "TestClient",
    format: "httpclient",
    onWarning: (warning) => {
      warnings.push(warning)
    }
  })

  assert.strictEqual(withWarnings, baseline)
  assert.deepStrictEqual(
    warnings.map((warning) => ({
      code: warning.code,
      path: warning.path,
      method: warning.method,
      operationId: warning.operationId
    })),
    expectedWarnings
  )
}, Effect.provide(OpenApiGenerator.layerTransformerSchema))

const assertTypeOnlyStableWithWarnings = Effect.fnUntraced(function*(
  spec: OpenAPISpec,
  expectedWarnings: ReadonlyArray<
    Pick<OpenApiGenerator.OpenApiGeneratorWarning, "code" | "path" | "method" | "operationId">
  >
) {
  const generator = yield* OpenApiGenerator.OpenApiGenerator
  const warnings: Array<OpenApiGenerator.OpenApiGeneratorWarning> = []

  const baseline = yield* generator.generate(spec, {
    name: "TestClient",
    format: "httpclient-type-only"
  })
  const withWarnings = yield* generator.generate(spec, {
    name: "TestClient",
    format: "httpclient-type-only",
    onWarning: (warning) => {
      warnings.push(warning)
    }
  })

  assert.strictEqual(withWarnings, baseline)
  assert.deepStrictEqual(
    warnings.map((warning) => ({
      code: warning.code,
      path: warning.path,
      method: warning.method,
      operationId: warning.operationId
    })),
    expectedWarnings
  )
}, Effect.provide(OpenApiGenerator.layerTransformerTs))

const regressionSpec: OpenAPISpec = {
  openapi: "3.1.0",
  info: {
    title: "Regression API",
    version: "1.0.0"
  },
  paths: {
    "/users/{id}": {
      get: {
        operationId: "getUser",
        summary: "Get user",
        description: "Read a user",
        parameters: [
          {
            name: "id",
            in: "path",
            schema: {
              type: "string"
            },
            required: true
          },
          {
            name: "filter",
            in: "query",
            schema: {
              type: "string"
            },
            required: false
          },
          {
            name: "trace-id",
            in: "header",
            schema: {
              type: "string"
            },
            required: false
          },
          {
            name: "session",
            in: "cookie",
            schema: {
              type: "string"
            },
            required: false
          }
        ],
        responses: {
          default: {
            description: "Default user response",
            content: {
              "application/json": {
                schema: {
                  type: "object",
                  properties: {
                    id: {
                      type: "string"
                    }
                  },
                  required: ["id"],
                  additionalProperties: false
                }
              }
            }
          }
        } as any,
        tags: ["Users"],
        security: [{ apiKey: [] }]
      }
    }
  },
  components: {
    schemas: {},
    securitySchemes: {
      apiKey: {
        type: "apiKey",
        name: "x-api-key",
        in: "header"
      }
    }
  },
  security: [],
  tags: [{ name: "Users" }]
}

const responseMatchingSpec: OpenAPISpec = {
  openapi: "3.1.0",
  info: {
    title: "Response matching API",
    version: "1.0.0"
  },
  paths: {
    "/auth/device/token": {
      post: {
        operationId: "pollDeviceToken",
        parameters: [],
        tags: ["ResponseMatching"],
        security: [],
        responses: {
          400: {
            description: "Problem details or OAuth polling state",
            content: {
              "application/problem+json": {
                schema: {
                  type: "object",
                  properties: {
                    kind: { const: "InvalidRequestError" },
                    code: { type: "string" }
                  },
                  required: ["kind", "code"],
                  additionalProperties: false
                }
              },
              "application/json": {
                schema: {
                  type: "object",
                  properties: {
                    kind: { const: "DeviceTokenOAuthError" },
                    error: { type: "string" }
                  },
                  required: ["kind", "error"],
                  additionalProperties: false
                }
              }
            }
          }
        }
      }
    },
    "/archive": {
      get: {
        operationId: "downloadArchive",
        parameters: [],
        tags: ["ResponseMatching"],
        security: [],
        responses: {
          200: {
            description: "Archive",
            content: {
              "application/zip": {
                schema: { type: "string", format: "binary" }
              }
            }
          },
          404: {
            description: "Not found",
            content: {
              "application/problem+json": {
                schema: {
                  type: "object",
                  properties: {
                    title: { type: "string" }
                  },
                  required: ["title"],
                  additionalProperties: false
                }
              }
            }
          }
        }
      }
    },
    "/avatar": {
      get: {
        operationId: "downloadAvatar",
        parameters: [],
        tags: ["ResponseMatching"],
        security: [],
        responses: {
          200: {
            description: "Avatar",
            content: {
              "image/png": {
                schema: { type: "string" }
              }
            }
          }
        }
      }
    },
    "/custom-binary": {
      get: {
        operationId: "downloadCustomBinary",
        parameters: [],
        tags: ["ResponseMatching"],
        security: [],
        responses: {
          200: {
            description: "Custom binary",
            content: {
              "application/vnd.example.data": {
                schema: { type: "string", format: "binary" }
              }
            }
          }
        }
      }
    },
    "/mixed-content": {
      get: {
        operationId: "downloadMixedContent",
        parameters: [],
        tags: ["ResponseMatching"],
        security: [],
        responses: {
          200: {
            description: "JSON metadata or binary content",
            content: {
              "application/json; charset=utf-8": {
                schema: {
                  type: "object",
                  properties: { href: { type: "string" } },
                  required: ["href"],
                  additionalProperties: false
                }
              },
              "application/octet-stream; boundary=payload": {
                schema: { type: "string" }
              }
            }
          },
          400: {
            description: "Invalid request",
            content: {
              "application/problem+json; charset=utf-8": {
                schema: {
                  type: "object",
                  properties: { title: { type: "string" } },
                  required: ["title"],
                  additionalProperties: false
                }
              }
            }
          }
        }
      }
    },
    "/resources/{id}": {
      head: {
        operationId: "checkResource",
        parameters: [{
          name: "id",
          in: "path",
          required: true,
          schema: { type: "string" }
        }],
        tags: ["ResponseMatching"],
        security: [],
        responses: {
          200: { description: "Exists" },
          404: { description: "Not found" },
          500: { description: "Server error" }
        }
      }
    }
  },
  components: {
    schemas: {},
    securitySchemes: {}
  },
  security: [],
  tags: [{ name: "ResponseMatching" }]
}

const voidSuccessSpec: OpenAPISpec = {
  openapi: "3.1.0",
  info: {
    title: "Void success API",
    version: "1.0.0"
  },
  paths: {
    "/mixed": {
      get: {
        operationId: "mixedSuccess",
        parameters: [],
        tags: ["VoidSuccess"],
        security: [],
        responses: {
          200: {
            description: "JSON value",
            content: {
              "application/json": {
                schema: { type: "string" }
              }
            }
          },
          204: { description: "No content" }
        }
      }
    },
    "/cached": {
      get: {
        operationId: "cached",
        parameters: [],
        tags: ["VoidSuccess"],
        security: [],
        responses: {
          304: { description: "Not modified" }
        }
      }
    }
  },
  components: {
    schemas: {},
    securitySchemes: {}
  },
  security: [],
  tags: [{ name: "VoidSuccess" }]
}

function multipartSpec(schema: JsonSchema.JsonSchema, schemas: JsonSchema.Definitions = {}): OpenAPISpec {
  return {
    openapi: "3.1.0",
    info: { title: "Upload API", version: "1.0.0" },
    paths: {
      "/upload": {
        post: {
          operationId: "upload",
          parameters: [],
          requestBody: {
            required: true,
            content: { "multipart/form-data": { schema } }
          },
          responses: { "204": { description: "Uploaded" } },
          tags: ["Upload"],
          security: []
        }
      }
    },
    components: { schemas, securitySchemes: {} },
    security: [],
    tags: [{ name: "Upload" }]
  }
}

function sharedMultipartSpec(
  schema: JsonSchema.JsonSchema,
  schemas: JsonSchema.Definitions,
  json: Record<string, unknown> = { schema }
): OpenAPISpec {
  const spec = multipartSpec(schema, schemas)
  return {
    ...spec,
    paths: {
      ...spec.paths,
      "/json": {
        post: {
          operationId: "createJson",
          parameters: [],
          requestBody: { required: true, content: { "application/json": json } } as any,
          responses: { "204": { description: "Created" } },
          tags: ["Upload"],
          security: []
        }
      }
    }
  }
}

const attachmentRef = { $ref: "#/components/schemas/Attachment" }

function attachmentSpec(paths: Record<string, OpenAPISpecPathItem>): OpenAPISpec {
  return {
    openapi: "3.1.0",
    info: { title: "Attachment API", version: "1.0.0" },
    paths: {
      "/attachments": {
        post: {
          operationId: "createAttachment",
          parameters: [],
          requestBody: {
            required: true,
            content: { "application/json": { schema: attachmentRef } }
          },
          responses: {
            "200": { description: "Created", content: { "application/json": { schema: attachmentRef } } }
          },
          tags: ["Attachments"],
          security: []
        }
      },
      ...paths
    },
    components: {
      schemas: {
        Attachment: {
          type: "object",
          properties: {
            name: { type: "string" },
            data: { type: "string", format: "binary" }
          },
          required: ["name", "data"],
          additionalProperties: false
        }
      },
      securitySchemes: {}
    },
    security: [],
    tags: [{ name: "Attachments" }]
  }
}

const cookieParameterSpec: OpenAPISpec = {
  openapi: "3.1.0",
  info: { title: "Cookie parameter API", version: "1.0.0" },
  paths: {
    "/greeting": {
      get: {
        operationId: "getGreeting",
        parameters: [{ name: "locale", in: "cookie", required: true, schema: { type: "string" } }],
        responses: { "204": { description: "No content" } },
        tags: ["Greeting"],
        security: []
      }
    }
  },
  components: { schemas: {}, securitySchemes: {} },
  security: [],
  tags: [{ name: "Greeting" }]
}

describe("OpenApiGenerator", () => {
  describe("schema", () => {
    it.effect("get operation", () =>
      assertRuntime(
        {
          openapi: "3.1.0",
          info: {
            title: "Test API",
            version: "1.0.0"
          },
          paths: {
            "/users/{id}": {
              get: {
                operationId: "getUser",
                parameters: [
                  {
                    name: "id",
                    in: "path",
                    schema: {
                      type: "string"
                    },
                    required: true
                  }
                ],
                responses: {
                  200: {
                    description: "User retrieved successfully",
                    content: {
                      "application/json": {
                        schema: {
                          type: "object",
                          properties: {
                            id: {
                              type: "string"
                            },
                            name: {
                              type: "string"
                            }
                          },
                          required: ["id", "name"],
                          additionalProperties: false,
                          description: "User object"
                        }
                      }
                    }
                  }
                },
                tags: ["Users"],
                security: []
              }
            }
          },
          components: {
            schemas: {},
            securitySchemes: {}
          },
          security: [],
          tags: []
        },
        `import * as Data from "effect/Data"
import * as Effect from "effect/Effect"
import type { SchemaError } from "effect/Schema"
import * as Schema from "effect/Schema"
import type * as HttpClient from "effect/http/HttpClient"
import * as HttpClientError from "effect/http/HttpClientError"
import * as HttpClientRequest from "effect/http/HttpClientRequest"
import * as HttpClientResponse from "effect/http/HttpClientResponse"
// schemas
export type GetUser200 = { readonly "id": string, readonly "name": string }
export const GetUser200 = Schema.Struct({ "id": Schema.String, "name": Schema.String }).annotate({ "description": "User object" })

export interface OperationConfig {
  /**
   * Whether or not the response should be included in the value returned from
   * an operation.
   *
   * If set to \`true\`, a tuple of \`[A, HttpClientResponse]\` will be returned,
   * where \`A\` is the success type of the operation.
   *
   * If set to \`false\`, only the success type of the operation will be returned.
   */
  readonly includeResponse?: boolean | undefined
}

/**
 * A utility type which optionally includes the response in the return result
 * of an operation based upon the value of the \`includeResponse\` configuration
 * option.
 */
export type WithOptionalResponse<A, Config extends OperationConfig | undefined> = Config extends {
  readonly includeResponse: true
} ? [A, HttpClientResponse.HttpClientResponse]
  : Config extends { readonly includeResponse?: false | undefined } | undefined ? A
  : A | [A, HttpClientResponse.HttpClientResponse]

export const make = <E, R>(
  httpClient: HttpClient.HttpClient.With<E, R>,
  options: {
    readonly transformClient?: ((client: HttpClient.HttpClient.With<E, R>) => Effect.Effect<HttpClient.HttpClient.With<E, R>>) | undefined
  } = {}
): TestClient<E, R> => {
  const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) =>
    Effect.flatMap(
      Effect.orElseSucceed(response.json, () => "Unexpected status code"),
      (description) =>
        Effect.fail(
          new HttpClientError.HttpClientError({
            reason: new HttpClientError.StatusCodeError({
              request: response.request,
              response,
              description: typeof description === "string" ? description : JSON.stringify(description),
            }),
          }),
        ),
    )
  const withResponse = <Config extends OperationConfig>(config: Config | undefined) => (
    f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<any, any>,
  ): (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<any, any, R> => {
    const withOptionalResponse = (
      config?.includeResponse
        ? (response: HttpClientResponse.HttpClientResponse) => Effect.map(f(response), (a) => [a, response])
        : (response: HttpClientResponse.HttpClientResponse) => f(response)
    ) as any
    return options?.transformClient
      ? (request) =>
          Effect.flatMap(
            Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)),
            withOptionalResponse
          )
      : (request) => Effect.flatMap(httpClient.execute(request), withOptionalResponse)
  }
  const __encodePathParam = encodeURIComponent
  const __makePathRequest = (
    method: (url: string) => HttpClientRequest.HttpClientRequest,
    parameters: ReadonlyArray<string>,
    getPath: () => string,
  ) => Effect.suspend(() => {
    const fail = (description: string, cause?: unknown) => Effect.fail(
      new HttpClientError.HttpClientError({
        reason: new HttpClientError.InvalidUrlError({
          request: method(""),
          cause,
          description,
        }),
      }),
    )
    if (parameters.some((value) => value === "" || /^(?:\\.|%2e){1,2}$/i.test(value))) {
      return fail("Path parameters must be non-empty and cannot be dot segments")
    }
    let path: string
    try {
      path = getPath()
    } catch (cause) {
      return fail("Failed to encode path parameter", cause)
    }
    if (path.split("/").some((segment) => /^(?:\\.|%2e){1,2}$/i.test(segment))) {
      return fail("Request paths cannot contain dot segments")
    }
    return Effect.succeed(method(path))
  })
  const decodeSuccess =
    <Schema extends Schema.Constraint>(schema: Schema) =>
    (response: HttpClientResponse.HttpClientResponse) =>
      HttpClientResponse.schemaBodyJson(schema)(response)
  return {
    httpClient,
    "getUser": (id, options: Parameters<TestClient["getUser"]>[1]) => __makePathRequest(HttpClientRequest.get, [id], () => "/users/" + __encodePathParam(id) + "").pipe(
    Effect.flatMap((request) => request.pipe(
      withResponse(options?.config)(HttpClientResponse.matchStatus({
      "2xx": decodeSuccess(GetUser200),
      orElse: unexpectedStatus
    }))
    ))
  )
  }
}

export interface TestClient<E = HttpClientError.HttpClientError, R = never> {
  readonly httpClient: HttpClient.HttpClient.With<E, R>
  readonly "getUser": {
    <Config extends OperationConfig | undefined = undefined>(id: string, options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<GetUser200, Config>, E | HttpClientError.HttpClientError | SchemaError, R>;
    <Config extends OperationConfig | undefined = undefined>(id: string, options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<GetUser200, Config | undefined>, E | HttpClientError.HttpClientError | SchemaError, R>;
  }
}

export interface TestClientError<Tag extends string, E> {
  readonly _tag: Tag
  readonly request: HttpClientRequest.HttpClientRequest
  readonly response: HttpClientResponse.HttpClientResponse
  readonly cause: E
}

class TestClientErrorImpl extends Data.Error<{
  _tag: string
  cause: any
  request: HttpClientRequest.HttpClientRequest
  response: HttpClientResponse.HttpClientResponse
}> {}

export const TestClientError = <Tag extends string, E>(
  tag: Tag,
  cause: E,
  response: HttpClientResponse.HttpClientResponse,
): TestClientError<Tag, E> =>
  new TestClientErrorImpl({
    _tag: tag,
    cause,
    response,
    request: response.request,
  }) as any`
      ))

    it.effect("resolves JSON Pointer-escaped local references", () =>
      assertRuntimeIncludes(
        {
          openapi: "3.1.0",
          info: {
            title: "Test API",
            version: "1.0.0"
          },
          paths: {
            "/widgets": {
              get: {
                operationId: "listWidgets",
                parameters: [
                  { $ref: "#/components/parameters/Page~1Limit" } as any,
                  { $ref: "#/components/parameters/Tilde~0Name" } as any
                ],
                responses: {
                  204: {
                    description: "No content"
                  }
                },
                tags: ["Widgets"],
                security: []
              }
            }
          },
          components: {
            schemas: {},
            parameters: {
              "Page/Limit": {
                name: "limit",
                in: "query",
                required: false,
                schema: { type: "integer" }
              },
              "Tilde~Name": {
                name: "tilde",
                in: "query",
                required: false,
                schema: { type: "string" }
              }
            }
          } as any,
          security: [],
          tags: [{ name: "Widgets" }]
        },
        [
          `readonly "limit"?: number`,
          `readonly "tilde"?: string`,
          `HttpClientRequest.setUrlParams({ "limit": options?.params?.["limit"] as any, "tilde": options?.params?.["tilde"] as any })`
        ]
      ))

    it.effect("sse operation decodes event payload from json string", () =>
      assertRuntimeIncludes(
        {
          openapi: "3.1.0",
          info: {
            title: "Test API",
            version: "1.0.0"
          },
          paths: {
            "/events": {
              get: {
                operationId: "streamEvents",
                parameters: [],
                responses: {
                  200: {
                    description: "Events streamed successfully",
                    content: {
                      "text/event-stream": {
                        schema: {
                          type: "object",
                          properties: {
                            type: {
                              type: "string"
                            },
                            value: {
                              type: "string"
                            }
                          },
                          required: ["type", "value"],
                          additionalProperties: false
                        }
                      }
                    }
                  }
                },
                tags: ["Events"],
                security: []
              }
            }
          },
          components: {
            schemas: {},
            securitySchemes: {}
          },
          security: [],
          tags: []
        },
        [
          `import * as Sse from "effect/encoding/Sse"`,
          `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>`,
          `"streamEventsSse": () => HttpClientRequest.get("/events").pipe(`,
          `sseRequest(StreamEvents200Sse)`,
          `schema: Schema.ConstraintDecoder<Type, DecodingServices>`
        ]
      ))

    it.effect("annotated sse operation decodes the full event schema", () =>
      assertRuntimeIncludes(
        {
          openapi: "3.1.0",
          info: {
            title: "Test API",
            version: "1.0.0"
          },
          paths: {
            "/events": {
              get: {
                operationId: "streamEvents",
                parameters: [],
                responses: {
                  200: {
                    description: "Events streamed successfully",
                    content: {
                      "text/event-stream": {
                        schema: {
                          type: "object",
                          properties: {
                            id: {
                              anyOf: [{ type: "string" }, { type: "null" }]
                            },
                            event: { const: "message" },
                            data: { type: "string" }
                          },
                          required: ["id", "event", "data"],
                          additionalProperties: false
                        },
                        "x-effect-stream": {
                          encoding: "sse",
                          errorSchema: {},
                          causeSchema: {},
                          failureEvent: "effect/http-api/stream/failure"
                        }
                      }
                    }
                  }
                },
                tags: ["Events"],
                security: []
              }
            }
          },
          components: {
            schemas: {},
            securitySchemes: {}
          },
          security: [],
          tags: []
        },
        [
          `"id": Schema.optionalKey(Schema.String), "event": Schema.Literal("message"), "data": Schema.String`,
          `"id": Schema.optionalKey(Schema.String), "event": Schema.Literal("effect/http-api/stream/failure"), "data": Schema.String`,
          `readonly "streamEventsSse": () => Stream.Stream<StreamEvents200Sse, E | HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError, R | typeof StreamEvents200Sse.DecodingServices>`,
          `sseEventRequest(StreamEvents200Sse)`,
          `Stream.pipeThroughChannel(Sse.decodeSchema(schema))`
        ]
      ))

    it.effect("form-urlencoded request body generates bodyUrlParams", () =>
      assertRuntimeIncludes(
        {
          openapi: "3.1.0",
          info: {
            title: "Test API",
            version: "1.0.0"
          },
          paths: {
            "/auth/token": {
              post: {
                operationId: "issueToken",
                parameters: [],
                requestBody: {
                  required: true,
                  content: {
                    "application/x-www-form-urlencoded": {
                      schema: {
                        type: "object",
                        properties: {
                          grant_type: { type: "string" },
                          client_id: { type: "string" }
                        },
                        required: ["grant_type", "client_id"],
                        additionalProperties: false
                      }
                    }
                  }
                } as any,
                responses: {
                  200: {
                    description: "Token response",
                    content: {
                      "application/json": {
                        schema: {
                          type: "object",
                          properties: {
                            access_token: { type: "string" }
                          },
                          required: ["access_token"],
                          additionalProperties: false
                        }
                      }
                    }
                  }
                },
                tags: ["Auth"],
                security: []
              }
            }
          },
          components: {
            schemas: {},
            securitySchemes: {}
          },
          security: [],
          tags: []
        },
        [
          `HttpClientRequest.bodyUrlParams(options.payload as any)`,
          `readonly payload: typeof IssueTokenRequestFormUrlEncoded.Encoded`
        ]
      ))

    it.effect("preserves response variants and routes binary and bodiless statuses", () =>
      assertRuntimeIncludes(responseMatchingSpec, [
        `export const PollDeviceToken400 = Schema.Union(`,
        `Schema.Literal("InvalidRequestError")`,
        `Schema.Literal("DeviceTokenOAuthError")`,
        `"400": decodeError("PollDeviceToken400", PollDeviceToken400)`,
        `TestClientError<"PollDeviceToken400", PollDeviceToken400>`,
        `export type DownloadArchive404 = { readonly "title": string }`,
        `const decodeBinary = (response: HttpClientResponse.HttpClientResponse) =>`,
        `Effect.map(response.arrayBuffer, (buffer) => new Uint8Array(buffer))`,
        `"2xx": decodeBinary`,
        `readonly "downloadArchive": {`,
        `<Config extends OperationConfig | undefined = undefined>(options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<Uint8Array, Config>`,
        `<Config extends OperationConfig | undefined = undefined>(options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<Uint8Array, Config | undefined>`,
        `readonly "downloadArchiveStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
        `readonly "downloadAvatarStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
        `"downloadAvatar": (options: Parameters<TestClient["downloadAvatar"]>[0]) => HttpClientRequest.get("/avatar").pipe(
      withResponse(options?.config)(HttpClientResponse.matchStatus({
      "2xx": decodeBinary`,
        `readonly "downloadCustomBinaryStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
        `"400": decodeError("DownloadMixedContent400", DownloadMixedContent400)`,
        `readonly "downloadMixedContent": {`,
        `<Config extends OperationConfig | undefined = undefined>(options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<Uint8Array, Config>`,
        `<Config extends OperationConfig | undefined = undefined>(options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<Uint8Array, Config | undefined>`,
        `readonly "downloadMixedContentStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
        `"200": () => Effect.void`,
        `"404": decodeVoidError("404")`,
        `"500": decodeVoidError("500")`,
        `TestClientError<"404", undefined>`,
        `TestClientError<"500", undefined>`
      ], [
        `"200": decodeSuccess(DownloadMixedContent200)`,
        `DownloadMixedContent200 | Uint8Array`
      ]))

    it.effect("routes mixed and non-2xx bodiless success responses", () =>
      assertRuntimeIncludes(voidSuccessSpec, [
        `"200": decodeSuccess(MixedSuccess200)`,
        `"204": () => Effect.void`,
        `"304": () => Effect.void`,
        `WithOptionalResponse<MixedSuccess200 | void, Config>`
      ]))

    it.effect("emits included component schemas that no operation references", () =>
      Effect.gen(function*() {
        const generator = yield* OpenApiGenerator.OpenApiGenerator
        const result = yield* generator.generate({
          openapi: "3.1.0",
          info: { title: "Test API", version: "1.0.0" },
          paths: {
            "/ping": {
              get: {
                operationId: "ping",
                parameters: [],
                responses: { 204: { description: "Pong" } },
                tags: ["Ping"],
                security: []
              }
            }
          },
          components: {
            schemas: {
              Legacy: {
                type: "object",
                properties: { value: { $ref: "#/components/schemas/LegacyValue" } },
                required: ["value"]
              },
              LegacyValue: { type: "string" },
              Unlisted: { type: "string" }
            },
            securitySchemes: {}
          },
          security: [],
          tags: [{ name: "Ping" }]
        }, { name: "TestClient", format: "httpclient", includeSchemas: ["Legacy"] })

        assert.include(result, "export const Legacy = ")
        assert.include(result, "export const LegacyValue = ")
        assert.notInclude(result, "Unlisted")
      }).pipe(Effect.provide(OpenApiGenerator.layerTransformerSchema)))
  })

  describe("type-only", () => {
    it.effect("get operation", () =>
      assertTypeOnly(
        {
          openapi: "3.1.0",
          info: {
            title: "Test API",
            version: "1.0.0"
          },
          paths: {
            "/users/{id}": {
              get: {
                operationId: "getUser",
                parameters: [
                  {
                    name: "id",
                    in: "path",
                    schema: {
                      type: "string"
                    },
                    required: true
                  }
                ],
                responses: {
                  200: {
                    description: "User retrieved successfully",
                    content: {
                      "application/json": {
                        schema: {
                          type: "object",
                          properties: {
                            id: {
                              type: "string"
                            },
                            name: {
                              type: "string"
                            }
                          },
                          required: ["id", "name"],
                          additionalProperties: false
                        }
                      }
                    }
                  }
                },
                tags: ["Users"],
                security: []
              }
            }
          },
          components: {
            schemas: {},
            securitySchemes: {}
          },
          security: [],
          tags: []
        },
        `import * as Data from "effect/Data"
import * as Effect from "effect/Effect"
import type * as HttpClient from "effect/http/HttpClient"
import * as HttpClientError from "effect/http/HttpClientError"
import * as HttpClientRequest from "effect/http/HttpClientRequest"
import * as HttpClientResponse from "effect/http/HttpClientResponse"
// schemas
export type GetUser200 = { readonly "id": string, readonly "name": string }

export interface OperationConfig {
  /**
   * Whether or not the response should be included in the value returned from
   * an operation.
   *
   * If set to \`true\`, a tuple of \`[A, HttpClientResponse]\` will be returned,
   * where \`A\` is the success type of the operation.
   *
   * If set to \`false\`, only the success type of the operation will be returned.
   */
  readonly includeResponse?: boolean | undefined
}

/**
 * A utility type which optionally includes the response in the return result
 * of an operation based upon the value of the \`includeResponse\` configuration
 * option.
 */
export type WithOptionalResponse<A, Config extends OperationConfig | undefined> = Config extends {
  readonly includeResponse: true
} ? [A, HttpClientResponse.HttpClientResponse]
  : Config extends { readonly includeResponse?: false | undefined } | undefined ? A
  : A | [A, HttpClientResponse.HttpClientResponse]

export const make = <E, R>(
  httpClient: HttpClient.HttpClient.With<E, R>,
  options: {
    readonly transformClient?: ((client: HttpClient.HttpClient.With<E, R>) => Effect.Effect<HttpClient.HttpClient.With<E, R>>) | undefined
  } = {}
): TestClient<E, R> => {
  const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) =>
    Effect.flatMap(
      Effect.orElseSucceed(response.json, () => "Unexpected status code"),
      (description) =>
        Effect.fail(
          new HttpClientError.HttpClientError({
            reason: new HttpClientError.StatusCodeError({
              request: response.request,
              response,
              description: typeof description === "string" ? description : JSON.stringify(description),
            }),
          }),
        ),
    )
  const withResponse = <Config extends OperationConfig>(config: Config | undefined) => (
    f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<any, any>,
  ): (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<any, any, R> => {
    const withOptionalResponse = (
      config?.includeResponse
        ? (response: HttpClientResponse.HttpClientResponse) => Effect.map(f(response), (a) => [a, response])
        : (response: HttpClientResponse.HttpClientResponse) => f(response)
    ) as any
    return options?.transformClient
      ? (request) =>
          Effect.flatMap(
            Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)),
            withOptionalResponse
          )
      : (request) => Effect.flatMap(httpClient.execute(request), withOptionalResponse)
  }
  const __encodePathParam = encodeURIComponent
  const __makePathRequest = (
    method: (url: string) => HttpClientRequest.HttpClientRequest,
    parameters: ReadonlyArray<string>,
    getPath: () => string,
  ) => Effect.suspend(() => {
    const fail = (description: string, cause?: unknown) => Effect.fail(
      new HttpClientError.HttpClientError({
        reason: new HttpClientError.InvalidUrlError({
          request: method(""),
          cause,
          description,
        }),
      }),
    )
    if (parameters.some((value) => value === "" || /^(?:\\.|%2e){1,2}$/i.test(value))) {
      return fail("Path parameters must be non-empty and cannot be dot segments")
    }
    let path: string
    try {
      path = getPath()
    } catch (cause) {
      return fail("Failed to encode path parameter", cause)
    }
    if (path.split("/").some((segment) => /^(?:\\.|%2e){1,2}$/i.test(segment))) {
      return fail("Request paths cannot contain dot segments")
    }
    return Effect.succeed(method(path))
  })
  const decodeSuccess = <A>(response: HttpClientResponse.HttpClientResponse) =>
    response.json as Effect.Effect<A, HttpClientError.HttpClientError>
  const decodeVoid = (_response: HttpClientResponse.HttpClientResponse) =>
    Effect.void
  const decodeError =
    <Tag extends string, E>(tag: Tag) =>
    (
      response: HttpClientResponse.HttpClientResponse,
    ): Effect.Effect<
      never,
      TestClientError<Tag, E> | HttpClientError.HttpClientError
    > =>
      Effect.flatMap(
        response.json as Effect.Effect<E, HttpClientError.HttpClientError>,
        (cause) => Effect.fail(TestClientError(tag, cause, response)),
      )
  const onRequest = <Config extends OperationConfig>(config: Config | undefined) => (
    successCodes: ReadonlyArray<string>,
    errorCodes?: Record<string, string>,
  ) => {
    const cases: any = { orElse: unexpectedStatus }
    for (const code of successCodes) {
      cases[code] = decodeSuccess
    }
    if (errorCodes) {
      for (const [code, tag] of Object.entries(errorCodes)) {
        cases[code] = decodeError(tag)
      }
    }
    if (successCodes.length === 0) {
      cases["2xx"] = decodeVoid
    }
    return withResponse(config)(HttpClientResponse.matchStatus(cases) as any)
  }
  return {
    httpClient,
    "getUser": (id, options: Parameters<TestClient["getUser"]>[1]) => __makePathRequest(HttpClientRequest.get, [id], () => "/users/" + __encodePathParam(id) + "").pipe(
    Effect.flatMap((request) => request.pipe(
      onRequest(options?.config)(["2xx"])
    ))
  )
  }
}

export interface TestClient<E = HttpClientError.HttpClientError, R = never> {
  readonly httpClient: HttpClient.HttpClient.With<E, R>
  readonly "getUser": {
    <Config extends OperationConfig | undefined = undefined>(id: string, options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<GetUser200, Config>, E | HttpClientError.HttpClientError, R>;
    <Config extends OperationConfig | undefined = undefined>(id: string, options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<GetUser200, Config | undefined>, E | HttpClientError.HttpClientError, R>;
  }
}

export interface TestClientError<Tag extends string, E> {
  readonly _tag: Tag
  readonly request: HttpClientRequest.HttpClientRequest
  readonly response: HttpClientResponse.HttpClientResponse
  readonly cause: E
}

class TestClientErrorImpl extends Data.Error<{
  _tag: string
  cause: any
  request: HttpClientRequest.HttpClientRequest
  response: HttpClientResponse.HttpClientResponse
}> {}

export const TestClientError = <Tag extends string, E>(
  tag: Tag,
  cause: E,
  response: HttpClientResponse.HttpClientResponse,
): TestClientError<Tag, E> =>
  new TestClientErrorImpl({
    _tag: tag,
    cause,
    response,
    request: response.request,
  }) as any`
      ))

    it.effect("preserves response variants and routes binary and bodiless statuses", () =>
      assertTypeOnlyIncludes(responseMatchingSpec, [
        `export type PollDeviceToken400 =`,
        `readonly "kind": "InvalidRequestError"`,
        `readonly "kind": "DeviceTokenOAuthError"`,
        `onRequest(options?.config)([], {"400":"PollDeviceToken400"})`,
        `const decodeBinary = (response: HttpClientResponse.HttpClientResponse) =>`,
        `onRequest(options?.config)([], {"404":"DownloadArchive404"}, {"binary":["2xx"],"voidSuccess":[],"voidError":[]})`,
        `readonly "downloadArchive": {`,
        `<Config extends OperationConfig | undefined = undefined>(options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<Uint8Array, Config>`,
        `<Config extends OperationConfig | undefined = undefined>(options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<Uint8Array, Config | undefined>`,
        `readonly "downloadAvatarStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
        `"downloadAvatar": (options: Parameters<TestClient["downloadAvatar"]>[0]) => HttpClientRequest.get("/avatar").pipe(
      onRequest(options?.config)([], undefined, {"binary":["2xx"],"voidSuccess":[],"voidError":[]})`,
        `readonly "downloadCustomBinaryStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
        `import * as HttpClient from "effect/http/HttpClient"`,
        `onRequest(options?.config)([], {"400":"DownloadMixedContent400"}, {"binary":["2xx"],"voidSuccess":[],"voidError":[]})`,
        `readonly "downloadMixedContent": {`,
        `<Config extends OperationConfig | undefined = undefined>(options: { readonly config: Config }): Effect.Effect<WithOptionalResponse<Uint8Array, Config>`,
        `<Config extends OperationConfig | undefined = undefined>(options: { readonly config?: Config | undefined } | undefined): Effect.Effect<WithOptionalResponse<Uint8Array, Config | undefined>`,
        `readonly "downloadMixedContentStream": () => Stream.Stream<Uint8Array, E | HttpClientError.HttpClientError, R>`,
        `onRequest(options?.config)([], undefined, {"binary":[],"voidSuccess":["200"],"voidError":["404","500"]})`,
        `cases[code] = decodeVoidError(code)`,
        `TestClientError<"404", undefined>`,
        `TestClientError<"500", undefined>`
      ], [
        `DownloadMixedContent200 | Uint8Array`
      ]))

    it.effect("routes mixed and non-2xx bodiless success responses", () =>
      assertTypeOnlyIncludes(voidSuccessSpec, [
        `onRequest(options?.config)(["200"], undefined, {"binary":[],"voidSuccess":["204"],"voidError":[]})`,
        `onRequest(options?.config)([], undefined, {"binary":[],"voidSuccess":["304"],"voidError":[]})`,
        `WithOptionalResponse<MixedSuccess200 | void, Config>`
      ]))

    itGeneratedClientsCompile("emits compilable clients for schema-backed and type-only formats", responseMatchingSpec)
  })

  describe("httpapi", () => {
    it.effect("generates tagged groups with endpoint annotations and representable parameters", () =>
      assertHttpApiIncludes(
        {
          openapi: "3.1.0",
          info: {
            title: "Test API",
            version: "1.0.0",
            summary: "Summary",
            description: "Description"
          },
          paths: {
            "/users/{id}": {
              get: {
                operationId: "getUser",
                summary: "Get user",
                description: "Read a user",
                deprecated: true,
                externalDocs: {
                  url: "https://example.com/get-user"
                },
                parameters: [
                  {
                    name: "id",
                    in: "path",
                    schema: { type: "string" },
                    required: true
                  },
                  {
                    name: "filter",
                    in: "query",
                    schema: { type: "string" },
                    required: false
                  },
                  {
                    name: "trace-id",
                    in: "header",
                    schema: { type: "string" },
                    required: false
                  }
                ],
                responses: {
                  200: {
                    description: "User",
                    content: {
                      "application/json": {
                        schema: {
                          type: "object",
                          properties: {
                            id: { type: "string" }
                          },
                          required: ["id"],
                          additionalProperties: false
                        }
                      }
                    }
                  },
                  404: {
                    description: "Not found"
                  }
                },
                tags: ["Users"],
                security: []
              }
            }
          },
          components: {
            schemas: {},
            securitySchemes: {}
          },
          security: [],
          tags: [
            {
              name: "Users",
              description: "User operations",
              externalDocs: {
                url: "https://example.com/users"
              }
            }
          ]
        },
        [
          `import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, HttpApiSecurity, OpenApi } from "effect/http-api"`,
          `export type GetUserPathParams = { readonly "id": string }`,
          `export const GetUserPathParams = Schema.Struct({ "id": Schema.String })`,
          `class UsersGroup extends HttpApiGroup.make("Users")`,
          `.annotate(OpenApi.Description, "User operations")`,
          `.annotate(OpenApi.ExternalDocs, {"url":"https://example.com/users"})`,
          `HttpApiEndpoint.get("getUser", "/users/:id", { params: GetUserPathParams, query: GetUserQuery, headers: GetUserHeaders, success: GetUser200, error: HttpApiSchema.Empty(404) })`,
          `.annotate(OpenApi.Identifier, "getUser")`,
          `.annotate(OpenApi.Summary, "Get user")`,
          `.annotate(OpenApi.Description, "Read a user")`,
          `.annotate(OpenApi.Deprecated, true)`,
          `.annotate(OpenApi.ExternalDocs, {"url":"https://example.com/get-user"})`,
          `export class TestClient extends HttpApi.make("TestClient")`,
          `.annotate(OpenApi.Title, "Test API")`,
          `.annotate(OpenApi.Version, "1.0.0")`,
          `.annotate(OpenApi.Summary, "Summary")`,
          `.annotate(OpenApi.Description, "Description")`,
          `.add(UsersGroup)`
        ],
        [
          `export class GetUserPathParams extends Schema.Class<GetUserPathParams>("GetUserPathParams")({ "id": Schema.String }) {}`
        ]
      ))

    it.effect("includes path-level parameters in generated httpapi endpoints", () =>
      assertHttpApiIncludes(
        {
          openapi: "3.1.0",
          info: {
            title: "Discord-style API",
            version: "1.0.0"
          },
          paths: {
            "/applications/{application_id}": {
              parameters: [
                {
                  name: "application_id",
                  in: "path",
                  schema: { type: "string" },
                  required: true
                }
              ],
              get: {
                operationId: "getApplication",
                parameters: [],
                responses: {
                  200: {
                    description: "Application"
                  }
                },
                tags: ["Applications"],
                security: []
              }
            }
          },
          components: {
            schemas: {},
            securitySchemes: {}
          },
          security: [],
          tags: [{ name: "Applications" }]
        },
        [
          `export type GetApplicationPathParams = { readonly "application_id": string }`,
          `export const GetApplicationPathParams = Schema.Struct({ "application_id": Schema.String })`,
          `HttpApiEndpoint.get("getApplication", "/applications/:application_id", { params: GetApplicationPathParams, success: HttpApiSchema.Empty(200) })`
        ],
        [
          `export class GetApplicationPathParams extends Schema.Class<GetApplicationPathParams>("GetApplicationPathParams")({ "application_id": Schema.String }) {}`
        ]
      ))

    it.effect("creates top-level fallback group for untagged operations", () =>
      assertHttpApiIncludes(
        {
          openapi: "3.1.0",
          info: {
            title: "Test API",
            version: "1.0.0"
          },
          paths: {
            "/health": {
              get: {
                operationId: "getHealth",
                parameters: [],
                responses: {
                  204: {
                    description: "No content"
                  }
                },
                tags: [] as any,
                security: []
              }
            }
          },
          components: {
            schemas: {},
            securitySchemes: {}
          },
          security: [],
          tags: []
        },
        [
          `class DefaultGroup extends HttpApiGroup.make("default", { topLevel: true })`,
          `HttpApiEndpoint.get("getHealth", "/health", { success: HttpApiSchema.Empty(204) })`,
          `.add(DefaultGroup)`
        ]
      ))

    it.effect("keeps the fallback group top-level when tagged default operations are present", () =>
      assertHttpApiIncludes(
        {
          openapi: "3.1.0",
          info: {
            title: "Test API",
            version: "1.0.0"
          },
          paths: {
            "/tagged": {
              get: {
                operationId: "getTagged",
                parameters: [],
                responses: {
                  200: {
                    description: "Tagged"
                  }
                },
                tags: ["default"],
                security: []
              }
            },
            "/untagged": {
              get: {
                operationId: "getUntagged",
                parameters: [],
                responses: {
                  204: {
                    description: "Untagged"
                  }
                },
                tags: [] as any,
                security: []
              }
            }
          },
          components: {
            schemas: {},
            securitySchemes: {}
          },
          security: [],
          tags: []
        },
        [
          `class DefaultGroup extends HttpApiGroup.make("default", { topLevel: true })`,
          `HttpApiEndpoint.get("getTagged", "/tagged", { success: HttpApiSchema.Empty(200) })`,
          `HttpApiEndpoint.get("getUntagged", "/untagged", { success: HttpApiSchema.Empty(204) })`,
          `.add(DefaultGroup)`
        ]
      ))

    it.effect("maps request and response encodings including optional request body approximation", () =>
      assertHttpApiIncludes(
        {
          openapi: "3.1.0",
          info: {
            title: "Test API",
            version: "1.0.0"
          },
          paths: {
            "/payload": {
              post: {
                operationId: "createPayload",
                parameters: [],
                requestBody: {
                  required: false,
                  content: {
                    "application/json": {
                      schema: {
                        type: "object",
                        properties: {
                          a: { type: "string" }
                        },
                        required: ["a"],
                        additionalProperties: false
                      }
                    },
                    "multipart/form-data": {
                      schema: {
                        type: "object",
                        properties: {
                          file: { type: "string", format: "binary" },
                          files: {