@effect/openapi-generator 4.0.0-beta.8 → 4.0.0-beta.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/HttpApiTransformer.d.ts +41 -0
  2. package/dist/HttpApiTransformer.d.ts.map +1 -0
  3. package/dist/HttpApiTransformer.js +383 -0
  4. package/dist/HttpApiTransformer.js.map +1 -0
  5. package/dist/JsonSchemaGenerator.d.ts +25 -3
  6. package/dist/JsonSchemaGenerator.d.ts.map +1 -1
  7. package/dist/JsonSchemaGenerator.js +178 -47
  8. package/dist/JsonSchemaGenerator.js.map +1 -1
  9. package/dist/OpenApiGenerator.d.ts +81 -7
  10. package/dist/OpenApiGenerator.d.ts.map +1 -1
  11. package/dist/OpenApiGenerator.js +707 -119
  12. package/dist/OpenApiGenerator.js.map +1 -1
  13. package/dist/OpenApiPatch.d.ts +47 -24
  14. package/dist/OpenApiPatch.d.ts.map +1 -1
  15. package/dist/OpenApiPatch.js +42 -19
  16. package/dist/OpenApiPatch.js.map +1 -1
  17. package/dist/OpenApiTransformer.d.ts +85 -12
  18. package/dist/OpenApiTransformer.d.ts.map +1 -1
  19. package/dist/OpenApiTransformer.js +85 -8
  20. package/dist/OpenApiTransformer.js.map +1 -1
  21. package/dist/ParsedOperation.d.ts +172 -1
  22. package/dist/ParsedOperation.d.ts.map +1 -1
  23. package/dist/ParsedOperation.js +32 -0
  24. package/dist/ParsedOperation.js.map +1 -1
  25. package/dist/Utils.d.ts +51 -0
  26. package/dist/Utils.d.ts.map +1 -1
  27. package/dist/Utils.js +61 -0
  28. package/dist/Utils.js.map +1 -1
  29. package/dist/main.d.ts +12 -0
  30. package/dist/main.d.ts.map +1 -1
  31. package/dist/main.js +41 -8
  32. package/dist/main.js.map +1 -1
  33. package/package.json +10 -8
  34. package/src/HttpApiTransformer.ts +538 -0
  35. package/src/JsonSchemaGenerator.ts +272 -47
  36. package/src/OpenApiGenerator.ts +994 -173
  37. package/src/OpenApiPatch.ts +56 -31
  38. package/src/OpenApiTransformer.ts +89 -12
  39. package/src/ParsedOperation.ts +220 -1
  40. package/src/Utils.ts +61 -0
  41. package/src/main.ts +58 -10
@@ -1,19 +1,46 @@
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";
1
14
  import * as Effect from "effect/Effect";
2
15
  import * as Layer from "effect/Layer";
3
16
  import * as Predicate from "effect/Predicate";
4
- import * as ServiceMap from "effect/ServiceMap";
5
17
  import * as String from "effect/String";
6
18
  import SwaggerToOpenApi from "swagger2openapi";
19
+ import * as HttpApiTransformer from "./HttpApiTransformer.js";
7
20
  import * as JsonSchemaGenerator from "./JsonSchemaGenerator.js";
8
21
  import * as OpenApiTransformer from "./OpenApiTransformer.js";
9
22
  import * as ParsedOperation from "./ParsedOperation.js";
10
23
  import * as Utils from "./Utils.js";
11
- export class OpenApiGenerator extends /*#__PURE__*/ServiceMap.Service()("OpenApiGenerator") {}
24
+ /**
25
+ * Service for turning OpenAPI or Swagger specifications into generated Effect
26
+ * HTTP client or HttpApi source code.
27
+ *
28
+ * @category services
29
+ * @since 4.0.0
30
+ */
31
+ export class OpenApiGenerator extends /*#__PURE__*/Context.Service()("OpenApiGenerator") {}
12
32
  const methodNames = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
33
+ /**
34
+ * Constructs the OpenAPI generator service implementation.
35
+ *
36
+ * @category constructors
37
+ * @since 4.0.0
38
+ */
13
39
  export const make = /*#__PURE__*/Effect.gen(function* () {
14
40
  const generate = Effect.fn(function* (spec, options) {
15
41
  const generator = JsonSchemaGenerator.make();
16
42
  const openApiTransformer = yield* OpenApiTransformer.OpenApiTransformer;
43
+ const emitWarning = makeWarningEmitter(options);
17
44
  // If we receive a Swagger 2.0 spec, convert it to an OpenApi 3.0 spec
18
45
  if (isSwaggerSpec(spec)) {
19
46
  spec = yield* convertSwaggerSpec(spec);
@@ -26,154 +53,715 @@ export const make = /*#__PURE__*/Effect.gen(function* () {
26
53
  }
27
54
  return current;
28
55
  }
29
- const operations = [];
30
- function handlePath(path, methods) {
31
- for (const method of methodNames) {
32
- const operation = methods[method];
33
- if (Predicate.isUndefined(operation)) {
34
- continue;
35
- }
36
- const id = operation.operationId ? Utils.camelize(operation.operationId) : `${method.toUpperCase()}${path}`;
37
- const description = Utils.nonEmptyString(operation.description) ?? Utils.nonEmptyString(operation.summary);
38
- const {
39
- pathIds,
40
- pathTemplate
41
- } = processPath(path);
42
- const op = ParsedOperation.makeDeepMutable({
43
- id,
44
- method,
45
- description,
46
- pathIds,
47
- pathTemplate
56
+ const multipartSchemaRefs = options.format === "httpapi" ? makeHttpApiMultipartSchemaRefs(spec.components?.schemas ?? {}) : undefined;
57
+ const parsed = parseOpenApi(spec, generator, resolveRef, options.format, emitWarning, multipartSchemaRefs);
58
+ // TODO: make a CLI option ?
59
+ const importName = "Schema";
60
+ const source = getDialect(spec);
61
+ const generation = options.format === "httpapi" ? generator.generateHttpApi(source, withHttpApiMultipartSchemas(spec.components?.schemas ?? {}, multipartSchemaRefs), {
62
+ onEnter: options.onEnter,
63
+ multipartSchemaRefs
64
+ }) : generator.generate(source, spec.components?.schemas ?? {}, options.format === "httpclient-type-only", {
65
+ onEnter: options.onEnter
66
+ });
67
+ if (options.format === "httpapi") {
68
+ const needsMultipartImport = generation.includes("Multipart.");
69
+ return String.stripMargin(`|${HttpApiTransformer.imports(importName, {
70
+ multipart: needsMultipartImport
71
+ })}
72
+ |${generation}
73
+ |${HttpApiTransformer.toImplementation(importName, options.name, parsed)}`);
74
+ }
75
+ return String.stripMargin(`|${openApiTransformer.imports(importName, parsed)}
76
+ |${generation}
77
+ |${openApiTransformer.toImplementation(importName, options.name, parsed)}
78
+ |
79
+ |${openApiTransformer.toTypes(importName, options.name, parsed)}`);
80
+ }, (effect, _, options) => Effect.provideServiceEffect(effect, OpenApiTransformer.OpenApiTransformer, options.format === "httpclient-type-only" ? Effect.sync(OpenApiTransformer.makeTransformerTs) : Effect.sync(OpenApiTransformer.makeTransformerSchema)));
81
+ return {
82
+ generate
83
+ };
84
+ });
85
+ const makeWarningEmitter = options => warning => {
86
+ options.onWarning?.(warning);
87
+ };
88
+ const parseOpenApi = (spec, generator, resolveRef, format, emitWarning, multipartSchemaRefs) => {
89
+ const operations = [];
90
+ const reservedSchemaNames = new Set(Object.keys(spec.components?.schemas ?? {}));
91
+ const isHttpApi = format === "httpapi";
92
+ const securitySchemes = isHttpApi ? parseSecuritySchemes(spec, resolveRef) : [];
93
+ const addSchema = (baseName, schema, operation) => {
94
+ let candidate = baseName;
95
+ let index = 2;
96
+ while (reservedSchemaNames.has(candidate)) {
97
+ candidate = `${baseName}${index}`;
98
+ index += 1;
99
+ }
100
+ if (candidate !== baseName) {
101
+ warnForOperation(emitWarning, operation, {
102
+ code: "naming-collision",
103
+ message: `Schema name "${baseName}" collided with an existing name and was renamed to "${candidate}".`
104
+ });
105
+ }
106
+ reservedSchemaNames.add(candidate);
107
+ return generator.addSchema(candidate, schema);
108
+ };
109
+ for (const [path, methods] of Object.entries(spec.paths)) {
110
+ for (const method of methodNames) {
111
+ const operation = methods[method];
112
+ if (Predicate.isUndefined(operation)) {
113
+ continue;
114
+ }
115
+ const id = operation.operationId ? Utils.camelize(operation.operationId) : `${method.toUpperCase()}${path}`;
116
+ const description = Utils.nonEmptyString(operation.description) ?? Utils.nonEmptyString(operation.summary);
117
+ const {
118
+ pathIds,
119
+ pathTemplate
120
+ } = processPath(path);
121
+ const op = ParsedOperation.makeDeepMutable({
122
+ id,
123
+ method,
124
+ description,
125
+ pathIds,
126
+ pathTemplate
127
+ });
128
+ op.path = path;
129
+ op.operationId = Utils.nonEmptyString(operation.operationId);
130
+ op.tags = [...(operation.tags ?? [])];
131
+ if (isHttpApi && op.tags.length > 1) {
132
+ warnForOperation(emitWarning, op, {
133
+ code: "additional-tags-dropped",
134
+ message: `Additional tags (${op.tags.slice(1).join(", ")}) were dropped. Only the first tag ("${op.tags[0]}") is used for grouping.`
48
135
  });
49
- const schemaId = Utils.identifier(operation.operationId ?? path);
50
- const validParameters = operation.parameters?.filter(param => {
51
- return param.in !== "path" && param.in !== "cookie";
52
- }) ?? [];
53
- if (validParameters.length > 0) {
54
- const schema = {
55
- type: "object",
56
- properties: {},
57
- required: [],
58
- additionalProperties: false
59
- };
60
- for (let parameter of validParameters) {
61
- if ("$ref" in parameter) {
62
- parameter = resolveRef(parameter.$ref);
136
+ }
137
+ op.metadata = {
138
+ summary: Utils.nonEmptyString(operation.summary),
139
+ description: Utils.nonEmptyString(operation.description),
140
+ deprecated: operation.deprecated === true,
141
+ externalDocs: operation.externalDocs
142
+ };
143
+ op.effectiveSecurity = cloneSecurityRequirements(operation.security ?? spec.security ?? []);
144
+ if (isHttpApi) {
145
+ warnForAndSecurityRequirements(emitWarning, op);
146
+ }
147
+ const schemaId = Utils.identifier(operation.operationId ?? path);
148
+ const pathParameters = Predicate.isObject(methods) && Array.isArray(methods.parameters) ? methods.parameters : undefined;
149
+ const parameters = resolveOperationParameters(pathParameters, Array.isArray(operation.parameters) ? operation.parameters : undefined, resolveRef);
150
+ for (const parameter of parameters) {
151
+ const parsedParameter = {
152
+ name: parameter.name,
153
+ in: parameter.in,
154
+ required: parameter.required === true,
155
+ description: Utils.nonEmptyString(parameter.description),
156
+ schema: parameter.schema
157
+ };
158
+ switch (parameter.in) {
159
+ case "path":
160
+ {
161
+ op.parameters.path.push(parsedParameter);
162
+ break;
63
163
  }
64
- if (parameter.in === "path") {
164
+ case "query":
165
+ {
166
+ op.parameters.query.push(parsedParameter);
167
+ break;
168
+ }
169
+ case "header":
170
+ {
171
+ op.parameters.header.push(parsedParameter);
172
+ break;
173
+ }
174
+ case "cookie":
175
+ {
176
+ op.parameters.cookie.push(parsedParameter);
177
+ warnForOperation(emitWarning, op, {
178
+ code: "cookie-parameter-dropped",
179
+ message: `Cookie parameter "${parameter.name}" was dropped because non-security cookie parameters are not supported.`
180
+ });
181
+ break;
182
+ }
183
+ }
184
+ }
185
+ const requestBody = resolveReference(operation.requestBody, resolveRef);
186
+ if (isHttpApi && !methodSupportsRequestBody(op.method) && Predicate.isObject(requestBody)) {
187
+ warnForOperation(emitWarning, op, {
188
+ code: "no-body-method-request-body-skipped",
189
+ message: `Operation was skipped because ${op.method.toUpperCase()} does not support request bodies.`
190
+ });
191
+ continue;
192
+ }
193
+ const resolvedResponses = Object.entries(operation.responses ?? {}).map(([status, response]) => [status, resolveReference(response, resolveRef)]);
194
+ const hasExplicitSuccessResponse = resolvedResponses.some(([status]) => {
195
+ if (!/^\d{3}$/.test(status)) {
196
+ return false;
197
+ }
198
+ return Number(status) < 400;
199
+ });
200
+ if (isHttpApi && hasSuccessfulSseResponse(resolvedResponses, hasExplicitSuccessResponse)) {
201
+ warnForOperation(emitWarning, op, {
202
+ code: "sse-operation-skipped",
203
+ message: "Operation was skipped because successful text/event-stream responses are not supported in HttpApi generation."
204
+ });
205
+ continue;
206
+ }
207
+ const validParameters = parameters.filter(parameter => parameter.in !== "path" && parameter.in !== "cookie");
208
+ const combinedParameterSchema = buildParameterSchema(validParameters, (parameter, added) => {
209
+ if (parameter.in === "query") {
210
+ Utils.spreadElementsInto(added, op.urlParams);
211
+ } else if (parameter.in === "header") {
212
+ Utils.spreadElementsInto(added, op.headers);
213
+ } else if (parameter.in === "cookie") {
214
+ Utils.spreadElementsInto(added, op.cookies);
215
+ }
216
+ });
217
+ if (combinedParameterSchema !== undefined) {
218
+ op.params = addSchema(`${schemaId}Params`, combinedParameterSchema.schema, op);
219
+ op.paramsOptional = combinedParameterSchema.optional;
220
+ }
221
+ if (isHttpApi) {
222
+ const pathParameterSchema = buildParameterSchema(op.parameters.path);
223
+ if (pathParameterSchema !== undefined) {
224
+ op.pathSchema = addSchema(`${schemaId}PathParams`, pathParameterSchema.schema, op);
225
+ }
226
+ const queryParameterSchema = buildParameterSchema(op.parameters.query);
227
+ if (queryParameterSchema !== undefined) {
228
+ op.querySchema = addSchema(`${schemaId}Query`, queryParameterSchema.schema, op);
229
+ op.querySchemaOptional = queryParameterSchema.optional;
230
+ }
231
+ const headerParameterSchema = buildParameterSchema(op.parameters.header);
232
+ if (headerParameterSchema !== undefined) {
233
+ op.headersSchema = addSchema(`${schemaId}Headers`, headerParameterSchema.schema, op);
234
+ op.headersSchemaOptional = headerParameterSchema.optional;
235
+ }
236
+ }
237
+ if (Predicate.isNotUndefined(requestBody) && Predicate.isObject(requestBody)) {
238
+ const content = Predicate.isObject(requestBody.content) ? requestBody.content : {};
239
+ const requestSchemaNames = new Map();
240
+ op.requestBody = {
241
+ required: requestBody.required === true,
242
+ contentTypes: Object.keys(content)
243
+ };
244
+ if (isHttpApi && requestBody.required === false) {
245
+ warnForOperation(emitWarning, op, {
246
+ code: "optional-request-body-approximated",
247
+ message: "Optional request body was approximated by adding a no-content payload alternative."
248
+ });
249
+ }
250
+ if (Predicate.isNotUndefined(content["application/json"]?.schema)) {
251
+ op.payload = addSchema(`${schemaId}RequestJson`, content["application/json"].schema, op);
252
+ requestSchemaNames.set("application/json", op.payload);
253
+ }
254
+ if (Predicate.isNotUndefined(content["multipart/form-data"]?.schema)) {
255
+ op.payload = addSchema(`${schemaId}RequestFormData`, transformMultipartSchema(content["multipart/form-data"].schema, multipartSchemaRefs, resolveRef), op);
256
+ op.payloadFormData = true;
257
+ requestSchemaNames.set("multipart/form-data", op.payload);
258
+ }
259
+ if (Predicate.isNotUndefined(content["application/x-www-form-urlencoded"]?.schema)) {
260
+ op.payload = addSchema(`${schemaId}RequestFormUrlEncoded`, content["application/x-www-form-urlencoded"].schema, op);
261
+ op.payloadFormUrlEncoded = true;
262
+ requestSchemaNames.set("application/x-www-form-urlencoded", op.payload);
263
+ }
264
+ if (isHttpApi) {
265
+ const representableRequestBody = [];
266
+ for (const [contentType, mediaType] of Object.entries(content)) {
267
+ if (!Predicate.isObject(mediaType) || Predicate.isUndefined(mediaType.schema)) {
65
268
  continue;
66
269
  }
67
- const paramSchema = parameter.schema;
68
- const added = [];
69
- if ("properties" in paramSchema && Predicate.isObject(paramSchema.properties)) {
70
- const required = "required" in paramSchema ? paramSchema.required : [];
71
- for (const [name, propSchema] of Object.entries(paramSchema.properties)) {
72
- const adjustedName = `${parameter.name}[${name}]`;
73
- schema.properties[adjustedName] = propSchema;
74
- if (required.includes(name)) {
75
- schema.required.push(adjustedName);
76
- }
77
- added.push(adjustedName);
78
- }
79
- } else {
80
- schema.properties[parameter.name] = parameter.schema;
81
- if (parameter.required) {
82
- schema.required.push(parameter.name);
83
- }
84
- added.push(parameter.name);
270
+ const encoding = getRequestMediaTypeEncoding(contentType);
271
+ if (encoding === undefined) {
272
+ continue;
85
273
  }
86
- if (parameter.in === "query") {
87
- Utils.spreadElementsInto(added, op.urlParams);
88
- } else if (parameter.in === "header") {
89
- Utils.spreadElementsInto(added, op.headers);
90
- } else if (parameter.in === "cookie") {
91
- Utils.spreadElementsInto(added, op.cookies);
274
+ let schemaName = requestSchemaNames.get(contentType);
275
+ if (schemaName === undefined) {
276
+ const schema = encoding === "multipart" ? transformMultipartSchema(mediaType.schema, multipartSchemaRefs, resolveRef) : mediaType.schema;
277
+ schemaName = addSchema(`${schemaId}Request${mediaTypeToSuffix(contentType)}`, schema, op);
278
+ requestSchemaNames.set(contentType, schemaName);
92
279
  }
280
+ representableRequestBody.push({
281
+ contentType,
282
+ encoding,
283
+ schema: schemaName
284
+ });
93
285
  }
94
- op.params = generator.addSchema(`${schemaId}Params`, schema);
95
- op.paramsOptional = !schema.required || schema.required.length === 0;
286
+ op.requestBodyRepresentable = representableRequestBody;
287
+ }
288
+ }
289
+ let defaultSchema;
290
+ for (const [status, response] of resolvedResponses) {
291
+ if (!Predicate.isObject(response)) {
292
+ continue;
96
293
  }
97
- if (Predicate.isNotUndefined(operation.requestBody?.content?.["application/json"]?.schema)) {
98
- op.payload = generator.addSchema(`${schemaId}RequestJson`, operation.requestBody.content["application/json"].schema);
294
+ const parsedStatus = isHttpApi ? remapDefaultResponseStatusForHttpApi(status, hasExplicitSuccessResponse) : status;
295
+ if (isHttpApi && status === "default") {
296
+ warnForOperation(emitWarning, op, {
297
+ code: "default-response-remapped",
298
+ message: `Default response was remapped to status ${parsedStatus} for HttpApi generation.`
299
+ });
99
300
  }
100
- if (Predicate.isNotUndefined(operation.requestBody?.content?.["multipart/form-data"]?.schema)) {
101
- op.payload = generator.addSchema(`${schemaId}RequestFormData`, operation.requestBody.content["multipart/form-data"].schema);
102
- op.payloadFormData = true;
301
+ const content = Predicate.isObject(response.content) ? response.content : undefined;
302
+ if (isHttpApi && Predicate.isNotUndefined(response.headers)) {
303
+ warnForOperation(emitWarning, op, {
304
+ code: "response-headers-ignored",
305
+ message: `Response headers on status ${status} were ignored in HttpApi generation.`
306
+ });
103
307
  }
104
- let defaultSchema;
105
- for (const entry of Object.entries(operation.responses ?? {})) {
106
- const status = entry[0];
107
- let response = entry[1];
108
- while ("$ref" in response) {
109
- response = resolveRef(response.$ref);
308
+ const representable = [];
309
+ let jsonSchemaName;
310
+ const jsonResponseSchema = content?.["application/json"]?.schema;
311
+ if (Predicate.isNotUndefined(jsonResponseSchema)) {
312
+ jsonSchemaName = addSchema(`${schemaId}${status}`, jsonResponseSchema, op);
313
+ if (isHttpApi) {
314
+ representable.push({
315
+ contentType: "application/json",
316
+ encoding: "json",
317
+ schema: jsonSchemaName
318
+ });
110
319
  }
111
- if (Predicate.isNotUndefined(response.content?.["application/json"]?.schema)) {
112
- const schemaName = generator.addSchema(`${schemaId}${status}`, response.content["application/json"].schema);
113
- if (status === "default") {
114
- defaultSchema = schemaName;
320
+ }
321
+ if (isHttpApi) {
322
+ for (const [contentType, mediaType] of Object.entries(content ?? {})) {
323
+ if (contentType === "application/json") {
115
324
  continue;
116
325
  }
117
- const statusLower = status.toLowerCase();
118
- const statusMajorNumber = Number(status[0]);
119
- if (Number.isNaN(statusMajorNumber)) {
326
+ if (!Predicate.isObject(mediaType) || Predicate.isUndefined(mediaType.schema)) {
120
327
  continue;
121
328
  }
122
- if (statusMajorNumber < 4) {
123
- op.successSchemas.set(statusLower, schemaName);
124
- } else {
125
- op.errorSchemas.set(statusLower, schemaName);
329
+ const encoding = getResponseMediaTypeEncoding(contentType);
330
+ if (encoding === undefined) {
331
+ continue;
126
332
  }
333
+ const schemaName = addSchema(`${schemaId}${status}${mediaTypeToSuffix(contentType)}`, mediaType.schema, op);
334
+ representable.push({
335
+ contentType,
336
+ encoding,
337
+ schema: schemaName
338
+ });
127
339
  }
128
- // Handle SSE streaming responses (text/event-stream)
129
- if (Predicate.isUndefined(op.sseSchema) && Predicate.isNotUndefined(response.content?.["text/event-stream"]?.schema)) {
130
- const statusMajorNumber = Number(status[0]);
131
- if (!Number.isNaN(statusMajorNumber) && statusMajorNumber < 4) {
132
- op.sseSchema = generator.addSchema(`${schemaId}${status}Sse`, response.content["text/event-stream"].schema);
133
- }
340
+ }
341
+ const isEmptyResponse = Predicate.isUndefined(content) || Object.keys(content).length === 0;
342
+ const parsedResponse = {
343
+ status: parsedStatus,
344
+ description: Utils.nonEmptyString(response.description),
345
+ contentTypes: Predicate.isNotUndefined(content) ? Object.keys(content) : [],
346
+ hasHeaders: Predicate.isNotUndefined(response.headers),
347
+ isEmpty: isEmptyResponse,
348
+ representable
349
+ };
350
+ op.responses.push(parsedResponse);
351
+ if (status === "default") {
352
+ op.defaultResponse = parsedResponse;
353
+ }
354
+ if (Predicate.isNotUndefined(jsonSchemaName)) {
355
+ const schemaName = jsonSchemaName;
356
+ if (status === "default" && !isHttpApi) {
357
+ defaultSchema = schemaName;
358
+ continue;
134
359
  }
135
- // Handle binary streaming responses (application/octet-stream)
136
- if (Predicate.isNotUndefined(response.content?.["application/octet-stream"])) {
137
- const statusMajorNumber = Number(status[0]);
138
- if (!Number.isNaN(statusMajorNumber) && statusMajorNumber < 4) {
139
- op.binaryResponse = true;
140
- }
360
+ const statusLower = parsedStatus.toLowerCase();
361
+ const statusMajorNumber = Number(parsedStatus[0]);
362
+ if (Number.isNaN(statusMajorNumber)) {
363
+ continue;
141
364
  }
142
- if (Predicate.isUndefined(response.content)) {
143
- if (status !== "default") {
144
- op.voidSchemas.add(status.toLowerCase());
145
- }
365
+ if (statusMajorNumber < 4) {
366
+ op.successSchemas.set(statusLower, schemaName);
367
+ } else {
368
+ op.errorSchemas.set(statusLower, schemaName);
369
+ }
370
+ }
371
+ const sseResponseSchema = content?.["text/event-stream"]?.schema;
372
+ if (Predicate.isUndefined(op.sseSchema) && Predicate.isNotUndefined(sseResponseSchema)) {
373
+ const statusMajorNumber = Number(parsedStatus[0]);
374
+ if (!Number.isNaN(statusMajorNumber) && statusMajorNumber < 4) {
375
+ op.sseSchema = addSchema(`${schemaId}${status}Sse`, sseResponseSchema, op);
376
+ }
377
+ }
378
+ if (Predicate.isNotUndefined(content?.["application/octet-stream"])) {
379
+ const statusMajorNumber = Number(parsedStatus[0]);
380
+ if (!Number.isNaN(statusMajorNumber) && statusMajorNumber < 4) {
381
+ op.binaryResponse = true;
382
+ }
383
+ }
384
+ if (isEmptyResponse) {
385
+ if (parsedStatus !== "default") {
386
+ op.voidSchemas.add(parsedStatus.toLowerCase());
146
387
  }
147
388
  }
148
- if (op.successSchemas.size === 0 && Predicate.isNotUndefined(defaultSchema)) {
149
- op.successSchemas.set("2xx", defaultSchema);
389
+ }
390
+ if (!isHttpApi && op.successSchemas.size === 0 && Predicate.isNotUndefined(defaultSchema)) {
391
+ op.successSchemas.set("2xx", defaultSchema);
392
+ warnForOperation(emitWarning, op, {
393
+ code: "default-response-remapped",
394
+ message: "Default response was remapped to 2xx for the current HttpClient outputs."
395
+ });
396
+ }
397
+ operations.push(op);
398
+ }
399
+ }
400
+ return {
401
+ metadata: {
402
+ title: spec.info.title,
403
+ version: spec.info.version,
404
+ summary: Utils.nonEmptyString(spec.info.summary),
405
+ description: Utils.nonEmptyString(spec.info.description),
406
+ license: spec.info.license,
407
+ servers: spec.servers
408
+ },
409
+ tags: (spec.tags ?? []).map(tag => ({
410
+ name: tag.name,
411
+ description: Utils.nonEmptyString(tag.description),
412
+ externalDocs: tag.externalDocs
413
+ })),
414
+ securitySchemes,
415
+ operations
416
+ };
417
+ };
418
+ const isOpenApiParameter = parameter => {
419
+ if (!Predicate.isObject(parameter)) {
420
+ return false;
421
+ }
422
+ return typeof parameter.name === "string" && (parameter.in === "path" || parameter.in === "query" || parameter.in === "header" || parameter.in === "cookie");
423
+ };
424
+ const resolveOperationParameters = (pathParameters, operationParameters, resolveRef) => {
425
+ const resolved = new Map();
426
+ const add = parameter => {
427
+ const current = resolveReference(parameter, resolveRef);
428
+ if (!isOpenApiParameter(current)) {
429
+ return;
430
+ }
431
+ const key = `${current.in}:${current.name}`;
432
+ if (resolved.has(key)) {
433
+ resolved.delete(key);
434
+ }
435
+ resolved.set(key, current);
436
+ };
437
+ for (const parameter of pathParameters ?? []) {
438
+ add(parameter);
439
+ }
440
+ for (const parameter of operationParameters ?? []) {
441
+ add(parameter);
442
+ }
443
+ return [...resolved.values()];
444
+ };
445
+ const buildParameterSchema = (parameters, onAdded) => {
446
+ if (parameters.length === 0) {
447
+ return;
448
+ }
449
+ const schema = {
450
+ type: "object",
451
+ properties: {},
452
+ required: [],
453
+ additionalProperties: false
454
+ };
455
+ for (const parameter of parameters) {
456
+ const paramSchema = parameter.schema;
457
+ const added = [];
458
+ if (Predicate.isObject(paramSchema) && "properties" in paramSchema && Predicate.isObject(paramSchema.properties)) {
459
+ const required = "required" in paramSchema ? paramSchema.required : [];
460
+ for (const [name, propertySchema] of Object.entries(paramSchema.properties)) {
461
+ const adjustedName = `${parameter.name}[${name}]`;
462
+ schema.properties[adjustedName] = propertySchema;
463
+ if (required.includes(name)) {
464
+ schema.required.push(adjustedName);
150
465
  }
151
- operations.push(op);
466
+ added.push(adjustedName);
152
467
  }
468
+ } else {
469
+ schema.properties[parameter.name] = parameter.schema;
470
+ if (parameter.required) {
471
+ schema.required.push(parameter.name);
472
+ }
473
+ added.push(parameter.name);
153
474
  }
154
- for (const [path, methods] of Object.entries(spec.paths)) {
155
- handlePath(path, methods);
475
+ onAdded?.(parameter, added);
476
+ }
477
+ return {
478
+ schema,
479
+ optional: schema.required.length === 0
480
+ };
481
+ };
482
+ const mediaTypeToSuffix = contentType => {
483
+ const normalized = contentType.toLowerCase();
484
+ switch (normalized) {
485
+ case "application/json":
486
+ return "Json";
487
+ case "multipart/form-data":
488
+ return "FormData";
489
+ case "application/x-www-form-urlencoded":
490
+ return "FormUrlEncoded";
491
+ case "text/plain":
492
+ return "Text";
493
+ case "application/octet-stream":
494
+ return "Binary";
495
+ }
496
+ const suffix = Utils.identifier(contentType);
497
+ return suffix.length > 0 ? suffix : "Body";
498
+ };
499
+ const makeHttpApiMultipartSchemaRefs = definitions => {
500
+ const names = new Set(Object.keys(definitions));
501
+ const allocate = base => {
502
+ let candidate = base;
503
+ let index = 2;
504
+ while (names.has(candidate)) {
505
+ candidate = `${base}${index}`;
506
+ index += 1;
156
507
  }
157
- // TODO: make a CLI option ?
158
- const importName = "Schema";
159
- const source = getDialect(spec);
160
- const generation = generator.generate(source, spec.components?.schemas ?? {}, options.typeOnly, {
161
- onEnter: options.onEnter
162
- });
163
- return String.stripMargin(`|${openApiTransformer.imports(importName, operations)}
164
- |${generation}
165
- |${openApiTransformer.toImplementation(importName, options.name, operations)}
166
- |
167
- |${openApiTransformer.toTypes(importName, options.name, operations)}`);
168
- }, (effect, _, options) => Effect.provideServiceEffect(effect, OpenApiTransformer.OpenApiTransformer, options.typeOnly ? Effect.sync(OpenApiTransformer.makeTransformerTs) : Effect.sync(OpenApiTransformer.makeTransformerSchema)));
508
+ names.add(candidate);
509
+ return candidate;
510
+ };
169
511
  return {
170
- generate
512
+ singleFile: allocate("__HttpApiMultipartSingleFile"),
513
+ files: allocate("__HttpApiMultipartFiles")
171
514
  };
172
- });
515
+ };
516
+ const toDefinitionRef = name => `#/$defs/${name.replaceAll("~", "~0").replaceAll("/", "~1")}`;
517
+ const withHttpApiMultipartSchemas = (definitions, multipartSchemaRefs) => {
518
+ if (multipartSchemaRefs === undefined) {
519
+ return definitions;
520
+ }
521
+ return {
522
+ ...definitions,
523
+ [multipartSchemaRefs.singleFile]: {
524
+ type: "string",
525
+ format: "binary"
526
+ },
527
+ [multipartSchemaRefs.files]: {
528
+ type: "array",
529
+ items: {
530
+ $ref: toDefinitionRef(multipartSchemaRefs.singleFile)
531
+ }
532
+ }
533
+ };
534
+ };
535
+ const transformMultipartSchema = (schema, multipartSchemaRefs, resolveRef) => {
536
+ if (multipartSchemaRefs === undefined) {
537
+ return schema;
538
+ }
539
+ const singleFileRef = toDefinitionRef(multipartSchemaRefs.singleFile);
540
+ const filesRef = toDefinitionRef(multipartSchemaRefs.files);
541
+ const cache = new Map();
542
+ const stack = new Set();
543
+ const visit = value => {
544
+ if (Array.isArray(value)) {
545
+ return value.map(visit);
546
+ }
547
+ if (!Predicate.isObject(value)) {
548
+ return value;
549
+ }
550
+ if (typeof value.$ref === "string" && value.$ref.startsWith("#/components/schemas/")) {
551
+ const cached = cache.get(value.$ref);
552
+ if (cached !== undefined) {
553
+ return cached;
554
+ }
555
+ if (stack.has(value.$ref)) {
556
+ return value;
557
+ }
558
+ stack.add(value.$ref);
559
+ const transformed = visit(resolveSchemaReference(value.$ref, resolveRef));
560
+ stack.delete(value.$ref);
561
+ cache.set(value.$ref, transformed);
562
+ return transformed;
563
+ }
564
+ if (isMultipartBinaryFile(value)) {
565
+ return {
566
+ $ref: singleFileRef
567
+ };
568
+ }
569
+ const out = {};
570
+ for (const [key, current] of Object.entries(value)) {
571
+ out[key] = visit(current);
572
+ }
573
+ if (isMultipartBinaryFiles(out, singleFileRef)) {
574
+ return {
575
+ $ref: filesRef
576
+ };
577
+ }
578
+ return out;
579
+ };
580
+ return visit(schema);
581
+ };
582
+ const resolveSchemaReference = (ref, resolveRef) => {
583
+ let current = {
584
+ $ref: ref
585
+ };
586
+ const seen = new Set();
587
+ while (Predicate.isObject(current) && typeof current.$ref === "string") {
588
+ if (seen.has(current.$ref)) {
589
+ return current;
590
+ }
591
+ seen.add(current.$ref);
592
+ current = resolveRef(current.$ref);
593
+ }
594
+ return current;
595
+ };
596
+ const isMultipartBinaryFile = value => Predicate.isObject(value) && value.type === "string" && (typeof value.format === "string" && value.format.toLowerCase() === "binary" || typeof value.contentEncoding === "string" && value.contentEncoding.toLowerCase() === "binary");
597
+ const isMultipartBinaryFiles = (value, singleFileRef) => {
598
+ if (value.type !== "array") {
599
+ return false;
600
+ }
601
+ const items = value.items;
602
+ return isMultipartBinaryFile(items) || Predicate.isObject(items) && items.$ref === singleFileRef;
603
+ };
604
+ const isJsonMediaType = contentType => contentType === "application/json" || contentType.startsWith("application/") && contentType.endsWith("+json");
605
+ const isTextMediaType = contentType => contentType.startsWith("text/");
606
+ const isBinaryMediaType = contentType => contentType === "application/octet-stream" || contentType.startsWith("application/") && (contentType.includes("binary") || contentType.endsWith("+octet-stream"));
607
+ const getRequestMediaTypeEncoding = contentType => {
608
+ const normalized = contentType.toLowerCase();
609
+ if (isJsonMediaType(normalized)) {
610
+ return "json";
611
+ }
612
+ if (normalized === "multipart/form-data") {
613
+ return "multipart";
614
+ }
615
+ if (normalized === "application/x-www-form-urlencoded") {
616
+ return "form-url-encoded";
617
+ }
618
+ if (isTextMediaType(normalized)) {
619
+ return "text";
620
+ }
621
+ if (isBinaryMediaType(normalized)) {
622
+ return "binary";
623
+ }
624
+ return;
625
+ };
626
+ const getResponseMediaTypeEncoding = contentType => {
627
+ const normalized = contentType.toLowerCase();
628
+ if (isJsonMediaType(normalized)) {
629
+ return "json";
630
+ }
631
+ if (normalized === "application/x-www-form-urlencoded") {
632
+ return "form-url-encoded";
633
+ }
634
+ if (isTextMediaType(normalized)) {
635
+ return "text";
636
+ }
637
+ if (isBinaryMediaType(normalized)) {
638
+ return "binary";
639
+ }
640
+ return;
641
+ };
642
+ const resolveReference = (input, resolveRef) => {
643
+ let current = input;
644
+ while (Predicate.isObject(current) && typeof current.$ref === "string") {
645
+ current = resolveRef(current.$ref);
646
+ }
647
+ return current;
648
+ };
649
+ const cloneSecurityRequirements = security => security.map(requirement => Object.fromEntries(Object.entries(requirement).map(([name, scopes]) => [name, [...scopes]])));
650
+ const parseSecuritySchemes = (spec, resolveRef) => {
651
+ const securitySchemes = spec.components?.securitySchemes ?? {};
652
+ const parsed = [];
653
+ for (const [name, value] of Object.entries(securitySchemes)) {
654
+ const scheme = resolveReference(value, resolveRef);
655
+ if (!Predicate.isObject(scheme)) {
656
+ continue;
657
+ }
658
+ if (scheme.type === "http" && typeof scheme.scheme === "string") {
659
+ const normalizedScheme = scheme.scheme.toLowerCase();
660
+ if (normalizedScheme === "basic") {
661
+ parsed.push({
662
+ name,
663
+ type: "basic",
664
+ description: Utils.nonEmptyString(scheme.description),
665
+ bearerFormat: undefined,
666
+ scheme: undefined,
667
+ key: undefined,
668
+ in: undefined
669
+ });
670
+ } else if (normalizedScheme === "bearer") {
671
+ parsed.push({
672
+ name,
673
+ type: "bearer",
674
+ description: Utils.nonEmptyString(scheme.description),
675
+ bearerFormat: Utils.nonEmptyString(scheme.bearerFormat),
676
+ scheme: undefined,
677
+ key: undefined,
678
+ in: undefined
679
+ });
680
+ } else {
681
+ parsed.push({
682
+ name,
683
+ type: "http",
684
+ description: Utils.nonEmptyString(scheme.description),
685
+ bearerFormat: Utils.nonEmptyString(scheme.bearerFormat),
686
+ scheme: scheme.scheme,
687
+ key: undefined,
688
+ in: undefined
689
+ });
690
+ }
691
+ continue;
692
+ }
693
+ if (scheme.type === "apiKey" && (scheme.in === "header" || scheme.in === "query" || scheme.in === "cookie") && typeof scheme.name === "string") {
694
+ parsed.push({
695
+ name,
696
+ type: "apiKey",
697
+ description: Utils.nonEmptyString(scheme.description),
698
+ bearerFormat: undefined,
699
+ scheme: undefined,
700
+ key: scheme.name,
701
+ in: scheme.in
702
+ });
703
+ }
704
+ }
705
+ return parsed;
706
+ };
707
+ const warnForAndSecurityRequirements = (emitWarning, operation) => {
708
+ if (operation.effectiveSecurity.some(requirement => Object.keys(requirement).length === 0)) {
709
+ return;
710
+ }
711
+ for (const requirement of operation.effectiveSecurity) {
712
+ const schemes = Object.keys(requirement);
713
+ if (schemes.length <= 1) {
714
+ continue;
715
+ }
716
+ warnForOperation(emitWarning, operation, {
717
+ code: "security-and-downgraded",
718
+ message: `Security requirement requiring all of [${schemes.join(", ")}] was downgraded to a placeholder middleware.`
719
+ });
720
+ }
721
+ };
722
+ const hasSuccessfulSseResponse = (responses, hasExplicitSuccessResponse) => {
723
+ for (const [status, response] of responses) {
724
+ if (!Predicate.isObject(response)) {
725
+ continue;
726
+ }
727
+ const content = Predicate.isObject(response.content) ? response.content : undefined;
728
+ if (Predicate.isUndefined(content?.["text/event-stream"]?.schema)) {
729
+ continue;
730
+ }
731
+ const remappedStatus = remapDefaultResponseStatusForHttpApi(status, hasExplicitSuccessResponse);
732
+ const statusCode = Number(remappedStatus);
733
+ if (!Number.isNaN(statusCode) && statusCode < 400) {
734
+ return true;
735
+ }
736
+ }
737
+ return false;
738
+ };
739
+ const remapDefaultResponseStatusForHttpApi = (status, hasExplicitSuccessResponse) => status === "default" ? hasExplicitSuccessResponse ? "500" : "200" : status;
740
+ const methodSupportsRequestBody = method => method !== "get" && method !== "head" && method !== "options" && method !== "trace";
741
+ const warnForOperation = (emitWarning, operation, warning) => {
742
+ emitWarning({
743
+ ...warning,
744
+ path: operation.path,
745
+ method: operation.method,
746
+ operationId: operation.operationId
747
+ });
748
+ };
173
749
  function getDialect(spec) {
174
750
  return spec.openapi.trim().startsWith("3.0") ? "openapi-3.0" : "openapi-3.1";
175
751
  }
752
+ /**
753
+ * Layer providing an OpenAPI generator for Schema-backed HTTP client and HttpApi output.
754
+ *
755
+ * @category layers
756
+ * @since 4.0.0
757
+ */
176
758
  export const layerTransformerSchema = /*#__PURE__*/Layer.effect(OpenApiGenerator, make);
759
+ /**
760
+ * Layer providing an OpenAPI generator for type-only HTTP client output.
761
+ *
762
+ * @category layers
763
+ * @since 4.0.0
764
+ */
177
765
  export const layerTransformerTs = /*#__PURE__*/Layer.effect(OpenApiGenerator, make);
178
766
  const isSwaggerSpec = spec => "swagger" in spec;
179
767
  const convertSwaggerSpec = /*#__PURE__*/Effect.fn(spec => Effect.callback(resume => {