The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | /** |
| 2 | * The `OpenApiGenerator` module orchestrates converting OpenAPI and Swagger |
| 3 | * documents into generated Effect source. |
| 4 | * |
| 5 | * It normalizes Swagger 2.0 input, resolves local references, builds the |
| 6 | * parsed operation model, registers request and response schemas, applies |
| 7 | * HttpApi-specific adaptations such as multipart helpers and security metadata, |
| 8 | * emits warnings for unsupported or lossy OpenAPI features, and then delegates |
| 9 | * final rendering to the HttpClient or HttpApi code generators. |
| 10 | * |
| 11 | * @since 4.0.0 |
| 12 | */ |
| 13 | import * as Context from "effect/Context" |
| 14 | import * as Effect from "effect/Effect" |
| 15 | import type { OpenAPISecurityScheme, OpenAPISpec, OpenAPISpecOperation } from "effect/http-api/OpenApi" |
| 16 | import type { HttpMethod } from "effect/http/HttpMethod" |
| 17 | import * as JsonPointer from "effect/JsonPointer" |
| 18 | import type * as JsonSchema from "effect/JsonSchema" |
| 19 | import * as Layer from "effect/Layer" |
| 20 | import * as Predicate from "effect/Predicate" |
| 21 | import * as Rec from "effect/Record" |
| 22 | import * as String from "effect/String" |
| 23 | import SwaggerToOpenApi from "swagger2openapi" |
| 24 | import * as HttpApiTransformer from "./HttpApiTransformer.ts" |
| 25 | import * as JsonSchemaGenerator from "./JsonSchemaGenerator.ts" |
| 26 | import * as OpenApiTransformer from "./OpenApiTransformer.ts" |
| 27 | import * as ParsedOperation from "./ParsedOperation.ts" |
| 28 | import * as Utils from "./Utils.ts" |
| 29 | |
| 30 | /** |
| 31 | * Service for turning OpenAPI or Swagger specifications into generated Effect |
| 32 | * HTTP client or HttpApi source code. |
| 33 | * |
| 34 | * @category services |
| 35 | * @since 4.0.0 |
| 36 | */ |
| 37 | export class OpenApiGenerator extends Context.Service< |
| 38 | OpenApiGenerator, |
| 39 | { readonly generate: (spec: OpenAPISpec, options: OpenApiGenerateOptions) => Effect.Effect<string> } |
| 40 | >()("OpenApiGenerator") {} |
| 41 | |
| 42 | /** |
| 43 | * Output targets supported by the OpenAPI generator. |
| 44 | * |
| 45 | * **Details** |
| 46 | * |
| 47 | * The `httpclient` and `httpclient-type-only` formats support non-security |
| 48 | * cookie parameters with primitive schemas, which generated clients send in |
| 49 | * the request `Cookie` header. Cookie parameters with structured schemas, such |
| 50 | * as objects or arrays, are dropped with a `cookie-parameter-dropped` warning. |
| 51 | * The `httpapi` format drops all non-security cookie parameters. |
| 52 | * |
| 53 | * The `Cookie` header is set before the request reaches the supplied |
| 54 | * `HttpClient`, so it is subject to that client's request transformations. |
| 55 | * Browsers manage the `Cookie` header themselves and ignore explicit values, |
| 56 | * and `HttpClient.withCookiesRef` replaces the header whenever its cookie jar |
| 57 | * is non-empty. |
| 58 | * |
| 59 | * @category models |
| 60 | * @since 4.0.0 |
| 61 | */ |
| 62 | export type OpenApiGeneratorFormat = "httpclient" | "httpclient-type-only" | "httpapi" |
| 63 | |
| 64 | /** |
| 65 | * Stable identifiers for non-fatal OpenAPI generation warnings. |
| 66 | * |
| 67 | * @category models |
| 68 | * @since 4.0.0 |
| 69 | */ |
| 70 | export type OpenApiGeneratorWarningCode = |
| 71 | | "cookie-parameter-dropped" |
| 72 | | "additional-tags-dropped" |
| 73 | | "sse-operation-skipped" |
| 74 | | "response-headers-ignored" |
| 75 | | "optional-request-body-approximated" |
| 76 | | "default-response-remapped" |
| 77 | | "security-and-downgraded" |
| 78 | | "no-body-method-request-body-skipped" |
| 79 | | "streaming-request-body-skipped" |
| 80 | | "naming-collision" |
| 81 | |
| 82 | /** |
| 83 | * Describes a non-fatal issue encountered while mapping an OpenAPI operation to |
| 84 | * generated Effect source. |
| 85 | * |
| 86 | * @category models |
| 87 | * @since 4.0.0 |
| 88 | */ |
| 89 | export interface OpenApiGeneratorWarning { |
| 90 | readonly code: OpenApiGeneratorWarningCode |
| 91 | readonly message: string |
| 92 | readonly path?: string | undefined |
| 93 | readonly method?: Lowercase<HttpMethod> | undefined |
| 94 | readonly operationId?: string | undefined |
| 95 | } |
| 96 | |
| 97 | /** |
| 98 | * Formats a generation warning as a single human-readable line. |
| 99 | * |
| 100 | * **Details** |
| 101 | * |
| 102 | * The line starts with `WARNING [code]`, followed by the HTTP method, path and |
| 103 | * operation id when the warning carries them, then the warning message. |
| 104 | * |
| 105 | * **Example** (Formatting an operation warning) |
| 106 | * |
| 107 | * ```ts import.meta.vitest |
| 108 | * import { formatWarning } from "@effect/openapi-generator/OpenApiGenerator" |
| 109 | * |
| 110 | * formatWarning({ |
| 111 | * code: "cookie-parameter-dropped", |
| 112 | * message: "Cookie parameter was dropped.", |
| 113 | * path: "/items", |
| 114 | * method: "get", |
| 115 | * operationId: "listItems" |
| 116 | * }) // => "WARNING [cookie-parameter-dropped] GET /items (listItems): Cookie parameter was dropped." |
| 117 | * ``` |
| 118 | * |
| 119 | * @category formatting |
| 120 | * @since 4.0.0 |
| 121 | */ |
| 122 | export const formatWarning = (warning: OpenApiGeneratorWarning): string => { |
| 123 | const context = [ |
| 124 | warning.method?.toUpperCase(), |
| 125 | warning.path, |
| 126 | warning.operationId ? `(${warning.operationId})` : undefined |
| 127 | ].filter((value): value is string => value !== undefined) |
| 128 | return context.length > 0 |
| 129 | ? `WARNING [${warning.code}] ${context.join(" ")}: ${warning.message}` |
| 130 | : `WARNING [${warning.code}] ${warning.message}` |
| 131 | } |
| 132 | |
| 133 | /** |
| 134 | * Options that control one OpenAPI generation run. |
| 135 | * |
| 136 | * @category options |
| 137 | * @since 4.0.0 |
| 138 | */ |
| 139 | export interface OpenApiGenerateOptions { |
| 140 | /** |
| 141 | * The name to give to the generated output. |
| 142 | */ |
| 143 | readonly name: string |
| 144 | /** |
| 145 | * The output format to generate. |
| 146 | */ |
| 147 | readonly format: OpenApiGeneratorFormat |
| 148 | /** |
| 149 | * Hook to transform each JSON Schema node before processing. |
| 150 | */ |
| 151 | readonly onEnter?: ((js: JsonSchema.JsonSchema) => JsonSchema.JsonSchema) | undefined |
| 152 | /** |
| 153 | * Component schemas to generate even when no operation references them. |
| 154 | */ |
| 155 | readonly includeSchemas?: ReadonlyArray<string> | undefined |
| 156 | /** |
| 157 | * Callback to receive non-fatal generation warnings. |
| 158 | */ |
| 159 | readonly onWarning?: ((warning: OpenApiGeneratorWarning) => void) | undefined |
| 160 | } |
| 161 | |
| 162 | interface HttpApiMultipartSchemaRefs { |
| 163 | readonly kind: "httpapi" |
| 164 | readonly singleFile: string |
| 165 | readonly files: string |
| 166 | } |
| 167 | |
| 168 | type MultipartSchemaRefs = HttpApiMultipartSchemaRefs | { readonly kind: "client"; readonly singleFile: string } |
| 169 | |
| 170 | const methodNames: ReadonlyArray<Lowercase<HttpMethod>> = [ |
| 171 | "get", |
| 172 | "put", |
| 173 | "post", |
| 174 | "delete", |
| 175 | "options", |
| 176 | "head", |
| 177 | "patch", |
| 178 | "trace", |
| 179 | "query" |
| 180 | ] |
| 181 | |
| 182 | /** |
| 183 | * Constructs the OpenAPI generator service implementation. |
| 184 | * |
| 185 | * @category constructors |
| 186 | * @since 4.0.0 |
| 187 | */ |
| 188 | export const make = Effect.gen(function*() { |
| 189 | const generate = Effect.fn( |
| 190 | function*(spec: OpenAPISpec, options: OpenApiGenerateOptions) { |
| 191 | const generator = JsonSchemaGenerator.make() |
| 192 | const openApiTransformer = yield* OpenApiTransformer.OpenApiTransformer |
| 193 | const emitWarning = makeWarningEmitter(options) |
| 194 | |
| 195 | if (isSwaggerSpec(spec)) { |
| 196 | spec = yield* convertSwaggerSpec(spec) |
| 197 | } |
| 198 | |
| 199 | function resolveRef(ref: string) { |
| 200 | const parts = ref.split("/").slice(1).map(JsonPointer.unescapeToken) |
| 201 | let current: any = spec |
| 202 | for (const part of parts) { |
| 203 | current = current[part] |
| 204 | } |
| 205 | return current |
| 206 | } |
| 207 | |
| 208 | const multipart = makeMultipartSchemas(spec, options.format, resolveRef) |
| 209 | |
| 210 | const parsed = parseOpenApi(spec, generator, resolveRef, options.format, emitWarning, multipart.transform) |
| 211 | multipart.finish(generator.schemas) |
| 212 | |
| 213 | // TODO: make a CLI option ? |
| 214 | const importName = "Schema" |
| 215 | const source = getDialect(spec) |
| 216 | const schemaOptions = { |
| 217 | onEnter: options.onEnter, |
| 218 | multipartSchemaRefs: multipart.refs, |
| 219 | includeSchemas: options.includeSchemas |
| 220 | } |
| 221 | const generation = options.format === "httpapi" |
| 222 | ? generator.generateHttpApi(source, multipart.definitions, schemaOptions) |
| 223 | : generator.generate(source, multipart.definitions, options.format === "httpclient-type-only", schemaOptions) |
| 224 | |
| 225 | if (options.format === "httpapi") { |
| 226 | const needsMultipartImport = generation.includes("Multipart.") |
| 227 | return String.stripMargin( |
| 228 | `|${HttpApiTransformer.imports(importName, { multipart: needsMultipartImport })} |
| 229 | |${generation} |
| 230 | |${HttpApiTransformer.toImplementation(importName, options.name, parsed)}` |
| 231 | ) |
| 232 | } |
| 233 | |
| 234 | return String.stripMargin( |
| 235 | `|${openApiTransformer.imports(importName, parsed)} |
| 236 | |${generation} |
| 237 | |${openApiTransformer.toImplementation(importName, options.name, parsed)} |
| 238 | | |
| 239 | |${openApiTransformer.toTypes(importName, options.name, parsed)}` |
| 240 | ) |
| 241 | }, |
| 242 | (effect, _, options) => |
| 243 | Effect.provideServiceEffect( |
| 244 | effect, |
| 245 | OpenApiTransformer.OpenApiTransformer, |
| 246 | options.format === "httpclient-type-only" |
| 247 | ? Effect.sync(OpenApiTransformer.makeTransformerTs) |
| 248 | : Effect.sync(OpenApiTransformer.makeTransformerSchema) |
| 249 | ) |
| 250 | ) |
| 251 | |
| 252 | return { generate } as const |
| 253 | }) |
| 254 | |
| 255 | type WarningEmitter = (warning: OpenApiGeneratorWarning) => void |
| 256 | |
| 257 | const makeWarningEmitter = (options: OpenApiGenerateOptions): WarningEmitter => (warning) => { |
| 258 | options.onWarning?.(warning) |
| 259 | } |
| 260 | |
| 261 | const parseOpenApi = ( |
| 262 | spec: OpenAPISpec, |
| 263 | generator: ReturnType<typeof JsonSchemaGenerator.make>, |
| 264 | resolveRef: (ref: string) => unknown, |
| 265 | format: OpenApiGeneratorFormat, |
| 266 | emitWarning: WarningEmitter, |
| 267 | transformMultipart: (schema: JsonSchema.JsonSchema) => JsonSchema.JsonSchema |
| 268 | ): ParsedOperation.ParsedOpenApi => { |
| 269 | const operations: Array<ParsedOperation.ParsedOperation> = [] |
| 270 | const reservedSchemaNames = new Set<string>(Object.keys(spec.components?.schemas ?? {})) |
| 271 | const isHttpApi = format === "httpapi" |
| 272 | const securitySchemes = isHttpApi ? parseSecuritySchemes(spec, resolveRef) : [] |
| 273 | |
| 274 | const addSchema = ( |
| 275 | baseName: string, |
| 276 | schema: JsonSchema.JsonSchema, |
| 277 | operation: ParsedOperation.ParsedOperation |
| 278 | ): string => { |
| 279 | let candidate = baseName |
| 280 | let index = 2 |
| 281 | while (reservedSchemaNames.has(candidate)) { |
| 282 | candidate = `${baseName}${index}` |
| 283 | index += 1 |
| 284 | } |
| 285 | if (candidate !== baseName) { |
| 286 | warnForOperation(emitWarning, operation, { |
| 287 | code: "naming-collision", |
| 288 | message: `Schema name "${baseName}" collided with an existing name and was renamed to "${candidate}".` |
| 289 | }) |
| 290 | } |
| 291 | reservedSchemaNames.add(candidate) |
| 292 | return generator.addSchema(candidate, schema) |
| 293 | } |
| 294 | |
| 295 | for (const [path, methods] of Object.entries(spec.paths)) { |
| 296 | const pathItem: Partial<Record<Lowercase<HttpMethod>, OpenAPISpecOperation>> = methods |
| 297 | for (const method of methodNames) { |
| 298 | const operation = method === "query" |
| 299 | ? pathItem.query ?? methods["x-oai-additionalOperations"]?.QUERY |
| 300 | : pathItem[method] |
| 301 | if (Predicate.isUndefined(operation)) { |
| 302 | continue |
| 303 | } |
| 304 | const id = operation.operationId |
| 305 | ? Utils.camelize(operation.operationId) |
| 306 | : `${method.toUpperCase()}${path}` |
| 307 | |
| 308 | const description = Utils.nonEmptyString(operation.description) ?? Utils.nonEmptyString(operation.summary) |
| 309 | |
| 310 | const { pathIds, pathTemplate } = processPath(path) |
| 311 | |
| 312 | const op = ParsedOperation.makeDeepMutable({ |
| 313 | id, |
| 314 | method, |
| 315 | description, |
| 316 | pathIds, |
| 317 | pathTemplate |
| 318 | }) |
| 319 | const httpClientResponses = op.httpClientResponses |
| 320 | op.path = path |
| 321 | op.operationId = Utils.nonEmptyString(operation.operationId) |
| 322 | op.tags = [...(operation.tags ?? [])] |
| 323 | if (isHttpApi && op.tags.length > 1) { |
| 324 | warnForOperation(emitWarning, op, { |
| 325 | code: "additional-tags-dropped", |
| 326 | message: `Additional tags (${op.tags.slice(1).join(", ")}) were dropped. Only the first tag ("${ |
| 327 | op.tags[0] |
| 328 | }") is used for grouping.` |
| 329 | }) |
| 330 | } |
| 331 | op.metadata = { |
| 332 | summary: Utils.nonEmptyString(operation.summary), |
| 333 | description: Utils.nonEmptyString(operation.description), |
| 334 | deprecated: operation.deprecated === true, |
| 335 | externalDocs: operation.externalDocs |
| 336 | } |
| 337 | op.effectiveSecurity = cloneSecurityRequirements(operation.security ?? spec.security ?? []) |
| 338 | if (isHttpApi) { |
| 339 | warnForAndSecurityRequirements(emitWarning, op) |
| 340 | } |
| 341 | |
| 342 | const schemaId = Utils.identifier(operation.operationId ?? path) |
| 343 | |
| 344 | const pathParameters = Array.isArray(methods.parameters) |
| 345 | ? methods.parameters |
| 346 | : undefined |
| 347 | const parameters = resolveOperationParameters( |
| 348 | pathParameters, |
| 349 | Array.isArray(operation.parameters) ? operation.parameters : undefined, |
| 350 | resolveRef |
| 351 | ) |
| 352 | const droppedCookies = new Set<OpenApiParameter>() |
| 353 | for (const parameter of parameters) { |
| 354 | const parsedParameter: ParsedOperation.ParsedOperationParameter = { |
| 355 | name: parameter.name, |
| 356 | in: parameter.in, |
| 357 | required: parameter.required === true, |
| 358 | description: Utils.nonEmptyString(parameter.description), |
| 359 | schema: parameter.schema |
| 360 | } |
| 361 | switch (parameter.in) { |
| 362 | case "path": { |
| 363 | op.parameters.path.push(parsedParameter) |
| 364 | break |
| 365 | } |
| 366 | case "query": { |
| 367 | op.parameters.query.push(parsedParameter) |
| 368 | if ((parameter.style ?? "form") === "form" && parameter.explode === false) { |
| 369 | op.commaUrlParams.push(parameter.name) |
| 370 | } |
| 371 | break |
| 372 | } |
| 373 | case "header": { |
| 374 | op.parameters.header.push(parsedParameter) |
| 375 | break |
| 376 | } |
| 377 | case "cookie": { |
| 378 | op.parameters.cookie.push(parsedParameter) |
| 379 | const dropReason = isHttpApi |
| 380 | ? "non-security cookie parameters are not supported" |
| 381 | : isPrimitiveSchema(parameter.schema, resolveRef) |
| 382 | ? undefined |
| 383 | : "only primitive cookie parameter schemas are supported" |
| 384 | if (dropReason !== undefined) { |
| 385 | droppedCookies.add(parameter) |
| 386 | warnForOperation(emitWarning, op, { |
| 387 | code: "cookie-parameter-dropped", |
| 388 | message: `Cookie parameter "${parameter.name}" was dropped because ${dropReason}.` |
| 389 | }) |
| 390 | } |
| 391 | break |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | const requestBody = resolveReference(operation.requestBody, resolveRef) |
| 397 | if (isHttpApi && !methodSupportsRequestBody(op.method) && Predicate.isObject(requestBody)) { |
| 398 | warnForOperation(emitWarning, op, { |
| 399 | code: "no-body-method-request-body-skipped", |
| 400 | message: `Operation was skipped because ${op.method.toUpperCase()} does not support request bodies.` |
| 401 | }) |
| 402 | continue |
| 403 | } |
| 404 | |
| 405 | const resolvedResponses = Object.entries(operation.responses ?? {}) |
| 406 | .filter(([status]) => isResponseStatus(status)) |
| 407 | .map(([status, response]) => [status, resolveReference(response, resolveRef)] as const) |
| 408 | const hasExplicitSuccessResponse = resolvedResponses.some(([status]) => { |
| 409 | if (!/^\d{3}$/.test(status)) { |
| 410 | return false |
| 411 | } |
| 412 | return Number(status) < 400 |
| 413 | }) |
| 414 | |
| 415 | if (isHttpApi && hasUnsupportedSuccessfulSseResponse(resolvedResponses, hasExplicitSuccessResponse)) { |
| 416 | warnForOperation(emitWarning, op, { |
| 417 | code: "sse-operation-skipped", |
| 418 | message: |
| 419 | "Operation was skipped because a successful SSE response is missing x-effect-stream metadata required for HttpApi generation." |
| 420 | }) |
| 421 | continue |
| 422 | } |
| 423 | |
| 424 | const validParameters = parameters.filter((parameter) => |
| 425 | parameter.in !== "path" && !droppedCookies.has(parameter) |
| 426 | ) |
| 427 | |
| 428 | const combinedParameterSchema = buildParameterSchema(validParameters, (parameter, added) => { |
| 429 | if (parameter.in === "query") { |
| 430 | Utils.spreadElementsInto(added, op.urlParams) |
| 431 | } else if (parameter.in === "header") { |
| 432 | Utils.spreadElementsInto(added, op.headers) |
| 433 | } else if (parameter.in === "cookie") { |
| 434 | Utils.spreadElementsInto(added, op.cookies) |
| 435 | } |
| 436 | }) |
| 437 | |
| 438 | if (combinedParameterSchema !== undefined) { |
| 439 | op.params = addSchema(`${schemaId}Params`, combinedParameterSchema.schema, op) |
| 440 | op.paramsOptional = combinedParameterSchema.optional |
| 441 | } |
| 442 | |
| 443 | if (isHttpApi) { |
| 444 | const pathParameterSchema = buildParameterSchema(op.parameters.path) |
| 445 | if (pathParameterSchema !== undefined) { |
| 446 | op.pathSchema = addSchema(`${schemaId}PathParams`, pathParameterSchema.schema, op) |
| 447 | } |
| 448 | |
| 449 | const queryParameterSchema = buildParameterSchema(op.parameters.query) |
| 450 | if (queryParameterSchema !== undefined) { |
| 451 | op.querySchema = addSchema(`${schemaId}Query`, queryParameterSchema.schema, op) |
| 452 | op.querySchemaOptional = queryParameterSchema.optional |
| 453 | } |
| 454 | |
| 455 | const headerParameterSchema = buildParameterSchema(op.parameters.header) |
| 456 | if (headerParameterSchema !== undefined) { |
| 457 | op.headersSchema = addSchema(`${schemaId}Headers`, headerParameterSchema.schema, op) |
| 458 | op.headersSchemaOptional = headerParameterSchema.optional |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | if (Predicate.isNotUndefined(requestBody) && Predicate.isObject(requestBody)) { |
| 463 | const content = Predicate.isObject(requestBody.content) |
| 464 | ? requestBody.content as Record<string, any> |
| 465 | : {} |
| 466 | const requestSchemaNames = new Map<string, string>() |
| 467 | op.requestBody = { |
| 468 | required: requestBody.required === true, |
| 469 | contentTypes: Object.keys(content) |
| 470 | } |
| 471 | if (isHttpApi && requestBody.required === false) { |
| 472 | warnForOperation(emitWarning, op, { |
| 473 | code: "optional-request-body-approximated", |
| 474 | message: "Optional request body was approximated by adding a no-content payload alternative." |
| 475 | }) |
| 476 | } |
| 477 | |
| 478 | if (Predicate.isNotUndefined(content["application/json"]?.schema)) { |
| 479 | op.payload = addSchema(`${schemaId}RequestJson`, content["application/json"].schema, op) |
| 480 | requestSchemaNames.set("application/json", op.payload) |
| 481 | } |
| 482 | |
| 483 | if ( |
| 484 | Predicate.isNotUndefined(content["multipart/form-data"]?.schema) && |
| 485 | !(isHttpApi && getEffectStreamEncoding(content["multipart/form-data"]) === "ndjson") |
| 486 | ) { |
| 487 | op.payload = addSchema( |
| 488 | `${schemaId}RequestFormData`, |
| 489 | transformMultipart(content["multipart/form-data"].schema), |
| 490 | op |
| 491 | ) |
| 492 | op.payloadFormData = true |
| 493 | requestSchemaNames.set("multipart/form-data", op.payload) |
| 494 | } |
| 495 | |
| 496 | if (Predicate.isNotUndefined(content["application/x-www-form-urlencoded"]?.schema)) { |
| 497 | op.payload = addSchema( |
| 498 | `${schemaId}RequestFormUrlEncoded`, |
| 499 | content["application/x-www-form-urlencoded"].schema, |
| 500 | op |
| 501 | ) |
| 502 | op.payloadFormUrlEncoded = true |
| 503 | requestSchemaNames.set("application/x-www-form-urlencoded", op.payload) |
| 504 | } |
| 505 | |
| 506 | if (isHttpApi) { |
| 507 | const representableRequestBody: Array<ParsedOperation.ParsedOperationMediaTypeSchema> = [] |
| 508 | for (const [contentType, mediaType] of Object.entries(content)) { |
| 509 | if (!Predicate.isObject(mediaType)) { |
| 510 | continue |
| 511 | } |
| 512 | const streamEncoding = getEffectStreamEncoding(mediaType) |
| 513 | if ( |
| 514 | streamEncoding !== "ndjson" && |
| 515 | unsupportedStreamingRequestMediaTypes.has(normalizeMediaType(contentType)) |
| 516 | ) { |
| 517 | warnForOperation(emitWarning, op, { |
| 518 | code: "streaming-request-body-skipped", |
| 519 | message: `Request body media type ${contentType} was skipped because HttpApi cannot stream it.` |
| 520 | }) |
| 521 | continue |
| 522 | } |
| 523 | if (streamEncoding === "uint8array") { |
| 524 | representableRequestBody.push({ |
| 525 | contentType, |
| 526 | encoding: "binary", |
| 527 | effectStream: "uint8array" |
| 528 | }) |
| 529 | continue |
| 530 | } |
| 531 | const ndjsonSchema = getNdjsonElementSchema(contentType, mediaType) |
| 532 | if (Predicate.isNotUndefined(ndjsonSchema)) { |
| 533 | representableRequestBody.push({ |
| 534 | contentType, |
| 535 | encoding: "json", |
| 536 | effectStream: "ndjson", |
| 537 | schema: requestSchemaNames.get(contentType) ?? addSchema( |
| 538 | `${schemaId}Request${mediaTypeToSuffix(contentType)}`, |
| 539 | ndjsonSchema, |
| 540 | op |
| 541 | ) |
| 542 | }) |
| 543 | continue |
| 544 | } |
| 545 | if (Predicate.isUndefined(mediaType.schema)) { |
| 546 | continue |
| 547 | } |
| 548 | const encoding = getRequestMediaTypeEncoding(contentType) |
| 549 | if (encoding === undefined) { |
| 550 | continue |
| 551 | } |
| 552 | let schemaName = requestSchemaNames.get(contentType) |
| 553 | if (schemaName === undefined) { |
| 554 | const schema = encoding === "multipart" |
| 555 | ? transformMultipart(mediaType.schema as JsonSchema.JsonSchema) |
| 556 | : mediaType.schema as JsonSchema.JsonSchema |
| 557 | schemaName = addSchema( |
| 558 | `${schemaId}Request${mediaTypeToSuffix(contentType)}`, |
| 559 | schema, |
| 560 | op |
| 561 | ) |
| 562 | requestSchemaNames.set(contentType, schemaName) |
| 563 | } |
| 564 | representableRequestBody.push({ |
| 565 | contentType, |
| 566 | encoding, |
| 567 | schema: schemaName |
| 568 | }) |
| 569 | } |
| 570 | op.requestBodyRepresentable = representableRequestBody |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | let defaultSchema: string | undefined |
| 575 | for (const [status, response] of resolvedResponses) { |
| 576 | if (!Predicate.isObject(response)) { |
| 577 | continue |
| 578 | } |
| 579 | |
| 580 | const parsedStatus = isHttpApi |
| 581 | ? remapDefaultResponseStatusForHttpApi(status, hasExplicitSuccessResponse) |
| 582 | : status |
| 583 | if (isHttpApi && status === "default") { |
| 584 | warnForOperation(emitWarning, op, { |
| 585 | code: "default-response-remapped", |
| 586 | message: `Default response was remapped to status ${parsedStatus} for HttpApi generation.` |
| 587 | }) |
| 588 | } |
| 589 | |
| 590 | const content = Predicate.isObject(response.content) |
| 591 | ? response.content as Record<string, any> |
| 592 | : undefined |
| 593 | if (isHttpApi && Predicate.isNotUndefined(response.headers)) { |
| 594 | warnForOperation(emitWarning, op, { |
| 595 | code: "response-headers-ignored", |
| 596 | message: `Response headers on status ${status} were ignored in HttpApi generation.` |
| 597 | }) |
| 598 | } |
| 599 | const representable: Array<ParsedOperation.ParsedOperationMediaTypeSchema> = [] |
| 600 | |
| 601 | let jsonSchemaName: string | undefined |
| 602 | let jsonResponseContentType: string | undefined |
| 603 | if (isHttpApi) { |
| 604 | const jsonResponseEntries = Object.entries(content ?? {}).filter(([contentType, mediaType]) => |
| 605 | isJsonMediaType(normalizeMediaType(contentType)) && |
| 606 | Predicate.isObject(mediaType) && |
| 607 | Predicate.isNotUndefined(mediaType.schema) && |
| 608 | !(isSuccessStatus(parsedStatus) && getEffectStreamEncoding(mediaType) === "ndjson") |
| 609 | ) |
| 610 | const jsonResponseEntry = jsonResponseEntries.find(([contentType]) => |
| 611 | normalizeMediaType(contentType) === "application/json" |
| 612 | ) ?? jsonResponseEntries[0] |
| 613 | if (Predicate.isNotUndefined(jsonResponseEntry)) { |
| 614 | const [contentType, mediaType] = jsonResponseEntry |
| 615 | jsonResponseContentType = contentType |
| 616 | jsonSchemaName = addSchema(`${schemaId}${status}`, mediaType.schema as JsonSchema.JsonSchema, op) |
| 617 | representable.push({ |
| 618 | contentType, |
| 619 | encoding: "json", |
| 620 | schema: jsonSchemaName |
| 621 | }) |
| 622 | } |
| 623 | } else { |
| 624 | const jsonSchemas = Object.entries(content ?? {}).flatMap(([contentType, mediaType]) => |
| 625 | isJsonMediaType(normalizeMediaType(contentType)) && |
| 626 | Predicate.isObject(mediaType) && |
| 627 | Predicate.isNotUndefined(mediaType.schema) |
| 628 | ? [mediaType.schema as JsonSchema.JsonSchema] |
| 629 | : [] |
| 630 | ) |
| 631 | if (jsonSchemas.length > 0) { |
| 632 | jsonSchemaName = addSchema( |
| 633 | `${schemaId}${status}`, |
| 634 | jsonSchemas.length === 1 ? jsonSchemas[0] : { anyOf: jsonSchemas }, |
| 635 | op |
| 636 | ) |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | if (isHttpApi) { |
| 641 | for (const [contentType, mediaType] of Object.entries(content ?? {})) { |
| 642 | if (contentType === jsonResponseContentType) { |
| 643 | continue |
| 644 | } |
| 645 | if (!Predicate.isObject(mediaType)) { |
| 646 | continue |
| 647 | } |
| 648 | |
| 649 | const streamEncoding = isSuccessStatus(parsedStatus) |
| 650 | ? getEffectStreamEncoding(mediaType) |
| 651 | : undefined |
| 652 | if (streamEncoding === "uint8array") { |
| 653 | representable.push({ |
| 654 | contentType, |
| 655 | encoding: "binary", |
| 656 | effectStream: "uint8array" |
| 657 | }) |
| 658 | continue |
| 659 | } |
| 660 | const ndjsonSchema = isSuccessStatus(parsedStatus) |
| 661 | ? getNdjsonElementSchema(contentType, mediaType) |
| 662 | : undefined |
| 663 | if (Predicate.isNotUndefined(ndjsonSchema)) { |
| 664 | representable.push({ |
| 665 | contentType, |
| 666 | encoding: "json", |
| 667 | effectStream: "ndjson", |
| 668 | schema: addSchema( |
| 669 | `${schemaId}${status}${mediaTypeToSuffix(contentType)}`, |
| 670 | ndjsonSchema, |
| 671 | op |
| 672 | ) |
| 673 | }) |
| 674 | continue |
| 675 | } |
| 676 | if (streamEncoding === "sse") { |
| 677 | const errorSchema = getEffectStreamErrorSchema(mediaType) |
| 678 | if (Predicate.isUndefined(mediaType.schema) || Predicate.isUndefined(errorSchema)) { |
| 679 | continue |
| 680 | } |
| 681 | representable.push({ |
| 682 | contentType, |
| 683 | encoding: "text", |
| 684 | effectStream: "sse", |
| 685 | schema: addSchema( |
| 686 | `${schemaId}${status}Sse`, |
| 687 | mediaType.schema as JsonSchema.JsonSchema, |
| 688 | op |
| 689 | ), |
| 690 | errorSchema: addSchema( |
| 691 | `${schemaId}${status}SseError`, |
| 692 | errorSchema, |
| 693 | op |
| 694 | ) |
| 695 | }) |
| 696 | continue |
| 697 | } |
| 698 | |
| 699 | if (Predicate.isUndefined(mediaType.schema)) { |
| 700 | continue |
| 701 | } |
| 702 | const encoding = getResponseMediaTypeEncoding(contentType) |
| 703 | if (encoding === undefined) { |
| 704 | continue |
| 705 | } |
| 706 | const schemaName = addSchema( |
| 707 | `${schemaId}${status}${mediaTypeToSuffix(contentType)}`, |
| 708 | mediaType.schema as JsonSchema.JsonSchema, |
| 709 | op |
| 710 | ) |
| 711 | representable.push({ |
| 712 | contentType, |
| 713 | encoding, |
| 714 | schema: schemaName |
| 715 | }) |
| 716 | } |
| 717 | } |
| 718 | |
| 719 | const isEmptyResponse = Predicate.isUndefined(content) || Object.keys(content).length === 0 |
| 720 | const parsedResponse = { |
| 721 | status: parsedStatus, |
| 722 | description: Utils.nonEmptyString(response.description), |
| 723 | contentTypes: Predicate.isNotUndefined(content) ? Object.keys(content) : [], |
| 724 | hasHeaders: Predicate.isNotUndefined(response.headers), |
| 725 | isEmpty: isEmptyResponse, |
| 726 | representable |
| 727 | } |
| 728 | op.responses.push(parsedResponse) |
| 729 | if (status === "default") { |
| 730 | op.defaultResponse = parsedResponse |
| 731 | } |
| 732 | |
| 733 | const normalizedStatus = parsedStatus.toLowerCase() |
| 734 | const hasBinaryResponse = Object.entries(content ?? {}).some(([contentType, mediaType]) => |
| 735 | Predicate.isObject(mediaType) && |
| 736 | (isBinaryMediaType(normalizeMediaType(contentType)) || isBinarySchema(mediaType.schema)) |
| 737 | ) |
| 738 | if (hasBinaryResponse && isSuccessStatus(parsedStatus)) { |
| 739 | httpClientResponses.binarySuccessStatuses.add(normalizedStatus) |
| 740 | } |
| 741 | |
| 742 | if (Predicate.isNotUndefined(jsonSchemaName)) { |
| 743 | if (status === "default" && !isHttpApi) { |
| 744 | defaultSchema = jsonSchemaName |
| 745 | continue |
| 746 | } |
| 747 | |
| 748 | if (Number.isNaN(Number(parsedStatus[0]))) { |
| 749 | continue |
| 750 | } |
| 751 | if (isSuccessStatus(parsedStatus)) { |
| 752 | if (!httpClientResponses.binarySuccessStatuses.has(normalizedStatus)) { |
| 753 | httpClientResponses.successSchemas.set(normalizedStatus, jsonSchemaName) |
| 754 | } |
| 755 | } else { |
| 756 | httpClientResponses.errorSchemas.set(normalizedStatus, jsonSchemaName) |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | const sseMediaType = content?.["text/event-stream"] |
| 761 | const sseResponseSchema = sseMediaType?.schema |
| 762 | if ( |
| 763 | !isHttpApi && Predicate.isUndefined(httpClientResponses.sseSchema) && |
| 764 | Predicate.isNotUndefined(sseResponseSchema) && |
| 765 | isSuccessStatus(parsedStatus) |
| 766 | ) { |
| 767 | const effectStream = sseMediaType["x-effect-stream"] |
| 768 | httpClientResponses.sseSchemaMode = getEffectStreamEncoding(sseMediaType) === "sse" ? "event" : "data" |
| 769 | httpClientResponses.sseSchema = addSchema( |
| 770 | `${schemaId}${status}Sse`, |
| 771 | httpClientResponses.sseSchemaMode === "event" |
| 772 | ? makeSseEventSchema( |
| 773 | resolveReference(sseResponseSchema, resolveRef), |
| 774 | effectStream?.encoding === "sse" ? effectStream.failureEvent : undefined |
| 775 | ) |
| 776 | : sseResponseSchema, |
| 777 | op |
| 778 | ) |
| 779 | } |
| 780 | |
| 781 | if (isEmptyResponse && parsedStatus !== "default") { |
| 782 | if (isSuccessStatus(normalizedStatus)) { |
| 783 | httpClientResponses.voidSuccessStatuses.add(normalizedStatus) |
| 784 | } else { |
| 785 | httpClientResponses.voidErrorStatuses.add(normalizedStatus) |
| 786 | } |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | if ( |
| 791 | !isHttpApi && httpClientResponses.successSchemas.size === 0 && Predicate.isNotUndefined(defaultSchema) |
| 792 | ) { |
| 793 | httpClientResponses.successSchemas.set("2xx", defaultSchema) |
| 794 | warnForOperation(emitWarning, op, { |
| 795 | code: "default-response-remapped", |
| 796 | message: "Default response was remapped to 2xx for the current HttpClient outputs." |
| 797 | }) |
| 798 | } |
| 799 | |
| 800 | operations.push(op) |
| 801 | } |
| 802 | } |
| 803 | |
| 804 | return { |
| 805 | metadata: { |
| 806 | title: spec.info.title, |
| 807 | version: spec.info.version, |
| 808 | summary: Utils.nonEmptyString(spec.info.summary), |
| 809 | description: Utils.nonEmptyString(spec.info.description), |
| 810 | license: spec.info.license, |
| 811 | servers: spec.servers |
| 812 | }, |
| 813 | tags: (spec.tags ?? []).map((tag) => ({ |
| 814 | name: tag.name, |
| 815 | description: Utils.nonEmptyString(tag.description), |
| 816 | externalDocs: tag.externalDocs |
| 817 | })), |
| 818 | securitySchemes, |
| 819 | operations |
| 820 | } |
| 821 | } |
| 822 | |
| 823 | interface OpenApiParameter { |
| 824 | readonly name: string |
| 825 | readonly in: "path" | "query" | "header" | "cookie" |
| 826 | readonly required: boolean |
| 827 | readonly schema: {} |
| 828 | readonly description?: string | undefined |
| 829 | readonly style?: string | undefined |
| 830 | readonly explode?: boolean | undefined |
| 831 | } |
| 832 | |
| 833 | const isOpenApiParameter = (parameter: unknown): parameter is OpenApiParameter => { |
| 834 | if (!Predicate.isObject(parameter)) { |
| 835 | return false |
| 836 | } |
| 837 | return ( |
| 838 | typeof parameter.name === "string" && |
| 839 | (parameter.in === "path" || parameter.in === "query" || parameter.in === "header" || parameter.in === "cookie") |
| 840 | ) |
| 841 | } |
| 842 | |
| 843 | const resolveOperationParameters = ( |
| 844 | pathParameters: ReadonlyArray<unknown> | undefined, |
| 845 | operationParameters: ReadonlyArray<unknown> | undefined, |
| 846 | resolveRef: (ref: string) => unknown |
| 847 | ): Array<OpenApiParameter> => { |
| 848 | const resolved = new Map<string, OpenApiParameter>() |
| 849 | const add = (parameter: unknown): void => { |
| 850 | const current = resolveReference(parameter, resolveRef) |
| 851 | if (!isOpenApiParameter(current)) { |
| 852 | return |
| 853 | } |
| 854 | |
| 855 | const key = `${current.in}:${current.name}` |
| 856 | if (resolved.has(key)) { |
| 857 | resolved.delete(key) |
| 858 | } |
| 859 | resolved.set(key, current) |
| 860 | } |
| 861 | |
| 862 | for (const parameter of pathParameters ?? []) { |
| 863 | add(parameter) |
| 864 | } |
| 865 | |
| 866 | for (const parameter of operationParameters ?? []) { |
| 867 | add(parameter) |
| 868 | } |
| 869 | |
| 870 | return [...resolved.values()] |
| 871 | } |
| 872 | |
| 873 | const buildParameterSchema = < |
| 874 | Parameter extends { |
| 875 | readonly name: string |
| 876 | readonly required: boolean |
| 877 | readonly schema: {} |
| 878 | readonly in?: "path" | "query" | "header" | "cookie" | undefined |
| 879 | } |
| 880 | >( |
| 881 | parameters: ReadonlyArray<Parameter>, |
| 882 | onAdded?: ((parameter: Parameter, added: Array<string>) => void) | undefined |
| 883 | ): { |
| 884 | readonly schema: JsonSchema.JsonSchema |
| 885 | readonly optional: boolean |
| 886 | } | undefined => { |
| 887 | if (parameters.length === 0) { |
| 888 | return |
| 889 | } |
| 890 | |
| 891 | const schema = { |
| 892 | type: "object" as JsonSchema.Type, |
| 893 | properties: {} as Record<string, JsonSchema.JsonSchema>, |
| 894 | required: [] as Array<string>, |
| 895 | additionalProperties: false |
| 896 | } |
| 897 | |
| 898 | for (const parameter of parameters) { |
| 899 | const paramSchema = parameter.schema as any |
| 900 | const added: Array<string> = [] |
| 901 | if ( |
| 902 | Predicate.isObject(paramSchema) && |
| 903 | "properties" in paramSchema && |
| 904 | Predicate.isObject(paramSchema.properties) |
| 905 | ) { |
| 906 | const required = "required" in paramSchema |
| 907 | ? paramSchema.required as Array<string> |
| 908 | : [] |
| 909 | |
| 910 | for (const [name, propertySchema] of Object.entries(paramSchema.properties)) { |
| 911 | const adjustedName = `${parameter.name}[${name}]` |
| 912 | Rec.assignProperty(schema.properties, adjustedName, propertySchema as JsonSchema.JsonSchema) |
| 913 | if (required.includes(name)) { |
| 914 | schema.required.push(adjustedName) |
| 915 | } |
| 916 | added.push(adjustedName) |
| 917 | } |
| 918 | } else { |
| 919 | Rec.assignProperty(schema.properties, parameter.name, parameter.schema as JsonSchema.JsonSchema) |
| 920 | if (parameter.required) { |
| 921 | schema.required.push(parameter.name) |
| 922 | } |
| 923 | added.push(parameter.name) |
| 924 | } |
| 925 | |
| 926 | onAdded?.(parameter, added) |
| 927 | } |
| 928 | |
| 929 | return { |
| 930 | schema, |
| 931 | optional: schema.required.length === 0 |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | const mediaTypeToSuffix = (contentType: string): string => { |
| 936 | const normalized = contentType.toLowerCase() |
| 937 | switch (normalized) { |
| 938 | case "application/json": |
| 939 | return "Json" |
| 940 | case "multipart/form-data": |
| 941 | return "FormData" |
| 942 | case "application/x-www-form-urlencoded": |
| 943 | return "FormUrlEncoded" |
| 944 | case "text/plain": |
| 945 | return "Text" |
| 946 | case "application/octet-stream": |
| 947 | return "Binary" |
| 948 | } |
| 949 | const suffix = Utils.identifier(contentType) |
| 950 | return suffix.length > 0 ? suffix : "Body" |
| 951 | } |
| 952 | |
| 953 | const makeMultipartSchemas = ( |
| 954 | spec: OpenAPISpec, |
| 955 | format: OpenApiGeneratorFormat, |
| 956 | resolveRef: (ref: string) => unknown |
| 957 | ) => { |
| 958 | const definitions = spec.components?.schemas ?? {} |
| 959 | const names = new Set(Object.keys(definitions)) |
| 960 | const allocate = (base: string): string => { |
| 961 | let candidate = base |
| 962 | let index = 2 |
| 963 | while (names.has(candidate)) { |
| 964 | candidate = `${base}${index}` |
| 965 | index += 1 |
| 966 | } |
| 967 | names.add(candidate) |
| 968 | return candidate |
| 969 | } |
| 970 | const output = { ...definitions } |
| 971 | const refs: MultipartSchemaRefs = format === "httpapi" |
| 972 | ? { |
| 973 | kind: "httpapi", |
| 974 | singleFile: allocate("__HttpApiMultipartSingleFile"), |
| 975 | files: allocate("__HttpApiMultipartFiles") |
| 976 | } |
| 977 | : { kind: "client", singleFile: allocate("__ClientMultipartFile") } |
| 978 | const singleFileRef = toDefinitionRef(refs.singleFile) |
| 979 | const filesRef = refs.kind === "httpapi" ? toDefinitionRef(refs.files) : undefined |
| 980 | Rec.assignProperty(output, refs.singleFile, { type: "string", format: "binary" }) |
| 981 | if (refs.kind === "httpapi") { |
| 982 | Rec.assignProperty(output, refs.files, { type: "array", items: { $ref: singleFileRef } }) |
| 983 | } |
| 984 | |
| 985 | const binaryComponents = new Map<string, boolean>() |
| 986 | const copies = new Map<string, string>() |
| 987 | const inlining = new Set<string>() |
| 988 | // Components reachable from a schema that is not a multipart body, filled in by `finish`. |
| 989 | let shared: ReadonlySet<string> = new Set() |
| 990 | |
| 991 | const hasBinary = (value: unknown, seen: Set<string>): boolean => { |
| 992 | if (Array.isArray(value)) return value.some((item) => hasBinary(item, seen)) |
| 993 | if (!Predicate.isObject(value)) return false |
| 994 | if (isMultipartBinaryFile(value)) return true |
| 995 | if (isComponentRef(value.$ref) && !seen.has(value.$ref)) { |
| 996 | seen.add(value.$ref) |
| 997 | if (hasBinary(resolveRef(value.$ref), seen)) return true |
| 998 | } |
| 999 | return Object.values(value).some((item) => hasBinary(item, seen)) |
| 1000 | } |
| 1001 | |
| 1002 | const isBinaryComponent = ($ref: string): boolean => { |
| 1003 | let binary = binaryComponents.get($ref) |
| 1004 | if (binary === undefined) { |
| 1005 | binary = hasBinary(resolveRef($ref), new Set([$ref])) |
| 1006 | binaryComponents.set($ref, binary) |
| 1007 | } |
| 1008 | return binary |
| 1009 | } |
| 1010 | |
| 1011 | // Copies a binary-bearing component to `<Name>Multipart`, leaving the original for JSON payloads. |
| 1012 | const copyComponent = ($ref: string): string => { |
| 1013 | let name = copies.get($ref) |
| 1014 | if (name === undefined) { |
| 1015 | name = allocate(`${JsonPointer.unescapeToken($ref.slice(componentRefPrefix.length))}Multipart`) |
| 1016 | copies.set($ref, name) |
| 1017 | Rec.assignProperty(output, name, visit(resolveRef($ref))) |
| 1018 | } |
| 1019 | return name |
| 1020 | } |
| 1021 | |
| 1022 | // The httpapi format inlines components that only multipart bodies use; reference siblings still apply. |
| 1023 | const inlineComponent = (value: Record<string, unknown>, $ref: string): unknown => { |
| 1024 | const { $ref: _, ...siblings } = value |
| 1025 | inlining.add($ref) |
| 1026 | const inlined = visit(resolveRef($ref)) |
| 1027 | inlining.delete($ref) |
| 1028 | return Object.keys(siblings).length === 0 ? inlined : { allOf: [inlined, visit(siblings)] } |
| 1029 | } |
| 1030 | |
| 1031 | // Follows component aliases so a reference to a binary string maps to the file schema too. |
| 1032 | const isBinaryFile = (value: unknown, seen: Set<string> = new Set()): boolean => { |
| 1033 | if (isMultipartBinaryFile(value)) return true |
| 1034 | if (!Predicate.isObject(value) || !isComponentRef(value.$ref) || seen.has(value.$ref)) return false |
| 1035 | seen.add(value.$ref) |
| 1036 | return isBinaryFile(resolveRef(value.$ref), seen) |
| 1037 | } |
| 1038 | |
| 1039 | const visit = (value: unknown): unknown => { |
| 1040 | if (Array.isArray(value)) return value.map(visit) |
| 1041 | if (!Predicate.isObject(value)) return value |
| 1042 | if (isBinaryFile(value)) return { $ref: singleFileRef } |
| 1043 | if ( |
| 1044 | filesRef !== undefined && isComponentRef(value.$ref) && !shared.has(value.$ref) && !inlining.has(value.$ref) |
| 1045 | ) { |
| 1046 | return inlineComponent(value, value.$ref) |
| 1047 | } |
| 1048 | const out = Rec.map(value, visit) |
| 1049 | if (isComponentRef(value.$ref) && isBinaryComponent(value.$ref)) { |
| 1050 | out.$ref = toDefinitionRef(copyComponent(value.$ref)) |
| 1051 | } |
| 1052 | if (filesRef !== undefined && isMultipartBinaryFiles(out, singleFileRef)) return { $ref: filesRef } |
| 1053 | return out |
| 1054 | } |
| 1055 | |
| 1056 | // Whether a component is shared is only known once every schema is registered, so `transform` hands |
| 1057 | // out a placeholder that `finish` fills in after parsing. |
| 1058 | const pending = new Map<JsonSchema.JsonSchema, JsonSchema.JsonSchema>() |
| 1059 | const transform = (schema: JsonSchema.JsonSchema): JsonSchema.JsonSchema => { |
| 1060 | const placeholder: JsonSchema.JsonSchema = {} |
| 1061 | pending.set(placeholder, schema) |
| 1062 | return placeholder |
| 1063 | } |
| 1064 | const finish = (schemas: Readonly<Record<string, JsonSchema.JsonSchema>>): void => { |
| 1065 | shared = collectComponentRefs(Object.values(schemas).filter((schema) => !pending.has(schema)), resolveRef) |
| 1066 | for (const [placeholder, schema] of pending) { |
| 1067 | Object.assign(placeholder, visit(schema)) |
| 1068 | } |
| 1069 | } |
| 1070 | |
| 1071 | return { refs, definitions: output, transform, finish } |
| 1072 | } |
| 1073 | |
| 1074 | const toDefinitionRef = (name: string): string => `#/$defs/${name.replaceAll("~", "~0").replaceAll("/", "~1")}` |
| 1075 | |
| 1076 | // Collects every component reachable from the schemas, following references through other components. |
| 1077 | // Only JSON Schema keywords that hold subschemas are walked, so a `$ref` inside `default`, `const` or |
| 1078 | // `examples` is treated as data. |
| 1079 | const collectComponentRefs = ( |
| 1080 | schemas: ReadonlyArray<JsonSchema.JsonSchema>, |
| 1081 | resolveRef: (ref: string) => unknown |
| 1082 | ): ReadonlySet<string> => { |
| 1083 | const seen = new Set<string>() |
| 1084 | const visit = (schema: unknown): void => { |
| 1085 | if (Array.isArray(schema)) { |
| 1086 | for (const item of schema) visit(item) |
| 1087 | return |
| 1088 | } |
| 1089 | if (!Predicate.isObject(schema)) return |
| 1090 | if (isComponentRef(schema.$ref) && !seen.has(schema.$ref)) { |
| 1091 | seen.add(schema.$ref) |
| 1092 | visit(resolveRef(schema.$ref)) |
| 1093 | } |
| 1094 | for (const key of subschemaKeywords) { |
| 1095 | visit(schema[key]) |
| 1096 | } |
| 1097 | for (const key of subschemaMapKeywords) { |
| 1098 | const map = schema[key] |
| 1099 | if (Predicate.isObject(map)) visit(Object.values(map)) |
| 1100 | } |
| 1101 | } |
| 1102 | for (const schema of schemas) visit(schema) |
| 1103 | return seen |
| 1104 | } |
| 1105 | |
| 1106 | const subschemaKeywords = [ |
| 1107 | "items", |
| 1108 | "prefixItems", |
| 1109 | "additionalItems", |
| 1110 | "additionalProperties", |
| 1111 | "unevaluatedItems", |
| 1112 | "unevaluatedProperties", |
| 1113 | "contains", |
| 1114 | "propertyNames", |
| 1115 | "contentSchema", |
| 1116 | "allOf", |
| 1117 | "anyOf", |
| 1118 | "oneOf", |
| 1119 | "not", |
| 1120 | "if", |
| 1121 | "then", |
| 1122 | "else" |
| 1123 | ] as const |
| 1124 | |
| 1125 | const subschemaMapKeywords = ["properties", "patternProperties", "dependentSchemas", "$defs", "definitions"] as const |
| 1126 | |
| 1127 | const componentRefPrefix = "#/components/schemas/" |
| 1128 | |
| 1129 | const isComponentRef = (value: unknown): value is string => |
| 1130 | typeof value === "string" && value.startsWith(componentRefPrefix) |
| 1131 | |
| 1132 | const isMultipartBinaryFile = (value: unknown): boolean => |
| 1133 | Predicate.isObject(value) && |
| 1134 | value.type === "string" && |
| 1135 | ( |
| 1136 | (typeof value.format === "string" && value.format.toLowerCase() === "binary") || |
| 1137 | (typeof value.contentEncoding === "string" && value.contentEncoding.toLowerCase() === "binary") |
| 1138 | ) |
| 1139 | |
| 1140 | const isMultipartBinaryFiles = (value: Record<string, unknown>, singleFileRef: string): boolean => { |
| 1141 | if (value.type !== "array") { |
| 1142 | return false |
| 1143 | } |
| 1144 | const items = value.items |
| 1145 | return isMultipartBinaryFile(items) || (Predicate.isObject(items) && items.$ref === singleFileRef) |
| 1146 | } |
| 1147 | |
| 1148 | const isJsonMediaType = (contentType: string): boolean => |
| 1149 | contentType === "application/json" || |
| 1150 | (contentType.startsWith("application/") && contentType.endsWith("+json")) |
| 1151 | |
| 1152 | const normalizeMediaType = (contentType: string): string => contentType.toLowerCase().split(";", 1)[0].trim() |
| 1153 | |
| 1154 | const isTextMediaType = (contentType: string): boolean => contentType.startsWith("text/") |
| 1155 | |
| 1156 | const binaryMediaTypes = new Set([ |
| 1157 | "application/octet-stream", |
| 1158 | "application/pdf", |
| 1159 | "application/zip", |
| 1160 | "application/gzip", |
| 1161 | "application/x-gzip", |
| 1162 | "application/x-tar", |
| 1163 | "application/x-zip-compressed" |
| 1164 | ]) |
| 1165 | |
| 1166 | const binaryMediaTypePrefixes = ["image/", "audio/", "video/", "font/"] |
| 1167 | |
| 1168 | const isBinaryMediaType = (contentType: string): boolean => |
| 1169 | binaryMediaTypes.has(contentType) || |
| 1170 | binaryMediaTypePrefixes.some((prefix) => contentType.startsWith(prefix)) || |
| 1171 | (contentType.startsWith("application/") && |
| 1172 | (contentType.includes("binary") || |
| 1173 | contentType.endsWith("+octet-stream") || |
| 1174 | contentType.endsWith("+zip") || |
| 1175 | contentType.endsWith("+gzip"))) |
| 1176 | |
| 1177 | const isBinarySchema = (schema: unknown): boolean => |
| 1178 | Predicate.isObject(schema) && |
| 1179 | ( |
| 1180 | (typeof schema.format === "string" && schema.format.toLowerCase() === "binary") || |
| 1181 | (typeof schema.contentEncoding === "string" && schema.contentEncoding.toLowerCase() === "binary") |
| 1182 | ) |
| 1183 | |
| 1184 | const isSuccessStatus = (status: string): boolean => { |
| 1185 | const statusMajorNumber = Number(status[0]) |
| 1186 | return !Number.isNaN(statusMajorNumber) && statusMajorNumber < 4 |
| 1187 | } |
| 1188 | |
| 1189 | // Response keys are emitted into generated identifiers, so anything other than |
| 1190 | // a status code, status range or `default` (such as `x-` extensions) is skipped. |
| 1191 | const isResponseStatus = (status: string): boolean => /^(?:[1-5]\d\d|[1-5]xx|default)$/i.test(status) |
| 1192 | |
| 1193 | const getRequestMediaTypeEncoding = ( |
| 1194 | contentType: string |
| 1195 | ): ParsedOperation.ParsedOperationMediaTypeEncoding | undefined => { |
| 1196 | const normalized = normalizeMediaType(contentType) |
| 1197 | if (isJsonMediaType(normalized)) { |
| 1198 | return "json" |
| 1199 | } |
| 1200 | if (normalized === "multipart/form-data") { |
| 1201 | return "multipart" |
| 1202 | } |
| 1203 | if (normalized === "application/x-www-form-urlencoded") { |
| 1204 | return "form-url-encoded" |
| 1205 | } |
| 1206 | if (isTextMediaType(normalized)) { |
| 1207 | return "text" |
| 1208 | } |
| 1209 | if (isBinaryMediaType(normalized)) { |
| 1210 | return "binary" |
| 1211 | } |
| 1212 | return |
| 1213 | } |
| 1214 | |
| 1215 | const getResponseMediaTypeEncoding = ( |
| 1216 | contentType: string |
| 1217 | ): ParsedOperation.ParsedOperationMediaTypeEncoding | undefined => { |
| 1218 | const normalized = normalizeMediaType(contentType) |
| 1219 | if (isJsonMediaType(normalized)) { |
| 1220 | return "json" |
| 1221 | } |
| 1222 | if (normalized === "application/x-www-form-urlencoded") { |
| 1223 | return "form-url-encoded" |
| 1224 | } |
| 1225 | if (isTextMediaType(normalized)) { |
| 1226 | return "text" |
| 1227 | } |
| 1228 | if (isBinaryMediaType(normalized)) { |
| 1229 | return "binary" |
| 1230 | } |
| 1231 | return |
| 1232 | } |
| 1233 | |
| 1234 | const getEffectStreamEncoding = (mediaType: object): "uint8array" | "sse" | "ndjson" | undefined => { |
| 1235 | const stream = (mediaType as Record<string, unknown>)["x-effect-stream"] |
| 1236 | if (!Predicate.isObject(stream)) { |
| 1237 | return |
| 1238 | } |
| 1239 | return stream.encoding === "uint8array" || stream.encoding === "sse" || stream.encoding === "ndjson" |
| 1240 | ? stream.encoding |
| 1241 | : undefined |
| 1242 | } |
| 1243 | |
| 1244 | const ndjsonMediaTypes = new Set(["application/x-ndjson", "application/jsonl"]) |
| 1245 | |
| 1246 | const unsupportedStreamingRequestMediaTypes = new Set(["application/json-seq", "text/event-stream"]) |
| 1247 | |
| 1248 | // Effect specs mark NDJSON with x-effect-stream on any content type. Other specs |
| 1249 | // use an OpenAPI 3.2 itemSchema on an NDJSON or JSONL content type. |
| 1250 | const getNdjsonElementSchema = (contentType: string, mediaType: object): JsonSchema.JsonSchema | undefined => { |
| 1251 | const record = mediaType as Record<string, unknown> |
| 1252 | if (getEffectStreamEncoding(mediaType) === "ndjson") { |
| 1253 | return Predicate.isObject(record.schema) ? record.schema as JsonSchema.JsonSchema : undefined |
| 1254 | } |
| 1255 | if ( |
| 1256 | Predicate.isUndefined(record["x-effect-stream"]) && |
| 1257 | ndjsonMediaTypes.has(normalizeMediaType(contentType)) && |
| 1258 | Predicate.isObject(record.itemSchema) |
| 1259 | ) { |
| 1260 | return record.itemSchema as JsonSchema.JsonSchema |
| 1261 | } |
| 1262 | return |
| 1263 | } |
| 1264 | |
| 1265 | const getEffectStreamErrorSchema = (mediaType: object): JsonSchema.JsonSchema | undefined => { |
| 1266 | const stream = (mediaType as Record<string, unknown>)["x-effect-stream"] |
| 1267 | if (!Predicate.isObject(stream) || !Predicate.isObject(stream.errorSchema)) { |
| 1268 | return |
| 1269 | } |
| 1270 | return stream.errorSchema as JsonSchema.JsonSchema |
| 1271 | } |
| 1272 | |
| 1273 | const makeSseEventSchema = ( |
| 1274 | input: JsonSchema.JsonSchema, |
| 1275 | failureEvent: string | undefined |
| 1276 | ): JsonSchema.JsonSchema => { |
| 1277 | const eventSchema = normalizeSseEventSchema(input) |
| 1278 | if (failureEvent === undefined) { |
| 1279 | return eventSchema |
| 1280 | } |
| 1281 | return { |
| 1282 | anyOf: [ |
| 1283 | eventSchema, |
| 1284 | { |
| 1285 | type: "object", |
| 1286 | properties: { |
| 1287 | id: { type: "string" }, |
| 1288 | event: { const: failureEvent }, |
| 1289 | data: { type: "string" } |
| 1290 | }, |
| 1291 | required: ["event", "data"], |
| 1292 | additionalProperties: false |
| 1293 | } |
| 1294 | ] |
| 1295 | } |
| 1296 | } |
| 1297 | |
| 1298 | const normalizeSseEventSchema = (input: JsonSchema.JsonSchema): JsonSchema.JsonSchema => { |
| 1299 | const schema = { ...input } as Record<string, any> |
| 1300 | for (const key of ["allOf", "anyOf", "oneOf"] as const) { |
| 1301 | if (Array.isArray(schema[key])) { |
| 1302 | schema[key] = schema[key].map(normalizeSseEventSchema) |
| 1303 | } |
| 1304 | } |
| 1305 | if ( |
| 1306 | schema.type !== "object" || |
| 1307 | !Predicate.isObject(schema.properties) || |
| 1308 | !Object.hasOwn(schema.properties, "id") || |
| 1309 | !Object.hasOwn(schema.properties, "event") || |
| 1310 | !Object.hasOwn(schema.properties, "data") |
| 1311 | ) { |
| 1312 | return schema as JsonSchema.JsonSchema |
| 1313 | } |
| 1314 | |
| 1315 | // OpenAPI represents `undefined` as required nullable; restore the SSE parser's optional wire field. |
| 1316 | schema.properties = { |
| 1317 | ...schema.properties, |
| 1318 | id: { type: "string" } |
| 1319 | } |
| 1320 | if (Array.isArray(schema.required)) { |
| 1321 | schema.required = schema.required.filter((name: unknown) => name !== "id") |
| 1322 | } |
| 1323 | return schema as JsonSchema.JsonSchema |
| 1324 | } |
| 1325 | |
| 1326 | const primitiveSchemaTypes = new Set(["string", "number", "integer", "boolean", "null"]) |
| 1327 | |
| 1328 | const isPrimitiveValue = (value: unknown): boolean => |
| 1329 | value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" |
| 1330 | |
| 1331 | // Cookie values are serialized with `String(value)`, so only schemas whose |
| 1332 | // values are always primitives can be represented. |
| 1333 | const isPrimitiveSchema = ( |
| 1334 | input: unknown, |
| 1335 | resolveRef: (ref: string) => unknown, |
| 1336 | ancestors: Set<unknown> = new Set() |
| 1337 | ): boolean => { |
| 1338 | const schema = resolveReference(input, resolveRef) |
| 1339 | if (!Predicate.isObject(schema) || ancestors.has(schema)) { |
| 1340 | return false |
| 1341 | } |
| 1342 | ancestors.add(schema) |
| 1343 | const members = [schema.anyOf, schema.oneOf, schema.allOf].filter(Array.isArray).flat() |
| 1344 | const membersArePrimitive = members.every((member) => isPrimitiveSchema(member, resolveRef, ancestors)) |
| 1345 | ancestors.delete(schema) |
| 1346 | if (!membersArePrimitive) { |
| 1347 | return false |
| 1348 | } |
| 1349 | if (schema.type !== undefined) { |
| 1350 | const types: ReadonlyArray<unknown> = Array.isArray(schema.type) ? schema.type : [schema.type] |
| 1351 | return types.every((type) => primitiveSchemaTypes.has(type as string)) |
| 1352 | } |
| 1353 | if (Array.isArray(schema.enum)) { |
| 1354 | return schema.enum.every(isPrimitiveValue) |
| 1355 | } |
| 1356 | if ("const" in schema) { |
| 1357 | return isPrimitiveValue(schema.const) |
| 1358 | } |
| 1359 | return members.length > 0 |
| 1360 | } |
| 1361 | |
| 1362 | const resolveReference = (input: unknown, resolveRef: (ref: string) => unknown): any => { |
| 1363 | let current = input |
| 1364 | while (Predicate.isObject(current) && typeof current.$ref === "string") { |
| 1365 | current = resolveRef(current.$ref) |
| 1366 | } |
| 1367 | return current |
| 1368 | } |
| 1369 | |
| 1370 | const cloneSecurityRequirements = ( |
| 1371 | security: ReadonlyArray<Record<string, ReadonlyArray<string>>> |
| 1372 | ): Array<ParsedOperation.ParsedOperationSecurityRequirement> => |
| 1373 | security.map((requirement) => |
| 1374 | Object.fromEntries( |
| 1375 | Object.entries(requirement).map(([name, scopes]) => [name, [...scopes]]) |
| 1376 | ) |
| 1377 | ) |
| 1378 | |
| 1379 | const parseSecuritySchemes = ( |
| 1380 | spec: OpenAPISpec, |
| 1381 | resolveRef: (ref: string) => unknown |
| 1382 | ): Array<ParsedOperation.ParsedOpenApiSecurityScheme> => { |
| 1383 | const securitySchemes = spec.components?.securitySchemes ?? {} |
| 1384 | const parsed: Array<ParsedOperation.ParsedOpenApiSecurityScheme> = [] |
| 1385 | |
| 1386 | for (const [name, value] of Object.entries(securitySchemes)) { |
| 1387 | const scheme = resolveReference(value, resolveRef) as OpenAPISecurityScheme | undefined |
| 1388 | if (!Predicate.isObject(scheme)) { |
| 1389 | continue |
| 1390 | } |
| 1391 | |
| 1392 | if (scheme.type === "http" && typeof scheme.scheme === "string") { |
| 1393 | const normalizedScheme = scheme.scheme.toLowerCase() |
| 1394 | if (normalizedScheme === "basic") { |
| 1395 | parsed.push({ |
| 1396 | name, |
| 1397 | type: "basic", |
| 1398 | description: Utils.nonEmptyString(scheme.description), |
| 1399 | bearerFormat: undefined, |
| 1400 | scheme: undefined, |
| 1401 | key: undefined, |
| 1402 | in: undefined |
| 1403 | }) |
| 1404 | } else if (normalizedScheme === "bearer") { |
| 1405 | parsed.push({ |
| 1406 | name, |
| 1407 | type: "bearer", |
| 1408 | description: Utils.nonEmptyString(scheme.description), |
| 1409 | bearerFormat: Utils.nonEmptyString(scheme.bearerFormat), |
| 1410 | scheme: undefined, |
| 1411 | key: undefined, |
| 1412 | in: undefined |
| 1413 | }) |
| 1414 | } else { |
| 1415 | parsed.push({ |
| 1416 | name, |
| 1417 | type: "http", |
| 1418 | description: Utils.nonEmptyString(scheme.description), |
| 1419 | bearerFormat: Utils.nonEmptyString(scheme.bearerFormat), |
| 1420 | scheme: scheme.scheme, |
| 1421 | key: undefined, |
| 1422 | in: undefined |
| 1423 | }) |
| 1424 | } |
| 1425 | continue |
| 1426 | } |
| 1427 | |
| 1428 | if ( |
| 1429 | scheme.type === "apiKey" && |
| 1430 | (scheme.in === "header" || scheme.in === "query" || scheme.in === "cookie") && |
| 1431 | typeof scheme.name === "string" |
| 1432 | ) { |
| 1433 | parsed.push({ |
| 1434 | name, |
| 1435 | type: "apiKey", |
| 1436 | description: Utils.nonEmptyString(scheme.description), |
| 1437 | bearerFormat: undefined, |
| 1438 | scheme: undefined, |
| 1439 | key: scheme.name, |
| 1440 | in: scheme.in |
| 1441 | }) |
| 1442 | } |
| 1443 | } |
| 1444 | |
| 1445 | return parsed |
| 1446 | } |
| 1447 | |
| 1448 | const warnForAndSecurityRequirements = ( |
| 1449 | emitWarning: WarningEmitter, |
| 1450 | operation: ParsedOperation.ParsedOperation |
| 1451 | ): void => { |
| 1452 | if (operation.effectiveSecurity.some((requirement) => Object.keys(requirement).length === 0)) { |
| 1453 | return |
| 1454 | } |
| 1455 | for (const requirement of operation.effectiveSecurity) { |
| 1456 | const schemes = Object.keys(requirement) |
| 1457 | if (schemes.length <= 1) { |
| 1458 | continue |
| 1459 | } |
| 1460 | warnForOperation(emitWarning, operation, { |
| 1461 | code: "security-and-downgraded", |
| 1462 | message: `Security requirement requiring all of [${ |
| 1463 | schemes.join(", ") |
| 1464 | }] was downgraded to a placeholder middleware.` |
| 1465 | }) |
| 1466 | } |
| 1467 | } |
| 1468 | |
| 1469 | const hasUnsupportedSuccessfulSseResponse = ( |
| 1470 | responses: ReadonlyArray<readonly [string, unknown]>, |
| 1471 | hasExplicitSuccessResponse: boolean |
| 1472 | ): boolean => { |
| 1473 | for (const [status, response] of responses) { |
| 1474 | if (!Predicate.isObject(response)) { |
| 1475 | continue |
| 1476 | } |
| 1477 | const remappedStatus = remapDefaultResponseStatusForHttpApi(status, hasExplicitSuccessResponse) |
| 1478 | const statusCode = Number(remappedStatus) |
| 1479 | if (Number.isNaN(statusCode) || statusCode >= 400) { |
| 1480 | continue |
| 1481 | } |
| 1482 | |
| 1483 | const content = Predicate.isObject(response.content) |
| 1484 | ? response.content as Record<string, any> |
| 1485 | : undefined |
| 1486 | if (Predicate.isUndefined(content)) { |
| 1487 | continue |
| 1488 | } |
| 1489 | |
| 1490 | for (const [contentType, mediaType] of Object.entries(content)) { |
| 1491 | if (!Predicate.isObject(mediaType)) { |
| 1492 | continue |
| 1493 | } |
| 1494 | const streamEncoding = getEffectStreamEncoding(mediaType) |
| 1495 | if (streamEncoding === "sse") { |
| 1496 | if (Predicate.isUndefined(mediaType.schema) || Predicate.isUndefined(getEffectStreamErrorSchema(mediaType))) { |
| 1497 | return true |
| 1498 | } |
| 1499 | continue |
| 1500 | } |
| 1501 | if (contentType === "text/event-stream" && streamEncoding !== "ndjson") { |
| 1502 | return true |
| 1503 | } |
| 1504 | } |
| 1505 | } |
| 1506 | return false |
| 1507 | } |
| 1508 | |
| 1509 | const remapDefaultResponseStatusForHttpApi = (status: string, hasExplicitSuccessResponse: boolean): string => |
| 1510 | status === "default" ? (hasExplicitSuccessResponse ? "500" : "200") : status |
| 1511 | |
| 1512 | const methodSupportsRequestBody = (method: Lowercase<HttpMethod>): boolean => |
| 1513 | method !== "get" && method !== "head" && method !== "options" && method !== "trace" |
| 1514 | |
| 1515 | const warnForOperation = ( |
| 1516 | emitWarning: WarningEmitter, |
| 1517 | operation: ParsedOperation.ParsedOperation, |
| 1518 | warning: { |
| 1519 | readonly code: OpenApiGeneratorWarningCode |
| 1520 | readonly message: string |
| 1521 | } |
| 1522 | ): void => { |
| 1523 | emitWarning({ |
| 1524 | ...warning, |
| 1525 | path: operation.path, |
| 1526 | method: operation.method, |
| 1527 | operationId: operation.operationId |
| 1528 | }) |
| 1529 | } |
| 1530 | |
| 1531 | function getDialect(spec: OpenAPISpec): "openapi-3.0" | "openapi-3.1" { |
| 1532 | return spec.openapi.trim().startsWith("3.0") ? "openapi-3.0" : "openapi-3.1" |
| 1533 | } |
| 1534 | |
| 1535 | /** |
| 1536 | * Layer providing an OpenAPI generator for Schema-backed HTTP client and HttpApi output. |
| 1537 | * |
| 1538 | * @category layers |
| 1539 | * @since 4.0.0 |
| 1540 | */ |
| 1541 | export const layerTransformerSchema: Layer.Layer<OpenApiGenerator> = Layer.effect(OpenApiGenerator, make) |
| 1542 | |
| 1543 | /** |
| 1544 | * Layer providing an OpenAPI generator for type-only HTTP client output. |
| 1545 | * |
| 1546 | * @category layers |
| 1547 | * @since 4.0.0 |
| 1548 | */ |
| 1549 | export const layerTransformerTs: Layer.Layer<OpenApiGenerator> = Layer.effect(OpenApiGenerator, make) |
| 1550 | |
| 1551 | const isSwaggerSpec = (spec: OpenAPISpec) => "swagger" in spec |
| 1552 | |
| 1553 | const convertSwaggerSpec = Effect.fn((spec: OpenAPISpec) => |
| 1554 | Effect.callback<OpenAPISpec>((resume) => { |
| 1555 | SwaggerToOpenApi.convertObj( |
| 1556 | spec as any, |
| 1557 | { laxDefaults: true, laxurls: true, patch: true, warnOnly: true }, |
| 1558 | (err, result) => { |
| 1559 | if (err) { |
| 1560 | resume(Effect.die(err)) |
| 1561 | } else { |
| 1562 | resume(Effect.succeed(result.openapi as any)) |
| 1563 | } |
| 1564 | } |
| 1565 | ) |
| 1566 | }).pipe(Effect.withSpan("OpenApi.convertSwaggerSpec")) |
| 1567 | ) |
| 1568 | |
| 1569 | const processPath = (path: string): { |
| 1570 | readonly pathIds: Array<string> |
| 1571 | readonly pathTemplate: string |
| 1572 | } => { |
| 1573 | const pathIds: Array<string> = [] |
| 1574 | const fragments: Array<string> = [] |
| 1575 | let offset = 0 |
| 1576 | for (const match of path.matchAll(/{([^}]+)}/g)) { |
| 1577 | fragments.push(JSON.stringify(path.slice(offset, match.index))) |
| 1578 | const id = Utils.camelize(match[1]) |
| 1579 | pathIds.push(id) |
| 1580 | fragments.push(`__encodePathParam(${id})`) |
| 1581 | offset = match.index + match[0].length |
| 1582 | } |
| 1583 | fragments.push(JSON.stringify(path.slice(offset))) |
| 1584 | const pathTemplate = fragments.join(" + ") |
| 1585 | return { pathIds, pathTemplate } as const |
| 1586 | } |